@henols/c64-re-tools 2.3.0-rc.1 → 2.3.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-packer/scripts/packer.ts +2 -20
- package/skills/c64-provenance/SKILL.md +15 -2
- package/skills/c64-provenance/scripts/lib/compare.ts +144 -16
- package/skills/c64-provenance/scripts/provenance.ts +37 -8
- package/skills/c64-source/SKILL.md +23 -2
- package/skills/c64-source/scripts/lib/loader.ts +281 -43
- package/skills/c64-source/scripts/source.ts +37 -9
- 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 +3 -3
- package/skills/c64-unpacker/scripts/lib/loads.ts +17 -4
- package/skills/c64-unpacker/scripts/unpacker.ts +15 -3
- package/src/compare.ts +18 -0
- package/src/host-client/coverage.ts +26 -0
package/package.json
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
import { posix } from "node:path";
|
|
7
7
|
|
|
8
8
|
import { findHandoffs, formatC64Address, parseTokenized, prgRange } from "#src/c64.ts";
|
|
9
|
-
import { compareBuild,
|
|
9
|
+
import { compareBuild, mergedPrograms } from "#src/compare.ts";
|
|
10
10
|
import { isRefusal, Refusal } from "#src/errors.ts";
|
|
11
11
|
import { readProjectFile, writeReported } from "#src/host-client/transfer.ts";
|
|
12
12
|
import { knowledgeNames } from "#src/knowledge/names.ts";
|
|
@@ -29,24 +29,6 @@ function sysEntry(program: Uint8Array): number | string {
|
|
|
29
29
|
return sys.address;
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
/** The inputs merged in load order, as the reference of the check: a later file wins where two overlap. */
|
|
33
|
-
function merged(programs: ReadonlyArray<{ start: number; body: Uint8Array }>): Reference {
|
|
34
|
-
const memory = new Uint8Array(0x10000);
|
|
35
|
-
const loaded = new Uint8Array(0x10000);
|
|
36
|
-
for (const { start, body } of programs) {
|
|
37
|
-
memory.set(body, start);
|
|
38
|
-
loaded.fill(1, start, start + body.length);
|
|
39
|
-
}
|
|
40
|
-
const segments: Array<{ start: number; end: number }> = [];
|
|
41
|
-
for (let address = 0; address < 0x10000; address++) {
|
|
42
|
-
if (loaded[address] === 0) continue;
|
|
43
|
-
const last = segments.at(-1);
|
|
44
|
-
if (last !== undefined && last.end === address - 1) last.end = address;
|
|
45
|
-
else segments.push({ start: address, end: address });
|
|
46
|
-
}
|
|
47
|
-
return { segments, byteAt: (address) => memory[address]! };
|
|
48
|
-
}
|
|
49
|
-
|
|
50
32
|
const samePath = (a: string, b: string) => posix.normalize(a.replaceAll("\\", "/")) === posix.normalize(b.replaceAll("\\", "/"));
|
|
51
33
|
|
|
52
34
|
await runScript({
|
|
@@ -88,7 +70,7 @@ await runScript({
|
|
|
88
70
|
const exitMemory = call.count("exit-memory");
|
|
89
71
|
const packed = await pack({ programs: programs.map((program) => program.bytes), entry, ...(exitMemory === undefined ? {} : { exitMemory }) }, localToolContext());
|
|
90
72
|
|
|
91
|
-
const reference =
|
|
73
|
+
const reference = mergedPrograms(programs);
|
|
92
74
|
const check = compareBuild(packed.unpacked, reference);
|
|
93
75
|
const entryReached = packed.entry === entry;
|
|
94
76
|
const different = !entryReached || check.segments.some((segment) => segment.result === "different");
|
|
@@ -20,6 +20,7 @@ This skill does not change project knowledge.
|
|
|
20
20
|
- Two or more releases, relative to the project folder. A release is `knowledge` (the program in the knowledge), a PRG file, or an `image.json` from c64-unpacker capture with its `entry_state.json` beside it. Extract releases from disk images with the c64-disk skill. Unpack packed releases with the c64-unpacker skill first.
|
|
21
21
|
- Optional: an address range to compare.
|
|
22
22
|
- Optional: a shift for a release that loads at a different address.
|
|
23
|
+
- Optional: `--align`, to map two releases with moved code in blocks of equal bytes.
|
|
23
24
|
- Optional: a number of frames to run each release, and a steps file.
|
|
24
25
|
- For one release: the program, the coverage and the other knowledge of the project. Put the program and the coverage in with `image` and `coverage` of the c64-knowledge skill.
|
|
25
26
|
- For the library: the program and the other knowledge of its project, and the library folder.
|
|
@@ -31,6 +32,7 @@ The script compares the releases locally. Only `--frames` uses the host runtime:
|
|
|
31
32
|
```
|
|
32
33
|
node <skill>/scripts/provenance.ts compare releases/a.prg releases/b.prg releases/c.prg
|
|
33
34
|
node <skill>/scripts/provenance.ts compare releases/a.prg releases/b.prg --shift 2:-256 --range '$0900-$09ff'
|
|
35
|
+
node <skill>/scripts/provenance.ts compare releases/a/image.json releases/b/image.json --align --range '$0400-$bfff'
|
|
34
36
|
node <skill>/scripts/provenance.ts compare knowledge .c64-re-tools/local/b/image.json --frames 600 --steps .c64-re-tools/local/start-game.json
|
|
35
37
|
node <skill>/scripts/provenance.ts separate --out .c64-re-tools/local/separate.json
|
|
36
38
|
node <skill>/scripts/provenance.ts leftovers --out .c64-re-tools/local/leftovers.json
|
|
@@ -40,6 +42,8 @@ node <skill>/scripts/provenance.ts leftovers --out .c64-re-tools/local/leftovers
|
|
|
40
42
|
|---|---|
|
|
41
43
|
| `--shift 2:-256` | Move release 2 (the first release is 1) by -256 bytes. Use it again for more releases. Give one shift for each release. |
|
|
42
44
|
| `--range '$0900-$09ff'` | Compare only the addresses in this range. |
|
|
45
|
+
| `--align` | Map release 1 to release 2 in blocks of equal bytes. Each block has its own shift. Give two releases. Do not use it with `--shift` or `--frames`. |
|
|
46
|
+
| `--min-block 24` | With `--align`: the minimum number of bytes in a block. The default is 16. |
|
|
43
47
|
| `--frames 600` | Run each release for this many frames, and give each listed difference its runtime evidence. |
|
|
44
48
|
| `--steps .c64-re-tools/local/start-game.json` | With `--frames`: a JSON list of action steps to run before the frames, for example a key to start the game. The steps are the steps of a c64-unpacker steps file. |
|
|
45
49
|
|
|
@@ -47,6 +51,15 @@ The script puts each PRG at its load address. An image has bytes only in its seg
|
|
|
47
51
|
|
|
48
52
|
With `--shift`, the addresses of `segments`, `common` and `differences` are the release addresses plus the `shift` of the release. The `start` and `end` of `runtime` are the addresses in the release itself, without the shift.
|
|
49
53
|
|
|
54
|
+
Use `--align` for two releases with added code and moved data. One shift does not fit them, and the shift suggestions are not useful. The map tells what each block of one release is in the other release. With `--align`, the result has the map, not `differences` and not the shift suggestions:
|
|
55
|
+
|
|
56
|
+
- `blocks`: the blocks of equal bytes, in the order of their addresses in release 1. `a` is the range in release 1. `b` is the range in release 2. `bytes` is the length of the block.
|
|
57
|
+
- `shift`: the address in `b` minus the address in `a`. The address of a byte in release 2 is its address in release 1 plus the `shift` of its block. The blocks can have a different order in release 2, because code moved.
|
|
58
|
+
- `onlyInA`: the ranges of release 1 that no block holds. Release 2 does not have these bytes, or it has other bytes there.
|
|
59
|
+
- `onlyInB`: the ranges of release 2 that no block holds. Release 2 added these bytes, or it changed them.
|
|
60
|
+
- `alignedShare`: the share of the bytes of the two releases that a block holds, with 3 decimals.
|
|
61
|
+
- Each list shows at most 64 items. `moreBlocks`, `moreOnlyInA` and `moreOnlyInB` give the number of the items that the list does not show. Use `--range` to see them.
|
|
62
|
+
|
|
50
63
|
With `--frames`, a PRG starts with autostart and RUN. An image starts from its bytes: the script writes the segments and the entry state from `entry_state.json` into the emulator, and starts at the entry. Watchpoints on each difference stop the run at its first access.
|
|
51
64
|
|
|
52
65
|
### Calling the script
|
|
@@ -74,7 +87,7 @@ With `--frames`, a PRG starts with autostart and RUN. An image starts from its b
|
|
|
74
87
|
## Workflow
|
|
75
88
|
|
|
76
89
|
1. Run the script on the releases.
|
|
77
|
-
2. Read `identicalShare`. If it is low and `suggestedShifts` is present, the releases are at different addresses. Run the script again with a `--shift` of `suggestedShifts`. `shiftsNotSuggested` tells why a found shift does not fit in `$0000-$ffff`.
|
|
90
|
+
2. Read `identicalShare`. If it is low and `suggestedShifts` is present, the releases are at different addresses. Run the script again with a `--shift` of `suggestedShifts`. `shiftsNotSuggested` tells why a found shift does not fit in `$0000-$ffff`. If no shift gives a high `identicalShare`, the code and the data can be at other addresses in each release. Then run the script again with `--align`.
|
|
78
91
|
|
|
79
92
|
`suggestedShifts` has at most 3 shifts for each release. The shift with the most `matchingSequences` is first. Data that did not move and code that moved give different shifts. Try each shift. `current: true` marks the shift of this run.
|
|
80
93
|
3. Read `differences`. Each one has an address range, the bytes of each release, and `groups`: the releases that have the same bytes there.
|
|
@@ -201,7 +214,7 @@ Record a confirmed conclusion as a normal comment, region, symbol, release, swit
|
|
|
201
214
|
|
|
202
215
|
## Result
|
|
203
216
|
|
|
204
|
-
The differing ranges with the bytes of each release and the groups that agree, and the share of identical bytes. `identicalShare` has 3 decimals. It is 1 only when no byte differs. `identicalBytes` and `differingBytes` give the counts. `common` gives the ranges where all releases have bytes. `releases` gives the segments and the `shift` of each release. With `--frames`, each difference also has `runtime`, and `run` tells if each release started, or why not.
|
|
217
|
+
The differing ranges with the bytes of each release and the groups that agree, and the share of identical bytes. `identicalShare` has 3 decimals. It is 1 only when no byte differs. `identicalBytes` and `differingBytes` give the counts. `common` gives the ranges where all releases have bytes. `releases` gives the segments and the `shift` of each release. With `--frames`, each difference also has `runtime`, and `run` tells if each release started, or why not. With `--align`, the result has `blocks`, `onlyInA`, `onlyInB` and `alignedShare` in place of `differences`.
|
|
205
218
|
|
|
206
219
|
For `leftovers`: the lists of findings, with `entry`, `roots` and the number of `stages`. `noStages` and `noCoverage` tell which knowledge is missing. Without a root, `roots` tells why `deadCode` is empty.
|
|
207
220
|
|
|
@@ -2,8 +2,10 @@
|
|
|
2
2
|
// has bytes in one or more segments: a PRG at its load address plus an
|
|
3
3
|
// optional shift, or the segments of an unpacker image. The comparison
|
|
4
4
|
// covers the addresses where every release has bytes, and reports where the
|
|
5
|
-
// releases differ and which releases agree there.
|
|
6
|
-
//
|
|
5
|
+
// releases differ and which releases agree there. For two releases with
|
|
6
|
+
// moved code, align maps the bytes of one to the other in blocks of equal
|
|
7
|
+
// bytes. It never decides which bytes are original: that needs evidence
|
|
8
|
+
// beyond one comparison.
|
|
7
9
|
|
|
8
10
|
import { type AddressRange, formatC64Address } from "#src/c64.ts";
|
|
9
11
|
|
|
@@ -53,9 +55,13 @@ export function identicalShare(identical: number, differing: number): number {
|
|
|
53
55
|
|
|
54
56
|
/** The ranges where every release has bytes, inside from..to. */
|
|
55
57
|
export function commonRanges(releases: Release[], from = 0x0000, to = 0xffff): AddressRange[] {
|
|
58
|
+
return rangesOf(Array.from({ length: to - from + 1 }, (_, offset) => from + offset).filter((address) => releases.every((release) => covers(release, address))));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Consecutive addresses in order as ranges. */
|
|
62
|
+
function rangesOf(addresses: number[]): AddressRange[] {
|
|
56
63
|
const ranges: AddressRange[] = [];
|
|
57
|
-
for (
|
|
58
|
-
if (!releases.every((release) => covers(release, address))) continue;
|
|
64
|
+
for (const address of addresses) {
|
|
59
65
|
const last = ranges.at(-1);
|
|
60
66
|
if (last !== undefined && last.end + 1 === address) last.end = address;
|
|
61
67
|
else ranges.push({ start: address, end: address });
|
|
@@ -102,6 +108,24 @@ function addressesOf(release: Release): number[] {
|
|
|
102
108
|
return release.segments.flatMap((segment) => Array.from({ length: segment.end - segment.start + 1 }, (_, offset) => segment.start + offset));
|
|
103
109
|
}
|
|
104
110
|
|
|
111
|
+
/** The length of the byte sequences that find equal bytes in two releases. */
|
|
112
|
+
const WINDOW = 8;
|
|
113
|
+
|
|
114
|
+
const windowKey = (release: Release, addresses: number[], at: number) => String.fromCharCode(...addresses.slice(at, at + WINDOW).map((address) => release.byteAt(address)));
|
|
115
|
+
|
|
116
|
+
/** The addresses where each 8-byte sequence of `addresses` starts, at most 8 for each sequence. */
|
|
117
|
+
function indexWindows(release: Release, addresses: number[]): Map<string, number[]> {
|
|
118
|
+
const positions = new Map<string, number[]>();
|
|
119
|
+
for (let at = 0; at + WINDOW <= addresses.length; at++) {
|
|
120
|
+
const key = windowKey(release, addresses, at);
|
|
121
|
+
const found = positions.get(key);
|
|
122
|
+
// Very common sequences (fill bytes) say nothing about the alignment.
|
|
123
|
+
if (found === undefined) positions.set(key, [addresses[at]!]);
|
|
124
|
+
else if (found.length < 8) found.push(addresses[at]!);
|
|
125
|
+
}
|
|
126
|
+
return positions;
|
|
127
|
+
}
|
|
128
|
+
|
|
105
129
|
/** Most shifts that suggestShifts gives: data that did not move can outvote code that did. */
|
|
106
130
|
export const MAX_SUGGESTED_SHIFTS = 3;
|
|
107
131
|
|
|
@@ -111,21 +135,11 @@ export const MAX_SUGGESTED_SHIFTS = 3;
|
|
|
111
135
|
* less than a tenth of the best one's votes is chance. Empty when nothing matches.
|
|
112
136
|
*/
|
|
113
137
|
export function suggestShifts(base: Release, other: Release): Array<{ shift: number; matches: number }> {
|
|
114
|
-
const
|
|
115
|
-
const key = (release: Release, addresses: number[], at: number) =>
|
|
116
|
-
String.fromCharCode(...addresses.slice(at, at + WINDOW).map((address) => release.byteAt(address)));
|
|
117
|
-
const baseAddresses = addressesOf(base);
|
|
138
|
+
const positions = indexWindows(base, addressesOf(base));
|
|
118
139
|
const otherAddresses = addressesOf(other);
|
|
119
|
-
const positions = new Map<string, number[]>();
|
|
120
|
-
for (let at = 0; at + WINDOW <= baseAddresses.length; at++) {
|
|
121
|
-
const found = positions.get(key(base, baseAddresses, at));
|
|
122
|
-
// Very common sequences (fill bytes) say nothing about the alignment.
|
|
123
|
-
if (found === undefined) positions.set(key(base, baseAddresses, at), [baseAddresses[at]!]);
|
|
124
|
-
else if (found.length < 8) found.push(baseAddresses[at]!);
|
|
125
|
-
}
|
|
126
140
|
const votes = new Map<number, number>();
|
|
127
141
|
for (let at = 0; at + WINDOW <= otherAddresses.length; at++) {
|
|
128
|
-
for (const address of positions.get(
|
|
142
|
+
for (const address of positions.get(windowKey(other, otherAddresses, at)) ?? []) {
|
|
129
143
|
const shift = address - otherAddresses[at]!;
|
|
130
144
|
votes.set(shift, (votes.get(shift) ?? 0) + 1);
|
|
131
145
|
}
|
|
@@ -134,6 +148,120 @@ export function suggestShifts(base: Release, other: Release): Array<{ shift: num
|
|
|
134
148
|
return ranked.filter((found) => found.matches * 10 >= ranked[0]!.matches).slice(0, MAX_SUGGESTED_SHIFTS);
|
|
135
149
|
}
|
|
136
150
|
|
|
151
|
+
export interface Block {
|
|
152
|
+
a: AddressRange;
|
|
153
|
+
b: AddressRange;
|
|
154
|
+
/** The address in b minus the address in a. */
|
|
155
|
+
shift: number;
|
|
156
|
+
bytes: number;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export interface Alignment {
|
|
160
|
+
/** In the order of their addresses in a. */
|
|
161
|
+
blocks: Block[];
|
|
162
|
+
/** The bytes of a that no block holds: removed in b. */
|
|
163
|
+
onlyInA: AddressRange[];
|
|
164
|
+
/** The bytes of b that no block holds: inserted in b. */
|
|
165
|
+
onlyInB: AddressRange[];
|
|
166
|
+
/** The share of the bytes of a and b in the range that a block holds, as identicalShare gives it. */
|
|
167
|
+
alignedShare: number;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Maps the bytes of `a` to the bytes of `b` in blocks of equal bytes, at least
|
|
172
|
+
* `minBlock` long, for releases with added code and moved data, where no one
|
|
173
|
+
* shift fits. Only the bytes inside `range` and the segments count. Each
|
|
174
|
+
* address of a that no block holds yet gets the longest block through it:
|
|
175
|
+
* from each address of b with the same 8 bytes, and from the shift of the
|
|
176
|
+
* block before. Then the longest blocks are kept with no byte of a or b in two
|
|
177
|
+
* blocks; a block that overlaps a kept one keeps its free parts. Blocks can
|
|
178
|
+
* cross: moved code changes the order.
|
|
179
|
+
*/
|
|
180
|
+
export function align(a: Release, b: Release, range: AddressRange, minBlock: number): Alignment {
|
|
181
|
+
const inRange = (address: number) => address >= range.start && address <= range.end;
|
|
182
|
+
const aAddresses = addressesOf(a).filter(inRange);
|
|
183
|
+
const bAddresses = addressesOf(b).filter(inRange);
|
|
184
|
+
// -1 where the release has no byte; an index outside $0000-$ffff gives undefined.
|
|
185
|
+
const bytesOf = (release: Release, addresses: number[]) => {
|
|
186
|
+
const bytes = new Int16Array(0x10000).fill(-1);
|
|
187
|
+
for (const address of addresses) bytes[address] = release.byteAt(address);
|
|
188
|
+
return bytes;
|
|
189
|
+
};
|
|
190
|
+
const bytesA = bytesOf(a, aAddresses);
|
|
191
|
+
const bytesB = bytesOf(b, bAddresses);
|
|
192
|
+
const equal = (x: number, y: number) => {
|
|
193
|
+
const value = bytesA[x];
|
|
194
|
+
return value !== undefined && value >= 0 && value === bytesB[y];
|
|
195
|
+
};
|
|
196
|
+
|
|
197
|
+
type Found = { a: number; b: number; bytes: number };
|
|
198
|
+
const index = indexWindows(b, bAddresses);
|
|
199
|
+
const found: Found[] = [];
|
|
200
|
+
let covered = -1;
|
|
201
|
+
let lastShift: number | undefined;
|
|
202
|
+
for (let at = 0; at < aAddresses.length; at++) {
|
|
203
|
+
const p = aAddresses[at]!;
|
|
204
|
+
if (p <= covered) continue;
|
|
205
|
+
const candidates = at + WINDOW <= aAddresses.length ? [...(index.get(windowKey(a, aAddresses, at)) ?? [])] : [];
|
|
206
|
+
if (lastShift !== undefined) candidates.push(p + lastShift);
|
|
207
|
+
let best: Found | undefined;
|
|
208
|
+
for (const q of candidates) {
|
|
209
|
+
if (!equal(p, q)) continue;
|
|
210
|
+
let back = 0;
|
|
211
|
+
while (equal(p - back - 1, q - back - 1)) back++;
|
|
212
|
+
let forward = 1;
|
|
213
|
+
while (equal(p + forward, q + forward)) forward++;
|
|
214
|
+
if (best === undefined || back + forward > best.bytes) best = { a: p - back, b: q - back, bytes: back + forward };
|
|
215
|
+
}
|
|
216
|
+
if (best === undefined || best.bytes < minBlock) continue;
|
|
217
|
+
found.push(best);
|
|
218
|
+
covered = best.a + best.bytes - 1;
|
|
219
|
+
lastShift = best.b - best.a;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// The longest first; a piece that is left of an overlapping block goes back in its place in that order.
|
|
223
|
+
const before = (x: Found, y: Found) => y.bytes - x.bytes || Math.abs(x.b - x.a) - Math.abs(y.b - y.a) || x.a - y.a;
|
|
224
|
+
const queue = found.sort(before);
|
|
225
|
+
const usedA = new Uint8Array(0x10000);
|
|
226
|
+
const usedB = new Uint8Array(0x10000);
|
|
227
|
+
const kept: Found[] = [];
|
|
228
|
+
for (let next = 0; next < queue.length; next++) {
|
|
229
|
+
const block = queue[next]!;
|
|
230
|
+
const pieces: Found[] = [];
|
|
231
|
+
let start: number | undefined;
|
|
232
|
+
for (let offset = 0; offset <= block.bytes; offset++) {
|
|
233
|
+
if (offset < block.bytes && usedA[block.a + offset] === 0 && usedB[block.b + offset] === 0) start ??= offset;
|
|
234
|
+
else if (start !== undefined) {
|
|
235
|
+
pieces.push({ a: block.a + start, b: block.b + start, bytes: offset - start });
|
|
236
|
+
start = undefined;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (pieces.length === 1 && pieces[0]!.bytes === block.bytes) {
|
|
240
|
+
kept.push(block);
|
|
241
|
+
usedA.fill(1, block.a, block.a + block.bytes);
|
|
242
|
+
usedB.fill(1, block.b, block.b + block.bytes);
|
|
243
|
+
continue;
|
|
244
|
+
}
|
|
245
|
+
for (const piece of pieces.filter((item) => item.bytes >= minBlock)) {
|
|
246
|
+
let place = next + 1;
|
|
247
|
+
while (place < queue.length && before(queue[place]!, piece) <= 0) place++;
|
|
248
|
+
queue.splice(place, 0, piece);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const alignedBytes = kept.reduce((sum, block) => sum + block.bytes, 0);
|
|
253
|
+
const onlyInA = rangesOf(aAddresses.filter((address) => usedA[address] === 0));
|
|
254
|
+
const onlyInB = rangesOf(bAddresses.filter((address) => usedB[address] === 0));
|
|
255
|
+
return {
|
|
256
|
+
blocks: kept
|
|
257
|
+
.sort((x, y) => x.a - y.a)
|
|
258
|
+
.map((block) => ({ a: { start: block.a, end: block.a + block.bytes - 1 }, b: { start: block.b, end: block.b + block.bytes - 1 }, shift: block.b - block.a, bytes: block.bytes })),
|
|
259
|
+
onlyInA,
|
|
260
|
+
onlyInB,
|
|
261
|
+
alignedShare: identicalShare(2 * alignedBytes, aAddresses.length + bAddresses.length - 2 * alignedBytes),
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
137
265
|
export type ShiftSuggestion = { release: number; shift: number; matchingSequences: number } | { release: number; matchingSequences: number; reason: string };
|
|
138
266
|
|
|
139
267
|
/**
|
|
@@ -43,7 +43,7 @@ import { platformNames } from "#src/platform.ts";
|
|
|
43
43
|
import { projectRoot } from "#src/project.ts";
|
|
44
44
|
import { knowledgeAt, knowledgeNames } from "#src/knowledge/names.ts";
|
|
45
45
|
import { listed, OPTIONS, runScript, UsageError, type Call, type CommandSpec } from "#src/script.ts";
|
|
46
|
-
import { compareReleases, identicalShare, shiftSuggestion, suggestShifts, type Release } from "./lib/compare.ts";
|
|
46
|
+
import { align, compareReleases, identicalShare, shiftSuggestion, suggestShifts, type Release } from "./lib/compare.ts";
|
|
47
47
|
import { findRoutine, libraryFolder, readLibrary, routineFrom, saveRoutine, suggest } from "./lib/library.ts";
|
|
48
48
|
import { watchRelease, type Start } from "./lib/runtime.ts";
|
|
49
49
|
import { findLeftovers } from "./lib/leftovers.ts";
|
|
@@ -100,7 +100,10 @@ function readRelease(name: string, shift: number): LoadedRelease {
|
|
|
100
100
|
};
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
-
/**
|
|
103
|
+
/** Most blocks and ranges that a list of --align shows. */
|
|
104
|
+
const MAX_ALIGNED = 64;
|
|
105
|
+
|
|
106
|
+
/** compare: the releases byte by byte, with --align a map of two releases in blocks, and with --frames the first access of each difference in each release. */
|
|
104
107
|
async function compare(call: Call): Promise<unknown> {
|
|
105
108
|
const positionals = call.subjects;
|
|
106
109
|
if (positionals.length < 2) throw new UsageError("compare needs two or more releases");
|
|
@@ -117,12 +120,40 @@ async function compare(call: Call): Promise<unknown> {
|
|
|
117
120
|
const frames = call.count("frames");
|
|
118
121
|
const stepsFile = call.string("steps");
|
|
119
122
|
if (stepsFile !== undefined && frames === undefined) throw new UsageError("--steps works only with --frames");
|
|
123
|
+
const aligned = call.flag("align");
|
|
124
|
+
const minBlock = call.count("min-block");
|
|
125
|
+
if (minBlock !== undefined && !aligned) throw new UsageError("--min-block works only with --align");
|
|
126
|
+
if (aligned) {
|
|
127
|
+
if (shifts.size > 0) throw new UsageError("--align does not work with --shift: --align finds the shift of each block itself. Remove --shift");
|
|
128
|
+
if (frames !== undefined) throw new UsageError("--align does not work with --frames: --align gives no differences to run. Run --frames without --align");
|
|
129
|
+
if (positionals.length !== 2) throw new UsageError(`--align maps two releases, not ${positionals.length}. Give two releases`);
|
|
130
|
+
}
|
|
120
131
|
const steps: ActionStep[] = stepsFile === undefined ? [] : readActionSteps(stepsFile, "--steps", knowledgeAt());
|
|
121
132
|
const loaded = positionals.map((path, index) => readRelease(path, shifts.get(index + 1) ?? 0));
|
|
122
133
|
const releases = loaded.map((item) => item.release);
|
|
123
134
|
const range = call.range("range");
|
|
124
135
|
const comparison = compareReleases(releases, range === undefined ? {} : { from: range.start, to: range.end });
|
|
125
136
|
const share = identicalShare(comparison.identicalBytes, comparison.differingBytes);
|
|
137
|
+
const show = (range: AddressRange) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) });
|
|
138
|
+
const compared = {
|
|
139
|
+
releases: loaded.map((item) => ({ name: item.release.name, shift: item.shift, segments: item.release.segments.map(show) })),
|
|
140
|
+
common: comparison.common.map(show),
|
|
141
|
+
identicalBytes: comparison.identicalBytes,
|
|
142
|
+
differingBytes: comparison.differingBytes,
|
|
143
|
+
identicalShare: share,
|
|
144
|
+
};
|
|
145
|
+
if (aligned) {
|
|
146
|
+
// Code added and data moved: one shift for the release cannot fit, so each block of equal bytes gets its own.
|
|
147
|
+
const alignment = align(releases[0]!, releases[1]!, range ?? { start: 0x0000, end: 0xffff }, minBlock ?? 16);
|
|
148
|
+
const capped = <T>(name: string, items: T[]) => ({ [name]: items.slice(0, MAX_ALIGNED), ...(items.length > MAX_ALIGNED ? { [`more${name[0]!.toUpperCase()}${name.slice(1)}`]: items.length - MAX_ALIGNED } : {}) });
|
|
149
|
+
return {
|
|
150
|
+
...compared,
|
|
151
|
+
alignedShare: alignment.alignedShare,
|
|
152
|
+
...capped("blocks", alignment.blocks.map((block) => ({ a: show(block.a), b: show(block.b), shift: block.shift, bytes: block.bytes }))),
|
|
153
|
+
...capped("onlyInA", alignment.onlyInA.map(show)),
|
|
154
|
+
...capped("onlyInB", alignment.onlyInB.map(show)),
|
|
155
|
+
};
|
|
156
|
+
}
|
|
126
157
|
// A poor match at the load addresses can mean that the releases are placed differently.
|
|
127
158
|
// Each release gets its best shifts: data that stayed can outvote code that moved, so one is not enough.
|
|
128
159
|
const applied = loaded.map((item) => item.shift);
|
|
@@ -165,11 +196,7 @@ async function compare(call: Call): Promise<unknown> {
|
|
|
165
196
|
}
|
|
166
197
|
|
|
167
198
|
return {
|
|
168
|
-
|
|
169
|
-
common: comparison.common.map((range) => ({ start: formatC64Address(range.start), end: formatC64Address(range.end) })),
|
|
170
|
-
identicalBytes: comparison.identicalBytes,
|
|
171
|
-
differingBytes: comparison.differingBytes,
|
|
172
|
-
identicalShare: share,
|
|
199
|
+
...compared,
|
|
173
200
|
differences: comparison.differences.map((difference, index) => ({
|
|
174
201
|
start: formatC64Address(difference.start),
|
|
175
202
|
end: formatC64Address(difference.end),
|
|
@@ -460,7 +487,7 @@ const LIBRARY = { kind: "text", value: "<folder>", required: true, help: "the li
|
|
|
460
487
|
const COMMANDS: CommandSpec[] = [
|
|
461
488
|
{
|
|
462
489
|
name: "compare",
|
|
463
|
-
summary: "Compares releases byte by byte, in their common ranges, and suggests shifts when they are placed differently.",
|
|
490
|
+
summary: "Compares releases byte by byte, in their common ranges, and suggests shifts when they are placed differently. With --align, maps two releases with moved code in blocks of equal bytes, each with its own shift.",
|
|
464
491
|
subjects: [{ name: "<release>", help: "knowledge (the program in the knowledge), a PRG at its load address, or an image.json of the c64-unpacker skill with the entry_state.json beside it. Two or more", list: true }],
|
|
465
492
|
options: {
|
|
466
493
|
shift: {
|
|
@@ -472,6 +499,8 @@ const COMMANDS: CommandSpec[] = [
|
|
|
472
499
|
example: (given) => `2:${given !== undefined && /^-\d+$/.test(given) ? given : "-256"}`,
|
|
473
500
|
},
|
|
474
501
|
range: { ...OPTIONS.range, help: "compare only the addresses from start to end" },
|
|
502
|
+
align: { kind: "flag", help: "map the first release to the second in blocks of equal bytes, each with its own shift, for releases with added code and moved data. Two releases; not with --shift or --frames" },
|
|
503
|
+
"min-block": { kind: "count", value: "<n>", min: 8, max: 0x10000, help: "with --align: the fewest bytes in a block (default 16)" },
|
|
475
504
|
frames: { ...OPTIONS.frames, max: MAX_EXECUTION_COUNT, help: "run each release in its own emulator for n frames, and give each listed difference its first access and whether it changed" },
|
|
476
505
|
steps: { ...OPTIONS.steps, help: "with --frames: action steps (JSON) to run before the frames" },
|
|
477
506
|
},
|
|
@@ -140,6 +140,26 @@ The script simulates the copies first. Then it runs `loader.prg` in the emulator
|
|
|
140
140
|
|
|
141
141
|
The entry state is the state of the base release. Thus the script builds and checks `loader.prg` with the switch values of the base release. For a loader of the default build, build `loader.asm` with the c64-assembler skill and no option.
|
|
142
142
|
|
|
143
|
+
### The packed loader
|
|
144
|
+
|
|
145
|
+
A loader file that loads into $d000 or higher writes the I/O area. When the image is too large for one loader file, `loader.asm` has the packed form. The packed form needs Exomizer. It has these differences:
|
|
146
|
+
|
|
147
|
+
- `loader.asm` holds only the copier and the bytes below $0400: pages $0002-$03ff of the entry state and the parts of segments there. The copier is in one free range, at `loader.copier`. The bytes below $0400 go into free ranges. When one range is too small, they go into more ranges, and each piece is a copy. Between these ranges, `loader.asm` holds the bytes of the image. The segments at $0400 and higher are not in `loader.asm`.
|
|
148
|
+
- The script packs the build of `main.asm` from $0400 and the build of `loader.asm` into `loader.prg` with Exomizer. Where the two builds overlap, the bytes of `loader.asm` are in `loader.prg`.
|
|
149
|
+
- `10 SYS` starts the unpacker. The unpacker writes all bytes, also at $d000-$dfff. Then it jumps to the copier with all RAM visible ($01 = $34).
|
|
150
|
+
- The unpacker uses the zero page and $0334-$03ff. Thus the copier writes pages $0002-$03ff after the unpack. Then it does steps 4 to 6.
|
|
151
|
+
- The jump to the entry uses the address of the entry, not its label. The build of `loader.asm` does not include `main.asm`.
|
|
152
|
+
|
|
153
|
+
The script checks the unpack in the emulator of Exomizer. All bytes of the two builds must be correct, and the unpacker must jump to the copier. Then the script runs `loader.prg` in the emulator, as for the plain loader. `loader.packed` gives `packedBytes` and `unpackedBytes`.
|
|
154
|
+
|
|
155
|
+
To make the packed loader for other switch values, do these steps:
|
|
156
|
+
|
|
157
|
+
1. Build the program with the c64-assembler skill: `assembler.ts build src main.asm --out build/main.prg`.
|
|
158
|
+
2. Build the copier with the c64-assembler skill: `assembler.ts build src loader.asm --out build/copier.prg`.
|
|
159
|
+
3. Pack the two files with the c64-packer skill: `packer.ts pack build/main.prg build/copier.prg --entry '$c000' --exit-memory '$34' --out build/loader.prg`. The comment at the start of `loader.asm` gives the `--entry` value.
|
|
160
|
+
|
|
161
|
+
These commands do not work when a segment starts below $0400. Then the build of `main.asm` has bytes in the area of the unpacker. They also do not work when a patch is between the ranges of `loader.asm`, because there `loader.asm` has the bytes of the image. In these cases, use `generate --loader` for the base release.
|
|
162
|
+
|
|
143
163
|
## Export for a new application
|
|
144
164
|
|
|
145
165
|
`export` writes the program of the knowledge as the start of a new program: a new project folder and a zip file of it. A person changes the source of the new project directly. The c64-export skill gives the full procedure.
|
|
@@ -255,7 +275,7 @@ Do not store:
|
|
|
255
275
|
- `switches`: the build of each switch that has patches. Each item has `kind`, `default`, `base`, the `define` for the c64-assembler skill and the patches. `result` is the result of the build with the switch at the value that is not `base`. `fits` tells that the build is good, and `changedBytes` counts the changed bytes. `overflow` tells that the code of a patch is longer than its range. `changes outside` gives the first byte outside the ranges that changed. `does not assemble` gives the diagnostics of ACME. `insideNames` lists the labels inside a patch. Code that writes to one of these labels changes the patch when the switch is on.
|
|
256
276
|
- `default`: the default build. `in` lists the switches whose patches are in. `result` and `changedBytes` are as in `switches`.
|
|
257
277
|
- `releases`: the build of each release. Each item has `label`, `base`, `file`, the `define` and the `result`. `identical` tells that the build gives the bytes of the file. `different` gives the segments that differ. `layout differs` tells that the release has other segments than the program: patches cannot move code, so this result does not fail the run. `file changed` tells that the file is not the file that the knowledge recorded. `does not assemble` gives the diagnostics of ACME.
|
|
258
|
-
- `loader`: the program, the copies in their order, the copier page, `stackByte`, `verified` and `differences`. `limits` lists the CIA values that the loader cannot set. An entry state from an old capture has no CIA values. Then `limits` tells you to capture the program again. When the script cannot make the loader, `loader` has `verified: false` and a `reason`. The loader includes the source. Thus a source that does not assemble to the program also stops the loader.
|
|
278
|
+
- `loader`: the program, the copies in their order, the copier page, `stackByte`, `verified` and `differences`. A packed loader also has `packed` with `packedBytes` and `unpackedBytes`. `limits` lists the CIA values that the loader cannot set. An entry state from an old capture has no CIA values. Then `limits` tells you to capture the program again. When the script cannot make the loader, `loader` has `verified: false` and a `reason`. The loader includes the source. Thus a source that does not assemble to the program also stops the loader.
|
|
259
279
|
|
|
260
280
|
`result` is `PASS` when the source is identical and the emulator check of the loader passes. `result` is `FAIL` for a failed check and for an entry in no segment. These also give `FAIL`:
|
|
261
281
|
|
|
@@ -282,8 +302,9 @@ Do not store:
|
|
|
282
302
|
- `dataOnly`: this is not a failure. If the space has code, give `--entry` or classify the code with the c64-knowledge skill. Then generate again.
|
|
283
303
|
- `entriesInData`: an analyzer region of data hides the code at the entry. If the entry is code, record a code region at the entry with the c64-knowledge skill, for example `classify '$0500-$05ff' code`. A region of the user or the LLM replaces the analyzer region. Then generate again.
|
|
284
304
|
- `loader.verified: false` with a `reason`: the script did not make the loader. The script still writes and checks the source. When no copy order or no free pages exist, or the loader needs too many copies, the reason gives the ranges. Capture the program again with fewer segments, or write the loader by hand.
|
|
305
|
+
- `loader.verified: false` with a `reason` about the packed form: the image is too large for one loader file. If the reason tells that Exomizer is not installed, stop the task. Give the message to the user. If the free ranges are too small for the copier and the bytes below $0400, the reason gives the largest free ranges. Write the loader by hand. If the unpack check of Exomizer fails, give the reason to the user.
|
|
285
306
|
- `loader.verified: false` with `differences`: the loader ran, and `differences` gives the bytes and registers that are not equal.
|
|
286
|
-
- `loader.verified: false` with `stop`: the loader did not get to its copier or to its jump. `stop` gives the address where it stopped and `port`, the value of $01. `history` gives the last 16 instructions. `cause` gives the first byte of the copier that is not equal to its byte in the loader file. If the copier ran, `cause` can also give the first byte that a copy did not write correctly.
|
|
307
|
+
- `loader.verified: false` with `stop`: the loader did not get to its copier or to its jump. `stop` gives the address where it stopped and `port`, the value of $01. `history` gives the last 16 instructions. `cause` gives the first byte of the copier that is not equal to its byte in the loader file. For a packed loader, `cause` gives the first byte of the copier that the unpack did not write. If the copier ran, `cause` can also give the first byte that a copy did not write correctly.
|
|
287
308
|
- `export` with `stage: "original"`: the source of the knowledge does not pass. Run `generate`, and correct the knowledge until `generate` gives PASS.
|
|
288
309
|
- `export` with `stage: "switches"`: the build with the export values changes bytes outside the patches, or a patch does not fit. Read `build`. Correct the patches.
|
|
289
310
|
- `export` refuses two switches that change one range: the export puts both alternatives in. Give all but one of them the kind `change` and the default of the base release with `switch` of the c64-knowledge skill.
|
|
@@ -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" };
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
// A person plays the program in the replay core: a page
|
|
2
|
-
// the screen and sends the keyboard and gamepad. The machine is frozen at the
|
|
1
|
+
// A person plays the program in the replay core: a page shows the screen and sends the keyboard and gamepad. The machine is frozen at the
|
|
3
2
|
// start screen until Start on the page; then the core runs one frame each
|
|
4
3
|
// 20 ms. End freezes it again and the recording is saved; Cancel ends the
|
|
5
4
|
// session without one. The reads of the program keep the input, so the
|
|
6
5
|
// recording needs nothing from the page. RESTORE is no read: it is an event
|
|
7
|
-
// of the recording (see record in recording.ts).
|
|
6
|
+
// of the recording (see record in recording.ts). The page listens on every
|
|
7
|
+
// address: in a dev container, a forward of the port from the host needs that.
|
|
8
8
|
|
|
9
9
|
import { createServer, type ServerResponse } from "node:http";
|
|
10
10
|
|
|
@@ -287,7 +287,7 @@ export async function play(core: Pick<C64RunSession, "command" | "status">, opti
|
|
|
287
287
|
response.writeHead(404).end();
|
|
288
288
|
}
|
|
289
289
|
});
|
|
290
|
-
await new Promise<void>((resolve) => server.listen(options.httpPort, "
|
|
290
|
+
await new Promise<void>((resolve) => server.listen(options.httpPort, "0.0.0.0", resolve));
|
|
291
291
|
const address = server.address();
|
|
292
292
|
options.ready("http://localhost:" + (typeof address === "object" && address !== null ? address.port : options.httpPort) + "/");
|
|
293
293
|
let tick = (await core.status("status")).tick;
|
|
@@ -76,7 +76,7 @@ async function recordCommand(call: Call): Promise<Record<string, unknown>> {
|
|
|
76
76
|
const person = playing
|
|
77
77
|
? (session: C64RunSession, restore: () => Promise<string | undefined>) => {
|
|
78
78
|
const ready = (url: string) =>
|
|
79
|
-
process.stderr.write("Open " + url + ". The start screen is frozen. Enter or Start begins the play, F12 or End saves the recording, F11 or Cancel ends without one. F9 changes the joystick port.\n");
|
|
79
|
+
process.stderr.write("Open " + url + ". In a dev container, forward port " + new URL(url).port + " to this computer first. The start screen is frozen. Enter or Start begins the play, F12 or End saves the recording, F11 or Cancel ends without one. F9 changes the joystick port.\n");
|
|
80
80
|
return play(session, { httpPort, joystick, ready, restore });
|
|
81
81
|
}
|
|
82
82
|
: undefined;
|
|
@@ -33,7 +33,7 @@ node <skill>/scripts/unpacker.ts loads original/game.d64 --steps .c64-re-tools/l
|
|
|
33
33
|
| `--until '$c000'` | `capture`: the address where the unpacked program starts. The capture stops there after the steps. To capture a later arrival at the address, add a `runUntil` step to an address after the first arrival. |
|
|
34
34
|
| `--out .c64-re-tools/local/capture` | `capture` and `loads`: the folder for the result, relative to the project folder. |
|
|
35
35
|
| `--range '$c000-$cfff'` | `capture` only: write this range as the one segment. Without it, the segments are the blocks that the stages wrote. The range must hold the `--until` address. |
|
|
36
|
-
| `--exclude '$a000-$a9ff'` | `capture`
|
|
36
|
+
| `--exclude '$a000-$a9ff'` | `capture` and `loads`: remove this range from the segments. You can give it more than once. `image.json` lists the ranges in `excluded`. For `capture`, the range must not hold the `--until` address. |
|
|
37
37
|
| `--timeout-frames 3000` | `capture` only: how many frames the program can run before the capture stops (default 3000). |
|
|
38
38
|
| `--frames 3000` | `trace` and `stages`: how many frames the program runs (default 3000). |
|
|
39
39
|
| `--entry '$c000'` | `trace`, `stages` and `capture`: start the program at this address. Without it, the script types RUN. A file that is not a BASIC program at `$0801` needs it. |
|
|
@@ -43,7 +43,7 @@ node <skill>/scripts/unpacker.ts loads original/game.d64 --steps .c64-re-tools/l
|
|
|
43
43
|
| `--min-block 64` | `loads` only: the smallest block of changed memory that becomes a segment (default 64). The result counts smaller changes as `smallChanges`. |
|
|
44
44
|
| `--min-stage 64` | `stages` and `capture`: the smallest block of written memory that starts a new stage when the CPU executes it (default 64). It does not change `wrote` or the segments. |
|
|
45
45
|
|
|
46
|
-
The capture reads RAM, also the RAM under the ROMs and the I/O area. The script refuses an option that the command does not use. It refuses a wrong `--range` or `--exclude` before the emulator starts.
|
|
46
|
+
The capture reads RAM, also the RAM under the ROMs and the I/O area. A segment can be in the RAM under the I/O area at `$d000`-`$dfff`. VICE shows each write there as an I/O write. Thus the script compares that RAM at the end of each stage or capture. The script refuses an option that the command does not use. It refuses a wrong `--range` or `--exclude` before the emulator starts.
|
|
47
47
|
|
|
48
48
|
A steps file is a JSON list of steps. Each step has the input of the MCP tool of the same action. An address in a step can be a name. The script refuses an unknown name before the emulator starts. The message gives the file and the step. For example, wait 50 frames and type a space:
|
|
49
49
|
|
|
@@ -134,7 +134,7 @@ A multi-load program loads more parts from the disk while it runs, for example o
|
|
|
134
134
|
]
|
|
135
135
|
```
|
|
136
136
|
|
|
137
|
-
2. Run `loads` with the steps file and a directory in `--out`. Add `--drive` when the program has its own drive code, for example a fast loader.
|
|
137
|
+
2. Run `loads` with the steps file and a directory in `--out`. Add `--drive` when the program has its own drive code, for example a fast loader. Add `--exclude` for each range of a loader, an intro or a loading picture that the program does not read. The script removes these ranges from the segments of each capture.
|
|
138
138
|
3. Each capture writes `<out>/<name>/` with `image.bin`, `image.json`, `entry_state.json` and a PRG for each segment. It removes the segment PRGs and the `drive8.prg` of an earlier capture that the new `image.json` does not list. A segment is a block of RAM from `$0400` that the program changed after the capture before. The first capture also has the program itself.
|
|
139
139
|
4. Put the part that you work on into the knowledge with `image <out>/<name>/image.json` of the c64-knowledge skill.
|
|
140
140
|
5. With `--drive`, `drive8.prg` is the drive RAM at `$0000`-`$07ff`. Put it into the knowledge with `image <out>/<name>/drive8.prg --space drive8`. Then analyze it with c64-static-analysis and `--space drive8`.
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
// image with its entry state, and with --drive the drive RAM as a PRG for
|
|
5
5
|
// knowledge space drive8. No tool guesses where a load ends: the steps decide.
|
|
6
6
|
|
|
7
|
-
import { COVERAGE, formatC64Address } from "#src/c64.ts";
|
|
7
|
+
import { type AddressRange, COVERAGE, formatC64Address } from "#src/c64.ts";
|
|
8
8
|
import { autostartLoaded, LOAD_LIMIT_FRAMES, RUN_LIMIT_FRAMES, typeRun } from "#src/host-client/autostart.ts";
|
|
9
|
-
import { readCoverage } from "#src/host-client/coverage.ts";
|
|
9
|
+
import { IO_RAM, markIoRamWrites, readCoverage } from "#src/host-client/coverage.ts";
|
|
10
10
|
import { ACTION_STEP_KINDS, checkActionStep, checkStepNames, isObject, runActionStep, VICE_STEP_KINDS, type ActionStep, type ActionStepKind } from "#src/host-client/steps.ts";
|
|
11
11
|
import { knowledgeAt } from "#src/knowledge/names.ts";
|
|
12
12
|
import { WireFailure } from "#src/host-client/tools.ts";
|
|
@@ -88,6 +88,17 @@ export function changedBlocks(before: Uint8Array, after: Uint8Array, map: Uint8A
|
|
|
88
88
|
return blocks.filter((block) => block.changed).map(({ start, end, bytes }) => ({ start, end, bytes }));
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
+
/**
|
|
92
|
+
* The blocks of a capture: the changed blocks, also in the RAM under the I/O
|
|
93
|
+
* area, which the map gives as I/O writes. An excluded range holds no write,
|
|
94
|
+
* so it cuts the blocks and counts in no small change. Changes `map`.
|
|
95
|
+
*/
|
|
96
|
+
export function captureBlocks(before: Uint8Array, after: Uint8Array, map: Uint8Array, writesKnown: boolean, exclude: readonly AddressRange[]): Array<{ start: number; end: number; bytes: number }> {
|
|
97
|
+
markIoRamWrites(map, before.subarray(IO_RAM.start, IO_RAM.end + 1), after.subarray(IO_RAM.start, IO_RAM.end + 1));
|
|
98
|
+
for (const range of exclude) map.fill(0, range.start, range.end + 1);
|
|
99
|
+
return changedBlocks(before, after, map, 16, writesKnown);
|
|
100
|
+
}
|
|
101
|
+
|
|
91
102
|
const hex4 = (value: number) => value.toString(16).padStart(4, "0");
|
|
92
103
|
|
|
93
104
|
/**
|
|
@@ -96,7 +107,7 @@ const hex4 = (value: number) => value.toString(16).padStart(4, "0");
|
|
|
96
107
|
* `drive` the drive RAM as drive8.prg. Blocks below `minBlock` bytes are
|
|
97
108
|
* counted, not written: a game changes its variables all the time.
|
|
98
109
|
*/
|
|
99
|
-
export async function loads(program: string, options: { out: string; steps: LoadStep[]; drive: boolean; minBlock: number }): Promise<{ output: Record<string, unknown>; failed: boolean }> {
|
|
110
|
+
export async function loads(program: string, options: { out: string; steps: LoadStep[]; drive: boolean; minBlock: number; exclude: AddressRange[] }): Promise<{ output: Record<string, unknown>; failed: boolean }> {
|
|
100
111
|
const client = await ViceSessionClient.open({ videoStandard: "pal" });
|
|
101
112
|
try {
|
|
102
113
|
// A clean machine at the READY prompt shows what the program changed at each capture. The run goes on after a capture, so it is read first.
|
|
@@ -159,7 +170,7 @@ export async function loads(program: string, options: { out: string; steps: Load
|
|
|
159
170
|
for (let address = load; address < Math.min(0x10000, load + loadedProgram.length - 2); address++) map[address]! |= COVERAGE.ramWrite;
|
|
160
171
|
loadedProgram = undefined;
|
|
161
172
|
}
|
|
162
|
-
const blocks =
|
|
173
|
+
const blocks = captureBlocks(previous, memory, map, writesKnown, options.exclude);
|
|
163
174
|
const segments = blocks.filter((block) => block.end - block.start + 1 >= options.minBlock);
|
|
164
175
|
const small = blocks.filter((block) => !segments.includes(block)).reduce((sum, block) => sum + block.bytes, 0);
|
|
165
176
|
const state = await machineState(client);
|
|
@@ -186,6 +197,7 @@ export async function loads(program: string, options: { out: string; steps: Load
|
|
|
186
197
|
capture: step.capture,
|
|
187
198
|
entry: formatC64Address(registers.pc),
|
|
188
199
|
segments: segments.map((segment, at) => ({ ...showRange(segment), file: files[at] })),
|
|
200
|
+
...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
|
|
189
201
|
vectors,
|
|
190
202
|
image: "image.bin",
|
|
191
203
|
...(drive === undefined ? {} : { drive }),
|
|
@@ -204,6 +216,7 @@ export async function loads(program: string, options: { out: string; steps: Load
|
|
|
204
216
|
pc: formatC64Address(registers.pc),
|
|
205
217
|
...(keyWait ? { keyWait: true } : {}),
|
|
206
218
|
segments: segments.map(showRange),
|
|
219
|
+
...(options.exclude.length === 0 ? {} : { excluded: options.exclude.map(showRange) }),
|
|
207
220
|
differsFromReset: entry.differsFromReset,
|
|
208
221
|
...(small === 0 ? {} : { smallChanges: small }),
|
|
209
222
|
...(drive === undefined ? {} : { drive: drive.file }),
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
import { type AddressRange, COVERAGE, EXECUTE, formatC64Address, READ, WRITE } from "#src/c64.ts";
|
|
10
10
|
import { autostartLoaded, LOAD_LIMIT_FRAMES, RUN_LIMIT_FRAMES, typeRun } from "#src/host-client/autostart.ts";
|
|
11
|
-
import { readCoverage, writtenBlocks } from "#src/host-client/coverage.ts";
|
|
11
|
+
import { IO_RAM, markIoRamWrites, readCoverage, writtenBlocks } from "#src/host-client/coverage.ts";
|
|
12
12
|
import { readActionSteps, runActionStep, type ActionStep } from "#src/host-client/steps.ts";
|
|
13
13
|
import { WireFailure } from "#src/host-client/tools.ts";
|
|
14
14
|
import { readPrg } from "#src/host-client/image.ts";
|
|
@@ -226,6 +226,14 @@ async function follow(
|
|
|
226
226
|
const basic = basicStart(bytes);
|
|
227
227
|
const notStarted = await startLoaded(client, program, bytes, options.entry);
|
|
228
228
|
if (notStarted !== undefined) return { stages: [], frames: 0, reached: false, failed: notStarted };
|
|
229
|
+
// The map gives a write to the RAM under the I/O area as an I/O write: a compare of that RAM at each stage end finds them.
|
|
230
|
+
const readIoRam = () => readRam(client, IO_RAM.start, IO_RAM.end - IO_RAM.start + 1);
|
|
231
|
+
let ioRam = await readIoRam();
|
|
232
|
+
const markIoRam = async (map: Uint8Array) => {
|
|
233
|
+
const now = await readIoRam();
|
|
234
|
+
markIoRamWrites(map, ioRam, now);
|
|
235
|
+
ioRam = now;
|
|
236
|
+
};
|
|
229
237
|
// The frames of each step end where a scenario's do: the first step counts from RUN, a later one from where it starts.
|
|
230
238
|
let anchor: { line: number; cycle: number } | undefined = await rasterAt(client);
|
|
231
239
|
const framed = () => (anchor === undefined ? {} : { anchor });
|
|
@@ -244,6 +252,7 @@ async function follow(
|
|
|
244
252
|
let stage = { map: new Uint8Array(0x10000), own: new Set<number>(), called: [] as AddressRange[] };
|
|
245
253
|
const startStage = async (next: number, last: Uint8Array) => {
|
|
246
254
|
mergeMaps(stage.map, last);
|
|
255
|
+
await markIoRam(stage.map);
|
|
247
256
|
found.push({ entry, firstFrame, frames: total - firstFrame, wrote: stageWrote(stage.map), next });
|
|
248
257
|
entry = next;
|
|
249
258
|
firstFrame = total;
|
|
@@ -434,6 +443,7 @@ async function follow(
|
|
|
434
443
|
else reached = await trackTo(options.until, left);
|
|
435
444
|
await client.snapshot({ action: "remove", name: STAGE_SNAPSHOT }).catch(() => undefined);
|
|
436
445
|
mergeMaps(stage.map, await readCoverage(client));
|
|
446
|
+
await markIoRam(stage.map);
|
|
437
447
|
found.push({ entry, firstFrame, frames: total - firstFrame, wrote: stageWrote(stage.map) });
|
|
438
448
|
return { stages: found, frames: total, reached, ...(halted === undefined ? {} : { halted }) };
|
|
439
449
|
}
|
|
@@ -562,6 +572,7 @@ const PROGRAM = { name: "<program>", help: "a PRG file, relative to the project
|
|
|
562
572
|
const FRAMES: OptionSpec = { ...OPTIONS.frames, max: 30_000, default: 3000, help: "run the program for n frames (default 3000)" };
|
|
563
573
|
const ENTRY: OptionSpec = { ...OPTIONS.entry, help: "start the program here in place of RUN" };
|
|
564
574
|
const STEPS: OptionSpec = { ...OPTIONS.steps, help: "action steps (JSON) that run right after the program starts, for example to press a key in an intro or to get through a menu" };
|
|
575
|
+
const EXCLUDE: OptionSpec = { kind: "range", value: "<start>-<end>", multiple: true, help: "a range to leave out of the segments, for example bytes that a crack left and the program never reads" };
|
|
565
576
|
const MIN_STAGE: OptionSpec = { kind: "count", value: "<bytes>", min: 1, max: 0x10000, default: 64, help: "a stage starts when the CPU executes a block of at least this many bytes that the stage before wrote (default 64)" };
|
|
566
577
|
|
|
567
578
|
/** The result of a command: PASS, or FAIL with the reason. */
|
|
@@ -611,7 +622,7 @@ const COMMANDS: CommandSpec[] = [
|
|
|
611
622
|
until: { kind: "address", value: "<address>", required: true, help: "the unpacked entry point" },
|
|
612
623
|
out: { ...OPTIONS.out, output: "folder", value: "<dir>", required: true, help: "the folder for the capture, relative to the project folder" },
|
|
613
624
|
range: { ...OPTIONS.range, help: "one segment in place of the found ones" },
|
|
614
|
-
exclude:
|
|
625
|
+
exclude: EXCLUDE,
|
|
615
626
|
"timeout-frames": { ...OPTIONS["timeout-frames"], max: 30_000, default: 3000, help: "stop the wait for --until after n frames (default 3000)" },
|
|
616
627
|
entry: ENTRY,
|
|
617
628
|
steps: STEPS,
|
|
@@ -639,8 +650,9 @@ const COMMANDS: CommandSpec[] = [
|
|
|
639
650
|
out: { ...OPTIONS.out, output: "folder", value: "<dir>", required: true, help: "the folder for the captures, relative to the project folder" },
|
|
640
651
|
drive: { kind: "flag", help: "also write the 2 KiB drive RAM as drive8.prg, for knowledge space drive8" },
|
|
641
652
|
"min-block": { kind: "count", value: "<bytes>", min: 1, max: 0x10000, default: 64, help: "write a changed block of at least this many bytes (default 64)" },
|
|
653
|
+
exclude: EXCLUDE,
|
|
642
654
|
},
|
|
643
|
-
run: async (call) => outcome(await loads(call.subject(0), { out: call.string("out")!, steps: readLoadSteps(call.string("steps")!), drive: call.flag("drive"), minBlock: call.count("min-block")
|
|
655
|
+
run: async (call) => outcome(await loads(call.subject(0), { out: call.string("out")!, steps: readLoadSteps(call.string("steps")!), drive: call.flag("drive"), minBlock: call.count("min-block")!, exclude: call.ranges("exclude") })),
|
|
644
656
|
},
|
|
645
657
|
];
|
|
646
658
|
|
package/src/compare.ts
CHANGED
|
@@ -47,3 +47,21 @@ export function compareBuild(prg: Uint8Array, program: Reference): { identical:
|
|
|
47
47
|
});
|
|
48
48
|
return { identical: checks.every((check) => check.result === "identical"), segments: checks };
|
|
49
49
|
}
|
|
50
|
+
|
|
51
|
+
/** PRG files merged in load order, as the reference of a check: a later file wins where two overlap. */
|
|
52
|
+
export function mergedPrograms(programs: ReadonlyArray<{ start: number; body: Uint8Array }>): Reference {
|
|
53
|
+
const memory = new Uint8Array(0x10000);
|
|
54
|
+
const loaded = new Uint8Array(0x10000);
|
|
55
|
+
for (const { start, body } of programs) {
|
|
56
|
+
memory.set(body, start);
|
|
57
|
+
loaded.fill(1, start, start + body.length);
|
|
58
|
+
}
|
|
59
|
+
const segments: Array<{ start: number; end: number }> = [];
|
|
60
|
+
for (let address = 0; address < 0x10000; address++) {
|
|
61
|
+
if (loaded[address] === 0) continue;
|
|
62
|
+
const last = segments.at(-1);
|
|
63
|
+
if (last !== undefined && last.end === address - 1) last.end = address;
|
|
64
|
+
else segments.push({ start: address, end: address });
|
|
65
|
+
}
|
|
66
|
+
return { segments, byteAt: (address) => memory[address]! };
|
|
67
|
+
}
|
|
@@ -19,6 +19,32 @@ export async function readCoverage(session: Pick<ViceSessionClient, "memmap">, s
|
|
|
19
19
|
return map;
|
|
20
20
|
}
|
|
21
21
|
|
|
22
|
+
/** The I/O area. VICE maps every write there as an I/O write, also one with the RAM banked in by $01. */
|
|
23
|
+
export const IO_RAM = { start: 0xd000, end: 0xdfff } as const;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Marks the RAM writes under the I/O area in a map from $0000, from two reads
|
|
27
|
+
* of that RAM. The RAM there changes only by a write with the I/O area banked
|
|
28
|
+
* out. A run of written or changed bytes is RAM written when one byte of it
|
|
29
|
+
* changed: a byte written with the value that was there is part of it too.
|
|
30
|
+
* A run of register writes changes no RAM. `before` and `after` hold $d000-$dfff.
|
|
31
|
+
*/
|
|
32
|
+
export function markIoRamWrites(map: Uint8Array, before: Uint8Array, after: Uint8Array): void {
|
|
33
|
+
const size = IO_RAM.end - IO_RAM.start + 1;
|
|
34
|
+
const written = (offset: number) => before[offset] !== after[offset] || (map[IO_RAM.start + offset]! & (COVERAGE.ioWrite | COVERAGE.ramWrite)) !== 0;
|
|
35
|
+
for (let start = 0; start < size; ) {
|
|
36
|
+
if (!written(start)) {
|
|
37
|
+
start++;
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
let end = start;
|
|
41
|
+
let changed = false;
|
|
42
|
+
for (; end < size && written(end); end++) changed ||= before[end] !== after[end];
|
|
43
|
+
if (changed) for (let offset = start; offset < end; offset++) map[IO_RAM.start + offset]! |= COVERAGE.ramWrite;
|
|
44
|
+
start = end;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
22
48
|
/** Runs of RAM that a program wrote, at least `minimum` bytes each, in a map from $0000. */
|
|
23
49
|
export function writtenBlocks(map: Uint8Array, minimum: number): CodeRange[] {
|
|
24
50
|
const blocks: CodeRange[] = [];
|