-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprogramator.py
More file actions
executable file
·232 lines (185 loc) · 7.58 KB
/
Copy pathprogramator.py
File metadata and controls
executable file
·232 lines (185 loc) · 7.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
#!/usr/bin/env python3
"""
programator.py — Firmware to Verilog converter
Converts firmware binary (.mem / .elf / .bin) to a synthesizable
Verilog RAM module. The generated module is self-contained:
- Has CPU memory interface (mem_valid, mem_addr, mem_wdata, mem_wstrb, mem_rdata, mem_ready)
- Handles its own timing in a single always block
- Initial values from firmware via Verilog initial begin
- Sync read from BRAM (1-cycle latency, handled internally)
Usage:
programator firmware.mem -o ram.v
programator firmware.elf --module-name ram --depth 2048 -o ram.v
programator firmware.mem --info
"""
import sys
import os
import argparse
import subprocess
def load_mem(path):
"""Load Verilog .mem file (objcopy -O verilog format) -> bytes"""
data = bytearray()
current_addr = 0
with open(path) as f:
for line in f:
line = line.strip()
if not line:
continue
if line.startswith('@'):
target_addr = int(line[1:], 16)
if target_addr > current_addr:
data.extend(b'\x00' * (target_addr - current_addr))
current_addr = target_addr
else:
for byte_str in line.split():
data.append(int(byte_str, 16))
current_addr += 1
return bytes(data)
def load_elf(path):
"""Load ELF file -> bytes via objcopy"""
tools = [
"riscv64-unknown-elf-objcopy",
"riscv32-unknown-elf-objcopy",
"objcopy",
]
tmp_mem = path + ".tmp.mem"
for tool in tools:
result = subprocess.run(
[tool, "-O", "verilog", path, tmp_mem],
capture_output=True
)
if result.returncode == 0:
data = load_mem(tmp_mem)
os.unlink(tmp_mem)
return data
print(f"[ERROR] objcopy not found. Tried: {', '.join(tools)}", file=sys.stderr)
sys.exit(1)
def load_bin(path):
with open(path, "rb") as f:
return f.read()
def load_firmware(path):
"""Auto-detect file type and load"""
ext = os.path.splitext(path)[1].lower()
if ext in ('.mem', '.hex'):
return load_mem(path)
elif ext in ('.elf', '.axf'):
return load_elf(path)
elif ext in ('.bin',):
return load_bin(path)
else:
with open(path, 'rb') as f:
magic = f.read(4)
if magic == b'\x7fELF':
return load_elf(path)
try:
return load_mem(path)
except Exception:
return load_bin(path)
def bytes_to_words(data, word_size_bytes, endian):
"""Convert byte array to list of words"""
words = []
remainder = len(data) % word_size_bytes
if remainder:
data = data + b'\x00' * (word_size_bytes - remainder)
for i in range(0, len(data), word_size_bytes):
chunk = data[i:i + word_size_bytes]
if endian == 'little':
word = int.from_bytes(chunk, byteorder='little')
else:
word = int.from_bytes(chunk, byteorder='big')
words.append(word)
return words
def generate_verilog(words, module_name, word_bits, depth):
"""Generate self-contained RAM module with CPU memory interface.
Single always block — no extra pipeline stages, BRAM-friendly."""
addr_bits = (depth - 1).bit_length()
hex_digits = word_bits // 4
byte_bits = word_bits // 8
lines = []
lines.append(f"// {module_name}.v -- Auto-generated by programator.py")
lines.append(f"// DO NOT EDIT -- regenerate with: programator <firmware> -o {module_name}.v")
lines.append(f"// Words: {len(words)}, Word size: {word_bits} bits, Depth: {depth}")
lines.append(f"// Self-contained memory subsystem with internal timing")
lines.append("")
lines.append(f"`timescale 1ns/1ps")
lines.append("")
lines.append(f"module {module_name} #(")
lines.append(f" parameter DEPTH = {depth}")
lines.append(f") (")
lines.append(f" input wire clk,")
lines.append(f" input wire mem_valid,")
lines.append(f" input wire [{addr_bits-1}:0] mem_addr,")
lines.append(f" input wire [{word_bits-1}:0] mem_wdata,")
lines.append(f" input wire [{byte_bits-1}:0] mem_wstrb,")
lines.append(f" output reg [{word_bits-1}:0] mem_rdata,")
lines.append(f" output reg mem_ready")
lines.append(f");")
lines.append(f" reg [{word_bits-1}:0] mem [0:DEPTH-1];")
lines.append(f"")
lines.append(f" initial begin")
for i, word in enumerate(words):
if word != 0:
lines.append(f" mem[{i}] = {word_bits}'h{word:0{hex_digits}X};")
lines.append(f" end")
lines.append(f"")
lines.append(f" always @(posedge clk) begin")
lines.append(f" mem_ready <= 0;")
lines.append(f" if (mem_valid) begin")
for b in range(byte_bits):
hi = (b + 1) * 8 - 1
lo = b * 8
lines.append(f" if (mem_wstrb[{b}]) mem[mem_addr][{hi}:{lo}] <= mem_wdata[{hi}:{lo}];")
lines.append(f" mem_rdata <= mem[mem_addr];")
lines.append(f" mem_ready <= 1;")
lines.append(f" end")
lines.append(f" end")
lines.append(f"")
lines.append(f"endmodule")
lines.append(f"")
return "\n".join(lines)
def main():
parser = argparse.ArgumentParser(
description="Convert firmware binary to synthesizable Verilog RAM module"
)
parser.add_argument("input", help="Input firmware file (.mem, .elf, .bin)")
parser.add_argument("-o", "--output", default=None, help="Output Verilog file (default: stdout)")
parser.add_argument("--module-name", default="ram", help="Verilog module name (default: ram)")
parser.add_argument("--word-size", type=int, default=32, help="Word size in bits (default: 32)")
parser.add_argument("--depth", type=int, default=None, help="RAM depth in words (default: auto)")
parser.add_argument("--endian", choices=["little", "big"], default="little")
parser.add_argument("--info", action="store_true", help="Print firmware info and exit")
args = parser.parse_args()
if not os.path.exists(args.input):
print(f"[ERROR] File not found: {args.input}", file=sys.stderr)
sys.exit(1)
word_bytes = args.word_size // 8
print(f"[PROG] Loading: {args.input}", file=sys.stderr)
data = load_firmware(args.input)
print(f"[PROG] Firmware size: {len(data)} bytes", file=sys.stderr)
words = bytes_to_words(data, word_bytes, args.endian)
print(f"[PROG] Words: {len(words)} x {args.word_size}-bit", file=sys.stderr)
if args.depth is None:
depth = max(256, 1 << (len(words) - 1).bit_length())
if depth < len(words):
depth = len(words)
else:
depth = args.depth
if len(words) > depth:
print(f"[WARN] Firmware ({len(words)} words) exceeds depth ({depth})", file=sys.stderr)
words = words[:depth]
if args.info:
print(f"Input: {args.input}")
print(f"Size: {len(data)} bytes / {len(words)} words")
print(f"Depth: {depth} words ({depth * word_bytes} bytes)")
return
print(f"[PROG] RAM depth: {depth} words ({depth * word_bytes} bytes)", file=sys.stderr)
verilog = generate_verilog(words, args.module_name, args.word_size, depth)
if args.output:
os.makedirs(os.path.dirname(os.path.abspath(args.output)), exist_ok=True)
with open(args.output, "w") as f:
f.write(verilog)
print(f"[PROG] Written: {args.output}", file=sys.stderr)
else:
print(verilog)
if __name__ == "__main__":
main()