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

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 (70) 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 +137 -17
  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 +71 -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 +43 -64
  24. package/skills/c64-provenance/scripts/lib/leftovers.ts +8 -3
  25. package/skills/c64-provenance/scripts/provenance.ts +65 -56
  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 +48 -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 +28 -13
  34. package/skills/c64-source/scripts/lib/loader.ts +4 -82
  35. package/skills/c64-source/scripts/lib/source.ts +3 -5
  36. package/skills/c64-source/scripts/source.ts +48 -51
  37. package/skills/c64-static-analysis/SKILL.md +52 -52
  38. package/skills/c64-static-analysis/scripts/lib/coverage.ts +55 -2
  39. package/skills/c64-static-analysis/scripts/lib/idioms.ts +43 -17
  40. package/skills/c64-static-analysis/scripts/static-analysis.ts +79 -15
  41. package/skills/c64-testing/SKILL.md +72 -58
  42. package/skills/c64-testing/references/recording-format.md +5 -80
  43. package/skills/c64-testing/references/scenario-format.md +4 -12
  44. package/skills/c64-testing/scripts/lib/play.ts +16 -8
  45. package/skills/c64-testing/scripts/lib/recording.ts +74 -9
  46. package/skills/c64-testing/scripts/lib/replay.ts +4 -0
  47. package/skills/c64-testing/scripts/lib/runs.ts +112 -1
  48. package/skills/c64-testing/scripts/lib/scenario.ts +12 -6
  49. package/skills/c64-testing/scripts/lib/start-screen.ts +27 -0
  50. package/skills/c64-testing/scripts/testing.ts +34 -13
  51. package/skills/c64-unpacker/SKILL.md +10 -30
  52. package/skills/emulator/SKILL.md +7 -36
  53. package/src/build-name.ts +12 -1
  54. package/src/c64.ts +16 -0
  55. package/src/knowledge/history.ts +8 -0
  56. package/src/knowledge/program.ts +84 -4
  57. package/src/knowledge/read.ts +46 -2
  58. package/src/knowledge/recording-files.ts +32 -0
  59. package/src/knowledge/schema.ts +3 -1
  60. package/src/knowledge/separate.ts +165 -11
  61. package/src/knowledge/start-screen.ts +99 -17
  62. package/src/knowledge/text.ts +2 -1
  63. package/src/knowledge/write.ts +15 -8
  64. package/src/loader.ts +167 -0
  65. package/src/native/decompiler/analyze.ts +7 -6
  66. package/src/native/decompiler/walk.ts +32 -2
  67. package/src/native/dxa.ts +4 -4
  68. package/src/native/types.ts +34 -4
  69. package/src/script.ts +102 -25
  70. package/skills/c64-export/SKILL.md +0 -63
@@ -281,8 +281,8 @@ export class Change {
281
281
 
282
282
  insertRelease(row: Omit<ReleaseRow, "revision">): void {
283
283
  this.#db
284
- .prepare("INSERT INTO releases (id, space, label, base, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?)")
285
- .run(this.#rowId(), row.space, row.label, row.base ? 1 : 0, row.comment ?? null, row.origin, this.id());
284
+ .prepare("INSERT INTO releases (id, space, label, base, file, sha256, comment, origin, valid_from_revision) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)")
285
+ .run(this.#rowId(), row.space, row.label, row.base ? 1 : 0, row.file ?? null, row.sha256 ?? null, row.comment ?? null, row.origin, this.id());
286
286
  }
287
287
 
288
288
  /** Bytes of a release other than the base release, as a memory row of the program holds them. */
@@ -1032,9 +1032,10 @@ function unswitchStep(db: DatabaseSync, change: Change, _origin: Origin, request
1032
1032
  /**
1033
1033
  * A release. `rows` are the bytes of a release other than the base release,
1034
1034
  * as memoryRows gives them: the address of each row and its bytes as hex. The
1035
- * base release has no bytes of its own: its bytes are the program.
1035
+ * base release has no bytes of its own: its bytes are the program. `file` and
1036
+ * `sha256` are the project file that the bytes come from and its SHA-256.
1036
1037
  */
1037
- type ReleaseRequest = InSpace & { label: string; base?: boolean; comment?: string; rows?: ReadonlyMap<number, string> };
1038
+ type ReleaseRequest = InSpace & { label: string; base?: boolean; file?: string; sha256?: string; comment?: string; rows?: ReadonlyMap<number, string> };
1038
1039
 
1039
1040
  function checkRelease(request: ReleaseRequest): void {
1040
1041
  checkSpace(request);
@@ -1046,6 +1047,8 @@ function checkRelease(request: ReleaseRequest): void {
1046
1047
  throw new Refusal("invalid-input", `The bytes of a release at ${formatC64Address(address & 0xffff)} are not a memory row.`);
1047
1048
  }
1048
1049
  }
1050
+ if (request.file !== undefined && (typeof request.file !== "string" || request.file.length === 0)) throw new Refusal("invalid-input", "The file of a release is a project path.");
1051
+ if (request.sha256 !== undefined && (typeof request.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(request.sha256))) throw new Refusal("invalid-input", "The SHA-256 of a release file is 64 lowercase hex digits.");
1049
1052
  checkCommentText(request.comment, "A release comment");
1050
1053
  }
1051
1054
 
@@ -1054,12 +1057,16 @@ function releaseStep(db: DatabaseSync, change: Change, origin: Origin, request:
1054
1057
  const existing = releaseLabeled(db, request.label, space);
1055
1058
  const base = request.base ?? existing?.base ?? false;
1056
1059
  const comment = request.comment === undefined ? existing?.comment : request.comment.trim();
1060
+ // A release that is recorded again without its file keeps the file that it has.
1061
+ const file = request.file ?? existing?.file;
1062
+ const sha256 = request.file === undefined ? existing?.sha256 : request.sha256;
1063
+ const sameFile = existing?.file === file && existing?.sha256 === sha256;
1057
1064
  const held = db.prepare("SELECT id, address, bytes FROM current_release_memory WHERE space = ? AND label = ?").all(space, request.label) as Array<{ id: string; address: number; bytes: string }>;
1058
1065
  // A release without new bytes keeps its bytes. The base release has none: its bytes are the program.
1059
1066
  const wanted = base ? new Map<number, string>() : (request.rows ?? new Map(held.map((row) => [row.address, row.bytes])));
1060
1067
  if (!base && wanted.size === 0) throw new Refusal("invalid-input", `The release ${request.label} has no bytes. Give the file of the release.`);
1061
1068
  const sameBytes = held.length === wanted.size && held.every((row) => wanted.get(row.address) === row.bytes);
1062
- if (existing !== undefined && existing.base === base && existing.comment === comment && sameBytes && !confirms(existing.origin, origin)) return { current: existing };
1069
+ if (existing !== undefined && existing.base === base && existing.comment === comment && sameFile && sameBytes && !confirms(existing.origin, origin)) return { current: existing };
1063
1070
  const other = baseLabel(db, space);
1064
1071
  if (base && other !== undefined && other !== request.label) throw new Refusal("conflict", `The release ${other} is the base release. A space has one base release.`);
1065
1072
  // Every switch takes its base value from the base release: it cannot change under them.
@@ -1069,9 +1076,9 @@ function releaseStep(db: DatabaseSync, change: Change, origin: Origin, request:
1069
1076
  }
1070
1077
  const symbol = symbolNamed(db, `${RELEASE_DEFINE}${request.label}`, space);
1071
1078
  if (symbol !== undefined) throw new Refusal("conflict", `The build of the release defines ${RELEASE_DEFINE}${request.label}, and that is the name of the symbol at ${formatC64Address(symbol.address)}. Give the release another label.`);
1072
- if (existing === undefined || existing.base !== base || existing.comment !== comment || confirms(existing.origin, origin)) {
1079
+ if (existing === undefined || existing.base !== base || existing.comment !== comment || !sameFile || confirms(existing.origin, origin)) {
1073
1080
  if (existing !== undefined) change.close("releases", "space = ? AND label = ?", space, request.label);
1074
- change.insertRelease({ space, label: request.label, base, ...(comment === undefined ? {} : { comment }), origin: origin as ReleaseRow["origin"] });
1081
+ change.insertRelease({ space, label: request.label, base, ...(file === undefined ? {} : { file }), ...(sha256 === undefined ? {} : { sha256 }), ...(comment === undefined ? {} : { comment }), origin: origin as ReleaseRow["origin"] });
1075
1082
  }
1076
1083
  // Only the rows that changed: a changed byte changes one short line of the text.
1077
1084
  const kept = new Set<number>();
@@ -1667,7 +1674,7 @@ const KEYS = {
1667
1674
  releases: {
1668
1675
  columns: RELEASE_COLUMNS,
1669
1676
  map: toRelease,
1670
- key: (row: ReleaseRow) => `${row.space}|${row.label}|${row.base}|${row.comment ?? ""}|${row.origin}`,
1677
+ key: (row: ReleaseRow) => `${row.space}|${row.label}|${row.base}|${row.file ?? ""}|${row.sha256 ?? ""}|${row.comment ?? ""}|${row.origin}`,
1671
1678
  },
1672
1679
  start_screens: {
1673
1680
  columns: START_SCREEN_COLUMNS,
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), dataRanges: report.dataRanges, 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,49 @@ 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, the data ranges that it used, and the data ranges that it left out because code starts in them. */
263
+ export interface SeedReport {
264
+ refused: RefusedSeed[];
265
+ /** The data ranges that the analysis kept as data, cut to the program. */
266
+ dataRanges: Array<{ start: number; end: number }>;
267
+ dataRangesLeftOut: Array<{ start: number; end: number; code: number }>;
268
+ }
269
+
247
270
  /**
248
271
  * The seeds that an analysis of [start, end] can use: the entry points inside
249
272
  * 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.
273
+ * is left out, so that the entry point is disassembled. `report` gives what
274
+ * was left out.
251
275
  */
252
- export function seedsInside(params: Pick<DecompilerParams, "entryPoints" | "dataRanges" | "codeStarts">, start: number, end: number): { entryPoints: number[]; codeStarts: number[]; dataRanges: DecompilerParams["dataRanges"] } {
276
+ export function seedsInside(params: Pick<DecompilerParams, "entryPoints" | "dataRanges" | "codeStarts">, start: number, end: number): { entryPoints: number[]; codeStarts: number[]; dataRanges: DecompilerParams["dataRanges"]; report: SeedReport } {
253
277
  const inside = (address: number) => address >= start && address <= end;
254
278
  const entryPoints = params.entryPoints.filter(inside);
255
279
  const codeStarts = (params.codeStarts ?? []).filter(inside);
256
280
  const code = [...entryPoints, ...codeStarts];
281
+ const dataRangesLeftOut: SeedReport["dataRangesLeftOut"] = [];
257
282
  const dataRanges = params.dataRanges
258
283
  .filter((range) => range.end >= start && range.start <= end)
259
284
  .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 };
285
+ .filter((range) => {
286
+ const held = code.find((entry) => entry >= range.start && entry <= range.end);
287
+ if (held !== undefined) dataRangesLeftOut.push({ ...range, code: held });
288
+ return held === undefined;
289
+ });
290
+ const outside = [...new Set([...params.entryPoints, ...(params.codeStarts ?? [])])].filter((address) => !inside(address)).sort((a, b) => a - b);
291
+ return { entryPoints, codeStarts, dataRanges, report: { refused: outside.map((address) => ({ address, reason: "outside-program" })), dataRanges, dataRangesLeftOut } };
262
292
  }
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,80 @@ 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)) {
479
+ // An empty list has no item that lacks the field.
480
+ if (node.length === 0) for (const item of wanted) found.add(item.path);
481
+ return node.map((item) => pick(item, wanted));
482
+ }
483
+ if (typeof node !== "object" || node === null) return undefined;
484
+ const out: Record<string, unknown> = {};
485
+ const groups = new Map<string, Wanted[]>();
486
+ for (const item of wanted) groups.set(item.rest[0]!, [...(groups.get(item.rest[0]!) ?? []), item]);
487
+ for (const [key, group] of groups) {
488
+ if (!(key in node)) continue;
489
+ const value = (node as Record<string, unknown>)[key];
490
+ const ends = group.filter((item) => item.rest.length === 1);
491
+ for (const item of ends) found.add(item.path);
492
+ const deeper = group.filter((item) => item.rest.length > 1).map((item) => ({ path: item.path, rest: item.rest.slice(1) }));
493
+ const part = deeper.length > 0 ? pick(value, deeper) : undefined;
494
+ if (ends.length > 0) out[key] = value;
495
+ else if (part !== undefined) out[key] = part;
496
+ }
497
+ return out;
498
+ };
499
+ const picked = pick(body, paths.map((path) => ({ path, rest: path.split(".") })));
500
+ return { body: picked ?? {}, missing: paths.filter((path) => !found.has(path)) };
439
501
  }
440
502
 
441
503
  /** True when --help comes before "--". */
@@ -625,19 +687,22 @@ export function parseCall(script: ScriptSpec, command: CommandSpec, argv: readon
625
687
  // ---------------------------------------------------------------------------
626
688
  // Running
627
689
 
628
- /** A hint for a body with a cut list: the rest of the first list that has one. */
629
- function cutListHint(body: unknown): string | undefined {
630
- const lists = (value: unknown, depth: number): string | undefined => {
690
+ /** A hint for a body with a cut list: the rest of the first cut list that the fields show, or of the first one without --fields. */
691
+ function cutListHint(body: unknown, fields?: readonly string[]): string | undefined {
692
+ // A field shows a list when it is the list, a field in it, or a field that holds it.
693
+ const shown = (path: string) => fields === undefined || path === "" || fields.some((field) => field === path || field.startsWith(`${path}.`) || path.startsWith(`${field}.`));
694
+ const lists = (value: unknown, path: string, depth: number): string | undefined => {
631
695
  if (typeof value !== "object" || value === null || depth > 2) return undefined;
632
696
  const rest = (value as { rest?: unknown; count?: unknown }).rest;
633
- if (typeof rest === "string" && typeof (value as { count?: unknown }).count === "number") return rest;
634
- for (const item of Object.values(value)) {
635
- const found = lists(item, depth + 1);
697
+ if (typeof rest === "string" && typeof (value as { count?: unknown }).count === "number") return shown(path) ? rest : undefined;
698
+ // A path through a list names the field of each item, so an item adds no key to the path.
699
+ for (const [key, item] of Object.entries(value)) {
700
+ const found = lists(item, Array.isArray(value) ? path : path === "" ? key : `${path}.${key}`, depth + 1);
636
701
  if (found !== undefined) return found;
637
702
  }
638
703
  return undefined;
639
704
  };
640
- const rest = lists(body, 0);
705
+ const rest = lists(body, "", 0);
641
706
  return rest === undefined ? undefined : `A list in the body is cut: count gives its full size. To get the rest, give ${rest}.`;
642
707
  }
643
708
 
@@ -710,15 +775,27 @@ async function envelope(script: Envelope): Promise<void> {
710
775
  process.on("unhandledRejection", fatal);
711
776
 
712
777
  try {
713
- const { project, argv } = takeProject(process.argv.slice(2));
778
+ const { project, argv: withFields } = takeProject(process.argv.slice(2));
779
+ const { fields, argv } = takeFields(withFields);
714
780
  if (project !== undefined) useProject(project);
715
781
  const result = await script.perform(argv, (command) => {
716
782
  commandName = command;
717
783
  });
718
784
  const { body, hint, nextAction } = result instanceof Reply ? result : { body: result ?? {}, hint: undefined, nextAction: undefined };
719
- 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);
785
+ const cut = cutListHint(body, fields);
786
+ let shownHint = hint === undefined ? cut : cut === undefined || hint.includes("--max-listed") ? hint : `${sentence(hint)} ${cut}`;
787
+ let shownBody: unknown = body ?? {};
788
+ // The fields are a view of the result: the command has done its work, so a path that the body lacks is no failure.
789
+ if (fields !== undefined) {
790
+ const picked = pickFields(shownBody, fields);
791
+ shownBody = picked.body;
792
+ if (picked.missing.length > 0) {
793
+ const top = typeof body === "object" && body !== null && !Array.isArray(body) ? Object.keys(body) : [];
794
+ const lacks = `The body has no ${wordList(picked.missing)}. ${top.length === 0 ? "It has no fields." : `Its fields are ${wordList(top)}.`}`;
795
+ shownHint = shownHint === undefined ? lacks : `${sentence(shownHint)} ${lacks}`;
796
+ }
797
+ }
798
+ print({ ok: true, command: commandName ?? "help", body: shownBody, ...(shownHint === undefined ? {} : { hint: shownHint }), ...(nextAction === undefined ? {} : { nextAction }) }, 0);
722
799
  trace().event("script.end", { ms: elapsedMs(started), status: 0, result: body });
723
800
  } catch (error) {
724
801
  fail(error);