Pcileech-tool/tlscan2pcileech_rw1c.py

71 lines
2.1 KiB
Python
Raw Permalink Normal View History

2025-08-10 16:58:35 +08:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
tlscan2pcileech_coe.py
TLScan .tlscan 文件转换成 PCILeech 所需的 COE 格式
用法
python tlscan2pcileech_coe.py input.tlscan
结果
同目录下生成 input_rw1.coe input_rw1c.coe
"""
import os
import sys
import datetime
import xml.etree.ElementTree as ET
# ---------- 参数 ----------
if len(sys.argv) < 2:
print("用法: python tlscan2pcileech_coe.py <xxx.tlscan>")
sys.exit(1)
src = sys.argv[1]
base, _ = os.path.splitext(src)
dst_rw1 = base + "_rw1.coe"
dst_rw1c = base + "_rw1c.coe"
# ---------- 读取 TLScan ----------
try:
bs_hex = ET.parse(src).find('.//bytes').text
except Exception as e:
sys.exit(f"解析 TLScan 文件失败: {e}")
bs_hex = ''.join(bs_hex.split())
if len(bs_hex) != 8192: # 4096 字节 => 8192 字符
sys.exit(f"期望 8192 个十六进制字符,实际 {len(bs_hex)}")
# ---------- 生成掩码 ----------
# 4096 字节 => 1024 个 dword
words_rw1 = [0] * 1024
words_rw1c = [0] * 1024
for i in range(4096):
val = int(bs_hex[i*2:i*2+2], 16)
# 简易规则0x01 视为 RW1C/RW1CS
if val != 0x00:
words_rw1[i//4] |= 1 << ((i % 4) * 8)
if val == 0x01:
words_rw1c[i//4] |= 1 << ((i % 4) * 8)
# ---------- 写 COE ----------
def write_coe(path, words):
with open(path, 'w') as f:
f.write(f'; Converted to COE from "{src}" on {datetime.datetime.now()}\n')
f.write('memory_initialization_radix=16;\nmemory_initialization_vector=\n')
for blk in range(16):
offset = blk * 256
f.write(f'; {offset:04x}\n')
for line in range(16):
idx = blk * 64 + line * 4
line_words = [words[idx + j] for j in range(4)]
f.write(','.join(f'{w:08x}' for w in line_words) + ',\n')
# 去掉最后一个逗号
f.seek(f.tell() - 2, os.SEEK_SET) # 回退 2 字节(,\n
f.truncate()
f.write('\n;\n')
write_coe(dst_rw1, words_rw1)
write_coe(dst_rw1c, words_rw1c)
print(f'已生成:\n {dst_rw1}\n {dst_rw1c}')