391 lines
16 KiB
Python
391 lines
16 KiB
Python
#!/usr/bin/env python3
|
||
"""Generate memory layout SVG diagrams for STM32F4-Base.
|
||
|
||
Usage:
|
||
python tools/arch_diagram/gen_memory_svg.py [--type ram|flash|taskstack|all]
|
||
|
||
Output (default --all):
|
||
docs/images/内存布局_RAM.svg
|
||
docs/images/内存布局_FLASH.svg
|
||
docs/images/任务栈预算.svg
|
||
"""
|
||
import argparse
|
||
import os
|
||
import sys
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Diagram data
|
||
# ---------------------------------------------------------------------------
|
||
|
||
# ── RAM breakdown (2026-09-21 @build, map Grand Totals; data/ram_report_20260921.md) ──
|
||
# Region 1: main SRAM RW_IRAM1 @0x20000000 (128KB = 131,072 B, DMA-reachable)
|
||
SRAM1_TOTAL = 131072
|
||
SRAM1_USED = 82048
|
||
SRAM1_FREE = SRAM1_TOTAL - SRAM1_USED
|
||
# Region 2: CCM RW_CCM @0x10000000 (64KB = 65,536 B, CPU only, DMA NOT reachable)
|
||
CCM_TOTAL = 65536
|
||
CCM_USED = 49184
|
||
CCM_FREE = CCM_TOTAL - CCM_USED
|
||
|
||
RAM1_CATEGORIES = [
|
||
("LVGL", 41460, "#4CAF50"),
|
||
("UI", 13532, "#FF9800"),
|
||
("FTL/BBT", 8812, "#9C27B0"),
|
||
("lftpd", 5324, "#8BC34A"),
|
||
("CMSIS", 5016, "#00BCD4"),
|
||
("NET", 4445, "#F44336"),
|
||
("HAL", 1280, "#607D8B"),
|
||
("C stack", 1024, "#795548"),
|
||
("other", 1155, "#9E9E9E"),
|
||
("free", SRAM1_FREE, "#E0E0E0"),
|
||
]
|
||
RAM2_CATEGORIES = [
|
||
("heap", 49184, "#2196F3"),
|
||
("free", CCM_FREE, "#E0E0E0"),
|
||
]
|
||
|
||
# ── Flash breakdown (1MB = 1,048,576 B; 2026-09-21 @build) ──────────────────
|
||
FLASH_TOTAL = 1048576
|
||
FLASH_CODE = 234976
|
||
FLASH_RO = 13824
|
||
FLASH_RW = 632
|
||
FLASH_USED = FLASH_CODE + FLASH_RO + FLASH_RW
|
||
FLASH_FREE = FLASH_TOTAL - FLASH_USED
|
||
|
||
FLASH_CATEGORIES = [
|
||
("代码段 (Code)", FLASH_CODE, "#2196F3"),
|
||
("只读数据 (RO)", FLASH_RO, "#4CAF50"),
|
||
("初始化数据 (RW)", FLASH_RW, "#FF9800"),
|
||
("Flash 空闲", FLASH_FREE, "#E0E0E0"),
|
||
]
|
||
|
||
# Flash code sub-breakdown (2026-09-21; top items from data/ram_report_20260921.md,
|
||
# long-tail .o objects below the report's top-44 threshold are counted in "其他")
|
||
FLASH_CODE_SUB = [
|
||
("LVGL 库", 98000, "#4CAF50"),
|
||
("应用代码/UI", 34110, "#2196F3"),
|
||
("FatFS", 8146, "#9C27B0"),
|
||
("dhara / FTL", 4982, "#FF9800"),
|
||
("HAL 驱动", 16000, "#607D8B"),
|
||
("FreeRTOS 内核", 10132, "#00BCD4"),
|
||
("CH395F 网络", 2738, "#F44336"),
|
||
("C 库 (microlib)", 4230, "#795548"),
|
||
("其他 (长尾)", 56638, "#E0E0E0"), # remainder
|
||
]
|
||
|
||
# ── Task stack budgets (2026-10-10 @build + 开机/空闲实测; data/stack_report_20261010.md) ──
|
||
# (name, cfg, prio, worst, peak_used, margin, margin_pct, verdict, desc)
|
||
# worst = max(静态最坏深度, 实测峰值); margin = cfg - worst
|
||
TASK_STACKS = [
|
||
("defaultTask", 4096, "Normal", 2776, 2152, 1320, 32, "PASS", "FatFS 挂载/探针 + 配置引擎 + syslog + 栈探针"),
|
||
("netTask", 3840, "Normal", 1872, 920, 1968, 51, "PASS", "CH395F 轮询、消息处理"),
|
||
("ftpTask", 4096, "Normal", 1216, 740, 2880, 70, "PASS", "lftpd FTP 服务(大缓冲已静态化)"),
|
||
("testTask", 8192, "BelowNormal", 496, 496, 7696, 93, "PASS", "测试套件(产品构建不创建,取静态最坏链)"),
|
||
("uiTask", 16384, "BelowNormal", 4016, 4016, 12368, 75, "PASS", "LVGL UI 主循环"),
|
||
("timeSyncTask", 2048, "Normal", 1024, 616, 1024, 50, "PASS", "TCP 时间同步(余量正好卡在 ISR 底线)"),
|
||
]
|
||
KERNEL_STACKS = [("idle", 512), ("timer", 1024)] # 128/256 words
|
||
|
||
HEAP_TOTAL = 49152 # configTOTAL_HEAP_SIZE(位于 RW_CCM)
|
||
HEAP_FREE = 8784 # 2026-09-21 实测(含 FTP 负载)
|
||
HEAP_MIN_EVER = 4848
|
||
TOTAL_STACKS = sum(t[1] for t in TASK_STACKS) # 38,656
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# SVG helpers
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def _text_width(text, char_w=7.2):
|
||
"""Rough monospace text width estimate (px)."""
|
||
return len(text) * char_w
|
||
|
||
|
||
def _wrap(text, max_chars=12):
|
||
"""Wrap label to multiple <tspan> lines."""
|
||
words = text.split("\n") if "\n" in text else text.split()
|
||
lines = []
|
||
current = ""
|
||
for w in words:
|
||
test = (current + " " + w).strip() if current else w
|
||
if len(test) > max_chars and current:
|
||
lines.append(current)
|
||
current = w
|
||
else:
|
||
current = test
|
||
if current:
|
||
lines.append(current)
|
||
return lines
|
||
|
||
|
||
def svg_header(w, h):
|
||
return (
|
||
f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {w} {h}" '
|
||
f'width="{w}" height="{h}" style="font-family:Consolas,\'Courier New\',monospace; '
|
||
f'font-size:12px; background:#fff">\n'
|
||
'<defs>\n'
|
||
'<style>\n'
|
||
'.title { font-size:14px; font-weight:bold; }\n'
|
||
'.label { font-size:11px; }\n'
|
||
'.legend-text { font-size:10px; }\n'
|
||
'.bar-seg { stroke:#fff; stroke-width:0.5; }\n'
|
||
'</style>\n'
|
||
'</defs>\n'
|
||
)
|
||
|
||
|
||
def svg_footer():
|
||
return '</svg>\n'
|
||
|
||
|
||
def _draw_bar_segment(x, y, w, h, fill, label_inside, label_outside="",
|
||
label_font=10, min_inside_w=40):
|
||
"""Return SVG fragment for a bar segment with label."""
|
||
parts = []
|
||
parts.append(f' <rect class="bar-seg" x="{x}" y="{y}" width="{w:.1f}" height="{h}" '
|
||
f'fill="{fill}" rx="2"/>\n')
|
||
if w > min_inside_w and label_inside:
|
||
# Center text inside bar
|
||
lines = _wrap(label_inside, max_chars=int(w / 7))
|
||
ty = y + h / 2 - (len(lines) - 1) * 6
|
||
for line in lines:
|
||
lx = x + w / 2
|
||
parts.append(f' <text x="{lx:.1f}" y="{ty:.1f}" text-anchor="middle" '
|
||
f'dominant-baseline="central" class="label" fill="#000">{line}</text>\n')
|
||
ty += 12
|
||
elif label_outside:
|
||
lx = x + w + 4
|
||
ty = y + h / 2
|
||
parts.append(f' <text x="{lx:.1f}" y="{ty:.1f}" text-anchor="start" '
|
||
f'dominant-baseline="central" class="legend-text" fill="#333">{label_outside}</text>\n')
|
||
return "".join(parts)
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Diagram generators
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def gen_ram_svg():
|
||
"""内存布局_RAM.svg — 两条堆叠条:主 SRAM(DMA 可达)+ CCM(仅 CPU)。"""
|
||
W, H = 820, 360
|
||
BAR_X, BAR_H = 60, 44
|
||
SCALE = (W - 80) / SRAM1_TOTAL # 128KB 占满宽;CCM (64KB) 占半宽
|
||
|
||
svg = svg_header(W, H)
|
||
svg += f'<text x="{W/2}" y="24" text-anchor="middle" class="title">SRAM (192KB) 使用布局 — 2026-09-21 @build</text>\n'
|
||
|
||
# Region 1: 主 SRAM
|
||
y1 = 50
|
||
svg += f'<text x="{BAR_X}" y="{y1-8}" class="label" fill="#555">主 SRAM RW_IRAM1 @0x20000000(128KB,DMA 可达)</text>\n'
|
||
x = BAR_X
|
||
for label, size, color in RAM1_CATEGORIES:
|
||
w = size * SCALE
|
||
if w < 1:
|
||
continue
|
||
inside = label if w > _text_width(label) + 10 else ""
|
||
svg += _draw_bar_segment(x, y1, w, BAR_H, color, inside, "")
|
||
x += w
|
||
svg += f'<text x="{BAR_X}" y="{y1+BAR_H+18}" class="label" fill="#333">'
|
||
svg += f'已用: {SRAM1_USED}B ({SRAM1_USED/SRAM1_TOTAL*100:.1f}%)'
|
||
svg += f' 空闲: {SRAM1_FREE}B ({SRAM1_FREE/SRAM1_TOTAL*100:.1f}%)'
|
||
svg += f' 总量: 128KB</text>\n'
|
||
|
||
# Region 2: CCM
|
||
y2 = y1 + BAR_H + 50
|
||
svg += f'<text x="{BAR_X}" y="{y2-8}" class="label" fill="#555">CCM RW_CCM @0x10000000(64KB,仅 CPU 可达,DMA 不可达)</text>\n'
|
||
x = BAR_X
|
||
for label, size, color in RAM2_CATEGORIES:
|
||
w = size * SCALE
|
||
if w < 1:
|
||
continue
|
||
inside = label if w > _text_width(label) + 10 else ""
|
||
svg += _draw_bar_segment(x, y2, w, BAR_H, color, inside, "")
|
||
x += w
|
||
svg += f'<text x="{BAR_X}" y="{y2+BAR_H+18}" class="label" fill="#333">'
|
||
svg += f'已用: {CCM_USED}B ({CCM_USED/CCM_TOTAL*100:.1f}%)'
|
||
svg += f' 空闲: {CCM_FREE}B ({CCM_FREE/CCM_TOTAL*100:.1f}%)'
|
||
svg += f' 总量: 64KB</text>\n'
|
||
|
||
# Legend(主 SRAM 两列 + CCM 两行)
|
||
ly = y2 + BAR_H + 40
|
||
lx = 60
|
||
half = (len(RAM1_CATEGORIES) + 1) // 2
|
||
for i, (label, size, color) in enumerate(RAM1_CATEGORIES):
|
||
pct = size / SRAM1_TOTAL * 100
|
||
kb = size / 1024
|
||
if i >= half:
|
||
lx2 = 420
|
||
else:
|
||
lx2 = 60
|
||
yy = 226 + (i % half) * 16
|
||
svg += f' <rect x="{lx2}" y="{yy}" width="12" height="12" fill="{color}" rx="2"/>\n'
|
||
svg += f' <text x="{lx2+16}" y="{yy+10}" class="legend-text" fill="#333">'
|
||
svg += f'主SRAM {label}: {kb:.1f}KB ({pct:.1f}%)</text>\n'
|
||
for i, (label, size, color) in enumerate(RAM2_CATEGORIES):
|
||
pct = size / CCM_TOTAL * 100
|
||
kb = size / 1024
|
||
yy = 322 + i * 16
|
||
svg += f' <rect x="{60}" y="{yy}" width="12" height="12" fill="{color}" rx="2"/>\n'
|
||
svg += f' <text x="{76}" y="{yy+10}" class="legend-text" fill="#333">'
|
||
svg += f'CCM {label}: {kb:.1f}KB ({pct:.1f}%)</text>\n'
|
||
|
||
svg += svg_footer()
|
||
return svg
|
||
|
||
|
||
def gen_flash_svg():
|
||
"""内存布局_FLASH.svg — bar + code sub-breakdown."""
|
||
W, H = 820, 240
|
||
BAR_X, BAR_Y, BAR_H = 60, 50, 40
|
||
SCALE = (W - 80) / FLASH_TOTAL
|
||
|
||
svg = svg_header(W, H)
|
||
svg += f'<text x="{W/2}" y="24" text-anchor="middle" class="title">Flash (1MB) 使用布局 — 2026-09-21 @build</text>\n'
|
||
|
||
x = BAR_X
|
||
for label, size, color in FLASH_CATEGORIES:
|
||
w = size * SCALE
|
||
if w < 1:
|
||
continue
|
||
inside = f"{label} {size/1024:.1f}KB" if w > 60 else ""
|
||
outside = "" if w > 60 else f"{label} {size/1024:.1f}KB"
|
||
svg += _draw_bar_segment(x, BAR_Y, w, BAR_H, color, inside, outside)
|
||
x += w
|
||
|
||
# Summary below bar
|
||
svg += f'<text x="{BAR_X}" y="{BAR_Y+BAR_H+18}" class="label" fill="#333">'
|
||
svg += f'已用: {FLASH_USED/1024:.1f}KB ({FLASH_USED/FLASH_TOTAL*100:.1f}%)'
|
||
svg += f' 空闲: {FLASH_FREE/1024:.1f}KB ({FLASH_FREE/FLASH_TOTAL*100:.1f}%)'
|
||
svg += f' 总量: 1024KB</text>\n'
|
||
|
||
# Code sub-breakdown mini bar
|
||
Y2 = 130
|
||
svg += f'<text x="{BAR_X}" y="{Y2-6}" class="label" fill="#555">代码段明细 ({FLASH_CODE/1024:.1f}KB)</text>\n'
|
||
SCALE2 = (W - 80) / FLASH_CODE
|
||
x2 = BAR_X
|
||
for label, size, color in FLASH_CODE_SUB:
|
||
w = size * SCALE2
|
||
if w < 1:
|
||
continue
|
||
inside = f"{label} {size/1024:.1f}KB" if w > 50 else ""
|
||
outside = "" if w > 50 else f"{label} {size/1024:.1f}KB"
|
||
svg += _draw_bar_segment(x2, Y2, w, 24, color, inside, outside)
|
||
x2 += w
|
||
|
||
svg += svg_footer()
|
||
return svg
|
||
|
||
|
||
def gen_taskstack_svg():
|
||
"""任务栈预算.svg — 每任务:分配栈条 + 最坏占用叠加条 + 实测余量/判定。"""
|
||
W, H = 880, 440
|
||
BAR_X = 190
|
||
MAX_STACK = 16384
|
||
SCALE = (W - BAR_X - 40) / MAX_STACK
|
||
Y_START = 64
|
||
ROW_PITCH = 40
|
||
BAR_H = 16
|
||
|
||
svg = svg_header(W, H)
|
||
svg += f'<text x="{W/2}" y="22" text-anchor="middle" class="title">FreeRTOS 任务栈预算(48KB 堆,2026-09-21 已迁 CCM)</text>\n'
|
||
svg += f'<text x="{W/2}" y="40" text-anchor="middle" class="legend-text" fill="#777">数据: 2026-10-10 @build + 开机/空闲实测(data/stack_report_20261010.md);最坏 = max(静态最坏链, 实测峰值)</text>\n'
|
||
svg += f'<text x="{BAR_X}" y="{Y_START-10}" class="legend-text" fill="#555">浅色条 = 分配栈 深色条 = 最坏占用(max(静态最坏, 实测峰值)) 下方文字 = 实测余量/判定</text>\n'
|
||
|
||
y = Y_START
|
||
for name, cfg, prio, worst, peak, margin, pct, verdict, desc in TASK_STACKS:
|
||
w = cfg * SCALE
|
||
wc = worst * SCALE
|
||
dark = "#2196F3" if prio == "Normal" else "#FF9800"
|
||
light = "#BBDEFB" if prio == "Normal" else "#FFE0B2"
|
||
vc = "#2E7D32" if verdict == "PASS" else "#C62828"
|
||
|
||
# 任务名(左侧)
|
||
svg += f' <text x="{BAR_X-4}" y="{y+8}" text-anchor="end" dominant-baseline="central" class="label" fill="#333">{name}</text>\n'
|
||
# 分配栈条(浅色)+ 最坏占用叠加条(深色)
|
||
svg += f' <rect class="bar-seg" x="{BAR_X}" y="{y}" width="{w:.1f}" height="{BAR_H}" fill="{light}" rx="3"/>\n'
|
||
svg += f' <rect x="{BAR_X}" y="{y}" width="{wc:.1f}" height="{BAR_H}" fill="{dark}" rx="3"/>\n'
|
||
# 数据行
|
||
svg += f' <text x="{BAR_X}" y="{y+BAR_H+11}" dominant-baseline="central" class="legend-text" fill="#333">'
|
||
svg += f'配置 {cfg}B | 实测峰值 {peak}B | 最坏 {worst}B | 余量 {margin}B ({pct}%) '
|
||
svg += f'<tspan fill="{vc}" font-weight="bold">{verdict}</tspan></text>\n'
|
||
y += ROW_PITCH
|
||
|
||
# 内核任务(静态小栈,未取句柄实测)
|
||
y += 4
|
||
for name, stack in KERNEL_STACKS:
|
||
w = max(stack * SCALE, 2)
|
||
svg += f' <text x="{BAR_X-4}" y="{y+6}" text-anchor="end" dominant-baseline="central" class="label" fill="#333">{name}</text>\n'
|
||
svg += f' <rect class="bar-seg" x="{BAR_X}" y="{y}" width="{w:.1f}" height="12" fill="#90A4AE" rx="2"/>\n'
|
||
svg += f' <text x="{BAR_X + w + 4}" y="{y+6}" dominant-baseline="central" class="legend-text" fill="#333">{stack}B(未实测)</text>\n'
|
||
y += 22
|
||
|
||
# 堆汇总(实测值)
|
||
y += 8
|
||
svg += f'<text x="{BAR_X}" y="{y}" class="label" fill="#555">'
|
||
svg += f'堆总量: {HEAP_TOTAL}B (48KB, RW_CCM) 任务栈合计: {TOTAL_STACKS}B ({TOTAL_STACKS/1024:.1f}KB) + 内核栈 {512+1024}B</text>\n'
|
||
y += 16
|
||
svg += f'<text x="{BAR_X}" y="{y}" class="label" fill="#555">'
|
||
svg += f'实测: free={HEAP_FREE}B / min_ever={HEAP_MIN_EVER}B(2026-09-21,含 FTP 负载) 判定: 6/6 PASS(余量 ≥ max(1024B, 配置×30%))</text>\n'
|
||
y += 24
|
||
# 颜色图例
|
||
svg += f' <rect x="{BAR_X}" y="{y}" width="10" height="10" fill="#2196F3" rx="2"/>\n'
|
||
svg += f' <text x="{BAR_X+14}" y="{y+8}" class="legend-text" fill="#333">Normal 优先级</text>\n'
|
||
svg += f' <rect x="{BAR_X+130}" y="{y}" width="10" height="10" fill="#FF9800" rx="2"/>\n'
|
||
svg += f' <text x="{BAR_X+144}" y="{y+8}" class="legend-text" fill="#333">BelowNormal 优先级</text>\n'
|
||
svg += f' <rect x="{BAR_X+290}" y="{y}" width="10" height="10" fill="#90A4AE" rx="2"/>\n'
|
||
svg += f' <text x="{BAR_X+304}" y="{y+8}" class="legend-text" fill="#333">内核任务栈 (idle/timer)</text>\n'
|
||
|
||
svg += svg_footer()
|
||
return svg
|
||
|
||
|
||
# ---------------------------------------------------------------------------
|
||
# Main
|
||
# ---------------------------------------------------------------------------
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description="Generate memory layout SVG diagrams")
|
||
parser.add_argument("--type", choices=["ram", "flash", "taskstack", "all"], default="all")
|
||
args = parser.parse_args()
|
||
|
||
out_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||
"docs", "images")
|
||
os.makedirs(out_dir, exist_ok=True)
|
||
|
||
generators = {
|
||
"ram": ("内存布局_RAM.svg", gen_ram_svg),
|
||
"flash": ("内存布局_FLASH.svg", gen_flash_svg),
|
||
"taskstack": ("任务栈预算.svg", gen_taskstack_svg),
|
||
}
|
||
|
||
if args.type == "all":
|
||
targets = generators.values()
|
||
else:
|
||
targets = [generators[args.type]]
|
||
|
||
for filename, gen_func in targets:
|
||
path = os.path.join(out_dir, filename)
|
||
svg = gen_func()
|
||
with open(path, "w", encoding="utf-8") as f:
|
||
f.write(svg)
|
||
print(f"OK: {filename} ({len(svg)} bytes)")
|
||
|
||
# XML self-check
|
||
for filename, _ in targets:
|
||
path = os.path.join(out_dir, filename)
|
||
with open(path, "r", encoding="utf-8") as f:
|
||
content = f.read()
|
||
if not content.startswith("<svg "):
|
||
print(f"FAIL: {filename} does not start with <svg", file=sys.stderr)
|
||
sys.exit(1)
|
||
if "</svg>" not in content:
|
||
print(f"FAIL: {filename} missing </svg>", file=sys.stderr)
|
||
sys.exit(1)
|
||
if 'xmlns="http://www.w3.org/2000/svg"' not in content:
|
||
print(f"FAIL: {filename} missing xmlns", file=sys.stderr)
|
||
sys.exit(1)
|
||
print("All SVG self-checks passed")
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|