@henols/c64-re-tools 2.6.0-rc.4 → 2.6.0-rc.5
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 +2 -2
- package/skills/c64-assembler/scripts/assembler.ts +4 -5
- package/skills/c64-development/SKILL.md +1 -1
- package/skills/c64-docs/SKILL.md +4 -4
- package/skills/c64-docs/scripts/docs.ts +3 -3
- package/skills/c64-docs/scripts/lib/reference.ts +3 -3
- package/skills/c64-docs/scripts/lib/source-map.ts +9 -4
- package/skills/c64-knowledge/SKILL.md +25 -16
- package/skills/c64-knowledge/scripts/knowledge.ts +26 -41
- package/skills/c64-provenance/SKILL.md +11 -10
- package/skills/c64-provenance/scripts/lib/library.ts +16 -16
- package/skills/c64-provenance/scripts/provenance.ts +33 -23
- package/skills/c64-reverse-engineering/SKILL.md +6 -6
- package/skills/c64-source/SKILL.md +14 -14
- package/skills/c64-source/scripts/lib/source.ts +9 -9
- package/skills/c64-source/scripts/source.ts +76 -65
- package/skills/c64-static-analysis/SKILL.md +4 -4
- package/skills/c64-static-analysis/scripts/static-analysis.ts +26 -33
- package/src/build-name.ts +3 -0
- package/src/knowledge/program.ts +44 -1
- package/src/knowledge/read.ts +3 -7
- package/src/knowledge/schema.ts +27 -8
- package/src/knowledge/text.ts +4 -2
- package/src/knowledge/write.ts +47 -14
- package/src/project.ts +13 -1
|
@@ -14,28 +14,26 @@ 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 { buildName, symbolsPath } from "#src/build-name.ts";
|
|
17
|
+
import { BUILD_DIRECTORY, buildName, symbolsPath } from "#src/build-name.ts";
|
|
18
18
|
import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
|
|
19
19
|
import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
|
|
20
20
|
import { IO_RAM } from "#src/host-client/coverage.ts";
|
|
21
|
-
import { readImage, type Image } from "#src/host-client/image.ts";
|
|
22
|
-
import { readProjectFile } from "#src/host-client/transfer.ts";
|
|
23
21
|
import { MAX_MEMORY_READ, WireFailure } from "#src/host-client/tools.ts";
|
|
24
22
|
import { writeReported, type Written } from "#src/host-client/transfer.ts";
|
|
25
23
|
import { ViceSessionClient } from "#src/host-client/vice-session.ts";
|
|
26
24
|
import { conflicts } from "#src/knowledge/conflicts.ts";
|
|
27
25
|
import { openForRead, withWrite } from "#src/knowledge/database.ts";
|
|
28
26
|
import { identifiers } from "#src/knowledge/expression.ts";
|
|
29
|
-
import { analyzedBytes, memoryRows, programCoverage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
|
|
27
|
+
import { analyzedBytes, memoryRows, programCoverage, releaseImage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
|
|
30
28
|
import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, startScreenRanges, type StartScreenRow, listAnalyzerNames, listComments, listMacros, listMacroUses, listModules, listOperands, listPatches, listReferences, listRegions, listReleases, listSpaces, listSwitches, listSymbols, type ReleaseRow, type SymbolRow } from "#src/knowledge/read.ts";
|
|
31
|
-
import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
|
|
29
|
+
import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
|
|
32
30
|
import { subtract, write } from "#src/knowledge/write.ts";
|
|
33
31
|
import { assemble, symbolsFileText } from "#src/native/acme.ts";
|
|
34
32
|
import { analyze } from "#src/native/ghidra/analyze.ts";
|
|
35
33
|
import { localToolContext } from "#src/native/local.ts";
|
|
36
34
|
import { GHIDRA_LIMITS, type AssembledSymbol, type Diagnostic } from "#src/native/types.ts";
|
|
37
35
|
import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romRanges, romUseOfProgram } from "#src/platform.ts";
|
|
38
|
-
import { ensureLocal, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRoot, resolveProjectPath } from "#src/project.ts";
|
|
36
|
+
import { ensureLocal, generatedDirectory, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
|
|
39
37
|
import { isoCet } from "#src/time.ts";
|
|
40
38
|
import { zipFiles } from "#src/zip.ts";
|
|
41
39
|
import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
|
|
@@ -109,7 +107,8 @@ function readKnowledge(space: Space, analyzerNames = false) {
|
|
|
109
107
|
operands: listOperands(db, undefined, undefined, space),
|
|
110
108
|
patches: listPatches(db, undefined, undefined, undefined, space),
|
|
111
109
|
switches: listSwitches(db, undefined, space).map((row): SourceSwitch => ({ name: row.name, kind: row.kind, default: row.default, base: baseValue(row, base), releases: row.releases, ...(row.comment === undefined ? {} : { comment: row.comment }) })),
|
|
112
|
-
|
|
110
|
+
// Each release with its bytes: the check builds it and compares the build with them.
|
|
111
|
+
releases: releases.map((release) => ({ ...release, image: releaseImage(db, release.label, space)! })),
|
|
113
112
|
macros: listMacros(db, undefined, space),
|
|
114
113
|
macroUses: listMacroUses(db, undefined, undefined, undefined, space),
|
|
115
114
|
// The start screen is of the C64 program: the loader shows it.
|
|
@@ -480,36 +479,25 @@ async function checkSwitch(row: SourceSwitch, patches: PatchBlock[], files: Arra
|
|
|
480
479
|
};
|
|
481
480
|
}
|
|
482
481
|
|
|
483
|
-
/** What the build of a release gives against the bytes of
|
|
482
|
+
/** What the build of a release gives against the bytes of the release in the knowledge. */
|
|
484
483
|
interface ReleaseCheck {
|
|
485
484
|
label: string;
|
|
486
485
|
base: boolean;
|
|
487
|
-
file: string;
|
|
488
486
|
define: string;
|
|
489
|
-
result: "identical" | "different" | "layout differs" | "
|
|
487
|
+
result: "identical" | "different" | "layout differs" | "does not assemble";
|
|
490
488
|
reason?: string;
|
|
491
489
|
segments?: SegmentCheck[];
|
|
492
490
|
diagnostics?: Diagnostic[];
|
|
493
491
|
}
|
|
494
492
|
|
|
495
493
|
/**
|
|
496
|
-
* Builds a release with RELEASE_<label> and compares it with its
|
|
494
|
+
* Builds a release with RELEASE_<label> and compares it with its bytes. A
|
|
497
495
|
* release whose segments are not the segments of the program has moved code,
|
|
498
496
|
* which patches cannot give: it is shown and does not fail the run.
|
|
499
497
|
*/
|
|
500
|
-
async function checkRelease(release: ReleaseRow, files: Array<{ name: string; text: string }>, program: ProgramImage): Promise<ReleaseCheck> {
|
|
501
|
-
const shown = { label: release.label, base: release.base,
|
|
502
|
-
|
|
503
|
-
try {
|
|
504
|
-
const bytes = readProjectFile(release.file).bytes;
|
|
505
|
-
if (createHash("sha256").update(bytes).digest("hex") !== release.sha256) {
|
|
506
|
-
return { ...shown, result: "file changed", reason: `The SHA-256 of ${release.file} is not the one that the knowledge has. Put back the file, or record the release again in the project knowledge.` };
|
|
507
|
-
}
|
|
508
|
-
image = readImage(release.file);
|
|
509
|
-
} catch (error) {
|
|
510
|
-
if (!(error instanceof Refusal || error instanceof WireFailure)) throw error;
|
|
511
|
-
return { ...shown, result: "file changed", reason: error.message };
|
|
512
|
-
}
|
|
498
|
+
async function checkRelease(release: ReleaseRow & { image: Pick<ProgramImage, "segments" | "byteAt"> }, files: Array<{ name: string; text: string }>, program: ProgramImage): Promise<ReleaseCheck> {
|
|
499
|
+
const shown = { label: release.label, base: release.base, define: `--define ${RELEASE_DEFINE}${release.label}=1` };
|
|
500
|
+
const { image } = release;
|
|
513
501
|
if (JSON.stringify(image.segments) !== JSON.stringify(program.segments)) {
|
|
514
502
|
const segments = (list: readonly AddressRange[]) => list.map((segment) => `${formatC64Address(segment.start)}-${formatC64Address(segment.end)}`).join(", ");
|
|
515
503
|
return { ...shown, result: "layout differs", reason: `The release has the segments ${segments(image.segments)}, and the program has ${segments(program.segments)}. Patches change bytes in place; they cannot move code.` };
|
|
@@ -715,13 +703,13 @@ const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", START_SCREEN_FI
|
|
|
715
703
|
/** A loader program that generate wrote: its build name, as buildName gives it for loader.asm. */
|
|
716
704
|
const LOADER_PROGRAM = /^(clean|custom_[a-z0-9_]+|release_[A-Za-z0-9_]+)_loader\.prg$/;
|
|
717
705
|
|
|
718
|
-
/** The loader programs of earlier runs in
|
|
719
|
-
function loaderPrograms(
|
|
720
|
-
const directory = resolveProjectPath(
|
|
706
|
+
/** The loader programs of earlier runs in the build folder, with their symbols files. */
|
|
707
|
+
function loaderPrograms(): string[] {
|
|
708
|
+
const directory = resolveProjectPath(BUILD_DIRECTORY);
|
|
721
709
|
if (!existsSync(directory)) return [];
|
|
722
710
|
return readdirSync(directory)
|
|
723
711
|
.filter((name) => LOADER_PROGRAM.test(name))
|
|
724
|
-
.flatMap((name) => [`${
|
|
712
|
+
.flatMap((name) => [`${BUILD_DIRECTORY}/${name}`, symbolsPath(`${BUILD_DIRECTORY}/${name}`)])
|
|
725
713
|
.filter((path) => existsSync(resolveProjectPath(path)));
|
|
726
714
|
}
|
|
727
715
|
|
|
@@ -742,7 +730,7 @@ function staleLoader(out: string, revision: string): { files: string[]; revision
|
|
|
742
730
|
const line = text.split(/\r?\n/).find((row) => row.startsWith(`; ${LOADER_REVISION}`));
|
|
743
731
|
const old = line?.slice(`; ${LOADER_REVISION}`.length).replace(/\.$/, "");
|
|
744
732
|
if (old === revision) return undefined;
|
|
745
|
-
const files = [...[...LOADER_FILES].filter((name) => existsSync(resolveProjectPath(`${out}/${name}`))).map((name) => `${out}/${name}`), ...loaderPrograms(
|
|
733
|
+
const files = [...[...LOADER_FILES].filter((name) => existsSync(resolveProjectPath(`${out}/${name}`))).map((name) => `${out}/${name}`), ...loaderPrograms()];
|
|
746
734
|
return { files, ...(old === undefined ? {} : { revision: old }) };
|
|
747
735
|
}
|
|
748
736
|
|
|
@@ -751,13 +739,15 @@ const LEFTOVER_RANGE = /^; Leftovers (\$[0-9a-f]{4})-(\$[0-9a-f]{4}):/m;
|
|
|
751
739
|
|
|
752
740
|
/**
|
|
753
741
|
* The leftovers of the earlier run: the ranges of its generated leftover
|
|
754
|
-
* files in `out`. Undefined when `out` has no
|
|
755
|
-
* was no earlier run to compare with.
|
|
742
|
+
* files in the leftovers folder of `out`. Undefined when `out` has no
|
|
743
|
+
* generated main.asm, so there was no earlier run to compare with.
|
|
756
744
|
*/
|
|
757
745
|
function earlierLeftovers(out: string): AddressRange[] | undefined {
|
|
758
|
-
const
|
|
759
|
-
const main = join(
|
|
746
|
+
const root = resolveProjectPath(out);
|
|
747
|
+
const main = join(root, "main.asm");
|
|
760
748
|
if (!existsSync(main) || !readFileSync(main, "utf8").startsWith(GENERATED_MARK)) return undefined;
|
|
749
|
+
const directory = join(root, LEFTOVER_FOLDER);
|
|
750
|
+
if (!existsSync(directory)) return [];
|
|
761
751
|
return readdirSync(directory)
|
|
762
752
|
.filter((name) => /^leftover_[0-9a-f]{4}\.asm$/.test(name))
|
|
763
753
|
.flatMap((name) => {
|
|
@@ -773,26 +763,45 @@ function outside(ranges: readonly AddressRange[], others: readonly AddressRange[
|
|
|
773
763
|
|
|
774
764
|
/**
|
|
775
765
|
* Removes the generated .asm files of an earlier run that this run does not
|
|
776
|
-
* write, and
|
|
777
|
-
* loader.asm stays unless this run has
|
|
778
|
-
* include loader.asm.
|
|
779
|
-
*
|
|
780
|
-
*
|
|
766
|
+
* write, and the reports of the earlier run (its source map and
|
|
767
|
+
* not_executed.json). An earlier loader.asm stays unless this run has
|
|
768
|
+
* --loader: a source of the user can include loader.asm. The files of a
|
|
769
|
+
* module are in `out` or in one folder of it: a folder that the run leaves
|
|
770
|
+
* empty goes too. Other files stay. Gives the paths it removed.
|
|
781
771
|
*/
|
|
782
772
|
function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boolean): string[] {
|
|
783
|
-
const directory = resolveProjectPath(out);
|
|
784
|
-
if (!existsSync(directory)) return [];
|
|
785
773
|
const removed: string[] = [];
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
const
|
|
789
|
-
|
|
790
|
-
if (LOADER_FILES.has(name) && !loaderRun) continue;
|
|
791
|
-
const old = name === NOT_EXECUTED_FILE || name === SOURCE_MAP_FILE || (name.endsWith(".asm") && !keep.has(name) && readFileSync(path, "utf8").startsWith(GENERATED_MARK));
|
|
792
|
-
if (!old) continue;
|
|
774
|
+
const reports = generatedDirectory(projectRelative(out));
|
|
775
|
+
for (const name of [SOURCE_MAP_FILE, NOT_EXECUTED_FILE]) {
|
|
776
|
+
const path = resolveProjectPath(`${reports}/${name}`);
|
|
777
|
+
if (!existsSync(path)) continue;
|
|
793
778
|
rmSync(path, { force: true });
|
|
794
|
-
removed.push(name);
|
|
779
|
+
removed.push(`${reports}/${name}`);
|
|
795
780
|
}
|
|
781
|
+
const root = resolveProjectPath(out);
|
|
782
|
+
if (!existsSync(root)) return removed;
|
|
783
|
+
/** Removes the old generated files of a folder ("" for `out` itself), and gives how many. */
|
|
784
|
+
const clean = (folder: string): number => {
|
|
785
|
+
const directory = folder === "" ? root : join(root, folder);
|
|
786
|
+
let count = 0;
|
|
787
|
+
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
788
|
+
const name = folder === "" ? entry.name : `${folder}/${entry.name}`;
|
|
789
|
+
if (entry.isDirectory() && folder === "") {
|
|
790
|
+
// A folder of the user that held no generated file stays, also when it is empty.
|
|
791
|
+
if (clean(name) > 0 && readdirSync(join(root, name)).length === 0) rmSync(join(root, name), { recursive: true, force: true });
|
|
792
|
+
continue;
|
|
793
|
+
}
|
|
794
|
+
if (!entry.isFile()) continue;
|
|
795
|
+
const path = join(directory, entry.name);
|
|
796
|
+
if (LOADER_FILES.has(name) && !loaderRun) continue;
|
|
797
|
+
if (!name.endsWith(".asm") || keep.has(name) || !readFileSync(path, "utf8").startsWith(GENERATED_MARK)) continue;
|
|
798
|
+
rmSync(path, { force: true });
|
|
799
|
+
removed.push(`${out}/${name}`);
|
|
800
|
+
count++;
|
|
801
|
+
}
|
|
802
|
+
return count;
|
|
803
|
+
};
|
|
804
|
+
clean("");
|
|
796
805
|
return removed;
|
|
797
806
|
}
|
|
798
807
|
|
|
@@ -851,7 +860,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
|
|
|
851
860
|
operands: knowledge.operands,
|
|
852
861
|
patches: knowledge.patches,
|
|
853
862
|
switches: knowledge.switches,
|
|
854
|
-
releases: knowledge.releases.map((release) => ({ label: release.label,
|
|
863
|
+
releases: knowledge.releases.map((release) => ({ label: release.label, base: release.base, ...(release.comment === undefined ? {} : { comment: release.comment }) })),
|
|
855
864
|
macros: knowledge.macros,
|
|
856
865
|
macroUses: knowledge.macroUses,
|
|
857
866
|
startScreen: knowledge.startScreen !== undefined && options.exported !== true,
|
|
@@ -1145,10 +1154,12 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1145
1154
|
const loaderName = buildName("loader.asm", { values: kept, defaults: new Map(configured.map((row) => [row.name, row.default])) });
|
|
1146
1155
|
// Read before the old files go: the leftovers of the earlier run, to tell what changed.
|
|
1147
1156
|
const earlier = earlierLeftovers(out);
|
|
1148
|
-
const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted)
|
|
1157
|
+
const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted);
|
|
1149
1158
|
const stale = loaderWanted || space !== DEFAULT_SPACE ? undefined : staleLoader(out, knowledge.revision);
|
|
1150
1159
|
const written: Written[] = withValues(files, laid, kept).map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
|
|
1151
|
-
|
|
1160
|
+
// The reports go to the local folder: the source folder holds only source files.
|
|
1161
|
+
const reports = generatedDirectory(projectRelative(out));
|
|
1162
|
+
written.push(writeReported(`${reports}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.revision, files)));
|
|
1152
1163
|
const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
|
|
1153
1164
|
const inData = entriesInData(entries, knowledge.regions);
|
|
1154
1165
|
if (rendered.notExecuted !== undefined) {
|
|
@@ -1162,7 +1173,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1162
1173
|
const files: Record<string, number> = {};
|
|
1163
1174
|
for (const range of placed) if (range.file !== undefined) files[range.file] = (files[range.file] ?? 0) + 1;
|
|
1164
1175
|
const all = { revision: knowledge.revision, instructions: rendered.notExecuted.instructions, files, ranges: placed };
|
|
1165
|
-
written.push(writeReported(`${
|
|
1176
|
+
written.push(writeReported(`${reports}/${NOT_EXECUTED_FILE}`, `${JSON.stringify(all, null, 2)}\n`));
|
|
1166
1177
|
}
|
|
1167
1178
|
// The leftovers that changed since the earlier run: the default build and the loader now leave out other bytes.
|
|
1168
1179
|
const added = earlier === undefined ? [] : outside(laid.leftovers, earlier);
|
|
@@ -1172,7 +1183,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1172
1183
|
const output: Record<string, unknown> = {
|
|
1173
1184
|
out,
|
|
1174
1185
|
files: written,
|
|
1175
|
-
sourceMap: `${
|
|
1186
|
+
sourceMap: `${reports}/${SOURCE_MAP_FILE}`,
|
|
1176
1187
|
// The values that config.asm keeps and that are not the default: a build of the source is not the default build.
|
|
1177
1188
|
...(notDefault.length === 0 ? {} : { config: { file: `${out}/${CONFIG_FILE}`, notDefault } }),
|
|
1178
1189
|
revision: knowledge.revision,
|
|
@@ -1196,7 +1207,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1196
1207
|
...(rendered.notExecuted === undefined
|
|
1197
1208
|
? {}
|
|
1198
1209
|
: {
|
|
1199
|
-
notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `${
|
|
1210
|
+
notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `${reports}/${NOT_EXECUTED_FILE}`) },
|
|
1200
1211
|
}),
|
|
1201
1212
|
...(laid.unusedModules.length === 0 ? {} : { unusedModules: laid.unusedModules.map((module) => ({ start: formatC64Address(module.start), file: module.file })) }),
|
|
1202
1213
|
// The bytes that nothing uses: in leftover files, which the default build and the loader leave out.
|
|
@@ -1206,7 +1217,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1206
1217
|
: changed === undefined
|
|
1207
1218
|
? {}
|
|
1208
1219
|
: { leftovers: { bytes: 0, changed } }
|
|
1209
|
-
: { leftovers: { bytes: laid.leftovers.reduce((sum, range) => sum + range.end - range.start + 1, 0), ...listed(laid.leftovers, max, (range) => ({ ...showRange(range), bytes: range.end - range.start + 1, file:
|
|
1220
|
+
: { leftovers: { bytes: laid.leftovers.reduce((sum, range) => sum + range.end - range.start + 1, 0), ...listed(laid.leftovers, max, (range) => ({ ...showRange(range), bytes: range.end - range.start + 1, file: `${LEFTOVER_FOLDER}/leftover_${range.start.toString(16).padStart(4, "0")}.asm` })), ...(changed === undefined ? {} : { changed }) } }),
|
|
1210
1221
|
...(rendered.expressions.length === 0 && rendered.operandsAsNumbers.length === 0 ? {} : { operandExpressions: rendered.expressions.length }),
|
|
1211
1222
|
...(rendered.operandsAsNumbers.length === 0
|
|
1212
1223
|
? {}
|
|
@@ -1227,10 +1238,10 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1227
1238
|
patchesNotWritten: listed(laid.patchesNotWritten, max, (item) => ({ start: formatC64Address(item.start), end: formatC64Address(item.end), switch: item.switch, reason: item.reason })),
|
|
1228
1239
|
}),
|
|
1229
1240
|
};
|
|
1230
|
-
// A loader program of an earlier run stays when this run checks no new one
|
|
1231
|
-
const loaderPath = `${
|
|
1241
|
+
// The loader program is a build: it goes to the build folder. A loader program of an earlier run stays when this run checks no new one.
|
|
1242
|
+
const loaderPath = `${BUILD_DIRECTORY}/${loaderName}.prg`;
|
|
1232
1243
|
const keptLoader = () => {
|
|
1233
|
-
const earlier = loaderPrograms(
|
|
1244
|
+
const earlier = loaderPrograms().filter((path) => path.endsWith(".prg"));
|
|
1234
1245
|
return earlier.length === 0 ? {} : { kept: earlier };
|
|
1235
1246
|
};
|
|
1236
1247
|
const notVerified = (fields: Record<string, unknown>) => ({ verified: false, ...fields, ...keptLoader() });
|
|
@@ -1298,7 +1309,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1298
1309
|
}
|
|
1299
1310
|
}
|
|
1300
1311
|
const program = stage?.program ?? packed?.program ?? copierBuild;
|
|
1301
|
-
// The check runs the new loader from a scratch file. Only a loader whose check ran goes to
|
|
1312
|
+
// The check runs the new loader from a scratch file. Only a loader whose check ran goes to the build folder, so a check
|
|
1302
1313
|
// that cannot run (no host, or a host of another release) keeps the loader program of an earlier run.
|
|
1303
1314
|
ensureLocal(projectRoot());
|
|
1304
1315
|
const scratch = `${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/${LOADER_CHECK_DIRECTORY}`;
|
|
@@ -1320,17 +1331,17 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1320
1331
|
ran = await runLoader(checkPath, program, loader, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined ? {} : { startScreen }), ...stageRun }, expected);
|
|
1321
1332
|
} catch (error) {
|
|
1322
1333
|
if (!isRefusal(error)) throw error;
|
|
1323
|
-
const what = loaderPrograms(
|
|
1334
|
+
const what = loaderPrograms().length > 0 ? "kept the loader program of an earlier run" : "wrote no loader program";
|
|
1324
1335
|
return { output: { ...output, loader: notVerified({ reason: `The check of ${loaderName}.prg did not run, so the script ${what}. ${error.message}` }) }, removed, failed: true };
|
|
1325
1336
|
} finally {
|
|
1326
1337
|
rmSync(resolveProjectPath(scratch), { recursive: true, force: true });
|
|
1327
1338
|
}
|
|
1328
1339
|
// A loader program of an earlier run with another build name goes: config.asm has other values now.
|
|
1329
|
-
for (const path of loaderPrograms(
|
|
1340
|
+
for (const path of loaderPrograms().filter((item) => item !== loaderPath && item !== symbolsPath(loaderPath))) {
|
|
1330
1341
|
rmSync(resolveProjectPath(path), { force: true });
|
|
1331
1342
|
removed.push(path);
|
|
1332
1343
|
}
|
|
1333
|
-
written.push(writeReported(loaderPath, program
|
|
1344
|
+
written.push(writeReported(loaderPath, program), writeReported(symbolsPath(loaderPath), symbolsFileText(loaderSymbols(loaderMain.symbols, loaderBuilt.symbols, stage?.symbols ?? []))));
|
|
1334
1345
|
if (stage !== undefined) written.push(writeReported(`${out}/${STAGE_FILE}`, stage.text, { what: "--out" }), writeReported(`${out}/${START_SCREEN_FILE}`, `${GENERATED_LINE}\n${START_SCREEN_CODE}`, { what: "--out" }));
|
|
1335
1346
|
output.loader = {
|
|
1336
1347
|
program: loaderPath,
|
|
@@ -1795,16 +1806,16 @@ await runScript({
|
|
|
1795
1806
|
commands: [
|
|
1796
1807
|
{
|
|
1797
1808
|
name: "generate",
|
|
1798
|
-
summary: "Writes the source files
|
|
1809
|
+
summary: "Writes the source files to --out and checks them. The source map and not_executed.json go to .c64-re-tools/local/generated/<dir>/. result is PASS when every check passes, else FAIL.",
|
|
1799
1810
|
options: {
|
|
1800
1811
|
out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "the folder for the source files, relative to the project folder", required: true },
|
|
1801
1812
|
entry: { ...OPTIONS.entry, multiple: true, help: "an address where code starts. The entry of the program, the routines and the code regions of the knowledge are entry points too" },
|
|
1802
1813
|
space: { ...OPTIONS.space, help: "the knowledge space of the program: c64 (the default), drive8, loading, or bank0 to bank255. --loader is for c64 only" },
|
|
1803
|
-
loader: { kind: "flag", help: "also write loader.asm and the loader program
|
|
1814
|
+
loader: { kind: "flag", help: "also write loader.asm, and write the loader program to build/<build>_loader.prg (build/clean_loader.prg with the defaults of config.asm), with its symbols in build/symbols/: the loader copies the segments into place, sets the entry state of the knowledge, and jumps to the entry. It is checked in the emulator. The loader leaves out the leftovers. When the check cannot run, the script keeps the loader program of an earlier run" },
|
|
1804
1815
|
"analyzer-names": { kind: "flag", help: "name an address that has no name of the user or the LLM, and no platform name, with its analyzer name" },
|
|
1805
1816
|
"max-listed": OPTIONS["max-listed"],
|
|
1806
1817
|
},
|
|
1807
|
-
notes: "The program, its entry state and the coverage come from the knowledge: put them into the project knowledge first. Code that no imported run executed is marked and listed, and
|
|
1818
|
+
notes: "The program, its entry state and the coverage come from the knowledge: put them into the project knowledge first. Code that no imported run executed is marked and listed, and .c64-re-tools/local/generated/<dir>/not_executed.json has all of its ranges. Without --analyzer-names, an address without a name gets a name of the source, for example l_17e2.",
|
|
1808
1819
|
run: async (call) => {
|
|
1809
1820
|
const { output, failed, removed } = await generate(call);
|
|
1810
1821
|
// A file of an earlier run that this run removed and did not write again.
|
|
@@ -29,7 +29,7 @@ To get the command list, run the script with no arguments.
|
|
|
29
29
|
| Get C-like code of a routine | `analyze --entry '$080d' --decompile '$0818'` |
|
|
30
30
|
| Get each instruction as JSON | `analyze --entry '$080d' --out-instructions .c64-re-tools/local/instructions.json` |
|
|
31
31
|
| Analyze drive code or a cartridge bank | `analyze --space drive8` |
|
|
32
|
-
|
|
|
32
|
+
| Write the macro candidates to the project knowledge | `analyze --apply-macros` |
|
|
33
33
|
| Get more items in each list | `analyze --max-listed 500` |
|
|
34
34
|
|
|
35
35
|
---
|
|
@@ -86,7 +86,7 @@ Each flag applies only to the commands in the table. On another command, the scr
|
|
|
86
86
|
| `--max-listed <n>` | `analyze` | List at most `n` items in each list. `0` lists no items. The counts stay complete. The default is 50. |
|
|
87
87
|
| `--out-listing <file>` | `analyze` | DXA only. Write the disassembly listing to this project file. There is no default. |
|
|
88
88
|
| `--out-instructions <file>` | `analyze` | Ghidra only. Write each instruction to this project file as JSON. There is no default. |
|
|
89
|
-
| `--
|
|
89
|
+
| `--apply-macros` | `analyze` | Write the macro candidates and their macros to the project knowledge as one revision of the LLM. Off by default. |
|
|
90
90
|
|
|
91
91
|
---
|
|
92
92
|
|
|
@@ -127,7 +127,7 @@ The `hint` gives each of these cases:
|
|
|
127
127
|
|
|
128
128
|
- `conflicts` is not empty. Find the correct answer in the emulator. Then correct the project knowledge.
|
|
129
129
|
- `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.
|
|
130
|
-
-
|
|
130
|
+
- `macros` has candidates, and the run had no `--apply-macros`. Examine the candidates. To write them to the project knowledge, run the analysis again with `--apply-macros`. Then generate the source again.
|
|
131
131
|
- A list is cut. Give a larger `--max-listed`. The project knowledge has all `labels` and `functions` as analyzer names.
|
|
132
132
|
|
|
133
133
|
There is no `nextAction`.
|
|
@@ -140,7 +140,7 @@ The script does not record the candidates. Examine each candidate and decide.
|
|
|
140
140
|
- `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.
|
|
141
141
|
- `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.
|
|
142
142
|
- `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.
|
|
143
|
-
- `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 or a use over them. With `--
|
|
143
|
+
- `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 or a use 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, and the uses. `otherMacros` names each macro that the project knowledge has with another body. The writes do not have the uses of that macro.
|
|
144
144
|
|
|
145
145
|
#### Which facts the analysis replaces
|
|
146
146
|
|
|
@@ -13,7 +13,8 @@ import { analyze as analyzeWithGhidra } from "#src/native/ghidra/analyze.ts";
|
|
|
13
13
|
import { localToolContext } from "#src/native/local.ts";
|
|
14
14
|
import { GHIDRA_LIMITS } from "#src/native/types.ts";
|
|
15
15
|
import { openForRead, withWrite } from "#src/knowledge/database.ts";
|
|
16
|
-
import { analyzedBytes, programCoverage, requireProgram } from "#src/knowledge/program.ts";
|
|
16
|
+
import { analyzedBytes, operandImages, programCoverage, requireProgram } from "#src/knowledge/program.ts";
|
|
17
|
+
import { applyBatch, type BatchOperation } from "#src/knowledge/write.ts";
|
|
17
18
|
import { importFindings, runProvenance, type ImportConflict, type ImportContext, type ImportResult, type NormalizedFindings } from "#src/knowledge/import.ts";
|
|
18
19
|
import { currentRevision, listMacros, listMacroUses, listPatches, listReferences, listRegions, listSymbols } from "#src/knowledge/read.ts";
|
|
19
20
|
import { DEFAULT_SPACE, SEMANTIC_ORIGINS, type Analyzer } from "#src/knowledge/schema.ts";
|
|
@@ -32,14 +33,15 @@ const ALL_NAMES = "a larger --max-listed. The project knowledge has all of them
|
|
|
32
33
|
|
|
33
34
|
/**
|
|
34
35
|
* The result with a hint for what the agent does next: conflicts to examine,
|
|
35
|
-
* analyzer data over executed code to classify, and
|
|
36
|
+
* analyzer data over executed code to classify, and macro candidates to write.
|
|
36
37
|
* The envelope adds the sentence for a cut list.
|
|
37
38
|
*/
|
|
38
|
-
function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number,
|
|
39
|
+
function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }) {
|
|
39
40
|
const hints: string[] = [];
|
|
40
41
|
if (conflicts > 0) hints.push("The analysis and the project knowledge disagree at each place in conflicts. Find the correct answer in the emulator. Then correct the project knowledge.");
|
|
41
42
|
if (coverageConflicts > 0) hints.push("The coverage shows executed code in each range of coverageConflicts. Classify each range as code, or as dual-use when its bytes are also data, in the project knowledge.");
|
|
42
|
-
if (
|
|
43
|
+
if (typeof macros.revision === "string") hints.push("The project knowledge has the macro candidates now. Generate the source again.");
|
|
44
|
+
else if (!macros.applied && macros.candidates > 0) hints.push("Examine idioms.candidates.macros. To write them to the project knowledge, run the analysis again with --apply-macros.");
|
|
43
45
|
if (hints.length === 0) return body;
|
|
44
46
|
return reply(body, { hint: hints.join(" ") });
|
|
45
47
|
}
|
|
@@ -73,11 +75,11 @@ function showMacro(candidate: MacroCandidate) {
|
|
|
73
75
|
* the ROMs that the program uses, as c64-source names them. A candidate is left out when
|
|
74
76
|
* a name or a reference target is inside it, or a patch or a use overlaps it:
|
|
75
77
|
* c64-source would write its instructions. The same use in the knowledge is
|
|
76
|
-
* known.
|
|
77
|
-
*
|
|
78
|
-
*
|
|
78
|
+
* known. The writes are the candidates with the macros they need. A macro of
|
|
79
|
+
* the catalogue that the knowledge has with another body leaves its
|
|
80
|
+
* candidates out of the writes.
|
|
79
81
|
*/
|
|
80
|
-
function macroCandidates(space: string, byteAt: ImageByte,
|
|
82
|
+
function macroCandidates(space: string, byteAt: ImageByte, romUse: RomUse) {
|
|
81
83
|
const db = openForRead();
|
|
82
84
|
try {
|
|
83
85
|
// The platform names that c64-source uses: a name of a ROM that the program does not use is no arg.
|
|
@@ -98,33 +100,20 @@ function macroCandidates(space: string, byteAt: ImageByte, batchPath: string | u
|
|
|
98
100
|
else if ([...named].some((address) => address > candidate.start && address <= candidate.end) || patches.some((patch) => overlaps(patch, candidate)) || uses.some((use) => overlaps(use, candidate))) leftOut++;
|
|
99
101
|
else candidates.push(candidate);
|
|
100
102
|
}
|
|
101
|
-
|
|
102
|
-
// A macro of the catalogue goes into the batch unless the knowledge has it; with another body, its uses stay out.
|
|
103
|
+
// A macro of the catalogue goes into the writes unless the knowledge has it; with another body, its uses stay out.
|
|
103
104
|
const macros = new Map(listMacros(db, undefined, space).map((macro) => [macro.name, macro]));
|
|
104
|
-
const
|
|
105
|
-
const batched: MacroCandidate[] = [];
|
|
105
|
+
const writes: BatchOperation[] = [];
|
|
106
106
|
const other = new Set<string>();
|
|
107
107
|
for (const idiom of CATALOGUE.filter((item) => candidates.some((candidate) => candidate.macro === item.name))) {
|
|
108
108
|
const existing = macros.get(idiom.name);
|
|
109
|
-
if (existing === undefined)
|
|
109
|
+
if (existing === undefined) writes.push({ op: "macro", space, name: idiom.name, params: [...idiom.params], body: idiom.body, comment: idiom.comment });
|
|
110
110
|
else if (existing.params.join(",") !== idiom.params.join(",") || existing.body !== idiom.body) other.add(idiom.name);
|
|
111
111
|
}
|
|
112
112
|
for (const candidate of candidates) {
|
|
113
113
|
if (other.has(candidate.macro)) continue;
|
|
114
|
-
|
|
115
|
-
batch.push({ op: "use", start: formatC64Address(candidate.start), end: formatC64Address(candidate.end), macro: candidate.macro, args: candidate.args, ...(space === DEFAULT_SPACE ? {} : { space }) });
|
|
114
|
+
writes.push({ op: "use", space, start: candidate.start, end: candidate.end, macro: candidate.macro, args: candidate.args });
|
|
116
115
|
}
|
|
117
|
-
|
|
118
|
-
return {
|
|
119
|
-
candidates,
|
|
120
|
-
known,
|
|
121
|
-
leftOut,
|
|
122
|
-
batch: {
|
|
123
|
-
...written,
|
|
124
|
-
writes: batch.length,
|
|
125
|
-
...(other.size === 0 ? {} : { otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not in the batch.`) }),
|
|
126
|
-
},
|
|
127
|
-
};
|
|
116
|
+
return { candidates, known, leftOut, writes, otherMacros: [...other].map((name) => `The knowledge has another macro ${name}: its candidates are not written.`) };
|
|
128
117
|
} finally {
|
|
129
118
|
db?.close();
|
|
130
119
|
}
|
|
@@ -194,7 +183,7 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
194
183
|
const analyzer = call.string("analyzer") as "dxa" | "ghidra";
|
|
195
184
|
const listingPath = call.string("out-listing");
|
|
196
185
|
const instructionsPath = call.string("out-instructions");
|
|
197
|
-
const
|
|
186
|
+
const applyMacros = call.flag("apply-macros");
|
|
198
187
|
if (analyzer === "dxa" && decompile.length > 0) throw new UsageError("--decompile works only with --analyzer ghidra");
|
|
199
188
|
if (analyzer === "ghidra" && listingPath !== undefined) throw new UsageError("--out-listing works only with --analyzer dxa");
|
|
200
189
|
if (analyzer === "dxa" && instructionsPath !== undefined) throw new UsageError("--out-instructions works only with --analyzer ghidra");
|
|
@@ -241,7 +230,10 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
241
230
|
const idiomsResult = () => {
|
|
242
231
|
const imported = withWrite((db) => importFindings(db, { ...idioms.findings, space }, { description: "Idioms in the program" }));
|
|
243
232
|
// The macro candidates read the code regions after both imports.
|
|
244
|
-
const macros = macroCandidates(space, byteAt,
|
|
233
|
+
const macros = macroCandidates(space, byteAt, romUseOfProgram(coverage, program.state));
|
|
234
|
+
// With --apply-macros, the candidates and their macros are a third revision of the LLM.
|
|
235
|
+
const platformNamed = new Map(platformNames().map((entry) => [entry.name, entry.address]));
|
|
236
|
+
const written = applyMacros && macros.writes.length > 0 ? withWrite((db) => applyBatch(db, { origin: "llm", description: "Macro candidates in the program", image: operandImages(db, platformNamed) }, macros.writes)) : undefined;
|
|
245
237
|
// Platform pitfalls are C64 facts: drive code and banks get none. Pitfalls and pointers read the code regions after both imports.
|
|
246
238
|
const codeDb = openForRead();
|
|
247
239
|
const code = listRegions(codeDb, undefined, "code", undefined, space);
|
|
@@ -264,10 +256,11 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
264
256
|
pointers: listed(pointers, max, showPointer, "a larger --max-listed"),
|
|
265
257
|
pitfalls: listed(pitfalls, max, showPitfall, "a larger --max-listed"),
|
|
266
258
|
macros: {
|
|
267
|
-
...listed(macros.candidates, max, showMacro, "a larger --max-listed
|
|
259
|
+
...listed(macros.candidates, max, showMacro, "a larger --max-listed"),
|
|
268
260
|
...(macros.known === 0 ? {} : { known: macros.known }),
|
|
269
261
|
...(macros.leftOut === 0 ? {} : { leftOut: macros.leftOut }),
|
|
270
|
-
...(
|
|
262
|
+
...(written === undefined ? {} : { revision: written.revision, writes: macros.writes.length }),
|
|
263
|
+
...(macros.otherMacros.length === 0 ? {} : { otherMacros: macros.otherMacros }),
|
|
271
264
|
},
|
|
272
265
|
},
|
|
273
266
|
},
|
|
@@ -315,7 +308,7 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
315
308
|
labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
|
|
316
309
|
...(written === undefined ? {} : { listing: written }),
|
|
317
310
|
};
|
|
318
|
-
return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, found.idioms.candidates.macros.
|
|
311
|
+
return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision });
|
|
319
312
|
}
|
|
320
313
|
|
|
321
314
|
const { result } = await analyzeWithGhidra({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
|
|
@@ -349,7 +342,7 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
349
342
|
? {}
|
|
350
343
|
: { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: withRemedy(item.reason) })) }),
|
|
351
344
|
};
|
|
352
|
-
return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, found.idioms.candidates.macros.
|
|
345
|
+
return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision });
|
|
353
346
|
}
|
|
354
347
|
|
|
355
348
|
await runScript({
|
|
@@ -368,7 +361,7 @@ await runScript({
|
|
|
368
361
|
"max-listed": { ...OPTIONS["max-listed"], help: "list at most n labels, functions or candidates (default 50, 0 for none). The counts are always given, and the knowledge has all labels and functions" },
|
|
369
362
|
"out-listing": { kind: "path", output: "file", value: "<file>", help: "dxa: write the disassembly listing to this project file" },
|
|
370
363
|
"out-instructions": { kind: "path", output: "file", value: "<file>", help: "ghidra: write every instruction (address, bytes, mnemonic, mode, operand, target, executed) to this project file as JSON" },
|
|
371
|
-
"
|
|
364
|
+
"apply-macros": { kind: "flag", help: "write the macro candidates (the macros and their uses) to the project knowledge as one revision of the LLM" },
|
|
372
365
|
},
|
|
373
366
|
notes: "The program and the coverage come from the project knowledge: put them into the project knowledge first. The executed code of the coverage gives entry points. Routine symbols in the knowledge are entry points too. Ghidra needs at least one entry point. DXA finds the SYS of a BASIC start by itself.",
|
|
374
367
|
run: analyze,
|
package/src/build-name.ts
CHANGED
|
@@ -9,6 +9,9 @@
|
|
|
9
9
|
|
|
10
10
|
import { basename, dirname, extname, join } from "node:path";
|
|
11
11
|
|
|
12
|
+
/** The folder of the builds, relative to the project folder. Git does not keep it. */
|
|
13
|
+
export const BUILD_DIRECTORY = "build";
|
|
14
|
+
|
|
12
15
|
/** The file with the value of each switch. The user edits it, and generate keeps the values. */
|
|
13
16
|
export const CONFIG_FILE = "config.asm";
|
|
14
17
|
|
package/src/knowledge/program.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { type AddressRange, COVERAGE, formatC64Address } from "../c64.ts";
|
|
|
11
11
|
|
|
12
12
|
import { COVERAGE_KINDS, DEFAULT_SPACE, MEMORY_ROW, type CoverageKind, type Space } from "./schema.ts";
|
|
13
13
|
import { coverageRuns } from "./read.ts";
|
|
14
|
-
import { checkSpace, write, type Evidence, type WriteContext } from "./write.ts";
|
|
14
|
+
import { checkSpace, write, type Evidence, type OperandImage, type WriteContext } from "./write.ts";
|
|
15
15
|
|
|
16
16
|
/** The 64 KiB of one space: offset n is address n. */
|
|
17
17
|
const SIZE = 0x10000;
|
|
@@ -278,3 +278,46 @@ export function programCoverage(db: DatabaseSync | undefined, space: Space = DEF
|
|
|
278
278
|
}
|
|
279
279
|
return { map, selfModified };
|
|
280
280
|
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* The program of each space in the knowledge that operand, patch and macro
|
|
284
|
+
* use writes in that space are checked against, with the platform names. A
|
|
285
|
+
* byte outside the segments of the program is not in it. Each program is
|
|
286
|
+
* read once, when a write in its space needs it.
|
|
287
|
+
*/
|
|
288
|
+
export function operandImages(db: DatabaseSync, platform: ReadonlyMap<string, number>): (space: string) => OperandImage {
|
|
289
|
+
const images = new Map<string, OperandImage>();
|
|
290
|
+
return (space) => {
|
|
291
|
+
const known = images.get(space);
|
|
292
|
+
if (known !== undefined) return known;
|
|
293
|
+
const image = requireProgram(db, space);
|
|
294
|
+
const inside = (at: number) => image.segments.some((segment) => at >= segment.start && at <= segment.end);
|
|
295
|
+
const made: OperandImage = { byteAt: (at) => (inside(at) ? image.byteAt(at) : undefined), platform };
|
|
296
|
+
images.set(space, made);
|
|
297
|
+
return made;
|
|
298
|
+
};
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
/**
|
|
302
|
+
* The bytes of a release: the program for the base release, else the bytes
|
|
303
|
+
* that the knowledge keeps for the release. Undefined when the space has no
|
|
304
|
+
* release with this label.
|
|
305
|
+
*/
|
|
306
|
+
export function releaseImage(db: DatabaseSync | undefined, label: string, space: Space = DEFAULT_SPACE): Pick<ProgramImage, "segments" | "byteAt"> | undefined {
|
|
307
|
+
if (db === undefined) return undefined;
|
|
308
|
+
const release = db.prepare("SELECT base FROM current_releases WHERE space = ? AND label = ?").get(space, label) as { base: number } | undefined;
|
|
309
|
+
if (release === undefined) return undefined;
|
|
310
|
+
if (release.base === 1) return programImage(db, space);
|
|
311
|
+
const rows = db.prepare("SELECT address, bytes FROM current_release_memory WHERE space = ? AND label = ? ORDER BY address").all(space, label) as Array<{ address: number; bytes: string }>;
|
|
312
|
+
const memory = new Uint8Array(SIZE);
|
|
313
|
+
const segments: AddressRange[] = [];
|
|
314
|
+
for (const row of rows) {
|
|
315
|
+
const bytes = Buffer.from(row.bytes, "hex");
|
|
316
|
+
memory.set(bytes, row.address);
|
|
317
|
+
const end = row.address + bytes.length - 1;
|
|
318
|
+
const last = segments.at(-1);
|
|
319
|
+
if (last !== undefined && last.end + 1 === row.address) last.end = end;
|
|
320
|
+
else segments.push({ start: row.address, end });
|
|
321
|
+
}
|
|
322
|
+
return { segments, byteAt: (address) => memory[address]! };
|
|
323
|
+
}
|
package/src/knowledge/read.ts
CHANGED
|
@@ -114,12 +114,10 @@ export interface SwitchRow {
|
|
|
114
114
|
revision: string;
|
|
115
115
|
}
|
|
116
116
|
|
|
117
|
-
/** A release of the program
|
|
117
|
+
/** A release of the program, and whether its bytes are the program of the knowledge. The bytes of another release are in release_memory. */
|
|
118
118
|
export interface ReleaseRow {
|
|
119
119
|
space: Space;
|
|
120
120
|
label: string;
|
|
121
|
-
file: string;
|
|
122
|
-
sha256: string;
|
|
123
121
|
base: boolean;
|
|
124
122
|
comment?: string;
|
|
125
123
|
origin: Extract<Origin, "user" | "llm">;
|
|
@@ -201,7 +199,7 @@ export const MODULE_COLUMNS = "space, start_address, file, title, origin, valid_
|
|
|
201
199
|
export const OPERAND_COLUMNS = "space, address, selector, symbol, offset, expression, origin, valid_from_revision";
|
|
202
200
|
export const PATCH_COLUMNS = "space, start_address, end_address, switch_name, code, comment, origin, valid_from_revision";
|
|
203
201
|
export const SWITCH_COLUMNS = "space, name, kind, default_value, releases, comment, origin, valid_from_revision";
|
|
204
|
-
export const RELEASE_COLUMNS = "space, label,
|
|
202
|
+
export const RELEASE_COLUMNS = "space, label, base, comment, origin, valid_from_revision";
|
|
205
203
|
export const MACRO_COLUMNS = "space, name, params, body, comment, origin, valid_from_revision";
|
|
206
204
|
export const MACRO_USE_COLUMNS = "space, start_address, end_address, macro, args, origin, valid_from_revision";
|
|
207
205
|
export const START_SCREEN_COLUMNS = "space, mode, screen, bitmap, charset, colours, colour, border, background, stage, call_address, colour_ram, comment, origin, valid_from_revision";
|
|
@@ -304,8 +302,6 @@ export function toRelease(row: Raw): ReleaseRow {
|
|
|
304
302
|
const release: ReleaseRow = {
|
|
305
303
|
space: row.space as Space,
|
|
306
304
|
label: row.label as string,
|
|
307
|
-
file: row.file as string,
|
|
308
|
-
sha256: row.sha256 as string,
|
|
309
305
|
base: row.base === 1,
|
|
310
306
|
origin: row.origin as ReleaseRow["origin"],
|
|
311
307
|
revision: row.valid_from_revision as string,
|
|
@@ -523,7 +519,7 @@ export function moduleAt(db: DatabaseSync | undefined, start: number, space: Spa
|
|
|
523
519
|
}
|
|
524
520
|
|
|
525
521
|
export function moduleWithFile(db: DatabaseSync | undefined, file: string, space: Space = DEFAULT_SPACE): ModuleRow | undefined {
|
|
526
|
-
const row = db?.prepare(`SELECT ${MODULE_COLUMNS} FROM current_modules WHERE space = ? AND file =
|
|
522
|
+
const row = db?.prepare(`SELECT ${MODULE_COLUMNS} FROM current_modules WHERE space = ? AND file = ? COLLATE NOCASE`).get(space, file) as Raw | undefined;
|
|
527
523
|
return row === undefined ? undefined : toModule(row);
|
|
528
524
|
}
|
|
529
525
|
|