@henols/c64-re-tools 2.5.1-rc.2 → 2.6.0-rc.10
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 +2 -2
- package/skills/c64-assembler/SKILL.md +26 -12
- package/skills/c64-assembler/scripts/assembler.ts +25 -13
- package/skills/c64-development/SKILL.md +2 -2
- package/skills/c64-docs/SKILL.md +4 -4
- package/skills/c64-docs/scripts/docs.ts +7 -7
- 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 +29 -20
- package/skills/c64-knowledge/scripts/knowledge.ts +33 -39
- package/skills/c64-knowledge/scripts/lib/listing.ts +18 -3
- package/skills/c64-packer/SKILL.md +1 -1
- 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 +16 -10
- package/skills/c64-source/SKILL.md +60 -42
- package/skills/c64-source/scripts/lib/export.ts +76 -32
- package/skills/c64-source/scripts/lib/loader.ts +26 -7
- package/skills/c64-source/scripts/lib/source.ts +21 -24
- package/skills/c64-source/scripts/lib/stage.ts +6 -5
- package/skills/c64-source/scripts/source.ts +213 -106
- package/skills/c64-static-analysis/SKILL.md +7 -5
- package/skills/c64-static-analysis/scripts/lib/coverage.ts +2 -25
- package/skills/c64-static-analysis/scripts/lib/instructions.ts +22 -20
- package/skills/c64-static-analysis/scripts/static-analysis.ts +36 -43
- package/skills/c64-testing/SKILL.md +5 -2
- package/skills/c64-testing/references/recording-format.md +18 -3
- package/skills/c64-testing/references/scenario-format.md +7 -6
- package/skills/c64-testing/scripts/lib/diff-files.ts +4 -18
- package/skills/c64-testing/scripts/lib/play.ts +39 -41
- package/skills/c64-testing/scripts/lib/recording.ts +46 -37
- package/skills/c64-testing/scripts/lib/replay.ts +1 -1
- package/skills/c64-testing/scripts/lib/runs.ts +2 -2
- package/skills/c64-testing/scripts/lib/scenario.ts +17 -10
- package/skills/c64-unpacker/SKILL.md +4 -1
- package/skills/c64-unpacker/scripts/lib/loads.ts +34 -13
- package/skills/c64-unpacker/scripts/unpacker.ts +5 -3
- package/skills/emulator/SKILL.md +7 -12
- package/src/build-name.ts +50 -0
- package/src/c64-keys.ts +98 -0
- package/src/c64.ts +20 -0
- package/src/cli/main.ts +3 -29
- package/src/host/main.ts +1 -1
- package/src/host/tools/index.ts +1 -6
- package/src/host/vice/session.ts +88 -9
- package/src/host-client/steps.ts +17 -17
- package/src/host-client/tools.ts +2 -7
- package/src/host-client/vice-session.ts +7 -1
- package/src/knowledge/program.ts +44 -1
- package/src/knowledge/read.ts +28 -8
- package/src/knowledge/schema.ts +33 -9
- package/src/knowledge/start-screen.ts +4 -0
- package/src/knowledge/text.ts +4 -2
- package/src/knowledge/write.ts +59 -25
- package/src/mcp/inputs.ts +12 -0
- package/src/mcp/server.ts +1 -1
- package/src/mcp/tools/input.ts +38 -5
- package/src/mcp/tools/machine.ts +3 -42
- package/src/mcp/tools/media.ts +1 -1
- package/src/native/acme.ts +1 -1
- package/src/native/c64run.ts +1 -1
- package/src/native/discover.ts +3 -3
- package/src/native/dxa.ts +12 -1
- package/src/native/ghidra/analyze.ts +74 -63
- package/src/native/ghidra/c64rt-wasm.ts +4 -0
- package/src/native/ghidra/language/c64rt_6510.sla +0 -0
- package/src/native/ghidra/pcode.ts +222 -0
- package/src/native/ghidra/walk.ts +205 -0
- package/src/native/ghidra/wasm.ts +98 -0
- package/src/native/processes.ts +4 -4
- package/src/native/types.ts +2 -2
- package/src/platform.ts +30 -1
- package/src/project.ts +17 -4
- package/src/protocol/tools.ts +1 -45
- package/src/protocol/vice.ts +47 -0
- package/src/script.ts +1 -1
- package/src/vsf.ts +98 -0
- package/tools/c64run.c +9 -12
- package/tools/install-container.sh +1 -2
- package/src/cli/status.ts +0 -127
- package/src/host/tools/status.ts +0 -47
- package/src/native/ghidra/index.ts +0 -170
- package/src/native/ghidra/scripts/C64Export.java +0 -274
- package/src/native/ghidra/scripts/C64Prepare.java +0 -66
- package/src/native/status.ts +0 -135
- package/tools/install-ghidra.sh +0 -40
|
@@ -11,30 +11,29 @@
|
|
|
11
11
|
|
|
12
12
|
import { createHash } from "node:crypto";
|
|
13
13
|
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
14
|
-
import { basename, join, relative, sep } from "node:path";
|
|
14
|
+
import { basename, dirname, join, relative, sep } from "node:path";
|
|
15
15
|
|
|
16
16
|
import { isRefusal, Refusal } from "#src/errors.ts";
|
|
17
|
-
import {
|
|
17
|
+
import { BUILD_DIRECTORY, buildName, symbolsPath } from "#src/build-name.ts";
|
|
18
|
+
import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
|
|
18
19
|
import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
|
|
19
20
|
import { IO_RAM } from "#src/host-client/coverage.ts";
|
|
20
|
-
import { readImage, type Image } from "#src/host-client/image.ts";
|
|
21
|
-
import { readProjectFile } from "#src/host-client/transfer.ts";
|
|
22
21
|
import { MAX_MEMORY_READ, WireFailure } from "#src/host-client/tools.ts";
|
|
23
22
|
import { writeReported, type Written } from "#src/host-client/transfer.ts";
|
|
24
23
|
import { ViceSessionClient } from "#src/host-client/vice-session.ts";
|
|
25
24
|
import { conflicts } from "#src/knowledge/conflicts.ts";
|
|
26
25
|
import { openForRead, withWrite } from "#src/knowledge/database.ts";
|
|
27
26
|
import { identifiers } from "#src/knowledge/expression.ts";
|
|
28
|
-
import { analyzedBytes, memoryRows, programCoverage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
|
|
29
|
-
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";
|
|
30
|
-
import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
|
|
27
|
+
import { analyzedBytes, memoryRows, programCoverage, releaseImage, requireProgram, type ProgramImage } from "#src/knowledge/program.ts";
|
|
28
|
+
import { ANALYZER_NAME_ORDER, baseValue, currentRevision, currentStartScreen, sourceRevision, 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";
|
|
29
|
+
import { CODE_REGION_TYPES, DEFAULT_SPACE, isSemantic, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, RELEASE_DEFINE, START_SCREEN_SWITCH, type Space } from "#src/knowledge/schema.ts";
|
|
31
30
|
import { subtract, write } from "#src/knowledge/write.ts";
|
|
32
31
|
import { assemble, symbolsFileText } from "#src/native/acme.ts";
|
|
33
32
|
import { analyze } from "#src/native/ghidra/analyze.ts";
|
|
34
33
|
import { localToolContext } from "#src/native/local.ts";
|
|
35
34
|
import { GHIDRA_LIMITS, type AssembledSymbol, type Diagnostic } from "#src/native/types.ts";
|
|
36
|
-
import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romUseOfProgram } from "#src/platform.ts";
|
|
37
|
-
import { ensureLocal, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRoot, resolveProjectPath } from "#src/project.ts";
|
|
35
|
+
import { decode as decodeRegister, describeAddress, platformNames, platformNamesFor, romRanges, romUseOfProgram } from "#src/platform.ts";
|
|
36
|
+
import { ensureLocal, generatedDirectory, LOCAL_DIRECTORY, newProjectFolder, PROJECT_DIRECTORY, projectRelative, projectRoot, resolveProjectPath } from "#src/project.ts";
|
|
38
37
|
import { isoCet } from "#src/time.ts";
|
|
39
38
|
import { zipFiles } from "#src/zip.ts";
|
|
40
39
|
import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
|
|
@@ -49,6 +48,7 @@ import {
|
|
|
49
48
|
startScreenPlan,
|
|
50
49
|
rasterLine,
|
|
51
50
|
loaderState,
|
|
51
|
+
loaderSymbols,
|
|
52
52
|
simulate,
|
|
53
53
|
START_SCREEN_CODE,
|
|
54
54
|
START_SCREEN_CONTINUE,
|
|
@@ -92,8 +92,11 @@ function readKnowledge(space: Space, analyzerNames = false) {
|
|
|
92
92
|
const second = listAnalyzerNames(db, undefined, undefined, undefined, space);
|
|
93
93
|
const releases = listReleases(db, undefined, space);
|
|
94
94
|
const base = releases.find((release) => release.base)?.label;
|
|
95
|
+
const startScreen = space === DEFAULT_SPACE ? currentStartScreen(db, space) : undefined;
|
|
95
96
|
return {
|
|
96
97
|
revision: currentRevision(db),
|
|
98
|
+
// The source and its loader hold the program of this space and the stage of its start screen: a change elsewhere does not change them.
|
|
99
|
+
sourceRevision: sourceRevision(db, space),
|
|
97
100
|
program: requireProgram(db, space),
|
|
98
101
|
// The coverage of the space: a run of the C64, or of a captured stage that coverage put into that space.
|
|
99
102
|
coverage: programCoverage(db, space)?.map,
|
|
@@ -107,11 +110,12 @@ function readKnowledge(space: Space, analyzerNames = false) {
|
|
|
107
110
|
operands: listOperands(db, undefined, undefined, space),
|
|
108
111
|
patches: listPatches(db, undefined, undefined, undefined, space),
|
|
109
112
|
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 }) })),
|
|
110
|
-
|
|
113
|
+
// Each release with its bytes: the check builds it and compares the build with them.
|
|
114
|
+
releases: releases.map((release) => ({ ...release, image: releaseImage(db, release.label, space)! })),
|
|
111
115
|
macros: listMacros(db, undefined, space),
|
|
112
116
|
macroUses: listMacroUses(db, undefined, undefined, undefined, space),
|
|
113
117
|
// The start screen is of the C64 program: the loader shows it.
|
|
114
|
-
startScreen
|
|
118
|
+
startScreen,
|
|
115
119
|
};
|
|
116
120
|
} finally {
|
|
117
121
|
db?.close();
|
|
@@ -142,6 +146,14 @@ function withAnalyzerNames(symbols: SymbolRow[], second: SymbolRow[]): SymbolRow
|
|
|
142
146
|
return [...symbols, ...added].sort((a, b) => a.address - b.address);
|
|
143
147
|
}
|
|
144
148
|
|
|
149
|
+
/** Where the CPU sees ROM in the image (romRanges): the entry, the routines, the code regions and `entries` stay code. */
|
|
150
|
+
function romOf(image: ProgramImage, knowledge: Pick<SourceKnowledge, "routines" | "regions">, entries: readonly number[], coverage: Uint8Array | undefined): AddressRange[] {
|
|
151
|
+
const inImage = (address: number) => image.segments.some((segment) => address >= segment.start && address <= segment.end);
|
|
152
|
+
const code = knowledge.regions.filter((region) => CODE_REGION_TYPES.includes(region.type) || region.type === "dual-use").map((region) => region.start);
|
|
153
|
+
const known = [...(image.entry === undefined ? [] : [image.entry]), ...entries, ...knowledge.routines, ...code];
|
|
154
|
+
return romRanges(coverage, image.state, (address) => (inImage(address) ? image.byteAt(address) : undefined), known);
|
|
155
|
+
}
|
|
156
|
+
|
|
145
157
|
/**
|
|
146
158
|
* Ghidra's instruction starts and lengths inside the image, seeded from the
|
|
147
159
|
* entry, from knowledge of any origin, and from the coverage: a run's flow
|
|
@@ -167,6 +179,8 @@ async function decode(image: ProgramImage, knowledge: Pick<SourceKnowledge, "rou
|
|
|
167
179
|
const dataRanges = knowledge.regions
|
|
168
180
|
.filter((region) => !CODE_REGION_TYPES.includes(region.type) && region.type !== "dual-use")
|
|
169
181
|
.flatMap((region) => image.segments.filter((segment) => region.start <= segment.end && segment.start <= region.end).map((segment) => ({ start: Math.max(region.start, segment.start), end: Math.min(region.end, segment.end) })));
|
|
182
|
+
// A JSR into ROM runs the ROM: the RAM bytes of the image under it are data, not the code of the call.
|
|
183
|
+
for (const range of romOf(image, knowledge, entries, coverage)) if (!dataRanges.some((data) => range.start <= data.end && data.start <= range.end)) dataRanges.push(range);
|
|
170
184
|
const { result } = await analyze(
|
|
171
185
|
{
|
|
172
186
|
imageKind: analyzedBytes(image).kind,
|
|
@@ -468,44 +482,32 @@ async function checkSwitch(row: SourceSwitch, patches: PatchBlock[], files: Arra
|
|
|
468
482
|
};
|
|
469
483
|
}
|
|
470
484
|
|
|
471
|
-
/** What the build of a release gives against the bytes of
|
|
485
|
+
/** What the build of a release gives against the bytes of the release in the knowledge. */
|
|
472
486
|
interface ReleaseCheck {
|
|
473
487
|
label: string;
|
|
474
488
|
base: boolean;
|
|
475
|
-
file: string;
|
|
476
489
|
define: string;
|
|
477
|
-
result: "identical" | "different" | "
|
|
478
|
-
reason?: string;
|
|
490
|
+
result: "identical" | "different" | "does not assemble";
|
|
479
491
|
segments?: SegmentCheck[];
|
|
492
|
+
/** The ranges of the program that the release does not have: the check does not compare them. */
|
|
493
|
+
notInRelease?: Array<{ start: string; end: string }>;
|
|
480
494
|
diagnostics?: Diagnostic[];
|
|
481
495
|
}
|
|
482
496
|
|
|
483
497
|
/**
|
|
484
|
-
* Builds a release with RELEASE_<label> and compares it with its
|
|
485
|
-
*
|
|
486
|
-
*
|
|
498
|
+
* Builds a release with RELEASE_<label> and compares it with its bytes, in
|
|
499
|
+
* each segment of the release, as the build compare of the assembler does. A
|
|
500
|
+
* part of the program that the release does not have is listed, not compared.
|
|
487
501
|
*/
|
|
488
|
-
async function checkRelease(release: ReleaseRow, files: Array<{ name: string; text: string }>, program: ProgramImage): Promise<ReleaseCheck> {
|
|
489
|
-
const shown = { label: release.label, base: release.base,
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
if (createHash("sha256").update(bytes).digest("hex") !== release.sha256) {
|
|
494
|
-
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.` };
|
|
495
|
-
}
|
|
496
|
-
image = readImage(release.file);
|
|
497
|
-
} catch (error) {
|
|
498
|
-
if (!(error instanceof Refusal || error instanceof WireFailure)) throw error;
|
|
499
|
-
return { ...shown, result: "file changed", reason: error.message };
|
|
500
|
-
}
|
|
501
|
-
if (JSON.stringify(image.segments) !== JSON.stringify(program.segments)) {
|
|
502
|
-
const segments = (list: readonly AddressRange[]) => list.map((segment) => `${formatC64Address(segment.start)}-${formatC64Address(segment.end)}`).join(", ");
|
|
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.` };
|
|
504
|
-
}
|
|
502
|
+
async function checkRelease(release: ReleaseRow & { image: Pick<ProgramImage, "segments" | "byteAt"> }, files: Array<{ name: string; text: string }>, program: ProgramImage): Promise<ReleaseCheck> {
|
|
503
|
+
const shown = { label: release.label, base: release.base, define: `--define ${RELEASE_DEFINE}${release.label}=1` };
|
|
504
|
+
const { image } = release;
|
|
505
|
+
const missing = program.segments.flatMap((segment) => subtract(segment, [...image.segments])).map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) }));
|
|
506
|
+
const notInRelease = missing.length === 0 ? {} : { notInRelease: missing };
|
|
505
507
|
const built = await assembleFiles(files, "main.asm", { [`${RELEASE_DEFINE}${release.label}`]: 1 });
|
|
506
|
-
if (built.program === undefined) return { ...shown, result: "does not assemble", diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS) };
|
|
508
|
+
if (built.program === undefined) return { ...shown, result: "does not assemble", diagnostics: built.diagnostics.slice(0, MAX_DIAGNOSTICS), ...notInRelease };
|
|
507
509
|
const checked = check(built.program, built.start!, image);
|
|
508
|
-
return { ...shown, result: checked.identical ? "identical" : "different", ...(checked.identical ? {} : { segments: checked.segments.filter((segment) => segment.result !== "identical") }) };
|
|
510
|
+
return { ...shown, result: checked.identical ? "identical" : "different", ...(checked.identical ? {} : { segments: checked.segments.filter((segment) => segment.result !== "identical") }), ...notInRelease };
|
|
509
511
|
}
|
|
510
512
|
|
|
511
513
|
/** Reads RAM in parts. */
|
|
@@ -568,8 +570,8 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, state:
|
|
|
568
570
|
const port01 = `$${port.toString(16).padStart(2, "0")}`;
|
|
569
571
|
return { verified: false, differences: [`The loader did not get to ${what}; it stopped at ${formatC64Address(pc)}.`], stop: { pc: formatC64Address(pc), port: port01, ...(cause === undefined ? {} : { cause }), history } };
|
|
570
572
|
};
|
|
571
|
-
// The start screen waits for a key or a fire button.
|
|
572
|
-
//
|
|
573
|
+
// The start screen waits for a key or a fire button. Not each VICE can press a key of the keyboard matrix,
|
|
574
|
+
// so the check lets it wait, then sets the PC to the code after the wait.
|
|
573
575
|
let screen: LoaderRun["startScreen"];
|
|
574
576
|
const screenDifferences: string[] = [];
|
|
575
577
|
const showScreen = async (at: { wait: number; continue: number }, wanted: StartScreenPlan, frames: number, copied: boolean, parts: readonly StagePart[] = [], colourRam?: Uint8Array): Promise<LoaderRun | undefined> => {
|
|
@@ -694,13 +696,26 @@ function sourceMapText(rendered: Rendered, space: string, revision: string | nul
|
|
|
694
696
|
return `${head},\n"labels": [\n${labels.join(",\n")}\n],\n"items": [\n${items.join(",\n")}\n]}\n`;
|
|
695
697
|
}
|
|
696
698
|
|
|
697
|
-
/** The folder in .c64-re-tools/local/ where the check of the loader runs the new loader.
|
|
699
|
+
/** The folder in .c64-re-tools/local/ where the check of the loader runs the new loader program. */
|
|
698
700
|
const LOADER_CHECK_DIRECTORY = "loader-check";
|
|
699
701
|
|
|
700
|
-
/** The files of the loader. Only a run with --loader writes them, so only such a run removes them. */
|
|
701
|
-
const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm",
|
|
702
|
+
/** The source files of the loader. Only a run with --loader writes them, so only such a run removes them. */
|
|
703
|
+
const LOADER_FILES: ReadonlySet<string> = new Set(["loader.asm", START_SCREEN_FILE, STAGE_FILE]);
|
|
702
704
|
|
|
703
|
-
/**
|
|
705
|
+
/** A loader program that generate wrote: its build name, as buildName gives it for loader.asm. */
|
|
706
|
+
const LOADER_PROGRAM = /^(clean|custom_[a-z0-9_]+|release_[A-Za-z0-9_]+)_loader\.prg$/;
|
|
707
|
+
|
|
708
|
+
/** The loader programs of earlier runs in the build folder, with their symbols files. */
|
|
709
|
+
function loaderPrograms(): string[] {
|
|
710
|
+
const directory = resolveProjectPath(BUILD_DIRECTORY);
|
|
711
|
+
if (!existsSync(directory)) return [];
|
|
712
|
+
return readdirSync(directory)
|
|
713
|
+
.filter((name) => LOADER_PROGRAM.test(name))
|
|
714
|
+
.flatMap((name) => [`${BUILD_DIRECTORY}/${name}`, symbolsPath(`${BUILD_DIRECTORY}/${name}`)])
|
|
715
|
+
.filter((path) => existsSync(resolveProjectPath(path)));
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** The start of the line of loader.asm that gives the newest knowledge revision of the spaces that the loader holds. */
|
|
704
719
|
const LOADER_REVISION = "Loader generated by c64-source from knowledge revision ";
|
|
705
720
|
|
|
706
721
|
/**
|
|
@@ -717,31 +732,81 @@ function staleLoader(out: string, revision: string): { files: string[]; revision
|
|
|
717
732
|
const line = text.split(/\r?\n/).find((row) => row.startsWith(`; ${LOADER_REVISION}`));
|
|
718
733
|
const old = line?.slice(`; ${LOADER_REVISION}`.length).replace(/\.$/, "");
|
|
719
734
|
if (old === revision) return undefined;
|
|
720
|
-
const files = [...LOADER_FILES].filter((name) => existsSync(resolveProjectPath(`${out}/${name}`))).map((name) => `${out}/${name}`);
|
|
735
|
+
const files = [...[...LOADER_FILES].filter((name) => existsSync(resolveProjectPath(`${out}/${name}`))).map((name) => `${out}/${name}`), ...loaderPrograms()];
|
|
721
736
|
return { files, ...(old === undefined ? {} : { revision: old }) };
|
|
722
737
|
}
|
|
723
738
|
|
|
739
|
+
/** The line of a leftover file that gives its range. */
|
|
740
|
+
const LEFTOVER_RANGE = /^; Leftovers (\$[0-9a-f]{4})-(\$[0-9a-f]{4}):/m;
|
|
741
|
+
|
|
742
|
+
/**
|
|
743
|
+
* The leftovers of the earlier run: the ranges of its generated leftover
|
|
744
|
+
* files in the leftovers folder of `out`. Undefined when `out` has no
|
|
745
|
+
* generated main.asm, so there was no earlier run to compare with.
|
|
746
|
+
*/
|
|
747
|
+
function earlierLeftovers(out: string): AddressRange[] | undefined {
|
|
748
|
+
const root = resolveProjectPath(out);
|
|
749
|
+
const main = join(root, "main.asm");
|
|
750
|
+
if (!existsSync(main) || !readFileSync(main, "utf8").startsWith(GENERATED_MARK)) return undefined;
|
|
751
|
+
const directory = join(root, LEFTOVER_FOLDER);
|
|
752
|
+
if (!existsSync(directory)) return [];
|
|
753
|
+
return readdirSync(directory)
|
|
754
|
+
.filter((name) => /^leftover_[0-9a-f]{4}\.asm$/.test(name))
|
|
755
|
+
.flatMap((name) => {
|
|
756
|
+
const found = LEFTOVER_RANGE.exec(readFileSync(join(directory, name), "utf8"));
|
|
757
|
+
return found === null ? [] : [{ start: parseC64Address(found[1]!), end: parseC64Address(found[2]!) }];
|
|
758
|
+
});
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
/** The bytes of `ranges` that are not in `others`, as ranges in address order. */
|
|
762
|
+
function outside(ranges: readonly AddressRange[], others: readonly AddressRange[]): AddressRange[] {
|
|
763
|
+
return [...ranges].sort((a, b) => a.start - b.start).flatMap((range) => subtract(range, [...others]));
|
|
764
|
+
}
|
|
765
|
+
|
|
724
766
|
/**
|
|
725
767
|
* Removes the generated .asm files of an earlier run that this run does not
|
|
726
|
-
* write, and
|
|
727
|
-
* loader.asm stays unless this run has
|
|
728
|
-
* include loader.asm.
|
|
729
|
-
*
|
|
768
|
+
* write, and the reports of the earlier run (its source map and
|
|
769
|
+
* not_executed.json). An earlier loader.asm stays unless this run has
|
|
770
|
+
* --loader: a source of the user can include loader.asm. The files of a
|
|
771
|
+
* module are in `out` or in one folder of it: a folder that the run leaves
|
|
772
|
+
* empty goes too. A folder with a generated main.asm is the source of another
|
|
773
|
+
* space, and it stays. Other files stay. Gives the paths it removed.
|
|
730
774
|
*/
|
|
731
775
|
function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boolean): string[] {
|
|
732
|
-
const directory = resolveProjectPath(out);
|
|
733
|
-
if (!existsSync(directory)) return [];
|
|
734
776
|
const removed: string[] = [];
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
const
|
|
738
|
-
|
|
739
|
-
if (LOADER_FILES.has(name) && !loaderRun) continue;
|
|
740
|
-
const old = name === NOT_EXECUTED_FILE || name === SOURCE_MAP_FILE || (name.endsWith(".asm") && !keep.has(name) && readFileSync(path, "utf8").startsWith(GENERATED_MARK));
|
|
741
|
-
if (!old) continue;
|
|
777
|
+
const reports = generatedDirectory(projectRelative(out));
|
|
778
|
+
for (const name of [SOURCE_MAP_FILE, NOT_EXECUTED_FILE]) {
|
|
779
|
+
const path = resolveProjectPath(`${reports}/${name}`);
|
|
780
|
+
if (!existsSync(path)) continue;
|
|
742
781
|
rmSync(path, { force: true });
|
|
743
|
-
removed.push(name);
|
|
782
|
+
removed.push(`${reports}/${name}`);
|
|
744
783
|
}
|
|
784
|
+
const root = resolveProjectPath(out);
|
|
785
|
+
if (!existsSync(root)) return removed;
|
|
786
|
+
/** Removes the old generated files of a folder ("" for `out` itself), and gives how many. */
|
|
787
|
+
const clean = (folder: string): number => {
|
|
788
|
+
const directory = folder === "" ? root : join(root, folder);
|
|
789
|
+
let count = 0;
|
|
790
|
+
for (const entry of readdirSync(directory, { withFileTypes: true })) {
|
|
791
|
+
const name = folder === "" ? entry.name : `${folder}/${entry.name}`;
|
|
792
|
+
if (entry.isDirectory() && folder === "") {
|
|
793
|
+
const main = join(root, name, "main.asm");
|
|
794
|
+
if (existsSync(main) && readFileSync(main, "utf8").startsWith(GENERATED_MARK)) continue;
|
|
795
|
+
// A folder of the user that held no generated file stays, also when it is empty.
|
|
796
|
+
if (clean(name) > 0 && readdirSync(join(root, name)).length === 0) rmSync(join(root, name), { recursive: true, force: true });
|
|
797
|
+
continue;
|
|
798
|
+
}
|
|
799
|
+
if (!entry.isFile()) continue;
|
|
800
|
+
const path = join(directory, entry.name);
|
|
801
|
+
if (LOADER_FILES.has(name) && !loaderRun) continue;
|
|
802
|
+
if (!name.endsWith(".asm") || keep.has(name) || !readFileSync(path, "utf8").startsWith(GENERATED_MARK)) continue;
|
|
803
|
+
rmSync(path, { force: true });
|
|
804
|
+
removed.push(`${out}/${name}`);
|
|
805
|
+
count++;
|
|
806
|
+
}
|
|
807
|
+
return count;
|
|
808
|
+
};
|
|
809
|
+
clean("");
|
|
745
810
|
return removed;
|
|
746
811
|
}
|
|
747
812
|
|
|
@@ -800,7 +865,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
|
|
|
800
865
|
operands: knowledge.operands,
|
|
801
866
|
patches: knowledge.patches,
|
|
802
867
|
switches: knowledge.switches,
|
|
803
|
-
releases: knowledge.releases.map((release) => ({ label: release.label,
|
|
868
|
+
releases: knowledge.releases.map((release) => ({ label: release.label, base: release.base, ...(release.comment === undefined ? {} : { comment: release.comment }) })),
|
|
804
869
|
macros: knowledge.macros,
|
|
805
870
|
macroUses: knowledge.macroUses,
|
|
806
871
|
startScreen: knowledge.startScreen !== undefined && options.exported !== true,
|
|
@@ -834,7 +899,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
|
|
|
834
899
|
|
|
835
900
|
let loader: LoaderPlan | undefined;
|
|
836
901
|
/** The build of main.asm that the loader loads: the switch values of the loader. */
|
|
837
|
-
let loaderMain: { program: Buffer; start: number } | undefined;
|
|
902
|
+
let loaderMain: { program: Buffer; start: number; symbols: AssembledSymbol[] } | undefined;
|
|
838
903
|
// An image without its entry has no program: the source is still written and checked, but the run fails.
|
|
839
904
|
const missingEntry = entryOutsideImage(image.entry, image.segments);
|
|
840
905
|
// A loader that cannot be planned does not stop the source: the source is written and checked, and the result says why.
|
|
@@ -846,7 +911,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
|
|
|
846
911
|
else {
|
|
847
912
|
const program = main.program;
|
|
848
913
|
const start = main.start!;
|
|
849
|
-
loaderMain = { program, start };
|
|
914
|
+
loaderMain = { program, start, symbols: main.symbols ?? [] };
|
|
850
915
|
try {
|
|
851
916
|
const entryName = laid.names.get(image.entry!);
|
|
852
917
|
loader = planLoader({
|
|
@@ -981,10 +1046,12 @@ async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; co
|
|
|
981
1046
|
return { parts: parts.map((range) => ({ start: range.start, body: memory.slice(range.start, range.end + 1) })), ...(colourRam === undefined ? {} : { colourRam }) };
|
|
982
1047
|
}
|
|
983
1048
|
|
|
984
|
-
/** What the show stage gives: loader
|
|
1049
|
+
/** What the show stage gives: the loader program, the source of the stage, and what its check needs. */
|
|
985
1050
|
interface BuiltStage {
|
|
986
1051
|
program: Buffer;
|
|
987
1052
|
text: string;
|
|
1053
|
+
/** The labels of the build of start_screen_stage.asm. */
|
|
1054
|
+
symbols: AssembledSymbol[];
|
|
988
1055
|
plan: StagePlan;
|
|
989
1056
|
parts: StagePart[];
|
|
990
1057
|
colourRam?: Uint8Array;
|
|
@@ -1019,17 +1086,24 @@ async function buildStage(files: Array<{ name: string; text: string }>, laid: La
|
|
|
1019
1086
|
const support = [...withValues(files, laid, values).filter((file) => file.name === CONFIG_FILE || file.name === "switches.asm"), { name: START_SCREEN_FILE, text: START_SCREEN_CODE }];
|
|
1020
1087
|
const assembleStage = async (text: string) => {
|
|
1021
1088
|
const built = await assembleFiles([...support, { name: STAGE_FILE, text }], STAGE_FILE);
|
|
1022
|
-
if (built.program === undefined)
|
|
1089
|
+
if (built.program === undefined) {
|
|
1090
|
+
// The source that failed stays readable: --out keeps the files of the last good run.
|
|
1091
|
+
ensureLocal(projectRoot());
|
|
1092
|
+
const kept = `${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/${LOADER_CHECK_DIRECTORY}/${STAGE_FILE}`;
|
|
1093
|
+
mkdirSync(dirname(resolveProjectPath(kept)), { recursive: true });
|
|
1094
|
+
writeFileSync(resolveProjectPath(kept), `${mark}\n${text}`);
|
|
1095
|
+
throw new WireFailure("operation-failed", `${STAGE_FILE} does not assemble: ${built.diagnostics.map((diagnostic) => diagnostic.message).join("; ")}. The source that failed is ${kept}. This is a defect of the script.`);
|
|
1096
|
+
}
|
|
1023
1097
|
const labels = new Map((built.symbols ?? []).map((symbol) => [symbol.name, symbol.kind === "address" ? symbol.address : symbol.value]));
|
|
1024
1098
|
const label = (name: string) => {
|
|
1025
1099
|
const value = labels.get(name);
|
|
1026
1100
|
if (value === undefined) throw new WireFailure("operation-failed", `The build of ${STAGE_FILE} has no ${name} label. This is a defect of the script.`);
|
|
1027
1101
|
return value;
|
|
1028
1102
|
};
|
|
1029
|
-
return { program: built.program, label };
|
|
1103
|
+
return { program: built.program, symbols: built.symbols ?? [], label };
|
|
1030
1104
|
};
|
|
1031
|
-
// The size of the show code does not depend on its address: one build without a stash gives it.
|
|
1032
|
-
const probe = await assembleStage(stageText(input, 0x1000, []));
|
|
1105
|
+
// The size of the show code does not depend on its address: one build without a stash and without the parts gives it.
|
|
1106
|
+
const probe = await assembleStage(stageText({ ...input, stage: [] }, 0x1000, []));
|
|
1033
1107
|
input.codeSize = probe.label(STAGE_CODE_END) - probe.label(STAGE_START) - 2;
|
|
1034
1108
|
const plan = planStage(input);
|
|
1035
1109
|
const built = await assembleStage(plan.text);
|
|
@@ -1037,8 +1111,8 @@ async function buildStage(files: Array<{ name: string; text: string }>, laid: La
|
|
|
1037
1111
|
const parts = stageParts(input, plan, built.program, built.label);
|
|
1038
1112
|
const packed = await packParts(parts, plan.code, 0x37, "the loader and the start screen of the stage", "the show stage", localToolContext());
|
|
1039
1113
|
const end = 0x0801 + packed.program.length - 3;
|
|
1040
|
-
if (end > 0xcfff) throw new Refusal("invalid-input", `loader
|
|
1041
|
-
return { program: packed.program, text: `${mark}\n${plan.text}`, plan, parts: stage, ...(colourRam === undefined ? {} : { colourRam }), packed, wait: built.label(START_SCREEN_WAIT), continue: built.label(START_SCREEN_CONTINUE), screen };
|
|
1114
|
+
if (end > 0xcfff) throw new Refusal("invalid-input", `The loader with the start screen of ${row.stage} would end at ${formatC64Address(end)}, after $cfff: loading it would write the I/O area. Capture the stage with less memory, so that its program holds only the start screen and the routine of the call.`);
|
|
1115
|
+
return { program: packed.program, text: `${mark}\n${plan.text}`, symbols: built.symbols, plan, parts: stage, ...(colourRam === undefined ? {} : { colourRam }), packed, wait: built.label(START_SCREEN_WAIT), continue: built.label(START_SCREEN_CONTINUE), screen };
|
|
1042
1116
|
}
|
|
1043
1117
|
|
|
1044
1118
|
/** The first line of each file that generate writes. */
|
|
@@ -1065,8 +1139,8 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1065
1139
|
const given = existsSync(configPath) ? configValues(readFileSync(configPath, "utf8")) : new Map<string, 0 | 1>();
|
|
1066
1140
|
const configNames = new Set([...knowledge.switches.map((row) => row.name), START_SCREEN_SWITCH, LEFTOVERS_SWITCH]);
|
|
1067
1141
|
const loaderValues = new Map([...given].filter(([name]) => configNames.has(name)));
|
|
1068
|
-
const header = [`Generated by c64-source from knowledge revision ${knowledge.
|
|
1069
|
-
const loaderHeader = [`${LOADER_REVISION}${knowledge.
|
|
1142
|
+
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 = [`${LOADER_REVISION}${knowledge.sourceRevision}.`, "It copies the segments into place, sets the entry state and jumps to the entry."];
|
|
1070
1144
|
const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused } = await buildSource(knowledge, {
|
|
1071
1145
|
space,
|
|
1072
1146
|
entries,
|
|
@@ -1081,10 +1155,16 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1081
1155
|
const configured = [...laid.switches, ...(laid.startScreen ? [{ name: START_SCREEN_SWITCH, default: 1 }] : []), ...(laid.leftovers.length > 0 ? [{ name: LEFTOVERS_SWITCH, default: 0 }] : [])];
|
|
1082
1156
|
const kept = new Map(configured.flatMap((row) => (given.has(row.name) ? [[row.name, given.get(row.name)!] as const] : [])));
|
|
1083
1157
|
const notDefault = configured.flatMap((row) => (kept.has(row.name) && kept.get(row.name) !== row.default ? [{ name: row.name, value: kept.get(row.name)!, default: row.default }] : []));
|
|
1084
|
-
|
|
1085
|
-
const
|
|
1158
|
+
// The loader program has the name of its build: clean_loader with the defaults of config.asm.
|
|
1159
|
+
const loaderName = buildName("loader.asm", { values: kept, defaults: new Map(configured.map((row) => [row.name, row.default])) });
|
|
1160
|
+
// Read before the old files go: the leftovers of the earlier run, to tell what changed.
|
|
1161
|
+
const earlier = earlierLeftovers(out);
|
|
1162
|
+
const removed = removeOldFiles(out, new Set(files.map((file) => file.name)), loaderWanted);
|
|
1163
|
+
const stale = loaderWanted || space !== DEFAULT_SPACE ? undefined : staleLoader(out, knowledge.sourceRevision);
|
|
1086
1164
|
const written: Written[] = withValues(files, laid, kept).map((file) => writeReported(`${out}/${file.name}`, file.text, { what: "--out" }));
|
|
1087
|
-
|
|
1165
|
+
// The reports go to the local folder: the source folder holds only source files.
|
|
1166
|
+
const reports = generatedDirectory(projectRelative(out));
|
|
1167
|
+
written.push(writeReported(`${reports}/${SOURCE_MAP_FILE}`, sourceMapText(rendered, space, knowledge.sourceRevision, files)));
|
|
1088
1168
|
const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
|
|
1089
1169
|
const inData = entriesInData(entries, knowledge.regions);
|
|
1090
1170
|
if (rendered.notExecuted !== undefined) {
|
|
@@ -1097,14 +1177,18 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1097
1177
|
});
|
|
1098
1178
|
const files: Record<string, number> = {};
|
|
1099
1179
|
for (const range of placed) if (range.file !== undefined) files[range.file] = (files[range.file] ?? 0) + 1;
|
|
1100
|
-
const all = { revision: knowledge.
|
|
1101
|
-
written.push(writeReported(`${
|
|
1180
|
+
const all = { revision: knowledge.sourceRevision, instructions: rendered.notExecuted.instructions, files, ranges: placed };
|
|
1181
|
+
written.push(writeReported(`${reports}/${NOT_EXECUTED_FILE}`, `${JSON.stringify(all, null, 2)}\n`));
|
|
1102
1182
|
}
|
|
1183
|
+
// The leftovers that changed since the earlier run: the default build and the loader now leave out other bytes.
|
|
1184
|
+
const added = earlier === undefined ? [] : outside(laid.leftovers, earlier);
|
|
1185
|
+
const dropped = earlier === undefined ? [] : outside(earlier, laid.leftovers);
|
|
1186
|
+
const changed = added.length + dropped.length === 0 ? undefined : { added: added.map(showRange), removed: dropped.map(showRange) };
|
|
1103
1187
|
|
|
1104
1188
|
const output: Record<string, unknown> = {
|
|
1105
1189
|
out,
|
|
1106
1190
|
files: written,
|
|
1107
|
-
sourceMap: `${
|
|
1191
|
+
sourceMap: `${reports}/${SOURCE_MAP_FILE}`,
|
|
1108
1192
|
// The values that config.asm keeps and that are not the default: a build of the source is not the default build.
|
|
1109
1193
|
...(notDefault.length === 0 ? {} : { config: { file: `${out}/${CONFIG_FILE}`, notDefault } }),
|
|
1110
1194
|
revision: knowledge.revision,
|
|
@@ -1128,15 +1212,17 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1128
1212
|
...(rendered.notExecuted === undefined
|
|
1129
1213
|
? {}
|
|
1130
1214
|
: {
|
|
1131
|
-
notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `${
|
|
1215
|
+
notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, showRange, `${reports}/${NOT_EXECUTED_FILE}`) },
|
|
1132
1216
|
}),
|
|
1133
1217
|
...(laid.unusedModules.length === 0 ? {} : { unusedModules: laid.unusedModules.map((module) => ({ start: formatC64Address(module.start), file: module.file })) }),
|
|
1134
1218
|
// The bytes that nothing uses: in leftover files, which the default build and the loader leave out.
|
|
1135
1219
|
...(laid.leftovers.length === 0
|
|
1136
1220
|
? knowledge.coverage === undefined && space === DEFAULT_SPACE
|
|
1137
1221
|
? { leftovers: { bytes: 0, noCoverage: "The knowledge has no coverage, so no range is a leftover, and the default build and the loader have every byte of the program." } }
|
|
1138
|
-
:
|
|
1139
|
-
|
|
1222
|
+
: changed === undefined
|
|
1223
|
+
? {}
|
|
1224
|
+
: { leftovers: { bytes: 0, changed } }
|
|
1225
|
+
: { leftovers: { bytes: laid.leftovers.reduce((sum, range) => sum + range.end - range.start + 1, 0), ...listed(laid.leftovers, max, (range) => ({ ...showRange(range), bytes: range.end - range.start + 1, file: `${LEFTOVER_FOLDER}/leftover_${range.start.toString(16).padStart(4, "0")}.asm` })), ...(changed === undefined ? {} : { changed }) } }),
|
|
1140
1226
|
...(rendered.expressions.length === 0 && rendered.operandsAsNumbers.length === 0 ? {} : { operandExpressions: rendered.expressions.length }),
|
|
1141
1227
|
...(rendered.operandsAsNumbers.length === 0
|
|
1142
1228
|
? {}
|
|
@@ -1157,9 +1243,12 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1157
1243
|
patchesNotWritten: listed(laid.patchesNotWritten, max, (item) => ({ start: formatC64Address(item.start), end: formatC64Address(item.end), switch: item.switch, reason: item.reason })),
|
|
1158
1244
|
}),
|
|
1159
1245
|
};
|
|
1160
|
-
//
|
|
1161
|
-
const loaderPath = `${
|
|
1162
|
-
const keptLoader = () =>
|
|
1246
|
+
// 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.
|
|
1247
|
+
const loaderPath = `${BUILD_DIRECTORY}/${loaderName}.prg`;
|
|
1248
|
+
const keptLoader = () => {
|
|
1249
|
+
const earlier = loaderPrograms().filter((path) => path.endsWith(".prg"));
|
|
1250
|
+
return earlier.length === 0 ? {} : { kept: earlier };
|
|
1251
|
+
};
|
|
1163
1252
|
const notVerified = (fields: Record<string, unknown>) => ({ verified: false, ...fields, ...keptLoader() });
|
|
1164
1253
|
// The loader includes the source, so it is built only from a source that is identical to the image.
|
|
1165
1254
|
const notBuilt = (reason: string) => (state === undefined ? {} : { loader: notVerified({ reason: loaderRefused ?? reason }) });
|
|
@@ -1192,7 +1281,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1192
1281
|
const releases: ReleaseCheck[] = [];
|
|
1193
1282
|
for (const release of knowledge.releases) releases.push(await checkRelease(release, files, image));
|
|
1194
1283
|
if (releases.length > 0) output.releases = releases;
|
|
1195
|
-
const releasesFailed = releases.some((item) => item.result !== "identical"
|
|
1284
|
+
const releasesFailed = releases.some((item) => item.result !== "identical");
|
|
1196
1285
|
const sourceFailed = laid.patchesNotWritten.length > 0 || switches.some((item) => item.result !== "fits") || defaultFailed || releasesFailed;
|
|
1197
1286
|
if (loaderRefused !== undefined) return { output: { ...output, loader: notVerified({ reason: loaderRefused }) }, removed, failed: true };
|
|
1198
1287
|
if (loader === undefined || loaderMain === undefined || state === undefined) return { output, removed, failed: missingEntry !== undefined || sourceFailed };
|
|
@@ -1205,7 +1294,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1205
1294
|
const fileByte = (address: number) => copierBuild[2 + address - (loader.packed?.start ?? 0x0801)]!;
|
|
1206
1295
|
// A start screen of a captured stage: the show stage holds the packed program, as a cracktro holds the game.
|
|
1207
1296
|
const stageRow = knowledge.startScreen?.stage === undefined ? undefined : knowledge.startScreen;
|
|
1208
|
-
// The packed form: Exomizer packs the build of main.asm with the copier. Without Exomizer, or when its check fails, there is no new loader.
|
|
1297
|
+
// The packed form: Exomizer packs the build of main.asm with the copier. Without Exomizer, or when its check fails, there is no new loader program.
|
|
1209
1298
|
let packed: PackedLoader | undefined;
|
|
1210
1299
|
if (loader.packed !== undefined) {
|
|
1211
1300
|
try {
|
|
@@ -1225,12 +1314,12 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1225
1314
|
}
|
|
1226
1315
|
}
|
|
1227
1316
|
const program = stage?.program ?? packed?.program ?? copierBuild;
|
|
1228
|
-
// The check runs the new loader from a scratch file. Only a loader whose check ran goes to
|
|
1229
|
-
// that cannot run (no host, or a host of another release) keeps the loader
|
|
1317
|
+
// The check runs the new loader from a scratch file. Only a loader whose check ran goes to the build folder, so a check
|
|
1318
|
+
// that cannot run (no host, or a host of another release) keeps the loader program of an earlier run.
|
|
1230
1319
|
ensureLocal(projectRoot());
|
|
1231
1320
|
const scratch = `${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/${LOADER_CHECK_DIRECTORY}`;
|
|
1232
1321
|
mkdirSync(resolveProjectPath(scratch), { recursive: true });
|
|
1233
|
-
const checkPath = `${scratch}
|
|
1322
|
+
const checkPath = `${scratch}/${loaderName}.prg`;
|
|
1234
1323
|
writeFileSync(resolveProjectPath(checkPath), program);
|
|
1235
1324
|
// The unpack runs before the copier, or before the show stage, which then starts the loader.
|
|
1236
1325
|
const unpackFrames = (cycles: number | undefined) => (cycles === undefined ? LOADER_FRAMES : RUN_LIMIT_FRAMES + Math.ceil(cycles / PAL_FRAME_CYCLES));
|
|
@@ -1247,15 +1336,21 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1247
1336
|
ran = await runLoader(checkPath, program, loader, state, { jump, copierSource, fileByte, copierFrames, ...(startScreen === undefined ? {} : { startScreen }), ...stageRun }, expected);
|
|
1248
1337
|
} catch (error) {
|
|
1249
1338
|
if (!isRefusal(error)) throw error;
|
|
1250
|
-
const what =
|
|
1251
|
-
return { output: { ...output, loader: notVerified({ reason: `The check of
|
|
1339
|
+
const what = loaderPrograms().length > 0 ? "kept the loader program of an earlier run" : "wrote no loader program";
|
|
1340
|
+
return { output: { ...output, loader: notVerified({ reason: `The check of ${loaderName}.prg did not run, so the script ${what}. ${error.message}` }) }, removed, failed: true };
|
|
1252
1341
|
} finally {
|
|
1253
1342
|
rmSync(resolveProjectPath(scratch), { recursive: true, force: true });
|
|
1254
1343
|
}
|
|
1255
|
-
|
|
1344
|
+
// A loader program of an earlier run with another build name goes: config.asm has other values now.
|
|
1345
|
+
for (const path of loaderPrograms().filter((item) => item !== loaderPath && item !== symbolsPath(loaderPath))) {
|
|
1346
|
+
rmSync(resolveProjectPath(path), { force: true });
|
|
1347
|
+
removed.push(path);
|
|
1348
|
+
}
|
|
1349
|
+
written.push(writeReported(loaderPath, program), writeReported(symbolsPath(loaderPath), symbolsFileText(loaderSymbols(loaderMain.symbols, loaderBuilt.symbols, stage?.symbols ?? []))));
|
|
1256
1350
|
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" }));
|
|
1257
1351
|
output.loader = {
|
|
1258
1352
|
program: loaderPath,
|
|
1353
|
+
symbols: symbolsPath(loaderPath),
|
|
1259
1354
|
...(packed === undefined ? {} : { packed: { packedBytes: packed.packedBytes, unpackedBytes: packed.unpackedBytes } }),
|
|
1260
1355
|
...(stage === undefined
|
|
1261
1356
|
? {}
|
|
@@ -1287,15 +1382,21 @@ function exportValue(row: SourceSwitch): 0 | 1 {
|
|
|
1287
1382
|
|
|
1288
1383
|
const NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
1289
1384
|
|
|
1290
|
-
/**
|
|
1291
|
-
|
|
1385
|
+
/**
|
|
1386
|
+
* The BASIC line that starts a PRG: its bytes, and the address of its first
|
|
1387
|
+
* SYS when the image holds it (the entry of a PRG without one in the
|
|
1388
|
+
* knowledge). Undefined when the first segment holds no BASIC line with a SYS.
|
|
1389
|
+
*/
|
|
1390
|
+
function basicStart(image: ProgramImage): { line: AddressRange; entry?: number } | undefined {
|
|
1292
1391
|
const first = image.segments[0];
|
|
1293
1392
|
if (first === undefined) return undefined;
|
|
1294
1393
|
const tokenized = parseTokenized(Uint8Array.from([first.start & 0xff, first.start >> 8, ...image.memory.subarray(first.start, first.end + 1)]));
|
|
1295
1394
|
if ("reason" in tokenized) return undefined;
|
|
1296
|
-
const sys = findHandoffs(tokenized.lines).find((handoff) => handoff.kind === "sys"
|
|
1297
|
-
|
|
1298
|
-
|
|
1395
|
+
const sys = findHandoffs(tokenized.lines).find((handoff) => handoff.kind === "sys");
|
|
1396
|
+
if (sys === undefined) return undefined;
|
|
1397
|
+
const line = { start: first.start, end: Math.min(first.end, tokenized.basicEnd - 1) };
|
|
1398
|
+
const address = "address" in sys ? sys.address : undefined;
|
|
1399
|
+
return address !== undefined && image.segments.some((segment) => address >= segment.start && address <= segment.end) ? { line, entry: address } : { line };
|
|
1299
1400
|
}
|
|
1300
1401
|
|
|
1301
1402
|
/** The parts of a region outside the holes. A part that is not the whole region has no element size: its length need not be a multiple of it. */
|
|
@@ -1334,9 +1435,10 @@ function freeRanges(knowledge: SourceKnowledge, memory: Uint8Array, instructions
|
|
|
1334
1435
|
for (const operand of knowledge.operands) {
|
|
1335
1436
|
const names = operand.symbol !== undefined ? [operand.symbol] : identifiers(operand.expression ?? "");
|
|
1336
1437
|
const targets = names.flatMap((item) => (addressOf.has(item) ? [(addressOf.get(item)! + (operand.symbol !== undefined ? operand.offset : 0)) & 0xffff] : []));
|
|
1337
|
-
|
|
1438
|
+
operandTargets.set(operand.address, targets);
|
|
1338
1439
|
}
|
|
1339
|
-
const
|
|
1440
|
+
const basic = basicStart(image);
|
|
1441
|
+
const entry = image.entry ?? basic?.entry;
|
|
1340
1442
|
return planDrops({
|
|
1341
1443
|
segments: image.segments,
|
|
1342
1444
|
memory,
|
|
@@ -1346,6 +1448,8 @@ function freeRanges(knowledge: SourceKnowledge, memory: Uint8Array, instructions
|
|
|
1346
1448
|
regions: effectiveRegions(knowledge.regions),
|
|
1347
1449
|
references: knowledge.references,
|
|
1348
1450
|
operandTargets,
|
|
1451
|
+
rom: romOf(image, knowledge, [], knowledge.coverage),
|
|
1452
|
+
...(basic === undefined ? {} : { basic: basic.line }),
|
|
1349
1453
|
changed: [...ranges.changed],
|
|
1350
1454
|
keep: [...ranges.keep],
|
|
1351
1455
|
drop: [...ranges.drop],
|
|
@@ -1365,9 +1469,12 @@ function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<numbe
|
|
|
1365
1469
|
const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
|
|
1366
1470
|
const screenParts = knowledge.startScreen === undefined || knowledge.startScreen.stage !== undefined ? [] : startScreenRanges(knowledge.startScreen).map((part) => part.range);
|
|
1367
1471
|
const named = knowledge.patches.flatMap((patch) => patchTargets(patch.code, addressOf)).map((address) => ({ start: address, end: address }));
|
|
1368
|
-
const keep = [...screenParts, ...kept, ...
|
|
1472
|
+
const keep = [...screenParts, ...kept, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
|
|
1369
1473
|
const changed = knowledge.patches.map((patch) => ({ start: patch.start, end: patch.end })).filter(inImage);
|
|
1370
|
-
|
|
1474
|
+
const free = freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] }).free.map((range) => ({ start: range.start, end: range.end }));
|
|
1475
|
+
// A macro use in code that nothing uses goes with that code. A leftover never cuts a use in two: its edge stops at the use.
|
|
1476
|
+
const cut = (range: AddressRange) => knowledge.macroUses.filter((use) => use.start <= range.end && range.start <= use.end && (use.start < range.start || use.end > range.end));
|
|
1477
|
+
return free.flatMap((range) => subtract(range, cut(range)));
|
|
1371
1478
|
}
|
|
1372
1479
|
|
|
1373
1480
|
/** Every file in a folder with its path in it, with / between the parts, in path order. `skip` leaves out a folder by its path. */
|
|
@@ -1575,7 +1682,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
|
|
|
1575
1682
|
),
|
|
1576
1683
|
);
|
|
1577
1684
|
for (const file of exported.files) files.push(put(`src/${file.name}`, file.text));
|
|
1578
|
-
files.push(put(`baseline/${name}.prg`, baseline.program), put(`baseline/${name}.
|
|
1685
|
+
files.push(put(`baseline/${name}.prg`, baseline.program), put(symbolsPath(`baseline/${name}.prg`), symbolsFileText(shownSymbols)));
|
|
1579
1686
|
for (const test of tests) files.push(put(test.file, test.text));
|
|
1580
1687
|
ensureLocal(to);
|
|
1581
1688
|
const folder = basename(to);
|
|
@@ -1650,9 +1757,9 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
|
|
|
1650
1757
|
steps.push("Read the reason of each item in patchesNotWritten, and the result of each switch and of the default build. Correct the patches and the switches in the project knowledge.");
|
|
1651
1758
|
again = true;
|
|
1652
1759
|
}
|
|
1653
|
-
const releases = body.releases as Array<{ result: string
|
|
1654
|
-
if (releases?.some((item) => item.result !== "identical"
|
|
1655
|
-
steps.push("Read the result of each release.
|
|
1760
|
+
const releases = body.releases as Array<{ result: string }> | undefined;
|
|
1761
|
+
if (releases?.some((item) => item.result !== "identical") === true) {
|
|
1762
|
+
steps.push("Read the result of each release. Record a switch and a patch in the project knowledge for each difference.");
|
|
1656
1763
|
again = true;
|
|
1657
1764
|
}
|
|
1658
1765
|
if ((body.loader as { verified?: boolean } | undefined)?.verified === false) steps.push("The loader is not verified. Read loader.reason, loader.differences and loader.stop.");
|
|
@@ -1707,16 +1814,16 @@ await runScript({
|
|
|
1707
1814
|
commands: [
|
|
1708
1815
|
{
|
|
1709
1816
|
name: "generate",
|
|
1710
|
-
summary: "Writes the source files
|
|
1817
|
+
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.",
|
|
1711
1818
|
options: {
|
|
1712
1819
|
out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "the folder for the source files, relative to the project folder", required: true },
|
|
1713
1820
|
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" },
|
|
1714
1821
|
space: { ...OPTIONS.space, help: "the knowledge space of the program: c64 (the default), drive8, loading, or bank0 to bank255. --loader is for c64 only" },
|
|
1715
|
-
loader: { kind: "flag", help: "also write loader.asm and loader.prg
|
|
1822
|
+
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" },
|
|
1716
1823
|
"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" },
|
|
1717
1824
|
"max-listed": OPTIONS["max-listed"],
|
|
1718
1825
|
},
|
|
1719
|
-
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
|
|
1826
|
+
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.",
|
|
1720
1827
|
run: async (call) => {
|
|
1721
1828
|
const { output, failed, removed } = await generate(call);
|
|
1722
1829
|
// A file of an earlier run that this run removed and did not write again.
|