#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 静态栈深度分析工具(RT-Thread / Cortex-M 固件) 用途:从编译产物(.elf) + -fstack-usage 结果(.su) 反推每个线程入口的最坏栈深度, 用于定位"栈溢出"类 HardFault(如 rt_thread_stack_check 误报/真溢出)。 用法: python stack_usage.py [--entry func ...] """ import re import sys import os import glob import shutil import subprocess from collections import defaultdict def _find_toolchain(): """定位 arm-none-eabi-* 所在目录。 顺序:环境变量 RTT_TOOLCHAIN_BIN > RT-Thread Studio 安装目录 > PATH。 工具链不在 PATH 时若直接调用会静默返回空输出,导致"无入口函数"的假象。 """ env = os.environ.get("RTT_TOOLCHAIN_BIN") if env and os.path.isdir(env): return env pats = [ r"D:/RT-ThreadStudio/repo/Extract/ToolChain_Support_Packages/ARM/" r"GNU_Tools_for_ARM_Embedded_Processors/*/bin", r"C:/RT-ThreadStudio/repo/Extract/ToolChain_Support_Packages/ARM/" r"GNU_Tools_for_ARM_Embedded_Processors/*/bin", r"D:/RT-ThreadStudio/**/GNU_Tools_for_ARM_Embedded_Processors/*/bin", ] cands = [] for p in pats: cands += glob.glob(p, recursive=True) cands.sort(reverse=True) # 取版本号较大的 for c in cands: if os.path.isfile(os.path.join(c, "arm-none-eabi-objdump.exe")) or \ os.path.isfile(os.path.join(c, "arm-none-eabi-objdump")): return c return None _TC = _find_toolchain() _EXE = ".exe" if os.name == "nt" else "" def _tool(name): """优先用定位到的工具链,否则回退到 PATH""" if _TC: p = os.path.join(_TC, name + _EXE) if os.path.isfile(p): return '"%s"' % p return name OBJDUMP = _tool("arm-none-eabi-objdump") NM = _tool("arm-none-eabi-nm") def run(cmd): # errors="replace":objdump/nm 输出中可能混入非 UTF-8 字节(调试信息里的中文路径等), # Windows 下默认按 locale 解码会直接抛 UnicodeDecodeError return subprocess.run(cmd, shell=True, capture_output=True, text=True, errors="replace").stdout def load_symbols(elf): """地址 -> (名字, 大小)""" out = run(f'{NM} -S --defined-only "{elf}"') syms = [] for line in out.splitlines(): p = line.split() if len(p) < 3: continue try: addr = int(p[0], 16) except ValueError: continue size = 0 name = p[2] if len(p) >= 4: try: size = int(p[1], 16) name = p[3] except ValueError: name = p[2] syms.append((addr, size, name)) syms.sort() return syms def addr_to_sym(syms, addr): lo, hi = 0, len(syms) - 1 best = None while lo <= hi: mid = (lo + hi) // 2 if syms[mid][0] <= addr: best = mid lo = mid + 1 else: hi = mid - 1 if best is None: return None a, s, n = syms[best] if s and addr >= a + s: return None return n def load_frames(su_dirs): """函数名 -> 栈帧字节数,来自 -fstack-usage (.su)""" frames = {} for d in su_dirs: if not os.path.isdir(d): continue for fn in os.listdir(d): if not fn.endswith(".su"): continue with open(os.path.join(d, fn), errors="ignore") as f: for line in f: parts = line.split("\t") if len(parts) < 2: continue m = re.match(r".*?:(\d+):(\d+):(\w+)", parts[0]) if not m: continue name = m.group(3) try: frames[name] = int(parts[1]) except ValueError: pass return frames def parse_disasm(elf): """函数名 -> (自身帧估算, [被调用函数名])""" out = run(f'{OBJDUMP} -d "{elf}"') funcs = {} cur = None for line in out.splitlines(): m = re.match(r"^([0-9a-f]{8}) <([^>]+)>:", line) if m: cur = m.group(2) funcs[cur] = {"push": 0, "sub": 0, "calls": []} continue if cur is None: continue if re.search(r"\tbl\t", line) or re.search(r"\tbl\.w\t", line): t = re.search(r"<([^>+]+)(\+0x[0-9a-f]+)?>", line) if t: funcs[cur]["calls"].append(t.group(1)) else: m2 = re.search(r"\tpush\t\{([^}]*)\}", line) if m2: funcs[cur]["push"] = max(funcs[cur]["push"], 4 * (m2.group(1).count(",") + 1)) m3 = re.search(r"\tsub\tsp, #(\d+)", line) if m3: funcs[cur]["sub"] = max(funcs[cur]["sub"], int(m3.group(1))) return funcs EXCLUDES = {"list_thread", "rt_hw_hard_fault_exception", "object_split", "object_split.constprop.1", "list_get_next"} def main(): elf = sys.argv[1] su_dirs = [] entries = [] i = 2 while i < len(sys.argv): if sys.argv[i] == "--entry": entries = sys.argv[i + 1:] break su_dirs.append(sys.argv[i]) i += 1 frames = load_frames(su_dirs) funcs = parse_disasm(elf) def frame_of(name): if name in frames: return frames[name] if name in funcs: return funcs[name]["push"] + funcs[name]["sub"] return 0 global EXCLUDES if not entries: entries = [n for n in funcs if n.endswith("_entry")] INF = 1 << 30 def worst(name, path, memo): """返回 (最坏栈深度, 最深路径)""" if name in path: return (0, []) if name in memo: return memo[name] f = frame_of(name) best = (0, []) for c in funcs.get(name, {}).get("calls", []): if c not in funcs or c in EXCLUDES: continue d, p = worst(c, path | {name}, memo) if d > best[0]: best = (d, p) res = (f + best[0], [name] + best[1]) memo[name] = res return res print(f"{'entry':34s} {'deepest-path-bytes':>18s} path") print("-" * 110) rows = [] for e in entries: if e not in funcs: continue memo = {} d, p = worst(e, set(), memo) rows.append((d, e, p)) for d, e, p in sorted(rows, reverse=True): chain = " -> ".join(p[:8]) + (" -> ..." if len(p) > 8 else "") print(f"{e:34s} {d:18d} {chain}") if __name__ == "__main__": main()