feat(saolei): 新增纯 C 扫雷(MMIO 显示 + 中断读鼠标),扩展 CPU 外设并清理仓库
## 背景
在原有五级流水 CPU 的基础上,用一颗 RISC-V 工具链把"纯 C 写的扫雷"编译成机器码
固化进片内 ROM 运行,并为此把 MMIO 外设从"只有一个 LED 寄存器"扩展成
显示(VGA 显存)+ 七段数码管 + 鼠标事件(含中断)的完整子系统。
原 LED MMIO 的语义保持不变,原有跑马灯/中断/指令回归不受影响。
## 硬件(pipelined-cpu/srcs)
- cpu21_mmio.v:扩展成 MMIO 中枢,新增
* 七段数码管寄存器(0x1004,8 位十六进制)
* 鼠标寄存器组(0x1100+):STATUS/DATA/ACK/CTRL/INPUT/TIME/FRAME/EVCNT/LEVEL/MAGIC
—— 含 16 项事件 FIFO 与 mouse_irq_o(读空自动回 0,不丢事件)
* 显示控制器(0x1140+):CTRL(光标可见/背景色)、CURSOR(列、行)
* 显存窗口(0x2000-0x27FF):写端口输出到板级顶层的双口 RAM,读保持组合读
* LEVEL(0x1120):软件中断寄存器,写 1 拉起 level_irq_o(用作"关卡入口")
* 地址译码、字节写合并、读数据 mux 全部按原风格实现
- 新增外设 RTL:cpu21_vga.v(640x480@60 按格子扫描,8x8 字模放大 2 倍)、
cpu21_seg7.v(8 位数码管动态扫描)、cpu21_pointer.v(5 向按键→鼠标事件,1 ms 去抖
+ 事件排队)、cpu21_ps2_mouse.v(可选真鼠标,PS/2 11 位帧接收 + 3 字节包解析)
- cpu21_riscv_redirect_int_bpb.v:新增外设总线端口(显存写/读回、鼠标事件输入、
中断输出、数码管数据、帧脉冲),例化扩展后的 cpu21_mmio
- cpu21_board_top.v:接入显存双口 RAM + VGA + 数码管 + 鼠标事件源,中断接线为
irq_i = {SW2, LEVEL|SW1, 鼠标|SW0};ROM 宏切换(定义 SAOLEI_ROM 加载扫雷程序);
ROM_WORDS 1024→8192
- cpu21_board_top.xdc:新增按键、SW[3]、8 位数码管、VGA、PS/2 的全部引脚约束
- tb_board_top.v:新端口显式接 0/1,避免悬空影响原跑马灯回归
- create_project.tcl:把 cpu21_saolei_rom.vh 按 Verilog Header 条件加入
## 软件(saolei/)
- sw/mmio.h:全部 MMIO 地址与格子编码(换地址只改这一个文件)
- sw/saolei.c:纯 C 扫雷 —— 背景"伪操作系统" main()(开始界面)+ 关卡 level_main()
(在 IRQ1 里跑完整局)+ 棋盘位图/布雷(首点安全)/BFS 展开/插旗/胜负判定/逐格绘制
- sw/isr.c:**中断读鼠标的代码**。三个固定地址入口:
* isr1_entry(.text.isr1=0x100)关卡入口:保存全部调用者保存寄存器 +
csrrsi 打开 MIE(让鼠标中断可嵌套)→ level_main
* isr2_entry(.text.isr2=0x200)鼠标读取:只存 ra → 纯 C 主体 isr_body
* isr3_entry(.text.isr3=0x300)备用:直接 uret
- sw/start.c:设 sp、清 .bss、进 main(只有这一处必要内联汇编)
- sw/linker.ld:复位 0x0、三个中断入口 0x100/0x200/0x300、栈顶 0x0FFC;
用 ASSERT 禁止 .data/.rodata(这颗核读不到 ROM 里的数据)
## 构建与工具链适配(saolei/tools)
- build.ps1:一键 C → .o → ELF → .hex + cpu21_saolei_rom.vh,任一步失败立刻停止
- check_isa.py:用"指令白名单"逐条检查反汇编,出现本核未实现的指令即报错并给修复提示
- elf2hex.py:裸二进制 → $readmemh hex + ROM 初始化头文件
- 三处针对本核的关键配置(都已写进脚本注释):
1) -march=rv32im_zicsr(GCC 15 起 rv32im 不含 Zicsr,csrrsi 会报错)
2) 不能禁链接器松弛:gcc 函数调用默认是 auipc+jalr,靠松弛压成 jal,
禁掉后 35 条 auipc 会留在代码里(本核没有 auipc);
用 -msmall-data-limit=0 防止松弛引入 gp 相对寻址
3) 中断入口地址必须写在段声明上(.text.isr1 0x100 : ...),
只写 ". = 0x100;" 会被 ld 忽略(实测 isr1 掉到了 0x14)
- 实测结果:text=3368B、data=0、bss=1436B,842 条指令全部通过 ISA 检查,
入口地址 _start=0x0 / isr1_entry=0x100 / isr2_entry=0x200 / isr3_entry=0x300
## 仓库清理
- 删除被工程取代的 saolei/hw、saolei/constrs(外设已并入 srcs/rtl)
- 删除全部 Vivado 生成物:.xpr、.runs、.sim、.cache、.hw、.ip_user_files、.Xil、
vivado.jou/log —— 需要工程时用 source create_project.tcl 一键重建(约 0.3 MB 源文件)
- .gitignore 增加 saolei/build/(构建产物可一键重建)
## 文档
- README:更新目录结构、仓库约定(不放生成物)、MMIO 地址表、文件与模块划分表、
上板说明,新增"扫雷程序(saolei/)"章节
- saolei/README.md:重写 —— 程序结构(背景/关卡/鼠标 + 三个中断入口)、
本核指令子集与对应写法、构建步骤与实测数据、MMIO 地址表、上板/仿真步骤、
操作说明、验证状态与已知可改进项
## 验证状态(如实说明)
- 已实测:C 工具链链路(编译/链接/ISA 检查/hex 生成/入口地址逐条核对)
- 未验证:所有 RTL 未经综合与仿真(本机无 Vivado),C 程序也未在仿真器/硬件上运行过;
建议先跑 tools/run_regress.ps1 确认原回归仍全 PASS,再用 SAOLEI_ROM 宏做行为仿真
This commit is contained in:
@@ -0,0 +1,174 @@
|
||||
# =============================================================================
|
||||
# build.ps1 —— 扫雷程序一键构建:C -> 汇编/目标文件 -> ELF -> .hex + .vh
|
||||
#
|
||||
# 用法(在 saolei\ 目录下):
|
||||
# powershell -ExecutionPolicy Bypass -File tools\build.ps1
|
||||
# powershell -ExecutionPolicy Bypass -File tools\build.ps1 -Prefix riscv64-unknown-elf-
|
||||
#
|
||||
# 产物(都在 saolei\build\ 下):
|
||||
# saolei.lst objdump -d 反汇编清单(这就是"编译出来的汇编",可以直接看)
|
||||
# saolei.elf 可执行文件
|
||||
# saolei.bin 裸二进制
|
||||
# saolei.hex $readmemh 格式:拷到 pipelined-cpu\srcs\rom\saolei.hex 就能
|
||||
# 用现成的测试平台(tb_no_intr 等)仿真
|
||||
# saolei.map 链接 map(看段地址和大小)
|
||||
# 并且会生成 pipelined-cpu\srcs\board\cpu21_saolei_rom.vh —— 供 cpu21_board_top.v 用
|
||||
# `include 固化进 ROM(在 Vivado 里定义宏 SAOLEI_ROM 即可切换到扫雷程序)
|
||||
#
|
||||
# 构建流程里有三道针对这颗 CPU 的关卡:
|
||||
# 1) -fno-pic -mcmodel=medlow -mno-relax:避免 auipc / 链接器松弛
|
||||
# 2) 链接脚本里的 ASSERT:禁止 .data / .rodata(这颗核读不到 ROM 里的数据)
|
||||
# 3) tools\check_isa.py:逐条检查反汇编,凡是用到未实现指令(auipc/lb/lbu/div...)
|
||||
# 直接报错并给出修复提示
|
||||
# =============================================================================
|
||||
param(
|
||||
[string]$Prefix = "",
|
||||
[int]$RomWords = 8192,
|
||||
[switch]$SkipIsaCheck
|
||||
)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$root = Split-Path -Parent $PSScriptRoot
|
||||
$sw = Join-Path $root 'sw'
|
||||
$build = Join-Path $root 'build'
|
||||
New-Item -ItemType Directory -Force $build | Out-Null
|
||||
|
||||
# ---------------------------------------------------------------- 工具链探测
|
||||
if (-not $Prefix) {
|
||||
foreach ($cand in 'riscv-none-elf-', 'riscv64-unknown-elf-', 'riscv32-unknown-elf-',
|
||||
'riscv-none-embed-', 'riscv64-linux-gnu-') {
|
||||
if (Get-Command ($cand + 'gcc') -ErrorAction SilentlyContinue) { $Prefix = $cand; break }
|
||||
}
|
||||
}
|
||||
if (-not $Prefix) {
|
||||
Write-Output "ERROR: 找不到 RISC-V 交叉编译器(riscv*-gcc)。"
|
||||
Write-Output ""
|
||||
Write-Output "装一个即可(推荐 xPack 的 riscv-none-elf-gcc,解压就用,不用管理员权限):"
|
||||
Write-Output " 1) 打开 https://github.com/xpack-dev-tools/riscv-none-elf-gcc-xpack/releases"
|
||||
Write-Output " 2) 下载 win32-x64 的 .zip(例如 xpack-riscv-none-elf-gcc-14.2.0-3-win32-x64.zip)"
|
||||
Write-Output " 3) 解压到例如 C:\tools\riscv-none-elf-gcc"
|
||||
Write-Output " 4) 把 C:\tools\riscv-none-elf-gcc\bin 加进 PATH(或者直接运行本脚本时):"
|
||||
Write-Output " powershell -ExecutionPolicy Bypass -File tools\build.ps1 -Prefix 'C:\tools\riscv-none-elf-gcc\bin\riscv-none-elf-'"
|
||||
exit 1
|
||||
}
|
||||
|
||||
$GCC = $Prefix + 'gcc'
|
||||
$OBJDUMP = $Prefix + 'objdump'
|
||||
$OBJCOPY = $Prefix + 'objcopy'
|
||||
$SIZE = $Prefix + 'size'
|
||||
|
||||
Write-Output "工具链前缀: $Prefix"
|
||||
|
||||
# ---------------------------------------------------------------- 编译参数
|
||||
# -march=rv32im_zicsr : RV32I + M 扩展 + Zicsr(CSR 指令:csrrw/csrrsi/csrrci)。
|
||||
# GCC 15 起不再默认给 rv32im 开 zicsr,中断入口里的
|
||||
# csrrsi 必须显式打开这个扩展才认。
|
||||
# -mcmodel=medlow -fno-pic : 用 lui/addi 绝对寻址,不产生 auipc
|
||||
# **必须放开链接器松弛**(不要 -mno-relax):gcc 的函数调用默认是
|
||||
# auipc ra, %pcrel_hi(f) + jalr ra, ra, %pcrel_lo(f)
|
||||
# 要靠链接器松弛把它变成一条 jal,否则 auipc 会留在最终代码里(这颗核没有)。
|
||||
# 松弛只会在两种情况下改变指令:把 pcrel 调用变成 jal,或在使用 gp 相对寻址时
|
||||
# 变成 gp 相对访问 —— 后者已被 -msmall-data-limit=0 从根上禁止。
|
||||
# -msmall-data-limit=0 : 不用 gp 相对寻址
|
||||
# -fno-builtin -nostdlib -ffreestanding : 不要 libc(没有环境,也没有 printf)
|
||||
# -fno-jump-tables : 不生成跳转表(跳转表会落在 .rodata,这颗核读不到)
|
||||
$ccCommon = @(
|
||||
'-march=rv32im_zicsr', '-mabi=ilp32',
|
||||
'-mcmodel=medlow',
|
||||
'-fno-pic', '-fno-PIC', '-fno-pie',
|
||||
'-msmall-data-limit=0', '-fno-common',
|
||||
'-fno-builtin', '-fno-stack-protector', '-fno-jump-tables',
|
||||
'-ffreestanding', '-nostdlib',
|
||||
'-ffunction-sections', '-fdata-sections',
|
||||
'-Os', '-Wall', '-Wextra'
|
||||
)
|
||||
|
||||
# 中断主体(isr.c)必须只使用 callee-saved 寄存器,否则会破坏被打断的代码。
|
||||
# 下面把所有"调用者保存"的通用寄存器都固定住,GCC 就只能用 s0-s11 和 sp。
|
||||
$fixedRegs = @()
|
||||
foreach ($r in 1, 3, 4, 5, 6, 7, 10, 11, 12, 13, 14, 15, 16, 17, 28, 29, 30, 31) {
|
||||
$fixedRegs += ('-ffixed-x' + $r)
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- 编译
|
||||
$objs = @()
|
||||
|
||||
# 跑外部命令并在非 0 退出码时立刻停下(native 命令失败不会抛异常,必须查 $LASTEXITCODE)
|
||||
function Invoke-Tool {
|
||||
param([string]$Exe, [string[]]$ArgList, [string]$What)
|
||||
& $Exe @ArgList
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
Write-Output ("ERROR: 失败 -> " + $What)
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
Write-Output "编译 start.c ..."
|
||||
Invoke-Tool -Exe $GCC -ArgList ($ccCommon + @('-c', (Join-Path $sw 'start.c'), '-o', (Join-Path $build 'start.o'))) -What 'start.c'
|
||||
$objs += (Join-Path $build 'start.o')
|
||||
|
||||
Write-Output "编译 saolei.c ..."
|
||||
Invoke-Tool -Exe $GCC -ArgList ($ccCommon + @('-c', (Join-Path $sw 'saolei.c'), '-o', (Join-Path $build 'saolei.o'))) -What 'saolei.c'
|
||||
$objs += (Join-Path $build 'saolei.o')
|
||||
|
||||
Write-Output "编译 isr.c(额外加 -ffixed 约束)..."
|
||||
Invoke-Tool -Exe $GCC -ArgList ($ccCommon + $fixedRegs + @('-c', (Join-Path $sw 'isr.c'), '-o', (Join-Path $build 'isr.o'))) -What 'isr.c'
|
||||
$objs += (Join-Path $build 'isr.o')
|
||||
|
||||
# ---------------------------------------------------------------- 链接
|
||||
$elf = Join-Path $build 'saolei.elf'
|
||||
$map = Join-Path $build 'saolei.map'
|
||||
$ld = Join-Path $sw 'linker.ld'
|
||||
|
||||
Write-Output "链接 ..."
|
||||
# 注意:PowerShell 会把未加引号的 "-Wl,--no-relax" 当成参数对解析(逗号引起),
|
||||
# 所以这里统一用参数数组,所有选项都带引号。
|
||||
$linkArgs = @(
|
||||
'-march=rv32im_zicsr', '-mabi=ilp32', '-nostdlib', '-nostartfiles',
|
||||
"-Wl,-Map=$map",
|
||||
'-T', $ld, '-o', $elf
|
||||
) + $objs
|
||||
Invoke-Tool -Exe $GCC -ArgList $linkArgs -What '链接(-T sw/linker.ld)'
|
||||
|
||||
# ---------------------------------------------------------------- 反汇编 + ISA 检查
|
||||
$lst = Join-Path $build 'saolei.lst'
|
||||
& $OBJDUMP -d -M no-aliases $elf | Out-File -Encoding utf8 $lst
|
||||
Write-Output "反汇编清单: $lst"
|
||||
|
||||
$isaOk = $true
|
||||
if (-not $SkipIsaCheck) {
|
||||
Write-Output ""
|
||||
& py (Join-Path $PSScriptRoot 'check_isa.py') $lst
|
||||
if ($LASTEXITCODE -ne 0) { $isaOk = $false }
|
||||
}
|
||||
|
||||
# ---------------------------------------------------------------- 转 hex / vh
|
||||
$bin = Join-Path $build 'saolei.bin'
|
||||
$hex = Join-Path $build 'saolei.hex'
|
||||
$vh = Join-Path $root '..\pipelined-cpu\srcs\board\cpu21_saolei_rom.vh'
|
||||
|
||||
& $OBJCOPY -O binary $elf $bin
|
||||
& py (Join-Path $PSScriptRoot 'elf2hex.py') $bin $hex $RomWords $vh
|
||||
|
||||
# ---------------------------------------------------------------- 汇总
|
||||
Write-Output ""
|
||||
Write-Output "==== 段大小 ===="
|
||||
& $SIZE $elf
|
||||
|
||||
$isrLine = Select-String -Path $lst -Pattern '^[0-9a-f]+ <(isr1_entry|isr2_entry|isr3_entry|_start)>:' |
|
||||
Select-Object -ExpandProperty Line
|
||||
Write-Output "==== 入口地址 ===="
|
||||
foreach ($l in $isrLine) { Write-Output (" " + $l) }
|
||||
Write-Output " 三个中断入口必须和顶层 cpu21_board_top 的参数一致:"
|
||||
Write-Output " linker.ld 的 .text.isr1/2/3 = IRQ1/2/3_VECTOR = 0x100/0x200/0x300"
|
||||
|
||||
Write-Output ""
|
||||
if ($isaOk) {
|
||||
Write-Output "构建完成:$hex 与 $vh 已生成。"
|
||||
Write-Output " 仿真:把 saolei.hex 拷到 pipelined-cpu\srcs\rom\saolei.hex,用 tb_no_intr 加载"
|
||||
Write-Output " 上板:cpu21_saolei_rom.vh 已生成到 srcs/board/,Vivado 里定义宏 SAOLEI_ROM 后综合"
|
||||
} else {
|
||||
Write-Output "构建完成,但 ISA 检查没通过(见上面的清单),这个 hex 放到 CPU 上会跑飞。"
|
||||
exit 1
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
"""check_isa.py —— 校验反汇编清单里没有这颗 CPU 未实现的指令。
|
||||
|
||||
用法: python tools/check_isa.py <objdump输出.txt>
|
||||
|
||||
为什么需要它:本 CPU(srcs/rtl/cpu21_riscv_decoder.v)只实现了 RV32I 的一个
|
||||
子集,最容易踩的三个坑是:
|
||||
* 没有 auipc -> 编译器一旦生成它,整段代码就废了(多为 PIC/rodata 引起)
|
||||
* 没有 lb/lh/lbu/lhu -> 只要碰 char/short 类型的读就会出现
|
||||
* 没有有符号 div/rem(只有 divu/remu) -> 有符号除法/取余会被静默算错
|
||||
|
||||
所以这里用"白名单"方式检查:出现名单外的助记符就报错并给出修复提示。
|
||||
退出码 = 违规条数(>255 时截断),0 表示通过。
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
# 这颗 CPU 真正实现了的指令(见 cpu21_riscv_decoder.v)
|
||||
ALLOWED = {
|
||||
# R 型
|
||||
"add", "sub", "sll", "slt", "sltu", "xor", "srl", "sra", "or", "and",
|
||||
# M 扩展(只有这几个)
|
||||
"mul", "mulh", "mulhsu", "mulhu", "divu", "remu",
|
||||
# I 型
|
||||
"addi", "slti", "sltiu", "xori", "ori", "andi", "slli", "srli", "srai",
|
||||
# 访存:只有 lw / sw / sb(没有 lb/lh/lbu/lhu/sh)
|
||||
"lw", "sw", "sb",
|
||||
# 控制流
|
||||
"beq", "bne", "blt", "bge", "bltu", "bgeu", "jal", "jalr",
|
||||
# 高位立即数
|
||||
"lui",
|
||||
# 系统
|
||||
"ecall", "uret", "csrrw", "csrrsi", "csrrci",
|
||||
}
|
||||
|
||||
# objdump 有时仍打印伪指令;这些展开后都是上面支持的指令
|
||||
ALIAS_OK = {
|
||||
"nop", "mv", "li", "j", "jr", "ret", "neg", "not",
|
||||
"beqz", "bnez", "blez", "bgez", "bltz", "bgtz",
|
||||
"seqz", "snez", "sltz", "sgtz",
|
||||
}
|
||||
|
||||
# 违规时给出针对性提示
|
||||
HINTS = {
|
||||
"auipc": "出现了 auipc:说明编译带了 PIC/PIE 或访问了只读数据。"
|
||||
"请用 -fno-pic -mcmodel=medlow,并去掉字符串/常量表(.rodata)",
|
||||
"lb": "没有 lb:不要用 char/short 类型读内存,改用 32 位字",
|
||||
"lh": "没有 lh:同上",
|
||||
"lbu": "没有 lbu:不要用 unsigned char/short 类型读内存(写显存可以用 sb,但别读回来)",
|
||||
"lhu": "没有 lhu:同上",
|
||||
"sh": "没有 sh:只用 sw / sb",
|
||||
"div": "没有有符号 div:改用 unsigned 运算(unsigned 除法会编成 divu)",
|
||||
"rem": "没有有符号 rem:改用 unsigned 运算(unsigned 取余会编成 remu)",
|
||||
"divw": "不支持 64 位运算",
|
||||
"remw": "不支持 64 位运算",
|
||||
"call": "call 会展开成 auipc+jalr:请直接用普通函数调用(jal)",
|
||||
"tail": "tail 会展开成 auipc:请用普通跳转",
|
||||
"fence": "没有 fence/fence.i",
|
||||
"ebreak": "没有 ebreak",
|
||||
"mret": "这颗核的中断返回是 uret,不是 mret",
|
||||
"sret": "这颗核的中断返回是 uret",
|
||||
"wfi": "没有 wfi:主循环只能用轮询",
|
||||
"unimp": "出现了 unimp(非法指令/内联汇编占位)",
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 2:
|
||||
print("用法: python tools/check_isa.py <objdump输出.txt>")
|
||||
return 2
|
||||
|
||||
path = sys.argv[1]
|
||||
total = 0
|
||||
violations = []
|
||||
|
||||
with open(path, encoding="utf-8", errors="replace") as f:
|
||||
for line in f:
|
||||
if "\t" not in line:
|
||||
continue
|
||||
parts = line.split("\t")
|
||||
if len(parts) < 3 or not parts[0].strip().endswith(":"):
|
||||
continue
|
||||
mnemonic = parts[2].strip().split()[0]
|
||||
if not mnemonic:
|
||||
continue
|
||||
total += 1
|
||||
if (mnemonic not in ALLOWED) and (mnemonic not in ALIAS_OK):
|
||||
violations.append((parts[0].strip(), mnemonic, line.rstrip()))
|
||||
|
||||
print("检查了 %d 条指令。" % total)
|
||||
|
||||
if not violations:
|
||||
print("ISA 检查通过:全部指令都在本 CPU 的实现范围内。")
|
||||
return 0
|
||||
|
||||
print("")
|
||||
print("!! ISA 检查失败:有 %d 条指令这颗 CPU 没有实现:" % len(violations))
|
||||
seen = set()
|
||||
for addr, mnemonic, raw in violations[:40]:
|
||||
print(" %s %s" % (addr, raw.strip()))
|
||||
seen.add(mnemonic)
|
||||
if len(violations) > 40:
|
||||
print(" ...(只列出前 40 条)")
|
||||
|
||||
print("")
|
||||
print("修复提示:")
|
||||
for m in sorted(seen):
|
||||
print(" * %s: %s" % (m, HINTS.get(m, "不在本 CPU 的指令白名单里")))
|
||||
return min(len(violations), 255)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,66 @@
|
||||
#!/usr/bin/env python3
|
||||
"""elf2hex.py —— 把 objcopy 出来的裸二进制转成 ROM 需要的两份文件。
|
||||
|
||||
用法: python tools/elf2hex.py <input.bin> <output.hex> [ROM_WORDS] [output.vh]
|
||||
|
||||
产出:
|
||||
1) <output.hex> 每行一个 32 位字($readmemh 格式,供 srcs/rom/ 下的
|
||||
测试平台加载,例如拷成 srcs/rom/saolei.hex)
|
||||
2) <output.vh>(可选) rom[i] = 32'h...; 语句,供
|
||||
pipelined-cpu/srcs/board/cpu21_board_top.v 里 `include
|
||||
固化进片内 ROM(未用到的地址填 NOP 0x00000013)
|
||||
(未用到的地址填 NOP 0x00000013)
|
||||
|
||||
字序:输入的 .bin 是按字节小端排列的机器码,这里按小端拼成 32 位字。
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
NOP = 0x00000013
|
||||
|
||||
|
||||
def main():
|
||||
if len(sys.argv) < 3:
|
||||
print("用法: python tools/elf2hex.py <input.bin> <output.hex> [ROM_WORDS] [output.vh]")
|
||||
return 2
|
||||
|
||||
src = sys.argv[1]
|
||||
dst = sys.argv[2]
|
||||
words_total = int(sys.argv[3]) if len(sys.argv) > 3 else 8192
|
||||
vh_path = sys.argv[4] if len(sys.argv) > 4 else None
|
||||
|
||||
with open(src, "rb") as f:
|
||||
data = f.read()
|
||||
|
||||
if len(data) % 4 != 0:
|
||||
print("警告:二进制长度 %d 不是 4 的倍数,尾部会被补 0" % len(data))
|
||||
data += b"\x00" * (4 - len(data) % 4)
|
||||
|
||||
words = []
|
||||
for i in range(0, len(data), 4):
|
||||
words.append(int.from_bytes(data[i:i + 4], "little"))
|
||||
|
||||
if len(words) > words_total:
|
||||
print("错误:程序 %d 个字,超过 ROM 容量 %d 个字(改大 ROM_WORDS 或精简程序)"
|
||||
% (len(words), words_total))
|
||||
return 1
|
||||
|
||||
with open(dst, "w", encoding="ascii") as f:
|
||||
for w in words:
|
||||
f.write("%08X\n" % w)
|
||||
|
||||
if vh_path:
|
||||
with open(vh_path, "w", encoding="utf-8") as f:
|
||||
f.write(" // 由 tools/elf2hex.py 生成,请勿手工编辑\n")
|
||||
f.write(" // 源文件:%s(%d 个字,其余填 NOP)\n" % (src, len(words)))
|
||||
for addr in range(words_total):
|
||||
w = words[addr] if addr < len(words) else NOP
|
||||
f.write(" rom[%d] = 32'h%08X;\n" % (addr, w))
|
||||
|
||||
print("已生成 %s(%d 个字)%s" % (dst, len(words),
|
||||
("、%s(%d 个字,NOP 填充)" % (vh_path, words_total)) if vh_path else ""))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user