VulnLLM-R-Interprocedural-Ceiling / phase0_differential.py
berteuraika's picture
Add: The Interprocedural Ceiling — replication & boundary analysis responding to VulnLLM-R (arXiv:2512.07533)
2a0b0fb verified
Raw
History Blame Contribute Delete
5.71 kB
#!/usr/bin/env python3
"""Phase 0, measurement B — DIFFERENTIAL RATE.
For N PrimeVul pairs, run cppcheck on BOTH the vulnerable and patched function and
measure how often the extracted findings DIFFER. If evidence(vuln)==evidence(patch),
the intra-procedural tool gives ZERO discriminative signal for that pair.
This is the true usable-signal ceiling for a static-evidence LoRA (<= decidability D)."""
import json, os, re, subprocess, tempfile, hashlib
from huggingface_hub import hf_hub_download
import pyarrow.parquet as pq
N_PAIRS = 100
CK = os.path.expanduser("~/.cache/phase0_diff_ckpt.jsonl")
# stub common typedefs so cppcheck doesn't misinfer types on header-less functions
PREAMBLE = ("typedef unsigned long size_t; typedef unsigned char uint8_t; "
"typedef unsigned short uint16_t; typedef unsigned int uint32_t; "
"typedef unsigned long long uint64_t; typedef long ssize_t; "
"typedef int int32_t; typedef long long int64_t;\n")
def is_java(code):
return bool(re.search(r'\b(public|private|protected)\s+\w+|System\.|import java|@Override', code or ''))
def cppcheck_findings(code):
"""Return a normalized set of (rule_id) findings from cppcheck on the isolated function."""
with tempfile.NamedTemporaryFile("w", suffix=".c", delete=False) as f:
f.write(PREAMBLE + code)
path = f.name
try:
# --enable=all, template gives us id per finding; suppress noise about missing includes
r = subprocess.run(
["cppcheck", "--enable=all", "--inconclusive", "--suppress=missingIncludeSystem",
"--suppress=unusedFunction", "--suppress=missingInclude",
"--template={id}:{line}:{severity}", "--quiet", path],
capture_output=True, text=True, timeout=60)
out = (r.stderr or "") + (r.stdout or "")
except Exception:
out = ""
finally:
os.unlink(path)
ids = set()
detailed = []
for line in out.splitlines():
m = re.match(r'([a-zA-Z0-9_]+):(\d+):(\w+)', line.strip())
if m:
rid, ln, sev = m.group(1), m.group(2), m.group(3)
# drop pure style/information noise; keep security-relevant severities
if sev in ("error", "warning", "portability") or rid in (
"arrayIndexOutOfBounds","bufferAccessOutOfBounds","nullPointer","uninitvar",
"memleak","doubleFree","useAfterFree","integerOverflow","signConversion",
"invalidScanfFormatWidth","formatString","negativeIndex","pointerOutOfBounds"):
ids.add(rid)
detailed.append(f"{rid}/{sev}")
return ids, detailed
def main():
p = hf_hub_download("ASSERT-KTH/PrimeVul","data/test_paired-00000-of-00001.parquet",repo_type="dataset")
t = pq.read_table(p); func = t.column("func").to_pylist(); lab = t.column("is_vulnerable").to_pylist()
# pairs are consecutive (2k, 2k+1); identify which is vuln
done = {}
if os.path.exists(CK):
for l in open(CK):
try: r=json.loads(l); done[r["k"]]=r
except: pass
ck = open(CK, "a")
n_c = n_java = 0
for k in range(N_PAIRS):
if k in done: continue
i0, i1 = 2*k, 2*k+1
# vuln vs patched
vi = i0 if lab[i0] else i1
pi = i1 if vi==i0 else i0
vcode, pcode = func[vi], func[pi]
lang = "java" if (is_java(vcode) or is_java(pcode)) else "c"
if lang == "java":
# no semgrep yet -> record as skipped for cppcheck differential (java handled separately)
rec = {"k":k, "lang":"java", "skipped":True}
ck.write(json.dumps(rec)+"\n"); ck.flush(); continue
vids, vdet = cppcheck_findings(vcode)
pids, pdet = cppcheck_findings(pcode)
# differential: does the tool distinguish the twins at all?
differ = (vids != pids)
# stronger: did the tool flag the VULN and NOT the patched (correct direction)?
directional = bool(vids - pids) # findings present in vuln but gone in patch
both_flagged = bool(vids and pids and vids==pids)
neither = (not vids and not pids)
rec = {"k":k, "lang":"c", "vuln_ids":sorted(vids), "patch_ids":sorted(pids),
"differ":differ, "directional":directional,
"both_same_flag":both_flagged, "neither_flagged":neither}
ck.write(json.dumps(rec)+"\n"); ck.flush()
ck.close()
# aggregate
recs=[json.loads(l) for l in open(CK)]
recs={r["k"]:r for r in recs}; recs=[recs[k] for k in sorted(recs)][:N_PAIRS]
cc=[r for r in recs if r.get("lang")=="c" and not r.get("skipped")]
java=[r for r in recs if r.get("lang")=="java"]
differ=sum(1 for r in cc if r["differ"])
directional=sum(1 for r in cc if r["directional"])
neither=sum(1 for r in cc if r["neither_flagged"])
both=sum(1 for r in cc if r["both_same_flag"])
nc=len(cc) or 1
print(f"\n===== PHASE 0 (B): cppcheck DIFFERENTIAL RATE on {len(cc)} C pairs ({len(java)} Java skipped) =====")
print(f"tool findings DIFFER between twins : {differ}/{nc} = {differ/nc*100:.1f}% <- upper bound on usable static signal")
print(f" of which DIRECTIONAL (vuln flagged, patch clean): {directional}/{nc} = {directional/nc*100:.1f}%")
print(f"same finding on BOTH twins (zero signal) : {both}/{nc} = {both/nc*100:.1f}%")
print(f"NEITHER twin flagged (tool blind) : {neither}/{nc} = {neither/nc*100:.1f}%")
print(f"\nInterpretation: 'directional' is the fraction where cppcheck ALONE hands the LoRA a")
print(f"clean discriminative feature. That is the realistic intra-procedural signal floor.")
if __name__=="__main__": main()