fcdev 0.0.0-stage → 0.1.0

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.
Files changed (71) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +81 -2
  3. package/bin/fcdev.mjs +17 -0
  4. package/package.json +38 -4
  5. package/src/build/build-plan.mjs +92 -0
  6. package/src/build/dependency-file.mjs +24 -0
  7. package/src/build/disk-builder.mjs +36 -0
  8. package/src/build/index.mjs +31 -0
  9. package/src/build/program-builder.mjs +209 -0
  10. package/src/build/source-collector.mjs +54 -0
  11. package/src/build/tool-arguments.mjs +83 -0
  12. package/src/cli/args-parser.mjs +84 -0
  13. package/src/cli/commands/build-command.mjs +34 -0
  14. package/src/cli/commands/debug-command.mjs +70 -0
  15. package/src/cli/commands/disasm-command.mjs +65 -0
  16. package/src/cli/commands/disk-command.mjs +34 -0
  17. package/src/cli/commands/info-command.mjs +33 -0
  18. package/src/cli/commands/project-info.mjs +57 -0
  19. package/src/cli/commands/run-command.mjs +68 -0
  20. package/src/cli/commands/sync-command.mjs +85 -0
  21. package/src/cli/index.mjs +100 -0
  22. package/src/config/config-loader.mjs +132 -0
  23. package/src/config/index.mjs +9 -0
  24. package/src/disasm/analysis.mjs +97 -0
  25. package/src/disasm/cdl.mjs +35 -0
  26. package/src/disasm/disassembler.mjs +114 -0
  27. package/src/disasm/index.mjs +16 -0
  28. package/src/disasm/info-writer.mjs +72 -0
  29. package/src/disasm/loaders.mjs +69 -0
  30. package/src/disasm/opcode-table.mjs +268 -0
  31. package/src/disasm/roundtrip.mjs +69 -0
  32. package/src/disasm/symbols.mjs +30 -0
  33. package/src/disasm/trace.mjs +25 -0
  34. package/src/emulator/debug-client.mjs +125 -0
  35. package/src/emulator/emulator-launcher.mjs +80 -0
  36. package/src/emulator/emulator-locator.mjs +62 -0
  37. package/src/emulator/index.mjs +11 -0
  38. package/src/packagers/fat-floppy.mjs +22 -0
  39. package/src/packagers/fat12-image.mjs +245 -0
  40. package/src/packagers/flat-binary.mjs +53 -0
  41. package/src/packagers/index.mjs +54 -0
  42. package/src/packagers/ines.mjs +38 -0
  43. package/src/shared/errors.mjs +25 -0
  44. package/src/shared/fs-utils.mjs +66 -0
  45. package/src/shared/index.mjs +11 -0
  46. package/src/shared/process.mjs +50 -0
  47. package/src/targets/index.mjs +17 -0
  48. package/src/targets/name-rules.mjs +33 -0
  49. package/src/targets/target-registry.mjs +187 -0
  50. package/src/toolchain/index.mjs +16 -0
  51. package/src/toolchain/toolchain-locator.mjs +104 -0
  52. package/targets/nes/asminc/fcnes.inc +16 -0
  53. package/targets/nes/chr/ascii-8x8.chr +0 -0
  54. package/targets/nes/chr/font8x8_basic.h +152 -0
  55. package/targets/nes/include/fcnes.h +45 -0
  56. package/targets/nes/lib/fcnes.lib +0 -0
  57. package/targets/nes/lib/nes-font.o +0 -0
  58. package/targets/nes/lib-build.json +9 -0
  59. package/targets/nes/src/fcnes.s +91 -0
  60. package/targets/nes/src/nes-font.s +12 -0
  61. package/targets/nes/target.json +27 -0
  62. package/targets/sb2000/asminc/sb2000.inc +216 -0
  63. package/targets/sb2000/include/sb2000-symbols.h +380 -0
  64. package/targets/sb2000/include/sb2000.h +52 -0
  65. package/targets/sb2000/lib/crt0.o +0 -0
  66. package/targets/sb2000/lib/sb2000.lib +0 -0
  67. package/targets/sb2000/lib-build.json +8 -0
  68. package/targets/sb2000/link.cfg +35 -0
  69. package/targets/sb2000/src/crt0.s +37 -0
  70. package/targets/sb2000/src/sb2000.s +67 -0
  71. package/targets/sb2000/target.json +28 -0
@@ -0,0 +1,114 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:disassembler.mjs
3
+ // 说明:反汇编主流程:读取映像、追踪代码、生成 da65 信息文件、运行 da65、回读校验。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:产物放在输出目录:<名>.bin(映像)、<名>.info(信息文件)、<名>.s(ca65 源码);回读不一致时仍保留这些文件,并报错说明第一个差异的位置。
8
+ // ------------------------------------------------------------------------
9
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
10
+ import path from 'node:path';
11
+ import { FcdevError } from '../shared/index.mjs';
12
+ import { runTool } from '../toolchain/index.mjs';
13
+ import { KIND_UNKNOWN, analyzeCode } from './analysis.mjs';
14
+ import { parseCdl } from './cdl.mjs';
15
+ import { buildRanges, renderInfo } from './info-writer.mjs';
16
+ import { loadBinary, loadInes } from './loaders.mjs';
17
+ import { verifyRoundtrip } from './roundtrip.mjs';
18
+ import { parseSymbols } from './symbols.mjs';
19
+ import { parseTrace } from './trace.mjs';
20
+
21
+ /**
22
+ * @typedef {object} DisassemblyReport
23
+ * @property {string} sourceFile 生成的 ca65 源码
24
+ * @property {string} infoFile 生成的 da65 信息文件
25
+ * @property {string} imageFile 反汇编的映像
26
+ * @property {string} description 输入的来源说明
27
+ * @property {number} size 映像字节数
28
+ * @property {number} codeBytes 属于指令的字节数
29
+ * @property {number} instructions 指令条数
30
+ * @property {string[]} warnings 追踪中放弃某一路的原因
31
+ * @property {boolean} verified 回读与原映像逐字节一致
32
+ */
33
+
34
+ /**
35
+ * 判断输入格式。
36
+ * @param {Buffer} buffer 文件内容
37
+ * @param {string|undefined} format 用户指定的格式
38
+ * @returns {'ines'|'binary'} 格式
39
+ * @throws {FcdevError} 指定了不认识的格式
40
+ */
41
+ function detectFormat(buffer, format) {
42
+ if (format === 'ines' || format === 'binary') return format;
43
+ if (format !== undefined) throw new FcdevError(`不认识的输入格式:${format}`, { code: 'ARGUMENT_INVALID', hint: '可用的格式:ines、binary' });
44
+ return buffer.subarray(0, 4).toString('latin1') === 'NES\x1a' ? 'ines' : 'binary';
45
+ }
46
+
47
+ /**
48
+ * 反汇编一个文件,并回读校验。
49
+ * @param {{inputFile: string, format?: string, base?: number, entries?: number[], cdlFile?: string, traceFile?: string, symbolsFile?: string, outDir: string, toolchain: import('../toolchain/index.mjs').Toolchain, includes?: string[]}} input 输入文件、格式、加载地址、入口、CDL、模拟器轨迹、符号文件、输出目录、工具链与 da65 要读的符号定义文件
50
+ * @returns {Promise<DisassemblyReport>} 报告
51
+ * @throws {FcdevError} 输入不合法、da65 失败,或回读校验不一致
52
+ */
53
+ export async function disassemble({ inputFile, format, base, entries = [], cdlFile, traceFile, symbolsFile, outDir, toolchain, includes = [] }) {
54
+ const buffer = readFileSync(inputFile);
55
+ const kind = detectFormat(buffer, format);
56
+ if (kind === 'binary' && base === undefined) {
57
+ throw new FcdevError('平铺二进制需要指定加载地址', { code: 'ARGUMENT_MISSING', hint: '用 --base <十六进制地址> 指定,如 --base 8000' });
58
+ }
59
+ const image = kind === 'ines' ? loadInes(buffer) : loadBinary(buffer, { base });
60
+
61
+ const vectorEntries = image.vectors ? [image.vectors.reset, image.vectors.nmi, image.vectors.irq] : [];
62
+ const cdl = cdlFile ? parseCdl(readFileSync(cdlFile), image.bytes.length) : null;
63
+ const traced = traceFile ? parseTrace(readFileSync(traceFile, 'utf8')) : [];
64
+ const allEntries = [...new Set([...vectorEntries, ...entries, ...traced])];
65
+ if (allEntries.length === 0 && cdl === null) {
66
+ throw new FcdevError('没有入口可供追踪代码', { code: 'ARGUMENT_MISSING', hint: '用 --entry <十六进制地址> 指定入口,或用 --cdl、--trace 提供运行记录' });
67
+ }
68
+ const analysis = analyzeCode({ bytes: image.bytes, base: image.base, entries: allEntries, cdl });
69
+
70
+ const symbols = symbolsFile ? parseSymbols(readFileSync(symbolsFile, 'utf8')) : [];
71
+ const vectorLabels = image.vectors
72
+ ? [{ name: 'reset', address: image.vectors.reset }, { name: 'nmi', address: image.vectors.nmi }, { name: 'irq', address: image.vectors.irq }]
73
+ : [];
74
+ const name = path.basename(inputFile, path.extname(inputFile)).replace(/[^A-Za-z0-9_-]/g, '_') || 'image';
75
+
76
+ mkdirSync(outDir, { recursive: true });
77
+ const imageFile = path.join(outDir, `${name}.bin`);
78
+ const infoFile = path.join(outDir, `${name}.info`);
79
+ const sourceFile = path.join(outDir, `${name}.s`);
80
+ writeFileSync(imageFile, image.bytes);
81
+ writeFileSync(infoFile, renderInfo({
82
+ inputName: path.basename(imageFile),
83
+ outputName: path.basename(sourceFile),
84
+ base: image.base,
85
+ ranges: buildRanges({ kinds: analysis.kinds, base: image.base, hasVectors: image.vectors !== null }),
86
+ labels: [...symbols, ...vectorLabels],
87
+ includes,
88
+ }));
89
+
90
+ const da65 = await runTool(toolchain, 'da65', ['-i', path.basename(infoFile), '--multi-pass'], { cwd: outDir });
91
+ if (da65.code !== 0) throw new FcdevError('da65 反汇编失败', { code: 'DISASM_DA65_FAILED', hint: `${da65.stdout}${da65.stderr}`.trim() });
92
+
93
+ const roundtrip = await verifyRoundtrip({ toolchain, sourceFile, expected: image.bytes, base: image.base, workDir: outDir, name });
94
+ if (!roundtrip.ok) {
95
+ const address = image.base + roundtrip.firstDifference;
96
+ throw new FcdevError(`回读校验不一致:偏移 ${roundtrip.firstDifference}(地址 $${address.toString(16).toUpperCase()})起与原映像不同`, {
97
+ code: 'DISASM_ROUNDTRIP_MISMATCH',
98
+ hint: `源码保留在 ${sourceFile},可对照 ${imageFile} 检查`,
99
+ });
100
+ }
101
+
102
+ const codeBytes = analysis.kinds.reduce((count, value) => count + (value === KIND_UNKNOWN ? 0 : 1), 0);
103
+ return {
104
+ sourceFile,
105
+ infoFile,
106
+ imageFile,
107
+ description: image.description,
108
+ size: image.bytes.length,
109
+ codeBytes,
110
+ instructions: analysis.instructions,
111
+ warnings: analysis.warnings,
112
+ verified: true,
113
+ };
114
+ }
@@ -0,0 +1,16 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:index.mjs
3
+ // 说明:disasm 目录的对外入口:反汇编并回读校验,以及解析符号文件、CDL 等辅助函数。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:无
8
+ // ------------------------------------------------------------------------
9
+ export { analyzeCode } from './analysis.mjs';
10
+ export { parseCdl } from './cdl.mjs';
11
+ export { disassemble } from './disassembler.mjs';
12
+ export { buildRanges, renderInfo } from './info-writer.mjs';
13
+ export { loadBinary, loadInes } from './loaders.mjs';
14
+ export { findFirstDifference, renderRoundtripConfig } from './roundtrip.mjs';
15
+ export { parseSymbols } from './symbols.mjs';
16
+ export { parseTrace } from './trace.mjs';
@@ -0,0 +1,72 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:info-writer.mjs
3
+ // 说明:把分析结果写成 da65 的信息文件:把整个映像划分成代码、数据与向量表几段,并给入口与用户符号起名字。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:信息文件语法见 da65 的文档;RANGE 的结束地址包含在内;各段首尾相接、互不重叠,没有遗漏,da65 才不会把没说明的字节按默认当成代码。
8
+ // ------------------------------------------------------------------------
9
+ import { FcdevError } from '../shared/index.mjs';
10
+ import { KIND_UNKNOWN } from './analysis.mjs';
11
+
12
+ /** ca65 标识符 */
13
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
14
+
15
+ /** 中断向量表的字节数:NMI、复位、IRQ 各一个字 */
16
+ export const VECTOR_TABLE_SIZE = 6;
17
+
18
+ /**
19
+ * @typedef {object} Range
20
+ * @property {number} start 起始地址
21
+ * @property {number} end 结束地址(包含)
22
+ * @property {'Code'|'ByteTable'|'AddrTable'} type 类型
23
+ */
24
+
25
+ /**
26
+ * 把映像划分成连续的段。
27
+ * @param {{kinds: Uint8Array, base: number, hasVectors: boolean}} input 每个字节的分类、起始地址与是否有向量表(占最后 6 字节)
28
+ * @returns {Range[]} 覆盖整个映像的段,按地址排序
29
+ */
30
+ export function buildRanges({ kinds, base, hasVectors }) {
31
+ const body = hasVectors ? kinds.length - VECTOR_TABLE_SIZE : kinds.length;
32
+ const ranges = [];
33
+ for (let offset = 0; offset < body; offset += 1) {
34
+ const type = kinds[offset] === KIND_UNKNOWN ? 'ByteTable' : 'Code';
35
+ const last = ranges.at(-1);
36
+ if (last && last.type === type) last.end = base + offset;
37
+ else ranges.push({ start: base + offset, end: base + offset, type });
38
+ }
39
+ if (hasVectors) ranges.push({ start: base + body, end: base + kinds.length - 1, type: 'AddrTable' });
40
+ return ranges;
41
+ }
42
+
43
+ /**
44
+ * 格式化十六进制地址。
45
+ * @param {number} address 地址
46
+ * @returns {string} 如 $C000
47
+ */
48
+ function hex(address) {
49
+ return `$${address.toString(16).toUpperCase().padStart(4, '0')}`;
50
+ }
51
+
52
+ /**
53
+ * 生成信息文件的内容。
54
+ * @param {{inputName: string, outputName: string, base: number, cpu?: string, ranges: Range[], labels: {name: string, address: number}[], includes?: string[]}} input 输入输出文件名、起始地址、CPU、各段、命名的地址与符号定义文件
55
+ * @returns {string} 信息文件内容
56
+ * @throws {FcdevError} 符号名不是合法的标识符
57
+ */
58
+ export function renderInfo({ inputName, outputName, base, cpu = '6502', ranges, labels, includes = [] }) {
59
+ const lines = [
60
+ `GLOBAL { INPUTNAME "${inputName}"; OUTPUTNAME "${outputName}"; STARTADDR ${hex(base)}; CPU "${cpu}"; PAGELENGTH 0; };`,
61
+ ...includes.map((file) => `ASMINC { FILE "${file.replaceAll('\\', '/')}"; };`),
62
+ ];
63
+ const seen = new Set();
64
+ for (const { name, address } of labels) {
65
+ if (!IDENTIFIER.test(name)) throw new FcdevError(`符号名“${name}”不是合法的标识符`, { code: 'DISASM_SYMBOL_INVALID' });
66
+ if (seen.has(address)) continue;
67
+ seen.add(address);
68
+ lines.push(`LABEL { NAME "${name}"; ADDR ${hex(address)}; };`);
69
+ }
70
+ for (const range of ranges) lines.push(`RANGE { START ${hex(range.start)}; END ${hex(range.end)}; TYPE ${range.type}; };`);
71
+ return `${lines.join('\n')}\n`;
72
+ }
@@ -0,0 +1,69 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:loaders.mjs
3
+ // 说明:读取待反汇编的文件:iNES(NROM)取出 PRG 与中断向量,平铺二进制按指定的加载地址处理。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:iNES 目前只支持映射器 0(NROM,16K 或 32K 的 PRG);其他映射器要先确定地址映射,不在首批范围。
8
+ // ------------------------------------------------------------------------
9
+ import { FcdevError } from '../shared/index.mjs';
10
+
11
+ /** iNES 文件头长度 */
12
+ const INES_HEADER_SIZE = 16;
13
+
14
+ /** iNES 的 trainer 块长度 */
15
+ const INES_TRAINER_SIZE = 512;
16
+
17
+ /**
18
+ * @typedef {object} Image
19
+ * @property {Buffer} bytes 要反汇编的字节
20
+ * @property {number} base 第一个字节的 CPU 地址
21
+ * @property {{nmi: number, reset: number, irq: number}|null} vectors 中断向量;没有时为 null
22
+ * @property {string} description 来源说明,写进报告
23
+ */
24
+
25
+ /**
26
+ * 读取 iNES 文件的 PRG 部分。
27
+ * @param {Buffer} buffer 文件内容
28
+ * @returns {Image} PRG 映像:16K 映在 $C000,32K 映在 $8000
29
+ * @throws {FcdevError} 不是 iNES 文件、映射器不是 0,或 PRG 大小不是 16K 与 32K
30
+ */
31
+ export function loadInes(buffer) {
32
+ if (buffer.length < INES_HEADER_SIZE || buffer.subarray(0, 4).toString('latin1') !== 'NES\x1a') {
33
+ throw new FcdevError('不是 iNES 文件(缺少 NES 文件头)', { code: 'DISASM_INPUT_INVALID' });
34
+ }
35
+ const mapper = (buffer[7] & 0xf0) | (buffer[6] >> 4);
36
+ if (mapper !== 0) {
37
+ throw new FcdevError(`暂不支持映射器 ${mapper}`, { code: 'DISASM_MAPPER_UNSUPPORTED', hint: '目前只支持 NROM(映射器 0);其他映射器可先导出某个 bank,用 --format binary 并指定加载地址' });
38
+ }
39
+ const prgSize = buffer[4] * 0x4000;
40
+ if (prgSize !== 0x4000 && prgSize !== 0x8000) {
41
+ throw new FcdevError(`NROM 的 PRG 应为 16K 或 32K,实际 ${prgSize} 字节`, { code: 'DISASM_INPUT_INVALID' });
42
+ }
43
+ const start = INES_HEADER_SIZE + (buffer[6] & 0x04 ? INES_TRAINER_SIZE : 0);
44
+ if (buffer.length < start + prgSize) {
45
+ throw new FcdevError('文件比 iNES 文件头声明的短', { code: 'DISASM_INPUT_INVALID' });
46
+ }
47
+ const bytes = buffer.subarray(start, start + prgSize);
48
+ return {
49
+ bytes,
50
+ base: 0x10000 - prgSize,
51
+ vectors: { nmi: bytes.readUInt16LE(prgSize - 6), reset: bytes.readUInt16LE(prgSize - 4), irq: bytes.readUInt16LE(prgSize - 2) },
52
+ description: `iNES NROM,PRG ${prgSize / 1024}K`,
53
+ };
54
+ }
55
+
56
+ /**
57
+ * 把平铺二进制当作映像。
58
+ * @param {Buffer} buffer 文件内容
59
+ * @param {{base: number}} options 第一个字节的 CPU 地址
60
+ * @returns {Image} 映像
61
+ * @throws {FcdevError} 文件为空,或超出 64K 地址空间
62
+ */
63
+ export function loadBinary(buffer, { base }) {
64
+ if (buffer.length === 0) throw new FcdevError('输入文件是空的', { code: 'DISASM_INPUT_INVALID' });
65
+ if (base + buffer.length > 0x10000) {
66
+ throw new FcdevError(`从 $${base.toString(16).toUpperCase()} 起放不下 ${buffer.length} 字节(超出 $FFFF)`, { code: 'DISASM_INPUT_INVALID' });
67
+ }
68
+ return { bytes: buffer, base, vectors: null, description: `平铺二进制,加载地址 $${base.toString(16).toUpperCase()}` };
69
+ }
@@ -0,0 +1,268 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:opcode-table.mjs
3
+ // 说明:6502 官方指令表:每个操作码的助记符、字节数与流程类别,非法操作码为 null。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:数据取自 cc65 的 da65 指令表(cc65/src/da65/opc6502.c);流程类别由助记符推出。
8
+ // ------------------------------------------------------------------------
9
+
10
+ /** 流程类别:next 顺序执行;branch 条件分支;jump 绝对跳转;jump-indirect 间接跳转;call 子程序调用;return 返回;stop 中断指令 */
11
+ export const OPCODES = [
12
+ ['brk', 1, 'stop'], // $00
13
+ ['ora', 2, 'next'], // $01
14
+ null, // $02
15
+ null, // $03
16
+ null, // $04
17
+ ['ora', 2, 'next'], // $05
18
+ ['asl', 2, 'next'], // $06
19
+ null, // $07
20
+ ['php', 1, 'next'], // $08
21
+ ['ora', 2, 'next'], // $09
22
+ ['asl', 1, 'next'], // $0a
23
+ null, // $0b
24
+ null, // $0c
25
+ ['ora', 3, 'next'], // $0d
26
+ ['asl', 3, 'next'], // $0e
27
+ null, // $0f
28
+ ['bpl', 2, 'branch'], // $10
29
+ ['ora', 2, 'next'], // $11
30
+ null, // $12
31
+ null, // $13
32
+ null, // $14
33
+ ['ora', 2, 'next'], // $15
34
+ ['asl', 2, 'next'], // $16
35
+ null, // $17
36
+ ['clc', 1, 'next'], // $18
37
+ ['ora', 3, 'next'], // $19
38
+ null, // $1a
39
+ null, // $1b
40
+ null, // $1c
41
+ ['ora', 3, 'next'], // $1d
42
+ ['asl', 3, 'next'], // $1e
43
+ null, // $1f
44
+ ['jsr', 3, 'call'], // $20
45
+ ['and', 2, 'next'], // $21
46
+ null, // $22
47
+ null, // $23
48
+ ['bit', 2, 'next'], // $24
49
+ ['and', 2, 'next'], // $25
50
+ ['rol', 2, 'next'], // $26
51
+ null, // $27
52
+ ['plp', 1, 'next'], // $28
53
+ ['and', 2, 'next'], // $29
54
+ ['rol', 1, 'next'], // $2a
55
+ null, // $2b
56
+ ['bit', 3, 'next'], // $2c
57
+ ['and', 3, 'next'], // $2d
58
+ ['rol', 3, 'next'], // $2e
59
+ null, // $2f
60
+ ['bmi', 2, 'branch'], // $30
61
+ ['and', 2, 'next'], // $31
62
+ null, // $32
63
+ null, // $33
64
+ null, // $34
65
+ ['and', 2, 'next'], // $35
66
+ ['rol', 2, 'next'], // $36
67
+ null, // $37
68
+ ['sec', 1, 'next'], // $38
69
+ ['and', 3, 'next'], // $39
70
+ null, // $3a
71
+ null, // $3b
72
+ null, // $3c
73
+ ['and', 3, 'next'], // $3d
74
+ ['rol', 3, 'next'], // $3e
75
+ null, // $3f
76
+ ['rti', 1, 'return'], // $40
77
+ ['eor', 2, 'next'], // $41
78
+ null, // $42
79
+ null, // $43
80
+ null, // $44
81
+ ['eor', 2, 'next'], // $45
82
+ ['lsr', 2, 'next'], // $46
83
+ null, // $47
84
+ ['pha', 1, 'next'], // $48
85
+ ['eor', 2, 'next'], // $49
86
+ ['lsr', 1, 'next'], // $4a
87
+ null, // $4b
88
+ ['jmp', 3, 'jump'], // $4c
89
+ ['eor', 3, 'next'], // $4d
90
+ ['lsr', 3, 'next'], // $4e
91
+ null, // $4f
92
+ ['bvc', 2, 'branch'], // $50
93
+ ['eor', 2, 'next'], // $51
94
+ null, // $52
95
+ null, // $53
96
+ null, // $54
97
+ ['eor', 2, 'next'], // $55
98
+ ['lsr', 2, 'next'], // $56
99
+ null, // $57
100
+ ['cli', 1, 'next'], // $58
101
+ ['eor', 3, 'next'], // $59
102
+ null, // $5a
103
+ null, // $5b
104
+ null, // $5c
105
+ ['eor', 3, 'next'], // $5d
106
+ ['lsr', 3, 'next'], // $5e
107
+ null, // $5f
108
+ ['rts', 1, 'return'], // $60
109
+ ['adc', 2, 'next'], // $61
110
+ null, // $62
111
+ null, // $63
112
+ null, // $64
113
+ ['adc', 2, 'next'], // $65
114
+ ['ror', 2, 'next'], // $66
115
+ null, // $67
116
+ ['pla', 1, 'next'], // $68
117
+ ['adc', 2, 'next'], // $69
118
+ ['ror', 1, 'next'], // $6a
119
+ null, // $6b
120
+ ['jmp', 3, 'jump-indirect'], // $6c
121
+ ['adc', 3, 'next'], // $6d
122
+ ['ror', 3, 'next'], // $6e
123
+ null, // $6f
124
+ ['bvs', 2, 'branch'], // $70
125
+ ['adc', 2, 'next'], // $71
126
+ null, // $72
127
+ null, // $73
128
+ null, // $74
129
+ ['adc', 2, 'next'], // $75
130
+ ['ror', 2, 'next'], // $76
131
+ null, // $77
132
+ ['sei', 1, 'next'], // $78
133
+ ['adc', 3, 'next'], // $79
134
+ null, // $7a
135
+ null, // $7b
136
+ null, // $7c
137
+ ['adc', 3, 'next'], // $7d
138
+ ['ror', 3, 'next'], // $7e
139
+ null, // $7f
140
+ null, // $80
141
+ ['sta', 2, 'next'], // $81
142
+ null, // $82
143
+ null, // $83
144
+ ['sty', 2, 'next'], // $84
145
+ ['sta', 2, 'next'], // $85
146
+ ['stx', 2, 'next'], // $86
147
+ null, // $87
148
+ ['dey', 1, 'next'], // $88
149
+ null, // $89
150
+ ['txa', 1, 'next'], // $8a
151
+ null, // $8b
152
+ ['sty', 3, 'next'], // $8c
153
+ ['sta', 3, 'next'], // $8d
154
+ ['stx', 3, 'next'], // $8e
155
+ null, // $8f
156
+ ['bcc', 2, 'branch'], // $90
157
+ ['sta', 2, 'next'], // $91
158
+ null, // $92
159
+ null, // $93
160
+ ['sty', 2, 'next'], // $94
161
+ ['sta', 2, 'next'], // $95
162
+ ['stx', 2, 'next'], // $96
163
+ null, // $97
164
+ ['tya', 1, 'next'], // $98
165
+ ['sta', 3, 'next'], // $99
166
+ ['txs', 1, 'next'], // $9a
167
+ null, // $9b
168
+ null, // $9c
169
+ ['sta', 3, 'next'], // $9d
170
+ null, // $9e
171
+ null, // $9f
172
+ ['ldy', 2, 'next'], // $a0
173
+ ['lda', 2, 'next'], // $a1
174
+ ['ldx', 2, 'next'], // $a2
175
+ null, // $a3
176
+ ['ldy', 2, 'next'], // $a4
177
+ ['lda', 2, 'next'], // $a5
178
+ ['ldx', 2, 'next'], // $a6
179
+ null, // $a7
180
+ ['tay', 1, 'next'], // $a8
181
+ ['lda', 2, 'next'], // $a9
182
+ ['tax', 1, 'next'], // $aa
183
+ null, // $ab
184
+ ['ldy', 3, 'next'], // $ac
185
+ ['lda', 3, 'next'], // $ad
186
+ ['ldx', 3, 'next'], // $ae
187
+ null, // $af
188
+ ['bcs', 2, 'branch'], // $b0
189
+ ['lda', 2, 'next'], // $b1
190
+ null, // $b2
191
+ null, // $b3
192
+ ['ldy', 2, 'next'], // $b4
193
+ ['lda', 2, 'next'], // $b5
194
+ ['ldx', 2, 'next'], // $b6
195
+ null, // $b7
196
+ ['clv', 1, 'next'], // $b8
197
+ ['lda', 3, 'next'], // $b9
198
+ ['tsx', 1, 'next'], // $ba
199
+ null, // $bb
200
+ ['ldy', 3, 'next'], // $bc
201
+ ['lda', 3, 'next'], // $bd
202
+ ['ldx', 3, 'next'], // $be
203
+ null, // $bf
204
+ ['cpy', 2, 'next'], // $c0
205
+ ['cmp', 2, 'next'], // $c1
206
+ null, // $c2
207
+ null, // $c3
208
+ ['cpy', 2, 'next'], // $c4
209
+ ['cmp', 2, 'next'], // $c5
210
+ ['dec', 2, 'next'], // $c6
211
+ null, // $c7
212
+ ['iny', 1, 'next'], // $c8
213
+ ['cmp', 2, 'next'], // $c9
214
+ ['dex', 1, 'next'], // $ca
215
+ null, // $cb
216
+ ['cpy', 3, 'next'], // $cc
217
+ ['cmp', 3, 'next'], // $cd
218
+ ['dec', 3, 'next'], // $ce
219
+ null, // $cf
220
+ ['bne', 2, 'branch'], // $d0
221
+ ['cmp', 2, 'next'], // $d1
222
+ null, // $d2
223
+ null, // $d3
224
+ null, // $d4
225
+ ['cmp', 2, 'next'], // $d5
226
+ ['dec', 2, 'next'], // $d6
227
+ null, // $d7
228
+ ['cld', 1, 'next'], // $d8
229
+ ['cmp', 3, 'next'], // $d9
230
+ null, // $da
231
+ null, // $db
232
+ null, // $dc
233
+ ['cmp', 3, 'next'], // $dd
234
+ ['dec', 3, 'next'], // $de
235
+ null, // $df
236
+ ['cpx', 2, 'next'], // $e0
237
+ ['sbc', 2, 'next'], // $e1
238
+ null, // $e2
239
+ null, // $e3
240
+ ['cpx', 2, 'next'], // $e4
241
+ ['sbc', 2, 'next'], // $e5
242
+ ['inc', 2, 'next'], // $e6
243
+ null, // $e7
244
+ ['inx', 1, 'next'], // $e8
245
+ ['sbc', 2, 'next'], // $e9
246
+ ['nop', 1, 'next'], // $ea
247
+ null, // $eb
248
+ ['cpx', 3, 'next'], // $ec
249
+ ['sbc', 3, 'next'], // $ed
250
+ ['inc', 3, 'next'], // $ee
251
+ null, // $ef
252
+ ['beq', 2, 'branch'], // $f0
253
+ ['sbc', 2, 'next'], // $f1
254
+ null, // $f2
255
+ null, // $f3
256
+ null, // $f4
257
+ ['sbc', 2, 'next'], // $f5
258
+ ['inc', 2, 'next'], // $f6
259
+ null, // $f7
260
+ ['sed', 1, 'next'], // $f8
261
+ ['sbc', 3, 'next'], // $f9
262
+ null, // $fa
263
+ null, // $fb
264
+ null, // $fc
265
+ ['sbc', 3, 'next'], // $fd
266
+ ['inc', 3, 'next'], // $fe
267
+ null, // $ff
268
+ ];
@@ -0,0 +1,69 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:roundtrip.mjs
3
+ // 说明:回读校验:把反汇编出的 ca65 源码重新汇编、链接,与原映像逐字节比较。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:链接配置只放一个从映像起始地址开始、大小恰好等于映像的内存区与一个 CODE 段;不一致时报告第一个不同的偏移与地址。
8
+ // ------------------------------------------------------------------------
9
+ import { readFileSync, writeFileSync } from 'node:fs';
10
+ import path from 'node:path';
11
+ import { FcdevError } from '../shared/index.mjs';
12
+ import { runTool } from '../toolchain/index.mjs';
13
+
14
+ /**
15
+ * 生成回读用的链接配置。
16
+ * @param {number} base 起始地址
17
+ * @param {number} size 映像大小
18
+ * @returns {string} ld65 配置内容
19
+ */
20
+ export function renderRoundtripConfig(base, size) {
21
+ return `MEMORY { ROM: file = %O, start = $${base.toString(16).toUpperCase()}, size = $${size.toString(16).toUpperCase()}; }
22
+ SEGMENTS { CODE: load = ROM, type = ro; }
23
+ `;
24
+ }
25
+
26
+ /**
27
+ * 找出两段字节的第一个差异。
28
+ * @param {Buffer} expected 原映像
29
+ * @param {Buffer} actual 回读得到的映像
30
+ * @returns {number} 第一个不同的偏移;完全相同时为 -1
31
+ */
32
+ export function findFirstDifference(expected, actual) {
33
+ const common = Math.min(expected.length, actual.length);
34
+ for (let offset = 0; offset < common; offset += 1) {
35
+ if (expected[offset] !== actual[offset]) return offset;
36
+ }
37
+ return expected.length === actual.length ? -1 : common;
38
+ }
39
+
40
+ /**
41
+ * 运行一个工具,失败时抛出带输出的错误。
42
+ * @param {import('../toolchain/index.mjs').Toolchain} toolchain 工具链
43
+ * @param {string} tool 工具名
44
+ * @param {string[]} args 参数
45
+ * @param {string} failure 失败说明
46
+ * @returns {Promise<void>}
47
+ * @throws {FcdevError} 工具退出码非零
48
+ */
49
+ async function runOrThrow(toolchain, tool, args, failure) {
50
+ const result = await runTool(toolchain, tool, args);
51
+ if (result.code !== 0) throw new FcdevError(failure, { code: 'DISASM_ROUNDTRIP_FAILED', hint: `${result.stdout}${result.stderr}`.trim() });
52
+ }
53
+
54
+ /**
55
+ * 重新汇编反汇编出的源码并与原映像比较。
56
+ * @param {{toolchain: import('../toolchain/index.mjs').Toolchain, sourceFile: string, expected: Buffer, base: number, workDir: string, name: string}} input 工具链、源码、原映像、起始地址、工作目录与文件名前缀
57
+ * @returns {Promise<{ok: boolean, firstDifference: number}>} 是否一致,以及第一个不同的偏移(一致时为 -1)
58
+ * @throws {FcdevError} 汇编或链接失败
59
+ */
60
+ export async function verifyRoundtrip({ toolchain, sourceFile, expected, base, workDir, name }) {
61
+ const objectFile = path.join(workDir, `${name}.roundtrip.o`);
62
+ const configFile = path.join(workDir, `${name}.roundtrip.cfg`);
63
+ const outputFile = path.join(workDir, `${name}.roundtrip.bin`);
64
+ writeFileSync(configFile, renderRoundtripConfig(base, expected.length));
65
+ await runOrThrow(toolchain, 'ca65', [sourceFile, '-o', objectFile], `重新汇编 ${path.basename(sourceFile)} 失败`);
66
+ await runOrThrow(toolchain, 'ld65', ['-C', configFile, '-o', outputFile, objectFile], '重新链接失败');
67
+ const firstDifference = findFirstDifference(expected, readFileSync(outputFile));
68
+ return { ok: firstDifference === -1, firstDifference };
69
+ }
@@ -0,0 +1,30 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:symbols.mjs
3
+ // 说明:读取用户提供的符号文件:每行“名字 = 地址”或“名字 地址”,用于给地址起名字。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:地址按十六进制,可带 $ 或 0x 前缀;以 ; 或 # 开头的行是注释,空行忽略。
8
+ // ------------------------------------------------------------------------
9
+ import { FcdevError } from '../shared/index.mjs';
10
+
11
+ /** 一行符号:名字、可选的等号、地址 */
12
+ const SYMBOL_LINE = /^([A-Za-z_][A-Za-z0-9_]*)\s*(?:=|\s)\s*(?:\$|0[xX])?([0-9A-Fa-f]{1,4})\s*(?:[;#].*)?$/;
13
+
14
+ /**
15
+ * 解析符号文件。
16
+ * @param {string} text 文件内容
17
+ * @returns {{name: string, address: number}[]} 符号列表,按文件里的顺序
18
+ * @throws {FcdevError} 某一行格式不对
19
+ */
20
+ export function parseSymbols(text) {
21
+ const symbols = [];
22
+ text.split(/\r?\n/).forEach((rawLine, index) => {
23
+ const line = rawLine.trim();
24
+ if (line === '' || line.startsWith(';') || line.startsWith('#')) return;
25
+ const match = SYMBOL_LINE.exec(line);
26
+ if (!match) throw new FcdevError(`符号文件第 ${index + 1} 行格式不对:${line}`, { code: 'DISASM_SYMBOL_INVALID', hint: '写成“名字 = $地址”或“名字 地址”' });
27
+ symbols.push({ name: match[1], address: Number.parseInt(match[2], 16) });
28
+ });
29
+ return symbols;
30
+ }
@@ -0,0 +1,25 @@
1
+ // ------------------------------------------------------------------------
2
+ // 名称:trace.mjs
3
+ // 说明:读取模拟器 trace 命令记录的指令轨迹:每行以 T 开头,第二列是执行到的指令地址。
4
+ // 作者:sungbin
5
+ // 邮箱:sungbin@3578.cn
6
+ // 日期:2026-11-10
7
+ // 备注:轨迹里的每个地址都是被真实执行过的指令开头,比 CDL 的“代码字节”更精确;用作追踪代码的入口。
8
+ // ------------------------------------------------------------------------
9
+
10
+ /** 轨迹的一行:T、四位十六进制的指令地址,后面是物理地址、字节、寄存器 */
11
+ const TRACE_LINE = /^T ([0-9A-Fa-f]{4}) /;
12
+
13
+ /**
14
+ * 取出轨迹里被执行过的指令地址。
15
+ * @param {string} text 轨迹文件内容
16
+ * @returns {number[]} 不重复的地址,按首次出现的顺序
17
+ */
18
+ export function parseTrace(text) {
19
+ const seen = new Set();
20
+ for (const line of text.split('\n')) {
21
+ const match = TRACE_LINE.exec(line);
22
+ if (match) seen.add(Number.parseInt(match[1], 16));
23
+ }
24
+ return [...seen];
25
+ }