怎么用JavaScript编写RISC-V子集汇编器并生成机器码
深入讲解如何使用原生JavaScript编写轻量级RISC-V(RV32I)子集汇编器,涵盖双遍扫描、符号表解析、B/J型相对跳转重定位及位运算编码生成机器码的完整实现。
Uint32Array 与十六进制机器码。
一、整体工作流程与两遍扫描机制
汇编器的核心任务是将人类可读的助记符(如 addi x1, x0, 10)映射为 CPU 控制单元能够识别的 32 位二进制指令字。在汇编程序中,往往会出现跨越后续未定义代码行的跳转标签(例如 bne x1, x2, exit,而 exit: 标签位于后方代码段中)。如果仅采用单遍顺序扫描,在遇到前向引用(Forward Reference)时,汇编器无法确定目标跳转地址与当前指令之间的字节偏移量。
解决此问题的标准工业做法是采用双遍扫描(Two-Pass)架构:
- 第一遍扫描(Pass 1 - 符号收集):逐行读取源码,清洗掉行尾注释与空白行;记录程序计数器(PC)指针;当遇到标签定义时,将标签名与当前 PC 的字节地址记录在符号表(Symbol Table)中;每解析到一条有效指令,PC 递增 4 个字节。
- 第二遍扫描(Pass 2 - 机器码生成):重新遍历过滤后的指令行,识别指令助记符并查找操作码格式(R、I、S、B、U、J);将寄存器别名转化为索引编号;根据第一遍建立的符号表计算分支与跳转指令的相对偏移量;最后运用 JavaScript 位移操作将各字段压缩进一个 32 位无符号整数中。
二、RV32I 核心指令格式与编码规则
RISC-V 指令集架构采用规整的定长 32 位指令编码,所有指令的最低 7 位(bits [6:0])均为操作码 opcode。为了以最精简的 JavaScript 逻辑覆盖控制流、算术运算与内存访存,本文选取的精简指令子集包含六种核心格式:
| 指令类型 | 典型指令 | 包含字段与位分布 | 用途说明 |
|---|---|---|---|
| R 型 (Register) | add, sub, and, or, slt |
funct7[31:25] | rs2[24:20] | rs1[19:15] | funct3[14:12] | rd[11:7] | opcode[6:0] | 纯寄存器间的算术与逻辑运算 |
| I 型 (Immediate) | addi, andi, ori, lw, jalr |
imm[11:0][31:20] | rs1[19:15] | funct3[14:12] | rd[11:7] | opcode[6:0] | 带 12 位有符号立即数的计算与加载 |
| S 型 (Store) | sw |
imm[11:5][31:25] | rs2[24:20] | rs1[19:15] | funct3[14:12] | imm[4:0][11:7] | opcode[6:0] | 内存写回,立即数被拆分为两部分 |
| B 型 (Branch) | beq, bne, blt, bge |
imm[12|10:5][31:25] | rs2[24:20] | rs1[19:15] | funct3[14:12] | imm[4:1|11][11:7] | opcode[6:0] | 条件跳转,立即数表示 2 字节对齐的 PC 偏移 |
| U 型 (Upper Imm) | lui |
imm[31:12][31:12] | rd[11:7] | opcode[6:0] | 加载 20 位高位立即数至寄存器 |
| J 型 (Jump) | jal |
imm[20|10:1|11|19:12][31:12] | rd[11:7] | opcode[6:0] | 无条件跳转并保存返回地址到 rd |
三、JavaScript 位运算编码核心实现
在 JavaScript 中进行底层二进制编码时,必须牢记 ECMAScript 规范对位运算符(|、&、<<、>>)的处理规则:所有操作数首先被隐式转换为32 位有符号整数。当最高位(bit 31)被置为 1 时,直接输出该变量会得到负数。为了保证生成的机器码为标准的 32 位无符号原码,每次编码完成前必须执行无符号右移运算符 >>> 0。
1. 寄存器索引映射
RISC-V 具备 32 个通用整数寄存器(x0 到 x31),在汇编代码中经常使用 ABI 别名。我们先建立名称到 5 位索引值的映射表:
const REGISTER_MAP = {
"zero": 0, "ra": 1, "sp": 2, "gp": 3, "tp": 4,
"t0": 5, "t1": 6, "t2": 7, "s0": 8, "fp": 8, "s1": 9,
"a0": 10, "a1": 11, "a2": 12, "a3": 13, "a4": 14, "a5": 15,
"a6": 16, "a7": 17, "s2": 18, "s3": 19, "s4": 20, "s5": 21,
"s6": 22, "s7": 23, "s8": 24, "s9": 25, "s10": 26, "s11": 27,
"t3": 28, "t4": 29, "t5": 30, "t6": 31
};
function parseReg(name) {
const clean = name.trim().toLowerCase();
if (clean.startsWith('x')) {
const idx = parseInt(clean.slice(1), 10);
if (idx >= 0 && idx < 32) return idx;
}
if (clean in REGISTER_MAP) return REGISTER_MAP[clean];
throw new Error(`未知或非法的寄存器名称: "${name}"`);
}
2. 各格式位拼装函数
根据 RISC-V 规范,编写对应格式的纯函数。特别注意 S 型与 B 型中立即数的离散位抽取:
// R 型:funct7 | rs2 | rs1 | funct3 | rd | opcode
function encodeR(opcode, rd, funct3, rs1, rs2, funct7) {
return (((funct7 & 0x7f) << 25) |
((rs2 & 0x1f) << 20) |
((rs1 & 0x1f) << 15) |
((funct3 & 0x7) << 12) |
((rd & 0x1f) << 7) |
(opcode & 0x7f)) >>> 0;
}
// I 型:imm[11:0] | rs1 | funct3 | rd | opcode
function encodeI(opcode, rd, funct3, rs1, imm) {
return (((imm & 0xfff) << 20) |
((rs1 & 0x1f) << 15) |
((funct3 & 0x7) << 12) |
((rd & 0x1f) << 7) |
(opcode & 0x7f)) >>> 0;
}
// S 型:imm[11:5] | rs2 | rs1 | funct3 | imm[4:0] | opcode
function encodeS(opcode, funct3, rs1, rs2, imm) {
const imm11_5 = (imm >> 5) & 0x7f;
const imm4_0 = imm & 0x1f;
return ((imm11_5 << 25) |
((rs2 & 0x1f) << 20) |
((rs1 & 0x1f) << 15) |
((funct3 & 0x7) << 12) |
(imm4_0 << 7) |
(opcode & 0x7f)) >>> 0;
}
// B 型:imm[12|10:5] | rs2 | rs1 | funct3 | imm[4:1|11] | opcode
function encodeB(opcode, funct3, rs1, rs2, imm) {
const b12 = (imm >> 12) & 0x1;
const b10_5 = (imm >> 5) & 0x3f;
const b4_1 = (imm >> 1) & 0xf;
const b11 = (imm >> 11) & 0x1;
return ((b12 << 31) |
(b10_5 << 25) |
((rs2 & 0x1f) << 20) |
((rs1 & 0x1f) << 15) |
((funct3 & 0x7) << 12) |
(b4_1 << 8) |
(b11 << 7) |
(opcode & 0x7f)) >>> 0;
}
// J 型:imm[20|10:1|11|19:12] | rd | opcode
function encodeJ(opcode, rd, imm) {
const b20 = (imm >> 20) & 0x1;
const b10_1 = (imm >> 1) & 0x3ff;
const b11 = (imm >> 11) & 0x1;
const b19_12 = (imm >> 12) & 0xff;
return ((b20 << 31) |
(b10_1 << 21) |
(b11 << 20) |
(b19_12 << 12) |
((rd & 0x1f) << 7) |
(opcode & 0x7f)) >>> 0;
}
四、编写完整的 JavaScript RISC-V 汇编器
以下是具备完整双遍扫描、错误防御与指令发射的独立 JavaScript 模块实现。支持十进制与十六进制立即数、内存寻址写法 offset(rs1) 以及标签相对寻址:
/**
* RV32I 汇编器轻量实现
*/
class RV32Assembler {
constructor() {
// 指令元数据描述表
this.INSTRUCTION_SET = {
// R-Type (opcode = 0x33)
'add': { type: 'R', opcode: 0x33, funct3: 0x0, funct7: 0x00 },
'sub': { type: 'R', opcode: 0x33, funct3: 0x0, funct7: 0x20 },
'and': { type: 'R', opcode: 0x33, funct3: 0x7, funct7: 0x00 },
'or': { type: 'R', opcode: 0x33, funct3: 0x6, funct7: 0x00 },
'slt': { type: 'R', opcode: 0x33, funct3: 0x2, funct7: 0x00 },
// I-Type (opcode = 0x13)
'addi': { type: 'I', opcode: 0x13, funct3: 0x0 },
'andi': { type: 'I', opcode: 0x13, funct3: 0x7 },
'ori': { type: 'I', opcode: 0x13, funct3: 0x6 },
'slti': { type: 'I', opcode: 0x13, funct3: 0x2 },
// Load (I-Type, opcode = 0x03)
'lw': { type: 'I_LOAD', opcode: 0x03, funct3: 0x2 },
// Store (S-Type, opcode = 0x23)
'sw': { type: 'S', opcode: 0x23, funct3: 0x2 },
// Branch (B-Type, opcode = 0x63)
'beq': { type: 'B', opcode: 0x63, funct3: 0x0 },
'bne': { type: 'B', opcode: 0x63, funct3: 0x1 },
'blt': { type: 'B', opcode: 0x63, funct3: 0x4 },
'bge': { type: 'B', opcode: 0x63, funct3: 0x5 },
// Upper (U-Type, opcode = 0x37)
'lui': { type: 'U', opcode: 0x37 },
// Jump (J-Type, opcode = 0x6f)
'jal': { type: 'J', opcode: 0x6f }
};
}
// 解析立即数字符串(支持 10、-4、0x1F)
parseImmediate(str) {
const clean = str.trim();
const val = clean.startsWith('0x') || clean.startsWith('0X')
? parseInt(clean, 16)
: parseInt(clean, 10);
if (Number.isNaN(val)) {
throw new Error(`无法识别的立即数格式: "${str}"`);
}
return val;
}
// 解析类似 4(sp) 或 0(x0) 的内存寻址
parseMemoryOperand(op) {
const match = op.match(/^([+-]?(?:0x[0-9a-fA-F]+|\d+))\s*\(([^)]+)\)$/);
if (!match) {
throw new Error(`内存操作数格式错误,期望 "offset(rs1)", 实际为: "${op}"`);
}
const offset = this.parseImmediate(match[1]);
const rs1 = parseReg(match[2]);
return { offset, rs1 };
}
assemble(sourceText) {
const lines = sourceText.split('\n');
const symbolTable = new Map();
const cleanInstructions = [];
// ===== 第一遍扫描:收集符号与指令地址 =====
let currentPC = 0;
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
let line = lines[lineIndex];
// 去除注释
const commentIdx = line.search(/#|\/\/\/);
if (commentIdx !== -1) line = line.substring(0, commentIdx);
line = line.trim();
if (!line) continue;
// 提取行首或单独一行的标签
while (line.includes(':')) {
const colonIdx = line.indexOf(':');
const label = line.substring(0, colonIdx).trim();
if (label) {
if (symbolTable.has(label)) {
throw new Error(`第 ${lineIndex + 1} 行:重复定义标签 "${label}"`);
}
symbolTable.set(label, currentPC);
}
line = line.substring(colonIdx + 1).trim();
}
if (!line) continue;
cleanInstructions.push({
pc: currentPC,
raw: line,
lineNum: lineIndex + 1
});
currentPC += 4;
}
// ===== 第二遍扫描:指令解析与二进制发射 =====
const machineCodes = new Uint32Array(cleanInstructions.length);
for (let i = 0; i < cleanInstructions.length; i++) {
const item = cleanInstructions[i];
const tokens = item.raw.split(/[\s,]+/).filter(t => t.length > 0);
const mnemonic = tokens[0].toLowerCase();
const meta = this.INSTRUCTION_SET[mnemonic];
if (!meta) {
throw new Error(`第 ${item.lineNum} 行:未实现的 RISC-V 助记符 "${mnemonic}"`);
}
let code = 0;
switch (meta.type) {
case 'R': {
// add rd, rs1, rs2
if (tokens.length < 4) throw new Error(`第 ${item.lineNum} 行:R 型指令参数不足`);
const rd = parseReg(tokens[1]);
const rs1 = parseReg(tokens[2]);
const rs2 = parseReg(tokens[3]);
code = encodeR(meta.opcode, rd, meta.funct3, rs1, rs2, meta.funct7);
break;
}
case 'I': {
// addi rd, rs1, imm
if (tokens.length < 4) throw new Error(`第 ${item.lineNum} 行:I 型指令参数不足`);
const rd = parseReg(tokens[1]);
const rs1 = parseReg(tokens[2]);
const imm = this.parseImmediate(tokens[3]);
if (imm < -2048 || imm > 2047) {
throw new Error(`第 ${item.lineNum} 行:12 位立即数越界 [-2048, 2047],实际为: ${imm}`);
}
code = encodeI(meta.opcode, rd, meta.funct3, rs1, imm);
break;
}
case 'I_LOAD': {
// lw rd, offset(rs1)
if (tokens.length < 3) throw new Error(`第 ${item.lineNum} 行:lw 指令参数不足`);
const rd = parseReg(tokens[1]);
const { offset, rs1 } = this.parseMemoryOperand(tokens[2]);
if (offset < -2048 || offset > 2047) {
throw new Error(`第 ${item.lineNum} 行:lw 偏移量越界 [-2048, 2047]`);
}
code = encodeI(meta.opcode, rd, meta.funct3, rs1, offset);
break;
}
case 'S': {
// sw rs2, offset(rs1)
if (tokens.length < 3) throw new Error(`第 ${item.lineNum} 行:sw 指令参数不足`);
const rs2 = parseReg(tokens[1]);
const { offset, rs1 } = this.parseMemoryOperand(tokens[2]);
if (offset < -2048 || offset > 2047) {
throw new Error(`第 ${item.lineNum} 行:sw 偏移量越界 [-2048, 2047]`);
}
code = encodeS(meta.opcode, meta.funct3, rs1, rs2, offset);
break;
}
case 'B': {
// beq rs1, rs2, label/offset
if (tokens.length < 4) throw new Error(`第 ${item.lineNum} 行:分支指令参数不足`);
const rs1 = parseReg(tokens[1]);
const rs2 = parseReg(tokens[2]);
const target = tokens[3];
let offset = 0;
if (symbolTable.has(target)) {
offset = symbolTable.get(target) - item.pc;
} else {
offset = this.parseImmediate(target);
}
if ((offset & 1) !== 0) {
throw new Error(`第 ${item.lineNum} 行:分支目标偏移必须为 2 字节对齐,实际为 ${offset}`);
}
if (offset < -4096 || offset > 4094) {
throw new Error(`第 ${item.lineNum} 行:分支跳转范围越界 [-4096, 4094],实际为 ${offset}`);
}
code = encodeB(meta.opcode, meta.funct3, rs1, rs2, offset);
break;
}
case 'U': {
// lui rd, imm
if (tokens.length < 3) throw new Error(`第 ${item.lineNum} 行:lui 指令参数不足`);
const rd = parseReg(tokens[1]);
const imm = this.parseImmediate(tokens[2]);
code = encodeU(meta.opcode, rd, imm);
break;
}
case 'J': {
// jal rd, label/offset
if (tokens.length < 3) throw new Error(`第 ${item.lineNum} 行:jal 指令参数不足`);
const rd = parseReg(tokens[1]);
const target = tokens[2];
let offset = 0;
if (symbolTable.has(target)) {
offset = symbolTable.get(target) - item.pc;
} else {
offset = this.parseImmediate(target);
}
if ((offset & 1) !== 0) {
throw new Error(`第 ${item.lineNum} 行:JAL 跳转偏移未对齐,实际为 ${offset}`);
}
code = encodeJ(meta.opcode, rd, offset);
break;
}
}
machineCodes[i] = code;
}
return {
words: machineCodes,
hexList: Array.from(machineCodes).map(w => '0x' + (w >>> 0).toString(16).padStart(8, '0')),
symbolTable
};
}
}
五、运行测试与机器码验证
下面通过一段标准的累加循环汇编程序测试上述汇编器的准确性。该程序初始化计数器上限为 5,累加 1 + 2 + 3 + 4 + 5,最后将计算结果写回内存基址:
// 汇编源程序测试用例
const asmCode = `
# RISC-V 累加测试程序
start:
addi x1, x0, 5 # 目标次数 n = 5
addi x2, x0, 0 # 累加器 sum = 0
addi x3, x0, 1 # 循环变量 i = 1
loop:
add x2, x2, x3 # sum += i
addi x3, x3, 1 # i++
bne x3, x1, loop # if (i != 5) goto loop
sw x2, 0(x0) # 将累加和写入内存 0x0
jal x0, exit # 跳转至程序退出
exit:
`;
const assembler = new RV32Assembler();
const result = assembler.assemble(asmCode);
console.log("=== 符号表 (Symbol Table) ===");
result.symbolTable.forEach((pc, name) => {
console.log(` ${name.padEnd(8)} -> 0x${pc.toString(16).padStart(4, '0')}`);
});
console.log("\n=== 生成的 32 位机器码 (Hex) ===");
result.hexList.forEach((hex, idx) => {
console.log(` [${idx * 4}] ${hex}`);
});
在 Node.js 环境或浏览器开发者控制台中执行该段代码,将输出以下结果:
bne x3, x1, loop 为例:当前指令 PC 为 0x0014 (20),目标 loop 的 PC 为 0x000C (12)。相对偏移为 12 - 20 = -8。在两的补码中,-8 经过 B 型重排后的编码刚好对应十六进制 0xfe119ce3,与 GNU 官方 riscv64-unknown-elf-as 输出完全一致。
六、内存输出格式:转化为小端序字节数组
RISC-V 硬件采用小端字节序(Little-Endian),即最低有效字节存放于最低内存地址。在浏览器中将 Uint32Array 转入虚拟机内存或作为文件导出时,应通过 DataView 或 Uint8Array 规范序列化:
function toLittleEndianBytes(words) {
const bytes = new Uint8Array(words.length * 4);
const view = new DataView(bytes.buffer);
for (let i = 0; i < words.length; i++) {
view.setUint32(i * 4, words[i], true); // true 代表小端序
}
return bytes;
}
// 导出格式示例
const rawBytes = toLittleEndianBytes(result.words);
console.log("内存原始字节流 (前 8 字节):", Array.from(rawBytes.slice(0, 8)).map(b => '0x' + b.toString(16).padStart(2, '0')));
// 输出: ["0x93", "0x00", "0x50", "0x00", "0x13", "0x01", "0x00", "0x00"]
七、边界防御与常见陷阱排查
在编写自主可控的汇编器时,生产级代码必须对各类输入边界做严格拦截,避免生成静默错误的机器码:
- 立即数符号扩展与范围校验:I 型指令的立即数仅占 12 位,取值区间严格限制在
[-2048, 2047]。若直接输入超过 2047 的正数(例如 4096),截断会导致立即数高位覆盖其它操作数字段。 - 分支指令最低位舍弃原则:B 型和 J 型指令的跳转偏移量必须是 2 字节(半字)对齐的。因为最低位恒为 0,RISC-V 指令格式在编码时不保存
imm[0],而是将imm[1]存放于相应比特位上。汇编器在提取时必须使用(imm >> 1)。 - x0 寄存器的硬件特性:
x0寄存器在硬件层被硬接线为 0。即使向x0写入(如addi x0, x0, 10),其数值也不会改变。汇编器允许此类合法语法作为nop(空操作)或丢弃操作执行。
JavaScript alert警告框怎么写入变量与拼接字符串
2026-11-23 08:19:24
JavaScript遍历树结构:收集所有从根到叶子的路径数组
2026-11-22 20:51:21
JavaScript对象与数组基础操作入门
2026-11-22 19:51:43
JS控制台console.log输出怎么实现换行
2026-11-22 17:29:57
JavaScript Fetch API怎么使用AbortController实现请求超时
2026-11-22 16:53:58








