@henols/c64-re-tools 2.6.0-rc.9 → 2.7.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.
- package/package.json +1 -1
- package/skills/c64-assembler/SKILL.md +7 -7
- package/skills/c64-assembler/scripts/assembler.ts +4 -3
- package/skills/c64-basic/SKILL.md +1 -1
- package/skills/c64-development/SKILL.md +7 -7
- package/skills/c64-disk/SKILL.md +13 -13
- package/skills/c64-docs/SKILL.md +25 -10
- package/skills/c64-docs/references/page-types.md +11 -11
- package/skills/c64-docs/references/style.md +21 -0
- package/skills/c64-docs/scripts/docs.ts +78 -18
- package/skills/c64-docs/scripts/lib/links.ts +1 -1
- package/skills/c64-docs/scripts/lib/reference.ts +117 -31
- package/skills/c64-docs/scripts/lib/source-map.ts +14 -0
- package/skills/c64-knowledge/SKILL.md +15 -14
- package/skills/c64-knowledge/scripts/knowledge.ts +17 -10
- package/skills/c64-memory-map/SKILL.md +1 -1
- package/skills/c64-packer/SKILL.md +1 -1
- package/skills/c64-provenance/SKILL.md +5 -4
- package/skills/c64-provenance/scripts/lib/compare.ts +1 -1
- package/skills/c64-reverse-engineering/SKILL.md +26 -11
- package/skills/c64-source/SKILL.md +18 -15
- package/skills/c64-source/scripts/lib/export.ts +20 -8
- package/skills/c64-source/scripts/lib/loader.ts +51 -28
- package/skills/c64-source/scripts/lib/source.ts +27 -20
- package/skills/c64-source/scripts/source.ts +68 -53
- package/skills/c64-static-analysis/SKILL.md +24 -22
- package/skills/c64-static-analysis/scripts/lib/findings.ts +11 -11
- package/skills/c64-static-analysis/scripts/lib/instructions.ts +4 -4
- package/skills/c64-static-analysis/scripts/lib/macros.ts +3 -1
- package/skills/c64-static-analysis/scripts/static-analysis.ts +36 -27
- package/skills/c64-testing/SKILL.md +32 -24
- package/skills/c64-testing/references/recording-format.md +15 -9
- package/skills/c64-testing/references/scenario-format.md +9 -7
- package/skills/c64-testing/scripts/lib/recording.ts +214 -49
- package/skills/c64-testing/scripts/lib/replay.ts +45 -19
- package/skills/c64-testing/scripts/lib/runs.ts +7 -2
- package/skills/c64-testing/scripts/lib/scenario.ts +31 -31
- package/skills/c64-testing/scripts/testing.ts +37 -16
- package/skills/c64-unpacker/SKILL.md +16 -14
- package/skills/c64-unpacker/scripts/lib/stages.ts +18 -3
- package/skills/c64-unpacker/scripts/unpacker.ts +38 -6
- package/src/build-name.ts +9 -4
- package/src/c64.ts +1 -1
- package/src/host/main.ts +2 -2
- package/src/host/server.ts +3 -1
- package/src/host/tools/index.ts +1 -1
- package/src/host/vice/process.ts +34 -17
- package/src/host/vice/session.ts +55 -27
- package/src/host-client/steps.ts +4 -1
- package/src/host-client/tools.ts +1 -1
- package/src/knowledge/evidence.ts +66 -0
- package/src/knowledge/history.ts +5 -5
- package/src/knowledge/import.ts +12 -5
- package/src/knowledge/program.ts +81 -33
- package/src/knowledge/read.ts +3 -3
- package/src/knowledge/schema.ts +7 -7
- package/src/knowledge/separate.ts +2 -2
- package/src/knowledge/start-screen.ts +2 -0
- package/src/knowledge/text.ts +28 -3
- package/src/knowledge/write.ts +7 -7
- package/src/mcp/tools/debug.ts +23 -21
- package/src/mcp/tools/memory.ts +12 -9
- package/src/native/c64run.ts +7 -4
- package/src/native/{ghidra → decompiler}/analyze.ts +17 -17
- package/src/native/{ghidra → decompiler}/language/c64rt_6510.slaspec +1 -1
- package/src/native/{ghidra → decompiler}/walk.ts +6 -6
- package/src/native/types.ts +25 -25
- package/src/opcodes.ts +1 -1
- package/src/project.ts +1 -1
- package/src/reference-pages.ts +64 -0
- package/src/script.ts +2 -2
- package/tools/c64run.c +151 -5
- /package/src/native/{ghidra → decompiler}/c64rt-wasm.ts +0 -0
- /package/src/native/{ghidra → decompiler}/language/c64rt_6510.cspec +0 -0
- /package/src/native/{ghidra → decompiler}/language/c64rt_6510.ldefs +0 -0
- /package/src/native/{ghidra → decompiler}/language/c64rt_6510.pspec +0 -0
- /package/src/native/{ghidra → decompiler}/language/c64rt_6510.sla +0 -0
- /package/src/native/{ghidra → decompiler}/pcode.ts +0 -0
- /package/src/native/{ghidra → decompiler}/wasm.ts +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// The c64-source script: generates ACME source from the program and the
|
|
2
|
-
// knowledge and
|
|
2
|
+
// knowledge and the decompiler's instructions, which it runs itself, and checks
|
|
3
3
|
// with ACME that the build of the base release assembles to the program byte
|
|
4
4
|
// by byte. With --loader it also writes a loader that recreates the entry
|
|
5
5
|
// state, simulates it, and checks it in the emulator. The default build may
|
|
@@ -14,6 +14,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync
|
|
|
14
14
|
import { basename, dirname, join, relative, sep } from "node:path";
|
|
15
15
|
|
|
16
16
|
import { isRefusal, Refusal } from "#src/errors.ts";
|
|
17
|
+
import { PACKAGE } from "#src/package.ts";
|
|
17
18
|
import { BUILD_DIRECTORY, buildName, symbolsPath } from "#src/build-name.ts";
|
|
18
19
|
import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
|
|
19
20
|
import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
|
|
@@ -29,11 +30,12 @@ import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, so
|
|
|
29
30
|
import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
|
|
30
31
|
import { subtract, write } from "#src/knowledge/write.ts";
|
|
31
32
|
import { assemble, symbolsFileText } from "#src/native/acme.ts";
|
|
32
|
-
import { analyze } from "#src/native/
|
|
33
|
+
import { analyze } from "#src/native/decompiler/analyze.ts";
|
|
33
34
|
import { localToolContext } from "#src/native/local.ts";
|
|
34
|
-
import {
|
|
35
|
+
import { DECOMPILER_LIMITS, type AssembledSymbol, type Diagnostic } from "#src/native/types.ts";
|
|
35
36
|
import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romRanges, romUseOfProgram } from "#src/platform.ts";
|
|
36
37
|
import { ensureLocal, generatedDirectory, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
|
|
38
|
+
import { generatedReferences } from "#src/reference-pages.ts";
|
|
37
39
|
import { isoCet } from "#src/time.ts";
|
|
38
40
|
import { zipFiles } from "#src/zip.ts";
|
|
39
41
|
import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
|
|
@@ -65,7 +67,7 @@ import { instructionWith, OPCODES } from "#src/opcodes.ts";
|
|
|
65
67
|
import { capturedColourRam } from "#src/knowledge/start-screen.ts";
|
|
66
68
|
import { planStage, STAGE_CODE_END, STAGE_FILE, STAGE_START, stageParts, stageText, type StageInput, type StagePart, type StagePlan } from "./lib/stage.ts";
|
|
67
69
|
import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
|
|
68
|
-
import { CONFIG_FILE, configText, configValues, entriesInData, entryOutsideImage, hasConfigFile, hasSwitchFile, layout, literalOperand, probeForms, render, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
|
|
70
|
+
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";
|
|
69
71
|
|
|
70
72
|
/** At most this many diagnostics or differences of one check. */
|
|
71
73
|
const MAX_DIAGNOSTICS = 20;
|
|
@@ -127,7 +129,7 @@ type SourceKnowledge = ReturnType<typeof readKnowledge>;
|
|
|
127
129
|
|
|
128
130
|
/**
|
|
129
131
|
* The names of the user and the LLM, and for each address without one the
|
|
130
|
-
* first analyzer name in the order heuristic,
|
|
132
|
+
* first analyzer name in the order heuristic, decompiler, DXA. An analyzer
|
|
131
133
|
* name that another address has already is left out. The analyzer names keep
|
|
132
134
|
* their origin, so a platform name still wins over them.
|
|
133
135
|
*/
|
|
@@ -155,11 +157,11 @@ function romOf(image: ProgramImage, knowledge: Pick<SourceKnowledge, "routines"
|
|
|
155
157
|
}
|
|
156
158
|
|
|
157
159
|
/**
|
|
158
|
-
*
|
|
160
|
+
* The decompiler's instruction starts and lengths inside the image, seeded from the
|
|
159
161
|
* entry, from knowledge of any origin, and from the coverage: a run's flow
|
|
160
162
|
* starts, also after a JSR, so code that an analyzer does not reach by itself
|
|
161
163
|
* is in the source. A program without a seed has no known code: it is data
|
|
162
|
-
* only, and
|
|
164
|
+
* only, and the decompiler does not run.
|
|
163
165
|
*/
|
|
164
166
|
async function decode(image: ProgramImage, knowledge: Pick<SourceKnowledge, "routines" | "regions">, entries: number[], coverage: Uint8Array | undefined): Promise<{ instructions: Map<number, number>; dataOnly: boolean }> {
|
|
165
167
|
const inImage = (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end);
|
|
@@ -184,9 +186,9 @@ async function decode(image: ProgramImage, knowledge: Pick<SourceKnowledge, "rou
|
|
|
184
186
|
const { result } = await analyze(
|
|
185
187
|
{
|
|
186
188
|
imageKind: analyzedBytes(image).kind,
|
|
187
|
-
entryPoints: entryPoints.slice(0,
|
|
188
|
-
codeStarts: flows.codeStarts.filter((address) => !seeds.has(address)).slice(0,
|
|
189
|
-
dataRanges: dataRanges.slice(0,
|
|
189
|
+
entryPoints: entryPoints.slice(0, DECOMPILER_LIMITS.entryPoints),
|
|
190
|
+
codeStarts: flows.codeStarts.filter((address) => !seeds.has(address)).slice(0, DECOMPILER_LIMITS.codeStarts),
|
|
191
|
+
dataRanges: dataRanges.slice(0, DECOMPILER_LIMITS.dataRanges),
|
|
190
192
|
labels: [],
|
|
191
193
|
decompile: [],
|
|
192
194
|
},
|
|
@@ -277,9 +279,9 @@ function usesInErrors(diagnostics: Diagnostic[], lineOf: ReadonlyMap<string, num
|
|
|
277
279
|
}
|
|
278
280
|
|
|
279
281
|
/** The first address where two byte runs differ, as a reason. */
|
|
280
|
-
function firstDifference(start: number, built: (address: number) => number,
|
|
282
|
+
function firstDifference(start: number, built: (address: number) => number, imageByte: (address: number) => number, end: number): string | undefined {
|
|
281
283
|
for (let address = start; address <= end; address++) {
|
|
282
|
-
if (built(address) !==
|
|
284
|
+
if (built(address) !== imageByte(address)) return `ACME assembles it to other bytes than the image: at ${formatC64Address(address)} it gives $${built(address).toString(16).padStart(2, "0")}, and the image has $${imageByte(address).toString(16).padStart(2, "0")}.`;
|
|
283
285
|
}
|
|
284
286
|
return undefined;
|
|
285
287
|
}
|
|
@@ -369,8 +371,8 @@ function blame(rendered: Rendered, built: Awaited<ReturnType<typeof assembleFile
|
|
|
369
371
|
for (const item of rendered.expressions) {
|
|
370
372
|
if (item.address + item.length - 1 > end || item.address < built.start!) continue;
|
|
371
373
|
const assembled = word((address) => built.program![2 + address - built.start!]!, item);
|
|
372
|
-
const
|
|
373
|
-
if (assembled !==
|
|
374
|
+
const imageWord = word(image.byteAt, item);
|
|
375
|
+
if (assembled !== imageWord) blamed.set(item.address, `ACME assembles it to ${show(assembled, item.length)}, and the image has ${show(imageWord, item.length)}.`);
|
|
374
376
|
}
|
|
375
377
|
return { numbers: blamed, uses };
|
|
376
378
|
}
|
|
@@ -524,7 +526,7 @@ async function readRam(client: ViceSessionClient, start: number, size: number):
|
|
|
524
526
|
* Runs the loader in the emulator to its jump to the entry and compares the
|
|
525
527
|
* machine with the entry state there. At the jump, every byte and register is
|
|
526
528
|
* set and no interrupt has run since the PLP: the 6502 takes one only after
|
|
527
|
-
* the JMP, as the
|
|
529
|
+
* the JMP, as the program can take one right at its entry.
|
|
528
530
|
*/
|
|
529
531
|
/** What the check of the loader gives. `stop`: why the loader did not get to its copier or its jump. */
|
|
530
532
|
interface LoaderRun {
|
|
@@ -702,6 +704,9 @@ const LOADER_CHECK_DIRECTORY = "loader-check";
|
|
|
702
704
|
/** The source files of the loader. Only a run with --loader writes them, so only such a run removes them. */
|
|
703
705
|
const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", START_SCREEN_FILE, STAGE_FILE]);
|
|
704
706
|
|
|
707
|
+
/** The source files of the show stage. A run writes them only with a loader program whose check ran, so only such a run removes them. */
|
|
708
|
+
const STAGE_FILES: ReadonlySet<string> = new Set([START_SCREEN_FILE, STAGE_FILE]);
|
|
709
|
+
|
|
705
710
|
/** A loader program that generate wrote: its build name, as buildName gives it for loader.asm. */
|
|
706
711
|
const LOADER_PROGRAM = /^(clean|custom_[a-z0-9_]+|release_[A-Za-z0-9_]+)_loader\.prg$/;
|
|
707
712
|
|
|
@@ -715,25 +720,28 @@ function loaderPrograms(): string[] {
|
|
|
715
720
|
.filter((path) => existsSync(resolveProjectPath(path)));
|
|
716
721
|
}
|
|
717
722
|
|
|
718
|
-
/** The
|
|
719
|
-
const
|
|
723
|
+
/** The line of loader.asm that gives the toolkit version and the newest knowledge revision of the spaces that the loader holds. */
|
|
724
|
+
const loaderLine = (revision: string) => `Loader generated by c64-source ${PACKAGE.version} from knowledge revision ${revision}.`;
|
|
725
|
+
const LOADER_LINE = /^; Loader generated by c64-source (\S+) from knowledge revision (\S+)\.$/;
|
|
720
726
|
|
|
721
727
|
/**
|
|
722
728
|
* The loader files of an earlier run that a run without --loader keeps, when
|
|
723
|
-
* the generated loader.asm is of another knowledge revision
|
|
724
|
-
* then copy other bytes than the source
|
|
725
|
-
* generated loader.asm, or it is of this
|
|
729
|
+
* the generated loader.asm is of another knowledge revision or of another
|
|
730
|
+
* version of the toolkit: the loader can then copy other bytes than the source
|
|
731
|
+
* has. Undefined when there is no generated loader.asm, or it is of this
|
|
732
|
+
* revision and version.
|
|
726
733
|
*/
|
|
727
|
-
function staleLoader(out: string, revision: string): { files: string[]; revision?: string } | undefined {
|
|
734
|
+
function staleLoader(out: string, revision: string): { files: string[]; revision?: string; version?: string } | undefined {
|
|
728
735
|
const path = resolveProjectPath(`${out}/loader.asm`);
|
|
729
736
|
if (!existsSync(path)) return undefined;
|
|
730
737
|
const text = readFileSync(path, "utf8");
|
|
731
738
|
if (!text.startsWith(GENERATED_MARK)) return undefined;
|
|
732
|
-
const
|
|
733
|
-
const
|
|
734
|
-
|
|
739
|
+
const found = text.split(/\r?\n/).map((row) => LOADER_LINE.exec(row)).find((match) => match !== null);
|
|
740
|
+
const version = found?.[1];
|
|
741
|
+
const old = found?.[2];
|
|
742
|
+
if (old === revision && version === PACKAGE.version) return undefined;
|
|
735
743
|
const files = [...[...LOADER_FILES].filter((name) => existsSync(resolveProjectPath(`${out}/${name}`))).map((name) => `${out}/${name}`), ...loaderPrograms()];
|
|
736
|
-
return { files, ...(old === undefined ? {} : { revision: old }) };
|
|
744
|
+
return { files, ...(old === undefined ? {} : { revision: old }), ...(version === undefined ? {} : { version }) };
|
|
737
745
|
}
|
|
738
746
|
|
|
739
747
|
/** The line of a leftover file that gives its range. */
|
|
@@ -798,7 +806,7 @@ function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boole
|
|
|
798
806
|
}
|
|
799
807
|
if (!entry.isFile()) continue;
|
|
800
808
|
const path = join(directory, entry.name);
|
|
801
|
-
if (LOADER_FILES.has(name) && !loaderRun) continue;
|
|
809
|
+
if ((LOADER_FILES.has(name) && !loaderRun) || STAGE_FILES.has(name)) continue;
|
|
802
810
|
if (!name.endsWith(".asm") || keep.has(name) || !readFileSync(path, "utf8").startsWith(GENERATED_MARK)) continue;
|
|
803
811
|
rmSync(path, { force: true });
|
|
804
812
|
removed.push(`${out}/${name}`);
|
|
@@ -810,22 +818,22 @@ function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boole
|
|
|
810
818
|
return removed;
|
|
811
819
|
}
|
|
812
820
|
|
|
813
|
-
/** The instructions that
|
|
821
|
+
/** The instructions that the decompiler decoded, and whether the program has known code. */
|
|
814
822
|
type DecodedProgram = Awaited<ReturnType<typeof decode>>;
|
|
815
823
|
|
|
816
824
|
/** How buildSource makes and checks the source of a knowledge. */
|
|
817
825
|
interface SourceOptions {
|
|
818
826
|
space: Space;
|
|
819
|
-
/** More entry points for
|
|
827
|
+
/** More entry points for the decompiler. */
|
|
820
828
|
entries: number[];
|
|
821
829
|
header: string[];
|
|
822
830
|
/** The first line of each file, or none. */
|
|
823
831
|
mark?: string;
|
|
824
832
|
/** The switch values of the build that must give the program. */
|
|
825
833
|
values: ReadonlyMap<string, number>;
|
|
826
|
-
/** The instructions of an earlier decode: then
|
|
834
|
+
/** The instructions of an earlier decode: then the decompiler does not run again. */
|
|
827
835
|
decoded?: DecodedProgram;
|
|
828
|
-
/** Mark the code that no run executed. Without the marks, the coverage only gives the seeds of
|
|
836
|
+
/** Mark the code that no run executed. Without the marks, the coverage only gives the seeds of the decompiler and the ROM use. */
|
|
829
837
|
notExecutedMarks: boolean;
|
|
830
838
|
/** With an entry state, the loader is planned too. */
|
|
831
839
|
state?: EntryState;
|
|
@@ -1013,13 +1021,11 @@ async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; co
|
|
|
1013
1021
|
if (row.colourRam === true && colourRam === undefined) throw new Refusal("not-found", `The start screen takes its colours from the colour RAM of the capture in ${stage}, and that capture has none. Capture the stage again while it shows the screen, and put it into the project knowledge with image --space ${stage}.`);
|
|
1014
1022
|
const image = knowledge.program;
|
|
1015
1023
|
const memory = Uint8Array.from(image.memory);
|
|
1016
|
-
const addresses = knowledge.symbols.map((symbol) => `${symbol.name} = ${formatC64Address(symbol.address)}`);
|
|
1017
1024
|
for (const patch of knowledge.patches) {
|
|
1018
1025
|
const owner = knowledge.switches.find((item) => item.name === patch.switch);
|
|
1019
1026
|
if (owner === undefined || owner.default === owner.base) continue;
|
|
1020
1027
|
const length = patch.end - patch.start + 1;
|
|
1021
|
-
const
|
|
1022
|
-
const built = await assembleFiles([{ name: "patch.asm", text: `${text}\n` }], "patch.asm");
|
|
1028
|
+
const built = await assembleFiles([{ name: "patch.asm", text: stagePatchText(knowledge.symbols, patch) }], "patch.asm");
|
|
1023
1029
|
if (built.program === undefined || built.start !== patch.start || built.program.length - 2 !== length) {
|
|
1024
1030
|
throw new Refusal("invalid-input", `The patch of ${patch.switch} at ${formatC64Address(patch.start)}-${formatC64Address(patch.end)} in ${stage} does not assemble to ${length} bytes: ${built.diagnostics.map((diagnostic) => diagnostic.message).join("; ") || "it is longer than its range"}. Correct the patch in the project knowledge.`);
|
|
1025
1031
|
}
|
|
@@ -1140,7 +1146,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1140
1146
|
const configNames = new Set([...knowledge.switches.map((row) => row.name), START_SCREEN_SWITCH, LEFTOVERS_SWITCH]);
|
|
1141
1147
|
const loaderValues = new Map([...given].filter(([name]) => configNames.has(name)));
|
|
1142
1148
|
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."];
|
|
1143
|
-
const loaderHeader = [
|
|
1149
|
+
const loaderHeader = [loaderLine(knowledge.sourceRevision), "It copies the segments into place, sets the entry state and jumps to the entry."];
|
|
1144
1150
|
const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused } = await buildSource(knowledge, {
|
|
1145
1151
|
space,
|
|
1146
1152
|
entries,
|
|
@@ -1165,6 +1171,10 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1165
1171
|
// The reports go to the local folder: the source folder holds only source files.
|
|
1166
1172
|
const reports = generatedDirectory(projectRelative(out));
|
|
1167
1173
|
written.push(writeReported(`${reports}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.sourceRevision, files)));
|
|
1174
|
+
// A reference that the project has from this source, made at an earlier revision: the new source makes it old.
|
|
1175
|
+
const staleReference = generatedReferences(projectRoot())
|
|
1176
|
+
.filter((reference) => reference.mapPath === `${reports}/${SOURCE_MAP_FILE}` && reference.revision !== knowledge.sourceRevision)
|
|
1177
|
+
.map((reference) => ({ folder: reference.folder, revision: reference.revision }));
|
|
1168
1178
|
const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
|
|
1169
1179
|
const inData = entriesInData(entries, knowledge.regions);
|
|
1170
1180
|
if (rendered.notExecuted !== undefined) {
|
|
@@ -1194,6 +1204,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1194
1204
|
revision: knowledge.revision,
|
|
1195
1205
|
// A run without --loader keeps the loader of an earlier run: one of another revision is stale.
|
|
1196
1206
|
...(stale === undefined ? {} : { staleLoader: { ...stale, ...(image.state === undefined || image.entry === undefined ? { noEntryState: true } : {}) } }),
|
|
1207
|
+
...(staleReference.length === 0 ? {} : { staleReference }),
|
|
1197
1208
|
instructions: rendered.instructions,
|
|
1198
1209
|
dataBytes: rendered.dataBytes,
|
|
1199
1210
|
...(rendered.undecodedBytes === 0 ? {} : { undecodedBytes: rendered.undecodedBytes }),
|
|
@@ -1212,7 +1223,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1212
1223
|
...(rendered.notExecuted === undefined
|
|
1213
1224
|
? {}
|
|
1214
1225
|
: {
|
|
1215
|
-
notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange,
|
|
1226
|
+
notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `a larger --max-listed, or read ${reports}/${NOT_EXECUTED_FILE}`) },
|
|
1216
1227
|
}),
|
|
1217
1228
|
...(laid.unusedModules.length === 0 ? {} : { unusedModules: laid.unusedModules.map((module) => ({ start: formatC64Address(module.start), file: module.file })) }),
|
|
1218
1229
|
// The bytes that nothing uses: in leftover files, which the default build and the loader leave out.
|
|
@@ -1342,7 +1353,9 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1342
1353
|
rmSync(resolveProjectPath(scratch), { recursive: true, force: true });
|
|
1343
1354
|
}
|
|
1344
1355
|
// A loader program of an earlier run with another build name goes: config.asm has other values now.
|
|
1345
|
-
|
|
1356
|
+
// The files of an earlier show stage go when this loader has no stage and this run did not write them.
|
|
1357
|
+
const stageFiles = stage === undefined ? [...STAGE_FILES].filter((name) => !files.some((file) => file.name === name)).map((name) => `${out}/${name}`).filter((path) => existsSync(resolveProjectPath(path)) && readFileSync(resolveProjectPath(path), "utf8").startsWith(GENERATED_MARK)) : [];
|
|
1358
|
+
for (const path of [...loaderPrograms().filter((item) => item !== loaderPath && item !== symbolsPath(loaderPath)), ...stageFiles]) {
|
|
1346
1359
|
rmSync(resolveProjectPath(path), { force: true });
|
|
1347
1360
|
removed.push(path);
|
|
1348
1361
|
}
|
|
@@ -1528,28 +1541,28 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
|
|
|
1528
1541
|
|
|
1529
1542
|
// 1. The source of the knowledge must give the base release byte for byte, with every patch in it.
|
|
1530
1543
|
const baseValues = new Map(knowledge.switches.map((row) => [row.name, row.base]));
|
|
1531
|
-
const
|
|
1532
|
-
if (
|
|
1533
|
-
const checked = check(
|
|
1534
|
-
if (!checked.identical) return { result: "FAIL", stage: "
|
|
1535
|
-
if (
|
|
1536
|
-
if (
|
|
1537
|
-
return { result: "FAIL", stage: "
|
|
1544
|
+
const baseSource = await buildSource(knowledge, { space: DEFAULT_SPACE, entries: [], header: [], values: baseValues, notExecutedMarks: false });
|
|
1545
|
+
if (baseSource.built.program === undefined) return { result: "FAIL", stage: "base", reason: "The source of the knowledge does not assemble.", diagnostics: baseSource.built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
|
|
1546
|
+
const checked = check(baseSource.built.program, baseSource.built.start!, image);
|
|
1547
|
+
if (!checked.identical) return { result: "FAIL", stage: "base", reason: "The source of the knowledge does not assemble to the program.", check: checked };
|
|
1548
|
+
if (baseSource.missingEntry !== undefined) return { result: "FAIL", stage: "base", reason: baseSource.missingEntry };
|
|
1549
|
+
if (baseSource.laid.patchesNotWritten.length > 0) {
|
|
1550
|
+
return { result: "FAIL", stage: "base", reason: "The source cannot write every patch.", patchesNotWritten: listed(baseSource.laid.patchesNotWritten, max, (item) => ({ ...shownRange(item), switch: item.switch, reason: item.reason })) };
|
|
1538
1551
|
}
|
|
1539
1552
|
|
|
1540
1553
|
// 2. Each switch at its export value. Two alternatives of one range cannot both be in.
|
|
1541
1554
|
const values = new Map(knowledge.switches.map((row) => [row.name, exportValue(row)]));
|
|
1542
|
-
for (const patch of
|
|
1555
|
+
for (const patch of baseSource.laid.patches.values()) {
|
|
1543
1556
|
const both = patch.alternatives.filter((alternative) => values.get(alternative.switch) !== alternative.base);
|
|
1544
1557
|
if (both.length > 1) {
|
|
1545
1558
|
throw new Refusal("invalid-input", `The switches ${both.map((item) => item.switch).join(" and ")} change ${formatC64Address(patch.start)}-${formatC64Address(patch.end)} in different ways, and the export puts both in. In the project knowledge, give all but one of them the kind change, with the default of the base release. Then export again.`);
|
|
1546
1559
|
}
|
|
1547
1560
|
}
|
|
1548
|
-
const withPatches = switchesOf(
|
|
1561
|
+
const withPatches = switchesOf(baseSource.laid);
|
|
1549
1562
|
const changedSwitches = knowledge.switches.filter((row) => values.get(row.name) !== row.base);
|
|
1550
1563
|
const patchesIn = changedSwitches.flatMap((row) => withPatches.get(row.name) ?? []);
|
|
1551
|
-
const baked = await assembleFiles(withValues(
|
|
1552
|
-
const bakedCheck = compareBuilds(baked, patchesIn, { program:
|
|
1564
|
+
const baked = await assembleFiles(withValues(baseSource.files, baseSource.laid, values), "main.asm");
|
|
1565
|
+
const bakedCheck = compareBuilds(baked, patchesIn, { program: baseSource.built.program, start: baseSource.built.start! });
|
|
1553
1566
|
const switches = knowledge.switches.map((row) => ({ name: row.name, kind: row.kind, base: row.base, value: values.get(row.name)! }));
|
|
1554
1567
|
if (bakedCheck.result !== "fits" || baked.program === undefined) return { result: "FAIL", stage: "switches", reason: "The build with the export values of the switches does not fit.", switches, build: bakedCheck };
|
|
1555
1568
|
|
|
@@ -1696,7 +1709,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
|
|
|
1696
1709
|
to: fromProject(to),
|
|
1697
1710
|
zip: zipWritten,
|
|
1698
1711
|
source: { project: basename(project), revision: knowledge.revision },
|
|
1699
|
-
files: listed(files.map((file) => ({ ...file, out: fromProject(join(to, file.out)) })), max, (file) => file, "the folder of the new project"),
|
|
1712
|
+
files: listed(files.map((file) => ({ ...file, out: fromProject(join(to, file.out)) })), max, (file) => file, "a larger --max-listed, or list the folder of the new project"),
|
|
1700
1713
|
switches,
|
|
1701
1714
|
check: exportCheck,
|
|
1702
1715
|
...(loaderOutput === undefined ? {} : { loader: loaderOutput }),
|
|
@@ -1778,22 +1791,24 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
|
|
|
1778
1791
|
}
|
|
1779
1792
|
if ([body.asBytes, body.operandsAsNumbers, body.macrosAsInstructions, body.patchesNotWritten].some(isCut)) steps.push("To see all items of a list, give a larger --max-listed.");
|
|
1780
1793
|
const staleLoader = body.staleLoader as { noEntryState?: boolean } | undefined;
|
|
1781
|
-
|
|
1794
|
+
// The reference is made from the source: it is the step after this run, also when the run has no finding.
|
|
1795
|
+
const reference = body.staleReference === undefined ? "" : " The reference pages in staleReference are from an earlier revision of this source. Generate the reference pages again from this source.";
|
|
1796
|
+
if (steps.length === 0 && staleLoader === undefined) return reply(body, { hint: `Read the source. Record names, comments, regions and modules in the project knowledge. Then generate again.${reference}` });
|
|
1782
1797
|
if (again) steps.push("Then generate again.");
|
|
1783
1798
|
// The run with --loader writes the loader again, so it is the next action also for the other findings.
|
|
1784
1799
|
const loaderAgain = staleLoader !== undefined && staleLoader.noEntryState !== true;
|
|
1785
1800
|
if (staleLoader !== undefined) {
|
|
1786
|
-
steps.push("The loader files in staleLoader.files are of another knowledge revision, and the run kept them.");
|
|
1801
|
+
steps.push("The loader files in staleLoader.files are of another knowledge revision or toolkit version, and the run kept them.");
|
|
1787
1802
|
steps.push(loaderAgain ? "To write the loader of this revision, generate with --loader." : "The knowledge has no entry state, so --loader cannot write them again. Remove them when the build does not use them.");
|
|
1788
1803
|
}
|
|
1789
|
-
return reply(body, { hint: steps.join(" ")
|
|
1804
|
+
return reply(body, { hint: `${steps.join(" ")}${reference}`, ...(again || loaderAgain ? { nextAction: generateAgain(call, call.flag("loader") || loaderAgain) } : {}) });
|
|
1790
1805
|
}
|
|
1791
1806
|
|
|
1792
1807
|
/** The hint of an export result: the action for a failed stage, or the next steps for the new project. */
|
|
1793
1808
|
function exportReply(body: Record<string, unknown>): Reply {
|
|
1794
1809
|
if (body.result === "FAIL") {
|
|
1795
1810
|
const hints: Record<string, string> = {
|
|
1796
|
-
|
|
1811
|
+
base: "Run generate, and correct the project knowledge until generate gives PASS. Then export again.",
|
|
1797
1812
|
switches: "Run generate. It builds each switch alone. Correct the patches in the project knowledge until each switch fits. Then export again.",
|
|
1798
1813
|
export: "This is a defect of the script. Give the result to the user.",
|
|
1799
1814
|
loader: "Read reason, and give it to the user.",
|
|
@@ -1842,7 +1857,7 @@ await runScript({
|
|
|
1842
1857
|
drop: { ...OPTIONS.range, multiple: true, help: "a range that becomes free: code that the entry does not reach (see unreachableExecuted), or data. Nothing that stays may go to it or read it" },
|
|
1843
1858
|
"max-listed": OPTIONS["max-listed"],
|
|
1844
1859
|
},
|
|
1845
|
-
notes: "Fixes, trainers and cheats are in, protection and crack changes are out, and a change keeps its default. Code becomes free only when no run executed it and nothing reaches it; data only when no run touched it and nothing names it. Charset, sprite, bitmap and screen data stay unless --drop names them. Addresses do not move: a free range is $00 with a label free_xxxx. The export needs coverage in the knowledge to make ranges free by itself.",
|
|
1860
|
+
notes: "Fixes, trainers and cheats are in, protection and crack changes are out, and a change keeps its default. Code becomes free only when no run executed it and nothing reaches it; data only when no run touched it and nothing names it. Charset, sprite, bitmap and screen data, and data in them, stay unless --drop names them. Addresses do not move: a free range is $00 with a label free_xxxx. The export needs coverage in the knowledge to make ranges free by itself.",
|
|
1846
1861
|
run: async (call) => exportReply(await exportProject(call)),
|
|
1847
1862
|
},
|
|
1848
1863
|
],
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: c64-static-analysis
|
|
3
|
-
description: Finds the structure of a C64 program with DXA or
|
|
3
|
+
description: Finds the structure of a C64 program with DXA or the decompiler, without running it. It records the code and data regions, the analyzer names and the references in the project knowledge. Use it to get a fast first pass of code and data, and a disassembly listing. Use it to get the routines, the references, an instruction list and decompiled code. Use it when the project knowledge has coverage, to find code that only a vector, a table or an interrupt reaches. Use it to find 6502 idioms, pointer candidates, raster pitfalls and macro candidates. It does not run the program. It does not give names to routines.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# Static analysis
|
|
@@ -43,23 +43,23 @@ To get the command list, run the script with no arguments.
|
|
|
43
43
|
- An entry point is an address where code starts. Give it with `--entry`. Get it from these sources:
|
|
44
44
|
- The SYS address of a BASIC start. Get it from a listing of the BASIC program.
|
|
45
45
|
- A vector or an interrupt target that you found in the emulator.
|
|
46
|
-
- An address in `functions` of an earlier
|
|
47
|
-
-
|
|
46
|
+
- An address in `functions` of an earlier decompiler result.
|
|
47
|
+
- The decompiler needs at least one entry point. DXA finds the SYS address of a BASIC start without help.
|
|
48
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.
|
|
49
49
|
- The two start vectors of a `CBM80` header at `$8000` are entry points without help.
|
|
50
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.
|
|
51
51
|
- If an analyzer decodes data as code, classify the region as data in the project knowledge. Then run `analyze` again.
|
|
52
52
|
- The facts of an analyzer are not entry points or data for the next analysis. Thus a new analysis can correct them.
|
|
53
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`.
|
|
54
|
-
-
|
|
55
|
-
- `--decompile` takes the address of a routine. Get it from `functions` of an earlier
|
|
54
|
+
- 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
|
+
- `--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
56
|
|
|
57
57
|
### Paths and the project folder
|
|
58
58
|
|
|
59
59
|
- Give each path relative to the project folder. The project folder is the nearest folder at or above the working directory that holds `.c64-re-tools/`.
|
|
60
60
|
- If the working directory is not in a project, give `--project <folder>` to each command. If the working directory has projects below it, the script refuses and lists them.
|
|
61
61
|
- In a group folder, each version of a program is a project. The script refuses the group folder and each folder in it that is not a project. Give `--project` with a project of the group, for example `--project v1`.
|
|
62
|
-
- A path that a command only reads can go into another project of the group, for example `../v1/
|
|
62
|
+
- A path that a command only reads can go into another project of the group, for example `../v1/releases/game.prg`. The command writes only in its own project.
|
|
63
63
|
- An address is `$` and 1 to 4 hex digits, for example `'$c000'` or `'$fb'`, or a name. A name is a symbol, else an analyzer name that only one analyzer gives. Put an address in single quotes in a shell.
|
|
64
64
|
- A range is `<start>-<end>`, for example `'$c000-$cfff'`. In a JSON file, a range is `start` and `end`.
|
|
65
65
|
- Bytes in a JSON file are hex in a field `data`, for example `"data": "a900"`.
|
|
@@ -80,13 +80,13 @@ Each flag applies only to the commands in the table. On another command, the scr
|
|
|
80
80
|
|
|
81
81
|
| Flag | Command | Effect |
|
|
82
82
|
|---|---|---|
|
|
83
|
-
| `--analyzer <dxa\|
|
|
83
|
+
| `--analyzer <dxa\|decompiler>` | `analyze` | The analyzer. `dxa` gives a fast first pass. `decompiler` gives a deeper pass. The default is `decompiler`. |
|
|
84
84
|
| `--entry <address>` | `analyze` | An entry point of the program. Give it again for more entry points. There is no default. |
|
|
85
|
-
| `--decompile <address>` | `analyze` |
|
|
85
|
+
| `--decompile <address>` | `analyze` | Only with `--analyzer decompiler`. Decompile the routine at this address. Give it again for more routines, at most 32. There is no default. |
|
|
86
86
|
| `--space <space>` | `analyze` | The knowledge space of the program: `drive8` for 1541 drive code, or `bank0` to `bank255` for a cartridge bank. The analysis reads the entry points from that space and writes the findings into it. The default is `c64`. |
|
|
87
87
|
| `--max-listed <n>` | `analyze` | List at most `n` items in each list. `0` lists no items. The counts stay complete. The default is 50. |
|
|
88
88
|
| `--out-listing <file>` | `analyze` | DXA only. Write the disassembly listing to this project file. There is no default. |
|
|
89
|
-
| `--out-instructions <file>` | `analyze` |
|
|
89
|
+
| `--out-instructions <file>` | `analyze` | Only with `--analyzer decompiler`. Write each instruction to this project file as JSON. There is no default. |
|
|
90
90
|
| `--apply-macros` | `analyze` | Write the macro candidates and their macros to the project knowledge as one revision of the LLM. Off by default. |
|
|
91
91
|
| `--skip <address>` | `analyze` | With `--apply-macros`: the start of a macro candidate that is not correct. The run does not write it. Give one `--skip` for each such candidate. |
|
|
92
92
|
|
|
@@ -96,13 +96,13 @@ Each flag applies only to the commands in the table. On another command, the scr
|
|
|
96
96
|
|
|
97
97
|
### `analyze`
|
|
98
98
|
|
|
99
|
-
Runs DXA or
|
|
99
|
+
Runs DXA or the decompiler over the program in the project knowledge. The script records the findings in the project knowledge as one revision. Then it records the 6502 idioms as a second revision. When the findings do not change the knowledge, the script records no revision for them.
|
|
100
100
|
|
|
101
|
-
The script records only structure: code and data regions, analyzer names, and the references from
|
|
101
|
+
The script records only structure: code and data regions, analyzer names, and the references from the decompiler. It does not record the listing or the decompiled code. Do not record the listing, the decompiled code or the function list as comments in the project knowledge.
|
|
102
102
|
|
|
103
103
|
`body` holds these fields for both analyzers:
|
|
104
104
|
|
|
105
|
-
- `analyzer`: `dxa` or `
|
|
105
|
+
- `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
106
|
- `revision`: the revision of the findings, or `null` when the knowledge did not change.
|
|
107
107
|
- `coverage`: the ranges that the analyzer examined.
|
|
108
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.
|
|
@@ -117,19 +117,21 @@ DXA also gives:
|
|
|
117
117
|
- `labels`: the names that DXA found, as a list.
|
|
118
118
|
- `listing`: the listing file, with `--out-listing`.
|
|
119
119
|
|
|
120
|
-
|
|
120
|
+
The decompiler also gives:
|
|
121
121
|
|
|
122
|
-
- `functions`: the routines that
|
|
122
|
+
- `functions`: the routines that the decompiler found, as a list, each with `entry` and `name`.
|
|
123
123
|
- `decompilations`: the C-like code of each `--decompile` routine, with `entry` and `text`. `truncated` tells that the text is cut.
|
|
124
|
-
- `notDecompiled`: the routines that
|
|
124
|
+
- `notDecompiled`: the routines that the decompiler did not decompile, each with a `reason`.
|
|
125
125
|
- `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
|
|
126
|
+
- `coverageGaps`: only with coverage. The executed instruction starts that are not in the instructions of the decompiler.
|
|
127
127
|
|
|
128
128
|
The `hint` gives each of these cases:
|
|
129
129
|
|
|
130
130
|
- `conflicts` is not empty. Find the correct answer in the emulator. Then correct the project knowledge.
|
|
131
131
|
- `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.
|
|
132
132
|
- `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
|
+
- 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
|
+
- `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.
|
|
133
135
|
- A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels` and `functions` as analyzer names.
|
|
134
136
|
|
|
135
137
|
There is no `nextAction`.
|
|
@@ -142,19 +144,19 @@ The script does not record the candidates. Examine each candidate and decide.
|
|
|
142
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.
|
|
143
145
|
- `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.
|
|
144
146
|
- `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.
|
|
145
|
-
- `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. `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.
|
|
147
|
+
- `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.
|
|
146
148
|
|
|
147
149
|
#### Which facts the analysis replaces
|
|
148
150
|
|
|
149
151
|
- The analysis never replaces a name or a region of the user or the LLM. Each disagreement shows in `conflicts`.
|
|
150
|
-
- DXA and
|
|
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.
|
|
151
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`.
|
|
152
|
-
- An idiom region (origin `heuristic`) replaces the part of a DXA or
|
|
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.
|
|
153
155
|
- An idiom table can be too long or too short. Correct its region in the project knowledge. Your region replaces it.
|
|
154
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.
|
|
155
157
|
- A fact that the user or the LLM removed does not come back. To remove a wrong fact, remove it in the project knowledge.
|
|
156
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.
|
|
157
|
-
- A
|
|
159
|
+
- A decompiler function that only branches and jumps reach is a `label`, not a `routine`.
|
|
158
160
|
|
|
159
161
|
#### Traps
|
|
160
162
|
|
|
@@ -171,7 +173,7 @@ The script does not record the candidates. Examine each candidate and decide.
|
|
|
171
173
|
|
|
172
174
|
#### Failures
|
|
173
175
|
|
|
174
|
-
- `invalid-input` about an entry point:
|
|
176
|
+
- `invalid-input` about an entry point: the decompiler has no entry point in the program. Give one with `--entry`.
|
|
175
177
|
- `stale-revision`: the project knowledge changed during the analysis. The script recorded nothing. Run `analyze` again.
|
|
176
178
|
- `operation-failed` about an incomplete result or listing: the analyzer did not give a complete result. The script recorded nothing. Tell the user.
|
|
177
179
|
- The script did not write the listing: the error tells if the project knowledge has the findings. Correct `--out-listing` and run `analyze` again.
|
|
@@ -184,7 +186,7 @@ The script does not record the candidates. Examine each candidate and decide.
|
|
|
184
186
|
2. Put each coverage map of the program into the project knowledge.
|
|
185
187
|
3. Run `analyze --analyzer dxa` for a first pass. Read the listing for a quick view of the code.
|
|
186
188
|
4. Find the important routines. Give them names in the project knowledge.
|
|
187
|
-
5. Run `analyze` with
|
|
189
|
+
5. Run `analyze` with the decompiler. Give the entry points with `--entry`. Give `--decompile` for the routines that you must understand.
|
|
188
190
|
6. Do the action for each `hint`. Examine the candidates.
|
|
189
191
|
7. Give each important routine a name in the project knowledge. Then run `analyze` again. The analyzers use the new names.
|
|
190
192
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
// Knowledge seeds for an analyzer, and the mapping of a
|
|
1
|
+
// Knowledge seeds for an analyzer, and the mapping of a decompiler result to the
|
|
2
2
|
// common normalized findings.
|
|
3
3
|
|
|
4
4
|
import type { DatabaseSync } from "node:sqlite";
|
|
@@ -6,9 +6,9 @@ import type { DatabaseSync } from "node:sqlite";
|
|
|
6
6
|
import type { NormalizedFindings } from "#src/knowledge/import.ts";
|
|
7
7
|
import { listRegions, listSymbols } from "#src/knowledge/read.ts";
|
|
8
8
|
import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, type Space } from "#src/knowledge/schema.ts";
|
|
9
|
-
import type { DxaResult,
|
|
9
|
+
import type { DxaResult, DecompilerParams, DecompilerResult } from "#src/native/types.ts";
|
|
10
10
|
|
|
11
|
-
export type Seeds = Pick<
|
|
11
|
+
export type Seeds = Pick<DecompilerParams, "entryPoints" | "dataRanges" | "labels">;
|
|
12
12
|
|
|
13
13
|
const semantic = (row: { origin: string }) => isSemantic(row.origin);
|
|
14
14
|
|
|
@@ -49,12 +49,12 @@ export function seedsFromKnowledge(db: DatabaseSync | undefined, extraEntryPoint
|
|
|
49
49
|
|
|
50
50
|
/**
|
|
51
51
|
* The 6510 opcodes with a low nibble of 1 or 3 use (zp,x) or (zp),y, also the
|
|
52
|
-
* undocumented ones.
|
|
52
|
+
* undocumented ones. The decompiler gives such an instruction a reference to the target
|
|
53
53
|
* that it computes from the pointer value at the entry state: a guess, because
|
|
54
54
|
* the program sets the pointer at run time. Only the reference to the pointer
|
|
55
55
|
* itself (zp or zp+1) is a fact.
|
|
56
56
|
*/
|
|
57
|
-
function guessedIndirectTarget(instructions:
|
|
57
|
+
function guessedIndirectTarget(instructions: DecompilerResult["instructions"]): (reference: { from: number; to: number }) => boolean {
|
|
58
58
|
const pointers = new Map<number, number>();
|
|
59
59
|
for (const instruction of instructions) {
|
|
60
60
|
const opcode = Number.parseInt(instruction.bytes.slice(0, 2), 16);
|
|
@@ -67,28 +67,28 @@ function guessedIndirectTarget(instructions: GhidraResult["instructions"]): (ref
|
|
|
67
67
|
}
|
|
68
68
|
|
|
69
69
|
/**
|
|
70
|
-
*
|
|
70
|
+
* The decompiler's result as normalized findings. A reference from a (zp,x) or (zp),y
|
|
71
71
|
* instruction to a computed target is not a finding (see guessedIndirectTarget).
|
|
72
72
|
* A function named by an echoed seed
|
|
73
73
|
* stays in the snapshot: its address holds the seed's semantic symbol, which
|
|
74
74
|
* the importer never replaces, so the name keeps its owner,
|
|
75
75
|
* and a code/data disagreement with that symbol is still reported.
|
|
76
76
|
*/
|
|
77
|
-
export function
|
|
78
|
-
//
|
|
77
|
+
export function decompilerFindings(result: DecompilerResult): NormalizedFindings {
|
|
78
|
+
// The decompiler can give one generated name to two functions, for example
|
|
79
79
|
// thunk_FUN_e434 to two thunks of one routine. A name
|
|
80
80
|
// must have one address, so a repeated name that is not a seed gets its address.
|
|
81
81
|
const uses = new Map<string, number>();
|
|
82
82
|
for (const fn of result.functions) uses.set(fn.name, (uses.get(fn.name) ?? 0) + 1);
|
|
83
|
-
const nameOf = (fn:
|
|
83
|
+
const nameOf = (fn: DecompilerResult["functions"][number]) =>
|
|
84
84
|
fn.nameSource !== "seed" && uses.get(fn.name)! > 1 ? `${fn.name}_${fn.entry.toString(16).padStart(4, "0")}` : fn.name;
|
|
85
85
|
// A function that branches and jumps reach, and no call, is a place in a routine: a label.
|
|
86
86
|
const called = new Set(result.references.filter((reference) => reference.type === "call").map((reference) => reference.to));
|
|
87
87
|
const jumped = new Set(result.references.filter((reference) => reference.type === "jump").map((reference) => reference.to));
|
|
88
88
|
const guessed = guessedIndirectTarget(result.instructions);
|
|
89
|
-
const kindOf = (fn:
|
|
89
|
+
const kindOf = (fn: DecompilerResult["functions"][number]) => (jumped.has(fn.entry) && !called.has(fn.entry) ? ("label" as const) : ("routine" as const));
|
|
90
90
|
return {
|
|
91
|
-
analyzer: "
|
|
91
|
+
analyzer: "decompiler",
|
|
92
92
|
coverage: result.coverage,
|
|
93
93
|
authoritative: { symbols: result.completeness.functions, regions: result.completeness.regions, references: result.completeness.references },
|
|
94
94
|
symbols: result.functions.map((fn) => ({ address: fn.entry, name: nameOf(fn), kind: kindOf(fn) })),
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
// The structured instruction list:
|
|
1
|
+
// The structured instruction list: the decompiler's decoded instructions with
|
|
2
2
|
// the addressing mode, the operand in 6502 syntax, the flow target and,
|
|
3
3
|
// with a coverage file, whether the instruction ran.
|
|
4
4
|
|
|
5
5
|
import { COVERAGE, formatC64Address } from "#src/c64.ts";
|
|
6
6
|
import { OPCODES, type Mode as OpcodeMode } from "#src/opcodes.ts";
|
|
7
|
-
import type {
|
|
7
|
+
import type { DecompilerInstruction } from "#src/native/types.ts";
|
|
8
8
|
|
|
9
9
|
export type Mode =
|
|
10
10
|
| "implied"
|
|
@@ -88,8 +88,8 @@ export interface ListedInstruction {
|
|
|
88
88
|
executed?: boolean;
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
-
/**
|
|
92
|
-
export function instructionList(instructions:
|
|
91
|
+
/** The decompiler's instructions as the list that --out-instructions writes. */
|
|
92
|
+
export function instructionList(instructions: DecompilerInstruction[], coverage?: Uint8Array): ListedInstruction[] {
|
|
93
93
|
return instructions.map((instruction) => {
|
|
94
94
|
const bytes = Buffer.from(instruction.bytes, "hex");
|
|
95
95
|
const mode = modeOf(bytes[0]!);
|
|
@@ -152,7 +152,9 @@ const MATCHERS: Record<string, { count: number; match: (run: Instruction[], name
|
|
|
152
152
|
const dst = memory(storeLow, "sta");
|
|
153
153
|
if (low === undefined || high === undefined || !same(dst, memory(storeHigh, "sta"), 1)) return undefined;
|
|
154
154
|
const value = low | (high << 8);
|
|
155
|
-
|
|
155
|
+
// A value of $0100 or more can be the address of a routine or a table, for example an IRQ handler: it gets its name.
|
|
156
|
+
// A smaller value is a number: the name of a zero-page address with that value is not what the code means.
|
|
157
|
+
return [addressArg(dst!, name), (value >= 0x100 ? name(value) : undefined) ?? formatC64Address(value)];
|
|
156
158
|
},
|
|
157
159
|
},
|
|
158
160
|
mov16: {
|