@henols/c64-re-tools 2.7.1 → 2.8.0-rc.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/skills/c64-assembler/SKILL.md +23 -38
- package/skills/c64-assembler/scripts/assembler.ts +137 -17
- package/skills/c64-basic/SKILL.md +11 -31
- package/skills/c64-basic/scripts/basic.ts +4 -1
- package/skills/c64-development/SKILL.md +2 -2
- package/skills/c64-disk/SKILL.md +11 -32
- package/skills/c64-docs/SKILL.md +27 -45
- package/skills/c64-docs/references/page-types.md +20 -18
- package/skills/c64-docs/references/style.md +10 -4
- package/skills/c64-docs/scripts/docs.ts +13 -2
- package/skills/c64-docs/scripts/lib/reference.ts +47 -5
- package/skills/c64-knowledge/SKILL.md +138 -267
- package/skills/c64-knowledge/references/batches.md +48 -0
- package/skills/c64-knowledge/references/coverage.md +29 -0
- package/skills/c64-knowledge/references/source-knowledge.md +72 -0
- package/skills/c64-knowledge/references/start-screen.md +44 -0
- package/skills/c64-knowledge/scripts/knowledge.ts +266 -61
- package/skills/c64-knowledge/scripts/lib/check.ts +133 -0
- package/skills/c64-knowledge/scripts/lib/listing.ts +71 -8
- package/skills/c64-memory-map/SKILL.md +11 -32
- package/skills/c64-packer/SKILL.md +11 -31
- package/skills/c64-provenance/SKILL.md +43 -64
- package/skills/c64-provenance/scripts/lib/leftovers.ts +8 -3
- package/skills/c64-provenance/scripts/provenance.ts +65 -56
- package/skills/c64-reverse-engineering/SKILL.md +20 -47
- package/skills/c64-reverse-engineering/references/comment-check.md +42 -0
- package/skills/c64-reverse-engineering/references/versions.md +47 -0
- package/skills/c64-source/SKILL.md +48 -237
- package/skills/c64-source/references/export.md +50 -0
- package/skills/c64-source/references/loader.md +78 -0
- package/skills/c64-source/references/source-format.md +46 -0
- package/skills/c64-source/scripts/lib/export.ts +28 -13
- package/skills/c64-source/scripts/lib/loader.ts +4 -82
- package/skills/c64-source/scripts/lib/source.ts +3 -5
- package/skills/c64-source/scripts/source.ts +48 -51
- package/skills/c64-static-analysis/SKILL.md +52 -52
- package/skills/c64-static-analysis/scripts/lib/coverage.ts +55 -2
- package/skills/c64-static-analysis/scripts/lib/idioms.ts +43 -17
- package/skills/c64-static-analysis/scripts/static-analysis.ts +79 -15
- package/skills/c64-testing/SKILL.md +72 -58
- package/skills/c64-testing/references/recording-format.md +5 -80
- package/skills/c64-testing/references/scenario-format.md +4 -12
- package/skills/c64-testing/scripts/lib/play.ts +16 -8
- package/skills/c64-testing/scripts/lib/recording.ts +74 -9
- package/skills/c64-testing/scripts/lib/replay.ts +4 -0
- package/skills/c64-testing/scripts/lib/runs.ts +112 -1
- package/skills/c64-testing/scripts/lib/scenario.ts +12 -6
- package/skills/c64-testing/scripts/lib/start-screen.ts +27 -0
- package/skills/c64-testing/scripts/testing.ts +34 -13
- package/skills/c64-unpacker/SKILL.md +10 -30
- package/skills/emulator/SKILL.md +7 -36
- package/src/build-name.ts +12 -1
- package/src/c64.ts +16 -0
- package/src/knowledge/history.ts +8 -0
- package/src/knowledge/program.ts +84 -4
- package/src/knowledge/read.ts +46 -2
- package/src/knowledge/recording-files.ts +32 -0
- package/src/knowledge/schema.ts +3 -1
- package/src/knowledge/separate.ts +165 -11
- package/src/knowledge/start-screen.ts +99 -17
- package/src/knowledge/text.ts +2 -1
- package/src/knowledge/write.ts +15 -8
- package/src/loader.ts +167 -0
- package/src/native/decompiler/analyze.ts +7 -6
- package/src/native/decompiler/walk.ts +32 -2
- package/src/native/dxa.ts +4 -4
- package/src/native/types.ts +34 -4
- package/src/script.ts +102 -25
- package/skills/c64-export/SKILL.md +0 -63
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Source format
|
|
2
|
+
|
|
3
|
+
This file gives the files, the names and the lines of the source that `generate` writes. For the command, see the section "Generate the source" of `SKILL.md`.
|
|
4
|
+
|
|
5
|
+
## The source files
|
|
6
|
+
|
|
7
|
+
- `main.asm` sets the address of each segment. It includes the files in address order.
|
|
8
|
+
- 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`.
|
|
9
|
+
- `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.
|
|
10
|
+
- 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.
|
|
11
|
+
- 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.
|
|
12
|
+
- `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.
|
|
13
|
+
- 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.
|
|
14
|
+
- `start_screen.asm` is the code that shows the start screen and waits. It is the same for each program.
|
|
15
|
+
- `switches.asm` holds each release of the knowledge. `main.asm` and `loader.asm` include it first. The script writes it only when the knowledge has switches or releases, or when the source has leftovers. For each release, a block `!ifdef RELEASE_<label>` gives each switch the value of that release.
|
|
16
|
+
- `leftovers/leftover_xxxx.asm` holds a range of leftovers. See "The leftovers".
|
|
17
|
+
- `macros.asm` holds the macros of the knowledge. `main.asm` and `loader.asm` include it.
|
|
18
|
+
|
|
19
|
+
## Names in the source
|
|
20
|
+
|
|
21
|
+
- A label or a constant gets the name of the address in the knowledge.
|
|
22
|
+
- Without a knowledge name, it gets the platform name, for example `EXTCOL` or `CHROUT`. A platform name wins over an analyzer name (`dxa`, `decompiler` or `heuristic`), for example `EXTCOL` over `ld020`. A `user` or `llm` name wins over a platform name.
|
|
23
|
+
- An address in the program without a name gets `l_xxxx`.
|
|
24
|
+
- A read or a write in the I/O area `$d000-$dfff` uses the register, also when the program has RAM there. For example, `lda $dd0e` is `lda CI2CRA` and `sta $d012` is `sta RASTER`. `constants.asm` has these names. An address without a platform name stays a number, for example `sta $d800,x`. The data label of the RAM stays at its data. A `user` or `llm` name of the address wins over the register.
|
|
25
|
+
- A platform name in an operand expression of the knowledge stays in the source. When the program has the address, `constants.asm` has the name, and the RAM there keeps its label.
|
|
26
|
+
- The source does not use the names of a ROM that the program does not use. `romNamesLeftOut` gives these ROMs.
|
|
27
|
+
- When the program uses no ROM, the zero page and pages 2 and 3 get no system names. An operand expression or a macro use with such a name gets that reason.
|
|
28
|
+
|
|
29
|
+
## Lines in the source
|
|
30
|
+
|
|
31
|
+
- `sta $d011 ; $d011: yScroll 3, rows 25, displayEnabled` is a store of an immediate to a register with a known meaning. The side comment gives the decoded value. A side comment in the knowledge replaces it.
|
|
32
|
+
- Code regions, and the decoded instructions outside of data regions, become instructions.
|
|
33
|
+
- Data regions become data by their type: `!byte`, `!word`, `!pet`, `!scr`, `!fill`, tables of labels, and sprite bytes in binary.
|
|
34
|
+
- `lda+2 $0012` is an absolute operand below $0100. `+1` is a zero-page operand with a label.
|
|
35
|
+
- `sta NMINV+1` is an address inside a platform entry of more than one byte, for example the high byte of a vector.
|
|
36
|
+
- `lda room_colours+5` is an address inside a data region with a named start. The address has no name of its own.
|
|
37
|
+
- `name = * + 1` is a label inside an instruction, for example for code that changes its own operand.
|
|
38
|
+
- `lda #<irq_handler` and `lda bar_colours-1,x` are operand expressions of the knowledge. An expression in a non-immediate mode that starts with a bracket gets `0+` before it. ACME reads `(...)` as indirect.
|
|
39
|
+
- `; = <irq_handler` at the end of an instruction with a number: the source cannot use this operand expression. `operandsAsNumbers` gives the reason.
|
|
40
|
+
- `!byte` with an instruction as its comment: ACME writes this instruction with a different opcode. The bytes keep the source identical.
|
|
41
|
+
- `not decoded` marks bytes in a code region that the script did not decode.
|
|
42
|
+
- `; not executed $xxxx-$yyyy` starts code that no run of the coverage executed. The range is an item of `notExecuted`.
|
|
43
|
+
- `+inc16 ptr` is a use of a macro of the knowledge. The comments inside a use go to its side comment.
|
|
44
|
+
- `!zone patch_PROTECTION_100e` starts a patch. The condition is the switch state that the program does not have. It is `!if TRAINER` when the base release has the switch off. It is `!if PROTECTION = 0` when the base release has it on.
|
|
45
|
+
- A patch block has the code of the patch and NOP to the end of the range. `else` has the code of the base release. The labels inside the range come before the zone as `name = * + n`.
|
|
46
|
+
- Alternatives are patches of two or more switches at one range. They follow as `} else { !if FIX_B {`. A line before them stops the build with `!error` when two of them are in.
|
|
@@ -7,12 +7,16 @@
|
|
|
7
7
|
// decoded instructions. Pass A starts at the entry and the hardware vectors:
|
|
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
|
-
// tells what stays. Without coverage nothing becomes free by itself.
|
|
10
|
+
// tells what stays. Without coverage nothing becomes free by itself. While the
|
|
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.
|
|
11
15
|
|
|
12
16
|
import { type AddressRange, COVERAGE, formatC64Address, pointerTableEntries, POINTER_TABLE_TYPES, type PointerTableType } from "#src/c64.ts";
|
|
13
17
|
import { symbolsPath } from "#src/build-name.ts";
|
|
14
18
|
import { Refusal } from "#src/errors.ts";
|
|
15
|
-
import { NO_FALL_THROUGH, type Root, separate } from "#src/knowledge/separate.ts";
|
|
19
|
+
import { computedFlows, NO_FALL_THROUGH, type Root, separate, type UnresolvedFlow, vectorHigh, WRITES_A, WRITES_X, WRITES_Y } from "#src/knowledge/separate.ts";
|
|
16
20
|
import type { RegionType } from "#src/knowledge/schema.ts";
|
|
17
21
|
import { OPCODES } from "#src/opcodes.ts";
|
|
18
22
|
|
|
@@ -42,10 +46,6 @@ const RAM_ACCESS = 0xff & ~(COVERAGE.romRead | COVERAGE.romExecute);
|
|
|
42
46
|
/** The I/O area: two immediates stored there are chip values, such as a timer latch, not an address. */
|
|
43
47
|
const IO_AREA: AddressRange = { start: 0xd000, end: 0xdfff };
|
|
44
48
|
|
|
45
|
-
/** The registers that each instruction changes, other than by a load of an immediate or a transfer. */
|
|
46
|
-
const WRITES_A = new Set(["lda", "adc", "sbc", "and", "ora", "eor", "pla", "lax", "anc", "asr", "arr", "ane", "lxa", "las", "slo", "rla", "sre", "rra", "isc"]);
|
|
47
|
-
const WRITES_X = new Set(["ldx", "inx", "dex", "tsx", "lax", "sbx", "lxa", "las"]);
|
|
48
|
-
const WRITES_Y = new Set(["ldy", "iny", "dey"]);
|
|
49
49
|
/** The registers that a JSR gets an address in, low byte first, as the KERNAL and BASIC routines get a pointer. */
|
|
50
50
|
const CALL_PAIRS = [
|
|
51
51
|
["x", "y"],
|
|
@@ -62,7 +62,8 @@ export interface DropInput {
|
|
|
62
62
|
instructions: ReadonlyMap<number, number>;
|
|
63
63
|
coverage?: Uint8Array;
|
|
64
64
|
regions: ReadonlyArray<{ start: number; end: number; type: RegionType }>;
|
|
65
|
-
|
|
65
|
+
/** A jump or call reference of the user or the LLM resolves the flow of its instruction. */
|
|
66
|
+
references: ReadonlyArray<{ from: number; to: number; kind: string; origin?: string }>;
|
|
66
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. */
|
|
67
68
|
operandTargets: ReadonlyMap<number, readonly number[]>;
|
|
68
69
|
/** The ranges where the CPU sees ROM and not the RAM of the image: code does not go there, and no address points there. */
|
|
@@ -87,6 +88,10 @@ export interface DropPlan {
|
|
|
87
88
|
unreachableExecuted: Array<AddressRange & { routine?: string }>;
|
|
88
89
|
/** False when the image has no entry and no hardware vectors: then nothing is unreachable. */
|
|
89
90
|
rooted: boolean;
|
|
91
|
+
/** Code that nothing reaches and that no run executed, which stays because of the flows in `unresolved`. */
|
|
92
|
+
unknown: AddressRange[];
|
|
93
|
+
/** The flows whose targets the knowledge does not give. */
|
|
94
|
+
unresolved: UnresolvedFlow[];
|
|
90
95
|
}
|
|
91
96
|
|
|
92
97
|
const inside = (address: number, ranges: readonly AddressRange[]) => ranges.some((range) => address >= range.start && address <= range.end);
|
|
@@ -198,10 +203,12 @@ function flowsOf(input: DropInput, inImage: (address: number) => boolean, indexe
|
|
|
198
203
|
case "rel":
|
|
199
204
|
flows.push({ from: at, to: (at + 2 + (operand < 0x80 ? operand : operand - 0x100)) & 0xffff });
|
|
200
205
|
break;
|
|
201
|
-
case "ind":
|
|
202
|
-
|
|
203
|
-
|
|
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) });
|
|
204
210
|
break;
|
|
211
|
+
}
|
|
205
212
|
case "abs":
|
|
206
213
|
case "zp":
|
|
207
214
|
if (opcode === 0x20 || opcode === 0x4c) {
|
|
@@ -318,8 +325,16 @@ export function planDrops(input: DropInput): DropPlan {
|
|
|
318
325
|
}
|
|
319
326
|
const passB = separate({ segments: [...input.segments], memory: input.memory, ...(input.entry === undefined ? {} : { entry: input.entry }), codeRegions: asRegions(candidates), references, roots: extra });
|
|
320
327
|
const automatic = input.coverage !== undefined && rooted;
|
|
321
|
-
const
|
|
322
|
-
|
|
328
|
+
const unreachableCode = candidates.filter((_, index) => automatic && passB.codeRegions[index]!.reachable === false);
|
|
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));
|
|
335
|
+
const droppedCode = unresolved.length === 0 ? unreachableCode : [];
|
|
336
|
+
const unknown = unresolved.length === 0 ? [] : merged(unreachableCode);
|
|
337
|
+
const stays = candidates.filter((block) => !droppedCode.includes(block));
|
|
323
338
|
const inStaying = (address: number) => stays.some((block) => address >= block.start && address <= block.end);
|
|
324
339
|
for (const range of input.drop) {
|
|
325
340
|
const into = flows.find((flow) => inStaying(flow.from) && inside(flow.to, [range]));
|
|
@@ -378,7 +393,7 @@ export function planDrops(input: DropInput): DropPlan {
|
|
|
378
393
|
const routine = routines.filter((item) => item.address <= range.start).at(-1)?.name;
|
|
379
394
|
return { ...range, ...(routine === undefined ? {} : { routine }) };
|
|
380
395
|
});
|
|
381
|
-
return { free, unreachableExecuted, rooted };
|
|
396
|
+
return { free, unreachableExecuted, rooted, unknown, unresolved };
|
|
382
397
|
}
|
|
383
398
|
|
|
384
399
|
/** The label of a free range. */
|
|
@@ -19,17 +19,14 @@ import { readFileSync } from "node:fs";
|
|
|
19
19
|
import { fileURLToPath } from "node:url";
|
|
20
20
|
|
|
21
21
|
import { COPIER_LINE } from "#src/build-name.ts";
|
|
22
|
-
import { type AddressRange, formatC64Address, formatC64Byte
|
|
23
|
-
import { compareBuild, mergedPrograms } from "#src/compare.ts";
|
|
22
|
+
import { type AddressRange, formatC64Address, formatC64Byte } from "#src/c64.ts";
|
|
24
23
|
import { Refusal } from "#src/errors.ts";
|
|
25
24
|
import { parseEntryState } from "#src/host-client/entry-state.ts";
|
|
26
25
|
import { isRomFont, startScreenRanges, type StartScreenRow } from "#src/knowledge/read.ts";
|
|
27
26
|
import { capturedColourRam, LOADER_JUMP } from "#src/knowledge/start-screen.ts";
|
|
27
|
+
import { COPIER_SOURCE } from "#src/loader.ts";
|
|
28
28
|
import { romUseOfPort } from "#src/platform.ts";
|
|
29
29
|
import { WireFailure } from "#src/host-client/tools.ts";
|
|
30
|
-
import { pack } from "#src/native/exomizer.ts";
|
|
31
|
-
import type { ToolContext } from "#src/native/run.ts";
|
|
32
|
-
import type { AssembledSymbol } from "#src/native/types.ts";
|
|
33
30
|
|
|
34
31
|
export interface EntryState {
|
|
35
32
|
pc: number;
|
|
@@ -506,8 +503,6 @@ function settingsLines(input: LoaderInput): string[] {
|
|
|
506
503
|
/** The label of a block: its first byte and the byte after it in the loader file, and its first address where it runs. */
|
|
507
504
|
const blockLabel = (start: number, part: "from" | "end" | "to") => `loader_${part}_${start.toString(16).padStart(4, "0")}`;
|
|
508
505
|
const plus = (label: string, offset: number) => (offset === 0 ? label : `${label}+${offset}`);
|
|
509
|
-
/** The label of the copier in the loader file, which the stub moves to its two pages. */
|
|
510
|
-
export const COPIER_SOURCE = "loader_copier_src";
|
|
511
506
|
|
|
512
507
|
/** A block of the loader: a segment with its files, or bytes of pages 0-3. */
|
|
513
508
|
interface Block {
|
|
@@ -596,7 +591,7 @@ function planForm(input: LoaderInput, colours: Uint8Array | undefined): LoaderPl
|
|
|
596
591
|
const order = copyOrder(plain);
|
|
597
592
|
if (order === undefined) {
|
|
598
593
|
const clashing = plain.filter((copy) => plain.some((other) => other !== copy && overlaps(copy.target, other.source))).map((copy) => `${copy.what} (packed at ${show(copy.source)})`);
|
|
599
|
-
throw new WireFailure("invalid-input", `No copy order exists: each of these copies writes over the packed bytes of another one: ${clashing.join(", ")}.
|
|
594
|
+
throw new WireFailure("invalid-input", `No copy order exists: each of these copies writes over the packed bytes of another one: ${clashing.join(", ")}. Give this reason to the user.`);
|
|
600
595
|
}
|
|
601
596
|
const loaded = { start: LOAD, end };
|
|
602
597
|
const areas = copierAreas(state.port);
|
|
@@ -763,7 +758,7 @@ function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof
|
|
|
763
758
|
placed.refusal === "copies"
|
|
764
759
|
? `A packed loader needs more than ${MAX_PACKED_COPIES} copies for the ${lowBytes} bytes of pages 0-3 in the free ranges.`
|
|
765
760
|
: `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier in ${areas.map(show).join(" or ")}, and ${lowBytes} more free bytes for pages 0-3 in ${show(PIECE_AREA)}, outside the segments. The copier runs with $01 = $35 and then with the $01 of the entry, so it is in RAM that both show.${screen === undefined ? "" : ` The start screen takes ${START_SCREEN_SIZES[screen.colourMode]} bytes of the copier: without it (unstart-screen), the copier is smaller.`}`;
|
|
766
|
-
throw new WireFailure("invalid-input", `${tooLarge} ${why} ${ranges}
|
|
761
|
+
throw new WireFailure("invalid-input", `${tooLarge} ${why} ${ranges} Give this reason to the user.`);
|
|
767
762
|
}
|
|
768
763
|
const { copier, pieces } = placed;
|
|
769
764
|
const copierEnd = copier + codeSize + COPY_ENTRY * pieces.length + 2 - 1;
|
|
@@ -906,59 +901,6 @@ function placePacked(copierFree: AddressRange[], free: AddressRange[], low: Para
|
|
|
906
901
|
return { refusal: "copies" };
|
|
907
902
|
}
|
|
908
903
|
|
|
909
|
-
/** What Exomizer makes of a packed loader. */
|
|
910
|
-
export interface PackedLoader {
|
|
911
|
-
/** The loader program: it loads at $0801 and starts with RUN. */
|
|
912
|
-
program: Buffer;
|
|
913
|
-
packedBytes: number;
|
|
914
|
-
unpackedBytes: number;
|
|
915
|
-
/** The CPU cycles of the unpack, when Exomizer gives them. */
|
|
916
|
-
cycles?: number;
|
|
917
|
-
}
|
|
918
|
-
|
|
919
|
-
/**
|
|
920
|
-
* Packs the loaded ranges of the build of main.asm from $0400 and the build of
|
|
921
|
-
* loader.asm (the copier wins where they overlap) with the entry at the copier
|
|
922
|
-
* and $01 = $34, and checks the unpack in the emulator of Exomizer: every byte
|
|
923
|
-
* of the two builds, and the jump to the copier. Refuses by name when it does
|
|
924
|
-
* not hold.
|
|
925
|
-
*/
|
|
926
|
-
export async function packLoader(main: Uint8Array, copier: Uint8Array, plan: LoaderPlan, context: ToolContext): Promise<PackedLoader> {
|
|
927
|
-
return packParts(packedParts(main, copier, plan), plan.copier, 0x34, "main.asm and loader.asm", "the copier", context);
|
|
928
|
-
}
|
|
929
|
-
|
|
930
|
-
/** What Exomizer packs in the packed form: the loaded ranges of the build of main.asm from $0400, and the build of loader.asm. */
|
|
931
|
-
function packedParts(main: Uint8Array, copier: Uint8Array, plan: Pick<LoaderPlan, "loaded">): Array<{ start: number; body: Uint8Array }> {
|
|
932
|
-
// The unpacker uses pages 0-3; the copier writes them. The leftovers between the loaded ranges are not packed.
|
|
933
|
-
const program = prgRange(main);
|
|
934
|
-
const ranges = plan.loaded.flatMap((range) => {
|
|
935
|
-
const start = Math.max(range.start, 0x0400, program.start);
|
|
936
|
-
const end = Math.min(range.end, program.start + program.body.length - 1);
|
|
937
|
-
return start <= end ? [{ start, body: program.body.subarray(start - program.start, end - program.start + 1) }] : [];
|
|
938
|
-
});
|
|
939
|
-
return [...ranges, prgRange(copier)];
|
|
940
|
-
}
|
|
941
|
-
|
|
942
|
-
/**
|
|
943
|
-
* Packs parts (a later one wins where they overlap) into one program that
|
|
944
|
-
* unpacks itself, starts at `entry` with $01 = `exitMemory`, and checks the
|
|
945
|
-
* unpack in the emulator of Exomizer: every byte of the parts, and the jump
|
|
946
|
-
* to the entry. Refuses by name when it does not hold.
|
|
947
|
-
*/
|
|
948
|
-
export async function packParts(parts: ReadonlyArray<{ start: number; body: Uint8Array }>, entry: number, exitMemory: number, what: string, entryName: string, context: ToolContext): Promise<PackedLoader> {
|
|
949
|
-
const prg = (part: { start: number; body: Uint8Array }) => Buffer.concat([Buffer.from([part.start & 0xff, part.start >> 8]), part.body]);
|
|
950
|
-
const packed = await pack({ programs: parts.map(prg), entry, exitMemory }, context);
|
|
951
|
-
if (packed.entry !== entry) throw new WireFailure("operation-failed", `The unpack in the emulator of Exomizer jumps to ${formatC64Address(packed.entry)}, not to ${entryName} at ${formatC64Address(entry)}.`);
|
|
952
|
-
const reference = mergedPrograms(parts);
|
|
953
|
-
const wrong = compareBuild(packed.unpacked, reference).segments.find((segment) => segment.result !== "identical");
|
|
954
|
-
if (wrong !== undefined) {
|
|
955
|
-
const first = wrong.firstDifference === undefined ? "" : `: the first is ${wrong.firstDifference.address}, ${wrong.firstDifference.built} and not ${wrong.firstDifference.reference}`;
|
|
956
|
-
throw new WireFailure("operation-failed", `The unpack in the emulator of Exomizer does not give ${wrong.start}-${wrong.end} of ${what} (${wrong.result}${first}).`);
|
|
957
|
-
}
|
|
958
|
-
const unpackedBytes = reference.segments.reduce((sum, segment) => sum + segment.end - segment.start + 1, 0);
|
|
959
|
-
return { program: packed.program, packedBytes: packed.program.length, unpackedBytes, ...(packed.cycles === undefined ? {} : { cycles: packed.cycles }) };
|
|
960
|
-
}
|
|
961
|
-
|
|
962
904
|
/**
|
|
963
905
|
* The copier: its copies by the table, the VIC-II and CIA parts, then $00/$01,
|
|
964
906
|
* the stack pointer, the flags and A/X/Y, and the jump to the entry. It ends
|
|
@@ -1104,23 +1046,3 @@ function vicLines(state: EntryState, earlier: number): string[] {
|
|
|
1104
1046
|
" bne .raster",
|
|
1105
1047
|
];
|
|
1106
1048
|
}
|
|
1107
|
-
|
|
1108
|
-
/**
|
|
1109
|
-
* The symbols of the loader program: the labels of the build of loader.asm, which
|
|
1110
|
-
* includes main.asm, and of start_screen_stage.asm when the loader has a show
|
|
1111
|
-
* stage. A test takes one symbols file. Refuses a name with two values.
|
|
1112
|
-
*/
|
|
1113
|
-
export function loaderSymbols(...builds: ReadonlyArray<readonly AssembledSymbol[]>): AssembledSymbol[] {
|
|
1114
|
-
const valueOf = (symbol: AssembledSymbol) => (symbol.kind === "address" ? symbol.address : symbol.value);
|
|
1115
|
-
const byName = new Map<string, AssembledSymbol>();
|
|
1116
|
-
for (const symbol of builds.flat()) {
|
|
1117
|
-
const known = byName.get(symbol.name);
|
|
1118
|
-
if (known !== undefined && valueOf(known) !== valueOf(symbol)) {
|
|
1119
|
-
throw new WireFailure("operation-failed", `The builds of the loader program give ${symbol.name} two values, ${valueOf(known)} and ${valueOf(symbol)}. This is a defect of the script.`);
|
|
1120
|
-
}
|
|
1121
|
-
// An address in one build can be outside the load range of the other build, where it is a constant.
|
|
1122
|
-
const kept = known === undefined || (known.kind === "constant" && symbol.kind === "address") ? symbol : known;
|
|
1123
|
-
byName.set(symbol.name, { ...kept, used: symbol.used || (known?.used ?? false) });
|
|
1124
|
-
}
|
|
1125
|
-
return [...byName.values()].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
|
|
1126
|
-
}
|
|
@@ -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
|
}
|
|
@@ -16,7 +16,7 @@ import { basename, dirname, join, relative, sep } from "node:path";
|
|
|
16
16
|
import { isRefusal, Refusal } from "#src/errors.ts";
|
|
17
17
|
import { PACKAGE } from "#src/package.ts";
|
|
18
18
|
import { BUILD_DIRECTORY, buildName, symbolsPath } from "#src/build-name.ts";
|
|
19
|
-
import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address,
|
|
19
|
+
import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
|
|
20
20
|
import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
|
|
21
21
|
import { IO_RAM } from "#src/host-client/coverage.ts";
|
|
22
22
|
import { MAX_MEMORY_READ, WireFailure } from "#src/host-client/tools.ts";
|
|
@@ -40,17 +40,14 @@ import { isoCet } from "#src/time.ts";
|
|
|
40
40
|
import { zipFiles } from "#src/zip.ts";
|
|
41
41
|
import { listed, OPTIONS, reply, runScript, UsageError, type Call, type Reply } from "#src/script.ts";
|
|
42
42
|
import { knowledgeNames } from "#src/knowledge/names.ts";
|
|
43
|
+
import { COPIER_SOURCE, leftoverRange, loaderSymbols, packLoader, packParts, type PackedLoader } from "#src/loader.ts";
|
|
43
44
|
import {
|
|
44
|
-
COPIER_SOURCE,
|
|
45
45
|
LOADER_JUMP,
|
|
46
46
|
loaderLimits,
|
|
47
|
-
packLoader,
|
|
48
|
-
packParts,
|
|
49
47
|
planLoader,
|
|
50
48
|
startScreenPlan,
|
|
51
49
|
rasterLine,
|
|
52
50
|
loaderState,
|
|
53
|
-
loaderSymbols,
|
|
54
51
|
simulate,
|
|
55
52
|
START_SCREEN_CODE,
|
|
56
53
|
START_SCREEN_CONTINUE,
|
|
@@ -60,13 +57,13 @@ import {
|
|
|
60
57
|
VIC_DISPLAY_REGISTERS,
|
|
61
58
|
type EntryState,
|
|
62
59
|
type LoaderPlan,
|
|
63
|
-
type PackedLoader,
|
|
64
60
|
type StartScreenPlan,
|
|
65
61
|
} from "./lib/loader.ts";
|
|
66
62
|
import { instructionWith, OPCODES } from "#src/opcodes.ts";
|
|
67
63
|
import { capturedColourRam } from "#src/knowledge/start-screen.ts";
|
|
68
64
|
import { planStage, STAGE_CODE_END, STAGE_FILE, STAGE_START, stageParts, stageText, type StageInput, type StagePart, type StagePlan } from "./lib/stage.ts";
|
|
69
65
|
import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
|
|
66
|
+
import type { UnresolvedFlow } from "#src/knowledge/separate.ts";
|
|
70
67
|
import { CONFIG_FILE, configText, configValues, entriesInData, entryOutsideImage, hasConfigFile, hasSwitchFile, layout, literalOperand, probeForms, render, stagePatchText, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
|
|
71
68
|
|
|
72
69
|
/** At most this many diagnostics or differences of one check. */
|
|
@@ -687,8 +684,6 @@ function leftOutNames(used: ReadonlyArray<{ name: string }>): Set<string> {
|
|
|
687
684
|
|
|
688
685
|
/** The first words of every file that the script writes. */
|
|
689
686
|
const GENERATED_MARK = "; Generated by c64-source";
|
|
690
|
-
/** The file with every range of instructions that no run executed. */
|
|
691
|
-
const NOT_EXECUTED_FILE = "not_executed.json";
|
|
692
687
|
/** The line of each name and address in the source, for links from the documentation. */
|
|
693
688
|
const SOURCE_MAP_FILE = "source-map.json";
|
|
694
689
|
|
|
@@ -750,9 +745,6 @@ function staleLoader(out: string, revision: string): { files: string[]; revision
|
|
|
750
745
|
return { files, ...(old === undefined ? {} : { revision: old }), ...(version === undefined ? {} : { version }) };
|
|
751
746
|
}
|
|
752
747
|
|
|
753
|
-
/** The line of a leftover file that gives its range. */
|
|
754
|
-
const LEFTOVER_RANGE = /^; Leftovers (\$[0-9a-f]{4})-(\$[0-9a-f]{4}):/m;
|
|
755
|
-
|
|
756
748
|
/**
|
|
757
749
|
* The leftovers of the earlier run: the ranges of its generated leftover
|
|
758
750
|
* files in the leftovers folder of `out`. Undefined when `out` has no
|
|
@@ -766,10 +758,7 @@ function earlierLeftovers(out: string): AddressRange[] | undefined {
|
|
|
766
758
|
if (!existsSync(directory)) return [];
|
|
767
759
|
return readdirSync(directory)
|
|
768
760
|
.filter((name) => /^leftover_[0-9a-f]{4}\.asm$/.test(name))
|
|
769
|
-
.flatMap((name) =>
|
|
770
|
-
const found = LEFTOVER_RANGE.exec(readFileSync(join(directory, name), "utf8"));
|
|
771
|
-
return found === null ? [] : [{ start: parseC64Address(found[1]!), end: parseC64Address(found[2]!) }];
|
|
772
|
-
});
|
|
761
|
+
.flatMap((name) => leftoverRange(readFileSync(join(directory, name), "utf8")) ?? []);
|
|
773
762
|
}
|
|
774
763
|
|
|
775
764
|
/** The bytes of `ranges` that are not in `others`, as ranges in address order. */
|
|
@@ -779,22 +768,14 @@ function outside(ranges: readonly AddressRange[], others: readonly AddressRange[
|
|
|
779
768
|
|
|
780
769
|
/**
|
|
781
770
|
* Removes the generated .asm files of an earlier run that this run does not
|
|
782
|
-
* write
|
|
783
|
-
*
|
|
784
|
-
*
|
|
785
|
-
*
|
|
786
|
-
*
|
|
787
|
-
* space, and it stays. Other files stay. Gives the paths it removed.
|
|
771
|
+
* write. An earlier loader.asm stays unless this run has --loader: a source of
|
|
772
|
+
* the user can include loader.asm. The files of a module are in `out` or in
|
|
773
|
+
* one folder of it: a folder that the run leaves empty goes too. A folder
|
|
774
|
+
* with a generated main.asm is the source of another space, and it stays.
|
|
775
|
+
* Other files stay. Gives the paths it removed.
|
|
788
776
|
*/
|
|
789
777
|
function removeOldFiles(out: string, keep: ReadonlySet<string>, loaderRun: boolean): string[] {
|
|
790
778
|
const removed: string[] = [];
|
|
791
|
-
const reports = generatedDirectory(projectRelative(out));
|
|
792
|
-
for (const name of [SOURCE_MAP_FILE, NOT_EXECUTED_FILE]) {
|
|
793
|
-
const path = resolveProjectPath(`${reports}/${name}`);
|
|
794
|
-
if (!existsSync(path)) continue;
|
|
795
|
-
rmSync(path, { force: true });
|
|
796
|
-
removed.push(`${reports}/${name}`);
|
|
797
|
-
}
|
|
798
779
|
const root = resolveProjectPath(out);
|
|
799
780
|
if (!existsSync(root)) return removed;
|
|
800
781
|
/** Removes the old generated files of a folder ("" for `out` itself), and gives how many. */
|
|
@@ -865,7 +846,8 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
|
|
|
865
846
|
const romUse = romUseOfProgram(coverage, image.state);
|
|
866
847
|
const platform = platformNamesFor(romUse);
|
|
867
848
|
const { instructions, dataOnly } = options.decoded ?? (await decode(image, knowledge, options.entries, coverage));
|
|
868
|
-
const
|
|
849
|
+
const leftoverPlan = options.leftovers === true && !dataOnly ? leftoversOf(knowledge, instructions) : { ranges: [], unknown: [], unresolved: [] };
|
|
850
|
+
const leftovers = leftoverPlan.ranges;
|
|
869
851
|
const laid = layout({
|
|
870
852
|
segments: image.segments,
|
|
871
853
|
byteAt: image.byteAt,
|
|
@@ -949,7 +931,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
|
|
|
949
931
|
}
|
|
950
932
|
}
|
|
951
933
|
if (loader !== undefined) files = [...files, ...marked([{ name: "loader.asm", text: loader.text }, ...(loader.startScreen === undefined ? [] : [{ name: START_SCREEN_FILE, text: START_SCREEN_CODE }])])];
|
|
952
|
-
return { romUse, instructions, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused };
|
|
934
|
+
return { romUse, instructions, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused, unknownCode: { unknown: leftoverPlan.unknown, unresolved: leftoverPlan.unresolved } };
|
|
953
935
|
}
|
|
954
936
|
|
|
955
937
|
/** The ranges that the loader loads, each with its files: the segments without the leftovers. */
|
|
@@ -1053,7 +1035,7 @@ async function stageBytes(row: StartScreenRow): Promise<{ parts: StagePart[]; co
|
|
|
1053
1035
|
// The call is the entry of the stage: what it does not reach and its run did not touch stays out.
|
|
1054
1036
|
const called = { ...knowledge, program: { ...image, entry: row.call } };
|
|
1055
1037
|
const { instructions } = await decode(called.program, called, [row.call], knowledge.coverage);
|
|
1056
|
-
const free = leftoversOf(called, instructions, screen);
|
|
1038
|
+
const free = leftoversOf(called, instructions, screen).ranges;
|
|
1057
1039
|
ranges = [...screen, ...image.segments.flatMap((segment) => subtract(segment, free))];
|
|
1058
1040
|
}
|
|
1059
1041
|
const parts: AddressRange[] = [];
|
|
@@ -1160,7 +1142,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1160
1142
|
const loaderValues = new Map([...given].filter(([name]) => configNames.has(name)));
|
|
1161
1143
|
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."];
|
|
1162
1144
|
const loaderHeader = [loaderLine(knowledge.sourceRevision), "It copies the segments into place, sets the entry state and jumps to the entry."];
|
|
1163
|
-
const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused } = await buildSource(knowledge, {
|
|
1145
|
+
const { romUse, dataOnly, laid, rendered, files, built, loader, loaderMain, missingEntry, loaderRefused, unknownCode } = await buildSource(knowledge, {
|
|
1164
1146
|
space,
|
|
1165
1147
|
entries,
|
|
1166
1148
|
header,
|
|
@@ -1190,19 +1172,13 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1190
1172
|
.map((reference) => ({ folder: reference.folder, revision: reference.revision }));
|
|
1191
1173
|
const showRange = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
|
|
1192
1174
|
const inData = entriesInData(entries, knowledge.regions);
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
const
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
});
|
|
1201
|
-
const files: Record<string, number> = {};
|
|
1202
|
-
for (const range of placed) if (range.file !== undefined) files[range.file] = (files[range.file] ?? 0) + 1;
|
|
1203
|
-
const all = { revision: knowledge.sourceRevision, instructions: rendered.notExecuted.instructions, files, ranges: placed };
|
|
1204
|
-
written.push(writeReported(`${reports}/${NOT_EXECUTED_FILE}`, `${JSON.stringify(all, null, 2)}\n`));
|
|
1205
|
-
}
|
|
1175
|
+
// Each range of code that no run executed, with the file of the source that holds it and the routine before it, as a report groups them.
|
|
1176
|
+
const routines = knowledge.symbols.filter((symbol) => symbol.kind === "routine").sort((a, b) => a.address - b.address);
|
|
1177
|
+
const placeRange = (range: AddressRange) => {
|
|
1178
|
+
const file = laid.pieces.find((piece) => range.start >= piece.start && range.start <= piece.end)?.file;
|
|
1179
|
+
const routine = routines.filter((symbol) => symbol.address <= range.start).at(-1)?.name;
|
|
1180
|
+
return { ...showRange(range), ...(file === undefined ? {} : { file }), ...(routine === undefined ? {} : { routine }) };
|
|
1181
|
+
};
|
|
1206
1182
|
// The leftovers that changed since the earlier run: the default build and the loader now leave out other bytes.
|
|
1207
1183
|
const added = earlier === undefined ? [] : outside(laid.leftovers, earlier);
|
|
1208
1184
|
const dropped = earlier === undefined ? [] : outside(earlier, laid.leftovers);
|
|
@@ -1236,7 +1212,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1236
1212
|
...(rendered.notExecuted === undefined
|
|
1237
1213
|
? {}
|
|
1238
1214
|
: {
|
|
1239
|
-
notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max,
|
|
1215
|
+
notExecuted: { instructions: rendered.notExecuted.instructions, ...listed(rendered.notExecuted.ranges, max, placeRange) },
|
|
1240
1216
|
}),
|
|
1241
1217
|
...(laid.unusedModules.length === 0 ? {} : { unusedModules: laid.unusedModules.map((module) => ({ start: formatC64Address(module.start), file: module.file })) }),
|
|
1242
1218
|
// The bytes that nothing uses: in leftover files, which the default build and the loader leave out.
|
|
@@ -1247,6 +1223,7 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
1247
1223
|
? {}
|
|
1248
1224
|
: { leftovers: { bytes: 0, changed } }
|
|
1249
1225
|
: { leftovers: { bytes: laid.leftovers.reduce((sum, range) => sum + range.end - range.start + 1, 0), ...listed(laid.leftovers, max, (range) => ({ ...showRange(range), bytes: range.end - range.start + 1, file: `${LEFTOVER_FOLDER}/leftover_${range.start.toString(16).padStart(4, "0")}.asm` })), ...(changed === undefined ? {} : { changed }) } }),
|
|
1226
|
+
...(unknownCode.unknown.length === 0 ? {} : { unknownCode: showUnknown(unknownCode, max) }),
|
|
1250
1227
|
...(rendered.expressions.length === 0 && rendered.operandsAsNumbers.length === 0 ? {} : { operandExpressions: rendered.expressions.length }),
|
|
1251
1228
|
...(rendered.operandsAsNumbers.length === 0
|
|
1252
1229
|
? {}
|
|
@@ -1489,7 +1466,7 @@ function freeRanges(knowledge: SourceKnowledge, memory: Uint8Array, instructions
|
|
|
1489
1466
|
* patch names and the ranges of `keep` stay, so each switch builds with
|
|
1490
1467
|
* LEFTOVERS = 0.
|
|
1491
1468
|
*/
|
|
1492
|
-
function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<number, number>, kept: readonly AddressRange[] = []): AddressRange[] {
|
|
1469
|
+
function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<number, number>, kept: readonly AddressRange[] = []): UnknownCode & { ranges: AddressRange[] } {
|
|
1493
1470
|
const image = knowledge.program;
|
|
1494
1471
|
const inImage = (range: AddressRange) => image.segments.some((segment) => range.start >= segment.start && range.end <= segment.end);
|
|
1495
1472
|
const addressOf = new Map(knowledge.symbols.map((symbol) => [symbol.name, symbol.address]));
|
|
@@ -1497,12 +1474,29 @@ function leftoversOf(knowledge: SourceKnowledge, instructions: ReadonlyMap<numbe
|
|
|
1497
1474
|
const named = knowledge.patches.flatMap((patch) => patchTargets(patch.code, addressOf)).map((address) => ({ start: address, end: address }));
|
|
1498
1475
|
const keep = [...screenParts, ...kept, ...named].map((range) => ({ start: range.start, end: range.end })).filter(inImage);
|
|
1499
1476
|
const changed = knowledge.patches.map((patch) => ({ start: patch.start, end: patch.end })).filter(inImage);
|
|
1500
|
-
const
|
|
1477
|
+
const plan = freeRanges(knowledge, image.memory, instructions, { changed, keep, drop: [] });
|
|
1478
|
+
const free = plan.free.map((range) => ({ start: range.start, end: range.end }));
|
|
1501
1479
|
// A macro use in code that nothing uses goes with that code. A leftover never cuts a use in two: its edge stops at the use.
|
|
1502
1480
|
const cut = (range: AddressRange) => knowledge.macroUses.filter((use) => use.start <= range.end && range.start <= use.end && (use.start < range.start || use.end > range.end));
|
|
1503
|
-
return free.flatMap((range) => subtract(range, cut(range)));
|
|
1481
|
+
return { ranges: free.flatMap((range) => subtract(range, cut(range))), unknown: plan.unknown, unresolved: plan.unresolved };
|
|
1504
1482
|
}
|
|
1505
1483
|
|
|
1484
|
+
/** Code that no flow reaches and no run executed, which stays because a flow in `unresolved` can go to it. */
|
|
1485
|
+
interface UnknownCode {
|
|
1486
|
+
unknown: AddressRange[];
|
|
1487
|
+
unresolved: UnresolvedFlow[];
|
|
1488
|
+
}
|
|
1489
|
+
|
|
1490
|
+
/** The unknown code of a result: its ranges, and the flows whose targets the knowledge does not give. */
|
|
1491
|
+
function showUnknown(code: UnknownCode, max: number) {
|
|
1492
|
+
return {
|
|
1493
|
+
...listed(code.unknown, max, (range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end), bytes: range.end - range.start + 1 })),
|
|
1494
|
+
unresolved: listed(code.unresolved, max, (flow) => ({ at: formatC64Address(flow.at), kind: flow.kind })),
|
|
1495
|
+
};
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
const UNKNOWN_HINT = "The code in unknownCode stays in the build: no run executed it, and a flow in unknownCode.unresolved can go to it. Find the targets of each flow in the emulator. Record a jump reference from the flow to each target in the project knowledge, also to an address outside the program. Then run the command again.";
|
|
1499
|
+
|
|
1506
1500
|
/** Every file in a folder with its path in it, with / between the parts, in path order. `skip` leaves out a folder by its path. */
|
|
1507
1501
|
function filesIn(root: string, skip: (path: string) => boolean, folder = ""): Array<{ path: string; bytes: Buffer }> {
|
|
1508
1502
|
const found: Array<{ path: string; bytes: Buffer }> = [];
|
|
@@ -1730,6 +1724,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
|
|
|
1730
1724
|
...(knowledge.coverage === undefined ? { noCoverage: "The knowledge has no coverage, so nothing became free by itself. Only --drop makes a range free." } : {}),
|
|
1731
1725
|
free: { bytes: freeBytes, ...listed(free, max, (range) => ({ ...shownRange(range), bytes: range.end - range.start + 1, what: range.what, label: freeName(range) })) },
|
|
1732
1726
|
unreachableExecuted: listed(plan.unreachableExecuted, max, (range) => ({ ...shownRange(range), ...(range.routine === undefined ? {} : { routine: range.routine }), drop: `--drop '${formatC64Address(range.start)}-${formatC64Address(range.end)}'` })),
|
|
1727
|
+
...(plan.unknown.length === 0 ? {} : { unknownCode: showUnknown(plan, max) }),
|
|
1733
1728
|
knowledge: kept,
|
|
1734
1729
|
tests: { written: tests.map((test) => test.file), leftOut: listed(testsLeftOut, max, (item) => item) },
|
|
1735
1730
|
...(spacesLeftOut.length === 0 ? {} : { spacesLeftOut }),
|
|
@@ -1790,6 +1785,7 @@ function generateReply(call: Call, body: Record<string, unknown>): Reply {
|
|
|
1790
1785
|
}
|
|
1791
1786
|
if ((body.loader as { verified?: boolean } | undefined)?.verified === false) steps.push("The loader is not verified. Read loader.reason, loader.differences and loader.stop.");
|
|
1792
1787
|
if ((body.leftovers as { noCoverage?: string } | undefined)?.noCoverage !== undefined && call.flag("loader")) steps.push("To leave out the bytes that nothing uses, put the coverage of the runs into the project knowledge. Then generate again.");
|
|
1788
|
+
if (body.unknownCode !== undefined) steps.push(UNKNOWN_HINT);
|
|
1793
1789
|
if (body.dataOnly !== undefined) {
|
|
1794
1790
|
steps.push("The source has only data. If the space has code, give --entry, or record a code region in the project knowledge.");
|
|
1795
1791
|
again = true;
|
|
@@ -1831,6 +1827,7 @@ function exportReply(body: Record<string, unknown>): Reply {
|
|
|
1831
1827
|
const steps = ["Build and test the new project as its README.md tells."];
|
|
1832
1828
|
if (body.noCoverage !== undefined) steps.push("To make unused code and data free, put the coverage of a run into the project knowledge. Then remove the new folder and its zip file, and export again.");
|
|
1833
1829
|
if (((body.unreachableExecuted as { count: number } | undefined)?.count ?? 0) > 0) steps.push("To make the code in unreachableExecuted free, remove the new folder and its zip file. Then export again with the drop value of the code.");
|
|
1830
|
+
if (body.unknownCode !== undefined) steps.push(UNKNOWN_HINT.replace("Then run the command again.", "Then remove the new folder and its zip file, and export again."));
|
|
1834
1831
|
if ([body.free, body.unreachableExecuted, body.operandsAsNumbers, body.macrosAsInstructions, (body.tests as { leftOut?: unknown } | undefined)?.leftOut].some(isCut)) steps.push("To see all items of a list, give a larger --max-listed.");
|
|
1835
1832
|
return reply(body, { hint: steps.join(" ") });
|
|
1836
1833
|
}
|
|
@@ -1842,7 +1839,7 @@ await runScript({
|
|
|
1842
1839
|
commands: [
|
|
1843
1840
|
{
|
|
1844
1841
|
name: "generate",
|
|
1845
|
-
summary: "Writes the source files to --out and checks them.
|
|
1842
|
+
summary: "Writes the source files to --out and checks them. result is PASS when every check passes, else FAIL.",
|
|
1846
1843
|
options: {
|
|
1847
1844
|
out: { ...OPTIONS.out, output: "folder", value: "<dir>", help: "the folder for the source files, relative to the project folder", required: true },
|
|
1848
1845
|
entry: { ...OPTIONS.entry, multiple: true, help: "an address where code starts. The entry of the program, the routines and the code regions of the knowledge are entry points too" },
|
|
@@ -1851,7 +1848,7 @@ await runScript({
|
|
|
1851
1848
|
"analyzer-names": { kind: "flag", help: "name an address that has no name of the user or the LLM, and no platform name, with its analyzer name" },
|
|
1852
1849
|
"max-listed": OPTIONS["max-listed"],
|
|
1853
1850
|
},
|
|
1854
|
-
notes: "The program, its entry state and the coverage come from the knowledge: put them into the project knowledge first. Code that no imported run executed is marked and listed,
|
|
1851
|
+
notes: "The program, its entry state and the coverage come from the knowledge: put them into the project knowledge first. Code that no imported run executed is marked and listed, each range with its file and the routine before it. Without --analyzer-names, an address without a name gets a name of the source, for example l_17e2.",
|
|
1855
1852
|
run: async (call) => {
|
|
1856
1853
|
const { output, failed, removed } = await generate(call);
|
|
1857
1854
|
// A file of an earlier run that this run removed and did not write again.
|