@@ -0,0 +1,857 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" 网络句柄失效值契约门禁(net-handle)。
为什么要有这根钩子(2026-11-18):
板端 104 连不上的真因不是 " 漏了一个 -1 " ,而是一个语言语义缺口被多种纪律叠出来:
文件作用域 `static` 的 fd 由 C 零初始化为 0,而本项目 net 层 fd 域是 0~7( 0 是**合法**
描述符),于是 " 从未打开 " 被 `fd >= 0` 判据当成 " 持有 fd " ,网络代际切换后误关别的服务的
监听槽,最终 104 建链拿到 FTP 的 220 banner。契约见 `docs/网络/网络句柄失效值契约.md`
与 `Drivers/BSP/NET/net_fd.h`;本脚本把契约里可机械判定的部分搬到提交期。
规则(对应任务书 §4;R1~R4 判 C 源文本,R5 判契约文件存在):
R1 fd 形标识符(名字含 fd / sock / socket / handle)与整数字面量比较。
R2 文件作用域 `static` 的 fd 标量 / 含 fd 成员的结构体:无初始化器、`= {0} `、
或指定初始化器缺 fd 成员 / fd 成员不是 NET_FD_INVALID。
R3 `memset(对象, 0, ...)` 作用于含 fd 成员的结构体后 5 行内没有回填 NET_FD_INVALID。
R4 `if (fd)` / `if (!fd)` 这种 " 数值真值 " 判据。
R5 `Drivers/BSP/NET/net_fd.h` 定义 NET_FD_INVALID,且 `net_socket.h` include 它。
白名单(为什么不是 " 漏判 " ):
`Drivers/BSP/NET/` 是契约的**层内**实现者:C4 明确允许它做 `0 <= fd < NET_MAX_SOCKETS`
区间校验,且 fd 槽数组以 " 槽下标 " 为身份、清零即释放(`memset(p_sock, 0, ...)` 正是
回收动作),对它套 R1~R4 会把正经实现判成违规。`test/host/` 是主机假对象,fd 域按
C7 从 0 起分配,同样需要按测试语域写断言。两者的契约合规性由 R5 + 独立验收复核。
用法:
python scripts/check_net_handle.py # 全仓扫描(钩子也是全仓扫描)
python scripts/check_net_handle.py --selftest # 自证:正例必抓、正确写法不误报
python scripts/check_net_handle.py --verbose # 打印被跳过的路径与判定细节
退出码:0 = 0 违规;1 = 有违规;2 = 契约文件缺失或内部错误(与 pre-commit 环境错误同口径)。
"""
from __future__ import annotations
import argparse
import os
import re
import sys
REPO = os . path . dirname ( os . path . dirname ( os . path . abspath ( __file__ ) ) )
NET_FD_H = " Drivers/BSP/NET/net_fd.h "
NET_SOCKET_H = " Drivers/BSP/NET/net_socket.h "
INVALID = " NET_FD_INVALID "
# 第三方 / 生成物 / 归档:跳过(与 cppcheck、coding-standard 的排除面同口径 + 归档脚本)。
SKIP_PREFIXES = (
" Drivers/CMSIS/ " ,
" Drivers/STM32F4xx_HAL_Driver/ " ,
" Drivers/BSP/dhara/ " ,
" Middlewares/ " ,
" Lib/ " ,
" MDK-ARM/ " ,
" IEC60870-Slave/ " ,
" App/protocol/iec60870/ " , # 旧路径(第三方钉死区,兼容尚未迁移的树)
# 2026-11-18 主树把 104 协议栈迁到 App/iec60870/。大写 IEC104_* 是尚未改造的
# 上游代码,排除面与 .pre-commit-config.yaml 的 coding-standard 同口径暂免检;
# 小写 iec104_* 是自研适配层,仍受本契约检查(含 net_mcu 的 fd 改动)。
" App/iec60870/common/ " ,
" App/iec60870/104/business/ " ,
" App/iec60870/104/IEC104_ " ,
" App/iec60870/104/IEC104. " ,
" App/iec60870/examples/ " ,
" scripts/archive/ " ,
" .opencode/ " ,
" .agents/ " ,
" .git/ " ,
" .venv/ " ,
" ci-artifacts/ " ,
" docs/ " ,
" simulator/build/ " ,
" simulator/SDL2/ " ,
" test/host/iec104_netmcu/results/ " , # 变异体生成物(故意植入缺陷,不能当源码判)
)
# R1~R4 的白名单(语义见文件头)。三者分开写,方便以后按需收窄。
WHITELIST = {
" R1 " : ( " Drivers/BSP/NET/ " , " test/host/ " ) ,
" R2 " : ( " Drivers/BSP/NET/ " , " test/host/ " ) ,
" R3 " : ( " Drivers/BSP/NET/ " , " test/host/ " ) ,
" R4 " : ( " Drivers/BSP/NET/ " , " test/host/ " ) ,
}
EXPR = r " [A-Za-z_] \ w*(?: \ s*(?: \ .|->) \ s*[A-Za-z_] \ w*)* "
LITERAL = r " (?:- \ s*)? \ d+(?:[uUlL]+)? "
OP = r " (?:>=|<=|==|!=|>|<) "
CMP_EXPR_FIRST = re . compile (
r " (?<![ \ w.>])( " + EXPR + r " ) \ s*( " + OP + r " ) \ s*( " + LITERAL + r " ) \ b " )
CMP_LITERAL_FIRST = re . compile (
r " (?<![ \ w.])( " + LITERAL + r " ) \ s*( " + OP + r " ) \ s*( " + EXPR + r " )(?! \ s*[ \ w(]) " )
IF_TRUTHY = re . compile (
r " \ bif \ s* \ ( \ s*(!? \ s*)( " + EXPR + r " ) \ s* \ ) " )
TYPE_QUALIFIERS = {
" static " , " const " , " volatile " , " extern " , " register " , " auto " ,
" unsigned " , " signed " , " long " , " short " , " int " , " char " , " float " , " double " ,
" void " , " struct " , " union " , " enum " , " inline " ,
}
# ------------------------------------------------------------------ 文本预处理
def strip_nocode ( text : str ) - > str :
""" 把注释 / 字符串 / 字符字面量的内容替换成空格,保留换行与偏移。
为什么必须做:本仓注释里大量写着 `fd >= 0` 这种**反面教材**( time_sntp.c 的
指针注释就是这么写的),不剥注释会把教材当违规。字符串里的 banner 同理。
"""
out = [ ]
i = 0
n = len ( text )
state = " code " # code | line | block | str | chr
while i < n :
c = text [ i ]
nxt = text [ i + 1 ] if i + 1 < n else " "
if state == " code " :
if c == " / " and nxt == " / " :
state = " line "
out . append ( " " )
i + = 2
continue
if c == " / " and nxt == " * " :
state = " block "
out . append ( " " )
i + = 2
continue
if c == ' " ' :
state = " str "
out . append ( " " )
i + = 1
continue
if c == " ' " :
state = " chr "
out . append ( " " )
i + = 1
continue
out . append ( c )
i + = 1
continue
# 非 code 状态:吞掉内容(换行保留,块注释换行要留给行号)
if c == " \n " :
out . append ( " \n " )
i + = 1
continue
if state == " line " :
out . append ( " " )
i + = 1
if nxt == " " :
state = " code "
continue
if state == " block " :
if c == " * " and nxt == " / " :
out . append ( " " )
i + = 2
state = " code "
continue
out . append ( " " )
i + = 1
continue
if state == " str " :
if c == " \\ " :
out . append ( " " )
i + = 2
continue
if c == ' " ' :
state = " code "
out . append ( " " )
i + = 1
continue
if state == " chr " :
if c == " \\ " :
out . append ( " " )
i + = 2
continue
if c == " ' " :
state = " code "
out . append ( " " )
i + = 1
continue
return " " . join ( out )
def line_of ( text : str , pos : int ) - > int :
""" 偏移 -> 1 基行号。 """
return text . count ( " \n " , 0 , pos ) + 1
# ------------------------------------------------------------------ 名字判定
def is_fd_name ( name : str ) - > bool :
""" fd 形标识符:名字含 fd / sock / socket / handle(整词形态)。
排除项都有实测理由:
- 全大写(`NET_MAX_SOCKETS`、`NET_FD_INVALID`)是宏/常量,不是 " 持有中的句柄 " ;
- `fd_bits` / `fd_mask` / `fd_set` 是位掩码,不是描述符;
- `handler` / `handled` 不是句柄(`handle` 只认整词与 `_handle` 结尾)。
"""
if not name :
return False
if name . isupper ( ) :
return False
low = name . lower ( )
# 状态/布尔/计数后缀:`sock_ok`( echo 是否成功)、`sock_state`、`sock_count`
# 这类名字带 sock 但不是句柄,按名字面判会误报(2026-11-18 在 test/board 实测到
# `if (sock_ok)`)。它们是"关于 socket 的标量",不是"保存 fd 的变量"。
if low . endswith ( ( " _bits " , " _mask " , " _set " , " _ok " , " _flag " , " _ready " , " _valid " ,
" _state " , " _err " , " _count " , " _num " , " _idx " , " _len " , " _size " ) ) :
return False
if re . search ( r " (^|_)fd(_|$) " , low ) or low . endswith ( " fd " ) :
return True
if " sock " in low :
return True
if re . search ( r " (^|_)handle(s)?(_|$) " , low ) :
return True
return False
def fd_name_kind ( name : str ) - > str | None :
""" 把 fd 形名字分成两档: ' fd ' ( fd/sock,真实描述符)与 ' handle ' (不透明句柄)。
为什么要分档(2026-11-18 实测):IEC 104 后端的 `handle` 是 uintptr_t 会话令牌,
它自己的头文件写明失效值是 IEC104_NET_INVALID_SOCKET( UINTPTR_MAX),而槽里
同时还有真正的 `int fd`。对 `handle == 0U`( " 没有句柄值 " )要求改写成
NET_FD_INVALID 会**改坏语义**;真正属于本契约那一类的是 " 用 -1 / <0 这种数值
形态表达失效 " 。故 handle 档只抓负数字面量(-1、< 0),fd/sock 档抓任何整数
字面量比较。
命名含 `handle` 者一律归 handle 档(2026-11-18 实测):`socket_handle` 同时含
socket 与 handle,但它是 104 的不透明会话令牌(uintptr_t),不是文件描述符;
若按 socket 归到 fd 档,就会逼着把 `socket_handle == 0U` 改写成
`== NET_FD_INVALID`,改坏语义。名字面里出现 handle 就说明持有者自认这是句柄。
"""
if not is_fd_name ( name ) :
return None
low = name . lower ( )
if re . search ( r " (^|_)handle(s)?(_|$) " , low ) :
return " handle "
if re . search ( r " (^|_)fd(_|$) " , low ) or low . endswith ( " fd " ) or " sock " in low :
return " fd "
return " handle "
def is_fd_member ( name : str ) - > bool :
""" 结构体成员是否是 " fd 成员 " : fd / sockfd / *_fd。比 R1 的名字面窄。"""
low = name . lower ( )
if low . endswith ( ( " _bits " , " _mask " , " _set " ) ) :
return False
return bool ( re . search ( r " (^|_)fd(_|$) " , low ) or low . endswith ( " fd " ) )
def last_name ( expr : str ) - > str :
""" 取成员表达式最后一个标识符:`s_ctx.fd` -> fd; `p->sockfd` -> sockfd。 """
parts = re . split ( r " ->| \ . " , expr )
return parts [ - 1 ] . strip ( )
# ------------------------------------------------------------------ struct 定义
def _match_brace ( code : str , open_pos : int ) - > int :
""" 从 ` { ` 开始做括号配对,返回匹配的 `}` 下标;失败返回 -1。 """
depth = 0
i = open_pos
while i < len ( code ) :
if code [ i ] == " { " :
depth + = 1
elif code [ i ] == " } " :
depth - = 1
if depth == 0 :
return i
i + = 1
return - 1
def parse_members ( body : str ) - > list [ str ] :
""" 从 struct 体里取成员名(跳过函数指针、位域、嵌套块)。 """
names = [ ]
for chunk in body . split ( " ; " ) :
c = chunk . strip ( )
if not c or " ( " in c :
continue
c = c . split ( " : " ) [ 0 ] . strip ( )
m = re . search ( r " ([A-Za-z_] \ w*) \ s*(?: \ [[^ \ ]]* \ ])? \ s*$ " , c )
if m :
names . append ( m . group ( 1 ) )
return names
def collect_struct_defs ( code : str ) - > dict [ str , set [ str ] ] :
""" 收集 typedef / 具名 struct 的类型名 -> 成员集合。 """
types : dict [ str , set [ str ] ] = { }
for m in re . finditer ( r " \ b(struct|union) \ s*([A-Za-z_] \ w*)? \ s* \ { " , code ) :
open_pos = m . end ( ) - 1
close_pos = _match_brace ( code , open_pos )
if close_pos < 0 :
continue
body = code [ open_pos + 1 : close_pos ]
members = set ( parse_members ( body ) )
prefix = code [ max ( 0 , m . start ( ) - 16 ) : m . start ( ) ]
tail = code [ close_pos + 1 : close_pos + 200 ]
alias_m = re . match ( r " \ s*([A-Za-z_] \ w*) \ s*; " , tail )
tag = m . group ( 2 )
if " typedef " in prefix . split ( ) or prefix . rstrip ( ) . endswith ( " typedef " ) :
if alias_m :
types [ alias_m . group ( 1 ) ] = members
if tag :
types [ tag ] = members
if alias_m and ( " typedef " in prefix ) :
types [ alias_m . group ( 1 ) ] = members
return types
def fd_members ( members : set [ str ] ) - > set [ str ] :
""" 成员集合里的 fd 成员名。 """
return { x for x in members if is_fd_member ( x ) }
# ------------------------------------------------------------------ 文件作用域 static
def file_scope_statics ( code : str ) - > list [ str ] :
""" 返回文件作用域(大括号深度 0)的 static 声明语句文本。 """
stats = [ ]
depth = 0
line_start = 0
stmt_start = None
i = 0
n = len ( code )
while i < n :
c = code [ i ]
if depth == 0 and stmt_start is None and code . startswith ( " static " , i ) and (
i == 0 or not ( code [ i - 1 ] . isalnum ( ) or code [ i - 1 ] == " _ " ) ) :
prev_nl = code . rfind ( " \n " , 0 , i )
lead = code [ prev_nl + 1 : i ]
if lead . strip ( ) == " " : # 声明行行首(允许缩进)
stmt_start = i
if c == " { " :
depth + = 1
elif c == " } " :
depth - = 1
elif c == " ; " and depth == 0 and stmt_start is not None :
stats . append ( code [ stmt_start : i + 1 ] )
stmt_start = None
elif c == " \n " and depth == 0 and stmt_start is not None :
# 跨行声明继续;但函数定义 `static void f(...)` 的头行以 { 结束,
# 它会在 depth>0 处走到 ;(函数体内的分号),由 contains('(') 过滤。
pass
i + = 1
return stats
def split_decl ( decl : str ) - > tuple [ str , str | None , str | None ] :
""" 拆 `static Type name = init;` -> (declarator, init, inline_struct_body)。 """
s = decl . strip ( )
s = re . sub ( r " ^static \ b " , " " , s ) . strip ( )
s = s [ : - 1 ] . strip ( ) if s . endswith ( " ; " ) else s
init = None
body = None
# 找顶层 '='(结构体体内可能有 '=',但 inline struct 的情况先按首个 '{' 处理)
brace = s . find ( " { " )
is_inline_struct = brace > = 0 and re . search ( r " \ b(struct|union) \ b " , s [ : brace ] )
if is_inline_struct :
# inline struct: `struct { ... } name` / `struct {...} name = {...}`
close = _match_brace ( s , brace )
if close > 0 :
after = s [ close + 1 : ]
body = s [ brace + 1 : close ]
eq = after . find ( " = " )
if eq > = 0 :
init = after [ eq + 1 : ] . strip ( )
after = after [ : eq ]
return after . strip ( ) , init , body
eq = s . find ( " = " )
if eq > = 0 :
init = s [ eq + 1 : ] . strip ( )
s = s [ : eq ] . strip ( )
return s , init , body
def var_type_and_name ( declarator : str ) - > tuple [ str | None , str | None ] :
""" 从声明符里取 (类型名, 变量名);函数/函数指针/数组返回 (None, None) 或带标记。 """
if " ( " in declarator :
return None , None
ids = re . findall ( r " [A-Za-z_] \ w* " , declarator )
if not ids :
return None , None
name = ids [ - 1 ]
type_tokens = [ t for t in ids [ : - 1 ] if t not in TYPE_QUALIFIERS ]
# 指针星号不影响类型名;多维/数组由调用方用 '[' 判断
return ( type_tokens [ 0 ] if type_tokens else None ) , name
def check_static_stmt ( stmt : str , types : dict [ str , set [ str ] ] , rel : str , hits : list ) - > None :
""" R2:单条文件作用域 static 声明。 """
declarator , init , inline_body = split_decl ( stmt )
if " [ " in declarator . split ( " = " ) [ 0 ] :
return # 槽数组:清零即"全部空闲",逐槽身份由状态机守卫(§6 盲区)
type_name , name = var_type_and_name ( declarator )
if name is None :
return
members : set [ str ] | None = None
if inline_body is not None :
members = set ( parse_members ( inline_body ) )
elif type_name and type_name in types :
members = types [ type_name ]
fd_names = fd_members ( members ) if members else set ( )
if fd_names :
if init is None :
hits . append ( ( rel , " R2 " , " 文件作用域 static 结构体 ` %s ` 含 fd 成员 %s 但无初始化器; "
" 用指定初始化器 . %s = %s "
% ( name , sorted ( fd_names ) , sorted ( fd_names ) [ 0 ] , INVALID ) ) )
return
body = init . strip ( )
if re . fullmatch ( r " \ { \ s*0[uUlL]* \ s* \ } " , body ) :
hits . append ( ( rel , " R2 " , " ` %s ` 用 `= {0} ` 清零初始化,fd 成员落成 0(0 是合法 fd); "
" 改用指定初始化器 . %s = %s "
% ( name , sorted ( fd_names ) [ 0 ] , INVALID ) ) )
return
designated = dict ( re . findall ( r " \ . \ s*([A-Za-z_] \ w*) \ s*= \ s*([^,}]+) " , body ) )
if not designated :
hits . append ( ( rel , " R2 " , " ` %s ` 的初始化器不是指定初始化器,无法保证 fd 成员为 %s ; "
" 改用 . %s = %s " % ( name , INVALID , sorted ( fd_names ) [ 0 ] , INVALID ) ) )
return
for fd in sorted ( fd_names ) :
if fd not in designated :
hits . append ( ( rel , " R2 " , " ` %s ` 的指定初始化器缺 fd 成员 `. %s `(零初始化 = 0 = 合法 fd); "
" 补 . %s = %s " % ( name , fd , fd , INVALID ) ) )
elif designated [ fd ] . strip ( ) . strip ( " () " ) . strip ( ) != INVALID :
hits . append ( ( rel , " R2 " , " ` %s . %s ` 初始化为 ` %s `,不是契约常量 %s "
% ( name , fd , designated [ fd ] . strip ( ) , INVALID ) ) )
return
# 标量 fd( `static int fd;`):只认 fd/sock 档。`static uintptr_t s_next_handle`
# 是一句柄**发号器**(单调递增、0 保留),不是"持有中的 fd",见 fd_name_kind 说明。
if fd_name_kind ( name ) == " fd " :
if init is None :
hits . append ( ( rel , " R2 " , " 文件作用域 static fd 标量 ` %s ` 无初始化器(会落成 0 = 合法 fd); "
" 改为 `static int %s = %s ;` " % ( name , name , INVALID ) ) )
elif init . strip ( ) . strip ( " () " ) . strip ( ) != INVALID :
hits . append ( ( rel , " R2 " , " 文件作用域 static fd 标量 ` %s ` 初始化为 ` %s `,不是契约常量 %s "
% ( name , init . strip ( ) , INVALID ) ) )
# ------------------------------------------------------------------ 变量类型表
def collect_var_types ( code : str ) - > dict [ str , str ] :
""" 粗粒度变量类型表(供 R3 用):名字 -> 类型名。后出现者覆盖先出现者。 """
vtypes : dict [ str , str ] = { }
decl_re = re . compile (
r " (?<![ \ w.])([A-Za-z_] \ w*) \ s*( \ * { 0,2}) \ s*([A-Za-z_] \ w*) \ s*(?=[;=, \ [)]) " )
for m in decl_re . finditer ( code ) :
t , stars , name = m . group ( 1 ) , m . group ( 2 ) , m . group ( 3 )
if t in TYPE_QUALIFIERS or name in TYPE_QUALIFIERS :
continue
vtypes [ name ] = t
return vtypes
# 句柄发号器族的具名失效/边界常量:出现它们就说明本文件自有一套句柄语义
# (实测:IEC 104 后端 `handle` 是 uintptr_t 会话令牌,失效值 IEC104_NET_INVALID_SOCKET
# = UINTPTR_MAX,发号器 `s_next_handle` 从 1 起、0 永不合法)。这类名字走"弱规则":
# - 与**具名常量**比较(任一方向)→ 永远不判;
# - 与 0 比较(`== 0U` / `!= 0U`)→ 不判(0 是该族自己的"没有句柄");
# - 与负数字面量比较(`== -1` / `< 0` / `>= 0`)→ 判(用数值形态表达失效,正是本契约拦的);
# - 真值判断 `if (handle)` / `if (!handle)` → 仍由 R4 判(弱规则不是"不检查")。
HANDLE_FAMILY_CONSTANTS = (
" IEC104_NET_INVALID_SOCKET " , " IEC104_NET_INVALID_HANDLE " ,
" UINTPTR_MAX " , " INTPTR_MAX " , " SIZE_MAX " ,
)
def handle_family_kind ( code : str ) - > str | None :
""" 本文件是否声明/使用了某句柄族的具名失效常量;返回该常量名(用于修复建议)。 """
for name in HANDLE_FAMILY_CONSTANTS :
if re . search ( r " \ b " + re . escape ( name ) + r " \ b " , code ) :
return name
return None
def should_flag ( kind : str , literal : str , op : str ) - > bool :
""" 该名字档位 + 该操作数是否算违规(见 fd_name_kind 的理由)。
handle 档(句柄发号器,0 永不合法)只抓 " 用负数域表达失效 " : `== -1` / `< 0` / `>= 0`。
`== 0U` 是 " 没有句柄值 " 的检查,不属于本契约的 fd 失效值类;与具名常量比较则根本不会
走到这里(正则只匹配整数字面量)。
"""
if kind == " fd " :
return True
lit = literal . strip ( )
if lit . startswith ( " - " ) :
return True
return lit . rstrip ( " uUlL " ) == " 0 " and op . strip ( ) in ( " < " , " >= " )
def named_hint ( expr : str , code : str = " " ) - > str :
""" 按名字档位给修复建议,避免把 104 句柄引向 NET_FD_INVALID。
句柄族(0 永不合法)如果本文件里已有具名失效常量,就直接点名它——让报错能照抄。
"""
if fd_name_kind ( last_name ( expr ) ) == " handle " :
fam = handle_family_kind ( code )
if fam :
return " 该句柄族的具名失效常量 ` %s `(句柄发号器的 0 永不合法,与 fd 的 0 合法域不同源) " % fam
return ( " 该句柄族的具名失效常量(网络 fd 用 NET_FD_INVALID; "
" 104 会话句柄用 IEC104_NET_INVALID_SOCKET) " )
return " ` %s == %s ` / ` %s != %s ` " % ( expr , INVALID , expr , INVALID )
# ------------------------------------------------------------------ 各规则扫描
def scan_text ( rel : str , raw : str , types : dict [ str , set [ str ] ] | None = None ,
verbose : bool = False ) - > list [ tuple [ str , str , str ] ] :
""" 扫一份 C 源文本,返回 [(rel, 规则, 说明)]。rel 用 posix 相对路径。 """
code = strip_nocode ( raw )
own_types = collect_struct_defs ( code )
all_types : dict [ str , set [ str ] ] = dict ( types or { } )
all_types . update ( own_types )
hits : list [ tuple [ str , str , str ] ] = [ ]
def whitelisted ( rule : str ) - > bool :
return any ( rel . startswith ( p ) for p in WHITELIST [ rule ] )
# R1:fd 形标识符 vs 整数字面量
if not whitelisted ( " R1 " ) :
for m in CMP_EXPR_FIRST . finditer ( code ) :
expr , op , lit = m . group ( 1 ) , m . group ( 2 ) , m . group ( 3 )
name = last_name ( expr )
kind = fd_name_kind ( name )
if kind and not expr_has_call ( code , m . start ( 1 ) ) and should_flag ( kind , lit , op ) :
hits . append ( ( rel , " R1 " , " 第 %d 行:` %s %s %s `——fd 形标识符与整数字面量比较; "
" 改用 %s (数值形态判据会随 fd 域/失效值变化失真) "
% ( line_of ( code , m . start ( ) ) , expr . strip ( ) , op , lit ,
named_hint ( expr . strip ( ) , code ) ) ) )
for m in CMP_LITERAL_FIRST . finditer ( code ) :
lit , op , expr = m . group ( 1 ) , m . group ( 2 ) , m . group ( 3 )
name = last_name ( expr )
kind = fd_name_kind ( name )
if kind and should_flag ( kind , lit , op ) :
hits . append ( ( rel , " R1 " , " 第 %d 行:` %s %s %s `——fd 形标识符与整数字面量比较; "
" 改用 %s (数值形态判据会随 fd 域/失效值变化失真) "
% ( line_of ( code , m . start ( ) ) , lit , op , expr . strip ( ) ,
named_hint ( expr . strip ( ) , code ) ) ) )
# R2:文件作用域 static
if not whitelisted ( " R2 " ) :
for stmt in file_scope_statics ( code ) :
check_static_stmt ( stmt , all_types , rel , hits )
# R3: memset 后 5 行内无 NET_FD_INVALID 回填
if not whitelisted ( " R3 " ) :
vtypes = collect_var_types ( code )
for m in re . finditer ( r " \ bmemset \ s* \ ( \ s*([^,]+?) \ s*, \ s*(?:0[uUlL]*| ' \\ 0 ' ) \ s*, " , code ) :
arg = m . group ( 1 ) . strip ( )
base , elem_expr , indexed = memset_target ( arg )
if base is None :
continue
if not indexed and is_array_decl ( code , base ) :
if verbose :
print ( " [net-handle] 跳过数组清零 %s : %d (槽表清零 = 全部空闲) "
% ( rel , line_of ( code , m . start ( ) ) ) )
continue
type_name = vtypes . get ( base )
if not type_name or type_name not in all_types :
continue
fds = fd_members ( all_types [ type_name ] )
if not fds :
continue
start_line = line_of ( code , m . end ( ) )
window = code . splitlines ( ) [ start_line - 1 : start_line + 4 ] # 后续 ≤5 行
text_win = " \n " . join ( window )
missing = [ fd for fd in sorted ( fds )
if not re . search ( re . escape ( elem_expr ) + r " \ s*(?: \ .|->) \ s* " + re . escape ( fd )
+ r " \ s*= \ s* " + re . escape ( INVALID ) + r " \ b " , text_win ) ]
if missing :
hits . append ( ( rel , " R3 " , " 第 %d 行:memset 清零 ` %s `(类型 %s )后 5 行内没有回填 "
" ` %s . %s = %s `;清零后的 0 是合法 fd "
% ( line_of ( code , m . start ( ) ) , elem_expr , type_name ,
elem_expr , missing [ 0 ] , INVALID ) ) )
# R4: if (fd) / if (!fd)
if not whitelisted ( " R4 " ) :
for m in IF_TRUTHY . finditer ( code ) :
neg , expr = m . group ( 1 ) , m . group ( 2 )
if is_fd_name ( last_name ( expr ) ) :
hits . append ( ( rel , " R4 " , " 第 %d 行:`if ( %s %s )`——把 fd 当布尔值判; "
" 改用 ` %s %s %s ` "
% ( line_of ( code , m . start ( ) ) ,
" ! " if neg . strip ( ) else " " , expr . strip ( ) ,
expr . strip ( ) , " != " if neg . strip ( ) else " == " , INVALID ) ) )
return hits
def expr_has_call ( code : str , start : int ) - > bool :
""" 表达式前若紧跟标识符且再往前是调用形态,说明是函数返回值(不判)。 """
j = start - 1
while j > = 0 and code [ j ] in " \t " :
j - = 1
return j > = 0 and code [ j ] in " )] "
def is_array_decl ( code : str , name : str ) - > bool :
""" name 是否是数组对象(声明处带 `[`)。 """
return bool ( re . search ( r " \ b[A-Za-z_] \ w* \ s+ " + re . escape ( name ) + r " \ s* \ [ " , code ) )
def memset_target ( arg : str ) - > tuple [ str | None , str , bool ] :
""" 解析 memset 第一参数:返回 (基名, 展示表达式, 是否元素/成员表达式)。 """
expr = arg . strip ( )
if expr . startswith ( " & " ) :
expr = expr [ 1 : ] . strip ( )
# 去掉强转 `(void *)`
expr = re . sub ( r " ^ \ ([^)]* \ ) \ s* " , " " , expr ) . strip ( )
m = re . fullmatch ( r " ([A-Za-z_] \ w*) \ s*( \ [[^ \ ]]* \ ])? " , expr )
if not m :
return None , expr , False
base = m . group ( 1 )
index = m . group ( 2 )
if index is None :
return base , base , False # 裸名字:是数组还是单对象,由调用方查声明
return base , expr , True # 数组元素:单个对象
# ------------------------------------------------------------------ R5
def check_contract ( root : str ) - > list [ tuple [ str , str , str ] ] :
""" R5:契约文件存在、定义常量、被 net_socket.h include。 """
hits = [ ]
fd_path = os . path . join ( root , NET_FD_H )
sock_path = os . path . join ( root , NET_SOCKET_H )
if not os . path . isfile ( fd_path ) :
hits . append ( ( NET_FD_H , " R5 " , " 契约头文件不存在;先按 ci-artifacts/net-fd-contract-brief.md §1 建它 " ) )
return hits
with open ( fd_path , " r " , encoding = " utf-8 " , errors = " replace " ) as f :
fd_text = strip_nocode ( f . read ( ) )
if not re . search ( r " ^ \ s*# \ s*define \ s+ " + INVALID + r " \ b " , fd_text , re . M ) :
hits . append ( ( NET_FD_H , " R5 " , " 没有 `#define %s `;失效值契约的唯一定义处必须在这里 " % INVALID ) )
if not os . path . isfile ( sock_path ) :
hits . append ( ( NET_SOCKET_H , " R5 " , " net_socket.h 不存在 " ) )
return hits
with open ( sock_path , " r " , encoding = " utf-8 " , errors = " replace " ) as f :
sock_raw = f . read ( )
# include 行必须对**原文**判:strip_nocode 会把 "net_fd.h" 这个字面量一起抹掉。
# 只认行首 `#include`,注释里的同形文本不会被行首锚点吃掉。
if not re . search ( r ' ^ \ s*# \ s*include \ s*[< " ]net_fd \ .h[> " ] ' , sock_raw , re . M ) :
hits . append ( ( NET_SOCKET_H , " R5 " , " 没有 `#include \" net_fd.h \" `;消费者拿不到契约常量 " ) )
return hits
# ------------------------------------------------------------------ 全仓扫描
def iter_sources ( root : str ) - > list [ str ] :
""" 全仓 .c/.h 相对路径(posix),按 SKIP_PREFIXES 排除。 """
out = [ ]
for dirpath , dirnames , filenames in os . walk ( root ) :
rel_dir = os . path . relpath ( dirpath , root ) . replace ( os . sep , " / " )
if rel_dir == " . " :
rel_dir = " "
else :
rel_dir + = " / "
dirnames [ : ] = sorted ( d for d in dirnames
if not any ( ( rel_dir + d + " / " ) . startswith ( p ) for p in SKIP_PREFIXES )
and d not in ( " .git " , " .venv " , " build " , " __pycache__ " ) )
for fn in sorted ( filenames ) :
if fn . endswith ( ( " .c " , " .h " ) ) :
rel = rel_dir + fn
if any ( rel . startswith ( p ) for p in SKIP_PREFIXES ) :
continue
out . append ( rel )
return out
def scan_tree ( root : str , verbose : bool = False ) - > tuple [ list , int ] :
files = iter_sources ( root )
types : dict [ str , set [ str ] ] = { }
texts = { }
for rel in files :
with open ( os . path . join ( root , rel ) , " r " , encoding = " utf-8 " , errors = " replace " ) as f :
texts [ rel ] = f . read ( )
types . update ( collect_struct_defs ( strip_nocode ( texts [ rel ] ) ) )
hits = [ ]
for rel in files :
hits . extend ( scan_text ( rel , texts [ rel ] , types , verbose = verbose ) )
hits . extend ( check_contract ( root ) )
return hits , len ( files )
# ------------------------------------------------------------------ selftest
def selftest ( ) - > int :
""" 内置正例/反例逐条断言:故意写错必须抓到,正确写法不误报。 """
checks = [ ] # (说明, 实际, 期望)
def expect ( desc , hits , rule , want ) :
got = sum ( 1 for h in hits if h [ 1 ] == rule )
checks . append ( ( desc , got , want ) )
# ---- R1
bad = " void f(void) \n { \n if (ctx.fd >= 0) { close_it(); } \n } \n "
expect ( " R1 抓 `ctx.fd >= 0` " , scan_text ( " App/x.c " , bad ) , " R1 " , 1 )
bad2 = " void f(void) \n { \n if (sockfd == -1) { return; } \n } \n "
expect ( " R1 抓 `sockfd == -1` " , scan_text ( " App/x.c " , bad2 ) , " R1 " , 1 )
bad3 = " void f(void) \n { \n if (-1 == fd) { return; } \n } \n "
expect ( " R1 抓反向字面量 `-1 == fd` " , scan_text ( " App/x.c " , bad3 ) , " R1 " , 1 )
good1 = " void f(void) \n { \n if (ctx.fd != NET_FD_INVALID) { use_it(); } \n } \n "
expect ( " R1 不误报 `!= NET_FD_INVALID` " , scan_text ( " App/x.c " , good1 ) , " R1 " , 0 )
good2 = " void f(void) \n { \n /* 反面教材:if (fd >= 0) 是错的 */ \n int x = 0; \n (void)x; \n } \n "
expect ( " R1 不误报注释里的反面教材 " , scan_text ( " App/x.c " , good2 ) , " R1 " , 0 )
good3 = " void f(void) \n { \n if (fd() >= 0) { return; } \n } \n "
expect ( " R1 不误报函数调用 `fd() >= 0` " , scan_text ( " App/x.c " , good3 ) , " R1 " , 0 )
bad4 = " void f(void) \n { \n if (handle < 0) { return; } \n } \n "
expect ( " R1 抓句柄用负数字面量表达失效 `handle < 0` " ,
scan_text ( " App/x.c " , bad4 ) , " R1 " , 1 )
good4 = " void f(void) \n { \n if (handle == 0U) { return; } \n } \n "
expect ( " R1 不误报句柄的 0 值检查 `handle == 0U`(0 是该族自己的空闲值) " ,
scan_text ( " App/x.c " , good4 ) , " R1 " , 0 )
good4b = " void f(void) \n { \n if (socket_handle == 0U) { return; } \n } \n "
expect ( " R1 不误报 `socket_handle == 0U`(名字含 handle 即句柄族,不按 socket 判 fd) " ,
scan_text ( " App/x.c " , good4b ) , " R1 " , 0 )
bad4b = " void f(void) \n { \n if (sockfd == 0) { return; } \n } \n "
expect ( " R1 抓真 fd 的数值形态 `sockfd == 0`( 0 在本仓是合法 fd) " ,
scan_text ( " App/x.c " , bad4b ) , " R1 " , 1 )
# ---- 句柄发号器族(104 后端):0 永不合法,与 fd 槽位的"0 合法"不同源。
# 弱规则 = 与具名失效常量/0 的比较不判,但真值判断与负数形态仍判(不是整目录白名单)。
g_sig = ( " IEC104_NetResult_t IEC104_Net_Close(IEC104_NetSocket_t socket_handle, int *native_error) \n "
" { \n if (socket_handle == IEC104_NET_INVALID_SOCKET || socket_handle == 0U) { \n "
" return ok; \n } \n return ok; \n } \n " )
expect ( " R1 不误报句柄族与具名失效常量/0 的比较(IEC104_Net_Close 实测反例) " ,
scan_text ( " App/protocol/iec104/iec104_net_mcu.c " , g_sig ) , " R1 " , 0 )
bad_h = " void f(void) \n { \n if (slot_handle == -1) { return; } \n } \n "
expect ( " R1 仍抓句柄族的负数形态 `slot_handle == -1`(弱规则不是不查) " ,
scan_text ( " App/x.c " , bad_h ) , " R1 " , 1 )
bad_h2 = " void f(void) \n { \n if (socket_handle) { return; } \n } \n "
expect ( " R4 仍抓句柄族真值判断 `if (socket_handle)` " ,
scan_text ( " App/x.c " , bad_h2 ) , " R4 " , 1 )
bad_h3 = " void f(void) \n { \n if (!slot_handle) { return; } \n } \n "
expect ( " R4 仍抓句柄族 `if (!slot_handle)` " ,
scan_text ( " App/x.c " , bad_h3 ) , " R4 " , 1 )
good5 = " void f(void) \n { \n int32_t sock_ok = (n == 4); \n if (sock_ok) { use_it(); } \n } \n "
expect ( " R1/R4 不误报 socket 状态布尔 `sock_ok` " ,
scan_text ( " App/x.c " , good5 ) , " R4 " , 0 )
# 宏 / 宏调用 / 函数实参:test/host 的 fd_set 风格(NET_FD_ZERO / NET_FD_SET /
# NET_FD_ISSET)把 fd 或字面量当**实参**传,不是"与字面量比较",一律不判。
good6 = ( " #define NET_FD_ZERO(set) memset((set), 0, sizeof(net_fd_set_t)) \n "
" #define NET_FD_SET(set, fd) do { (void)(fd); } while (0) \n "
" void f(void) \n { \n NET_FD_SET(&set, 0); \n } \n " )
expect ( " R1/R3 不误报 fd_set 宏定义与宏实参字面量 " , scan_text ( " App/x.c " , good6 ) , " R1 " , 0 )
expect ( " R3 不误报宏定义里的 memset " , scan_text ( " App/x.c " , good6 ) , " R3 " , 0 )
good7 = " void f(void) \n { \n if (NET_FD_ISSET(fd, &set)) { use_it(); } \n } \n "
expect ( " R4 不误报宏调用 `if (NET_FD_ISSET(fd, &set))` " , scan_text ( " App/x.c " , good7 ) , " R4 " , 0 )
good8 = " void f(void) \n { \n if (NET_MAX_SOCKETS > 0) { return; } \n } \n "
expect ( " R1 不误报全大写常量 `NET_MAX_SOCKETS > 0` " , scan_text ( " App/x.c " , good8 ) , " R1 " , 0 )
good9 = " void f(void) \n { \n if (fd >= 0) { return; } \n } \n "
expect ( " R1 抓函数体内的真判据(对照组,证明上面的放行不是整体失灵) " ,
scan_text ( " App/x.c " , good9 ) , " R1 " , 1 )
wl = " void f(void) \n { \n if (p->fd >= 0) { return; } \n } \n "
expect ( " R1 白名单 Drivers/BSP/NET/ 不报 " , scan_text ( " Drivers/BSP/NET/net_socket.c " , wl ) , " R1 " , 0 )
# ---- R2
t = " typedef struct { \n uint8_t state; \n int fd; \n } ctx_t; \n "
expect ( " R2 抓无初始化器 fd 标量 " , scan_text ( " App/x.c " , " static int fd; \n " ) , " R2 " , 1 )
expect ( " R2 抓 `= {0} ` " , scan_text ( " App/x.c " , t + " static ctx_t s_ctx = {0} ; \n " ) , " R2 " , 1 )
expect ( " R2 抓指定初始化器缺 fd 成员 " ,
scan_text ( " App/x.c " , t + " static ctx_t s_ctx = { .state = 0 }; \n " ) , " R2 " , 1 )
expect ( " R2 抓 `.fd = -1`(不是契约常量) " ,
scan_text ( " App/x.c " , t + " static ctx_t s_ctx = { .fd = -1 }; \n " ) , " R2 " , 1 )
expect ( " R2 抓匿名 struct 无初始化器 " ,
scan_text ( " App/x.c " , " static struct { \n int fd; \n } s_ctx; \n " ) , " R2 " , 1 )
expect ( " R2 不误报正确指定初始化器 " ,
scan_text ( " App/x.c " , t + " static ctx_t s_ctx = { \n .fd = NET_FD_INVALID, \n }; \n " ) , " R2 " , 0 )
expect ( " R2 不误报无 fd 成员的 static " ,
scan_text ( " App/x.c " , " static uint32_t s_rng; \n " ) , " R2 " , 0 )
expect ( " R2 不误报函数声明 " ,
scan_text ( " App/x.c " , " static void f(int fd); \n " ) , " R2 " , 0 )
expect ( " R2 不误报句柄发号器 `static uintptr_t s_next_handle = 1U;` " ,
scan_text ( " App/x.c " , " static uintptr_t s_next_handle = 1U; \n " ) , " R2 " , 0 )
# ---- R3
r3_bad = ( t + " void f(void) \n { \n static ctx_t s_ctx; \n "
" memset(&s_ctx, 0, sizeof(s_ctx)); \n s_ctx.state = 1; \n } \n " )
expect ( " R3 抓 memset 后不回填 " , scan_text ( " App/x.c " , r3_bad ) , " R3 " , 1 )
r3_good = ( t + " void f(void) \n { \n static ctx_t s_ctx; \n "
" memset(&s_ctx, 0, sizeof(s_ctx)); \n "
" s_ctx.fd = NET_FD_INVALID; \n s_ctx.state = 1; \n } \n " )
expect ( " R3 不误报 memset 后回填 " , scan_text ( " App/x.c " , r3_good ) , " R3 " , 0 )
r3_other = ( " typedef struct { \n uint32_t a; \n } plain_t; \n "
" void f(void) \n { \n static plain_t s; \n memset(&s, 0, sizeof(s)); \n } \n " )
expect ( " R3 不误报无 fd 成员结构体 " , scan_text ( " App/x.c " , r3_other ) , " R3 " , 0 )
r3_arr = ( t + " static ctx_t s_tab[4]; \n void f(void) \n { \n "
" memset(s_tab, 0, sizeof(s_tab)); \n } \n " )
expect ( " R3 跳过整数组清零(槽表语义) " , scan_text ( " App/x.c " , r3_arr ) , " R3 " , 0 )
# ---- R4
expect ( " R4 抓 `if (fd)` " , scan_text ( " App/x.c " , " void f(void) \n { \n if (fd) { use_it(); } \n } \n " ) , " R4 " , 1 )
expect ( " R4 抓 `if (!ctx.fd)` " ,
scan_text ( " App/x.c " , " void f(void) \n { \n if (!ctx.fd) { open_it(); } \n } \n " ) , " R4 " , 1 )
expect ( " R4 不误报 `if (ctx.fd != NET_FD_INVALID)` " ,
scan_text ( " App/x.c " , " void f(void) \n { \n if (ctx.fd != NET_FD_INVALID) { return; } \n } \n " ) , " R4 " , 0 )
expect ( " R4 不误报其它布尔 " ,
scan_text ( " App/x.c " , " void f(void) \n { \n if (s_ready) { return; } \n } \n " ) , " R4 " , 0 )
ok = True
print ( " === net-handle selftest === " )
for desc , got , want in checks :
passed = got == want
ok = ok and passed
print ( " [ %s ] %s (命中 %d ,期望 %d ) " % ( " PASS " if passed else " FAIL " , desc , got , want ) )
# ---- R5:契约文件的三态(用临时目录,不污染工作区)
r5_checks = [ ]
import tempfile
with tempfile . TemporaryDirectory ( ) as tmp :
def write ( rel , body ) :
path = os . path . join ( tmp , rel )
os . makedirs ( os . path . dirname ( path ) , exist_ok = True )
with open ( path , " w " , encoding = " utf-8 " , newline = " \n " ) as f :
f . write ( body )
r5_checks . append ( ( " R5 缺契约文件必报 " , len ( check_contract ( tmp ) ) , 1 ) )
write ( NET_FD_H , " #ifndef NET_FD_H \n #define NET_FD_H \n #define NET_FD_INVALID (-1) \n #endif \n " )
r5_checks . append ( ( " R5 有定义但 net_socket.h 缺失必报 " , len ( check_contract ( tmp ) ) , 1 ) )
write ( NET_SOCKET_H , ' #include " net_fd.h " \n ' )
r5_checks . append ( ( " R5 齐备时 0 违规 " , len ( check_contract ( tmp ) ) , 0 ) )
write ( NET_SOCKET_H , ' #include " net_types.h " \n ' )
r5_checks . append ( ( " R5 net_socket.h 未 include 契约必报 " , len ( check_contract ( tmp ) ) , 1 ) )
for desc , got , want in r5_checks :
passed = got == want
ok = ok and passed
print ( " [ %s ] %s (命中 %d ,期望 %d ) " % ( " PASS " if passed else " FAIL " , desc , got , want ) )
total = len ( checks ) + len ( r5_checks )
print ( " SELFTEST: %s ( %d 条断言) " % ( " PASS " if ok else " FAIL " , total ) )
return 0 if ok else 1
# ------------------------------------------------------------------ main
def main ( ) - > int :
if hasattr ( sys . stdout , " reconfigure " ) :
sys . stdout . reconfigure ( encoding = " utf-8 " , errors = " replace " )
ap = argparse . ArgumentParser ( description = " 网络句柄失效值契约门禁(R1~R5) " )
ap . add_argument ( " --selftest " , action = " store_true " , help = " 自证:正例必抓、正确写法不误报 " )
ap . add_argument ( " --verbose " , action = " store_true " , help = " 打印跳过路径与判定细节 " )
ap . add_argument ( " --root " , default = REPO , help = " 仓库根(默认脚本所在仓库) " )
args = ap . parse_args ( )
if args . selftest :
return selftest ( )
root = os . path . abspath ( args . root )
hits , nfiles = scan_tree ( root , verbose = args . verbose )
print ( " [net-handle] 扫描 %d 个 C/H 文件(跳过第三方/生成物/归档) " % nfiles )
if hits :
counts : dict [ str , int ] = { }
for rel , rule , msg in hits :
counts [ rule ] = counts . get ( rule , 0 ) + 1
print ( " FAIL [ %s ] %s : %s " % ( rule , rel , msg ) )
print ( " [net-handle] 违规 %d 条: %s " % (
len ( hits ) , " " . join ( " %s = %d " % ( k , counts [ k ] ) for k in sorted ( counts ) ) ) )
print ( " [net-handle] 契约与正反例 → docs/门禁说明/net-handle.md; "
" 豁免只允许写进本脚本的 WHITELIST 并在文档 §7 说明理由 " )
return 1
print ( " [net-handle] PASS: R1~R5 全绿,0 违规 " )
return 0
if __name__ == " __main__ " :
sys . exit ( main ( ) )