diff --git a/tasks/csa159/pair_163861/task_prompt.md b/tasks/csa159/pair_163861/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ed36e726d2efb3830c475171ec25870036020dc5 --- /dev/null +++ b/tasks/csa159/pair_163861/task_prompt.md @@ -0,0 +1,377 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `interprocedural_dataflow` + +### Current failure diagnosis + +- The failed rollout used a syntax-only AST pattern and therefore did not establish the cross-function failure condition: an allocation failure in the xa_store path can leave xarray metadata indicating non-empty while no entry is enumerable. +- Matching every direct callee whose name ends in _empty treated unrelated list, queue, and project-specific predicates as if they shared xa_empty's failure semantics. +- Odd negation parity inside a WARN/BUG expansion proves only expression shape; it does not prove that the affected xarray state can feasibly reach the teardown assertion. +- Refinement remained feedback_required, the semantic mechanism was rated inadequate, and the semantic score stayed below threshold despite successful differential detection. + +### Preserve from prior rollouts + +- Preserve successful compile, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve process quality at or above the configured threshold. +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Establish that a feasible allocation-error or partial-completion path associated with xa_store can produce an xarray whose head metadata is non-NULL while no actual entry is enumerable. +- Establish that this exceptional xarray fact propagates across the relevant function boundaries to the same abstract xarray object inspected during teardown. +- Establish that xa_empty on that object can evaluate false because it observes head metadata, and that its negated result controls a reachable WARN_ON_ONCE trap path. +- Distinguish the vulnerable metadata-based assertion from the patched behavior, where xa_for_each reaches the warning only after observing an actual entry. + +### Implementation constraints + +- Use CSA interprocedural analysis with ProgramState facts or equivalent call summaries for the exceptional xa_store outcome and preserve object identity for the affected xarray region across calls. +- Use call-event callbacks suitable for modeling xa_store and xa_empty, and combine them with CFG or branch-condition evidence that the xa_empty result controls the macro-expanded trap path. +- Inspect the post-preprocessing assertion structure because WARN_ON_ONCE is not a callable sink; recognize its reachable __bug_table trap through AST/CFG relationships rather than a WARN_ON_ONCE call event. +- Emit a report only when the exceptional xa_store-derived fact, the same xarray region, the false xa_empty result, and the reachable trap branch are all related. +- Attach the diagnostic to the vulnerable xa_empty use in the assertion and keep the report within the function containing that use. +- Scope modeling to evidenced xarray semantics; do not infer equivalent behavior from generic *_empty naming conventions. +- Use stable API or semantic identities for xarray operations and regions, without file paths, line numbers, local variable names, commit identifiers, or changed-line anchors. + +### Validation checklist + +- Compile the new checker successfully against the target Clang Static Analyzer API and verify checker registration and loading. +- Scan both supplied pre-patch inputs and confirm the expected diagnostics occur at the xa_empty call in __io_uring_free. +- Scan both supplied post-patch inputs and confirm zero diagnostics after replacement with xa_for_each. +- Verify each pre-patch report is on the changed assertion line with no duplicate report for the same semantic path. +- Add or run a relevant case where a normal xa_store outcome reaches !xa_empty and confirm that the exceptional-state report is suppressed. +- Add or run relevant negative cases for list_empty, skb_queue_empty, arbitrary *_empty functions, and negated emptiness tests outside trap assertions. +- Confirm interprocedural propagation uses the same xarray region and does not report when the exceptional fact belongs to a different container. +- Complete refinement with an accepted clean outcome while retaining G6, hard validation, code verification, and the configured process-score threshold. + +### Avoid and forbidden regressions + +- Do not reuse a syntax-only odd-negation plus trap-assembly pattern as sufficient evidence of the vulnerability. +- Do not classify all functions ending in _empty, including list_empty_careful, as metadata-only predicates with xa_empty's partial-insertion behavior. +- Do not report solely because !xa_empty appears inside a WARN_ON, WARN_ON_ONCE, WARN_ONCE, BUG, or BUG_ON expansion. +- Do not rely on PreCall or PostCall to observe WARN_ON_ONCE itself, because preprocessing expands it into a statement expression and inline trap assembly. +- Do not substitute generic warning proximity or before/after disappearance for proof of the failed-store state reaching the assertion. +- Do not introduce source-text matching or patch-local file, function, variable, line, or commit anchors. diff --git a/tasks/csa159/pair_163978/checker_template.cpp b/tasks/csa159/pair_163978/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_163978/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_163978/config.json b/tasks/csa159/pair_163978/config.json new file mode 100644 index 0000000000000000000000000000000000000000..94e857426e78b43c18cf1a5333e7cc2334307683 --- /dev/null +++ b/tasks/csa159/pair_163978/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "504fa212d7030fb1c042290dc2eb92b21515573a", + "after_commit": "3bb2a01caa813d3a1845d378bbe4169ef280d394", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/b7bfaa761d760e72a969d116517eaa12e404c262/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/b7bfaa761d760e72a969d116517eaa12e404c262/compile_commands.json", + "changed_files": [ + "lib/kobject.c" + ], + "commit_message": "kobject: Fix slab-out-of-bounds in fill_kobj_path()\n\nIn kobject_get_path(), if kobj->name is changed between calls\nget_kobj_path_length() and fill_kobj_path() and the length becomes\nlonger, then fill_kobj_path() will have an out-of-bounds bug.\n\nThe actual current problem occurs when the ixgbe probe.\n\nIn ixgbe_mii_bus_init(), if the length of netdev->dev.kobj.name\nlength becomes longer, out-of-bounds will occur.\n\ncpu0 cpu1\nixgbe_probe\n register_netdev(netdev)\n netdev_register_kobject\n device_add\n kobject_uevent // Sending ADD events\n systemd-udevd // rename netdev\n dev_change_name\n device_rename\n kobject_rename\n ixgbe_mii_bus_init |\n mdiobus_register |\n __mdiobus_register |\n device_register |\n device_add |\n kobject_uevent |\n kobject_get_path |\n len = get_kobj_path_length // old name |\n path = kzalloc(len, gfp_mask); |\n kobj->name = name;\n /* name length becomes\n * longer\n */\n fill_kobj_path /* kobj path length is\n * longer than path,\n * resulting in out of\n * bounds when filling path\n */\n\nThis is the kasan report:\n\n==================================================================\nBUG: KASAN: slab-out-of-bounds in fill_kobj_path+0x50/0xc0\nWrite of size 7 at addr ff1100090573d1fd by task kworker/28:1/673\n\n Workqueue: events work_for_cpu_fn\n Call Trace:\n \n dump_stack_lvl+0x34/0x48\n print_address_description.constprop.0+0x86/0x1e7\n print_report+0x36/0x4f\n kasan_report+0xad/0x130\n kasan_check_range+0x35/0x1c0\n memcpy+0x39/0x60\n fill_kobj_path+0x50/0xc0\n kobject_get_path+0x5a/0xc0\n kobject_uevent_env+0x140/0x460\n device_add+0x5c7/0x910\n __mdiobus_register+0x14e/0x490\n ixgbe_probe.cold+0x441/0x574 [ixgbe]\n local_pci_probe+0x78/0xc0\n work_for_cpu_fn+0x26/0x40\n process_one_work+0x3b6/0x6a0\n worker_thread+0x368/0x520\n kthread+0x165/0x1a0\n ret_from_fork+0x1f/0x30\n\nThis reproducer triggers that bug:\n\nwhile:\ndo\n rmmod ixgbe\n sleep 0.5\n modprobe ixgbe\n sleep 0.5\n\nWhen calling fill_kobj_path() to fill path, if the name length of\nkobj becomes longer, return failure and retry. This fixes the problem.\n\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nSigned-off-by: Wang Hai \nLink: https://lore.kernel.org/r/20221220012143.52141-1-wanghai38@huawei.com\nSigned-off-by: Greg Kroah-Hartman ", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_163978/patch.diff b/tasks/csa159/pair_163978/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0e973e1d578bb7dd56dd038d64486a30e630a8ca --- /dev/null +++ b/tasks/csa159/pair_163978/patch.diff @@ -0,0 +1,49 @@ +diff --git a/lib/kobject.c b/lib/kobject.c +index 985ee1c4f2c6..d20ce15eec2d 100644 +--- a/lib/kobject.c ++++ b/lib/kobject.c +@@ -112,7 +112,7 @@ static int get_kobj_path_length(const struct kobject *kobj) + return length; + } + +-static void fill_kobj_path(const struct kobject *kobj, char *path, int length) ++static int fill_kobj_path(const struct kobject *kobj, char *path, int length) + { + const struct kobject *parent; + +@@ -121,12 +121,16 @@ static void fill_kobj_path(const struct kobject *kobj, char *path, int length) + int cur = strlen(kobject_name(parent)); + /* back up enough to print this name with '/' */ + length -= cur; ++ if (length <= 0) ++ return -EINVAL; + memcpy(path + length, kobject_name(parent), cur); + *(path + --length) = '/'; + } + + pr_debug("kobject: '%s' (%p): %s: path = '%s'\n", kobject_name(kobj), + kobj, __func__, path); ++ ++ return 0; + } + + /** +@@ -141,13 +145,17 @@ char *kobject_get_path(const struct kobject *kobj, gfp_t gfp_mask) + char *path; + int len; + ++retry: + len = get_kobj_path_length(kobj); + if (len == 0) + return NULL; + path = kzalloc(len, gfp_mask); + if (!path) + return NULL; +- fill_kobj_path(kobj, path, len); ++ if (fill_kobj_path(kobj, path, len)) { ++ kfree(path); ++ goto retry; ++ } + + return path; + } \ No newline at end of file diff --git a/tasks/csa159/pair_163978/post_functions.txt b/tasks/csa159/pair_163978/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..6c44698ef9143c294d05c446720b1bf794329fe1 --- /dev/null +++ b/tasks/csa159/pair_163978/post_functions.txt @@ -0,0 +1,61 @@ +### File: lib/kobject.c +```c +static int get_kobj_path_length(const struct kobject *kobj) +{ + int length = 1; + const struct kobject *parent = kobj; + + /* walk up the ancestors until we hit the one pointing to the + * root. + * Add 1 to strlen for leading '/' of each level. + */ + do { + if (kobject_name(parent) == NULL) + return 0; + length += strlen(kobject_name(parent)) + 1; + parent = parent->parent; + } while (parent); + return length; +} + +static int fill_kobj_path(const struct kobject *kobj, char *path, int length) +{ + const struct kobject *parent; + + --length; + for (parent = kobj; parent; parent = parent->parent) { + int cur = strlen(kobject_name(parent)); + /* back up enough to print this name with '/' */ + length -= cur; + if (length <= 0) + return -EINVAL; + memcpy(path + length, kobject_name(parent), cur); + *(path + --length) = '/'; + } + + pr_debug("kobject: '%s' (%p): %s: path = '%s'\n", kobject_name(kobj), + kobj, __func__, path); + + return 0; +} + +char *kobject_get_path(const struct kobject *kobj, gfp_t gfp_mask) +{ + char *path; + int len; + +retry: + len = get_kobj_path_length(kobj); + if (len == 0) + return NULL; + path = kzalloc(len, gfp_mask); + if (!path) + return NULL; + if (fill_kobj_path(kobj, path, len)) { + kfree(path); + goto retry; + } + + return path; +} +``` diff --git a/tasks/csa159/pair_163978/pre_functions.txt b/tasks/csa159/pair_163978/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..b041b1d1c60f1d3f36afb95f7b046b5f76744512 --- /dev/null +++ b/tasks/csa159/pair_163978/pre_functions.txt @@ -0,0 +1,53 @@ +### File: lib/kobject.c +```c +static int get_kobj_path_length(const struct kobject *kobj) +{ + int length = 1; + const struct kobject *parent = kobj; + + /* walk up the ancestors until we hit the one pointing to the + * root. + * Add 1 to strlen for leading '/' of each level. + */ + do { + if (kobject_name(parent) == NULL) + return 0; + length += strlen(kobject_name(parent)) + 1; + parent = parent->parent; + } while (parent); + return length; +} + +static void fill_kobj_path(const struct kobject *kobj, char *path, int length) +{ + const struct kobject *parent; + + --length; + for (parent = kobj; parent; parent = parent->parent) { + int cur = strlen(kobject_name(parent)); + /* back up enough to print this name with '/' */ + length -= cur; + memcpy(path + length, kobject_name(parent), cur); + *(path + --length) = '/'; + } + + pr_debug("kobject: '%s' (%p): %s: path = '%s'\n", kobject_name(kobj), + kobj, __func__, path); +} + +char *kobject_get_path(const struct kobject *kobj, gfp_t gfp_mask) +{ + char *path; + int len; + + len = get_kobj_path_length(kobj); + if (len == 0) + return NULL; + path = kzalloc(len, gfp_mask); + if (!path) + return NULL; + fill_kobj_path(kobj, path, len); + + return path; +} +``` diff --git a/tasks/csa159/pair_163978/task_prompt.md b/tasks/csa159/pair_163978/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..3c8f990feb31d45b52d2ee52684b8fd9e2d2eecf --- /dev/null +++ b/tasks/csa159/pair_163978/task_prompt.md @@ -0,0 +1,381 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `interprocedural_dataflow` + +### Current failure diagnosis + +- The prior rollout detected a generic negative destination offset but did not prove the specific defect fixed by the patch: a length measured by get_kobj_path_length() becoming stale before fill_kobj_path() writes into the allocation. +- It did not establish that path is the beginning of the allocation returned by kzalloc(), nor relate the allocation extent to the later memcpy and decremented store. +- It had no model for the relationship between the sizing and filling operations or for concurrent kobject name or ancestry growth, so its reports covered a superset of the patched defect. +- The final refinement, semantic mechanism, and semantic score checks failed even though compilation, differential validation, scope sharpness, and hardcoding checks passed. + +### Preserve from prior rollouts + +- Preserve successful compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve at least the previously adequate path-sensitive CSA reasoning level. +- Preserve semantic score at or above the configured threshold and process quality at or above its configured threshold. +- Do not introduce dependence on patch anchors, patch-local identifiers, literals, line numbers, or source-text matching. +- Keep the checker project-general and free of patch-local hardcoding. + +### Required semantic proof + +- Establish that a destination write can occur through a pointer derived from the allocation base, with an effective offset that is negative relative to the beginning of that allocation. +- Track the allocation size or available extent from the allocation-producing operation and relate it to the length computed before the fill operation. +- Connect the value returned or established by get_kobj_path_length() with the length consumed by fill_kobj_path(), including the intervening allocation and function boundary. +- Establish that the write is reachable without a terminating condition proving the effective offset is non-negative, and that the patched length <= 0 return excludes the corresponding unsafe path. +- Represent the stale-size condition caused by a possible change in the kobject name or ancestry between measurement and filling sufficiently to distinguish the fixed race from unrelated negative arithmetic. +- Keep the claimed defect precise: the write begins before the allocated path buffer; do not infer that every negative arithmetic expression is an out-of-bounds access. + +### Implementation constraints + +- Use CSA path-sensitive ProgramState and ConstraintManager facts at the write sink, combined with interprocedural propagation across the sizing, allocation, and filling functions. +- Model destination-writing calls such as memcpy and direct pointer stores only when their destination can be tied to the tracked allocation base and effective offset. +- Preserve correct handling of pointer arithmetic, nested element or field regions, signed values, and pre/post-decrement side effects without manually re-evaluating expressions. +- Carry allocation extent and relevant length provenance through returns, arguments, and aliases rather than recognizing only local AST shapes. +- Use CFG reachability and terminating guards to suppress the patched paths, while reporting at the concrete write location with a path-sensitive diagnostic. +- Keep matching structural and semantic; do not special-case fill_kobj_path, get_kobj_path_length, kobject_get_path, kobject, path, length, or patch-specific APIs. +- Limit reports to the project-general stale-size allocation/write relation and avoid broad classification of arbitrary writable byte-pointer calls without established provenance. + +### Validation checklist + +- Compile the new checker and retain code verification success. +- Scan the supplied pre-patch source and confirm the expected vulnerable writes are reported at or near the memcpy and direct-store sinks. +- Scan the supplied post-patch source and confirm those reports disappear because the terminating guard and retry path exclude the unsafe relation. +- Verify report locations belong to the changed functions and remain within the established diagnostic-distance threshold. +- Check that the before/after result preserves objective gate G6, including differential detection, sharpness, and non-patched-function false-positive control. +- Exercise a refinement set with nonnegative guarded offsets, interior pointers, concrete offsets, unrelated negative arithmetic, and writes lacking allocation provenance. +- Confirm the checker remains patch-anchor-free and patch-hardcoding-free under implementation and scan checks. +- Require refinement acceptance, semantic mechanism adequacy, semantic correctness, and semantic score threshold success before rollout. + +### Avoid and forbidden regressions + +- Do not treat any feasible negative symbolic offset as sufficient evidence of this vulnerability. +- Do not rely solely on local PreCall or PreStmt destination shape without allocation extent and cross-function provenance. +- Do not force all pointer offsets into a signed interpretation when the source semantics do not establish that interpretation. +- Do not broadly classify every mutable byte-buffer first parameter as a destination sink without proving the relevant write and allocation relationship. +- Do not claim that a nonnegative offset proves the entire write range fits within the allocation. +- Do not model the patch by matching its function names, variable names, guard text, changed lines, or literal constants. +- Do not regress the successful compile, validation, objective-gate, scope-control, semantic-level, semantic-score, process-quality, anchor-free, or hardcoding-free checks. diff --git a/tasks/csa159/pair_164140/checker_template.cpp b/tasks/csa159/pair_164140/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_164140/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_164140/config.json b/tasks/csa159/pair_164140/config.json new file mode 100644 index 0000000000000000000000000000000000000000..32b26b1dd06befcd56e2cafeb2c7da381a619577 --- /dev/null +++ b/tasks/csa159/pair_164140/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "60316d7f10b17a7ebb1ead0642fee8710e1560e0", + "after_commit": "23d05d563b7e7b0314e65c8e882bc27eac2da8e7", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/33cc938e65a98f1d29d0a18403dbbee050dcad9a/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/33cc938e65a98f1d29d0a18403dbbee050dcad9a/compile_commands.json", + "changed_files": [ + "net/core/skbuff.c" + ], + "commit_message": "net: prevent mss overflow in skb_segment()\n\nOnce again syzbot is able to crash the kernel in skb_segment() [1]\n\nGSO_BY_FRAGS is a forbidden value, but unfortunately the following\ncomputation in skb_segment() can reach it quite easily :\n\n\tmss = mss * partial_segs;\n\n65535 = 3 * 5 * 17 * 257, so many initial values of mss can lead to\na bad final result.\n\nMake sure to limit segmentation so that the new mss value is smaller\nthan GSO_BY_FRAGS.\n\n[1]\n\ngeneral protection fault, probably for non-canonical address 0xdffffc000000000e: 0000 [#1] PREEMPT SMP KASAN\nKASAN: null-ptr-deref in range [0x0000000000000070-0x0000000000000077]\nCPU: 1 PID: 5079 Comm: syz-executor993 Not tainted 6.7.0-rc4-syzkaller-00141-g1ae4cd3cbdd0 #0\nHardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 11/10/2023\nRIP: 0010:skb_segment+0x181d/0x3f30 net/core/skbuff.c:4551\nCode: 83 e3 02 e9 fb ed ff ff e8 90 68 1c f9 48 8b 84 24 f8 00 00 00 48 8d 78 70 48 b8 00 00 00 00 00 fc ff df 48 89 fa 48 c1 ea 03 <0f> b6 04 02 84 c0 74 08 3c 03 0f 8e 8a 21 00 00 48 8b 84 24 f8 00\nRSP: 0018:ffffc900043473d0 EFLAGS: 00010202\nRAX: dffffc0000000000 RBX: 0000000000010046 RCX: ffffffff886b1597\nRDX: 000000000000000e RSI: ffffffff886b2520 RDI: 0000000000000070\nRBP: ffffc90004347578 R08: 0000000000000005 R09: 000000000000ffff\nR10: 000000000000ffff R11: 0000000000000002 R12: ffff888063202ac0\nR13: 0000000000010000 R14: 000000000000ffff R15: 0000000000000046\nFS: 0000555556e7e380(0000) GS:ffff8880b9900000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 0000000020010000 CR3: 0000000027ee2000 CR4: 00000000003506f0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\nCall Trace:\n\nudp6_ufo_fragment+0xa0e/0xd00 net/ipv6/udp_offload.c:109\nipv6_gso_segment+0x534/0x17e0 net/ipv6/ip6_offload.c:120\nskb_mac_gso_segment+0x290/0x610 net/core/gso.c:53\n__skb_gso_segment+0x339/0x710 net/core/gso.c:124\nskb_gso_segment include/net/gso.h:83 [inline]\nvalidate_xmit_skb+0x36c/0xeb0 net/core/dev.c:3626\n__dev_queue_xmit+0x6f3/0x3d60 net/core/dev.c:4338\ndev_queue_xmit include/linux/netdevice.h:3134 [inline]\npacket_xmit+0x257/0x380 net/packet/af_packet.c:276\npacket_snd net/packet/af_packet.c:3087 [inline]\npacket_sendmsg+0x24c6/0x5220 net/packet/af_packet.c:3119\nsock_sendmsg_nosec net/socket.c:730 [inline]\n__sock_sendmsg+0xd5/0x180 net/socket.c:745\n__sys_sendto+0x255/0x340 net/socket.c:2190\n__do_sys_sendto net/socket.c:2202 [inline]\n__se_sys_sendto net/socket.c:2198 [inline]\n__x64_sys_sendto+0xe0/0x1b0 net/socket.c:2198\ndo_syscall_x64 arch/x86/entry/common.c:52 [inline]\ndo_syscall_64+0x40/0x110 arch/x86/entry/common.c:83\nentry_SYSCALL_64_after_hwframe+0x63/0x6b\nRIP: 0033:0x7f8692032aa9\nCode: 28 00 00 00 75 05 48 83 c4 28 c3 e8 d1 19 00 00 90 48 89 f8 48 89 f7 48 89 d6 48 89 ca 4d 89 c2 4d 89 c8 4c 8b 4c 24 08 0f 05 <48> 3d 01 f0 ff ff 73 01 c3 48 c7 c1 b8 ff ff ff f7 d8 64 89 01 48\nRSP: 002b:00007fff8d685418 EFLAGS: 00000246 ORIG_RAX: 000000000000002c\nRAX: ffffffffffffffda RBX: 0000000000000003 RCX: 00007f8692032aa9\nRDX: 0000000000010048 RSI: 00000000200000c0 RDI: 0000000000000003\nRBP: 00000000000f4240 R08: 0000000020000540 R09: 0000000000000014\nR10: 0000000000000000 R11: 0000000000000246 R12: 00007fff8d685480\nR13: 0000000000000001 R14: 00007fff8d685480 R15: 0000000000000003\n\nModules linked in:\n---[ end trace 0000000000000000 ]---\nRIP: 0010:skb_segment+0x181d/0x3f30 net/core/skbuff.c:4551\nCode: 83 e3 02 e9 fb ed ff ff e8 90 68 1c f9 48 8b 84 24 f8 00 00 00 48 8d 78 70 48 b8 00 00 00 00 00 fc ff df 48 89 fa 48 c1 ea 03 <0f> b6 04 02 84 c0 74 08 3c 03 0f 8e 8a 21 00 00 48 8b 84 24 f8 00\nRSP: 0018:ffffc900043473d0 EFLAGS: 00010202\nRAX: dffffc0000000000 RBX: 0000000000010046 RCX: ffffffff886b1597\nRDX: 000000000000000e RSI: ffffffff886b2520 RDI: 0000000000000070\nRBP: ffffc90004347578 R08: 0000000000000005 R09: 000000000000ffff\nR10: 000000000000ffff R11: 0000000000000002 R12: ffff888063202ac0\nR13: 0000000000010000 R14: 000000000000ffff R15: 0000000000000046\nFS: 0000555556e7e380(0000) GS:ffff8880b9900000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 0000000020010000 CR3: 0000000027ee2000 CR4: 00000000003506f0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\n\nFixes: 3953c46c3ac7 (\"sk_buff: allow segmenting based on frag sizes\")\nSigned-off-by: Eric Dumazet \nCc: Marcelo Ricardo Leitner \nReviewed-by: Willem de Bruijn \nLink: https://lore.kernel.org/r/20231212164621.4131800-1-edumazet@google.com\nSigned-off-by: Jakub Kicinski ", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_164140/patch.diff b/tasks/csa159/pair_164140/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..71a1d601fa74d1dc6571443eb2981aea98d7237a --- /dev/null +++ b/tasks/csa159/pair_164140/patch.diff @@ -0,0 +1,15 @@ +diff --git a/net/core/skbuff.c b/net/core/skbuff.c +index b157efea5dea..83af8aaeb893 100644 +--- a/net/core/skbuff.c ++++ b/net/core/skbuff.c +@@ -4522,8 +4522,9 @@ struct sk_buff *skb_segment(struct sk_buff *head_skb, + /* GSO partial only requires that we trim off any excess that + * doesn't fit into an MSS sized block, so take care of that + * now. ++ * Cap len to not accidentally hit GSO_BY_FRAGS. + */ +- partial_segs = len / mss; ++ partial_segs = min(len, GSO_BY_FRAGS - 1) / mss; + if (partial_segs > 1) + mss *= partial_segs; + else \ No newline at end of file diff --git a/tasks/csa159/pair_164140/post_functions.txt b/tasks/csa159/pair_164140/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..d726876af4089b877f6013c4f9ea79de20043539 --- /dev/null +++ b/tasks/csa159/pair_164140/post_functions.txt @@ -0,0 +1,328 @@ +### File: net/core/skbuff.c +```c +struct sk_buff *skb_segment(struct sk_buff *head_skb, + netdev_features_t features) +{ + struct sk_buff *segs = NULL; + struct sk_buff *tail = NULL; + struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list; + unsigned int mss = skb_shinfo(head_skb)->gso_size; + unsigned int doffset = head_skb->data - skb_mac_header(head_skb); + unsigned int offset = doffset; + unsigned int tnl_hlen = skb_tnl_header_len(head_skb); + unsigned int partial_segs = 0; + unsigned int headroom; + unsigned int len = head_skb->len; + struct sk_buff *frag_skb; + skb_frag_t *frag; + __be16 proto; + bool csum, sg; + int err = -ENOMEM; + int i = 0; + int nfrags, pos; + + if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) && + mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) { + struct sk_buff *check_skb; + + for (check_skb = list_skb; check_skb; check_skb = check_skb->next) { + if (skb_headlen(check_skb) && !check_skb->head_frag) { + /* gso_size is untrusted, and we have a frag_list with + * a linear non head_frag item. + * + * If head_skb's headlen does not fit requested gso_size, + * it means that the frag_list members do NOT terminate + * on exact gso_size boundaries. Hence we cannot perform + * skb_frag_t page sharing. Therefore we must fallback to + * copying the frag_list skbs; we do so by disabling SG. + */ + features &= ~NETIF_F_SG; + break; + } + } + } + + __skb_push(head_skb, doffset); + proto = skb_network_protocol(head_skb, NULL); + if (unlikely(!proto)) + return ERR_PTR(-EINVAL); + + sg = !!(features & NETIF_F_SG); + csum = !!can_checksum_protocol(features, proto); + + if (sg && csum && (mss != GSO_BY_FRAGS)) { + if (!(features & NETIF_F_GSO_PARTIAL)) { + struct sk_buff *iter; + unsigned int frag_len; + + if (!list_skb || + !net_gso_ok(features, skb_shinfo(head_skb)->gso_type)) + goto normal; + + /* If we get here then all the required + * GSO features except frag_list are supported. + * Try to split the SKB to multiple GSO SKBs + * with no frag_list. + * Currently we can do that only when the buffers don't + * have a linear part and all the buffers except + * the last are of the same length. + */ + frag_len = list_skb->len; + skb_walk_frags(head_skb, iter) { + if (frag_len != iter->len && iter->next) + goto normal; + if (skb_headlen(iter) && !iter->head_frag) + goto normal; + + len -= iter->len; + } + + if (len != frag_len) + goto normal; + } + + /* GSO partial only requires that we trim off any excess that + * doesn't fit into an MSS sized block, so take care of that + * now. + * Cap len to not accidentally hit GSO_BY_FRAGS. + */ + partial_segs = min(len, GSO_BY_FRAGS - 1) / mss; + if (partial_segs > 1) + mss *= partial_segs; + else + partial_segs = 0; + } + +normal: + headroom = skb_headroom(head_skb); + pos = skb_headlen(head_skb); + + if (skb_orphan_frags(head_skb, GFP_ATOMIC)) + return ERR_PTR(-ENOMEM); + + nfrags = skb_shinfo(head_skb)->nr_frags; + frag = skb_shinfo(head_skb)->frags; + frag_skb = head_skb; + + do { + struct sk_buff *nskb; + skb_frag_t *nskb_frag; + int hsize; + int size; + + if (unlikely(mss == GSO_BY_FRAGS)) { + len = list_skb->len; + } else { + len = head_skb->len - offset; + if (len > mss) + len = mss; + } + + hsize = skb_headlen(head_skb) - offset; + + if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) && + (skb_headlen(list_skb) == len || sg)) { + BUG_ON(skb_headlen(list_skb) > len); + + nskb = skb_clone(list_skb, GFP_ATOMIC); + if (unlikely(!nskb)) + goto err; + + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; + frag_skb = list_skb; + pos += skb_headlen(list_skb); + + while (pos < offset + len) { + BUG_ON(i >= nfrags); + + size = skb_frag_size(frag); + if (pos + size > offset + len) + break; + + i++; + pos += size; + frag++; + } + + list_skb = list_skb->next; + + if (unlikely(pskb_trim(nskb, len))) { + kfree_skb(nskb); + goto err; + } + + hsize = skb_end_offset(nskb); + if (skb_cow_head(nskb, doffset + headroom)) { + kfree_skb(nskb); + goto err; + } + + nskb->truesize += skb_end_offset(nskb) - hsize; + skb_release_head_state(nskb); + __skb_push(nskb, doffset); + } else { + if (hsize < 0) + hsize = 0; + if (hsize > len || !sg) + hsize = len; + + nskb = __alloc_skb(hsize + doffset + headroom, + GFP_ATOMIC, skb_alloc_rx_flag(head_skb), + NUMA_NO_NODE); + + if (unlikely(!nskb)) + goto err; + + skb_reserve(nskb, headroom); + __skb_put(nskb, doffset); + } + + if (segs) + tail->next = nskb; + else + segs = nskb; + tail = nskb; + + __copy_skb_header(nskb, head_skb); + + skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom); + skb_reset_mac_len(nskb); + + skb_copy_from_linear_data_offset(head_skb, -tnl_hlen, + nskb->data - tnl_hlen, + doffset + tnl_hlen); + + if (nskb->len == len + doffset) + goto perform_csum_check; + + if (!sg) { + if (!csum) { + if (!nskb->remcsum_offload) + nskb->ip_summed = CHECKSUM_NONE; + SKB_GSO_CB(nskb)->csum = + skb_copy_and_csum_bits(head_skb, offset, + skb_put(nskb, + len), + len); + SKB_GSO_CB(nskb)->csum_start = + skb_headroom(nskb) + doffset; + } else { + if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len)) + goto err; + } + continue; + } + + nskb_frag = skb_shinfo(nskb)->frags; + + skb_copy_from_linear_data_offset(head_skb, offset, + skb_put(nskb, hsize), hsize); + + skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags & + SKBFL_SHARED_FRAG; + + if (skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC)) + goto err; + + while (pos < offset + len) { + if (i >= nfrags) { + if (skb_orphan_frags(list_skb, GFP_ATOMIC) || + skb_zerocopy_clone(nskb, list_skb, + GFP_ATOMIC)) + goto err; + + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; + frag_skb = list_skb; + if (!skb_headlen(list_skb)) { + BUG_ON(!nfrags); + } else { + BUG_ON(!list_skb->head_frag); + + /* to make room for head_frag. */ + i--; + frag--; + } + + list_skb = list_skb->next; + } + + if (unlikely(skb_shinfo(nskb)->nr_frags >= + MAX_SKB_FRAGS)) { + net_warn_ratelimited( + "skb_segment: too many frags: %u %u\n", + pos, mss); + err = -EINVAL; + goto err; + } + + *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag; + __skb_frag_ref(nskb_frag); + size = skb_frag_size(nskb_frag); + + if (pos < offset) { + skb_frag_off_add(nskb_frag, offset - pos); + skb_frag_size_sub(nskb_frag, offset - pos); + } + + skb_shinfo(nskb)->nr_frags++; + + if (pos + size <= offset + len) { + i++; + frag++; + pos += size; + } else { + skb_frag_size_sub(nskb_frag, pos + size - (offset + len)); + goto skip_fraglist; + } + + nskb_frag++; + } + +skip_fraglist: + nskb->data_len = len - hsize; + nskb->len += nskb->data_len; + nskb->truesize += nskb->data_len; + +perform_csum_check: + if (!csum) { + if (skb_has_shared_frag(nskb) && + __skb_linearize(nskb)) + goto err; + + if (!nskb->remcsum_offload) + nskb->ip_summed = CHECKSUM_NONE; + SKB_GSO_CB(nskb)->csum = + skb_checksum(nskb, doffset, + nskb->len - doffset, 0); + SKB_GSO_CB(nskb)->csum_start = + skb_headroom(nskb) + doffset; + } + } while ((offset += len) < head_skb->len); + + /* Some callers want to get the end of the list. + * Put it in segs->prev to avoid walking the list. + * (see validate_xmit_skb_list() for example) + */ + segs->prev = tail; + + if (partial_segs) { + struct sk_buff *iter; + int type = skb_shinfo(head_skb)->gso_type; + unsigned short gso_size = skb_shinfo(head_skb)->gso_size; + + /* Update type to add partial and then remove dodgy if set */ + type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL; + type &= ~SKB_GSO_DODGY; + + /* Update GSO info and prepare to start updating headers on + * our way back down the stack of protocols. + */ + for (iter = segs; iter; iter = iter->next) { + skb_shi + +// ... (759 more chars) +``` diff --git a/tasks/csa159/pair_164140/pre_functions.txt b/tasks/csa159/pair_164140/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..13fb132f0d43e0a32f1ee609a6b8f9dbd2191410 --- /dev/null +++ b/tasks/csa159/pair_164140/pre_functions.txt @@ -0,0 +1,328 @@ +### File: net/core/skbuff.c +```c +struct sk_buff *skb_segment(struct sk_buff *head_skb, + netdev_features_t features) +{ + struct sk_buff *segs = NULL; + struct sk_buff *tail = NULL; + struct sk_buff *list_skb = skb_shinfo(head_skb)->frag_list; + unsigned int mss = skb_shinfo(head_skb)->gso_size; + unsigned int doffset = head_skb->data - skb_mac_header(head_skb); + unsigned int offset = doffset; + unsigned int tnl_hlen = skb_tnl_header_len(head_skb); + unsigned int partial_segs = 0; + unsigned int headroom; + unsigned int len = head_skb->len; + struct sk_buff *frag_skb; + skb_frag_t *frag; + __be16 proto; + bool csum, sg; + int err = -ENOMEM; + int i = 0; + int nfrags, pos; + + if ((skb_shinfo(head_skb)->gso_type & SKB_GSO_DODGY) && + mss != GSO_BY_FRAGS && mss != skb_headlen(head_skb)) { + struct sk_buff *check_skb; + + for (check_skb = list_skb; check_skb; check_skb = check_skb->next) { + if (skb_headlen(check_skb) && !check_skb->head_frag) { + /* gso_size is untrusted, and we have a frag_list with + * a linear non head_frag item. + * + * If head_skb's headlen does not fit requested gso_size, + * it means that the frag_list members do NOT terminate + * on exact gso_size boundaries. Hence we cannot perform + * skb_frag_t page sharing. Therefore we must fallback to + * copying the frag_list skbs; we do so by disabling SG. + */ + features &= ~NETIF_F_SG; + break; + } + } + } + + __skb_push(head_skb, doffset); + proto = skb_network_protocol(head_skb, NULL); + if (unlikely(!proto)) + return ERR_PTR(-EINVAL); + + sg = !!(features & NETIF_F_SG); + csum = !!can_checksum_protocol(features, proto); + + if (sg && csum && (mss != GSO_BY_FRAGS)) { + if (!(features & NETIF_F_GSO_PARTIAL)) { + struct sk_buff *iter; + unsigned int frag_len; + + if (!list_skb || + !net_gso_ok(features, skb_shinfo(head_skb)->gso_type)) + goto normal; + + /* If we get here then all the required + * GSO features except frag_list are supported. + * Try to split the SKB to multiple GSO SKBs + * with no frag_list. + * Currently we can do that only when the buffers don't + * have a linear part and all the buffers except + * the last are of the same length. + */ + frag_len = list_skb->len; + skb_walk_frags(head_skb, iter) { + if (frag_len != iter->len && iter->next) + goto normal; + if (skb_headlen(iter) && !iter->head_frag) + goto normal; + + len -= iter->len; + } + + if (len != frag_len) + goto normal; + } + + /* GSO partial only requires that we trim off any excess that + * doesn't fit into an MSS sized block, so take care of that + * now. + */ + partial_segs = len / mss; + if (partial_segs > 1) + mss *= partial_segs; + else + partial_segs = 0; + } + +normal: + headroom = skb_headroom(head_skb); + pos = skb_headlen(head_skb); + + if (skb_orphan_frags(head_skb, GFP_ATOMIC)) + return ERR_PTR(-ENOMEM); + + nfrags = skb_shinfo(head_skb)->nr_frags; + frag = skb_shinfo(head_skb)->frags; + frag_skb = head_skb; + + do { + struct sk_buff *nskb; + skb_frag_t *nskb_frag; + int hsize; + int size; + + if (unlikely(mss == GSO_BY_FRAGS)) { + len = list_skb->len; + } else { + len = head_skb->len - offset; + if (len > mss) + len = mss; + } + + hsize = skb_headlen(head_skb) - offset; + + if (hsize <= 0 && i >= nfrags && skb_headlen(list_skb) && + (skb_headlen(list_skb) == len || sg)) { + BUG_ON(skb_headlen(list_skb) > len); + + nskb = skb_clone(list_skb, GFP_ATOMIC); + if (unlikely(!nskb)) + goto err; + + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; + frag_skb = list_skb; + pos += skb_headlen(list_skb); + + while (pos < offset + len) { + BUG_ON(i >= nfrags); + + size = skb_frag_size(frag); + if (pos + size > offset + len) + break; + + i++; + pos += size; + frag++; + } + + list_skb = list_skb->next; + + if (unlikely(pskb_trim(nskb, len))) { + kfree_skb(nskb); + goto err; + } + + hsize = skb_end_offset(nskb); + if (skb_cow_head(nskb, doffset + headroom)) { + kfree_skb(nskb); + goto err; + } + + nskb->truesize += skb_end_offset(nskb) - hsize; + skb_release_head_state(nskb); + __skb_push(nskb, doffset); + } else { + if (hsize < 0) + hsize = 0; + if (hsize > len || !sg) + hsize = len; + + nskb = __alloc_skb(hsize + doffset + headroom, + GFP_ATOMIC, skb_alloc_rx_flag(head_skb), + NUMA_NO_NODE); + + if (unlikely(!nskb)) + goto err; + + skb_reserve(nskb, headroom); + __skb_put(nskb, doffset); + } + + if (segs) + tail->next = nskb; + else + segs = nskb; + tail = nskb; + + __copy_skb_header(nskb, head_skb); + + skb_headers_offset_update(nskb, skb_headroom(nskb) - headroom); + skb_reset_mac_len(nskb); + + skb_copy_from_linear_data_offset(head_skb, -tnl_hlen, + nskb->data - tnl_hlen, + doffset + tnl_hlen); + + if (nskb->len == len + doffset) + goto perform_csum_check; + + if (!sg) { + if (!csum) { + if (!nskb->remcsum_offload) + nskb->ip_summed = CHECKSUM_NONE; + SKB_GSO_CB(nskb)->csum = + skb_copy_and_csum_bits(head_skb, offset, + skb_put(nskb, + len), + len); + SKB_GSO_CB(nskb)->csum_start = + skb_headroom(nskb) + doffset; + } else { + if (skb_copy_bits(head_skb, offset, skb_put(nskb, len), len)) + goto err; + } + continue; + } + + nskb_frag = skb_shinfo(nskb)->frags; + + skb_copy_from_linear_data_offset(head_skb, offset, + skb_put(nskb, hsize), hsize); + + skb_shinfo(nskb)->flags |= skb_shinfo(head_skb)->flags & + SKBFL_SHARED_FRAG; + + if (skb_zerocopy_clone(nskb, frag_skb, GFP_ATOMIC)) + goto err; + + while (pos < offset + len) { + if (i >= nfrags) { + if (skb_orphan_frags(list_skb, GFP_ATOMIC) || + skb_zerocopy_clone(nskb, list_skb, + GFP_ATOMIC)) + goto err; + + i = 0; + nfrags = skb_shinfo(list_skb)->nr_frags; + frag = skb_shinfo(list_skb)->frags; + frag_skb = list_skb; + if (!skb_headlen(list_skb)) { + BUG_ON(!nfrags); + } else { + BUG_ON(!list_skb->head_frag); + + /* to make room for head_frag. */ + i--; + frag--; + } + + list_skb = list_skb->next; + } + + if (unlikely(skb_shinfo(nskb)->nr_frags >= + MAX_SKB_FRAGS)) { + net_warn_ratelimited( + "skb_segment: too many frags: %u %u\n", + pos, mss); + err = -EINVAL; + goto err; + } + + *nskb_frag = (i < 0) ? skb_head_frag_to_page_desc(frag_skb) : *frag; + __skb_frag_ref(nskb_frag); + size = skb_frag_size(nskb_frag); + + if (pos < offset) { + skb_frag_off_add(nskb_frag, offset - pos); + skb_frag_size_sub(nskb_frag, offset - pos); + } + + skb_shinfo(nskb)->nr_frags++; + + if (pos + size <= offset + len) { + i++; + frag++; + pos += size; + } else { + skb_frag_size_sub(nskb_frag, pos + size - (offset + len)); + goto skip_fraglist; + } + + nskb_frag++; + } + +skip_fraglist: + nskb->data_len = len - hsize; + nskb->len += nskb->data_len; + nskb->truesize += nskb->data_len; + +perform_csum_check: + if (!csum) { + if (skb_has_shared_frag(nskb) && + __skb_linearize(nskb)) + goto err; + + if (!nskb->remcsum_offload) + nskb->ip_summed = CHECKSUM_NONE; + SKB_GSO_CB(nskb)->csum = + skb_checksum(nskb, doffset, + nskb->len - doffset, 0); + SKB_GSO_CB(nskb)->csum_start = + skb_headroom(nskb) + doffset; + } + } while ((offset += len) < head_skb->len); + + /* Some callers want to get the end of the list. + * Put it in segs->prev to avoid walking the list. + * (see validate_xmit_skb_list() for example) + */ + segs->prev = tail; + + if (partial_segs) { + struct sk_buff *iter; + int type = skb_shinfo(head_skb)->gso_type; + unsigned short gso_size = skb_shinfo(head_skb)->gso_size; + + /* Update type to add partial and then remove dodgy if set */ + type |= (features & NETIF_F_GSO_PARTIAL) / NETIF_F_GSO_PARTIAL * SKB_GSO_PARTIAL; + type &= ~SKB_GSO_DODGY; + + /* Update GSO info and prepare to start updating headers on + * our way back down the stack of protocols. + */ + for (iter = segs; iter; iter = iter->next) { + skb_shinfo(iter)->gso_size = gso_size; + skb_shinfo(iter)->gso_segs = partial_se + +// ... (685 more chars) +``` diff --git a/tasks/csa159/pair_164140/task_prompt.md b/tasks/csa159/pair_164140/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..dc748064a33cf67b156cedcd05fcaa50c9f6fb5e --- /dev/null +++ b/tasks/csa159/pair_164140/task_prompt.md @@ -0,0 +1,380 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `syntax_only` + +### Current failure diagnosis + +- Only process_score failed (79.35 below threshold). hard_validation, objective_gate G6, refinement_accepted, semantic_mechanism, semantic_score, anchor_free, and hardcoding_free already passed. +- Validation-and-recovery scored 7/10 because two synthetic analyzer repros never recovered: one called undeclared min(); the other broke parsing a hand-rolled min/__careful_cmp/__builtin_choose_expr expansion. +- Plan-to-code consistency scored 9/12: on B = B * P the multiplier extractor can bind the reused divisor VarDecl instead of the recorded quotient. +- CSA implementation quality marked has_report_logic false (EmitBasicReport without a BugType member or dedicated report helper), costing 0.5/4. +- Eight fix cycles were consumed recovering compile failures (deprecated StringRef::startswith, undeclared ExprStmt), inflating process cost after checker.so already built. + +### Preserve from prior rollouts + +- Preserve successful compile, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve an accepted or clean refinement outcome. +- Preserve the previously adequate syntax_only CSA mechanism (same-function AST pattern match of the patched arithmetic; no ProgramState or interprocedural machinery). +- Preserve semantic score at or above the configured threshold. +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Prove an unsigned same-function idiom P = A / B followed by self-multiply B *= P or B = B * P where dividend A is not statically bounded below the GSO_BY_FRAGS sentinel 0xFFFF, so B * P can wrap to that forbidden value. +- Treat a min-style cap of A whose subtree evaluates to GSO_BY_FRAGS-1 (65534 / 0xFFFE) as the safe form that keeps B * P <= 65534. +- The intended true positive is skb_segment GSO-partial arithmetic: uncapped len/mss folded back into mss; the patched min(len, GSO_BY_FRAGS-1)/mss form must be silent. +- The diagnostic must be raised at the self-multiply sink, not at the division. + +### Implementation constraints + +- Implement Checker (or equivalent one-pass function-body AST walk) that records unsigned division assignments then matches a later self-multiply of the same divisor by that quotient. +- Register a BugType and emit through BugReporter at the multiply statement so report logic is structurally present. +- Recognize Linux min-family AST (ChooseExpr, StmtExpr, ConditionalOperator, min/min_t/clamp-style calls) plus a constant 65534 as the project GSO cap, not as a file- or hunk-local token. +- Match only unsigned integer VarDecl pairs inside one function body; do not key off skb_segment, net/core/skbuff.c, CVE ids, or changed line numbers. +- Use current LLVM/Clang APIs and real Stmt/Expr nodes only. +- When the multiply RHS is BO_Mul, the matched multiplier must be the recorded quotient VarDecl, never the LHS divisor. + +### Validation checklist + +- Fresh sources compile to a loadable checker.so with zero compiler diagnostics. +- Pre-patch scan of net/core/skbuff.c::skb_segment reports at mss *= partial_segs (median distance about 1 line from the patched arithmetic). +- Post-patch scan is clean on min(len, GSO_BY_FRAGS-1)/mss (n_patched=0, patched_clean). +- Differential: relevant warnings disappear only inside skb_segment; unrelated disappearances stay 0; sparsity/relevance remain 1.0. +- Cross-validation stays VALID and refinement stays accepted or clean. +- If a standalone repro is used, it must compile with a min() that actually produces a capping AST containing 65534, and any analyzer failure must be recovered. +- Re-score process_score above threshold without dropping G6 or semantic_score. + +### Avoid and forbidden regressions + +- Do not edit, clone, resume, or reconstruct the prior MssOverflowChecker/BodyWalker. +- Do not finish with unrecovered synthetic repros that cannot compile or cannot expand min(). +- Do not call StringRef::startswith or dyn_cast to ExprStmt. +- Do not treat either operand of B = B * P as interchangeable. +- Do not use path-sensitive SVal tracking of mss*partial_segs or a PreStmt-only callback that cannot see the earlier division. +- Do not encode the patch hunk, source path, or function name as the match key. +- Do not omit a BugType/report helper. +- Do not burn repeated compile-fix cycles on deprecated or non-existent AST APIs. diff --git a/tasks/csa159/pair_164279/checker_template.cpp b/tasks/csa159/pair_164279/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_164279/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_164279/config.json b/tasks/csa159/pair_164279/config.json new file mode 100644 index 0000000000000000000000000000000000000000..ea7e297fef74c20e96a4e047d0e186b336a7a131 --- /dev/null +++ b/tasks/csa159/pair_164279/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "6da6680632792709cecf2b006f2fe3ca7857e791", + "after_commit": "d0aac2363549e12cc79b8e285f13d5a9f42fd08e", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/a38297e3fb012ddfa7ce0321a7e5a8daeb1872b6/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/a38297e3fb012ddfa7ce0321a7e5a8daeb1872b6/compile_commands.json", + "changed_files": [ + "block/blk-cgroup.c" + ], + "commit_message": "blk-cgroup: fix list corruption from reorder of WRITE ->lqueued\n\n__blkcg_rstat_flush() can be run anytime, especially when blk_cgroup_bio_start\nis being executed.\n\nIf WRITE of `->lqueued` is re-ordered with READ of 'bisc->lnode.next' in\nthe loop of __blkcg_rstat_flush(), `next_bisc` can be assigned with one\nstat instance being added in blk_cgroup_bio_start(), then the local\nlist in __blkcg_rstat_flush() could be corrupted.\n\nFix the issue by adding one barrier.\n\nCc: Tejun Heo \nCc: Waiman Long \nFixes: 3b8cc6298724 (\"blk-cgroup: Optimize blkcg_rstat_flush()\")\nSigned-off-by: Ming Lei \nLink: https://lore.kernel.org/r/20240515013157.443672-3-ming.lei@redhat.com\nSigned-off-by: Jens Axboe ", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_164279/patch.diff b/tasks/csa159/pair_164279/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6214f9917dad555b788ac7c04e863dacc6c29b93 --- /dev/null +++ b/tasks/csa159/pair_164279/patch.diff @@ -0,0 +1,21 @@ +diff --git a/block/blk-cgroup.c b/block/blk-cgroup.c +index 8699f193cf31..52367a4501d0 100644 +--- a/block/blk-cgroup.c ++++ b/block/blk-cgroup.c +@@ -1035,6 +1035,16 @@ static void __blkcg_rstat_flush(struct blkcg *blkcg, int cpu) + struct blkg_iostat cur; + unsigned int seq; + ++ /* ++ * Order assignment of `next_bisc` from `bisc->lnode.next` in ++ * llist_for_each_entry_safe and clearing `bisc->lqueued` for ++ * avoiding to assign `next_bisc` with new next pointer added ++ * in blk_cgroup_bio_start() in case of re-ordering. ++ * ++ * The pair barrier is implied in llist_add() in blk_cgroup_bio_start(). ++ */ ++ smp_mb(); ++ + WRITE_ONCE(bisc->lqueued, false); + + /* fetch the current per-cpu values */ \ No newline at end of file diff --git a/tasks/csa159/pair_164279/post_functions.txt b/tasks/csa159/pair_164279/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..a5ca0cabca17269b2bd25f18b0e08b7f9a07cb15 --- /dev/null +++ b/tasks/csa159/pair_164279/post_functions.txt @@ -0,0 +1,62 @@ +### File: block/blk-cgroup.c +```c +static void __blkcg_rstat_flush(struct blkcg *blkcg, int cpu) +{ + struct llist_head *lhead = per_cpu_ptr(blkcg->lhead, cpu); + struct llist_node *lnode; + struct blkg_iostat_set *bisc, *next_bisc; + unsigned long flags; + + rcu_read_lock(); + + lnode = llist_del_all(lhead); + if (!lnode) + goto out; + + /* + * For covering concurrent parent blkg update from blkg_release(). + * + * When flushing from cgroup, cgroup_rstat_lock is always held, so + * this lock won't cause contention most of time. + */ + raw_spin_lock_irqsave(&blkg_stat_lock, flags); + + /* + * Iterate only the iostat_cpu's queued in the lockless list. + */ + llist_for_each_entry_safe(bisc, next_bisc, lnode, lnode) { + struct blkcg_gq *blkg = bisc->blkg; + struct blkcg_gq *parent = blkg->parent; + struct blkg_iostat cur; + unsigned int seq; + + /* + * Order assignment of `next_bisc` from `bisc->lnode.next` in + * llist_for_each_entry_safe and clearing `bisc->lqueued` for + * avoiding to assign `next_bisc` with new next pointer added + * in blk_cgroup_bio_start() in case of re-ordering. + * + * The pair barrier is implied in llist_add() in blk_cgroup_bio_start(). + */ + smp_mb(); + + WRITE_ONCE(bisc->lqueued, false); + + /* fetch the current per-cpu values */ + do { + seq = u64_stats_fetch_begin(&bisc->sync); + blkg_iostat_set(&cur, &bisc->cur); + } while (u64_stats_fetch_retry(&bisc->sync, seq)); + + blkcg_iostat_update(blkg, &cur, &bisc->last); + + /* propagate global delta to parent (unless that's root) */ + if (parent && parent->parent) + blkcg_iostat_update(parent, &blkg->iostat.cur, + &blkg->iostat.last); + } + raw_spin_unlock_irqrestore(&blkg_stat_lock, flags); +out: + rcu_read_unlock(); +} +``` diff --git a/tasks/csa159/pair_164279/pre_functions.txt b/tasks/csa159/pair_164279/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2a343281dc44e4ee25ddb91e8aaa2793ca05b016 --- /dev/null +++ b/tasks/csa159/pair_164279/pre_functions.txt @@ -0,0 +1,52 @@ +### File: block/blk-cgroup.c +```c +static void __blkcg_rstat_flush(struct blkcg *blkcg, int cpu) +{ + struct llist_head *lhead = per_cpu_ptr(blkcg->lhead, cpu); + struct llist_node *lnode; + struct blkg_iostat_set *bisc, *next_bisc; + unsigned long flags; + + rcu_read_lock(); + + lnode = llist_del_all(lhead); + if (!lnode) + goto out; + + /* + * For covering concurrent parent blkg update from blkg_release(). + * + * When flushing from cgroup, cgroup_rstat_lock is always held, so + * this lock won't cause contention most of time. + */ + raw_spin_lock_irqsave(&blkg_stat_lock, flags); + + /* + * Iterate only the iostat_cpu's queued in the lockless list. + */ + llist_for_each_entry_safe(bisc, next_bisc, lnode, lnode) { + struct blkcg_gq *blkg = bisc->blkg; + struct blkcg_gq *parent = blkg->parent; + struct blkg_iostat cur; + unsigned int seq; + + WRITE_ONCE(bisc->lqueued, false); + + /* fetch the current per-cpu values */ + do { + seq = u64_stats_fetch_begin(&bisc->sync); + blkg_iostat_set(&cur, &bisc->cur); + } while (u64_stats_fetch_retry(&bisc->sync, seq)); + + blkcg_iostat_update(blkg, &cur, &bisc->last); + + /* propagate global delta to parent (unless that's root) */ + if (parent && parent->parent) + blkcg_iostat_update(parent, &blkg->iostat.cur, + &blkg->iostat.last); + } + raw_spin_unlock_irqrestore(&blkg_stat_lock, flags); +out: + rcu_read_unlock(); +} +``` diff --git a/tasks/csa159/pair_164279/task_prompt.md b/tasks/csa159/pair_164279/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_164279/task_prompt.md @@ -0,0 +1,318 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` diff --git a/tasks/csa159/pair_164624/checker_template.cpp b/tasks/csa159/pair_164624/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_164624/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_164624/config.json b/tasks/csa159/pair_164624/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d4a1157b4c8a2b1229c14d429d7c85dc2639a946 --- /dev/null +++ b/tasks/csa159/pair_164624/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "8adc718881e0a70127f8843dd70e69a80de39352", + "after_commit": "78a033433a5ae4fee85511ee075bc9a48312c79e", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/f0e2f00c49db0cba1feff7ce5a5f163d2152056f/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/f0e2f00c49db0cba1feff7ce5a5f163d2152056f/compile_commands.json", + "changed_files": [ + "drivers/gpu/drm/i915/gt/intel_engine_cs.c" + ], + "commit_message": "drm/i915/gt: Cleanup partial engine discovery failures\n\nIf we abort driver initialisation in the middle of gt/engine discovery,\nsome engines will be fully setup and some not. Those incompletely setup\nengines only have 'engine->release == NULL' and so will leak any of the\ncommon objects allocated.\n\nv2:\n - Drop the destroy_pinned_context() helper for now. It's not really\n worth it with just a single callsite at the moment. (Janusz)\n\nSigned-off-by: Chris Wilson \nCc: Janusz Krzysztofik \nSigned-off-by: Matt Roper \nReviewed-by: Janusz Krzysztofik \nLink: https://patchwork.freedesktop.org/patch/msgid/20220915232654.3283095-2-matthew.d.roper@intel.com", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_164624/patch.diff b/tasks/csa159/pair_164624/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..10b51848180de62d03f29c6c32d213eb4931266c --- /dev/null +++ b/tasks/csa159/pair_164624/patch.diff @@ -0,0 +1,19 @@ +diff --git a/drivers/gpu/drm/i915/gt/intel_engine_cs.c b/drivers/gpu/drm/i915/gt/intel_engine_cs.c +index 1f7188129cd1..2ddcad497fa3 100644 +--- a/drivers/gpu/drm/i915/gt/intel_engine_cs.c ++++ b/drivers/gpu/drm/i915/gt/intel_engine_cs.c +@@ -1274,8 +1274,13 @@ int intel_engines_init(struct intel_gt *gt) + return err; + + err = setup(engine); +- if (err) ++ if (err) { ++ intel_engine_cleanup_common(engine); + return err; ++ } ++ ++ /* The backend should now be responsible for cleanup */ ++ GEM_BUG_ON(engine->release == NULL); + + err = engine_init_common(engine); + if (err) \ No newline at end of file diff --git a/tasks/csa159/pair_164624/post_functions.txt b/tasks/csa159/pair_164624/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2000ea6c458689c6124b9edfb3ba947e02b3c10f --- /dev/null +++ b/tasks/csa159/pair_164624/post_functions.txt @@ -0,0 +1,44 @@ +### File: drivers/gpu/drm/i915/gt/intel_engine_cs.c +```c +int intel_engines_init(struct intel_gt *gt) +{ + int (*setup)(struct intel_engine_cs *engine); + struct intel_engine_cs *engine; + enum intel_engine_id id; + int err; + + if (intel_uc_uses_guc_submission(>->uc)) { + gt->submission_method = INTEL_SUBMISSION_GUC; + setup = intel_guc_submission_setup; + } else if (HAS_EXECLISTS(gt->i915)) { + gt->submission_method = INTEL_SUBMISSION_ELSP; + setup = intel_execlists_submission_setup; + } else { + gt->submission_method = INTEL_SUBMISSION_RING; + setup = intel_ring_submission_setup; + } + + for_each_engine(engine, gt, id) { + err = engine_setup_common(engine); + if (err) + return err; + + err = setup(engine); + if (err) { + intel_engine_cleanup_common(engine); + return err; + } + + /* The backend should now be responsible for cleanup */ + GEM_BUG_ON(engine->release == NULL); + + err = engine_init_common(engine); + if (err) + return err; + + intel_engine_add_user(engine); + } + + return 0; +} +``` diff --git a/tasks/csa159/pair_164624/pre_functions.txt b/tasks/csa159/pair_164624/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..42a548a5d25612472fc5ac326d9e7d224b66e7b6 --- /dev/null +++ b/tasks/csa159/pair_164624/pre_functions.txt @@ -0,0 +1,39 @@ +### File: drivers/gpu/drm/i915/gt/intel_engine_cs.c +```c +int intel_engines_init(struct intel_gt *gt) +{ + int (*setup)(struct intel_engine_cs *engine); + struct intel_engine_cs *engine; + enum intel_engine_id id; + int err; + + if (intel_uc_uses_guc_submission(>->uc)) { + gt->submission_method = INTEL_SUBMISSION_GUC; + setup = intel_guc_submission_setup; + } else if (HAS_EXECLISTS(gt->i915)) { + gt->submission_method = INTEL_SUBMISSION_ELSP; + setup = intel_execlists_submission_setup; + } else { + gt->submission_method = INTEL_SUBMISSION_RING; + setup = intel_ring_submission_setup; + } + + for_each_engine(engine, gt, id) { + err = engine_setup_common(engine); + if (err) + return err; + + err = setup(engine); + if (err) + return err; + + err = engine_init_common(engine); + if (err) + return err; + + intel_engine_add_user(engine); + } + + return 0; +} +``` diff --git a/tasks/csa159/pair_164624/task_prompt.md b/tasks/csa159/pair_164624/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..0481ba954287ddf7edb9f35f7a7ee98b44b855e1 --- /dev/null +++ b/tasks/csa159/pair_164624/task_prompt.md @@ -0,0 +1,376 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `path_sensitive` + +### Current failure diagnosis + +- The prior checker tracked an acquired object until an explicit common cleanup, but never cleared or transferred that obligation after backend setup succeeded; it therefore reported the later engine_init_common failure even though backend teardown owns the object at that point. +- Suffix-based acquire and release matching generalized beyond the specific engine initialization protocol, leaving semantic ownership insufficiently modeled. +- The rollout remained refinement-unaccepted because its semantic result was only partial, and process quality was below threshold despite successful compilation, validation, and hardcoding checks. + +### Preserve from prior rollouts + +- Preserve successful compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve the previously adequate path-sensitive CSA mechanism level. +- Preserve semantic score at or above the configured threshold. +- Do not introduce dependence on patch anchors such as changed line numbers, local patch text, or exact diff locations. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- On a path where engine_setup_common(engine) successfully acquires common resources, establish that a nonzero return from the subsequent backend setup(engine) is an error path requiring intel_engine_cleanup_common(engine). +- Suppress the diagnostic when the acquisition call itself returns the failing value, because that path does not establish a successfully acquired resource. +- Discharge the common-resource obligation when intel_engine_cleanup_common(engine) executes on the same path. +- Model successful backend setup(engine) as an ownership transfer to the backend, so a later engine_init_common(engine) failure is not reported as a missing common cleanup. +- Report the vulnerable return locally in intel_engines_init at the failed backend setup path, and distinguish it from normal zero returns and ownership-transferred paths. + +### Implementation constraints + +- Use ProgramState to carry the per-object acquisition, release, acquisition-result, and ownership-transfer facts along each path. +- Use check::PostCall to observe the relevant helper calls and setup result, and check::PreStmt to inspect the same-path obligation and prove a nonzero integer error return. +- Key tracked facts by the managed object region and preserve frame ownership so diagnostics are not emitted for unrelated inlined callees or objects. +- Recognize the specific project protocol represented by engine_setup_common, intel_engine_cleanup_common, setup, and engine_init_common rather than relying on unrestricted suffix-only helper matching. +- Attach the report to the actual error return and the tracked object, with no diagnostics for normal returns, unconstrained return values, or non-error return types. +- Keep the checker project-general over the documented helper and ownership convention; do not encode patch line numbers, changed text, local variable names, or exact patch anchors. + +### Validation checklist + +- Compile the new checker successfully against the CSA API and verify that the produced checker artifact loads. +- Run both vulnerable and patched revisions through the scan and code-verification validation without regressing hard validation. +- Confirm the vulnerable revision reports the failed setup(engine) return in intel_engines_init and that the patched revision has no corresponding report there. +- Confirm the later engine_init_common failure is not reported in the patched revision because successful setup transferred teardown responsibility. +- Verify that acquisition-self-failure paths, zero returns, and paths with explicit intel_engine_cleanup_common do not produce diagnostics. +- Verify differential and scope behavior: the relevant warning disappears after the patch, no unrelated non-patched warnings disappear, and report locations remain near the affected function. +- Recheck anchor-free and hardcoding-free status, objective gate G6, semantic mechanism level, and configured semantic-score threshold. + +### Avoid and forbidden regressions + +- Do not treat every still-pending explicit cleanup obligation as a leak after successful backend setup; represent ownership transfer before evaluating later returns. +- Do not use syntax-only matching of an if-and-return shape, EndFunction, or PostStmt as the primary proof of the path-specific defect. +- Do not report merely because a resource lacks an explicit common cleanup when backend ownership has been established. +- Do not broaden matching to arbitrary names that happen to share acquire or release suffixes without proving the corresponding object protocol. +- Do not weaken the accepted path-sensitive contract to improve process or differential scores. +- Do not regress compilation, before/after validation, code verification, objective eligibility, semantic adequacy, anchor independence, or hardcoding independence. diff --git a/tasks/csa159/pair_164760/checker_template.cpp b/tasks/csa159/pair_164760/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_164760/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_164760/config.json b/tasks/csa159/pair_164760/config.json new file mode 100644 index 0000000000000000000000000000000000000000..ec995a27f07bd26e2dba6631bd85aa494b896bb2 --- /dev/null +++ b/tasks/csa159/pair_164760/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "965adae5a33a998e2b62ec1b37c5eb21f1875b15", + "after_commit": "15a901361ec3fb1c393f91880e1cbf24ec0a88bd", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/ffd294d346d185b70e28b1a28abe367bbfe53c04/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/ffd294d346d185b70e28b1a28abe367bbfe53c04/compile_commands.json", + "changed_files": [ + "net/ipv4/ipmr_base.c" + ], + "commit_message": "ipmr: do not call mr_mfc_uses_dev() for unres entries\n\nsyzbot found that calling mr_mfc_uses_dev() for unres entries\nwould crash [1], because c->mfc_un.res.minvif / c->mfc_un.res.maxvif\nalias to \"struct sk_buff_head unresolved\", which contain two pointers.\n\nThis code never worked, lets remove it.\n\n[1]\nUnable to handle kernel paging request at virtual address ffff5fff2d536613\nKASAN: maybe wild-memory-access in range [0xfffefff96a9b3098-0xfffefff96a9b309f]\nModules linked in:\nCPU: 1 UID: 0 PID: 7321 Comm: syz.0.16 Not tainted 6.13.0-rc7-syzkaller-g1950a0af2d55 #0\nHardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 09/13/2024\npstate: 80400005 (Nzcv daif +PAN -UAO -TCO -DIT -SSBS BTYPE=--)\n pc : mr_mfc_uses_dev net/ipv4/ipmr_base.c:290 [inline]\n pc : mr_table_dump+0x5a4/0x8b0 net/ipv4/ipmr_base.c:334\n lr : mr_mfc_uses_dev net/ipv4/ipmr_base.c:289 [inline]\n lr : mr_table_dump+0x694/0x8b0 net/ipv4/ipmr_base.c:334\nCall trace:\n mr_mfc_uses_dev net/ipv4/ipmr_base.c:290 [inline] (P)\n mr_table_dump+0x5a4/0x8b0 net/ipv4/ipmr_base.c:334 (P)\n mr_rtm_dumproute+0x254/0x454 net/ipv4/ipmr_base.c:382\n ipmr_rtm_dumproute+0x248/0x4b4 net/ipv4/ipmr.c:2648\n rtnl_dump_all+0x2e4/0x4e8 net/core/rtnetlink.c:4327\n rtnl_dumpit+0x98/0x1d0 net/core/rtnetlink.c:6791\n netlink_dump+0x4f0/0xbc0 net/netlink/af_netlink.c:2317\n netlink_recvmsg+0x56c/0xe64 net/netlink/af_netlink.c:1973\n sock_recvmsg_nosec net/socket.c:1033 [inline]\n sock_recvmsg net/socket.c:1055 [inline]\n sock_read_iter+0x2d8/0x40c net/socket.c:1125\n new_sync_read fs/read_write.c:484 [inline]\n vfs_read+0x740/0x970 fs/read_write.c:565\n ksys_read+0x15c/0x26c fs/read_write.c:708\n\nFixes: cb167893f41e (\"net: Plumb support for filtering ipv4 and ipv6 multicast route dumps\")\nReported-by: syzbot+5cfae50c0e5f2c500013@syzkaller.appspotmail.com\nCloses: https://lore.kernel.org/netdev/678fe2d1.050a0220.15cac.00b3.GAE@google.com/T/#u\nSigned-off-by: Eric Dumazet \nReviewed-by: David Ahern \nLink: https://patch.msgid.link/20250121181241.841212-1-edumazet@google.com\nSigned-off-by: Jakub Kicinski ", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_164760/patch.diff b/tasks/csa159/pair_164760/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c1671c899cc5ba2e5a052b18f7ba5a7d7af5eb5a --- /dev/null +++ b/tasks/csa159/pair_164760/patch.diff @@ -0,0 +1,14 @@ +diff --git a/net/ipv4/ipmr_base.c b/net/ipv4/ipmr_base.c +index 03b6eee407a2..28d77d454d44 100644 +--- a/net/ipv4/ipmr_base.c ++++ b/net/ipv4/ipmr_base.c +@@ -330,9 +330,6 @@ int mr_table_dump(struct mr_table *mrt, struct sk_buff *skb, + list_for_each_entry(mfc, &mrt->mfc_unres_queue, list) { + if (e < s_e) + goto next_entry2; +- if (filter->dev && +- !mr_mfc_uses_dev(mrt, mfc, filter->dev)) +- goto next_entry2; + + err = fill(mrt, skb, NETLINK_CB(cb->skb).portid, + cb->nlh->nlmsg_seq, mfc, RTM_NEWROUTE, flags); \ No newline at end of file diff --git a/tasks/csa159/pair_164760/post_functions.txt b/tasks/csa159/pair_164760/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..29b93d3e82a485fede5b9d249814387c92358379 --- /dev/null +++ b/tasks/csa159/pair_164760/post_functions.txt @@ -0,0 +1,54 @@ +### File: net/ipv4/ipmr_base.c +```c +int mr_table_dump(struct mr_table *mrt, struct sk_buff *skb, + struct netlink_callback *cb, + int (*fill)(struct mr_table *mrt, struct sk_buff *skb, + u32 portid, u32 seq, struct mr_mfc *c, + int cmd, int flags), + spinlock_t *lock, struct fib_dump_filter *filter) +{ + unsigned int e = 0, s_e = cb->args[1]; + unsigned int flags = NLM_F_MULTI; + struct mr_mfc *mfc; + int err; + + if (filter->filter_set) + flags |= NLM_F_DUMP_FILTERED; + + list_for_each_entry_rcu(mfc, &mrt->mfc_cache_list, list, + lockdep_rtnl_is_held()) { + if (e < s_e) + goto next_entry; + if (filter->dev && + !mr_mfc_uses_dev(mrt, mfc, filter->dev)) + goto next_entry; + + err = fill(mrt, skb, NETLINK_CB(cb->skb).portid, + cb->nlh->nlmsg_seq, mfc, RTM_NEWROUTE, flags); + if (err < 0) + goto out; +next_entry: + e++; + } + + spin_lock_bh(lock); + list_for_each_entry(mfc, &mrt->mfc_unres_queue, list) { + if (e < s_e) + goto next_entry2; + + err = fill(mrt, skb, NETLINK_CB(cb->skb).portid, + cb->nlh->nlmsg_seq, mfc, RTM_NEWROUTE, flags); + if (err < 0) { + spin_unlock_bh(lock); + goto out; + } +next_entry2: + e++; + } + spin_unlock_bh(lock); + err = 0; +out: + cb->args[1] = e; + return err; +} +``` diff --git a/tasks/csa159/pair_164760/pre_functions.txt b/tasks/csa159/pair_164760/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..1daef140b73fdc142ea126c2aa5c47593e87ab77 --- /dev/null +++ b/tasks/csa159/pair_164760/pre_functions.txt @@ -0,0 +1,57 @@ +### File: net/ipv4/ipmr_base.c +```c +int mr_table_dump(struct mr_table *mrt, struct sk_buff *skb, + struct netlink_callback *cb, + int (*fill)(struct mr_table *mrt, struct sk_buff *skb, + u32 portid, u32 seq, struct mr_mfc *c, + int cmd, int flags), + spinlock_t *lock, struct fib_dump_filter *filter) +{ + unsigned int e = 0, s_e = cb->args[1]; + unsigned int flags = NLM_F_MULTI; + struct mr_mfc *mfc; + int err; + + if (filter->filter_set) + flags |= NLM_F_DUMP_FILTERED; + + list_for_each_entry_rcu(mfc, &mrt->mfc_cache_list, list, + lockdep_rtnl_is_held()) { + if (e < s_e) + goto next_entry; + if (filter->dev && + !mr_mfc_uses_dev(mrt, mfc, filter->dev)) + goto next_entry; + + err = fill(mrt, skb, NETLINK_CB(cb->skb).portid, + cb->nlh->nlmsg_seq, mfc, RTM_NEWROUTE, flags); + if (err < 0) + goto out; +next_entry: + e++; + } + + spin_lock_bh(lock); + list_for_each_entry(mfc, &mrt->mfc_unres_queue, list) { + if (e < s_e) + goto next_entry2; + if (filter->dev && + !mr_mfc_uses_dev(mrt, mfc, filter->dev)) + goto next_entry2; + + err = fill(mrt, skb, NETLINK_CB(cb->skb).portid, + cb->nlh->nlmsg_seq, mfc, RTM_NEWROUTE, flags); + if (err < 0) { + spin_unlock_bh(lock); + goto out; + } +next_entry2: + e++; + } + spin_unlock_bh(lock); + err = 0; +out: + cb->args[1] = e; + return err; +} +``` diff --git a/tasks/csa159/pair_164760/task_prompt.md b/tasks/csa159/pair_164760/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_164760/task_prompt.md @@ -0,0 +1,318 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` diff --git a/tasks/csa159/pair_164920/checker_template.cpp b/tasks/csa159/pair_164920/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_164920/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_164920/config.json b/tasks/csa159/pair_164920/config.json new file mode 100644 index 0000000000000000000000000000000000000000..c4cfca488a5d5787ee034c9bbe86e427a5705723 --- /dev/null +++ b/tasks/csa159/pair_164920/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "a47c397bb29fce1751dc755246a2c8deeca5e38f", + "after_commit": "7a6b1ab7475fd6478eeaf5c9d1163e7a18125c8f", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/c4681547bcce777daf576925a966ffa824edd09d/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/c4681547bcce777daf576925a966ffa824edd09d/compile_commands.json", + "changed_files": [ + "net/core/neighbour.c" + ], + "commit_message": "neighbour: allow NUD_NOARP entries to be forced GCed\n\nIFF_POINTOPOINT interfaces use NUD_NOARP entries for IPv6. It's possible to\nfill up the neighbour table with enough entries that it will overflow for\nvalid connections after that.\n\nThis behaviour is more prevalent after commit 58956317c8de (\"neighbor:\nImprove garbage collection\") is applied, as it prevents removal from\nentries that are not NUD_FAILED, unless they are more than 5s old.\n\nFixes: 58956317c8de (neighbor: Improve garbage collection)\nReported-by: Kasper Dupont \nSigned-off-by: Thadeu Lima de Souza Cascardo \nSigned-off-by: David Ahern \nSigned-off-by: David S. Miller ", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_164920/patch.diff b/tasks/csa159/pair_164920/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..52b609163daa259e964f6e56435d29119b62758d --- /dev/null +++ b/tasks/csa159/pair_164920/patch.diff @@ -0,0 +1,12 @@ +diff --git a/net/core/neighbour.c b/net/core/neighbour.c +index 98f20efbfadf..bf774575ad71 100644 +--- a/net/core/neighbour.c ++++ b/net/core/neighbour.c +@@ -238,6 +238,7 @@ static int neigh_forced_gc(struct neigh_table *tbl) + + write_lock(&n->lock); + if ((n->nud_state == NUD_FAILED) || ++ (n->nud_state == NUD_NOARP) || + (tbl->is_multicast && + tbl->is_multicast(n->primary_key)) || + time_after(tref, n->updated)) \ No newline at end of file diff --git a/tasks/csa159/pair_164920/post_functions.txt b/tasks/csa159/pair_164920/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..64bee768db89f1790b3ca6881482bde5f3ea1167 --- /dev/null +++ b/tasks/csa159/pair_164920/post_functions.txt @@ -0,0 +1,40 @@ +### File: net/core/neighbour.c +```c +static int neigh_forced_gc(struct neigh_table *tbl) +{ + int max_clean = atomic_read(&tbl->gc_entries) - tbl->gc_thresh2; + unsigned long tref = jiffies - 5 * HZ; + struct neighbour *n, *tmp; + int shrunk = 0; + + NEIGH_CACHE_STAT_INC(tbl, forced_gc_runs); + + write_lock_bh(&tbl->lock); + + list_for_each_entry_safe(n, tmp, &tbl->gc_list, gc_list) { + if (refcount_read(&n->refcnt) == 1) { + bool remove = false; + + write_lock(&n->lock); + if ((n->nud_state == NUD_FAILED) || + (n->nud_state == NUD_NOARP) || + (tbl->is_multicast && + tbl->is_multicast(n->primary_key)) || + time_after(tref, n->updated)) + remove = true; + write_unlock(&n->lock); + + if (remove && neigh_remove_one(n, tbl)) + shrunk++; + if (shrunk >= max_clean) + break; + } + } + + tbl->last_flush = jiffies; + + write_unlock_bh(&tbl->lock); + + return shrunk; +} +``` diff --git a/tasks/csa159/pair_164920/pre_functions.txt b/tasks/csa159/pair_164920/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..3e2f120ba6dafc1dbd79c8fd702bc53e7dc952dc --- /dev/null +++ b/tasks/csa159/pair_164920/pre_functions.txt @@ -0,0 +1,39 @@ +### File: net/core/neighbour.c +```c +static int neigh_forced_gc(struct neigh_table *tbl) +{ + int max_clean = atomic_read(&tbl->gc_entries) - tbl->gc_thresh2; + unsigned long tref = jiffies - 5 * HZ; + struct neighbour *n, *tmp; + int shrunk = 0; + + NEIGH_CACHE_STAT_INC(tbl, forced_gc_runs); + + write_lock_bh(&tbl->lock); + + list_for_each_entry_safe(n, tmp, &tbl->gc_list, gc_list) { + if (refcount_read(&n->refcnt) == 1) { + bool remove = false; + + write_lock(&n->lock); + if ((n->nud_state == NUD_FAILED) || + (tbl->is_multicast && + tbl->is_multicast(n->primary_key)) || + time_after(tref, n->updated)) + remove = true; + write_unlock(&n->lock); + + if (remove && neigh_remove_one(n, tbl)) + shrunk++; + if (shrunk >= max_clean) + break; + } + } + + tbl->last_flush = jiffies; + + write_unlock_bh(&tbl->lock); + + return shrunk; +} +``` diff --git a/tasks/csa159/pair_164920/task_prompt.md b/tasks/csa159/pair_164920/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..546a56a72aa34259745cf82a91986c1768246d32 --- /dev/null +++ b/tasks/csa159/pair_164920/task_prompt.md @@ -0,0 +1,381 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `control_flow` + +### Current failure diagnosis + +- The rollout failed the process-quality and hardcoding-free checks because the design embedded patch-specific context and did not provide a sufficiently general, rigorous implementation argument. +- Lexical parent lookup was treated as domination, while a whole-function AST scan collected assignments without proving that they reach the reclamation sink, occur before it, or define the guard value used there. +- The safety test was polarity-insensitive: `nud_state != NUD_NOARP`, negated tests, and arbitrary bit tests could suppress a report even though they exclude rather than admit NUD_NOARP. +- The analysis did not prove that the state predicate, flag definition, guard, and `neigh_remove_one` argument concern the same neighbour object. +- The stated consequence was overstated because multicast and age alternatives can still permit removal; the defect is absence of state-based eligibility for NUD_NOARP when the other alternatives are false. + +### Preserve from prior rollouts + +- The synthesized checker must compile successfully against the supplied CSA environment. +- Preserve successful differential validation: diagnostics must occur on the vulnerable source and disappear on the patched source. +- Preserve code verification and objective eligibility gate G6. +- Preserve an accepted or clean refinement outcome. +- Retain at least the previously adequate semantic score and CSA mechanism capability. +- Remain independent of patch anchors such as changed line numbers or diff locations. + +### Required semantic proof + +- Identify a reclamation call whose execution is control-dependent on a local eligibility value derived from predicates over a neighbour object's `nud_state`. +- Use CFG ordering and reaching-definition relationships to connect only definitions that can reach the sink guard before the sink; unrelated, overwritten, unreachable, or later assignments must not affect the result. +- Prove object identity between the neighbour passed to reclamation and the neighbour whose state is tested, accounting for casts and equivalent expression forms without conflating different objects. +- Interpret predicate polarity and Boolean structure so that only a positively effective NUD_NOARP alternative counts as coverage; inequality, negation, or a test on an excluding branch is not safe. +- Report when setting the relevant object to NUD_NOARP, with independent multicast and age alternatives false, cannot make the sink eligible through the state predicate. +- Suppress when a reachable definition governing the sink positively admits NUD_NOARP for that same object, as in the added equality disjunct. + +### Implementation constraints + +- Use a CSA callback that permits one enclosing-function analysis, such as `check::ASTCodeBody`, or a call callback paired with the enclosing `AnalysisDeclContext` CFG; do not rely solely on lexical ParentMap ancestry. +- Build explicit CFG control-dependence, dominance, statement-order, and reaching-definition checks between the eligibility definition, guard, and reclamation sink without introducing ProgramState tracking. +- Normalize relevant Boolean expressions through parentheses, implicit casts, logical operators, and unary negation before deciding whether NUD_NOARP is admitted or excluded. +- Resolve the state member, NUD_NOARP declaration/value, sink callee, flag declarations, and sink argument through AST declarations and expression identity rather than source-text matching. +- Emit one diagnostic at the controlling eligibility predicate or guarded reclamation operation, with a source range local to the proven relation. +- Keep scope project-general within neighbour reclamation semantics; do not restrict matching to `neigh_forced_gc`, a local variable name such as `remove`, a source path, a commit identifier, or a line number. +- Do not encode the patch as an exact token sequence or use the numeric value `0x40` as a substitute for establishing the NUD_NOARP semantic declaration. + +### Validation checklist + +- Compile the checker plugin and verify registration and loading with the supplied Clang Static Analyzer. +- Scan both supplied vulnerable inputs and confirm relevant diagnostics in `neigh_forced_gc`; scan both patched inputs and confirm zero diagnostics. +- Confirm diagnostics remain within the changed function and near the eligibility predicate or its guarded `neigh_remove_one` sink, with no warnings in non-patched functions. +- Verify that unconditional or state-independent `neigh_remove_one` calls are suppressed. +- Add refinements showing that positive `nud_state == NUD_NOARP` coverage suppresses while `nud_state != NUD_NOARP`, negated equality, and excluding branches do not. +- Add refinements with unrelated objects, assignments after the sink, unreachable assignments, and overwritten flag definitions; none may falsely establish safety. +- Add a refinement where NUD_NOARP coverage reaches the sink through an equivalent positively oriented guard and confirm suppression without requiring the exact patch spelling. +- Run code verification, differential cross-validation, hardcoding detection, and refinement evaluation, requiring G6 and an accepted or clean outcome. + +### Avoid and forbidden regressions + +- Do not reuse the failed lexical-parent plus unrestricted whole-function assignment scan as a substitute for CFG proof. +- Do not treat the mere presence of any NUD_NOARP comparison anywhere in the function as evidence that reclamation accepts that state. +- Do not classify inequality, polarity-reversed expressions, or arbitrary bitwise occurrence as a safe NUD_NOARP admission. +- Do not assume every NUD_NOARP entry is unconditionally unreclaimable; phrase the finding around missing state-based eligibility and resulting retention when other alternatives are false. +- Do not add path-sensitive ProgramState or interprocedural propagation when intraprocedural CFG analysis establishes the required relation. +- Do not embed patch prose, commit metadata, source locations, changed-function identity, or exact patched syntax in matching logic or checker-facing implementation metadata. diff --git a/tasks/csa159/pair_164974/checker_template.cpp b/tasks/csa159/pair_164974/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_164974/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_164974/config.json b/tasks/csa159/pair_164974/config.json new file mode 100644 index 0000000000000000000000000000000000000000..7e211c594576cf971f68e043f67dfa999a167b2f --- /dev/null +++ b/tasks/csa159/pair_164974/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "a902f3dec70a46332a8c99604de384fbabd734e5", + "after_commit": "31b62908693c90d4d07db597e685d9f25a120073", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/610a9b8f49fbcf1100716370d3b5f6f884a2835a/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/610a9b8f49fbcf1100716370d3b5f6f884a2835a/compile_commands.json", + "changed_files": [ + "net/sunrpc/xprtmultipath.c" + ], + "commit_message": "SUNRPC: Fix a suspicious RCU usage warning\n\nI received the following warning while running cthon against an ontap\nserver running pNFS:\n\n[ 57.202521] =============================\n[ 57.202522] WARNING: suspicious RCU usage\n[ 57.202523] 6.7.0-rc3-g2cc14f52aeb7 #41492 Not tainted\n[ 57.202525] -----------------------------\n[ 57.202525] net/sunrpc/xprtmultipath.c:349 RCU-list traversed in non-reader section!!\n[ 57.202527]\n other info that might help us debug this:\n\n[ 57.202528]\n rcu_scheduler_active = 2, debug_locks = 1\n[ 57.202529] no locks held by test5/3567.\n[ 57.202530]\n stack backtrace:\n[ 57.202532] CPU: 0 PID: 3567 Comm: test5 Not tainted 6.7.0-rc3-g2cc14f52aeb7 #41492 5b09971b4965c0aceba19f3eea324a4a806e227e\n[ 57.202534] Hardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS unknown 2/2/2022\n[ 57.202536] Call Trace:\n[ 57.202537] \n[ 57.202540] dump_stack_lvl+0x77/0xb0\n[ 57.202551] lockdep_rcu_suspicious+0x154/0x1a0\n[ 57.202556] rpc_xprt_switch_has_addr+0x17c/0x190 [sunrpc ebe02571b9a8ceebf7d98e71675af20c19bdb1f6]\n[ 57.202596] rpc_clnt_setup_test_and_add_xprt+0x50/0x180 [sunrpc ebe02571b9a8ceebf7d98e71675af20c19bdb1f6]\n[ 57.202621] ? rpc_clnt_add_xprt+0x254/0x300 [sunrpc ebe02571b9a8ceebf7d98e71675af20c19bdb1f6]\n[ 57.202646] rpc_clnt_add_xprt+0x27a/0x300 [sunrpc ebe02571b9a8ceebf7d98e71675af20c19bdb1f6]\n[ 57.202671] ? __pfx_rpc_clnt_setup_test_and_add_xprt+0x10/0x10 [sunrpc ebe02571b9a8ceebf7d98e71675af20c19bdb1f6]\n[ 57.202696] nfs4_pnfs_ds_connect+0x345/0x760 [nfsv4 c716d88496ded0ea6d289bbea684fa996f9b57a9]\n[ 57.202728] ? __pfx_nfs4_test_session_trunk+0x10/0x10 [nfsv4 c716d88496ded0ea6d289bbea684fa996f9b57a9]\n[ 57.202754] nfs4_fl_prepare_ds+0x75/0xc0 [nfs_layout_nfsv41_files e3a4187f18ae8a27b630f9feae6831b584a9360a]\n[ 57.202760] filelayout_write_pagelist+0x4a/0x200 [nfs_layout_nfsv41_files e3a4187f18ae8a27b630f9feae6831b584a9360a]\n[ 57.202765] pnfs_generic_pg_writepages+0xbe/0x230 [nfsv4 c716d88496ded0ea6d289bbea684fa996f9b57a9]\n[ 57.202788] __nfs_pageio_add_request+0x3fd/0x520 [nfs 6c976fa593a7c2976f5a0aeb4965514a828e6902]\n[ 57.202813] nfs_pageio_add_request+0x18b/0x390 [nfs 6c976fa593a7c2976f5a0aeb4965514a828e6902]\n[ 57.202831] nfs_do_writepage+0x116/0x1e0 [nfs 6c976fa593a7c2976f5a0aeb4965514a828e6902]\n[ 57.202849] nfs_writepages_callback+0x13/0x30 [nfs 6c976fa593a7c2976f5a0aeb4965514a828e6902]\n[ 57.202866] write_cache_pages+0x265/0x450\n[ 57.202870] ? __pfx_nfs_writepages_callback+0x10/0x10 [nfs 6c976fa593a7c2976f5a0aeb4965514a828e6902]\n[ 57.202891] nfs_writepages+0x141/0x230 [nfs 6c976fa593a7c2976f5a0aeb4965514a828e6902]\n[ 57.202913] do_writepages+0xd2/0x230\n[ 57.202917] ? filemap_fdatawrite_wbc+0x5c/0x80\n[ 57.202921] filemap_fdatawrite_wbc+0x67/0x80\n[ 57.202924] filemap_write_and_wait_range+0xd9/0x170\n[ 57.202930] nfs_wb_all+0x49/0x180 [nfs 6c976fa593a7c2976f5a0aeb4965514a828e6902]\n[ 57.202947] nfs4_file_flush+0x72/0xb0 [nfsv4 c716d88496ded0ea6d289bbea684fa996f9b57a9]\n[ 57.202969] __se_sys_close+0x46/0xd0\n[ 57.202972] do_syscall_64+0x68/0x100\n[ 57.202975] ? do_syscall_64+0x77/0x100\n[ 57.202976] ? do_syscall_64+0x77/0x100\n[ 57.202979] entry_SYSCALL_64_after_hwframe+0x6e/0x76\n[ 57.202982] RIP: 0033:0x7fe2b12e4a94\n[ 57.202985] Code: 00 f7 d8 64 89 01 48 83 c8 ff c3 66 2e 0f 1f 84 00 00 00 00 00 90 f3 0f 1e fa 80 3d d5 18 0e 00 00 74 13 b8 03 00 00 00 0f 05 <48> 3d 00 f0 ff ff 77 44 c3 0f 1f 00 48 83 ec 18 89 7c 24 0c e8 c3\n[ 57.202987] RSP: 002b:00007ffe857ddb38 EFLAGS: 00000202 ORIG_RAX: 0000000000000003\n[ 57.202989] RAX: ffffffffffffffda RBX: 00007ffe857dfd68 RCX: 00007fe2b12e4a94\n[ 57.202991] RDX: 0000000000002000 RSI: 00007ffe857ddc40 RDI: 0000000000000003\n[ 57.202992] RBP: 00007ffe857dfc50 R08: 7fffffffffffffff R09: 0000000065650f49\n[ 57.202993] R10: 00007fe2b11f8300 R11: 0000000000000202 R12: 0000000000000000\n[ 57.202994] R13: 00007ffe857dfd80 R14: 00007fe2b1445000 R15: 0000000000000000\n[ 57.202999] \n\nThe problem seems to be that two out of three callers aren't taking the\nrcu_read_lock() before calling the list_for_each_entry_rcu() function in\nrpc_xprt_switch_has_addr(). I fix this by having\nrpc_xprt_switch_has_addr() unconditionaly take the rcu_read_lock(),\nwhich is okay to do recursively in the case that the lock has already\nbeen taken by a caller.\n\nReviewed-by: Jeff Layton \nSigned-off-by: Anna Schumaker ", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_164974/patch.diff b/tasks/csa159/pair_164974/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0376104abc03fd042565e7f182efb8886cc8ea31 --- /dev/null +++ b/tasks/csa159/pair_164974/patch.diff @@ -0,0 +1,35 @@ +diff --git a/net/sunrpc/xprtmultipath.c b/net/sunrpc/xprtmultipath.c +index 701250b305db..0706575d9392 100644 +--- a/net/sunrpc/xprtmultipath.c ++++ b/net/sunrpc/xprtmultipath.c +@@ -336,8 +336,9 @@ struct rpc_xprt *xprt_iter_current_entry_offline(struct rpc_xprt_iter *xpi) + xprt_switch_find_current_entry_offline); + } + +-bool rpc_xprt_switch_has_addr(struct rpc_xprt_switch *xps, +- const struct sockaddr *sap) ++static ++bool __rpc_xprt_switch_has_addr(struct rpc_xprt_switch *xps, ++ const struct sockaddr *sap) + { + struct list_head *head; + struct rpc_xprt *pos; +@@ -356,6 +357,18 @@ bool rpc_xprt_switch_has_addr(struct rpc_xprt_switch *xps, + return false; + } + ++bool rpc_xprt_switch_has_addr(struct rpc_xprt_switch *xps, ++ const struct sockaddr *sap) ++{ ++ bool res; ++ ++ rcu_read_lock(); ++ res = __rpc_xprt_switch_has_addr(xps, sap); ++ rcu_read_unlock(); ++ ++ return res; ++} ++ + static + struct rpc_xprt *xprt_switch_find_next_entry(struct list_head *head, + const struct rpc_xprt *cur, bool check_active) \ No newline at end of file diff --git a/tasks/csa159/pair_164974/post_functions.txt b/tasks/csa159/pair_164974/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..13696c953002e4460280f09ba778bcb4ecc2a2d5 --- /dev/null +++ b/tasks/csa159/pair_164974/post_functions.txt @@ -0,0 +1,43 @@ +### File: net/sunrpc/xprtmultipath.c +```c +static +struct rpc_xprt *xprt_iter_current_entry_offline(struct rpc_xprt_iter *xpi) +{ + return _xprt_iter_current_entry(xpi, + xprt_switch_find_first_entry_offline, + xprt_switch_find_current_entry_offline); +} + +static +bool __rpc_xprt_switch_has_addr(struct rpc_xprt_switch *xps, + const struct sockaddr *sap) +{ + struct list_head *head; + struct rpc_xprt *pos; + + if (xps == NULL || sap == NULL) + return false; + + head = &xps->xps_xprt_list; + list_for_each_entry_rcu(pos, head, xprt_switch) { + if (rpc_cmp_addr_port(sap, (struct sockaddr *)&pos->addr)) { + pr_info("RPC: addr %s already in xprt switch\n", + pos->address_strings[RPC_DISPLAY_ADDR]); + return true; + } + } + return false; +} + +bool rpc_xprt_switch_has_addr(struct rpc_xprt_switch *xps, + const struct sockaddr *sap) +{ + bool res; + + rcu_read_lock(); + res = __rpc_xprt_switch_has_addr(xps, sap); + rcu_read_unlock(); + + return res; +} +``` diff --git a/tasks/csa159/pair_164974/pre_functions.txt b/tasks/csa159/pair_164974/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..6691814a1b22b0089b7dab4f35dcc6ce7826bfd2 --- /dev/null +++ b/tasks/csa159/pair_164974/pre_functions.txt @@ -0,0 +1,52 @@ +### File: net/sunrpc/xprtmultipath.c +```c +static +struct rpc_xprt *xprt_iter_current_entry_offline(struct rpc_xprt_iter *xpi) +{ + return _xprt_iter_current_entry(xpi, + xprt_switch_find_first_entry_offline, + xprt_switch_find_current_entry_offline); +} + +bool rpc_xprt_switch_has_addr(struct rpc_xprt_switch *xps, + const struct sockaddr *sap) +{ + struct list_head *head; + struct rpc_xprt *pos; + + if (xps == NULL || sap == NULL) + return false; + + head = &xps->xps_xprt_list; + list_for_each_entry_rcu(pos, head, xprt_switch) { + if (rpc_cmp_addr_port(sap, (struct sockaddr *)&pos->addr)) { + pr_info("RPC: addr %s already in xprt switch\n", + pos->address_strings[RPC_DISPLAY_ADDR]); + return true; + } + } + return false; +} + +static +struct rpc_xprt *xprt_switch_find_next_entry(struct list_head *head, + const struct rpc_xprt *cur, bool check_active) +{ + struct rpc_xprt *pos, *prev = NULL; + bool found = false; + + list_for_each_entry_rcu(pos, head, xprt_switch) { + if (cur == prev) + found = true; + /* for request to return active transports return only + * active, for request to return offline transports + * return only offline + */ + if (found && ((check_active && xprt_is_active(pos)) || + (!check_active && !xprt_is_active(pos)))) + return pos; + prev = pos; + } + return NULL; +} +``` diff --git a/tasks/csa159/pair_164974/task_prompt.md b/tasks/csa159/pair_164974/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..2815420752eb6dfd0b57dd31a5246c5660000cb8 --- /dev/null +++ b/tasks/csa159/pair_164974/task_prompt.md @@ -0,0 +1,370 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `syntax_only` + +### Current failure diagnosis + +- semantic_mechanism failed because path-sensitive RCULockDepth ProgramState tracking plus a static-versus-exported entry heuristic were judged overkill; the required relation is a same-function AST fact. +- refinement_accepted failed with outcome feedback_required after one round; the rollout never converged on an accepted mechanism. +- The prior design proved exploded-graph lock-state reachability even though absence of rcu_read_lock in the same non-static function as list_for_each_entry_rcu is visible from an AST walk. + +### Preserve from prior rollouts + +- Preserve successful compile, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve semantic score at or above the configured threshold. +- Preserve process quality at or above the configured threshold. +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Report when a non-static function body expands an RCU list-traversal macro (list_for_each_entry_rcu and documented friends) and does not itself contain an rcu_read_lock family call; that is the pre-patch rpc_xprt_switch_has_addr defect. +- Treat as safe when the traversal lives only in a static helper, or when the same function contains rcu_read_lock/rcu_read_lock_bh/rcu_read_lock_sched/rcu_read_lock_nested (post-patch: lock in the public wrapper, walk in static __rpc_xprt_switch_has_addr). +- Exported functions may be invoked without a held RCU read-side critical section; file-local helpers may rely on their callers and must not be treated as standalone defects. + +### Implementation constraints + +- Use an AST-body or AST-declaration callback over function definitions; do not register ProgramState traits or update lock nesting on exploded-graph paths. +- Detect RCU traversals by macro-expansion names (list_for_each_entry_rcu, list_for_each_entry_continue_rcu, list_for_each_entry_from_rcu, list_for_each_rcu, hlist_for_each_entry_rcu and documented friends) and lock acquisition by callee identifiers in the rcu_read_lock family. +- Emit the diagnostic at the traversal site inside non-static FunctionDecls only; suppress SC_Static helpers. +- Remain project_general for the Linux RCU list protocol; do not key checks off net/sunrpc/xprtmultipath.c, rpc_xprt_switch_has_addr, __rpc_xprt_switch_has_addr, or patch line numbers. +- If walking statements, use the loop-condition or macro-expansion location; these RCU macros need not appear as a ForStmt CFG node. + +### Validation checklist + +- Plugin compiles, registers, and keeps hard_validation passing. +- before_commit scan of net/sunrpc/xprtmultipath.c reports on non-static rpc_xprt_switch_has_addr at list_for_each_entry_rcu with N_buggy > 0. +- after_commit scan yields N_patched = 0 because the public wrapper contains rcu_read_lock without a traversal and the static helper is suppressed. +- No warning on pre-existing static helpers such as xprt_switch_find_next_entry that also expand list_for_each_entry_rcu. +- Reports stay in the patched function near the traversal; no unrelated disappeared diagnostics. +- Refinement must be accepted; semantic_mechanism must classify the checker as syntax_only rather than path-sensitive overkill. + +### Avoid and forbidden regressions + +- Do not reintroduce RCULockDepth, checkBeginFunction entry-depth seeding, checkPreCall lock/unlock counting, or checkBranchCondition sink reporting. +- Do not treat inlining or exploded-graph lock reachability as required for this instance. +- Do not emit reports on static RCU helpers whose callers are expected to hold rcu_read_lock. +- Do not drop compile, before/after, G6, anchor_free, or hardcoding_free invariants to chase mechanism score. diff --git a/tasks/csa159/pair_165542/checker_template.cpp b/tasks/csa159/pair_165542/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_165542/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_165542/config.json b/tasks/csa159/pair_165542/config.json new file mode 100644 index 0000000000000000000000000000000000000000..3b63351bc1f9329dcbebcaa56ccbc17893adf285 --- /dev/null +++ b/tasks/csa159/pair_165542/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "e3952fcce1aad934f1322843b564ff86256444b2", + "after_commit": "cc16eecae687912238ee6efbff71ad31e2bc414e", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/cfb92440ee71adcc2105b0890bb01ac3cddb8507/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/cfb92440ee71adcc2105b0890bb01ac3cddb8507/compile_commands.json", + "changed_files": [ + "fs/jbd2/transaction.c" + ], + "commit_message": "jbd2: fix use-after-free of transaction_t race\n\njbd2_journal_wait_updates() is called with j_state_lock held. But if\nthere is a commit in progress, then this transaction might get committed\nand freed via jbd2_journal_commit_transaction() ->\njbd2_journal_free_transaction(), when we release j_state_lock.\nSo check for journal->j_running_transaction everytime we release and\nacquire j_state_lock to avoid use-after-free issue.\n\nLink: https://lore.kernel.org/r/948c2fed518ae739db6a8f7f83f1d58b504f87d0.1644497105.git.ritesh.list@gmail.com\nFixes: 4f98186848707f53 (\"jbd2: refactor wait logic for transaction updates into a common function\")\nCc: stable@kernel.org\nReported-and-tested-by: syzbot+afa2ca5171d93e44b348@syzkaller.appspotmail.com\nReviewed-by: Jan Kara \nSigned-off-by: Ritesh Harjani \nSigned-off-by: Theodore Ts'o ", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_165542/patch.diff b/tasks/csa159/pair_165542/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..58a61f40e3d70b8f7a6922721a7c04d08976944b --- /dev/null +++ b/tasks/csa159/pair_165542/patch.diff @@ -0,0 +1,66 @@ +diff --git a/fs/jbd2/transaction.c b/fs/jbd2/transaction.c +index 8e2f8275a253..259e00046a8b 100644 +--- a/fs/jbd2/transaction.c ++++ b/fs/jbd2/transaction.c +@@ -842,27 +842,38 @@ EXPORT_SYMBOL(jbd2_journal_restart); + */ + void jbd2_journal_wait_updates(journal_t *journal) + { +- transaction_t *commit_transaction = journal->j_running_transaction; ++ DEFINE_WAIT(wait); + +- if (!commit_transaction) +- return; ++ while (1) { ++ /* ++ * Note that the running transaction can get freed under us if ++ * this transaction is getting committed in ++ * jbd2_journal_commit_transaction() -> ++ * jbd2_journal_free_transaction(). This can only happen when we ++ * release j_state_lock -> schedule() -> acquire j_state_lock. ++ * Hence we should everytime retrieve new j_running_transaction ++ * value (after j_state_lock release acquire cycle), else it may ++ * lead to use-after-free of old freed transaction. ++ */ ++ transaction_t *transaction = journal->j_running_transaction; + +- spin_lock(&commit_transaction->t_handle_lock); +- while (atomic_read(&commit_transaction->t_updates)) { +- DEFINE_WAIT(wait); ++ if (!transaction) ++ break; + ++ spin_lock(&transaction->t_handle_lock); + prepare_to_wait(&journal->j_wait_updates, &wait, +- TASK_UNINTERRUPTIBLE); +- if (atomic_read(&commit_transaction->t_updates)) { +- spin_unlock(&commit_transaction->t_handle_lock); +- write_unlock(&journal->j_state_lock); +- schedule(); +- write_lock(&journal->j_state_lock); +- spin_lock(&commit_transaction->t_handle_lock); ++ TASK_UNINTERRUPTIBLE); ++ if (!atomic_read(&transaction->t_updates)) { ++ spin_unlock(&transaction->t_handle_lock); ++ finish_wait(&journal->j_wait_updates, &wait); ++ break; + } ++ spin_unlock(&transaction->t_handle_lock); ++ write_unlock(&journal->j_state_lock); ++ schedule(); + finish_wait(&journal->j_wait_updates, &wait); ++ write_lock(&journal->j_state_lock); + } +- spin_unlock(&commit_transaction->t_handle_lock); + } + + /** +@@ -877,8 +888,6 @@ void jbd2_journal_wait_updates(journal_t *journal) + */ + void jbd2_journal_lock_updates(journal_t *journal) + { +- DEFINE_WAIT(wait); +- + jbd2_might_wait_for_commit(journal); + + write_lock(&journal->j_state_lock); \ No newline at end of file diff --git a/tasks/csa159/pair_165542/post_functions.txt b/tasks/csa159/pair_165542/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..ee114b2d3189300f9df40b52c4669d91168b8268 --- /dev/null +++ b/tasks/csa159/pair_165542/post_functions.txt @@ -0,0 +1,38 @@ +### File: fs/jbd2/transaction.c +```c +void jbd2_journal_wait_updates(journal_t *journal) +{ + DEFINE_WAIT(wait); + + while (1) { + /* + * Note that the running transaction can get freed under us if + * this transaction is getting committed in + * jbd2_journal_commit_transaction() -> + * jbd2_journal_free_transaction(). This can only happen when we + * release j_state_lock -> schedule() -> acquire j_state_lock. + * Hence we should everytime retrieve new j_running_transaction + * value (after j_state_lock release acquire cycle), else it may + * lead to use-after-free of old freed transaction. + */ + transaction_t *transaction = journal->j_running_transaction; + + if (!transaction) + break; + + spin_lock(&transaction->t_handle_lock); + prepare_to_wait(&journal->j_wait_updates, &wait, + TASK_UNINTERRUPTIBLE); + if (!atomic_read(&transaction->t_updates)) { + spin_unlock(&transaction->t_handle_lock); + finish_wait(&journal->j_wait_updates, &wait); + break; + } + spin_unlock(&transaction->t_handle_lock); + write_unlock(&journal->j_state_lock); + schedule(); + finish_wait(&journal->j_wait_updates, &wait); + write_lock(&journal->j_state_lock); + } +} +``` diff --git a/tasks/csa159/pair_165542/pre_functions.txt b/tasks/csa159/pair_165542/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..6deadfd0b8b1852a1f97d131c4f2056b684e8dad --- /dev/null +++ b/tasks/csa159/pair_165542/pre_functions.txt @@ -0,0 +1,58 @@ +### File: fs/jbd2/transaction.c +```c +void jbd2_journal_wait_updates(journal_t *journal) +{ + transaction_t *commit_transaction = journal->j_running_transaction; + + if (!commit_transaction) + return; + + spin_lock(&commit_transaction->t_handle_lock); + while (atomic_read(&commit_transaction->t_updates)) { + DEFINE_WAIT(wait); + + prepare_to_wait(&journal->j_wait_updates, &wait, + TASK_UNINTERRUPTIBLE); + if (atomic_read(&commit_transaction->t_updates)) { + spin_unlock(&commit_transaction->t_handle_lock); + write_unlock(&journal->j_state_lock); + schedule(); + write_lock(&journal->j_state_lock); + spin_lock(&commit_transaction->t_handle_lock); + } + finish_wait(&journal->j_wait_updates, &wait); + } + spin_unlock(&commit_transaction->t_handle_lock); +} + +void jbd2_journal_lock_updates(journal_t *journal) +{ + DEFINE_WAIT(wait); + + jbd2_might_wait_for_commit(journal); + + write_lock(&journal->j_state_lock); + ++journal->j_barrier_count; + + /* Wait until there are no reserved handles */ + if (atomic_read(&journal->j_reserved_credits)) { + write_unlock(&journal->j_state_lock); + wait_event(journal->j_wait_reserved, + atomic_read(&journal->j_reserved_credits) == 0); + write_lock(&journal->j_state_lock); + } + + /* Wait until there are no running t_updates */ + jbd2_journal_wait_updates(journal); + + write_unlock(&journal->j_state_lock); + + /* + * We have now established a barrier against other normal updates, but + * we also need to barrier against other jbd2_journal_lock_updates() calls + * to make sure that we serialise special journal-locked operations + * too. + */ + mutex_lock(&journal->j_barrier); +} +``` diff --git a/tasks/csa159/pair_165542/task_prompt.md b/tasks/csa159/pair_165542/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..bd7b79ea0e167566d38bd52e63972a6327a63d43 --- /dev/null +++ b/tasks/csa159/pair_165542/task_prompt.md @@ -0,0 +1,382 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `path_sensitive` + +### Current failure diagnosis + +- The rollout proved the syntactic sequence of memory load, blocking call, and later dereference, but did not prove that synchronization or ownership protection had been relinquished so that the pointee could actually be freed. +- Treating every memory-loaded local pointer as stale after any classified blocking call was semantically broader than the CVE and exposed false-positive risk for pointers protected by a live lock, reference, or refcount. +- The refinement round ended with feedback_required, so the proposed scope and transfer rules were not accepted as clean or converged. +- Process quality remained below threshold because project scans were repeated after parse failures without resolving the missing-header or invalid-flag environment, even though later harness validation supplied successful differential evidence. +- The 10-before and 0-after result demonstrated patch discrimination, but patch discrimination alone did not establish the use-after-free root cause required by semantic_mechanism. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve semantic score at or above the configured threshold. +- Do not introduce dependence on changed lines, patch anchors, or diagnostic proximity to the patch. +- Do not introduce patch-local hardcoding such as jbd2 function, field, type, file, or line names. + +### Required semantic proof + +- Track a pointer value loaded from shared mutable memory and retain its identity through relevant local copies along an analyzed execution path. +- Establish that the protection relevant to that shared pointer is relinquished before a scheduling or blocking operation, creating the concurrency window identified by the patch evidence. +- Require a feasible path from the original load through the protection-release and scheduling window to a dereference of the same cached value. +- Report only when no reload from the shared memory location replaces the cached value after the last qualifying scheduling window and before the dereference on that path. +- Treat a reload after the release-schedule-reacquire cycle as the safety operation demonstrated by the patched loop. +- Exclude cases where path evidence shows that protection or a live ownership/reference guarantee remains effective across the blocking operation. + +### Implementation constraints + +- Use path-sensitive CSA callbacks and ProgramState traits to represent cached-value origin, relevant protection or ownership status, exposure to a qualifying scheduling window, and replacement by reload. +- Model assignments and initializers through bind or equivalent expression-value events so facts follow the pointer value through local copies and are killed when overwritten by an unrelated value. +- Observe direct scheduling/blocking calls and relevant protection transitions in statement callbacks; do not mark every live pointer stale merely because a function contains a blocking call. +- Recognize dereference sinks including member access through a pointer, unary dereference, array subscripting, and address-taking of a member used in call arguments. +- Keep the analysis intraprocedural unless the required event is directly represented in the current exploded path; do not claim a callee-side free has been proven when only a generic call name was observed. +- Emit a path-sensitive report at the stale dereference, with supporting load and qualifying scheduling-window events when CSA path diagnostics can represent them. +- Keep scope project-general by using semantic AST types, regions, symbols, and documented kernel synchronization or scheduling APIs rather than patch-specific identifiers. + +### Validation checklist + +- Build the fresh checker plugin successfully against the supplied Clang Static Analyzer API and verify registration under the intended checker name. +- Resolve the project parsing environment before scanning; confirm both supplied source versions are analyzed with no skipped files or compile errors. +- Scan the vulnerable source and require diagnostics for the stale transaction value that survives the lock-release and schedule cycle to the later dereference. +- Scan the patched source and require no diagnostic because each loop iteration reloads j_running_transaction after the prior scheduling cycle. +- Verify the primary diagnostic is located at the stale dereference in jbd2_journal_wait_updates, with load and scheduling-window events represented as supporting path context rather than separate warnings. +- Add focused cases for no blocking call, reload after blocking, unrelated overwrite, local or parameter origin, local-copy propagation, and dereferences nested in call arguments. +- Add refinement cases where a lock or live reference remains protective across a wait and require no report, addressing the semantic false-positive concern. +- Re-run differential and code verification and retain the observed eligibility properties: vulnerable presence, patched cleanliness, relevant disappearance, and no unrelated disappearance. + +### Avoid and forbidden regressions + +- Do not repeat a function-wide AST or CFG may-analysis that marks all cached pointers crossed after any blocking primitive without path-specific protection evidence. +- Do not equate sleeping or scheduling by itself with proof that an arbitrary pointee can be freed. +- Do not use diagnostic disappearance in the patched revision as a substitute for proving pointer identity, exposure, and missing reload. +- Do not report at the load, lock operation, or blocking call when the vulnerability manifests at the later stale dereference. +- Do not infer safety from a reload on only some alternate path; the analyzed reporting path must still carry the old value to the sink. +- Do not broaden scheduling primitive lists or exclude APIs solely to tune this patch's warning count. +- Do not repeat scans after parser failure without first correcting and verifying the compilation flags and header environment. +- Do not rely on the prior checker implementation as an artifact to edit, repair, resume, reconstruct, or copy. diff --git a/tasks/csa159/pair_165550/checker_template.cpp b/tasks/csa159/pair_165550/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_165550/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_165550/config.json b/tasks/csa159/pair_165550/config.json new file mode 100644 index 0000000000000000000000000000000000000000..9ef434ae892d134a4d62ebd38e844d73d5b9cc6e --- /dev/null +++ b/tasks/csa159/pair_165550/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "e48e99b6edf41c69c5528aa7ffb2daf3c59ee105", + "after_commit": "0405d4b63d082861f4eaff9d39c78ee9dc34f845", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/1e7857b28020ba57ca7fdafae7ac855ba326c697/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/1e7857b28020ba57ca7fdafae7ac855ba326c697/compile_commands.json", + "changed_files": [ + "fs/isofs/export.c" + ], + "commit_message": "isofs: Prevent the use of too small fid\n\nsyzbot reported a slab-out-of-bounds Read in isofs_fh_to_parent. [1]\n\nThe handle_bytes value passed in by the reproducing program is equal to 12.\nIn handle_to_path(), only 12 bytes of memory are allocated for the structure\nfile_handle->f_handle member, which causes an out-of-bounds access when\naccessing the member parent_block of the structure isofs_fid in isofs,\nbecause accessing parent_block requires at least 16 bytes of f_handle.\nHere, fh_len is used to indirectly confirm that the value of handle_bytes\nis greater than 3 before accessing parent_block.\n\n[1]\nBUG: KASAN: slab-out-of-bounds in isofs_fh_to_parent+0x1b8/0x210 fs/isofs/export.c:183\nRead of size 4 at addr ffff0000cc030d94 by task syz-executor215/6466\nCPU: 1 UID: 0 PID: 6466 Comm: syz-executor215 Not tainted 6.14.0-rc7-syzkaller-ga2392f333575 #0\nHardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 02/12/2025\nCall trace:\n show_stack+0x2c/0x3c arch/arm64/kernel/stacktrace.c:466 (C)\n __dump_stack lib/dump_stack.c:94 [inline]\n dump_stack_lvl+0xe4/0x150 lib/dump_stack.c:120\n print_address_description mm/kasan/report.c:408 [inline]\n print_report+0x198/0x550 mm/kasan/report.c:521\n kasan_report+0xd8/0x138 mm/kasan/report.c:634\n __asan_report_load4_noabort+0x20/0x2c mm/kasan/report_generic.c:380\n isofs_fh_to_parent+0x1b8/0x210 fs/isofs/export.c:183\n exportfs_decode_fh_raw+0x2dc/0x608 fs/exportfs/expfs.c:523\n do_handle_to_path+0xa0/0x198 fs/fhandle.c:257\n handle_to_path fs/fhandle.c:385 [inline]\n do_handle_open+0x8cc/0xb8c fs/fhandle.c:403\n __do_sys_open_by_handle_at fs/fhandle.c:443 [inline]\n __se_sys_open_by_handle_at fs/fhandle.c:434 [inline]\n __arm64_sys_open_by_handle_at+0x80/0x94 fs/fhandle.c:434\n __invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]\n invoke_syscall+0x98/0x2b8 arch/arm64/kernel/syscall.c:49\n el0_svc_common+0x130/0x23c arch/arm64/kernel/syscall.c:132\n do_el0_svc+0x48/0x58 arch/arm64/kernel/syscall.c:151\n el0_svc+0x54/0x168 arch/arm64/kernel/entry-common.c:744\n el0t_64_sync_handler+0x84/0x108 arch/arm64/kernel/entry-common.c:762\n el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:600\n\nAllocated by task 6466:\n kasan_save_stack mm/kasan/common.c:47 [inline]\n kasan_save_track+0x40/0x78 mm/kasan/common.c:68\n kasan_save_alloc_info+0x40/0x50 mm/kasan/generic.c:562\n poison_kmalloc_redzone mm/kasan/common.c:377 [inline]\n __kasan_kmalloc+0xac/0xc4 mm/kasan/common.c:394\n kasan_kmalloc include/linux/kasan.h:260 [inline]\n __do_kmalloc_node mm/slub.c:4294 [inline]\n __kmalloc_noprof+0x32c/0x54c mm/slub.c:4306\n kmalloc_noprof include/linux/slab.h:905 [inline]\n handle_to_path fs/fhandle.c:357 [inline]\n do_handle_open+0x5a4/0xb8c fs/fhandle.c:403\n __do_sys_open_by_handle_at fs/fhandle.c:443 [inline]\n __se_sys_open_by_handle_at fs/fhandle.c:434 [inline]\n __arm64_sys_open_by_handle_at+0x80/0x94 fs/fhandle.c:434\n __invoke_syscall arch/arm64/kernel/syscall.c:35 [inline]\n invoke_syscall+0x98/0x2b8 arch/arm64/kernel/syscall.c:49\n el0_svc_common+0x130/0x23c arch/arm64/kernel/syscall.c:132\n do_el0_svc+0x48/0x58 arch/arm64/kernel/syscall.c:151\n el0_svc+0x54/0x168 arch/arm64/kernel/entry-common.c:744\n el0t_64_sync_handler+0x84/0x108 arch/arm64/kernel/entry-common.c:762\n el0t_64_sync+0x198/0x19c arch/arm64/kernel/entry.S:600\n\nReported-by: syzbot+4d7cd7dd0ce1aa8d5c65@syzkaller.appspotmail.com\nCloses: https://syzkaller.appspot.com/bug?extid=4d7cd7dd0ce1aa8d5c65\nTested-by: syzbot+4d7cd7dd0ce1aa8d5c65@syzkaller.appspotmail.com\nCC: stable@vger.kernel.org\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nSigned-off-by: Edward Adam Davis \nSigned-off-by: Jan Kara \nLink: https://patch.msgid.link/tencent_9C8CB8A7E7C6C512C7065DC98B6EDF6EC606@qq.com", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_165550/patch.diff b/tasks/csa159/pair_165550/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c449229893c34bd62ef279afa1df9fa629fa49da --- /dev/null +++ b/tasks/csa159/pair_165550/patch.diff @@ -0,0 +1,13 @@ +diff --git a/fs/isofs/export.c b/fs/isofs/export.c +index 35768a63fb1d..421d247fae52 100644 +--- a/fs/isofs/export.c ++++ b/fs/isofs/export.c +@@ -180,7 +180,7 @@ static struct dentry *isofs_fh_to_parent(struct super_block *sb, + return NULL; + + return isofs_export_iget(sb, +- fh_len > 2 ? ifid->parent_block : 0, ++ fh_len > 3 ? ifid->parent_block : 0, + ifid->parent_offset, + fh_len > 4 ? ifid->parent_generation : 0); + } \ No newline at end of file diff --git a/tasks/csa159/pair_165550/post_functions.txt b/tasks/csa159/pair_165550/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..1a7d27461404a3402ee298e2caa3a3324c1d8abd --- /dev/null +++ b/tasks/csa159/pair_165550/post_functions.txt @@ -0,0 +1,16 @@ +### File: fs/isofs/export.c +```c +static struct dentry *isofs_fh_to_parent(struct super_block *sb, + struct fid *fid, int fh_len, int fh_type) +{ + struct isofs_fid *ifid = (struct isofs_fid *)fid; + + if (fh_len < 2 || fh_type != 2) + return NULL; + + return isofs_export_iget(sb, + fh_len > 3 ? ifid->parent_block : 0, + ifid->parent_offset, + fh_len > 4 ? ifid->parent_generation : 0); +} +``` diff --git a/tasks/csa159/pair_165550/pre_functions.txt b/tasks/csa159/pair_165550/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2563c8679cba500c3b376e028b6c36fb81137c63 --- /dev/null +++ b/tasks/csa159/pair_165550/pre_functions.txt @@ -0,0 +1,16 @@ +### File: fs/isofs/export.c +```c +static struct dentry *isofs_fh_to_parent(struct super_block *sb, + struct fid *fid, int fh_len, int fh_type) +{ + struct isofs_fid *ifid = (struct isofs_fid *)fid; + + if (fh_len < 2 || fh_type != 2) + return NULL; + + return isofs_export_iget(sb, + fh_len > 2 ? ifid->parent_block : 0, + ifid->parent_offset, + fh_len > 4 ? ifid->parent_generation : 0); +} +``` diff --git a/tasks/csa159/pair_165550/task_prompt.md b/tasks/csa159/pair_165550/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_165550/task_prompt.md @@ -0,0 +1,318 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` diff --git a/tasks/csa159/pair_165655/checker_template.cpp b/tasks/csa159/pair_165655/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_165655/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_165655/config.json b/tasks/csa159/pair_165655/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d62e91cae6fbc9780292693c943f5d0a3a47428f --- /dev/null +++ b/tasks/csa159/pair_165655/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "ef5621758a02fe8178de9d0df414ffb79463ff86", + "after_commit": "87507bcb4f5de16bb419e9509d874f4db6c0ad0f", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/32346491ddf24599decca06190ebca03ff9de7f8/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/32346491ddf24599decca06190ebca03ff9de7f8/compile_commands.json", + "changed_files": [ + "net/ipv4/fib_semantics.c" + ], + "commit_message": "ipv4: Fix a data-race around sysctl_fib_multipath_use_neigh.\n\nWhile reading sysctl_fib_multipath_use_neigh, it can be changed\nconcurrently. Thus, we need to add READ_ONCE() to its reader.\n\nFixes: a6db4494d218 (\"net: ipv4: Consider failed nexthops in multipath routes\")\nSigned-off-by: Kuniyuki Iwashima \nSigned-off-by: David S. Miller ", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_165655/patch.diff b/tasks/csa159/pair_165655/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..fcabf01c0ead3ea8e574a3c3ef0ff6563d08dae6 --- /dev/null +++ b/tasks/csa159/pair_165655/patch.diff @@ -0,0 +1,13 @@ +diff --git a/net/ipv4/fib_semantics.c b/net/ipv4/fib_semantics.c +index d9fdcbae16ee..db7b2503f068 100644 +--- a/net/ipv4/fib_semantics.c ++++ b/net/ipv4/fib_semantics.c +@@ -2216,7 +2216,7 @@ void fib_select_multipath(struct fib_result *res, int hash) + } + + change_nexthops(fi) { +- if (net->ipv4.sysctl_fib_multipath_use_neigh) { ++ if (READ_ONCE(net->ipv4.sysctl_fib_multipath_use_neigh)) { + if (!fib_good_nh(nexthop_nh)) + continue; + if (!first) { \ No newline at end of file diff --git a/tasks/csa159/pair_165655/post_functions.txt b/tasks/csa159/pair_165655/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..593d33dfcce05cb80474fb9d0c53839b0bd5335f --- /dev/null +++ b/tasks/csa159/pair_165655/post_functions.txt @@ -0,0 +1,33 @@ +### File: net/ipv4/fib_semantics.c +```c +void fib_select_multipath(struct fib_result *res, int hash) +{ + struct fib_info *fi = res->fi; + struct net *net = fi->fib_net; + bool first = false; + + if (unlikely(res->fi->nh)) { + nexthop_path_fib_result(res, hash); + return; + } + + change_nexthops(fi) { + if (READ_ONCE(net->ipv4.sysctl_fib_multipath_use_neigh)) { + if (!fib_good_nh(nexthop_nh)) + continue; + if (!first) { + res->nh_sel = nhsel; + res->nhc = &nexthop_nh->nh_common; + first = true; + } + } + + if (hash > atomic_read(&nexthop_nh->fib_nh_upper_bound)) + continue; + + res->nh_sel = nhsel; + res->nhc = &nexthop_nh->nh_common; + return; + } endfor_nexthops(fi); +} +``` diff --git a/tasks/csa159/pair_165655/pre_functions.txt b/tasks/csa159/pair_165655/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..cd6ccad2448742e14850f517dd398e3fbece8269 --- /dev/null +++ b/tasks/csa159/pair_165655/pre_functions.txt @@ -0,0 +1,33 @@ +### File: net/ipv4/fib_semantics.c +```c +void fib_select_multipath(struct fib_result *res, int hash) +{ + struct fib_info *fi = res->fi; + struct net *net = fi->fib_net; + bool first = false; + + if (unlikely(res->fi->nh)) { + nexthop_path_fib_result(res, hash); + return; + } + + change_nexthops(fi) { + if (net->ipv4.sysctl_fib_multipath_use_neigh) { + if (!fib_good_nh(nexthop_nh)) + continue; + if (!first) { + res->nh_sel = nhsel; + res->nhc = &nexthop_nh->nh_common; + first = true; + } + } + + if (hash > atomic_read(&nexthop_nh->fib_nh_upper_bound)) + continue; + + res->nh_sel = nhsel; + res->nhc = &nexthop_nh->nh_common; + return; + } endfor_nexthops(fi); +} +``` diff --git a/tasks/csa159/pair_165655/task_prompt.md b/tasks/csa159/pair_165655/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..f5b5d67b936f21c615ba61441956bfbec152203e --- /dev/null +++ b/tasks/csa159/pair_165655/task_prompt.md @@ -0,0 +1,380 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `control_flow` + +### Current failure diagnosis + +- Refinement was not accepted because the prior semantic rationale remained partial despite successful compilation and differential validation. +- A sysctl_ field-name prefix alone does not prove that a field is shared and concurrently writable, so the rollout could diagnose ordinary fields for which no race is possible. +- Volatile qualification was treated as equivalent to READ_ONCE protection, but the evidence states that volatile does not generally provide READ_ONCE concurrency semantics. +- The successful before/after result established correlation with the patch but did not by itself prove the full vulnerable read, concurrent-write, and missing-protection relation. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve at least the previously adequate CSA mechanism level; the new control-flow design must not reduce the decision procedure to weaker patch matching. +- Preserve the semantic score at or above the configured threshold. +- Preserve process quality at or above the configured threshold. +- Remain independent of patch anchors. +- Remain free of patch-local hardcoding. + +### Required semantic proof + +- Establish that an evaluated load of a kernel sysctl-backed shared field is reachable and controls or contributes to behavior in the analyzed function. +- Require evidence stronger than the sysctl_ prefix alone that the field represents a concurrently writable sysctl knob. +- Establish that the relevant load is not governed by READ_ONCE or an equivalent kernel one-access read annotation in its macro-expansion ancestry. +- Do not classify a read as safe solely because its lvalue type is volatile-qualified. +- Exclude pure write destinations from the read-side report while preserving reads embedded in compound, conditional, or otherwise evaluated expressions. + +### Implementation constraints + +- Use a CSA statement callback that observes evaluated MemberExpr reads, with CFG reachability or an equivalent control-flow relationship used before reporting. +- Use Clang AST declarations and SourceManager/Lexer macro-expansion APIs rather than source-text substring matching. +- Classify read versus write context structurally, accounting for parentheses, implicit casts, compound assignments, increments, and nested expressions rather than checking only an immediate plain-assignment parent. +- Emit the diagnostic at the vulnerable field load and attach its source range; do not report at a function entry, macro definition, or unrelated control-flow node. +- Keep analysis project-general without embedding fib_select_multipath, sysctl_fib_multipath_use_neigh, fib_semantics.c, changed line numbers, or diff literals. +- Do not rely on ProgramState to simulate cross-CPU interleavings that are not represented in the analyzed execution path. +- Use only concurrency evidence observable from the supplied kernel source and preprocessing structure; do not infer concurrent writability from naming convention alone. + +### Validation checklist + +- Compile the checker as a loadable CSA plugin with the target Clang analyzer API and verify registration succeeds. +- Scan the vulnerable source and confirm diagnostics are produced for the reachable plain load in fib_select_multipath. +- Scan the patched source and confirm the READ_ONCE-wrapped load produces no diagnostic. +- Confirm every vulnerable diagnostic is located on the field access at the changed statement and that no warning appears outside the patched function in the paired scan. +- Add a relevant negative case showing that an unrelated sysctl_-prefixed field without evidence of concurrent sysctl backing is not reported. +- Add a negative case showing that a READ_ONCE-protected read through nested macro-argument expansion is recognized. +- Add a refinement case showing that bare volatile qualification does not automatically suppress an otherwise proven unsafe read. +- Add read/write-context cases covering plain assignment, compound assignment, increment, and a field read used in a branch condition. + +### Avoid and forbidden regressions + +- Do not restore the blanket rule that every sysctl_-prefixed FieldDecl is necessarily shared and concurrently writable. +- Do not use volatile qualification as a general substitute for READ_ONCE or as an unconditional safety exemption. +- Do not treat before/after warning disappearance alone as proof that all emitted reports represent real races. +- Do not match raw source text, filenames, function names, the patched field name, line numbers, or nearby patch tokens. +- Do not report unevaluated references or pure store destinations as vulnerable reads. +- Do not claim that single-path symbolic execution observes the concurrent writer or cross-CPU interleaving. diff --git a/tasks/csa159/pair_165738/checker_template.cpp b/tasks/csa159/pair_165738/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_165738/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_165738/config.json b/tasks/csa159/pair_165738/config.json new file mode 100644 index 0000000000000000000000000000000000000000..aaf7568c469fa8d19150a321c80dd894d78cbaab --- /dev/null +++ b/tasks/csa159/pair_165738/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "f6837f34a34973ef6600c08195ed300e24e97317", + "after_commit": "504fa212d7030fb1c042290dc2eb92b21515573a", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/b7bfaa761d760e72a969d116517eaa12e404c262/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/b7bfaa761d760e72a969d116517eaa12e404c262/compile_commands.json", + "changed_files": [ + "drivers/base/dd.c" + ], + "commit_message": "driver core: Make driver_deferred_probe_timeout a static variable\n\nIt is not used outside of its compilation unit, so there's no need to\nexport this variable.\n\nSigned-off-by: Javier Martinez Canillas \nReviewed-by: Andrew Halaney \nAcked-by: John Stultz \nLink: https://lore.kernel.org/r/20221227232152.3094584-1-javierm@redhat.com\nSigned-off-by: Greg Kroah-Hartman ", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_165738/patch.diff b/tasks/csa159/pair_165738/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..05c3fffb63eb9aa0d46112058131c28a773c5c15 --- /dev/null +++ b/tasks/csa159/pair_165738/patch.diff @@ -0,0 +1,32 @@ +diff --git a/drivers/base/dd.c b/drivers/base/dd.c +index e9b2f9c25efe..69daf9d414eb 100644 +--- a/drivers/base/dd.c ++++ b/drivers/base/dd.c +@@ -257,13 +257,11 @@ static int deferred_devs_show(struct seq_file *s, void *data) + DEFINE_SHOW_ATTRIBUTE(deferred_devs); + + #ifdef CONFIG_MODULES +-int driver_deferred_probe_timeout = 10; ++static int driver_deferred_probe_timeout = 10; + #else +-int driver_deferred_probe_timeout; ++static int driver_deferred_probe_timeout; + #endif + +-EXPORT_SYMBOL_GPL(driver_deferred_probe_timeout); +- + static int __init deferred_probe_timeout_setup(char *str) + { + int timeout; +diff --git a/include/linux/device/driver.h b/include/linux/device/driver.h +index 2114d65b862f..50d0a416a5e7 100644 +--- a/include/linux/device/driver.h ++++ b/include/linux/device/driver.h +@@ -240,7 +240,6 @@ driver_find_device_by_acpi_dev(struct device_driver *drv, const void *adev) + } + #endif + +-extern int driver_deferred_probe_timeout; + void driver_deferred_probe_add(struct device *dev); + int driver_deferred_probe_check_state(struct device *dev); + void driver_init(void); \ No newline at end of file diff --git a/tasks/csa159/pair_165738/post_functions.txt b/tasks/csa159/pair_165738/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..17eef118506a32c0f0fa6391398e9faa6b2d5395 --- /dev/null +++ b/tasks/csa159/pair_165738/post_functions.txt @@ -0,0 +1,26 @@ +### File: drivers/base/dd.c +```c +static int deferred_devs_show(struct seq_file *s, void *data) +{ + struct device_private *curr; + + mutex_lock(&deferred_probe_mutex); + + list_for_each_entry(curr, &deferred_probe_pending_list, deferred_probe) + seq_printf(s, "%s\t%s", dev_name(curr->device), + curr->device->p->deferred_probe_reason ?: "\n"); + + mutex_unlock(&deferred_probe_mutex); + + return 0; +} + +static int __init deferred_probe_timeout_setup(char *str) +{ + int timeout; + + if (!kstrtoint(str, 10, &timeout)) + driver_deferred_probe_timeout = timeout; + return 1; +} +``` diff --git a/tasks/csa159/pair_165738/pre_functions.txt b/tasks/csa159/pair_165738/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..17eef118506a32c0f0fa6391398e9faa6b2d5395 --- /dev/null +++ b/tasks/csa159/pair_165738/pre_functions.txt @@ -0,0 +1,26 @@ +### File: drivers/base/dd.c +```c +static int deferred_devs_show(struct seq_file *s, void *data) +{ + struct device_private *curr; + + mutex_lock(&deferred_probe_mutex); + + list_for_each_entry(curr, &deferred_probe_pending_list, deferred_probe) + seq_printf(s, "%s\t%s", dev_name(curr->device), + curr->device->p->deferred_probe_reason ?: "\n"); + + mutex_unlock(&deferred_probe_mutex); + + return 0; +} + +static int __init deferred_probe_timeout_setup(char *str) +{ + int timeout; + + if (!kstrtoint(str, 10, &timeout)) + driver_deferred_probe_timeout = timeout; + return 1; +} +``` diff --git a/tasks/csa159/pair_165738/task_prompt.md b/tasks/csa159/pair_165738/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..f34f9267a7820e87192fb9bc14d2aa7152e53763 --- /dev/null +++ b/tasks/csa159/pair_165738/task_prompt.md @@ -0,0 +1,383 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `syntax_only` + +### Current failure diagnosis + +- Process quality remained below threshold despite successful build, differential detection, code verification, objective gate G6, and accepted refinement. +- The prior semantic model treated every mutable file-scope definition with external linkage as vulnerable, creating a broad superset that includes globals intentionally shared between built-in translation units. +- The analysis did not establish the decisive EXPORT_SYMBOL_GPL relationship, so the claim that any loadable module could access the object remained unproven from linkage alone. +- The assumption that const-qualified external globals are categorically harmless was not justified by the patch evidence. +- A late compile validation failure had no evidenced successful recovery, weakening confidence in the final validation process. + +### Preserve from prior rollouts + +- Retain successful checker compilation, before/after validation, and code verification. +- Retain objective eligibility gate G6. +- Retain an accepted or clean refinement outcome. +- Use at least the previously adequate syntax-only CSA mechanism. +- Maintain the semantic score at or above the configured threshold. +- Remain independent of patch anchors such as changed line numbers or diff positions. +- Remain free of patch-local identifiers, file paths, commit hashes, and variable-name hardcoding. + +### Required semantic proof + +- Prove that a main-file VarDecl is a mutable file-scope object definition with external formal linkage. +- Prove that the same declared object is the target of an EXPORT_SYMBOL_GPL expansion in the translation unit, rather than inferring module visibility from external linkage alone. +- Treat the conjunction of writable external definition and GPL export as the vulnerable condition: writable policy state is exposed to loadable modules. +- Treat internal linkage introduced by static, absence of a definition, or absence of the matching export as sufficient to prevent this specific diagnostic. +- Correlate declaration and export by canonical declaration identity or equivalent AST identity, not by textual name comparison. + +### Implementation constraints + +- Use declaration-level AST callbacks, with check::ASTDecl as the primary callback for collecting candidate definitions; no ProgramState, CFG, dominance, or interprocedural propagation is required. +- Use syntax-level AST or preprocessor-origin evidence sufficient to recognize EXPORT_SYMBOL_GPL and associate its referenced declaration with the candidate VarDecl; do not model it as a CallEvent because the macro expands to non-call constructs. +- Filter candidate definitions with isFileVarDecl(), isThisDeclarationADefinition(), hasExternalFormalLinkage(), and SourceManager main-file ownership. +- Determine writability from the declared object type without relying on an unsupported claim that every const export is harmless. +- Emit one BasicReport per qualifying canonical object because an AST declaration callback has no path-sensitive error node. +- Anchor the diagnostic at the externally linked writable VarDecl definition, the declaration changed by the patch. +- Keep the checker project-general while recognizing the semantically relevant export facility; do not mention driver_deferred_probe_timeout, dd.c, driver.h, or patch line numbers. + +### Validation checklist + +- Compile the fresh checker successfully with the target Clang Static Analyzer API and record a final successful compile after every failed compile attempt. +- Scan the buggy revision and confirm diagnostics for both CONFIG_MODULES-dependent pre-patch definitions represented by the harness, with the observed aggregate N_buggy=2. +- Scan the patched revision and confirm N_patched=0 after the definitions gain internal linkage and EXPORT_SYMBOL_GPL is removed. +- Confirm every buggy diagnostic is attached to the changed global declaration span at line 260 or its configuration-equivalent location, with no function-body report. +- Add a refinement case for a mutable external definition that is not exported and require no diagnostic. +- Add a refinement case for a mutable external definition targeted by EXPORT_SYMBOL_GPL and require exactly one diagnostic per analyzed configuration. +- Check that included-header extern declarations, local variables, and non-definitions do not produce reports. +- Re-run cross-validation, code verification, objective gate G6, hardcoding and anchor checks, semantic scoring, and refinement acceptance after the final build. + +### Avoid and forbidden regressions + +- Do not reuse external linkage alone as a proxy for loadable-module exposure. +- Do not search raw source text for EXPORT_SYMBOL_GPL or correlate objects by spelling alone. +- Do not use check::PreCall for the export macro, because its expansion is not an observable call event. +- Do not use check::PreStmt for file-scope variables, which have no enclosing DeclStmt. +- Do not add path-sensitive state, CFG ordering, dominance, or interprocedural dataflow when the required facts are declaration and export syntax. +- Do not suppress all const-qualified objects under the unsupported assertion that read-only exported data is always harmless. +- Do not accept a final validation sequence containing an unrecovered compile or scan failure. +- Do not introduce special cases for the patched symbol, files, line numbers, configuration branch, or commit. diff --git a/tasks/csa159/pair_17613/checker_template.cpp b/tasks/csa159/pair_17613/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_17613/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_17613/config.json b/tasks/csa159/pair_17613/config.json new file mode 100644 index 0000000000000000000000000000000000000000..6f5337441f3be1371a68fe495678f0dc23a86d5d --- /dev/null +++ b/tasks/csa159/pair_17613/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "FFmpeg_FFmpeg", + "before_commit": "d31940f04e864542819fb6b998d796e14305bd3c", + "after_commit": "9ccc633068c6fe76989f487c8932bd11886ad65b", + "repo_path": "/workspace/repo/FFmpeg/FFmpeg", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FFmpeg_FFmpeg/ff6de6b180fd7c931410f81fb404ab3dbf30d40b/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FFmpeg_FFmpeg/ff6de6b180fd7c931410f81fb404ab3dbf30d40b/compile_commands.json", + "changed_files": [ + "libavcodec/hevcdec.c" + ], + "commit_message": "avcodec/hevcdec: Avoid only partly skiping duplicate first slices\n\nFixes: NULL pointer dereference and out of array access\nFixes: 13871/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_HEVC_fuzzer-5746167087890432\nFixes: 13845/clusterfuzz-testcase-minimized-ffmpeg_AV_CODEC_ID_HEVC_fuzzer-5650370728034304\n\nThis also fixes the return code for explode mode\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/projects/ffmpeg\nReviewed-by: James Almer \nSigned-off-by: Michael Niedermayer \n(cherry picked from commit 54655623a82632e7624714d7b2a3e039dc5faa7e)\nSigned-off-by: Michael Niedermayer ", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_17613/patch.diff b/tasks/csa159/pair_17613/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..130bd7a59c32de3d9a5341356c44704a03fb03e6 --- /dev/null +++ b/tasks/csa159/pair_17613/patch.diff @@ -0,0 +1,34 @@ +diff --git a/libavcodec/hevcdec.c b/libavcodec/hevcdec.c +index 734c42037a..2412bd0a97 100644 +--- a/libavcodec/hevcdec.c ++++ b/libavcodec/hevcdec.c +@@ -472,6 +472,11 @@ static int hls_slice_header(HEVCContext *s) + + // Coded parameters + sh->first_slice_in_pic_flag = get_bits1(gb); ++ if (s->ref && sh->first_slice_in_pic_flag) { ++ av_log(s->avctx, AV_LOG_ERROR, "Two slices reporting being the first in the same frame.\n"); ++ return 1; // This slice will be skiped later, do not corrupt state ++ } ++ + if ((IS_IDR(s) || IS_BLA(s)) && sh->first_slice_in_pic_flag) { + s->seq_decode = (s->seq_decode + 1) & 0xff; + s->max_ra = INT_MAX; +@@ -2862,12 +2867,13 @@ static int decode_nal_unit(HEVCContext *s, const H2645NAL *nal) + ret = hls_slice_header(s); + if (ret < 0) + return ret; ++ if (ret == 1) { ++ ret = AVERROR_INVALIDDATA; ++ goto fail; ++ } ++ + + if (s->sh.first_slice_in_pic_flag) { +- if (s->ref) { +- av_log(s->avctx, AV_LOG_ERROR, "Two slices reporting being the first in the same frame.\n"); +- goto fail; +- } + if (s->max_ra == INT_MAX) { + if (s->nal_unit_type == HEVC_NAL_CRA_NUT || IS_BLA(s)) { + s->max_ra = s->poc; \ No newline at end of file diff --git a/tasks/csa159/pair_17613/post_functions.txt b/tasks/csa159/pair_17613/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..7f1d0525df419fbb83019a3bd0b690808f3d7062 --- /dev/null +++ b/tasks/csa159/pair_17613/post_functions.txt @@ -0,0 +1,205 @@ +### File: libavcodec/hevcdec.c +```c +static int hls_slice_header(HEVCContext *s) +{ + GetBitContext *gb = &s->HEVClc->gb; + SliceHeader *sh = &s->sh; + int i, ret; + + // Coded parameters + sh->first_slice_in_pic_flag = get_bits1(gb); + if (s->ref && sh->first_slice_in_pic_flag) { + av_log(s->avctx, AV_LOG_ERROR, "Two slices reporting being the first in the same frame.\n"); + return 1; // This slice will be skiped later, do not corrupt state + } + + if ((IS_IDR(s) || IS_BLA(s)) && sh->first_slice_in_pic_flag) { + s->seq_decode = (s->seq_decode + 1) & 0xff; + s->max_ra = INT_MAX; + if (IS_IDR(s)) + ff_hevc_clear_refs(s); + } + sh->no_output_of_prior_pics_flag = 0; + if (IS_IRAP(s)) + sh->no_output_of_prior_pics_flag = get_bits1(gb); + + sh->pps_id = get_ue_golomb_long(gb); + if (sh->pps_id >= HEVC_MAX_PPS_COUNT || !s->ps.pps_list[sh->pps_id]) { + av_log(s->avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", sh->pps_id); + return AVERROR_INVALIDDATA; + } + if (!sh->first_slice_in_pic_flag && + s->ps.pps != (HEVCPPS*)s->ps.pps_list[sh->pps_id]->data) { + av_log(s->avctx, AV_LOG_ERROR, "PPS changed between slices.\n"); + return AVERROR_INVALIDDATA; + } + s->ps.pps = (HEVCPPS*)s->ps.pps_list[sh->pps_id]->data; + if (s->nal_unit_type == HEVC_NAL_CRA_NUT && s->last_eos == 1) + sh->no_output_of_prior_pics_flag = 1; + + if (s->ps.sps != (HEVCSPS*)s->ps.sps_list[s->ps.pps->sps_id]->data) { + const HEVCSPS *sps = (HEVCSPS*)s->ps.sps_list[s->ps.pps->sps_id]->data; + const HEVCSPS *last_sps = s->ps.sps; + enum AVPixelFormat pix_fmt; + + if (last_sps && IS_IRAP(s) && s->nal_unit_type != HEVC_NAL_CRA_NUT) { + if (sps->width != last_sps->width || sps->height != last_sps->height || + sps->temporal_layer[sps->max_sub_layers - 1].max_dec_pic_buffering != + last_sps->temporal_layer[last_sps->max_sub_layers - 1].max_dec_pic_buffering) + sh->no_output_of_prior_pics_flag = 0; + } + ff_hevc_clear_refs(s); + + pix_fmt = get_format(s, sps); + if (pix_fmt < 0) + return pix_fmt; + + ret = set_sps(s, sps, pix_fmt); + if (ret < 0) + return ret; + + s->seq_decode = (s->seq_decode + 1) & 0xff; + s->max_ra = INT_MAX; + } + + sh->dependent_slice_segment_flag = 0; + if (!sh->first_slice_in_pic_flag) { + int slice_address_length; + + if (s->ps.pps->dependent_slice_segments_enabled_flag) + sh->dependent_slice_segment_flag = get_bits1(gb); + + slice_address_length = av_ceil_log2(s->ps.sps->ctb_width * + s->ps.sps->ctb_height); + sh->slice_segment_addr = get_bitsz(gb, slice_address_length); + if (sh->slice_segment_addr >= s->ps.sps->ctb_width * s->ps.sps->ctb_height) { + av_log(s->avctx, AV_LOG_ERROR, + "Invalid slice segment address: %u.\n", + sh->slice_segment_addr); + return AVERROR_INVALIDDATA; + } + + if (!sh->dependent_slice_segment_flag) { + sh->slice_addr = sh->slice_segment_addr; + s->slice_idx++; + } + } else { + sh->slice_segment_addr = sh->slice_addr = 0; + s->slice_idx = 0; + s->slice_initialized = 0; + } + + if (!sh->dependent_slice_segment_flag) { + s->slice_initialized = 0; + + for (i = 0; i < s->ps.pps->num_extra_slice_header_bits; i++) + skip_bits(gb, 1); // slice_reserved_undetermined_flag[] + + sh->slice_type = get_ue_golomb_long(gb); + if (!(sh->slice_type == HEVC_SLICE_I || + sh->slice_type == HEVC_SLICE_P || + sh->slice_type == HEVC_SLICE_B)) { + av_log(s->avctx, AV_LOG_ERROR, "Unknown slice type: %d.\n", + sh->slice_type); + return AVERROR_INVALIDDATA; + } + if (IS_IRAP(s) && sh->slice_type != HEVC_SLICE_I) { + av_log(s->avctx, AV_LOG_ERROR, "Inter slices in an IRAP frame.\n"); + return AVERROR_INVALIDDATA; + } + + // when flag is not present, picture is inferred to be output + sh->pic_output_flag = 1; + if (s->ps.pps->output_flag_present_flag) + sh->pic_output_flag = get_bits1(gb); + + if (s->ps.sps->separate_colour_plane_flag) + sh->colour_plane_id = get_bits(gb, 2); + + if (!IS_IDR(s)) { + int poc, pos; + + sh->pic_order_cnt_lsb = get_bits(gb, s->ps.sps->log2_max_poc_lsb); + poc = ff_hevc_compute_poc(s->ps.sps, s->pocTid0, sh->pic_order_cnt_lsb, s->nal_unit_type); + if (!sh->first_slice_in_pic_flag && poc != s->poc) { + av_log(s->avctx, AV_LOG_WARNING, + "Ignoring POC change between slices: %d -> %d\n", s->poc, poc); + if (s->avctx->err_recognition & AV_EF_EXPLODE) + return AVERROR_INVALIDDATA; + poc = s->poc; + } + s->poc = poc; + + sh->short_term_ref_pic_set_sps_flag = get_bits1(gb); + pos = get_bits_left(gb); + if (!sh->short_term_ref_pic_set_sps_flag) { + ret = ff_hevc_decode_short_term_rps(gb, s->avctx, &sh->slice_rps, s->ps.sps, 1); + if (ret < 0) + return ret; + + sh->short_term_rps = &sh->slice_rps; + } else { + int numbits, rps_idx; + + if (!s->ps.sps->nb_st_rps) { + av_log(s->avctx, AV_LOG_ERROR, "No ref lists in the SPS.\n"); + return AVERROR_INVALIDDATA; + } + + numbits = av_ceil_log2(s->ps.sps->nb_st_rps); + rps_idx = numbits > 0 ? get_bits(gb, numbits) : 0; + sh->short_term_rps = &s->ps.sps->st_rps[rps_idx]; + } + sh->short_term_ref_pic_set_size = pos - get_bits_left(gb); + + pos = get_bits_left(gb); + ret = decode_lt_rps(s, &sh->long_term_rps, gb); + if (ret < 0) { + av_log(s->avctx, AV_LOG_WARNING, "Invalid long term RPS.\n"); + if (s->avctx->err_recognition & AV_EF_EXPLODE) + return AVERROR_INVALIDDATA; + } + sh->long_term_ref_pic_set_size = pos - get_bits_left(gb); + + if (s->ps.sps->sps_temporal_mvp_enabled_flag) + sh->slice_temporal_mvp_enabled_flag = get_bits1(gb); + else + sh->slice_temporal_mvp_enabled_flag = 0; + } else { + s->sh.short_term_rps = NULL; + s->poc = 0; + } + + /* 8.3.1 */ + if (sh->first_slice_in_pic_flag && s->temporal_id == 0 && + s->nal_unit_type != HEVC_NAL_TRAIL_N && + s->nal_unit_type != HEVC_NAL_TSA_N && + s->nal_unit_type != HEVC_NAL_STSA_N && + s->nal_unit_type != HEVC_NAL_RADL_N && + s->nal_unit_type != HEVC_NAL_RADL_R && + s->nal_unit_type != HEVC_NAL_RASL_N && + s->nal_unit_type != HEVC_NAL_RASL_R) + s->pocTid0 = s->poc; + + if (s->ps.sps->sao_enabled) { + sh->slice_sample_adaptive_offset_flag[0] = get_bits1(gb); + if (s->ps.sps->chroma_format_idc) { + sh->slice_sample_adaptive_offset_flag[1] = + sh->slice_sample_adaptive_offset_flag[2] = get_bits1(gb); + } + } else { + sh->slice_sample_adaptive_offset_flag[0] = 0; + sh->slice_sample_adaptive_offset_flag[1] = 0; + sh->slice_sample_adaptive_offset_flag[2] = 0; + } + + sh->nb_refs[L0] = sh->nb_refs[L1] = 0; + if (sh->slice_type == HEVC_SLICE_P || sh->slice_type == HEVC_SLICE_B) { + int nb_refs; + + sh->nb_refs[L0] = s->ps.pps->num_ref_idx_l0_default_active; + if (sh->slice_type == HEVC_SLICE_B) + sh->nb_refs[L1] = s->ps.pps->num_ref_idx_l1_default_active; + +// ... (14146 more chars) +``` diff --git a/tasks/csa159/pair_17613/pre_functions.txt b/tasks/csa159/pair_17613/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..e42ce534953e7c69178781bd2931abce7d9432b4 --- /dev/null +++ b/tasks/csa159/pair_17613/pre_functions.txt @@ -0,0 +1,205 @@ +### File: libavcodec/hevcdec.c +```c +static int hls_slice_header(HEVCContext *s) +{ + GetBitContext *gb = &s->HEVClc->gb; + SliceHeader *sh = &s->sh; + int i, ret; + + // Coded parameters + sh->first_slice_in_pic_flag = get_bits1(gb); + if ((IS_IDR(s) || IS_BLA(s)) && sh->first_slice_in_pic_flag) { + s->seq_decode = (s->seq_decode + 1) & 0xff; + s->max_ra = INT_MAX; + if (IS_IDR(s)) + ff_hevc_clear_refs(s); + } + sh->no_output_of_prior_pics_flag = 0; + if (IS_IRAP(s)) + sh->no_output_of_prior_pics_flag = get_bits1(gb); + + sh->pps_id = get_ue_golomb_long(gb); + if (sh->pps_id >= HEVC_MAX_PPS_COUNT || !s->ps.pps_list[sh->pps_id]) { + av_log(s->avctx, AV_LOG_ERROR, "PPS id out of range: %d\n", sh->pps_id); + return AVERROR_INVALIDDATA; + } + if (!sh->first_slice_in_pic_flag && + s->ps.pps != (HEVCPPS*)s->ps.pps_list[sh->pps_id]->data) { + av_log(s->avctx, AV_LOG_ERROR, "PPS changed between slices.\n"); + return AVERROR_INVALIDDATA; + } + s->ps.pps = (HEVCPPS*)s->ps.pps_list[sh->pps_id]->data; + if (s->nal_unit_type == HEVC_NAL_CRA_NUT && s->last_eos == 1) + sh->no_output_of_prior_pics_flag = 1; + + if (s->ps.sps != (HEVCSPS*)s->ps.sps_list[s->ps.pps->sps_id]->data) { + const HEVCSPS *sps = (HEVCSPS*)s->ps.sps_list[s->ps.pps->sps_id]->data; + const HEVCSPS *last_sps = s->ps.sps; + enum AVPixelFormat pix_fmt; + + if (last_sps && IS_IRAP(s) && s->nal_unit_type != HEVC_NAL_CRA_NUT) { + if (sps->width != last_sps->width || sps->height != last_sps->height || + sps->temporal_layer[sps->max_sub_layers - 1].max_dec_pic_buffering != + last_sps->temporal_layer[last_sps->max_sub_layers - 1].max_dec_pic_buffering) + sh->no_output_of_prior_pics_flag = 0; + } + ff_hevc_clear_refs(s); + + pix_fmt = get_format(s, sps); + if (pix_fmt < 0) + return pix_fmt; + + ret = set_sps(s, sps, pix_fmt); + if (ret < 0) + return ret; + + s->seq_decode = (s->seq_decode + 1) & 0xff; + s->max_ra = INT_MAX; + } + + sh->dependent_slice_segment_flag = 0; + if (!sh->first_slice_in_pic_flag) { + int slice_address_length; + + if (s->ps.pps->dependent_slice_segments_enabled_flag) + sh->dependent_slice_segment_flag = get_bits1(gb); + + slice_address_length = av_ceil_log2(s->ps.sps->ctb_width * + s->ps.sps->ctb_height); + sh->slice_segment_addr = get_bitsz(gb, slice_address_length); + if (sh->slice_segment_addr >= s->ps.sps->ctb_width * s->ps.sps->ctb_height) { + av_log(s->avctx, AV_LOG_ERROR, + "Invalid slice segment address: %u.\n", + sh->slice_segment_addr); + return AVERROR_INVALIDDATA; + } + + if (!sh->dependent_slice_segment_flag) { + sh->slice_addr = sh->slice_segment_addr; + s->slice_idx++; + } + } else { + sh->slice_segment_addr = sh->slice_addr = 0; + s->slice_idx = 0; + s->slice_initialized = 0; + } + + if (!sh->dependent_slice_segment_flag) { + s->slice_initialized = 0; + + for (i = 0; i < s->ps.pps->num_extra_slice_header_bits; i++) + skip_bits(gb, 1); // slice_reserved_undetermined_flag[] + + sh->slice_type = get_ue_golomb_long(gb); + if (!(sh->slice_type == HEVC_SLICE_I || + sh->slice_type == HEVC_SLICE_P || + sh->slice_type == HEVC_SLICE_B)) { + av_log(s->avctx, AV_LOG_ERROR, "Unknown slice type: %d.\n", + sh->slice_type); + return AVERROR_INVALIDDATA; + } + if (IS_IRAP(s) && sh->slice_type != HEVC_SLICE_I) { + av_log(s->avctx, AV_LOG_ERROR, "Inter slices in an IRAP frame.\n"); + return AVERROR_INVALIDDATA; + } + + // when flag is not present, picture is inferred to be output + sh->pic_output_flag = 1; + if (s->ps.pps->output_flag_present_flag) + sh->pic_output_flag = get_bits1(gb); + + if (s->ps.sps->separate_colour_plane_flag) + sh->colour_plane_id = get_bits(gb, 2); + + if (!IS_IDR(s)) { + int poc, pos; + + sh->pic_order_cnt_lsb = get_bits(gb, s->ps.sps->log2_max_poc_lsb); + poc = ff_hevc_compute_poc(s->ps.sps, s->pocTid0, sh->pic_order_cnt_lsb, s->nal_unit_type); + if (!sh->first_slice_in_pic_flag && poc != s->poc) { + av_log(s->avctx, AV_LOG_WARNING, + "Ignoring POC change between slices: %d -> %d\n", s->poc, poc); + if (s->avctx->err_recognition & AV_EF_EXPLODE) + return AVERROR_INVALIDDATA; + poc = s->poc; + } + s->poc = poc; + + sh->short_term_ref_pic_set_sps_flag = get_bits1(gb); + pos = get_bits_left(gb); + if (!sh->short_term_ref_pic_set_sps_flag) { + ret = ff_hevc_decode_short_term_rps(gb, s->avctx, &sh->slice_rps, s->ps.sps, 1); + if (ret < 0) + return ret; + + sh->short_term_rps = &sh->slice_rps; + } else { + int numbits, rps_idx; + + if (!s->ps.sps->nb_st_rps) { + av_log(s->avctx, AV_LOG_ERROR, "No ref lists in the SPS.\n"); + return AVERROR_INVALIDDATA; + } + + numbits = av_ceil_log2(s->ps.sps->nb_st_rps); + rps_idx = numbits > 0 ? get_bits(gb, numbits) : 0; + sh->short_term_rps = &s->ps.sps->st_rps[rps_idx]; + } + sh->short_term_ref_pic_set_size = pos - get_bits_left(gb); + + pos = get_bits_left(gb); + ret = decode_lt_rps(s, &sh->long_term_rps, gb); + if (ret < 0) { + av_log(s->avctx, AV_LOG_WARNING, "Invalid long term RPS.\n"); + if (s->avctx->err_recognition & AV_EF_EXPLODE) + return AVERROR_INVALIDDATA; + } + sh->long_term_ref_pic_set_size = pos - get_bits_left(gb); + + if (s->ps.sps->sps_temporal_mvp_enabled_flag) + sh->slice_temporal_mvp_enabled_flag = get_bits1(gb); + else + sh->slice_temporal_mvp_enabled_flag = 0; + } else { + s->sh.short_term_rps = NULL; + s->poc = 0; + } + + /* 8.3.1 */ + if (sh->first_slice_in_pic_flag && s->temporal_id == 0 && + s->nal_unit_type != HEVC_NAL_TRAIL_N && + s->nal_unit_type != HEVC_NAL_TSA_N && + s->nal_unit_type != HEVC_NAL_STSA_N && + s->nal_unit_type != HEVC_NAL_RADL_N && + s->nal_unit_type != HEVC_NAL_RADL_R && + s->nal_unit_type != HEVC_NAL_RASL_N && + s->nal_unit_type != HEVC_NAL_RASL_R) + s->pocTid0 = s->poc; + + if (s->ps.sps->sao_enabled) { + sh->slice_sample_adaptive_offset_flag[0] = get_bits1(gb); + if (s->ps.sps->chroma_format_idc) { + sh->slice_sample_adaptive_offset_flag[1] = + sh->slice_sample_adaptive_offset_flag[2] = get_bits1(gb); + } + } else { + sh->slice_sample_adaptive_offset_flag[0] = 0; + sh->slice_sample_adaptive_offset_flag[1] = 0; + sh->slice_sample_adaptive_offset_flag[2] = 0; + } + + sh->nb_refs[L0] = sh->nb_refs[L1] = 0; + if (sh->slice_type == HEVC_SLICE_P || sh->slice_type == HEVC_SLICE_B) { + int nb_refs; + + sh->nb_refs[L0] = s->ps.pps->num_ref_idx_l0_default_active; + if (sh->slice_type == HEVC_SLICE_B) + sh->nb_refs[L1] = s->ps.pps->num_ref_idx_l1_default_active; + + if (get_bits1(gb)) { // num_ref_idx_active_override_flag + sh->nb_refs[L0] = get_ue_golomb_long(gb) + 1; + if (sh->slice_type == HEVC_SLICE_B) + sh->nb_refs[L1] = get_ue_go + +// ... (13993 more chars) +``` diff --git a/tasks/csa159/pair_17613/task_prompt.md b/tasks/csa159/pair_17613/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_17613/task_prompt.md @@ -0,0 +1,318 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` diff --git a/tasks/csa159/pair_3538/checker_template.cpp b/tasks/csa159/pair_3538/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_3538/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_3538/config.json b/tasks/csa159/pair_3538/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0b800500aff1a5c53de2144af10a865c3b81d43e --- /dev/null +++ b/tasks/csa159/pair_3538/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "gpac_gpac", + "before_commit": "5ce0c906ed8599d218036b18b78e8126a496f137", + "after_commit": "7bb1b4a4dd23c885f9db9f577dfe79ecc5433109", + "repo_path": "/workspace/repo/gpac/gpac", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/gpac_gpac/91d397ddce227a2559bb9b16528c8087e5425961/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/gpac_gpac/91d397ddce227a2559bb9b16528c8087e5425961/compile_commands.json", + "changed_files": [ + "src/media_tools/av_parsers.c" + ], + "commit_message": "fixed #1893", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_3538/patch.diff b/tasks/csa159/pair_3538/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..51451a343ae02d5df9231c72690a8aa02d1c67b9 --- /dev/null +++ b/tasks/csa159/pair_3538/patch.diff @@ -0,0 +1,17 @@ +diff --git a/src/media_tools/av_parsers.c b/src/media_tools/av_parsers.c +index 3ce9a9015..4ea0db8a9 100644 +--- a/src/media_tools/av_parsers.c ++++ b/src/media_tools/av_parsers.c +@@ -3980,10 +3980,8 @@ void gf_av1_reset_state(AV1State *state, Bool is_destroy) + gf_list_del(l1); + gf_list_del(l2); + if (state->bs) { +- if (gf_bs_get_position(state->bs)) { +- u32 size; +- gf_bs_get_content_no_truncate(state->bs, &state->frame_obus, &size, &state->frame_obus_alloc); +- } ++ u32 size; ++ gf_bs_get_content_no_truncate(state->bs, &state->frame_obus, &size, &state->frame_obus_alloc); + gf_bs_del(state->bs); + } + state->bs = NULL; \ No newline at end of file diff --git a/tasks/csa159/pair_3538/post_functions.txt b/tasks/csa159/pair_3538/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..e722a2a7baf491ef7d2ce5cc7cfecb91a0deb180 --- /dev/null +++ b/tasks/csa159/pair_3538/post_functions.txt @@ -0,0 +1,45 @@ +### File: src/media_tools/av_parsers.c +```c +GF_EXPORT +void gf_av1_reset_state(AV1State *state, Bool is_destroy) +{ + GF_List *l1, *l2; + + if (state->frame_state.header_obus) { + while (gf_list_count(state->frame_state.header_obus)) { + GF_AV1_OBUArrayEntry *a = (GF_AV1_OBUArrayEntry*)gf_list_pop_back(state->frame_state.header_obus); + if (a->obu) gf_free(a->obu); + gf_free(a); + } + } + + if (state->frame_state.frame_obus) { + while (gf_list_count(state->frame_state.frame_obus)) { + GF_AV1_OBUArrayEntry *a = (GF_AV1_OBUArrayEntry*)gf_list_pop_back(state->frame_state.frame_obus); + if (a->obu) gf_free(a->obu); + gf_free(a); + } + } + l1 = state->frame_state.frame_obus; + l2 = state->frame_state.header_obus; + memset(&state->frame_state, 0, sizeof(AV1StateFrame)); + state->frame_state.is_first_frame = GF_TRUE; + + if (is_destroy) { + gf_list_del(l1); + gf_list_del(l2); + if (state->bs) { + u32 size; + gf_bs_get_content_no_truncate(state->bs, &state->frame_obus, &size, &state->frame_obus_alloc); + gf_bs_del(state->bs); + } + state->bs = NULL; + } + else { + state->frame_state.frame_obus = l1; + state->frame_state.header_obus = l2; + if (state->bs) + gf_bs_seek(state->bs, 0); + } +} +``` diff --git a/tasks/csa159/pair_3538/pre_functions.txt b/tasks/csa159/pair_3538/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..ce32554b1768fe565f4bf31d54431d9bf2ad83b7 --- /dev/null +++ b/tasks/csa159/pair_3538/pre_functions.txt @@ -0,0 +1,47 @@ +### File: src/media_tools/av_parsers.c +```c +GF_EXPORT +void gf_av1_reset_state(AV1State *state, Bool is_destroy) +{ + GF_List *l1, *l2; + + if (state->frame_state.header_obus) { + while (gf_list_count(state->frame_state.header_obus)) { + GF_AV1_OBUArrayEntry *a = (GF_AV1_OBUArrayEntry*)gf_list_pop_back(state->frame_state.header_obus); + if (a->obu) gf_free(a->obu); + gf_free(a); + } + } + + if (state->frame_state.frame_obus) { + while (gf_list_count(state->frame_state.frame_obus)) { + GF_AV1_OBUArrayEntry *a = (GF_AV1_OBUArrayEntry*)gf_list_pop_back(state->frame_state.frame_obus); + if (a->obu) gf_free(a->obu); + gf_free(a); + } + } + l1 = state->frame_state.frame_obus; + l2 = state->frame_state.header_obus; + memset(&state->frame_state, 0, sizeof(AV1StateFrame)); + state->frame_state.is_first_frame = GF_TRUE; + + if (is_destroy) { + gf_list_del(l1); + gf_list_del(l2); + if (state->bs) { + if (gf_bs_get_position(state->bs)) { + u32 size; + gf_bs_get_content_no_truncate(state->bs, &state->frame_obus, &size, &state->frame_obus_alloc); + } + gf_bs_del(state->bs); + } + state->bs = NULL; + } + else { + state->frame_state.frame_obus = l1; + state->frame_state.header_obus = l2; + if (state->bs) + gf_bs_seek(state->bs, 0); + } +} +``` diff --git a/tasks/csa159/pair_3538/task_prompt.md b/tasks/csa159/pair_3538/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..43f12813b8eb0219349f648c20d88f940484cf8f --- /dev/null +++ b/tasks/csa159/pair_3538/task_prompt.md @@ -0,0 +1,374 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `path_sensitive` + +### Current failure diagnosis + +- The independent rollout failed only refinement_accepted: outcome was feedback_required after one round, so the synthesis stayed unproven at the refinement gate despite compile, paired scan, cross-validation, and semantic scoring succeeding. +- The prior design proved the bug with check::PreCall plus a whole-function CFGDomTree walk rather than ProgramState facts on the exploded graph, so the accepted path-sensitive contract (conditional detach versus unconditional free) was only shown indirectly and refinement did not converge. +- Ledger unresolved blocker remains that refinement is not accepted or clean; a new synthesis must re-establish the every-path detach-before-free proof instead of treating the previous plugin as finished work. + +### Preserve from prior rollouts + +- Keep hard_validation: the plugin must compile, the before/after scans of av_parsers.c must stay differentially correct, and code verification must pass. +- Keep objective eligibility gate G6, including the prior differential result of one warning on buggy gf_av1_reset_state and zero on the patched function. +- Keep the accepted path-sensitive mechanism contract and semantic score at or above 9.0/adequate; do not drop to a call-site-only match. +- Keep process quality at or above the prior 92.86 threshold. +- Remain free of patch-anchor dependence and patch-local hardcoding, as already achieved by the ledger. + +### Required semantic proof + +- A path that reaches gf_bs_del(bs) is unsafe when an earlier gf_bs_get_content or gf_bs_get_content_no_truncate on the same bitstream writes a persistent output (struct field, global, array element, or non-NULL-initialized local such as &state->frame_obus) and that transfer did not execute on this path, so del frees a buffer the output still aliases (CVE-2021-40572 / CWE-416). +- Canonical true positive: in pre-patch gf_av1_reset_state the transfer sits inside if (gf_bs_get_position(state->bs)) while gf_bs_del(state->bs) is outside that guard under if (state->bs). +- Canonical true negative: post-patch the transfer is in the same block immediately before gf_bs_del, so it executes on every path to the destroy and the checker must go silent. +- Safe when some transfer on that bitstream executes on every path to del, when the only transfer output is a fresh local initialized to NULL, or when the destroyed bitstream has no preceding transfer in the enclosing function. + +### Implementation constraints + +- Implement a path-sensitive checker that records, in ProgramState along exploded-graph paths, whether a gf_bs_get_content* ownership transfer has already executed for the bitstream region reaching gf_bs_del; check::PreCall or check::PostCall on those APIs is required, and CFG dominance may only support the every-path claim, not replace path facts. +- Bind the vulnerability class to the stable GPAC APIs gf_bs_del (1 arg), gf_bs_get_content (3 args), and gf_bs_get_content_no_truncate (4 args); identify the same bitstream by argument/region identity after stripping no-op casts, not by enclosing function name. +- Classify the transfer output as persistent versus a fresh NULL-initialized local; only persistent outputs (including FieldRegion such as state->frame_obus) may participate in a report. +- Emit a PathSensitiveBugReport at the gf_bs_del origin expression when the current path can skip detach while a persistent alias remains; do not emit after the patched same-block order. +- Scope is project-general GPAC bitstream transfer-versus-destroy in the analyzed TU (av_parsers.c). Do not model opaque GF_BitStream internals from bitstream.c and do not write a Level-1 checker for gf_av1_reset_state only. +- Forbid patch-hunk source matching, hardcoded lines 3980-3987, and requiring the identifier gf_bs_get_position as the guard. + +### Validation checklist + +- Compile the new checker as a CSA plugin with zero compile failures. +- Before-patch scan of src/media_tools/av_parsers.c::gf_av1_reset_state must produce exactly one warning at the unconditional gf_bs_del under if (state->bs) while the transfer is still position-guarded. +- After-patch scan of the same function must produce zero warnings once gf_bs_get_content_no_truncate and gf_bs_del share a block with transfer first. +- The diagnostic location must sit on the destroy call (median distance 0 from the patched span; old del anchor near line 3987). +- Confirm no reports at other av_parsers.c gf_bs_get_content* sites that already dominate del, share a loop block with del (~6546, ~8499), or write fresh NULL locals (dst_no_epb, output, and similar). +- Re-run refinement until accepted/clean; a single feedback_required round is not sufficient. +- Cross-validation must remain N_buggy=1, N_patched=0, relevance_ratio 1.0, and sparsity_ratio 1.0 with no warnings disappearing outside the patched function. + +### Avoid and forbidden regressions + +- Do not treat mere co-occurrence of gf_bs_get_content* and gf_bs_del in one function as a defect, and do not resume, copy, or patch the previous checker.cpp. +- Do not hardcode gf_av1_reset_state, AV1State, frame_obus, frame_obus_alloc, or the removed gf_bs_get_position guard from the diff. +- Do not build an interprocedural model of bitstream.c allocator internals or a generic malloc/free checker. +- Do not regress hard_validation, objective_gate G6, semantic_mechanism, semantic_score, process_score, anchor_free, or hardcoding_free. +- Do not stop while refinement_accepted is false or while the only proof is a syntax/AST scan without per-path transfer facts. +- Do not warn when a transfer already executes on every path to del or when the transfer output is a fresh NULL-initialized local. diff --git a/tasks/csa159/pair_4253/checker_template.cpp b/tasks/csa159/pair_4253/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_4253/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_4253/config.json b/tasks/csa159/pair_4253/config.json new file mode 100644 index 0000000000000000000000000000000000000000..7e59eb7ece6c5d4165ccdb2034a4496b28221b9c --- /dev/null +++ b/tasks/csa159/pair_4253/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "gpac_gpac", + "before_commit": "a97e5e8625e46eedd2512cc74727d662c9204e0e", + "after_commit": "9024531ee8e6ae8318a8fe0cbb64710d1acc31f6", + "repo_path": "/workspace/repo/gpac/gpac", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/gpac_gpac/040999e052bd084203e0447fac8f1f13eb7406d5/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/gpac_gpac/040999e052bd084203e0447fac8f1f13eb7406d5/compile_commands.json", + "changed_files": [ + "src/isomedia/box_funcs.c" + ], + "commit_message": "fixed #2537", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_4253/patch.diff b/tasks/csa159/pair_4253/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..297dc32995fcce76d61454e30e92af78690d16b1 --- /dev/null +++ b/tasks/csa159/pair_4253/patch.diff @@ -0,0 +1,26 @@ +diff --git a/src/isomedia/box_funcs.c b/src/isomedia/box_funcs.c +index d3791dde5..02643a306 100644 +--- a/src/isomedia/box_funcs.c ++++ b/src/isomedia/box_funcs.c +@@ -99,6 +99,7 @@ GF_Err gf_isom_box_parse_ex(GF_Box **outBox, GF_BitStream *bs, u32 parent_type, + char uuid[16]; + GF_Err e; + GF_BitStream *uncomp_bs = NULL; ++ GF_BitStream *orig_bs = NULL; + u8 *uncomp_data = NULL; + u32 compressed_size=0; + GF_Box *newBox; +@@ -205,6 +206,7 @@ GF_Err gf_isom_box_parse_ex(GF_Box **outBox, GF_BitStream *bs, u32 parent_type, + //keep size as complete box size for tests below + size = osize + 8; + uncomp_bs = gf_bs_new(uncomp_data, osize, GF_BITSTREAM_READ); ++ orig_bs = bs; + bs = uncomp_bs; + start = 0; + gf_free(compb); +@@ -348,6 +350,7 @@ GF_Err gf_isom_box_parse_ex(GF_Box **outBox, GF_BitStream *bs, u32 parent_type, + } + #endif + newBox->internal_flags = GF_ISOM_BOX_COMPRESSED; ++ bs = orig_bs; + } \ No newline at end of file diff --git a/tasks/csa159/pair_4253/post_functions.txt b/tasks/csa159/pair_4253/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..6688b54945fde90b19f69ad8601f3d70d9286faf --- /dev/null +++ b/tasks/csa159/pair_4253/post_functions.txt @@ -0,0 +1,251 @@ +### File: src/isomedia/box_funcs.c +```c +GF_Err gf_isom_box_parse_ex(GF_Box **outBox, GF_BitStream *bs, u32 parent_type, Bool is_root_box, u64 parent_size) +{ + u32 type, uuid_type, hdr_size, restore_type; + u64 size, start, comp_start, end; + char uuid[16]; + GF_Err e; + GF_BitStream *uncomp_bs = NULL; + GF_BitStream *orig_bs = NULL; + u8 *uncomp_data = NULL; + u32 compressed_size=0; + GF_Box *newBox; + Bool skip_logs = (gf_bs_get_cookie(bs) & GF_ISOM_BS_COOKIE_NO_LOGS ) ? GF_TRUE : GF_FALSE; + Bool is_special = GF_TRUE; + + if ((bs == NULL) || (outBox == NULL) ) return GF_BAD_PARAM; + *outBox = NULL; + if (gf_bs_available(bs) < 8) { + return GF_ISOM_INCOMPLETE_FILE; + } + + comp_start = start = gf_bs_get_position(bs); + + uuid_type = 0; + size = (u64) gf_bs_read_u32(bs); + hdr_size = 4; + /*fix for some boxes found in some old hinted files*/ + if ((size >= 2) && (size <= 4)) { + size = 4; + type = GF_ISOM_BOX_TYPE_VOID; + } else { + type = gf_bs_read_u32(bs); + hdr_size += 4; + /*no size means till end of file - EXCEPT FOR some old QuickTime boxes...*/ + if (type == GF_ISOM_BOX_TYPE_TOTL) + size = 12; + if (!size) { + if (is_root_box) { + if (!skip_logs) { + GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[iso file] Warning Read Box type %s (0x%08X) size 0 reading till the end of file\n", gf_4cc_to_str(type), type)); + } + size = gf_bs_available(bs) + 8; + } else { + if (!skip_logs) { + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Read Box type %s (0x%08X) at position "LLU" has size 0 but is not at root/file level. Forbidden, skipping end of parent box !\n", gf_4cc_to_str(type), type, start)); + return GF_SKIP_BOX; + } + return GF_OK; + } + } + if ((is_root_box && (size>=8)) + || (type==GF_QT_BOX_TYPE_CMOV) + ) { + u32 do_uncompress = 0; + u8 *compb = NULL; + u32 extra_bytes = 0; + u32 osize = 0; + u32 otype = type; + + if (type==GF_4CC('!', 'm', 'o', 'v')) { + do_uncompress = 1; + type = GF_ISOM_BOX_TYPE_MOOV; + } + else if (type==GF_QT_BOX_TYPE_CMOV) { + do_uncompress = 2; + u32 cbtype, cbsize, ctype; + //parse child boxes directly + cbsize = gf_bs_read_u32(bs); + if (cbsize != 12) return GF_ISOM_INVALID_FILE; + cbtype = gf_bs_read_u32(bs); + if (cbtype != GF_QT_BOX_TYPE_DCOM) return GF_ISOM_INVALID_FILE; + ctype = gf_bs_read_u32(bs); + if (ctype != GF_4CC('z', 'l', 'i', 'b')) return GF_NOT_SUPPORTED; + cbsize = gf_bs_read_u32(bs); + if (cbsize <= 12) return GF_ISOM_INVALID_FILE; + cbtype = gf_bs_read_u32(bs); + if (cbtype != GF_QT_BOX_TYPE_CMVD) return GF_ISOM_INVALID_FILE; + + //uncompressed size + gf_bs_read_u32(bs); + extra_bytes = 6*4; + parent_size=0; + parent_type=type; + type = cbtype; + } +#ifndef GPAC_DISABLE_ISOM_FRAGMENTS + else if (type==GF_4CC('!', 'm', 'o', 'f')) { + do_uncompress = 1; + type = GF_ISOM_BOX_TYPE_MOOF; + } + else if (type==GF_4CC('!', 's', 'i', 'x')) { + do_uncompress = 1; + type = GF_ISOM_BOX_TYPE_SIDX; + } + else if (type==GF_4CC('!', 's', 's', 'x')) { + do_uncompress = 1; + type = GF_ISOM_BOX_TYPE_SSIX; + } +#endif + if (do_uncompress) { + compb = gf_malloc((u32) (size-8)); + if (!compb) return GF_OUT_OF_MEM; + + compressed_size = (u32) (size - 8 - extra_bytes); + gf_bs_read_data(bs, compb, compressed_size); + e = gf_gz_decompress_payload_ex(compb, compressed_size, &uncomp_data, &osize, (do_uncompress==2) ? GF_TRUE : GF_FALSE); + if (e) { + gf_free(compb); + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Failed to uncompress payload for box type %s (0x%08X)\n", gf_4cc_to_str(otype), otype)); + return e; + } + + //keep size as complete box size for tests below + size = osize + 8; + uncomp_bs = gf_bs_new(uncomp_data, osize, GF_BITSTREAM_READ); + orig_bs = bs; + bs = uncomp_bs; + start = 0; + gf_free(compb); + } + } + } + +#define ERR_EXIT(_e) { \ + if (uncomp_bs) {\ + gf_free(uncomp_data);\ + gf_bs_del(uncomp_bs); \ + }\ + return _e;\ + } + + /*handle uuid*/ + memset(uuid, 0, 16); + if (type == GF_ISOM_BOX_TYPE_UUID ) { + if (gf_bs_available(bs) < 16) { + ERR_EXIT(GF_ISOM_INCOMPLETE_FILE); + } + gf_bs_read_data(bs, uuid, 16); + hdr_size += 16; + uuid_type = gf_isom_solve_uuid_box(uuid); + } + + //handle large box + if (size == 1) { + if (gf_bs_available(bs) < 8) { + ERR_EXIT(GF_ISOM_INCOMPLETE_FILE); + } + size = gf_bs_read_u64(bs); + hdr_size += 8; + } + if (!skip_logs) + GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[iso file] Read Box type %s size "LLD" start "LLD"\n", gf_4cc_to_str(type), size, start)); + + if ( size < hdr_size ) { + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Box %s size "LLD" less than box header size %d\n", gf_4cc_to_str(type), size, hdr_size)); + ERR_EXIT(GF_ISOM_INVALID_FILE); + } + //if parent size is given, make sure box fits within parent + if (parent_size && (parent_sizereference_type = type; + } else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_IREF)) { + newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFI); + if (!newBox) ERR_EXIT(GF_OUT_OF_MEM); + ((GF_ItemReferenceTypeBox*)newBox)->reference_type = type; + } else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TRGR)) { + newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_TRGT); + if (!newBox) ERR_EXIT(GF_OUT_OF_MEM); + ((GF_TrackGroupTypeBox*)newBox)->group_type = type; + } else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_GRPL)) { + newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_GRPT); + if (!newBox) ERR_EXIT(GF_OUT_OF_MEM); + ((GF_EntityToGroupTypeBox*)newBox)->grouping_type = type; + } else { + //OK, create the box based on the type + is_special = GF_FALSE; + newBox = gf_isom_box_new_ex(uuid_type ? uuid_type : type, parent_type, skip_logs, is_root_box); + if (!newBox) ERR_EXIT(GF_OUT_OF_MEM); + } + + //OK, init and read this box + if (type==GF_ISOM_BOX_TYPE_UUID && !is_special) { + memcpy(((GF_UUIDBox *)newBox)->uuid, uuid, 16); + ((GF_UUIDBox *)newBox)->internal_4cc = uuid_type; + } + + if (!newBox->type) newBox->type = type; + if (restore_type) + newBox->type = restore_type; + + end = gf_bs_available(bs); + if (size - hdr_size > end ) { + newBox->size = size - hdr_size - end; + *outBox = newBox; + ERR_EXIT(GF_ISOM_INCOMPLETE_FILE); + } + + newBox->size = size - hdr_size; + + e = gf_isom_full_box_read(newBox, bs); + if (!e) e = gf_isom_box_read(newBox, bs); + if (e) { + if (gf_opts_get_bool("core", "no-check")) + e = GF_OK; + } + newBox->size = size; + end = gf_bs_get_position(bs); + + if (uncomp_bs) { + gf_free(uncomp_data); + gf_bs_del(uncomp_bs); + if (e) { + gf_isom_box_del(newBox); + *outBox = NULL; + return e; + } + //move size to real bitstream offsets for tests below + size -= 8; + //remember compressed vs real size info for moov in order to properly recompute chunk offset + if (type==GF_ISOM_BOX_TYPE_MOOV) { + ((GF_MovieBox *)newBox)->compressed_diff = (s32)size - (s32)compressed_size; + ((GF_MovieBox *)newBox)->file_offset = comp_start; + } + else if (type==GF_QT_BOX_TYPE_CMVD) { + //do not store compressed diff or file offset, cmov uses offsets in the compressed file + newBox->size = compressed_size + 8 + 6*4; + } +#ifndef GPAC_DISABLE_ISOM_FRAGMENTS + //remember compressed vs real size info for moof in order to properly recompute data_offset/base_data_offset + else if (type==GF_ISOM_BOX_TYPE_MOO + +// ... (1721 more chars) +``` diff --git a/tasks/csa159/pair_4253/pre_functions.txt b/tasks/csa159/pair_4253/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..5081db8c76e10a2204b9937d2564232b901b60c0 --- /dev/null +++ b/tasks/csa159/pair_4253/pre_functions.txt @@ -0,0 +1,250 @@ +### File: src/isomedia/box_funcs.c +```c +GF_Err gf_isom_box_parse_ex(GF_Box **outBox, GF_BitStream *bs, u32 parent_type, Bool is_root_box, u64 parent_size) +{ + u32 type, uuid_type, hdr_size, restore_type; + u64 size, start, comp_start, end; + char uuid[16]; + GF_Err e; + GF_BitStream *uncomp_bs = NULL; + u8 *uncomp_data = NULL; + u32 compressed_size=0; + GF_Box *newBox; + Bool skip_logs = (gf_bs_get_cookie(bs) & GF_ISOM_BS_COOKIE_NO_LOGS ) ? GF_TRUE : GF_FALSE; + Bool is_special = GF_TRUE; + + if ((bs == NULL) || (outBox == NULL) ) return GF_BAD_PARAM; + *outBox = NULL; + if (gf_bs_available(bs) < 8) { + return GF_ISOM_INCOMPLETE_FILE; + } + + comp_start = start = gf_bs_get_position(bs); + + uuid_type = 0; + size = (u64) gf_bs_read_u32(bs); + hdr_size = 4; + /*fix for some boxes found in some old hinted files*/ + if ((size >= 2) && (size <= 4)) { + size = 4; + type = GF_ISOM_BOX_TYPE_VOID; + } else { + type = gf_bs_read_u32(bs); + hdr_size += 4; + /*no size means till end of file - EXCEPT FOR some old QuickTime boxes...*/ + if (type == GF_ISOM_BOX_TYPE_TOTL) + size = 12; + if (!size) { + if (is_root_box) { + if (!skip_logs) { + GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[iso file] Warning Read Box type %s (0x%08X) size 0 reading till the end of file\n", gf_4cc_to_str(type), type)); + } + size = gf_bs_available(bs) + 8; + } else { + if (!skip_logs) { + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Read Box type %s (0x%08X) at position "LLU" has size 0 but is not at root/file level. Forbidden, skipping end of parent box !\n", gf_4cc_to_str(type), type, start)); + return GF_SKIP_BOX; + } + return GF_OK; + } + } + if ((is_root_box && (size>=8)) + || (type==GF_QT_BOX_TYPE_CMOV) + ) { + u32 do_uncompress = 0; + u8 *compb = NULL; + u32 extra_bytes = 0; + u32 osize = 0; + u32 otype = type; + + if (type==GF_4CC('!', 'm', 'o', 'v')) { + do_uncompress = 1; + type = GF_ISOM_BOX_TYPE_MOOV; + } + else if (type==GF_QT_BOX_TYPE_CMOV) { + do_uncompress = 2; + u32 cbtype, cbsize, ctype; + //parse child boxes directly + cbsize = gf_bs_read_u32(bs); + if (cbsize != 12) return GF_ISOM_INVALID_FILE; + cbtype = gf_bs_read_u32(bs); + if (cbtype != GF_QT_BOX_TYPE_DCOM) return GF_ISOM_INVALID_FILE; + ctype = gf_bs_read_u32(bs); + if (ctype != GF_4CC('z', 'l', 'i', 'b')) return GF_NOT_SUPPORTED; + cbsize = gf_bs_read_u32(bs); + if (cbsize <= 12) return GF_ISOM_INVALID_FILE; + cbtype = gf_bs_read_u32(bs); + if (cbtype != GF_QT_BOX_TYPE_CMVD) return GF_ISOM_INVALID_FILE; + + //uncompressed size + gf_bs_read_u32(bs); + extra_bytes = 6*4; + parent_size=0; + parent_type=type; + type = cbtype; + } +#ifndef GPAC_DISABLE_ISOM_FRAGMENTS + else if (type==GF_4CC('!', 'm', 'o', 'f')) { + do_uncompress = 1; + type = GF_ISOM_BOX_TYPE_MOOF; + } + else if (type==GF_4CC('!', 's', 'i', 'x')) { + do_uncompress = 1; + type = GF_ISOM_BOX_TYPE_SIDX; + } + else if (type==GF_4CC('!', 's', 's', 'x')) { + do_uncompress = 1; + type = GF_ISOM_BOX_TYPE_SSIX; + } +#endif + if (do_uncompress) { + compb = gf_malloc((u32) (size-8)); + if (!compb) return GF_OUT_OF_MEM; + + compressed_size = (u32) (size - 8 - extra_bytes); + gf_bs_read_data(bs, compb, compressed_size); + e = gf_gz_decompress_payload_ex(compb, compressed_size, &uncomp_data, &osize, (do_uncompress==2) ? GF_TRUE : GF_FALSE); + if (e) { + gf_free(compb); + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Failed to uncompress payload for box type %s (0x%08X)\n", gf_4cc_to_str(otype), otype)); + return e; + } + + //keep size as complete box size for tests below + size = osize + 8; + uncomp_bs = gf_bs_new(uncomp_data, osize, GF_BITSTREAM_READ); + bs = uncomp_bs; + start = 0; + gf_free(compb); + } + } + } + +#define ERR_EXIT(_e) { \ + if (uncomp_bs) {\ + gf_free(uncomp_data);\ + gf_bs_del(uncomp_bs); \ + }\ + return _e;\ + } + + /*handle uuid*/ + memset(uuid, 0, 16); + if (type == GF_ISOM_BOX_TYPE_UUID ) { + if (gf_bs_available(bs) < 16) { + ERR_EXIT(GF_ISOM_INCOMPLETE_FILE); + } + gf_bs_read_data(bs, uuid, 16); + hdr_size += 16; + uuid_type = gf_isom_solve_uuid_box(uuid); + } + + //handle large box + if (size == 1) { + if (gf_bs_available(bs) < 8) { + ERR_EXIT(GF_ISOM_INCOMPLETE_FILE); + } + size = gf_bs_read_u64(bs); + hdr_size += 8; + } + if (!skip_logs) + GF_LOG(GF_LOG_DEBUG, GF_LOG_CONTAINER, ("[iso file] Read Box type %s size "LLD" start "LLD"\n", gf_4cc_to_str(type), size, start)); + + if ( size < hdr_size ) { + GF_LOG(GF_LOG_ERROR, GF_LOG_CONTAINER, ("[iso file] Box %s size "LLD" less than box header size %d\n", gf_4cc_to_str(type), size, hdr_size)); + ERR_EXIT(GF_ISOM_INVALID_FILE); + } + //if parent size is given, make sure box fits within parent + if (parent_size && (parent_sizereference_type = type; + } else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_IREF)) { + newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_REFI); + if (!newBox) ERR_EXIT(GF_OUT_OF_MEM); + ((GF_ItemReferenceTypeBox*)newBox)->reference_type = type; + } else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_TRGR)) { + newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_TRGT); + if (!newBox) ERR_EXIT(GF_OUT_OF_MEM); + ((GF_TrackGroupTypeBox*)newBox)->group_type = type; + } else if (parent_type && (parent_type == GF_ISOM_BOX_TYPE_GRPL)) { + newBox = gf_isom_box_new(GF_ISOM_BOX_TYPE_GRPT); + if (!newBox) ERR_EXIT(GF_OUT_OF_MEM); + ((GF_EntityToGroupTypeBox*)newBox)->grouping_type = type; + } else { + //OK, create the box based on the type + is_special = GF_FALSE; + newBox = gf_isom_box_new_ex(uuid_type ? uuid_type : type, parent_type, skip_logs, is_root_box); + if (!newBox) ERR_EXIT(GF_OUT_OF_MEM); + } + + //OK, init and read this box + if (type==GF_ISOM_BOX_TYPE_UUID && !is_special) { + memcpy(((GF_UUIDBox *)newBox)->uuid, uuid, 16); + ((GF_UUIDBox *)newBox)->internal_4cc = uuid_type; + } + + if (!newBox->type) newBox->type = type; + if (restore_type) + newBox->type = restore_type; + + end = gf_bs_available(bs); + if (size - hdr_size > end ) { + newBox->size = size - hdr_size - end; + *outBox = newBox; + ERR_EXIT(GF_ISOM_INCOMPLETE_FILE); + } + + newBox->size = size - hdr_size; + + e = gf_isom_full_box_read(newBox, bs); + if (!e) e = gf_isom_box_read(newBox, bs); + if (e) { + if (gf_opts_get_bool("core", "no-check")) + e = GF_OK; + } + newBox->size = size; + end = gf_bs_get_position(bs); + + if (uncomp_bs) { + gf_free(uncomp_data); + gf_bs_del(uncomp_bs); + if (e) { + gf_isom_box_del(newBox); + *outBox = NULL; + return e; + } + //move size to real bitstream offsets for tests below + size -= 8; + //remember compressed vs real size info for moov in order to properly recompute chunk offset + if (type==GF_ISOM_BOX_TYPE_MOOV) { + ((GF_MovieBox *)newBox)->compressed_diff = (s32)size - (s32)compressed_size; + ((GF_MovieBox *)newBox)->file_offset = comp_start; + } + else if (type==GF_QT_BOX_TYPE_CMVD) { + //do not store compressed diff or file offset, cmov uses offsets in the compressed file + newBox->size = compressed_size + 8 + 6*4; + } +#ifndef GPAC_DISABLE_ISOM_FRAGMENTS + //remember compressed vs real size info for moof in order to properly recompute data_offset/base_data_offset + else if (type==GF_ISOM_BOX_TYPE_MOOF) { + ((GF_MovieFragmentBox *)newBox)->compress + +// ... (1656 more chars) +``` diff --git a/tasks/csa159/pair_4253/task_prompt.md b/tasks/csa159/pair_4253/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_4253/task_prompt.md @@ -0,0 +1,318 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` diff --git a/tasks/csa159/pair_4701/checker_template.cpp b/tasks/csa159/pair_4701/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_4701/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_4701/config.json b/tasks/csa159/pair_4701/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d56d42184f5136c3680ec34bbcb864b1a6e0215b --- /dev/null +++ b/tasks/csa159/pair_4701/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "FFmpeg_FFmpeg", + "before_commit": "654b21ef176a807bf4e8359a4ed52c629d766100", + "after_commit": "292e41ce650a7b5ca5de4ae87fff0d6a90d9fc97", + "repo_path": "/workspace/repo/FFmpeg/FFmpeg", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FFmpeg_FFmpeg/a7f9b3b954ece129402ac7ef8f96e0fa1c01d8ba/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FFmpeg_FFmpeg/a7f9b3b954ece129402ac7ef8f96e0fa1c01d8ba/compile_commands.json", + "changed_files": [ + "libavcodec/tiff.c" + ], + "commit_message": "avcodec/tiff: Disallow striped and tiled tiffs except for DNG\n\nstrips + tiles is not allowed in TIFF\nDNG uses a separate codepath\n\nRegression since da5b3d002862d1e105002a6dc1567e6551860896.\n\nFixes: NULL pointer dereference\nFixes: poc1\nFixes: Ticket8960\n\nFound-by: 1vanChen of NSFOCUS Security Team\nSigned-off-by: Michael Niedermayer ", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_4701/patch.diff b/tasks/csa159/pair_4701/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e141a01396155a88e14bb03a1bc2976810d9c73e --- /dev/null +++ b/tasks/csa159/pair_4701/patch.diff @@ -0,0 +1,24 @@ +diff --git a/libavcodec/tiff.c b/libavcodec/tiff.c +index fa1f44ce1d..f68f9818ad 100644 +--- a/libavcodec/tiff.c ++++ b/libavcodec/tiff.c +@@ -1923,14 +1923,17 @@ again: + has_strip_bits = s->strippos || s->strips || s->stripoff || s->rps || s->sot || s->sstype || s->stripsize || s->stripsizesoff; + + if (has_tile_bits && has_strip_bits) { +- av_log(avctx, AV_LOG_WARNING, "Tiled TIFF is not allowed to strip\n"); ++ int tiled_dng = s->is_tiled && is_dng; ++ av_log(avctx, tiled_dng ? AV_LOG_WARNING : AV_LOG_ERROR, "Tiled TIFF is not allowed to strip\n"); ++ if (!tiled_dng) ++ return AVERROR_INVALIDDATA; + } + + /* now we have the data and may start decoding */ + if ((ret = init_image(s, &frame)) < 0) + return ret; + +- if (!s->is_tiled) { ++ if (!s->is_tiled || has_strip_bits) { + if (s->strips == 1 && !s->stripsize) { + av_log(avctx, AV_LOG_WARNING, "Image data size missing\n"); + s->stripsize = avpkt->size - s->stripoff; \ No newline at end of file diff --git a/tasks/csa159/pair_4701/post_functions.txt b/tasks/csa159/pair_4701/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..4ce0d71810d512dfe09665a5c5783f90fc82b6a2 --- /dev/null +++ b/tasks/csa159/pair_4701/post_functions.txt @@ -0,0 +1,231 @@ +### File: libavcodec/tiff.c +```c +static int decode_frame(AVCodecContext *avctx, + void *data, int *got_frame, AVPacket *avpkt) +{ + TiffContext *const s = avctx->priv_data; + AVFrame *const p = data; + ThreadFrame frame = { .f = data }; + unsigned off, last_off; + int le, ret, plane, planes; + int i, j, entries, stride; + unsigned soff, ssize; + uint8_t *dst; + GetByteContext stripsizes; + GetByteContext stripdata; + int retry_for_subifd, retry_for_page; + int is_dng; + int has_tile_bits, has_strip_bits; + + bytestream2_init(&s->gb, avpkt->data, avpkt->size); + + // parse image header + if ((ret = ff_tdecode_header(&s->gb, &le, &off))) { + av_log(avctx, AV_LOG_ERROR, "Invalid TIFF header\n"); + return ret; + } else if (off >= UINT_MAX - 14 || avpkt->size < off + 14) { + av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n"); + return AVERROR_INVALIDDATA; + } + s->le = le; + // TIFF_BPP is not a required tag and defaults to 1 + + s->tiff_type = TIFF_TYPE_TIFF; +again: + s->is_thumbnail = 0; + s->bppcount = s->bpp = 1; + s->photometric = TIFF_PHOTOMETRIC_NONE; + s->compr = TIFF_RAW; + s->fill_order = 0; + s->white_level = 0; + s->is_bayer = 0; + s->is_tiled = 0; + s->is_jpeg = 0; + s->cur_page = 0; + s->last_tag = 0; + + for (i = 0; i < 65536; i++) + s->dng_lut[i] = i; + + free_geotags(s); + + // Reset these offsets so we can tell if they were set this frame + s->stripsizesoff = s->strippos = 0; + /* parse image file directory */ + bytestream2_seek(&s->gb, off, SEEK_SET); + entries = ff_tget_short(&s->gb, le); + if (bytestream2_get_bytes_left(&s->gb) < entries * 12) + return AVERROR_INVALIDDATA; + for (i = 0; i < entries; i++) { + if ((ret = tiff_decode_tag(s, p)) < 0) + return ret; + } + + if (s->get_thumbnail && !s->is_thumbnail) { + av_log(avctx, AV_LOG_INFO, "No embedded thumbnail present\n"); + return AVERROR_EOF; + } + + /** whether we should process this IFD's SubIFD */ + retry_for_subifd = s->sub_ifd && (s->get_subimage || (!s->get_thumbnail && s->is_thumbnail)); + /** whether we should process this multi-page IFD's next page */ + retry_for_page = s->get_page && s->cur_page + 1 < s->get_page; // get_page is 1-indexed + + last_off = off; + if (retry_for_page) { + // set offset to the next IFD + off = ff_tget_long(&s->gb, le); + } else if (retry_for_subifd) { + // set offset to the SubIFD + off = s->sub_ifd; + } + + if (retry_for_subifd || retry_for_page) { + if (!off) { + av_log(avctx, AV_LOG_ERROR, "Requested entry not found\n"); + return AVERROR_INVALIDDATA; + } + if (off <= last_off) { + avpriv_request_sample(s->avctx, "non increasing IFD offset"); + return AVERROR_INVALIDDATA; + } + if (off >= UINT_MAX - 14 || avpkt->size < off + 14) { + av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n"); + return AVERROR_INVALIDDATA; + } + s->sub_ifd = 0; + goto again; + } + + /* At this point we've decided on which (Sub)IFD to process */ + + is_dng = (s->tiff_type == TIFF_TYPE_DNG || s->tiff_type == TIFF_TYPE_CINEMADNG); + + for (i = 0; igeotag_count; i++) { + const char *keyname = get_geokey_name(s->geotags[i].key); + if (!keyname) { + av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key); + continue; + } + if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) { + av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key); + continue; + } + ret = av_dict_set(&p->metadata, keyname, s->geotags[i].val, 0); + if (ret<0) { + av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname); + return ret; + } + } + + if (is_dng) { + int bps; + + if (s->bpp % s->bppcount) + return AVERROR_INVALIDDATA; + bps = s->bpp / s->bppcount; + if (bps < 8 || bps > 32) + return AVERROR_INVALIDDATA; + + if (s->white_level == 0) + s->white_level = (1LL << bps) - 1; /* Default value as per the spec */ + + if (s->white_level <= s->black_level) { + av_log(avctx, AV_LOG_ERROR, "BlackLevel (%"PRId32") must be less than WhiteLevel (%"PRId32")\n", + s->black_level, s->white_level); + return AVERROR_INVALIDDATA; + } + + if (s->planar) + return AVERROR_PATCHWELCOME; + } + + if (!s->is_tiled && !s->strippos && !s->stripoff) { + av_log(avctx, AV_LOG_ERROR, "Image data is missing\n"); + return AVERROR_INVALIDDATA; + } + + has_tile_bits = s->is_tiled || s->tile_byte_counts_offset || s->tile_offsets_offset || s->tile_width || s->tile_length || s->tile_count; + has_strip_bits = s->strippos || s->strips || s->stripoff || s->rps || s->sot || s->sstype || s->stripsize || s->stripsizesoff; + + if (has_tile_bits && has_strip_bits) { + int tiled_dng = s->is_tiled && is_dng; + av_log(avctx, tiled_dng ? AV_LOG_WARNING : AV_LOG_ERROR, "Tiled TIFF is not allowed to strip\n"); + if (!tiled_dng) + return AVERROR_INVALIDDATA; + } + + /* now we have the data and may start decoding */ + if ((ret = init_image(s, &frame)) < 0) + return ret; + + if (!s->is_tiled || has_strip_bits) { + if (s->strips == 1 && !s->stripsize) { + av_log(avctx, AV_LOG_WARNING, "Image data size missing\n"); + s->stripsize = avpkt->size - s->stripoff; + } + + if (s->stripsizesoff) { + if (s->stripsizesoff >= (unsigned)avpkt->size) + return AVERROR_INVALIDDATA; + bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff, + avpkt->size - s->stripsizesoff); + } + if (s->strippos) { + if (s->strippos >= (unsigned)avpkt->size) + return AVERROR_INVALIDDATA; + bytestream2_init(&stripdata, avpkt->data + s->strippos, + avpkt->size - s->strippos); + } + + if (s->rps <= 0 || s->rps % s->subsampling[1]) { + av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps); + return AVERROR_INVALIDDATA; + } + } + + if (s->photometric == TIFF_PHOTOMETRIC_LINEAR_RAW || + s->photometric == TIFF_PHOTOMETRIC_CFA) { + p->color_trc = AVCOL_TRC_LINEAR; + } else if (s->photometric == TIFF_PHOTOMETRIC_BLACK_IS_ZERO) { + p->color_trc = AVCOL_TRC_GAMMA22; + } + + /* Handle DNG images with JPEG-compressed tiles */ + + if (is_dng && s->is_tiled) { + if (!s->is_jpeg) { + avpriv_report_missing_feature(avctx, "DNG uncompressed tiled images"); + return AVERROR_PATCHWELCOME; + } else if (!s->is_bayer) { + avpriv_report_missing_feature(avctx, "DNG JPG-compressed tiled non-bayer-encoded images"); + return AVERROR_PATCHWELCOME; + } else { + if ((ret = dng_decode_tiles(avctx, (AVFrame*)data, avpkt)) > 0) + *got_frame = 1; + return ret; + } + } + + /* Handle TIFF images and DNG images with uncompressed strips (non-tiled) */ + + planes = s->planar ? s->bppcount : 1; + for (plane = 0; plane < planes; plane++) { + uint8_t *five_planes = NULL; + int remaining = avpkt->size; + int decoded_height; + stride = p->linesize[plane]; + dst = p->data[plane]; + if (s->photometric == TIFF_PHOTOMETRIC_SEPARATED && + s->avctx->pix_fmt == AV_PIX_FMT_RGBA) { + stride = stride * 5 / 4; + five_planes = + dst = av_malloc(stride * s->height); + if (!dst) + return AVERROR(ENOMEM); + } + for (i = 0; i < s->height; i += s->rps) { + + +// ... (5950 more chars) +``` diff --git a/tasks/csa159/pair_4701/pre_functions.txt b/tasks/csa159/pair_4701/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..30d7e462c4f30d9f2cee2ba50711a6ee50fc6f61 --- /dev/null +++ b/tasks/csa159/pair_4701/pre_functions.txt @@ -0,0 +1,232 @@ +### File: libavcodec/tiff.c +```c +static int decode_frame(AVCodecContext *avctx, + void *data, int *got_frame, AVPacket *avpkt) +{ + TiffContext *const s = avctx->priv_data; + AVFrame *const p = data; + ThreadFrame frame = { .f = data }; + unsigned off, last_off; + int le, ret, plane, planes; + int i, j, entries, stride; + unsigned soff, ssize; + uint8_t *dst; + GetByteContext stripsizes; + GetByteContext stripdata; + int retry_for_subifd, retry_for_page; + int is_dng; + int has_tile_bits, has_strip_bits; + + bytestream2_init(&s->gb, avpkt->data, avpkt->size); + + // parse image header + if ((ret = ff_tdecode_header(&s->gb, &le, &off))) { + av_log(avctx, AV_LOG_ERROR, "Invalid TIFF header\n"); + return ret; + } else if (off >= UINT_MAX - 14 || avpkt->size < off + 14) { + av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n"); + return AVERROR_INVALIDDATA; + } + s->le = le; + // TIFF_BPP is not a required tag and defaults to 1 + + s->tiff_type = TIFF_TYPE_TIFF; +again: + s->is_thumbnail = 0; + s->bppcount = s->bpp = 1; + s->photometric = TIFF_PHOTOMETRIC_NONE; + s->compr = TIFF_RAW; + s->fill_order = 0; + s->white_level = 0; + s->is_bayer = 0; + s->is_tiled = 0; + s->is_jpeg = 0; + s->cur_page = 0; + s->last_tag = 0; + + for (i = 0; i < 65536; i++) + s->dng_lut[i] = i; + + free_geotags(s); + + // Reset these offsets so we can tell if they were set this frame + s->stripsizesoff = s->strippos = 0; + /* parse image file directory */ + bytestream2_seek(&s->gb, off, SEEK_SET); + entries = ff_tget_short(&s->gb, le); + if (bytestream2_get_bytes_left(&s->gb) < entries * 12) + return AVERROR_INVALIDDATA; + for (i = 0; i < entries; i++) { + if ((ret = tiff_decode_tag(s, p)) < 0) + return ret; + } + + if (s->get_thumbnail && !s->is_thumbnail) { + av_log(avctx, AV_LOG_INFO, "No embedded thumbnail present\n"); + return AVERROR_EOF; + } + + /** whether we should process this IFD's SubIFD */ + retry_for_subifd = s->sub_ifd && (s->get_subimage || (!s->get_thumbnail && s->is_thumbnail)); + /** whether we should process this multi-page IFD's next page */ + retry_for_page = s->get_page && s->cur_page + 1 < s->get_page; // get_page is 1-indexed + + last_off = off; + if (retry_for_page) { + // set offset to the next IFD + off = ff_tget_long(&s->gb, le); + } else if (retry_for_subifd) { + // set offset to the SubIFD + off = s->sub_ifd; + } + + if (retry_for_subifd || retry_for_page) { + if (!off) { + av_log(avctx, AV_LOG_ERROR, "Requested entry not found\n"); + return AVERROR_INVALIDDATA; + } + if (off <= last_off) { + avpriv_request_sample(s->avctx, "non increasing IFD offset"); + return AVERROR_INVALIDDATA; + } + if (off >= UINT_MAX - 14 || avpkt->size < off + 14) { + av_log(avctx, AV_LOG_ERROR, "IFD offset is greater than image size\n"); + return AVERROR_INVALIDDATA; + } + s->sub_ifd = 0; + goto again; + } + + /* At this point we've decided on which (Sub)IFD to process */ + + is_dng = (s->tiff_type == TIFF_TYPE_DNG || s->tiff_type == TIFF_TYPE_CINEMADNG); + + for (i = 0; igeotag_count; i++) { + const char *keyname = get_geokey_name(s->geotags[i].key); + if (!keyname) { + av_log(avctx, AV_LOG_WARNING, "Unknown or unsupported GeoTIFF key %d\n", s->geotags[i].key); + continue; + } + if (get_geokey_type(s->geotags[i].key) != s->geotags[i].type) { + av_log(avctx, AV_LOG_WARNING, "Type of GeoTIFF key %d is wrong\n", s->geotags[i].key); + continue; + } + ret = av_dict_set(&p->metadata, keyname, s->geotags[i].val, 0); + if (ret<0) { + av_log(avctx, AV_LOG_ERROR, "Writing metadata with key '%s' failed\n", keyname); + return ret; + } + } + + if (is_dng) { + int bps; + + if (s->bpp % s->bppcount) + return AVERROR_INVALIDDATA; + bps = s->bpp / s->bppcount; + if (bps < 8 || bps > 32) + return AVERROR_INVALIDDATA; + + if (s->white_level == 0) + s->white_level = (1LL << bps) - 1; /* Default value as per the spec */ + + if (s->white_level <= s->black_level) { + av_log(avctx, AV_LOG_ERROR, "BlackLevel (%"PRId32") must be less than WhiteLevel (%"PRId32")\n", + s->black_level, s->white_level); + return AVERROR_INVALIDDATA; + } + + if (s->planar) + return AVERROR_PATCHWELCOME; + } + + if (!s->is_tiled && !s->strippos && !s->stripoff) { + av_log(avctx, AV_LOG_ERROR, "Image data is missing\n"); + return AVERROR_INVALIDDATA; + } + + has_tile_bits = s->is_tiled || s->tile_byte_counts_offset || s->tile_offsets_offset || s->tile_width || s->tile_length || s->tile_count; + has_strip_bits = s->strippos || s->strips || s->stripoff || s->rps || s->sot || s->sstype || s->stripsize || s->stripsizesoff; + + if (has_tile_bits && has_strip_bits) { + av_log(avctx, AV_LOG_WARNING, "Tiled TIFF is not allowed to strip\n"); + } + + /* now we have the data and may start decoding */ + if ((ret = init_image(s, &frame)) < 0) + return ret; + + if (!s->is_tiled) { + if (s->strips == 1 && !s->stripsize) { + av_log(avctx, AV_LOG_WARNING, "Image data size missing\n"); + s->stripsize = avpkt->size - s->stripoff; + } + + if (s->stripsizesoff) { + if (s->stripsizesoff >= (unsigned)avpkt->size) + return AVERROR_INVALIDDATA; + bytestream2_init(&stripsizes, avpkt->data + s->stripsizesoff, + avpkt->size - s->stripsizesoff); + } + if (s->strippos) { + if (s->strippos >= (unsigned)avpkt->size) + return AVERROR_INVALIDDATA; + bytestream2_init(&stripdata, avpkt->data + s->strippos, + avpkt->size - s->strippos); + } + + if (s->rps <= 0 || s->rps % s->subsampling[1]) { + av_log(avctx, AV_LOG_ERROR, "rps %d invalid\n", s->rps); + return AVERROR_INVALIDDATA; + } + } + + if (s->photometric == TIFF_PHOTOMETRIC_LINEAR_RAW || + s->photometric == TIFF_PHOTOMETRIC_CFA) { + p->color_trc = AVCOL_TRC_LINEAR; + } else if (s->photometric == TIFF_PHOTOMETRIC_BLACK_IS_ZERO) { + p->color_trc = AVCOL_TRC_GAMMA22; + } + + /* Handle DNG images with JPEG-compressed tiles */ + + if (is_dng && s->is_tiled) { + if (!s->is_jpeg) { + avpriv_report_missing_feature(avctx, "DNG uncompressed tiled images"); + return AVERROR_PATCHWELCOME; + } else if (!s->is_bayer) { + avpriv_report_missing_feature(avctx, "DNG JPG-compressed tiled non-bayer-encoded images"); + return AVERROR_PATCHWELCOME; + } else { + if ((ret = dng_decode_tiles(avctx, (AVFrame*)data, avpkt)) > 0) + *got_frame = 1; + return ret; + } + } + + /* Handle TIFF images and DNG images with uncompressed strips (non-tiled) */ + + planes = s->planar ? s->bppcount : 1; + for (plane = 0; plane < planes; plane++) { + uint8_t *five_planes = NULL; + int remaining = avpkt->size; + int decoded_height; + stride = p->linesize[plane]; + dst = p->data[plane]; + if (s->photometric == TIFF_PHOTOMETRIC_SEPARATED && + s->avctx->pix_fmt == AV_PIX_FMT_RGBA) { + stride = stride * 5 / 4; + five_planes = + dst = av_malloc(stride * s->height); + if (!dst) + return AVERROR(ENOMEM); + } + for (i = 0; i < s->height; i += s->rps) { + if (i) + dst += s->rps * stride; + if (s->stripsizesoff) + ssize = ff_tget(&stripsizes, s->sstype, le); + + +// ... (5794 more chars) +``` diff --git a/tasks/csa159/pair_4701/task_prompt.md b/tasks/csa159/pair_4701/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..030941227f351e07fa0ff10ac24f0a8f9e77798d --- /dev/null +++ b/tasks/csa159/pair_4701/task_prompt.md @@ -0,0 +1,369 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `control_flow` + +### Current failure diagnosis + +- Buggy scan emitted 0 warnings (G3): hard validation, differential detection, and sharpness never fired, refinement was not run, and semantic/process scores stayed at 0. +- The report gate required ProgramState to prove local has_strip_bits definitely non-zero; that flag is assigned from opaque TiffContext fields CSA does not constrain, so every real sink was suppressed. +- InitializedGBContexts facts were collected at bytestream2_init PreCall but sit before a non-inlined init_image() call, so the exploded graph never presented an uninitialized ff_tget of stripsizes/stripdata. +- Path-sensitive tracking was treated as mandatory because init still does not structurally dominate the later loop; that over-specified the needed guard/sink relation and left the checker unproven. + +### Preserve from prior rollouts + +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Local GetByteContext objects stripsizes and stripdata are read by ff_tget-family calls on a CFG path that never executes bytestream2_init on those same objects. +- The init block is control-dependent on a tile predicate (!s->is_tiled) that is independent of the strip-indicator predicates (s->stripsizesoff / s->strippos) that guard the reads, so a tiled image with strip tags skips setup and still reaches the reads. +- Safety after the fix is that every reachable strip-context read is preceded by init: either the mixed tile+strip path returns AVERROR_INVALIDDATA, or the strip-indicator that guards the read implies the widened init guard (!s->is_tiled || has_strip_bits). + +### Implementation constraints + +- Use check::ASTCodeBody or an equivalent CFG walk of decode_frame; do not depend on exploded-graph constraints of TiffContext fields or has_strip_bits SVals. +- Prove a guard/sink relation between the controlling expression of bytestream2_init on a local GetByteContext and the controlling expression of the later ff_tget on that same local; use reachability only as support, not sole before/after dominance. +- Emit the diagnostic at the strip-loop ff_tget (or equivalent) use of the local inside libavcodec/tiff.c::decode_frame, not at the patched if-header or av_log lines. +- Key on GetByteContext locals plus the bytestream2_init versus ff_tget API contract; do not key on commit IDs, changed line numbers, or the exact patched guard spelling. +- No debug llvm::errs and no extra BeginFunction/PreStmt logging callbacks. + +### Validation checklist + +- Plugin compiles and registers as a CSA checker. +- scan_before on pre-patch libavcodec/tiff.c yields n_buggy >= 1 in decode_frame. +- At least one buggy warning is at ff_tget(&stripsizes) or ff_tget(&stripdata) in the strip-decode loop, not only the tiled+strip warning log. +- scan_after on post-patch decode_frame yields n_patched = 0 for this class because strip-guarded reads now imply init or the mixed path returns. +- Reports stay inside libavcodec/tiff.c::decode_frame and satisfy function_or_precise_changed_span_v2 near the strip uses. +- Re-confirm hardcoding_free and anchor_free, then run refinement until accepted. + +### Avoid and forbidden regressions + +- Do not repeat PreCall plus InitializedGBContexts ProgramState plus a has_strip_bits isNull report gate. +- Do not treat structural non-dominance of the init block as proof that ProgramState path-sensitivity is required; post-patch init still does not dominate the loop. +- Do not name-lookup has_strip_bits as a required runtime fact CSA must constrain. +- Do not hardcode patch lines 1926-1936 or the string Tiled TIFF is not allowed to strip. +- Do not rely on CSA inlining init_image or concretizing TiffContext fields. +- Do not ship a syntax-only call matcher that ignores tile versus strip guards, which cannot separate patched from vulnerable code. diff --git a/tasks/csa159/pair_4869/checker_template.cpp b/tasks/csa159/pair_4869/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_4869/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_4869/config.json b/tasks/csa159/pair_4869/config.json new file mode 100644 index 0000000000000000000000000000000000000000..a820f32a0cd894eda9ebdd58356ece66793bce0c --- /dev/null +++ b/tasks/csa159/pair_4869/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "FFmpeg_FFmpeg", + "before_commit": "a0341b4d74f4db289e15dac0d2988eaa2d18a1bb", + "after_commit": "e371f031b942d73e02c090170975561fabd5c264", + "repo_path": "/workspace/repo/FFmpeg/FFmpeg", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FFmpeg_FFmpeg/7f9978b0bdfc80ac23248df743645d1efc7e123f/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FFmpeg_FFmpeg/7f9978b0bdfc80ac23248df743645d1efc7e123f/compile_commands.json", + "changed_files": [ + "libavcodec/pngdec.c" + ], + "commit_message": "avcodec/pngdec: Fix off by 1 size in decode_zbuf()\n\nFixes out of array access\nFixes: 444/fuzz-2-ffmpeg_VIDEO_AV_CODEC_ID_PNG_fuzzer\n\nFound-by: continuous fuzzing process https://github.com/google/oss-fuzz/tree/master/targets/ffmpeg\nSigned-off-by: Michael Niedermayer ", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_4869/patch.diff b/tasks/csa159/pair_4869/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f14e1f6c58cc970588eefd239cbe4990d8702547 --- /dev/null +++ b/tasks/csa159/pair_4869/patch.diff @@ -0,0 +1,21 @@ +diff --git a/libavcodec/pngdec.c b/libavcodec/pngdec.c +index 2f8d266c27..50a0a296b3 100644 +--- a/libavcodec/pngdec.c ++++ b/libavcodec/pngdec.c +@@ -437,13 +437,13 @@ static int decode_zbuf(AVBPrint *bp, const uint8_t *data, + av_bprint_init(bp, 0, -1); + + while (zstream.avail_in > 0) { +- av_bprint_get_buffer(bp, 1, &buf, &buf_size); +- if (!buf_size) { ++ av_bprint_get_buffer(bp, 2, &buf, &buf_size); ++ if (buf_size < 2) { + ret = AVERROR(ENOMEM); + goto fail; + } + zstream.next_out = buf; +- zstream.avail_out = buf_size; ++ zstream.avail_out = buf_size - 1; + ret = inflate(&zstream, Z_PARTIAL_FLUSH); + if (ret != Z_OK && ret != Z_STREAM_END) { + ret = AVERROR_EXTERNAL; \ No newline at end of file diff --git a/tasks/csa159/pair_4869/post_functions.txt b/tasks/csa159/pair_4869/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..797bfe51a7f5044ab7448e3d11b0c36488032096 --- /dev/null +++ b/tasks/csa159/pair_4869/post_functions.txt @@ -0,0 +1,46 @@ +### File: libavcodec/pngdec.c +```c +static int decode_zbuf(AVBPrint *bp, const uint8_t *data, + const uint8_t *data_end) +{ + z_stream zstream; + unsigned char *buf; + unsigned buf_size; + int ret; + + zstream.zalloc = ff_png_zalloc; + zstream.zfree = ff_png_zfree; + zstream.opaque = NULL; + if (inflateInit(&zstream) != Z_OK) + return AVERROR_EXTERNAL; + zstream.next_in = (unsigned char *)data; + zstream.avail_in = data_end - data; + av_bprint_init(bp, 0, -1); + + while (zstream.avail_in > 0) { + av_bprint_get_buffer(bp, 2, &buf, &buf_size); + if (buf_size < 2) { + ret = AVERROR(ENOMEM); + goto fail; + } + zstream.next_out = buf; + zstream.avail_out = buf_size - 1; + ret = inflate(&zstream, Z_PARTIAL_FLUSH); + if (ret != Z_OK && ret != Z_STREAM_END) { + ret = AVERROR_EXTERNAL; + goto fail; + } + bp->len += zstream.next_out - buf; + if (ret == Z_STREAM_END) + break; + } + inflateEnd(&zstream); + bp->str[bp->len] = 0; + return 0; + +fail: + inflateEnd(&zstream); + av_bprint_finalize(bp, NULL); + return ret; +} +``` diff --git a/tasks/csa159/pair_4869/pre_functions.txt b/tasks/csa159/pair_4869/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..3947c7511603afe26bfe5731a77d6964e3f80fe6 --- /dev/null +++ b/tasks/csa159/pair_4869/pre_functions.txt @@ -0,0 +1,46 @@ +### File: libavcodec/pngdec.c +```c +static int decode_zbuf(AVBPrint *bp, const uint8_t *data, + const uint8_t *data_end) +{ + z_stream zstream; + unsigned char *buf; + unsigned buf_size; + int ret; + + zstream.zalloc = ff_png_zalloc; + zstream.zfree = ff_png_zfree; + zstream.opaque = NULL; + if (inflateInit(&zstream) != Z_OK) + return AVERROR_EXTERNAL; + zstream.next_in = (unsigned char *)data; + zstream.avail_in = data_end - data; + av_bprint_init(bp, 0, -1); + + while (zstream.avail_in > 0) { + av_bprint_get_buffer(bp, 1, &buf, &buf_size); + if (!buf_size) { + ret = AVERROR(ENOMEM); + goto fail; + } + zstream.next_out = buf; + zstream.avail_out = buf_size; + ret = inflate(&zstream, Z_PARTIAL_FLUSH); + if (ret != Z_OK && ret != Z_STREAM_END) { + ret = AVERROR_EXTERNAL; + goto fail; + } + bp->len += zstream.next_out - buf; + if (ret == Z_STREAM_END) + break; + } + inflateEnd(&zstream); + bp->str[bp->len] = 0; + return 0; + +fail: + inflateEnd(&zstream); + av_bprint_finalize(bp, NULL); + return ret; +} +``` diff --git a/tasks/csa159/pair_4869/task_prompt.md b/tasks/csa159/pair_4869/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_4869/task_prompt.md @@ -0,0 +1,318 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` diff --git a/tasks/csa159/pair_6060/checker_template.cpp b/tasks/csa159/pair_6060/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_6060/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_6060/config.json b/tasks/csa159/pair_6060/config.json new file mode 100644 index 0000000000000000000000000000000000000000..186e290b518a8b1b4ae096b761b8a73c6b8e6fe1 --- /dev/null +++ b/tasks/csa159/pair_6060/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "FreeRDP_FreeRDP", + "before_commit": "733ee3208306b1ea32697b356c0215180fc3f049", + "after_commit": "b8beb55913471952f92770c90c372139d78c16c0", + "repo_path": "/workspace/repo/FreeRDP/FreeRDP", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FreeRDP_FreeRDP/1628939227fa82fa492f068f178f0cc0a42c518b/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FreeRDP_FreeRDP/1628939227fa82fa492f068f178f0cc0a42c518b/compile_commands.json", + "changed_files": [ + "libfreerdp/core/orders.c" + ], + "commit_message": "Fixed OOB read in update_read_cache_bitmap_v3_order\n\nCVE-2020-11096 thanks @antonio-morales for finding this.", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_6060/patch.diff b/tasks/csa159/pair_6060/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..83edf4fedd00fc08d1531948a87df9e383be3a10 --- /dev/null +++ b/tasks/csa159/pair_6060/patch.diff @@ -0,0 +1,234 @@ +diff --git a/libfreerdp/core/orders.c b/libfreerdp/core/orders.c +index 90d79f54d..744bf3cd6 100644 +--- a/libfreerdp/core/orders.c ++++ b/libfreerdp/core/orders.c +@@ -113,20 +113,74 @@ BYTE get_primary_drawing_order_field_bytes(UINT32 orderType, BOOL* pValid) + } + } + +-static const BYTE CBR2_BPP[] = { 0, 0, 0, 8, 16, 24, 32 }; +- +-static const BYTE BPP_CBR2[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, +- 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 }; +- +-static const BYTE CBR23_BPP[] = { 0, 0, 0, 8, 16, 24, 32 }; +- +-static const BYTE BPP_CBR23[] = { 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, +- 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 }; +- +-static const BYTE BMF_BPP[] = { 0, 1, 0, 8, 16, 24, 32, 0 }; ++static BYTE get_cbr2_bpp(UINT32 bpp, BOOL* pValid) ++{ ++ if (pValid) ++ *pValid = TRUE; ++ switch (bpp) ++ { ++ case 3: ++ return 8; ++ case 4: ++ return 16; ++ case 5: ++ return 24; ++ case 6: ++ return 32; ++ default: ++ WLog_WARN(TAG, "Invalid bpp %" PRIu32, bpp); ++ if (pValid) ++ *pValid = FALSE; ++ return 0; ++ } ++} + +-static const BYTE BPP_BMF[] = { 0, 1, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, +- 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0 }; ++static BYTE get_bmf_bpp(UINT32 bmf, BOOL* pValid) ++{ ++ if (pValid) ++ *pValid = TRUE; ++ switch (bmf) ++ { ++ case 1: ++ return 1; ++ case 3: ++ return 8; ++ case 4: ++ return 16; ++ case 5: ++ return 24; ++ case 6: ++ return 32; ++ default: ++ WLog_WARN(TAG, "Invalid bmf %" PRIu32, bmf); ++ if (pValid) ++ *pValid = FALSE; ++ return 0; ++ } ++} ++static BYTE get_bpp_bmf(UINT32 bpp, BOOL* pValid) ++{ ++ if (pValid) ++ *pValid = TRUE; ++ switch (bpp) ++ { ++ case 1: ++ return 1; ++ case 8: ++ return 3; ++ case 16: ++ return 4; ++ case 24: ++ return 5; ++ case 32: ++ return 6; ++ default: ++ WLog_WARN(TAG, "Invalid color depth %" PRIu32, bpp); ++ if (pValid) ++ *pValid = FALSE; ++ return 0; ++ } ++} + + static BOOL check_order_activated(wLog* log, rdpSettings* settings, const char* orderName, + BOOL condition) +@@ -814,9 +868,11 @@ static INLINE BOOL update_read_brush(wStream* s, rdpBrush* brush, BYTE fieldFlag + + if (brush->style & CACHED_BRUSH) + { ++ BOOL rc; + brush->index = brush->hatch; +- brush->bpp = BMF_BPP[brush->style & 0x07]; +- ++ brush->bpp = get_bmf_bpp(brush->style, &rc); ++ if (!rc) ++ return FALSE; + if (brush->bpp == 0) + brush->bpp = 1; + } +@@ -858,9 +914,11 @@ static INLINE BOOL update_write_brush(wStream* s, rdpBrush* brush, BYTE fieldFla + + if (brush->style & CACHED_BRUSH) + { ++ BOOL rc; + brush->hatch = brush->index; +- brush->bpp = BMF_BPP[brush->style & 0x07]; +- ++ brush->bpp = get_bmf_bpp(brush->style, &rc); ++ if (!rc) ++ return FALSE; + if (brush->bpp == 0) + brush->bpp = 1; + } +@@ -2016,6 +2074,7 @@ BOOL update_write_cache_bitmap_order(wStream* s, const CACHE_BITMAP_ORDER* cache + static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s, + BOOL compressed, UINT16 flags) + { ++ BOOL rc; + BYTE bitsPerPixelId; + CACHE_BITMAP_V2_ORDER* cache_bitmap_v2; + +@@ -2030,7 +2089,9 @@ static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* updat + cache_bitmap_v2->cacheId = flags & 0x0003; + cache_bitmap_v2->flags = (flags & 0xFF80) >> 7; + bitsPerPixelId = (flags & 0x0078) >> 3; +- cache_bitmap_v2->bitmapBpp = CBR2_BPP[bitsPerPixelId]; ++ cache_bitmap_v2->bitmapBpp = get_cbr2_bpp(bitsPerPixelId, &rc); ++ if (!rc) ++ goto fail; + + if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT) + { +@@ -2109,13 +2170,16 @@ int update_approximate_cache_bitmap_v2_order(CACHE_BITMAP_V2_ORDER* cache_bitmap + BOOL update_write_cache_bitmap_v2_order(wStream* s, CACHE_BITMAP_V2_ORDER* cache_bitmap_v2, + BOOL compressed, UINT16* flags) + { ++ BOOL rc; + BYTE bitsPerPixelId; + + if (!Stream_EnsureRemainingCapacity( + s, update_approximate_cache_bitmap_v2_order(cache_bitmap_v2, compressed, flags))) + return FALSE; + +- bitsPerPixelId = BPP_CBR2[cache_bitmap_v2->bitmapBpp]; ++ bitsPerPixelId = get_bpp_bmf(cache_bitmap_v2->bitmapBpp, &rc); ++ if (!rc) ++ return FALSE; + *flags = (cache_bitmap_v2->cacheId & 0x0003) | (bitsPerPixelId << 3) | + ((cache_bitmap_v2->flags << 7) & 0xFF80); + +@@ -2177,6 +2241,7 @@ BOOL update_write_cache_bitmap_v2_order(wStream* s, CACHE_BITMAP_V2_ORDER* cache + static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* update, wStream* s, + UINT16 flags) + { ++ BOOL rc; + BYTE bitsPerPixelId; + BITMAP_DATA_EX* bitmapData; + UINT32 new_len; +@@ -2194,7 +2259,9 @@ static CACHE_BITMAP_V3_ORDER* update_read_cache_bitmap_v3_order(rdpUpdate* updat + cache_bitmap_v3->cacheId = flags & 0x00000003; + cache_bitmap_v3->flags = (flags & 0x0000FF80) >> 7; + bitsPerPixelId = (flags & 0x00000078) >> 3; +- cache_bitmap_v3->bpp = CBR23_BPP[bitsPerPixelId]; ++ cache_bitmap_v3->bpp = get_cbr2_bpp(bitsPerPixelId, &rc); ++ if (!rc) ++ goto fail; + + if (Stream_GetRemainingLength(s) < 21) + goto fail; +@@ -2242,6 +2309,7 @@ int update_approximate_cache_bitmap_v3_order(CACHE_BITMAP_V3_ORDER* cache_bitmap + BOOL update_write_cache_bitmap_v3_order(wStream* s, CACHE_BITMAP_V3_ORDER* cache_bitmap_v3, + UINT16* flags) + { ++ BOOL rc; + BYTE bitsPerPixelId; + BITMAP_DATA_EX* bitmapData; + +@@ -2250,7 +2318,9 @@ BOOL update_write_cache_bitmap_v3_order(wStream* s, CACHE_BITMAP_V3_ORDER* cache + return FALSE; + + bitmapData = &cache_bitmap_v3->bitmapData; +- bitsPerPixelId = BPP_CBR23[cache_bitmap_v3->bpp]; ++ bitsPerPixelId = get_bpp_bmf(cache_bitmap_v3->bpp, &rc); ++ if (!rc) ++ return FALSE; + *flags = (cache_bitmap_v3->cacheId & 0x00000003) | + ((cache_bitmap_v3->flags << 7) & 0x0000FF80) | ((bitsPerPixelId << 3) & 0x00000078); + Stream_Write_UINT16(s, cache_bitmap_v3->cacheIndex); /* cacheIndex (2 bytes) */ +@@ -2574,6 +2644,7 @@ static BOOL update_compress_brush(wStream* s, const BYTE* input, BYTE bpp) + static CACHE_BRUSH_ORDER* update_read_cache_brush_order(rdpUpdate* update, wStream* s, UINT16 flags) + { + int i; ++ BOOL rc; + BYTE iBitmapFormat; + BOOL compressed = FALSE; + CACHE_BRUSH_ORDER* cache_brush = calloc(1, sizeof(CACHE_BRUSH_ORDER)); +@@ -2587,10 +2658,10 @@ static CACHE_BRUSH_ORDER* update_read_cache_brush_order(rdpUpdate* update, wStre + Stream_Read_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */ + Stream_Read_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */ + +- if (iBitmapFormat >= ARRAYSIZE(BMF_BPP)) ++ cache_brush->bpp = get_bmf_bpp(iBitmapFormat, &rc); ++ if (!rc) + goto fail; + +- cache_brush->bpp = BMF_BPP[iBitmapFormat]; + Stream_Read_UINT8(s, cache_brush->cx); /* cx (1 byte) */ + Stream_Read_UINT8(s, cache_brush->cy); /* cy (1 byte) */ + Stream_Read_UINT8(s, cache_brush->style); /* style (1 byte) */ +@@ -2661,13 +2732,16 @@ BOOL update_write_cache_brush_order(wStream* s, const CACHE_BRUSH_ORDER* cache_b + { + int i; + BYTE iBitmapFormat; ++ BOOL rc; + BOOL compressed = FALSE; + + if (!Stream_EnsureRemainingCapacity(s, + update_approximate_cache_brush_order(cache_brush, flags))) + return FALSE; + +- iBitmapFormat = BPP_BMF[cache_brush->bpp]; ++ iBitmapFormat = get_bpp_bmf(cache_brush->bpp, &rc); ++ if (!rc) ++ return FALSE; + Stream_Write_UINT8(s, cache_brush->index); /* cacheEntry (1 byte) */ + Stream_Write_UINT8(s, iBitmapFormat); /* iBitmapFormat (1 byte) */ + Stream_Write_UINT8(s, cache_brush->cx); /* cx (1 byte) */ \ No newline at end of file diff --git a/tasks/csa159/pair_6060/post_functions.txt b/tasks/csa159/pair_6060/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..0fb5d6fd38f7d5e081478219f5f340b47f37ddef --- /dev/null +++ b/tasks/csa159/pair_6060/post_functions.txt @@ -0,0 +1,336 @@ +### File: libfreerdp/core/orders.c +```c +BYTE get_primary_drawing_order_field_bytes(UINT32 orderType, BOOL* pValid) +{ + if (pValid) + *pValid = TRUE; + switch (orderType) + { + case 0: + return DSTBLT_ORDER_FIELD_BYTES; + case 1: + return PATBLT_ORDER_FIELD_BYTES; + case 2: + return SCRBLT_ORDER_FIELD_BYTES; + case 3: + return 0; + case 4: + return 0; + case 5: + return 0; + case 6: + return 0; + case 7: + return DRAW_NINE_GRID_ORDER_FIELD_BYTES; + case 8: + return MULTI_DRAW_NINE_GRID_ORDER_FIELD_BYTES; + case 9: + return LINE_TO_ORDER_FIELD_BYTES; + case 10: + return OPAQUE_RECT_ORDER_FIELD_BYTES; + case 11: + return SAVE_BITMAP_ORDER_FIELD_BYTES; + case 12: + return 0; + case 13: + return MEMBLT_ORDER_FIELD_BYTES; + case 14: + return MEM3BLT_ORDER_FIELD_BYTES; + case 15: + return MULTI_DSTBLT_ORDER_FIELD_BYTES; + case 16: + return MULTI_PATBLT_ORDER_FIELD_BYTES; + case 17: + return MULTI_SCRBLT_ORDER_FIELD_BYTES; + case 18: + return MULTI_OPAQUE_RECT_ORDER_FIELD_BYTES; + case 19: + return FAST_INDEX_ORDER_FIELD_BYTES; + case 20: + return POLYGON_SC_ORDER_FIELD_BYTES; + case 21: + return POLYGON_CB_ORDER_FIELD_BYTES; + case 22: + return POLYLINE_ORDER_FIELD_BYTES; + case 23: + return 0; + case 24: + return FAST_GLYPH_ORDER_FIELD_BYTES; + case 25: + return ELLIPSE_SC_ORDER_FIELD_BYTES; + case 26: + return ELLIPSE_CB_ORDER_FIELD_BYTES; + case 27: + return GLYPH_INDEX_ORDER_FIELD_BYTES; + default: + if (pValid) + *pValid = FALSE; + WLog_WARN(TAG, "Invalid orderType 0x%08X received", orderType); + return 0; + } +} + +static BYTE get_cbr2_bpp(UINT32 bpp, BOOL* pValid) +{ + if (pValid) + *pValid = TRUE; + switch (bpp) + { + case 3: + return 8; + case 4: + return 16; + case 5: + return 24; + case 6: + return 32; + default: + WLog_WARN(TAG, "Invalid bpp %" PRIu32, bpp); + if (pValid) + *pValid = FALSE; + return 0; + } +} + +static INLINE BOOL update_read_delta(wStream* s, INT32* value) +{ + BYTE byte; + + if (Stream_GetRemainingLength(s) < 1) + { + WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); + return FALSE; + } + + Stream_Read_UINT8(s, byte); + + if (byte & 0x40) + *value = (byte | ~0x3F); + else + *value = (byte & 0x3F); + + if (byte & 0x80) + { + if (Stream_GetRemainingLength(s) < 1) + { + WLog_ERR(TAG, "Stream_GetRemainingLength(s) < 1"); + return FALSE; + } + + Stream_Read_UINT8(s, byte); + *value = (*value << 8) | byte; + } + + return TRUE; +} + +static INLINE void update_read_glyph_delta(wStream* s, UINT16* value) +{ + BYTE byte; + Stream_Read_UINT8(s, byte); + + if (byte == 0x80) + Stream_Read_UINT16(s, *value); + else + *value = (byte & 0x3F); +} + +static INLINE BOOL update_read_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags) +{ + if (fieldFlags & ORDER_FIELD_01) + { + if (Stream_GetRemainingLength(s) < 1) + return FALSE; + + Stream_Read_UINT8(s, brush->x); + } + + if (fieldFlags & ORDER_FIELD_02) + { + if (Stream_GetRemainingLength(s) < 1) + return FALSE; + + Stream_Read_UINT8(s, brush->y); + } + + if (fieldFlags & ORDER_FIELD_03) + { + if (Stream_GetRemainingLength(s) < 1) + return FALSE; + + Stream_Read_UINT8(s, brush->style); + } + + if (fieldFlags & ORDER_FIELD_04) + { + if (Stream_GetRemainingLength(s) < 1) + return FALSE; + + Stream_Read_UINT8(s, brush->hatch); + } + + if (brush->style & CACHED_BRUSH) + { + BOOL rc; + brush->index = brush->hatch; + brush->bpp = get_bmf_bpp(brush->style, &rc); + if (!rc) + return FALSE; + if (brush->bpp == 0) + brush->bpp = 1; + } + + if (fieldFlags & ORDER_FIELD_05) + { + if (Stream_GetRemainingLength(s) < 7) + return FALSE; + + brush->data = (BYTE*)brush->p8x8; + Stream_Read_UINT8(s, brush->data[7]); + Stream_Read_UINT8(s, brush->data[6]); + Stream_Read_UINT8(s, brush->data[5]); + Stream_Read_UINT8(s, brush->data[4]); + Stream_Read_UINT8(s, brush->data[3]); + Stream_Read_UINT8(s, brush->data[2]); + Stream_Read_UINT8(s, brush->data[1]); + brush->data[0] = brush->hatch; + } + + return TRUE; +} + +static CACHE_BITMAP_ORDER* update_read_cache_bitmap_order(rdpUpdate* update, wStream* s, + BOOL compressed, UINT16 flags) +{ + CACHE_BITMAP_ORDER* cache_bitmap; + + if (!update || !s) + return NULL; + + cache_bitmap = calloc(1, sizeof(CACHE_BITMAP_ORDER)); + + if (!cache_bitmap) + goto fail; + + if (Stream_GetRemainingLength(s) < 9) + goto fail; + + Stream_Read_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */ + Stream_Seek_UINT8(s); /* pad1Octet (1 byte) */ + Stream_Read_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */ + Stream_Read_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */ + Stream_Read_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */ + + if ((cache_bitmap->bitmapBpp < 1) || (cache_bitmap->bitmapBpp > 32)) + { + WLog_Print(update->log, WLOG_ERROR, "invalid bitmap bpp %" PRIu32 "", + cache_bitmap->bitmapBpp); + goto fail; + } + + Stream_Read_UINT16(s, cache_bitmap->bitmapLength); /* bitmapLength (2 bytes) */ + Stream_Read_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */ + + if (compressed) + { + if ((flags & NO_BITMAP_COMPRESSION_HDR) == 0) + { + BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr); + + if (Stream_GetRemainingLength(s) < 8) + goto fail; + + Stream_Read(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */ + cache_bitmap->bitmapLength -= 8; + } + } + + if (cache_bitmap->bitmapLength == 0) + goto fail; + + if (Stream_GetRemainingLength(s) < cache_bitmap->bitmapLength) + goto fail; + + cache_bitmap->bitmapDataStream = malloc(cache_bitmap->bitmapLength); + + if (!cache_bitmap->bitmapDataStream) + goto fail; + + Stream_Read(s, cache_bitmap->bitmapDataStream, cache_bitmap->bitmapLength); + cache_bitmap->compressed = compressed; + return cache_bitmap; +fail: + free_cache_bitmap_order(update->context, cache_bitmap); + return NULL; +} + +int update_approximate_cache_bitmap_order(const CACHE_BITMAP_ORDER* cache_bitmap, BOOL compressed, + UINT16* flags) +{ + return 64 + cache_bitmap->bitmapLength; +} + +BOOL update_write_cache_bitmap_order(wStream* s, const CACHE_BITMAP_ORDER* cache_bitmap, + BOOL compressed, UINT16* flags) +{ + UINT32 bitmapLength = cache_bitmap->bitmapLength; + int inf = update_approximate_cache_bitmap_order(cache_bitmap, compressed, flags); + + if (!Stream_EnsureRemainingCapacity(s, inf)) + return FALSE; + + *flags = NO_BITMAP_COMPRESSION_HDR; + + if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0) + bitmapLength += 8; + + Stream_Write_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */ + Stream_Write_UINT8(s, 0); /* pad1Octet (1 byte) */ + Stream_Write_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */ + Stream_Write_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */ + Stream_Write_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */ + Stream_Write_UINT16(s, bitmapLength); /* bitmapLength (2 bytes) */ + Stream_Write_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */ + + if (compressed) + { + if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0) + { + BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr); + Stream_Write(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */ + bitmapLength -= 8; + } + + Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength); + } + else + { + Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength); + } + + return TRUE; +} + +static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s, + BOOL compressed, UINT16 flags) +{ + BOOL rc; + BYTE bitsPerPixelId; + CACHE_BITMAP_V2_ORDER* cache_bitmap_v2; + + if (!update || !s) + return NULL; + + cache_bitmap_v2 = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER)); + + if (!cache_bitmap_v2) + goto fail; + + cache_bitmap_v2->cacheId = flags & 0x0003; + cache_bitmap_v2->flags = (flags & 0xFF80) >> 7; + bitsPerPixelId = (flags & 0x0078) >> 3; + cache_bitmap_v2->bitmapBpp = get_cbr2_bpp(bitsPerPixelId, &rc); + if (!rc) + +// ... (9904 more chars) +``` diff --git a/tasks/csa159/pair_6060/pre_functions.txt b/tasks/csa159/pair_6060/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..83e1395420860ca59679669cc74a6ba50ced7af4 --- /dev/null +++ b/tasks/csa159/pair_6060/pre_functions.txt @@ -0,0 +1,318 @@ +### File: libfreerdp/core/orders.c +```c +BYTE get_primary_drawing_order_field_bytes(UINT32 orderType, BOOL* pValid) +{ + if (pValid) + *pValid = TRUE; + switch (orderType) + { + case 0: + return DSTBLT_ORDER_FIELD_BYTES; + case 1: + return PATBLT_ORDER_FIELD_BYTES; + case 2: + return SCRBLT_ORDER_FIELD_BYTES; + case 3: + return 0; + case 4: + return 0; + case 5: + return 0; + case 6: + return 0; + case 7: + return DRAW_NINE_GRID_ORDER_FIELD_BYTES; + case 8: + return MULTI_DRAW_NINE_GRID_ORDER_FIELD_BYTES; + case 9: + return LINE_TO_ORDER_FIELD_BYTES; + case 10: + return OPAQUE_RECT_ORDER_FIELD_BYTES; + case 11: + return SAVE_BITMAP_ORDER_FIELD_BYTES; + case 12: + return 0; + case 13: + return MEMBLT_ORDER_FIELD_BYTES; + case 14: + return MEM3BLT_ORDER_FIELD_BYTES; + case 15: + return MULTI_DSTBLT_ORDER_FIELD_BYTES; + case 16: + return MULTI_PATBLT_ORDER_FIELD_BYTES; + case 17: + return MULTI_SCRBLT_ORDER_FIELD_BYTES; + case 18: + return MULTI_OPAQUE_RECT_ORDER_FIELD_BYTES; + case 19: + return FAST_INDEX_ORDER_FIELD_BYTES; + case 20: + return POLYGON_SC_ORDER_FIELD_BYTES; + case 21: + return POLYGON_CB_ORDER_FIELD_BYTES; + case 22: + return POLYLINE_ORDER_FIELD_BYTES; + case 23: + return 0; + case 24: + return FAST_GLYPH_ORDER_FIELD_BYTES; + case 25: + return ELLIPSE_SC_ORDER_FIELD_BYTES; + case 26: + return ELLIPSE_CB_ORDER_FIELD_BYTES; + case 27: + return GLYPH_INDEX_ORDER_FIELD_BYTES; + default: + if (pValid) + *pValid = FALSE; + WLog_WARN(TAG, "Invalid orderType 0x%08X received", orderType); + return 0; + } +} + +static BOOL check_order_activated(wLog* log, rdpSettings* settings, const char* orderName, + BOOL condition) +{ + if (!condition) + { + if (settings->AllowUnanouncedOrdersFromServer) + { + WLog_Print(log, WLOG_WARN, + "%s - SERVER BUG: The support for this feature was not announced!", + orderName); + return TRUE; + } + else + { + WLog_Print(log, WLOG_ERROR, + "%s - SERVER BUG: The support for this feature was not announced! Use " + "/relax-order-checks to ignore", + orderName); + return FALSE; + } + } + + return TRUE; +} + +static INLINE BOOL update_read_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags) +{ + if (fieldFlags & ORDER_FIELD_01) + { + if (Stream_GetRemainingLength(s) < 1) + return FALSE; + + Stream_Read_UINT8(s, brush->x); + } + + if (fieldFlags & ORDER_FIELD_02) + { + if (Stream_GetRemainingLength(s) < 1) + return FALSE; + + Stream_Read_UINT8(s, brush->y); + } + + if (fieldFlags & ORDER_FIELD_03) + { + if (Stream_GetRemainingLength(s) < 1) + return FALSE; + + Stream_Read_UINT8(s, brush->style); + } + + if (fieldFlags & ORDER_FIELD_04) + { + if (Stream_GetRemainingLength(s) < 1) + return FALSE; + + Stream_Read_UINT8(s, brush->hatch); + } + + if (brush->style & CACHED_BRUSH) + { + brush->index = brush->hatch; + brush->bpp = BMF_BPP[brush->style & 0x07]; + + if (brush->bpp == 0) + brush->bpp = 1; + } + + if (fieldFlags & ORDER_FIELD_05) + { + if (Stream_GetRemainingLength(s) < 7) + return FALSE; + + brush->data = (BYTE*)brush->p8x8; + Stream_Read_UINT8(s, brush->data[7]); + Stream_Read_UINT8(s, brush->data[6]); + Stream_Read_UINT8(s, brush->data[5]); + Stream_Read_UINT8(s, brush->data[4]); + Stream_Read_UINT8(s, brush->data[3]); + Stream_Read_UINT8(s, brush->data[2]); + Stream_Read_UINT8(s, brush->data[1]); + brush->data[0] = brush->hatch; + } + + return TRUE; +} + +static INLINE BOOL update_write_brush(wStream* s, rdpBrush* brush, BYTE fieldFlags) +{ + if (fieldFlags & ORDER_FIELD_01) + { + Stream_Write_UINT8(s, brush->x); + } + + if (fieldFlags & ORDER_FIELD_02) + { + Stream_Write_UINT8(s, brush->y); + } + + if (fieldFlags & ORDER_FIELD_03) + { + Stream_Write_UINT8(s, brush->style); + } + + if (brush->style & CACHED_BRUSH) + { + brush->hatch = brush->index; + brush->bpp = BMF_BPP[brush->style & 0x07]; + + if (brush->bpp == 0) + brush->bpp = 1; + } + + if (fieldFlags & ORDER_FIELD_04) + { + Stream_Write_UINT8(s, brush->hatch); + } + + if (fieldFlags & ORDER_FIELD_05) + { + brush->data = (BYTE*)brush->p8x8; + Stream_Write_UINT8(s, brush->data[7]); + Stream_Write_UINT8(s, brush->data[6]); + Stream_Write_UINT8(s, brush->data[5]); + Stream_Write_UINT8(s, brush->data[4]); + Stream_Write_UINT8(s, brush->data[3]); + Stream_Write_UINT8(s, brush->data[2]); + Stream_Write_UINT8(s, brush->data[1]); + brush->data[0] = brush->hatch; + } + + return TRUE; +} + +BOOL update_write_cache_bitmap_order(wStream* s, const CACHE_BITMAP_ORDER* cache_bitmap, + BOOL compressed, UINT16* flags) +{ + UINT32 bitmapLength = cache_bitmap->bitmapLength; + int inf = update_approximate_cache_bitmap_order(cache_bitmap, compressed, flags); + + if (!Stream_EnsureRemainingCapacity(s, inf)) + return FALSE; + + *flags = NO_BITMAP_COMPRESSION_HDR; + + if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0) + bitmapLength += 8; + + Stream_Write_UINT8(s, cache_bitmap->cacheId); /* cacheId (1 byte) */ + Stream_Write_UINT8(s, 0); /* pad1Octet (1 byte) */ + Stream_Write_UINT8(s, cache_bitmap->bitmapWidth); /* bitmapWidth (1 byte) */ + Stream_Write_UINT8(s, cache_bitmap->bitmapHeight); /* bitmapHeight (1 byte) */ + Stream_Write_UINT8(s, cache_bitmap->bitmapBpp); /* bitmapBpp (1 byte) */ + Stream_Write_UINT16(s, bitmapLength); /* bitmapLength (2 bytes) */ + Stream_Write_UINT16(s, cache_bitmap->cacheIndex); /* cacheIndex (2 bytes) */ + + if (compressed) + { + if ((*flags & NO_BITMAP_COMPRESSION_HDR) == 0) + { + BYTE* bitmapComprHdr = (BYTE*)&(cache_bitmap->bitmapComprHdr); + Stream_Write(s, bitmapComprHdr, 8); /* bitmapComprHdr (8 bytes) */ + bitmapLength -= 8; + } + + Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength); + } + else + { + Stream_Write(s, cache_bitmap->bitmapDataStream, bitmapLength); + } + + return TRUE; +} + +static CACHE_BITMAP_V2_ORDER* update_read_cache_bitmap_v2_order(rdpUpdate* update, wStream* s, + BOOL compressed, UINT16 flags) +{ + BYTE bitsPerPixelId; + CACHE_BITMAP_V2_ORDER* cache_bitmap_v2; + + if (!update || !s) + return NULL; + + cache_bitmap_v2 = calloc(1, sizeof(CACHE_BITMAP_V2_ORDER)); + + if (!cache_bitmap_v2) + goto fail; + + cache_bitmap_v2->cacheId = flags & 0x0003; + cache_bitmap_v2->flags = (flags & 0xFF80) >> 7; + bitsPerPixelId = (flags & 0x0078) >> 3; + cache_bitmap_v2->bitmapBpp = CBR2_BPP[bitsPerPixelId]; + + if (cache_bitmap_v2->flags & CBR2_PERSISTENT_KEY_PRESENT) + { + if (Stream_GetRemainingLength(s) < 8) + goto fail; + + Stream_Read_UINT32(s, cache_bitmap_v2->key1); /* key1 (4 bytes) */ + Stream_Read_UINT32(s, cache_bitmap_v2->key2); /* key2 (4 bytes) */ + } + + if (cache_bitmap_v2->flags & CBR2_HEIGHT_SAME_AS_WIDTH) + { + if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth)) /* bitmapWidth */ + goto fail; + + cache_bitmap_v2->bitmapHeight = cache_bitmap_v2->bitmapWidth; + } + else + { + if (!update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapWidth) || /* bitmapWidth */ + !update_read_2byte_unsigned(s, &cache_bitmap_v2->bitmapHeight)) /* bitmapHeight */ + goto fail; + } + + if (!update_read_4byte_unsigned(s, &cache_bitmap_v2->bitmapLength) || /* bitmapLength */ + !update_read_2byte_unsigned(s, &cache_bitmap_v2->cacheIndex)) /* cacheIndex */ + goto fail; + + if (cache_bitmap_v2->flags & CBR2_DO_NOT_CACHE) + cache_bitmap_v2->cacheIndex = BITMAP_CACHE_WAITING_LIST_INDEX; + + if (compressed) + { + if (!(cache_bitmap_v2->flags & CBR2_NO_BITMAP_COMPRESSION_HDR)) + { + if (Stream_GetRemainingLength(s) < 8) + goto fail; + + Stream_Read_UINT16( + s, cache_bitmap_v2->cbCompFirstRowSize); /* cbCompFirstRowSize (2 bytes) */ + Stream_Read_UINT16( + s, cache_bitmap_v2->cbCompMainBodySize); /* cbCompMainBodySize (2 bytes) */ + Stream_Read_UINT16(s, cache_bitmap_v2->cbScanWidth); /* cbScanWidth (2 bytes) */ + Stream_Read_UINT16( + s, cache_bitmap_v2->cbUncompressedSize); /* cbUncompressedSize (2 bytes) */ + cache_bitmap_v2->bitmapLength = cache_bitmap_v2->cbCompMainBodySize; + } + } + + + +// ... (10828 more chars) +``` diff --git a/tasks/csa159/pair_6060/task_prompt.md b/tasks/csa159/pair_6060/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..3d22f335bef7150558d1ec425f831fae36945adf --- /dev/null +++ b/tasks/csa159/pair_6060/task_prompt.md @@ -0,0 +1,387 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `control_flow` + +### Current failure diagnosis + +- The rollout failed the process-quality threshold despite compiling, passing paired validation, and producing five relevant pre-patch diagnostics with none post-patch. +- The syntax-only interval design over-approximated the defect because it ignored reachability and dominating bounds checks; notably, BMF_BPP[iBitmapFormat] is reached only after iBitmapFormat values at or above the table extent branch to fail. +- Function-wide assignment collection ignored statement order and controlling branches, so it could associate definitions that do not reach a subscript. +- The claimed tightness of interval endpoints was unsound for correlated expressions such as x-x and for some transformed masked values. +- The analysis incorrectly characterized lookup operations in write-side functions as out-of-bounds writes; these are out-of-bounds reads from lookup tables used while serializing output. +- The plan underrepresented the patch's rejection of unsupported but array-in-bounds encodings, which is distinct from memory bounds safety. + +### Preserve from prior rollouts + +- The synthesized checker must compile successfully and retain successful before/after validation and code verification. +- Retain objective eligibility gate G6. +- Retain an accepted or clean refinement outcome. +- Use a CSA mechanism at least as strong as the previously accepted syntax-only mechanism. +- Maintain the semantic score at or above the configured threshold. +- Raise and maintain process quality at or above the configured threshold. +- Remain independent of patch anchors such as changed line numbers, commit identifiers, function names, accessor names, and deleted table names. +- Remain free of patch-local hardcoding and project-specific scope. + +### Required semantic proof + +- At each qualifying ArraySubscriptExpr, establish that the base denotes a fixed-extent constant integer array with extent N. +- Establish from sound integer-domain evidence that an index value below zero or at least N can reach the subscript along a feasible CFG path. +- Treat a bounds check as protective only when its in-bounds successor dominates or otherwise necessarily controls the subscript and the rejecting successor cannot reach it. +- Suppress BMF_BPP[iBitmapFormat] when the preceding iBitmapFormat >= ARRAYSIZE(BMF_BPP) check transfers all out-of-range values to fail before the access. +- Report the unguarded CBR2_BPP, CBR23_BPP, BPP_CBR2, BPP_CBR23, and BPP_BMF accesses where their reachable index domains exceed their extents. +- Distinguish memory-safety proof from accepted-encoding validation: unsupported values that remain within the old array extent are not OOB solely because the patch later rejects them. + +### Implementation constraints + +- Use a CSA callback and local CFG analysis capable of relating an ArraySubscriptExpr to preceding guards, assignments, branches, and terminating or fail edges; control-flow reasoning is required, but ProgramState tracking and interprocedural propagation are not. +- Compute reaching definitions or equivalent ordered local facts rather than collecting every assignment in the function without regard to CFG position. +- Use sound AST and type semantics for constants, casts, masks, shifts, and integer ranges; do not claim endpoint attainability when operands are correlated unless that claim is proven. +- Recognize protective comparisons in semantically equivalent operand orders and branch forms, and require the protective relation to hold on every path reaching the sink. +- Report at the unsafe array subscript and include its source range; do not report at a declaration, guard, parser call, or replacement accessor. +- Keep scope project-general through array extent, const qualification, integer element type, index semantics, and CFG relations rather than FreeRDP identifiers. +- Limit the checker to lookup-table OOB reads; do not label accesses in serialization functions as writes to the lookup table. +- Do not infer protocol-valid value sets from initializer contents such as zero entries unless a separate, evidence-backed semantic rule proves that contract. + +### Validation checklist + +- Build and load the checker against the required Clang Static Analyzer API without compilation, registration, or analyzer failures. +- Scan the vulnerable source and confirm diagnostics at the five unguarded unsafe lookup subscripts identified by paired verification. +- Confirm no diagnostic for the guarded BMF_BPP[iBitmapFormat] access because its rejecting check prevents out-of-range values from reaching the subscript. +- Scan the patched source and confirm zero diagnostics after raw lookup subscripts are replaced by validating accessors. +- Verify every vulnerable diagnostic is located on the corresponding ArraySubscriptExpr with median distance zero from the relevant patch site and no reports in non-patched functions. +- Add refinement cases for a dominating upper-bound guard, a non-dominating guard, reversed comparison operands, early return or goto rejection, and assignment after validation. +- Add arithmetic refinement cases covering correlated expressions such as x-x, masked and shifted indices, narrowing casts, signed negative ranges, and multiple reaching definitions. +- Confirm the final run preserves successful code verification, G6 eligibility, accepted refinement, semantic threshold, hardcoding-free status, anchor-free status, and the process-quality threshold. + +### Avoid and forbidden regressions + +- Do not reuse the syntax-only shortcut that reports from a declared or assignment-derived range without checking whether out-of-bounds values can reach the access. +- Do not suppress merely because a nearby statement resembles a guard; prove its CFG relationship and rejecting behavior. +- Do not perform function-wide unordered assignment aggregation. +- Do not propagate interval tightness mechanically through operations involving correlated operands. +- Do not report the guarded BMF_BPP access as vulnerable. +- Do not conflate unsupported in-bounds encodings with out-of-bounds memory access. +- Do not introduce names, line locations, table extents, mask constants, or patch-specific accessor patterns as matching anchors. +- Do not add ProgramState or interprocedural dataflow unless CFG-local proof is shown insufficient by new evidence. diff --git a/tasks/csa159/pair_6105/checker_template.cpp b/tasks/csa159/pair_6105/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_6105/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_6105/config.json b/tasks/csa159/pair_6105/config.json new file mode 100644 index 0000000000000000000000000000000000000000..67dab192215a31e33ab373a0649b412ae9050e65 --- /dev/null +++ b/tasks/csa159/pair_6105/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "FreeRDP_FreeRDP", + "before_commit": "d1112c279bd1a327e8e4d0b5f371458bf2579659", + "after_commit": "17c363a5162fd4dc77b1df54e48d7bd9bf6b3be7", + "repo_path": "/workspace/repo/FreeRDP/FreeRDP", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FreeRDP_FreeRDP/52fbfb7b1268749c2e5947542ffdd9c395b99305/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FreeRDP_FreeRDP/52fbfb7b1268749c2e5947542ffdd9c395b99305/compile_commands.json", + "changed_files": [ + "libfreerdp/codec/zgfx.c" + ], + "commit_message": "Fixed CVE-2018-8784\n\nThanks to Eyal Itkin from Check Point Software Technologies.", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_6105/patch.diff b/tasks/csa159/pair_6105/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4d6a7e28dcb4f943c2d0c330cc085345ac08e5b8 --- /dev/null +++ b/tasks/csa159/pair_6105/patch.diff @@ -0,0 +1,72 @@ +diff --git a/libfreerdp/codec/zgfx.c b/libfreerdp/codec/zgfx.c +index f94c41b20..551fffc83 100644 +--- a/libfreerdp/codec/zgfx.c ++++ b/libfreerdp/codec/zgfx.c +@@ -137,6 +137,7 @@ static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits) + _zgfx->cBitsCurrent -= _nbits; + _zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent; + _zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1); ++ return TRUE; + } + + static void zgfx_history_buffer_ring_write(ZGFX_CONTEXT* zgfx, const BYTE* src, size_t count) +@@ -229,9 +230,15 @@ static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t + UINT32 count; + UINT32 distance; + BYTE* pbSegment; +- size_t cbSegment = segmentSize - 1; ++ size_t cbSegment; + +- if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1)) ++ if (!zgfx || !stream) ++ return FALSE; ++ ++ cbSegment = segmentSize - 1; ++ ++ if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1) || ++ (segmentSize > UINT32_MAX)) + return FALSE; + + Stream_Read_UINT8(stream, flags); /* header (1 byte) */ +@@ -242,6 +249,10 @@ static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t + if (!(flags & PACKET_COMPRESSED)) + { + zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment); ++ ++ if (cbSegment > sizeof(zgfx->OutputBuffer)) ++ return FALSE; ++ + CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); + zgfx->OutputCount = cbSegment; + return TRUE; +@@ -280,6 +291,9 @@ static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t + if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize) + zgfx->HistoryIndex = 0; + ++ if (zgfx->OutputCount >= sizeof(zgfx->OutputBuffer)) ++ return FALSE; ++ + zgfx->OutputBuffer[zgfx->OutputCount++] = c; + } + else +@@ -313,6 +327,9 @@ static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t + count += zgfx->bits; + } + ++ if (count > sizeof(zgfx->OutputBuffer) - zgfx->OutputCount) ++ return FALSE; ++ + zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); + zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); + zgfx->OutputCount += count; +@@ -325,6 +342,10 @@ static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t + zgfx->cBitsRemaining -= zgfx->cBitsCurrent; + zgfx->cBitsCurrent = 0; + zgfx->BitsCurrent = 0; ++ ++ if (count > sizeof(zgfx->OutputBuffer) - zgfx->OutputCount) ++ return FALSE; ++ + CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count); + zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count); + zgfx->pbInputCurrent += count; \ No newline at end of file diff --git a/tasks/csa159/pair_6105/post_functions.txt b/tasks/csa159/pair_6105/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..82e5336ffaee04f9b0bcf87769630c87145be236 --- /dev/null +++ b/tasks/csa159/pair_6105/post_functions.txt @@ -0,0 +1,198 @@ +### File: libfreerdp/codec/zgfx.c +```c +static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits) +{ + if (!_zgfx) + return FALSE; + + while (_zgfx->cBitsCurrent < _nbits) + { + _zgfx->BitsCurrent <<= 8; + + if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd) + _zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++; + + _zgfx->cBitsCurrent += 8; + } + + _zgfx->cBitsRemaining -= _nbits; + _zgfx->cBitsCurrent -= _nbits; + _zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent; + _zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1); + return TRUE; +} + +static void zgfx_history_buffer_ring_write(ZGFX_CONTEXT* zgfx, const BYTE* src, size_t count) +{ + UINT32 front; + + if (count <= 0) + return; + + if (count > zgfx->HistoryBufferSize) + { + const size_t residue = count - zgfx->HistoryBufferSize; + count = zgfx->HistoryBufferSize; + src += residue; + zgfx->HistoryIndex = (zgfx->HistoryIndex + residue) % zgfx->HistoryBufferSize; + } + + if (zgfx->HistoryIndex + count <= zgfx->HistoryBufferSize) + { + CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, count); + + if ((zgfx->HistoryIndex += count) == zgfx->HistoryBufferSize) + zgfx->HistoryIndex = 0; + } + else + { + front = zgfx->HistoryBufferSize - zgfx->HistoryIndex; + CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, front); + CopyMemory(zgfx->HistoryBuffer, &src[front], count - front); + zgfx->HistoryIndex = count - front; + } +} + +static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize) +{ + BYTE c; + BYTE flags; + UINT32 extra = 0; + int opIndex; + int haveBits; + int inPrefix; + UINT32 count; + UINT32 distance; + BYTE* pbSegment; + size_t cbSegment; + + if (!zgfx || !stream) + return FALSE; + + cbSegment = segmentSize - 1; + + if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1) || + (segmentSize > UINT32_MAX)) + return FALSE; + + Stream_Read_UINT8(stream, flags); /* header (1 byte) */ + zgfx->OutputCount = 0; + pbSegment = Stream_Pointer(stream); + Stream_Seek(stream, cbSegment); + + if (!(flags & PACKET_COMPRESSED)) + { + zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment); + + if (cbSegment > sizeof(zgfx->OutputBuffer)) + return FALSE; + + CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); + zgfx->OutputCount = cbSegment; + return TRUE; + } + + zgfx->pbInputCurrent = pbSegment; + zgfx->pbInputEnd = &pbSegment[cbSegment - 1]; + /* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */ + zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd; + zgfx->cBitsCurrent = 0; + zgfx->BitsCurrent = 0; + + while (zgfx->cBitsRemaining) + { + haveBits = 0; + inPrefix = 0; + + for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++) + { + while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength) + { + zgfx_GetBits(zgfx, 1); + inPrefix = (inPrefix << 1) + zgfx->bits; + haveBits++; + } + + if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode) + { + if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0) + { + /* Literal */ + zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); + c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits); + zgfx->HistoryBuffer[zgfx->HistoryIndex] = c; + + if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize) + zgfx->HistoryIndex = 0; + + if (zgfx->OutputCount >= sizeof(zgfx->OutputBuffer)) + return FALSE; + + zgfx->OutputBuffer[zgfx->OutputCount++] = c; + } + else + { + zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); + distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits; + + if (distance != 0) + { + /* Match */ + zgfx_GetBits(zgfx, 1); + + if (zgfx->bits == 0) + { + count = 3; + } + else + { + count = 4; + extra = 2; + zgfx_GetBits(zgfx, 1); + + while (zgfx->bits == 1) + { + count *= 2; + extra++; + zgfx_GetBits(zgfx, 1); + } + + zgfx_GetBits(zgfx, extra); + count += zgfx->bits; + } + + if (count > sizeof(zgfx->OutputBuffer) - zgfx->OutputCount) + return FALSE; + + zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); + zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); + zgfx->OutputCount += count; + } + else + { + /* Unencoded */ + zgfx_GetBits(zgfx, 15); + count = zgfx->bits; + zgfx->cBitsRemaining -= zgfx->cBitsCurrent; + zgfx->cBitsCurrent = 0; + zgfx->BitsCurrent = 0; + + if (count > sizeof(zgfx->OutputBuffer) - zgfx->OutputCount) + return FALSE; + + CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count); + zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count); + zgfx->pbInputCurrent += count; + zgfx->cBitsRemaining -= (8 * count); + zgfx->OutputCount += count; + } + } + + break; + } + } + } + + return TRUE; +} +``` diff --git a/tasks/csa159/pair_6105/pre_functions.txt b/tasks/csa159/pair_6105/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..b1f4c6dcdd30b8ee012ce4080b61f166756538a3 --- /dev/null +++ b/tasks/csa159/pair_6105/pre_functions.txt @@ -0,0 +1,177 @@ +### File: libfreerdp/codec/zgfx.c +```c +static INLINE BOOL zgfx_GetBits(ZGFX_CONTEXT* _zgfx, UINT32 _nbits) +{ + if (!_zgfx) + return FALSE; + + while (_zgfx->cBitsCurrent < _nbits) + { + _zgfx->BitsCurrent <<= 8; + + if (_zgfx->pbInputCurrent < _zgfx->pbInputEnd) + _zgfx->BitsCurrent += *(_zgfx->pbInputCurrent)++; + + _zgfx->cBitsCurrent += 8; + } + + _zgfx->cBitsRemaining -= _nbits; + _zgfx->cBitsCurrent -= _nbits; + _zgfx->bits = _zgfx->BitsCurrent >> _zgfx->cBitsCurrent; + _zgfx->BitsCurrent &= ((1 << _zgfx->cBitsCurrent) - 1); +} + +static void zgfx_history_buffer_ring_write(ZGFX_CONTEXT* zgfx, const BYTE* src, size_t count) +{ + UINT32 front; + + if (count <= 0) + return; + + if (count > zgfx->HistoryBufferSize) + { + const size_t residue = count - zgfx->HistoryBufferSize; + count = zgfx->HistoryBufferSize; + src += residue; + zgfx->HistoryIndex = (zgfx->HistoryIndex + residue) % zgfx->HistoryBufferSize; + } + + if (zgfx->HistoryIndex + count <= zgfx->HistoryBufferSize) + { + CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, count); + + if ((zgfx->HistoryIndex += count) == zgfx->HistoryBufferSize) + zgfx->HistoryIndex = 0; + } + else + { + front = zgfx->HistoryBufferSize - zgfx->HistoryIndex; + CopyMemory(&(zgfx->HistoryBuffer[zgfx->HistoryIndex]), src, front); + CopyMemory(zgfx->HistoryBuffer, &src[front], count - front); + zgfx->HistoryIndex = count - front; + } +} + +static BOOL zgfx_decompress_segment(ZGFX_CONTEXT* zgfx, wStream* stream, size_t segmentSize) +{ + BYTE c; + BYTE flags; + UINT32 extra = 0; + int opIndex; + int haveBits; + int inPrefix; + UINT32 count; + UINT32 distance; + BYTE* pbSegment; + size_t cbSegment = segmentSize - 1; + + if ((Stream_GetRemainingLength(stream) < segmentSize) || (segmentSize < 1)) + return FALSE; + + Stream_Read_UINT8(stream, flags); /* header (1 byte) */ + zgfx->OutputCount = 0; + pbSegment = Stream_Pointer(stream); + Stream_Seek(stream, cbSegment); + + if (!(flags & PACKET_COMPRESSED)) + { + zgfx_history_buffer_ring_write(zgfx, pbSegment, cbSegment); + CopyMemory(zgfx->OutputBuffer, pbSegment, cbSegment); + zgfx->OutputCount = cbSegment; + return TRUE; + } + + zgfx->pbInputCurrent = pbSegment; + zgfx->pbInputEnd = &pbSegment[cbSegment - 1]; + /* NumberOfBitsToDecode = ((NumberOfBytesToDecode - 1) * 8) - ValueOfLastByte */ + zgfx->cBitsRemaining = 8 * (cbSegment - 1) - *zgfx->pbInputEnd; + zgfx->cBitsCurrent = 0; + zgfx->BitsCurrent = 0; + + while (zgfx->cBitsRemaining) + { + haveBits = 0; + inPrefix = 0; + + for (opIndex = 0; ZGFX_TOKEN_TABLE[opIndex].prefixLength != 0; opIndex++) + { + while (haveBits < ZGFX_TOKEN_TABLE[opIndex].prefixLength) + { + zgfx_GetBits(zgfx, 1); + inPrefix = (inPrefix << 1) + zgfx->bits; + haveBits++; + } + + if (inPrefix == ZGFX_TOKEN_TABLE[opIndex].prefixCode) + { + if (ZGFX_TOKEN_TABLE[opIndex].tokenType == 0) + { + /* Literal */ + zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); + c = (BYTE)(ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits); + zgfx->HistoryBuffer[zgfx->HistoryIndex] = c; + + if (++zgfx->HistoryIndex == zgfx->HistoryBufferSize) + zgfx->HistoryIndex = 0; + + zgfx->OutputBuffer[zgfx->OutputCount++] = c; + } + else + { + zgfx_GetBits(zgfx, ZGFX_TOKEN_TABLE[opIndex].valueBits); + distance = ZGFX_TOKEN_TABLE[opIndex].valueBase + zgfx->bits; + + if (distance != 0) + { + /* Match */ + zgfx_GetBits(zgfx, 1); + + if (zgfx->bits == 0) + { + count = 3; + } + else + { + count = 4; + extra = 2; + zgfx_GetBits(zgfx, 1); + + while (zgfx->bits == 1) + { + count *= 2; + extra++; + zgfx_GetBits(zgfx, 1); + } + + zgfx_GetBits(zgfx, extra); + count += zgfx->bits; + } + + zgfx_history_buffer_ring_read(zgfx, distance, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); + zgfx_history_buffer_ring_write(zgfx, &(zgfx->OutputBuffer[zgfx->OutputCount]), count); + zgfx->OutputCount += count; + } + else + { + /* Unencoded */ + zgfx_GetBits(zgfx, 15); + count = zgfx->bits; + zgfx->cBitsRemaining -= zgfx->cBitsCurrent; + zgfx->cBitsCurrent = 0; + zgfx->BitsCurrent = 0; + CopyMemory(&(zgfx->OutputBuffer[zgfx->OutputCount]), zgfx->pbInputCurrent, count); + zgfx_history_buffer_ring_write(zgfx, zgfx->pbInputCurrent, count); + zgfx->pbInputCurrent += count; + zgfx->cBitsRemaining -= (8 * count); + zgfx->OutputCount += count; + } + } + + break; + } + } + } + + return TRUE; +} +``` diff --git a/tasks/csa159/pair_6105/task_prompt.md b/tasks/csa159/pair_6105/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..03e3a799f06b38f06b83cc61c482e311143a8f91 --- /dev/null +++ b/tasks/csa159/pair_6105/task_prompt.md @@ -0,0 +1,385 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `path_sensitive` + +### Current failure diagnosis + +- The rollout did not converge because refinement required further feedback and the process score remained below threshold. +- One diagnostic remained on the patched match-expansion call because loop widening replaced count and OutputCount with fresh symbols, preventing the early-return guard from discharging the capacity predicate. +- The offset policy required O > E to be entailed, which avoids widening artifacts but can miss feasible unsafe offsets and therefore needs a more rigorously justified treatment. +- Suppressing every destination expressed through a local pointer was broader than the evidenced forwarded-helper case and could hide relevant writes. +- A failed analyzer invocation caused by missing project headers was validated through synthetic tests instead of directly demonstrating recovery with the original project scan configuration. + +### Preserve from prior rollouts + +- Preserve successful compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Achieve an accepted or clean refinement outcome. +- Retain at least the previously adequate path-sensitive CSA mechanism level. +- Maintain the semantic score at or above the configured threshold. +- Remain independent of patch anchors such as changed line numbers or inserted guard text. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- For each relevant write, derive E from the destination array's declared extent, O from the destination region's byte offset, and L from the write count or scalar element size. +- Report when the current path establishes an invalid destination offset or permits L > E - O after constraining O to the valid range; never evaluate unsigned E - O on a state where O may exceed E. +- Prove patched early-return paths safe only when their ProgramState constraints make the corresponding unsafe offset-and-length state infeasible. +- Cover all four evidenced sinks: the uncompressed copy at offset zero, the one-byte literal store, the match-expansion helper write, and the unencoded copy. +- Treat zero-length writes as non-writing operations and handle O == E correctly: safe only for L == 0. +- Exclude reads, source arguments, HistoryBuffer operations, and writes to unrelated arrays from the vulnerability relation. + +### Implementation constraints + +- Use check::PreCall for bulk and helper-mediated writes so destination and count SVals are inspected before execution while guard constraints remain in ProgramState. +- Use check::Bind for scalar stores, requiring an ElementRegion destination and obtaining its symbolic index from the region rather than matching an array-subscript expression. +- Model zgfx_history_buffer_ring_read at its caller-visible contract, with destination argument 2 and count argument 3, so its output write is covered without requiring helper inlining. +- Resolve the destination through MemRegion relationships to the fixed constant-size byte-array field in the ZGFX codec context, and obtain capacity from ConstantArrayType rather than a numeric literal. +- Perform comparisons with SValBuilder and ProgramState::assume on the same path state, preserving signedness and width through explicit type-aware casts. +- Emit diagnostics at the caller-side write expression or scalar store responsible for the capacity violation, without duplicate helper-body attribution. +- Keep scope project-general and structure-based; names may identify stable ZGFX types, fields, and callable write contracts, but safety must not depend on source text, guard shape, line numbers, or patch-added tokens. +- Any helper-forwarding suppression must be proven from parameter or alias provenance and must not classify arbitrary local pointers as helper-mediated destinations. + +### Validation checklist + +- Compile the synthesized checker against the supplied Clang Static Analyzer API and verify checker registration and plugin loading without diagnostics. +- Run the original project before and after scans with the correct checker name, project include paths, and captured compilation flags; do not substitute synthetic-only success for a failed project invocation. +- Confirm diagnostics on the vulnerable source for the uncompressed copy, match-expansion helper call, and unencoded copy, and separately exercise the literal scalar store when analyzer path exploration can reach it. +- Require the patched source to be clean at all four guarded writes, including the match-expansion call that previously retained a widening-induced report. +- Verify each vulnerable diagnostic is located at the relevant caller-side write or scalar store and that no duplicate report is emitted from the helper body. +- Test boundary states for O < E, O == E with L == 0 and L == 1, O > E, L == E - O, and L > E - O. +- Verify no reports for HistoryBuffer writes, reads from OutputBuffer, source-pointer uses, unrelated constant arrays, or safe guarded paths. +- Run refinement to an accepted or clean outcome and preserve G6, semantic threshold, anchor-free, hardcoding-free, and code-verification results. + +### Avoid and forbidden regressions + +- Do not reduce the design to syntax-only or CFG-only guard matching; safety depends on path-specific symbolic offset and length constraints. +- Do not recognize protection by matching sizeof expressions, early-return spelling, source text, changed lines, or other patch artifacts. +- Do not omit the custom match-expansion writer by limiting call handling to memcpy, memmove, or memset families. +- Do not subtract the offset from the extent before constraining the offset to a valid range, because unsigned underflow can create false safety. +- Do not use unconditional entailment-only reporting as a shortcut for all offset cases without proving that feasible unsafe executions are retained. +- Do not suppress all writes through local pointer variables; this can conceal direct or aliased output-buffer writes. +- Do not report ArraySubscriptExpr occurrences without proving they are stores, and do not inspect source arguments as destinations. +- Do not accept a patched warning as an unavoidable loop-widening artifact; refinement must eliminate it without losing vulnerable sink coverage. diff --git a/tasks/csa159/pair_6132/checker_template.cpp b/tasks/csa159/pair_6132/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_6132/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_6132/config.json b/tasks/csa159/pair_6132/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b370b316dcb1bd7111ea2c1e6083af8b75861020 --- /dev/null +++ b/tasks/csa159/pair_6132/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "FreeRDP_FreeRDP", + "before_commit": "dffd893dc5874b63c99777d7df147e37c770fc92", + "after_commit": "06c32f170093a6ecde93e3bc07fed6a706bfbeb3", + "repo_path": "/workspace/repo/FreeRDP/FreeRDP", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FreeRDP_FreeRDP/08fd2876b98ebf45114d0b5cfe6ea948adbc0025/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FreeRDP_FreeRDP/08fd2876b98ebf45114d0b5cfe6ea948adbc0025/compile_commands.json", + "changed_files": [ + "channels/video/client/video_main.c" + ], + "commit_message": "Fixed int overflow in PresentationContext_new\n\nThanks to hac425 CVE-2020-11038", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_6132/patch.diff b/tasks/csa159/pair_6132/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..61c3d2c8102a290ea08e14f9f7a7add0a9c2673d --- /dev/null +++ b/tasks/csa159/pair_6132/patch.diff @@ -0,0 +1,29 @@ +diff --git a/channels/video/client/video_main.c b/channels/video/client/video_main.c +index a161a1143..1efadb399 100644 +--- a/channels/video/client/video_main.c ++++ b/channels/video/client/video_main.c +@@ -220,8 +220,14 @@ error_frames: + static PresentationContext* PresentationContext_new(VideoClientContext* video, BYTE PresentationId, + UINT32 x, UINT32 y, UINT32 width, UINT32 height) + { ++ size_t s; + VideoClientContextPriv* priv = video->priv; +- PresentationContext* ret = calloc(1, sizeof(*ret)); ++ PresentationContext* ret; ++ s = width * height * 4ULL; ++ if (s > INT32_MAX) ++ return NULL; ++ ++ ret = calloc(1, sizeof(*ret)); + if (!ret) + return NULL; + +@@ -243,7 +249,7 @@ static PresentationContext* PresentationContext_new(VideoClientContext* video, B + goto error_currentSample; + } + +- ret->surfaceData = BufferPool_Take(priv->surfacePool, width * height * 4); ++ ret->surfaceData = BufferPool_Take(priv->surfacePool, s); + if (!ret->surfaceData) + { + WLog_ERR(TAG, "unable to allocate surfaceData"); \ No newline at end of file diff --git a/tasks/csa159/pair_6132/post_functions.txt b/tasks/csa159/pair_6132/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..81cebc8a01823d8b015f1aa0bdde6233c2e4e2a0 --- /dev/null +++ b/tasks/csa159/pair_6132/post_functions.txt @@ -0,0 +1,115 @@ +### File: channels/video/client/video_main.c +```c +static VideoClientContextPriv* VideoClientContextPriv_new(VideoClientContext* video) +{ + VideoClientContextPriv* ret = calloc(1, sizeof(*ret)); + if (!ret) + return NULL; + + ret->frames = Queue_New(TRUE, 10, 2); + if (!ret->frames) + { + WLog_ERR(TAG, "unable to allocate frames queue"); + goto error_frames; + } + + ret->surfacePool = BufferPool_New(FALSE, 0, 16); + if (!ret->surfacePool) + { + WLog_ERR(TAG, "unable to create surface pool"); + goto error_surfacePool; + } + + if (!InitializeCriticalSectionAndSpinCount(&ret->framesLock, 4 * 1000)) + { + WLog_ERR(TAG, "unable to initialize frames lock"); + goto error_spinlock; + } + + ret->video = video; + + /* don't set to unlimited so that we have the chance to send a feedback in + * the first second (for servers that want feedback directly) + */ + ret->lastSentRate = 30; + return ret; + +error_spinlock: + BufferPool_Free(ret->surfacePool); +error_surfacePool: + Queue_Free(ret->frames); +error_frames: + free(ret); + return NULL; +} + +static PresentationContext* PresentationContext_new(VideoClientContext* video, BYTE PresentationId, + UINT32 x, UINT32 y, UINT32 width, UINT32 height) +{ + size_t s; + VideoClientContextPriv* priv = video->priv; + PresentationContext* ret; + s = width * height * 4ULL; + if (s > INT32_MAX) + return NULL; + + ret = calloc(1, sizeof(*ret)); + if (!ret) + return NULL; + + ret->video = video; + ret->PresentationId = PresentationId; + + ret->h264 = h264_context_new(FALSE); + if (!ret->h264) + { + WLog_ERR(TAG, "unable to create a h264 context"); + goto error_h264; + } + h264_context_reset(ret->h264, width, height); + + ret->currentSample = Stream_New(NULL, 4096); + if (!ret->currentSample) + { + WLog_ERR(TAG, "unable to create current packet stream"); + goto error_currentSample; + } + + ret->surfaceData = BufferPool_Take(priv->surfacePool, s); + if (!ret->surfaceData) + { + WLog_ERR(TAG, "unable to allocate surfaceData"); + goto error_surfaceData; + } + + ret->surface = video->createSurface(video, ret->surfaceData, x, y, width, height); + if (!ret->surface) + { + WLog_ERR(TAG, "unable to create surface"); + goto error_surface; + } + + ret->yuv = yuv_context_new(FALSE); + if (!ret->yuv) + { + WLog_ERR(TAG, "unable to create YUV decoder"); + goto error_yuv; + } + + yuv_context_reset(ret->yuv, width, height); + ret->refCounter = 1; + return ret; + +error_yuv: + video->deleteSurface(video, ret->surface); +error_surface: + BufferPool_Return(priv->surfacePool, ret->surfaceData); +error_surfaceData: + Stream_Free(ret->currentSample, TRUE); +error_currentSample: + h264_context_free(ret->h264); +error_h264: + free(ret); + return NULL; +} +``` diff --git a/tasks/csa159/pair_6132/pre_functions.txt b/tasks/csa159/pair_6132/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..efcddd9a6abcd149445d5b31ffd94b4662ce4fe8 --- /dev/null +++ b/tasks/csa159/pair_6132/pre_functions.txt @@ -0,0 +1,109 @@ +### File: channels/video/client/video_main.c +```c +static VideoClientContextPriv* VideoClientContextPriv_new(VideoClientContext* video) +{ + VideoClientContextPriv* ret = calloc(1, sizeof(*ret)); + if (!ret) + return NULL; + + ret->frames = Queue_New(TRUE, 10, 2); + if (!ret->frames) + { + WLog_ERR(TAG, "unable to allocate frames queue"); + goto error_frames; + } + + ret->surfacePool = BufferPool_New(FALSE, 0, 16); + if (!ret->surfacePool) + { + WLog_ERR(TAG, "unable to create surface pool"); + goto error_surfacePool; + } + + if (!InitializeCriticalSectionAndSpinCount(&ret->framesLock, 4 * 1000)) + { + WLog_ERR(TAG, "unable to initialize frames lock"); + goto error_spinlock; + } + + ret->video = video; + + /* don't set to unlimited so that we have the chance to send a feedback in + * the first second (for servers that want feedback directly) + */ + ret->lastSentRate = 30; + return ret; + +error_spinlock: + BufferPool_Free(ret->surfacePool); +error_surfacePool: + Queue_Free(ret->frames); +error_frames: + free(ret); + return NULL; +} + +static PresentationContext* PresentationContext_new(VideoClientContext* video, BYTE PresentationId, + UINT32 x, UINT32 y, UINT32 width, UINT32 height) +{ + VideoClientContextPriv* priv = video->priv; + PresentationContext* ret = calloc(1, sizeof(*ret)); + if (!ret) + return NULL; + + ret->video = video; + ret->PresentationId = PresentationId; + + ret->h264 = h264_context_new(FALSE); + if (!ret->h264) + { + WLog_ERR(TAG, "unable to create a h264 context"); + goto error_h264; + } + h264_context_reset(ret->h264, width, height); + + ret->currentSample = Stream_New(NULL, 4096); + if (!ret->currentSample) + { + WLog_ERR(TAG, "unable to create current packet stream"); + goto error_currentSample; + } + + ret->surfaceData = BufferPool_Take(priv->surfacePool, width * height * 4); + if (!ret->surfaceData) + { + WLog_ERR(TAG, "unable to allocate surfaceData"); + goto error_surfaceData; + } + + ret->surface = video->createSurface(video, ret->surfaceData, x, y, width, height); + if (!ret->surface) + { + WLog_ERR(TAG, "unable to create surface"); + goto error_surface; + } + + ret->yuv = yuv_context_new(FALSE); + if (!ret->yuv) + { + WLog_ERR(TAG, "unable to create YUV decoder"); + goto error_yuv; + } + + yuv_context_reset(ret->yuv, width, height); + ret->refCounter = 1; + return ret; + +error_yuv: + video->deleteSurface(video, ret->surface); +error_surface: + BufferPool_Return(priv->surfacePool, ret->surfaceData); +error_surfaceData: + Stream_Free(ret->currentSample, TRUE); +error_currentSample: + h264_context_free(ret->h264); +error_h264: + free(ret); + return NULL; +} +``` diff --git a/tasks/csa159/pair_6132/task_prompt.md b/tasks/csa159/pair_6132/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..1dfc47717a2de41d83dfa53913d233b5a268a50e --- /dev/null +++ b/tasks/csa159/pair_6132/task_prompt.md @@ -0,0 +1,374 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `syntax_only` + +### Current failure diagnosis + +- The independent rollout failed solely on refinement_accepted: refinement ended in feedback_required after one round and never became accepted or clean. +- Diagnostic sharpness stayed weak (6.95/15): of two buggy warnings, only one is near the patch and the median distance is 298.5 lines, so refinement could not treat the report set as locally proven. +- Differential quality left patched_clean at 0.5 (N_buggy=2, N_patched=1) because a second BufferPool_Take of a 32-bit runtime product remains after the patch, blocking refinement convergence even though compile, scans, and semantic score 8.0 passed. + +### Preserve from prior rollouts + +- Preserve successful compile, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve the previously adequate CSA mechanism level: call_match by anchoring on the allocator and classifying the size argument's syntactic shape. +- Preserve semantic score at or above the configured threshold (adequate / 8.0). +- Preserve process quality at or above the configured threshold. +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Unpatched PresentationContext_new passes BufferPool_Take a size argument that is a <=32-bit multiplication of runtime UINT32 values (width * height * 4), which can wrap and return an undersized surface buffer later overwritten with the true byte count. +- Patched PresentationContext_new must not match: the size argument is a DeclRefExpr to a precomputed value (s from width * height * 4ULL after s > INT32_MAX rejection), not an overflowing multiplication expression. +- The report condition is the overflowed size computation at BufferPool_Take argument 1, generalized to that allocator API; a nested <=32-bit runtime product still wraps even if a later cast or 64-bit literal widens the outer expression. + +### Implementation constraints + +- Use check::PreCall; resolve the callee with dyn_cast_or_null(Call.getDecl()), match BufferPool_Take, require >=2 args, and inspect Call.getArgExpr(1). +- Overflowing size means, after IgnoreParenImpCasts and recursion through CastExpr and nested BinaryOperator, a BO_Mul whose ASTContext type width is <=32 bits and at least one operand is not constant-foldable via EvaluateAsInt. +- Emit a non-fatal PathSensitiveBugReport on generateNonFatalErrorNode and addRange on the size argument so the diagnostic is the call-site size expr. +- Scope is project-general on BufferPool_Take only; do not key off PresentationContext_new, video_main.c, width/height/s, line numbers, or a required literal 4. +- Do not use ProgramState, taint, CFG dominance, or modeling of the INT32_MAX guard; patched safety is the structural absence of an overflowing mul in the size argument. + +### Validation checklist + +- Compile the checker to a loadable .so with zero diagnostics, including no CallEvent API mismatch. +- Unpatched scan must report BufferPool_Take in channels/video/client/video_main.c::PresentationContext_new on size arg width * height * 4. +- Patched scan must drop that PresentationContext_new warning because the size arg is s; keep it in the relevant disappeared set under function_or_precise_changed_span_v2. +- A remaining BufferPool_Take(frame->w * frame->h * 4) may warn in both snapshots as the same unfixed pattern; it must not disappear as an unrelated finding and must not be required to vanish. +- The PresentationContext_new diagnostic range must sit on the BufferPool_Take size argument (old ~line 246 / new ~line 252), not hundreds of lines away. +- Refinement must finish accepted/clean rather than feedback_required, while hard_validation, G6, semantic_mechanism, and score thresholds still pass. +- Reconfirm hardcoding_free and anchor_free: matching is driven by allocator name plus size-expr shape/type, not file/line/commit/local names. + +### Avoid and forbidden regressions + +- Do not use Call.getDirectCallee(); that member is not on clang::ento::CallEvent and already broke compilation. +- Do not match only the exact spelling width * height * 4 or patch-local names/lines; that is hardcoding and under-generalizes the API. +- Do not add path-sensitive or interprocedural machinery to track the INT32_MAX guard; that exceeds the accepted call_match contract. +- Do not drop the second true overflowing BufferPool_Take only to force patched_clean=1 or to raise sharpness. +- Do not flag a plain DeclRefExpr/constant size, and do not treat a widened outer product as safe when an inner <=32-bit runtime mul still wraps. +- Do not reconstruct or copy the prior checker, and do not regress hard_validation, objective_gate, semantic_mechanism, semantic_score, process_score, anchor_free, or hardcoding_free. diff --git a/tasks/csa159/pair_7278/checker_template.cpp b/tasks/csa159/pair_7278/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_7278/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_7278/config.json b/tasks/csa159/pair_7278/config.json new file mode 100644 index 0000000000000000000000000000000000000000..ea766ffb47d9c06807224b874938f9d1e51bf783 --- /dev/null +++ b/tasks/csa159/pair_7278/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "libarchive_libarchive", + "before_commit": "50952acd22df3326c49771f5e5ba48630899468c", + "after_commit": "dfd6b54ce33960e420fb206d8872fb759b577ad9", + "repo_path": "/workspace/repo/libarchive/libarchive", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/libarchive_libarchive/b4099917d6893ed77af24caff1156e044ebd4fa5/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/libarchive_libarchive/b4099917d6893ed77af24caff1156e044ebd4fa5/compile_commands.json", + "changed_files": [ + "libarchive/archive_write_disk_posix.c" + ], + "commit_message": "Fixes for Issue #745 and Issue #746 from Doran Moppert.", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_7278/patch.diff b/tasks/csa159/pair_7278/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b6b41370618dec37344ec51264317eabe685bd33 --- /dev/null +++ b/tasks/csa159/pair_7278/patch.diff @@ -0,0 +1,426 @@ +diff --git a/libarchive/archive_write_disk_posix.c b/libarchive/archive_write_disk_posix.c +index 8f0421e7..abe1a86d 100644 +--- a/libarchive/archive_write_disk_posix.c ++++ b/libarchive/archive_write_disk_posix.c +@@ -326,12 +326,14 @@ struct archive_write_disk { + + #define HFS_BLOCKS(s) ((s) >> 12) + ++static int check_symlinks_fsobj(char *path, int *error_number, struct archive_string *error_string, int flags); + static int check_symlinks(struct archive_write_disk *); + static int create_filesystem_object(struct archive_write_disk *); + static struct fixup_entry *current_fixup(struct archive_write_disk *, const char *pathname); + #if defined(HAVE_FCHDIR) && defined(PATH_MAX) + static void edit_deep_directories(struct archive_write_disk *ad); + #endif ++static int cleanup_pathname_fsobj(char *path, int *error_number, struct archive_string *error_string, int flags); + static int cleanup_pathname(struct archive_write_disk *); + static int create_dir(struct archive_write_disk *, char *); + static int create_parent_dir(struct archive_write_disk *, char *); +@@ -2014,6 +2016,10 @@ create_filesystem_object(struct archive_write_disk *a) + const char *linkname; + mode_t final_mode, mode; + int r; ++ /* these for check_symlinks_fsobj */ ++ char *linkname_copy; /* non-const copy of linkname */ ++ struct archive_string error_string; ++ int error_number; + + /* We identify hard/symlinks according to the link names. */ + /* Since link(2) and symlink(2) don't handle modes, we're done here. */ +@@ -2022,6 +2028,27 @@ create_filesystem_object(struct archive_write_disk *a) + #if !HAVE_LINK + return (EPERM); + #else ++ archive_string_init(&error_string); ++ linkname_copy = strdup(linkname); ++ if (linkname_copy == NULL) { ++ return (EPERM); ++ } ++ /* TODO: consider using the cleaned-up path as the link target? */ ++ r = cleanup_pathname_fsobj(linkname_copy, &error_number, &error_string, a->flags); ++ if (r != ARCHIVE_OK) { ++ archive_set_error(&a->archive, error_number, "%s", error_string.s); ++ free(linkname_copy); ++ /* EPERM is more appropriate than error_number for our callers */ ++ return (EPERM); ++ } ++ r = check_symlinks_fsobj(linkname_copy, &error_number, &error_string, a->flags); ++ if (r != ARCHIVE_OK) { ++ archive_set_error(&a->archive, error_number, "%s", error_string.s); ++ free(linkname_copy); ++ /* EPERM is more appropriate than error_number for our callers */ ++ return (EPERM); ++ } ++ free(linkname_copy); + r = link(linkname, a->name) ? errno : 0; + /* + * New cpio and pax formats allow hardlink entries +@@ -2362,115 +2389,228 @@ current_fixup(struct archive_write_disk *a, const char *pathname) + * recent paths. + */ + /* TODO: Extend this to support symlinks on Windows Vista and later. */ ++ ++/* ++ * Checks the given path to see if any elements along it are symlinks. Returns ++ * ARCHIVE_OK if there are none, otherwise puts an error in errmsg. ++ */ + static int +-check_symlinks(struct archive_write_disk *a) ++check_symlinks_fsobj(char *path, int *error_number, struct archive_string *error_string, int flags) + { + #if !defined(HAVE_LSTAT) + /* Platform doesn't have lstat, so we can't look for symlinks. */ + (void)a; /* UNUSED */ ++ (void)path; /* UNUSED */ ++ (void)error_number; /* UNUSED */ ++ (void)error_string; /* UNUSED */ ++ (void)flags; /* UNUSED */ + return (ARCHIVE_OK); + #else +- char *pn; ++ int res = ARCHIVE_OK; ++ char *tail; ++ char *head; ++ int last; + char c; + int r; + struct stat st; ++ int restore_pwd; ++ ++ /* Nothing to do here if name is empty */ ++ if(path[0] == '\0') ++ return (ARCHIVE_OK); + + /* + * Guard against symlink tricks. Reject any archive entry whose + * destination would be altered by a symlink. ++ * ++ * Walk the filename in chunks separated by '/'. For each segment: ++ * - if it doesn't exist, continue ++ * - if it's symlink, abort or remove it ++ * - if it's a directory and it's not the last chunk, cd into it ++ * As we go: ++ * head points to the current (relative) path ++ * tail points to the temporary \0 terminating the segment we're currently examining ++ * c holds what used to be in *tail ++ * last is 1 if this is the last tail + */ +- /* Whatever we checked last time doesn't need to be re-checked. */ +- pn = a->name; +- if (archive_strlen(&(a->path_safe)) > 0) { +- char *p = a->path_safe.s; +- while ((*pn != '\0') && (*p == *pn)) +- ++p, ++pn; +- } ++ restore_pwd = open(".", O_RDONLY | O_BINARY | O_CLOEXEC); ++ __archive_ensure_cloexec_flag(restore_pwd); ++ if (restore_pwd < 0) ++ return (ARCHIVE_FATAL); ++ head = path; ++ tail = path; ++ last = 0; ++ /* TODO: reintroduce a safe cache here? */ + /* Skip the root directory if the path is absolute. */ +- if(pn == a->name && pn[0] == '/') +- ++pn; +- c = pn[0]; +- /* Keep going until we've checked the entire name. */ +- while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) { ++ if(tail == path && tail[0] == '/') ++ ++tail; ++ /* Keep going until we've checked the entire name. ++ * head, tail, path all alias the same string, which is ++ * temporarily zeroed at tail, so be careful restoring the ++ * stashed (c=tail[0]) for error messages. ++ * Exiting the loop with break is okay; continue is not. ++ */ ++ while (!last) { ++ /* Skip the separator we just consumed, plus any adjacent ones */ ++ while (*tail == '/') ++ ++tail; + /* Skip the next path element. */ +- while (*pn != '\0' && *pn != '/') +- ++pn; +- c = pn[0]; +- pn[0] = '\0'; ++ while (*tail != '\0' && *tail != '/') ++ ++tail; ++ /* is this the last path component? */ ++ last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0'); ++ /* temporarily truncate the string here */ ++ c = tail[0]; ++ tail[0] = '\0'; + /* Check that we haven't hit a symlink. */ +- r = lstat(a->name, &st); ++ r = lstat(head, &st); + if (r != 0) { ++ tail[0] = c; + /* We've hit a dir that doesn't exist; stop now. */ + if (errno == ENOENT) { + break; + } else { +- /* Note: This effectively disables deep directory ++ /* Treat any other error as fatal - best to be paranoid here ++ * Note: This effectively disables deep directory + * support when security checks are enabled. + * Otherwise, very long pathnames that trigger + * an error here could evade the sandbox. + * TODO: We could do better, but it would probably + * require merging the symlink checks with the + * deep-directory editing. */ +- return (ARCHIVE_FAILED); ++ if (error_number) *error_number = errno; ++ if (error_string) ++ archive_string_sprintf(error_string, ++ "Could not stat %s", ++ path); ++ res = ARCHIVE_FAILED; ++ break; ++ } ++ } else if (S_ISDIR(st.st_mode)) { ++ if (!last) { ++ if (chdir(head) != 0) { ++ tail[0] = c; ++ if (error_number) *error_number = errno; ++ if (error_string) ++ archive_string_sprintf(error_string, ++ "Could not chdir %s", ++ path); ++ res = (ARCHIVE_FATAL); ++ break; ++ } ++ /* Our view is now from inside this dir: */ ++ head = tail + 1; + } + } else if (S_ISLNK(st.st_mode)) { +- if (c == '\0') { ++ if (last) { + /* + * Last element is symlink; remove it + * so we can overwrite it with the + * item being extracted. + */ +- if (unlink(a->name)) { +- archive_set_error(&a->archive, errno, +- "Could not remove symlink %s", +- a->name); +- pn[0] = c; +- return (ARCHIVE_FAILED); ++ if (unlink(head)) { ++ tail[0] = c; ++ if (error_number) *error_number = errno; ++ if (error_string) ++ archive_string_sprintf(error_string, ++ "Could not remove symlink %s", ++ path); ++ res = ARCHIVE_FAILED; ++ break; + } +- a->pst = NULL; + /* + * Even if we did remove it, a warning + * is in order. The warning is silly, + * though, if we're just replacing one + * symlink with another symlink. + */ +- if (!S_ISLNK(a->mode)) { +- archive_set_error(&a->archive, 0, +- "Removing symlink %s", +- a->name); ++ tail[0] = c; ++ /* FIXME: not sure how important this is to restore ++ if (!S_ISLNK(path)) { ++ if (error_number) *error_number = 0; ++ if (error_string) ++ archive_string_sprintf(error_string, ++ "Removing symlink %s", ++ path); + } ++ */ + /* Symlink gone. No more problem! */ +- pn[0] = c; +- return (0); +- } else if (a->flags & ARCHIVE_EXTRACT_UNLINK) { ++ res = ARCHIVE_OK; ++ break; ++ } else if (flags & ARCHIVE_EXTRACT_UNLINK) { + /* User asked us to remove problems. */ +- if (unlink(a->name) != 0) { +- archive_set_error(&a->archive, 0, +- "Cannot remove intervening symlink %s", +- a->name); +- pn[0] = c; +- return (ARCHIVE_FAILED); ++ if (unlink(head) != 0) { ++ tail[0] = c; ++ if (error_number) *error_number = 0; ++ if (error_string) ++ archive_string_sprintf(error_string, ++ "Cannot remove intervening symlink %s", ++ path); ++ res = ARCHIVE_FAILED; ++ break; + } +- a->pst = NULL; ++ tail[0] = c; + } else { +- archive_set_error(&a->archive, 0, +- "Cannot extract through symlink %s", +- a->name); +- pn[0] = c; +- return (ARCHIVE_FAILED); ++ tail[0] = c; ++ if (error_number) *error_number = 0; ++ if (error_string) ++ archive_string_sprintf(error_string, ++ "Cannot extract through symlink %s", ++ path); ++ res = ARCHIVE_FAILED; ++ break; + } + } +- pn[0] = c; +- if (pn[0] != '\0') +- pn++; /* Advance to the next segment. */ ++ /* be sure to always maintain this */ ++ tail[0] = c; ++ if (tail[0] != '\0') ++ tail++; /* Advance to the next segment. */ + } +- pn[0] = c; +- /* We've checked and/or cleaned the whole path, so remember it. */ +- archive_strcpy(&a->path_safe, a->name); +- return (ARCHIVE_OK); ++ /* Catches loop exits via break */ ++ tail[0] = c; ++#ifdef HAVE_FCHDIR ++ /* If we changed directory above, restore it here. */ ++ if (restore_pwd >= 0) { ++ r = fchdir(restore_pwd); ++ if (r != 0) { ++ if(error_number) *error_number = errno; ++ if(error_string) ++ archive_string_sprintf(error_string, ++ "chdir() failure"); ++ } ++ close(restore_pwd); ++ restore_pwd = -1; ++ if (r != 0) { ++ res = (ARCHIVE_FATAL); ++ } ++ } ++#endif ++ /* TODO: reintroduce a safe cache here? */ ++ return res; + #endif + } + ++/* ++ * Check a->name for symlinks, returning ARCHIVE_OK if its clean, otherwise ++ * calls archive_set_error and returns ARCHIVE_{FATAL,FAILED} ++ */ ++static int ++check_symlinks(struct archive_write_disk *a) ++{ ++ struct archive_string error_string; ++ int error_number; ++ int rc; ++ archive_string_init(&error_string); ++ rc = check_symlinks_fsobj(a->name, &error_number, &error_string, a->flags); ++ if (rc != ARCHIVE_OK) { ++ archive_set_error(&a->archive, error_number, "%s", error_string.s); ++ } ++ archive_string_free(&error_string); ++ a->pst = NULL; /* to be safe */ ++ return rc; ++} ++ ++ + #if defined(__CYGWIN__) + /* + * 1. Convert a path separator from '\' to '/' . +@@ -2544,15 +2684,17 @@ cleanup_pathname_win(struct archive_write_disk *a) + * is set) if the path is absolute. + */ + static int +-cleanup_pathname(struct archive_write_disk *a) ++cleanup_pathname_fsobj(char *path, int *error_number, struct archive_string *error_string, int flags) + { + char *dest, *src; + char separator = '\0'; + +- dest = src = a->name; ++ dest = src = path; + if (*src == '\0') { +- archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, +- "Invalid empty pathname"); ++ if (error_number) *error_number = ARCHIVE_ERRNO_MISC; ++ if (error_string) ++ archive_string_sprintf(error_string, ++ "Invalid empty pathname"); + return (ARCHIVE_FAILED); + } + +@@ -2561,9 +2703,11 @@ cleanup_pathname(struct archive_write_disk *a) + #endif + /* Skip leading '/'. */ + if (*src == '/') { +- if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { +- archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, +- "Path is absolute"); ++ if (flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { ++ if (error_number) *error_number = ARCHIVE_ERRNO_MISC; ++ if (error_string) ++ archive_string_sprintf(error_string, ++ "Path is absolute"); + return (ARCHIVE_FAILED); + } + +@@ -2590,10 +2734,11 @@ cleanup_pathname(struct archive_write_disk *a) + } else if (src[1] == '.') { + if (src[2] == '/' || src[2] == '\0') { + /* Conditionally warn about '..' */ +- if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { +- archive_set_error(&a->archive, +- ARCHIVE_ERRNO_MISC, +- "Path contains '..'"); ++ if (flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { ++ if (error_number) *error_number = ARCHIVE_ERRNO_MISC; ++ if (error_string) ++ archive_string_sprintf(error_string, ++ "Path contains '..'"); + return (ARCHIVE_FAILED); + } + } +@@ -2624,7 +2769,7 @@ cleanup_pathname(struct archive_write_disk *a) + * We've just copied zero or more path elements, not including the + * final '/'. + */ +- if (dest == a->name) { ++ if (dest == path) { + /* + * Nothing got copied. The path must have been something + * like '.' or '/' or './' or '/././././/./'. +@@ -2639,6 +2784,21 @@ cleanup_pathname(struct archive_write_disk *a) + return (ARCHIVE_OK); + } + ++static int ++cleanup_pathname(struct archive_write_disk *a) ++{ ++ struct archive_string error_string; ++ int error_number; ++ int rc; ++ archive_string_init(&error_string); ++ rc = cleanup_pathname_fsobj(a->name, &error_number, &error_string, a->flags); ++ if (rc != ARCHIVE_OK) { ++ archive_set_error(&a->archive, error_number, "%s", error_string.s); ++ } ++ archive_string_free(&error_string); ++ return rc; ++} ++ + /* + * Create the parent directory of the specified path, assuming path + * is already in mutable storage. \ No newline at end of file diff --git a/tasks/csa159/pair_7278/post_functions.txt b/tasks/csa159/pair_7278/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..b6a71eb2e3d98e313f6c5aaf9f45da49e22fc927 --- /dev/null +++ b/tasks/csa159/pair_7278/post_functions.txt @@ -0,0 +1,273 @@ +### File: libarchive/archive_write_disk_posix.c +```c +static int +create_filesystem_object(struct archive_write_disk *a) +{ + /* Create the entry. */ + const char *linkname; + mode_t final_mode, mode; + int r; + /* these for check_symlinks_fsobj */ + char *linkname_copy; /* non-const copy of linkname */ + struct archive_string error_string; + int error_number; + + /* We identify hard/symlinks according to the link names. */ + /* Since link(2) and symlink(2) don't handle modes, we're done here. */ + linkname = archive_entry_hardlink(a->entry); + if (linkname != NULL) { +#if !HAVE_LINK + return (EPERM); +#else + archive_string_init(&error_string); + linkname_copy = strdup(linkname); + if (linkname_copy == NULL) { + return (EPERM); + } + /* TODO: consider using the cleaned-up path as the link target? */ + r = cleanup_pathname_fsobj(linkname_copy, &error_number, &error_string, a->flags); + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, error_number, "%s", error_string.s); + free(linkname_copy); + /* EPERM is more appropriate than error_number for our callers */ + return (EPERM); + } + r = check_symlinks_fsobj(linkname_copy, &error_number, &error_string, a->flags); + if (r != ARCHIVE_OK) { + archive_set_error(&a->archive, error_number, "%s", error_string.s); + free(linkname_copy); + /* EPERM is more appropriate than error_number for our callers */ + return (EPERM); + } + free(linkname_copy); + r = link(linkname, a->name) ? errno : 0; + /* + * New cpio and pax formats allow hardlink entries + * to carry data, so we may have to open the file + * for hardlink entries. + * + * If the hardlink was successfully created and + * the archive doesn't have carry data for it, + * consider it to be non-authoritative for meta data. + * This is consistent with GNU tar and BSD pax. + * If the hardlink does carry data, let the last + * archive entry decide ownership. + */ + if (r == 0 && a->filesize <= 0) { + a->todo = 0; + a->deferred = 0; + } else if (r == 0 && a->filesize > 0) { + a->fd = open(a->name, + O_WRONLY | O_TRUNC | O_BINARY | O_CLOEXEC); + __archive_ensure_cloexec_flag(a->fd); + if (a->fd < 0) + r = errno; + } + return (r); +#endif + } + linkname = archive_entry_symlink(a->entry); + if (linkname != NULL) { +#if HAVE_SYMLINK + return symlink(linkname, a->name) ? errno : 0; +#else + return (EPERM); +#endif + } + + /* + * The remaining system calls all set permissions, so let's + * try to take advantage of that to avoid an extra chmod() + * call. (Recall that umask is set to zero right now!) + */ + + /* Mode we want for the final restored object (w/o file type bits). */ + final_mode = a->mode & 07777; + /* + * The mode that will actually be restored in this step. Note + * that SUID, SGID, etc, require additional work to ensure + * security, so we never restore them at this point. + */ + mode = final_mode & 0777 & ~a->user_umask; + + switch (a->mode & AE_IFMT) { + default: + /* POSIX requires that we fall through here. */ + /* FALLTHROUGH */ + case AE_IFREG: + a->fd = open(a->name, + O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode); + __archive_ensure_cloexec_flag(a->fd); + r = (a->fd < 0); + break; + case AE_IFCHR: +#ifdef HAVE_MKNOD + /* Note: we use AE_IFCHR for the case label, and + * S_IFCHR for the mknod() call. This is correct. */ + r = mknod(a->name, mode | S_IFCHR, + archive_entry_rdev(a->entry)); + break; +#else + /* TODO: Find a better way to warn about our inability + * to restore a char device node. */ + return (EINVAL); +#endif /* HAVE_MKNOD */ + case AE_IFBLK: +#ifdef HAVE_MKNOD + r = mknod(a->name, mode | S_IFBLK, + archive_entry_rdev(a->entry)); + break; +#else + /* TODO: Find a better way to warn about our inability + * to restore a block device node. */ + return (EINVAL); +#endif /* HAVE_MKNOD */ + case AE_IFDIR: + mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE; + r = mkdir(a->name, mode); + if (r == 0) { + /* Defer setting dir times. */ + a->deferred |= (a->todo & TODO_TIMES); + a->todo &= ~TODO_TIMES; + /* Never use an immediate chmod(). */ + /* We can't avoid the chmod() entirely if EXTRACT_PERM + * because of SysV SGID inheritance. */ + if ((mode != final_mode) + || (a->flags & ARCHIVE_EXTRACT_PERM)) + a->deferred |= (a->todo & TODO_MODE); + a->todo &= ~TODO_MODE; + } + break; + case AE_IFIFO: +#ifdef HAVE_MKFIFO + r = mkfifo(a->name, mode); + break; +#else + /* TODO: Find a better way to warn about our inability + * to restore a fifo. */ + return (EINVAL); +#endif /* HAVE_MKFIFO */ + } + + /* All the system calls above set errno on failure. */ + if (r) + return (errno); + + /* If we managed to set the final mode, we've avoided a chmod(). */ + if (mode == final_mode) + a->todo &= ~TODO_MODE; + return (0); +} + +static struct fixup_entry * +new_fixup(struct archive_write_disk *a, const char *pathname) +{ + struct fixup_entry *fe; + + fe = (struct fixup_entry *)calloc(1, sizeof(struct fixup_entry)); + if (fe == NULL) { + archive_set_error(&a->archive, ENOMEM, + "Can't allocate memory for a fixup"); + return (NULL); + } + fe->next = a->fixup_list; + a->fixup_list = fe; + fe->fixup = 0; + fe->name = strdup(pathname); + return (fe); +} + +static struct fixup_entry * +current_fixup(struct archive_write_disk *a, const char *pathname) +{ + if (a->current_fixup == NULL) + a->current_fixup = new_fixup(a, pathname); + return (a->current_fixup); +} + +static int +check_symlinks_fsobj(char *path, int *error_number, struct archive_string *error_string, int flags) +{ +#if !defined(HAVE_LSTAT) + /* Platform doesn't have lstat, so we can't look for symlinks. */ + (void)a; /* UNUSED */ + (void)path; /* UNUSED */ + (void)error_number; /* UNUSED */ + (void)error_string; /* UNUSED */ + (void)flags; /* UNUSED */ + return (ARCHIVE_OK); +#else + int res = ARCHIVE_OK; + char *tail; + char *head; + int last; + char c; + int r; + struct stat st; + int restore_pwd; + + /* Nothing to do here if name is empty */ + if(path[0] == '\0') + return (ARCHIVE_OK); + + /* + * Guard against symlink tricks. Reject any archive entry whose + * destination would be altered by a symlink. + * + * Walk the filename in chunks separated by '/'. For each segment: + * - if it doesn't exist, continue + * - if it's symlink, abort or remove it + * - if it's a directory and it's not the last chunk, cd into it + * As we go: + * head points to the current (relative) path + * tail points to the temporary \0 terminating the segment we're currently examining + * c holds what used to be in *tail + * last is 1 if this is the last tail + */ + restore_pwd = open(".", O_RDONLY | O_BINARY | O_CLOEXEC); + __archive_ensure_cloexec_flag(restore_pwd); + if (restore_pwd < 0) + return (ARCHIVE_FATAL); + head = path; + tail = path; + last = 0; + /* TODO: reintroduce a safe cache here? */ + /* Skip the root directory if the path is absolute. */ + if(tail == path && tail[0] == '/') + ++tail; + /* Keep going until we've checked the entire name. + * head, tail, path all alias the same string, which is + * temporarily zeroed at tail, so be careful restoring the + * stashed (c=tail[0]) for error messages. + * Exiting the loop with break is okay; continue is not. + */ + while (!last) { + /* Skip the separator we just consumed, plus any adjacent ones */ + while (*tail == '/') + ++tail; + /* Skip the next path element. */ + while (*tail != '\0' && *tail != '/') + ++tail; + /* is this the last path component? */ + last = (tail[0] == '\0') || (tail[0] == '/' && tail[1] == '\0'); + /* temporarily truncate the string here */ + c = tail[0]; + tail[0] = '\0'; + /* Check that we haven't hit a symlink. */ + r = lstat(head, &st); + if (r != 0) { + tail[0] = c; + /* We've hit a dir that doesn't exist; stop now. */ + if (errno == ENOENT) { + break; + } else { + /* Treat any other error as fatal - best to be paranoid here + * Note: This effectively disables deep directory + * support when security checks are enabled. + * Otherwise, very long pathnames that trigger + * an error here could evade the sandbox. + * TODO: We could do better, but it would probably + + +// ... (4347 more chars) +``` diff --git a/tasks/csa159/pair_7278/pre_functions.txt b/tasks/csa159/pair_7278/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2a266e8ef6129803be5edc4e192ce3212053de20 --- /dev/null +++ b/tasks/csa159/pair_7278/pre_functions.txt @@ -0,0 +1,304 @@ +### File: libarchive/archive_write_disk_posix.c +```c +static int +create_filesystem_object(struct archive_write_disk *a) +{ + /* Create the entry. */ + const char *linkname; + mode_t final_mode, mode; + int r; + + /* We identify hard/symlinks according to the link names. */ + /* Since link(2) and symlink(2) don't handle modes, we're done here. */ + linkname = archive_entry_hardlink(a->entry); + if (linkname != NULL) { +#if !HAVE_LINK + return (EPERM); +#else + r = link(linkname, a->name) ? errno : 0; + /* + * New cpio and pax formats allow hardlink entries + * to carry data, so we may have to open the file + * for hardlink entries. + * + * If the hardlink was successfully created and + * the archive doesn't have carry data for it, + * consider it to be non-authoritative for meta data. + * This is consistent with GNU tar and BSD pax. + * If the hardlink does carry data, let the last + * archive entry decide ownership. + */ + if (r == 0 && a->filesize <= 0) { + a->todo = 0; + a->deferred = 0; + } else if (r == 0 && a->filesize > 0) { + a->fd = open(a->name, + O_WRONLY | O_TRUNC | O_BINARY | O_CLOEXEC); + __archive_ensure_cloexec_flag(a->fd); + if (a->fd < 0) + r = errno; + } + return (r); +#endif + } + linkname = archive_entry_symlink(a->entry); + if (linkname != NULL) { +#if HAVE_SYMLINK + return symlink(linkname, a->name) ? errno : 0; +#else + return (EPERM); +#endif + } + + /* + * The remaining system calls all set permissions, so let's + * try to take advantage of that to avoid an extra chmod() + * call. (Recall that umask is set to zero right now!) + */ + + /* Mode we want for the final restored object (w/o file type bits). */ + final_mode = a->mode & 07777; + /* + * The mode that will actually be restored in this step. Note + * that SUID, SGID, etc, require additional work to ensure + * security, so we never restore them at this point. + */ + mode = final_mode & 0777 & ~a->user_umask; + + switch (a->mode & AE_IFMT) { + default: + /* POSIX requires that we fall through here. */ + /* FALLTHROUGH */ + case AE_IFREG: + a->fd = open(a->name, + O_WRONLY | O_CREAT | O_EXCL | O_BINARY | O_CLOEXEC, mode); + __archive_ensure_cloexec_flag(a->fd); + r = (a->fd < 0); + break; + case AE_IFCHR: +#ifdef HAVE_MKNOD + /* Note: we use AE_IFCHR for the case label, and + * S_IFCHR for the mknod() call. This is correct. */ + r = mknod(a->name, mode | S_IFCHR, + archive_entry_rdev(a->entry)); + break; +#else + /* TODO: Find a better way to warn about our inability + * to restore a char device node. */ + return (EINVAL); +#endif /* HAVE_MKNOD */ + case AE_IFBLK: +#ifdef HAVE_MKNOD + r = mknod(a->name, mode | S_IFBLK, + archive_entry_rdev(a->entry)); + break; +#else + /* TODO: Find a better way to warn about our inability + * to restore a block device node. */ + return (EINVAL); +#endif /* HAVE_MKNOD */ + case AE_IFDIR: + mode = (mode | MINIMUM_DIR_MODE) & MAXIMUM_DIR_MODE; + r = mkdir(a->name, mode); + if (r == 0) { + /* Defer setting dir times. */ + a->deferred |= (a->todo & TODO_TIMES); + a->todo &= ~TODO_TIMES; + /* Never use an immediate chmod(). */ + /* We can't avoid the chmod() entirely if EXTRACT_PERM + * because of SysV SGID inheritance. */ + if ((mode != final_mode) + || (a->flags & ARCHIVE_EXTRACT_PERM)) + a->deferred |= (a->todo & TODO_MODE); + a->todo &= ~TODO_MODE; + } + break; + case AE_IFIFO: +#ifdef HAVE_MKFIFO + r = mkfifo(a->name, mode); + break; +#else + /* TODO: Find a better way to warn about our inability + * to restore a fifo. */ + return (EINVAL); +#endif /* HAVE_MKFIFO */ + } + + /* All the system calls above set errno on failure. */ + if (r) + return (errno); + + /* If we managed to set the final mode, we've avoided a chmod(). */ + if (mode == final_mode) + a->todo &= ~TODO_MODE; + return (0); +} + +static int +check_symlinks(struct archive_write_disk *a) +{ +#if !defined(HAVE_LSTAT) + /* Platform doesn't have lstat, so we can't look for symlinks. */ + (void)a; /* UNUSED */ + return (ARCHIVE_OK); +#else + char *pn; + char c; + int r; + struct stat st; + + /* + * Guard against symlink tricks. Reject any archive entry whose + * destination would be altered by a symlink. + */ + /* Whatever we checked last time doesn't need to be re-checked. */ + pn = a->name; + if (archive_strlen(&(a->path_safe)) > 0) { + char *p = a->path_safe.s; + while ((*pn != '\0') && (*p == *pn)) + ++p, ++pn; + } + /* Skip the root directory if the path is absolute. */ + if(pn == a->name && pn[0] == '/') + ++pn; + c = pn[0]; + /* Keep going until we've checked the entire name. */ + while (pn[0] != '\0' && (pn[0] != '/' || pn[1] != '\0')) { + /* Skip the next path element. */ + while (*pn != '\0' && *pn != '/') + ++pn; + c = pn[0]; + pn[0] = '\0'; + /* Check that we haven't hit a symlink. */ + r = lstat(a->name, &st); + if (r != 0) { + /* We've hit a dir that doesn't exist; stop now. */ + if (errno == ENOENT) { + break; + } else { + /* Note: This effectively disables deep directory + * support when security checks are enabled. + * Otherwise, very long pathnames that trigger + * an error here could evade the sandbox. + * TODO: We could do better, but it would probably + * require merging the symlink checks with the + * deep-directory editing. */ + return (ARCHIVE_FAILED); + } + } else if (S_ISLNK(st.st_mode)) { + if (c == '\0') { + /* + * Last element is symlink; remove it + * so we can overwrite it with the + * item being extracted. + */ + if (unlink(a->name)) { + archive_set_error(&a->archive, errno, + "Could not remove symlink %s", + a->name); + pn[0] = c; + return (ARCHIVE_FAILED); + } + a->pst = NULL; + /* + * Even if we did remove it, a warning + * is in order. The warning is silly, + * though, if we're just replacing one + * symlink with another symlink. + */ + if (!S_ISLNK(a->mode)) { + archive_set_error(&a->archive, 0, + "Removing symlink %s", + a->name); + } + /* Symlink gone. No more problem! */ + pn[0] = c; + return (0); + } else if (a->flags & ARCHIVE_EXTRACT_UNLINK) { + /* User asked us to remove problems. */ + if (unlink(a->name) != 0) { + archive_set_error(&a->archive, 0, + "Cannot remove intervening symlink %s", + a->name); + pn[0] = c; + return (ARCHIVE_FAILED); + } + a->pst = NULL; + } else { + archive_set_error(&a->archive, 0, + "Cannot extract through symlink %s", + a->name); + pn[0] = c; + return (ARCHIVE_FAILED); + } + } + pn[0] = c; + if (pn[0] != '\0') + pn++; /* Advance to the next segment. */ + } + pn[0] = c; + /* We've checked and/or cleaned the whole path, so remember it. */ + archive_strcpy(&a->path_safe, a->name); + return (ARCHIVE_OK); +#endif +} + +static int +cleanup_pathname(struct archive_write_disk *a) +{ + char *dest, *src; + char separator = '\0'; + + dest = src = a->name; + if (*src == '\0') { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Invalid empty pathname"); + return (ARCHIVE_FAILED); + } + +#if defined(__CYGWIN__) + cleanup_pathname_win(a); +#endif + /* Skip leading '/'. */ + if (*src == '/') { + if (a->flags & ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS) { + archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC, + "Path is absolute"); + return (ARCHIVE_FAILED); + } + + separator = *src++; + } + + /* Scan the pathname one element at a time. */ + for (;;) { + /* src points to first char after '/' */ + if (src[0] == '\0') { + break; + } else if (src[0] == '/') { + /* Found '//', ignore second one. */ + src++; + continue; + } else if (src[0] == '.') { + if (src[1] == '\0') { + /* Ignore trailing '.' */ + break; + } else if (src[1] == '/') { + /* Skip './'. */ + src += 2; + continue; + } else if (src[1] == '.') { + if (src[2] == '/' || src[2] == '\0') { + /* Conditionally warn about '..' */ + if (a->flags & ARCHIVE_EXTRACT_SECURE_NODOTDOT) { + archive_set_error(&a->archive, + ARCHIVE_ERRNO_MISC, + "Path contains '..'"); + return (ARCHIVE_FAILED); + } + } + /* + * Note: Under + +// ... (1073 more chars) +``` diff --git a/tasks/csa159/pair_7278/task_prompt.md b/tasks/csa159/pair_7278/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..3a003c8eb17d416142add9c1e837da32f9207df7 --- /dev/null +++ b/tasks/csa159/pair_7278/task_prompt.md @@ -0,0 +1,382 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `path_sensitive` + +### Current failure diagnosis + +- The rollout failed process_score and hardcoding_free despite compiling and producing the correct before/after differential. +- Patch-local material, including a commit-specific identifier in checker comments, caused the hardcoding finding and reduced plan-to-code consistency. +- The safety model treated either cleanup_pathname* or check_symlinks* as sufficient, while the patch requires both pathname cleanup and symlink traversal checks. +- Sanitizer calls were credited without proving an ARCHIVE_OK result on the path reaching the sink. +- Provenance coverage was limited to strdup/strndup and an arbitrary eight-hop resolution bound, leaving the claimed project-general behavior incompletely supported. +- The written plan described the linkat source operand inconsistently, creating ambiguity despite the implementation using zero-based argument index 1. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve an accepted or clean refinement outcome. +- Preserve the previously adequate path-sensitive CSA mechanism level. +- Preserve a semantic score at or above the configured threshold. +- Do not introduce patch-anchor dependence. + +### Required semantic proof + +- At link or linkat, prove that the existing-path operand originates from archive-controlled hardlink metadata; use zero-based argument index 0 for link and index 1 for linkat. +- Track value provenance through the copy or alias operations needed by the supplied patched flow so validation of a mutable copy can be associated with the original archive-derived path used at the sink. +- Suppress only when both pathname cleanup and symlink-component validation have successfully completed for a value derived from the same untrusted origin on the path reaching the sink. +- Treat validation as path ordered: checks performed only after the sink, on another path, or for another origin must not establish safety. +- Report when the archive-derived source reaches the hardlink sink without the complete successful validation sequence, representing the path traversal and arbitrary host-file overwrite risk. + +### Implementation constraints + +- Use path-sensitive ProgramState facts for archive-derived origins, derivations or aliases, and distinct successful completion states for pathname cleanup and symlink validation. +- Use check::PostCall or equivalent call-result callbacks to model the archive metadata source, relevant value propagation, and validator outcomes; use check::PreCall at link and linkat as the reporting point. +- Relate validator return values and subsequent control flow so a validation fact is retained only on states where the result permits execution to continue as successfully validated. +- Attach the diagnostic to the actual link or linkat call and mark the originating symbolic value interesting for the path report. +- Keep scope project-general for archive-controlled hardlink paths rather than restricting detection to create_filesystem_object or one source location. +- Model stable API semantics only where justified by the source evidence; do not encode line numbers, diff positions, local variable names, labels, commit identifiers, issue identifiers, or patch-specific prose. +- Avoid arbitrary provenance-depth limits; use canonical-origin state or cycle-safe resolution whose correctness does not depend on a fixed hop count. + +### Validation checklist + +- Compile and load the newly synthesized checker successfully with the target Clang Static Analyzer environment. +- Scan the vulnerable source and confirm exactly one relevant warning at the link call in create_filesystem_object. +- Scan the patched source and confirm zero warnings after both guarded validators succeed before the same link call. +- Run code verification and preserve one disappeared warning in the patched function, zero unrelated disappeared warnings, and zero warnings far from the patch. +- Confirm unrelated link and linkat calls with non-archive-derived source paths do not report. +- Confirm link uses argument 0 and linkat uses zero-based argument 1 as the existing-path source operand. +- Add refinement cases showing that only cleanup, only symlink checking, a failed or ignored validator result, validation of a different origin, or validation after the sink does not suppress. +- Confirm a copied archive-derived path validated successfully by both required checks suppresses the warning even though the sink receives the original provenance-equivalent value. + +### Avoid and forbidden regressions + +- Do not use syntax-only call matching or local AST adjacency as a substitute for path-sensitive provenance and ordering. +- Do not mark an origin fully validated after only one of the two required protections. +- Do not assume that calling a validator implies success without accounting for its result and the reaching branch. +- Do not suppress based on a validator applied to an unrelated argument or merely because a validator name appears in the function. +- Do not restrict propagation to only strdup and strndup when the claimed scope requires semantically equivalent copies or aliases supported by the source. +- Do not include CVE numbers, commit hashes, issue numbers, patch line locations, or patch-local identifiers in matching logic, comments, checker descriptions, or diagnostics. +- Do not broaden the sink rule to archive symlink creation or ordinary filesystem link calls unsupported by archive-derived hardlink provenance. diff --git a/tasks/csa159/pair_7287/checker_template.cpp b/tasks/csa159/pair_7287/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_7287/checker_template.cpp @@ -0,0 +1,98 @@ +// ============================================================================ +// CSA Checker Template +// ============================================================================ +// Fill in the sections marked with TODO to implement your checker. +// The checker is compiled with -fno-rtti to match the LLVM 18 build config. +// It is loaded via: clang -cc1 -load checker.so -analyzer-checker=your.CheckerName +// +// Compilation: +// clang++ -std=c++17 -fPIC -shared -fno-rtti -fno-exceptions \ +// -I${LLVM_BUILD_DIR}/include \ +// checker.cpp -o checker.so \ +// -Wl,--allow-shlib-undefined +// +// Usage: +// clang -cc1 -load ./checker.so -analyzer-checker=your.CheckerName -analyze +// ============================================================================ + +#include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h" +#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h" +#include "clang/StaticAnalyzer/Core/Checker.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h" +#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h" +#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h" + +using namespace clang; +using namespace ento; + +namespace { + +// ──────────────────────────────────────────────────────────────── +// TODO: Rename this class to describe your checker's purpose. +// ──────────────────────────────────────────────────────────────── +class {{CHECKER_CLASS_NAME}} + : public Checker // for checking after function calls +{ + // TODO: Customize the bug type name and category. + mutable std::unique_ptr BT; + +public: + {{CHECKER_CLASS_NAME}}() + : BT(new BugType(this, "{{BUG_NAME}}", "{{BUG_CATEGORY}}")) {} + + // ── PreCall callback (fires before every function call) ────── + void checkPreCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your pre-call analysis logic here. + // + // Common patterns: + // + // 1. Check if the called function matches a specific name: + // if (Call.getCalleeIdentifier()) { + // StringRef name = Call.getCalleeIdentifier()->getName(); + // if (name == "target_function") { ... } + // } + // + // 2. Get the program state: + // ProgramStateRef State = C.getState(); + // + // 3. Get arguments: + // SVal Arg = Call.getArgSVal(0); + // + // 4. Generate a bug report: + // ExplodedNode *ErrNode = C.generateErrorNode(); + // if (ErrNode) { + // auto R = std::make_unique( + // *BT, "Description of the bug", ErrNode); + // C.emitReport(std::move(R)); + // } + } + + // ── PostCall callback (fires after every function call) ───── + void checkPostCall(const CallEvent &Call, CheckerContext &C) const { + // TODO: Implement your post-call analysis logic here. + // + // Common pattern — check the return value: + // SVal RetVal = Call.getReturnValue(); + // if (RetVal.isUnknownOrUndef()) return; + // + // ProgramStateRef State = C.getState(); + // // Modify state based on post-call conditions... + } +}; + +} // anonymous namespace + +// ──────────────────────────────────────────────────────────────── +// Registration — DO NOT modify the function signatures. +// ──────────────────────────────────────────────────────────────── + +extern "C" void clang_registerCheckers(CheckerRegistry ®istry) { + registry.addChecker<{{CHECKER_CLASS_NAME}}>( + "{{CHECKER_FULL_NAME}}", // e.g., "your.NullDereferenceChecker" + "{{CHECKER_DESC}}", // e.g., "Detects null pointer dereference" + "{{CHECKER_DOC_URI}}"); // e.g., "https://example.com/docs" +} + +extern "C" const char clang_analyzerAPIVersionString[] = + CLANG_ANALYZER_API_VERSION_STRING; diff --git a/tasks/csa159/pair_7287/config.json b/tasks/csa159/pair_7287/config.json new file mode 100644 index 0000000000000000000000000000000000000000..06dbb65443094c2a9054b04d8f5f69bc40f5f79a --- /dev/null +++ b/tasks/csa159/pair_7287/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "libarchive_libarchive", + "before_commit": "d767d7904781794442938df6b0dd29c8da325e03", + "after_commit": "22531545514043e04633e1c015c7540b9de9dbe4", + "repo_path": "/workspace/repo/libarchive/libarchive", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/libarchive_libarchive/e5d1fbb2e24ad7ce3b94740c99c053c9ce24bffd/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/libarchive_libarchive/e5d1fbb2e24ad7ce3b94740c99c053c9ce24bffd/compile_commands.json", + "changed_files": [ + "libarchive/archive_write.c" + ], + "commit_message": "Limit write requests to at most INT_MAX.\nThis prevents a certain common programming error (passing -1 to write)\nfrom leading to other problems deeper in the library.", + "t_valid": 50, + "t_plausible": 20, + "triage_sample_size": 10, + "max_synthesis_retry": 0, + "max_in_session_redesigns": 1, + "max_refinement_iter": 3 +} diff --git a/tasks/csa159/pair_7287/patch.diff b/tasks/csa159/pair_7287/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7eb35a4ec9cbbfc2fdff5498d78672db425828c1 --- /dev/null +++ b/tasks/csa159/pair_7287/patch.diff @@ -0,0 +1,18 @@ +diff --git a/libarchive/archive_write.c b/libarchive/archive_write.c +index eede5e05..be856215 100644 +--- a/libarchive/archive_write.c ++++ b/libarchive/archive_write.c +@@ -673,8 +673,13 @@ static ssize_t + _archive_write_data(struct archive *_a, const void *buff, size_t s) + { + struct archive_write *a = (struct archive_write *)_a; ++ const size_t max_write = INT_MAX; ++ + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_DATA, "archive_write_data"); ++ /* In particular, this catches attempts to pass negative values. */ ++ if (s > max_write) ++ s = max_write; + archive_clear_error(&a->archive); + return ((a->format_write_data)(a, buff, s)); + } \ No newline at end of file diff --git a/tasks/csa159/pair_7287/post_functions.txt b/tasks/csa159/pair_7287/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2981ab22932bc940929dac98fc48f22001708dc1 --- /dev/null +++ b/tasks/csa159/pair_7287/post_functions.txt @@ -0,0 +1,17 @@ +### File: libarchive/archive_write.c +```c +static ssize_t +_archive_write_data(struct archive *_a, const void *buff, size_t s) +{ + struct archive_write *a = (struct archive_write *)_a; + const size_t max_write = INT_MAX; + + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_DATA, "archive_write_data"); + /* In particular, this catches attempts to pass negative values. */ + if (s > max_write) + s = max_write; + archive_clear_error(&a->archive); + return ((a->format_write_data)(a, buff, s)); +} +``` diff --git a/tasks/csa159/pair_7287/pre_functions.txt b/tasks/csa159/pair_7287/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..7d8a22a4a438aa4c52072e32cec4f8e38a1ec191 --- /dev/null +++ b/tasks/csa159/pair_7287/pre_functions.txt @@ -0,0 +1,28 @@ +### File: libarchive/archive_write.c +```c +static ssize_t +_archive_write_data(struct archive *_a, const void *buff, size_t s) +{ + struct archive_write *a = (struct archive_write *)_a; + archive_check_magic(&a->archive, ARCHIVE_WRITE_MAGIC, + ARCHIVE_STATE_DATA, "archive_write_data"); + archive_clear_error(&a->archive); + return ((a->format_write_data)(a, buff, s)); +} + +static struct archive_write_filter * +filter_lookup(struct archive *_a, int n) +{ + struct archive_write *a = (struct archive_write *)_a; + struct archive_write_filter *f = a->filter_first; + if (n == -1) + return a->filter_last; + if (n < 0) + return NULL; + while (n > 0 && f != NULL) { + f = f->next_filter; + --n; + } + return f; +} +``` diff --git a/tasks/csa159/pair_7287/task_prompt.md b/tasks/csa159/pair_7287/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ac91451030d04354a0e581fa32bf1da1f51a1856 --- /dev/null +++ b/tasks/csa159/pair_7287/task_prompt.md @@ -0,0 +1,373 @@ +# Task: Synthesize a CSA Checker from a CVE Patch + +## Your Role + +You are a static analysis expert. Synthesize a Clang Static Analyzer (CSA) checker +that detects the bug pattern fixed by the CVE patch in this working directory. + +You have full filesystem and bash access — use them. + +### Skills + +Many skills are available under `.claude/skills/` — covering vulnerability analysis, +checker design, debugging, code audit, security patterns, and more. Each skill +encodes reusable expertise: take time to explore them, read their SKILL.md files, +and invoke those that look useful via the Skill tool. Let the task guide which +ones you reach for. + +## File Layout + +``` +/work/ +├── compile.sh ← RUN ME: compile checker.cpp → checker.so +├── checker_template.cpp ← skeleton, start here +├── patch.diff ← the CVE fix +├── pre_functions.txt ← buggy source (before_commit) +├── post_functions.txt ← patched source (after_commit) +├── config.json ← paths, commit_message, commit hashes, flags +├── scan/ +│ ├── scan_before.sh ← RUN ME: scan before_commit → N_buggy +│ ├── scan_after.sh ← RUN ME: scan after_commit → N_patched +│ └── flags_*.txt ← pre-extracted compile flags (-I, -D) +├── references/ +│ ├── repo_knowledge.md ← project-specific API/convention reference +│ ├── patterns_summary.md ← (optional) historical bug pattern summary +│ ├── cwe_cards/ ← CWE knowledge library (all categories) +│ │ ├── index.json ← lookup index — use to find relevant cards +│ │ ├── CWE-{id}(-variant).md ← Tier 1/2 per-CWE detection patterns +│ │ ├── Category-{name}.md ← Tier 3 umbrella cards (rare CWEs grouped) +│ ├── csa_headers_api.md ← API quick reference (extracted from LLVM 18 headers) +│ ├── csa_checker_patterns.md ← pattern catalog (resource tracking, null check, etc.) +│ ├── csa_utility_functions.h ← copy-paste C++ helpers for checker.cpp (AST traversal, expression eval, etc.) +│ └── examples/ +│ └── llvm-official/ ← 5 official checker sources (with comments) +│ ├── 01_div_zero.cpp +│ ├── 02_simple_stream.cpp +│ ├── 03_undef_result.cpp +│ ├── 04_nullability.cpp +│ └── 05_malloc.cpp +│ +├── checker.cpp ← YOUR OUTPUT: synthesized checker +├── checker.so ← YOUR OUTPUT: compiled checker +├── state.json ← YOUR OUTPUT: structured task state +├── scope_statement.md ← YOUR OUTPUT: checker scope analysis (Level 1/2/3) +└── summary.json ← YOUR OUTPUT: final report +``` + +## Resources + +**Read these before writing any code:** + +1. **`references/csa_headers_api.md`** — CSA API quick reference. Extracted directly from + LLVM 18 headers. Covers all checker callbacks, ProgramState operations, SVal types, + MemRegion hierarchy, and bug reporting. **Read this first whenever you need API info.** + +2. **`references/csa_checker_patterns.md`** — Pattern catalog. Documents 5 battle-tested + patterns from official LLVM checkers: resource tracking, null checking, undefined + value detection, division-by-zero, and malloc/free. Each pattern includes skeleton + code, state traits, and key API usage. + +3. **`references/examples/llvm-official/`** — 5 official LLVM 18 checker implementations + with explanatory comments: + - `01_div_zero.cpp` — simplest checker (169 lines, 1 callback) + - `02_simple_stream.cpp` — resource tracking (292 lines, fopen/fclose) + - `03_undef_result.cpp` — PostStmt pattern (160 lines) + - `04_nullability.cpp` — multi-callback checker (1247 lines) + - `05_malloc.cpp` — comprehensive malloc/free (1511 lines) + +4. **`checker_template.cpp`** — Skeleton with placeholders. Start here. + +5. **`references/repo_knowledge.md`** — Project-specific reference. Contains this + repository's memory allocation API, key data types, source layout, and typical + CVE patterns. **Read this before writing the checker** — knowing the project's + alloc/free conventions and common bug patterns saves many grep rounds. + +5b. **`references/patterns_summary.md`** — (may not exist) Historical synthesis + patterns for this project. If present, it contains a concise summary of the + most common bug patterns, frequent CWE categories, and reusable checker + architectures observed in previous synthesis runs. Read after repo_knowledge.md. + +6. **`references/cwe_cards/`** — Complete CWE knowledge base covering all + vulnerability categories. **The framework provides the full library — + you must identify the vulnerability type yourself.** Workflow: + + 1. Analyse the patch diff and commit message to determine the vulnerability + type (buffer overflow, UAF, null deref, integer overflow, race condition, + etc.). Do NOT rely on the CWE label — treat it as a hint at most. + 2. Open ``index.json`` to discover available cards and their tiers. + 3. Read the relevant card(s) for **detection strategies**, **checker + architecture suggestions**, and **known false-positive patterns**. + + Card tiers: + - ``CWE-{id}(-{variant}).md`` — Tier 1/2 cards for common CWEs; kernel / + userspace variants when the detection strategy differs substantially. + - ``Category-{name}.md`` — Tier 3 umbrella cards grouping rarer CWEs by + category (input validation, resource management, etc.). + +7. **`references/csa_utility_functions.h`** — Copy-paste C++ helper functions for + checker.cpp. Includes AST traversal (`findSpecificTypeInParents/Children`), + expression evaluation (`EvaluateExprToInt`, `inferSymbolMaxVal`), array/string + size extraction, MemRegion helpers, and `ExprHasName()` for robust function + matching. All verified against LLVM 18. **Read before implementing detection + logic** — these save writing boilerplate that's easy to get wrong. + +## Environment + +Key paths are in ``config.json``. + +### Pre-built scripts + +| Script | What it does | +|--------|-------------| +| `bash compile.sh` | Compile checker.cpp → checker.so (with correct flags) | +| `CHECKER_NAME= bash scan/scan_before.sh` | Scan before_commit, count warnings → N_buggy | +| `CHECKER_NAME= bash scan/scan_after.sh` | Scan after_commit, count warnings → N_patched | + +```bash +# Compile (run from workdir root) +bash compile.sh + +# Scan — set CHECKER_NAME to the string passed to addChecker<>() +CHECKER_NAME=your.CheckerName bash scan/scan_before.sh # → N_buggy +CHECKER_NAME=your.CheckerName bash scan/scan_after.sh # → N_patched +``` + +- ``compile.sh`` already has the correct ``-I`` / ``-fno-rtti`` flags. +- ``scan/scan_*.sh`` count only warnings tagged with your checker name. +- Scan environments (source files + compile flags) are pre-built in ``scan/``. + +### Scan Script Integrity (CRITICAL) + +The scan scripts (``scan/scan_before.sh``, ``scan/scan_after.sh``) are the **only +valid measurement** of N_buggy and N_patched. They are the ground truth that the +Python-side validator will also use. You MUST obey these rules: + +**1. Never bypass the scan scripts.** Do NOT run ``clang --analyze`` directly + to measure warning counts. The Python validator runs the same scan scripts + — if you measured with a different command, your numbers will not reproduce + and the synthesis will be rejected. + +**2. If the scan script prints COMPILE_ERROR** (missing headers, undeclared + identifiers, etc.), the scan environment needs repair. You MUST fix it: + - Add missing ``-I`` include paths to the flags files in ``scan/`` + - Copy needed generated headers (e.g. ``autoconf.h``) from the snapshot + - If the file fundamentally cannot be compiled by clang, stop and write + ``summary.json`` with ``status: "failed"`` and an honest ``failure_reason`` + +**3. Only trust scan script output.** The ``Total warnings: N`` line + printed by the scan script is the number that goes into ``summary.json``. + If the scan script says 0, write 0. Fabricating numbers that the scan + script did not produce will cause the Python validator to reject the + synthesis. + +- If compile fails: read the error, fix ``checker.cpp``, retry (max 3 cycles). +- If validation fails: revise checker logic, re-compile, re-scan. + +## MCP Tools + +You have access to 3 MCP tools under the `csa-tools` server (prefixed `mcp__csa-tools__`). +Each returns **source context embedded in the result** — no need to follow up with Read. + +| Tool | What it does | Key advantage | +|------|-------------|---------------| +| `search(pattern, scope)` | Search for a pattern in source / LLVM headers / workdir | Returns file:line + 3 lines context — grep + Read in one call | +| `compile()` | Run compile.sh, return parsed diagnostics | Errors include checker.cpp context — fix without reading the file | +| `scan(checker_name)` | Run before/after scan, return N_buggy + N_patched + warning locations | Each warning includes source context — no manual clang --analyze needed | + +### When to use each + +- **`search`**: Whenever you would type `grep -rn "X"` or `find ... -name`. Use `scope="source"` for CVE code, `scope="llvm"` for CSA API headers, `scope="all"` when unsure. +- **`compile`**: Instead of `bash compile.sh` followed by reading checker.cpp at error lines. +- **`scan`**: Instead of running scan_before.sh + scan_after.sh + manual clang inspection. Returns everything you need to decide next action. + +## Semantic Design Contract — before writing checker.cpp + +Create the analysis portions of `state.json` and `scope_statement.md` **before** +writing checker.cpp. They are a design contract, not a retrospective summary. +After compilation, update only implementation facts such as `build_attempts`. + +In `patch_analysis`, distinguish the vulnerable operation, its trigger, and the +semantic fact introduced by the patch that makes it safe. In `detection_plan`, +make `report_condition`, `safe_condition`, and `source_level_signal` concrete +CSA-observable facts. In `api_choice`, record the mechanism level and explain +why the selected callback can observe and prove those facts. + +In `scope_statement.md`, include this mapping table and check it again after +implementation: + +| Semantic condition | CSA evidence | checker.cpp implementation | +| --- | --- | --- | +| report condition | AST / SVal / MemRegion / CFG evidence | callback, helper, and branch that reports | +| safe condition | path constraint, guard, state discharge, or structural fact | branch that suppresses the report | + +Every condition in the plan must have an implementation entry. Do not claim a +condition that checker.cpp does not implement, and do not silently add a code +condition absent from the plan. + +## Mechanism Selection — diagnose before coding + +Choose the weakest CSA mechanism that can prove the vulnerability property: + +1. **syntax-only AST**: only when local AST shape itself is the defect; +2. **control flow / dominance**: when guard placement relative to a sink matters; +3. **path-sensitive ProgramState/SVal**: when an unsafe state must reach a use; +4. **cross-procedure/dataflow**: when the required fact crosses function boundaries. + +For a guard-based patch, prove both that the guard rejects the unsafe value and +that it dominates the vulnerable use. For path-sensitive or cross-procedure +defects, do not replace the required state or flow proof with local AST matching +or source-text substring matching merely because it passes the differential scan. +Record the selected level as `api_choice.mechanism_level`. + +## Semantic identity, locality, and final validation + +Before accepting the checker, verify that its primary matching logic does not +depend on patch-local variable names, labels, line numbers, commit IDs, or unique +literals. Project APIs, types, and stable semantic call relationships are valid +scope anchors when they define the vulnerability class. Attach the report to the +actual vulnerable operation, and implement every suppression as a real safe +condition rather than the mere presence of a nearby guard-shaped statement. + +The required final sequence is: **compile → before scan → after scan → inspect +the final checker name, artifacts, and report locations → write summary.json**. +Always run the final compile and both scans. `MAX_IN_SESSION_REDESIGNS` limits only +additional redesign cycles after a failed validation; if it is zero, preserve the +real validation evidence and report failure honestly rather than fabricating counts. + +## Validation Criteria + +``` +VALID : N_buggy > N_patched AND N_patched < 50 +INVALID : otherwise → revise and re-validate (max 1 attempts) +``` + +## Refinement + +Do NOT self-refine the checker repeatedly. Your goal is to produce the first +checker that passes the Validation Criteria above — fix compile errors and +validation failures only. False positives are triaged and repaired by the +framework's refinement stage: you will receive a concrete FP list via +session resume (if needed) and fix only those. Reserve budget for that stage. + +## Output + +Produce all of the following **only when completely done**: + +| File | Content | +|------|---------| +| ``checker.cpp`` | Synthesized checker source code | +| ``checker.so`` | Compiled checker plugin | +| ``state.json`` | Structured task state (see schema below) | +| ``scope_statement.md`` | Checker scope analysis in prose (Level 1/2/3) | +| ``summary.json`` | Final report (see schema below) | + +Writing ``summary.json`` signals completion. Do NOT write it early. + +### ``state.json`` + +Create this before writing checker.cpp to capture the design contract. After the +checker compiles, update only implementation facts and retain the original +semantic plan. + +```json +{ + "patch_analysis": { + "summary": "One sentence describing the vulnerability this patch fixes", + "changed_files": ["file1.c", "file2.h"], + "changed_functions": ["func_a", "func_b"], + "bug_type": "buffer_overflow | use_after_free | null_deref | integer_overflow | race_condition | resource_leak | double_free | input_validation | other", + "fix_strategy": "add_bounds_check | add_null_check | add_size_check | add_early_return | reorder_operations | change_api_signature | other", + "affected_types": ["GF_BitStream", "custom_struct_t"], + "critical_calls": ["gf_strdup", "memcpy"] + }, + "detection_plan": { + "bug_pattern": "High-level description of the vulnerability pattern (e.g. 'heap buffer overflow when reading variable-length data into a fixed-size stack buffer without size bound')", + "report_condition": "When should the checker emit a warning? (e.g. 'call to gf_strdup where the argument originates from a fixed-size local array that was populated by variable-length bitstream reads')", + "safe_condition": "When should the checker NOT emit a warning? (e.g. 'argument originates from a heap allocation or a size-bounded source')", + "source_level_signal": "What AST / MemRegion / SVal property does the checker look for? (e.g. 'MemRegion extent < parameter size at a PreCall to gf_strdup')" + }, + "api_choice": { + "mechanism_level": "syntactic_ast | control_flow | path_sensitive | interprocedural_dataflow", + "callback": "check::PreCall | check::PostCall | check::PreStmt | check::PostStmt | check::Bind | check::DeadSymbols | check::EndFunction | ...", + "reasoning": "Why this callback and its AST/state/CFG evidence prove the report and safe conditions", + "alternatives_considered": ["check::PostCall"] + }, + "implementation": { + "scope_level": "patch_specific | project_general | cross_project", + "checker_name": "project.CheckerName", + "build_attempts": 1 + } +} +``` + +### ``summary.json`` + +```json +{ + "status": "plausible | failed", + "bug_pattern": "One sentence describing the bug pattern", + "scope_level": "patch_specific | project_general | cross_project", + "checker_cpp": "checker.cpp", + "checker_so": "checker.so", + "n_buggy": 0, + "n_patched": 0, + "total_reports": 0, + "fp_rate_estimate": 0.0, + "failure_reason": null +} +``` + +## Feedback-derived requirements for this fresh synthesis + +A prior independent rollout exposed the risks below. Start again from the patch +in this new session. Do not reconstruct, edit, or assume the prior checker. + +Required mechanism level: `syntax_only` + +### Current failure diagnosis + +- semantic_mechanism failed: the rollout used path-sensitive PreCall/SVal assumeInclusiveRange reasoning, which the evaluator marked overkill versus the minimum syntax_only proof that a local INT_MAX clamp is missing. +- The prior report condition was feasibility of size > INT_MAX in ProgramState at the sink, not the local AST presence or absence of the clamp predicate beside the format_write_data call. +- Compile, differential detection (n_buggy=1, n_patched=0), sharpness, FP control, and refinement all passed, but semantic status stayed partial because mechanism_adapted was heavier than a missing-local-clamp defect requires. + +### Preserve from prior rollouts + +- Preserve successful compile, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve an accepted or clean refinement outcome. +- Preserve semantic score at or above the configured threshold. +- Preserve process quality at or above the configured threshold. +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Show that an indirect call through the format_write_data member of struct archive_write forwards its size_t length (argument index 2) with no local bound to INT_MAX. +- Unpatched _archive_write_data returns (a->format_write_data)(a, buff, s) with parameter s unconstrained, so a caller-controlled length such as (size_t)-1/SIZE_MAX can reach that sink. +- Patched safety is the same-function clamp if (s > max_write) s = max_write with max_write == INT_MAX; AST presence of that cap is the safe condition, and its absence is the defect. +- Emit only when the format_write_data sink exists and the INT_MAX/max_write cap on the forwarded size is not a local AST relation; stay silent when that cap is present. + +### Implementation constraints + +- Use an AST-level CSA entry (check::ASTCodeBody or an equivalent function-body walk). Do not use check::PreCall, ProgramState, SVal, or assumeInclusiveRange. +- Identify the sink as a CallExpr whose callee, after stripping parentheses and casts, is a MemberExpr named format_write_data with at least three arguments; the size operand is index 2. +- In the enclosing function body, recognize a local clamp of that size operand against INT_MAX (a comparison with INT_MAX/max_write plus an assignment that caps the size) as a same-function AST relation, not CFG dominance or path constraints. +- Report at the format_write_data call expression in the write-data dispatch, not at archive_check_magic, archive_clear_error, or unrelated helpers. +- Keep project-general scope on libarchive's format_write_data callback API; do not hardcode patch paths, line numbers, commit hashes, or _archive_write_data as the sole matching key. + +### Validation checklist + +- Compile the new checker to a loadable clang plugin/shared object with zero compiler diagnostics. +- Scan unpatched libarchive/archive_write.c and require a warning on the unbounded (a->format_write_data)(a, buff, s) call in _archive_write_data. +- Scan patched libarchive/archive_write.c after the INT_MAX clamp and require zero reports in _archive_write_data. +- Place the buggy diagnostic on or immediately beside the format_write_data call (prior median distance was 1 line) and inside the patched function. +- Require n_buggy >= 1, n_patched = 0, no warnings in non-patched functions, and an accepted or clean refinement outcome. +- Confirm semantic_mechanism now matches syntax_only missing-clamp proof so the previous overkill path-sensitive classification does not recur. + +### Avoid and forbidden regressions + +- Do not restore path-sensitive range reasoning, constraint-manager queries, or PreCall argument SVal tests to decide whether size > INT_MAX is feasible. +- Do not treat a function-name match on _archive_write_data as a substitute for identifying the format_write_data sink and the missing INT_MAX clamp. +- Do not report after the sink consumes the size (PostCall) and do not require interprocedural facts from the public archive_write_data API into callees. +- Do not encode patch hunks, source lines 676-682, or commit-specific text from archive_write.c as matching constants. +- Do not sacrifice differential cleanliness, G6, refinement acceptance, or hardcoding/anchor-free constraints in order to keep a heavier mechanism.