@henols/c64-re-tools 2.7.1 → 2.8.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/package.json +1 -1
  2. package/skills/c64-assembler/SKILL.md +23 -38
  3. package/skills/c64-assembler/scripts/assembler.ts +114 -16
  4. package/skills/c64-basic/SKILL.md +11 -31
  5. package/skills/c64-basic/scripts/basic.ts +4 -1
  6. package/skills/c64-development/SKILL.md +2 -2
  7. package/skills/c64-disk/SKILL.md +11 -32
  8. package/skills/c64-docs/SKILL.md +27 -45
  9. package/skills/c64-docs/references/page-types.md +20 -18
  10. package/skills/c64-docs/references/style.md +10 -4
  11. package/skills/c64-docs/scripts/docs.ts +13 -2
  12. package/skills/c64-docs/scripts/lib/reference.ts +47 -5
  13. package/skills/c64-knowledge/SKILL.md +138 -267
  14. package/skills/c64-knowledge/references/batches.md +48 -0
  15. package/skills/c64-knowledge/references/coverage.md +29 -0
  16. package/skills/c64-knowledge/references/source-knowledge.md +72 -0
  17. package/skills/c64-knowledge/references/start-screen.md +44 -0
  18. package/skills/c64-knowledge/scripts/knowledge.ts +266 -61
  19. package/skills/c64-knowledge/scripts/lib/check.ts +133 -0
  20. package/skills/c64-knowledge/scripts/lib/listing.ts +72 -8
  21. package/skills/c64-memory-map/SKILL.md +11 -32
  22. package/skills/c64-packer/SKILL.md +11 -31
  23. package/skills/c64-provenance/SKILL.md +40 -62
  24. package/skills/c64-provenance/scripts/lib/leftovers.ts +8 -3
  25. package/skills/c64-provenance/scripts/provenance.ts +64 -55
  26. package/skills/c64-reverse-engineering/SKILL.md +20 -47
  27. package/skills/c64-reverse-engineering/references/comment-check.md +42 -0
  28. package/skills/c64-reverse-engineering/references/versions.md +47 -0
  29. package/skills/c64-source/SKILL.md +43 -237
  30. package/skills/c64-source/references/export.md +50 -0
  31. package/skills/c64-source/references/loader.md +78 -0
  32. package/skills/c64-source/references/source-format.md +46 -0
  33. package/skills/c64-source/scripts/lib/export.ts +20 -7
  34. package/skills/c64-source/scripts/lib/loader.ts +4 -82
  35. package/skills/c64-source/scripts/source.ts +48 -51
  36. package/skills/c64-static-analysis/SKILL.md +51 -52
  37. package/skills/c64-static-analysis/scripts/lib/coverage.ts +55 -2
  38. package/skills/c64-static-analysis/scripts/lib/idioms.ts +28 -9
  39. package/skills/c64-static-analysis/scripts/static-analysis.ts +69 -15
  40. package/skills/c64-testing/SKILL.md +72 -58
  41. package/skills/c64-testing/references/recording-format.md +5 -80
  42. package/skills/c64-testing/references/scenario-format.md +4 -12
  43. package/skills/c64-testing/scripts/lib/play.ts +16 -8
  44. package/skills/c64-testing/scripts/lib/recording.ts +74 -9
  45. package/skills/c64-testing/scripts/lib/replay.ts +4 -0
  46. package/skills/c64-testing/scripts/lib/runs.ts +112 -1
  47. package/skills/c64-testing/scripts/lib/scenario.ts +12 -6
  48. package/skills/c64-testing/scripts/lib/start-screen.ts +27 -0
  49. package/skills/c64-testing/scripts/testing.ts +34 -13
  50. package/skills/c64-unpacker/SKILL.md +10 -30
  51. package/skills/emulator/SKILL.md +7 -36
  52. package/src/build-name.ts +12 -1
  53. package/src/knowledge/history.ts +8 -0
  54. package/src/knowledge/program.ts +73 -1
  55. package/src/knowledge/read.ts +46 -2
  56. package/src/knowledge/recording-files.ts +32 -0
  57. package/src/knowledge/schema.ts +3 -1
  58. package/src/knowledge/separate.ts +90 -3
  59. package/src/knowledge/start-screen.ts +99 -17
  60. package/src/knowledge/text.ts +2 -1
  61. package/src/knowledge/write.ts +15 -8
  62. package/src/loader.ts +167 -0
  63. package/src/native/decompiler/analyze.ts +7 -6
  64. package/src/native/decompiler/walk.ts +32 -2
  65. package/src/native/dxa.ts +4 -4
  66. package/src/native/types.ts +32 -4
  67. package/src/script.ts +87 -17
  68. package/skills/c64-export/SKILL.md +0 -63
package/src/loader.ts ADDED
@@ -0,0 +1,167 @@
1
+ // The packed loader program of a generated source. Exomizer packs the loaded
2
+ // ranges of the build of main.asm (from $0400) and the build of loader.asm,
3
+ // which holds the copier and the bytes of pages 0-3, into one program that
4
+ // unpacks itself and starts the copier with all RAM visible ($01 = $34).
5
+ // c64-source packs it for the loader that it checks; c64-assembler packs it
6
+ // for other switch values, from the same files and with the same parts. The
7
+ // loaded ranges are the segments of the program without the leftovers: a
8
+ // leftover file of the source gives its range in its first line.
9
+
10
+ import { type AddressRange, formatC64Address, prgRange } from "./c64.ts";
11
+ import { compareBuild, mergedPrograms } from "./compare.ts";
12
+ import { Refusal } from "./errors.ts";
13
+ import { pack } from "./native/exomizer.ts";
14
+ import type { ToolContext } from "./native/run.ts";
15
+ import type { AssembledSymbol } from "./native/types.ts";
16
+
17
+ /** The label of the copier in loader.asm. In the packed form, its address is the copier address, where the unpack jumps. */
18
+ export const COPIER_SOURCE = "loader_copier_src";
19
+
20
+ /** The memory configuration at the start of the copier of the packed form: all RAM visible. */
21
+ export const PACKED_EXIT_MEMORY = 0x34;
22
+
23
+ /** The pages that the unpacker of Exomizer uses: the copier of the packed form writes them, so main.asm is packed from here. */
24
+ const PACKED_FROM = 0x0400;
25
+
26
+ /** The first line of a leftover file: `; Leftovers $xxxx-$yyyy: ...`. */
27
+ const LEFTOVER_RANGE = /^; Leftovers (\$[0-9a-f]{4})-(\$[0-9a-f]{4}):/m;
28
+
29
+ /** The range of a leftover file of a generated source, from its first line. Undefined for a text without that line. */
30
+ export function leftoverRange(text: string): AddressRange | undefined {
31
+ const found = LEFTOVER_RANGE.exec(text);
32
+ return found === null ? undefined : { start: Number.parseInt(found[1]!.slice(1), 16), end: Number.parseInt(found[2]!.slice(1), 16) };
33
+ }
34
+
35
+ const show = (range: AddressRange) => `${formatC64Address(range.start)}-${formatC64Address(range.end)}`;
36
+
37
+ /** The parts of `range` outside every hole, in address order. */
38
+ function without(range: AddressRange, holes: readonly AddressRange[]): AddressRange[] {
39
+ let pieces = [range];
40
+ for (const hole of holes) {
41
+ pieces = pieces.flatMap((piece) => {
42
+ if (hole.end < piece.start || hole.start > piece.end) return [piece];
43
+ return [
44
+ ...(hole.start > piece.start ? [{ start: piece.start, end: hole.start - 1 }] : []),
45
+ ...(hole.end < piece.end ? [{ start: hole.end + 1, end: piece.end }] : []),
46
+ ];
47
+ });
48
+ }
49
+ return pieces;
50
+ }
51
+
52
+ /**
53
+ * The ranges that the packed loader loads from a build of main.asm: the
54
+ * segments of the program without the leftovers. Refuses what only the loader
55
+ * of generate can have: a start screen of a captured stage, which is a program
56
+ * of its own in front of the packed loader, and a segment below $0400, whose
57
+ * bytes loader.asm holds with the switch values of generate.
58
+ */
59
+ export function packedRanges(segments: readonly AddressRange[], leftovers: readonly AddressRange[], stage: string | undefined): AddressRange[] {
60
+ if (stage !== undefined) {
61
+ throw new Refusal("invalid-input", `The start screen is of the captured stage ${stage}, and only the generation of the source with the loader makes that loader program. Set the switch values in config.asm, and generate the source with the loader.`);
62
+ }
63
+ const loaded = [...segments].sort((a, b) => a.start - b.start).flatMap((segment) => without(segment, leftovers));
64
+ const low = loaded.find((range) => range.start < PACKED_FROM);
65
+ if (low !== undefined) {
66
+ throw new Refusal("invalid-input", `The segment ${show(low)} starts below $0400, and loader.asm holds its bytes there with the switch values of generate. Set the switch values in config.asm, and generate the source with the loader.`);
67
+ }
68
+ return loaded;
69
+ }
70
+
71
+ /**
72
+ * Checks the two builds of the packed form before the pack: the build of
73
+ * main.asm holds each loaded range, and the build of loader.asm, which holds
74
+ * the bytes of the program between its free ranges, has the bytes of the build
75
+ * of main.asm there. A patch of a switch between the free ranges changes them,
76
+ * and the copier build would put the old bytes back. Refuses by name.
77
+ */
78
+ export function checkPackedBuilds(main: Uint8Array, copier: Uint8Array, loaded: readonly AddressRange[]): void {
79
+ const program = prgRange(main);
80
+ const outside = loaded.find((range) => range.start < program.start || range.end > program.end);
81
+ if (outside !== undefined) {
82
+ throw new Refusal("invalid-input", `The build of main.asm does not hold ${show(outside)} of the program in the knowledge. Generate the source again from the knowledge.`);
83
+ }
84
+ const build = prgRange(copier);
85
+ for (const range of loaded) {
86
+ for (let address = Math.max(range.start, build.start); address <= Math.min(range.end, build.end); address++) {
87
+ if (build.body[address - build.start] === program.body[address - program.start]) continue;
88
+ throw new Refusal(
89
+ "invalid-input",
90
+ `These switch values change the byte at ${formatC64Address(address)}, between the free ranges of loader.asm (${show(build)}), and loader.asm holds the byte of generate there. Set the switch values in config.asm, and generate the source with the loader.`,
91
+ );
92
+ }
93
+ }
94
+ }
95
+
96
+ /** What Exomizer makes of a packed loader. */
97
+ export interface PackedLoader {
98
+ /** The loader program: it loads at $0801 and starts with RUN. */
99
+ program: Buffer;
100
+ packedBytes: number;
101
+ unpackedBytes: number;
102
+ /** The CPU cycles of the unpack, when Exomizer gives them. */
103
+ cycles?: number;
104
+ }
105
+
106
+ /**
107
+ * Packs the loaded ranges of the build of main.asm from $0400 and the build of
108
+ * loader.asm (the copier wins where they overlap) with the entry at the copier
109
+ * and $01 = $34, and checks the unpack in the emulator of Exomizer: every byte
110
+ * of the two builds, and the jump to the copier. Refuses by name when it does
111
+ * not hold.
112
+ */
113
+ export async function packLoader(main: Uint8Array, copier: Uint8Array, plan: { loaded: readonly AddressRange[]; copier: number }, context: ToolContext): Promise<PackedLoader> {
114
+ return packParts(packedParts(main, copier, plan.loaded), plan.copier, PACKED_EXIT_MEMORY, "main.asm and loader.asm", "the copier", context);
115
+ }
116
+
117
+ /** What Exomizer packs in the packed form: the loaded ranges of the build of main.asm from $0400, and the build of loader.asm. */
118
+ function packedParts(main: Uint8Array, copier: Uint8Array, loaded: readonly AddressRange[]): Array<{ start: number; body: Uint8Array }> {
119
+ // The unpacker uses pages 0-3; the copier writes them. The leftovers between the loaded ranges are not packed.
120
+ const program = prgRange(main);
121
+ const ranges = loaded.flatMap((range) => {
122
+ const start = Math.max(range.start, PACKED_FROM, program.start);
123
+ const end = Math.min(range.end, program.end);
124
+ return start <= end ? [{ start, body: program.body.subarray(start - program.start, end - program.start + 1) }] : [];
125
+ });
126
+ return [...ranges, prgRange(copier)];
127
+ }
128
+
129
+ /**
130
+ * Packs parts (a later one wins where they overlap) into one program that
131
+ * unpacks itself, starts at `entry` with $01 = `exitMemory`, and checks the
132
+ * unpack in the emulator of Exomizer: every byte of the parts, and the jump
133
+ * to the entry. Refuses by name when it does not hold.
134
+ */
135
+ export async function packParts(parts: ReadonlyArray<{ start: number; body: Uint8Array }>, entry: number, exitMemory: number, what: string, entryName: string, context: ToolContext): Promise<PackedLoader> {
136
+ const prg = (part: { start: number; body: Uint8Array }) => Buffer.concat([Buffer.from([part.start & 0xff, part.start >> 8]), part.body]);
137
+ const packed = await pack({ programs: parts.map(prg), entry, exitMemory }, context);
138
+ if (packed.entry !== entry) throw new Refusal("operation-failed", `The unpack in the emulator of Exomizer jumps to ${formatC64Address(packed.entry)}, not to ${entryName} at ${formatC64Address(entry)}.`);
139
+ const reference = mergedPrograms(parts);
140
+ const wrong = compareBuild(packed.unpacked, reference).segments.find((segment) => segment.result !== "identical");
141
+ if (wrong !== undefined) {
142
+ const first = wrong.firstDifference === undefined ? "" : `: the first is ${wrong.firstDifference.address}, ${wrong.firstDifference.built} and not ${wrong.firstDifference.reference}`;
143
+ throw new Refusal("operation-failed", `The unpack in the emulator of Exomizer does not give ${wrong.start}-${wrong.end} of ${what} (${wrong.result}${first}).`);
144
+ }
145
+ const unpackedBytes = reference.segments.reduce((sum, segment) => sum + segment.end - segment.start + 1, 0);
146
+ return { program: packed.program, packedBytes: packed.program.length, unpackedBytes, ...(packed.cycles === undefined ? {} : { cycles: packed.cycles }) };
147
+ }
148
+
149
+ /**
150
+ * The symbols of the loader program: the labels of the build of loader.asm,
151
+ * of the build of main.asm, and of start_screen_stage.asm when the loader has
152
+ * a show stage. A test takes one symbols file. Refuses a name with two values.
153
+ */
154
+ export function loaderSymbols(...builds: ReadonlyArray<readonly AssembledSymbol[]>): AssembledSymbol[] {
155
+ const valueOf = (symbol: AssembledSymbol) => (symbol.kind === "address" ? symbol.address : symbol.value);
156
+ const byName = new Map<string, AssembledSymbol>();
157
+ for (const symbol of builds.flat()) {
158
+ const known = byName.get(symbol.name);
159
+ if (known !== undefined && valueOf(known) !== valueOf(symbol)) {
160
+ throw new Refusal("operation-failed", `The builds of the loader program give ${symbol.name} two values, ${valueOf(known)} and ${valueOf(symbol)}. This is a defect of the script.`);
161
+ }
162
+ // An address in one build can be outside the load range of the other build, where it is a constant.
163
+ const kept = known === undefined || (known.kind === "constant" && symbol.kind === "address") ? symbol : known;
164
+ byName.set(symbol.name, { ...kept, used: symbol.used || (known?.used ?? false) });
165
+ }
166
+ return [...byName.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
167
+ }
@@ -4,7 +4,7 @@
4
4
  // before the script imports it.
5
5
 
6
6
  import { describeError, WireFailure } from "../../protocol/messages.ts";
7
- import { checkDecompilerResult, checkRequestBounds, DECOMPILER_LIMITS, imageRange, seedsInside, type DecompilerParams, type DecompilerResult } from "../types.ts";
7
+ import { checkDecompilerResult, checkRequestBounds, DECOMPILER_LIMITS, imageRange, seedsInside, type DecompilerParams, type DecompilerResult, type SeedReport } from "../types.ts";
8
8
  import type { ToolContext } from "../run.ts";
9
9
  import { walk } from "./walk.ts";
10
10
  import { decompile, loadImage, setName, SLEIGH_VERSION } from "./wasm.ts";
@@ -16,21 +16,22 @@ export async function analyze(
16
16
  params: DecompilerParams,
17
17
  image: Buffer,
18
18
  context: ToolContext,
19
- ): Promise<{ result: DecompilerResult }> {
19
+ ): Promise<{ result: DecompilerResult; seeds: SeedReport }> {
20
20
  checkRequestBounds(params);
21
21
  const { start, end, body } = imageRange(params.imageKind, image);
22
22
 
23
23
  // The decoder sees only the loaded bytes; labels may name any address.
24
- const { entryPoints, codeStarts, dataRanges } = seedsInside(params, start, end);
24
+ const { entryPoints, codeStarts, dataRanges, report } = seedsInside(params, start, end);
25
25
  if (entryPoints.length === 0) {
26
26
  throw new WireFailure("invalid-input", "Give at least one entry point inside the program, for example the SYS address of its BASIC loader.");
27
27
  }
28
28
  context.signal.throwIfAborted();
29
29
 
30
- let walked: ReturnType<typeof walk>;
30
+ let walked: Omit<ReturnType<typeof walk>, "refusedSeeds">;
31
+ let refusedSeeds: ReturnType<typeof walk>["refusedSeeds"];
31
32
  try {
32
33
  loadImage(body, start);
33
- walked = walk(body, start, end, { entryPoints, codeStarts, dataRanges, labels: params.labels });
34
+ ({ refusedSeeds, ...walked } = walk(body, start, end, { entryPoints, codeStarts, dataRanges, labels: params.labels }));
34
35
  } catch (error) {
35
36
  context.log?.(`The decoder failed: ${describeError(error)}`);
36
37
  throw new WireFailure("operation-failed", `The decoder failed: ${describeError(error)}. Nothing was imported.`);
@@ -44,7 +45,7 @@ export async function analyze(
44
45
  context.log?.(`Decompiler result rejected: ${describeError(error)}`);
45
46
  throw new WireFailure("operation-failed", `The decompiler returned an incomplete or inconsistent result. Nothing was imported. The check found: ${describeError(error)}.`);
46
47
  }
47
- return { result };
48
+ return { result, seeds: { refused: [...report.refused, ...refusedSeeds].sort((a, b) => a.address - b.address), dataRangesLeftOut: report.dataRangesLeftOut } };
48
49
  }
49
50
 
50
51
  /** The requested routines as C text, within the character bounds; the labels name routines and data. */
@@ -6,7 +6,7 @@
6
6
  // code before it, or else from the pointer in the image.
7
7
 
8
8
  import { SYMBOL_NAME } from "../../c64.ts";
9
- import type { DecompilerInstruction, DecompilerResult } from "../types.ts";
9
+ import type { DecompilerInstruction, DecompilerResult, RefusedSeed } from "../types.ts";
10
10
  import { PcodeState } from "./pcode.ts";
11
11
  import { decode, type Decoded, type Varnode } from "./wasm.ts";
12
12
 
@@ -39,7 +39,7 @@ function operandValue(bytes: readonly number[]): number | undefined {
39
39
  }
40
40
 
41
41
  /** Decodes [start, end] from the seeds; the image bytes are already loaded at start. */
42
- export function walk(image: Uint8Array, start: number, end: number, seeds: WalkSeeds): Omit<DecompilerResult, "decompilations" | "completeness" | "toolVersion"> {
42
+ export function walk(image: Uint8Array, start: number, end: number, seeds: WalkSeeds): Omit<DecompilerResult, "decompilations" | "completeness" | "toolVersion"> & { refusedSeeds: RefusedSeed[] } {
43
43
  const isData = new Uint8Array(0x10000);
44
44
  for (const range of seeds.dataRanges) isData.fill(1, range.start, range.end + 1);
45
45
  const imageByte = (address: number) => (address >= start && address <= end ? image[address - start] : undefined);
@@ -140,6 +140,12 @@ export function walk(image: Uint8Array, start: number, end: number, seeds: WalkS
140
140
  if (instruction.fallthrough) work.push(last + 1);
141
141
  }
142
142
 
143
+ // Read before the bytes that operands access become data: the data ranges then are the seeds' own.
144
+ const refusedSeeds = [...new Set([...seeds.entryPoints, ...seeds.codeStarts])]
145
+ .filter((address) => !instructions.has(address))
146
+ .sort((a, b) => a - b)
147
+ .map((address) => refusal(address, end, owner, isData));
148
+
143
149
  for (const instruction of instructions.values()) {
144
150
  for (const address of instruction.accessed) if (address >= start && address <= end && owner[address] === -1) isData[address] = 1;
145
151
  }
@@ -157,6 +163,7 @@ export function walk(image: Uint8Array, start: number, end: number, seeds: WalkS
157
163
  }
158
164
  }
159
165
  return {
166
+ refusedSeeds,
160
167
  coverage: [{ start, end }],
161
168
  functions: [...functions]
162
169
  .filter((entry) => instructions.has(entry))
@@ -174,6 +181,29 @@ export function walk(image: Uint8Array, start: number, end: number, seeds: WalkS
174
181
  };
175
182
  }
176
183
 
184
+ /**
185
+ * Why the walk did not decode a seed inside the program: its byte is in an
186
+ * instruction or a data range, no instruction decodes there, or its instruction
187
+ * runs past the end, into an instruction or into a data range.
188
+ */
189
+ function refusal(address: number, end: number, owner: Int32Array, isData: Uint8Array): RefusedSeed {
190
+ if (owner[address] !== -1) return { address, reason: "inside-instruction", at: owner[address]! };
191
+ if (isData[address]) return { address, reason: "in-data" };
192
+ let decoded: Decoded;
193
+ try {
194
+ decoded = decode(address);
195
+ } catch {
196
+ return { address, reason: "not-decodable" };
197
+ }
198
+ const last = address + decoded.length - 1;
199
+ if (last > end) return { address, reason: "past-end" };
200
+ for (let at = address + 1; at <= last; at++) {
201
+ if (owner[at] !== -1) return { address, reason: "into-instruction", at: owner[at]! };
202
+ if (isData[at]) return { address, reason: "into-data" };
203
+ }
204
+ return { address, reason: "not-decodable" };
205
+ }
206
+
177
207
  /** The target of the indirect jump at address, or undefined; a zero pointer is no target. */
178
208
  function indirectTarget(address: number, decoded: Decoded, instructions: Map<number, Instruction>, owner: Int32Array, imageByte: (address: number) => number | undefined): number | undefined {
179
209
  const chain: Decoded[] = [];
package/src/native/dxa.ts CHANGED
@@ -11,7 +11,7 @@ import { stripVTControlCharacters } from "node:util";
11
11
  import { Refusal } from "../errors.ts";
12
12
  import { SYMBOL_NAME } from "../c64.ts";
13
13
  import { describeError, WireFailure } from "../protocol/messages.ts";
14
- import { checkDxaResult, checkRequestBounds, imageRange, seedsInside, type DxaParams, type DxaResult } from "./types.ts";
14
+ import { checkDxaResult, checkRequestBounds, imageRange, seedsInside, type DxaParams, type DxaResult, type SeedReport } from "./types.ts";
15
15
  import { Workspace } from "./staging.ts";
16
16
  import { DXA, findTool } from "./discover.ts";
17
17
  import { outputTail, runTool, runToolOrFail, type ToolContext } from "./run.ts";
@@ -118,11 +118,11 @@ export async function analyze(
118
118
  params: DxaParams,
119
119
  image: Buffer,
120
120
  context: ToolContext,
121
- ): Promise<{ result: DxaResult; attachments: Buffer[] }> {
121
+ ): Promise<{ result: DxaResult; attachments: Buffer[]; seeds: SeedReport }> {
122
122
  checkRequestBounds(params);
123
123
  const executable = findTool(DXA, context.env);
124
124
  const { start, end } = imageRange(params.imageKind, image);
125
- const { entryPoints, dataRanges } = seedsInside(params, start, end);
125
+ const { entryPoints, dataRanges, report } = seedsInside(params, start, end);
126
126
 
127
127
  const workspace = Workspace.create(context.supervisor);
128
128
  try {
@@ -171,7 +171,7 @@ export async function analyze(
171
171
  const tail = outputTail("dxa", { stdout: "", stderr: run.stderr }, workspace.root);
172
172
  throw new WireFailure("operation-failed", `dxa returned an incomplete or inconsistent listing. Nothing was imported. The check found: ${describeError(error)}.${tail}`);
173
173
  }
174
- return { result, attachments: [listing] };
174
+ return { result, attachments: [listing], seeds: report };
175
175
  } finally {
176
176
  workspace.remove();
177
177
  }
@@ -244,19 +244,47 @@ export function imageRange(kind: ImageKind, image: Uint8Array): { start: number;
244
244
  return prgRange(image);
245
245
  }
246
246
 
247
+ /**
248
+ * Why an analysis did not decode an entry point or a code start that it got:
249
+ * outside the program, in a data range, inside an instruction that it decoded
250
+ * (`at`), no instruction decodes there, or the instruction runs past the end
251
+ * of the program, into an instruction (`at`) or into a data range.
252
+ */
253
+ export type RefusedSeedReason = "outside-program" | "in-data" | "inside-instruction" | "not-decodable" | "past-end" | "into-instruction" | "into-data";
254
+
255
+ export interface RefusedSeed {
256
+ address: number;
257
+ reason: RefusedSeedReason;
258
+ /** The start of the instruction that holds the seed or that the seed runs into. */
259
+ at?: number;
260
+ }
261
+
262
+ /** What an analysis did with its seeds: the seeds that it did not decode, and the data ranges that it left out because code starts in them. */
263
+ export interface SeedReport {
264
+ refused: RefusedSeed[];
265
+ dataRangesLeftOut: Array<{ start: number; end: number; code: number }>;
266
+ }
267
+
247
268
  /**
248
269
  * The seeds that an analysis of [start, end] can use: the entry points inside
249
270
  * it, and the data ranges cut to it. A data range that holds an entry point
250
- * is left out, so that the entry point is disassembled.
271
+ * is left out, so that the entry point is disassembled. `report` gives what
272
+ * was left out.
251
273
  */
252
- export function seedsInside(params: Pick<DecompilerParams, "entryPoints" | "dataRanges" | "codeStarts">, start: number, end: number): { entryPoints: number[]; codeStarts: number[]; dataRanges: DecompilerParams["dataRanges"] } {
274
+ export function seedsInside(params: Pick<DecompilerParams, "entryPoints" | "dataRanges" | "codeStarts">, start: number, end: number): { entryPoints: number[]; codeStarts: number[]; dataRanges: DecompilerParams["dataRanges"]; report: SeedReport } {
253
275
  const inside = (address: number) => address >= start && address <= end;
254
276
  const entryPoints = params.entryPoints.filter(inside);
255
277
  const codeStarts = (params.codeStarts ?? []).filter(inside);
256
278
  const code = [...entryPoints, ...codeStarts];
279
+ const dataRangesLeftOut: SeedReport["dataRangesLeftOut"] = [];
257
280
  const dataRanges = params.dataRanges
258
281
  .filter((range) => range.end >= start && range.start <= end)
259
282
  .map((range) => ({ start: Math.max(range.start, start), end: Math.min(range.end, end) }))
260
- .filter((range) => !code.some((entry) => entry >= range.start && entry <= range.end));
261
- return { entryPoints, codeStarts, dataRanges };
283
+ .filter((range) => {
284
+ const held = code.find((entry) => entry >= range.start && entry <= range.end);
285
+ if (held !== undefined) dataRangesLeftOut.push({ ...range, code: held });
286
+ return held === undefined;
287
+ });
288
+ const outside = [...new Set([...params.entryPoints, ...(params.codeStarts ?? [])])].filter((address) => !inside(address)).sort((a, b) => a - b);
289
+ return { entryPoints, codeStarts, dataRanges, report: { refused: outside.map((address) => ({ address, reason: "outside-program" })), dataRangesLeftOut } };
262
290
  }
package/src/script.ts CHANGED
@@ -14,6 +14,8 @@
14
14
  // command that worked. error is one sentence: what is wrong. hint tells what to
15
15
  // do. nextAction is a full command line that runs from any directory. With no
16
16
  // arguments or with --help, the command is "help" and the body is the usage.
17
+ // --fields <path>,<path> prints only those parts of the body, so that an agent
18
+ // reads a result without code of its own.
17
19
  // Nothing is thrown out of a script: every failure becomes an error envelope.
18
20
 
19
21
  import { resolve } from "node:path";
@@ -343,7 +345,8 @@ export function listed<T, U = T>(items: readonly T[], max: number, show: (item:
343
345
  /** The conventions in the help of every script. */
344
346
  export const CONVENTIONS = `Addresses are $ and 1 to 4 hex digits, for example '$c000' or '$fb', or a name: a symbol, else an analyzer name that only one analyzer gives. A range is <start>-<end>, for example '$c000-$cfff'. Quote them in a shell.
345
347
  Paths are relative to the project folder. Every script takes --project <folder>: the project folder, relative to the working directory. Without it, the script uses the nearest folder at or above the working directory that holds .c64-re-tools/. In a group folder, give --project with a project of the group. A path that a command only reads can go into another project of the group, for example ../v1/releases/game.prg.
346
- Each command prints one JSON envelope: {ok: true, command, body, hint?, nextAction?} with exit status 0, or {ok: false, command?, code, error, hint?, nextAction?} with exit status 2.`;
348
+ Each command prints one JSON envelope: {ok: true, command, body, hint?, nextAction?} with exit status 0, or {ok: false, command?, code, error, hint?, nextAction?} with exit status 2.
349
+ Every script takes --fields <path>,<path>: the body then has only those dotted paths, for example --fields revision,regions.listed.start. A path through a list gives that field of each item.`;
347
350
 
348
351
  function optionLabel(name: string, spec: OptionSpec): string {
349
352
  return spec.kind === "flag" ? `--${name}` : `--${name} ${spec.value ?? "<value>"}`;
@@ -400,7 +403,7 @@ function commandOptions(command: CommandSpec): Record<string, OptionSpec> {
400
403
  for (const [name, spec] of Object.entries(options)) {
401
404
  const shared = (OPTIONS as Record<string, OptionSpec>)[name];
402
405
  if (shared !== undefined && shared.kind !== spec.kind) throw fault(`--${name} of ${command.name} is a ${spec.kind}, but OPTIONS has it as a ${shared.kind}`);
403
- if (name === "help" || name === "project") throw fault(`--${name} of ${command.name}: the contract owns this option`);
406
+ if (name === "help" || name === "project" || name === "fields") throw fault(`--${name} of ${command.name}: the contract owns this option`);
404
407
  if (spec.kind === "path" && (name === "out" || name.startsWith("out-")) && spec.output === undefined) throw fault(`--${name} of ${command.name} has no output kind (file or folder)`);
405
408
  if (spec.output !== undefined && spec.kind !== "path") throw fault(`--${name} of ${command.name} has an output kind, but it is a ${spec.kind}, not a path`);
406
409
  }
@@ -408,12 +411,12 @@ function commandOptions(command: CommandSpec): Record<string, OptionSpec> {
408
411
  }
409
412
 
410
413
  /**
411
- * Takes --project <folder> and --project=<folder> out of a command line, up to "--".
412
- * Returns the folder and the other arguments. Refuses a --project without a folder or a second --project.
414
+ * Takes an option of the contract, --<name> <value> or --<name>=<value>, out of a command line, up to "--".
415
+ * Returns the value and the other arguments. Refuses the option without a value or a second one.
413
416
  */
414
- export function takeProject(argv: readonly string[]): { project?: string; argv: string[] } {
417
+ function takeContractOption(argv: readonly string[], name: string, needs: string): { value?: string; argv: string[] } {
415
418
  const rest: string[] = [];
416
- let project: string | undefined;
419
+ let found: string | undefined;
417
420
  for (let index = 0; index < argv.length; index++) {
418
421
  const argument = argv[index]!;
419
422
  if (argument === "--") {
@@ -421,21 +424,76 @@ export function takeProject(argv: readonly string[]): { project?: string; argv:
421
424
  break;
422
425
  }
423
426
  let value: string | undefined;
424
- if (argument === "--project") {
427
+ if (argument === `--${name}`) {
425
428
  value = argv[index + 1];
426
- if (value === undefined || value.startsWith("-")) throw new UsageError("--project needs a folder");
429
+ if (value === undefined || value.startsWith("-")) throw new UsageError(`--${name} needs ${needs}`);
427
430
  index++;
428
- } else if (argument.startsWith("--project=")) {
429
- value = argument.slice("--project=".length);
430
- if (value === "") throw new UsageError("--project needs a folder");
431
+ } else if (argument.startsWith(`--${name}=`)) {
432
+ value = argument.slice(`--${name}=`.length);
433
+ if (value === "") throw new UsageError(`--${name} needs ${needs}`);
431
434
  } else {
432
435
  rest.push(argument);
433
436
  continue;
434
437
  }
435
- if (project !== undefined) throw new UsageError("give --project only once");
436
- project = value;
438
+ if (found !== undefined) throw new UsageError(`give --${name} only once`);
439
+ found = value;
437
440
  }
438
- return project === undefined ? { argv: rest } : { project, argv: rest };
441
+ return found === undefined ? { argv: rest } : { value: found, argv: rest };
442
+ }
443
+
444
+ /**
445
+ * Takes --project <folder> and --project=<folder> out of a command line, up to "--".
446
+ * Returns the folder and the other arguments. Refuses a --project without a folder or a second --project.
447
+ */
448
+ export function takeProject(argv: readonly string[]): { project?: string; argv: string[] } {
449
+ const { value, argv: rest } = takeContractOption(argv, "project", "a folder");
450
+ return value === undefined ? { argv: rest } : { project: value, argv: rest };
451
+ }
452
+
453
+ /**
454
+ * Takes --fields <path>,<path> out of a command line, up to "--": the dotted
455
+ * paths of the body to print. Refuses --fields without paths, an empty path
456
+ * and a second --fields.
457
+ */
458
+ export function takeFields(argv: readonly string[]): { fields?: string[]; argv: string[] } {
459
+ const { value, argv: rest } = takeContractOption(argv, "fields", "one or more dotted paths of the body, for example --fields revision,regions.listed.start");
460
+ if (value === undefined) return { argv: rest };
461
+ const fields = value.split(",").map((path) => path.trim());
462
+ if (fields.some((path) => path === "" || path.split(".").some((part) => part === ""))) throw new UsageError(`--fields ${value} has an empty path: give the paths as a,b.c, without spaces or empty parts`);
463
+ return { fields, argv: rest };
464
+ }
465
+
466
+ /**
467
+ * The parts of a body at the dotted paths, with their nesting. A path through
468
+ * a list takes the rest of the path from each item, and two paths through one
469
+ * list give one list. `missing` holds the paths that no part of the body has.
470
+ */
471
+ export function pickFields(body: unknown, paths: readonly string[]): { body: unknown; missing: string[] } {
472
+ const found = new Set<string>();
473
+ interface Wanted {
474
+ path: string;
475
+ rest: readonly string[];
476
+ }
477
+ const pick = (node: unknown, wanted: readonly Wanted[]): unknown => {
478
+ if (Array.isArray(node)) return node.map((item) => pick(item, wanted));
479
+ if (typeof node !== "object" || node === null) return undefined;
480
+ const out: Record<string, unknown> = {};
481
+ const groups = new Map<string, Wanted[]>();
482
+ for (const item of wanted) groups.set(item.rest[0]!, [...(groups.get(item.rest[0]!) ?? []), item]);
483
+ for (const [key, group] of groups) {
484
+ if (!(key in node)) continue;
485
+ const value = (node as Record<string, unknown>)[key];
486
+ const ends = group.filter((item) => item.rest.length === 1);
487
+ for (const item of ends) found.add(item.path);
488
+ const deeper = group.filter((item) => item.rest.length > 1).map((item) => ({ path: item.path, rest: item.rest.slice(1) }));
489
+ const part = deeper.length > 0 ? pick(value, deeper) : undefined;
490
+ if (ends.length > 0) out[key] = value;
491
+ else if (part !== undefined) out[key] = part;
492
+ }
493
+ return out;
494
+ };
495
+ const picked = pick(body, paths.map((path) => ({ path, rest: path.split(".") })));
496
+ return { body: picked ?? {}, missing: paths.filter((path) => !found.has(path)) };
439
497
  }
440
498
 
441
499
  /** True when --help comes before "--". */
@@ -710,15 +768,27 @@ async function envelope(script: Envelope): Promise<void> {
710
768
  process.on("unhandledRejection", fatal);
711
769
 
712
770
  try {
713
- const { project, argv } = takeProject(process.argv.slice(2));
771
+ const { project, argv: withFields } = takeProject(process.argv.slice(2));
772
+ const { fields, argv } = takeFields(withFields);
714
773
  if (project !== undefined) useProject(project);
715
774
  const result = await script.perform(argv, (command) => {
716
775
  commandName = command;
717
776
  });
718
777
  const { body, hint, nextAction } = result instanceof Reply ? result : { body: result ?? {}, hint: undefined, nextAction: undefined };
719
778
  const cut = cutListHint(body);
720
- const shownHint = hint === undefined ? cut : cut === undefined || hint.includes("--max-listed") ? hint : `${sentence(hint)} ${cut}`;
721
- print({ ok: true, command: commandName ?? "help", body: body ?? {}, ...(shownHint === undefined ? {} : { hint: shownHint }), ...(nextAction === undefined ? {} : { nextAction }) }, 0);
779
+ let shownHint = hint === undefined ? cut : cut === undefined || hint.includes("--max-listed") ? hint : `${sentence(hint)} ${cut}`;
780
+ let shownBody: unknown = body ?? {};
781
+ // The fields are a view of the result: the command has done its work, so a path that the body lacks is no failure.
782
+ if (fields !== undefined) {
783
+ const picked = pickFields(shownBody, fields);
784
+ shownBody = picked.body;
785
+ if (picked.missing.length > 0) {
786
+ const top = typeof body === "object" && body !== null && !Array.isArray(body) ? Object.keys(body) : [];
787
+ const lacks = `The body has no ${wordList(picked.missing)}. ${top.length === 0 ? "It has no fields." : `Its fields are ${wordList(top)}.`}`;
788
+ shownHint = shownHint === undefined ? lacks : `${sentence(shownHint)} ${lacks}`;
789
+ }
790
+ }
791
+ print({ ok: true, command: commandName ?? "help", body: shownBody, ...(shownHint === undefined ? {} : { hint: shownHint }), ...(nextAction === undefined ? {} : { nextAction }) }, 0);
722
792
  trace().event("script.end", { ms: elapsedMs(started), status: 0, result: body });
723
793
  } catch (error) {
724
794
  fail(error);
@@ -1,63 +0,0 @@
1
- ---
2
- name: c64-export
3
- description: Exports a rebuilt C64 program as the start of a new program. The export sets each switch to one value in the code. Corrections, trainers and cheats are in, and copy protection and crack changes are out. It removes code and data that nothing uses. It writes a new project folder with the source, a baseline program, the tests and a small knowledge, and a zip file of the folder. Use it when the user asks to "export the project", "start a new game from this rebuild" or "make a clean package of the code". It does not change the rebuilt project or its knowledge.
4
- ---
5
-
6
- # C64 export
7
-
8
- ## Purpose
9
-
10
- Make the start of a new program from a rebuilt program. The new program is a new project. A person changes its source directly.
11
-
12
- Do not change the rebuilt project or its knowledge.
13
-
14
- ## Inputs
15
-
16
- - A rebuilt project: the generation of its source from the project knowledge gives PASS.
17
- - The folder of the new project. It must be new or empty, and no project can hold it. Use a folder beside the project, for example `../game-new`.
18
- - Optional: the coverage of the runs in the knowledge. Without coverage, nothing becomes free by itself.
19
-
20
- ## Workflow
21
-
22
- 1. Generate the source from the project knowledge into `src`. Continue only when the result is PASS. If it is not PASS, stop. Complete the rebuild of the program first.
23
- 2. Read the switches in the project knowledge. Tell the user the export value of each switch:
24
- - `fix`, `trainer` and `cheat`: 1. The code becomes a part of the new program.
25
- - `protection` and `crack`: 0.
26
- - `change`: its default.
27
-
28
- If the user wants another value for a switch, change its kind or its default in the project knowledge first.
29
- 3. Export the program of the project knowledge to the folder of the new project.
30
- 4. Read `unreachableExecuted` in the result of the export. Each range is code that a run executed and that the entry does not get to now. For each range, find the code that calls it in the project knowledge:
31
- - Only code that the export removed calls it, for example a copy check: drop the range.
32
- - Code that the knowledge does not show can call it, for example through a pointer: keep the range.
33
- - If you are not sure, ask the user.
34
- 5. To drop a range, remove the folder and the zip file of the export. Then export again, and drop each range.
35
- 6. Build the new project with the build commands in its `README.md`. Use the new folder as the project. The build that compares with the baseline must give PASS.
36
- 7. Run each test of the new project with the test commands in its `README.md`. Use the new folder as the project. Each test must give PASS.
37
-
38
- ### The answer
39
-
40
- Give the user a short answer at the end:
41
-
42
- 1. The folder and the zip file.
43
- 2. The value of each switch.
44
- 3. The free ranges, with their bytes.
45
- 4. Each test and its result, and the tests that the export left out, with the reason.
46
- 5. The next step: develop features and fixes in the source of the new project.
47
-
48
- ## Knowledge
49
-
50
- Read the switches, and the code at the addresses of `unreachableExecuted`.
51
-
52
- Do not write to the knowledge of the rebuilt project. The export writes the knowledge of the new project.
53
-
54
- ## Result
55
-
56
- A new project folder and a zip file of it. Its build is identical to its baseline, and each of its tests gives PASS.
57
-
58
- ## Failure and conflicts
59
-
60
- - The export gives FAIL: read `stage` and `reason`. Do as `reason` tells.
61
- - The export refuses the folder: give a new or empty folder outside every project. Remove a folder or a zip file of an earlier export only when this task made it.
62
- - A test of the new project gives FAIL: the export dropped a range that the program uses. Remove the folder and the zip file. Export again and keep the range. Then test again.
63
- - A task reports `installation-incomplete` or `machine-unavailable`: stop the whole task. Give the message to the user and wait for the user. Do not continue with other tasks.