mvd001/cyberset / scripts /code /ingest_megavul.py
mvd001's picture
download
raw
8.6 kB
#!/usr/bin/env python3
"""MegaVul 2024-04 (Ni et al., MSR'24; GPL-3.0; OneDrive share https://1drv.ms/f/s!AtzrzuojQf5sgeISZ9zN_4owVnUn9g) -> staged rows.
Input (streamed with ijson, never loaded whole):
raw/megavul/2024-04/{c_cpp,java}/megavul_simple.json one flat object per function (code, diff, labels, CVE/CWE, commit, git_url)
raw/megavul/2024-04/{c_cpp,java}/cve_with_graph_abstract_commit.json hierarchical CVE -> commits -> files: only commit_date, parent commit,
CVE publish date and CVSS score are taken from it (joined on commit_hash / cve_id)
(megavul.json = megavul_simple.json + parameter/return-type fields; not needed. The c_cpp megavul.json of this download is truncated.)
Mapping onto `code_sample` (normalisation, sample_id hashing, MinHash, size/minified filters = codecommon.StageWriter, i.e. identical to the main tier):
is_vul=true : func_before -> is_vulnerable=true, pair_role=vuln (vuln_lines = '-' lines of diff_func, numbered within func_before)
func -> is_vulnerable=false, pair_role=fix (same pair_id)
is_vul=false: func -> is_vulnerable=false, pair_role=unrelated_in_commit (unchanged function of a file touched by the fix commit)
label_source = nvd_patch_commit (MegaVul mines CVE fix commits from NVD references, same as CVEfixes/Big-Vul), confidence from
codecommon.confidence (vuln 0.65 / fix 0.60 / unrelated 0.50, -0.30 for test/vendor/minified paths); the +0.05 one-function-commit bonus
is applied in build_megavul_gpl.py exactly as build_code_tier.py does for CVEfixes/MoreFixes.
Rows are staged under work/megavul/stage/megavul (NOT work/stage/) so a rebuild of the permissively-licensed public tier never mixes in GPL rows."""
import sys, os, json, re, datetime, itertools
sys.path.insert(0, os.path.dirname(__file__)); import codecommon as C
import ijson
C.STAGE = f"{C.ROOT}/work/megavul/stage"
RAW = f"{C.ROOT}/raw/megavul/2024-04"; LIC = "GPL-3.0"; DS = "megavul_2024_04"
KEEP = ("cve_id", "cwe_ids", "cvss_vector", "cvss_is_v3", "repo_name", "commit_hash", "git_url", "file_path", "func_name", "func_before", "func",
"diff_func", "is_vul", "func_graph_path_before", "func_graph_path")
META = {} # lang -> (cve_id -> {publish_date, cvss_base_score}, commit_hash -> {commit_date, parent_commit_hash}, counts)
def load_meta(lang):
cves, commits, n = {}, {}, {"cves": 0, "commits": 0, "vul_funcs": 0, "non_vul_funcs": 0}
with open(f"{RAW}/{lang}/cve_with_graph_abstract_commit.json", "rb") as f:
for c in ijson.items(f, "item", use_float=True):
n["cves"] += 1; cves[c["cve_id"]] = {"publish_date": c.get("publish_date"), "cvss_base_score": c.get("cvss_base_score")}
for cm in c.get("commits") or []:
n["commits"] += 1; commits[cm["commit_hash"]] = {"commit_date": cm.get("commit_date"), "parent_commit_hash": cm.get("parent_commit_hash")}
for fl in cm.get("files") or []:
n["vul_funcs"] += len(fl.get("vulnerable_functions") or []); n["non_vul_funcs"] += len(fl.get("non_vulnerable_functions") or [])
return cves, commits, n
_HUNK = re.compile(r"^@@ -(\d+)(?:,\d+)? \+\d+(?:,\d+)? @@")
def deleted_lines(diff):
"""1-based line numbers (within func_before) of '-' lines in MegaVul's unified diff_func."""
out, old = [], None
for ln in (diff or "").split("\n"):
m = _HUNK.match(ln)
if m: old = int(m.group(1)); continue
if old is None or ln.startswith("---") or ln.startswith("+++"): continue
if ln.startswith("-"): out.append(old); old += 1
elif ln.startswith("+"): pass
else: old += 1
return out
def work(wi, args):
lang, start, recs = args
w = C.StageWriter("megavul", worker=wi, clear=False)
for j, r in enumerate(recs):
idx = start + j; url = r.get("git_url") or ""
cm = r.pop("_commit", None) or {}; cv = r.pop("_cve", None) or {}
repo = url.split("/commit/")[0] if "/commit/" in url else None
ld = C.lang_from_path(r.get("file_path") or "")[1] if lang == "c_cpp" else "java"
if lang == "c_cpp" and ld not in ("c", "cpp", "c_or_cpp_header"): ld = "c_or_cpp"
cd = cm.get("commit_date")
cd = datetime.datetime.fromtimestamp(int(cd), datetime.timezone.utc).strftime("%Y-%m-%d") if cd not in (None, "") else None
extra = {"megavul_index": idx, "cvss_vector": r.get("cvss_vector"), "cvss_base_score": cv.get("cvss_base_score"),
"cvss_is_v3": r.get("cvss_is_v3"), "cve_published": cv.get("publish_date"), "parent_commit": cm.get("parent_commit_hash"),
"megavul_repo_name": r.get("repo_name")}
common = dict(language=lang, language_detail=ld, project=C.project_from_repo(repo) or r.get("repo_name"), repo_url=repo,
commit_sha=r.get("commit_hash"), commit_date=cd, file_path=r.get("file_path"), func_name=r.get("func_name"),
cve_ids=C.cves(r.get("cve_id")), cwe_ids=C.cwes(r.get("cwe_ids")), label_source="nvd_patch_commit",
source_dataset="megavul", source_license=LIC, publishable_code=True, source_split=None)
oid = f"{lang}:{idx}"
if r.get("is_vul"):
pid = C.sha256(f"megavul:{oid}")[:32]
w.add(code=r.get("func_before"), is_vulnerable=True, pair_id=pid, pair_role="vuln", vuln_lines=deleted_lines(r.get("diff_func")),
label_confidence=C.confidence("nvd_patch_commit", "vuln", path=r.get("file_path")),
origin={"dataset": DS, "original_id": f"{oid}:before", "original_label": "is_vul=1:func_before"},
extra=json.dumps(dict(extra, megavul_graph=r.get("func_graph_path_before"))), **common)
w.add(code=r.get("func"), is_vulnerable=False, pair_id=pid, pair_role="fix",
label_confidence=C.confidence("nvd_patch_commit", "fix", path=r.get("file_path")),
origin={"dataset": DS, "original_id": f"{oid}:after", "original_label": "is_vul=1:func_after"},
extra=json.dumps(dict(extra, megavul_graph=r.get("func_graph_path"))), **common)
else:
w.add(code=r.get("func"), is_vulnerable=False, pair_role="unrelated_in_commit",
label_confidence=C.confidence("nvd_patch_commit", "unrelated_in_commit", path=r.get("file_path")),
origin={"dataset": DS, "original_id": f"{oid}:func", "original_label": "is_vul=0"},
extra=json.dumps(dict(extra, megavul_graph=r.get("func_graph_path"))), **common)
return (lang, len(recs), sum(1 for r in recs if r.get("is_vul")), w.close(), w.too_big)
def tasks(chunk=2000):
k = 0
for lang in ("c_cpp", "java"):
cves, commits, n = load_meta(lang); META[lang] = n; print("[meta]", lang, n, flush=True)
with open(f"{RAW}/{lang}/megavul_simple.json", "rb") as f:
it = ijson.items(f, "item", use_float=True); start = 0
while True:
recs = [dict({x: r.get(x) for x in KEEP}, _commit=commits.get(r.get("commit_hash")), _cve=cves.get(r.get("cve_id")))
for r in itertools.islice(it, chunk)]
if not recs: break
yield (k, (lang, start, recs)); start += len(recs); k += 1
def _run(a): return work(*a)
if __name__ == "__main__":
# bounded in-flight queue (Pool.imap would read the whole generator -> whole file in RAM)
import multiprocessing as mp, collections, threading
procs = int(os.environ.get("MEGAVUL_PROCS", "3"))
C.clear_stage("megavul"); tot = collections.Counter(); sem = threading.BoundedSemaphore(procs * 2); res = []
def done(r):
lang, n, nv, rows, big = r; tot[(lang, "records")] += n; tot[(lang, "vul_records")] += nv; tot[(lang, "rows")] += rows
tot[(lang, "too_big")] += big; sem.release()
def fail(e): print("worker error:", repr(e), flush=True); sem.release(); raise SystemExit(1)
with mp.Pool(procs, maxtasksperchild=40) as p:
for k, a in tasks():
sem.acquire(); res.append(p.apply_async(_run, ((k, a),), callback=done, error_callback=fail))
for r in res: r.get()
out = {f"{a}.{b}": v for (a, b), v in sorted(tot.items())}; out["hierarchical_counts"] = META
os.makedirs(f"{C.ROOT}/work/megavul", exist_ok=True)
json.dump(out, open(f"{C.ROOT}/work/megavul/ingest_counts.json", "w"), indent=1)
open(f"{C.STAGE}/megavul/MINHASH_VERSION", "w").write(str(C.MINHASH_VERSION))
print("[megavul]", out, flush=True)

Xet Storage Details

Size:
8.6 kB
·
Xet hash:
93fb345baa30e28d84d876868b052bca79925645d0d615889bd6dae43a93fbf9

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.