@henols/c64-re-tools 2.8.0-rc.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.
- package/package.json +1 -1
- package/skills/c64-assembler/SKILL.md +2 -2
- package/skills/c64-assembler/scripts/assembler.ts +32 -10
- package/skills/c64-knowledge/scripts/lib/listing.ts +7 -8
- package/skills/c64-provenance/SKILL.md +6 -5
- package/skills/c64-provenance/scripts/provenance.ts +15 -15
- package/skills/c64-source/SKILL.md +6 -1
- package/skills/c64-source/scripts/lib/export.ts +18 -16
- package/skills/c64-source/scripts/lib/source.ts +3 -5
- package/skills/c64-static-analysis/SKILL.md +3 -2
- package/skills/c64-static-analysis/scripts/lib/idioms.ts +19 -12
- package/skills/c64-static-analysis/scripts/static-analysis.ts +14 -4
- package/src/c64.ts +16 -0
- package/src/knowledge/program.ts +34 -26
- package/src/knowledge/separate.ts +130 -63
- package/src/native/decompiler/analyze.ts +1 -1
- package/src/native/types.ts +4 -2
- package/src/script.ts +16 -9
package/package.json
CHANGED
|
@@ -134,7 +134,7 @@ Assembles the source and writes the program to `--out`, or to `build/<name>.prg`
|
|
|
134
134
|
- `identical`.
|
|
135
135
|
- `different`, with `differences` and `firstDifference`. `firstDifference` gives `address`, and the byte of the build (`built`) and of the reference (`reference`), each as `$` and two hex digits.
|
|
136
136
|
- `not covered`, with `uncovered`: the build does not hold all bytes of the segment.
|
|
137
|
-
- `loader`: only with `--switch`, the entry `main.asm` and a `loader.asm` in the source root. It is the loader program of these switch values, with `out`, `bytes` and `sha256`. `symbolsFile` is its symbols file. `packed` gives `packedBytes` and `unpackedBytes` of the packed form. `verified` is always `false`, because no check of the loader program runs.
|
|
137
|
+
- `loader`: only with `--switch`, the entry `main.asm` and a `loader.asm` in the source root. It is the loader program of these switch values, with `out`, `bytes` and `sha256`. `symbolsFile` is its symbols file. `packed` gives `packedBytes` and `unpackedBytes` of the packed form. `verified` is always `false`, because no check of the loader program runs. When the script cannot make the loader program, `loader` holds only `written`, which is `false`, and `reason`.
|
|
138
138
|
|
|
139
139
|
Do as the result tells:
|
|
140
140
|
|
|
@@ -142,13 +142,13 @@ Do as the result tells:
|
|
|
142
142
|
- `result` is `FAIL` and `assembled` is `false`: the source has errors, and the script wrote no program. `hint` tells you to correct the source. Correct the source at the file and the line of each diagnostic. Then run `build` again.
|
|
143
143
|
- `result` is `FAIL` and `assembled` is `true`: the program is not identical to the reference. The script wrote the program. Read the first difference of each segment in `compare.segments`. Without `--release`, read the section "Switches" first.
|
|
144
144
|
- `hint` tells that `symbols` is cut: give a larger `--max-listed`, or read the symbols file for the full list.
|
|
145
|
+
- `loader.written` is `false`: the script wrote the program of `main.asm`, but it cannot make the loader program of these switch values. Do as `loader.reason` tells.
|
|
145
146
|
- Error `not-found` names the entry: give the main source file relative to the source root.
|
|
146
147
|
- Error `not-found` names an include folder: give `--include` a folder with files, relative to the source root.
|
|
147
148
|
- Error `invalid-input` names an include folder: the folder is outside the project folder. Give `--include` a folder inside the project folder.
|
|
148
149
|
- Error `not-found` names a release: the project knowledge has no release with that label. Record the release in the project knowledge, or give the label of a recorded release.
|
|
149
150
|
- Error `not-found` tells that the knowledge has no program: put the program bytes into the project knowledge. Then use `--compare` again.
|
|
150
151
|
- Error `invalid-input` names a switch: give `--switch` a switch of `config.asm`, with the value 0 or 1.
|
|
151
|
-
- Error `invalid-input` tells you to set the switch values in `config.asm`: this build cannot make the loader program of these switch values. Set the values in `config.asm`. Then generate the source with the loader.
|
|
152
152
|
- Error `invalid-input`: an option or a path is wrong. Do as `hint` tells. The script refuses `--space` without `--compare` or `--release`.
|
|
153
153
|
|
|
154
154
|
The script does not keep the diagnostics or the program in the project knowledge.
|
|
@@ -6,12 +6,14 @@
|
|
|
6
6
|
// program with the same values: the build of loader.asm in the plain form,
|
|
7
7
|
// and in the packed form the pack of the build of main.asm with the build of
|
|
8
8
|
// loader.asm, the copier, as generate packs it. No check of that loader runs.
|
|
9
|
+
// When the knowledge or the builds do not permit the pack, the build writes
|
|
10
|
+
// the program of main.asm and no loader program, and tells why.
|
|
9
11
|
|
|
10
12
|
import { posix } from "node:path";
|
|
11
13
|
|
|
12
14
|
import { BUILD_DIRECTORY, type BuildKind, buildName, CONFIG_FILE, configValues, COPIER_LINE, symbolsPath, withConfigValues } from "#src/build-name.ts";
|
|
13
15
|
import { type AddressRange, formatC64Address } from "#src/c64.ts";
|
|
14
|
-
import { Refusal } from "#src/errors.ts";
|
|
16
|
+
import { isRefusal, Refusal } from "#src/errors.ts";
|
|
15
17
|
import { readSourceTree, writeReported } from "#src/host-client/transfer.ts";
|
|
16
18
|
import { openForRead } from "#src/knowledge/database.ts";
|
|
17
19
|
import { knowledgeNames } from "#src/knowledge/names.ts";
|
|
@@ -61,16 +63,27 @@ function switchDefaults(space: Space): Map<string, number> {
|
|
|
61
63
|
}
|
|
62
64
|
}
|
|
63
65
|
|
|
64
|
-
/** What the packed form needs from the knowledge: the loaded ranges. Refuses a start screen of a captured stage and a segment below $0400. */
|
|
65
|
-
function packedLoaded(leftovers: readonly AddressRange[]): AddressRange[] {
|
|
66
|
+
/** What the packed form needs from the knowledge of the space: the loaded ranges. Refuses a start screen of a captured stage and a segment below $0400. */
|
|
67
|
+
function packedLoaded(leftovers: readonly AddressRange[], space: Space): AddressRange[] {
|
|
66
68
|
const db = openForRead();
|
|
67
69
|
try {
|
|
68
|
-
return packedRanges(requireProgram(db).segments, leftovers, currentStartScreen(db)?.stage);
|
|
70
|
+
return packedRanges(requireProgram(db, space).segments, leftovers, currentStartScreen(db, space)?.stage);
|
|
69
71
|
} finally {
|
|
70
72
|
db?.close();
|
|
71
73
|
}
|
|
72
74
|
}
|
|
73
75
|
|
|
76
|
+
/** The message of a refusal of `work`, or undefined when it did not refuse: a refusal of the loader program does not stop the build of main.asm. */
|
|
77
|
+
function refusalOf(work: () => void): string | undefined {
|
|
78
|
+
try {
|
|
79
|
+
work();
|
|
80
|
+
return undefined;
|
|
81
|
+
} catch (error) {
|
|
82
|
+
if (isRefusal(error)) return error.message;
|
|
83
|
+
throw error;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
74
87
|
await runScript({
|
|
75
88
|
name: "assembler",
|
|
76
89
|
summary: "Assembles project source with ACME and writes the program into the project.",
|
|
@@ -146,13 +159,17 @@ await runScript({
|
|
|
146
159
|
// With --switch, main.asm of a generated source with a loader also gives the loader program of these values.
|
|
147
160
|
const loaderIndex = switches.size > 0 && entry === "main.asm" ? inSource(LOADER_FILE) : -1;
|
|
148
161
|
let loaded: AddressRange[] | undefined;
|
|
162
|
+
// Why the build writes no loader program.
|
|
163
|
+
let noLoader: string | undefined;
|
|
149
164
|
if (loaderIndex >= 0 && textOf(loaderIndex).split(/\r?\n/).includes(COPIER_LINE)) {
|
|
150
165
|
// The packed form: the loaded ranges are the segments of the program without the leftover files of the source.
|
|
151
166
|
const folder = posix.join(tree.sourceDir, LEFTOVER_FOLDER);
|
|
152
167
|
const leftovers = tree.files.flatMap((file, index) => (posix.dirname(file.path) === folder ? (leftoverRange(textOf(index)) ?? []) : []));
|
|
153
|
-
|
|
168
|
+
noLoader = refusalOf(() => {
|
|
169
|
+
loaded = packedLoaded(leftovers, call.space);
|
|
170
|
+
});
|
|
154
171
|
// The toolkit never installs a tool: without Exomizer the build refuses by name before ACME runs.
|
|
155
|
-
findTool(EXOMIZER);
|
|
172
|
+
if (noLoader === undefined) findTool(EXOMIZER);
|
|
156
173
|
}
|
|
157
174
|
|
|
158
175
|
const { result, attachments } = await assemble(params, contents, localToolContext());
|
|
@@ -165,7 +182,7 @@ await runScript({
|
|
|
165
182
|
|
|
166
183
|
// The loader is made before a file is written: a refusal writes nothing.
|
|
167
184
|
let loader: { program: Buffer; symbols: AssembledSymbol[]; packed?: PackedLoader } | undefined;
|
|
168
|
-
if (loaderIndex >= 0) {
|
|
185
|
+
if (loaderIndex >= 0 && noLoader === undefined) {
|
|
169
186
|
const copier = await assemble({ ...params, entrySource: LOADER_FILE }, contents, localToolContext());
|
|
170
187
|
if (!copier.result.assembled) {
|
|
171
188
|
const [first] = copier.result.diagnostics;
|
|
@@ -178,9 +195,12 @@ await runScript({
|
|
|
178
195
|
else {
|
|
179
196
|
const at = copier.result.symbols!.find((symbol) => symbol.name === COPIER_SOURCE);
|
|
180
197
|
if (at?.kind !== "address") throw new Refusal("invalid-input", `${LOADER_FILE} has no label ${COPIER_SOURCE} at its copier. Generate the source with the loader again.`);
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
198
|
+
const packedFrom = loaded;
|
|
199
|
+
noLoader = refusalOf(() => checkPackedBuilds(built, copierBuild, packedFrom));
|
|
200
|
+
if (noLoader === undefined) {
|
|
201
|
+
const packed = await packLoader(built, copierBuild, { loaded: packedFrom, copier: at.address }, localToolContext());
|
|
202
|
+
loader = { program: packed.program, symbols, packed };
|
|
203
|
+
}
|
|
184
204
|
}
|
|
185
205
|
}
|
|
186
206
|
|
|
@@ -196,6 +216,7 @@ await runScript({
|
|
|
196
216
|
...(different && label === undefined ? ["Without --release, a source with switches builds with the values of config.asm and --switch, and that program can differ from the base release. To check a release, give --release <label> with --compare."] : []),
|
|
197
217
|
...(symbols.rest === undefined ? [] : [`symbols is cut. To get all symbols, give ${symbols.rest}.`]),
|
|
198
218
|
...(loader === undefined ? [] : ["loader.out is the loader program of these switch values. No check of the loader program ran, so loader.verified is false."]),
|
|
219
|
+
...(noLoader === undefined ? [] : ["The build wrote the program of main.asm, but no loader program of these switch values: loader.reason tells why."]),
|
|
199
220
|
];
|
|
200
221
|
return reply({
|
|
201
222
|
result: different ? "FAIL" : "PASS",
|
|
@@ -209,6 +230,7 @@ await runScript({
|
|
|
209
230
|
...(all ? {} : { unusedConstants: result.symbols!.length - shown.length }),
|
|
210
231
|
diagnostics: result.diagnostics,
|
|
211
232
|
...(compared === undefined ? {} : { compare: compared }),
|
|
233
|
+
...(noLoader !== undefined ? { loader: { written: false, reason: noLoader } } : {}),
|
|
212
234
|
...(loader === undefined
|
|
213
235
|
? {}
|
|
214
236
|
: {
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// the bytes from coverage files, and the references in and out. Nothing here
|
|
4
4
|
// reads files: knowledge.ts gives the lookups.
|
|
5
5
|
|
|
6
|
-
import { COVERAGE, formatC64Address, formatC64Byte, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
|
|
6
|
+
import { COVERAGE, formatC64Address, formatC64Byte, POINTER_TABLE_TYPES, pointerEntryText, pointerTableEntries, type PointerTableType, splitEntryByte } from "#src/c64.ts";
|
|
7
7
|
import { instructionWith, MODE_LENGTH, OPCODES, type Mode } from "#src/opcodes.ts";
|
|
8
8
|
|
|
9
9
|
export interface ListingSource {
|
|
@@ -80,8 +80,9 @@ function operandOf(mode: Mode, address: number, low: number, high: number, sourc
|
|
|
80
80
|
}
|
|
81
81
|
|
|
82
82
|
/**
|
|
83
|
-
* The values of a table region
|
|
84
|
-
*
|
|
83
|
+
* The values of a table region in the form that c64-source writes, with the names of the
|
|
84
|
+
* knowledge and the platform: a word of a words or an address table as one !word value, and
|
|
85
|
+
* each byte of a split table as <target or >target. A byte of no entry has no value.
|
|
85
86
|
*/
|
|
86
87
|
function tableValues(region: Region, source: ListingSource): Map<number, { length: 1 | 2; text: string }> {
|
|
87
88
|
const values = new Map<number, { length: 1 | 2; text: string }>();
|
|
@@ -97,15 +98,13 @@ function tableValues(region: Region, source: ListingSource): Map<number, { lengt
|
|
|
97
98
|
const split = region.type === "addresses-split" || region.type === "rts-addresses-split";
|
|
98
99
|
for (const entry of pointerTableEntries({ start: region.start, end: region.end, type: region.type as PointerTableType }, byteAt)) {
|
|
99
100
|
if (!present(entry.low) || !present(entry.high)) continue;
|
|
100
|
-
const
|
|
101
|
-
const text = rts ? `${target}-1` : target;
|
|
101
|
+
const text = pointerEntryText(entry.target, rts, (address) => targetName(address, source));
|
|
102
102
|
if (!split) {
|
|
103
103
|
values.set(entry.low, { length: 2, text });
|
|
104
104
|
continue;
|
|
105
105
|
}
|
|
106
|
-
|
|
107
|
-
values.set(entry.
|
|
108
|
-
values.set(entry.high, { length: 1, text: `>${part}` });
|
|
106
|
+
values.set(entry.low, { length: 1, text: splitEntryByte(text, false) });
|
|
107
|
+
values.set(entry.high, { length: 1, text: splitEntryByte(text, true) });
|
|
109
108
|
}
|
|
110
109
|
return values;
|
|
111
110
|
}
|
|
@@ -169,16 +169,17 @@ Gives evidence from the program in the project knowledge, its stages and its cov
|
|
|
169
169
|
- `access` is `executed`, `read`, `written`, `read-written` or `untouched`. `untouched` bytes did not take part in the runs.
|
|
170
170
|
- A `read` byte right after executed code, or at a return address, can be a dummy read of the 6502. The program does not use it.
|
|
171
171
|
- `roots`: the addresses where the reachability starts, each with `address` and `from`. The roots are the entry, and the NMI, RESET and IRQ vectors at `$fffa`-`$ffff` when the program holds them. A text in place of the list tells why no code region is reachable.
|
|
172
|
-
- `codeRegions
|
|
172
|
+
- `codeRegions`: the code regions in the project knowledge, as a list. Each region has `reachable`, and `executed` with coverage. `unknown` is `true` for a region that is not dead code, as in `unknownCode` of `leftovers`.
|
|
173
173
|
- `codeRegions.unreachable`: the code regions that no chain of call and jump references reaches from a root.
|
|
174
|
+
- `unresolved`: only when a code region is unknown. These are the flows whose targets the project knowledge does not give, as in `leftovers`.
|
|
174
175
|
- `outside`: only with coverage. `read` and `executed` give the RAM outside the program that the program used but did not write. A loader or an earlier stage put these bytes there. `generated` gives the code that the program wrote outside its segments.
|
|
175
176
|
- `out`, `bytes` and `sha256`: the `--out` file. It has the fields of the body, with all items of each list.
|
|
176
177
|
|
|
177
|
-
`hint`: a list is cut. Run the command again with a larger `--max-listed
|
|
178
|
+
`hint`: a list is cut. Run the command again with a larger `--max-listed`, or read the `--out` file.
|
|
178
179
|
|
|
179
180
|
Traps:
|
|
180
181
|
|
|
181
|
-
- No code regions in the project knowledge: `codeRegions` is
|
|
182
|
+
- No code regions in the project knowledge: `codeRegions.count` is 0. Analyze the program for its code regions and its references first.
|
|
182
183
|
- Many `untouched` ranges: do more coverage runs for these parts. Put the coverage into the project knowledge before you decide.
|
|
183
184
|
- Error `not-found`: the project knowledge has no program. Put the program into the project knowledge.
|
|
184
185
|
|
|
@@ -196,13 +197,13 @@ Finds what the program in the project knowledge holds in addition to its working
|
|
|
196
197
|
| `residue` | Bytes that no run touched, and that are not text, BASIC, fill or a code region. `bytes` shows the first 16 bytes. |
|
|
197
198
|
| `copies` | At least 32 bytes that are the same as earlier bytes of the program. `copyOf` is the address of the earlier bytes. |
|
|
198
199
|
| `deadCode` | Code regions that no root reaches, as in `codeRegions.unreachable` of `separate`, and that no run executed. |
|
|
199
|
-
| `unknownCode` | Code regions that no root reaches and that no run executed, but that are not dead code. No coverage shows that they did not run, or a flow in `unresolved` can go to them. Each flow has `at` and `kind`. |
|
|
200
|
+
| `unknownCode` | Code regions that no root reaches and that no run executed, but that are not dead code. No coverage shows that they did not run, or a flow in `unresolved` can go to them. Each flow has `at` and `kind`: `indirect-jump`, `written-operand` or `pushed-return`. |
|
|
200
201
|
|
|
201
202
|
Each finding has `stages`: the unpack stages that wrote its bytes. A stage before the last stage is a depacker, an intro or a loader. Each finding also has `access`: the accesses of its bytes in the coverage.
|
|
202
203
|
|
|
203
204
|
`out`, `bytes` and `sha256` give the `--out` file. It has the fields of the body, with all findings and the full texts.
|
|
204
205
|
|
|
205
|
-
`hint`: a list is cut. Run the command again with a larger `--max-listed
|
|
206
|
+
`hint`: a list is cut. Run the command again with a larger `--max-listed`, or read the `--out` file. To get only the lists that you need, give `--fields`, for example `--fields text,deadCode`.
|
|
206
207
|
|
|
207
208
|
Text from another computer can show the tools of the developer:
|
|
208
209
|
|
|
@@ -282,8 +282,6 @@ function programEvidence() {
|
|
|
282
282
|
...(coverage === undefined ? {} : { coverage }),
|
|
283
283
|
codeRegions: regions,
|
|
284
284
|
references,
|
|
285
|
-
// A reference of the user or the LLM from a jump gives the targets of its flow.
|
|
286
|
-
resolvedSites: new Set(references.filter((reference) => (SEMANTIC_ORIGINS as readonly string[]).includes(reference.origin)).map((reference) => reference.from)),
|
|
287
285
|
});
|
|
288
286
|
return { program, stages, coverage, found };
|
|
289
287
|
}
|
|
@@ -302,14 +300,15 @@ function separateCommand(call: Call): unknown {
|
|
|
302
300
|
const loaded = { entry: program.entry, stages };
|
|
303
301
|
const show = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
|
|
304
302
|
const ranges = found.ranges.map((range) => ({ ...show(range), ...(range.stage === undefined ? {} : { stage: range.stage }), ...(range.access === undefined ? {} : { access: range.access }) }));
|
|
305
|
-
const codeRegions = found.codeRegions.map((region) => ({ ...show(region), type: region.type, ...(region.reachable === undefined ? {} : { reachable: region.reachable }), ...(region.executed === undefined ? {} : { executed: region.executed }) }));
|
|
303
|
+
const codeRegions = found.codeRegions.map((region) => ({ ...show(region), type: region.type, ...(region.reachable === undefined ? {} : { reachable: region.reachable }), ...(region.executed === undefined ? {} : { executed: region.executed }), ...(region.unknown === undefined ? {} : { unknown: true }) }));
|
|
304
|
+
const unresolved = found.unresolved.map((flow) => ({ at: formatC64Address(flow.at), kind: flow.kind }));
|
|
306
305
|
const outside = { read: found.outside.read.map(show), executed: found.outside.executed.map(show), generated: found.outside.generated.map(show) };
|
|
307
306
|
const roots = showRoots(found.roots);
|
|
308
307
|
const bytes = (filter: (range: (typeof found.ranges)[number]) => boolean) => found.ranges.filter(filter).reduce((sum, range) => sum + range.end - range.start + 1, 0);
|
|
309
308
|
const lastStage = loaded.stages === undefined ? undefined : loaded.stages.length - 1;
|
|
310
|
-
/** The body with at most `most` items in each list. */
|
|
311
|
-
const bodyOf = (most: number) => {
|
|
312
|
-
const list = <T>(items: T[]) => listed(items, most);
|
|
309
|
+
/** The body with at most `most` items in each list; `rest` tells where the other items are. */
|
|
310
|
+
const bodyOf = (most: number, rest: string) => {
|
|
311
|
+
const list = <T>(items: T[]) => listed(items, most, undefined, rest);
|
|
313
312
|
return {
|
|
314
313
|
...(loaded.entry === undefined ? {} : { entry: formatC64Address(loaded.entry) }),
|
|
315
314
|
...(lastStage === undefined
|
|
@@ -322,11 +321,12 @@ function separateCommand(call: Call): unknown {
|
|
|
322
321
|
ranges: list(ranges),
|
|
323
322
|
// The roots of the reachability: the entry and the hardware vectors in the image.
|
|
324
323
|
roots: roots.length === 0 ? NO_ROOTS : roots,
|
|
325
|
-
//
|
|
324
|
+
// Each code region with its evidence, and the ones that no root reaches.
|
|
326
325
|
codeRegions: {
|
|
327
|
-
|
|
326
|
+
...list(codeRegions),
|
|
328
327
|
...(roots.length === 0 ? {} : { unreachable: list(codeRegions.filter((region) => region.reachable === false)) }),
|
|
329
328
|
},
|
|
329
|
+
...(unresolved.length === 0 ? {} : { unresolved: list(unresolved) }),
|
|
330
330
|
...(coverage === undefined ? {} : { outside: { read: list(outside.read), executed: list(outside.executed), generated: list(outside.generated) } }),
|
|
331
331
|
};
|
|
332
332
|
};
|
|
@@ -348,12 +348,12 @@ function cutNote(body: unknown): string | undefined {
|
|
|
348
348
|
|
|
349
349
|
/**
|
|
350
350
|
* The body with at most `max` items in each list, and with --out the file of
|
|
351
|
-
* the same fields with all items. A cut list names a larger --max-listed
|
|
352
|
-
* envelope gives that note.
|
|
351
|
+
* the same fields with all items. A cut list names a larger --max-listed, and
|
|
352
|
+
* the file of --out or --out itself: the envelope gives that note.
|
|
353
353
|
*/
|
|
354
|
-
function withFile(bodyOf: (most: number) => Record<string, unknown>, max: number, out: string | undefined): Record<string, unknown> {
|
|
355
|
-
const written = out === undefined ? undefined : writeReported(out, `${JSON.stringify(bodyOf(Number.POSITIVE_INFINITY), null, 1)}\n`, { what: "--out" });
|
|
356
|
-
return { ...bodyOf(max), ...(written === undefined ? {} : written) };
|
|
354
|
+
function withFile(bodyOf: (most: number, rest: string) => Record<string, unknown>, max: number, out: string | undefined): Record<string, unknown> {
|
|
355
|
+
const written = out === undefined ? undefined : writeReported(out, `${JSON.stringify(bodyOf(Number.POSITIVE_INFINITY, ""), null, 1)}\n`, { what: "--out" });
|
|
356
|
+
return { ...bodyOf(max, out === undefined ? "a larger --max-listed, or --out <file>" : `a larger --max-listed, or read ${out}`), ...(written === undefined ? {} : written) };
|
|
357
357
|
}
|
|
358
358
|
|
|
359
359
|
/** The longest text that the result shows; --out has all of it. */
|
|
@@ -389,8 +389,8 @@ function leftoversCommand(call: Call): unknown {
|
|
|
389
389
|
unresolved: found.unresolved.map((flow) => ({ at: formatC64Address(flow.at), kind: flow.kind })),
|
|
390
390
|
};
|
|
391
391
|
/** The body with at most `most` items in each list; the file has the full texts. */
|
|
392
|
-
const bodyOf = (most: number) => {
|
|
393
|
-
const list = <T>(items: T[]) => listed(items, most);
|
|
392
|
+
const bodyOf = (most: number, rest: string) => {
|
|
393
|
+
const list = <T>(items: T[]) => listed(items, most, undefined, rest);
|
|
394
394
|
const shown = Number.isFinite(most) ? SHOWN_TEXT : Number.POSITIVE_INFINITY;
|
|
395
395
|
return {
|
|
396
396
|
...(program.entry === undefined ? {} : { entry: formatC64Address(program.entry) }),
|
|
@@ -111,7 +111,12 @@ To make the source better, change the project knowledge. Then generate again.
|
|
|
111
111
|
- `notExecuted`: with coverage, the count of instructions that no run executed, and their ranges. Each range has its source `file` and the `routine` before it.
|
|
112
112
|
- `unusedModules`: modules whose start is in no segment of the program. Often the program does not hold the code that the knowledge describes.
|
|
113
113
|
- `leftovers`: the bytes that nothing uses, with `bytes` and each range with its `file`. See "The leftovers". `noCoverage` tells that the knowledge has no coverage, so no range is a leftover. `changed` gives the ranges that are `added` to the leftovers and `removed` from them since the earlier run in `--out`.
|
|
114
|
-
- `unknownCode`: code that nothing reaches and that no run executed, which is not a leftover. A flow in `unresolved` can go to it
|
|
114
|
+
- `unknownCode`: code that nothing reaches and that no run executed, which is not a leftover. A flow in `unresolved` can go to it. Each flow has `at` and `kind`:
|
|
115
|
+
- `indirect-jump`: a JMP through a vector. The bytes of the program do not give the value of the vector.
|
|
116
|
+
- `written-operand`: a JMP or JSR whose address a run wrote.
|
|
117
|
+
- `pushed-return`: an RTS or RTI to an address that the code pushed.
|
|
118
|
+
|
|
119
|
+
The default build and the loader keep this code. Find the targets of each flow in the emulator. Record a jump reference from the flow to each target in the project knowledge. When the flow goes outside the program, for example a crash through the I/O area, record the reference to that address. Then generate again.
|
|
115
120
|
- `operandExpressions`: the count of instructions with an operand expression.
|
|
116
121
|
- `operandsAsNumbers`: each operand expression that the source has as a number, with its `address`, `expression` and `reason`.
|
|
117
122
|
- `macroUses`: the count of macro uses in the source.
|
|
@@ -8,15 +8,16 @@
|
|
|
8
8
|
// it tells what the program can reach. Pass B also starts at each block that
|
|
9
9
|
// a run executed, at --keep and at the patches that the export changed: it
|
|
10
10
|
// tells what stays. Without coverage nothing becomes free by itself. While the
|
|
11
|
-
//
|
|
12
|
-
// jump through a vector that
|
|
13
|
-
// wrote
|
|
11
|
+
// code that stays has a flow whose targets the knowledge does not give (an
|
|
12
|
+
// indirect jump through a vector that the code's own immediates do not set, a
|
|
13
|
+
// jump whose address a run wrote, or an RTS to an address that the code
|
|
14
|
+
// pushed), code that nothing reaches is unknown: it stays.
|
|
14
15
|
|
|
15
16
|
import { type AddressRange, COVERAGE, formatC64Address, pointerTableEntries, POINTER_TABLE_TYPES, type PointerTableType } from "#src/c64.ts";
|
|
16
17
|
import { symbolsPath } from "#src/build-name.ts";
|
|
17
18
|
import { Refusal } from "#src/errors.ts";
|
|
18
|
-
import { NO_FALL_THROUGH, type Root, separate, type UnresolvedFlow,
|
|
19
|
-
import {
|
|
19
|
+
import { computedFlows, NO_FALL_THROUGH, type Root, separate, type UnresolvedFlow, vectorHigh, WRITES_A, WRITES_X, WRITES_Y } from "#src/knowledge/separate.ts";
|
|
20
|
+
import type { RegionType } from "#src/knowledge/schema.ts";
|
|
20
21
|
import { OPCODES } from "#src/opcodes.ts";
|
|
21
22
|
|
|
22
23
|
/**
|
|
@@ -45,10 +46,6 @@ const RAM_ACCESS = 0xff & ~(COVERAGE.romRead | COVERAGE.romExecute);
|
|
|
45
46
|
/** The I/O area: two immediates stored there are chip values, such as a timer latch, not an address. */
|
|
46
47
|
const IO_AREA: AddressRange = { start: 0xd000, end: 0xdfff };
|
|
47
48
|
|
|
48
|
-
/** The registers that each instruction changes, other than by a load of an immediate or a transfer. */
|
|
49
|
-
const WRITES_A = new Set(["lda", "adc", "sbc", "and", "ora", "eor", "pla", "lax", "anc", "asr", "arr", "ane", "lxa", "las", "slo", "rla", "sre", "rra", "isc"]);
|
|
50
|
-
const WRITES_X = new Set(["ldx", "inx", "dex", "tsx", "lax", "sbx", "lxa", "las"]);
|
|
51
|
-
const WRITES_Y = new Set(["ldy", "iny", "dey"]);
|
|
52
49
|
/** The registers that a JSR gets an address in, low byte first, as the KERNAL and BASIC routines get a pointer. */
|
|
53
50
|
const CALL_PAIRS = [
|
|
54
51
|
["x", "y"],
|
|
@@ -65,7 +62,7 @@ export interface DropInput {
|
|
|
65
62
|
instructions: ReadonlyMap<number, number>;
|
|
66
63
|
coverage?: Uint8Array;
|
|
67
64
|
regions: ReadonlyArray<{ start: number; end: number; type: RegionType }>;
|
|
68
|
-
/** A reference of the user or the LLM resolves the flow of its instruction. */
|
|
65
|
+
/** A jump or call reference of the user or the LLM resolves the flow of its instruction. */
|
|
69
66
|
references: ReadonlyArray<{ from: number; to: number; kind: string; origin?: string }>;
|
|
70
67
|
/** The addresses that the operand expression of an instruction names, by the address of each instruction with an operand expression; none for a constant. */
|
|
71
68
|
operandTargets: ReadonlyMap<number, readonly number[]>;
|
|
@@ -206,10 +203,12 @@ function flowsOf(input: DropInput, inImage: (address: number) => boolean, indexe
|
|
|
206
203
|
case "rel":
|
|
207
204
|
flows.push({ from: at, to: (at + 2 + (operand < 0x80 ? operand : operand - 0x100)) & 0xffff });
|
|
208
205
|
break;
|
|
209
|
-
case "ind":
|
|
210
|
-
|
|
211
|
-
|
|
206
|
+
case "ind": {
|
|
207
|
+
const high = vectorHigh(operand);
|
|
208
|
+
reads.push({ from: at, start: operand, end: operand }, { from: at, start: high, end: high });
|
|
209
|
+
if (inImage(operand) && inImage(high)) flows.push({ from: at, to: memory[operand]! | (memory[high]! << 8) });
|
|
212
210
|
break;
|
|
211
|
+
}
|
|
213
212
|
case "abs":
|
|
214
213
|
case "zp":
|
|
215
214
|
if (opcode === 0x20 || opcode === 0x4c) {
|
|
@@ -327,9 +326,12 @@ export function planDrops(input: DropInput): DropPlan {
|
|
|
327
326
|
const passB = separate({ segments: [...input.segments], memory: input.memory, ...(input.entry === undefined ? {} : { entry: input.entry }), codeRegions: asRegions(candidates), references, roots: extra });
|
|
328
327
|
const automatic = input.coverage !== undefined && rooted;
|
|
329
328
|
const unreachableCode = candidates.filter((_, index) => automatic && passB.codeRegions[index]!.reachable === false);
|
|
330
|
-
// A flow that nobody resolved can go to any of that code: it stays, as unknown.
|
|
331
|
-
const
|
|
332
|
-
const unresolved =
|
|
329
|
+
// A flow that nobody resolved can go to any of that code: it stays, as unknown. Only a flow in code that stays can run.
|
|
330
|
+
const live = candidates.filter((block) => !unreachableCode.includes(block));
|
|
331
|
+
const unresolved =
|
|
332
|
+
unreachableCode.length === 0
|
|
333
|
+
? []
|
|
334
|
+
: computedFlows({ starts: [...instructions.keys()], memory: input.memory, inImage, coverage: input.coverage, references: input.references }).unresolved.filter((flow) => live.some((block) => flow.at >= block.start && flow.at <= block.end));
|
|
333
335
|
const droppedCode = unresolved.length === 0 ? unreachableCode : [];
|
|
334
336
|
const unknown = unresolved.length === 0 ? [] : merged(unreachableCode);
|
|
335
337
|
const stays = candidates.filter((block) => !droppedCode.includes(block));
|
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
// loads it.
|
|
16
16
|
|
|
17
17
|
import { CONFIG_FILE, configValues } from "#src/build-name.ts";
|
|
18
|
-
import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, POINTER_TABLE_TYPES, pointerTableEntries, type PointerTableType } from "#src/c64.ts";
|
|
18
|
+
import { type AddressRange, COVERAGE, formatC64Address, formatC64Byte, POINTER_TABLE_TYPES, pointerEntryText, pointerTableEntries, type PointerTableType, splitEntryByte } from "#src/c64.ts";
|
|
19
19
|
import { WireFailure } from "#src/host-client/tools.ts";
|
|
20
20
|
import { identifiers, operandText, replaceIdentifiers, type OperandExpression } from "#src/knowledge/expression.ts";
|
|
21
21
|
import { type CommentPlacement, isAnalyzer, isGeneratedFile, LEFTOVER_FOLDER, LEFTOVERS_SWITCH, SEGMENT_FOLDER, RELEASE_DEFINE, START_SCREEN_SWITCH, type Origin, type RegionType, type SwitchKind } from "#src/knowledge/schema.ts";
|
|
@@ -779,8 +779,6 @@ function cellsOf(item: DataItem, layout: Layout, breaks: Set<number>): Cell[] {
|
|
|
779
779
|
const { byteAt } = layout;
|
|
780
780
|
const cells: Cell[] = [];
|
|
781
781
|
const name = (address: number) => layout.names.get(address);
|
|
782
|
-
const expression = (target: number) => name(target) ?? formatC64Address(target);
|
|
783
|
-
const rtsExpression = (target: number) => (name(target) === undefined ? formatC64Address((target - 1) & 0xffff) : `${name(target)}-1`);
|
|
784
782
|
const byteCell = (address: number, text = formatC64Byte(byteAt(address))): Cell => ({ address, length: 1, directive: "!byte", text });
|
|
785
783
|
|
|
786
784
|
if (item.region !== undefined && POINTER_TYPES.includes(item.type)) {
|
|
@@ -798,14 +796,14 @@ function cellsOf(item: DataItem, layout: Layout, breaks: Set<number>): Cell[] {
|
|
|
798
796
|
cells.push(byteCell(address));
|
|
799
797
|
continue;
|
|
800
798
|
}
|
|
801
|
-
const text =
|
|
799
|
+
const text = pointerEntryText(part.pair.target, rts, name);
|
|
802
800
|
const whole = !split && !part.high && address + 1 <= item.end && !breaks.has(address + 1);
|
|
803
801
|
if (whole) {
|
|
804
802
|
cells.push({ address, length: 2, directive: "!word", text });
|
|
805
803
|
address++;
|
|
806
804
|
continue;
|
|
807
805
|
}
|
|
808
|
-
cells.push(byteCell(address,
|
|
806
|
+
cells.push(byteCell(address, splitEntryByte(text, part.high)));
|
|
809
807
|
}
|
|
810
808
|
return cells;
|
|
811
809
|
}
|
|
@@ -133,7 +133,7 @@ The `hint` gives each of these cases:
|
|
|
133
133
|
|
|
134
134
|
- `conflicts` is not empty. Find the correct answer in the emulator. Then correct the project knowledge.
|
|
135
135
|
- `coverageConflicts` is not empty. Classify each range as code in the project knowledge, or as `dual-use` when its bytes are also data. For many ranges, write all classifications in one batch of changes.
|
|
136
|
-
- `seeds.refused` is not
|
|
136
|
+
- `seeds.refused` has a seed with a reason that is not `outside-program`, or an `--entry` outside the program. See "Refused seeds and coverage gaps".
|
|
137
137
|
- `writtenNotExecuted` is not empty. A wrong entry point leads an analyzer from code into data. Examine the routine that holds the instructions in `from`. Correct the routine or its region in the project knowledge. Then run `analyze` again.
|
|
138
138
|
- `idioms.candidates.macros` has candidates, and the run had no `--apply-macros`. Examine the candidates. To write the correct candidates to the project knowledge, run the analysis again with `--apply-macros`. Give `--skip` with the start of each candidate that is not correct. Then generate the source again.
|
|
139
139
|
- The last analysis of the same program bytes used another analyzer version. Thus a change in `revision` can come from the new analyzer, and not from the program or the project knowledge.
|
|
@@ -151,7 +151,8 @@ Each item of `seeds.refused` and `coverageGaps` has a `reason`. `at` gives the i
|
|
|
151
151
|
| `inside-instruction` | Another instruction holds the address. Examine both in the listing. If the address is a wrong routine or region in the project knowledge, correct it. If both instructions run, classify the bytes as `dual-use`. |
|
|
152
152
|
| `into-instruction` | The instruction at the address runs into the instruction at `at`. Do as for `inside-instruction`. |
|
|
153
153
|
| `in-data`, `into-data` | A data range of the analysis holds the address or its instruction. `range` gives the data range of a gap. If the code runs, correct the data region in the project knowledge. |
|
|
154
|
-
| `outside-program
|
|
154
|
+
| `outside-program` | The address is not in the program. If the program copies the routine to this address when it runs, the routine is correct. If not, correct the entry point or the routine. |
|
|
155
|
+
| `past-end` | The instruction at the address runs past the end of the program. Correct the entry point or the routine. |
|
|
155
156
|
| `not-decodable` | No instruction decodes at the address. Correct the entry point or the routine. |
|
|
156
157
|
| `not-reached` | Only in `coverageGaps`: no flow and no seed reached the start. Give it with `--entry`, or record a routine there. |
|
|
157
158
|
|
|
@@ -105,13 +105,17 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
|
|
|
105
105
|
}
|
|
106
106
|
if (targets.length === 0) continue;
|
|
107
107
|
const n = targets.length;
|
|
108
|
-
const
|
|
109
|
-
?
|
|
108
|
+
const parts: Parameters<typeof addRegions>[1] = interleaved
|
|
109
|
+
? [{ start: low, end: low + 2 * n - 1, type: "rts-addresses" }]
|
|
110
110
|
: low + n === high
|
|
111
|
-
?
|
|
112
|
-
:
|
|
113
|
-
|
|
114
|
-
|
|
111
|
+
? [{ start: low, end: high + n - 1, type: "rts-addresses-split" }]
|
|
112
|
+
: [{ start: low, end: low + n - 1, type: "bytes" }, { start: high, end: high + n - 1, type: "bytes" }];
|
|
113
|
+
// Another dispatch through the same table: the table is recorded, and this RTS goes to its targets too.
|
|
114
|
+
const known = parts.every((part) => regions.some((region) => region.start === part.start && region.end === part.end && region.type === part.type));
|
|
115
|
+
if (!known) {
|
|
116
|
+
if (!addRegions("rts-table", parts)) continue;
|
|
117
|
+
counts.rtsTables++;
|
|
118
|
+
}
|
|
115
119
|
for (const target of targets) {
|
|
116
120
|
references.push({ from: at + 8, to: target, kind: "jump" });
|
|
117
121
|
entryPoints.add(target);
|
|
@@ -123,13 +127,16 @@ export function findIdioms(byteAt: ImageByte, range: { start: number; end: numbe
|
|
|
123
127
|
for (let at = range.start; at + 3 * MIN_JUMPS - 1 <= range.end; at++) {
|
|
124
128
|
let n = 0;
|
|
125
129
|
while (at + 3 * n + 2 <= range.end && byteAt(at + 3 * n) === 0x4c) n++;
|
|
126
|
-
if (n < MIN_JUMPS
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
130
|
+
if (n < MIN_JUMPS) continue;
|
|
131
|
+
if (addRegions("jump-table", [{ start: at, end: at + 3 * n - 1, type: "jumps" }])) {
|
|
132
|
+
counts.jumpTables++;
|
|
133
|
+
for (let index = 0; index < n; index++) {
|
|
134
|
+
entryPoints.add(at + 3 * index);
|
|
135
|
+
const target = word(byteAt, at + 3 * index + 1)!;
|
|
136
|
+
if (plausible(byteAt, target, range)) entryPoints.add(target);
|
|
137
|
+
}
|
|
132
138
|
}
|
|
139
|
+
// The JMPs inside the run are the same table: a run that is left out is left out once.
|
|
133
140
|
at += 3 * n - 1;
|
|
134
141
|
}
|
|
135
142
|
|
|
@@ -40,7 +40,7 @@ const ALL_REGIONS = "a larger --max-listed. The project knowledge has all of the
|
|
|
40
40
|
*/
|
|
41
41
|
function withHint(body: Record<string, unknown>, conflicts: number, coverageConflicts: number, macros: { candidates: number; applied: boolean; revision: string | null | undefined }, version: { now: string | undefined; last: string | undefined; revision: string | null }, retiredReferences: number, guards: { refused: number; writtenNotExecuted: number }) {
|
|
42
42
|
const hints: string[] = [];
|
|
43
|
-
if (guards.refused > 0) hints.push(`The analysis did not decode ${guards.refused} of
|
|
43
|
+
if (guards.refused > 0) hints.push(`The analysis did not decode ${guards.refused} seeds in the program or of --entry: seeds.refused gives each refused seed with its reason. A seed inside an instruction or in data is often a wrong routine or region in the project knowledge. Examine it in the listing, and correct the project knowledge.`);
|
|
44
44
|
if (guards.writtenNotExecuted > 0) hints.push("Each range in writtenNotExecuted is code of the analyzer on bytes that the runs wrote and never executed. Its from gives the instructions that reach it. Examine the routine that holds them: a wrong entry point leads the analyzer into data. Correct the project knowledge, and run the analysis again.");
|
|
45
45
|
if (version.revision !== null && version.now !== undefined && version.last !== undefined && version.now !== version.last) {
|
|
46
46
|
hints.push(`The last analysis of this program used ${version.last}. Thus a change in revision ${version.revision} can come from the new analyzer version, and not from the program or the project knowledge.`);
|
|
@@ -55,6 +55,15 @@ function withHint(body: Record<string, unknown>, conflicts: number, coverageConf
|
|
|
55
55
|
return reply(body, { hint: hints.join(" ") });
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
+
/**
|
|
59
|
+
* The refused seeds that can be a fault of the project knowledge: a routine
|
|
60
|
+
* outside the program can be code that the program copies there when it
|
|
61
|
+
* runs, so only an --entry outside the program counts.
|
|
62
|
+
*/
|
|
63
|
+
function toCorrect(refused: readonly RefusedSeed[], entries: readonly number[]): number {
|
|
64
|
+
return refused.filter((seed) => seed.reason !== "outside-program" || entries.includes(seed.address)).length;
|
|
65
|
+
}
|
|
66
|
+
|
|
58
67
|
/** A refused seed with $ addresses. */
|
|
59
68
|
function showRefused(seed: RefusedSeed) {
|
|
60
69
|
return { address: formatC64Address(seed.address), reason: seed.reason, ...(seed.at === undefined ? {} : { at: formatC64Address(seed.at) }) };
|
|
@@ -355,7 +364,7 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
355
364
|
labels: listed(result.labels, max, (label) => ({ address: formatC64Address(label.address), name: label.name }), ALL_NAMES),
|
|
356
365
|
...(written === undefined ? {} : { listing: written }),
|
|
357
366
|
};
|
|
358
|
-
return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired, { refused: report.refused
|
|
367
|
+
return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired, { refused: toCorrect(report.refused, entries), writtenNotExecuted: runOnWritten.length });
|
|
359
368
|
}
|
|
360
369
|
|
|
361
370
|
const { result, seeds: report } = await analyzeWithDecompiler({ imageKind, ...seeds, codeStarts, decompile }, bytes, localToolContext());
|
|
@@ -369,7 +378,8 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
369
378
|
const overlaps = listRegions(overlapDb, undefined, "dual-use", undefined, space);
|
|
370
379
|
overlapDb?.close();
|
|
371
380
|
const gaps = coverage === undefined ? [] : executedStarts(coverage, inProgram).filter((address) => address >= loaded.start && address <= loaded.end && !decoded.has(address) && !overlaps.some((region) => address >= region.start && address <= region.end));
|
|
372
|
-
|
|
381
|
+
// The data ranges that the decompiler used: not the ranges that hold a seed, and only the part in the program.
|
|
382
|
+
const explained = explainGaps(gaps, result.instructions, report.refused, report.dataRanges);
|
|
373
383
|
const runOnWritten = writtenNotExecutedOf("decompiler", space, coverage);
|
|
374
384
|
let instructions: Record<string, unknown> | undefined;
|
|
375
385
|
if (instructionsPath !== undefined) {
|
|
@@ -394,7 +404,7 @@ async function analyze(call: Call): Promise<unknown> {
|
|
|
394
404
|
? {}
|
|
395
405
|
: { notDecompiled: result.notDecompiled!.map((item) => ({ entry: formatC64Address(item.entry), reason: item.reason })) }),
|
|
396
406
|
};
|
|
397
|
-
return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired, { refused: report.refused
|
|
407
|
+
return withHint(body, imported.conflicts.length + found.idioms.conflicts.length, body.coverageConflicts?.length ?? 0, { candidates: found.idioms.candidates.macros.count, applied: applyMacros, revision: found.idioms.candidates.macros.revision }, { now: result.toolVersion, last: lastVersion, revision: imported.revision }, imported.changes.references.retired, { refused: toCorrect(report.refused, entries), writtenNotExecuted: runOnWritten.length });
|
|
398
408
|
}
|
|
399
409
|
|
|
400
410
|
/** A coverage gap with $ addresses. */
|
package/src/c64.ts
CHANGED
|
@@ -79,6 +79,22 @@ export function pointerTableEntries(table: { start: number; end: number; type: P
|
|
|
79
79
|
});
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
/**
|
|
83
|
+
* The ACME text of a pointer table entry: the name of its target, else its
|
|
84
|
+
* address. An entry of an RTS table holds the target - 1: name-1, or the
|
|
85
|
+
* address before the target.
|
|
86
|
+
*/
|
|
87
|
+
export function pointerEntryText(target: number, rts: boolean, nameOf: (address: number) => string | undefined): string {
|
|
88
|
+
const name = nameOf(target);
|
|
89
|
+
if (!rts) return name ?? formatC64Address(target);
|
|
90
|
+
return name === undefined ? formatC64Address((target - 1) & 0xffff) : `${name}-1`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** One byte of an entry of a split table: <text or >text, with the text in parentheses unless it is one name or number. */
|
|
94
|
+
export function splitEntryByte(text: string, high: boolean): string {
|
|
95
|
+
return `${high ? ">" : "<"}${/^[$A-Za-z_.0-9]+$/.test(text) ? text : `(${text})`}`;
|
|
96
|
+
}
|
|
97
|
+
|
|
82
98
|
/** How 6502 code refers to an address. A pointer is code that builds the address from immediates. */
|
|
83
99
|
export const REFERENCE_KINDS = ["call", "jump", "read", "write", "reference", "pointer"] as const;
|
|
84
100
|
export type ReferenceKind = (typeof REFERENCE_KINDS)[number];
|
package/src/knowledge/program.ts
CHANGED
|
@@ -145,14 +145,19 @@ function rangesText(ranges: readonly AddressRange[]): string {
|
|
|
145
145
|
return ranges.map((range) => (range.start === range.end ? at(range.start) : `${at(range.start)}-${at(range.end)}`)).join(" ");
|
|
146
146
|
}
|
|
147
147
|
|
|
148
|
-
/**
|
|
149
|
-
function
|
|
148
|
+
/** Calls `each` with the start and the end of each range of ranges as text. */
|
|
149
|
+
function forRanges(text: string, each: (start: number, end: number) => void): void {
|
|
150
150
|
for (const item of text.split(" ")) {
|
|
151
151
|
const [start, end] = item.split("-");
|
|
152
|
-
|
|
152
|
+
each(Number.parseInt(start!.slice(1), 16), Number.parseInt((end ?? start)!.slice(1), 16));
|
|
153
153
|
}
|
|
154
154
|
}
|
|
155
155
|
|
|
156
|
+
/** Sets 1 in `map` at each address of ranges as text. */
|
|
157
|
+
function fillRanges(map: Uint8Array, text: string): void {
|
|
158
|
+
forRanges(text, (start, end) => map.fill(1, start, end + 1));
|
|
159
|
+
}
|
|
160
|
+
|
|
156
161
|
/** The union of the coverage of one space: a map of each kind, 1 at each address that a map of the space has. */
|
|
157
162
|
function currentCoverage(db: DatabaseSync, space: Space): Map<CoverageKind, Uint8Array> {
|
|
158
163
|
const maps = new Map<CoverageKind, Uint8Array>(COVERAGE_KINDS.map((kind) => [kind, new Uint8Array(SIZE)]));
|
|
@@ -244,26 +249,20 @@ export function addCoverage(
|
|
|
244
249
|
/** What the runs did at an address: executed (x wins), read and written (rw), read, written, or nothing (-). */
|
|
245
250
|
export type Access = "x" | "rw" | "r" | "w" | "-";
|
|
246
251
|
|
|
247
|
-
/** The
|
|
248
|
-
const
|
|
249
|
-
const
|
|
250
|
-
const WRITES: readonly CoverageKind[] = ["w", "io-w"];
|
|
251
|
-
|
|
252
|
-
/** The access of a set of coverage kinds: an execute wins, then a read and a write together. */
|
|
253
|
-
function accessOf(kinds: ReadonlySet<CoverageKind>): Access {
|
|
254
|
-
const has = (list: readonly CoverageKind[]) => list.some((kind) => kinds.has(kind));
|
|
255
|
-
if (has(EXECUTES)) return "x";
|
|
256
|
-
if (has(READS)) return has(WRITES) ? "rw" : "r";
|
|
257
|
-
return has(WRITES) ? "w" : "-";
|
|
258
|
-
}
|
|
252
|
+
/** The bit of each coverage kind in a mask of kinds. */
|
|
253
|
+
const kindBit = (kind: CoverageKind) => 1 << COVERAGE_KINDS.indexOf(kind);
|
|
254
|
+
const maskOf = (kinds: readonly CoverageKind[]) => kinds.reduce((mask, kind) => mask | kindBit(kind), 0);
|
|
259
255
|
|
|
260
|
-
/**
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
256
|
+
/** The kinds of coverage ranges that count as an execute, a read and a write: RAM, ROM and the I/O area. */
|
|
257
|
+
const EXECUTES = maskOf(["x", "rom-x", "io-x"]);
|
|
258
|
+
const READS = maskOf(["r", "rom-r", "io-r"]);
|
|
259
|
+
const WRITES = maskOf(["w", "io-w"]);
|
|
260
|
+
|
|
261
|
+
/** The access of a mask of coverage kinds: an execute wins, then a read and a write together. */
|
|
262
|
+
function accessOf(kinds: number): Access {
|
|
263
|
+
if ((kinds & EXECUTES) !== 0) return "x";
|
|
264
|
+
if ((kinds & READS) !== 0) return (kinds & WRITES) !== 0 ? "rw" : "r";
|
|
265
|
+
return (kinds & WRITES) !== 0 ? "w" : "-";
|
|
267
266
|
}
|
|
268
267
|
|
|
269
268
|
/**
|
|
@@ -275,12 +274,21 @@ export function coverageAccess(db: DatabaseSync | undefined, space: Space = DEFA
|
|
|
275
274
|
if (db === undefined) return undefined;
|
|
276
275
|
const maps = [...new Set(coverageRuns(db).filter((run) => run.space === space).map((run) => run.name))];
|
|
277
276
|
if (maps.length === 0) return undefined;
|
|
278
|
-
|
|
277
|
+
// The kinds of each map at each address, as a mask: each lookup then reads one value for each map.
|
|
278
|
+
const masks = new Map(maps.map((map) => [map, new Uint16Array(SIZE)]));
|
|
279
|
+
for (const row of db.prepare("SELECT map, kind, ranges FROM current_coverage WHERE space = ?").all(space) as Array<{ map: string; kind: CoverageKind; ranges: string }>) {
|
|
280
|
+
const mask = masks.get(row.map);
|
|
281
|
+
if (mask === undefined) continue;
|
|
282
|
+
const bit = kindBit(row.kind);
|
|
283
|
+
forRanges(row.ranges, (start, end) => {
|
|
284
|
+
for (let address = start; address <= end; address++) mask[address]! |= bit;
|
|
285
|
+
});
|
|
286
|
+
}
|
|
279
287
|
return (address) => {
|
|
280
|
-
|
|
288
|
+
let all = 0;
|
|
281
289
|
const each = maps.map((map) => {
|
|
282
|
-
const kinds =
|
|
283
|
-
|
|
290
|
+
const kinds = masks.get(map)![address]!;
|
|
291
|
+
all |= kinds;
|
|
284
292
|
return { map, access: accessOf(kinds) };
|
|
285
293
|
});
|
|
286
294
|
return { maps: each, access: accessOf(all) };
|
|
@@ -9,6 +9,8 @@
|
|
|
9
9
|
// bytes the publisher shipped.
|
|
10
10
|
|
|
11
11
|
import { type AddressRange, COVERAGE, executedRamCode, instructionLength } from "../c64.ts";
|
|
12
|
+
import { OPCODES } from "../opcodes.ts";
|
|
13
|
+
import { isSemantic } from "./schema.ts";
|
|
12
14
|
|
|
13
15
|
export type Access = "executed" | "read" | "written" | "read-written" | "untouched";
|
|
14
16
|
|
|
@@ -22,9 +24,8 @@ export interface SeparationInput {
|
|
|
22
24
|
/** Joined coverage files. */
|
|
23
25
|
coverage?: Uint8Array;
|
|
24
26
|
codeRegions: Array<AddressRange & { type: string }>;
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
resolvedSites?: ReadonlySet<number>;
|
|
27
|
+
/** A jump or call reference of the user or the LLM also resolves the flow of its instruction. */
|
|
28
|
+
references: Array<{ from: number; to: number; kind: string; origin?: string | undefined }>;
|
|
28
29
|
/** More roots after the entry and the hardware vectors, for example code that a run executed. */
|
|
29
30
|
roots?: Root[];
|
|
30
31
|
}
|
|
@@ -47,12 +48,19 @@ export interface CodeRegionEvidence extends AddressRange {
|
|
|
47
48
|
|
|
48
49
|
/**
|
|
49
50
|
* A flow whose targets the knowledge does not give: a JMP (indirect) through
|
|
50
|
-
* a vector that
|
|
51
|
-
* address bytes a run wrote
|
|
51
|
+
* a vector that the code's own immediates do not set, a JMP or JSR whose
|
|
52
|
+
* address bytes a run wrote, or an RTS or RTI to an address that the code
|
|
53
|
+
* pushed.
|
|
52
54
|
*/
|
|
53
55
|
export interface UnresolvedFlow {
|
|
54
56
|
at: number;
|
|
55
|
-
kind: "indirect-jump" | "written-operand";
|
|
57
|
+
kind: "indirect-jump" | "written-operand" | "pushed-return";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The computed flows of the code: the targets that the bytes of the program give, and the flows that stay open. */
|
|
61
|
+
export interface ComputedFlows {
|
|
62
|
+
targets: Array<{ from: number; to: number }>;
|
|
63
|
+
unresolved: UnresolvedFlow[];
|
|
56
64
|
}
|
|
57
65
|
|
|
58
66
|
/** An address where the reachability starts, and why: the entry, a hardware vector in the image, or a root that the caller gives. */
|
|
@@ -73,7 +81,7 @@ export interface Separation {
|
|
|
73
81
|
* pieces of code with gaps of up to two operand bytes.
|
|
74
82
|
*/
|
|
75
83
|
outside: { read: AddressRange[]; executed: AddressRange[]; generated: AddressRange[] };
|
|
76
|
-
/** The unresolved flows of the code regions: while one exists, an unreached code region is unknown. */
|
|
84
|
+
/** The unresolved flows of the code regions that a root reaches or that a run executed: while one exists, an unreached code region is unknown. */
|
|
77
85
|
unresolved: UnresolvedFlow[];
|
|
78
86
|
}
|
|
79
87
|
|
|
@@ -122,64 +130,116 @@ export function regionStarts(regions: readonly AddressRange[], memory: Uint8Arra
|
|
|
122
130
|
return starts.sort((a, b) => a - b);
|
|
123
131
|
}
|
|
124
132
|
|
|
133
|
+
/** The address of the high byte of the vector of a JMP (N): the 6510 reads it from N + 1 in the same page, so JMP ($10ff) reads $1000. */
|
|
134
|
+
export const vectorHigh = (vector: number) => (vector & 0xff00) | ((vector + 1) & 0xff);
|
|
135
|
+
|
|
136
|
+
/** The registers that each instruction changes, other than by a load of an immediate or a transfer. */
|
|
137
|
+
export const WRITES_A = new Set(["lda", "adc", "sbc", "and", "ora", "eor", "pla", "lax", "anc", "asr", "arr", "ane", "lxa", "las", "slo", "rla", "sre", "rra", "isc"]);
|
|
138
|
+
export const WRITES_X = new Set(["ldx", "inx", "dex", "tsx", "lax", "sbx", "lxa", "las"]);
|
|
139
|
+
export const WRITES_Y = new Set(["ldy", "iny", "dey"]);
|
|
140
|
+
|
|
141
|
+
/** The instructions that change the byte at their operand with a value that no immediate gives. */
|
|
142
|
+
const CHANGES_MEMORY = new Set(["inc", "dec", "asl", "lsr", "rol", "ror", "sax", "slo", "rla", "sre", "rra", "dcp", "isc"]);
|
|
143
|
+
|
|
125
144
|
/**
|
|
126
|
-
* The
|
|
127
|
-
*
|
|
128
|
-
* A
|
|
129
|
-
*
|
|
145
|
+
* The computed flows of the instructions at `starts`: a JMP (N), a JMP or JSR
|
|
146
|
+
* whose address bytes a run wrote, and an RTS or RTI after pushes in its run
|
|
147
|
+
* of instructions. A jump or call reference of the user or the LLM from the
|
|
148
|
+
* instruction resolves its flow; for a pushed return, also one of the idiom
|
|
149
|
+
* pass, which reads the table of an RTS dispatch. Else the bytes resolve it:
|
|
150
|
+
* each byte holds its image byte and the immediates that the code stores
|
|
151
|
+
* there, and the flow goes to each word of these values. A byte that another
|
|
152
|
+
* write of the code changes, or that a run wrote while no store of the code
|
|
153
|
+
* does, or that is outside the image without such a store, leaves the flow
|
|
154
|
+
* unresolved.
|
|
130
155
|
*/
|
|
131
|
-
export function
|
|
132
|
-
const
|
|
156
|
+
export function computedFlows(input: { starts: readonly number[]; memory: Uint8Array; inImage: (address: number) => boolean; coverage?: Uint8Array | undefined; references: ReadonlyArray<{ from: number; kind: string; origin?: string | undefined }> }): ComputedFlows {
|
|
157
|
+
const { memory } = input;
|
|
158
|
+
const written = (address: number) => input.coverage !== undefined && (input.coverage[address & 0xffff]! & COVERAGE.ramWrite) !== 0;
|
|
159
|
+
const jumpsFrom = (origins: (origin: string | undefined) => boolean) => new Set(input.references.filter((reference) => (reference.kind === "jump" || reference.kind === "call") && origins(reference.origin)).map((reference) => reference.from));
|
|
160
|
+
const resolved = jumpsFrom(isSemantic);
|
|
161
|
+
const fromTable = jumpsFrom((origin) => isSemantic(origin) || origin === "heuristic");
|
|
162
|
+
const starts = [...input.starts].sort((a, b) => a - b);
|
|
163
|
+
|
|
164
|
+
// The immediates that the code stores at each address; null when another write changes it.
|
|
165
|
+
const stored = new Map<number, Set<number> | null>();
|
|
166
|
+
const store = (address: number, value: number | undefined) => {
|
|
167
|
+
const known = stored.get(address);
|
|
168
|
+
if (known === null) return;
|
|
169
|
+
stored.set(address, value === undefined ? null : (known ?? new Set<number>()).add(value));
|
|
170
|
+
};
|
|
171
|
+
// The return addresses that the code pushed before an RTS or RTI, as far as immediates give them.
|
|
172
|
+
const returns: Array<{ at: number; low: number | undefined; high: number | undefined; offset: 0 | 1 }> = [];
|
|
133
173
|
let registers: { a?: number | undefined; x?: number | undefined; y?: number | undefined } = {};
|
|
174
|
+
let pushes: Array<number | undefined> = [];
|
|
134
175
|
let previousEnd = -2;
|
|
135
|
-
for (const at of
|
|
136
|
-
if (at > previousEnd + 1)
|
|
176
|
+
for (const at of starts) {
|
|
177
|
+
if (at > previousEnd + 1) {
|
|
178
|
+
registers = {};
|
|
179
|
+
pushes = [];
|
|
180
|
+
}
|
|
137
181
|
const opcode = memory[at]!;
|
|
182
|
+
const { mnemonic, mode } = OPCODES[opcode]!;
|
|
138
183
|
const length = instructionLength(opcode);
|
|
139
184
|
previousEnd = at + length - 1;
|
|
140
|
-
const operand = length === 3 ? memory[at + 1]! | (memory[(at + 2) & 0xffff]! << 8) : memory[(at + 1) & 0xffff]!;
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
185
|
+
const operand = length === 3 ? memory[(at + 1) & 0xffff]! | (memory[(at + 2) & 0xffff]! << 8) : memory[(at + 1) & 0xffff]!;
|
|
186
|
+
if (mode === "zp" || mode === "abs") {
|
|
187
|
+
const register = mnemonic === "sta" ? "a" : mnemonic === "stx" ? "x" : mnemonic === "sty" ? "y" : undefined;
|
|
188
|
+
if (register !== undefined) store(operand, registers[register]);
|
|
189
|
+
else if (CHANGES_MEMORY.has(mnemonic)) store(operand, undefined);
|
|
190
|
+
}
|
|
191
|
+
if (mnemonic === "pha") pushes.push(registers.a);
|
|
192
|
+
if (mnemonic === "php") pushes.push(undefined);
|
|
193
|
+
if (mnemonic === "pla" || mnemonic === "plp") pushes.pop();
|
|
194
|
+
if (mnemonic === "txs") pushes = [];
|
|
195
|
+
if (mnemonic === "rts" && pushes.length >= 2) returns.push({ at, low: pushes.at(-1), high: pushes.at(-2), offset: 1 });
|
|
196
|
+
if (mnemonic === "rti" && pushes.length >= 3) returns.push({ at, low: pushes.at(-2), high: pushes.at(-3), offset: 0 });
|
|
197
|
+
const loaded = mode === "imm" ? operand : undefined;
|
|
198
|
+
if (WRITES_A.has(mnemonic) || (mode === "imp" && ["asl", "lsr", "rol", "ror"].includes(mnemonic))) registers.a = mnemonic === "lda" ? loaded : undefined;
|
|
199
|
+
if (WRITES_X.has(mnemonic)) registers.x = mnemonic === "ldx" ? loaded : undefined;
|
|
200
|
+
if (WRITES_Y.has(mnemonic)) registers.y = mnemonic === "ldy" ? loaded : undefined;
|
|
201
|
+
if (mnemonic === "tax") registers.x = registers.a;
|
|
202
|
+
if (mnemonic === "tay") registers.y = registers.a;
|
|
203
|
+
if (mnemonic === "txa") registers.a = registers.x;
|
|
204
|
+
if (mnemonic === "tya") registers.a = registers.y;
|
|
205
|
+
if (mnemonic === "jsr") registers = {};
|
|
206
|
+
if (NO_FALL_THROUGH.has(opcode)) {
|
|
207
|
+
registers = {};
|
|
208
|
+
pushes = [];
|
|
156
209
|
}
|
|
157
|
-
if (NO_FALL_THROUGH.has(opcode)) registers = {};
|
|
158
210
|
}
|
|
159
|
-
return new Set([...stored].filter((address) => stored.has((address + 1) & 0xffff)));
|
|
160
|
-
}
|
|
161
211
|
|
|
162
|
-
/**
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
const
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
if (
|
|
174
|
-
const
|
|
212
|
+
/** The values of a byte when the code reads it, or undefined when they are not known. */
|
|
213
|
+
const valuesAt = (address: number): number[] | undefined => {
|
|
214
|
+
const own = stored.get(address);
|
|
215
|
+
if (own === null || (own === undefined && (written(address) || !input.inImage(address)))) return undefined;
|
|
216
|
+
return [...new Set([...(own ?? []), ...(input.inImage(address) ? [memory[address]!] : [])])];
|
|
217
|
+
};
|
|
218
|
+
const targets: ComputedFlows["targets"] = [];
|
|
219
|
+
/** Adds a flow from `from` to each word of the bytes at `low` and `high`; false when a byte is not known. */
|
|
220
|
+
const wordsAt = (from: number, low: number, high: number) => {
|
|
221
|
+
const lows = valuesAt(low);
|
|
222
|
+
const highs = valuesAt(high);
|
|
223
|
+
if (lows === undefined || highs === undefined) return false;
|
|
224
|
+
for (const lowByte of lows) for (const highByte of highs) targets.push({ from, to: lowByte | (highByte << 8) });
|
|
225
|
+
return true;
|
|
226
|
+
};
|
|
227
|
+
const unresolved: UnresolvedFlow[] = [];
|
|
228
|
+
for (const at of starts) {
|
|
229
|
+
if (resolved.has(at)) continue;
|
|
230
|
+
const opcode = memory[at]!;
|
|
175
231
|
if (opcode === 0x6c) {
|
|
176
|
-
const vector =
|
|
177
|
-
if (
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
}
|
|
232
|
+
const vector = memory[(at + 1) & 0xffff]! | (memory[(at + 2) & 0xffff]! << 8);
|
|
233
|
+
if (!wordsAt(at, vector, vectorHigh(vector))) unresolved.push({ at, kind: "indirect-jump" });
|
|
234
|
+
} else if ((opcode === 0x4c || opcode === 0x20) && (written(at + 1) || written(at + 2))) {
|
|
235
|
+
if (!wordsAt(at, (at + 1) & 0xffff, (at + 2) & 0xffff)) unresolved.push({ at, kind: "written-operand" });
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
for (const pushed of returns) {
|
|
239
|
+
if (pushed.low !== undefined && pushed.high !== undefined) targets.push({ from: pushed.at, to: ((pushed.low | (pushed.high << 8)) + pushed.offset) & 0xffff });
|
|
240
|
+
else if (!fromTable.has(pushed.at)) unresolved.push({ at: pushed.at, kind: "pushed-return" });
|
|
181
241
|
}
|
|
182
|
-
return
|
|
242
|
+
return { targets, unresolved: unresolved.sort((a, b) => a.at - b.at) };
|
|
183
243
|
}
|
|
184
244
|
|
|
185
245
|
/** The most instructions outside the code regions that the run on from a region goes through, for example an instruction in a dual-use region. */
|
|
@@ -252,9 +312,11 @@ export function separate(input: SeparationInput): Separation {
|
|
|
252
312
|
const to = next === undefined ? undefined : runOn(next);
|
|
253
313
|
return to === undefined ? [] : [{ from: region.end, to }];
|
|
254
314
|
});
|
|
255
|
-
//
|
|
315
|
+
// A store anywhere in the code can change a vector, so the computed flows read every region.
|
|
316
|
+
const computed = computedFlows({ starts: regionStarts(regions, input.memory), memory: input.memory, inImage, coverage: input.coverage, references: input.references });
|
|
317
|
+
// From the regions that hold a root, through call and jump references, the targets of computed flows and the run on, to every region they reach.
|
|
256
318
|
const next = regions.map((): number[] => []);
|
|
257
|
-
for (const flow of [...input.references.filter((reference) => reference.kind === "call" || reference.kind === "jump"), ...runsOn]) {
|
|
319
|
+
for (const flow of [...input.references.filter((reference) => reference.kind === "call" || reference.kind === "jump"), ...computed.targets, ...runsOn]) {
|
|
258
320
|
const from = holding(flow.from);
|
|
259
321
|
const to = holding(flow.to);
|
|
260
322
|
if (from >= 0 && to >= 0) next[from]!.push(to);
|
|
@@ -275,15 +337,20 @@ export function separate(input: SeparationInput): Separation {
|
|
|
275
337
|
queue.push(to);
|
|
276
338
|
}
|
|
277
339
|
}
|
|
278
|
-
|
|
340
|
+
// Undefined without coverage.
|
|
341
|
+
const ran = regions.map((region): boolean | undefined => {
|
|
342
|
+
if (input.coverage === undefined) return undefined;
|
|
343
|
+
for (let address = region.start; address <= region.end; address++) if (executed[address] === 1) return true;
|
|
344
|
+
return false;
|
|
345
|
+
});
|
|
346
|
+
// Only a flow in code that a root reaches or that a run executed can run: a flow in dead code goes nowhere.
|
|
347
|
+
const unresolved = computed.unresolved.filter((flow) => {
|
|
348
|
+
const index = holding(flow.at);
|
|
349
|
+
return index >= 0 && (reached.has(index) || ran[index] === true);
|
|
350
|
+
});
|
|
279
351
|
const codeRegions = regions.map((region, index): CodeRegionEvidence => {
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
ran = false;
|
|
283
|
-
for (let address = region.start; address <= region.end && !ran; address++) ran = executed[address] === 1;
|
|
284
|
-
}
|
|
285
|
-
const unreached = roots.length > 0 && !reached.has(index) && ran !== true;
|
|
286
|
-
return { start: region.start, end: region.end, type: region.type, ...(roots.length === 0 ? {} : { reachable: reached.has(index) }), ...(ran === undefined ? {} : { executed: ran }), ...(unreached && (unresolved.length > 0 || input.coverage === undefined) ? { unknown: true as const } : {}) };
|
|
352
|
+
const unreached = roots.length > 0 && !reached.has(index) && ran[index] !== true;
|
|
353
|
+
return { start: region.start, end: region.end, type: region.type, ...(roots.length === 0 ? {} : { reachable: reached.has(index) }), ...(ran[index] === undefined ? {} : { executed: ran[index] }), ...(unreached && (unresolved.length > 0 || input.coverage === undefined) ? { unknown: true as const } : {}) };
|
|
287
354
|
});
|
|
288
355
|
|
|
289
356
|
const read: number[] = [];
|
|
@@ -45,7 +45,7 @@ export async function analyze(
|
|
|
45
45
|
context.log?.(`Decompiler result rejected: ${describeError(error)}`);
|
|
46
46
|
throw new WireFailure("operation-failed", `The decompiler returned an incomplete or inconsistent result. Nothing was imported. The check found: ${describeError(error)}.`);
|
|
47
47
|
}
|
|
48
|
-
return { result, seeds: { refused: [...report.refused, ...refusedSeeds].sort((a, b) => a.address - b.address), dataRangesLeftOut: report.dataRangesLeftOut } };
|
|
48
|
+
return { result, seeds: { refused: [...report.refused, ...refusedSeeds].sort((a, b) => a.address - b.address), dataRanges: report.dataRanges, dataRangesLeftOut: report.dataRangesLeftOut } };
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
/** The requested routines as C text, within the character bounds; the labels name routines and data. */
|
package/src/native/types.ts
CHANGED
|
@@ -259,9 +259,11 @@ export interface RefusedSeed {
|
|
|
259
259
|
at?: number;
|
|
260
260
|
}
|
|
261
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. */
|
|
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
263
|
export interface SeedReport {
|
|
264
264
|
refused: RefusedSeed[];
|
|
265
|
+
/** The data ranges that the analysis kept as data, cut to the program. */
|
|
266
|
+
dataRanges: Array<{ start: number; end: number }>;
|
|
265
267
|
dataRangesLeftOut: Array<{ start: number; end: number; code: number }>;
|
|
266
268
|
}
|
|
267
269
|
|
|
@@ -286,5 +288,5 @@ export function seedsInside(params: Pick<DecompilerParams, "entryPoints" | "data
|
|
|
286
288
|
return held === undefined;
|
|
287
289
|
});
|
|
288
290
|
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 } };
|
|
291
|
+
return { entryPoints, codeStarts, dataRanges, report: { refused: outside.map((address) => ({ address, reason: "outside-program" })), dataRanges, dataRangesLeftOut } };
|
|
290
292
|
}
|
package/src/script.ts
CHANGED
|
@@ -475,7 +475,11 @@ export function pickFields(body: unknown, paths: readonly string[]): { body: unk
|
|
|
475
475
|
rest: readonly string[];
|
|
476
476
|
}
|
|
477
477
|
const pick = (node: unknown, wanted: readonly Wanted[]): unknown => {
|
|
478
|
-
if (Array.isArray(node))
|
|
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
|
+
}
|
|
479
483
|
if (typeof node !== "object" || node === null) return undefined;
|
|
480
484
|
const out: Record<string, unknown> = {};
|
|
481
485
|
const groups = new Map<string, Wanted[]>();
|
|
@@ -683,19 +687,22 @@ export function parseCall(script: ScriptSpec, command: CommandSpec, argv: readon
|
|
|
683
687
|
// ---------------------------------------------------------------------------
|
|
684
688
|
// Running
|
|
685
689
|
|
|
686
|
-
/** A hint for a body with a cut list: the rest of the first list that
|
|
687
|
-
function cutListHint(body: unknown): string | undefined {
|
|
688
|
-
|
|
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 => {
|
|
689
695
|
if (typeof value !== "object" || value === null || depth > 2) return undefined;
|
|
690
696
|
const rest = (value as { rest?: unknown; count?: unknown }).rest;
|
|
691
|
-
if (typeof rest === "string" && typeof (value as { count?: unknown }).count === "number") return rest;
|
|
692
|
-
|
|
693
|
-
|
|
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);
|
|
694
701
|
if (found !== undefined) return found;
|
|
695
702
|
}
|
|
696
703
|
return undefined;
|
|
697
704
|
};
|
|
698
|
-
const rest = lists(body, 0);
|
|
705
|
+
const rest = lists(body, "", 0);
|
|
699
706
|
return rest === undefined ? undefined : `A list in the body is cut: count gives its full size. To get the rest, give ${rest}.`;
|
|
700
707
|
}
|
|
701
708
|
|
|
@@ -775,7 +782,7 @@ async function envelope(script: Envelope): Promise<void> {
|
|
|
775
782
|
commandName = command;
|
|
776
783
|
});
|
|
777
784
|
const { body, hint, nextAction } = result instanceof Reply ? result : { body: result ?? {}, hint: undefined, nextAction: undefined };
|
|
778
|
-
const cut = cutListHint(body);
|
|
785
|
+
const cut = cutListHint(body, fields);
|
|
779
786
|
let shownHint = hint === undefined ? cut : cut === undefined || hint.includes("--max-listed") ? hint : `${sentence(hint)} ${cut}`;
|
|
780
787
|
let shownBody: unknown = body ?? {};
|
|
781
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.
|