#!/usr/bin/env python3 """thread_local 析构安全审计(VDE-1271)。 背景(docs/reference/132): 本机 MinGW GCC 16.1 UCRT 工具链存在 thread_local 非平凡析构缺陷。 只要某个工作线程里初始化了带非平凡析构函数的 thread_local 对象 (std::string / std::vector / std::mt19937 等),线程退出时 LdrShutdownThread -> tls_callback -> run_dtor_list 阶段释放内存, 约 5%-20% 概率触发 STATUS_HEAP_CORRUPTION (0xC0000374)。 最小复现与 cdb 栈见 docs/reference/132。 约定: 线程局部状态必须用「thread_local 指针 + 首次 new、进程生命周期内不释放」 (指针本身平凡析构,不注册 TLS 析构回调),或改为显式传参上下文。 确需例外时在声明后加注释标记 vde-tls-safe 并说明理由。 用法: python tools/kernel_audit/thread_local_audit.py --root . python tools/kernel_audit/thread_local_audit.py --root . --self-test 退出码:0 PASS,1 发现违规/自检失败,2 用法或环境错误。 """ from __future__ import annotations import argparse import re import sys from pathlib import Path # 已知带非平凡析构的类型标记(出现即需要指针化/例外标记)。 RISKY_MARKERS = ( "std::string", "std::wstring", "std::vector", "std::map", "std::set", "std::unordered_map", "std::unordered_set", "std::list", "std::deque", "std::function", "std::shared_ptr", "std::unique_ptr", "std::weak_ptr", "std::mt19937", "std::ostringstream", "std::istringstream", "std::stringstream", "std::tuple", "std::optional", "std::variant", "StepImportDiagnostic", "StepImportOptions", ) SAFE_MARK = "vde-tls-safe" SCAN_DIRS = ("src", "include") SOURCE_SUFFIXES = (".cpp", ".cc", ".cxx", ".h", ".hpp", ".hh") _TLS_RE = re.compile(r"\bthread_local\b") def strip_comments(text: str) -> str: """把 // 与 /* */ 注释替换为空格,保留换行与字符串字面量。""" out = [] i = 0 n = len(text) state = "code" # code | line | block | dq | sq while i < n: ch = text[i] nxt = text[i + 1] if i + 1 < n else "" if state == "code": if ch == "/" and nxt == "/": state = "line" out.append(" ") i += 1 elif ch == "/" and nxt == "*": state = "block" out.append(" ") i += 1 elif ch == '"': state = "dq" out.append(ch) elif ch == "'": state = "sq" out.append(ch) else: out.append(ch) elif state == "line": if ch == "\n": state = "code" out.append("\n") else: out.append(" ") elif state == "block": if ch == "*" and nxt == "/": state = "code" out.append(" ") i += 1 elif ch == "\n": out.append("\n") else: out.append(" ") else: # string literal out.append(ch) if ch == "\\" and i + 1 < n: out.append(text[i + 1]) i += 1 elif (state == "dq" and ch == '"') or (state == "sq" and ch == "'"): state = "code" i += 1 return "".join(out) def declaration_segment(rest: str) -> str: """截取 thread_local 之后的声明文本(到初始化器/构造调用/语句结束)。""" for stop in (";", "="): pos = rest.find(stop) if pos >= 0: rest = rest[:pos] pos = rest.find("(") if pos >= 0: rest = rest[:pos] return rest def classify(line: str, raw: str = "") -> str: """返回 'ok' | 'risky' | 'none'(无 thread_local)。 raw 用于识别注释里的 vde-tls-safe 例外标记(注释已在 line 中被剥离)。 """ if SAFE_MARK in raw or SAFE_MARK in line: return "ok" m = _TLS_RE.search(line) if not m: return "none" segment = declaration_segment(line[m.end():]) if "*" in segment or "&" in segment: return "ok" if any(marker in segment for marker in RISKY_MARKERS): return "risky" return "ok" def scan_file(path: Path, display: str): violations = [] total = 0 try: text = path.read_text(encoding="utf-8") except OSError: return violations, total stripped = strip_comments(text).splitlines() raw_lines = text.splitlines() for lineno, line in enumerate(stripped, 1): if not _TLS_RE.search(line): continue total += 1 raw = raw_lines[lineno - 1] if lineno - 1 < len(raw_lines) else line if classify(line, raw) == "risky": violations.append((display, lineno, raw.strip())) return violations, total def iter_sources(root: Path): for name in SCAN_DIRS: base = root / name if not base.is_dir(): continue for path in sorted(base.rglob("*")): if not path.is_file() or path.suffix.lower() not in SOURCE_SUFFIXES: continue if "third_party" in path.parts: continue yield path def self_test() -> int: cases = [ ("static thread_local std::string g_x;", "risky"), ("thread_local std::mt19937 gen(std::random_device{}());", "risky"), ("thread_local std::vector v;", "risky"), ("static thread_local StepImportDiagnostic g_import_diag;", "risky"), ("static thread_local std::string* msg = nullptr;", "ok"), ("static thread_local std::mt19937* gen = nullptr;", "ok"), ("static thread_local int depth = 0;", "ok"), ("static thread_local size_t stCount[3] = {0};", "ok"), ("int x = 0;", "none"), ("// thread_local std::string g_x;", "none"), ("static thread_local std::string g_x; // vde-tls-safe: test", "ok"), ] # 先走注释剥离,再分类,验证注释不会误报。 failures = [] for source, expected in cases: stripped = strip_comments(source) got = classify(stripped, source) if got != expected: failures.append((source, expected, got)) if failures: print("[FAIL] thread_local_audit self-test:") for source, expected, got in failures: print(" {!r}: expected={} got={}".format(source, expected, got)) return 1 print("[PASS] thread_local_audit self-test: {} cases".format(len(cases))) return 0 def main(argv=None) -> int: parser = argparse.ArgumentParser(description="thread_local 非平凡析构安全审计") parser.add_argument("--root", default=".", help="仓库根目录") parser.add_argument("--self-test", action="store_true", help="先运行内置自检") parser.add_argument("--json", action="store_true", help="JSON 输出") args = parser.parse_args(argv) root = Path(args.root).resolve() if not root.is_dir(): print("错误: 根目录不存在: {}".format(root), file=sys.stderr) return 2 rc = self_test() if args.self_test else 0 violations = [] total = 0 files = 0 for path in iter_sources(root): files += 1 shown = path.relative_to(root).as_posix() found, count = scan_file(path, shown) violations.extend(found) total += count if args.json: import json print(json.dumps({ "files": files, "thread_local_declarations": total, "violations": [ {"file": f, "line": line, "declaration": decl} for f, line, decl in violations ], }, ensure_ascii=False, indent=2)) else: for path, line, decl in violations: print("[FAIL] {}:{}: {}".format(path, line, decl)) print("") print("RESULT: {} (files={} thread_local_declarations={} violations={})".format( "FAIL" if violations else "PASS", files, total, len(violations))) return 1 if (violations or rc) else 0 if __name__ == "__main__": sys.exit(main())