@henols/c64-re-tools 2.6.0-rc.10 → 2.6.0-rc.11

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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henols/c64-re-tools",
3
- "version": "2.6.0-rc.10",
3
+ "version": "2.6.0-rc.11",
4
4
  "description": "Agent-friendly Commodore 64 engineering toolkit for reverse engineering, debugging, development and testing.",
5
5
  "license": "MIT",
6
6
  "author": "Henrik Olsson",
@@ -6,6 +6,7 @@
6
6
  import { posix } from "node:path";
7
7
 
8
8
  import { formatC64Address, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
9
+ import { IO_RAM } from "#src/host-client/coverage.ts";
9
10
  import { bitmapFrame, charsetFrame, encodePng, PATTERN_PALETTES, scaleFrame, screenText, spriteSheet, type GraphicsMode } from "#src/graphics.ts";
10
11
  import { mermaidGraph, ownerOf, routineEdges, routineHeads, type GraphReference, type RoutineHead } from "#src/knowledge/graph.ts";
11
12
  import type { CommentRow, ModuleRow, ReferenceRow, RegionRow, SymbolRow } from "#src/knowledge/read.ts";
@@ -133,10 +134,17 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
133
134
  return entries.has(named.name) ? entryOfName(page, named.name, shown) : codeOfName(page, named.name).replace(`\`${named.name}\``, `\`${shown}\``);
134
135
  };
135
136
  const capped = (items: string[]) => (items.length <= MAX_LISTED ? items.join(", ") : `${items.slice(0, MAX_LISTED).join(", ")} and ${items.length - MAX_LISTED} more`);
137
+ /**
138
+ * The references that use the data at their target. An access to the I/O area inside the image is the
139
+ * register, as the source writes it: it uses no data of the RAM under it, unless the knowledge names that
140
+ * address. So the code of the SID and the CIAs is no reader of the sprites in RAM at $d400 or $dc00.
141
+ */
142
+ const named = new Set(input.symbols.map((symbol) => symbol.address));
143
+ const dataReferences = input.references.filter((reference) => !(reference.to >= IO_RAM.start && reference.to <= IO_RAM.end && input.image?.inImage(reference.to) === true && !named.has(reference.to)));
136
144
  /** The routines that read or write a range, each linked to its entry. */
137
145
  const ownersOf = (page: string, start: number, end: number, kind: string) =>
138
146
  capped(
139
- [...new Set(input.references.filter((reference) => reference.kind === kind && reference.to >= start && reference.to <= end).map((reference) => ownerAt(reference.from)?.name ?? hex(reference.from)))].map((name) =>
147
+ [...new Set(dataReferences.filter((reference) => reference.kind === kind && reference.to >= start && reference.to <= end).map((reference) => ownerAt(reference.from)?.name ?? hex(reference.from)))].map((name) =>
140
148
  entries.has(name) ? entryOfName(page, name, name) : `\`${name}\``,
141
149
  ),
142
150
  );
@@ -204,7 +212,7 @@ export function buildReference(input: ReferenceInput): { files: ReferenceFile[];
204
212
  .filter((comment) => comment.address === address)
205
213
  .sort((a, b) => (a.placement === b.placement ? 0 : a.placement === "line" ? -1 : 1))
206
214
  .map((comment) => comment.text.replace(/\s*\r?\n\s*/g, " ").trim());
207
- const incoming = (entry: Entry) => input.references.filter((reference) => reference.to >= entry.address && reference.to <= entry.spanEnd);
215
+ const incoming = (entry: Entry) => dataReferences.filter((reference) => reference.to >= entry.address && reference.to <= entry.spanEnd);
208
216
  const outgoing = (head: RoutineHead) => input.references.filter((reference) => ownerAt(reference.from)?.address === head.address);
209
217
  const entryText = (page: string, entry: Entry): string[] => {
210
218
  const lines = ["", `<a id="${entry.name}"></a>`, `### ${codeOfName(page, entry.name)} \`${entry.spanEnd > entry.address ? range(entry.address, entry.spanEnd) : hex(entry.address)}\``, "", `*${entry.kind}*`];
@@ -251,7 +251,7 @@ When a git merge left conflicts in the knowledge, each read body also has `confl
251
251
  - `body.lines` has `count` and `listed`. `listed` holds one line for each instruction of a code region, and one `!byte` line for other bytes.
252
252
  - Each line has `address`, `bytes`, `text`, `referencesIn` and `referencesOut`. It can also have `label`, `analyzerNames`, `lineComments` and `comment`. `lineComments` are the line comments before the line. `comment` is the side comment.
253
253
  - `text` is the instruction with the names of its target. An operand expression of the knowledge replaces the operand.
254
- - When the knowledge has coverage, `access` tells if a run executed (`x`), read (`r`) or wrote (`w`) the bytes of the line, or `-` for none.
254
+ - When the knowledge has coverage, `access` tells if a run executed (`x`), read (`r`) or wrote (`w`) the bytes of the line, or `-` for none. An `r` on code can come from a read of the 6502 that the program does not do, for example the byte after an RTS or the opcode at the PC when an interrupt starts.
255
255
  - With `--out`, the body has `lines` as a number, and `out`, `bytes` and `sha256` of the text file.
256
256
  - If the knowledge has no program in the space, the script refuses. Put the program in with `image` first.
257
257
  - Use `listing` in place of your own disassembler.
@@ -119,7 +119,7 @@ To make the source better, change the project knowledge. Then generate again.
119
119
  - `patchesNotWritten`: each patch that the source does not have, with its range, `switch` and `reason`.
120
120
  - `switches`, `default`, `releases`: the checks of the switches. See "Switches and releases".
121
121
  - `loader`: the check of the loader. See "The loader".
122
- - `staleLoader`: a run without `--loader` kept `loader.asm` and the loader program of another knowledge revision. `files` gives the files. `revision` gives the revision of `loader.asm`. Without `revision`, `loader.asm` does not give one. `noEntryState: true` tells that the knowledge has no entry state for a new loader. A change in a space that the loader does not hold does not make the loader stale. The loader holds space `c64` and the space of the stage of the start screen.
122
+ - `staleLoader`: a run without `--loader` kept `loader.asm` and the loader program of another knowledge revision, or of another version of the toolkit. `files` gives the files. `revision` gives the revision of `loader.asm`, and `version` its toolkit version. Without `revision`, `loader.asm` does not give one. `noEntryState: true` tells that the knowledge has no entry state for a new loader. A change in a space that the loader does not hold does not make the loader stale. The loader holds space `c64` and the space of the stage of the start screen.
123
123
 
124
124
  `result` is `FAIL` for each of these:
125
125
 
@@ -155,7 +155,7 @@ Do these actions for the findings:
155
155
  - Each module in the knowledge is one file. A module starts at its address. It stops at the next module or at the end of its segment. The file of a module can be in a folder, for example `music/driver.asm`. Without modules, each segment is one file, `segments/segment_xxxx.asm`.
156
156
  - `constants.asm` holds the names of addresses outside the program, for example `EXTCOL = $d020`. It also holds the register names in the program, for example `RASTER = $d012`. The names are in groups by memory area, in address order. Drive code and banks have one group only.
157
157
  - The side comment of a constant is the knowledge comment of the address. Without a comment, it is the platform meaning. When the knowledge name is not the platform name, the platform name comes first. For an I/O mirror without a meaning, the comment gives the register that the mirror repeats.
158
- - After the side comment, `Used:` counts how the source uses the name. The kinds are `read`, `written`, `modified`, `called`, `jumped to`, `jumped through`, `branched to`, `pointer`, `address`, `table` and `macro argument`. `address` is an immediate operand expression. `table` is an entry in a table of addresses.
158
+ - After the side comment, `Used:` counts how the source uses the name. The kinds are `read`, `written`, `modified`, `called`, `jumped to`, `jumped through`, `branched to`, `pointer`, `address`, `table` and `macro argument`. `address` is an immediate operand expression. `table` is an entry in a table of addresses. A macro line counts one `macro argument` for each name in its args. The other bytes that the macro reads or writes, for example the high byte of a 16-bit value, count for no name.
159
159
  - `config.asm` holds the value of each switch, for example `PROTECTION = 0`. The switches are in groups by kind. The side comment gives the releases that have the switch on, the ranges of its patches and the comment of the switch.
160
160
  - You can change a value in `config.asm` to 0 or 1. The next run keeps the values of the file. It adds a new switch with its default. It removes a switch that the knowledge does not have.
161
161
  - When the knowledge has a start screen, `config.asm` also has `START_SCREEN = 1`. Set it to 0 to start the program at once. Then assemble `loader.asm` again.
@@ -201,7 +201,7 @@ A leftover is a range of the program that nothing uses: unused code, old copies
201
201
  - `main.asm` builds a leftover file only when `LEFTOVERS` is 1. When it is 0, the build skips the bytes. Thus the addresses after the range do not change.
202
202
  - `config.asm` has `LEFTOVERS = 0`. Thus the default build is the clean program, without the leftovers.
203
203
  - Each release has `LEFTOVERS = 1`. Thus the build of a release gives the bytes of the release.
204
- - The loader program never has the leftovers. The loader does not copy them, and the memory there keeps the bytes that were in it before.
204
+ - The loader program never has the leftovers. The plain form does not copy them, and the memory there keeps the bytes that were in it before. The packed form unpacks the build of `main.asm` in one piece, so the leftovers are $00.
205
205
  - Without coverage, no range is a leftover. Put the coverage of the runs into the project knowledge. Then generate again.
206
206
  - When `leftovers.changed` has ranges, the default build and the loader program now leave out other bytes. A test that observes the `added` bytes on the loader program gets other values there. Fill the `added` ranges in the test of the leftovers. In a test that compares them, exclude them with the reason that they are leftovers.
207
207
  - A leftover can be wrong when the coverage does not show a use. For example, the VIC-II reads a range, or the program reads a range before it writes it. Then a test of the loader program fails. Record the region in the project knowledge, or put the coverage of more runs into it. Do not change the source.
@@ -561,16 +561,6 @@ export function layout(input: SourceInput): Layout {
561
561
  }
562
562
  }
563
563
  }
564
- // A macro line also uses the addresses that its instructions name besides its args, for example the high byte
565
- // CUTHI of +mov16 CUTLO: a name of the source counts that use too. The args count as macro argument above.
566
- for (const candidate of accepted) {
567
- const argAddresses = new Set(candidate.use.args.flatMap((arg) => identifiers(arg)).map((name) => byName.get(name)));
568
- for (const item of candidate.items) {
569
- if (!takesAddress(OPCODES[item.opcode]!.mode)) continue;
570
- const value = operandValue(item.address, item.opcode, input.byteAt)!;
571
- if (!argAddresses.has(value) && uses.has(value)) tally(value, useKind(item.opcode));
572
- }
573
- }
574
564
 
575
565
  const names = new Map<number, string>();
576
566
  const taken = new Set([...knowledgeNames, ...platform.values()]);
@@ -14,6 +14,7 @@ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync
14
14
  import { basename, dirname, join, relative, sep } from "node:path";
15
15
 
16
16
  import { isRefusal, Refusal } from "#src/errors.ts";
17
+ import { PACKAGE } from "#src/package.ts";
17
18
  import { BUILD_DIRECTORY, buildName, symbolsPath } from "#src/build-name.ts";
18
19
  import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
19
20
  import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
@@ -715,25 +716,28 @@ function loaderPrograms(): string[] {
715
716
  .filter((path) => existsSync(resolveProjectPath(path)));
716
717
  }
717
718
 
718
- /** The start of the line of loader.asm that gives the newest knowledge revision of the spaces that the loader holds. */
719
- const LOADER_REVISION = "Loader generated by c64-source from knowledge revision ";
719
+ /** The line of loader.asm that gives the toolkit version and the newest knowledge revision of the spaces that the loader holds. */
720
+ const loaderLine = (revision: string) => `Loader generated by c64-source ${PACKAGE.version} from knowledge revision ${revision}.`;
721
+ const LOADER_LINE = /^; Loader generated by c64-source (\S+) from knowledge revision (\S+)\.$/;
720
722
 
721
723
  /**
722
724
  * The loader files of an earlier run that a run without --loader keeps, when
723
- * the generated loader.asm is of another knowledge revision: the loader can
724
- * then copy other bytes than the source has. Undefined when there is no
725
- * generated loader.asm, or it is of this revision.
725
+ * the generated loader.asm is of another knowledge revision or of another
726
+ * version of the toolkit: the loader can then copy other bytes than the source
727
+ * has. Undefined when there is no generated loader.asm, or it is of this
728
+ * revision and version.
726
729
  */
727
- function staleLoader(out: string, revision: string): { files: string[]; revision?: string } | undefined {
730
+ function staleLoader(out: string, revision: string): { files: string[]; revision?: string; version?: string } | undefined {
728
731
  const path = resolveProjectPath(`${out}/loader.asm`);
729
732
  if (!existsSync(path)) return undefined;
730
733
  const text = readFileSync(path, "utf8");
731
734
  if (!text.startsWith(GENERATED_MARK)) return undefined;
732
- const line = text.split(/\r?\n/).find((row) => row.startsWith(`; ${LOADER_REVISION}`));
733
- const old = line?.slice(`; ${LOADER_REVISION}`.length).replace(/\.$/, "");
734
- if (old === revision) return undefined;
735
+ const found = text.split(/\r?\n/).map((row) => LOADER_LINE.exec(row)).find((match) => match !== null);
736
+ const version = found?.[1];
737
+ const old = found?.[2];
738
+ if (old === revision && version === PACKAGE.version) return undefined;
735
739
  const files = [...[...LOADER_FILES].filter((name) => existsSync(resolveProjectPath(`${out}/${name}`))).map((name) => `${out}/${name}`), ...loaderPrograms()];
736
- return { files, ...(old === undefined ? {} : { revision: old }) };
740
+ return { files, ...(old === undefined ? {} : { revision: old }), ...(version === undefined ? {} : { version }) };
737
741
  }
738
742
 
739
743
  /** The line of a leftover file that gives its range. */
@@ -1140,7 +1144,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
1140
1144
  const configNames = new Set([...knowledge.switches.map((row) => row.name), START_SCREEN_SWITCH, LEFTOVERS_SWITCH]);
1141
1145
  const loaderValues = new Map([...given].filter(([name]) => configNames.has(name)));
1142
1146
  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."];
1147
+ const loaderHeader = [loaderLine(knowledge.sourceRevision), "It copies the segments into place, sets the entry state and jumps to the entry."];
1144
1148
  const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused } = await buildSource(knowledge, {
1145
1149
  space,
1146
1150
  entries,
@@ -1783,7 +1787,7 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
1783
1787
  // The run with --loader writes the loader again, so it is the next action also for the other findings.
1784
1788
  const loaderAgain = staleLoader !== undefined && staleLoader.noEntryState !== true;
1785
1789
  if (staleLoader !== undefined) {
1786
- steps.push("The loader files in staleLoader.files are of another knowledge revision, and the run kept them.");
1790
+ steps.push("The loader files in staleLoader.files are of another knowledge revision or toolkit version, and the run kept them.");
1787
1791
  steps.push(loaderAgain ? "To write the loader of this revision, generate with --loader." : "The knowledge has no entry state, so --loader cannot write them again. Remove them when the build does not use them.");
1788
1792
  }
1789
1793
  return reply(body, { hint: steps.join(" "), ...(again || loaderAgain ? { nextAction: generateAgain(call, call.flag("loader") || loaderAgain) } : {}) });
@@ -96,7 +96,7 @@ Each flag applies only to the commands in the table. On another command, the scr
96
96
 
97
97
  ### `analyze`
98
98
 
99
- Runs DXA or Ghidra over the program in the project knowledge. The script records the findings in the project knowledge as one revision. Then it records the 6502 idioms as a second revision.
99
+ Runs DXA or Ghidra over the program in the project knowledge. The script records the findings in the project knowledge as one revision. Then it records the 6502 idioms as a second revision. When the findings do not change the knowledge, the script records no revision for them.
100
100
 
101
101
  The script records only structure: code and data regions, analyzer names, and the references from Ghidra. It does not record the listing or the decompiled code. Do not record the listing, the decompiled code or the function list as comments in the project knowledge.
102
102
 
@@ -142,7 +142,7 @@ The script does not record the candidates. Examine each candidate and decide.
142
142
  - `selfModified`: opcodes that the program wrote and then executed. The write and the execution must be in one coverage file. A coverage file does not record the order. Thus a candidate can also be code that ran first, and that the program then wrote over. To prevent this, save one coverage file for each part of the program, for example the intro, the game, or a loader that copies code. Clear the memory map between the parts.
143
143
  - `pointers`: code that makes an address from immediates. A `vector` or a `zero-page pointer` candidate stores a low byte (`low`) and a high byte (`high`) to a vector or to a zero-page pair. A `sprite pointer` candidate stores an immediate (`at`) to a sprite pointer of the screen at `$0400` in VIC bank 0. For each correct candidate, record a low and a high operand expression to its `target` in the project knowledge. Then a rebuild can move the target.
144
144
  - `pitfalls`: code that a C64 runs in a different way than it reads. For `raster-bit-8`, the instruction at `at` reads `$D011`, and the instruction at `store` writes the value back. The write can move the raster interrupt to line 256 or later. On PAL, past line 311, the interrupt never comes. Where the code must not keep bit 7, add a comment and test the program.
145
- - `macros`: runs of instructions that one macro line can replace, for example `+inc16 ptr`. Each candidate has `macro`, `start`, `end`, `args` and `text`. The macros are `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. An arg is a name of the user or the LLM, or a platform name of a ROM that the program uses. `known` counts the uses that the project knowledge has. `leftOut` counts the candidates with a label inside, or with a patch over them, or with another use of the project knowledge over them. With `--apply-macros`, `revision` gives the revision of the writes, and `writes` counts them. The writes hold the macros that the project knowledge does not have, with their bodies, and the uses. Do not write these macros yourself. `otherMacros` names each macro that the project knowledge has with another body. The writes do not have the uses of that macro. `skipped` counts the candidates that `--skip` left out. `notCandidates` lists each `--skip` address that starts no candidate.
145
+ - `macros`: runs of instructions that one macro line can replace, for example `+inc16 ptr`. Each candidate has `macro`, `start`, `end`, `args` and `text`. The macros are `inc16`, `dec16`, `add16_8`, `add16`, `sub16`, `set16`, `mov16` and `wait_line`. An arg is a name of the user or the LLM, or a platform name of a ROM that the program uses. A value of `set16` below $0100 is a number. `known` counts the uses that the project knowledge has. `leftOut` counts the candidates with a label inside, or with a patch over them, or with another use of the project knowledge over them. With `--apply-macros`, `revision` gives the revision of the writes, and `writes` counts them. The writes hold the macros that the project knowledge does not have, with their bodies, and the uses. Do not write these macros yourself. `otherMacros` names each macro that the project knowledge has with another body. The writes do not have the uses of that macro. `skipped` counts the candidates that `--skip` left out. `notCandidates` lists each `--skip` address that starts no candidate.
146
146
 
147
147
  #### Which facts the analysis replaces
148
148
 
@@ -152,7 +152,9 @@ const MATCHERS: Record<string, { count: number; match: (run: Instruction[], name
152
152
  const dst = memory(storeLow, "sta");
153
153
  if (low === undefined || high === undefined || !same(dst, memory(storeHigh, "sta"), 1)) return undefined;
154
154
  const value = low | (high << 8);
155
- return [addressArg(dst!, name), name(value) ?? formatC64Address(value)];
155
+ // A value of $0100 or more can be the address of a routine or a table, for example an IRQ handler: it gets its name.
156
+ // A smaller value is a number: the name of a zero-page address with that value is not what the code means.
157
+ return [addressArg(dst!, name), (value >= 0x100 ? name(value) : undefined) ?? formatC64Address(value)];
156
158
  },
157
159
  },
158
160
  mov16: {
@@ -14,6 +14,7 @@ import { C64RunSession, PAL_FRAME_CYCLES } from "#src/native/c64run.ts";
14
14
  import { localToolContext } from "#src/native/local.ts";
15
15
  import { Workspace } from "#src/native/staging.ts";
16
16
  import { knowledgeNames } from "#src/knowledge/names.ts";
17
+ import { LOCAL_DIRECTORY, PROJECT_DIRECTORY, projectRelative } from "#src/project.ts";
17
18
  import { OPTIONS, reply, runScript, UsageError, type Call, type CommandSpec, type Reply } from "#src/script.ts";
18
19
  import { diffFiles } from "./lib/diff-files.ts";
19
20
  import { CANCELLED, play } from "./lib/play.ts";
@@ -104,9 +105,13 @@ async function recordCommand(call: Call): Promise<Reply> {
104
105
  writeReported(`${out}/${RECORDING_FILES.reads}`, outcome.reads, { what: "--out" }),
105
106
  writeReported(`${out}/${RECORDING_FILES.coverage}`, outcome.coverage, { what: "--out" }),
106
107
  ];
108
+ // A recording in the local folder is a work file: git ignores it, so it is no test.
109
+ const keep = projectRelative(out).startsWith(`${PROJECT_DIRECTORY}/${LOCAL_DIRECTORY}/`)
110
+ ? `Git ignores ${out}. To keep the recording as a test, record again with --out tests/recordings/<name>.`
111
+ : `Commit ${out} with the scenarios.`;
107
112
  return reply(
108
113
  { result: "PASS", recorded: true, out, ...summary, files },
109
- { hint: `Commit ${out} with the scenarios. Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage. ${summary.coverageFrom === null ? "The coverage did not start: the map is empty." : "The map has no marks for the code that ran before coverageFrom."} To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
114
+ { hint: `${keep} Add ${out}/${RECORDING_FILES.coverage} to the project knowledge as coverage. ${summary.coverageFrom === null ? "The coverage did not start: the map is empty." : "The map has no marks for the code that ran before coverageFrom."} To make sure that the recording replays, run nextAction.`, nextAction: call.next("replay", out) },
110
115
  );
111
116
  } finally {
112
117
  await core.close();