@henols/c64-re-tools 2.3.0-rc.1 → 2.3.0-rc.3
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 +2 -3
- package/skills/c64-assembler/SKILL.md +4 -6
- package/skills/c64-basic/SKILL.md +2 -4
- package/skills/c64-development/SKILL.md +3 -3
- package/skills/c64-disk/SKILL.md +3 -7
- package/skills/c64-docs/SKILL.md +2 -4
- package/skills/c64-export/SKILL.md +4 -4
- package/skills/c64-knowledge/SKILL.md +3 -3
- package/skills/c64-memory-map/SKILL.md +1 -3
- package/skills/c64-packer/SKILL.md +9 -11
- package/skills/c64-packer/scripts/packer.ts +2 -20
- package/skills/c64-provenance/SKILL.md +18 -7
- package/skills/c64-provenance/scripts/lib/compare.ts +144 -16
- package/skills/c64-provenance/scripts/provenance.ts +37 -8
- package/skills/c64-reverse-engineering/SKILL.md +3 -3
- package/skills/c64-source/SKILL.md +37 -18
- package/skills/c64-source/scripts/lib/loader.ts +281 -43
- package/skills/c64-source/scripts/source.ts +37 -9
- package/skills/c64-static-analysis/SKILL.md +4 -4
- package/skills/c64-testing/SKILL.md +13 -13
- package/skills/c64-testing/references/recording-format.md +1 -1
- package/skills/c64-testing/references/scenario-format.md +3 -3
- package/skills/c64-testing/scripts/lib/play.ts +4 -4
- package/skills/c64-testing/scripts/testing.ts +1 -1
- package/skills/c64-unpacker/SKILL.md +12 -12
- package/skills/c64-unpacker/scripts/lib/loads.ts +17 -4
- package/skills/c64-unpacker/scripts/unpacker.ts +15 -3
- package/skills/emulator/SKILL.md +3 -3
- package/src/cli/cleanup.ts +30 -0
- package/src/cli/main.ts +5 -1
- package/src/compare.ts +18 -0
- package/src/host-client/coverage.ts +26 -0
- package/src/mcp/tools/machine.ts +2 -2
- package/README.md +0 -143
|
@@ -5,12 +5,17 @@
|
|
|
5
5
|
// pointer, A, X, Y and the flags, and jumps to the entry. The copies run
|
|
6
6
|
// from a free page with SEI and all RAM visible, in an order where no copy
|
|
7
7
|
// overwrites the packed bytes of a copy that has not run yet. The plan is
|
|
8
|
-
// simulated here before the emulator runs it.
|
|
8
|
+
// simulated here before the emulator runs it. An image too large for one
|
|
9
|
+
// loader file gets the packed form: Exomizer unpacks the program and the
|
|
10
|
+
// copier, and the copier writes only pages $0002-$03ff.
|
|
9
11
|
|
|
10
|
-
import { type AddressRange, formatC64Address, formatC64Byte } from "#src/c64.ts";
|
|
12
|
+
import { type AddressRange, formatC64Address, formatC64Byte, prgRange } from "#src/c64.ts";
|
|
13
|
+
import { compareBuild, mergedPrograms } from "#src/compare.ts";
|
|
11
14
|
import { Refusal } from "#src/errors.ts";
|
|
12
15
|
import { parseEntryState } from "#src/host-client/entry-state.ts";
|
|
13
16
|
import { WireFailure } from "#src/host-client/tools.ts";
|
|
17
|
+
import { pack } from "#src/native/exomizer.ts";
|
|
18
|
+
import type { ToolContext } from "#src/native/run.ts";
|
|
14
19
|
|
|
15
20
|
export interface EntryState {
|
|
16
21
|
pc: number;
|
|
@@ -104,6 +109,8 @@ export interface LoaderPlan {
|
|
|
104
109
|
text: string;
|
|
105
110
|
/** The CIA timers and masks that the loader sets, when the entry state has them. */
|
|
106
111
|
cia?: CiaPlan;
|
|
112
|
+
/** The packed form: loader.asm holds only the copier and pages 0-3 from `start` to `end`, and Exomizer packs it with the build of main.asm. */
|
|
113
|
+
packed?: { start: number };
|
|
107
114
|
}
|
|
108
115
|
|
|
109
116
|
/**
|
|
@@ -185,15 +192,19 @@ const underRom = (address: number) => (address >= 0xa000 && address <= 0xbfff) |
|
|
|
185
192
|
/**
|
|
186
193
|
* Why a loader stopped before its jump, from the RAM after the stop: the first
|
|
187
194
|
* byte of the moved copier that is not the byte of the loader file, else, when
|
|
188
|
-
* the copier ran, the first byte that a copy did not write as planned.
|
|
195
|
+
* the copier ran, the first byte that a copy did not write as planned. In the
|
|
196
|
+
* packed form the unpack puts the copier in place, and `fileByte` gives the
|
|
197
|
+
* build of loader.asm.
|
|
189
198
|
*/
|
|
190
199
|
export function stopCause(ram: Uint8Array, plan: LoaderPlan, copierSource: number, fileByte: (address: number) => number, copied: boolean, expected: (address: number) => number): string | undefined {
|
|
191
200
|
for (let offset = 0; offset <= plan.end - copierSource; offset++) {
|
|
192
201
|
const got = ram[plan.copier + offset]!;
|
|
193
202
|
const wanted = fileByte(copierSource + offset);
|
|
194
203
|
if (got === wanted) continue;
|
|
204
|
+
const at = formatC64Address(plan.copier + offset);
|
|
205
|
+
if (plan.packed !== undefined) return `The copier at ${at} holds ${formatC64Byte(got)}, not ${formatC64Byte(wanted)} of the build of loader.asm: the unpack did not write it.`;
|
|
195
206
|
const rom = underRom(copierSource + offset) ? `; ${formatC64Address(copierSource + offset)} is under a ROM, so the move read the ROM` : "";
|
|
196
|
-
return `The copier at ${
|
|
207
|
+
return `The copier at ${at} holds ${formatC64Byte(got)}, not ${formatC64Byte(wanted)} from ${formatC64Address(copierSource + offset)} of the loader file${rom}.`;
|
|
197
208
|
}
|
|
198
209
|
if (!copied) return undefined;
|
|
199
210
|
for (const copy of plan.copies) {
|
|
@@ -380,11 +391,33 @@ const plus = (label: string, offset: number) => (offset === 0 ? label : `${label
|
|
|
380
391
|
/** The label of the copier in the loader file, which the stub moves to its two pages. */
|
|
381
392
|
export const COPIER_SOURCE = "loader_copier_src";
|
|
382
393
|
|
|
383
|
-
/**
|
|
394
|
+
/** A block of the loader: a segment with its files, or bytes of pages 0-3. */
|
|
395
|
+
interface Block {
|
|
396
|
+
what: string;
|
|
397
|
+
range: AddressRange;
|
|
398
|
+
files?: string[];
|
|
399
|
+
pseudo: number;
|
|
400
|
+
bytes: (address: number) => number;
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/** The block's bytes as !byte lines of 16. */
|
|
404
|
+
function byteLines(range: AddressRange, bytes: (address: number) => number): string[] {
|
|
405
|
+
const lines: string[] = [];
|
|
406
|
+
for (let address = range.start; address <= range.end; address += 16) {
|
|
407
|
+
const last = Math.min(range.end, address + 15);
|
|
408
|
+
lines.push(` !byte ${Array.from({ length: last - address + 1 }, (_, offset) => formatC64Byte(bytes(address + offset))).join(",")}`);
|
|
409
|
+
}
|
|
410
|
+
return lines;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* Plans the loader: the packed layout, the copy order and the copier page, and writes loader.asm.
|
|
415
|
+
* An image too large for one loader file gets the packed form (see planPacked). Refuses by name when no plan exists.
|
|
416
|
+
*/
|
|
384
417
|
export function planLoader(input: LoaderInput): LoaderPlan {
|
|
385
418
|
const { state } = input;
|
|
386
419
|
// What the copies write: each segment without $00/$01, which the loader sets last, and pages $0002-$03ff where no segment is.
|
|
387
|
-
const blocks:
|
|
420
|
+
const blocks: Block[] = [];
|
|
388
421
|
for (const segment of input.segments) blocks.push({ what: `segment ${show(segment)}`, range: segment, files: segment.files, pseudo: segment.start, bytes: input.byteAt });
|
|
389
422
|
for (const part of subtract({ start: 0x0002, end: 0x03ff }, input.segments)) {
|
|
390
423
|
blocks.push({ what: `entry state ${show(part)}`, range: part, pseudo: part.start, bytes: (address) => state.pages[address]! });
|
|
@@ -408,13 +441,14 @@ export function planLoader(input: LoaderInput): LoaderPlan {
|
|
|
408
441
|
}
|
|
409
442
|
const cia = ciaSection(state);
|
|
410
443
|
const ciaSize = cia === undefined ? 0 : cia.ops.reduce((sum, op) => sum + op.bytes, 0);
|
|
444
|
+
const codeSize = COPIER_CODE_SIZE + (state.vic === undefined ? 0 : VIC_SIZE) + ciaSize;
|
|
445
|
+
const copierImage = at;
|
|
446
|
+
const end = copierImage + codeSize + COPY_ENTRY * plain.length + 2 - 1;
|
|
447
|
+
// The end can be past $ffff, which is no address.
|
|
448
|
+
if (end > LOAD_LIMIT) return planPacked(input, blocks, cia, codeSize, `The plain loader would end ${end > 0xffff ? "past $ffff" : `at ${formatC64Address(end)}`}, after ${formatC64Address(LOAD_LIMIT)}: loading it would write the I/O area.`);
|
|
411
449
|
// The CIA part takes room from the copy table in the copier's two pages.
|
|
412
|
-
const maxCopies = Math.min(MAX_COPIES, Math.floor((COPIER_LIMIT -
|
|
450
|
+
const maxCopies = Math.min(MAX_COPIES, Math.floor((COPIER_LIMIT - codeSize - 2) / COPY_ENTRY));
|
|
413
451
|
if (plain.length > maxCopies) throw new WireFailure("invalid-input", `The loader needs ${plain.length} copies; it can do at most ${maxCopies}. Join segments in the unpacker capture (--range) or write the loader by hand.`);
|
|
414
|
-
const copierImage = at;
|
|
415
|
-
const copierSize = COPIER_CODE_SIZE + (state.vic === undefined ? 0 : VIC_SIZE) + ciaSize + COPY_ENTRY * plain.length + 2;
|
|
416
|
-
const end = copierImage + copierSize - 1;
|
|
417
|
-
if (end > LOAD_LIMIT) throw new WireFailure("invalid-input", `The loader would end at ${formatC64Address(end)}, after ${formatC64Address(LOAD_LIMIT)}: loading it would write the I/O area. The image is too large for one loader file.`);
|
|
418
452
|
|
|
419
453
|
const order = copyOrder(plain);
|
|
420
454
|
if (order === undefined) {
|
|
@@ -456,20 +490,245 @@ export function planLoader(input: LoaderInput): LoaderPlan {
|
|
|
456
490
|
for (const block of blocks) {
|
|
457
491
|
lines.push("", `; ${block.what}`, blockLabel(block.range.start, "from"), `!pseudopc ${formatC64Address(block.pseudo)} {`, blockLabel(block.range.start, "to"));
|
|
458
492
|
if (block.files !== undefined) for (const file of block.files) lines.push(`!source "${file}"`);
|
|
459
|
-
else
|
|
460
|
-
for (let address = block.range.start; address <= block.range.end; address += 16) {
|
|
461
|
-
const last = Math.min(block.range.end, address + 15);
|
|
462
|
-
lines.push(` !byte ${Array.from({ length: last - address + 1 }, (_, offset) => formatC64Byte(block.bytes(address + offset))).join(",")}`);
|
|
463
|
-
}
|
|
464
|
-
}
|
|
493
|
+
else lines.push(...byteLines(block.range, block.bytes));
|
|
465
494
|
lines.push("}", blockLabel(block.range.start, "end"));
|
|
466
495
|
}
|
|
467
|
-
|
|
468
|
-
lines.push(
|
|
496
|
+
lines.push("", `; The copier runs at ${formatC64Address(copier)}. The flags pass through ${formatC64Address(stackByte)}, the free stack byte below the stack pointer.`, COPIER_SOURCE, `!pseudopc ${formatC64Address(copier)} {`);
|
|
497
|
+
lines.push(...copierLines(state, cia, stackByte, input.entryName ?? formatC64Address(input.entry)));
|
|
498
|
+
copies.forEach((copy, index) => {
|
|
499
|
+
// A block that starts at $0000 skips $00/$01, which the loader sets last.
|
|
500
|
+
const start = copyBlocks[index]!;
|
|
501
|
+
const skip = copy.target.start - start;
|
|
502
|
+
const [from, end, to] = [blockLabel(start, "from"), blockLabel(start, "end"), blockLabel(start, "to")];
|
|
503
|
+
const length = skip === 0 ? `${end} - ${from}` : `${end} - ${from} - ${skip}`;
|
|
504
|
+
const read = copy.backward ? `${end} - 1` : plus(from, skip);
|
|
505
|
+
const write = copy.backward ? `${to} + ${end} - ${from} - 1` : plus(to, skip);
|
|
506
|
+
lines.push(` !word ${length}, ${read}, ${write} : !byte ${copy.backward ? 1 : 0} ; ${copy.what}`);
|
|
507
|
+
});
|
|
508
|
+
lines.push(" !word 0", "}", "}");
|
|
509
|
+
|
|
510
|
+
return {
|
|
511
|
+
blocks: blocks.map((block, index) => ({ what: block.what, range: block.range, packedAt: packedAt[index]!, bytes: block.bytes })),
|
|
512
|
+
copies,
|
|
513
|
+
copier,
|
|
514
|
+
stackByte,
|
|
515
|
+
end,
|
|
516
|
+
text: `${lines.join("\n")}\n`,
|
|
517
|
+
...(cia === undefined ? {} : { cia: cia.plan }),
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
/** Where the packed form puts its copier with the bytes of pages 0-3: the copier sets $01 to $35 and to the entry's value, so it is not under a ROM or the I/O area. */
|
|
522
|
+
const PACKED_AREAS: readonly AddressRange[] = [
|
|
523
|
+
{ start: 0x0400, end: 0x9fff },
|
|
524
|
+
{ start: 0xc000, end: 0xcfff },
|
|
525
|
+
];
|
|
526
|
+
/** The free ranges that a refusal of the packed form names. */
|
|
527
|
+
const SHOWN_FREE = 8;
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* The packed form of the loader, for an image too large for one loader file:
|
|
531
|
+
* Exomizer packs the build of main.asm (from $0400) and the build of
|
|
532
|
+
* loader.asm into loader.prg, which starts at the copier with all RAM
|
|
533
|
+
* visible ($01 = $34). loader.asm holds only the copier, in one free range,
|
|
534
|
+
* and the bytes of pages $0002-$03ff, in pieces in the free ranges: the
|
|
535
|
+
* unpacker of Exomizer uses the zero page and $0334-$03ff, so the copier
|
|
536
|
+
* writes them after the unpack. Between its ranges, loader.asm holds the
|
|
537
|
+
* bytes of the image, so its build does not change a segment.
|
|
538
|
+
*/
|
|
539
|
+
function planPacked(input: LoaderInput, blocks: Block[], cia: ReturnType<typeof ciaSection>, codeSize: number, tooLarge: string): LoaderPlan {
|
|
540
|
+
const { state } = input;
|
|
541
|
+
// The parts below $0400 without $00/$01, which the loader sets last.
|
|
542
|
+
const low = blocks.flatMap((block) => {
|
|
543
|
+
const range = { start: Math.max(block.range.start, 0x0002), end: Math.min(block.range.end, 0x03ff) };
|
|
544
|
+
if (range.start > range.end) return [];
|
|
545
|
+
const cut = range.start !== block.range.start || range.end !== block.range.end;
|
|
546
|
+
return [{ what: cut ? `${block.what}, part ${show(range)}` : block.what, range, bytes: block.bytes }];
|
|
547
|
+
});
|
|
548
|
+
const lowBytes = low.reduce((sum, block) => sum + block.range.end - block.range.start + 1, 0);
|
|
549
|
+
const free = PACKED_AREAS.flatMap((area) => subtract(area, input.segments));
|
|
550
|
+
const placed = placePacked(free, low, codeSize);
|
|
551
|
+
if ("refusal" in placed) {
|
|
552
|
+
const largest = [...free].sort((a, b) => b.end - b.start - (a.end - a.start)).slice(0, SHOWN_FREE);
|
|
553
|
+
const ranges = largest.length === 0 ? "none" : largest.map((range) => `${show(range)} (${range.end - range.start + 1} bytes)`).join(", ");
|
|
554
|
+
const why =
|
|
555
|
+
placed.refusal === "copies"
|
|
556
|
+
? `A packed loader needs more than ${MAX_PACKED_COPIES} copies for the ${lowBytes} bytes of pages 0-3 in the free ranges.`
|
|
557
|
+
: `A packed loader needs one free range of ${codeSize + COPY_ENTRY * Math.max(low.length, 1) + 2} bytes or more for its copier, and ${lowBytes} more free bytes for pages 0-3, in $0400-$9fff or $c000-$cfff outside the segments.`;
|
|
558
|
+
throw new WireFailure("invalid-input", `${tooLarge} ${why} The largest free ranges there: ${ranges}. Write the loader by hand.`);
|
|
559
|
+
}
|
|
560
|
+
const { copier, pieces } = placed;
|
|
561
|
+
const copierEnd = copier + codeSize + COPY_ENTRY * pieces.length + 2 - 1;
|
|
562
|
+
// The sources are at $0400 or higher and the targets below: any order works.
|
|
563
|
+
const copies: Copy[] = pieces.map((piece) => ({ what: piece.what, target: piece.target, source: { start: piece.at, end: piece.at + piece.target.end - piece.target.start }, backward: false }));
|
|
564
|
+
const start = Math.min(copier, ...pieces.map((piece) => piece.at));
|
|
565
|
+
const end = Math.max(copierEnd, ...copies.map((copy) => copy.source.end));
|
|
566
|
+
const stackByte = 0x0100 + state.sp;
|
|
567
|
+
const lines: string[] = [
|
|
568
|
+
...input.header.map((line) => `; ${line}`),
|
|
569
|
+
"; The image is too large for one loader file, so this is the packed form. c64-packer packs the",
|
|
570
|
+
`; build of main.asm and the build of this file into loader.prg, with --entry '${formatC64Address(copier)}' and --exit-memory '$34'.`,
|
|
571
|
+
"; The unpacker of Exomizer uses the zero page and $0334-$03ff, so the copier writes pages $0002-$03ff after the unpack.",
|
|
469
572
|
"",
|
|
573
|
+
"!cpu 6510",
|
|
574
|
+
];
|
|
575
|
+
// The parts in address order: the copier, the pieces of pages 0-3, and the bytes of the image between them.
|
|
576
|
+
const parts: Array<{ range: AddressRange; text: string[] }> = [];
|
|
577
|
+
const copierText = [
|
|
470
578
|
`; The copier runs at ${formatC64Address(copier)}. The flags pass through ${formatC64Address(stackByte)}, the free stack byte below the stack pointer.`,
|
|
579
|
+
`* = ${formatC64Address(copier)}`,
|
|
471
580
|
COPIER_SOURCE,
|
|
472
|
-
|
|
581
|
+
// The entry by its address: main.asm, which has its label, is not in this build.
|
|
582
|
+
...copierLines(state, cia, stackByte, `${formatC64Address(input.entry)}${input.entryName === undefined ? "" : ` ; ${input.entryName} in main.asm`}`),
|
|
583
|
+
];
|
|
584
|
+
for (const copy of copies) {
|
|
585
|
+
const [from, to] = [blockLabel(copy.target.start, "from"), blockLabel(copy.target.start, "end")];
|
|
586
|
+
copierText.push(` !word ${to} - ${from}, ${from}, ${formatC64Address(copy.target.start)} : !byte 0 ; ${copy.what}`);
|
|
587
|
+
}
|
|
588
|
+
copierText.push(" !word 0", "}");
|
|
589
|
+
parts.push({ range: { start: copier, end: copierEnd }, text: copierText });
|
|
590
|
+
for (const piece of pieces) {
|
|
591
|
+
const range = { start: piece.at, end: piece.at + piece.target.end - piece.target.start };
|
|
592
|
+
const text = [`; ${piece.what}`, `* = ${formatC64Address(piece.at)}`, blockLabel(piece.target.start, "from"), ...byteLines(piece.target, piece.bytes), blockLabel(piece.target.start, "end")];
|
|
593
|
+
parts.push({ range, text });
|
|
594
|
+
}
|
|
595
|
+
const used = parts.map((part) => part.range);
|
|
596
|
+
for (const segment of input.segments) {
|
|
597
|
+
const within = { start: Math.max(segment.start, start), end: Math.min(segment.end, end) };
|
|
598
|
+
if (within.start > within.end) continue;
|
|
599
|
+
for (const range of subtract(within, used)) {
|
|
600
|
+
parts.push({ range, text: [`; The bytes of the image at ${show(range)}, so the build of this file does not change them`, `* = ${formatC64Address(range.start)}`, ...byteLines(range, input.byteAt)] });
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
parts.sort((a, b) => a.range.start - b.range.start);
|
|
604
|
+
for (const part of parts) lines.push("", ...part.text);
|
|
605
|
+
return {
|
|
606
|
+
blocks: pieces.map((piece) => ({ what: piece.what, range: piece.target, packedAt: piece.at, bytes: piece.bytes })),
|
|
607
|
+
copies,
|
|
608
|
+
copier,
|
|
609
|
+
stackByte,
|
|
610
|
+
end,
|
|
611
|
+
text: `${lines.join("\n")}\n`,
|
|
612
|
+
...(cia === undefined ? {} : { cia: cia.plan }),
|
|
613
|
+
packed: { start },
|
|
614
|
+
};
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/** The copy table of the packed form: X indexes it, so it fits in 256 bytes. */
|
|
618
|
+
const MAX_PACKED_COPIES = Math.floor((256 - 2) / COPY_ENTRY);
|
|
619
|
+
|
|
620
|
+
/** A piece of pages 0-3 in the packed form: its target and where the copier reads it. */
|
|
621
|
+
interface Piece {
|
|
622
|
+
what: string;
|
|
623
|
+
target: AddressRange;
|
|
624
|
+
at: number;
|
|
625
|
+
bytes: (address: number) => number;
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
/**
|
|
629
|
+
* Puts the parts of pages 0-3 into the free ranges, in their order: each time
|
|
630
|
+
* into the nearest range that holds the rest, else into the largest range.
|
|
631
|
+
* A part that does not fit in one range is split, and each piece is a copy.
|
|
632
|
+
* Undefined when the ranges are too small.
|
|
633
|
+
*/
|
|
634
|
+
function placePieces(ranges: AddressRange[], low: ReadonlyArray<{ what: string; range: AddressRange; bytes: (address: number) => number }>, distance: (range: AddressRange) => number): Piece[] | undefined {
|
|
635
|
+
const left = ranges.map((range) => ({ ...range }));
|
|
636
|
+
const pieces: Piece[] = [];
|
|
637
|
+
let rest = low.reduce((sum, block) => sum + block.range.end - block.range.start + 1, 0);
|
|
638
|
+
const length = (range: AddressRange) => range.end - range.start + 1;
|
|
639
|
+
let target: AddressRange | undefined;
|
|
640
|
+
for (const block of low) {
|
|
641
|
+
let next = block.range.start;
|
|
642
|
+
while (next <= block.range.end) {
|
|
643
|
+
if (target === undefined || target.start > target.end) {
|
|
644
|
+
const open = left.filter((range) => range.start <= range.end);
|
|
645
|
+
if (open.length === 0) return undefined;
|
|
646
|
+
const holding = open.filter((range) => length(range) >= rest).sort((a, b) => distance(a) - distance(b));
|
|
647
|
+
target = holding[0] ?? open.sort((a, b) => length(b) - length(a))[0]!;
|
|
648
|
+
}
|
|
649
|
+
const count = Math.min(block.range.end - next + 1, length(target));
|
|
650
|
+
const part = { start: next, end: next + count - 1 };
|
|
651
|
+
const cut = part.start !== block.range.start || part.end !== block.range.end;
|
|
652
|
+
pieces.push({ what: cut ? `${block.what}, bytes ${show(part)}` : block.what, target: part, at: target.start, bytes: block.bytes });
|
|
653
|
+
target.start += count;
|
|
654
|
+
next += count;
|
|
655
|
+
rest -= count;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
return pieces;
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* Where the packed form puts its copier and the pieces of pages 0-3: the copier
|
|
663
|
+
* in one free range, a free page of the plain copier first, else the start of a
|
|
664
|
+
* free range. The placement with the fewest pieces wins, then the one with the
|
|
665
|
+
* shortest build of loader.asm.
|
|
666
|
+
*/
|
|
667
|
+
function placePacked(free: AddressRange[], low: Parameters<typeof placePieces>[1], codeSize: number): { copier: number; pieces: Piece[] } | { refusal: "room" | "copies" } {
|
|
668
|
+
const candidates = [...COPIER_PAGES, ...free.map((range) => range.start)];
|
|
669
|
+
// The table has one entry per piece: a split can make the copier larger, so the room for the table grows until it holds every piece.
|
|
670
|
+
for (let copies = Math.max(low.length, 1); copies <= MAX_PACKED_COPIES; ) {
|
|
671
|
+
const size = codeSize + COPY_ENTRY * copies + 2;
|
|
672
|
+
let best: { copier: number; pieces: Piece[]; span: number } | undefined;
|
|
673
|
+
for (const copier of candidates) {
|
|
674
|
+
const range = { start: copier, end: copier + size - 1 };
|
|
675
|
+
if (!free.some((area) => range.start >= area.start && range.end <= area.end)) continue;
|
|
676
|
+
// A piece goes to the start of its range: a range below the copier adds its whole length to the build.
|
|
677
|
+
const distance = (other: AddressRange) => (other.end < range.start ? range.start - other.start : other.start - range.end);
|
|
678
|
+
const pieces = placePieces(free.flatMap((area) => subtract(area, [range])), low, distance);
|
|
679
|
+
if (pieces === undefined) continue;
|
|
680
|
+
const span = Math.max(range.end, ...pieces.map((piece) => piece.at + piece.target.end - piece.target.start)) - Math.min(copier, ...pieces.map((piece) => piece.at));
|
|
681
|
+
if (best === undefined || pieces.length < best.pieces.length || (pieces.length === best.pieces.length && span < best.span)) best = { copier, pieces, span };
|
|
682
|
+
}
|
|
683
|
+
if (best === undefined) return { refusal: "room" };
|
|
684
|
+
if (best.pieces.length <= copies) return best;
|
|
685
|
+
copies = best.pieces.length;
|
|
686
|
+
}
|
|
687
|
+
return { refusal: "copies" };
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/** What Exomizer makes of a packed loader. */
|
|
691
|
+
export interface PackedLoader {
|
|
692
|
+
/** loader.prg: it loads at $0801 and starts with RUN. */
|
|
693
|
+
program: Buffer;
|
|
694
|
+
packedBytes: number;
|
|
695
|
+
unpackedBytes: number;
|
|
696
|
+
/** The CPU cycles of the unpack, when Exomizer gives them. */
|
|
697
|
+
cycles?: number;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/**
|
|
701
|
+
* Packs the build of main.asm from $0400 and the build of loader.asm (the
|
|
702
|
+
* copier wins where they overlap) with the entry at the copier and $01 = $34,
|
|
703
|
+
* and checks the unpack in the emulator of Exomizer: every byte of the two
|
|
704
|
+
* builds, and the jump to the copier. Refuses by name when it does not hold.
|
|
705
|
+
*/
|
|
706
|
+
export async function packLoader(main: Uint8Array, copier: Uint8Array, plan: LoaderPlan, context: ToolContext): Promise<PackedLoader> {
|
|
707
|
+
// The unpacker uses pages 0-3; the copier writes them.
|
|
708
|
+
const program = prgRange(main);
|
|
709
|
+
const skip = Math.max(0, 0x0400 - program.start);
|
|
710
|
+
const parts = [...(skip < program.body.length ? [{ start: program.start + skip, body: program.body.subarray(skip) }] : []), prgRange(copier)];
|
|
711
|
+
const prg = (part: { start: number; body: Uint8Array }) => Buffer.concat([Buffer.from([part.start & 0xff, part.start >> 8]), part.body]);
|
|
712
|
+
const packed = await pack({ programs: parts.map(prg), entry: plan.copier, exitMemory: 0x34 }, context);
|
|
713
|
+
if (packed.entry !== plan.copier) throw new WireFailure("operation-failed", `The unpack in the emulator of Exomizer jumps to ${formatC64Address(packed.entry)}, not to the copier at ${formatC64Address(plan.copier)}.`);
|
|
714
|
+
const reference = mergedPrograms(parts);
|
|
715
|
+
const wrong = compareBuild(packed.unpacked, reference).segments.find((segment) => segment.result !== "identical");
|
|
716
|
+
if (wrong !== undefined) {
|
|
717
|
+
const first = wrong.firstDifference === undefined ? "" : `: the first is ${wrong.firstDifference.address}, ${wrong.firstDifference.built} and not ${wrong.firstDifference.reference}`;
|
|
718
|
+
throw new WireFailure("operation-failed", `The unpack in the emulator of Exomizer does not give ${wrong.start}-${wrong.end} of main.asm and loader.asm (${wrong.result}${first}).`);
|
|
719
|
+
}
|
|
720
|
+
const unpackedBytes = reference.segments.reduce((sum, segment) => sum + segment.end - segment.start + 1, 0);
|
|
721
|
+
return { program: packed.program, packedBytes: packed.program.length, unpackedBytes, ...(packed.cycles === undefined ? {} : { cycles: packed.cycles }) };
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/**
|
|
725
|
+
* The copier: its copies by the table, the VIC-II and CIA parts, then $00/$01,
|
|
726
|
+
* the stack pointer, the flags and A/X/Y, and the jump to the entry. It ends
|
|
727
|
+
* with the label of the table; the caller writes the table and closes the zone.
|
|
728
|
+
*/
|
|
729
|
+
function copierLines(state: EntryState, cia: ReturnType<typeof ciaSection>, stackByte: number, jumpTarget: string): string[] {
|
|
730
|
+
const [port0, port1] = state.port;
|
|
731
|
+
return [
|
|
473
732
|
"!zone loader_copier {",
|
|
474
733
|
" lda #$34",
|
|
475
734
|
" sta $01",
|
|
@@ -540,7 +799,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
|
|
|
540
799
|
` ldy #${formatC64Byte(state.y)}`,
|
|
541
800
|
" plp",
|
|
542
801
|
// A global label: the check of the loader stops here, before an interrupt can run.
|
|
543
|
-
`${LOADER_JUMP} jmp ${
|
|
802
|
+
`${LOADER_JUMP} jmp ${jumpTarget}`,
|
|
544
803
|
".count !word 0",
|
|
545
804
|
".index !byte 0",
|
|
546
805
|
".back !byte 0",
|
|
@@ -551,28 +810,7 @@ export function planLoader(input: LoaderInput): LoaderPlan {
|
|
|
551
810
|
`.vicval !byte ${VIC_DISPLAY_REGISTERS.map((item) => formatC64Byte(state.vic!.registers[item.register]!)).join(",")}`,
|
|
552
811
|
]),
|
|
553
812
|
".table",
|
|
554
|
-
|
|
555
|
-
copies.forEach((copy, index) => {
|
|
556
|
-
// A block that starts at $0000 skips $00/$01, which the loader sets last.
|
|
557
|
-
const start = copyBlocks[index]!;
|
|
558
|
-
const skip = copy.target.start - start;
|
|
559
|
-
const [from, end, to] = [blockLabel(start, "from"), blockLabel(start, "end"), blockLabel(start, "to")];
|
|
560
|
-
const length = skip === 0 ? `${end} - ${from}` : `${end} - ${from} - ${skip}`;
|
|
561
|
-
const read = copy.backward ? `${end} - 1` : plus(from, skip);
|
|
562
|
-
const write = copy.backward ? `${to} + ${end} - ${from} - 1` : plus(to, skip);
|
|
563
|
-
lines.push(` !word ${length}, ${read}, ${write} : !byte ${copy.backward ? 1 : 0} ; ${copy.what}`);
|
|
564
|
-
});
|
|
565
|
-
lines.push(" !word 0", "}", "}");
|
|
566
|
-
|
|
567
|
-
return {
|
|
568
|
-
blocks: blocks.map((block, index) => ({ what: block.what, range: block.range, packedAt: packedAt[index]!, bytes: block.bytes })),
|
|
569
|
-
copies,
|
|
570
|
-
copier,
|
|
571
|
-
stackByte,
|
|
572
|
-
end,
|
|
573
|
-
text: `${lines.join("\n")}\n`,
|
|
574
|
-
...(cia === undefined ? {} : { cia: cia.plan }),
|
|
575
|
-
};
|
|
813
|
+
];
|
|
576
814
|
}
|
|
577
815
|
|
|
578
816
|
/**
|
|
@@ -13,7 +13,7 @@ import { createHash } from "node:crypto";
|
|
|
13
13
|
import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
14
14
|
import { basename, join, relative, sep } from "node:path";
|
|
15
15
|
|
|
16
|
-
import { Refusal } from "#src/errors.ts";
|
|
16
|
+
import { isRefusal, Refusal } from "#src/errors.ts";
|
|
17
17
|
import { type AddressRange, coverageSeedKinds, findHandoffs, formatC64Address, parseTokenized, textToPetscii } from "#src/c64.ts";
|
|
18
18
|
import { autostartLoaded, RUN_LIMIT_FRAMES } from "#src/host-client/autostart.ts";
|
|
19
19
|
import { readImage, type Image } from "#src/host-client/image.ts";
|
|
@@ -38,7 +38,7 @@ import { isoCet } from "#src/time.ts";
|
|
|
38
38
|
import { zipFiles } from "#src/zip.ts";
|
|
39
39
|
import { listed, OPTIONS, runScript, UsageError, type Call } from "#src/script.ts";
|
|
40
40
|
import { knowledgeNames } from "#src/knowledge/names.ts";
|
|
41
|
-
import { COPIER_SOURCE, LOADER_JUMP, loaderLimits, planLoader, rasterLine, loaderState, simulate, stopCause, VIC_DISPLAY_REGISTERS, type EntryState, type LoaderPlan } from "./lib/loader.ts";
|
|
41
|
+
import { COPIER_SOURCE, LOADER_JUMP, loaderLimits, packLoader, planLoader, rasterLine, loaderState, simulate, stopCause, VIC_DISPLAY_REGISTERS, type EntryState, type LoaderPlan, type PackedLoader } from "./lib/loader.ts";
|
|
42
42
|
import { instructionWith, OPCODES } from "#src/opcodes.ts";
|
|
43
43
|
import { freeName, planDrops, readmeText, rewriteTest } from "./lib/export.ts";
|
|
44
44
|
import { CONFIG_FILE, configText, configValues, entriesInData, entryOutsideImage, hasSwitchFile, layout, literalOperand, probeForms, render, switchesOf, type Layout, type PatchBlock, type Rendered, type SourceSwitch } from "./lib/source.ts";
|
|
@@ -54,6 +54,8 @@ const DATA_ONLY = "The knowledge has no entry, routine, code region or executed
|
|
|
54
54
|
|
|
55
55
|
/** The copies of a full 64 KiB take about 140 frames. */
|
|
56
56
|
const LOADER_FRAMES = 1500;
|
|
57
|
+
/** CPU cycles of one PAL frame: 312 lines of 63 cycles. */
|
|
58
|
+
const PAL_FRAME_CYCLES = 312 * 63;
|
|
57
59
|
|
|
58
60
|
/** The knowledge of one space that the source uses, read once. With `analyzerNames`, an address without a name takes its first analyzer name. */
|
|
59
61
|
function readKnowledge(space: Space, analyzerNames = false) {
|
|
@@ -506,7 +508,16 @@ interface LoaderRun {
|
|
|
506
508
|
/** The history entries that a stop of the loader gives, so the agent sees the last instructions. */
|
|
507
509
|
const STOP_HISTORY = 16;
|
|
508
510
|
|
|
509
|
-
|
|
511
|
+
/** How the check of the loader runs it: the copier's address in the loader file, the file byte there, and the frames to the copier. */
|
|
512
|
+
interface LoaderRunPlan {
|
|
513
|
+
jump: number;
|
|
514
|
+
copierSource: number;
|
|
515
|
+
fileByte: (address: number) => number;
|
|
516
|
+
copierFrames: number;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
async function runLoader(path: string, program: Buffer, plan: LoaderPlan, image: ProgramImage, state: EntryState, run: LoaderRunPlan, expected: (address: number) => number): Promise<LoaderRun> {
|
|
520
|
+
const { jump, copierSource, fileByte } = run;
|
|
510
521
|
const client = await ViceSessionClient.open({ videoStandard: "pal" });
|
|
511
522
|
try {
|
|
512
523
|
await client.reset({ mode: "hard", run: false });
|
|
@@ -517,11 +528,11 @@ async function runLoader(path: string, program: Buffer, plan: LoaderPlan, image:
|
|
|
517
528
|
const ram = await readRam(client, 0x0000, 0x10000);
|
|
518
529
|
const port = Buffer.from((await client.memoryRead({ address: 0x0001, size: 1, space: "c64", view: "cpu" })).data, "hex")[0]!;
|
|
519
530
|
const history = (await client.cpuHistory({ limit: STOP_HISTORY, space: "c64" })).entries.map((entry) => `${formatC64Address(entry.address)} ${entry.text}`);
|
|
520
|
-
const cause = stopCause(ram, plan, copierSource,
|
|
531
|
+
const cause = stopCause(ram, plan, copierSource, fileByte, copied, expected);
|
|
521
532
|
const port01 = `$${port.toString(16).padStart(2, "0")}`;
|
|
522
533
|
return { verified: false, differences: [`The loader did not get to ${what}; it stopped at ${formatC64Address(pc)}.`], stop: { pc: formatC64Address(pc), port: port01, ...(cause === undefined ? {} : { cause }), history } };
|
|
523
534
|
};
|
|
524
|
-
const copier = await client.runUntil({ target: { kind: "address", address: plan.copier, space: "c64" }, timeoutFrames:
|
|
535
|
+
const copier = await client.runUntil({ target: { kind: "address", address: plan.copier, space: "c64" }, timeoutFrames: run.copierFrames });
|
|
525
536
|
if (!copier.reached) return await stopped(copier.pc, false, `its copier at ${formatC64Address(plan.copier)}`);
|
|
526
537
|
const atJump = await client.runUntil({ target: { kind: "address", address: jump, space: "c64" }, timeoutFrames: LOADER_FRAMES });
|
|
527
538
|
if (!atJump.reached) return await stopped(atJump.pc, true, `its jump to the entry at ${formatC64Address(jump)}`);
|
|
@@ -696,7 +707,7 @@ async function buildSource(knowledge: SourceKnowledge, options: SourceOptions) {
|
|
|
696
707
|
const entryName = laid.names.get(image.entry!);
|
|
697
708
|
loader = planLoader({ segments, byteAt: image.byteAt, state, entry: image.entry!, ...(entryName === undefined ? {} : { entryName }), switches: hasSwitchFile(laid), macros: laid.macros.length > 0, header: options.loaderHeader ?? [] });
|
|
698
709
|
} catch (error) {
|
|
699
|
-
if (!(error
|
|
710
|
+
if (!isRefusal(error)) throw error;
|
|
700
711
|
loaderRefused = error.message;
|
|
701
712
|
}
|
|
702
713
|
}
|
|
@@ -740,7 +751,7 @@ async function buildLoader(files: Array<{ name: string; text: string }>, laid: L
|
|
|
740
751
|
for (let address = block.range.start; address <= block.range.end; address++) if (memory[block.packedAt + address - block.range.start] !== block.bytes(address)) return true;
|
|
741
752
|
return false;
|
|
742
753
|
});
|
|
743
|
-
if (loaderBuilt.start !== 0x0801 || loaderBuilt.start + program.length - 3 !== loader.end || wrongPacking !== undefined) {
|
|
754
|
+
if (loaderBuilt.start !== (loader.packed?.start ?? 0x0801) || loaderBuilt.start + program.length - 3 !== loader.end || wrongPacking !== undefined) {
|
|
744
755
|
throw new WireFailure("operation-failed", `The assembled loader does not have the planned layout${wrongPacking === undefined ? "" : ` (${wrongPacking.what})`}. This is a defect of the c64-source script.`);
|
|
745
756
|
}
|
|
746
757
|
const symbolValue = (name: string) => {
|
|
@@ -894,12 +905,28 @@ async function generate(call: Call): Promise<{ output: Record<string, unknown>;
|
|
|
894
905
|
// The entry state is the state of the base release: the loader is built and checked with it.
|
|
895
906
|
const loaderBuilt = await buildLoader(files, laid, loader, image, state, baseValues);
|
|
896
907
|
if ("diagnostics" in loaderBuilt) return { output: { ...output, loader: { verified: false, reason: "loader.asm does not assemble.", diagnostics: loaderBuilt.diagnostics } }, removed, failed: true };
|
|
897
|
-
const {
|
|
908
|
+
const { jump, copierSource, expected } = loaderBuilt;
|
|
909
|
+
const copierBuild = loaderBuilt.program;
|
|
910
|
+
const fileByte = (address: number) => copierBuild[2 + address - (loader.packed?.start ?? 0x0801)]!;
|
|
911
|
+
// The packed form: Exomizer packs the build of main.asm with the copier. Without Exomizer, or when its check fails, there is no loader.prg.
|
|
912
|
+
let packed: PackedLoader | undefined;
|
|
913
|
+
if (loader.packed !== undefined) {
|
|
914
|
+
try {
|
|
915
|
+
packed = await packLoader(built.program, copierBuild, loader, localToolContext());
|
|
916
|
+
} catch (error) {
|
|
917
|
+
if (!isRefusal(error)) throw error;
|
|
918
|
+
return { output: { ...output, loader: { verified: false, reason: `loader.asm has the packed form, and the pack with Exomizer failed. ${error.message}` } }, removed, failed: true };
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
const program = packed?.program ?? copierBuild;
|
|
898
922
|
const loaderPath = `${out}/loader.prg`;
|
|
899
923
|
written.push(writeReported(loaderPath, program, { what: "--out" }));
|
|
900
|
-
|
|
924
|
+
// The unpack runs before the copier.
|
|
925
|
+
const copierFrames = packed === undefined ? RUN_LIMIT_FRAMES : packed.cycles === undefined ? LOADER_FRAMES : RUN_LIMIT_FRAMES + Math.ceil(packed.cycles / PAL_FRAME_CYCLES);
|
|
926
|
+
const ran = await runLoader(loaderPath, program, loader, image, state, { jump, copierSource, fileByte, copierFrames }, expected);
|
|
901
927
|
output.loader = {
|
|
902
928
|
program: loaderPath,
|
|
929
|
+
...(packed === undefined ? {} : { packed: { packedBytes: packed.packedBytes, unpackedBytes: packed.unpackedBytes } }),
|
|
903
930
|
copies: loader.copies.map((copy) => ({ what: copy.what, to: `${formatC64Address(copy.target.start)}-${formatC64Address(copy.target.end)}` })),
|
|
904
931
|
copier: formatC64Address(loader.copier),
|
|
905
932
|
stackByte: formatC64Address(loader.stackByte),
|
|
@@ -1112,6 +1139,7 @@ async function exportProject(call: Call): Promise<Record<string, unknown>> {
|
|
|
1112
1139
|
let loaderOutput: Record<string, unknown> | undefined;
|
|
1113
1140
|
if (state !== undefined) {
|
|
1114
1141
|
if (exported.loader === undefined) return { result: "FAIL", stage: "loader", reason: exported.loaderRefused ?? "The loader could not be planned." };
|
|
1142
|
+
if (exported.loader.packed !== undefined) return { result: "FAIL", stage: "loader", reason: "The program is too large for one loader file, and export does not make the packed form of the loader." };
|
|
1115
1143
|
const loaderBuilt = await buildLoader(exported.files, exported.laid, exported.loader, derived.program, state, new Map());
|
|
1116
1144
|
if ("diagnostics" in loaderBuilt) return { result: "FAIL", stage: "loader", reason: "loader.asm does not assemble. This is a defect of the c64-source script.", diagnostics: loaderBuilt.diagnostics };
|
|
1117
1145
|
baseline = { program: loaderBuilt.program, symbols: loaderBuilt.symbols, entryFile: "loader.asm" };
|
|
@@ -16,9 +16,9 @@ Find the static structure of a C64 program. Record the structure in the project
|
|
|
16
16
|
- Entry points: addresses where code starts, for example the SYS address from the c64-basic skill. Routine symbols in the knowledge are entry points too. Ghidra needs at least one. DXA finds the SYS of a BASIC start by itself.
|
|
17
17
|
- Optional: routines to decompile (Ghidra), or a file for the listing (DXA).
|
|
18
18
|
|
|
19
|
-
## Tools
|
|
19
|
+
## Tools
|
|
20
20
|
|
|
21
|
-
The script reads the program, the coverage and the current knowledge
|
|
21
|
+
The script reads the program, the coverage and the current knowledge. It records the result in the project knowledge, `.c64-re-tools/knowledge/`.
|
|
22
22
|
|
|
23
23
|
```
|
|
24
24
|
node <skill>/scripts/static-analysis.ts analyze --analyzer dxa --out-listing .c64-re-tools/local/game.lst
|
|
@@ -138,8 +138,8 @@ The exit status is 0, also with conflicts.
|
|
|
138
138
|
- `invalid-input` with a message about an entry point: no entry point is inside the program for Ghidra. Give one with `--entry`.
|
|
139
139
|
- `stale-revision`: the knowledge changed during the analysis. The script recorded nothing. Run the analysis again.
|
|
140
140
|
- `operation-failed` with a message about an incomplete result or listing: the analyzer did not give a complete result. The script recorded nothing. Tell the user.
|
|
141
|
-
- `installation-incomplete
|
|
142
|
-
- `notDecompiled`: Ghidra did not decompile these routines. Each entry has the reason. If the reason says that the decompiler did not start, tell the user the remedy in the reason.
|
|
141
|
+
- `installation-incomplete` or `machine-unavailable`: stop the task. Give the message to the user and wait for the user. Do not install, start or change a tool yourself. Do not make a replacement for the tool, for example your own disk parser, disassembler or emulator script.
|
|
142
|
+
- `notDecompiled`: Ghidra did not decompile these routines. Each entry has the reason. If the reason says that the decompiler did not start, tell the user the remedy in the reason.
|
|
143
143
|
|
|
144
144
|
## Handoffs
|
|
145
145
|
|