@henols/c64-re-tools 2.2.0-rc.2 → 2.2.0-rc.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -73,7 +73,7 @@ function rangesWhere(has: (address: number) => boolean): AddressRange[] {
73
73
  }
74
74
 
75
75
  /** The memory rows of the segments: at most MEMORY_ROW bytes, never across a multiple of MEMORY_ROW. */
76
- function memoryRows(segments: readonly AddressRange[], byteAt: (address: number) => number): Map<number, string> {
76
+ export function memoryRows(segments: readonly AddressRange[], byteAt: (address: number) => number): Map<number, string> {
77
77
  const rows = new Map<number, string>();
78
78
  for (const segment of segments) {
79
79
  for (let at = segment.start; at <= segment.end; ) {
@@ -6,7 +6,7 @@
6
6
  // or executes outside the image. Evidence only: nothing here decides what is
7
7
  // original.
8
8
 
9
- import { type AddressRange, COVERAGE, executedRamCode, instructionLength } from "#src/c64.ts";
9
+ import { type AddressRange, COVERAGE, executedRamCode, instructionLength } from "../c64.ts";
10
10
 
11
11
  export type Access = "executed" | "read" | "written" | "read-written" | "untouched";
12
12
 
@@ -21,6 +21,8 @@ export interface SeparationInput {
21
21
  coverage?: Uint8Array;
22
22
  codeRegions: Array<AddressRange & { type: string }>;
23
23
  references: Array<{ from: number; to: number; kind: string }>;
24
+ /** More roots after the entry and the hardware vectors, for example code that a run executed. */
25
+ roots?: Root[];
24
26
  }
25
27
 
26
28
  export interface EvidenceRange extends AddressRange {
@@ -37,14 +39,14 @@ export interface CodeRegionEvidence extends AddressRange {
37
39
  executed?: boolean;
38
40
  }
39
41
 
40
- /** An address where the reachability starts, and why: the entry, or a hardware vector in the image. */
42
+ /** An address where the reachability starts, and why: the entry, a hardware vector in the image, or a root that the caller gives. */
41
43
  export interface Root {
42
44
  address: number;
43
- from: "entry" | "NMI vector $fffa" | "RESET vector $fffc" | "IRQ vector $fffe";
45
+ from: "entry" | "NMI vector $fffa" | "RESET vector $fffc" | "IRQ vector $fffe" | "executed code" | "kept range" | "table entry";
44
46
  }
45
47
 
46
48
  export interface Separation {
47
- /** The roots of the reachability, in the order entry, NMI, RESET, IRQ. */
49
+ /** The roots of the reachability, in the order entry, NMI, RESET, IRQ, then the roots of the input. */
48
50
  roots: Root[];
49
51
  ranges: EvidenceRange[];
50
52
  codeRegions: CodeRegionEvidence[];
@@ -78,7 +80,7 @@ export function reachabilityRoots(segments: readonly AddressRange[], memory: Uin
78
80
  }
79
81
 
80
82
  /** BRK, JMP, RTI, RTS, JMP (indirect) and the JAM opcodes: the CPU does not run on to the next instruction after them. */
81
- const NO_FALL_THROUGH = new Set([0x00, 0x4c, 0x40, 0x60, 0x6c, 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72, 0x92, 0xb2, 0xd2, 0xf2]);
83
+ export const NO_FALL_THROUGH = new Set([0x00, 0x4c, 0x40, 0x60, 0x6c, 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72, 0x92, 0xb2, 0xd2, 0xf2]);
82
84
 
83
85
  /**
84
86
  * The address after a code region where the CPU runs on, or undefined when
@@ -141,13 +143,14 @@ export function separate(input: SeparationInput): Separation {
141
143
  }
142
144
  }
143
145
 
144
- // Reachability: from the regions that hold a root, through call and jump references and the run on
145
- // from the last instruction of a region into the next address, to a fixed point.
146
146
  const regions = input.codeRegions.filter((region) => input.segments.some((segment) => region.start <= segment.end && segment.start <= region.end));
147
- const holding = (address: number) => regions.findIndex((region) => address >= region.start && address <= region.end);
148
- const roots = reachabilityRoots(input.segments, input.memory, input.entry);
149
- const reached = new Set<number>();
150
- for (const root of roots) if (holding(root.address) >= 0) reached.add(holding(root.address));
147
+ // The region of each address: the first region that holds it, as a search in region order finds it.
148
+ const owner = new Int32Array(0x10000).fill(-1);
149
+ regions.forEach((region, index) => {
150
+ for (let address = Math.max(region.start, 0); address <= Math.min(region.end, 0xffff); address++) if (owner[address] === -1) owner[address] = index;
151
+ });
152
+ const holding = (address: number) => (address >= 0 && address <= 0xffff ? owner[address]! : -1);
153
+ const roots = [...reachabilityRoots(input.segments, input.memory, input.entry), ...(input.roots ?? [])];
151
154
  // The CPU runs the bytes after the region as instructions: through bytes of no code region (a dual-use
152
155
  // instruction, for example) into the next code region, unless one of them does not run on.
153
156
  const runOn = (from: number): number | undefined => {
@@ -164,16 +167,27 @@ export function separate(input: SeparationInput): Separation {
164
167
  const to = next === undefined ? undefined : runOn(next);
165
168
  return to === undefined ? [] : [{ from: region.end, to }];
166
169
  });
167
- const flows = [...input.references.filter((reference) => reference.kind === "call" || reference.kind === "jump"), ...runsOn];
168
- for (let grown = true; grown; ) {
169
- grown = false;
170
- for (const flow of flows) {
171
- const from = holding(flow.from);
172
- const to = holding(flow.to);
173
- if (from >= 0 && to >= 0 && reached.has(from) && !reached.has(to)) {
174
- reached.add(to);
175
- grown = true;
176
- }
170
+ // From the regions that hold a root, through call and jump references and the run on, to every region they reach.
171
+ const next = regions.map((): number[] => []);
172
+ for (const flow of [...input.references.filter((reference) => reference.kind === "call" || reference.kind === "jump"), ...runsOn]) {
173
+ const from = holding(flow.from);
174
+ const to = holding(flow.to);
175
+ if (from >= 0 && to >= 0) next[from]!.push(to);
176
+ }
177
+ const reached = new Set<number>();
178
+ const queue: number[] = [];
179
+ for (const root of roots) {
180
+ const index = holding(root.address);
181
+ if (index >= 0 && !reached.has(index)) {
182
+ reached.add(index);
183
+ queue.push(index);
184
+ }
185
+ }
186
+ while (queue.length > 0) {
187
+ for (const to of next[queue.pop()!]!) {
188
+ if (reached.has(to)) continue;
189
+ reached.add(to);
190
+ queue.push(to);
177
191
  }
178
192
  }
179
193
  const codeRegions = regions.map((region, index): CodeRegionEvidence => {
@@ -4,6 +4,7 @@
4
4
  import { existsSync, readFileSync } from "node:fs";
5
5
  import { isAbsolute, join, relative, sep } from "node:path";
6
6
 
7
+ import { formatC64Address } from "../c64.ts";
7
8
  import { WireFailure } from "../protocol/messages.ts";
8
9
  import { isRelativePath } from "../protocol/tools.ts";
9
10
  import type { AcmeParams, AcmeResult, AssembledSymbol, Diagnostic } from "./types.ts";
@@ -11,6 +12,16 @@ import { Workspace } from "./staging.ts";
11
12
  import { ACME, findTool } from "./discover.ts";
12
13
  import { outputTail, runToolOrFail, type ToolContext } from "./run.ts";
13
14
 
15
+ /** A symbol of a build as a person and c64-testing read it: an address as $ and four hex digits, a constant as $ and at least four hex digits. */
16
+ export function showSymbol(symbol: AssembledSymbol) {
17
+ return symbol.kind === "address"
18
+ ? { name: symbol.name, kind: "address", address: formatC64Address(symbol.address), used: symbol.used }
19
+ : { name: symbol.name, kind: "constant", value: `$${symbol.value.toString(16).padStart(4, "0")}`, used: symbol.used };
20
+ }
21
+
22
+ /** The text of a symbols file (--out-symbols): the symbols of a build, which c64-testing reads for the names of a program. */
23
+ export const symbolsFileText = (symbols: readonly AssembledSymbol[]) => `${JSON.stringify({ symbols: symbols.map(showSymbol) }, null, 1)}\n`;
24
+
14
25
  const PROGRAM = "program.prg";
15
26
  const SYMBOLS = "symbols.txt";
16
27
  const TIMEOUT_MS = 60_000;
package/src/project.ts CHANGED
@@ -7,7 +7,7 @@
7
7
  import { Refusal } from "./errors.ts";
8
8
  import { accessSync, constants, existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, statSync, writeFileSync } from "node:fs";
9
9
  import { homedir } from "node:os";
10
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
10
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
11
11
 
12
12
  /** The folder that marks a project and holds its knowledge. */
13
13
  export const PROJECT_DIRECTORY = ".c64-re-tools";
@@ -130,6 +130,30 @@ export function namedProject(folder: string, cwd: string = process.cwd()): strin
130
130
  return path;
131
131
  }
132
132
 
133
+ /**
134
+ * The folder of a new project that `folder` names, relative to the project
135
+ * `currentRoot` or absolute, and the zip file beside it (`<folder>.zip`). The
136
+ * folder must not exist or be empty. It must be outside the current project
137
+ * and must not hold it, and no folder above it is a project: then the new
138
+ * project is a project of its own.
139
+ */
140
+ export function newProjectFolder(folder: string, currentRoot: string): { root: string; zip: string } {
141
+ if (folder.length === 0) throw new Refusal("invalid-input", "The folder of the new project must not be empty.");
142
+ const root = resolve(currentRoot, folder);
143
+ const zip = `${root}.zip`;
144
+ if (dirname(root) === root) throw new Refusal("invalid-input", `${folder} is the root of a file system. Give a folder for the new project.`);
145
+ if (root === homedir()) throw new Refusal("invalid-input", "The home folder cannot be the folder of a new project.");
146
+ if (isInside(currentRoot, root)) throw new Refusal("invalid-input", `${folder} is inside the project ${currentRoot}. Give a folder outside it, for example ../${basename(root)}.`);
147
+ if (isInside(root, currentRoot)) throw new Refusal("invalid-input", `${folder} holds the project ${currentRoot}. Give a folder outside it.`);
148
+ const outer = foldersUpFrom(root).slice(1).find(isProject);
149
+ if (outer !== undefined) throw new Refusal("invalid-input", `${folder} is inside the project ${outer}. Give a folder that is in no project.`);
150
+ const stat = statSync(root, { throwIfNoEntry: false });
151
+ if (stat !== undefined && !stat.isDirectory()) throw new Refusal("invalid-input", `${folder} is not a folder.`);
152
+ if (stat !== undefined && readdirSync(root).length > 0) throw new Refusal("conflict", `${folder} is not empty. Give a new or empty folder, or remove the folder of an earlier export.`);
153
+ if (existsSync(zip)) throw new Refusal("conflict", `${zip} exists. Remove the zip file of an earlier export, or give another folder.`);
154
+ return { root, zip };
155
+ }
156
+
133
157
  /**
134
158
  * Makes .c64-re-tools/local/ with its .gitignore when the project has
135
159
  * .c64-re-tools/ and local/ has no .gitignore yet. A folder that is not
package/src/zip.ts ADDED
@@ -0,0 +1,89 @@
1
+ // A zip archive of files given as bytes. The same files give the same bytes:
2
+ // the entries are in path order, each has the time 1980-01-01 00:00, and no
3
+ // field depends on the machine. Each file is deflated, or stored when deflate
4
+ // does not make it smaller. No ZIP64: an archive that needs it is refused.
5
+
6
+ import { crc32, deflateRawSync } from "node:zlib";
7
+
8
+ import { Refusal } from "./errors.ts";
9
+
10
+ export interface ZipEntry {
11
+ /** The path in the archive, with / between the parts. */
12
+ path: string;
13
+ bytes: Uint8Array;
14
+ }
15
+
16
+ const LOCAL_SIGNATURE = 0x04034b50;
17
+ const CENTRAL_SIGNATURE = 0x02014b50;
18
+ const END_SIGNATURE = 0x06054b50;
19
+ /** Version 2.0: deflate. */
20
+ const VERSION = 20;
21
+ /** Bit 11: the path is UTF-8. */
22
+ const UTF8_FLAG = 0x0800;
23
+ const STORED = 0;
24
+ const DEFLATED = 8;
25
+ /** 1980-01-01 in MS-DOS date format; the time is 00:00. */
26
+ const DOS_DATE = (1 << 5) | 1;
27
+ const LIMIT = 0xffffffff;
28
+ const MAX_ENTRIES = 0xffff;
29
+
30
+ /** The archive of the entries, sorted by path. Refuses a duplicate or an unsafe path, and an archive that needs ZIP64. */
31
+ export function zipFiles(entries: readonly ZipEntry[]): Buffer {
32
+ const sorted = [...entries].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
33
+ if (sorted.length > MAX_ENTRIES) throw new Refusal("invalid-input", `A zip archive holds at most ${MAX_ENTRIES} files without ZIP64; this one has ${sorted.length}.`);
34
+ const locals: Buffer[] = [];
35
+ const centrals: Buffer[] = [];
36
+ let offset = 0;
37
+ sorted.forEach((entry, index) => {
38
+ const path = entry.path;
39
+ if (path === "" || path.startsWith("/") || path.includes("\\") || path.split("/").some((part) => part === "" || part === "." || part === "..")) {
40
+ throw new Refusal("invalid-input", `${JSON.stringify(path)} is not a relative path with / between its parts.`);
41
+ }
42
+ if (index > 0 && sorted[index - 1]!.path === path) throw new Refusal("invalid-input", `The zip archive has ${path} two times.`);
43
+ const name = Buffer.from(path, "utf8");
44
+ const deflated = deflateRawSync(entry.bytes, { level: 9 });
45
+ const method = deflated.length < entry.bytes.length ? DEFLATED : STORED;
46
+ const data = method === DEFLATED ? deflated : Buffer.from(entry.bytes);
47
+ if (entry.bytes.length > LIMIT || offset > LIMIT) throw new Refusal("invalid-input", `${path} is too large for a zip archive without ZIP64.`);
48
+ const crc = crc32(entry.bytes);
49
+
50
+ const local = Buffer.alloc(30);
51
+ local.writeUInt32LE(LOCAL_SIGNATURE, 0);
52
+ local.writeUInt16LE(VERSION, 4);
53
+ local.writeUInt16LE(UTF8_FLAG, 6);
54
+ local.writeUInt16LE(method, 8);
55
+ local.writeUInt16LE(0, 10);
56
+ local.writeUInt16LE(DOS_DATE, 12);
57
+ local.writeUInt32LE(crc, 14);
58
+ local.writeUInt32LE(data.length, 18);
59
+ local.writeUInt32LE(entry.bytes.length, 22);
60
+ local.writeUInt16LE(name.length, 26);
61
+ local.writeUInt16LE(0, 28);
62
+ locals.push(local, name, data);
63
+
64
+ const central = Buffer.alloc(46);
65
+ central.writeUInt32LE(CENTRAL_SIGNATURE, 0);
66
+ central.writeUInt16LE(VERSION, 4);
67
+ central.writeUInt16LE(VERSION, 6);
68
+ central.writeUInt16LE(UTF8_FLAG, 8);
69
+ central.writeUInt16LE(method, 10);
70
+ central.writeUInt16LE(0, 12);
71
+ central.writeUInt16LE(DOS_DATE, 14);
72
+ central.writeUInt32LE(crc, 16);
73
+ central.writeUInt32LE(data.length, 20);
74
+ central.writeUInt32LE(entry.bytes.length, 24);
75
+ central.writeUInt16LE(name.length, 28);
76
+ central.writeUInt32LE(offset, 42);
77
+ centrals.push(central, name);
78
+ offset += local.length + name.length + data.length;
79
+ });
80
+ const directory = Buffer.concat(centrals);
81
+ if (offset > LIMIT || directory.length > LIMIT) throw new Refusal("invalid-input", "The files are too large for a zip archive without ZIP64.");
82
+ const end = Buffer.alloc(22);
83
+ end.writeUInt32LE(END_SIGNATURE, 0);
84
+ end.writeUInt16LE(sorted.length, 8);
85
+ end.writeUInt16LE(sorted.length, 10);
86
+ end.writeUInt32LE(directory.length, 12);
87
+ end.writeUInt32LE(offset, 16);
88
+ return Buffer.concat([...locals, directory, end]);
89
+ }