diff --git a/tasks/csa159/pair_135405/post_functions.txt b/tasks/csa159/pair_135405/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2b6e78a10e1066b388da6b5035d1d2c18609c60a --- /dev/null +++ b/tasks/csa159/pair_135405/post_functions.txt @@ -0,0 +1,144 @@ +### File: src/ext-cmd.c +```c +static int select_read(int sockfd, char buffer[], int bufsize, struct timeval *tv) +{ + fd_set rfds; + int retval; + + FD_ZERO(&rfds); + FD_SET(sockfd, &rfds); + + retval = select(sockfd + 1, &rfds, NULL, NULL, tv); + + if (retval == -1) { + // Error + return -1; + } else if (retval) { + // Data available + return read(sockfd, buffer, bufsize); + } else { + // Timeout reached + return 0; + } +} + +static int append_strings(char buf[], size_t bufsize, int argc, char *argv[]) +{ + int i; + int len; + + // Check input length + len = 0; + for (i = 0; i < argc; ++i) { + len += 1 + strlen(argv[i]); + if(len >= bufsize) { + return EXIT_FAILURE; + } + } + + // Concatenate strings + buf[0] = '\0'; + for (i = 0; i < argc; ++i) { + if (i) { + strcat(buf, " "); + } + strcat(buf, argv[i]); + } + strcat(buf, "\n"); + + return EXIT_SUCCESS; +} + +int cmd_client(int argc, char *argv[]) +{ + char buffer[256]; + const char *path; + struct sockaddr_un addr; + struct timeval tv; + ssize_t size; + int sock; + + // Default unix socket path + path = CMD_PATH; + + // Skip program name + argc -= 1; + argv += 1; + + if (argc >= 1) { + if (strcmp(argv[0], "-h") == 0) { + fprintf(stdout, "%s", g_client_usage); + return 0; + } else if (strcmp(argv[0], "-p") == 0) { + if (argc >= 2) { + path = argv[1]; + // Skip option and path + argc -= 2; + argv += 2; + } else { + fprintf(stderr, "Path is missing!\n"); + return 1; + } + } + } + + if (EXIT_FAILURE == append_strings(buffer, sizeof(buffer), argc, argv)) { + fprintf(stderr, "Input to long\n"); + return EXIT_FAILURE; + } + + sock = socket(AF_LOCAL, SOCK_STREAM, 0); + if (sock < 0) { + fprintf(stderr, "socket(): %s\n", strerror(errno)); + return EXIT_FAILURE; + } + + addr.sun_family = AF_LOCAL; + strcpy(addr.sun_path, path); + + if (connect(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) { + fprintf(stderr, "Failed to connect to '%s': %s\n", path, strerror(errno)); + goto error; + } + + /* Set receive timeout: 200ms */ + tv.tv_sec = 0; + tv.tv_usec = 200000; + +#ifndef __CYGWIN__ + if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) < 0) { + fprintf(stderr, "setsockopt(): %s\n", strerror(errno)); + goto error; + } +#endif + + // Send request + send(sock, buffer, strlen(buffer), 0); + + while (1) { + // Receive replies +#ifdef __CYGWIN__ + size = select_read(sock, buffer, strlen(buffer), &tv); +#else + size = read(sock, buffer, strlen(buffer)); +#endif + if (size <= 0) { + break; + } + + buffer[size] = '\0'; + printf("%s", buffer); + } + + close(sock); + + return EXIT_SUCCESS; + +error: + if (sock > 0) { + close(sock); + } + + return EXIT_FAILURE; +} +``` diff --git a/tasks/csa159/pair_135405/pre_functions.txt b/tasks/csa159/pair_135405/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..f363483462aaf58ffe2cc54cbd13a952dece855f --- /dev/null +++ b/tasks/csa159/pair_135405/pre_functions.txt @@ -0,0 +1,123 @@ +### File: src/ext-cmd.c +```c +static int select_read(int sockfd, char buffer[], int bufsize, struct timeval *tv) +{ + fd_set rfds; + int retval; + + FD_ZERO(&rfds); + FD_SET(sockfd, &rfds); + + retval = select(sockfd + 1, &rfds, NULL, NULL, tv); + + if (retval == -1) { + // Error + return -1; + } else if (retval) { + // Data available + return read(sockfd, buffer, bufsize); + } else { + // Timeout reached + return 0; + } +} + +int cmd_client(int argc, char *argv[]) +{ + char buffer[256]; + const char *path; + struct sockaddr_un addr; + struct timeval tv; + ssize_t size; + int sock; + size_t i; + + // Default unix socket path + path = CMD_PATH; + + // Skip program name + argc -= 1; + argv += 1; + + if (argc >= 1) { + if (strcmp(argv[0], "-h") == 0) { + fprintf(stdout, "%s", g_client_usage); + return 0; + } else if (strcmp(argv[0], "-p") == 0) { + if (argc >= 2) { + path = argv[1]; + // Skip option and path + argc -= 2; + argv += 2; + } else { + fprintf(stderr, "Path is missing!\n"); + return 1; + } + } + } + + // Construct request string from args + buffer[0] = '\0'; + for (i = 0; i < argc; ++i) { + if (i) { + strcat(buffer, " "); + } + strcat(buffer, argv[i]); + } + strcat(buffer, "\n"); + + sock = socket(AF_LOCAL, SOCK_STREAM, 0); + if (sock < 0) { + fprintf(stderr, "socket(): %s\n", strerror(errno)); + return EXIT_FAILURE; + } + + addr.sun_family = AF_LOCAL; + strcpy(addr.sun_path, path); + + if (connect(sock, (struct sockaddr *) &addr, sizeof(addr)) < 0) { + fprintf(stderr, "Failed to connect to '%s': %s\n", path, strerror(errno)); + goto error; + } + + /* Set receive timeout: 200ms */ + tv.tv_sec = 0; + tv.tv_usec = 200000; + +#ifndef __CYGWIN__ + if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) < 0) { + fprintf(stderr, "setsockopt(): %s\n", strerror(errno)); + goto error; + } +#endif + + // Send request + send(sock, buffer, strlen(buffer), 0); + + while (1) { + // Receive replies +#ifdef __CYGWIN__ + size = select_read(sock, buffer, strlen(buffer), &tv); +#else + size = read(sock, buffer, strlen(buffer)); +#endif + if (size <= 0) { + break; + } + + buffer[size] = '\0'; + printf("%s", buffer); + } + + close(sock); + + return EXIT_SUCCESS; + +error: + if (sock > 0) { + close(sock); + } + + return EXIT_FAILURE; +} +``` diff --git a/tasks/csa159/pair_135405/task_prompt.md b/tasks/csa159/pair_135405/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..a329ecf562cd2176c88f8237b3e77652d988b566 --- /dev/null +++ b/tasks/csa159/pair_135405/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: `control_flow` + +### Current failure diagnosis + +- The prior rollout did not prove that a candidate condition constrains the accumulated output length; it accepted any relational comparison with an operand at least as large as the capacity. +- Source-order precedence was substituted for reachability and dominance, so a guard on another branch or a bypassable guard could incorrectly suppress a real overflow. +- Termination was recognized without proving comparison orientation or which successor reaches the writes; accepting arbitrary return, goto, break, or continue constructs made the safe condition unsound. +- Treating every nonliteral source as unbounded ignored the cumulative semantics of repeated concatenation, including argument lengths, separators, newline, and the terminating null byte. +- Process quality remained below threshold because validation included working-directory mistakes, an avoidable CSA API type error, unreliable scans with compile errors, and some weakly evidenced recovery steps. + +### Preserve from prior rollouts + +- The new synthesis must compile successfully and pass before/after validation and code verification. +- Preserve objective eligibility gate G6. +- Preserve an accepted or clean refinement outcome. +- Maintain the semantic score at or above the configured threshold while correcting the semantic mechanism. +- Remain independent of patch anchors such as changed line numbers or exact diff locations. +- Remain free of patch-local hardcoding, including project-specific function, variable, file, or macro names. + +### Required semantic proof + +- Report only when repeated unbounded string writes can reach a fixed-capacity destination without a proven bound on the total required bytes. +- Relate the checked quantity to the same accumulated length consumed by the writes, accounting for each source length, inserted separators, the final newline, and null termination. +- A suppressing guard must compare that accumulated requirement against the destination capacity with the correct operator and operand orientation. +- Prove through the CFG that the rejecting successor exits before every relevant write and that every path reaching those writes passed through the safe successor. +- For the patched structure, establish that completion of the length-accumulation loop and the condition len >= capacity imply len < capacity on all paths entering the later concatenation loop. +- Do not infer safety merely from a nonliteral source being preceded by some capacity-like comparison; absence or presence of the precise length-to-capacity relation controls the diagnostic. + +### Implementation constraints + +- Use check::PreCall, or an equivalently local pre-write callback, for strcat/strcpy so destination and source arguments are available and the diagnostic is emitted at the unsafe call. +- Recover the destination extent from CSA region and type information, including an inlined caller's fixed array when observable, rather than from spelling or a literal capacity value. +- Use the enclosing AnalysisDeclContext CFG and dominance or equivalent all-path reachability reasoning; SourceManager ordering alone is insufficient. +- Identify the length accumulator by its data dependencies on strlen-derived source lengths and added delimiter costs, not by its identifier. +- Accept a guard only when its safe CFG edge dominates the relevant writes and its rejecting edge cannot rejoin before them. +- Resolve a size parameter to a concrete destination capacity only through semantic argument/type relationships such as sizeof of the same destination; do not guess from parameter position or value alone. +- Keep scope project-general around fixed-capacity destinations and standard unbounded string-copy or concatenation sinks, with no special treatment of ext-cmd.c, cmd_client, append_strings, buffer, len, bufsize, argv, or 256. +- Avoid persistent ProgramState traits or cross-function fact propagation unless CFG and call-context facts demonstrably cannot establish the required relation. + +### Validation checklist + +- Build the new checker against the supplied LLVM/Clang API with no diagnostics and verify registration and loading before scanning. +- Run scans from verified working directories with the supplied include flags; reject any result in which either source version has a compile error or skipped file. +- Confirm exactly the relevant vulnerable-version diagnostic is produced and the patched version is clean, preserving N_buggy=1 and N_patched=0. +- Confirm the vulnerable diagnostic is located on the length-unknown strcat in cmd_client, at zero or comparably minimal distance from the changed vulnerable operation. +- Add focused negative tests showing that an unrelated large-constant comparison, reversed or permissive comparison, terminating wrong branch, source-ordered but bypassable guard, or nondominating guard does not establish safety. +- Add a positive safety test matching the patch semantics: accumulated strlen plus delimiter costs is rejected at or above the same buffer capacity before all concatenations. +- Run code verification and ensure no warnings disappear only in non-patched functions and no unrelated strcpy to a struct field is newly diagnosed outside the declared scope. +- Complete refinement with an accepted or clean outcome and retain objective gate G6 and the configured semantic-score threshold. + +### Avoid and forbidden regressions + +- Do not reuse the failed heuristic of collecting arbitrary preceding IfStmt nodes and accepting any capacity-sized operand plus any syntactically nested terminator. +- Do not equate lexical source order with dominance, path reachability, or enforcement of a guard. +- Do not suppress on a comparison unless the checker proves accumulator identity, comparison direction, rejecting successor, and the path relationship to every sink. +- Do not use a pure strcat/strcpy syntax match or fixed-array plus nonliteral-source match; those patterns cannot distinguish the patched helper from the vulnerability. +- Do not introduce unnecessary caller-to-callee dataflow or symbolic-state machinery merely to recover a literal value when semantic CFG and argument relationships suffice. +- Do not rely on file paths, source lines, patch anchors, project identifiers, exact variable names, or the literal capacity 256. +- Do not count scans with parse failures, missing headers, invalid flags, or unverified recovery commands as validation evidence. diff --git a/tasks/csa159/pair_135446/checker_template.cpp b/tasks/csa159/pair_135446/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_135446/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_135446/config.json b/tasks/csa159/pair_135446/config.json new file mode 100644 index 0000000000000000000000000000000000000000..ae9517392fd925348f6c77653ea5763957323358 --- /dev/null +++ b/tasks/csa159/pair_135446/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "openSUSE_libsolv", + "before_commit": "926244b99d3261b3f60bd974612999a9c781a7ab", + "after_commit": "0077ef29eb46d2e1df2f230fc95a1d9748d49dec", + "repo_path": "/workspace/repo/openSUSE/libsolv", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/openSUSE_libsolv/7046fb004987c7f1b3722628d9a4ca1c67577188/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/openSUSE_libsolv/7046fb004987c7f1b3722628d9a4ca1c67577188/compile_commands.json", + "changed_files": [ + "ext/testcase.c" + ], + "commit_message": "testcase_read: error out if repos are added or the system is changed too late\n\nWe must not add new solvables after the considered map was created, the solver\nwas created, or jobs were added. We may not changed the system after jobs have\nbeen added.\n\n(Jobs may point inside the whatproviedes array, so we must not invalidate this\narea.)", + "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_135446/patch.diff b/tasks/csa159/pair_135446/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ab21aab793614565f09e0259d98fa337e124c837 --- /dev/null +++ b/tasks/csa159/pair_135446/patch.diff @@ -0,0 +1,46 @@ +diff --git a/ext/testcase.c b/ext/testcase.c +index 0be7a213..8fb6d793 100644 +--- a/ext/testcase.c ++++ b/ext/testcase.c +@@ -1991,6 +1991,7 @@ testcase_read(Pool *pool, FILE *fp, const char *testcase, Queue *job, char **res + Id *genid = 0; + int ngenid = 0; + Queue autoinstq; ++ int oldjobsize = job ? job->count : 0; + + if (resultp) + *resultp = 0; +@@ -2065,6 +2066,21 @@ testcase_read(Pool *pool, FILE *fp, const char *testcase, Queue *job, char **res + int prio, subprio; + const char *rdata; + ++ if (pool->considered) ++ { ++ pool_error(pool, 0, "testcase_read: cannot add repos after packages were disabled"); ++ continue; ++ } ++ if (solv) ++ { ++ pool_error(pool, 0, "testcase_read: cannot add repos after the solver was created"); ++ continue; ++ } ++ if (job && job->count != oldjobsize) ++ { ++ pool_error(pool, 0, "testcase_read: cannot add repos after jobs have been created"); ++ continue; ++ } + prepared = 0; + if (!poolflagsreset) + { +@@ -2125,6 +2141,11 @@ testcase_read(Pool *pool, FILE *fp, const char *testcase, Queue *job, char **res + int i; + + /* must set the disttype before the arch */ ++ if (job && job->count != oldjobsize) ++ { ++ pool_error(pool, 0, "testcase_read: cannot change the system after jobs have been created"); ++ continue; ++ } + prepared = 0; + if (strcmp(pieces[2], "*") != 0) + { \ No newline at end of file diff --git a/tasks/csa159/pair_135446/post_functions.txt b/tasks/csa159/pair_135446/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..385b68a348d806c6c3be5e16ca9e386681b90d16 --- /dev/null +++ b/tasks/csa159/pair_135446/post_functions.txt @@ -0,0 +1,313 @@ +### File: ext/testcase.c +```c +Solver * +testcase_read(Pool *pool, FILE *fp, const char *testcase, Queue *job, char **resultp, int *resultflagsp) +{ + Solver *solv; + char *buf, *bufp; + int bufl; + char *testcasedir, *s; + int l; + char **pieces = 0; + int npieces = 0; + int prepared = 0; + int closefp = !fp; + int poolflagsreset = 0; + int missing_features = 0; + Id *genid = 0; + int ngenid = 0; + Queue autoinstq; + int oldjobsize = job ? job->count : 0; + + if (resultp) + *resultp = 0; + if (resultflagsp) + *resultflagsp = 0; + if (!fp && !(fp = fopen(testcase, "r"))) + { + pool_error(pool, 0, "testcase_read: could not open '%s'", testcase); + return 0; + } + testcasedir = solv_strdup(testcase); + s = strrchr(testcasedir, '/'); +#ifdef _WIN32 + buf = strrchr(testcasedir, '\\'); + if (!s || (buf && buf > s)) + s = buf; +#endif + if (s) + s[1] = 0; + else + *testcasedir = 0; + bufl = 1024; + buf = solv_malloc(bufl); + bufp = buf; + solv = 0; + queue_init(&autoinstq); + for (;;) + { + if (bufp - buf + 16 > bufl) + { + bufl = bufp - buf; + buf = solv_realloc(buf, bufl + 512); + bufp = buf + bufl; + bufl += 512; + } + if (!fgets(bufp, bufl - (bufp - buf), fp)) + break; + bufp = buf; + l = strlen(buf); + if (!l || buf[l - 1] != '\n') + { + bufp += l; + continue; + } + buf[--l] = 0; + s = buf; + while (*s && (*s == ' ' || *s == '\t')) + s++; + if (!*s || *s == '#') + continue; + npieces = 0; + /* split it in pieces */ + for (;;) + { + while (*s == ' ' || *s == '\t') + s++; + if (!*s) + break; + pieces = solv_extend(pieces, npieces, 1, sizeof(*pieces), 7); + pieces[npieces++] = s; + while (*s && *s != ' ' && *s != '\t') + s++; + if (*s) + *s++ = 0; + } + pieces = solv_extend(pieces, npieces, 1, sizeof(*pieces), 7); + pieces[npieces] = 0; + if (!strcmp(pieces[0], "repo") && npieces >= 4) + { + Repo *repo = repo_create(pool, pieces[1]); + FILE *rfp; + int prio, subprio; + const char *rdata; + + if (pool->considered) + { + pool_error(pool, 0, "testcase_read: cannot add repos after packages were disabled"); + continue; + } + if (solv) + { + pool_error(pool, 0, "testcase_read: cannot add repos after the solver was created"); + continue; + } + if (job && job->count != oldjobsize) + { + pool_error(pool, 0, "testcase_read: cannot add repos after jobs have been created"); + continue; + } + prepared = 0; + if (!poolflagsreset) + { + poolflagsreset = 1; + testcase_resetpoolflags(pool); /* hmm */ + } + if (sscanf(pieces[2], "%d.%d", &prio, &subprio) != 2) + { + subprio = 0; + prio = atoi(pieces[2]); + } + repo->priority = prio; + repo->subpriority = subprio; + if (strcmp(pieces[3], "empty") != 0) + { + const char *repotype = pool_tmpjoin(pool, pieces[3], 0, 0); /* gets overwritten in case */ + if (!strcmp(pieces[4], "")) + { + char *idata = read_inline_file(fp, &buf, &bufp, &bufl); + rdata = ""; + rfp = solv_fmemopen(idata, strlen(idata), "rf"); + } + else + { + rdata = pool_tmpjoin(pool, testcasedir, pieces[4], 0); + rfp = solv_xfopen(rdata, "r"); + } + if (!rfp) + { + pool_error(pool, 0, "testcase_read: could not open '%s'", rdata); + } + else if (!strcmp(repotype, "testtags")) + { + testcase_add_testtags(repo, rfp, 0); + fclose(rfp); + } + else if (!strcmp(repotype, "solv")) + { + repo_add_solv(repo, rfp, 0); + fclose(rfp); + } +#if ENABLE_TESTCASE_HELIXREPO + else if (!strcmp(repotype, "helix")) + { + repo_add_helix(repo, rfp, 0); + fclose(rfp); + } +#endif + else + { + fclose(rfp); + pool_error(pool, 0, "testcase_read: unknown repo type for repo '%s'", repo->name); + } + } + } + else if (!strcmp(pieces[0], "system") && npieces >= 3) + { + int i; + + /* must set the disttype before the arch */ + if (job && job->count != oldjobsize) + { + pool_error(pool, 0, "testcase_read: cannot change the system after jobs have been created"); + continue; + } + prepared = 0; + if (strcmp(pieces[2], "*") != 0) + { + char *dp = pieces[2]; + while (dp && *dp) + { + char *dpe = strchr(dp, ','); + if (dpe) + *dpe = 0; + for (i = 0; disttype2str[i].str != 0; i++) + if (!strcmp(disttype2str[i].str, dp)) + break; + if (dpe) + *dpe++ = ','; + if (disttype2str[i].str) + { +#ifdef MULTI_SEMANTICS + if (pool->disttype != disttype2str[i].type) + pool_setdisttype(pool, disttype2str[i].type); +#endif + if (pool->disttype == disttype2str[i].type) + break; + } + dp = dpe; + } + if (!(dp && *dp)) + { + pool_error(pool, 0, "testcase_read: system: could not change disttype to '%s'", pieces[2]); + missing_features = 1; + } + } + if (strcmp(pieces[1], "unset") == 0 || strcmp(pieces[1], "-") == 0) + pool_setarch(pool, 0); + else if (pieces[1][0] == ':') + pool_setarchpolicy(pool, pieces[1] + 1); + else + pool_setarch(pool, pieces[1]); + if (npieces > 3) + { + Repo *repo = testcase_str2repo(pool, pieces[3]); + if (!repo) + pool_error(pool, 0, "testcase_read: system: unknown repo '%s'", pieces[3]); + else + pool_set_installed(pool, repo); + } + } + else if (!strcmp(pieces[0], "job") && npieces > 1) + { + char *sp; + Id how, what; + if (prepared <= 0) + { + pool_addfileprovides(pool); + pool_createwhatprovides(pool); + prepared = 1; + } + if (npieces >= 3 && !strcmp(pieces[2], "selection")) + { + addselectionjob(pool, pieces + 1, npieces - 1, job, 0, 0); + continue; + } + if (npieces >= 4 && !strcmp(pieces[2], "selection_matchdeps")) + { + pieces[2] = pieces[1]; + addselectionjob(pool, pieces + 2, npieces - 2, job, SELECTIONJOB_MATCHDEPS, pool_str2id(pool, pieces[3], 1)); + continue; + } + if (npieces >= 4 && !strcmp(pieces[2], "selection_matchdepid")) + { + pieces[2] = pieces[1]; + addselectionjob(pool, pieces + 2, npieces - 2, job, SELECTIONJOB_MATCHDEPID, pool_str2id(pool, pieces[3], 1)); + continue; + } + if (npieces >= 4 && !strcmp(pieces[2], "selection_matchsolvable")) + { + pieces[2] = pieces[1]; + addselectionjob(pool, pieces + 2, npieces - 2, job, SELECTIONJOB_MATCHSOLVABLE, pool_str2id(pool, pieces[3], 1)); + continue; + } + /* rejoin */ + for (sp = pieces[1]; sp < pieces[npieces - 1]; sp++) + if (*sp == 0) + *sp = ' '; + how = testcase_str2job(pool, pieces[1], &what); + if (how >= 0 && job) + queue_push2(job, how, what); + } + else if (!strcmp(pieces[0], "vendorclass") && npieces > 1) + { + pool_addvendorclass(pool, (const char **)(pieces + 1)); + } + else if (!strcmp(pieces[0], "namespace") && npieces > 1) + { + int i = strlen(pieces[1]); + s = strchr(pieces[1], '('); + if (!s || pieces[1][i - 1] != ')') + { + pool_error(pool, 0, "testcase_read: bad namespace '%s'", pieces[1]); + } + else + { + Id name, evr, id; + Queue q; + queue_init(&q); + *s = 0; + pieces[1][i - 1] = 0; + name = pool_str2id(pool, pieces[1], 1); + evr = pool_str2id(pool, s + 1, 1); + *s = '('; + pieces[1][i - 1] = ')'; + id = pool_rel2id(pool, name, evr, REL_NAMESPACE, 1); + for (i = 2; i < npieces; i++) + queue_push(&q, testcase_str2solvid(pool, pieces[i])); + /* now do the callback */ + if (prepared <= 0) + { + pool_addfileprovides(pool); + pool_createwhatprovides(pool); + prepared = 1; + } + pool->whatprovides_rel[GETRELID(id)] = pool_queuetowhatprovides(pool, &q); + queue_free(&q); + } + } + else if (!strcmp(pieces[0], "poolflags")) + { + int i; + if (!poolflagsreset) + { + poolflagsreset = 1; + testcase_resetpoolflags(pool); /* hmm */ + } + for (i = 1; i < npieces; i++) + testcase_setpoolflags(pool, pieces[i]); + } + else if + +// ... (5039 more chars) +``` diff --git a/tasks/csa159/pair_135446/pre_functions.txt b/tasks/csa159/pair_135446/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..bbc7e20aab9ccc2d83e3d0fc7edac9a0ede712c8 --- /dev/null +++ b/tasks/csa159/pair_135446/pre_functions.txt @@ -0,0 +1,315 @@ +### File: ext/testcase.c +```c +Solver * +testcase_read(Pool *pool, FILE *fp, const char *testcase, Queue *job, char **resultp, int *resultflagsp) +{ + Solver *solv; + char *buf, *bufp; + int bufl; + char *testcasedir, *s; + int l; + char **pieces = 0; + int npieces = 0; + int prepared = 0; + int closefp = !fp; + int poolflagsreset = 0; + int missing_features = 0; + Id *genid = 0; + int ngenid = 0; + Queue autoinstq; + + if (resultp) + *resultp = 0; + if (resultflagsp) + *resultflagsp = 0; + if (!fp && !(fp = fopen(testcase, "r"))) + { + pool_error(pool, 0, "testcase_read: could not open '%s'", testcase); + return 0; + } + testcasedir = solv_strdup(testcase); + s = strrchr(testcasedir, '/'); +#ifdef _WIN32 + buf = strrchr(testcasedir, '\\'); + if (!s || (buf && buf > s)) + s = buf; +#endif + if (s) + s[1] = 0; + else + *testcasedir = 0; + bufl = 1024; + buf = solv_malloc(bufl); + bufp = buf; + solv = 0; + queue_init(&autoinstq); + for (;;) + { + if (bufp - buf + 16 > bufl) + { + bufl = bufp - buf; + buf = solv_realloc(buf, bufl + 512); + bufp = buf + bufl; + bufl += 512; + } + if (!fgets(bufp, bufl - (bufp - buf), fp)) + break; + bufp = buf; + l = strlen(buf); + if (!l || buf[l - 1] != '\n') + { + bufp += l; + continue; + } + buf[--l] = 0; + s = buf; + while (*s && (*s == ' ' || *s == '\t')) + s++; + if (!*s || *s == '#') + continue; + npieces = 0; + /* split it in pieces */ + for (;;) + { + while (*s == ' ' || *s == '\t') + s++; + if (!*s) + break; + pieces = solv_extend(pieces, npieces, 1, sizeof(*pieces), 7); + pieces[npieces++] = s; + while (*s && *s != ' ' && *s != '\t') + s++; + if (*s) + *s++ = 0; + } + pieces = solv_extend(pieces, npieces, 1, sizeof(*pieces), 7); + pieces[npieces] = 0; + if (!strcmp(pieces[0], "repo") && npieces >= 4) + { + Repo *repo = repo_create(pool, pieces[1]); + FILE *rfp; + int prio, subprio; + const char *rdata; + + prepared = 0; + if (!poolflagsreset) + { + poolflagsreset = 1; + testcase_resetpoolflags(pool); /* hmm */ + } + if (sscanf(pieces[2], "%d.%d", &prio, &subprio) != 2) + { + subprio = 0; + prio = atoi(pieces[2]); + } + repo->priority = prio; + repo->subpriority = subprio; + if (strcmp(pieces[3], "empty") != 0) + { + const char *repotype = pool_tmpjoin(pool, pieces[3], 0, 0); /* gets overwritten in case */ + if (!strcmp(pieces[4], "")) + { + char *idata = read_inline_file(fp, &buf, &bufp, &bufl); + rdata = ""; + rfp = solv_fmemopen(idata, strlen(idata), "rf"); + } + else + { + rdata = pool_tmpjoin(pool, testcasedir, pieces[4], 0); + rfp = solv_xfopen(rdata, "r"); + } + if (!rfp) + { + pool_error(pool, 0, "testcase_read: could not open '%s'", rdata); + } + else if (!strcmp(repotype, "testtags")) + { + testcase_add_testtags(repo, rfp, 0); + fclose(rfp); + } + else if (!strcmp(repotype, "solv")) + { + repo_add_solv(repo, rfp, 0); + fclose(rfp); + } +#if ENABLE_TESTCASE_HELIXREPO + else if (!strcmp(repotype, "helix")) + { + repo_add_helix(repo, rfp, 0); + fclose(rfp); + } +#endif + else + { + fclose(rfp); + pool_error(pool, 0, "testcase_read: unknown repo type for repo '%s'", repo->name); + } + } + } + else if (!strcmp(pieces[0], "system") && npieces >= 3) + { + int i; + + /* must set the disttype before the arch */ + prepared = 0; + if (strcmp(pieces[2], "*") != 0) + { + char *dp = pieces[2]; + while (dp && *dp) + { + char *dpe = strchr(dp, ','); + if (dpe) + *dpe = 0; + for (i = 0; disttype2str[i].str != 0; i++) + if (!strcmp(disttype2str[i].str, dp)) + break; + if (dpe) + *dpe++ = ','; + if (disttype2str[i].str) + { +#ifdef MULTI_SEMANTICS + if (pool->disttype != disttype2str[i].type) + pool_setdisttype(pool, disttype2str[i].type); +#endif + if (pool->disttype == disttype2str[i].type) + break; + } + dp = dpe; + } + if (!(dp && *dp)) + { + pool_error(pool, 0, "testcase_read: system: could not change disttype to '%s'", pieces[2]); + missing_features = 1; + } + } + if (strcmp(pieces[1], "unset") == 0 || strcmp(pieces[1], "-") == 0) + pool_setarch(pool, 0); + else if (pieces[1][0] == ':') + pool_setarchpolicy(pool, pieces[1] + 1); + else + pool_setarch(pool, pieces[1]); + if (npieces > 3) + { + Repo *repo = testcase_str2repo(pool, pieces[3]); + if (!repo) + pool_error(pool, 0, "testcase_read: system: unknown repo '%s'", pieces[3]); + else + pool_set_installed(pool, repo); + } + } + else if (!strcmp(pieces[0], "job") && npieces > 1) + { + char *sp; + Id how, what; + if (prepared <= 0) + { + pool_addfileprovides(pool); + pool_createwhatprovides(pool); + prepared = 1; + } + if (npieces >= 3 && !strcmp(pieces[2], "selection")) + { + addselectionjob(pool, pieces + 1, npieces - 1, job, 0, 0); + continue; + } + if (npieces >= 4 && !strcmp(pieces[2], "selection_matchdeps")) + { + pieces[2] = pieces[1]; + addselectionjob(pool, pieces + 2, npieces - 2, job, SELECTIONJOB_MATCHDEPS, pool_str2id(pool, pieces[3], 1)); + continue; + } + if (npieces >= 4 && !strcmp(pieces[2], "selection_matchdepid")) + { + pieces[2] = pieces[1]; + addselectionjob(pool, pieces + 2, npieces - 2, job, SELECTIONJOB_MATCHDEPID, pool_str2id(pool, pieces[3], 1)); + continue; + } + if (npieces >= 4 && !strcmp(pieces[2], "selection_matchsolvable")) + { + pieces[2] = pieces[1]; + addselectionjob(pool, pieces + 2, npieces - 2, job, SELECTIONJOB_MATCHSOLVABLE, pool_str2id(pool, pieces[3], 1)); + continue; + } + /* rejoin */ + for (sp = pieces[1]; sp < pieces[npieces - 1]; sp++) + if (*sp == 0) + *sp = ' '; + how = testcase_str2job(pool, pieces[1], &what); + if (how >= 0 && job) + queue_push2(job, how, what); + } + else if (!strcmp(pieces[0], "vendorclass") && npieces > 1) + { + pool_addvendorclass(pool, (const char **)(pieces + 1)); + } + else if (!strcmp(pieces[0], "namespace") && npieces > 1) + { + int i = strlen(pieces[1]); + s = strchr(pieces[1], '('); + if (!s || pieces[1][i - 1] != ')') + { + pool_error(pool, 0, "testcase_read: bad namespace '%s'", pieces[1]); + } + else + { + Id name, evr, id; + Queue q; + queue_init(&q); + *s = 0; + pieces[1][i - 1] = 0; + name = pool_str2id(pool, pieces[1], 1); + evr = pool_str2id(pool, s + 1, 1); + *s = '('; + pieces[1][i - 1] = ')'; + id = pool_rel2id(pool, name, evr, REL_NAMESPACE, 1); + for (i = 2; i < npieces; i++) + queue_push(&q, testcase_str2solvid(pool, pieces[i])); + /* now do the callback */ + if (prepared <= 0) + { + pool_addfileprovides(pool); + pool_createwhatprovides(pool); + prepared = 1; + } + pool->whatprovides_rel[GETRELID(id)] = pool_queuetowhatprovides(pool, &q); + queue_free(&q); + } + } + else if (!strcmp(pieces[0], "poolflags")) + { + int i; + if (!poolflagsreset) + { + poolflagsreset = 1; + testcase_resetpoolflags(pool); /* hmm */ + } + for (i = 1; i < npieces; i++) + testcase_setpoolflags(pool, pieces[i]); + } + else if (!strcmp(pieces[0], "solverflags") && npieces > 1) + { + int i; + if (!solv) + { + solv = solver_create(pool); + testcase_resetsolverflags(solv); + } + for (i = 1; i < npieces; i++) + testcase_setsolverflags(solv, pieces[i]); + } + else if (!strcmp(pieces[0], "result") && npieces > 1) + { + char *result = 0; + int resultflags = str2resultflags(pool, pieces[1]); + const char *rdata; + if (npieces > 2) + { + rdata = pool_tmpjoin(pool, testcasedir, pieces[2], 0); + if (!strcmp(pieces[2], "")) + result = read_inline_file(fp, &buf, &bufp, &bufl); + else + { + FILE *rfp = fopen(rdata, "r") + +// ... (4380 more chars) +``` diff --git a/tasks/csa159/pair_135446/task_prompt.md b/tasks/csa159/pair_135446/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..9f777044ed23034c5fa2557a40e9b8a81d647e17 --- /dev/null +++ b/tasks/csa159/pair_135446/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: `control_flow` + +### Current failure diagnosis + +- Path-sensitive ProgramState traits never became true: testcase_read dispatches on opaque fgets/strcmp of FILE input, so CSA never explores one exploded path that both enqueues jobs (or creates the solver / stores pool->considered) and later reaches a repo/system sink. +- scan_before produced n_buggy=0 on the buggy tree, so hard_validation, objective_gate (G3), semantic_mechanism, semantic_score, process_score, and refinement_accepted all failed; refinement was not run. +- JobsAdded/SolverSym/ConsideredSym could not survive the parse-loop back-edge, so PreCall sink predicates stayed false even though the sources and sinks are present in the same function. +- repo_create was treated as a repo sink even though the patch still calls it before the new continue-guards, so that sink choice cannot separate buggy from patched even if state tracking had worked. + +### Preserve from prior rollouts + +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- In testcase_read's parse loop, a job-queue write (addselectionjob or queue_push2 on the caller Queue*), solver_create, or a store to pool->considered can CFG-reach a later repo-content or system-change sink via the loop back-edge. +- Repo-content sinks are testcase_add_testtags, repo_add_solv, and repo_add_helix (the operations after the patch continue-guards), not repo_create which still executes before those guards. +- System-change sinks are pool_setarch, pool_setarchpolicy, and pool_set_installed. +- A finding requires that the sink is not dominated by a continue-guard on pool->considered, a non-null solv, or a job-queue count that differs from its function-entry value. +- Patched code is safe because those continue-guards dominate the sinks; buggy code has the same sinks with no such dominating guards. + +### Implementation constraints + +- Walk the CFG/AST of functions that both mutate a Queue* job parameter and call repo-add or system-change APIs (checkASTCodeBody or equivalent); do not rely on ProgramState facts surviving I/O-driven loops. +- Prove source-to-sink reachability through the parse-loop back-edge and test whether considered/solv/job-count continue-guards dominate each sink. +- Report at the unguarded sink call inside testcase_read using the sink source range; do not key diagnostics on repo_create. +- Identify sources and sinks by stable libsolv API and type names (s_Queue, s_Pool::considered, solver_create, repo_add_*, pool_setarch*) rather than patch locals, line numbers, or commit IDs. +- Keep reports inside the function that owns both the job-queue parameter and the parse loop; do not require interprocedural value tracking into addselectionjob. +- Silence on the patched TU must come from the new if-continue guards dominating the sinks, not from proving a symbolic job->count inequality. + +### Validation checklist + +- Checker compiles and registers as a CSA plugin. +- scan_before on the buggy tree yields n_buggy>0 with at least one warning in ext/testcase.c::testcase_read. +- Warning locations are at testcase_add_testtags/repo_add_solv/repo_add_helix and/or pool_setarch/pool_setarchpolicy/pool_set_installed, near the pre-patch repo (~2068) and system (~2128) handler spans. +- scan_after on the patched tree yields n_patched=0 for those sinks because the new guards dominate them, and the buggy reports disappear only in the patched function. +- No diagnostic is emitted solely at repo_create, which remains reachable after the patch. +- Cross-validation records N_buggy>0 and N_patched=0; refinement is executed and accepted. +- Reports must remain valid without matching the identifier oldjobsize. + +### Avoid and forbidden regressions + +- Do not track JobsAdded, SolverSym, ConsideredSym, or JobCountAtEntry in ProgramState across the fgets loop. +- Do not treat repo_create as a repo-invalidation sink. +- Do not match oldjobsize, patch line numbers, or commit hashes. +- Do not require a single exploded path to execute both a job/solver/disable command and a later repo/system command. +- Do not dump llvm::errs debug traces. +- Do not treat co-occurrence of source and sink call names in one function as sufficient without CFG reachability and guard-dominance (that does not distinguish patched from buggy). +- Do not demand interprocedural dataflow through addselectionjob or queue_push2 to prove that Queue::count changed. diff --git a/tasks/csa159/pair_135624/checker_template.cpp b/tasks/csa159/pair_135624/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_135624/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_135624/config.json b/tasks/csa159/pair_135624/config.json new file mode 100644 index 0000000000000000000000000000000000000000..18eda57327dc4a0a1e52ea0fcc6a7d5a414807ce --- /dev/null +++ b/tasks/csa159/pair_135624/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "sass_libsass", + "before_commit": "c93f0581c6b7794d8c1d5637c5c4dabd591b1d57", + "after_commit": "eb15533b07773c30dc03c9d742865604f47120ef", + "repo_path": "/workspace/repo/sass/libsass", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/sass_libsass/5c2501eaa115aafafb254fa4f3522efa0ee14edb/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/sass_libsass/5c2501eaa115aafafb254fa4f3522efa0ee14edb/compile_commands.json", + "changed_files": [ + "src/parser.cpp" + ], + "commit_message": "Fix memory leak in `parse_ie_keyword_arg`\n\n`kwd_arg` would never get freed when there was a parse error in\n`parse_ie_keyword_arg`.\n\nCloses #2656", + "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_135624/patch.diff b/tasks/csa159/pair_135624/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1ab4142ddb9ddad51575529f8e049623ec20b026 --- /dev/null +++ b/tasks/csa159/pair_135624/patch.diff @@ -0,0 +1,13 @@ +diff --git a/src/parser.cpp b/src/parser.cpp +index 374ffa13..516d593d 100644 +--- a/src/parser.cpp ++++ b/src/parser.cpp +@@ -1918,7 +1918,7 @@ namespace Sass { + + String_Obj Parser::parse_ie_keyword_arg() + { +- String_Schema_Ptr kwd_arg = SASS_MEMORY_NEW(String_Schema, pstate, 3); ++ String_Schema_Obj kwd_arg = SASS_MEMORY_NEW(String_Schema, pstate, 3); + if (lex< variable >()) { + kwd_arg->append(SASS_MEMORY_NEW(Variable, pstate, Util::normalize_underscores(lexed))); + } else { \ No newline at end of file diff --git a/tasks/csa159/pair_135624/post_functions.txt b/tasks/csa159/pair_135624/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2d5e0747dddc33a1bf09582a72590daf55c76dcc --- /dev/null +++ b/tasks/csa159/pair_135624/post_functions.txt @@ -0,0 +1,67 @@ +### File: src/parser.cpp +```c +String_Obj Parser::parse_ie_property() + { + lex< ie_property >(); + Token str(lexed); + const char* i = str.begin; + // see if there any interpolants + const char* p = find_first_in_interval< exactly, block_comment >(str.begin, str.end); + if (!p) { + return SASS_MEMORY_NEW(String_Quoted, pstate, std::string(str.begin, str.end)); + } + + String_Schema_Ptr schema = SASS_MEMORY_NEW(String_Schema, pstate); + while (i < str.end) { + p = find_first_in_interval< exactly, block_comment >(i, str.end); + if (p) { + if (i < p) { + schema->append(SASS_MEMORY_NEW(String_Constant, pstate, std::string(i, p))); // accumulate the preceding segment if it's nonempty + } + if (peek < sequence < optional_spaces, exactly > >(p+2)) { position = p+2; + css_error("Invalid CSS", " after ", ": expected expression (e.g. 1px, bold), was "); + } + const char* j = skip_over_scopes< exactly, exactly >(p+2, str.end); // find the closing brace + if (j) { + // parse the interpolant and accumulate it + Expression_Obj interp_node = Parser::from_token(Token(p+2, j), ctx, traces, pstate, source).parse_list(); + interp_node->is_interpolant(true); + schema->append(interp_node); + i = j; + } + else { + // throw an error if the interpolant is unterminated + error("unterminated interpolant inside IE function " + str.to_string()); + } + } + else { // no interpolants left; add the last segment if nonempty + if (i < str.end) { + schema->append(SASS_MEMORY_NEW(String_Constant, pstate, std::string(i, str.end))); + } + break; + } + } + return schema; + } + +String_Obj Parser::parse_ie_keyword_arg() + { + String_Schema_Obj kwd_arg = SASS_MEMORY_NEW(String_Schema, pstate, 3); + if (lex< variable >()) { + kwd_arg->append(SASS_MEMORY_NEW(Variable, pstate, Util::normalize_underscores(lexed))); + } else { + lex< alternatives< identifier_schema, identifier > >(); + kwd_arg->append(SASS_MEMORY_NEW(String_Constant, pstate, lexed)); + } + lex< exactly<'='> >(); + kwd_arg->append(SASS_MEMORY_NEW(String_Constant, pstate, lexed)); + if (peek< variable >()) kwd_arg->append(parse_list()); + else if (lex< number >()) { + std::string parsed(lexed); + Util::normalize_decimals(parsed); + kwd_arg->append(lexed_number(parsed)); + } + else if (peek < ie_keyword_arg_value >()) { kwd_arg->append(parse_list()); } + return kwd_arg; + } +``` diff --git a/tasks/csa159/pair_135624/pre_functions.txt b/tasks/csa159/pair_135624/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..0330eceebf636f870f47dfc7859e81aebb327561 --- /dev/null +++ b/tasks/csa159/pair_135624/pre_functions.txt @@ -0,0 +1,67 @@ +### File: src/parser.cpp +```c +String_Obj Parser::parse_ie_property() + { + lex< ie_property >(); + Token str(lexed); + const char* i = str.begin; + // see if there any interpolants + const char* p = find_first_in_interval< exactly, block_comment >(str.begin, str.end); + if (!p) { + return SASS_MEMORY_NEW(String_Quoted, pstate, std::string(str.begin, str.end)); + } + + String_Schema_Ptr schema = SASS_MEMORY_NEW(String_Schema, pstate); + while (i < str.end) { + p = find_first_in_interval< exactly, block_comment >(i, str.end); + if (p) { + if (i < p) { + schema->append(SASS_MEMORY_NEW(String_Constant, pstate, std::string(i, p))); // accumulate the preceding segment if it's nonempty + } + if (peek < sequence < optional_spaces, exactly > >(p+2)) { position = p+2; + css_error("Invalid CSS", " after ", ": expected expression (e.g. 1px, bold), was "); + } + const char* j = skip_over_scopes< exactly, exactly >(p+2, str.end); // find the closing brace + if (j) { + // parse the interpolant and accumulate it + Expression_Obj interp_node = Parser::from_token(Token(p+2, j), ctx, traces, pstate, source).parse_list(); + interp_node->is_interpolant(true); + schema->append(interp_node); + i = j; + } + else { + // throw an error if the interpolant is unterminated + error("unterminated interpolant inside IE function " + str.to_string()); + } + } + else { // no interpolants left; add the last segment if nonempty + if (i < str.end) { + schema->append(SASS_MEMORY_NEW(String_Constant, pstate, std::string(i, str.end))); + } + break; + } + } + return schema; + } + +String_Obj Parser::parse_ie_keyword_arg() + { + String_Schema_Ptr kwd_arg = SASS_MEMORY_NEW(String_Schema, pstate, 3); + if (lex< variable >()) { + kwd_arg->append(SASS_MEMORY_NEW(Variable, pstate, Util::normalize_underscores(lexed))); + } else { + lex< alternatives< identifier_schema, identifier > >(); + kwd_arg->append(SASS_MEMORY_NEW(String_Constant, pstate, lexed)); + } + lex< exactly<'='> >(); + kwd_arg->append(SASS_MEMORY_NEW(String_Constant, pstate, lexed)); + if (peek< variable >()) kwd_arg->append(parse_list()); + else if (lex< number >()) { + std::string parsed(lexed); + Util::normalize_decimals(parsed); + kwd_arg->append(lexed_number(parsed)); + } + else if (peek < ie_keyword_arg_value >()) { kwd_arg->append(parse_list()); } + return kwd_arg; + } +``` diff --git a/tasks/csa159/pair_135624/task_prompt.md b/tasks/csa159/pair_135624/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..44c717680ff56c5a5a39b91ee2d05bc442ff6694 --- /dev/null +++ b/tasks/csa159/pair_135624/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: `path_sensitive` + +### Current failure diagnosis + +- The rollout did not establish hard validation, leaving the objective gate at G5 rather than the required G6 and the process score below threshold. +- Refinement ended with feedback_required rather than an accepted or clean outcome. +- The exception oracle treated a throw lexically present in a callee or transitive callee as propagating, without proving that it escapes intervening catch scopes. +- The claimed safe cases exceeded the demonstrated ownership model: direct SharedImpl assignment and all stated transfer forms were not fully recognized. +- Differential sharpness was low: 12 buggy-tree reports and 11 patched-tree reports produced only one patch-relevant disappearance, although no unrelated warning disappeared. + +### Preserve from prior rollouts + +- Retain the accepted path-sensitive mechanism level and a semantic score at or above the configured threshold. +- Retain an accepted or clean refinement outcome. +- Remain independent of changed lines, patch text, commit identity, source locations, and the names parse_ie_keyword_arg and kwd_arg. +- Remain free of patch-local hardcoding while using stable project ownership semantics. +- Preserve detection of the relevant buggy allocation and suppression after immediate owning String_Schema_Obj initialization. + +### Required semantic proof + +- Prove that a feasible path creates a MemRegion for a SharedObj-derived allocation and reaches an exception-propagating operation while that same region remains unadopted. +- Prove that SharedImpl ownership has not been established before the sink on the reporting path; adoption on a sibling path must not discharge the region. +- Treat a sink as relevant only when an exception can escape the called operation and unwind across the lifetime of the raw local, accounting for visible catches rather than merely finding a nested throw. +- Suppress the report when every feasible path to an escaping-exception sink first transfers the allocation into an owning SharedImpl. +- Distinguish raw, non-owning pointer storage from ownership-producing construction, assignment, parameter transfer, or return conversion according to the evidenced SharedImpl contract. + +### Implementation constraints + +- Use ProgramState keyed by allocation identity, with check::PostStmt to introduce unadopted SharedObj-derived regions and path-local transitions to update ownership. +- Observe ownership-producing SharedImpl operations with callbacks appropriate to construction and any supported assignment or transfer forms; each discharge must resolve to the tracked MemRegion. +- Use check::PreCall for the throwing sink because exception-unwind exits are not represented adequately by check::EndFunction. +- Derive ordering and reachability from the ExplodedGraph and current ProgramState, not lexical source order; keep the ownership proof intraprocedural. +- Any auxiliary callee analysis must be structural, bounded, cycle-safe, restricted to available evidence, and distinguish escaping throws from throws caught before return. +- Emit one diagnostic per proven allocation-path condition, with the primary location at the allocation and a secondary note at the exception-capable call. +- Scope matching to stable SharedObj inheritance and SharedImpl ownership behavior rather than parser function names, variable names, filenames, line numbers, or changed literals. + +### Validation checklist + +- Compile and load the checker against the target Clang Static Analyzer API with no diagnostics or registration failures. +- Scan both source revisions and confirm a diagnostic in buggy Parser::parse_ie_keyword_arg that disappears after String_Schema_Ptr becomes String_Schema_Obj. +- Confirm the primary diagnostic location is the vulnerable String_Schema allocation and the path note identifies the proven escaping-exception sink. +- Exercise branch cases where adoption occurs on all paths, one path, or no path, verifying that ProgramState does not discharge sibling paths. +- Exercise immediate construction and each supported later ownership-transfer form, especially direct SharedImpl assignment, and require clean results after adoption. +- Exercise direct throws, transitively escaping throws, locally caught throws, indirect or unavailable callees, loops, early returns, and non-SharedObj allocations. +- Review the 11 warnings that remain in the patched tree against the full ownership and exception-propagation proof; suppress unsupported cases semantically rather than by location. +- Require hard validation, objective eligibility of at least G6, accepted or clean refinement, and a process score above threshold before rollout. + +### Avoid and forbidden regressions + +- Do not reduce the design to syntax-only or control-flow-only matching; local declaration shape and CFG order cannot represent path-specific ownership. +- Do not use check::Bind as the sole adoption signal because raw binding and SharedImpl ownership are not reliably distinguished there. +- Do not defer detection to check::EndFunction or assume CSA models exception-unwind exits as ordinary analyzed paths. +- Do not classify a call as propagating solely because a visible body or transitive callee contains CXXThrowExpr. +- Do not claim ownership-transfer safe cases that the selected callbacks and region resolution cannot demonstrate. +- Do not suppress remaining reports to improve sharpness through patch anchors, function allowlists, line proximity, source-text matching, or changed identifiers. +- Do not report non-SharedObj allocations or paths on which an owning SharedImpl has already adopted the tracked region. diff --git a/tasks/csa159/pair_135745/checker_template.cpp b/tasks/csa159/pair_135745/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_135745/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_135745/config.json b/tasks/csa159/pair_135745/config.json new file mode 100644 index 0000000000000000000000000000000000000000..45614674aceeca96dad4370bca888caac5149e3c --- /dev/null +++ b/tasks/csa159/pair_135745/config.json @@ -0,0 +1,20 @@ +{ + "project_id": "verdammelt_tnef", + "before_commit": "5af0791db67d50ce5ebc16252626c679bb4079fb", + "after_commit": "cfdd80f52b31215bb4cf59ffb6e1bf5be93ead7c", + "repo_path": "/workspace/repo/verdammelt/tnef", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/verdammelt_tnef/5af0791db67d50ce5ebc16252626c679bb4079fb/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/verdammelt_tnef/5af0791db67d50ce5ebc16252626c679bb4079fb/compile_commands.json", + "changed_files": [ + "src/mapi_attr.c", + "src/util.c" + ], + "commit_message": "Handle overflow problem reported in #23\n\n1. Assert that names must be non-zero length.\n2. Keep unicode_to_utf8 from underflowing.", + "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_135745/patch.diff b/tasks/csa159/pair_135745/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b2e39ec62f2d2678ab7aab8f5ed817e1ab590339 --- /dev/null +++ b/tasks/csa159/pair_135745/patch.diff @@ -0,0 +1,68 @@ +diff --git a/src/mapi_attr.c b/src/mapi_attr.c +index 3f3250b..455cc67 100644 +--- a/src/mapi_attr.c ++++ b/src/mapi_attr.c +@@ -211,6 +211,8 @@ mapi_attr_read (size_t len, unsigned char *buf) + CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; + + /* read the data into a buffer */ ++ /* read the data into a buffer */ ++ assert(a->names[i].len != 0); + assert(idx+a->names[i].len <= len); + a->names[i].data = unicode_to_utf8(a->names[i].len, buf+idx); + +diff --git a/src/util.c b/src/util.c +index 9a56e0e..db9e714 100644 +--- a/src/util.c ++++ b/src/util.c +@@ -85,28 +85,29 @@ unicode_to_utf8 (size_t len, unsigned char* buf) + int j = 0; + unsigned char *utf8 = malloc (3 * len/2 + 1); /* won't get any longer than this */ + +- for (i = 0; i < len - 1; i += 2) +- { +- uint32 c = GETINT16(buf + i); +- if (c <= 0x007f) +- { +- utf8[j++] = 0x00 | ((c & 0x007f) >> 0); +- } +- else if (c < 0x07ff) +- { +- utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6); +- utf8[j++] = 0x80 | ((c & 0x003f) >> 0); +- } +- else +- { +- utf8[j++] = 0xe0 | ((c & 0xf000) >> 12); +- utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6); +- utf8[j++] = 0x80 | ((c & 0x003f) >> 0); +- } ++ if (len > 0) { ++ for (i = 0; i < len - 1; i += 2) ++ { ++ uint32 c = GETINT16(buf + i); ++ if (c <= 0x007f) ++ { ++ utf8[j++] = 0x00 | ((c & 0x007f) >> 0); ++ } ++ else if (c < 0x07ff) ++ { ++ utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6); ++ utf8[j++] = 0x80 | ((c & 0x003f) >> 0); ++ } ++ else ++ { ++ utf8[j++] = 0xe0 | ((c & 0xf000) >> 12); ++ utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6); ++ utf8[j++] = 0x80 | ((c & 0x003f) >> 0); ++ } ++ } + } +- ++ + utf8[j] = '\0'; +- ++ + return utf8; + } +- \ No newline at end of file diff --git a/tasks/csa159/pair_135745/post_functions.txt b/tasks/csa159/pair_135745/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..b5e3c67231b90e9844223f512530534cbf3ca1b6 --- /dev/null +++ b/tasks/csa159/pair_135745/post_functions.txt @@ -0,0 +1,220 @@ +### File: src/mapi_attr.c +```c +MAPI_Attr** +mapi_attr_read (size_t len, unsigned char *buf) +{ + size_t idx = 0; + uint32 i,j; + assert(len > 4); + uint32 num_properties = GETINT32(buf+idx); + assert((num_properties+1) != 0); + MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); + + idx += 4; + + if (!attrs) return NULL; + for (i = 0; i < num_properties; i++) + { + MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); + MAPI_Value* v = NULL; + + CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; + CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; + + /* handle special case of GUID prefixed properties */ + if (a->name & GUID_EXISTS_FLAG) + { + /* copy GUID */ + a->guid = CHECKED_XMALLOC(GUID, 1); + copy_guid_from_buf(a->guid, buf+idx, len-idx); + idx += sizeof (GUID); + + CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; + if (a->num_names > 0) + { + size_t i; + + a->names = CHECKED_XCALLOC(VarLenData, a->num_names); + assert(a->names); + for (i = 0; i < a->num_names; i++) + { + size_t j; + + CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; + + /* read the data into a buffer */ + /* read the data into a buffer */ + assert(a->names[i].len != 0); + assert(idx+a->names[i].len <= len); + a->names[i].data = unicode_to_utf8(a->names[i].len, buf+idx); + + idx += pad_to_4byte(a->names[i].len); + } + } + else + { + /* get the 'real' name */ + CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; + } + } + + /* + * Multi-value types and string/object/binary types have + * multiple values + */ + if (a->type & MULTI_VALUE_FLAG || + a->type == szMAPI_STRING || + a->type == szMAPI_UNICODE_STRING || + a->type == szMAPI_OBJECT || + a->type == szMAPI_BINARY) + { + CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); + idx += 4; + } + else + { + a->num_values = 1; + } + + /* Amend the type in case of multi-value type */ + if (a->type & MULTI_VALUE_FLAG) + { + a->type -= MULTI_VALUE_FLAG; + } + + + v = alloc_mapi_values (a); + assert(v); + for (j = 0; j < a->num_values; j++) + { + switch (a->type) + { + case szMAPI_SHORT: /* 2 bytes */ + v->len = 2; + CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); + idx += 4; /* assume padding of 2, advance by 4! */ + break; + + case szMAPI_INT: /* 4 bytes */ + v->len = 4; + CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); + idx += 4; + v++; + break; + + case szMAPI_FLOAT: /* 4 bytes */ + case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ + v->len = 4; + CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); + idx += v->len; + break; + + case szMAPI_SYSTIME: /* 8 bytes */ + v->len = 8; + CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); + CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); + idx += 8; + v++; + break; + + case szMAPI_DOUBLE: /* 8 bytes */ + case szMAPI_APPTIME: + case szMAPI_CURRENCY: + case szMAPI_INT8BYTE: + v->len = 8; + CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); + CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); + idx += v->len; + break; + + case szMAPI_CLSID: + v->len = sizeof (GUID); + copy_guid_from_buf(&v->data.guid, buf+idx, len-idx); + idx += v->len; + break; + + case szMAPI_STRING: + case szMAPI_UNICODE_STRING: + case szMAPI_OBJECT: + case szMAPI_BINARY: + CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; + + assert(v->len + idx <= len); + + if (a->type == szMAPI_UNICODE_STRING) + { + assert(v->len != 0); + v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); + } + else + { + v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); + memmove (v->data.buf, buf+idx, v->len); + } + + idx += pad_to_4byte(v->len); + v++; + break; + + case szMAPI_NULL: /* illegal in input tnef streams */ + case szMAPI_ERROR: + case szMAPI_UNSPECIFIED: + fprintf (stderr, + "Invalid attribute, input file may be corrupted\n"); + if (!ENCODE_SKIP) exit (1); + + return NULL; + + default: /* should never get here */ + fprintf (stderr, + "Undefined attribute, input file may be corrupted\n"); + if (!ENCODE_SKIP) exit (1); + + return NULL; + + } + if (DEBUG_ON) mapi_attr_dump (attrs[i]); + } + } + attrs[i] = NULL; + + return attrs; +} +``` + +### File: src/util.c +```c +unsigned char* +unicode_to_utf8 (size_t len, unsigned char* buf) +{ + int i = 0; + int j = 0; + unsigned char *utf8 = malloc (3 * len/2 + 1); /* won't get any longer than this */ + + if (len > 0) { + for (i = 0; i < len - 1; i += 2) + { + uint32 c = GETINT16(buf + i); + if (c <= 0x007f) + { + utf8[j++] = 0x00 | ((c & 0x007f) >> 0); + } + else if (c < 0x07ff) + { + utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6); + utf8[j++] = 0x80 | ((c & 0x003f) >> 0); + } + else + { + utf8[j++] = 0xe0 | ((c & 0xf000) >> 12); + utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6); + utf8[j++] = 0x80 | ((c & 0x003f) >> 0); + } + } + } + + utf8[j] = '\0'; + + return utf8; +} +``` diff --git a/tasks/csa159/pair_135745/pre_functions.txt b/tasks/csa159/pair_135745/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..488eeb17befcfd687bb5e199415c85d46eb85cdd --- /dev/null +++ b/tasks/csa159/pair_135745/pre_functions.txt @@ -0,0 +1,216 @@ +### File: src/mapi_attr.c +```c +MAPI_Attr** +mapi_attr_read (size_t len, unsigned char *buf) +{ + size_t idx = 0; + uint32 i,j; + assert(len > 4); + uint32 num_properties = GETINT32(buf+idx); + assert((num_properties+1) != 0); + MAPI_Attr** attrs = CHECKED_XMALLOC (MAPI_Attr*, (num_properties + 1)); + + idx += 4; + + if (!attrs) return NULL; + for (i = 0; i < num_properties; i++) + { + MAPI_Attr* a = attrs[i] = CHECKED_XCALLOC(MAPI_Attr, 1); + MAPI_Value* v = NULL; + + CHECKINT16(idx, len); a->type = GETINT16(buf+idx); idx += 2; + CHECKINT16(idx, len); a->name = GETINT16(buf+idx); idx += 2; + + /* handle special case of GUID prefixed properties */ + if (a->name & GUID_EXISTS_FLAG) + { + /* copy GUID */ + a->guid = CHECKED_XMALLOC(GUID, 1); + copy_guid_from_buf(a->guid, buf+idx, len-idx); + idx += sizeof (GUID); + + CHECKINT32(idx, len); a->num_names = GETINT32(buf+idx); idx += 4; + if (a->num_names > 0) + { + size_t i; + + a->names = CHECKED_XCALLOC(VarLenData, a->num_names); + assert(a->names); + for (i = 0; i < a->num_names; i++) + { + size_t j; + + CHECKINT32(idx, len); a->names[i].len = GETINT32(buf+idx); idx += 4; + + /* read the data into a buffer */ + assert(idx+a->names[i].len <= len); + a->names[i].data = unicode_to_utf8(a->names[i].len, buf+idx); + + idx += pad_to_4byte(a->names[i].len); + } + } + else + { + /* get the 'real' name */ + CHECKINT32(idx, len); a->name = GETINT32(buf+idx); idx+= 4; + } + } + + /* + * Multi-value types and string/object/binary types have + * multiple values + */ + if (a->type & MULTI_VALUE_FLAG || + a->type == szMAPI_STRING || + a->type == szMAPI_UNICODE_STRING || + a->type == szMAPI_OBJECT || + a->type == szMAPI_BINARY) + { + CHECKINT32(idx, len); a->num_values = GETINT32(buf+idx); + idx += 4; + } + else + { + a->num_values = 1; + } + + /* Amend the type in case of multi-value type */ + if (a->type & MULTI_VALUE_FLAG) + { + a->type -= MULTI_VALUE_FLAG; + } + + + v = alloc_mapi_values (a); + assert(v); + for (j = 0; j < a->num_values; j++) + { + switch (a->type) + { + case szMAPI_SHORT: /* 2 bytes */ + v->len = 2; + CHECKINT16(idx, len); v->data.bytes2 = GETINT16(buf+idx); + idx += 4; /* assume padding of 2, advance by 4! */ + break; + + case szMAPI_INT: /* 4 bytes */ + v->len = 4; + CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); + idx += 4; + v++; + break; + + case szMAPI_FLOAT: /* 4 bytes */ + case szMAPI_BOOLEAN: /* this should be 2 bytes + 2 padding */ + v->len = 4; + CHECKINT32(idx, len); v->data.bytes4 = GETINT32(buf+idx); + idx += v->len; + break; + + case szMAPI_SYSTIME: /* 8 bytes */ + v->len = 8; + CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); + CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); + idx += 8; + v++; + break; + + case szMAPI_DOUBLE: /* 8 bytes */ + case szMAPI_APPTIME: + case szMAPI_CURRENCY: + case szMAPI_INT8BYTE: + v->len = 8; + CHECKINT32(idx, len); v->data.bytes8[0] = GETINT32(buf+idx); + CHECKINT32(idx+4, len); v->data.bytes8[1] = GETINT32(buf+idx+4); + idx += v->len; + break; + + case szMAPI_CLSID: + v->len = sizeof (GUID); + copy_guid_from_buf(&v->data.guid, buf+idx, len-idx); + idx += v->len; + break; + + case szMAPI_STRING: + case szMAPI_UNICODE_STRING: + case szMAPI_OBJECT: + case szMAPI_BINARY: + CHECKINT32(idx, len); v->len = GETINT32(buf+idx); idx += 4; + + assert(v->len + idx <= len); + + if (a->type == szMAPI_UNICODE_STRING) + { + assert(v->len != 0); + v->data.buf = (unsigned char*)unicode_to_utf8(v->len, buf+idx); + } + else + { + v->data.buf = CHECKED_XMALLOC(unsigned char, v->len); + memmove (v->data.buf, buf+idx, v->len); + } + + idx += pad_to_4byte(v->len); + v++; + break; + + case szMAPI_NULL: /* illegal in input tnef streams */ + case szMAPI_ERROR: + case szMAPI_UNSPECIFIED: + fprintf (stderr, + "Invalid attribute, input file may be corrupted\n"); + if (!ENCODE_SKIP) exit (1); + + return NULL; + + default: /* should never get here */ + fprintf (stderr, + "Undefined attribute, input file may be corrupted\n"); + if (!ENCODE_SKIP) exit (1); + + return NULL; + + } + if (DEBUG_ON) mapi_attr_dump (attrs[i]); + } + } + attrs[i] = NULL; + + return attrs; +} +``` + +### File: src/util.c +```c +unsigned char* +unicode_to_utf8 (size_t len, unsigned char* buf) +{ + int i = 0; + int j = 0; + unsigned char *utf8 = malloc (3 * len/2 + 1); /* won't get any longer than this */ + + for (i = 0; i < len - 1; i += 2) + { + uint32 c = GETINT16(buf + i); + if (c <= 0x007f) + { + utf8[j++] = 0x00 | ((c & 0x007f) >> 0); + } + else if (c < 0x07ff) + { + utf8[j++] = 0xc0 | ((c & 0x07c0) >> 6); + utf8[j++] = 0x80 | ((c & 0x003f) >> 0); + } + else + { + utf8[j++] = 0xe0 | ((c & 0xf000) >> 12); + utf8[j++] = 0x80 | ((c & 0x0fc0) >> 6); + utf8[j++] = 0x80 | ((c & 0x003f) >> 0); + } + } + + utf8[j] = '\0'; + + return utf8; +} +``` diff --git a/tasks/csa159/pair_135745/task_prompt.md b/tasks/csa159/pair_135745/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_135745/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_135749/checker_template.cpp b/tasks/csa159/pair_135749/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_135749/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_135749/config.json b/tasks/csa159/pair_135749/config.json new file mode 100644 index 0000000000000000000000000000000000000000..dd62f317d97a5a6a5108775ff3ed73a2840547f4 --- /dev/null +++ b/tasks/csa159/pair_135749/config.json @@ -0,0 +1,20 @@ +{ + "project_id": "verdammelt_tnef", + "before_commit": "c5044689e50039635e7700fe2472fd632ac77176", + "after_commit": "8dccf79857ceeb7a6d3e42c1e762e7b865d5344d", + "repo_path": "/workspace/repo/verdammelt/tnef", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/verdammelt_tnef/99c70157998ff5f3c3e0fd1669c7cffdaaa32048/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/verdammelt_tnef/99c70157998ff5f3c3e0fd1669c7cffdaaa32048/compile_commands.json", + "changed_files": [ + "src/file.c", + "src/tnef.c" + ], + "commit_message": "Check types to avoid invalid reads/writes.", + "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_135749/patch.diff b/tasks/csa159/pair_135749/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..658ce6634f09cc4ed216a59cf1bbc1f4041df689 --- /dev/null +++ b/tasks/csa159/pair_135749/patch.diff @@ -0,0 +1,71 @@ +diff --git a/src/file.c b/src/file.c +index 4dacda4..4b3d81d 100644 +--- a/src/file.c ++++ b/src/file.c +@@ -173,11 +173,13 @@ file_add_mapi_attrs (File* file, MAPI_Attr** attrs) + switch (a->name) + { + case MAPI_ATTACH_LONG_FILENAME: ++ assert(a->type == szMAPI_STRING); + if (file->name) XFREE(file->name); + file->name = strdup( (char*)a->values[0].data.buf ); + break; + + case MAPI_ATTACH_DATA_OBJ: ++ assert((a->type == szMAPI_BINARY) || (a->type == szMAPI_OBJECT)); + file->len = a->values[0].len; + if (file->data) XFREE (file->data); + file->data = CHECKED_XMALLOC (unsigned char, file->len); +@@ -185,12 +187,14 @@ file_add_mapi_attrs (File* file, MAPI_Attr** attrs) + break; + + case MAPI_ATTACH_MIME_TAG: ++ assert(a->type == szMAPI_STRING); + if (file->mime_type) XFREE (file->mime_type); + file->mime_type = CHECKED_XMALLOC (char, a->values[0].len); + memmove (file->mime_type, a->values[0].data.buf, a->values[0].len); + break; + + case MAPI_ATTACH_CONTENT_ID: ++ assert(a->type == szMAPI_STRING); + if (file->content_id) XFREE(file->content_id); + file->content_id = CHECKED_XMALLOC (char, a->values[0].len); + memmove (file->content_id, a->values[0].data.buf, a->values[0].len); +diff --git a/src/tnef.c b/src/tnef.c +index 0f1d9e4..7f74e88 100644 +--- a/src/tnef.c ++++ b/src/tnef.c +@@ -165,10 +165,12 @@ get_html_data (MAPI_Attr *a) + int j; + for (j = 0; j < a->num_values; j++) + { +- body[j] = XMALLOC(VarLenData, 1); +- body[j]->len = a->values[j].len; +- body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len); +- memmove (body[j]->data, a->values[j].data.buf, body[j]->len); ++ if (a->type == szMAPI_BINARY) { ++ body[j] = XMALLOC(VarLenData, 1); ++ body[j]->len = a->values[j].len; ++ body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len); ++ memmove (body[j]->data, a->values[j].data.buf, body[j]->len); ++ } + } + return body; + } +@@ -306,13 +308,13 @@ parse_file (FILE* input_file, char* directory, + for (i = 0; mapi_attrs[i]; i++) + { + MAPI_Attr *a = mapi_attrs[i]; +- +- if (a->name == MAPI_BODY_HTML) ++ ++ if (a->type == szMAPI_BINARY && a->name == MAPI_BODY_HTML) + { + body.html_bodies = get_html_data (a); + html_size = a->num_values; + } +- else if (a->name == MAPI_RTF_COMPRESSED) ++ else if (a->type == szMAPI_BINARY && a->name == MAPI_RTF_COMPRESSED) + { + body.rtf_bodies = get_rtf_data (a); + rtf_size = a->num_values; \ No newline at end of file diff --git a/tasks/csa159/pair_135749/post_functions.txt b/tasks/csa159/pair_135749/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..99a38adf63e95aad2fc17d0a8f6d654fe0a76194 --- /dev/null +++ b/tasks/csa159/pair_135749/post_functions.txt @@ -0,0 +1,226 @@ +### File: src/file.c +```c +static void +file_add_mapi_attrs (File* file, MAPI_Attr** attrs) +{ + int i; + for (i = 0; attrs[i]; i++) + { + MAPI_Attr* a = attrs[i]; + + if (a->num_values) + { + + switch (a->name) + { + case MAPI_ATTACH_LONG_FILENAME: + assert(a->type == szMAPI_STRING); + if (file->name) XFREE(file->name); + file->name = strdup( (char*)a->values[0].data.buf ); + break; + + case MAPI_ATTACH_DATA_OBJ: + assert((a->type == szMAPI_BINARY) || (a->type == szMAPI_OBJECT)); + file->len = a->values[0].len; + if (file->data) XFREE (file->data); + file->data = CHECKED_XMALLOC (unsigned char, file->len); + memmove (file->data, a->values[0].data.buf, file->len); + break; + + case MAPI_ATTACH_MIME_TAG: + assert(a->type == szMAPI_STRING); + if (file->mime_type) XFREE (file->mime_type); + file->mime_type = CHECKED_XMALLOC (char, a->values[0].len); + memmove (file->mime_type, a->values[0].data.buf, a->values[0].len); + break; + + case MAPI_ATTACH_CONTENT_ID: + assert(a->type == szMAPI_STRING); + if (file->content_id) XFREE(file->content_id); + file->content_id = CHECKED_XMALLOC (char, a->values[0].len); + memmove (file->content_id, a->values[0].data.buf, a->values[0].len); + break; + + default: + break; + } + } + } +} +``` + +### File: src/tnef.c +```c +static VarLenData** +get_html_data (MAPI_Attr *a) +{ + VarLenData **body = XCALLOC(VarLenData*, a->num_values + 1); + + int j; + for (j = 0; j < a->num_values; j++) + { + if (a->type == szMAPI_BINARY) { + body[j] = XMALLOC(VarLenData, 1); + body[j]->len = a->values[j].len; + body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len); + memmove (body[j]->data, a->values[j].data.buf, body[j]->len); + } + } + return body; +} + +int +parse_file (FILE* input_file, char* directory, + char *body_filename, char *body_pref, + int flags) +{ + uint32 d; + uint16 key; + Attr *attr = NULL; + File *file = NULL; + int rtf_size = 0, html_size = 0; + MessageBody body; + memset (&body, '\0', sizeof (MessageBody)); + + /* store the program options in our file global variables */ + g_flags = flags; + + /* check that this is in fact a TNEF file */ + d = geti32(input_file); + if (d != TNEF_SIGNATURE) + { + fprintf (stdout, "Seems not to be a TNEF file\n"); + return 1; + } + + /* Get the key */ + key = geti16(input_file); + debug_print ("TNEF Key: %hx\n", key); + + /* The rest of the file is a series of 'messages' and 'attachments' */ + while ( data_left( input_file ) ) + { + attr = read_object( input_file ); + + if ( attr == NULL ) break; + + /* This signals the beginning of a file */ + if (attr->name == attATTACHRENDDATA) + { + if (file) + { + file_write (file, directory); + file_free (file); + } + else + { + file = CHECKED_XCALLOC (File, 1); + } + } + + /* Add the data to our lists. */ + switch (attr->lvl_type) + { + case LVL_MESSAGE: + if (attr->name == attBODY) + { + body.text_body = get_text_data (attr); + } + else if (attr->name == attMAPIPROPS) + { + MAPI_Attr **mapi_attrs + = mapi_attr_read (attr->len, attr->buf); + if (mapi_attrs) + { + int i; + for (i = 0; mapi_attrs[i]; i++) + { + MAPI_Attr *a = mapi_attrs[i]; + + if (a->type == szMAPI_BINARY && a->name == MAPI_BODY_HTML) + { + body.html_bodies = get_html_data (a); + html_size = a->num_values; + } + else if (a->type == szMAPI_BINARY && a->name == MAPI_RTF_COMPRESSED) + { + body.rtf_bodies = get_rtf_data (a); + rtf_size = a->num_values; + } + } + /* cannot save attributes to file, since they + * are not attachment attributes */ + /* file_add_mapi_attrs (file, mapi_attrs); */ + mapi_attr_free_list (mapi_attrs); + XFREE (mapi_attrs); + } + } + break; + case LVL_ATTACHMENT: + file_add_attr (file, attr); + break; + default: + fprintf (stderr, "Invalid lvl type on attribute: %d\n", + attr->lvl_type); + return 1; + break; + } + attr_free (attr); + XFREE (attr); + } + + if (file) + { + file_write (file, directory); + file_free (file); + XFREE (file); + } + + /* Write the message body */ + if (flags & SAVEBODY) + { + int i = 0; + int all_flag = 0; + if (strcmp (body_pref, "all") == 0) + { + all_flag = 1; + body_pref = "rht"; + } + + for (; i < 3; i++) + { + File **files + = get_body_files (body_filename, body_pref[i], &body); + if (files) + { + int j = 0; + for (; files[j]; j++) + { + file_write(files[j], directory); + file_free (files[j]); + XFREE(files[j]); + } + XFREE(files); + if (!all_flag) break; + } + } + } + + if (body.text_body) + { + free_bodies(body.text_body, 1); + XFREE(body.text_body); + } + if (rtf_size > 0) + { + free_bodies(body.rtf_bodies, rtf_size); + XFREE(body.rtf_bodies); + } + if (html_size > 0) + { + free_bodies(body.html_bodies, html_size); + XFREE(body.html_bodies); + } + return 0; +} +``` diff --git a/tasks/csa159/pair_135749/pre_functions.txt b/tasks/csa159/pair_135749/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2fba85ca0b9ac9adf7334a55638bafd2f310efed --- /dev/null +++ b/tasks/csa159/pair_135749/pre_functions.txt @@ -0,0 +1,284 @@ +### File: src/file.c +```c +static void +file_add_mapi_attrs (File* file, MAPI_Attr** attrs) +{ + int i; + for (i = 0; attrs[i]; i++) + { + MAPI_Attr* a = attrs[i]; + + if (a->num_values) + { + + switch (a->name) + { + case MAPI_ATTACH_LONG_FILENAME: + if (file->name) XFREE(file->name); + file->name = strdup( (char*)a->values[0].data.buf ); + break; + + case MAPI_ATTACH_DATA_OBJ: + file->len = a->values[0].len; + if (file->data) XFREE (file->data); + file->data = CHECKED_XMALLOC (unsigned char, file->len); + memmove (file->data, a->values[0].data.buf, file->len); + break; + + case MAPI_ATTACH_MIME_TAG: + if (file->mime_type) XFREE (file->mime_type); + file->mime_type = CHECKED_XMALLOC (char, a->values[0].len); + memmove (file->mime_type, a->values[0].data.buf, a->values[0].len); + break; + + case MAPI_ATTACH_CONTENT_ID: + if (file->content_id) XFREE(file->content_id); + file->content_id = CHECKED_XMALLOC (char, a->values[0].len); + memmove (file->content_id, a->values[0].data.buf, a->values[0].len); + break; + + default: + break; + } + } + } +} +``` + +### File: src/tnef.c +```c +static VarLenData** +get_html_data (MAPI_Attr *a) +{ + VarLenData **body = XCALLOC(VarLenData*, a->num_values + 1); + + int j; + for (j = 0; j < a->num_values; j++) + { + body[j] = XMALLOC(VarLenData, 1); + body[j]->len = a->values[j].len; + body[j]->data = CHECKED_XCALLOC(unsigned char, a->values[j].len); + memmove (body[j]->data, a->values[j].data.buf, body[j]->len); + } + return body; +} + +int +data_left (FILE* input_file) +{ + int retval = 1; + + if (feof(input_file)) retval = 0; + else if (input_file != stdin) + { + /* check if there is enough data left */ + struct stat statbuf; + size_t pos, data_left; + fstat (fileno(input_file), &statbuf); + pos = ftell(input_file); + data_left = (statbuf.st_size - pos); + + if (data_left > 0 && data_left < MINIMUM_ATTR_LENGTH) + { + if ( CRUFT_SKIP ) + { + /* look for specific flavor of cruft -- trailing "\r\n" */ + + if ( data_left == 2 ) + { + int c = fgetc( input_file ); + + if ( c < 0 ) /* this should never happen */ + { + fprintf( stderr, "ERROR: confused beyond all redemption.\n" ); + exit (1); + } + + ungetc( c, input_file ); + + if ( c == 0x0d ) /* test for "\r" part of "\r\n" */ + { + /* "trust" that next char is 0x0a and ignore this cruft */ + + if ( VERBOSE_ON ) + fprintf( stderr, "WARNING: garbage at end of file (ignored)\n" ); + + if ( DEBUG_ON ) + debug_print( "!!garbage at end of file (ignored)\n" ); + } + else + { + fprintf( stderr, "ERROR: garbage at end of file.\n" ); + } + } + else + { + fprintf (stderr, "ERROR: garbage at end of file.\n"); + } + } + else + { + fprintf (stderr, "ERROR: garbage at end of file.\n"); + } + + retval = 0; + } + } + return retval; +} + +int +parse_file (FILE* input_file, char* directory, + char *body_filename, char *body_pref, + int flags) +{ + uint32 d; + uint16 key; + Attr *attr = NULL; + File *file = NULL; + int rtf_size = 0, html_size = 0; + MessageBody body; + memset (&body, '\0', sizeof (MessageBody)); + + /* store the program options in our file global variables */ + g_flags = flags; + + /* check that this is in fact a TNEF file */ + d = geti32(input_file); + if (d != TNEF_SIGNATURE) + { + fprintf (stdout, "Seems not to be a TNEF file\n"); + return 1; + } + + /* Get the key */ + key = geti16(input_file); + debug_print ("TNEF Key: %hx\n", key); + + /* The rest of the file is a series of 'messages' and 'attachments' */ + while ( data_left( input_file ) ) + { + attr = read_object( input_file ); + + if ( attr == NULL ) break; + + /* This signals the beginning of a file */ + if (attr->name == attATTACHRENDDATA) + { + if (file) + { + file_write (file, directory); + file_free (file); + } + else + { + file = CHECKED_XCALLOC (File, 1); + } + } + + /* Add the data to our lists. */ + switch (attr->lvl_type) + { + case LVL_MESSAGE: + if (attr->name == attBODY) + { + body.text_body = get_text_data (attr); + } + else if (attr->name == attMAPIPROPS) + { + MAPI_Attr **mapi_attrs + = mapi_attr_read (attr->len, attr->buf); + if (mapi_attrs) + { + int i; + for (i = 0; mapi_attrs[i]; i++) + { + MAPI_Attr *a = mapi_attrs[i]; + + if (a->name == MAPI_BODY_HTML) + { + body.html_bodies = get_html_data (a); + html_size = a->num_values; + } + else if (a->name == MAPI_RTF_COMPRESSED) + { + body.rtf_bodies = get_rtf_data (a); + rtf_size = a->num_values; + } + } + /* cannot save attributes to file, since they + * are not attachment attributes */ + /* file_add_mapi_attrs (file, mapi_attrs); */ + mapi_attr_free_list (mapi_attrs); + XFREE (mapi_attrs); + } + } + break; + case LVL_ATTACHMENT: + file_add_attr (file, attr); + break; + default: + fprintf (stderr, "Invalid lvl type on attribute: %d\n", + attr->lvl_type); + return 1; + break; + } + attr_free (attr); + XFREE (attr); + } + + if (file) + { + file_write (file, directory); + file_free (file); + XFREE (file); + } + + /* Write the message body */ + if (flags & SAVEBODY) + { + int i = 0; + int all_flag = 0; + if (strcmp (body_pref, "all") == 0) + { + all_flag = 1; + body_pref = "rht"; + } + + for (; i < 3; i++) + { + File **files + = get_body_files (body_filename, body_pref[i], &body); + if (files) + { + int j = 0; + for (; files[j]; j++) + { + file_write(files[j], directory); + file_free (files[j]); + XFREE(files[j]); + } + XFREE(files); + if (!all_flag) break; + } + } + } + + if (body.text_body) + { + free_bodies(body.text_body, 1); + XFREE(body.text_body); + } + if (rtf_size > 0) + { + free_bodies(body.rtf_bodies, rtf_size); + XFREE(body.rtf_bodies); + } + if (html_size > 0) + { + free_bodies(body.html_bodies, html_size); + XFREE(body.html_bodies); + } + return 0; +} +``` diff --git a/tasks/csa159/pair_135749/task_prompt.md b/tasks/csa159/pair_135749/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..7d52e461b15325db31649518caa48b605b199438 --- /dev/null +++ b/tasks/csa159/pair_135749/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 + +- The prior rollout used a path-sensitive region and ProgramState design although the minimum sufficient evidence is the local syntactic relationship between each MAPI attribute case, its buffer consumer, and the required type predicate. +- Its generic memmove/memcpy compatibility set incorrectly accepted STRING, UNICODE_STRING, BINARY, and OBJECT for every byte consumer, missing the per-attribute requirements: STRING for long filename, MIME tag, and content ID; BINARY or OBJECT for attachment data; and BINARY for HTML and RTF dispatch. +- Process quality remained below threshold because the final validation deliberately loaded a nonexistent checker and was not recovered, despite successful compilation, differential scans, and code verification. + +### 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. +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Identify consumption of MAPI_Attr value storage as a string or byte buffer and determine the exact required type from the local attribute semantic: STRING for MAPI_ATTACH_LONG_FILENAME, MAPI_ATTACH_MIME_TAG, and MAPI_ATTACH_CONTENT_ID; BINARY or OBJECT for MAPI_ATTACH_DATA_OBJ; and BINARY for MAPI_BODY_HTML and MAPI_RTF_COMPRESSED. +- Report an unsafe operation when the required type predicate is absent from the local syntactic guard or dispatch condition protecting the relevant buffer access. +- Treat the patched forms as safe only when their exact per-attribute type predicates are present before the consumer or in the enclosing dispatch condition; do not treat an unconstrained or merely generally buffer-compatible type as sufficient. + +### Implementation constraints + +- Use a syntax-oriented CSA callback such as check::PreCall or an equivalent AST call inspection to examine generic consumers including strdup, strndup, memmove, and memcpy without relying on ProgramState constraint propagation. +- Relate the consumer to MAPI_Attr value expressions and the enclosing attribute-name case or dispatch condition using AST structure and local source relationships, not source line numbers, changed-function names, or patch anchors. +- Encode the documented project semantic types and attribute identifiers, with separate required-type sets for each attribute category rather than one sink-wide compatibility set. +- Emit diagnostics at the vulnerable consumer expression or its source buffer argument, and suppress diagnostics for non-MAPI buffers and for consumers protected by the exact required local predicate. +- Keep the checker project-general within the documented MAPI_Attr/MAPI_Value and generic consumer scope; do not depend on path-sensitive symbolic regions, dominance engines, or interprocedural fact propagation. + +### Validation checklist + +- Build the new checker and verify that the produced shared object loads under its registered checker name using the correct source-tree working directory and absolute source paths. +- Run the before-version scan and confirm five diagnostics: four in file_add_mapi_attrs and one in get_html_data, located at the five vulnerable consumers. +- Run the after-version scan and confirm zero diagnostics in the patched functions, including suppression from assert predicates and from the binary dispatch conditions. +- Check exact semantic refinement: STRING is required for long filename, MIME tag, and content ID; BINARY or OBJECT for attachment data; and BINARY for HTML and RTF paths. +- Verify no diagnostics are added for unrelated Attr or VarLenData consumers and that no warnings disappear outside the relevant patched functions. +- Repeat compile, before/after scan, report-location, and checker-load validation without intentionally invoking a nonexistent checker; record any failure and recover before final verification. + +### Avoid and forbidden regressions + +- Do not use a generic sink-only compatibility rule that treats all string, binary, and object types as interchangeable. +- Do not require fragile SymbolRegionValue provenance or ProgramState assumptions when local syntax establishes the required relation. +- Do not classify unknown or unconstrained types as safe merely because the operation is a byte-oriented consumer. +- Do not hardcode changed files, line numbers, patch anchors, commit identifiers, or patch-local variable names. +- Do not leave validation with an unrecovered invalid-checker or wrong-working-directory failure. diff --git a/tasks/csa159/pair_136251/checker_template.cpp b/tasks/csa159/pair_136251/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_136251/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_136251/config.json b/tasks/csa159/pair_136251/config.json new file mode 100644 index 0000000000000000000000000000000000000000..3d750b7ef11ffb8330c4ee297061e39dc0433fc8 --- /dev/null +++ b/tasks/csa159/pair_136251/config.json @@ -0,0 +1,36 @@ +{ + "project_id": "openexr_openexr", + "before_commit": "031199cd4fc062dd7bfe902c6552cf22f6bfbbdb", + "after_commit": "e79d2296496a50826a15c667bf92bdc5a05518b4", + "repo_path": "/workspace/repo/openexr/openexr", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/openexr_openexr/031199cd4fc062dd7bfe902c6552cf22f6bfbbdb/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/openexr_openexr/031199cd4fc062dd7bfe902c6552cf22f6bfbbdb/compile_commands.json", + "changed_files": [ + "OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp", + "OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp", + "OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp", + "OpenEXR/IlmImf/ImfDwaCompressor.cpp", + "OpenEXR/IlmImf/ImfFastHuf.cpp", + "OpenEXR/IlmImf/ImfHeader.cpp", + "OpenEXR/IlmImf/ImfHuf.cpp", + "OpenEXR/IlmImf/ImfInputFile.cpp", + "OpenEXR/IlmImf/ImfMisc.cpp", + "OpenEXR/IlmImf/ImfPizCompressor.cpp", + "OpenEXR/IlmImf/ImfRle.cpp", + "OpenEXR/IlmImf/ImfScanLineInputFile.cpp", + "OpenEXR/IlmImf/ImfTiledInputFile.cpp", + "OpenEXR/IlmImf/ImfTiledMisc.cpp", + "OpenEXR/IlmImfTest/testDeepTiledBasic.cpp", + "OpenEXR/IlmImfTest/testMultiPartApi.cpp", + "OpenEXR/IlmImfTest/testMultiPartThreading.cpp", + "OpenEXR/exrmakepreview/makePreview.cpp" + ], + "commit_message": "fix memory leaks and invalid memory accesses\n\nSigned-off-by: Peter Hillman ", + "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_136251/patch.diff b/tasks/csa159/pair_136251/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9088ff1df825fe54b06da805692191d0e4385e25 --- /dev/null +++ b/tasks/csa159/pair_136251/patch.diff @@ -0,0 +1,1071 @@ +diff --git a/OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp b/OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp +index 7e0dac09..fac7fc43 100644 +--- a/OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp ++++ b/OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp +@@ -44,6 +44,7 @@ + + #include + #include ++#include + OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER + + using std::vector; +@@ -179,7 +180,7 @@ CompositeDeepScanLine::Data::handleDeepFrameBuffer (DeepFrameBuffer& buf, + int start, + int end) + { +- int width=_dataWindow.size().x+1; ++ ptrdiff_t width=_dataWindow.size().x+1; + size_t pixelcount = width * (end-start+1); + pointers.resize(_channels.size()); + counts.resize(pixelcount); +diff --git a/OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp b/OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp +index 5371d7d5..4989fd7a 100644 +--- a/OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp ++++ b/OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp +@@ -914,8 +914,7 @@ void DeepScanLineInputFile::initialize(const Header& header) + } + catch (...) + { +- delete _data; +- _data=NULL; ++ // Don't delete _data here, leave that to caller + throw; + } + } +@@ -931,8 +930,15 @@ DeepScanLineInputFile::DeepScanLineInputFile(InputPartData* part) + _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); + _data->version = part->version; + +- initialize(part->header); +- ++ try ++ { ++ initialize(part->header); ++ } ++ catch(...) ++ { ++ delete _data; ++ throw; ++ } + _data->lineOffsets = part->chunkOffsets; + + _data->partNumber = part->partNumber; +@@ -944,7 +950,6 @@ DeepScanLineInputFile::DeepScanLineInputFile + : + _data (new Data (numThreads)) + { +- _data->_streamData = new InputStreamMutex(); + _data->_deleteStream = true; + OPENEXR_IMF_INTERNAL_NAMESPACE::IStream* is = 0; + +@@ -954,12 +959,29 @@ DeepScanLineInputFile::DeepScanLineInputFile + readMagicNumberAndVersionField(*is, _data->version); + // + // Backward compatibility to read multpart file. +- // ++ // multiPartInitialize will create _streamData + if (isMultiPart(_data->version)) + { + compatibilityInitialize(*is); + return; + } ++ } ++ catch (IEX_NAMESPACE::BaseExc &e) ++ { ++ if (is) delete is; ++ if (_data) delete _data; ++ ++ REPLACE_EXC (e, "Cannot read image file " ++ "\"" << fileName << "\". " << e.what()); ++ throw; ++ } ++ ++ // ++ // not multiPart - allocate stream data and intialise as normal ++ // ++ try ++ { ++ _data->_streamData = new InputStreamMutex(); + _data->_streamData->is = is; + _data->memoryMapped = is->isMemoryMapped(); + _data->header.readFrom (*_data->_streamData->is, _data->version); +@@ -975,7 +997,10 @@ DeepScanLineInputFile::DeepScanLineInputFile + catch (IEX_NAMESPACE::BaseExc &e) + { + if (is) delete is; +- if (_data && _data->_streamData) delete _data->_streamData; ++ if (_data && _data->_streamData) ++ { ++ delete _data->_streamData; ++ } + if (_data) delete _data; + + REPLACE_EXC (e, "Cannot read image file " +@@ -985,7 +1010,10 @@ DeepScanLineInputFile::DeepScanLineInputFile + catch (...) + { + if (is) delete is; +- if (_data && _data->_streamData) delete _data->_streamData; ++ if (_data && _data->_streamData) ++ { ++ delete _data->_streamData; ++ } + if (_data) delete _data; + + throw; +@@ -1009,7 +1037,18 @@ DeepScanLineInputFile::DeepScanLineInputFile + + _data->version =version; + +- initialize (header); ++ try ++ { ++ initialize (header); ++ } ++ catch (...) ++ { ++ if (_data && _data->_streamData) ++ { ++ delete _data->_streamData; ++ } ++ if (_data) delete _data; ++ } + + readLineOffsets (*_data->_streamData->is, + _data->lineOrder, +@@ -1041,8 +1080,9 @@ DeepScanLineInputFile::~DeepScanLineInputFile () + // + + if (_data->partNumber == -1 && _data->_streamData) ++ { + delete _data->_streamData; +- ++ } + delete _data; + } + } +diff --git a/OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp b/OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp +index 916717f7..38ea33cd 100644 +--- a/OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp ++++ b/OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp +@@ -283,7 +283,8 @@ DeepTiledInputFile::Data::Data (int numThreads): + multiPartBackwardSupport(false), + numThreads(numThreads), + memoryMapped(false), +- _streamData(NULL), ++ sampleCountTableComp(nullptr), ++ _streamData(nullptr), + _deleteStream(false) + { + // +@@ -308,6 +309,8 @@ DeepTiledInputFile::Data::~Data () + + for (size_t i = 0; i < slices.size(); i++) + delete slices[i]; ++ ++ delete sampleCountTableComp; + } + + +@@ -878,7 +881,15 @@ DeepTiledInputFile::DeepTiledInputFile (InputPartData* part) : + _data (new Data (part->numThreads)) + { + _data->_deleteStream=false; +- multiPartInitialize(part); ++ try ++ { ++ multiPartInitialize(part); ++ } ++ catch(...) ++ { ++ delete _data; ++ throw; ++ } + } + + +diff --git a/OpenEXR/IlmImf/ImfDwaCompressor.cpp b/OpenEXR/IlmImf/ImfDwaCompressor.cpp +index d029121d..872c8c7d 100644 +--- a/OpenEXR/IlmImf/ImfDwaCompressor.cpp ++++ b/OpenEXR/IlmImf/ImfDwaCompressor.cpp +@@ -266,8 +266,9 @@ struct DwaCompressor::Classifier + " (truncated rule)."); + + { +- char suffix[Name::SIZE]; +- memset (suffix, 0, Name::SIZE); ++ // maximum length of string plus one byte for terminating NULL ++ char suffix[Name::SIZE+1]; ++ memset (suffix, 0, Name::SIZE+1); + Xdr::read (ptr, std::min(size, Name::SIZE-1), suffix); + _suffix = std::string(suffix); + } +@@ -2419,7 +2420,7 @@ DwaCompressor::uncompress + unsigned short ruleSize = 0; + Xdr::read(dataPtr, ruleSize); + +- if (ruleSize < 0) ++ if (ruleSize < Xdr::size() ) + throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" + " (corrupt header file)."); + +@@ -2814,6 +2815,14 @@ DwaCompressor::uncompress + if (IMATH_NAMESPACE::modp (y, cd->ySampling) != 0) + continue; + ++ // ++ // sanity check for buffer data lying within range ++ // ++ if (cd->planarUncBufferEnd + dstScanlineSize - _planarUncBuffer[UNKNOWN] > _planarUncBufferSize[UNKNOWN] ) ++ { ++ throw Iex::InputExc("DWA data corrupt"); ++ } ++ + memcpy (rowPtrs[chan][row], + cd->planarUncBufferEnd, + dstScanlineSize); +diff --git a/OpenEXR/IlmImf/ImfFastHuf.cpp b/OpenEXR/IlmImf/ImfFastHuf.cpp +index 3e00bdd7..9ccf2e15 100644 +--- a/OpenEXR/IlmImf/ImfFastHuf.cpp ++++ b/OpenEXR/IlmImf/ImfFastHuf.cpp +@@ -256,14 +256,29 @@ FastHufDecoder::FastHufDecoder + int symbol = *i >> 6; + + if (mapping[codeLen] >= static_cast(_numSymbols)) ++ { ++ delete[] _idToSymbol; ++ _idToSymbol = NULL; + throw IEX_NAMESPACE::InputExc ("Huffman decode error " + "(Invalid symbol in header)."); +- ++ } + _idToSymbol[mapping[codeLen]] = symbol; + mapping[codeLen]++; + } + +- buildTables(base, offset); ++ // ++ // exceptions can be thrown whilst building tables. Delete ++ // _idToSynmbol before re-throwing to prevent memory leak ++ // ++ try ++ { ++ buildTables(base, offset); ++ }catch(...) ++ { ++ delete[] _idToSymbol; ++ _idToSymbol = NULL; ++ throw; ++ } + } + + +diff --git a/OpenEXR/IlmImf/ImfHeader.cpp b/OpenEXR/IlmImf/ImfHeader.cpp +index e29ec421..6d63cd2e 100644 +--- a/OpenEXR/IlmImf/ImfHeader.cpp ++++ b/OpenEXR/IlmImf/ImfHeader.cpp +@@ -873,6 +873,7 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const + } + + const std::string & part_type=hasType() ? type() : ""; ++ + + if(part_type!="" && !isSupportedType(part_type)) + { +@@ -882,6 +883,7 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const + return; + } + ++ bool isDeep = isDeepData(part_type); + + // + // If the file is tiled, verify that the tile description has reasonable +@@ -902,7 +904,7 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const + + const TileDescription &tileDesc = tileDescription(); + +- if (tileDesc.xSize <= 0 || tileDesc.ySize <= 0) ++ if (tileDesc.xSize <= 0 || tileDesc.ySize <= 0 || tileDesc.xSize > INT_MAX || tileDesc.ySize > INT_MAX ) + throw IEX_NAMESPACE::ArgExc ("Invalid tile size in image header."); + + if (maxTileWidth > 0 && +@@ -953,7 +955,8 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const + if (!isValidCompression (this->compression())) + throw IEX_NAMESPACE::ArgExc ("Unknown compression type in image header."); + +- if(isDeepData(part_type)) ++ ++ if( isDeep ) + { + if (!isValidDeepCompression (this->compression())) + throw IEX_NAMESPACE::ArgExc ("Compression type in header not valid for deep data"); +@@ -965,6 +968,8 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const + // If the file is tiled then for each channel, the type must be one of the + // predefined values, and the x and y sampling must both be 1. + // ++ // x and y sampling must currently also be 1 for deep scanline images ++ // + // If the file is not tiled then for each channel, the type must be one + // of the predefined values, the x and y coordinates of the data window's + // upper left corner must be divisible by the x and y subsampling factors, +@@ -974,7 +979,7 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const + + const ChannelList &channels = this->channels(); + +- if (isTiled) ++ if (isTiled || isDeep) + { + for (ChannelList::ConstIterator i = channels.begin(); + i != channels.end(); +diff --git a/OpenEXR/IlmImf/ImfHuf.cpp b/OpenEXR/IlmImf/ImfHuf.cpp +index 97909a5b..fabb5faa 100644 +--- a/OpenEXR/IlmImf/ImfHuf.cpp ++++ b/OpenEXR/IlmImf/ImfHuf.cpp +@@ -1052,7 +1052,10 @@ hufUncompress (const char compressed[], + unsigned short raw[], + int nRaw) + { +- if (nCompressed == 0) ++ // ++ // need at least 20 bytes for header ++ // ++ if (nCompressed < 20 ) + { + if (nRaw != 0) + notEnoughData(); +@@ -1070,6 +1073,12 @@ hufUncompress (const char compressed[], + + const char *ptr = compressed + 20; + ++ if ( ptr + (nBits+7 )/8 > compressed+nCompressed) ++ { ++ notEnoughData(); ++ return; ++ } ++ + // + // Fast decoder needs at least 2x64-bits of compressed data, and + // needs to be run-able on this platform. Otherwise, fall back +diff --git a/OpenEXR/IlmImf/ImfInputFile.cpp b/OpenEXR/IlmImf/ImfInputFile.cpp +index 8661c104..74c1a353 100644 +--- a/OpenEXR/IlmImf/ImfInputFile.cpp ++++ b/OpenEXR/IlmImf/ImfInputFile.cpp +@@ -475,7 +475,15 @@ InputFile::InputFile (InputPartData* part) : + _data (new Data (part->numThreads)) + { + _data->_deleteStream=false; +- multiPartInitialize (part); ++ try ++ { ++ multiPartInitialize (part); ++ } ++ catch(...) ++ { ++ delete _data; ++ throw; ++ } + } + + +diff --git a/OpenEXR/IlmImf/ImfMisc.cpp b/OpenEXR/IlmImf/ImfMisc.cpp +index 27755432..d0b6fb26 100644 +--- a/OpenEXR/IlmImf/ImfMisc.cpp ++++ b/OpenEXR/IlmImf/ImfMisc.cpp +@@ -114,9 +114,9 @@ bytesPerLineTable (const Header &header, + c != channels.end(); + ++c) + { +- int nBytes = pixelTypeSize (c.channel().type) * +- (dataWindow.max.x - dataWindow.min.x + 1) / +- c.channel().xSampling; ++ size_t nBytes = size_t(pixelTypeSize (c.channel().type)) * ++ size_t(dataWindow.max.x - dataWindow.min.x + 1) / ++ size_t(c.channel().xSampling); + + for (int y = dataWindow.min.y, i = 0; y <= dataWindow.max.y; ++y, ++i) + if (modp (y, c.channel().ySampling) == 0) +@@ -269,6 +269,7 @@ defaultFormat (Compressor * compressor) + } + + ++//obsolete + int + numLinesInBuffer (Compressor * compressor) + { +@@ -1842,6 +1843,39 @@ usesLongNames (const Header &header) + return false; + } + ++namespace ++{ ++// for a given compression type, return the number of scanlines ++// compressed into a single chunk ++// TODO add to API and move to ImfCompressor.cpp ++int ++numLinesInBuffer(Compression comp) ++{ ++ switch(comp) ++ { ++ case NO_COMPRESSION : ++ case RLE_COMPRESSION: ++ case ZIPS_COMPRESSION: ++ return 1; ++ case ZIP_COMPRESSION: ++ return 16; ++ case PIZ_COMPRESSION: ++ return 32; ++ case PXR24_COMPRESSION: ++ return 16; ++ case B44_COMPRESSION: ++ case B44A_COMPRESSION: ++ case DWAA_COMPRESSION: ++ return 32; ++ case DWAB_COMPRESSION: ++ return 256; ++ ++ default: ++ throw IEX_NAMESPACE::ArgExc ("Unknown compression type"); ++ } ++} ++} ++ + int + getScanlineChunkOffsetTableSize(const Header& header) + { +@@ -1851,17 +1885,11 @@ getScanlineChunkOffsetTableSize(const Header& header) + size_t maxBytesPerLine = bytesPerLineTable (header, + bytesPerLine); + +- Compressor* compressor = newCompressor(header.compression(), +- maxBytesPerLine, +- header); +- +- int linesInBuffer = numLinesInBuffer (compressor); ++ int linesInBuffer = numLinesInBuffer ( header.compression() ); + + int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y + + linesInBuffer) / linesInBuffer; + +- delete compressor; +- + return lineOffsetSize; + } + +diff --git a/OpenEXR/IlmImf/ImfPizCompressor.cpp b/OpenEXR/IlmImf/ImfPizCompressor.cpp +index 7a49d42d..edc141ad 100644 +--- a/OpenEXR/IlmImf/ImfPizCompressor.cpp ++++ b/OpenEXR/IlmImf/ImfPizCompressor.cpp +@@ -492,7 +492,9 @@ PizCompressor::uncompress (const char *inPtr, + // This is the cunompress function which is used by both the tiled and + // scanline decompression routines. + // +- ++ ++ const char* inputEnd=inPtr+inSize; ++ + // + // Special case - empty input buffer + // +@@ -503,6 +505,7 @@ PizCompressor::uncompress (const char *inPtr, + return 0; + } + ++ + // + // Determine the layout of the compressed pixel data + // +@@ -549,6 +552,12 @@ PizCompressor::uncompress (const char *inPtr, + AutoArray bitmap; + memset (bitmap, 0, sizeof (unsigned char) * BITMAP_SIZE); + ++ ++ if(inPtr + sizeof(unsigned short)*2 > inputEnd) ++ { ++ throw InputExc ("PIZ compressed data too short"); ++ } ++ + Xdr::read (inPtr, minNonZero); + Xdr::read (inPtr, maxNonZero); + +@@ -560,8 +569,14 @@ PizCompressor::uncompress (const char *inPtr, + + if (minNonZero <= maxNonZero) + { +- Xdr::read (inPtr, (char *) &bitmap[0] + minNonZero, +- maxNonZero - minNonZero + 1); ++ size_t bytesToRead = maxNonZero - minNonZero + 1; ++ if(inPtr + bytesToRead > inputEnd) ++ { ++ throw InputExc ("PIZ compressed data too short"); ++ } ++ ++Xdr::read (inPtr, (char *) &bitmap[0] + minNonZero, ++ bytesToRead); + } + + AutoArray lut; +@@ -570,6 +585,11 @@ PizCompressor::uncompress (const char *inPtr, + // + // Huffman decoding + // ++ if(inPtr + sizeof(int)> inputEnd) ++ { ++ throw InputExc ("PIZ compressed data too short"); ++ } ++ + + int length; + Xdr::read (inPtr, length); +diff --git a/OpenEXR/IlmImf/ImfRle.cpp b/OpenEXR/IlmImf/ImfRle.cpp +index 7be6ac44..f6992fa5 100644 +--- a/OpenEXR/IlmImf/ImfRle.cpp ++++ b/OpenEXR/IlmImf/ImfRle.cpp +@@ -129,6 +129,11 @@ rleUncompress (int inLength, int maxLength, const signed char in[], char out[]) + if (0 > (maxLength -= count)) + return 0; + ++ // check the input buffer is big enough to contain ++ // 'count' bytes of remaining data ++ if (inLength < 0) ++ return 0; ++ + memcpy(out, in, count); + out += count; + in += count; +diff --git a/OpenEXR/IlmImf/ImfScanLineInputFile.cpp b/OpenEXR/IlmImf/ImfScanLineInputFile.cpp +index 9d7404f3..2a559654 100644 +--- a/OpenEXR/IlmImf/ImfScanLineInputFile.cpp ++++ b/OpenEXR/IlmImf/ImfScanLineInputFile.cpp +@@ -1097,8 +1097,6 @@ newLineBufferTask (TaskGroup *group, + + void ScanLineInputFile::initialize(const Header& header) + { +- try +- { + _data->header = header; + + _data->lineOrder = _data->header.lineOrder(); +@@ -1112,6 +1110,12 @@ void ScanLineInputFile::initialize(const Header& header) + + size_t maxBytesPerLine = bytesPerLineTable (_data->header, + _data->bytesPerLine); ++ ++ if(maxBytesPerLine > INT_MAX) ++ { ++ throw IEX_NAMESPACE::InputExc("maximum bytes per scanline exceeds maximum permissible size"); ++ } ++ + + for (size_t i = 0; i < _data->lineBuffers.size(); i++) + { +@@ -1143,13 +1147,6 @@ void ScanLineInputFile::initialize(const Header& header) + _data->linesInBuffer) / _data->linesInBuffer; + + _data->lineOffsets.resize (lineOffsetSize); +- } +- catch (...) +- { +- delete _data; +- _data=NULL; +- throw; +- } + } + + +@@ -1164,8 +1161,27 @@ ScanLineInputFile::ScanLineInputFile(InputPartData* part) + + _data->version = part->version; + +- initialize(part->header); +- ++ try ++ { ++ initialize(part->header); ++ } ++ catch(...) ++ { ++ if (!_data->memoryMapped) ++ { ++ for (size_t i = 0; i < _data->lineBuffers.size(); i++) ++ { ++ if( _data->lineBuffers[i] ) ++ { ++ EXRFreeAligned(_data->lineBuffers[i]->buffer); ++ _data->lineBuffers[i]->buffer=nullptr; ++ } ++ } ++ } ++ ++ delete _data; ++ throw; ++ } + _data->lineOffsets = part->chunkOffsets; + + _data->partNumber = part->partNumber; +@@ -1188,19 +1204,43 @@ ScanLineInputFile::ScanLineInputFile + _streamData->is = is; + _data->memoryMapped = is->isMemoryMapped(); + +- initialize(header); +- +- // +- // (TODO) this is nasty - we need a better way of working out what type of file has been used. +- // in any case I believe this constructor only gets used with single part files +- // and 'version' currently only tracks multipart state, so setting to 0 (not multipart) works for us +- // +- +- _data->version=0; +- readLineOffsets (*_streamData->is, +- _data->lineOrder, +- _data->lineOffsets, +- _data->fileIsComplete); ++ try ++ { ++ ++ initialize(header); ++ ++ // ++ // (TODO) this is nasty - we need a better way of working out what type of file has been used. ++ // in any case I believe this constructor only gets used with single part files ++ // and 'version' currently only tracks multipart state, so setting to 0 (not multipart) works for us ++ // ++ ++ _data->version=0; ++ readLineOffsets (*_streamData->is, ++ _data->lineOrder, ++ _data->lineOffsets, ++ _data->fileIsComplete); ++ } ++ catch(...) ++ { ++ if(_data) ++ { ++ if (!_data->memoryMapped) ++ { ++ for (size_t i = 0; i < _data->lineBuffers.size(); i++) ++ { ++ if( _data->lineBuffers[i] ) ++ { ++ EXRFreeAligned(_data->lineBuffers[i]->buffer); ++ _data->lineBuffers[i]->buffer=nullptr; ++ } ++ } ++ } ++ } ++ delete _streamData; ++ delete _data; ++ throw; ++ } + } + + +@@ -1422,6 +1462,14 @@ ScanLineInputFile::setFrameBuffer (const FrameBuffer &frameBuffer) + // not possible. + break; + } ++ ++ // ++ // optimization mode cannot currently skip subsampled channels ++ // ++ if (i.channel().xSampling!=1 || i.channel().ySampling!=1) ++ { ++ optimizationPossible = false; ++ } + ++i; + } + +diff --git a/OpenEXR/IlmImf/ImfTiledInputFile.cpp b/OpenEXR/IlmImf/ImfTiledInputFile.cpp +index bda7bad5..e6936d53 100644 +--- a/OpenEXR/IlmImf/ImfTiledInputFile.cpp ++++ b/OpenEXR/IlmImf/ImfTiledInputFile.cpp +@@ -703,61 +703,56 @@ TiledInputFile::TiledInputFile (const char fileName[], int numThreads): + IStream* is = 0; + try + { +- is = new StdIFStream (fileName); +- readMagicNumberAndVersionField(*is, _data->version); +- +- // +- // Backward compatibility to read multpart file. +- // +- if (isMultiPart(_data->version)) +- { +- compatibilityInitialize(*is); +- return; +- } +- +- _data->_streamData = new InputStreamMutex(); +- _data->_streamData->is = is; +- _data->header.readFrom (*_data->_streamData->is, _data->version); +- initialize(); +- //read tile offsets - we are not multipart or deep +- _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); +- _data->_streamData->currentPosition = _data->_streamData->is->tellg(); +- } +- catch (IEX_NAMESPACE::BaseExc &e) +- { +- if (_data->_streamData != 0) ++ try + { +- if (_data->_streamData->is != 0) ++ is = new StdIFStream (fileName); ++ readMagicNumberAndVersionField(*is, _data->version); ++ ++ // ++ // Backward compatibility to read multpart file. ++ // ++ if (isMultiPart(_data->version)) + { +- delete _data->_streamData->is; +- _data->_streamData->is = is = 0; ++ compatibilityInitialize(*is); ++ return; + } + +- delete _data->_streamData; ++ _data->_streamData = new InputStreamMutex(); ++ _data->_streamData->is = is; ++ _data->header.readFrom (*_data->_streamData->is, _data->version); ++ initialize(); ++ //read tile offsets - we are not multipart or deep ++ _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); ++ _data->_streamData->currentPosition = _data->_streamData->is->tellg(); ++ } ++ catch (IEX_NAMESPACE::BaseExc &e) ++ { ++ REPLACE_EXC (e, "Cannot open image file " ++ "\"" << fileName << "\". " << e.what()); ++ throw; + } +- +- if (is != 0) +- delete is; +- +- REPLACE_EXC (e, "Cannot open image file " +- "\"" << fileName << "\". " << e.what()); +- throw; + } + catch (...) + { +- if ( _data->_streamData != 0) ++ if (!_data->memoryMapped) + { +- if ( _data->_streamData->is != 0) ++ for (size_t i = 0; i < _data->tileBuffers.size(); i++) + { +- delete _data->_streamData->is; +- _data->_streamData->is = is = 0; ++ if(_data->tileBuffers[i]) ++ { ++ delete [] _data->tileBuffers[i]->buffer; ++ } + } +- ++ } ++ if ( _data->_streamData != 0) ++ { ++ delete _data->_streamData->is; ++ _data->_streamData->is = is = 0; + delete _data->_streamData; + } + +- if (is != 0) +- delete is; ++ delete is; ++ delete _data; + throw; + } + } +@@ -776,38 +771,45 @@ TiledInputFile::TiledInputFile (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream &is, int + + try + { +- readMagicNumberAndVersionField(is, _data->version); +- +- // +- // Backward compatibility to read multpart file. +- // +- if (isMultiPart(_data->version)) ++ try + { +- compatibilityInitialize(is); +- return; +- } ++ readMagicNumberAndVersionField(is, _data->version); + +- streamDataCreated = true; +- _data->_streamData = new InputStreamMutex(); +- _data->_streamData->is = &is; +- _data->header.readFrom (*_data->_streamData->is, _data->version); +- initialize(); +- // file is guaranteed to be single part, regular image +- _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); +- _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); +- _data->_streamData->currentPosition = _data->_streamData->is->tellg(); +- } +- catch (IEX_NAMESPACE::BaseExc &e) +- { +- if (streamDataCreated) delete _data->_streamData; +- delete _data; ++ // ++ // Backward compatibility to read multpart file. ++ // ++ if (isMultiPart(_data->version)) ++ { ++ compatibilityInitialize(is); ++ return; ++ } + +- REPLACE_EXC (e, "Cannot open image file " +- "\"" << is.fileName() << "\". " << e.what()); +- throw; ++ streamDataCreated = true; ++ _data->_streamData = new InputStreamMutex(); ++ _data->_streamData->is = &is; ++ _data->header.readFrom (*_data->_streamData->is, _data->version); ++ initialize(); ++ // file is guaranteed to be single part, regular image ++ _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); ++ _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); ++ _data->_streamData->currentPosition = _data->_streamData->is->tellg(); ++ } ++ catch (IEX_NAMESPACE::BaseExc &e) ++ { ++ REPLACE_EXC (e, "Cannot open image file " ++ "\"" << is.fileName() << "\". " << e.what()); ++ throw; ++ } + } + catch (...) + { ++ if (!_data->memoryMapped) ++ { ++ for (size_t i = 0; i < _data->tileBuffers.size(); i++) ++ { ++ delete [] _data->tileBuffers[i]->buffer; ++ } ++ } + if (streamDataCreated) delete _data->_streamData; + delete _data; + throw; +@@ -831,13 +833,29 @@ TiledInputFile::TiledInputFile (const Header &header, + // we have somehow got the header. + // + +- _data->_streamData->is = is; +- _data->header = header; +- _data->version = version; +- initialize(); +- _data->tileOffsets.readFrom (*(_data->_streamData->is),_data->fileIsComplete,false,false); +- _data->memoryMapped = is->isMemoryMapped(); +- _data->_streamData->currentPosition = _data->_streamData->is->tellg(); ++ try ++ { ++ _data->_streamData->is = is; ++ _data->header = header; ++ _data->version = version; ++ initialize(); ++ _data->tileOffsets.readFrom (*(_data->_streamData->is),_data->fileIsComplete,false,false); ++ _data->memoryMapped = is->isMemoryMapped(); ++ _data->_streamData->currentPosition = _data->_streamData->is->tellg(); ++ } ++ catch(...) ++ { ++ if (!_data->memoryMapped) ++ { ++ for (size_t i = 0; i < _data->tileBuffers.size(); i++) ++ { ++ delete [] _data->tileBuffers[i]->buffer; ++ } ++ } ++ delete _data->_streamData; ++ delete _data; ++ throw; ++ } + } + + +@@ -845,7 +863,15 @@ TiledInputFile::TiledInputFile (InputPartData* part) + { + _data = new Data (part->numThreads); + _data->_deleteStream=false; +- multiPartInitialize(part); ++ try ++ { ++ multiPartInitialize(part); ++ } ++ catch(...) ++ { ++ if (_data) delete _data; ++ throw; ++ } + } + + +diff --git a/OpenEXR/IlmImf/ImfTiledMisc.cpp b/OpenEXR/IlmImf/ImfTiledMisc.cpp +index d262f734..8552ada2 100644 +--- a/OpenEXR/IlmImf/ImfTiledMisc.cpp ++++ b/OpenEXR/IlmImf/ImfTiledMisc.cpp +@@ -363,40 +363,51 @@ getTiledChunkOffsetTableSize(const Header& header) + // + Int64 lineOffsetSize = 0; + const TileDescription &desc = header.tileDescription(); +- switch (desc.mode) ++ try + { +- case ONE_LEVEL: +- case MIPMAP_LEVELS: +- for (int i = 0; i < numXLevels; i++) +- { +- lineOffsetSize += static_cast(numXTiles[i]) * static_cast(numYTiles[i]); +- if ( lineOffsetSize > static_cast(std::numeric_limits::max()) ) ++ switch (desc.mode) ++ { ++ case ONE_LEVEL: ++ case MIPMAP_LEVELS: ++ for (int i = 0; i < numXLevels; i++) + { +- throw IEX_NAMESPACE::LogicExc("Maximum number of tiles exceeded"); ++ lineOffsetSize += static_cast(numXTiles[i]) * static_cast(numYTiles[i]); ++ if ( lineOffsetSize > static_cast(std::numeric_limits::max()) ) ++ { ++ throw IEX_NAMESPACE::LogicExc("Maximum number of tiles exceeded"); ++ } + } +- } +- break; +- case RIPMAP_LEVELS: +- for (int i = 0; i < numXLevels; i++) +- { +- for (int j = 0; j < numYLevels; j++) ++ break; ++ case RIPMAP_LEVELS: ++ for (int i = 0; i < numXLevels; i++) + { +- lineOffsetSize += static_cast(numXTiles[i]) * static_cast(numYTiles[j]); +- if ( lineOffsetSize > static_cast(std::numeric_limits::max()) ) +- { +- throw IEX_NAMESPACE::LogicExc("Maximum number of tiles exceeded"); +- } ++ for (int j = 0; j < numYLevels; j++) ++ { ++ lineOffsetSize += static_cast(numXTiles[i]) * static_cast(numYTiles[j]); ++ if ( lineOffsetSize > static_cast(std::numeric_limits::max()) ) ++ { ++ throw IEX_NAMESPACE::LogicExc("Maximum number of tiles exceeded"); ++ } ++ } + } +- } +- break; +- case NUM_LEVELMODES : +- throw IEX_NAMESPACE::LogicExc("Bad level mode getting chunk offset table size"); ++ break; ++ case NUM_LEVELMODES : ++ throw IEX_NAMESPACE::LogicExc("Bad level mode getting chunk offset table size"); ++ } ++ delete[] numXTiles; ++ delete[] numYTiles; ++ ++ return static_cast(lineOffsetSize); ++ + } ++ catch(...) ++ { ++ delete[] numXTiles; ++ delete[] numYTiles; + +- delete[] numXTiles; +- delete[] numYTiles; ++ throw; ++ } + +- return static_cast(lineOffsetSize); + } + + +diff --git a/OpenEXR/IlmImfTest/testDeepTiledBasic.cpp b/OpenEXR/IlmImfTest/testDeepTiledBasic.cpp +index e81b56a7..9fab3553 100644 +--- a/OpenEXR/IlmImfTest/testDeepTiledBasic.cpp ++++ b/OpenEXR/IlmImfTest/testDeepTiledBasic.cpp +@@ -754,15 +754,12 @@ void readFile (int channelCount, + { + for (int k = 0; k < channelCount; k++) + { +- if( !randomChannels || read_channel[k]==1) +- { + if (channelTypes[k] == 0) + delete[] (unsigned int*) data[k][i][j]; + if (channelTypes[k] == 1) + delete[] (half*) data[k][i][j]; + if (channelTypes[k] == 2) + delete[] (float*) data[k][i][j]; +- } + } + for( int f = 0 ; f < fillChannels ; ++f ) + { +diff --git a/OpenEXR/IlmImfTest/testMultiPartApi.cpp b/OpenEXR/IlmImfTest/testMultiPartApi.cpp +index c6265b88..c0bfb688 100644 +--- a/OpenEXR/IlmImfTest/testMultiPartApi.cpp ++++ b/OpenEXR/IlmImfTest/testMultiPartApi.cpp +@@ -463,6 +463,21 @@ generateRandomFile (int partCount, const std::string & fn) + } + } + ++ for (size_t i = 0 ; i < parts.size() ; ++i ) ++ { ++ int partType = partTypes[i]; ++ ++ if (partType == 0) ++ { ++ delete (OutputPart*) parts[i]; ++ } ++ else ++ { ++ delete (TiledOutputPart*) parts[i]; ++ } ++ ++ } ++ + delete[] tiledHalfData; + delete[] tiledUintData; + delete[] tiledFloatData; +diff --git a/OpenEXR/IlmImfTest/testMultiPartThreading.cpp b/OpenEXR/IlmImfTest/testMultiPartThreading.cpp +index 68eb8fa9..c4e05704 100644 +--- a/OpenEXR/IlmImfTest/testMultiPartThreading.cpp ++++ b/OpenEXR/IlmImfTest/testMultiPartThreading.cpp +@@ -625,6 +625,18 @@ generateRandomFile (int partCount, const std::string & fn) + } + } + ++ for (int i = 0; i < partCount; i++) ++ { ++ if (partTypes[i] == 0) ++ { ++ delete (OutputPart*) parts[i]; ++ } ++ else ++ { ++ delete (TiledOutputPart*) parts[i]; ++ } ++ } ++ + delete threadPool; + + delete[] tiledHalfData; +diff --git a/OpenEXR/exrmakepreview/makePreview.cpp b/OpenEXR/exrmakepreview/makePreview.cpp +index e2d08798..28205aa0 100644 +--- a/OpenEXR/exrmakepreview/makePreview.cpp ++++ b/OpenEXR/exrmakepreview/makePreview.cpp +@@ -120,8 +120,8 @@ generatePreview (const char inFileName[], + previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1); + previewPixels.resizeErase (previewHeight, previewWidth); + +- float fx = (previewWidth > 1)? (float (w - 1) / (previewWidth - 1)): 1; +- float fy = (previewHeight > 1)? (float (h - 1) / (previewHeight - 1)): 1; ++ double fx = (previewWidth > 1)? (double (w - 1) / (previewWidth - 1)): 1; ++ double fy = (previewHeight > 1)? (double (h - 1) / (previewHeight - 1)): 1; + float m = Math::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f)); + + for (int y = 0; y < previewHeight; ++y) \ No newline at end of file diff --git a/tasks/csa159/pair_136251/post_functions.txt b/tasks/csa159/pair_136251/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..86691d7f20e026f8a1f16942fb5fc12640654b14 --- /dev/null +++ b/tasks/csa159/pair_136251/post_functions.txt @@ -0,0 +1,3380 @@ +### File: OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp +```c +void +CompositeDeepScanLine::Data::handleDeepFrameBuffer (DeepFrameBuffer& buf, + std::vector< unsigned int > & counts, + vector< std::vector< float* > > & pointers, + const Header& header, + int start, + int end) +{ + ptrdiff_t width=_dataWindow.size().x+1; + size_t pixelcount = width * (end-start+1); + pointers.resize(_channels.size()); + counts.resize(pixelcount); + buf.insertSampleCountSlice (Slice (OPENEXR_IMF_INTERNAL_NAMESPACE::UINT, + (char *) (&counts[0]-_dataWindow.min.x-start*width), + sizeof(unsigned int), + sizeof(unsigned int)*width)); + + pointers[0].resize(pixelcount); + buf.insert ("Z", DeepSlice (OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT, + (char *)(&pointers[0][0]-_dataWindow.min.x-start*width), + sizeof(float *), + sizeof(float *)*width, + sizeof(float) )); + + if(_zback) + { + pointers[1].resize(pixelcount); + buf.insert ("ZBack", DeepSlice (OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT, + (char *)(&pointers[1][0]-_dataWindow.min.x-start*width), + sizeof(float *), + sizeof(float *)*width, + sizeof(float) )); + } + + pointers[2].resize(pixelcount); + buf.insert ("A", DeepSlice (OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT, + (char *)(&pointers[2][0]-_dataWindow.min.x-start*width), + sizeof(float *), + sizeof(float *)*width, + sizeof(float) )); + + + size_t i =0; + for(FrameBuffer::ConstIterator qt = _outputFrameBuffer.begin(); + qt != _outputFrameBuffer.end(); + qt++) + { + int channel_in_source = _bufferMap[i]; + if(channel_in_source>2) + { + // not dealt with yet (0,1,2 previously inserted) + pointers[channel_in_source].resize(pixelcount); + buf.insert (qt.name(), + DeepSlice (OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT, + (char *)(&pointers[channel_in_source][0]-_dataWindow.min.x-start*width), + sizeof(float *), + sizeof(float *)*width, + sizeof(float) )); + } + + i++; + } + +} +``` + +### File: OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp +```c +void DeepScanLineInputFile::initialize(const Header& header) +{ + try + { + if (header.type() != DEEPSCANLINE) + throw IEX_NAMESPACE::ArgExc("Can't build a DeepScanLineInputFile from " + "a type-mismatched part."); + + if(header.version()!=1) + { + THROW(IEX_NAMESPACE::ArgExc, "Version " << header.version() << " not supported for deepscanline images in this version of the library"); + } + + _data->header = header; + + _data->lineOrder = _data->header.lineOrder(); + + const Box2i &dataWindow = _data->header.dataWindow(); + + _data->minX = dataWindow.min.x; + _data->maxX = dataWindow.max.x; + _data->minY = dataWindow.min.y; + _data->maxY = dataWindow.max.y; + + _data->sampleCount.resizeErase(_data->maxY - _data->minY + 1, + _data->maxX - _data->minX + 1); + _data->lineSampleCount.resizeErase(_data->maxY - _data->minY + 1); + + Compressor* compressor = newCompressor(_data->header.compression(), + 0, + _data->header); + + _data->linesInBuffer = numLinesInBuffer (compressor); + + delete compressor; + + _data->nextLineBufferMinY = _data->minY - 1; + + int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y + + _data->linesInBuffer) / _data->linesInBuffer; + + _data->lineOffsets.resize (lineOffsetSize); + + for (size_t i = 0; i < _data->lineBuffers.size(); i++) + _data->lineBuffers[i] = new LineBuffer (); + + _data->gotSampleCount.resizeErase(_data->maxY - _data->minY + 1); + for (int i = 0; i < _data->maxY - _data->minY + 1; i++) + _data->gotSampleCount[i] = false; + + _data->maxSampleCountTableSize = min(_data->linesInBuffer, _data->maxY - _data->minY + 1) * + (_data->maxX - _data->minX + 1) * + sizeof(unsigned int); + + _data->sampleCountTableBuffer.resizeErase(_data->maxSampleCountTableSize); + + _data->sampleCountTableComp = newCompressor(_data->header.compression(), + _data->maxSampleCountTableSize, + _data->header); + + _data->bytesPerLine.resize (_data->maxY - _data->minY + 1); + + const ChannelList & c=header.channels(); + + _data->combinedSampleSize=0; + for(ChannelList::ConstIterator i=c.begin();i!=c.end();i++) + { + switch(i.channel().type) + { + case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF : + _data->combinedSampleSize+=Xdr::size(); + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT : + _data->combinedSampleSize+=Xdr::size(); + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT : + _data->combinedSampleSize+=Xdr::size(); + break; + default : + THROW(IEX_NAMESPACE::ArgExc, "Bad type for channel " << i.name() << " initializing deepscanline reader"); + + } + } + + } + catch (...) + { + // Don't delete _data here, leave that to caller + throw; + } +} +``` + +### File: OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2011, Industrial Light & Magic, a division of Lucas +// Digital Ltd. LLC +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Industrial Light & Magic nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + +//----------------------------------------------------------------------------- +// +// class DeepTiledInputFile +// +//----------------------------------------------------------------------------- + +#include +#include +#include +#include +#include +#include +#include +#include "ImathBox.h" +#include +#include +#include +#include +#include +#include +#include +#include "IlmThreadPool.h" +#include "IlmThreadSemaphore.h" +#include "IlmThreadMutex.h" +#include "ImfInputStreamMutex.h" +#include "ImfInputPartData.h" +#include "ImathVec.h" +#include "Iex.h" +#include +#include +#include +#include +#include + +#include "ImfNamespace.h" + +OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER + +using IMATH_NAMESPACE::Box2i; +using IMATH_NAMESPACE::V2i; +using std::string; +using std::vector; +using std::min; +using std::max; +using ILMTHREAD_NAMESPACE::Mutex; +using ILMTHREAD_NAMESPACE::Lock; +using ILMTHREAD_NAMESPACE::Semaphore; +using ILMTHREAD_NAMESPACE::Task; +using ILMTHREAD_NAMESPACE::TaskGroup; +using ILMTHREAD_NAMESPACE::ThreadPool; + +namespace { + +struct TInSliceInfo +{ + PixelType typeInFrameBuffer; + PixelType typeInFile; + char* pointerArrayBase; + size_t xStride; + size_t yStride; + ptrdiff_t sampleStride; + bool fill; + bool skip; + double fillValue; + int xTileCoords; + int yTileCoords; + + TInSliceInfo (PixelType typeInFrameBuffer = HALF, + char * base = NULL, + PixelType typeInFile = HALF, + size_t xStride = 0, + size_t yStride = 0, + ptrdiff_t sampleStride = 0, + bool fill = false, + bool skip = false, + double fillValue = 0.0, + int xTileCoords = 0, + int yTileCoords = 0); +}; + + +TInSliceInfo::TInSliceInfo (PixelType tifb, + char * b, + PixelType tifl, + size_t xs, size_t ys, + ptrdiff_t spst, + bool f, bool s, + double fv, + int xtc, + int ytc) +: + typeInFrameBuffer (tifb), + typeInFile (tifl), + pointerArrayBase (b), + xStride (xs), + yStride (ys), + sampleStride (spst), + fill (f), + skip (s), + fillValue (fv), + xTileCoords (xtc), + yTileCoords (ytc) +{ + // empty +} + + +struct TileBuffer +{ + Array2D sampleCount; + const char * uncompressedData; + char * buffer; + Int64 dataSize; + Int64 uncompressedDataSize; + Compressor * compressor; + Compressor::Format format; + int dx; + int dy; + int lx; + int ly; + bool hasException; + string exception; + + TileBuffer (); + ~TileBuffer (); + + inline void wait () {_sem.wait();} + inline void post () {_sem.post();} + + protected: + + Semaphore _sem; +}; + + +TileBuffer::TileBuffer (): + uncompressedData (0), + buffer (0), + dataSize (0), + compressor (0), + format (defaultFormat (compressor)), + dx (-1), + dy (-1), + lx (-1), + ly (-1), + hasException (false), + exception (), + _sem (1) +{ + // empty +} + + +TileBuffer::~TileBuffer () +{ + delete compressor; +} + +} // namespace + + +class MultiPartInputFile; + + +// +// struct TiledInputFile::Data stores things that will be +// needed between calls to readTile() +// + +struct DeepTiledInputFile::Data: public Mutex +{ + Header header; // the image header + TileDescription tileDesc; // describes the tile layout + int version; // file's version + DeepFrameBuffer frameBuffer; // framebuffer to write into + LineOrder lineOrder; // the file's lineorder + int minX; // data window's min x coord + int maxX; // data window's max x coord + int minY; // data window's min y coord + int maxY; // data window's max x coord + + int numXLevels; // number of x levels + int numYLevels; // number of y levels + int * numXTiles; // number of x tiles at a level + int * numYTiles; // number of y tiles at a level + + TileOffsets tileOffsets; // stores offsets in file for + // each tile + + bool fileIsComplete; // True if no tiles are missing + // in the file + + vector slices; // info about channels in file + + // ourselves? or does someone + // else do it? + + int partNumber; // part number + + bool multiPartBackwardSupport; // if we are reading a multipart file + // using OpenEXR 1.7 API + + int numThreads; // number of threads + + MultiPartInputFile* multiPartFile; // the MultiPartInputFile used to + // support backward compatibility + + vector tileBuffers; // each holds a single tile + + bool memoryMapped; + +// ... (52727 more chars) +``` + +### File: OpenEXR/IlmImf/ImfDwaCompressor.cpp +```c +struct DwaCompressor::Classifier +{ + Classifier (std::string suffix, + CompressorScheme scheme, + PixelType type, + int cscIdx, + bool caseInsensitive): + _suffix(suffix), + _scheme(scheme), + _type(type), + _cscIdx(cscIdx), + _caseInsensitive(caseInsensitive) + { + if (caseInsensitive) + std::transform(_suffix.begin(), _suffix.end(), _suffix.begin(), tolower); + } + + Classifier (const char *&ptr, int size) + { + if (size <= 0) + throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" + " (truncated rule)."); + + { + // maximum length of string plus one byte for terminating NULL + char suffix[Name::SIZE+1]; + memset (suffix, 0, Name::SIZE+1); + Xdr::read (ptr, std::min(size, Name::SIZE-1), suffix); + _suffix = std::string(suffix); + } + + if (static_cast(size) < _suffix.length() + 1 + 2*Xdr::size()) + throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" + " (truncated rule)."); + + char value; + Xdr::read (ptr, value); + + _cscIdx = (int)(value >> 4) - 1; + if (_cscIdx < -1 || _cscIdx >= 3) + throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" + " (corrupt cscIdx rule)."); + + _scheme = (CompressorScheme)((value >> 2) & 3); + if (_scheme < 0 || _scheme >= NUM_COMPRESSOR_SCHEMES) + throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" + " (corrupt scheme rule)."); + + _caseInsensitive = (value & 1 ? true : false); + + Xdr::read (ptr, value); + if (value < 0 || value >= NUM_PIXELTYPES) + throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" + " (corrupt rule)."); + _type = (PixelType)value; + } +``` + +### File: OpenEXR/IlmImf/ImfFastHuf.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2009-2014 DreamWorks Animation LLC. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of DreamWorks Animation nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + +#include "ImfFastHuf.h" +#include + +#include +#include +#include +#include + +OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER + +// +// Adapted from hufUnpackEncTable - +// We don't need to reconstruct the code book, just the encoded +// lengths for each symbol. From the lengths, we can build the +// base + offset tables. This should be a bit more efficient +// for sparse code books. +// +// table - ptr to the start of the code length data. Will be +// updated as we decode data +// +// numBytes - size of the encoded table (I think)? +// +// minSymbol - smallest symbol in the code book +// +// maxSymbol - largest symbol in the code book. +// +// rleSymbol - the symbol to trigger RLE in the encoded bitstream +// + +FastHufDecoder::FastHufDecoder + (const char *&table, + int numBytes, + int minSymbol, + int maxSymbol, + int rleSymbol) +: + _rleSymbol (rleSymbol), + _numSymbols (0), + _minCodeLength (255), + _maxCodeLength (0), + _idToSymbol (0) +{ + // + // List of symbols that we find with non-zero code lengths + // (listed in the order we find them). Store these in the + // same format as the code book stores codes + lengths - + // low 6 bits are the length, everything above that is + // the symbol. + // + + std::vector symbols; + + // + // The 'base' table is the minimum code at each code length. base[i] + // is the smallest code (numerically) of length i. + // + + Int64 base[MAX_CODE_LEN + 1]; + + // + // The 'offset' table is the position (in sorted order) of the first id + // of a given code lenght. Array is indexed by code length, like base. + // + + Int64 offset[MAX_CODE_LEN + 1]; + + // + // Count of how many codes at each length there are. Array is + // indexed by code length, like base and offset. + // + + size_t codeCount[MAX_CODE_LEN + 1]; + + for (int i = 0; i <= MAX_CODE_LEN; ++i) + { + codeCount[i] = 0; + base[i] = 0xffffffffffffffffULL; + offset[i] = 0; + } + + // + // Count the number of codes, the min/max code lengths, the number of + // codes with each length, and record symbols with non-zero code + // length as we find them. + // + + const char *currByte = table; + Int64 currBits = 0; + int currBitCount = 0; + + const int SHORT_ZEROCODE_RUN = 59; + const int LONG_ZEROCODE_RUN = 63; + const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; + + for (Int64 symbol = static_cast(minSymbol); symbol <= static_cast(maxSymbol); symbol++) + { + if (currByte - table > numBytes) + { + throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table " + "(Truncated table data)."); + } + + // + // Next code length - either: + // 0-58 (literal code length) + // 59-62 (various lengths runs of 0) + // 63 (run of n 0's, with n is the next 8 bits) + // + + Int64 codeLen = readBits (6, currBits, currBitCount, currByte); + + if (codeLen == (Int64) LONG_ZEROCODE_RUN) + { + if (currByte - table > numBytes) + { + throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table " + "(Truncated table data)."); + } + + int runLen = readBits (8, currBits, currBitCount, currByte) + + SHORTEST_LONG_RUN; + + if (symbol + runLen > static_cast(maxSymbol + 1)) + { + throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table " + "(Run beyond end of table)."); + } + + symbol += runLen - 1; + + } + else if (codeLen >= static_cast(SHORT_ZEROCODE_RUN)) + { + int runLen = codeLen - SHORT_ZEROCODE_RUN + 2; + + if (symbol + runLen > static_cast(maxSymbol + 1)) + { + throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table " + "(Run beyond end of table)."); + } + + symbol += runLen - 1; + + } + else if (codeLen != 0) + { + symbols.push_back ((symbol << 6) | (codeLen & 63)); + + if (codeLen < _minCodeLength) + _minCodeLength = codeLen; + + if (codeLen > _maxCodeLength) + _maxCodeLength = codeLen; + + codeCount[codeLen]++; + } + } + + for (int i = 0; i < MAX_CODE_LEN; ++i) + _numSymbols += codeCount[i]; + + table = currByte; + + // + // Compute base - once we have the code length counts, there + // is a closed form solution for this + // + + { + double* countTmp = new double[_maxCodeLength+1]; + + for (int l = _minCodeLength; l <= _maxCodeLength; ++l) + { + countTmp[l] = (double)codeCount[l] * + (double)(2 << (_maxCodeLength-l)); + } + + for (int l = _minCodeLength; l <= _maxCodeLength; ++l) + { + double tmp = 0; + + for (int k =l + 1; k <= _maxCodeLength; ++k) + tmp += countTmp[k]; + + tmp /= (double)(2 << (_maxCodeLength - l)); + + base[l] = (Int64)ceil (tmp); + } + + delete [] countTmp; + } + + // + // Compute offset - these are the positions of the first + // id (not symbol) that has length [i] + // + + offset[_maxCodeLength] = 0; + + for (int i= _maxCodeLength - 1; i >= _minCodeLength; i--) + offset[i] = offset[i + 1] + codeCount[i + 1]; + + // + // Allocate and fill the symbol-to-id mapping. Smaller Ids should be + // mapped to less-frequent symbols (which have longer codes). Use + // the offset table to tell us where the id's for a given code + // length start off. + // + + _idToSymbol = new int[_numSymbols]; + + Int64 mapping[MAX_CODE_LEN + 1]; + for (int i = 0; i < MAX_CODE_LEN + 1; ++i) + mapping[i] = -1; + for (int i = _minCodeLength; i <= _maxCodeLength; ++i) + mapping[i] = + +// ... (15190 more chars) +``` + +### File: OpenEXR/IlmImf/ImfHeader.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas +// Digital Ltd. LLC +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Industrial Light & Magic nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + + + +//----------------------------------------------------------------------------- +// +// class Header +// +//----------------------------------------------------------------------------- + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "IlmThreadMutex.h" +#include "Iex.h" +#include +#include +#include +#include +#include "ImfTiledMisc.h" +#include "ImfNamespace.h" + +OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER + +using namespace std; +using IMATH_NAMESPACE::Box2i; +using IMATH_NAMESPACE::V2i; +using IMATH_NAMESPACE::V2f; +using ILMTHREAD_NAMESPACE::Mutex; +using ILMTHREAD_NAMESPACE::Lock; + + +namespace { + +int maxImageWidth = 0; +int maxImageHeight = 0; +int maxTileWidth = 0; +int maxTileHeight = 0; + + +void +initialize (Header &header, + const Box2i &displayWindow, + const Box2i &dataWindow, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +{ + header.insert ("displayWindow", Box2iAttribute (displayWindow)); + header.insert ("dataWindow", Box2iAttribute (dataWindow)); + if ( !std::isnormal (pixelAspectRatio) || pixelAspectRatio < 0.f) + THROW (IEX_NAMESPACE::ArgExc, "Invalid pixel aspect ratio"); + header.insert ("pixelAspectRatio", FloatAttribute (pixelAspectRatio)); + header.insert ("screenWindowCenter", V2fAttribute (screenWindowCenter)); + header.insert ("screenWindowWidth", FloatAttribute (screenWindowWidth)); + header.insert ("lineOrder", LineOrderAttribute (lineOrder)); + header.insert ("compression", CompressionAttribute (compression)); + header.insert ("channels", ChannelListAttribute ()); +} + +template +void checkIsNullTerminated (const char (&str)[N], const char *what) +{ + for (size_t i = 0; i < N; ++i) { + if (str[i] == '\0') + return; + } + std::stringstream s; + s << "Invalid " << what << ": it is more than " << (N - 1) + << " characters long."; + throw IEX_NAMESPACE::InputExc(s); +} + +} // namespace + + +Header::Header (int width, + int height, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +: + _map() +{ + staticInitialize(); + + Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1)); + + initialize (*this, + displayWindow, + displayWindow, + pixelAspectRatio, + screenWindowCenter, + screenWindowWidth, + lineOrder, + compression); +} + + +Header::Header (int width, + int height, + const Box2i &dataWindow, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +: + _map() +{ + staticInitialize(); + + Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1)); + + initialize (*this, + displayWindow, + dataWindow, + pixelAspectRatio, + screenWindowCenter, + screenWindowWidth, + lineOrder, + compression); +} + + +Header::Header (const Box2i &displayWindow, + const Box2i &dataWindow, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +: + _map() +{ + staticInitialize(); + + initialize (*this, + displayWindow, + dataWindow, + pixelAspectRatio, + screenWindowCenter, + screenWindowWidth, + lineOrder, + compression); +} + + +Header::Header (const Header &other): _map() +{ + for (AttributeMap::const_iterator i = other._map.begin(); + i != other._map.end(); + ++i) + { + insert (*i->first, *i->second); + } +} + + +Header::~Header () +{ + for (AttributeMap::iterator i = _map.begin(); + i != _map.end(); + ++i) + { + delete i->second; + } +} + + +Header & +Header::operator = (const Header &other) +{ + if (this != &other) + { + for (AttributeMap::iterator i = _map.begin(); + i != _map.end(); + ++i) + { + delete i->second; + } + + _map.erase (_map.begin(), _map.end()); + + for (AttributeMap::const_iterator i = other._map.begin(); + i != other._map.end(); + ++i) + { + insert (*i->first, *i->second); + } + } + + return *this; +} + + +void +Header::erase (const char name[]) +{ + if (name[0] == 0) + THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string."); + + + AttributeMap::iterator i = _map.find (name); + if (i != _map.end()) + _map.erase (i); + +} + + +void +Header::erase (const string &name) +{ + erase (name.c_str()); +} + + +void +Header::insert (const char name[], const Attribute &attribute) +{ + if (name[0] == 0) + THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string."); + + AttributeMap::iterator i = _map.find (name); + + if (i == _map.end()) + { + Attribute *tmp = attribute.copy(); + + try + { + _map[name] = tmp; + } + catch (...) + { + delete tmp; + throw; + } + } + else + { + if (strcmp (i->second->typeName(), attribute.typeName())) + THROW (IEX_NAMESPACE::TypeExc, "Cannot assign a value of " + "type \"" << attribute.typeName() << "\" " + "to image attribute \"" << name << "\" of " + "type \"" << i->second->typeName() << "\"."); + + Attribute *tmp = attribute.copy(); + delete i->second; + i->second = tmp; + } +} + + +void +Header::insert (const string &name, const Attribute &attribute) +{ + insert (name.c_str(), attribute); +} + + +Attribute & +Header::operator [] (const char name[]) +{ + AttributeMap::iterator i = _map.find (name); + + if (i = + +// ... (22731 more chars) +``` + +### File: OpenEXR/IlmImf/ImfHuf.cpp +```c +void +hufUncompress (const char compressed[], + int nCompressed, + unsigned short raw[], + int nRaw) +{ + // + // need at least 20 bytes for header + // + if (nCompressed < 20 ) + { + if (nRaw != 0) + notEnoughData(); + + return; + } + + int im = readUInt (compressed); + int iM = readUInt (compressed + 4); + // int tableLength = readUInt (compressed + 8); + int nBits = readUInt (compressed + 12); + + if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) + invalidTableSize(); + + const char *ptr = compressed + 20; + + if ( ptr + (nBits+7 )/8 > compressed+nCompressed) + { + notEnoughData(); + return; + } + + // + // Fast decoder needs at least 2x64-bits of compressed data, and + // needs to be run-able on this platform. Otherwise, fall back + // to the original decoder + // + + if (FastHufDecoder::enabled() && nBits > 128) + { + FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM); + fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw); + } + else + { + AutoArray freq; + AutoArray hdec; + + hufClearDecTable (hdec); + + hufUnpackEncTable (&ptr, + nCompressed - (ptr - compressed), + im, + iM, + freq); + + try + { + if (nBits > 8 * (nCompressed - (ptr - compressed))) + invalidNBits(); + + hufBuildDecTable (freq, im, iM, hdec); + hufDecode (freq, hdec, ptr, nBits, iM, nRaw, raw); + } + catch (...) + { + hufFreeDecTable (hdec); + throw; + } + + hufFreeDecTable (hdec); + } +} +``` + +### File: OpenEXR/IlmImf/ImfInputFile.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas +// Digital Ltd. LLC +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Industrial Light & Magic nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + +//----------------------------------------------------------------------------- +// +// class InputFile +// +//----------------------------------------------------------------------------- + +#include "ImfCheckedArithmetic.h" +#include "ImfInputFile.h" +#include "ImfScanLineInputFile.h" +#include "ImfTiledInputFile.h" +#include "ImfChannelList.h" +#include "ImfMisc.h" +#include "ImfStdIO.h" +#include "ImfVersion.h" +#include "ImfPartType.h" +#include "ImfInputPartData.h" +#include "ImfMultiPartInputFile.h" + +#include +#include + +#include "ImathFun.h" +#include "IlmThreadMutex.h" +#include "Iex.h" +#include "half.h" + +#include +#include + +#include "ImfNamespace.h" + +OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER + + +using IMATH_NAMESPACE::Box2i; +using IMATH_NAMESPACE::divp; +using IMATH_NAMESPACE::modp; +using ILMTHREAD_NAMESPACE::Mutex; +using ILMTHREAD_NAMESPACE::Lock; + + +// +// Struct InputFile::Data stores things that will be +// needed between calls to readPixels +// + +struct InputFile::Data : public Mutex +{ + Header header; + int version; + bool isTiled; + + TiledInputFile * tFile; + ScanLineInputFile * sFile; + DeepScanLineInputFile * dsFile; + + LineOrder lineOrder; // the file's lineorder + int minY; // data window's min y coord + int maxY; // data window's max x coord + + FrameBuffer tFileBuffer; + FrameBuffer * cachedBuffer; + CompositeDeepScanLine * compositor; // for loading deep files + + int cachedTileY; + int offset; + + int numThreads; + + int partNumber; + InputPartData* part; + + bool multiPartBackwardSupport; + MultiPartInputFile* multiPartFile; + InputStreamMutex * _streamData; + bool _deleteStream; + + Data (int numThreads); + ~Data (); + + void deleteCachedBuffer(); +}; + + +InputFile::Data::Data (int numThreads): + isTiled (false), + tFile (0), + sFile (0), + dsFile(0), + cachedBuffer (0), + compositor(0), + cachedTileY (-1), + numThreads (numThreads), + partNumber (-1), + part(NULL), + multiPartBackwardSupport (false), + multiPartFile (0), + _streamData(0), + _deleteStream(false) + +{ + // empty +} + + +InputFile::Data::~Data () +{ + if (tFile) + delete tFile; + if (sFile) + delete sFile; + if (dsFile) + delete dsFile; + if (compositor) + delete compositor; + + deleteCachedBuffer(); + + if (multiPartBackwardSupport && multiPartFile) + delete multiPartFile; +} + + +void +InputFile::Data::deleteCachedBuffer() +{ + // + // Delete the cached frame buffer, and all memory + // allocated for the slices in the cached frameBuffer. + // + + if (cachedBuffer) + { + for (FrameBuffer::Iterator k = cachedBuffer->begin(); + k != cachedBuffer->end(); + ++k) + { + Slice &s = k.slice(); + + switch (s.type) + { + case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT: + + delete [] (((unsigned int *)s.base) + offset); + break; + + case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF: + + delete [] ((half *)s.base + offset); + break; + + case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT: + + delete [] (((float *)s.base) + offset); + break; + case NUM_PIXELTYPES : + throw(IEX_NAMESPACE::ArgExc("Invalid pixel type")); + } + } + + // + // delete the cached frame buffer + // + + delete cachedBuffer; + cachedBuffer = 0; + } +} + + +namespace { + +void +bufferedReadPixels (InputFile::Data* ifd, int scanLine1, int scanLine2) +{ + // + // bufferedReadPixels reads each row of tiles that intersect the + // scan-line range (scanLine1 to scanLine2). The previous row of + // tiles is cached in order to prevent redundent tile reads when + // accessing scanlines sequentially. + // + + int minY = std::min (scanLine1, scanLine2); + int maxY = std::max (scanLine1, scanLine2); + + if (minY < ifd->minY || maxY > ifd->maxY) + { + throw IEX_NAMESPACE::ArgExc ("Tried to read scan line outside " + "the image file's data window."); + } + + // + // The minimum and maximum y tile coordinates that intersect this + // scanline range + // + + int minDy = (minY - ifd->minY) / ifd->tFile->tileYSize(); + int maxDy = (maxY - ifd->minY) / ifd->tFile->tileYSize(); + + // + // Figure out which one is first in the file so we can read without seeking + // + + int yStart, yEnd, yStep; + + if (ifd->lineOrder == DECREASING_Y) + { + yStart = maxDy; + yEnd = minDy - 1; + yStep = -1; + } + else + { + yStart = minDy; + yEnd = maxDy + 1; + yStep = 1; + } + + // + // the number of pixels in a row of tiles + // + + Box2i levelRange = ifd->tFile->dataWindowForLevel(0); + + // + // Read the tiles into our temporary framebuffer and copy them into + // the user's buffer + // + + for (int j = yStart; j != yEnd; j += yStep) + { + Box2i tileRange = ifd->tFile->dataWindowForTile (0, j, 0); + + int minYThisRow = std::max (minY, tileRange.min.y); + int maxYThisRow = std::min (maxY, tileRange.max.y); + + if (j != ifd->cachedTileY) + { + // + // We don't have any valid buffered info, so we need to read in + // from the file. + // + + ifd->tFile->readTiles (0, ifd->tFile->numXTiles (0) - 1, j, j); + ifd->cachedTileY = j; + } + + // + // Copy the data from our cached framebuffer into the user's + // framebuffer. + // + + for (FrameBuffer::ConstIterator k = ifd->cachedBuffer->begin(); + k != ifd->cachedBuffer->end(); + ++k) + { + Slice fromSlice = k.slice(); // slice to write from + Slice toSlice = ifd->tFileBuffer[k.name()]; // slice to write to + + char *fromPtr, *toPtr; + int size = pixelTypeSize (toSlice.type); + + int xStart = levelRange.min.x; + int yStart = minYThisRow; + + while (modp (xStart, toSlice.xSampling) != 0) + ++xStart; + + while (modp (yStart, toSlice.ySampling) != 0) + + +// ... (16012 more chars) +``` + +### File: OpenEXR/IlmImf/ImfMisc.cpp +```c +size_t +bytesPerLineTable (const Header &header, + vector &bytesPerLine) +{ + const Box2i &dataWindow = header.dataWindow(); + const ChannelList &channels = header.channels(); + + bytesPerLine.resize (dataWindow.max.y - dataWindow.min.y + 1); + + for (ChannelList::ConstIterator c = channels.begin(); + c != channels.end(); + ++c) + { + size_t nBytes = size_t(pixelTypeSize (c.channel().type)) * + size_t(dataWindow.max.x - dataWindow.min.x + 1) / + size_t(c.channel().xSampling); + + for (int y = dataWindow.min.y, i = 0; y <= dataWindow.max.y; ++y, ++i) + if (modp (y, c.channel().ySampling) == 0) + bytesPerLine[i] += nBytes; + } + + size_t maxBytesPerLine = 0; + + for (int y = dataWindow.min.y, i = 0; y <= dataWindow.max.y; ++y, ++i) + if (maxBytesPerLine < bytesPerLine[i]) + maxBytesPerLine = bytesPerLine[i]; + + return maxBytesPerLine; +} + +int +numLinesInBuffer (Compressor * compressor) +{ + return compressor? compressor->numScanLines(): 1; +} + +bool +usesLongNames (const Header &header) +{ + // + // If an OpenEXR file contains any attribute names, attribute type names + // or channel names longer than 31 characters, then the file cannot be + // read by older versions of the IlmImf library (up to OpenEXR 1.6.1). + // Before writing the file header, we check if the header contains + // any names longer than 31 characters; if it does, then we set the + // LONG_NAMES_FLAG in the file version number. Older versions of the + // IlmImf library will refuse to read files that have the LONG_NAMES_FLAG + // set. Without the flag, older versions of the library would mis- + // interpret the file as broken. + // + + for (Header::ConstIterator i = header.begin(); + i != header.end(); + ++i) + { + if (strlen (i.name()) >= 32 || strlen (i.attribute().typeName()) >= 32) + return true; + } + + const ChannelList &channels = header.channels(); + + for (ChannelList::ConstIterator i = channels.begin(); + i != channels.end(); + ++i) + { + if (strlen (i.name()) >= 32) + return true; + } + + return false; +} + +int +numLinesInBuffer(Compression comp) +{ + switch(comp) + { + case NO_COMPRESSION : + case RLE_COMPRESSION: + case ZIPS_COMPRESSION: + return 1; + case ZIP_COMPRESSION: + return 16; + case PIZ_COMPRESSION: + return 32; + case PXR24_COMPRESSION: + return 16; + case B44_COMPRESSION: + case B44A_COMPRESSION: + case DWAA_COMPRESSION: + return 32; + case DWAB_COMPRESSION: + return 256; + + default: + throw IEX_NAMESPACE::ArgExc ("Unknown compression type"); + } +} +``` + +### File: OpenEXR/IlmImf/ImfPizCompressor.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas +// Digital Ltd. LLC +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Industrial Light & Magic nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + + +//----------------------------------------------------------------------------- +// +// class PizCompressor +// +//----------------------------------------------------------------------------- + +#include "ImfPizCompressor.h" +#include "ImfHeader.h" +#include "ImfChannelList.h" +#include "ImfHuf.h" +#include "ImfWav.h" +#include "ImfMisc.h" +#include "ImfCheckedArithmetic.h" +#include +#include +#include +#include "ImfIO.h" +#include "ImfXdr.h" +#include "ImfAutoArray.h" +#include +#include +#include "ImfNamespace.h" + +OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER + +using IMATH_NAMESPACE::divp; +using IMATH_NAMESPACE::modp; +using IMATH_NAMESPACE::Box2i; +using IMATH_NAMESPACE::V2i; +using IEX_NAMESPACE::InputExc; + +namespace { + +// +// Functions to compress the range of values in the pixel data +// + +const int USHORT_RANGE = (1 << 16); +const int BITMAP_SIZE = (USHORT_RANGE >> 3); + +void +bitmapFromData (const unsigned short data[/*nData*/], + int nData, + unsigned char bitmap[BITMAP_SIZE], + unsigned short &minNonZero, + unsigned short &maxNonZero) +{ + for (int i = 0; i < BITMAP_SIZE; ++i) + bitmap[i] = 0; + + for (int i = 0; i < nData; ++i) + bitmap[data[i] >> 3] |= (1 << (data[i] & 7)); + + bitmap[0] &= ~1; // zero is not explicitly stored in + // the bitmap; we assume that the + // data always contain zeroes + minNonZero = BITMAP_SIZE - 1; + maxNonZero = 0; + + for (int i = 0; i < BITMAP_SIZE; ++i) + { + if (bitmap[i]) + { + if (minNonZero > i) + minNonZero = i; + if (maxNonZero < i) + maxNonZero = i; + } + } +} + + +unsigned short +forwardLutFromBitmap (const unsigned char bitmap[BITMAP_SIZE], + unsigned short lut[USHORT_RANGE]) +{ + int k = 0; + + for (int i = 0; i < USHORT_RANGE; ++i) + { + if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) + lut[i] = k++; + else + lut[i] = 0; + } + + return k - 1; // maximum value stored in lut[], +} // i.e. number of ones in bitmap minus 1 + + +unsigned short +reverseLutFromBitmap (const unsigned char bitmap[BITMAP_SIZE], + unsigned short lut[USHORT_RANGE]) +{ + int k = 0; + + for (int i = 0; i < USHORT_RANGE; ++i) + { + if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) + lut[k++] = i; + } + + int n = k - 1; + + while (k < USHORT_RANGE) + lut[k++] = 0; + + return n; // maximum k where lut[k] is non-zero, +} // i.e. number of ones in bitmap minus 1 + + +void +applyLut (const unsigned short lut[USHORT_RANGE], + unsigned short data[/*nData*/], + int nData) +{ + for (int i = 0; i < nData; ++i) + data[i] = lut[data[i]]; +} + + +} // namespace + + +struct PizCompressor::ChannelData +{ + unsigned short * start; + unsigned short * end; + int nx; + int ny; + int ys; + int size; +}; + + +PizCompressor::PizCompressor + (const Header &hdr, + size_t maxScanLineSize, + size_t numScanLines) +: + Compressor (hdr), + _maxScanLineSize (maxScanLineSize), + _format (XDR), + _numScanLines (numScanLines), + _tmpBuffer (0), + _outBuffer (0), + _numChans (0), + _channels (hdr.channels()), + _channelData (0) +{ + // TODO: Remove this when we can change the ABI + (void) _maxScanLineSize; + size_t tmpBufferSize = uiMult (maxScanLineSize, numScanLines) / 2; + + size_t outBufferSize = + uiAdd (uiMult (maxScanLineSize, numScanLines), + size_t (65536 + 8192)); + + _tmpBuffer = new unsigned short + [checkArraySize (tmpBufferSize, sizeof (unsigned short))]; + + _outBuffer = new char [outBufferSize]; + + const ChannelList &channels = header().channels(); + bool onlyHalfChannels = true; + + for (ChannelList::ConstIterator c = channels.begin(); + c != channels.end(); + ++c) + { + _numChans++; + + assert (pixelTypeSize (c.channel().type) % pixelTypeSize (HALF) == 0); + + if (c.channel().type != HALF) + onlyHalfChannels = false; + } + + _channelData = new ChannelData[_numChans]; + + const Box2i &dataWindow = hdr.dataWindow(); + + _minX = dataWindow.min.x; + _maxX = dataWindow.max.x; + _maxY = dataWindow.max.y; + + // + // We can support uncompressed data in the machine's native format + // if all image channels are of type HALF, and if the Xdr and the + // native represenations of a half have the same size. + // + + if (onlyHalfChannels && (sizeof (half) == pixelTypeSize (HALF))) + _format = NATIVE; +} + + +PizCompressor::~PizCompressor () +{ + delete [] _tmpBuffer; + delete [] _outBuffer; + delete [] _channelData; +} + + +int +PizCompressor::numScanLines () const +{ + return _numScanLines; +} + + +Compressor::Format +PizCompressor::format () const +{ + return _format; +} + + +int +PizCompressor::compress (const char *inPtr, + int inSize, + int minY, + const char *&outPtr) +{ + return compress (inPtr, + inSize, + Box2i (V2i (_minX, minY), + V2i (_maxX, minY + numScanLines() - 1)), + outPtr); +} + + +int +PizCompressor::compressTile (const char *inPtr, + int inSize, + IMATH_NAMESPACE::Box2i range, + const char *&outPtr) +{ + return compress (inPtr, inSize, range, outPtr); +} + + +int +PizCompressor::uncompress (const char *inPtr, + int inSize, + int minY, + const char *&outPtr) +{ + return uncompress (inPtr, + inSize, + Box2i (V2i (_minX, minY), + V2i (_maxX, minY + numScanLines() - 1)), + outPtr); +} + + +int +PizCompressor::uncompressTile (const char *inPtr, + int inSize, + IMATH_NAMESPACE::Box2i range, + const char *&outPtr) +{ + return uncompress (inPtr, inSize, range, outPtr); +} + + +int +PizCompressor::compress (const char *inPtr, + int inSize, + IMATH_NAMESPACE::Box2i range, + const char *&outPtr) +{ + // + // This is the compress function which is used by both the tiled and + // scanline compression routines. + // + + // + // Special case �- empty input buffer + // + + if (inSize == 0) + { + outPtr = _outBuffer; + return 0; + } + + // + // Rearrange the pixel data so that the wavelet + // and Huffman encoders can process them easily. + // + // The wavelet and Huffman encoders both handle only + // 16-bit data, so 32-bit data must be split into smaller + // pieces. We treat each 32-bit ch + +// ... (7393 more chars) +``` + +### File: OpenEXR/IlmImf/ImfRle.cpp +```c +int +rleUncompress (int inLength, int maxLength, const signed char in[], char out[]) +{ + char *outStart = out; + + while (inLength > 0) + { + if (*in < 0) + { + int count = -((int)*in++); + inLength -= count + 1; + + if (0 > (maxLength -= count)) + return 0; + + // check the input buffer is big enough to contain + // 'count' bytes of remaining data + if (inLength < 0) + return 0; + + memcpy(out, in, count); + out += count; + in += count; + } + else + { + int count = *in++; + inLength -= 2; + + if (0 > (maxLength -= count + 1)) + return 0; + + memset(out, *(char*)in, count+1); + out += count+1; + + in++; + } + } + + return out - outStart; +} +``` + +### File: OpenEXR/IlmImf/ImfScanLineInputFile.cpp +```c +void ScanLineInputFile::initialize(const Header& header) +{ + _data->header = header; + + _data->lineOrder = _data->header.lineOrder(); + + const Box2i &dataWindow = _data->header.dataWindow(); + + _data->minX = dataWindow.min.x; + _data->maxX = dataWindow.max.x; + _data->minY = dataWindow.min.y; + _data->maxY = dataWindow.max.y; + + size_t maxBytesPerLine = bytesPerLineTable (_data->header, + _data->bytesPerLine); + + if(maxBytesPerLine > INT_MAX) + { + throw IEX_NAMESPACE::InputExc("maximum bytes per scanline exceeds maximum permissible size"); + } + + + for (size_t i = 0; i < _data->lineBuffers.size(); i++) + { + _data->lineBuffers[i] = new LineBuffer (newCompressor + (_data->header.compression(), + maxBytesPerLine, + _data->header)); + } + + _data->linesInBuffer = + numLinesInBuffer (_data->lineBuffers[0]->compressor); + + _data->lineBufferSize = maxBytesPerLine * _data->linesInBuffer; + + if (!_streamData->is->isMemoryMapped()) + { + for (size_t i = 0; i < _data->lineBuffers.size(); i++) + { + _data->lineBuffers[i]->buffer = (char *) EXRAllocAligned(_data->lineBufferSize*sizeof(char),16); + } + } + _data->nextLineBufferMinY = _data->minY - 1; + + offsetInLineBufferTable (_data->bytesPerLine, + _data->linesInBuffer, + _data->offsetInLineBuffer); + + int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y + + _data->linesInBuffer) / _data->linesInBuffer; + + _data->lineOffsets.resize (lineOffsetSize); +} + +void +ScanLineInputFile::setFrameBuffer (const FrameBuffer &frameBuffer) +{ + Lock lock (*_streamData); + + + + const ChannelList &channels = _data->header.channels(); + for (FrameBuffer::ConstIterator j = frameBuffer.begin(); + j != frameBuffer.end(); + ++j) + { + ChannelList::ConstIterator i = channels.find (j.name()); + + if (i == channels.end()) + continue; + + if (i.channel().xSampling != j.slice().xSampling || + i.channel().ySampling != j.slice().ySampling) + THROW (IEX_NAMESPACE::ArgExc, "X and/or y subsampling factors " + "of \"" << i.name() << "\" channel " + "of input file \"" << fileName() << "\" are " + "not compatible with the frame buffer's " + "subsampling factors."); + } + + // optimization is possible if this is a little endian system + // and both inputs and outputs are half floats + // + bool optimizationPossible = true; + + if (!GLOBAL_SYSTEM_LITTLE_ENDIAN) + { + optimizationPossible =false; + } + + vector optData; + + + // + // Initialize the slice table for readPixels(). + // + + vector slices; + ChannelList::ConstIterator i = channels.begin(); + + // current offset of channel: pixel data starts at offset*width into the + // decompressed scanline buffer + size_t offset = 0; + + for (FrameBuffer::ConstIterator j = frameBuffer.begin(); + j != frameBuffer.end(); + ++j) + { + while (i != channels.end() && strcmp (i.name(), j.name()) < 0) + { + // + // Channel i is present in the file but not + // in the frame buffer; data for channel i + // will be skipped during readPixels(). + // + + slices.push_back (InSliceInfo (i.channel().type, + i.channel().type, + 0, // base + 0, // xStride + 0, // yStride + i.channel().xSampling, + i.channel().ySampling, + false, // fill + true, // skip + 0.0)); // fillValue + + switch(i.channel().type) + { + case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF : + offset++; + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT : + offset+=2; + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT : + offset+=2; + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::NUM_PIXELTYPES: + default: + // not possible. + break; + } + + // + // optimization mode cannot currently skip subsampled channels + // + if (i.channel().xSampling!=1 || i.channel().ySampling!=1) + { + optimizationPossible = false; + } + ++i; + } + + bool fill = false; + + if (i == channels.end() || strcmp (i.name(), j.name()) > 0) + { + // + // Channel i is present in the frame buffer, but not in the file. + // In the frame buffer, slice j will be filled with a default value. + // + + fill = true; + } + + slices.push_back (InSliceInfo (j.slice().type, + fill? j.slice().type: + i.channel().type, + j.slice().base, + j.slice().xStride, + j.slice().yStride, + j.slice().xSampling, + j.slice().ySampling, + fill, + false, // skip + j.slice().fillValue)); + + if(!fill && i.channel().type!=OPENEXR_IMF_INTERNAL_NAMESPACE::HALF) + { + optimizationPossible = false; + } + + if(j.slice().type != OPENEXR_IMF_INTERNAL_NAMESPACE::HALF) + { + optimizationPossible = false; + } + if(j.slice().xSampling!=1 || j.slice().ySampling!=1) + { + optimizationPossible = false; + } + + + if(optimizationPossible) + { + sliceOptimizationData dat; + dat.base = j.slice().base; + dat.fill = fill; + dat.fillValue = j.slice().fillValue; + dat.offset = offset; + dat.xStride = j.slice().xStride; + dat.yStride = j.slice().yStride; + dat.xSampling = j.slice().xSampling; + dat.ySampling = j.slice().ySampling; + optData.push_back(dat); + } + + if(!fill) + { + switch(i.channel().type) + { + case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF : + offset++; + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT : + offset+=2; + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT : + offset+=2; + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::NUM_PIXELTYPES: + default: + // not possible. + break; + } + } + + + + if (i != channels.end() && !fill) + ++i; + } + + + if(optimizationPossible) + { + // + // check optimisibility + // based on channel ordering and fill channel positions + // + sort(optData.begin(),optData.end()); + _data->optimizationMode = detectOptimizationMode(optData); + } + + if(!optimizationPossible || _data->optimizationMode._optimizable==false) + { + optData = vector(); + _data->optimizationMode._optimizable=false; + } + + // + // Store the new frame buffer. + // + + _data->frameBuffer = frameBuffer; + _data->slices = slices; + _data->optimizationData = optData; +} +``` + +### File: OpenEXR/IlmImf/ImfTiledInputFile.cpp +```c +try + { + try + { + is = new StdIFStream (fileName); + readMagicNumberAndVersionField(*is, _data->version); + + // + // Backward compatibility to read multpart file. + // + if (isMultiPart(_data->version)) + { + compatibilityInitialize(*is); + return; + } + + _data->_streamData = new InputStreamMutex(); + _data->_streamData->is = is; + _data->header.readFrom (*_data->_streamData->is, _data->version); + initialize(); + //read tile offsets - we are not multipart or deep + _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); + _data->_streamData->currentPosition = _data->_streamData->is->tellg(); + } + +try + { + try + { + readMagicNumberAndVersionField(is, _data->version); + + // + // Backward compatibility to read multpart file. + // + if (isMultiPart(_data->version)) + { + compatibilityInitialize(is); + return; + } + + streamDataCreated = true; + _data->_streamData = new InputStreamMutex(); + _data->_streamData->is = &is; + _data->header.readFrom (*_data->_streamData->is, _data->version); + initialize(); + // file is guaranteed to be single part, regular image + _data->tileOffsets.readFrom (*(_data->_streamData->is), _data->fileIsComplete,false,false); + _data->memoryMapped = _data->_streamData->is->isMemoryMapped(); + _data->_streamData->currentPosition = _data->_streamData->is->tellg(); + } +``` + +### File: OpenEXR/IlmImf/ImfTiledMisc.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas +// Digital Ltd. LLC +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Industrial Light & Magic nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + + +//----------------------------------------------------------------------------- +// +// Miscellaneous stuff related to tiled files +// +//----------------------------------------------------------------------------- + +#include +#include "Iex.h" +#include +#include +#include +#include + +#include "ImfNamespace.h" + +OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER + +using IMATH_NAMESPACE::Box2i; +using IMATH_NAMESPACE::V2i; + + +int +levelSize (int min, int max, int l, LevelRoundingMode rmode) +{ + if (l < 0) + throw IEX_NAMESPACE::ArgExc ("Argument not in valid range."); + + int a = max - min + 1; + int b = (1 << l); + int size = a / b; + + if (rmode == ROUND_UP && size * b < a) + size += 1; + + return std::max (size, 1); +} + + +Box2i +dataWindowForLevel (const TileDescription &tileDesc, + int minX, int maxX, + int minY, int maxY, + int lx, int ly) +{ + V2i levelMin = V2i (minX, minY); + + V2i levelMax = levelMin + + V2i (levelSize (minX, maxX, lx, tileDesc.roundingMode) - 1, + levelSize (minY, maxY, ly, tileDesc.roundingMode) - 1); + + return Box2i(levelMin, levelMax); +} + + +Box2i +dataWindowForTile (const TileDescription &tileDesc, + int minX, int maxX, + int minY, int maxY, + int dx, int dy, + int lx, int ly) +{ + V2i tileMin = V2i (minX + dx * tileDesc.xSize, + minY + dy * tileDesc.ySize); + + V2i tileMax = tileMin + V2i (tileDesc.xSize - 1, tileDesc.ySize - 1); + + V2i levelMax = dataWindowForLevel + (tileDesc, minX, maxX, minY, maxY, lx, ly).max; + + tileMax = V2i (std::min (tileMax[0], levelMax[0]), + std::min (tileMax[1], levelMax[1])); + + return Box2i (tileMin, tileMax); +} + + +size_t +calculateBytesPerPixel (const Header &header) +{ + const ChannelList &channels = header.channels(); + + size_t bytesPerPixel = 0; + + for (ChannelList::ConstIterator c = channels.begin(); + c != channels.end(); + ++c) + { + bytesPerPixel += pixelTypeSize (c.channel().type); + } + + return bytesPerPixel; +} + + +void +calculateBytesPerLine (const Header &header, + char* sampleCountBase, + int sampleCountXStride, + int sampleCountYStride, + int minX, int maxX, + int minY, int maxY, + std::vector& xOffsets, + std::vector& yOffsets, + std::vector& bytesPerLine) +{ + const ChannelList &channels = header.channels(); + + int pos = 0; + for (ChannelList::ConstIterator c = channels.begin(); + c != channels.end(); + ++c, ++pos) + { + int xOffset = xOffsets[pos]; + int yOffset = yOffsets[pos]; + int i = 0; + for (int y = minY - yOffset; y <= maxY - yOffset; y++, i++) + for (int x = minX - xOffset; x <= maxX - xOffset; x++) + { + bytesPerLine[i] += sampleCount(sampleCountBase, + sampleCountXStride, + sampleCountYStride, + x, y) + * pixelTypeSize (c.channel().type); + } + } +} + + +namespace { + +int +floorLog2 (int x) +{ + // + // For x > 0, floorLog2(y) returns floor(log(x)/log(2)). + // + + int y = 0; + + while (x > 1) + { + y += 1; + x >>= 1; + } + + return y; +} + + +int +ceilLog2 (int x) +{ + // + // For x > 0, ceilLog2(y) returns ceil(log(x)/log(2)). + // + + int y = 0; + int r = 0; + + while (x > 1) + { + if (x & 1) + r = 1; + + y += 1; + x >>= 1; + } + + return y + r; +} + + +int +roundLog2 (int x, LevelRoundingMode rmode) +{ + return (rmode == ROUND_DOWN)? floorLog2 (x): ceilLog2 (x); +} + + +int +calculateNumXLevels (const TileDescription& tileDesc, + int minX, int maxX, + int minY, int maxY) +{ + int num = 0; + + switch (tileDesc.mode) + { + case ONE_LEVEL: + + num = 1; + break; + + case MIPMAP_LEVELS: + + { + int w = maxX - minX + 1; + int h = maxY - minY + 1; + num = roundLog2 (std::max (w, h), tileDesc.roundingMode) + 1; + } + break; + + case RIPMAP_LEVELS: + + { + int w = maxX - minX + 1; + num = roundLog2 (w, tileDesc.roundingMode) + 1; + } + break; + + default: + + throw IEX_NAMESPACE::ArgExc ("Unknown LevelMode format."); + } + + return num; +} + + +int +calculateNumYLevels (const TileDescription& tileDesc, + int minX, int maxX, + int minY, int maxY) +{ + int num = 0; + + switch (tileDesc.mode) + { + case ONE_LEVEL: + + num = 1; + break; + + case MIPMAP_LEVELS: + + { + int w = maxX - minX + 1; + int h = maxY - minY + 1; + num = roundLog2 (std::max (w, h), tileDesc.roundingMode) + 1; + } + break; + + case RIPMAP_LEVELS: + + { + int h = maxY - minY + 1; + num = roundLog2 (h, tileDesc.roundingMode) + 1; + } + break; + + default: + + throw IEX_NAMESPACE::ArgExc ("Unknown LevelMode format."); + } + + return num; +} + + +void +calculateNumTiles (int *numTiles, + int numLevels, + int min, int max, + int size, + LevelRoundingMode rmode) +{ + for (int i = 0; i < numLevels; i++) + { + numTiles[i] = (levelSize (min, max, i, rmode) + size - 1) / size; + } +} + +} // namespace + + +void +precalculateTileInfo (const TileDescription& tileDesc, + int minX, int maxX, + int minY, int maxY, + int *&numXTiles, int *&numYTiles, + int &numXLevels, int &numYLevels) +{ + numXLevels = calculateNumXLevels(tileDesc, minX, maxX, minY, maxY); + numYLevels = calculateNumYLevels(tileDesc, minX, maxX, minY, maxY); + + numXTiles = new int[numXLevels]; + numYTiles = new int[numYLevels]; + + calculateNumTiles (numXTiles, + numXLevels, + minX, maxX, + tileDesc.xSize, + tileDesc.roundingMode); + + calculateNumTiles (numYTiles, + numYLevels, + minY, maxY, + tileDesc.ySize, + tileDesc.roundingMode); +} + + +int +getTiledChunkOffsetTableSize(const Header& header) +{ + // + // Save the dataWindow information + // + + const Box2i &dataWindow = header.dataWindow(); + + // + // Precompute level and tile information. + // + + int* n + +// ... (2039 more chars) +``` + +### File: OpenEXR/IlmImfTest/testDeepTiledBasic.cpp +```c +void readFile (int channelCount, + bool bulkRead, + bool relativeCoords, + bool randomChannels, + const std::string & filename) +{ + if (relativeCoords) + assert(bulkRead == false); + + cout << "reading " << flush; + + DeepTiledInputFile file (filename.c_str(), 4); + + const Header& fileHeader = file.header(); + assert (fileHeader.displayWindow() == header.displayWindow()); + assert (fileHeader.dataWindow() == header.dataWindow()); + assert (fileHeader.pixelAspectRatio() == header.pixelAspectRatio()); + assert (fileHeader.screenWindowCenter() == header.screenWindowCenter()); + assert (fileHeader.screenWindowWidth() == header.screenWindowWidth()); + assert (fileHeader.lineOrder() == header.lineOrder()); + assert (fileHeader.compression() == header.compression()); + assert (fileHeader.channels() == header.channels()); + assert (fileHeader.type() == header.type()); + assert (fileHeader.tileDescription() == header.tileDescription()); + + Array2D localSampleCount; + localSampleCount.resizeErase(height, width); + + // also test filling channels. Generate up to 2 extra channels + int fillChannels=random_int(3); + + Array > data(channelCount+fillChannels); + for (int i = 0; i < channelCount+fillChannels; i++) + data[i].resizeErase(height, width); + + DeepFrameBuffer frameBuffer; + + int memOffset; + if (relativeCoords) + memOffset = 0; + else + memOffset = dataWindow.min.x + dataWindow.min.y * width; + frameBuffer.insertSampleCountSlice (Slice (IMF::UINT, + (char *) (&localSampleCount[0][0] - memOffset), + sizeof (unsigned int) * 1, + sizeof (unsigned int) * width, + 1, 1, + 0, + relativeCoords, + relativeCoords)); + + + vector read_channel(channelCount); + int channels_added=0; + for (int i = 0; i < channelCount; i++) + { + if(randomChannels) + { + read_channel[i] = random_int(2); + + } + if(!randomChannels || read_channel[i]==1) + { + PixelType type = IMF::NUM_PIXELTYPES; + if (channelTypes[i] == 0) + type = IMF::UINT; + if (channelTypes[i] == 1) + type = IMF::HALF; + if (channelTypes[i] == 2) + type = IMF::FLOAT; + + stringstream ss; + ss << i; + string str = ss.str(); + + int sampleSize = 0; + if (channelTypes[i] == 0) sampleSize = sizeof (unsigned int); + if (channelTypes[i] == 1) sampleSize = sizeof (half); + if (channelTypes[i] == 2) sampleSize = sizeof (float); + + int pointerSize = sizeof (char *); + + frameBuffer.insert (str, + DeepSlice (type, + (char *) (&data[i][0][0] - memOffset), + pointerSize * 1, + pointerSize * width, + sampleSize, + 1, 1, + 0, + relativeCoords, + relativeCoords)); + channels_added++; + } + } + if(channels_added==0) + { + cout << "skipping " < +#include +#include +#include +#include +#include + +#include "tmpDir.h" +#include "testMultiPartApi.h" +#include "random.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace IMF = OPENEXR_IMF_NAMESPACE; +using namespace IMF; +using namespace std; +using namespace IMATH_NAMESPACE; + +namespace +{ + +const int height = 263; +const int width = 197; + +struct Task +{ + int partNumber; + int tx, ty, lx, ly; + + Task(int partNumber): + partNumber(partNumber) + {} + + Task(int partNumber, int tx, int ty, int lx, int ly): + partNumber(partNumber), + tx(tx), + ty(ty), + lx(lx), + ly(ly) + {} +}; + +vector
headers; +vector pixelTypes; +vector partTypes; +vector levelModes; + +template +void fillPixels (Array2D &ph, int width, int height) +{ + ph.resizeErase(height, width); + for (int y = 0; y < height; ++y) + for (int x = 0; x < width; ++x) + { + // + // We do this because half cannot store number bigger than 2048 exactly. + // + ph[y][x] = (y * width + x) % 2049; + } +} + +template +bool checkPixels (Array2D &ph, int lx, int rx, int ly, int ry, int width) +{ + for (int y = ly; y <= ry; ++y) + for (int x = lx; x <= rx; ++x) + if (ph[y][x] != static_cast(((y * width + x) % 2049))) + { + cout << "value at " << x << ", " << y << ": " << ph[y][x] + << ", should be " << (y * width + x) % 2049 << endl << flush; + return false; + } + return true; +} + +template +bool checkPixels (Array2D &ph, int width, int height) +{ + return checkPixels (ph, 0, width - 1, 0, height - 1, width); +} + +void generateRandomHeaders(int partCount, vector
& headers, vector& taskList) +{ + headers.clear(); + for (int i = 0; i < partCount; i++) + { + Header header(width, height); + int pixelType = random_int(3); + int partType = random_int(2); + pixelTypes[i] = pixelType; + partTypes[i] = partType; + + stringstream ss; + ss << i; + header.setName(ss.str()); + + switch (pixelType) + { + case 0: + header.channels().insert("UINT", Channel(IMF::UINT)); + break; + case 1: + header.channels().insert("FLOAT", Channel(IMF::FLOAT)); + break; + case 2: + header.channels().insert("HALF", Channel(IMF::HALF)); + break; + } + + switch (partType) + { + case 0: + header.setType(SCANLINEIMAGE); + break; + case 1: + header.setType(TILEDIMAGE); + break; + } + + int tileX; + int tileY; + int levelMode = 0; + if (partType == 1) + { + tileX = random_int(width) + 1; + tileY = random_int(height) + 1; + levelMode = random_int(3); + levelModes[i] = levelMode; + LevelMode lm = NUM_LEVELMODES; + switch (levelMode) + { + case 0: + lm = ONE_LEVEL; + break; + case 1: + lm = MIPMAP_LEVELS; + break; + case 2: + lm = RIPMAP_LEVELS; + break; + } + header.setTileDescription(TileDescription(tileX, tileY, lm)); + } + + // + // Add lines or tiles to task list. + // + if (partType == 0) + { + for (int j = 0; j < height; j++) + taskList.push_back(Task(i)); + } + else + { + int numXLevel; + int numYLevel; + int* numXTiles; + int* numYTiles; + precalculateTileInfo (header.tileDescription(), + 0, width - 1, + 0, height - 1, + numXTiles, numYTiles, + numXLevel, numYLevel); + + for (int lx = 0; lx < numXLevel; lx++) + for (int ly = 0; ly < numYLevel; ly++) + { + if (levelMode == 1) + if (lx != ly) continue; + + // Get all tasks for this level. + for (int tx = 0; tx < numXTiles[lx]; tx++) + for (int ty = 0; ty < numYTiles[ly]; ty++) + taskList.push_back(Task(i, tx, ty, lx, ly)); + } + + delete[] numXTiles; + delete[] numYTiles; + } + +// if (partType == 0) +// { +// cout << "pixelType = " << pixelType << " partType = " << partType +// << endl << flush; +// } +// else +// { +// cout << "pixelType = " << pixelType << " partType = " << partType +// << " levelMode = " << levelModes[i] << endl << flush; +// } + + headers.push_back(header); + } +} + +void setOutputFrameBuffer(FrameBuffer& frameBuffer, int pixelType, + Array2D& uData, Array2D& fData, + Array2D& hData, int width) +{ + switch (pixelType) + { + case 0: + frameBuffer.insert ("UINT", + Slice (IMF::UINT, + (char *) (&uData[0][0]), + sizeof (uData[0][0]) * 1, + sizeof (uData[0][0]) * width)); + break; + case 1: + frameBuffer.insert ("FLOAT", + Slice (IMF::FLOAT, + + +// ... (16703 more chars) +``` + +### File: OpenEXR/IlmImfTest/testMultiPartThreading.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2011, Industrial Light & Magic, a division of Lucas +// Digital Ltd. LLC +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Industrial Light & Magic nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + +#ifdef NDEBUG +# undef NDEBUG +#endif + +#include +#include +#include +#include +#include +#include + +#include "tmpDir.h" +#include "testMultiPartThreading.h" +#include "random.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace IMF = OPENEXR_IMF_NAMESPACE; +using namespace IMF; +using namespace std; +using namespace IMATH_NAMESPACE; +using namespace ILMTHREAD_NAMESPACE; + +namespace +{ + +const int height = 263; +const int width = 197; + +vector
headers; +vector pixelTypes; +vector partTypes; +vector levelModes; + +Mutex mutexes[200]; + +template +void fillPixels (Array2D &ph, int width, int height) +{ + ph.resizeErase(height, width); + for (int y = 0; y < height; ++y) + for (int x = 0; x < width; ++x) + { + // + // We do this because half cannot store number bigger than 2048 exactly. + // + ph[y][x] = (y * width + x) % 2049; + } +} + +template +bool checkPixels (Array2D &ph, int lx, int rx, int ly, int ry, int width) +{ + for (int y = ly; y <= ry; ++y) + for (int x = lx; x <= rx; ++x) + if (ph[y][x] != static_cast(((y * width + x) % 2049))) + { + cout << "value at " << x << ", " << y << ": " << ph[y][x] + << ", should be " << (y * width + x) % 2049 << endl << flush; + return false; + } + return true; +} + +template +bool checkPixels (Array2D &ph, int width, int height) +{ + return checkPixels (ph, 0, width - 1, 0, height - 1, width); +} + +void setOutputFrameBuffer(FrameBuffer& frameBuffer, int pixelType, + Array2D& uData, Array2D& fData, + Array2D& hData, int width) +{ + switch (pixelType) + { + case 0: + frameBuffer.insert ("UINT", + Slice (IMF::UINT, + (char *) (&uData[0][0]), + sizeof (uData[0][0]) * 1, + sizeof (uData[0][0]) * width)); + break; + case 1: + frameBuffer.insert ("FLOAT", + Slice (IMF::FLOAT, + (char *) (&fData[0][0]), + sizeof (fData[0][0]) * 1, + sizeof (fData[0][0]) * width)); + break; + case 2: + frameBuffer.insert ("HALF", + Slice (IMF::HALF, + (char *) (&hData[0][0]), + sizeof (hData[0][0]) * 1, + sizeof (hData[0][0]) * width)); + break; + } +} + +void setInputFrameBuffer(FrameBuffer& frameBuffer, int pixelType, + Array2D& uData, Array2D& fData, + Array2D& hData, int width, int height) +{ + switch (pixelType) + { + case 0: + uData.resizeErase(height, width); + frameBuffer.insert ("UINT", + Slice (IMF::UINT, + (char *) (&uData[0][0]), + sizeof (uData[0][0]) * 1, + sizeof (uData[0][0]) * width, + 1, 1, + 0)); + break; + case 1: + fData.resizeErase(height, width); + frameBuffer.insert ("FLOAT", + Slice (IMF::FLOAT, + (char *) (&fData[0][0]), + sizeof (fData[0][0]) * 1, + sizeof (fData[0][0]) * width, + 1, 1, + 0)); + break; + case 2: + hData.resizeErase(height, width); + frameBuffer.insert ("HALF", + Slice (IMF::HALF, + (char *) (&hData[0][0]), + sizeof (hData[0][0]) * 1, + sizeof (hData[0][0]) * width, + 1, 1, + 0)); + break; + } +} + +struct WritingTaskData +{ + int partNumber; + int tx, ty, lx, ly; + + WritingTaskData(int partNumber): + partNumber(partNumber) + {} + + WritingTaskData(int partNumber, int tx, int ty, int lx, int ly): + partNumber(partNumber), + tx(tx), + ty(ty), + lx(lx), + ly(ly) + {} +}; + +class WritingTask: public Task +{ + public: + WritingTask (TaskGroup *group, MultiPartOutputFile* file, vector data, + Array2D* tiledFrameBuffers): + Task(group), + file(file), + data(data), + tiledFrameBuffers(tiledFrameBuffers) + {} + + void execute() + { + for (size_t i = 0; i < data.size(); i++) + { + int partNumber = data[i]->partNumber; + int partType = partTypes[partNumber]; + + if (partType == 0) + { + OutputPart part(*file, partNumber); + part.writePixels(); + } + else + { + int tx = data[i]->tx; + int ty = data[i]->ty; + int lx = data[i]->lx; + int ly = data[i]->ly; + TiledOutputPart part(*file, partNumber); + + // + // We add lock here to assure that two threads that accessing + // the same part won't mess things up. + + +// ... (19490 more chars) +``` + +### File: OpenEXR/exrmakepreview/makePreview.cpp +```c +void +generatePreview (const char inFileName[], + float exposure, + int previewWidth, + int &previewHeight, + Array2D &previewPixels) +{ + // + // Read the input file + // + + RgbaInputFile in (inFileName); + + Box2i dw = in.dataWindow(); + float a = in.pixelAspectRatio(); + int w = dw.max.x - dw.min.x + 1; + int h = dw.max.y - dw.min.y + 1; + + Array2D pixels (h, w); + in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w); + in.readPixels (dw.min.y, dw.max.y); + + // + // Make a preview image + // + + previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1); + previewPixels.resizeErase (previewHeight, previewWidth); + + double fx = (previewWidth > 1)? (double (w - 1) / (previewWidth - 1)): 1; + double fy = (previewHeight > 1)? (double (h - 1) / (previewHeight - 1)): 1; + float m = Math::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f)); + + for (int y = 0; y < previewHeight; ++y) + { + for (int x = 0; x < previewWidth; ++x) + { + PreviewRgba &preview = previewPixels[y][x]; + const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)]; + + preview.r = gamma (pixel.r, m); + preview.g = gamma (pixel.g, m); + preview.b = gamma (pixel.b, m); + preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f); + } + } +} +``` diff --git a/tasks/csa159/pair_136251/pre_functions.txt b/tasks/csa159/pair_136251/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..3f471f57b9d1d9d793f3c212b73a094e651c485d --- /dev/null +++ b/tasks/csa159/pair_136251/pre_functions.txt @@ -0,0 +1,2527 @@ +### File: OpenEXR/IlmImf/ImfCompositeDeepScanLine.cpp +```c +void +CompositeDeepScanLine::Data::handleDeepFrameBuffer (DeepFrameBuffer& buf, + std::vector< unsigned int > & counts, + vector< std::vector< float* > > & pointers, + const Header& header, + int start, + int end) +{ + int width=_dataWindow.size().x+1; + size_t pixelcount = width * (end-start+1); + pointers.resize(_channels.size()); + counts.resize(pixelcount); + buf.insertSampleCountSlice (Slice (OPENEXR_IMF_INTERNAL_NAMESPACE::UINT, + (char *) (&counts[0]-_dataWindow.min.x-start*width), + sizeof(unsigned int), + sizeof(unsigned int)*width)); + + pointers[0].resize(pixelcount); + buf.insert ("Z", DeepSlice (OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT, + (char *)(&pointers[0][0]-_dataWindow.min.x-start*width), + sizeof(float *), + sizeof(float *)*width, + sizeof(float) )); + + if(_zback) + { + pointers[1].resize(pixelcount); + buf.insert ("ZBack", DeepSlice (OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT, + (char *)(&pointers[1][0]-_dataWindow.min.x-start*width), + sizeof(float *), + sizeof(float *)*width, + sizeof(float) )); + } + + pointers[2].resize(pixelcount); + buf.insert ("A", DeepSlice (OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT, + (char *)(&pointers[2][0]-_dataWindow.min.x-start*width), + sizeof(float *), + sizeof(float *)*width, + sizeof(float) )); + + + size_t i =0; + for(FrameBuffer::ConstIterator qt = _outputFrameBuffer.begin(); + qt != _outputFrameBuffer.end(); + qt++) + { + int channel_in_source = _bufferMap[i]; + if(channel_in_source>2) + { + // not dealt with yet (0,1,2 previously inserted) + pointers[channel_in_source].resize(pixelcount); + buf.insert (qt.name(), + DeepSlice (OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT, + (char *)(&pointers[channel_in_source][0]-_dataWindow.min.x-start*width), + sizeof(float *), + sizeof(float *)*width, + sizeof(float) )); + } + + i++; + } + +} +``` + +### File: OpenEXR/IlmImf/ImfDeepScanLineInputFile.cpp +```c +void DeepScanLineInputFile::initialize(const Header& header) +{ + try + { + if (header.type() != DEEPSCANLINE) + throw IEX_NAMESPACE::ArgExc("Can't build a DeepScanLineInputFile from " + "a type-mismatched part."); + + if(header.version()!=1) + { + THROW(IEX_NAMESPACE::ArgExc, "Version " << header.version() << " not supported for deepscanline images in this version of the library"); + } + + _data->header = header; + + _data->lineOrder = _data->header.lineOrder(); + + const Box2i &dataWindow = _data->header.dataWindow(); + + _data->minX = dataWindow.min.x; + _data->maxX = dataWindow.max.x; + _data->minY = dataWindow.min.y; + _data->maxY = dataWindow.max.y; + + _data->sampleCount.resizeErase(_data->maxY - _data->minY + 1, + _data->maxX - _data->minX + 1); + _data->lineSampleCount.resizeErase(_data->maxY - _data->minY + 1); + + Compressor* compressor = newCompressor(_data->header.compression(), + 0, + _data->header); + + _data->linesInBuffer = numLinesInBuffer (compressor); + + delete compressor; + + _data->nextLineBufferMinY = _data->minY - 1; + + int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y + + _data->linesInBuffer) / _data->linesInBuffer; + + _data->lineOffsets.resize (lineOffsetSize); + + for (size_t i = 0; i < _data->lineBuffers.size(); i++) + _data->lineBuffers[i] = new LineBuffer (); + + _data->gotSampleCount.resizeErase(_data->maxY - _data->minY + 1); + for (int i = 0; i < _data->maxY - _data->minY + 1; i++) + _data->gotSampleCount[i] = false; + + _data->maxSampleCountTableSize = min(_data->linesInBuffer, _data->maxY - _data->minY + 1) * + (_data->maxX - _data->minX + 1) * + sizeof(unsigned int); + + _data->sampleCountTableBuffer.resizeErase(_data->maxSampleCountTableSize); + + _data->sampleCountTableComp = newCompressor(_data->header.compression(), + _data->maxSampleCountTableSize, + _data->header); + + _data->bytesPerLine.resize (_data->maxY - _data->minY + 1); + + const ChannelList & c=header.channels(); + + _data->combinedSampleSize=0; + for(ChannelList::ConstIterator i=c.begin();i!=c.end();i++) + { + switch(i.channel().type) + { + case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF : + _data->combinedSampleSize+=Xdr::size(); + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT : + _data->combinedSampleSize+=Xdr::size(); + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT : + _data->combinedSampleSize+=Xdr::size(); + break; + default : + THROW(IEX_NAMESPACE::ArgExc, "Bad type for channel " << i.name() << " initializing deepscanline reader"); + + } + } + + } + catch (...) + { + delete _data; + _data=NULL; + throw; + } +} + +void +DeepScanLineInputFile::compatibilityInitialize(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is) +{ + is.seekg(0); + // + // Construct a MultiPartInputFile, initialize TiledInputFile + // with the part 0 data. + // (TODO) maybe change the third parameter of the constructor of MultiPartInputFile later. + // + _data->multiPartBackwardSupport = true; + _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads); + InputPartData* part = _data->multiPartFile->getPart(0); + + multiPartInitialize(part); +} +``` + +### File: OpenEXR/IlmImf/ImfDeepTiledInputFile.cpp +```c +void +DeepTiledInputFile::compatibilityInitialize(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is) +{ + is.seekg(0); + // + // Construct a MultiPartInputFile, initialize TiledInputFile + // with the part 0 data. + // (TODO) maybe change the third parameter of the constructor of MultiPartInputFile later. + // + _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads); + _data->multiPartBackwardSupport = true; + InputPartData* part = _data->multiPartFile->getPart(0); + + multiPartInitialize(part); +} +``` + +### File: OpenEXR/IlmImf/ImfDwaCompressor.cpp +```c +struct DwaCompressor::Classifier +{ + Classifier (std::string suffix, + CompressorScheme scheme, + PixelType type, + int cscIdx, + bool caseInsensitive): + _suffix(suffix), + _scheme(scheme), + _type(type), + _cscIdx(cscIdx), + _caseInsensitive(caseInsensitive) + { + if (caseInsensitive) + std::transform(_suffix.begin(), _suffix.end(), _suffix.begin(), tolower); + } + + Classifier (const char *&ptr, int size) + { + if (size <= 0) + throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" + " (truncated rule)."); + + { + char suffix[Name::SIZE]; + memset (suffix, 0, Name::SIZE); + Xdr::read (ptr, std::min(size, Name::SIZE-1), suffix); + _suffix = std::string(suffix); + } + + if (static_cast(size) < _suffix.length() + 1 + 2*Xdr::size()) + throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" + " (truncated rule)."); + + char value; + Xdr::read (ptr, value); + + _cscIdx = (int)(value >> 4) - 1; + if (_cscIdx < -1 || _cscIdx >= 3) + throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" + " (corrupt cscIdx rule)."); + + _scheme = (CompressorScheme)((value >> 2) & 3); + if (_scheme < 0 || _scheme >= NUM_COMPRESSOR_SCHEMES) + throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" + " (corrupt scheme rule)."); + + _caseInsensitive = (value & 1 ? true : false); + + Xdr::read (ptr, value); + if (value < 0 || value >= NUM_PIXELTYPES) + throw IEX_NAMESPACE::InputExc("Error uncompressing DWA data" + " (corrupt rule)."); + _type = (PixelType)value; + } +``` + +### File: OpenEXR/IlmImf/ImfFastHuf.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2009-2014 DreamWorks Animation LLC. +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of DreamWorks Animation nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + +#include "ImfFastHuf.h" +#include + +#include +#include +#include +#include + +OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER + +// +// Adapted from hufUnpackEncTable - +// We don't need to reconstruct the code book, just the encoded +// lengths for each symbol. From the lengths, we can build the +// base + offset tables. This should be a bit more efficient +// for sparse code books. +// +// table - ptr to the start of the code length data. Will be +// updated as we decode data +// +// numBytes - size of the encoded table (I think)? +// +// minSymbol - smallest symbol in the code book +// +// maxSymbol - largest symbol in the code book. +// +// rleSymbol - the symbol to trigger RLE in the encoded bitstream +// + +FastHufDecoder::FastHufDecoder + (const char *&table, + int numBytes, + int minSymbol, + int maxSymbol, + int rleSymbol) +: + _rleSymbol (rleSymbol), + _numSymbols (0), + _minCodeLength (255), + _maxCodeLength (0), + _idToSymbol (0) +{ + // + // List of symbols that we find with non-zero code lengths + // (listed in the order we find them). Store these in the + // same format as the code book stores codes + lengths - + // low 6 bits are the length, everything above that is + // the symbol. + // + + std::vector symbols; + + // + // The 'base' table is the minimum code at each code length. base[i] + // is the smallest code (numerically) of length i. + // + + Int64 base[MAX_CODE_LEN + 1]; + + // + // The 'offset' table is the position (in sorted order) of the first id + // of a given code lenght. Array is indexed by code length, like base. + // + + Int64 offset[MAX_CODE_LEN + 1]; + + // + // Count of how many codes at each length there are. Array is + // indexed by code length, like base and offset. + // + + size_t codeCount[MAX_CODE_LEN + 1]; + + for (int i = 0; i <= MAX_CODE_LEN; ++i) + { + codeCount[i] = 0; + base[i] = 0xffffffffffffffffULL; + offset[i] = 0; + } + + // + // Count the number of codes, the min/max code lengths, the number of + // codes with each length, and record symbols with non-zero code + // length as we find them. + // + + const char *currByte = table; + Int64 currBits = 0; + int currBitCount = 0; + + const int SHORT_ZEROCODE_RUN = 59; + const int LONG_ZEROCODE_RUN = 63; + const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; + + for (Int64 symbol = static_cast(minSymbol); symbol <= static_cast(maxSymbol); symbol++) + { + if (currByte - table > numBytes) + { + throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table " + "(Truncated table data)."); + } + + // + // Next code length - either: + // 0-58 (literal code length) + // 59-62 (various lengths runs of 0) + // 63 (run of n 0's, with n is the next 8 bits) + // + + Int64 codeLen = readBits (6, currBits, currBitCount, currByte); + + if (codeLen == (Int64) LONG_ZEROCODE_RUN) + { + if (currByte - table > numBytes) + { + throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table " + "(Truncated table data)."); + } + + int runLen = readBits (8, currBits, currBitCount, currByte) + + SHORTEST_LONG_RUN; + + if (symbol + runLen > static_cast(maxSymbol + 1)) + { + throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table " + "(Run beyond end of table)."); + } + + symbol += runLen - 1; + + } + else if (codeLen >= static_cast(SHORT_ZEROCODE_RUN)) + { + int runLen = codeLen - SHORT_ZEROCODE_RUN + 2; + + if (symbol + runLen > static_cast(maxSymbol + 1)) + { + throw IEX_NAMESPACE::InputExc ("Error decoding Huffman table " + "(Run beyond end of table)."); + } + + symbol += runLen - 1; + + } + else if (codeLen != 0) + { + symbols.push_back ((symbol << 6) | (codeLen & 63)); + + if (codeLen < _minCodeLength) + _minCodeLength = codeLen; + + if (codeLen > _maxCodeLength) + _maxCodeLength = codeLen; + + codeCount[codeLen]++; + } + } + + for (int i = 0; i < MAX_CODE_LEN; ++i) + _numSymbols += codeCount[i]; + + table = currByte; + + // + // Compute base - once we have the code length counts, there + // is a closed form solution for this + // + + { + double* countTmp = new double[_maxCodeLength+1]; + + for (int l = _minCodeLength; l <= _maxCodeLength; ++l) + { + countTmp[l] = (double)codeCount[l] * + (double)(2 << (_maxCodeLength-l)); + } + + for (int l = _minCodeLength; l <= _maxCodeLength; ++l) + { + double tmp = 0; + + for (int k =l + 1; k <= _maxCodeLength; ++k) + tmp += countTmp[k]; + + tmp /= (double)(2 << (_maxCodeLength - l)); + + base[l] = (Int64)ceil (tmp); + } + + delete [] countTmp; + } + + // + // Compute offset - these are the positions of the first + // id (not symbol) that has length [i] + // + + offset[_maxCodeLength] = 0; + + for (int i= _maxCodeLength - 1; i >= _minCodeLength; i--) + offset[i] = offset[i + 1] + codeCount[i + 1]; + + // + // Allocate and fill the symbol-to-id mapping. Smaller Ids should be + // mapped to less-frequent symbols (which have longer codes). Use + // the offset table to tell us where the id's for a given code + // length start off. + // + + _idToSymbol = new int[_numSymbols]; + + Int64 mapping[MAX_CODE_LEN + 1]; + for (int i = 0; i < MAX_CODE_LEN + 1; ++i) + mapping[i] = -1; + for (int i = _minCodeLength; i <= _maxCodeLength; ++i) + mapping[i] = + +// ... (14845 more chars) +``` + +### File: OpenEXR/IlmImf/ImfHeader.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas +// Digital Ltd. LLC +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Industrial Light & Magic nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + + + +//----------------------------------------------------------------------------- +// +// class Header +// +//----------------------------------------------------------------------------- + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "IlmThreadMutex.h" +#include "Iex.h" +#include +#include +#include +#include +#include "ImfTiledMisc.h" +#include "ImfNamespace.h" + +OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER + +using namespace std; +using IMATH_NAMESPACE::Box2i; +using IMATH_NAMESPACE::V2i; +using IMATH_NAMESPACE::V2f; +using ILMTHREAD_NAMESPACE::Mutex; +using ILMTHREAD_NAMESPACE::Lock; + + +namespace { + +int maxImageWidth = 0; +int maxImageHeight = 0; +int maxTileWidth = 0; +int maxTileHeight = 0; + + +void +initialize (Header &header, + const Box2i &displayWindow, + const Box2i &dataWindow, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +{ + header.insert ("displayWindow", Box2iAttribute (displayWindow)); + header.insert ("dataWindow", Box2iAttribute (dataWindow)); + if ( !std::isnormal (pixelAspectRatio) || pixelAspectRatio < 0.f) + THROW (IEX_NAMESPACE::ArgExc, "Invalid pixel aspect ratio"); + header.insert ("pixelAspectRatio", FloatAttribute (pixelAspectRatio)); + header.insert ("screenWindowCenter", V2fAttribute (screenWindowCenter)); + header.insert ("screenWindowWidth", FloatAttribute (screenWindowWidth)); + header.insert ("lineOrder", LineOrderAttribute (lineOrder)); + header.insert ("compression", CompressionAttribute (compression)); + header.insert ("channels", ChannelListAttribute ()); +} + +template +void checkIsNullTerminated (const char (&str)[N], const char *what) +{ + for (size_t i = 0; i < N; ++i) { + if (str[i] == '\0') + return; + } + std::stringstream s; + s << "Invalid " << what << ": it is more than " << (N - 1) + << " characters long."; + throw IEX_NAMESPACE::InputExc(s); +} + +} // namespace + + +Header::Header (int width, + int height, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +: + _map() +{ + staticInitialize(); + + Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1)); + + initialize (*this, + displayWindow, + displayWindow, + pixelAspectRatio, + screenWindowCenter, + screenWindowWidth, + lineOrder, + compression); +} + + +Header::Header (int width, + int height, + const Box2i &dataWindow, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +: + _map() +{ + staticInitialize(); + + Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1)); + + initialize (*this, + displayWindow, + dataWindow, + pixelAspectRatio, + screenWindowCenter, + screenWindowWidth, + lineOrder, + compression); +} + + +Header::Header (const Box2i &displayWindow, + const Box2i &dataWindow, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +: + _map() +{ + staticInitialize(); + + initialize (*this, + displayWindow, + dataWindow, + pixelAspectRatio, + screenWindowCenter, + screenWindowWidth, + lineOrder, + compression); +} + + +Header::Header (const Header &other): _map() +{ + for (AttributeMap::const_iterator i = other._map.begin(); + i != other._map.end(); + ++i) + { + insert (*i->first, *i->second); + } +} + + +Header::~Header () +{ + for (AttributeMap::iterator i = _map.begin(); + i != _map.end(); + ++i) + { + delete i->second; + } +} + + +Header & +Header::operator = (const Header &other) +{ + if (this != &other) + { + for (AttributeMap::iterator i = _map.begin(); + i != _map.end(); + ++i) + { + delete i->second; + } + + _map.erase (_map.begin(), _map.end()); + + for (AttributeMap::const_iterator i = other._map.begin(); + i != other._map.end(); + ++i) + { + insert (*i->first, *i->second); + } + } + + return *this; +} + + +void +Header::erase (const char name[]) +{ + if (name[0] == 0) + THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string."); + + + AttributeMap::iterator i = _map.find (name); + if (i != _map.end()) + _map.erase (i); + +} + + +void +Header::erase (const string &name) +{ + erase (name.c_str()); +} + + +void +Header::insert (const char name[], const Attribute &attribute) +{ + if (name[0] == 0) + THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string."); + + AttributeMap::iterator i = _map.find (name); + + if (i == _map.end()) + { + Attribute *tmp = attribute.copy(); + + try + { + _map[name] = tmp; + } + catch (...) + { + delete tmp; + throw; + } + } + else + { + if (strcmp (i->second->typeName(), attribute.typeName())) + THROW (IEX_NAMESPACE::TypeExc, "Cannot assign a value of " + "type \"" << attribute.typeName() << "\" " + "to image attribute \"" << name << "\" of " + "type \"" << i->second->typeName() << "\"."); + + Attribute *tmp = attribute.copy(); + delete i->second; + i->second = tmp; + } +} + + +void +Header::insert (const string &name, const Attribute &attribute) +{ + insert (name.c_str(), attribute); +} + + +Attribute & +Header::operator [] (const char name[]) +{ + AttributeMap::iterator i = _map.find (name); + + if (i = + +// ... (22549 more chars) +``` + +### File: OpenEXR/IlmImf/ImfHuf.cpp +```c +void +hufUncompress (const char compressed[], + int nCompressed, + unsigned short raw[], + int nRaw) +{ + if (nCompressed == 0) + { + if (nRaw != 0) + notEnoughData(); + + return; + } + + int im = readUInt (compressed); + int iM = readUInt (compressed + 4); + // int tableLength = readUInt (compressed + 8); + int nBits = readUInt (compressed + 12); + + if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) + invalidTableSize(); + + const char *ptr = compressed + 20; + + // + // Fast decoder needs at least 2x64-bits of compressed data, and + // needs to be run-able on this platform. Otherwise, fall back + // to the original decoder + // + + if (FastHufDecoder::enabled() && nBits > 128) + { + FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM); + fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw); + } + else + { + AutoArray freq; + AutoArray hdec; + + hufClearDecTable (hdec); + + hufUnpackEncTable (&ptr, + nCompressed - (ptr - compressed), + im, + iM, + freq); + + try + { + if (nBits > 8 * (nCompressed - (ptr - compressed))) + invalidNBits(); + + hufBuildDecTable (freq, im, iM, hdec); + hufDecode (freq, hdec, ptr, nBits, iM, nRaw, raw); + } + catch (...) + { + hufFreeDecTable (hdec); + throw; + } + + hufFreeDecTable (hdec); + } +} +``` + +### File: OpenEXR/IlmImf/ImfInputFile.cpp +```c +void +InputFile::compatibilityInitialize (OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is) +{ + is.seekg(0); + + // + // Construct a MultiPartInputFile, initialize InputFile + // with the part 0 data. + // (TODO) may want to have a way to set the reconstruction flag. + // + _data->multiPartBackwardSupport = true; + _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads); + InputPartData* part = _data->multiPartFile->getPart(0); + + multiPartInitialize (part); +} +``` + +### File: OpenEXR/IlmImf/ImfMisc.cpp +```c +size_t +bytesPerLineTable (const Header &header, + vector &bytesPerLine) +{ + const Box2i &dataWindow = header.dataWindow(); + const ChannelList &channels = header.channels(); + + bytesPerLine.resize (dataWindow.max.y - dataWindow.min.y + 1); + + for (ChannelList::ConstIterator c = channels.begin(); + c != channels.end(); + ++c) + { + int nBytes = pixelTypeSize (c.channel().type) * + (dataWindow.max.x - dataWindow.min.x + 1) / + c.channel().xSampling; + + for (int y = dataWindow.min.y, i = 0; y <= dataWindow.max.y; ++y, ++i) + if (modp (y, c.channel().ySampling) == 0) + bytesPerLine[i] += nBytes; + } + + size_t maxBytesPerLine = 0; + + for (int y = dataWindow.min.y, i = 0; y <= dataWindow.max.y; ++y, ++i) + if (maxBytesPerLine < bytesPerLine[i]) + maxBytesPerLine = bytesPerLine[i]; + + return maxBytesPerLine; +} + +int +numLinesInBuffer (Compressor * compressor) +{ + return compressor? compressor->numScanLines(): 1; +} + +bool +usesLongNames (const Header &header) +{ + // + // If an OpenEXR file contains any attribute names, attribute type names + // or channel names longer than 31 characters, then the file cannot be + // read by older versions of the IlmImf library (up to OpenEXR 1.6.1). + // Before writing the file header, we check if the header contains + // any names longer than 31 characters; if it does, then we set the + // LONG_NAMES_FLAG in the file version number. Older versions of the + // IlmImf library will refuse to read files that have the LONG_NAMES_FLAG + // set. Without the flag, older versions of the library would mis- + // interpret the file as broken. + // + + for (Header::ConstIterator i = header.begin(); + i != header.end(); + ++i) + { + if (strlen (i.name()) >= 32 || strlen (i.attribute().typeName()) >= 32) + return true; + } + + const ChannelList &channels = header.channels(); + + for (ChannelList::ConstIterator i = channels.begin(); + i != channels.end(); + ++i) + { + if (strlen (i.name()) >= 32) + return true; + } + + return false; +} + +int +getScanlineChunkOffsetTableSize(const Header& header) +{ + const Box2i &dataWindow = header.dataWindow(); + + vector bytesPerLine; + size_t maxBytesPerLine = bytesPerLineTable (header, + bytesPerLine); + + Compressor* compressor = newCompressor(header.compression(), + maxBytesPerLine, + header); + + int linesInBuffer = numLinesInBuffer (compressor); + + int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y + + linesInBuffer) / linesInBuffer; + + delete compressor; + + return lineOffsetSize; +} +``` + +### File: OpenEXR/IlmImf/ImfPizCompressor.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas +// Digital Ltd. LLC +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Industrial Light & Magic nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + + +//----------------------------------------------------------------------------- +// +// class PizCompressor +// +//----------------------------------------------------------------------------- + +#include "ImfPizCompressor.h" +#include "ImfHeader.h" +#include "ImfChannelList.h" +#include "ImfHuf.h" +#include "ImfWav.h" +#include "ImfMisc.h" +#include "ImfCheckedArithmetic.h" +#include +#include +#include +#include "ImfIO.h" +#include "ImfXdr.h" +#include "ImfAutoArray.h" +#include +#include +#include "ImfNamespace.h" + +OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER + +using IMATH_NAMESPACE::divp; +using IMATH_NAMESPACE::modp; +using IMATH_NAMESPACE::Box2i; +using IMATH_NAMESPACE::V2i; +using IEX_NAMESPACE::InputExc; + +namespace { + +// +// Functions to compress the range of values in the pixel data +// + +const int USHORT_RANGE = (1 << 16); +const int BITMAP_SIZE = (USHORT_RANGE >> 3); + +void +bitmapFromData (const unsigned short data[/*nData*/], + int nData, + unsigned char bitmap[BITMAP_SIZE], + unsigned short &minNonZero, + unsigned short &maxNonZero) +{ + for (int i = 0; i < BITMAP_SIZE; ++i) + bitmap[i] = 0; + + for (int i = 0; i < nData; ++i) + bitmap[data[i] >> 3] |= (1 << (data[i] & 7)); + + bitmap[0] &= ~1; // zero is not explicitly stored in + // the bitmap; we assume that the + // data always contain zeroes + minNonZero = BITMAP_SIZE - 1; + maxNonZero = 0; + + for (int i = 0; i < BITMAP_SIZE; ++i) + { + if (bitmap[i]) + { + if (minNonZero > i) + minNonZero = i; + if (maxNonZero < i) + maxNonZero = i; + } + } +} + + +unsigned short +forwardLutFromBitmap (const unsigned char bitmap[BITMAP_SIZE], + unsigned short lut[USHORT_RANGE]) +{ + int k = 0; + + for (int i = 0; i < USHORT_RANGE; ++i) + { + if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) + lut[i] = k++; + else + lut[i] = 0; + } + + return k - 1; // maximum value stored in lut[], +} // i.e. number of ones in bitmap minus 1 + + +unsigned short +reverseLutFromBitmap (const unsigned char bitmap[BITMAP_SIZE], + unsigned short lut[USHORT_RANGE]) +{ + int k = 0; + + for (int i = 0; i < USHORT_RANGE; ++i) + { + if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) + lut[k++] = i; + } + + int n = k - 1; + + while (k < USHORT_RANGE) + lut[k++] = 0; + + return n; // maximum k where lut[k] is non-zero, +} // i.e. number of ones in bitmap minus 1 + + +void +applyLut (const unsigned short lut[USHORT_RANGE], + unsigned short data[/*nData*/], + int nData) +{ + for (int i = 0; i < nData; ++i) + data[i] = lut[data[i]]; +} + + +} // namespace + + +struct PizCompressor::ChannelData +{ + unsigned short * start; + unsigned short * end; + int nx; + int ny; + int ys; + int size; +}; + + +PizCompressor::PizCompressor + (const Header &hdr, + size_t maxScanLineSize, + size_t numScanLines) +: + Compressor (hdr), + _maxScanLineSize (maxScanLineSize), + _format (XDR), + _numScanLines (numScanLines), + _tmpBuffer (0), + _outBuffer (0), + _numChans (0), + _channels (hdr.channels()), + _channelData (0) +{ + // TODO: Remove this when we can change the ABI + (void) _maxScanLineSize; + size_t tmpBufferSize = uiMult (maxScanLineSize, numScanLines) / 2; + + size_t outBufferSize = + uiAdd (uiMult (maxScanLineSize, numScanLines), + size_t (65536 + 8192)); + + _tmpBuffer = new unsigned short + [checkArraySize (tmpBufferSize, sizeof (unsigned short))]; + + _outBuffer = new char [outBufferSize]; + + const ChannelList &channels = header().channels(); + bool onlyHalfChannels = true; + + for (ChannelList::ConstIterator c = channels.begin(); + c != channels.end(); + ++c) + { + _numChans++; + + assert (pixelTypeSize (c.channel().type) % pixelTypeSize (HALF) == 0); + + if (c.channel().type != HALF) + onlyHalfChannels = false; + } + + _channelData = new ChannelData[_numChans]; + + const Box2i &dataWindow = hdr.dataWindow(); + + _minX = dataWindow.min.x; + _maxX = dataWindow.max.x; + _maxY = dataWindow.max.y; + + // + // We can support uncompressed data in the machine's native format + // if all image channels are of type HALF, and if the Xdr and the + // native represenations of a half have the same size. + // + + if (onlyHalfChannels && (sizeof (half) == pixelTypeSize (HALF))) + _format = NATIVE; +} + + +PizCompressor::~PizCompressor () +{ + delete [] _tmpBuffer; + delete [] _outBuffer; + delete [] _channelData; +} + + +int +PizCompressor::numScanLines () const +{ + return _numScanLines; +} + + +Compressor::Format +PizCompressor::format () const +{ + return _format; +} + + +int +PizCompressor::compress (const char *inPtr, + int inSize, + int minY, + const char *&outPtr) +{ + return compress (inPtr, + inSize, + Box2i (V2i (_minX, minY), + V2i (_maxX, minY + numScanLines() - 1)), + outPtr); +} + + +int +PizCompressor::compressTile (const char *inPtr, + int inSize, + IMATH_NAMESPACE::Box2i range, + const char *&outPtr) +{ + return compress (inPtr, inSize, range, outPtr); +} + + +int +PizCompressor::uncompress (const char *inPtr, + int inSize, + int minY, + const char *&outPtr) +{ + return uncompress (inPtr, + inSize, + Box2i (V2i (_minX, minY), + V2i (_maxX, minY + numScanLines() - 1)), + outPtr); +} + + +int +PizCompressor::uncompressTile (const char *inPtr, + int inSize, + IMATH_NAMESPACE::Box2i range, + const char *&outPtr) +{ + return uncompress (inPtr, inSize, range, outPtr); +} + + +int +PizCompressor::compress (const char *inPtr, + int inSize, + IMATH_NAMESPACE::Box2i range, + const char *&outPtr) +{ + // + // This is the compress function which is used by both the tiled and + // scanline compression routines. + // + + // + // Special case �- empty input buffer + // + + if (inSize == 0) + { + outPtr = _outBuffer; + return 0; + } + + // + // Rearrange the pixel data so that the wavelet + // and Huffman encoders can process them easily. + // + // The wavelet and Huffman encoders both handle only + // 16-bit data, so 32-bit data must be split into smaller + // pieces. We treat each 32-bit ch + +// ... (6963 more chars) +``` + +### File: OpenEXR/IlmImf/ImfRle.cpp +```c +int +rleUncompress (int inLength, int maxLength, const signed char in[], char out[]) +{ + char *outStart = out; + + while (inLength > 0) + { + if (*in < 0) + { + int count = -((int)*in++); + inLength -= count + 1; + + if (0 > (maxLength -= count)) + return 0; + + memcpy(out, in, count); + out += count; + in += count; + } + else + { + int count = *in++; + inLength -= 2; + + if (0 > (maxLength -= count + 1)) + return 0; + + memset(out, *(char*)in, count+1); + out += count+1; + + in++; + } + } + + return out - outStart; +} +``` + +### File: OpenEXR/IlmImf/ImfScanLineInputFile.cpp +```c +void ScanLineInputFile::initialize(const Header& header) +{ + try + { + _data->header = header; + + _data->lineOrder = _data->header.lineOrder(); + + const Box2i &dataWindow = _data->header.dataWindow(); + + _data->minX = dataWindow.min.x; + _data->maxX = dataWindow.max.x; + _data->minY = dataWindow.min.y; + _data->maxY = dataWindow.max.y; + + size_t maxBytesPerLine = bytesPerLineTable (_data->header, + _data->bytesPerLine); + + for (size_t i = 0; i < _data->lineBuffers.size(); i++) + { + _data->lineBuffers[i] = new LineBuffer (newCompressor + (_data->header.compression(), + maxBytesPerLine, + _data->header)); + } + + _data->linesInBuffer = + numLinesInBuffer (_data->lineBuffers[0]->compressor); + + _data->lineBufferSize = maxBytesPerLine * _data->linesInBuffer; + + if (!_streamData->is->isMemoryMapped()) + { + for (size_t i = 0; i < _data->lineBuffers.size(); i++) + { + _data->lineBuffers[i]->buffer = (char *) EXRAllocAligned(_data->lineBufferSize*sizeof(char),16); + } + } + _data->nextLineBufferMinY = _data->minY - 1; + + offsetInLineBufferTable (_data->bytesPerLine, + _data->linesInBuffer, + _data->offsetInLineBuffer); + + int lineOffsetSize = (dataWindow.max.y - dataWindow.min.y + + _data->linesInBuffer) / _data->linesInBuffer; + + _data->lineOffsets.resize (lineOffsetSize); + } + catch (...) + { + delete _data; + _data=NULL; + throw; + } +} + +void +ScanLineInputFile::setFrameBuffer (const FrameBuffer &frameBuffer) +{ + Lock lock (*_streamData); + + + + const ChannelList &channels = _data->header.channels(); + for (FrameBuffer::ConstIterator j = frameBuffer.begin(); + j != frameBuffer.end(); + ++j) + { + ChannelList::ConstIterator i = channels.find (j.name()); + + if (i == channels.end()) + continue; + + if (i.channel().xSampling != j.slice().xSampling || + i.channel().ySampling != j.slice().ySampling) + THROW (IEX_NAMESPACE::ArgExc, "X and/or y subsampling factors " + "of \"" << i.name() << "\" channel " + "of input file \"" << fileName() << "\" are " + "not compatible with the frame buffer's " + "subsampling factors."); + } + + // optimization is possible if this is a little endian system + // and both inputs and outputs are half floats + // + bool optimizationPossible = true; + + if (!GLOBAL_SYSTEM_LITTLE_ENDIAN) + { + optimizationPossible =false; + } + + vector optData; + + + // + // Initialize the slice table for readPixels(). + // + + vector slices; + ChannelList::ConstIterator i = channels.begin(); + + // current offset of channel: pixel data starts at offset*width into the + // decompressed scanline buffer + size_t offset = 0; + + for (FrameBuffer::ConstIterator j = frameBuffer.begin(); + j != frameBuffer.end(); + ++j) + { + while (i != channels.end() && strcmp (i.name(), j.name()) < 0) + { + // + // Channel i is present in the file but not + // in the frame buffer; data for channel i + // will be skipped during readPixels(). + // + + slices.push_back (InSliceInfo (i.channel().type, + i.channel().type, + 0, // base + 0, // xStride + 0, // yStride + i.channel().xSampling, + i.channel().ySampling, + false, // fill + true, // skip + 0.0)); // fillValue + + switch(i.channel().type) + { + case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF : + offset++; + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT : + offset+=2; + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT : + offset+=2; + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::NUM_PIXELTYPES: + default: + // not possible. + break; + } + ++i; + } + + bool fill = false; + + if (i == channels.end() || strcmp (i.name(), j.name()) > 0) + { + // + // Channel i is present in the frame buffer, but not in the file. + // In the frame buffer, slice j will be filled with a default value. + // + + fill = true; + } + + slices.push_back (InSliceInfo (j.slice().type, + fill? j.slice().type: + i.channel().type, + j.slice().base, + j.slice().xStride, + j.slice().yStride, + j.slice().xSampling, + j.slice().ySampling, + fill, + false, // skip + j.slice().fillValue)); + + if(!fill && i.channel().type!=OPENEXR_IMF_INTERNAL_NAMESPACE::HALF) + { + optimizationPossible = false; + } + + if(j.slice().type != OPENEXR_IMF_INTERNAL_NAMESPACE::HALF) + { + optimizationPossible = false; + } + if(j.slice().xSampling!=1 || j.slice().ySampling!=1) + { + optimizationPossible = false; + } + + + if(optimizationPossible) + { + sliceOptimizationData dat; + dat.base = j.slice().base; + dat.fill = fill; + dat.fillValue = j.slice().fillValue; + dat.offset = offset; + dat.xStride = j.slice().xStride; + dat.yStride = j.slice().yStride; + dat.xSampling = j.slice().xSampling; + dat.ySampling = j.slice().ySampling; + optData.push_back(dat); + } + + if(!fill) + { + switch(i.channel().type) + { + case OPENEXR_IMF_INTERNAL_NAMESPACE::HALF : + offset++; + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::FLOAT : + offset+=2; + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::UINT : + offset+=2; + break; + case OPENEXR_IMF_INTERNAL_NAMESPACE::NUM_PIXELTYPES: + default: + // not possible. + break; + } + } + + + + if (i != channels.end() && !fill) + ++i; + } + + + if(optimizationPossible) + { + // + // check optimisibility + // based on channel ordering and fill channel positions + // + sort(optData.begin(),optData.end()); + _data->optimizationMode = detectOptimizationMode(optData); + } + + if(!optimizationPossible || _data->optimizationMode._optimizable==false) + { + optData = vector(); + _data->optimizationMode._optimizable=false; + } + + // + // Store the new frame buffer. + // + + _data->frameBuffer = frameBuffer; + _data->slices = slices; + _data->optimizationData = optData; +} +``` + +### File: OpenEXR/IlmImf/ImfTiledInputFile.cpp +```c +void +TiledInputFile::compatibilityInitialize(OPENEXR_IMF_INTERNAL_NAMESPACE::IStream& is) +{ + is.seekg(0); + // + // Construct a MultiPartInputFile, initialize TiledInputFile + // with the part 0 data. + // (TODO) maybe change the third parameter of the constructor of MultiPartInputFile later. + // + _data->multiPartBackwardSupport = true; + _data->multiPartFile = new MultiPartInputFile(is, _data->numThreads); + InputPartData* part = _data->multiPartFile->getPart(0); + + multiPartInitialize(part); +} +``` + +### File: OpenEXR/IlmImf/ImfTiledMisc.cpp +```c +int +getTiledChunkOffsetTableSize(const Header& header) +{ + // + // Save the dataWindow information + // + + const Box2i &dataWindow = header.dataWindow(); + + // + // Precompute level and tile information. + // + + int* numXTiles; + int* numYTiles; + int numXLevels; + int numYLevels; + precalculateTileInfo (header.tileDescription(), + dataWindow.min.x, dataWindow.max.x, + dataWindow.min.y, dataWindow.max.y, + numXTiles, numYTiles, + numXLevels, numYLevels); + + // + // Calculate lineOffsetSize. + // + Int64 lineOffsetSize = 0; + const TileDescription &desc = header.tileDescription(); + switch (desc.mode) + { + case ONE_LEVEL: + case MIPMAP_LEVELS: + for (int i = 0; i < numXLevels; i++) + { + lineOffsetSize += static_cast(numXTiles[i]) * static_cast(numYTiles[i]); + if ( lineOffsetSize > static_cast(std::numeric_limits::max()) ) + { + throw IEX_NAMESPACE::LogicExc("Maximum number of tiles exceeded"); + } + } + break; + case RIPMAP_LEVELS: + for (int i = 0; i < numXLevels; i++) + { + for (int j = 0; j < numYLevels; j++) + { + lineOffsetSize += static_cast(numXTiles[i]) * static_cast(numYTiles[j]); + if ( lineOffsetSize > static_cast(std::numeric_limits::max()) ) + { + throw IEX_NAMESPACE::LogicExc("Maximum number of tiles exceeded"); + } + } + } + break; + case NUM_LEVELMODES : + throw IEX_NAMESPACE::LogicExc("Bad level mode getting chunk offset table size"); + } + + delete[] numXTiles; + delete[] numYTiles; + + return static_cast(lineOffsetSize); +} +``` + +### File: OpenEXR/IlmImfTest/testDeepTiledBasic.cpp +```c +void readFile (int channelCount, + bool bulkRead, + bool relativeCoords, + bool randomChannels, + const std::string & filename) +{ + if (relativeCoords) + assert(bulkRead == false); + + cout << "reading " << flush; + + DeepTiledInputFile file (filename.c_str(), 4); + + const Header& fileHeader = file.header(); + assert (fileHeader.displayWindow() == header.displayWindow()); + assert (fileHeader.dataWindow() == header.dataWindow()); + assert (fileHeader.pixelAspectRatio() == header.pixelAspectRatio()); + assert (fileHeader.screenWindowCenter() == header.screenWindowCenter()); + assert (fileHeader.screenWindowWidth() == header.screenWindowWidth()); + assert (fileHeader.lineOrder() == header.lineOrder()); + assert (fileHeader.compression() == header.compression()); + assert (fileHeader.channels() == header.channels()); + assert (fileHeader.type() == header.type()); + assert (fileHeader.tileDescription() == header.tileDescription()); + + Array2D localSampleCount; + localSampleCount.resizeErase(height, width); + + // also test filling channels. Generate up to 2 extra channels + int fillChannels=random_int(3); + + Array > data(channelCount+fillChannels); + for (int i = 0; i < channelCount+fillChannels; i++) + data[i].resizeErase(height, width); + + DeepFrameBuffer frameBuffer; + + int memOffset; + if (relativeCoords) + memOffset = 0; + else + memOffset = dataWindow.min.x + dataWindow.min.y * width; + frameBuffer.insertSampleCountSlice (Slice (IMF::UINT, + (char *) (&localSampleCount[0][0] - memOffset), + sizeof (unsigned int) * 1, + sizeof (unsigned int) * width, + 1, 1, + 0, + relativeCoords, + relativeCoords)); + + + vector read_channel(channelCount); + int channels_added=0; + for (int i = 0; i < channelCount; i++) + { + if(randomChannels) + { + read_channel[i] = random_int(2); + + } + if(!randomChannels || read_channel[i]==1) + { + PixelType type = IMF::NUM_PIXELTYPES; + if (channelTypes[i] == 0) + type = IMF::UINT; + if (channelTypes[i] == 1) + type = IMF::HALF; + if (channelTypes[i] == 2) + type = IMF::FLOAT; + + stringstream ss; + ss << i; + string str = ss.str(); + + int sampleSize = 0; + if (channelTypes[i] == 0) sampleSize = sizeof (unsigned int); + if (channelTypes[i] == 1) sampleSize = sizeof (half); + if (channelTypes[i] == 2) sampleSize = sizeof (float); + + int pointerSize = sizeof (char *); + + frameBuffer.insert (str, + DeepSlice (type, + (char *) (&data[i][0][0] - memOffset), + pointerSize * 1, + pointerSize * width, + sampleSize, + 1, 1, + 0, + relativeCoords, + relativeCoords)); + channels_added++; + } + } + if(channels_added==0) + { + cout << "skipping " < +#include +#include +#include +#include +#include + +#include "tmpDir.h" +#include "testMultiPartApi.h" +#include "random.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace IMF = OPENEXR_IMF_NAMESPACE; +using namespace IMF; +using namespace std; +using namespace IMATH_NAMESPACE; + +namespace +{ + +const int height = 263; +const int width = 197; + +struct Task +{ + int partNumber; + int tx, ty, lx, ly; + + Task(int partNumber): + partNumber(partNumber) + {} + + Task(int partNumber, int tx, int ty, int lx, int ly): + partNumber(partNumber), + tx(tx), + ty(ty), + lx(lx), + ly(ly) + {} +}; + +vector
headers; +vector pixelTypes; +vector partTypes; +vector levelModes; + +template +void fillPixels (Array2D &ph, int width, int height) +{ + ph.resizeErase(height, width); + for (int y = 0; y < height; ++y) + for (int x = 0; x < width; ++x) + { + // + // We do this because half cannot store number bigger than 2048 exactly. + // + ph[y][x] = (y * width + x) % 2049; + } +} + +template +bool checkPixels (Array2D &ph, int lx, int rx, int ly, int ry, int width) +{ + for (int y = ly; y <= ry; ++y) + for (int x = lx; x <= rx; ++x) + if (ph[y][x] != static_cast(((y * width + x) % 2049))) + { + cout << "value at " << x << ", " << y << ": " << ph[y][x] + << ", should be " << (y * width + x) % 2049 << endl << flush; + return false; + } + return true; +} + +template +bool checkPixels (Array2D &ph, int width, int height) +{ + return checkPixels (ph, 0, width - 1, 0, height - 1, width); +} + +void generateRandomHeaders(int partCount, vector
& headers, vector& taskList) +{ + headers.clear(); + for (int i = 0; i < partCount; i++) + { + Header header(width, height); + int pixelType = random_int(3); + int partType = random_int(2); + pixelTypes[i] = pixelType; + partTypes[i] = partType; + + stringstream ss; + ss << i; + header.setName(ss.str()); + + switch (pixelType) + { + case 0: + header.channels().insert("UINT", Channel(IMF::UINT)); + break; + case 1: + header.channels().insert("FLOAT", Channel(IMF::FLOAT)); + break; + case 2: + header.channels().insert("HALF", Channel(IMF::HALF)); + break; + } + + switch (partType) + { + case 0: + header.setType(SCANLINEIMAGE); + break; + case 1: + header.setType(TILEDIMAGE); + break; + } + + int tileX; + int tileY; + int levelMode = 0; + if (partType == 1) + { + tileX = random_int(width) + 1; + tileY = random_int(height) + 1; + levelMode = random_int(3); + levelModes[i] = levelMode; + LevelMode lm = NUM_LEVELMODES; + switch (levelMode) + { + case 0: + lm = ONE_LEVEL; + break; + case 1: + lm = MIPMAP_LEVELS; + break; + case 2: + lm = RIPMAP_LEVELS; + break; + } + header.setTileDescription(TileDescription(tileX, tileY, lm)); + } + + // + // Add lines or tiles to task list. + // + if (partType == 0) + { + for (int j = 0; j < height; j++) + taskList.push_back(Task(i)); + } + else + { + int numXLevel; + int numYLevel; + int* numXTiles; + int* numYTiles; + precalculateTileInfo (header.tileDescription(), + 0, width - 1, + 0, height - 1, + numXTiles, numYTiles, + numXLevel, numYLevel); + + for (int lx = 0; lx < numXLevel; lx++) + for (int ly = 0; ly < numYLevel; ly++) + { + if (levelMode == 1) + if (lx != ly) continue; + + // Get all tasks for this level. + for (int tx = 0; tx < numXTiles[lx]; tx++) + for (int ty = 0; ty < numYTiles[ly]; ty++) + taskList.push_back(Task(i, tx, ty, lx, ly)); + } + + delete[] numXTiles; + delete[] numYTiles; + } + +// if (partType == 0) +// { +// cout << "pixelType = " << pixelType << " partType = " << partType +// << endl << flush; +// } +// else +// { +// cout << "pixelType = " << pixelType << " partType = " << partType +// << " levelMode = " << levelModes[i] << endl << flush; +// } + + headers.push_back(header); + } +} + +void setOutputFrameBuffer(FrameBuffer& frameBuffer, int pixelType, + Array2D& uData, Array2D& fData, + Array2D& hData, int width) +{ + switch (pixelType) + { + case 0: + frameBuffer.insert ("UINT", + Slice (IMF::UINT, + (char *) (&uData[0][0]), + sizeof (uData[0][0]) * 1, + sizeof (uData[0][0]) * width)); + break; + case 1: + frameBuffer.insert ("FLOAT", + Slice (IMF::FLOAT, + + +// ... (16431 more chars) +``` + +### File: OpenEXR/IlmImfTest/testMultiPartThreading.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2011, Industrial Light & Magic, a division of Lucas +// Digital Ltd. LLC +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Industrial Light & Magic nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + +#ifdef NDEBUG +# undef NDEBUG +#endif + +#include +#include +#include +#include +#include +#include + +#include "tmpDir.h" +#include "testMultiPartThreading.h" +#include "random.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace IMF = OPENEXR_IMF_NAMESPACE; +using namespace IMF; +using namespace std; +using namespace IMATH_NAMESPACE; +using namespace ILMTHREAD_NAMESPACE; + +namespace +{ + +const int height = 263; +const int width = 197; + +vector
headers; +vector pixelTypes; +vector partTypes; +vector levelModes; + +Mutex mutexes[200]; + +template +void fillPixels (Array2D &ph, int width, int height) +{ + ph.resizeErase(height, width); + for (int y = 0; y < height; ++y) + for (int x = 0; x < width; ++x) + { + // + // We do this because half cannot store number bigger than 2048 exactly. + // + ph[y][x] = (y * width + x) % 2049; + } +} + +template +bool checkPixels (Array2D &ph, int lx, int rx, int ly, int ry, int width) +{ + for (int y = ly; y <= ry; ++y) + for (int x = lx; x <= rx; ++x) + if (ph[y][x] != static_cast(((y * width + x) % 2049))) + { + cout << "value at " << x << ", " << y << ": " << ph[y][x] + << ", should be " << (y * width + x) % 2049 << endl << flush; + return false; + } + return true; +} + +template +bool checkPixels (Array2D &ph, int width, int height) +{ + return checkPixels (ph, 0, width - 1, 0, height - 1, width); +} + +void setOutputFrameBuffer(FrameBuffer& frameBuffer, int pixelType, + Array2D& uData, Array2D& fData, + Array2D& hData, int width) +{ + switch (pixelType) + { + case 0: + frameBuffer.insert ("UINT", + Slice (IMF::UINT, + (char *) (&uData[0][0]), + sizeof (uData[0][0]) * 1, + sizeof (uData[0][0]) * width)); + break; + case 1: + frameBuffer.insert ("FLOAT", + Slice (IMF::FLOAT, + (char *) (&fData[0][0]), + sizeof (fData[0][0]) * 1, + sizeof (fData[0][0]) * width)); + break; + case 2: + frameBuffer.insert ("HALF", + Slice (IMF::HALF, + (char *) (&hData[0][0]), + sizeof (hData[0][0]) * 1, + sizeof (hData[0][0]) * width)); + break; + } +} + +void setInputFrameBuffer(FrameBuffer& frameBuffer, int pixelType, + Array2D& uData, Array2D& fData, + Array2D& hData, int width, int height) +{ + switch (pixelType) + { + case 0: + uData.resizeErase(height, width); + frameBuffer.insert ("UINT", + Slice (IMF::UINT, + (char *) (&uData[0][0]), + sizeof (uData[0][0]) * 1, + sizeof (uData[0][0]) * width, + 1, 1, + 0)); + break; + case 1: + fData.resizeErase(height, width); + frameBuffer.insert ("FLOAT", + Slice (IMF::FLOAT, + (char *) (&fData[0][0]), + sizeof (fData[0][0]) * 1, + sizeof (fData[0][0]) * width, + 1, 1, + 0)); + break; + case 2: + hData.resizeErase(height, width); + frameBuffer.insert ("HALF", + Slice (IMF::HALF, + (char *) (&hData[0][0]), + sizeof (hData[0][0]) * 1, + sizeof (hData[0][0]) * width, + 1, 1, + 0)); + break; + } +} + +struct WritingTaskData +{ + int partNumber; + int tx, ty, lx, ly; + + WritingTaskData(int partNumber): + partNumber(partNumber) + {} + + WritingTaskData(int partNumber, int tx, int ty, int lx, int ly): + partNumber(partNumber), + tx(tx), + ty(ty), + lx(lx), + ly(ly) + {} +}; + +class WritingTask: public Task +{ + public: + WritingTask (TaskGroup *group, MultiPartOutputFile* file, vector data, + Array2D* tiledFrameBuffers): + Task(group), + file(file), + data(data), + tiledFrameBuffers(tiledFrameBuffers) + {} + + void execute() + { + for (size_t i = 0; i < data.size(); i++) + { + int partNumber = data[i]->partNumber; + int partType = partTypes[partNumber]; + + if (partType == 0) + { + OutputPart part(*file, partNumber); + part.writePixels(); + } + else + { + int tx = data[i]->tx; + int ty = data[i]->ty; + int lx = data[i]->lx; + int ly = data[i]->ly; + TiledOutputPart part(*file, partNumber); + + // + // We add lock here to assure that two threads that accessing + // the same part won't mess things up. + + +// ... (19261 more chars) +``` + +### File: OpenEXR/exrmakepreview/makePreview.cpp +```c +void +generatePreview (const char inFileName[], + float exposure, + int previewWidth, + int &previewHeight, + Array2D &previewPixels) +{ + // + // Read the input file + // + + RgbaInputFile in (inFileName); + + Box2i dw = in.dataWindow(); + float a = in.pixelAspectRatio(); + int w = dw.max.x - dw.min.x + 1; + int h = dw.max.y - dw.min.y + 1; + + Array2D pixels (h, w); + in.setFrameBuffer (ComputeBasePointer (&pixels[0][0], dw), 1, w); + in.readPixels (dw.min.y, dw.max.y); + + // + // Make a preview image + // + + previewHeight = max (int (h / (w * a) * previewWidth + .5f), 1); + previewPixels.resizeErase (previewHeight, previewWidth); + + float fx = (previewWidth > 1)? (float (w - 1) / (previewWidth - 1)): 1; + float fy = (previewHeight > 1)? (float (h - 1) / (previewHeight - 1)): 1; + float m = Math::pow (2.f, IMATH_NAMESPACE::clamp (exposure + 2.47393f, -20.f, 20.f)); + + for (int y = 0; y < previewHeight; ++y) + { + for (int x = 0; x < previewWidth; ++x) + { + PreviewRgba &preview = previewPixels[y][x]; + const Rgba &pixel = pixels[int (y * fy + .5f)][int (x * fx + .5f)]; + + preview.r = gamma (pixel.r, m); + preview.g = gamma (pixel.g, m); + preview.b = gamma (pixel.b, m); + preview.a = int (IMATH_NAMESPACE::clamp (pixel.a * 255.f, 0.f, 255.f) + .5f); + } + } +} +``` diff --git a/tasks/csa159/pair_136251/task_prompt.md b/tasks/csa159/pair_136251/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..99fa3674f0c7bc0c4c38d9fe7b0d94fca261ad1a --- /dev/null +++ b/tasks/csa159/pair_136251/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 prior rollout achieved the required semantic result and differential result, but process quality was below threshold. +- Patch-local hardcoding was detected because the checker source embedded the patch commit identifier in its explanatory text, despite otherwise avoiding patch anchors. + +### 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 path-sensitive CSA mechanism level as adequate for the vulnerability. +- Preserve semantic score at or above the configured threshold. +- Do not introduce dependence on patch anchors. + +### Required semantic proof + +- Establish that the RLE decompressor can reach the input memcpy with a feasible path where the remaining input counter is negative. +- Treat the input pointer and remaining-length counter as the paired buffer invariant: after consuming the run-length byte and decrementing by count plus one, a negative remaining count means the memcpy may read beyond the input. +- Establish that the patched negative-length guard rejects every such path before the memcpy, making the negative-counter feasibility query infeasible at the sink. +- Report the unsafe relation only for the relevant input-buffer memcpy in the RLE decompressor. + +### Implementation constraints + +- Use a path-sensitive sink callback such as check::PreCall so the query observes ProgramState immediately before the relevant memcpy. +- Recognize the three-argument memcpy operation and require its source expression to resolve to the function's input parameter. +- Restrict analysis to rleUncompress and obtain the remaining-length parameter through the function declaration and analyzer state rather than source-text matching. +- Construct and query the symbolic predicate remaining_length < 0 with the CSA constraint manager; remain silent when the value is unknown or undefined. +- Emit a non-fatal diagnostic at the relevant memcpy call, with no reports for unrelated copies or sibling branches such as the separate memset path. +- Do not encode commit identifiers, patch line numbers, patch-specific comments, source snippets, or other patch-local anchors. + +### Validation checklist + +- Compile the new checker successfully against the available Clang Static Analyzer API and verify that registration and report logic are present. +- Run the official before-and-after scans and confirm at least one relevant report in the buggy program and no report in the patched program. +- Confirm the disappeared diagnostic belongs to rleUncompress and is located at or immediately around the relevant memcpy, with no warnings in unrelated functions. +- Check that non-patched code produces no reports attributable to this rule and that the result remains sparse. +- Verify the negative-state query is feasible on the buggy path and infeasible after the patched guard, rather than relying only on textual guard placement. +- Run code verification and refinement evaluation, preserving the objective gate, semantic threshold, and accepted or clean refinement outcome. +- Run process and hardcoding checks to ensure the implementation contains no patch-anchor dependence or commit-specific identifiers. + +### Avoid and forbidden regressions + +- Do not replace the path-sensitive state query with syntax-only matching or dominance placement alone. +- Do not report merely because a memcpy exists in the function; require the source-parameter relation and feasible negative remaining-length state. +- Do not model unrelated OpenEXR fixes or broaden the rule to other decompressor functions without supplied semantic evidence. +- Do not report when analyzer information about the remaining-length value is unknown or undefined. +- Do not introduce patch-specific commit hashes, line numbers, copied patch text, or source-text signatures. +- Do not weaken the accepted path-sensitive semantic contract to improve process or hardcoding scores. diff --git a/tasks/csa159/pair_136252/checker_template.cpp b/tasks/csa159/pair_136252/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_136252/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_136252/config.json b/tasks/csa159/pair_136252/config.json new file mode 100644 index 0000000000000000000000000000000000000000..5abfc18a737d1f0ac1b9f1cb5dcb72c0eaa3e907 --- /dev/null +++ b/tasks/csa159/pair_136252/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "openexr_openexr", + "before_commit": "1cbf6b9a4497f71586ac11dc60ed21cf0cc529bd", + "after_commit": "6bad53af7eebed507564dd5fc90320e4c6a6c0bc", + "repo_path": "/workspace/repo/openexr/openexr", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/openexr_openexr/6546ff20961003825f86662efe16842ff6a64f32/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/openexr_openexr/6546ff20961003825f86662efe16842ff6a64f32/compile_commands.json", + "changed_files": [ + "OpenEXR/IlmImf/ImfHeader.cpp" + ], + "commit_message": "Force tile sizes to be less than INT_MAX bytes, in line with the maximum dimensions of data windows\n\nSigned-off-by: Peter Hillman ", + "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_136252/patch.diff b/tasks/csa159/pair_136252/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d050687447f434a6b803428e46b77a1566bc457a --- /dev/null +++ b/tasks/csa159/pair_136252/patch.diff @@ -0,0 +1,13 @@ +diff --git a/OpenEXR/IlmImf/ImfHeader.cpp b/OpenEXR/IlmImf/ImfHeader.cpp +index e29ec421..f3655e3f 100644 +--- a/OpenEXR/IlmImf/ImfHeader.cpp ++++ b/OpenEXR/IlmImf/ImfHeader.cpp +@@ -902,7 +902,7 @@ Header::sanityCheck (bool isTiled, bool isMultipartFile) const + + const TileDescription &tileDesc = tileDescription(); + +- if (tileDesc.xSize <= 0 || tileDesc.ySize <= 0) ++ if (tileDesc.xSize <= 0 || tileDesc.ySize <= 0 || tileDesc.xSize > INT_MAX || tileDesc.ySize > INT_MAX ) + throw IEX_NAMESPACE::ArgExc ("Invalid tile size in image header."); + + if (maxTileWidth > 0 && \ No newline at end of file diff --git a/tasks/csa159/pair_136252/post_functions.txt b/tasks/csa159/pair_136252/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..4ca9b067b421dc1d52a3cc65f3bfca30358b8c04 --- /dev/null +++ b/tasks/csa159/pair_136252/post_functions.txt @@ -0,0 +1,333 @@ +### File: OpenEXR/IlmImf/ImfHeader.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas +// Digital Ltd. LLC +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Industrial Light & Magic nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + + + +//----------------------------------------------------------------------------- +// +// class Header +// +//----------------------------------------------------------------------------- + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "IlmThreadMutex.h" +#include "Iex.h" +#include +#include +#include +#include +#include "ImfTiledMisc.h" +#include "ImfNamespace.h" + +OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER + +using namespace std; +using IMATH_NAMESPACE::Box2i; +using IMATH_NAMESPACE::V2i; +using IMATH_NAMESPACE::V2f; +using ILMTHREAD_NAMESPACE::Mutex; +using ILMTHREAD_NAMESPACE::Lock; + + +namespace { + +int maxImageWidth = 0; +int maxImageHeight = 0; +int maxTileWidth = 0; +int maxTileHeight = 0; + + +void +initialize (Header &header, + const Box2i &displayWindow, + const Box2i &dataWindow, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +{ + header.insert ("displayWindow", Box2iAttribute (displayWindow)); + header.insert ("dataWindow", Box2iAttribute (dataWindow)); + if ( !std::isnormal (pixelAspectRatio) || pixelAspectRatio < 0.f) + THROW (IEX_NAMESPACE::ArgExc, "Invalid pixel aspect ratio"); + header.insert ("pixelAspectRatio", FloatAttribute (pixelAspectRatio)); + header.insert ("screenWindowCenter", V2fAttribute (screenWindowCenter)); + header.insert ("screenWindowWidth", FloatAttribute (screenWindowWidth)); + header.insert ("lineOrder", LineOrderAttribute (lineOrder)); + header.insert ("compression", CompressionAttribute (compression)); + header.insert ("channels", ChannelListAttribute ()); +} + +template +void checkIsNullTerminated (const char (&str)[N], const char *what) +{ + for (size_t i = 0; i < N; ++i) { + if (str[i] == '\0') + return; + } + std::stringstream s; + s << "Invalid " << what << ": it is more than " << (N - 1) + << " characters long."; + throw IEX_NAMESPACE::InputExc(s); +} + +} // namespace + + +Header::Header (int width, + int height, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +: + _map() +{ + staticInitialize(); + + Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1)); + + initialize (*this, + displayWindow, + displayWindow, + pixelAspectRatio, + screenWindowCenter, + screenWindowWidth, + lineOrder, + compression); +} + + +Header::Header (int width, + int height, + const Box2i &dataWindow, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +: + _map() +{ + staticInitialize(); + + Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1)); + + initialize (*this, + displayWindow, + dataWindow, + pixelAspectRatio, + screenWindowCenter, + screenWindowWidth, + lineOrder, + compression); +} + + +Header::Header (const Box2i &displayWindow, + const Box2i &dataWindow, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +: + _map() +{ + staticInitialize(); + + initialize (*this, + displayWindow, + dataWindow, + pixelAspectRatio, + screenWindowCenter, + screenWindowWidth, + lineOrder, + compression); +} + + +Header::Header (const Header &other): _map() +{ + for (AttributeMap::const_iterator i = other._map.begin(); + i != other._map.end(); + ++i) + { + insert (*i->first, *i->second); + } +} + + +Header::~Header () +{ + for (AttributeMap::iterator i = _map.begin(); + i != _map.end(); + ++i) + { + delete i->second; + } +} + + +Header & +Header::operator = (const Header &other) +{ + if (this != &other) + { + for (AttributeMap::iterator i = _map.begin(); + i != _map.end(); + ++i) + { + delete i->second; + } + + _map.erase (_map.begin(), _map.end()); + + for (AttributeMap::const_iterator i = other._map.begin(); + i != other._map.end(); + ++i) + { + insert (*i->first, *i->second); + } + } + + return *this; +} + + +void +Header::erase (const char name[]) +{ + if (name[0] == 0) + THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string."); + + + AttributeMap::iterator i = _map.find (name); + if (i != _map.end()) + _map.erase (i); + +} + + +void +Header::erase (const string &name) +{ + erase (name.c_str()); +} + + +void +Header::insert (const char name[], const Attribute &attribute) +{ + if (name[0] == 0) + THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string."); + + AttributeMap::iterator i = _map.find (name); + + if (i == _map.end()) + { + Attribute *tmp = attribute.copy(); + + try + { + _map[name] = tmp; + } + catch (...) + { + delete tmp; + throw; + } + } + else + { + if (strcmp (i->second->typeName(), attribute.typeName())) + THROW (IEX_NAMESPACE::TypeExc, "Cannot assign a value of " + "type \"" << attribute.typeName() << "\" " + "to image attribute \"" << name << "\" of " + "type \"" << i->second->typeName() << "\"."); + + Attribute *tmp = attribute.copy(); + delete i->second; + i->second = tmp; + } +} + + +void +Header::insert (const string &name, const Attribute &attribute) +{ + insert (name.c_str(), attribute); +} + + +Attribute & +Header::operator [] (const char name[]) +{ + AttributeMap::iterator i = _map.find (name); + + if (i = + +// ... (22606 more chars) +``` diff --git a/tasks/csa159/pair_136252/pre_functions.txt b/tasks/csa159/pair_136252/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..1c387b0168ddb98b1a1e8b29f1069baf5ccedc54 --- /dev/null +++ b/tasks/csa159/pair_136252/pre_functions.txt @@ -0,0 +1,333 @@ +### File: OpenEXR/IlmImf/ImfHeader.cpp +```c +/////////////////////////////////////////////////////////////////////////// +// +// Copyright (c) 2004, Industrial Light & Magic, a division of Lucas +// Digital Ltd. LLC +// +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// * Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// * Redistributions in binary form must reproduce the above +// copyright notice, this list of conditions and the following disclaimer +// in the documentation and/or other materials provided with the +// distribution. +// * Neither the name of Industrial Light & Magic nor the names of +// its contributors may be used to endorse or promote products derived +// from this software without specific prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +/////////////////////////////////////////////////////////////////////////// + + + +//----------------------------------------------------------------------------- +// +// class Header +// +//----------------------------------------------------------------------------- + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "IlmThreadMutex.h" +#include "Iex.h" +#include +#include +#include +#include +#include "ImfTiledMisc.h" +#include "ImfNamespace.h" + +OPENEXR_IMF_INTERNAL_NAMESPACE_SOURCE_ENTER + +using namespace std; +using IMATH_NAMESPACE::Box2i; +using IMATH_NAMESPACE::V2i; +using IMATH_NAMESPACE::V2f; +using ILMTHREAD_NAMESPACE::Mutex; +using ILMTHREAD_NAMESPACE::Lock; + + +namespace { + +int maxImageWidth = 0; +int maxImageHeight = 0; +int maxTileWidth = 0; +int maxTileHeight = 0; + + +void +initialize (Header &header, + const Box2i &displayWindow, + const Box2i &dataWindow, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +{ + header.insert ("displayWindow", Box2iAttribute (displayWindow)); + header.insert ("dataWindow", Box2iAttribute (dataWindow)); + if ( !std::isnormal (pixelAspectRatio) || pixelAspectRatio < 0.f) + THROW (IEX_NAMESPACE::ArgExc, "Invalid pixel aspect ratio"); + header.insert ("pixelAspectRatio", FloatAttribute (pixelAspectRatio)); + header.insert ("screenWindowCenter", V2fAttribute (screenWindowCenter)); + header.insert ("screenWindowWidth", FloatAttribute (screenWindowWidth)); + header.insert ("lineOrder", LineOrderAttribute (lineOrder)); + header.insert ("compression", CompressionAttribute (compression)); + header.insert ("channels", ChannelListAttribute ()); +} + +template +void checkIsNullTerminated (const char (&str)[N], const char *what) +{ + for (size_t i = 0; i < N; ++i) { + if (str[i] == '\0') + return; + } + std::stringstream s; + s << "Invalid " << what << ": it is more than " << (N - 1) + << " characters long."; + throw IEX_NAMESPACE::InputExc(s); +} + +} // namespace + + +Header::Header (int width, + int height, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +: + _map() +{ + staticInitialize(); + + Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1)); + + initialize (*this, + displayWindow, + displayWindow, + pixelAspectRatio, + screenWindowCenter, + screenWindowWidth, + lineOrder, + compression); +} + + +Header::Header (int width, + int height, + const Box2i &dataWindow, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +: + _map() +{ + staticInitialize(); + + Box2i displayWindow (V2i (0, 0), V2i (width - 1, height - 1)); + + initialize (*this, + displayWindow, + dataWindow, + pixelAspectRatio, + screenWindowCenter, + screenWindowWidth, + lineOrder, + compression); +} + + +Header::Header (const Box2i &displayWindow, + const Box2i &dataWindow, + float pixelAspectRatio, + const V2f &screenWindowCenter, + float screenWindowWidth, + LineOrder lineOrder, + Compression compression) +: + _map() +{ + staticInitialize(); + + initialize (*this, + displayWindow, + dataWindow, + pixelAspectRatio, + screenWindowCenter, + screenWindowWidth, + lineOrder, + compression); +} + + +Header::Header (const Header &other): _map() +{ + for (AttributeMap::const_iterator i = other._map.begin(); + i != other._map.end(); + ++i) + { + insert (*i->first, *i->second); + } +} + + +Header::~Header () +{ + for (AttributeMap::iterator i = _map.begin(); + i != _map.end(); + ++i) + { + delete i->second; + } +} + + +Header & +Header::operator = (const Header &other) +{ + if (this != &other) + { + for (AttributeMap::iterator i = _map.begin(); + i != _map.end(); + ++i) + { + delete i->second; + } + + _map.erase (_map.begin(), _map.end()); + + for (AttributeMap::const_iterator i = other._map.begin(); + i != other._map.end(); + ++i) + { + insert (*i->first, *i->second); + } + } + + return *this; +} + + +void +Header::erase (const char name[]) +{ + if (name[0] == 0) + THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string."); + + + AttributeMap::iterator i = _map.find (name); + if (i != _map.end()) + _map.erase (i); + +} + + +void +Header::erase (const string &name) +{ + erase (name.c_str()); +} + + +void +Header::insert (const char name[], const Attribute &attribute) +{ + if (name[0] == 0) + THROW (IEX_NAMESPACE::ArgExc, "Image attribute name cannot be an empty string."); + + AttributeMap::iterator i = _map.find (name); + + if (i == _map.end()) + { + Attribute *tmp = attribute.copy(); + + try + { + _map[name] = tmp; + } + catch (...) + { + delete tmp; + throw; + } + } + else + { + if (strcmp (i->second->typeName(), attribute.typeName())) + THROW (IEX_NAMESPACE::TypeExc, "Cannot assign a value of " + "type \"" << attribute.typeName() << "\" " + "to image attribute \"" << name << "\" of " + "type \"" << i->second->typeName() << "\"."); + + Attribute *tmp = attribute.copy(); + delete i->second; + i->second = tmp; + } +} + + +void +Header::insert (const string &name, const Attribute &attribute) +{ + insert (name.c_str(), attribute); +} + + +Attribute & +Header::operator [] (const char name[]) +{ + AttributeMap::iterator i = _map.find (name); + + if (i = + +// ... (22549 more chars) +``` diff --git a/tasks/csa159/pair_136252/task_prompt.md b/tasks/csa159/pair_136252/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..90172fbe15f47d2cd031e946d602913b15e45215 --- /dev/null +++ b/tasks/csa159/pair_136252/task_prompt.md @@ -0,0 +1,384 @@ +# 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 rollout used CFG dominance even though the patch-local security requirement can be established from the validation condition, its TileDescription field identities, comparison polarity, and rejecting branch. +- Requiring a same-function direct call to getTiledChunkOffsetTableSize narrowed detection incorrectly: Header::sanityCheck can contain the defective validation without containing the eventual hazardous computation. +- The checker therefore remained only partially semantically correct despite producing the desired one-before, zero-after differential result and a patch-adjacent diagnostic. +- The control-flow model also had unsound refinements: treating goto as a function exit and using block dominance without proving the relevant branch edge can misclassify variants. +- The latest rollout regressed semantic score from 7.0 to 4.0, below the configured threshold, while semantic_mechanism remained failed. + +### 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 semantic and process scores at or above their configured thresholds. +- Preserve the observed differential behavior: one relevant warning on the buggy revision and none on the patched revision. +- Preserve diagnostic sharpness at the changed validation site and avoid warnings in non-patched scope. +- Remain independent of patch anchors and patch-local hardcoding. + +### Required semantic proof + +- Identify the validation of unsigned TileDescription xSize and ySize fields obtained for a Header in Header::sanityCheck or an equivalent project-general validation context. +- For each relevant dimension, determine whether the rejecting condition excludes values above the maximum representable signed value used by downstream tile-size arithmetic. +- Accept semantically equivalent upper-bound predicates, including reversed operands and equivalent strict or inclusive bounds, only when their comparison polarity rejects the oversized value. +- Require both xSize and ySize to have effective upper-bound rejection; report when either dimension is protected only by the existing zero or lower-bound validation. +- Associate the predicates with the same TileDescription value being validated and require the rejection branch to throw, return, or invoke a recognized noreturn operation. +- Do not require the hazardous size-computation call to occur in the validation function; the source evidence establishes that successful validation permits later signed tile-size use. + +### Implementation constraints + +- Use a function-body AST callback such as check::ASTCodeBody and semantic AST identities, including canonical FieldDecl and record/type information. +- Inspect the complete validation condition, including parenthesized expressions and logical disjunctions, and normalize comparison operand order and integer constant expressions. +- Recognize unsigned xSize and ySize members of canonical TileDescription rather than arbitrary unsigned members or textually similar expressions. +- Tie member accesses to the same TileDescription-producing expression or Header receiver using AST structure; do not use path-global symbols or unrelated-instance aggregation. +- Emit the report at the deficient validation condition or missing-bound-relevant field comparison so the location remains adjacent to the original changed span. +- Keep scope project-general while allowing project semantic names needed to identify TileDescription dimensions; do not depend on file paths, line numbers, commit identifiers, diff text, or source formatting. +- No CFG, dominance, ProgramState, constraint solving, or interprocedural propagation is required unless synthesis evidence demonstrates a validation form that cannot be decided by local AST relations. + +### Validation checklist + +- Compile the checker against the supplied Clang Static Analyzer API and verify successful registration and loading. +- Scan both revisions with valid OpenEXR include and generated-configuration paths; reject results contaminated by source compile errors. +- Confirm exactly one relevant buggy-revision warning and zero patched-revision warnings. +- Confirm the buggy warning is located on the TileDescription validation condition at or immediately adjacent to the changed source span. +- Verify clean results for both dimensions correctly bounded, reversed-operand equivalents, equivalent inclusive bounds, unrelated unsigned members, and unrelated TileDescription instances. +- Verify warnings when only xSize or only ySize is upper-bounded, when a bound exceeds the signed maximum, and when an upper-bound-looking predicate has non-rejecting polarity. +- Verify that a terminating rejecting branch is accepted while a branch that falls through is not treated as effective validation. +- Run code verification and refinement, preserving G6, clean refinement, anchor-free and hardcoding-free status, and configured semantic/process score thresholds. + +### Avoid and forbidden regressions + +- Do not require a direct getTiledChunkOffsetTableSize call in the same function as the validation. +- Do not repeat the prior CFG-dominance design merely because it produced the expected differential counts. +- Do not infer safety from the mere textual presence of INT_MAX, a greater-than operator, or either dimension alone. +- Do not treat the maxTileWidth and maxTileHeight narrowing-cast branch as proof that TileDescription xSize and ySize are bounded. +- Do not use path-global ProgramState or SymbolRef collections that can combine facts from different Header or TileDescription instances. +- Do not treat goto as proof that the current function terminates. +- Do not key detection or reporting to ImfHeader.cpp, line 905, exact patch text, local formatting, or revision-specific anchors. +- Do not trade away semantic-score compliance, process quality, differential validation, or false-positive control to simplify implementation. diff --git a/tasks/csa159/pair_136342/checker_template.cpp b/tasks/csa159/pair_136342/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_136342/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_136342/config.json b/tasks/csa159/pair_136342/config.json new file mode 100644 index 0000000000000000000000000000000000000000..db54a36457251138857ec6fcef748c73f7069090 --- /dev/null +++ b/tasks/csa159/pair_136342/config.json @@ -0,0 +1,20 @@ +{ + "project_id": "vadz_libtiff", + "before_commit": "3206e0c752a62da1ae606867113ed3bf9bf73306", + "after_commit": "3996fa0f84f4a8b7e65fe4b8f0681711022034ea", + "repo_path": "/workspace/repo/vadz/libtiff", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/vadz_libtiff/2701f47b544ab7eb2d40bb9e0542f17a7ba1437a/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/vadz_libtiff/2701f47b544ab7eb2d40bb9e0542f17a7ba1437a/compile_commands.json", + "changed_files": [ + "tools/pal2rgb.c", + "tools/thumbnail.c" + ], + "commit_message": "* tools/pal2rgb.c, tools/thumbnail.c: fix crash by disabling TIFFTAG_INKNAMES\ncopying. The right fix would be to properly copy it, but not worth the burden\nfor those esoteric utilities.\nhttp://bugzilla.maptools.org/show_bug.cgi?id=2484 (CVE-2014-8127)", + "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_136342/patch.diff b/tasks/csa159/pair_136342/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9b0f447b0ecf0267950c641b529d88c2566ff0af --- /dev/null +++ b/tasks/csa159/pair_136342/patch.diff @@ -0,0 +1,41 @@ +diff --git a/ChangeLog b/ChangeLog +index 2dc5f4b5..0f070dd9 100644 +--- a/ChangeLog ++++ b/ChangeLog +@@ -1,3 +1,10 @@ ++2014-12-21 Even Rouault ++ ++ * tools/pal2rgb.c, tools/thumbnail.c: fix crash by disabling TIFFTAG_INKNAMES ++ copying. The right fix would be to properly copy it, but not worth the burden ++ for those esoteric utilities. ++ http://bugzilla.maptools.org/show_bug.cgi?id=2484 (CVE-2014-8127) ++ + 2014-12-21 Even Rouault + + * tools/thumbnail.c: fix out-of-buffer write +diff --git a/tools/pal2rgb.c b/tools/pal2rgb.c +index bfe7899d..3fc3de3e 100644 +--- a/tools/pal2rgb.c ++++ b/tools/pal2rgb.c +@@ -372,7 +372,7 @@ static struct cpTag { + { TIFFTAG_CLEANFAXDATA, 1, TIFF_SHORT }, + { TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG }, + { TIFFTAG_INKSET, 1, TIFF_SHORT }, +- { TIFFTAG_INKNAMES, 1, TIFF_ASCII }, ++ /*{ TIFFTAG_INKNAMES, 1, TIFF_ASCII },*/ /* Needs much more complicated logic. See tiffcp */ + { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, + { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, + { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, +diff --git a/tools/thumbnail.c b/tools/thumbnail.c +index c50bbffc..73f9c34a 100644 +--- a/tools/thumbnail.c ++++ b/tools/thumbnail.c +@@ -257,7 +257,7 @@ static struct cpTag { + { TIFFTAG_CLEANFAXDATA, 1, TIFF_SHORT }, + { TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG }, + { TIFFTAG_INKSET, 1, TIFF_SHORT }, +- { TIFFTAG_INKNAMES, 1, TIFF_ASCII }, ++ /*{ TIFFTAG_INKNAMES, 1, TIFF_ASCII },*/ /* Needs much more complicated logic. See tiffcp */ + { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, + { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, + { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, \ No newline at end of file diff --git a/tasks/csa159/pair_136342/post_functions.txt b/tasks/csa159/pair_136342/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..fd07aa83074c5be3d4b24d9a46c9b3688d30b563 --- /dev/null +++ b/tasks/csa159/pair_136342/post_functions.txt @@ -0,0 +1,567 @@ +### File: tools/pal2rgb.c +```c +/* $Id$ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tif_config.h" + +#include +#include +#include +#include + +#ifdef HAVE_UNISTD_H +# include +#endif + +#ifdef NEED_LIBPORT +# include "libport.h" +#endif + +#include "tiffio.h" + +#define streq(a,b) (strcmp(a,b) == 0) +#define strneq(a,b,n) (strncmp(a,b,n) == 0) + +static void usage(void); +static void cpTags(TIFF* in, TIFF* out); + +static int +checkcmap(int n, uint16* r, uint16* g, uint16* b) +{ + while (n-- > 0) + if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256) + return (16); + fprintf(stderr, "Warning, assuming 8-bit colormap.\n"); + return (8); +} + +#define CopyField(tag, v) \ + if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) +#define CopyField3(tag, v1, v2, v3) \ + if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) + +static uint16 compression = (uint16) -1; +static uint16 predictor = 0; +static int quality = 75; /* JPEG quality */ +static int jpegcolormode = JPEGCOLORMODE_RGB; +static int processCompressOptions(char*); + +int +main(int argc, char* argv[]) +{ + uint16 bitspersample, shortv; + uint32 imagewidth, imagelength; + uint16 config = PLANARCONFIG_CONTIG; + uint32 rowsperstrip = (uint32) -1; + uint16 photometric = PHOTOMETRIC_RGB; + uint16 *rmap, *gmap, *bmap; + uint32 row; + int cmap = -1; + TIFF *in, *out; + int c; + extern int optind; + extern char* optarg; + + while ((c = getopt(argc, argv, "C:c:p:r:")) != -1) + switch (c) { + case 'C': /* force colormap interpretation */ + cmap = atoi(optarg); + break; + case 'c': /* compression scheme */ + if (!processCompressOptions(optarg)) + usage(); + break; + case 'p': /* planar configuration */ + if (streq(optarg, "separate")) + config = PLANARCONFIG_SEPARATE; + else if (streq(optarg, "contig")) + config = PLANARCONFIG_CONTIG; + else + usage(); + break; + case 'r': /* rows/strip */ + rowsperstrip = atoi(optarg); + break; + case '?': + usage(); + /*NOTREACHED*/ + } + if (argc - optind != 2) + usage(); + in = TIFFOpen(argv[optind], "r"); + if (in == NULL) + return (-1); + if (!TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &shortv) || + shortv != PHOTOMETRIC_PALETTE) { + fprintf(stderr, "%s: Expecting a palette image.\n", + argv[optind]); + return (-1); + } + if (!TIFFGetField(in, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) { + fprintf(stderr, + "%s: No colormap (not a valid palette image).\n", + argv[optind]); + return (-1); + } + bitspersample = 0; + TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample); + if (bitspersample != 8) { + fprintf(stderr, "%s: Sorry, can only handle 8-bit images.\n", + argv[optind]); + return (-1); + } + out = TIFFOpen(argv[optind+1], "w"); + if (out == NULL) + return (-2); + cpTags(in, out); + TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &imagewidth); + TIFFGetField(in, TIFFTAG_IMAGELENGTH, &imagelength); + if (compression != (uint16)-1) + TIFFSetField(out, TIFFTAG_COMPRESSION, compression); + else + TIFFGetField(in, TIFFTAG_COMPRESSION, &compression); + switch (compression) { + case COMPRESSION_JPEG: + if (jpegcolormode == JPEGCOLORMODE_RGB) + photometric = PHOTOMETRIC_YCBCR; + else + photometric = PHOTOMETRIC_RGB; + TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); + TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode); + break; + case COMPRESSION_LZW: + case COMPRESSION_DEFLATE: + if (predictor != 0) + TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); + break; + } + TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric); + TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3); + TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); + TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, + rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip)); + (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv); + if (cmap == -1) + cmap = checkcmap(1<= 0; i--) { +#define CVT(x) (((x) * 255) / ((1L<<16)-1)) + rmap[i] = CVT(rmap[i]); + gmap[i] = CVT(gmap[i]); + bmap[i] = CVT(bmap[i]); + } + } + { unsigned char *ibuf, *obuf; + register unsigned char* pp; + register uint32 x; + ibuf = (unsigned char*)_TIFFmalloc(TIFFScanlineSize(in)); + obuf = (unsigned char*)_TIFFmalloc(TIFFScanlineSize(out)); + switch (config) { + case PLANARCONFIG_CONTIG: + for (row = 0; row < imagelength; row++) { + if (!TIFFReadScanline(in, ibuf, row, 0)) + goto done; + pp = obuf; + for (x = 0; x < imagewidth; x++) { + *pp++ = (unsigned char) rmap[ibuf[x]]; + *pp++ = (unsigned char) gmap[ibuf[x]]; + *pp++ = (unsigned char) bmap[ibuf[x]]; + } + if (!TIFFWriteScanline(out, obuf, row, 0)) + goto done; + } + break; + case PLANARCONFIG_SEPARATE: + for (row = 0; row < imagelength; row++) { + if (!TIFFReadScanline(in, ibuf, row, 0)) + goto done; + for (pp = obuf, x = 0; x < imagewidth; x++) + *pp++ = (unsigned char) rmap[ibuf[x]]; + if (!TIFFWriteScanline(out, obuf, row, 0)) + goto done; + for (pp = obuf, x = 0; x < imagewidth; x++) + *pp++ = (unsigned char) gmap[ibuf[x]]; + if (!TIFFWriteScanline(out, obuf, row, 0)) + goto done; + for (pp = obuf, x = 0; x < imagewidth; x++) + *pp++ = (unsigned char) bmap[ibuf[x]]; + if (!TIFFWriteScanline(out, obuf, row, 0)) + goto done; + } + break; + } + _TIFFfree(ibuf); + _TIFFfree(obuf); + } +done: + (void) TIFFClose(in); + (void) TIFFClose(out); + return (0); +} + +static int +processCompressOptions(char* opt) +{ + if (streq(opt, "none")) + compression = COMPRESSION_NONE; + else if (streq(opt, "packbits")) + compression = COMPRESSION_PACKBITS; + else if (strneq(opt, "jpeg", 4)) { + char* cp = strchr(opt, ':'); + + compression = COMPRESSION_JPEG; + while( cp ) + { + if (isdigit((int)cp[1])) + quality = atoi(cp+1); + else if (cp[1] == 'r' ) + jpegcolormode = JPEGCOLORMODE_RAW; + else + usage(); + + cp = strchr(cp+1,':'); + } + } else if (strneq(opt, "lzw", 3)) { + char* cp = strchr(opt, ':'); + if (cp) + predictor = atoi(cp+1); + compression = COMPRESSION_LZW; + } else if (strneq(opt, "zip", 3)) { + char* cp = strchr(opt, ':'); + if (cp) + predictor = atoi(cp+1); + compression = COMPRESSION_DEFLATE; + } else + return (0); + return (1); +} + +#define CopyField(tag, v) \ + if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) +#define CopyField2(tag, v1, v2) \ + if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) +#define CopyField3(tag, v1, v2, v3) \ + if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) +#define CopyField4(tag, v1, v2, v3, v4) \ + if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) + +static void +cpTag(TIFF* in, TIFF* out, uint16 + +// ... (4689 more chars) +``` + +### File: tools/thumbnail.c +```c +/* $Id$ */ + +/* + * Copyright (c) 1994-1997 Sam Leffler + * Copyright (c) 1994-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tif_config.h" + +#include +#include +#include +#include + +#ifdef HAVE_UNISTD_H +# include +#endif + +#ifdef NEED_LIBPORT +# include "libport.h" +#endif + +#include "tiffio.h" + +#ifndef HAVE_GETOPT +extern int getopt(int, char**, char*); +#endif + +#define streq(a,b) (strcmp(a,b) == 0) + +#ifndef TIFFhowmany8 +# define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3) +#endif + +typedef enum { + EXP50, + EXP60, + EXP70, + EXP80, + EXP90, + EXP, + LINEAR +} Contrast; + +static uint32 tnw = 216; /* thumbnail width */ +static uint32 tnh = 274; /* thumbnail height */ +static Contrast contrast = LINEAR; /* current contrast */ +static uint8* thumbnail; + +static int cpIFD(TIFF*, TIFF*); +static int generateThumbnail(TIFF*, TIFF*); +static void initScale(); +static void usage(void); + +extern char* optarg; +extern int optind; + +int +main(int argc, char* argv[]) +{ + TIFF* in; + TIFF* out; + int c; + + while ((c = getopt(argc, argv, "w:h:c:")) != -1) { + switch (c) { + case 'w': tnw = strtoul(optarg, NULL, 0); break; + case 'h': tnh = strtoul(optarg, NULL, 0); break; + case 'c': contrast = streq(optarg, "exp50") ? EXP50 : + streq(optarg, "exp60") ? EXP60 : + streq(optarg, "exp70") ? EXP70 : + streq(optarg, "exp80") ? EXP80 : + streq(optarg, "exp90") ? EXP90 : + streq(optarg, "exp") ? EXP : + streq(optarg, "linear")? LINEAR : + EXP; + break; + default: usage(); + } + } + if (argc-optind != 2) + usage(); + + out = TIFFOpen(argv[optind+1], "w"); + if (out == NULL) + return 2; + in = TIFFOpen(argv[optind], "r"); + if( in == NULL ) + return 2; + + thumbnail = (uint8*) _TIFFmalloc(tnw * tnh); + if (!thumbnail) { + TIFFError(TIFFFileName(in), + "Can't allocate space for thumbnail buffer."); + return 1; + } + + if (in != NULL) { + initScale(); + do { + if (!generateThumbnail(in, out)) + goto bad; + if (!cpIFD(in, out) || !TIFFWriteDirectory(out)) + goto bad; + } while (TIFFReadDirectory(in)); + (void) TIFFClose(in); + } + (void) TIFFClose(out); + return 0; +bad: + (void) TIFFClose(out); + return 1; +} + +#define CopyField(tag, v) \ + if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) +#define CopyField2(tag, v1, v2) \ + if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) +#define CopyField3(tag, v1, v2, v3) \ + if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) +#define CopyField4(tag, v1, v2, v3, v4) \ + if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) + +static void +cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) +{ + switch (type) { + case TIFF_SHORT: + if (count == 1) { + uint16 shortv; + CopyField(tag, shortv); + } else if (count == 2) { + uint16 shortv1, shortv2; + CopyField2(tag, shortv1, shortv2); + } else if (count == 4) { + uint16 *tr, *tg, *tb, *ta; + CopyField4(tag, tr, tg, tb, ta); + } else if (count == (uint16) -1) { + uint16 shortv1; + uint16* shortav; + CopyField2(tag, shortv1, shortav); + } + break; + case TIFF_LONG: + { uint32 longv; + CopyField(tag, longv); + } + break; + case TIFF_LONG8: + { uint64 longv8; + CopyField(tag, longv8); + } + break; + case TIFF_SLONG8: + { int64 longv8; + CopyField(tag, longv8); + } + break; + case TIFF_RATIONAL: + if (count == 1) { + float floatv; + CopyField(tag, floatv); + } else if (count == (uint16) -1) { + float* floatav; + CopyField(tag, floatav); + } + break; + case TIFF_ASCII: + { char* stringv; + CopyField(tag, stringv); + } + break; + case TIFF_DOUBLE: + if (count == 1) { + double doublev; + CopyField(tag, doublev); + } else if (count == (uint16) -1) { + double* doubleav; + CopyField(tag, doubleav); + } + break; + case TIFF_IFD8: + { toff_t ifd8; + CopyField(tag, ifd8); + } + break; default: + TIFFError(TIFFFileName(in), + "Data type %d is not supported, tag %d skipped.", + tag, type); + } +} + +#undef CopyField4 +#undef CopyField3 +#undef CopyField2 +#undef CopyField + +static struct cpTag { + uint16 tag; + uint16 count; + TIFFDataType type; +} tags[] = { + { TIFFTAG_IMAGEWIDTH, 1, TIFF_LONG }, + { TIFFTAG_IMAGELENGTH, 1, TIFF_LONG }, + { TIFFTAG_BITSPERSAMPLE, 1, TIFF_SHORT }, + { TIFFTAG_COMPRESSION, 1, TIFF_SHORT }, + { TIFFTAG_FILLORDER, 1, TIFF_SHORT }, + { TIFFTAG_SAMPLESPERPIXEL, 1, TIFF_SHORT }, + { TIFFTAG_ROWSPERSTRIP, 1, TIFF_LONG }, + { TIFFTAG_PLANARCONFIG, 1, TIFF_SHORT }, + { TIFFTAG_GROUP3OPTIONS, 1, TIFF_LONG }, + { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, + { TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT }, + { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, + { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, + { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, + { TIFFTAG_MAKE, 1, TIFF_ASCII }, + { TIFFTAG_MODEL, 1, TIFF_ASCII }, + { TIFFTAG_ORIENTATION, 1, TIFF_SHORT }, + { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, + { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, + { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, + { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, + { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, + { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, + { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, + { TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG }, + { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, + { TIFFTAG_PAGENUMBER, 2, TIFF_SHORT }, + { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, + { TIFFTAG_DATETIME, 1, TIFF_ASCII }, + { TIFFTAG_ARTIST, 1, TIFF_ASCII }, + { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, + { TIFFTAG_WHITEPOINT, 2, TIFF_RATIONAL }, + { TIFFTAG_PRIMARYCHROMATICITIES, (uint16) -1,TIFF_RATIONAL }, + { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, + { TIFFTAG_BADFAXLINES, 1, TIFF_LONG }, + { TIFFTAG_CLEANFAXDATA, 1, TIFF_SHORT }, + { TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG }, + { TIFFTAG_INKSET, 1, TIFF_SHORT }, + /*{ TIFFTAG_INKNAMES, 1, TIFF_ASCII },*/ /* Needs much more complicated logic. See tiffcp */ + { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, + { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, + { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, + { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, + { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, + { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, + { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, + { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, +}; +#define NTAGS (sizeof (tags) / sizeof (tags[0])) + +static void +cpTags(TIFF* in, TIFF* out) +{ + struct cpTag *p; + for (p = tags; p < &tags[NTAGS]; p++) + { + /* Horrible: but TIFFGetField() expects 2 arguments to be passed */ + /* if we request a tag that is defined in a codec, but that codec */ + /* is + +// ... (10457 more chars) +``` diff --git a/tasks/csa159/pair_136342/pre_functions.txt b/tasks/csa159/pair_136342/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..ada96e8c12e3b7606918a5eb423a0760f124b486 --- /dev/null +++ b/tasks/csa159/pair_136342/pre_functions.txt @@ -0,0 +1,570 @@ +### File: tools/pal2rgb.c +```c +/* $Id$ */ + +/* + * Copyright (c) 1988-1997 Sam Leffler + * Copyright (c) 1991-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tif_config.h" + +#include +#include +#include +#include + +#ifdef HAVE_UNISTD_H +# include +#endif + +#ifdef NEED_LIBPORT +# include "libport.h" +#endif + +#include "tiffio.h" + +#define streq(a,b) (strcmp(a,b) == 0) +#define strneq(a,b,n) (strncmp(a,b,n) == 0) + +static void usage(void); +static void cpTags(TIFF* in, TIFF* out); + +static int +checkcmap(int n, uint16* r, uint16* g, uint16* b) +{ + while (n-- > 0) + if (*r++ >= 256 || *g++ >= 256 || *b++ >= 256) + return (16); + fprintf(stderr, "Warning, assuming 8-bit colormap.\n"); + return (8); +} + +#define CopyField(tag, v) \ + if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) +#define CopyField3(tag, v1, v2, v3) \ + if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) + +static uint16 compression = (uint16) -1; +static uint16 predictor = 0; +static int quality = 75; /* JPEG quality */ +static int jpegcolormode = JPEGCOLORMODE_RGB; +static int processCompressOptions(char*); + +int +main(int argc, char* argv[]) +{ + uint16 bitspersample, shortv; + uint32 imagewidth, imagelength; + uint16 config = PLANARCONFIG_CONTIG; + uint32 rowsperstrip = (uint32) -1; + uint16 photometric = PHOTOMETRIC_RGB; + uint16 *rmap, *gmap, *bmap; + uint32 row; + int cmap = -1; + TIFF *in, *out; + int c; + extern int optind; + extern char* optarg; + + while ((c = getopt(argc, argv, "C:c:p:r:")) != -1) + switch (c) { + case 'C': /* force colormap interpretation */ + cmap = atoi(optarg); + break; + case 'c': /* compression scheme */ + if (!processCompressOptions(optarg)) + usage(); + break; + case 'p': /* planar configuration */ + if (streq(optarg, "separate")) + config = PLANARCONFIG_SEPARATE; + else if (streq(optarg, "contig")) + config = PLANARCONFIG_CONTIG; + else + usage(); + break; + case 'r': /* rows/strip */ + rowsperstrip = atoi(optarg); + break; + case '?': + usage(); + /*NOTREACHED*/ + } + if (argc - optind != 2) + usage(); + in = TIFFOpen(argv[optind], "r"); + if (in == NULL) + return (-1); + if (!TIFFGetField(in, TIFFTAG_PHOTOMETRIC, &shortv) || + shortv != PHOTOMETRIC_PALETTE) { + fprintf(stderr, "%s: Expecting a palette image.\n", + argv[optind]); + return (-1); + } + if (!TIFFGetField(in, TIFFTAG_COLORMAP, &rmap, &gmap, &bmap)) { + fprintf(stderr, + "%s: No colormap (not a valid palette image).\n", + argv[optind]); + return (-1); + } + bitspersample = 0; + TIFFGetField(in, TIFFTAG_BITSPERSAMPLE, &bitspersample); + if (bitspersample != 8) { + fprintf(stderr, "%s: Sorry, can only handle 8-bit images.\n", + argv[optind]); + return (-1); + } + out = TIFFOpen(argv[optind+1], "w"); + if (out == NULL) + return (-2); + cpTags(in, out); + TIFFGetField(in, TIFFTAG_IMAGEWIDTH, &imagewidth); + TIFFGetField(in, TIFFTAG_IMAGELENGTH, &imagelength); + if (compression != (uint16)-1) + TIFFSetField(out, TIFFTAG_COMPRESSION, compression); + else + TIFFGetField(in, TIFFTAG_COMPRESSION, &compression); + switch (compression) { + case COMPRESSION_JPEG: + if (jpegcolormode == JPEGCOLORMODE_RGB) + photometric = PHOTOMETRIC_YCBCR; + else + photometric = PHOTOMETRIC_RGB; + TIFFSetField(out, TIFFTAG_JPEGQUALITY, quality); + TIFFSetField(out, TIFFTAG_JPEGCOLORMODE, jpegcolormode); + break; + case COMPRESSION_LZW: + case COMPRESSION_DEFLATE: + if (predictor != 0) + TIFFSetField(out, TIFFTAG_PREDICTOR, predictor); + break; + } + TIFFSetField(out, TIFFTAG_PHOTOMETRIC, photometric); + TIFFSetField(out, TIFFTAG_SAMPLESPERPIXEL, 3); + TIFFSetField(out, TIFFTAG_PLANARCONFIG, config); + TIFFSetField(out, TIFFTAG_ROWSPERSTRIP, + rowsperstrip = TIFFDefaultStripSize(out, rowsperstrip)); + (void) TIFFGetField(in, TIFFTAG_PLANARCONFIG, &shortv); + if (cmap == -1) + cmap = checkcmap(1<= 0; i--) { +#define CVT(x) (((x) * 255) / ((1L<<16)-1)) + rmap[i] = CVT(rmap[i]); + gmap[i] = CVT(gmap[i]); + bmap[i] = CVT(bmap[i]); + } + } + { unsigned char *ibuf, *obuf; + register unsigned char* pp; + register uint32 x; + ibuf = (unsigned char*)_TIFFmalloc(TIFFScanlineSize(in)); + obuf = (unsigned char*)_TIFFmalloc(TIFFScanlineSize(out)); + switch (config) { + case PLANARCONFIG_CONTIG: + for (row = 0; row < imagelength; row++) { + if (!TIFFReadScanline(in, ibuf, row, 0)) + goto done; + pp = obuf; + for (x = 0; x < imagewidth; x++) { + *pp++ = (unsigned char) rmap[ibuf[x]]; + *pp++ = (unsigned char) gmap[ibuf[x]]; + *pp++ = (unsigned char) bmap[ibuf[x]]; + } + if (!TIFFWriteScanline(out, obuf, row, 0)) + goto done; + } + break; + case PLANARCONFIG_SEPARATE: + for (row = 0; row < imagelength; row++) { + if (!TIFFReadScanline(in, ibuf, row, 0)) + goto done; + for (pp = obuf, x = 0; x < imagewidth; x++) + *pp++ = (unsigned char) rmap[ibuf[x]]; + if (!TIFFWriteScanline(out, obuf, row, 0)) + goto done; + for (pp = obuf, x = 0; x < imagewidth; x++) + *pp++ = (unsigned char) gmap[ibuf[x]]; + if (!TIFFWriteScanline(out, obuf, row, 0)) + goto done; + for (pp = obuf, x = 0; x < imagewidth; x++) + *pp++ = (unsigned char) bmap[ibuf[x]]; + if (!TIFFWriteScanline(out, obuf, row, 0)) + goto done; + } + break; + } + _TIFFfree(ibuf); + _TIFFfree(obuf); + } +done: + (void) TIFFClose(in); + (void) TIFFClose(out); + return (0); +} + +static int +processCompressOptions(char* opt) +{ + if (streq(opt, "none")) + compression = COMPRESSION_NONE; + else if (streq(opt, "packbits")) + compression = COMPRESSION_PACKBITS; + else if (strneq(opt, "jpeg", 4)) { + char* cp = strchr(opt, ':'); + + compression = COMPRESSION_JPEG; + while( cp ) + { + if (isdigit((int)cp[1])) + quality = atoi(cp+1); + else if (cp[1] == 'r' ) + jpegcolormode = JPEGCOLORMODE_RAW; + else + usage(); + + cp = strchr(cp+1,':'); + } + } else if (strneq(opt, "lzw", 3)) { + char* cp = strchr(opt, ':'); + if (cp) + predictor = atoi(cp+1); + compression = COMPRESSION_LZW; + } else if (strneq(opt, "zip", 3)) { + char* cp = strchr(opt, ':'); + if (cp) + predictor = atoi(cp+1); + compression = COMPRESSION_DEFLATE; + } else + return (0); + return (1); +} + +#define CopyField(tag, v) \ + if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) +#define CopyField2(tag, v1, v2) \ + if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) +#define CopyField3(tag, v1, v2, v3) \ + if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) +#define CopyField4(tag, v1, v2, v3, v4) \ + if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) + +static void +cpTag(TIFF* in, TIFF* out, uint16 + +// ... (4633 more chars) +``` + +### File: tools/thumbnail.c +```c +/* $Id$ */ + +/* + * Copyright (c) 1994-1997 Sam Leffler + * Copyright (c) 1994-1997 Silicon Graphics, Inc. + * + * Permission to use, copy, modify, distribute, and sell this software and + * its documentation for any purpose is hereby granted without fee, provided + * that (i) the above copyright notices and this permission notice appear in + * all copies of the software and related documentation, and (ii) the names of + * Sam Leffler and Silicon Graphics may not be used in any advertising or + * publicity relating to the software without the specific, prior written + * permission of Sam Leffler and Silicon Graphics. + * + * THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, + * EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY + * WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. + * + * IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR + * ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND, + * OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, + * WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF + * LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE + * OF THIS SOFTWARE. + */ + +#include "tif_config.h" + +#include +#include +#include +#include + +#ifdef HAVE_UNISTD_H +# include +#endif + +#ifdef NEED_LIBPORT +# include "libport.h" +#endif + +#include "tiffio.h" + +#ifndef HAVE_GETOPT +extern int getopt(int, char**, char*); +#endif + +#define streq(a,b) (strcmp(a,b) == 0) + +#ifndef TIFFhowmany8 +# define TIFFhowmany8(x) (((x)&0x07)?((uint32)(x)>>3)+1:(uint32)(x)>>3) +#endif + +typedef enum { + EXP50, + EXP60, + EXP70, + EXP80, + EXP90, + EXP, + LINEAR +} Contrast; + +static uint32 tnw = 216; /* thumbnail width */ +static uint32 tnh = 274; /* thumbnail height */ +static Contrast contrast = LINEAR; /* current contrast */ +static uint8* thumbnail; + +static int cpIFD(TIFF*, TIFF*); +static int generateThumbnail(TIFF*, TIFF*); +static void initScale(); +static void usage(void); + +extern char* optarg; +extern int optind; + +int +main(int argc, char* argv[]) +{ + TIFF* in; + TIFF* out; + int c; + + while ((c = getopt(argc, argv, "w:h:c:")) != -1) { + switch (c) { + case 'w': tnw = strtoul(optarg, NULL, 0); break; + case 'h': tnh = strtoul(optarg, NULL, 0); break; + case 'c': contrast = streq(optarg, "exp50") ? EXP50 : + streq(optarg, "exp60") ? EXP60 : + streq(optarg, "exp70") ? EXP70 : + streq(optarg, "exp80") ? EXP80 : + streq(optarg, "exp90") ? EXP90 : + streq(optarg, "exp") ? EXP : + streq(optarg, "linear")? LINEAR : + EXP; + break; + default: usage(); + } + } + if (argc-optind != 2) + usage(); + + out = TIFFOpen(argv[optind+1], "w"); + if (out == NULL) + return 2; + in = TIFFOpen(argv[optind], "r"); + if( in == NULL ) + return 2; + + thumbnail = (uint8*) _TIFFmalloc(tnw * tnh); + if (!thumbnail) { + TIFFError(TIFFFileName(in), + "Can't allocate space for thumbnail buffer."); + return 1; + } + + if (in != NULL) { + initScale(); + do { + if (!generateThumbnail(in, out)) + goto bad; + if (!cpIFD(in, out) || !TIFFWriteDirectory(out)) + goto bad; + } while (TIFFReadDirectory(in)); + (void) TIFFClose(in); + } + (void) TIFFClose(out); + return 0; +bad: + (void) TIFFClose(out); + return 1; +} + +#define CopyField(tag, v) \ + if (TIFFGetField(in, tag, &v)) TIFFSetField(out, tag, v) +#define CopyField2(tag, v1, v2) \ + if (TIFFGetField(in, tag, &v1, &v2)) TIFFSetField(out, tag, v1, v2) +#define CopyField3(tag, v1, v2, v3) \ + if (TIFFGetField(in, tag, &v1, &v2, &v3)) TIFFSetField(out, tag, v1, v2, v3) +#define CopyField4(tag, v1, v2, v3, v4) \ + if (TIFFGetField(in, tag, &v1, &v2, &v3, &v4)) TIFFSetField(out, tag, v1, v2, v3, v4) + +static void +cpTag(TIFF* in, TIFF* out, uint16 tag, uint16 count, TIFFDataType type) +{ + switch (type) { + case TIFF_SHORT: + if (count == 1) { + uint16 shortv; + CopyField(tag, shortv); + } else if (count == 2) { + uint16 shortv1, shortv2; + CopyField2(tag, shortv1, shortv2); + } else if (count == 4) { + uint16 *tr, *tg, *tb, *ta; + CopyField4(tag, tr, tg, tb, ta); + } else if (count == (uint16) -1) { + uint16 shortv1; + uint16* shortav; + CopyField2(tag, shortv1, shortav); + } + break; + case TIFF_LONG: + { uint32 longv; + CopyField(tag, longv); + } + break; + case TIFF_LONG8: + { uint64 longv8; + CopyField(tag, longv8); + } + break; + case TIFF_SLONG8: + { int64 longv8; + CopyField(tag, longv8); + } + break; + case TIFF_RATIONAL: + if (count == 1) { + float floatv; + CopyField(tag, floatv); + } else if (count == (uint16) -1) { + float* floatav; + CopyField(tag, floatav); + } + break; + case TIFF_ASCII: + { char* stringv; + CopyField(tag, stringv); + } + break; + case TIFF_DOUBLE: + if (count == 1) { + double doublev; + CopyField(tag, doublev); + } else if (count == (uint16) -1) { + double* doubleav; + CopyField(tag, doubleav); + } + break; + case TIFF_IFD8: + { toff_t ifd8; + CopyField(tag, ifd8); + } + break; default: + TIFFError(TIFFFileName(in), + "Data type %d is not supported, tag %d skipped.", + tag, type); + } +} + +#undef CopyField4 +#undef CopyField3 +#undef CopyField2 +#undef CopyField + +static struct cpTag { + uint16 tag; + uint16 count; + TIFFDataType type; +} tags[] = { + { TIFFTAG_IMAGEWIDTH, 1, TIFF_LONG }, + { TIFFTAG_IMAGELENGTH, 1, TIFF_LONG }, + { TIFFTAG_BITSPERSAMPLE, 1, TIFF_SHORT }, + { TIFFTAG_COMPRESSION, 1, TIFF_SHORT }, + { TIFFTAG_FILLORDER, 1, TIFF_SHORT }, + { TIFFTAG_SAMPLESPERPIXEL, 1, TIFF_SHORT }, + { TIFFTAG_ROWSPERSTRIP, 1, TIFF_LONG }, + { TIFFTAG_PLANARCONFIG, 1, TIFF_SHORT }, + { TIFFTAG_GROUP3OPTIONS, 1, TIFF_LONG }, + { TIFFTAG_SUBFILETYPE, 1, TIFF_LONG }, + { TIFFTAG_PHOTOMETRIC, 1, TIFF_SHORT }, + { TIFFTAG_THRESHHOLDING, 1, TIFF_SHORT }, + { TIFFTAG_DOCUMENTNAME, 1, TIFF_ASCII }, + { TIFFTAG_IMAGEDESCRIPTION, 1, TIFF_ASCII }, + { TIFFTAG_MAKE, 1, TIFF_ASCII }, + { TIFFTAG_MODEL, 1, TIFF_ASCII }, + { TIFFTAG_ORIENTATION, 1, TIFF_SHORT }, + { TIFFTAG_MINSAMPLEVALUE, 1, TIFF_SHORT }, + { TIFFTAG_MAXSAMPLEVALUE, 1, TIFF_SHORT }, + { TIFFTAG_XRESOLUTION, 1, TIFF_RATIONAL }, + { TIFFTAG_YRESOLUTION, 1, TIFF_RATIONAL }, + { TIFFTAG_PAGENAME, 1, TIFF_ASCII }, + { TIFFTAG_XPOSITION, 1, TIFF_RATIONAL }, + { TIFFTAG_YPOSITION, 1, TIFF_RATIONAL }, + { TIFFTAG_GROUP4OPTIONS, 1, TIFF_LONG }, + { TIFFTAG_RESOLUTIONUNIT, 1, TIFF_SHORT }, + { TIFFTAG_PAGENUMBER, 2, TIFF_SHORT }, + { TIFFTAG_SOFTWARE, 1, TIFF_ASCII }, + { TIFFTAG_DATETIME, 1, TIFF_ASCII }, + { TIFFTAG_ARTIST, 1, TIFF_ASCII }, + { TIFFTAG_HOSTCOMPUTER, 1, TIFF_ASCII }, + { TIFFTAG_WHITEPOINT, 2, TIFF_RATIONAL }, + { TIFFTAG_PRIMARYCHROMATICITIES, (uint16) -1,TIFF_RATIONAL }, + { TIFFTAG_HALFTONEHINTS, 2, TIFF_SHORT }, + { TIFFTAG_BADFAXLINES, 1, TIFF_LONG }, + { TIFFTAG_CLEANFAXDATA, 1, TIFF_SHORT }, + { TIFFTAG_CONSECUTIVEBADFAXLINES, 1, TIFF_LONG }, + { TIFFTAG_INKSET, 1, TIFF_SHORT }, + { TIFFTAG_INKNAMES, 1, TIFF_ASCII }, + { TIFFTAG_DOTRANGE, 2, TIFF_SHORT }, + { TIFFTAG_TARGETPRINTER, 1, TIFF_ASCII }, + { TIFFTAG_SAMPLEFORMAT, 1, TIFF_SHORT }, + { TIFFTAG_YCBCRCOEFFICIENTS, (uint16) -1,TIFF_RATIONAL }, + { TIFFTAG_YCBCRSUBSAMPLING, 2, TIFF_SHORT }, + { TIFFTAG_YCBCRPOSITIONING, 1, TIFF_SHORT }, + { TIFFTAG_REFERENCEBLACKWHITE, (uint16) -1,TIFF_RATIONAL }, + { TIFFTAG_EXTRASAMPLES, (uint16) -1, TIFF_SHORT }, +}; +#define NTAGS (sizeof (tags) / sizeof (tags[0])) + +static void +cpTags(TIFF* in, TIFF* out) +{ + struct cpTag *p; + for (p = tags; p < &tags[NTAGS]; p++) + { + /* Horrible: but TIFFGetField() expects 2 arguments to be passed */ + /* if we request a tag that is defined in a codec, but that codec */ + /* isn't used */ + if( p->tag == TIFFTAG_GROUP3OPTIONS ) + { + + +// ... (10401 more chars) +``` diff --git a/tasks/csa159/pair_136342/task_prompt.md b/tasks/csa159/pair_136342/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_136342/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_136864/checker_template.cpp b/tasks/csa159/pair_136864/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_136864/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_136864/config.json b/tasks/csa159/pair_136864/config.json new file mode 100644 index 0000000000000000000000000000000000000000..601d1ca9be75d41fc6d2269e56ee36dabd2bef47 --- /dev/null +++ b/tasks/csa159/pair_136864/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "ImageMagick_ImageMagick6", + "before_commit": "b466a96965afc1308a4ace93f5535c2b770f294b", + "after_commit": "7486477aa00c5c7856b111506da075b6cdfa8b73", + "repo_path": "/workspace/repo/ImageMagick/ImageMagick6", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ImageMagick_ImageMagick6/b7c9c8972ef11481d92b1f57172fe72c54b0c4a2/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ImageMagick_ImageMagick6/b7c9c8972ef11481d92b1f57172fe72c54b0c4a2/compile_commands.json", + "changed_files": [ + "coders/tiff.c" + ], + "commit_message": "https://github.com/ImageMagick/ImageMagick/issues/1857", + "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_136864/patch.diff b/tasks/csa159/pair_136864/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0b54d63a393336156cbe75a2f6d6014986641f34 --- /dev/null +++ b/tasks/csa159/pair_136864/patch.diff @@ -0,0 +1,23 @@ +diff --git a/coders/tiff.c b/coders/tiff.c +index 0256a6c1e..15c993364 100644 +--- a/coders/tiff.c ++++ b/coders/tiff.c +@@ -1701,7 +1701,8 @@ RestoreMSCWarning + } + if (TIFFIsTiled(tiff) != MagickFalse) + method=ReadTileMethod; +- if (photometric == PHOTOMETRIC_LOGLUV) ++ if ((photometric == PHOTOMETRIC_LOGLUV) || ++ (photometric == PHOTOMETRIC_YCBCR)) + method=ReadGenericMethod; + if (image->compression == JPEGCompression) + method=GetJPEGMethod(image,tiff,photometric,bits_per_sample, +@@ -1834,8 +1835,6 @@ RestoreMSCWarning + Convert stripped TIFF image. + */ + extent=TIFFStripSize(tiff)+sizeof(uint32); +- if (photometric == PHOTOMETRIC_YCBCR) +- extent<<=1; + strip_pixels=(unsigned char *) AcquireQuantumMemory(extent, + sizeof(*strip_pixels)); + if (strip_pixels == (unsigned char *) NULL) \ No newline at end of file diff --git a/tasks/csa159/pair_136864/post_functions.txt b/tasks/csa159/pair_136864/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..81978e3cb90f884645196d5448b83be5f0149e20 --- /dev/null +++ b/tasks/csa159/pair_136864/post_functions.txt @@ -0,0 +1,282 @@ +### File: coders/tiff.c +```c +static Image *ReadTIFFImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ +#define ThrowTIFFException(severity,message) \ +{ \ + if (pixel_info != (MemoryInfo *) NULL) \ + pixel_info=RelinquishVirtualMemory(pixel_info); \ + if (quantum_info != (QuantumInfo *) NULL) \ + quantum_info=DestroyQuantumInfo(quantum_info); \ + TIFFClose(tiff); \ + ThrowReaderException(severity,message); \ +} + + const char + *option; + + float + *chromaticity, + x_position, + y_position, + x_resolution, + y_resolution; + + Image + *image; + + int + tiff_status; + + MagickBooleanType + more_frames, + status; + + MemoryInfo + *pixel_info = (MemoryInfo *) NULL; + + QuantumInfo + *quantum_info; + + QuantumType + quantum_type; + + register ssize_t + i; + + size_t + number_pixels, + pad; + + ssize_t + y; + + TIFF + *tiff; + + TIFFMethodType + method; + + uint16 + compress_tag, + bits_per_sample, + endian, + extra_samples, + interlace, + max_sample_value, + min_sample_value, + orientation, + pages, + photometric, + *sample_info, + sample_format, + samples_per_pixel, + units, + value; + + uint32 + height, + rows_per_strip, + width; + + unsigned char + *pixels; + + void + *sans[2] = { NULL, NULL }; + + /* + Open image. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + if (image_info->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", + image_info->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + image=AcquireImage(image_info); + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + (void) SetMagickThreadValue(tiff_exception,exception); + tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, + TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, + TIFFUnmapBlob); + if (tiff == (TIFF *) NULL) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + if (exception->severity > ErrorException) + { + TIFFClose(tiff); + image=DestroyImageList(image); + return((Image *) NULL); + } + if (image_info->number_scenes != 0) + { + /* + Generate blank images for subimage specification (e.g. image.tif[4]. + We need to check the number of directores because it is possible that + the subimage(s) are stored in the photoshop profile. + */ + if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff)) + { + for (i=0; i < (ssize_t) image_info->scene; i++) + { + status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; + if (status == MagickFalse) + { + TIFFClose(tiff); + image=DestroyImageList(image); + return((Image *) NULL); + } + AcquireNextImage(image_info,image); + if (GetNextImageInList(image) == (Image *) NULL) + { + TIFFClose(tiff); + image=DestroyImageList(image); + return((Image *) NULL); + } + image=SyncNextImageInList(image); + } + } + } + more_frames=MagickTrue; + do + { +DisableMSCWarning(4127) + if (0 && (image_info->verbose != MagickFalse)) + TIFFPrintDirectory(tiff,stdout,MagickFalse); +RestoreMSCWarning + photometric=PHOTOMETRIC_RGB; + if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || + (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1)) + { + TIFFClose(tiff); + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + } + if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) && + ((bits_per_sample <= 0) || (bits_per_sample > 32))) + { + TIFFClose(tiff); + ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); + } + if (sample_format == SAMPLEFORMAT_IEEEFP) + (void) SetImageProperty(image,"quantum:format","floating-point"); + switch (photometric) + { + case PHOTOMETRIC_MINISBLACK: + { + (void) SetImageProperty(image,"tiff:photometric","min-is-black"); + break; + } + case PHOTOMETRIC_MINISWHITE: + { + (void) SetImageProperty(image,"tiff:photometric","min-is-white"); + break; + } + case PHOTOMETRIC_PALETTE: + { + (void) SetImageProperty(image,"tiff:photometric","palette"); + break; + } + case PHOTOMETRIC_RGB: + { + (void) SetImageProperty(image,"tiff:photometric","RGB"); + break; + } + case PHOTOMETRIC_CIELAB: + { + (void) SetImageProperty(image,"tiff:photometric","CIELAB"); + break; + } + case PHOTOMETRIC_LOGL: + { + (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); + break; + } + case PHOTOMETRIC_LOGLUV: + { + (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); + break; + } +#if defined(PHOTOMETRIC_MASK) + case PHOTOMETRIC_MASK: + { + (void) SetImageProperty(image,"tiff:photometric","MASK"); + break; + } +#endif + case PHOTOMETRIC_SEPARATED: + { + (void) SetImageProperty(image,"tiff:photometric","separated"); + break; + } + case PHOTOMETRIC_YCBCR: + { + (void) SetImageProperty(image,"tiff:photometric","YCBCR"); + break; + } + default: + { + (void) SetImageProperty(image,"tiff:photometric","unknown"); + break; + } + } + if (image->debug != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", + (unsigned int) width,(unsigned int) height); + (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", + interlace); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "Bits per sample: %u",bits_per_sample); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "Min sample value: %u",min_sample_value); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "Max sample value: %u",max_sample_value); + (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " + "interpretation: %s",GetImageProperty(image,"tiff:photometric")); + } + image->columns=(size_t) width; + image->rows=(size_t) height; + image->depth=(size_t) bits_per_sample; + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", + (double) image->depth); + image->endian=MSBEndian; + if (endian == FILLORDER_LSB2MSB) + image->endian=LSBEndian; +#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) + if (TIFFIsBigEndian(tiff) == 0) + { + (void) SetImageProperty(image,"tiff:endian","lsb"); + image->endian=LSBEndian; + } + else + { + (void) SetImageProperty(image,"tiff:endian","msb"); + image->endian=MSBEndian; + } +#endif + if ((photometric == PHOTOMETRIC_MINISBLACK) || + (photometric == PHOTOMETRIC_MINISWHITE)) + + +// ... (24492 more chars) +``` diff --git a/tasks/csa159/pair_136864/pre_functions.txt b/tasks/csa159/pair_136864/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..cd17b25ca939ef5f5bbd21abc7656f5a531773c3 --- /dev/null +++ b/tasks/csa159/pair_136864/pre_functions.txt @@ -0,0 +1,282 @@ +### File: coders/tiff.c +```c +static Image *ReadTIFFImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ +#define ThrowTIFFException(severity,message) \ +{ \ + if (pixel_info != (MemoryInfo *) NULL) \ + pixel_info=RelinquishVirtualMemory(pixel_info); \ + if (quantum_info != (QuantumInfo *) NULL) \ + quantum_info=DestroyQuantumInfo(quantum_info); \ + TIFFClose(tiff); \ + ThrowReaderException(severity,message); \ +} + + const char + *option; + + float + *chromaticity, + x_position, + y_position, + x_resolution, + y_resolution; + + Image + *image; + + int + tiff_status; + + MagickBooleanType + more_frames, + status; + + MemoryInfo + *pixel_info = (MemoryInfo *) NULL; + + QuantumInfo + *quantum_info; + + QuantumType + quantum_type; + + register ssize_t + i; + + size_t + number_pixels, + pad; + + ssize_t + y; + + TIFF + *tiff; + + TIFFMethodType + method; + + uint16 + compress_tag, + bits_per_sample, + endian, + extra_samples, + interlace, + max_sample_value, + min_sample_value, + orientation, + pages, + photometric, + *sample_info, + sample_format, + samples_per_pixel, + units, + value; + + uint32 + height, + rows_per_strip, + width; + + unsigned char + *pixels; + + void + *sans[2] = { NULL, NULL }; + + /* + Open image. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + if (image_info->debug != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", + image_info->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + image=AcquireImage(image_info); + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + (void) SetMagickThreadValue(tiff_exception,exception); + tiff=TIFFClientOpen(image->filename,"rb",(thandle_t) image,TIFFReadBlob, + TIFFWriteBlob,TIFFSeekBlob,TIFFCloseBlob,TIFFGetBlobSize,TIFFMapBlob, + TIFFUnmapBlob); + if (tiff == (TIFF *) NULL) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + if (exception->severity > ErrorException) + { + TIFFClose(tiff); + image=DestroyImageList(image); + return((Image *) NULL); + } + if (image_info->number_scenes != 0) + { + /* + Generate blank images for subimage specification (e.g. image.tif[4]. + We need to check the number of directores because it is possible that + the subimage(s) are stored in the photoshop profile. + */ + if (image_info->scene < (size_t)TIFFNumberOfDirectories(tiff)) + { + for (i=0; i < (ssize_t) image_info->scene; i++) + { + status=TIFFReadDirectory(tiff) != 0 ? MagickTrue : MagickFalse; + if (status == MagickFalse) + { + TIFFClose(tiff); + image=DestroyImageList(image); + return((Image *) NULL); + } + AcquireNextImage(image_info,image); + if (GetNextImageInList(image) == (Image *) NULL) + { + TIFFClose(tiff); + image=DestroyImageList(image); + return((Image *) NULL); + } + image=SyncNextImageInList(image); + } + } + } + more_frames=MagickTrue; + do + { +DisableMSCWarning(4127) + if (0 && (image_info->verbose != MagickFalse)) + TIFFPrintDirectory(tiff,stdout,MagickFalse); +RestoreMSCWarning + photometric=PHOTOMETRIC_RGB; + if ((TIFFGetField(tiff,TIFFTAG_IMAGEWIDTH,&width) != 1) || + (TIFFGetField(tiff,TIFFTAG_IMAGELENGTH,&height) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_PHOTOMETRIC,&photometric,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_COMPRESSION,&compress_tag,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_FILLORDER,&endian,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_PLANARCONFIG,&interlace,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLESPERPIXEL,&samples_per_pixel,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_BITSPERSAMPLE,&bits_per_sample,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_SAMPLEFORMAT,&sample_format,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_MINSAMPLEVALUE,&min_sample_value,sans) != 1) || + (TIFFGetFieldDefaulted(tiff,TIFFTAG_MAXSAMPLEVALUE,&max_sample_value,sans) != 1)) + { + TIFFClose(tiff); + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + } + if (((sample_format != SAMPLEFORMAT_IEEEFP) || (bits_per_sample != 64)) && + ((bits_per_sample <= 0) || (bits_per_sample > 32))) + { + TIFFClose(tiff); + ThrowReaderException(CorruptImageError,"UnsupportedBitsPerPixel"); + } + if (sample_format == SAMPLEFORMAT_IEEEFP) + (void) SetImageProperty(image,"quantum:format","floating-point"); + switch (photometric) + { + case PHOTOMETRIC_MINISBLACK: + { + (void) SetImageProperty(image,"tiff:photometric","min-is-black"); + break; + } + case PHOTOMETRIC_MINISWHITE: + { + (void) SetImageProperty(image,"tiff:photometric","min-is-white"); + break; + } + case PHOTOMETRIC_PALETTE: + { + (void) SetImageProperty(image,"tiff:photometric","palette"); + break; + } + case PHOTOMETRIC_RGB: + { + (void) SetImageProperty(image,"tiff:photometric","RGB"); + break; + } + case PHOTOMETRIC_CIELAB: + { + (void) SetImageProperty(image,"tiff:photometric","CIELAB"); + break; + } + case PHOTOMETRIC_LOGL: + { + (void) SetImageProperty(image,"tiff:photometric","CIE Log2(L)"); + break; + } + case PHOTOMETRIC_LOGLUV: + { + (void) SetImageProperty(image,"tiff:photometric","LOGLUV"); + break; + } +#if defined(PHOTOMETRIC_MASK) + case PHOTOMETRIC_MASK: + { + (void) SetImageProperty(image,"tiff:photometric","MASK"); + break; + } +#endif + case PHOTOMETRIC_SEPARATED: + { + (void) SetImageProperty(image,"tiff:photometric","separated"); + break; + } + case PHOTOMETRIC_YCBCR: + { + (void) SetImageProperty(image,"tiff:photometric","YCBCR"); + break; + } + default: + { + (void) SetImageProperty(image,"tiff:photometric","unknown"); + break; + } + } + if (image->debug != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %ux%u", + (unsigned int) width,(unsigned int) height); + (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Interlace: %u", + interlace); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "Bits per sample: %u",bits_per_sample); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "Min sample value: %u",min_sample_value); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + "Max sample value: %u",max_sample_value); + (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Photometric " + "interpretation: %s",GetImageProperty(image,"tiff:photometric")); + } + image->columns=(size_t) width; + image->rows=(size_t) height; + image->depth=(size_t) bits_per_sample; + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Image depth: %.20g", + (double) image->depth); + image->endian=MSBEndian; + if (endian == FILLORDER_LSB2MSB) + image->endian=LSBEndian; +#if defined(MAGICKCORE_HAVE_TIFFISBIGENDIAN) + if (TIFFIsBigEndian(tiff) == 0) + { + (void) SetImageProperty(image,"tiff:endian","lsb"); + image->endian=LSBEndian; + } + else + { + (void) SetImageProperty(image,"tiff:endian","msb"); + image->endian=MSBEndian; + } +#endif + if ((photometric == PHOTOMETRIC_MINISBLACK) || + (photometric == PHOTOMETRIC_MINISWHITE)) + + +// ... (24512 more chars) +``` diff --git a/tasks/csa159/pair_136864/task_prompt.md b/tasks/csa159/pair_136864/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..f6025ce05461a9b336faf74b80ef7d265754e3aa --- /dev/null +++ b/tasks/csa159/pair_136864/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 failed rollout proved only that a candidate guard dominates the decode sink; it did not prove that the guard's assignment remains the reaching definition of the dispatch variable at the switch or sink. +- The guard recognizer unsoundly accepted a YCbCr equality beneath logical AND, although the assignment then protects only the subset of YCbCr executions satisfying the other operand. +- A recursively discovered assignment anywhere in the taken branch was treated as guaranteed, even when nested under another conditional or followed by a reassignment. +- Only the first TIFFReadEncodedStrip call was analyzed, leaving additional relevant sinks unchecked. +- The report condition omitted the allocation and buffer-flow evidence: it did not connect TIFFStripSize-derived extent arithmetic and AcquireQuantumMemory to the destination passed to TIFFReadEncodedStrip. +- The overflow model understated the pre-patch behavior by overlooking the unchecked YCbCr extent left shift and its possible wraparound. +- Scope identification accepted any enum-based switch rather than establishing the relevant TIFF method dispatch relation, reducing semantic precision and process quality. + +### 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 semantic score at or above the configured threshold. +- Remain independent of changed-line, commit, and patch-anchor locations. +- Remain free of patch-local identifier and literal hardcoding. + +### Required semantic proof + +- For each candidate sink, establish that TIFFReadEncodedStrip writes through the same buffer object produced by AcquireQuantumMemory from an extent derived from TIFFStripSize. +- Model the buggy YCbCr allocation arithmetic, including the pre-patch extent left shift, and establish how unchecked wraparound can make the allocated object smaller than the size supplied to or consumed by the strip decode path. +- Establish that PHOTOMETRIC_YCBCR can select the TIFF strip-method case containing the sink in the vulnerable source. +- Treat the patched source as safe only when the YCbCr comparison guarantees execution of an assignment that moves the same dispatch variable away from the strip case. +- Prove with CFG reachability and reaching-definition or kill analysis that no path from the protective assignment to the method dispatch overwrites the dispatch variable with the strip method. +- For compound conditions, prove that every YCbCr execution takes the protective branch; disjunction is acceptable only when the YCbCr equality itself is sufficient, while conjunction requires proof that its other conditions always hold. +- Analyze and classify every relevant strip-decode sink independently. + +### Implementation constraints + +- Use a whole-function callback such as check::BeginFunction so analysis does not depend on ExprEngine exploration of the unvisited strip case. +- Build the function CFG and use dominance, reachability, same-block ordering, and definition-kill relationships to prove the guard-to-dispatch-to-sink relation. +- Resolve direct callees, declaration identities, argument identities, switch and case ancestry, assignments, allocation expressions, and constants through AST APIs and constant evaluation. +- Identify the dispatch as the project's TIFFMethodType relation, not merely an arbitrary enum switch, while avoiding dependence on local variable names. +- Associate AcquireQuantumMemory's result with the buffer argument of each TIFFReadEncodedStrip call and associate its extent with TIFFStripSize-based arithmetic. +- Emit one localized BasicBugReport per unprotected relevant sink, with primary location and source range on the TIFFReadEncodedStrip call rather than the function-entry callback. +- Use conservative semantics: inability to prove a complete guard, unmodified reaching assignment, or required buffer relation must not be interpreted as proof of safety. +- Keep scope project-general using stable TIFF API/type semantics and structural relationships, without source lines, commit IDs, changed text, or patch-only names. + +### Validation checklist + +- Compile the new checker plugin against the available Clang Static Analyzer API and verify checker registration and report construction. +- Scan the vulnerable source and require a diagnostic in coders/tiff.c::ReadTIFFImage at the relevant TIFFReadEncodedStrip call. +- Scan the patched source and require zero diagnostics after proving the YCbCr-to-generic dispatch guard. +- Run code verification and cross-validation, preserving N_buggy=1, N_patched=0, one relevant disappeared warning, and no unrelated disappeared warnings. +- Verify diagnostic locality at the vulnerable decode sink and record its distance from both the allocation change and guard change. +- Test a conjunction guard and a conditionally nested assignment; neither may suppress unless protection is guaranteed for all YCbCr flows. +- Test reassignment of the method after the guard and before dispatch; restoration of the strip method must produce a report. +- Test multiple strip-decode sinks plus allocation/buffer mismatches, then run refinement and require an accepted or clean result. + +### Avoid and forbidden regressions + +- Do not rely on check::PreStmt, check::PostCall, or sink-time ProgramState observations because the analyzer budget did not explore the strip case. +- Do not equate lexical precedence or guard-block dominance alone with preservation of the assigned dispatch value. +- Do not accept any assignment to a non-strip constant when that assignment is optional, conditionally nested, or subsequently killed. +- Do not treat PHOTOMETRIC_YCBCR under logical AND as an unconditional rejection of all YCbCr inputs. +- Do not report every TIFFReadEncodedStrip call solely from its callee name and enclosing switch shape. +- Do not stop after finding the first sink in a function. +- Do not omit the TIFFStripSize-derived allocation, unchecked shift or wraparound, destination-buffer, and decode-size relationships central to the overflow. +- Do not introduce line-number matching, changed-text matching, local variable-name matching, or arbitrary enum acceptance. diff --git a/tasks/csa159/pair_137200/checker_template.cpp b/tasks/csa159/pair_137200/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_137200/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_137200/config.json b/tasks/csa159/pair_137200/config.json new file mode 100644 index 0000000000000000000000000000000000000000..c7b9dd64490938685d313aea5c6923679d316f61 --- /dev/null +++ b/tasks/csa159/pair_137200/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "ccxvii_mujs", + "before_commit": "77ab465f1c394bb77f00966cd950650f3f53cb24", + "after_commit": "fa3d30fd18c348bb4b1f3858fb860f4fcd4b2045", + "repo_path": "/workspace/repo/ccxvii/mujs", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ccxvii_mujs/eed76191580004d5461bdf8accd8ca23e8541b57/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ccxvii_mujs/eed76191580004d5461bdf8accd8ca23e8541b57/compile_commands.json", + "changed_files": [ + "regexp.c" + ], + "commit_message": "Fix 697448: Limit the maximum program size to something reasonable.\n\nA regular expression with lots of nested repetition can lead to\ninteger overflow when calculating the size of the program.\n\nCheck max program size when counting the number of instructions required\nfor a loop, so we can bail before integer overflow can happen.", + "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_137200/patch.diff b/tasks/csa159/pair_137200/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..612851c019deeaf4db0dfd8ea7cd668d1d7bc740 --- /dev/null +++ b/tasks/csa159/pair_137200/patch.diff @@ -0,0 +1,84 @@ +diff --git a/regexp.c b/regexp.c +index 01c18a3..4a5948b 100644 +--- a/regexp.c ++++ b/regexp.c +@@ -16,6 +16,7 @@ + #define REPINF 255 + #define MAXTHREAD 1000 + #define MAXSUB REG_MAXSUB ++#define MAXPROG (32 << 10) + + typedef struct Reclass Reclass; + typedef struct Renode Renode; +@@ -595,23 +596,25 @@ struct Reinst { + Reinst *y; + }; + +-static int count(Renode *node) ++static int count(struct cstate *g, Renode *node) + { +- int min, max; ++ int min, max, n; + if (!node) return 0; + switch (node->type) { + default: return 1; +- case P_CAT: return count(node->x) + count(node->y); +- case P_ALT: return count(node->x) + count(node->y) + 2; ++ case P_CAT: return count(g, node->x) + count(g, node->y); ++ case P_ALT: return count(g, node->x) + count(g, node->y) + 2; + case P_REP: + min = node->m; + max = node->n; +- if (min == max) return count(node->x) * min; +- if (max < REPINF) return count(node->x) * max + (max - min); +- return count(node->x) * (min + 1) + 2; +- case P_PAR: return count(node->x) + 2; +- case P_PLA: return count(node->x) + 2; +- case P_NLA: return count(node->x) + 2; ++ if (min == max) n = count(g, node->x) * min; ++ else if (max < REPINF) n = count(g, node->x) * max + (max - min); ++ else n = count(g, node->x) * (min + 1) + 2; ++ if (n < 0 || n > MAXPROG) die(g, "program too large"); ++ return n; ++ case P_PAR: return count(g, node->x) + 2; ++ case P_PLA: return count(g, node->x) + 2; ++ case P_NLA: return count(g, node->x) + 2; + } + } + +@@ -813,7 +816,7 @@ Reprog *regcompx(void *(*alloc)(void *ctx, void *p, int n), void *ctx, + struct cstate g; + Renode *node; + Reinst *split, *jump; +- int i; ++ int i, n; + + g.pstart = NULL; + g.prog = NULL; +@@ -847,8 +850,17 @@ Reprog *regcompx(void *(*alloc)(void *ctx, void *p, int n), void *ctx, + if (g.lookahead != 0) + die(&g, "syntax error"); + ++#ifdef TEST ++ dumpnode(node); ++ putchar('\n'); ++#endif ++ ++ n = 6 + count(&g, node); ++ if (n < 0 || n > MAXPROG) ++ die(&g, "program too large"); ++ + g.prog->nsub = g.nsub; +- g.prog->start = g.prog->end = alloc(ctx, NULL, (count(node) + 6) * sizeof (Reinst)); ++ g.prog->start = g.prog->end = alloc(ctx, NULL, n * sizeof (Reinst)); + if (!g.prog->start) + die(&g, "cannot allocate regular expression instruction list"); + +@@ -864,8 +876,6 @@ Reprog *regcompx(void *(*alloc)(void *ctx, void *p, int n), void *ctx, + emit(g.prog, I_END); + + #ifdef TEST +- dumpnode(node); +- putchar('\n'); + dumpprog(g.prog); + #endif \ No newline at end of file diff --git a/tasks/csa159/pair_137200/post_functions.txt b/tasks/csa159/pair_137200/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2e75c7998ffc42605dca963d611db944de061f3a --- /dev/null +++ b/tasks/csa159/pair_137200/post_functions.txt @@ -0,0 +1,127 @@ +### File: regexp.c +```c +static int count(struct cstate *g, Renode *node) +{ + int min, max, n; + if (!node) return 0; + switch (node->type) { + default: return 1; + case P_CAT: return count(g, node->x) + count(g, node->y); + case P_ALT: return count(g, node->x) + count(g, node->y) + 2; + case P_REP: + min = node->m; + max = node->n; + if (min == max) n = count(g, node->x) * min; + else if (max < REPINF) n = count(g, node->x) * max + (max - min); + else n = count(g, node->x) * (min + 1) + 2; + if (n < 0 || n > MAXPROG) die(g, "program too large"); + return n; + case P_PAR: return count(g, node->x) + 2; + case P_PLA: return count(g, node->x) + 2; + case P_NLA: return count(g, node->x) + 2; + } +} + +static void dumpprog(Reprog *prog) +{ + Reinst *inst; + int i; + for (i = 0, inst = prog->start; inst < prog->end; ++i, ++inst) { + printf("% 5d: ", i); + switch (inst->opcode) { + case I_END: puts("end"); break; + case I_JUMP: printf("jump %d\n", (int)(inst->x - prog->start)); break; + case I_SPLIT: printf("split %d %d\n", (int)(inst->x - prog->start), (int)(inst->y - prog->start)); break; + case I_PLA: printf("pla %d %d\n", (int)(inst->x - prog->start), (int)(inst->y - prog->start)); break; + case I_NLA: printf("nla %d %d\n", (int)(inst->x - prog->start), (int)(inst->y - prog->start)); break; + case I_ANY: puts("any"); break; + case I_ANYNL: puts("anynl"); break; + case I_CHAR: printf(inst->c >= 32 && inst->c < 127 ? "char '%c'\n" : "char U+%04X\n", inst->c); break; + case I_CCLASS: puts("cclass"); break; + case I_NCCLASS: puts("ncclass"); break; + case I_REF: printf("ref %d\n", inst->n); break; + case I_BOL: puts("bol"); break; + case I_EOL: puts("eol"); break; + case I_WORD: puts("word"); break; + case I_NWORD: puts("nword"); break; + case I_LPAR: printf("lpar %d\n", inst->n); break; + case I_RPAR: printf("rpar %d\n", inst->n); break; + } + } +} + +Reprog *regcompx(void *(*alloc)(void *ctx, void *p, int n), void *ctx, + const char *pattern, int cflags, const char **errorp) +{ + struct cstate g; + Renode *node; + Reinst *split, *jump; + int i, n; + + g.pstart = NULL; + g.prog = NULL; + + if (setjmp(g.kaboom)) { + if (errorp) *errorp = g.error; + alloc(ctx, g.pstart, 0); + alloc(ctx, g.prog, 0); + return NULL; + } + + g.prog = alloc(ctx, NULL, sizeof (Reprog)); + if (!g.prog) + die(&g, "cannot allocate regular expression"); + g.pstart = g.pend = alloc(ctx, NULL, sizeof (Renode) * strlen(pattern) * 2); + if (!g.pstart) + die(&g, "cannot allocate regular expression parse list"); + + g.source = pattern; + g.ncclass = 0; + g.nsub = 1; + for (i = 0; i < MAXSUB; ++i) + g.sub[i] = 0; + + g.prog->flags = cflags; + + next(&g); + node = parsealt(&g); + if (g.lookahead == ')') + die(&g, "unmatched ')'"); + if (g.lookahead != 0) + die(&g, "syntax error"); + +#ifdef TEST + dumpnode(node); + putchar('\n'); +#endif + + n = 6 + count(&g, node); + if (n < 0 || n > MAXPROG) + die(&g, "program too large"); + + g.prog->nsub = g.nsub; + g.prog->start = g.prog->end = alloc(ctx, NULL, n * sizeof (Reinst)); + if (!g.prog->start) + die(&g, "cannot allocate regular expression instruction list"); + + split = emit(g.prog, I_SPLIT); + split->x = split + 3; + split->y = split + 1; + emit(g.prog, I_ANYNL); + jump = emit(g.prog, I_JUMP); + jump->x = split; + emit(g.prog, I_LPAR); + compile(g.prog, node); + emit(g.prog, I_RPAR); + emit(g.prog, I_END); + +#ifdef TEST + dumpprog(g.prog); +#endif + + alloc(ctx, g.pstart, 0); + + if (errorp) *errorp = NULL; + return g.prog; +} +``` diff --git a/tasks/csa159/pair_137200/pre_functions.txt b/tasks/csa159/pair_137200/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..83d83c69e5412f526222877b1d2739d0afc7a05f --- /dev/null +++ b/tasks/csa159/pair_137200/pre_functions.txt @@ -0,0 +1,101 @@ +### File: regexp.c +```c +static int count(Renode *node) +{ + int min, max; + if (!node) return 0; + switch (node->type) { + default: return 1; + case P_CAT: return count(node->x) + count(node->y); + case P_ALT: return count(node->x) + count(node->y) + 2; + case P_REP: + min = node->m; + max = node->n; + if (min == max) return count(node->x) * min; + if (max < REPINF) return count(node->x) * max + (max - min); + return count(node->x) * (min + 1) + 2; + case P_PAR: return count(node->x) + 2; + case P_PLA: return count(node->x) + 2; + case P_NLA: return count(node->x) + 2; + } +} + +static Reinst *emit(Reprog *prog, int opcode) +{ + Reinst *inst = prog->end++; + inst->opcode = opcode; + inst->n = 0; + inst->c = 0; + inst->cc = NULL; + inst->x = inst->y = NULL; + return inst; +} + +Reprog *regcompx(void *(*alloc)(void *ctx, void *p, int n), void *ctx, + const char *pattern, int cflags, const char **errorp) +{ + struct cstate g; + Renode *node; + Reinst *split, *jump; + int i; + + g.pstart = NULL; + g.prog = NULL; + + if (setjmp(g.kaboom)) { + if (errorp) *errorp = g.error; + alloc(ctx, g.pstart, 0); + alloc(ctx, g.prog, 0); + return NULL; + } + + g.prog = alloc(ctx, NULL, sizeof (Reprog)); + if (!g.prog) + die(&g, "cannot allocate regular expression"); + g.pstart = g.pend = alloc(ctx, NULL, sizeof (Renode) * strlen(pattern) * 2); + if (!g.pstart) + die(&g, "cannot allocate regular expression parse list"); + + g.source = pattern; + g.ncclass = 0; + g.nsub = 1; + for (i = 0; i < MAXSUB; ++i) + g.sub[i] = 0; + + g.prog->flags = cflags; + + next(&g); + node = parsealt(&g); + if (g.lookahead == ')') + die(&g, "unmatched ')'"); + if (g.lookahead != 0) + die(&g, "syntax error"); + + g.prog->nsub = g.nsub; + g.prog->start = g.prog->end = alloc(ctx, NULL, (count(node) + 6) * sizeof (Reinst)); + if (!g.prog->start) + die(&g, "cannot allocate regular expression instruction list"); + + split = emit(g.prog, I_SPLIT); + split->x = split + 3; + split->y = split + 1; + emit(g.prog, I_ANYNL); + jump = emit(g.prog, I_JUMP); + jump->x = split; + emit(g.prog, I_LPAR); + compile(g.prog, node); + emit(g.prog, I_RPAR); + emit(g.prog, I_END); + +#ifdef TEST + dumpnode(node); + putchar('\n'); + dumpprog(g.prog); +#endif + + alloc(ctx, g.pstart, 0); + + if (errorp) *errorp = NULL; + return g.prog; +} +``` diff --git a/tasks/csa159/pair_137200/task_prompt.md b/tasks/csa159/pair_137200/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..08997f4d6fe4a9d6fc2e6fd5a260d98872f95496 --- /dev/null +++ b/tasks/csa159/pair_137200/task_prompt.md @@ -0,0 +1,378 @@ +# 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 only failed ledger check is process_score (73.91 below threshold); objective G6, semantic score 7.0, refinement, hard_validation, anchor_free, and hardcoding_free already passed. +- Patch-understanding artifacts were incomplete: state.json was empty, has_patch_analysis was false, and CSA analysis fields were left unfilled despite comments describing the CWE-190 count-times-repetition overflow. +- Detection-plan quality was reduced because structured plan fields were unfilled and the safe_condition was not recorded as a dominating terminating upper-bound guard on the stored product. +- Validation recovery lost points on four compile failures (incomplete CallEvent, wrong CallEvent API, missing source path, incomplete CFGStmtMap) with the same missing-header class repeated across 15 cycles. +- The rollout was marked salvaged after budget exhaustion, so process quality stayed unproven even though buggy/patched scans were plausible (n_buggy=3, n_patched=0). + +### 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 CSA mechanism level. +- Preserve semantic score at or above the configured threshold. +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Pre-patch P_REP in count() returns a signed ≤32-bit product of a call-computed instruction count and a repetition factor (count(x)*min, count(x)*max+(max-min), count(x)*(min+1)+2) with no bound check; that wrapped value is the overflowable size/count (CWE-190) the patch later stored in n. +- A site is unsafe iff that product is returned or otherwise consumed without an intervening IfStmt that references the stored local, compares it to a non-negative constant upper bound (including n<0 || n>LIMIT), and whose then-branch cannot fall through. +- A site is safe iff the product is stored in a local signed integer and every later use, including return n, is dominated by such a terminating guard (die/longjmp/noreturn/return on the out-of-range branch), matching the post-patch MAXPROG protocol. +- The checkable relation is intra-function guard-vs-use on the size product; proving overflow into the later alloc(n*sizeof(Reinst)) or emit path is not required to establish the patched protocol. + +### Implementation constraints + +- Register a CheckerRegistry checker and analyze each FunctionDecl body via checkASTCodeBody and/or path-sensitive callbacks, obtaining CFG, CFGStmtMap, ParentMap, and CFGDomTree from AnalysisDeclContext; full symbolic overflow math is optional, not mandatory. +- Consider only signed integer BO_Mul of width ≤32 bits with a CallExpr somewhere in an operand; classify the consumer by walking parents to ReturnStmt, a local signed store, or other use, and emit the report at the multiplication with its source range. +- Treat a use as protected only when an IfStmt bounds-guard on that local dominates it (same-block earlier CFG index, CFGDomTree, or earlier sibling in the same CompoundStmt) and stmt/callee never-return analysis shows the then-branch terminates (ReturnStmt, isNoReturn, or abort/exit/longjmp/assert, including callees whose body ends in those). +- Limit diagnostics to the main-file TU; do not key behavior on regexp.c, count, regcompx, die, MAXPROG, the string program too large, or patch line numbers. +- Include complete analysis headers before the first compile (CFGStmtMap.h, Dominators.h, ParentMap.h, PathDiagnostic.h, CheckerRegistry.h); do not dereference CallEvent or CFGStmtMap without their defining headers. +- Do not use source-text matching, project-specific path filters, or an allocation-argument requirement that would hide the three P_REP return products. + +### Validation checklist + +- Compile the checker to a shared object with clang++ -std=c++17 -fPIC -shared and confirm a clean checker.so with no incomplete-type or missing-file errors. +- Scan pre-patch regexp.c and require exactly three warnings, all inside regexp.c::count, on the three P_REP signed multiplications (count(...)*min, *max, and *(min+1)). +- Scan post-patch regexp.c and require zero warnings: n = product; if (n < 0 || n > MAXPROG) die(...); return n must silence count(), and the guarded n * sizeof(Reinst) alloc in regcompx must remain clean. +- Confirm location quality: reports on the mul expressions, median distance 0 from the changed P_REP lines, n_buggy=3, n_patched=0, relevance_ratio=1.0, sparsity_ratio=1.0, no reports outside patched functions. +- Re-run code verification and cross-validation (VALID with N_buggy=3 N_patched=0, T_VALID=50) and keep refinement accepted/clean. +- Before finish, fill patch-analysis and structured detection-plan artifacts, including safe_condition = dominating terminating upper-bound guard and sink = unguarded return/use of the size product. + +### Avoid and forbidden regressions + +- Do not ship empty state.json, empty scope_statement, or unfilled structured plan fields. +- Do not repeat the incomplete-type compile loop (CallEvent without CallEvent.h, CFGStmtMap without CFGStmtMap.h, or compiling a non-existent debug_checker.cpp path). +- Do not make reporting depend on MAXPROG, die, count, regcompx, regexp.c, commit hashes, or exact patch line numbers. +- Do not demand interprocedural taint from count() into alloc/emit, and do not require an allocation sink as the report condition (that would miss the intra-function P_REP returns). +- Do not replace guard-dominance plus never-return reasoning with syntax-only multiplication matching or unsigned sizeof multiplies. +- Do not regress the 3-vs-0 differential, G6, semantic score ≥ 7.0, refinement cleanliness, anchor_free, or hardcoding_free. +- Do not copy, resume, or reconstruct the prior SizeCountOverflowChecker sources. diff --git a/tasks/csa159/pair_137357/checker_template.cpp b/tasks/csa159/pair_137357/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_137357/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_137357/config.json b/tasks/csa159/pair_137357/config.json new file mode 100644 index 0000000000000000000000000000000000000000..bd80e4c37703701200643e1bfa97dfca943eb3b1 --- /dev/null +++ b/tasks/csa159/pair_137357/config.json @@ -0,0 +1,20 @@ +{ + "project_id": "jerryscript-project_jerryscript", + "before_commit": "4aa27371b6de44d87d96713ef3b3d87dd988a957", + "after_commit": "bd1c4df9a608cc7193330944c857ca4f6294b993", + "repo_path": "/workspace/repo/jerryscript-project/jerryscript", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/jerryscript-project_jerryscript/aaf0442611e0707a3bc680d30b532b93e30e1066/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/jerryscript-project_jerryscript/aaf0442611e0707a3bc680d30b532b93e30e1066/compile_commands.json", + "changed_files": [ + "jerry-core/parser/js/js-parser-statm.c", + "jerry-core/parser/js/js-scanner-ops.c" + ], + "commit_message": "Fix keyword parsing after use strict. (#3740)\n\nJerryScript-DCO-1.0-Signed-off-by: Zoltan Herczeg zherczeg.u-szeged@partner.samsung.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_137357/patch.diff b/tasks/csa159/pair_137357/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b206c8f25b6137116b019e25d2abb4fab2b54b80 --- /dev/null +++ b/tasks/csa159/pair_137357/patch.diff @@ -0,0 +1,232 @@ +diff --git a/jerry-core/parser/js/js-parser-statm.c b/jerry-core/parser/js/js-parser-statm.c +index 38182f95..0647a54a 100644 +--- a/jerry-core/parser/js/js-parser-statm.c ++++ b/jerry-core/parser/js/js-parser-statm.c +@@ -2592,6 +2592,16 @@ parser_parse_label (parser_context_t *context_p) /**< context */ + parser_stack_iterator_init (context_p, &context_p->last_statement); + } /* parser_parse_label */ + ++/** ++ * Strict mode types for statement parsing. ++ */ ++typedef enum ++{ ++ PARSER_USE_STRICT_NOT_FOUND = 0, /**< 'use strict' directive is not found */ ++ PARSER_USE_STRICT_FOUND = 1, /**< 'use strict' directive is found but strict mode has already been enabled */ ++ PARSER_USE_STRICT_SET = 2, /**< strict mode is enabled after 'use strict' directive is found */ ++} parser_strict_mode_type_t; ++ + /** + * Parse statements. + */ +@@ -2627,7 +2637,7 @@ parser_parse_statements (parser_context_t *context_p) /**< context */ + && context_p->token.lit_location.type == LEXER_STRING_LITERAL) + { + lexer_lit_location_t lit_location; +- bool is_use_strict = false; ++ parser_strict_mode_type_t strict_mode = PARSER_USE_STRICT_NOT_FOUND; + + JERRY_ASSERT (context_p->stack_depth == 0); + #ifndef JERRY_NDEBUG +@@ -2636,7 +2646,14 @@ parser_parse_statements (parser_context_t *context_p) /**< context */ + + if (lexer_string_is_use_strict (context_p)) + { +- is_use_strict = true; ++ strict_mode = PARSER_USE_STRICT_FOUND; ++ ++ if (!(context_p->status_flags & PARSER_IS_STRICT)) ++ { ++ /* The next token should be parsed in strict mode. */ ++ context_p->status_flags |= PARSER_IS_STRICT; ++ strict_mode = PARSER_USE_STRICT_SET; ++ } + } + + lit_location = context_p->token.lit_location; +@@ -2645,6 +2662,11 @@ parser_parse_statements (parser_context_t *context_p) /**< context */ + if (!lexer_string_is_directive (context_p)) + { + /* The string is part of an expression statement. */ ++ if (strict_mode == PARSER_USE_STRICT_SET) ++ { ++ context_p->status_flags &= (uint32_t) ~PARSER_IS_STRICT; ++ } ++ + #if ENABLED (JERRY_DEBUGGER) + if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED) + { +@@ -2670,24 +2692,20 @@ parser_parse_statements (parser_context_t *context_p) /**< context */ + break; + } + +- if (is_use_strict) +- { + #if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) +- if (context_p->is_show_opcodes +- && !(context_p->status_flags & PARSER_IS_STRICT)) +- { +- JERRY_DEBUG_MSG (" Note: switch to strict mode\n\n"); +- } ++ if (strict_mode == PARSER_USE_STRICT_SET && context_p->is_show_opcodes) ++ { ++ JERRY_DEBUG_MSG (" Note: switch to strict mode\n\n"); ++ } + #endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */ +-#if ENABLED (JERRY_ES2015) +- if (context_p->status_flags & PARSER_FUNCTION_HAS_NON_SIMPLE_PARAM) +- { +- parser_raise_error (context_p, PARSER_ERR_USE_STRICT_NOT_ALLOWED); +- } +-#endif /* ENABLED (JERRY_ES2015) */ + +- context_p->status_flags |= PARSER_IS_STRICT; ++#if ENABLED (JERRY_ES2015) ++ if (strict_mode != PARSER_USE_STRICT_NOT_FOUND ++ && (context_p->status_flags & PARSER_FUNCTION_HAS_NON_SIMPLE_PARAM)) ++ { ++ parser_raise_error (context_p, PARSER_ERR_USE_STRICT_NOT_ALLOWED); + } ++#endif /* ENABLED (JERRY_ES2015) */ + + if (context_p->token.type == LEXER_SEMICOLON) + { +@@ -3048,7 +3066,13 @@ parser_parse_statements (parser_context_t *context_p) /**< context */ + scanner_release_next (context_p, sizeof (scanner_info_t)); + } + +- parser_parse_expression_statement (context_p, PARSE_EXPR); ++ if (context_p->status_flags & PARSER_IS_FUNCTION) ++ { ++ parser_parse_expression_statement (context_p, PARSE_EXPR); ++ break; ++ } ++ ++ parser_parse_block_expression (context_p, PARSE_EXPR); + break; + } + +diff --git a/jerry-core/parser/js/js-scanner-ops.c b/jerry-core/parser/js/js-scanner-ops.c +index 0270d012..569be23f 100644 +--- a/jerry-core/parser/js/js-scanner-ops.c ++++ b/jerry-core/parser/js/js-scanner-ops.c +@@ -539,15 +539,22 @@ scanner_check_directives (parser_context_t *context_p, /**< context */ + { + bool is_use_strict = false; + +- if (lexer_string_is_use_strict (context_p)) ++ if (lexer_string_is_use_strict (context_p) ++ && !(context_p->status_flags & PARSER_IS_STRICT)) + { + is_use_strict = true; ++ context_p->status_flags |= PARSER_IS_STRICT; + } + + lexer_next_token (context_p); + + if (!lexer_string_is_directive (context_p)) + { ++ if (is_use_strict) ++ { ++ context_p->status_flags &= (uint32_t) ~PARSER_IS_STRICT; ++ } ++ + /* The string is part of an expression statement. */ + scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION; + break; +@@ -555,7 +562,6 @@ scanner_check_directives (parser_context_t *context_p, /**< context */ + + if (is_use_strict) + { +- context_p->status_flags |= PARSER_IS_STRICT; + scanner_context_p->active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_IS_STRICT; + } + +diff --git a/tests/jerry/strict2.js b/tests/jerry/strict2.js +new file mode 100644 +index 00000000..37e2a860 +--- /dev/null ++++ b/tests/jerry/strict2.js +@@ -0,0 +1,82 @@ ++// Copyright JS Foundation and other contributors, http://js.foundation ++// ++// Licensed under the Apache License, Version 2.0 (the "License"); ++// you may not use this file except in compliance with the License. ++// You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, software ++// distributed under the License is distributed on an "AS IS" BASIS ++// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++// See the License for the specific language governing permissions and ++// limitations under the License. ++ ++function check_syntax_error (script) ++{ ++ try ++ { ++ eval (script); ++ assert (false); ++ } ++ catch (e) ++ { ++ assert (e instanceof SyntaxError); ++ } ++} ++ ++var ++ implements = 0, ++ private = 1, ++ public = 2, ++ interface = 3, ++ package = 4, ++ protected = 5, ++ let = 6, ++ yield = 7, ++ static = 8; ++ ++check_syntax_error("'use strict'\nimplements") ++check_syntax_error("'use strict'\n\\u0069mplements") ++assert(eval("'use stric'\nimplements") === 0) ++assert(eval("'use stric'\n\\u0069mplements") === 0) ++ ++check_syntax_error("'use strict'\nprivate") ++check_syntax_error("'use strict'\n\\u0070rivate") ++assert(eval("'use stric'\nprivate") === 1) ++assert(eval("'use stric'\n\\u0070rivate") === 1) ++ ++check_syntax_error("'use strict'\npublic") ++check_syntax_error("'use strict'\n\\u0070ublic") ++assert(eval("'use stric'\npublic") === 2) ++assert(eval("'use stric'\n\\u0070ublic") === 2) ++ ++check_syntax_error("'use strict'\ninterface") ++check_syntax_error("'use strict'\n\\u0069nterface") ++assert(eval("'use stric'\ninterface") === 3) ++assert(eval("'use stric'\n\\u0069nterface") === 3) ++ ++check_syntax_error("'use strict'\npackage") ++check_syntax_error("'use strict'\n\\u0070ackage") ++assert(eval("'use stric'\npackage") === 4) ++assert(eval("'use stric'\n\\u0070ackage") === 4) ++ ++check_syntax_error("'use strict'\nprotected") ++check_syntax_error("'use strict'\n\\u0070rotected") ++assert(eval("'use stric'\nprotected") === 5) ++assert(eval("'use stric'\n\\u0070rotected") === 5) ++ ++check_syntax_error("'use strict'\nlet") ++check_syntax_error("'use strict'\n\\u006cet") ++assert(eval("'use stric'\nlet") === 6) ++assert(eval("'use stric'\n\\u006cet") === 6) ++ ++check_syntax_error("'use strict'\nyield") ++check_syntax_error("'use strict'\n\\u0079ield") ++assert(eval("'use stric'\nyield") === 7) ++assert(eval("'use stric'\n\\u0079ield") === 7) ++ ++check_syntax_error("'use strict'\nstatic") ++check_syntax_error("'use strict'\n\\u0073tatic") ++assert(eval("'use stric'\nstatic") === 8) ++assert(eval("'use stric'\n\\u0073tatic") === 8) \ No newline at end of file diff --git a/tasks/csa159/pair_137357/post_functions.txt b/tasks/csa159/pair_137357/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..1a3d7e2f2e046748a54ccc61d575015a9361df9e --- /dev/null +++ b/tasks/csa159/pair_137357/post_functions.txt @@ -0,0 +1,278 @@ +### File: jerry-core/parser/js/js-parser-statm.c +```c +static void +parser_parse_label (parser_context_t *context_p) /**< context */ +{ + parser_stack_iterator_t iterator; + parser_label_statement_t label_statement; + + parser_stack_iterator_init (context_p, &iterator); + + while (true) + { + uint8_t type = parser_stack_iterator_read_uint8 (&iterator); + if (type == PARSER_STATEMENT_START) + { + break; + } + + if (type == PARSER_STATEMENT_LABEL) + { + parser_stack_iterator_skip (&iterator, 1); + parser_stack_iterator_read (&iterator, &label_statement, sizeof (parser_label_statement_t)); + parser_stack_iterator_skip (&iterator, sizeof (parser_label_statement_t)); + + if (lexer_current_is_literal (context_p, &label_statement.label_ident)) + { + parser_raise_error (context_p, PARSER_ERR_DUPLICATED_LABEL); + } + } + else + { + parser_stack_iterator_skip (&iterator, parser_statement_length (type)); + } + } + + label_statement.label_ident = context_p->token.lit_location; + label_statement.break_list_p = NULL; + parser_stack_push (context_p, &label_statement, sizeof (parser_label_statement_t)); + parser_stack_push_uint8 (context_p, PARSER_STATEMENT_LABEL); + parser_stack_iterator_init (context_p, &context_p->last_statement); +} + +void +parser_parse_statements (parser_context_t *context_p) /**< context */ +{ + /* Statement parsing cannot be nested. */ + JERRY_ASSERT (context_p->last_statement.current_p == NULL); + parser_stack_push_uint8 (context_p, PARSER_STATEMENT_START); + parser_stack_iterator_init (context_p, &context_p->last_statement); + +#if ENABLED (JERRY_DEBUGGER) + /* Set lexical enviroment for the debugger. */ + if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED) + { + context_p->status_flags |= PARSER_LEXICAL_ENV_NEEDED; + context_p->last_breakpoint_line = 0; + } +#endif /* ENABLED (JERRY_DEBUGGER) */ + +#if ENABLED (JERRY_LINE_INFO) || ENABLED (JERRY_ES2015_MODULE_SYSTEM) + if (JERRY_CONTEXT (resource_name) != ECMA_VALUE_UNDEFINED) + { + parser_emit_cbc_ext (context_p, CBC_EXT_RESOURCE_NAME); + parser_flush_cbc (context_p); + } +#endif /* ENABLED (JERRY_LINE_INFO) || ENABLED (JERRY_ES2015_MODULE_SYSTEM) */ +#if ENABLED (JERRY_LINE_INFO) + context_p->last_line_info_line = 0; +#endif /* ENABLED (JERRY_LINE_INFO) */ + + while (context_p->token.type == LEXER_LITERAL + && context_p->token.lit_location.type == LEXER_STRING_LITERAL) + { + lexer_lit_location_t lit_location; + parser_strict_mode_type_t strict_mode = PARSER_USE_STRICT_NOT_FOUND; + + JERRY_ASSERT (context_p->stack_depth == 0); +#ifndef JERRY_NDEBUG + JERRY_ASSERT (context_p->context_stack_depth == context_p->stack_depth); +#endif /* !JERRY_NDEBUG */ + + if (lexer_string_is_use_strict (context_p)) + { + strict_mode = PARSER_USE_STRICT_FOUND; + + if (!(context_p->status_flags & PARSER_IS_STRICT)) + { + /* The next token should be parsed in strict mode. */ + context_p->status_flags |= PARSER_IS_STRICT; + strict_mode = PARSER_USE_STRICT_SET; + } + } + + lit_location = context_p->token.lit_location; + lexer_next_token (context_p); + + if (!lexer_string_is_directive (context_p)) + { + /* The string is part of an expression statement. */ + if (strict_mode == PARSER_USE_STRICT_SET) + { + context_p->status_flags &= (uint32_t) ~PARSER_IS_STRICT; + } + +#if ENABLED (JERRY_DEBUGGER) + if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED) + { + JERRY_ASSERT (context_p->last_breakpoint_line == 0); + + parser_emit_cbc (context_p, CBC_BREAKPOINT_DISABLED); + parser_flush_cbc (context_p); + + parser_append_breakpoint_info (context_p, JERRY_DEBUGGER_BREAKPOINT_LIST, context_p->token.line); + + context_p->last_breakpoint_line = context_p->token.line; + } +#endif /* ENABLED (JERRY_DEBUGGER) */ +#if ENABLED (JERRY_LINE_INFO) + parser_emit_line_info (context_p, context_p->token.line, false); +#endif /* ENABLED (JERRY_LINE_INFO) */ + + lexer_construct_literal_object (context_p, &lit_location, LEXER_STRING_LITERAL); + parser_emit_cbc_literal_from_token (context_p, CBC_PUSH_LITERAL); + /* The extra_value is used for saving the token. */ + context_p->token.extra_value = context_p->token.type; + context_p->token.type = LEXER_EXPRESSION_START; + break; + } + +#if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) + if (strict_mode == PARSER_USE_STRICT_SET && context_p->is_show_opcodes) + { + JERRY_DEBUG_MSG (" Note: switch to strict mode\n\n"); + } +#endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */ + +#if ENABLED (JERRY_ES2015) + if (strict_mode != PARSER_USE_STRICT_NOT_FOUND + && (context_p->status_flags & PARSER_FUNCTION_HAS_NON_SIMPLE_PARAM)) + { + parser_raise_error (context_p, PARSER_ERR_USE_STRICT_NOT_ALLOWED); + } +#endif /* ENABLED (JERRY_ES2015) */ + + if (context_p->token.type == LEXER_SEMICOLON) + { + lexer_next_token (context_p); + } + + /* The last directive prologue can be the result of the script. */ + if (!(context_p->status_flags & PARSER_IS_FUNCTION) + && (context_p->token.type != LEXER_LITERAL + || context_p->token.lit_location.type != LEXER_STRING_LITERAL)) + { + lexer_construct_literal_object (context_p, &lit_location, LEXER_STRING_LITERAL); + parser_emit_cbc_literal_from_token (context_p, CBC_PUSH_LITERAL); + parser_emit_cbc (context_p, CBC_POP_BLOCK); + parser_flush_cbc (context_p); + break; + } + } + + if (context_p->status_flags & PARSER_IS_STRICT + && context_p->status_flags & PARSER_HAS_NON_STRICT_ARG) + { + parser_raise_error (context_p, PARSER_ERR_NON_STRICT_ARG_DEFINITION); + } + + while (context_p->token.type != LEXER_EOS + || context_p->stack_top_uint8 != PARSER_STATEMENT_START) + { +#ifndef JERRY_NDEBUG + JERRY_ASSERT (context_p->stack_depth == context_p->context_stack_depth); +#endif /* !JERRY_NDEBUG */ + +#if ENABLED (JERRY_ES2015) + JERRY_ASSERT (context_p->stack_top_uint8 != PARSER_STATEMENT_PRIVATE_SCOPE + && context_p->stack_top_uint8 != PARSER_STATEMENT_PRIVATE_CONTEXT); +#endif /* ENABLED (JERRY_ES2015) */ + +#if ENABLED (JERRY_DEBUGGER) + if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED + && context_p->token.line != context_p->last_breakpoint_line + && context_p->token.type != LEXER_SEMICOLON + && context_p->token.type != LEXER_LEFT_BRACE + && context_p->token.type != LEXER_RIGHT_BRACE + && context_p->token.type != LEXER_KEYW_VAR + && context_p->token.type != LEXER_KEYW_LET + && context_p->token.type != LEXER_KEYW_CONST + && context_p->token.type != LEXER_KEYW_FUNCTION + && context_p->token.type != LEXER_KEYW_CASE + && context_p->token.type != LEXER_KEYW_DEFAULT) + { + parser_emit_cbc (context_p, CBC_BREAKPOINT_DISABLED); + parser_flush_cbc (context_p); + + parser_append_breakpoint_info (context_p, JERRY_DEBUGGER_BREAKPOINT_LIST, context_p->token.line); + + context_p->last_breakpoint_line = context_p->token.line; + } +#endif /* ENABLED (JERRY_DEBUGGER) */ + +#if ENABLED (JERRY_LINE_INFO) + if (context_p->token.line != context_p->last_line_info_line + && context_p->token.type != LEXER_SEMICOLON + && context_p->token.type != LEXER_LEFT_BRACE + && context_p->token.type != LEXER_RIGHT_BRACE + && context_p->token.type != LEXER_KEYW_VAR + && context_p->token.type != LEXER_KEYW_LET + && context_p->token.type != LEXER_KEYW_CONST + && context_p->token.type != LEXER_KEYW_FUNCTION + && context_p->token.type != LEXER_KEYW_CASE + && context_p->token.type != LEXER_KEYW_DEFAULT) + { + parser_emit_line_info (context_p, context_p->token.line, true); + } +#endif /* ENABLED (JERRY_LINE_INFO) */ + + switch (context_p->token.type) + { + case LEXER_SEMICOLON: + { + break; + } + + case LEXER_RIGHT_BRACE: + { + if (parser_statement_flags[context_p->stack_top_uint8] & PARSER_STATM_ + +// ... (17308 more chars) +``` + +### File: jerry-core/parser/js/js-scanner-ops.c +```c +void +scanner_check_directives (parser_context_t *context_p, /**< context */ + scanner_context_t *scanner_context_p) /**< scanner context */ +{ + scanner_context_p->mode = SCAN_MODE_STATEMENT_OR_TERMINATOR; + + while (context_p->token.type == LEXER_LITERAL + && context_p->token.lit_location.type == LEXER_STRING_LITERAL) + { + bool is_use_strict = false; + + if (lexer_string_is_use_strict (context_p) + && !(context_p->status_flags & PARSER_IS_STRICT)) + { + is_use_strict = true; + context_p->status_flags |= PARSER_IS_STRICT; + } + + lexer_next_token (context_p); + + if (!lexer_string_is_directive (context_p)) + { + if (is_use_strict) + { + context_p->status_flags &= (uint32_t) ~PARSER_IS_STRICT; + } + + /* The string is part of an expression statement. */ + scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION; + break; + } + + if (is_use_strict) + { + scanner_context_p->active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_IS_STRICT; + } + + if (context_p->token.type == LEXER_SEMICOLON) + { + lexer_next_token (context_p); + } + } +} +``` diff --git a/tasks/csa159/pair_137357/pre_functions.txt b/tasks/csa159/pair_137357/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..b53380992a5cd70753a27e903ed97865302b25c8 --- /dev/null +++ b/tasks/csa159/pair_137357/pre_functions.txt @@ -0,0 +1,278 @@ +### File: jerry-core/parser/js/js-parser-statm.c +```c +static void +parser_parse_label (parser_context_t *context_p) /**< context */ +{ + parser_stack_iterator_t iterator; + parser_label_statement_t label_statement; + + parser_stack_iterator_init (context_p, &iterator); + + while (true) + { + uint8_t type = parser_stack_iterator_read_uint8 (&iterator); + if (type == PARSER_STATEMENT_START) + { + break; + } + + if (type == PARSER_STATEMENT_LABEL) + { + parser_stack_iterator_skip (&iterator, 1); + parser_stack_iterator_read (&iterator, &label_statement, sizeof (parser_label_statement_t)); + parser_stack_iterator_skip (&iterator, sizeof (parser_label_statement_t)); + + if (lexer_current_is_literal (context_p, &label_statement.label_ident)) + { + parser_raise_error (context_p, PARSER_ERR_DUPLICATED_LABEL); + } + } + else + { + parser_stack_iterator_skip (&iterator, parser_statement_length (type)); + } + } + + label_statement.label_ident = context_p->token.lit_location; + label_statement.break_list_p = NULL; + parser_stack_push (context_p, &label_statement, sizeof (parser_label_statement_t)); + parser_stack_push_uint8 (context_p, PARSER_STATEMENT_LABEL); + parser_stack_iterator_init (context_p, &context_p->last_statement); +} + +void +parser_parse_statements (parser_context_t *context_p) /**< context */ +{ + /* Statement parsing cannot be nested. */ + JERRY_ASSERT (context_p->last_statement.current_p == NULL); + parser_stack_push_uint8 (context_p, PARSER_STATEMENT_START); + parser_stack_iterator_init (context_p, &context_p->last_statement); + +#if ENABLED (JERRY_DEBUGGER) + /* Set lexical enviroment for the debugger. */ + if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED) + { + context_p->status_flags |= PARSER_LEXICAL_ENV_NEEDED; + context_p->last_breakpoint_line = 0; + } +#endif /* ENABLED (JERRY_DEBUGGER) */ + +#if ENABLED (JERRY_LINE_INFO) || ENABLED (JERRY_ES2015_MODULE_SYSTEM) + if (JERRY_CONTEXT (resource_name) != ECMA_VALUE_UNDEFINED) + { + parser_emit_cbc_ext (context_p, CBC_EXT_RESOURCE_NAME); + parser_flush_cbc (context_p); + } +#endif /* ENABLED (JERRY_LINE_INFO) || ENABLED (JERRY_ES2015_MODULE_SYSTEM) */ +#if ENABLED (JERRY_LINE_INFO) + context_p->last_line_info_line = 0; +#endif /* ENABLED (JERRY_LINE_INFO) */ + + while (context_p->token.type == LEXER_LITERAL + && context_p->token.lit_location.type == LEXER_STRING_LITERAL) + { + lexer_lit_location_t lit_location; + bool is_use_strict = false; + + JERRY_ASSERT (context_p->stack_depth == 0); +#ifndef JERRY_NDEBUG + JERRY_ASSERT (context_p->context_stack_depth == context_p->stack_depth); +#endif /* !JERRY_NDEBUG */ + + if (lexer_string_is_use_strict (context_p)) + { + is_use_strict = true; + } + + lit_location = context_p->token.lit_location; + lexer_next_token (context_p); + + if (!lexer_string_is_directive (context_p)) + { + /* The string is part of an expression statement. */ +#if ENABLED (JERRY_DEBUGGER) + if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED) + { + JERRY_ASSERT (context_p->last_breakpoint_line == 0); + + parser_emit_cbc (context_p, CBC_BREAKPOINT_DISABLED); + parser_flush_cbc (context_p); + + parser_append_breakpoint_info (context_p, JERRY_DEBUGGER_BREAKPOINT_LIST, context_p->token.line); + + context_p->last_breakpoint_line = context_p->token.line; + } +#endif /* ENABLED (JERRY_DEBUGGER) */ +#if ENABLED (JERRY_LINE_INFO) + parser_emit_line_info (context_p, context_p->token.line, false); +#endif /* ENABLED (JERRY_LINE_INFO) */ + + lexer_construct_literal_object (context_p, &lit_location, LEXER_STRING_LITERAL); + parser_emit_cbc_literal_from_token (context_p, CBC_PUSH_LITERAL); + /* The extra_value is used for saving the token. */ + context_p->token.extra_value = context_p->token.type; + context_p->token.type = LEXER_EXPRESSION_START; + break; + } + + if (is_use_strict) + { +#if ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) + if (context_p->is_show_opcodes + && !(context_p->status_flags & PARSER_IS_STRICT)) + { + JERRY_DEBUG_MSG (" Note: switch to strict mode\n\n"); + } +#endif /* ENABLED (JERRY_PARSER_DUMP_BYTE_CODE) */ +#if ENABLED (JERRY_ES2015) + if (context_p->status_flags & PARSER_FUNCTION_HAS_NON_SIMPLE_PARAM) + { + parser_raise_error (context_p, PARSER_ERR_USE_STRICT_NOT_ALLOWED); + } +#endif /* ENABLED (JERRY_ES2015) */ + + context_p->status_flags |= PARSER_IS_STRICT; + } + + if (context_p->token.type == LEXER_SEMICOLON) + { + lexer_next_token (context_p); + } + + /* The last directive prologue can be the result of the script. */ + if (!(context_p->status_flags & PARSER_IS_FUNCTION) + && (context_p->token.type != LEXER_LITERAL + || context_p->token.lit_location.type != LEXER_STRING_LITERAL)) + { + lexer_construct_literal_object (context_p, &lit_location, LEXER_STRING_LITERAL); + parser_emit_cbc_literal_from_token (context_p, CBC_PUSH_LITERAL); + parser_emit_cbc (context_p, CBC_POP_BLOCK); + parser_flush_cbc (context_p); + break; + } + } + + if (context_p->status_flags & PARSER_IS_STRICT + && context_p->status_flags & PARSER_HAS_NON_STRICT_ARG) + { + parser_raise_error (context_p, PARSER_ERR_NON_STRICT_ARG_DEFINITION); + } + + while (context_p->token.type != LEXER_EOS + || context_p->stack_top_uint8 != PARSER_STATEMENT_START) + { +#ifndef JERRY_NDEBUG + JERRY_ASSERT (context_p->stack_depth == context_p->context_stack_depth); +#endif /* !JERRY_NDEBUG */ + +#if ENABLED (JERRY_ES2015) + JERRY_ASSERT (context_p->stack_top_uint8 != PARSER_STATEMENT_PRIVATE_SCOPE + && context_p->stack_top_uint8 != PARSER_STATEMENT_PRIVATE_CONTEXT); +#endif /* ENABLED (JERRY_ES2015) */ + +#if ENABLED (JERRY_DEBUGGER) + if (JERRY_CONTEXT (debugger_flags) & JERRY_DEBUGGER_CONNECTED + && context_p->token.line != context_p->last_breakpoint_line + && context_p->token.type != LEXER_SEMICOLON + && context_p->token.type != LEXER_LEFT_BRACE + && context_p->token.type != LEXER_RIGHT_BRACE + && context_p->token.type != LEXER_KEYW_VAR + && context_p->token.type != LEXER_KEYW_LET + && context_p->token.type != LEXER_KEYW_CONST + && context_p->token.type != LEXER_KEYW_FUNCTION + && context_p->token.type != LEXER_KEYW_CASE + && context_p->token.type != LEXER_KEYW_DEFAULT) + { + parser_emit_cbc (context_p, CBC_BREAKPOINT_DISABLED); + parser_flush_cbc (context_p); + + parser_append_breakpoint_info (context_p, JERRY_DEBUGGER_BREAKPOINT_LIST, context_p->token.line); + + context_p->last_breakpoint_line = context_p->token.line; + } +#endif /* ENABLED (JERRY_DEBUGGER) */ + +#if ENABLED (JERRY_LINE_INFO) + if (context_p->token.line != context_p->last_line_info_line + && context_p->token.type != LEXER_SEMICOLON + && context_p->token.type != LEXER_LEFT_BRACE + && context_p->token.type != LEXER_RIGHT_BRACE + && context_p->token.type != LEXER_KEYW_VAR + && context_p->token.type != LEXER_KEYW_LET + && context_p->token.type != LEXER_KEYW_CONST + && context_p->token.type != LEXER_KEYW_FUNCTION + && context_p->token.type != LEXER_KEYW_CASE + && context_p->token.type != LEXER_KEYW_DEFAULT) + { + parser_emit_line_info (context_p, context_p->token.line, true); + } +#endif /* ENABLED (JERRY_LINE_INFO) */ + + switch (context_p->token.type) + { + case LEXER_SEMICOLON: + { + break; + } + + case LEXER_RIGHT_BRACE: + { + if (parser_statement_flags[context_p->stack_top_uint8] & PARSER_STATM_SINGLE_STATM) + { + parser_raise_error (context_p, PARSER_ERR_STATEMENT_EXPECTED); + } + break; + } + + case LEXER_LEFT_BRACE: + { +#if ENABLED (JERRY_ES2015) + if (context_p->next_scanner_info_p->source_p == context_p->source_p) + { + parser_push_block_context (context_p, false); + } + e + +// ... (16760 more chars) +``` + +### File: jerry-core/parser/js/js-scanner-ops.c +```c +void +scanner_check_directives (parser_context_t *context_p, /**< context */ + scanner_context_t *scanner_context_p) /**< scanner context */ +{ + scanner_context_p->mode = SCAN_MODE_STATEMENT_OR_TERMINATOR; + + while (context_p->token.type == LEXER_LITERAL + && context_p->token.lit_location.type == LEXER_STRING_LITERAL) + { + bool is_use_strict = false; + + if (lexer_string_is_use_strict (context_p)) + { + is_use_strict = true; + } + + lexer_next_token (context_p); + + if (!lexer_string_is_directive (context_p)) + { + /* The string is part of an expression statement. */ + scanner_context_p->mode = SCAN_MODE_POST_PRIMARY_EXPRESSION; + break; + } + + if (is_use_strict) + { + context_p->status_flags |= PARSER_IS_STRICT; + scanner_context_p->active_literal_pool_p->status_flags |= SCANNER_LITERAL_POOL_IS_STRICT; + } + + if (context_p->token.type == LEXER_SEMICOLON) + { + lexer_next_token (context_p); + } + } +} +``` diff --git a/tasks/csa159/pair_137357/task_prompt.md b/tasks/csa159/pair_137357/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..76ee340d225cfc4cf190de1070e8def40553d41f --- /dev/null +++ b/tasks/csa159/pair_137357/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: `path_sensitive` + +### Current failure diagnosis + +- The rollout failed only the process-quality threshold, scoring 73.91 despite passing compilation, differential detection, code verification, objective gate G6, refinement, and semantic checks. +- The detection plan and implementation did not encode successful lexer_string_is_directive validation as a distinct prerequisite state, so an enable between token advancement and directive validation could be reported even though the stated contract required validation first. +- Strict-enable recognition was broader than the plan: fallback checks on the bound value or symbolic OR expression could classify stores beyond the specified status_flags OR-assignment with the strict bit. +- The first build placed the ProgramState trait registration in an invalid namespace; recovery succeeded, but the avoidable compile cycle reduced process quality. + +### Preserve from prior rollouts + +- Maintain successful checker compilation, paired before/after scanning, and code verification. +- Retain objective eligibility gate G6 and an accepted or clean refinement outcome. +- Retain the accepted path-sensitive CSA mechanism and a semantic score at or above the configured threshold. +- Remain independent of patch line anchors, changed-function allowlists, and other patch-local hardcoding. +- Keep project-general scope so equivalent directive-processing sites can be detected without restricting analysis to the two patched functions. + +### Required semantic proof + +- On one feasible intraprocedural path, prove that lexer_string_is_use_strict(ctx) returns true while the same parser context is not provably already strict. +- Prove that lexer_next_token(ctx) then classifies the token immediately following that recognized string before PARSER_IS_STRICT is enabled on ctx. +- Require lexer_string_is_directive(ctx) to return true for that same pending directive operation before permitting a report; its false branch must invalidate the candidate. +- Prove that a subsequent store enables PARSER_IS_STRICT in ctx->status_flags for the identical canonical parser-context region, and report only this late enable. +- Treat an enable observed after recognition but before the relevant token advance as safe, including the patched speculative-enable design and its later rollback when directive validation fails. +- Do not report for failed use-strict recognition, rejected directives, observably already-strict contexts, unrelated parser-context objects, or unrelated flag updates. + +### Implementation constraints + +- Use ProgramState to carry a per-context protocol with distinct phases for recognized, token-advanced, directive-validated, safely resolved, and cleared candidates; a reportable phase must be reachable only after all required successful events. +- Use check::PostCall to split and constrain the boolean results of lexer_string_is_use_strict and lexer_string_is_directive, check::PreCall to observe lexer_next_token before classification, and check::Bind to inspect the destination region of the strict-enable store. +- Key state by the canonical base MemRegion of the parser-context argument and require every recognition, advance, validation, and store event to resolve to the same key. +- Recognize the sink through the parser_context status_flags FieldRegion and AST/constant semantics showing an OR-assignment that enables the PARSER_IS_STRICT bit; do not broaden sink matching merely because a resulting value has bit 0 set. +- Anchor the diagnostic at the late strict-enable store, mark the associated context region interesting, and discharge the candidate so one path does not emit duplicate reports. +- Keep analysis intraprocedural and project-general: stable JerryScript parser/lexer APIs and strict-bit semantics are permitted, but source paths, function names, patch coordinates, and before/after text are not. +- Place REGISTER_MAP_WITH_PROGRAMSTATE where its ProgramStateTrait specialization is in a namespace enclosing clang::ento, consistent with the Clang API used by the build environment. + +### Validation checklist + +- Compile the fresh checker plugin against the target Clang Static Analyzer API with no diagnostics before running scans. +- Scan the vulnerable revision and require exactly the two relevant warnings in parser_parse_statements and scanner_check_directives, each located at the late status_flags strict-enable store. +- Scan the patched revision and require zero warnings, demonstrating that enable-before-lexer_next_token transitions the candidate to a safe state. +- Run paired code verification and confirm both vulnerable warnings disappear in the patched functions, no warnings appear in non-patched functions, and median report distance from the relevant patch site remains zero. +- Exercise refinement cases for failed use-strict recognition, lexer_string_is_directive returning false, an already-strict context, a different context object, unrelated status_flags updates, and speculative enable followed by rollback; all must remain clean. +- Add a focused ordering case where strict enable occurs after lexer_next_token but before directive validation; it must not report because successful validation has not yet been established. +- Add a positive focused case with recognition true, token advance, directive validation true, and late strict enable on one context; it must report once at the store. +- Reconfirm objective gate G6, accepted or clean refinement, anchor-free and hardcoding-free checks, and the required semantic threshold after validation. + +### Avoid and forbidden regressions + +- Do not use syntax-only matching, AST adjacency, CFG dominance alone, or untracked control-flow ordering; these cannot establish all feasible-path and same-operation conditions. +- Do not reuse a state model in which token advancement alone makes a candidate reportable while directive validation merely clears the false branch. +- Do not infer a strict-enable sink from arbitrary concrete or symbolic bound values without proving the specified status_flags OR-assignment semantics. +- Do not suppress unknown preexisting strict status as definitely safe; only a concretely established strict bit proves the already-strict exclusion. +- Do not match the unrelated parser_parse_block_expression change or generalize the checker to arbitrary mode flags outside this vulnerability pattern. +- Do not specialize detection to parser_parse_statements, scanner_check_directives, their files, changed lines, diagnostic coordinates, or patch text. +- Do not place ProgramState registration inside an anonymous namespace that cannot legally specialize clang::ento::ProgramStateTrait. diff --git a/tasks/csa159/pair_137374/checker_template.cpp b/tasks/csa159/pair_137374/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_137374/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_137374/config.json b/tasks/csa159/pair_137374/config.json new file mode 100644 index 0000000000000000000000000000000000000000..1693ba1852ccd30ee82092e0eba258b6a3df7873 --- /dev/null +++ b/tasks/csa159/pair_137374/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "jerryscript-project_jerryscript", + "before_commit": "8fa7819c1f79c7c28aba7ed8ceb4d00cc007e839", + "after_commit": "2a3782141c75eb5be5d99eaab42541ea510321b4", + "repo_path": "/workspace/repo/jerryscript-project/jerryscript", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/jerryscript-project_jerryscript/c51b2682760e062c8735a91635ae1f02634aa74b/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/jerryscript-project_jerryscript/c51b2682760e062c8735a91635ae1f02634aa74b/compile_commands.json", + "changed_files": [ + "jerry-core/vm/opcodes.c" + ], + "commit_message": "Fix fast array objects cannot hold private properties (#4952)\n\nThis patch fixes #4934.\n\nJerryScript-DCO-1.0-Signed-off-by: Robert Fancsik robert.fancsik@h-lab.eu", + "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_137374/patch.diff b/tasks/csa159/pair_137374/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1161fab95dfff3c578bf4e0347b919e816b6d8b4 --- /dev/null +++ b/tasks/csa159/pair_137374/patch.diff @@ -0,0 +1,61 @@ +diff --git a/jerry-core/vm/opcodes.c b/jerry-core/vm/opcodes.c +index 710c1552..ee644487 100644 +--- a/jerry-core/vm/opcodes.c ++++ b/jerry-core/vm/opcodes.c +@@ -1235,6 +1235,11 @@ opfunc_find_private_key (ecma_object_t *class_object_p, /**< class environment * + ecma_string_t *search_key_p, /**< key */ + ecma_string_t **out_private_key_p) /**< [out] private key */ + { ++ if (ecma_op_object_is_fast_array (obj_p)) ++ { ++ return NULL; ++ } ++ + ecma_string_t *internal_string_p = ecma_get_internal_string (LIT_INTERNAL_MAGIC_STRING_CLASS_PRIVATE_ELEMENTS); + ecma_property_t *prop_p = ecma_find_named_property (class_object_p, internal_string_p); + +diff --git a/tests/jerry/es.next/regression-test-issue-4934.js b/tests/jerry/es.next/regression-test-issue-4934.js +new file mode 100644 +index 00000000..c82a0f7b +--- /dev/null ++++ b/tests/jerry/es.next/regression-test-issue-4934.js +@@ -0,0 +1,39 @@ ++// Copyright JS Foundation and other contributors, http://js.foundation ++// ++// Licensed under the Apache License, Version 2.0 (the "License"); ++// you may not use this file except in compliance with the License. ++// You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, software ++// distributed under the License is distributed on an "AS IS" BASIS ++// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++// See the License for the specific language governing permissions and ++// limitations under the License. ++ ++function expectTypeError(cb) { ++ try { ++ cb(); ++ assert(false); ++ } catch (e) { ++ assert(e instanceof TypeError); ++ } ++} ++ ++class JSEtest { ++ static set #m(v) { ++ this._v = v; ++ } ++ ++ static b() { ++ new Proxy([1], {}).#m = "Test262"; ++ } ++ ++ static c() { ++ [1].#m = "Test262"; ++ } ++} ++ ++expectTypeError(_ => JSEtest.b()); ++expectTypeError(_ => JSEtest.c()); \ No newline at end of file diff --git a/tasks/csa159/pair_137374/post_functions.txt b/tasks/csa159/pair_137374/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..713d593e2ea3e89db03c04af025b2b92cc4f17e3 --- /dev/null +++ b/tasks/csa159/pair_137374/post_functions.txt @@ -0,0 +1,52 @@ +### File: jerry-core/vm/opcodes.c +```c +static ecma_property_t * +opfunc_find_private_key (ecma_object_t *class_object_p, /**< class environment */ + ecma_object_t *obj_p, /**< object */ + ecma_string_t *search_key_p, /**< key */ + ecma_string_t **out_private_key_p) /**< [out] private key */ +{ + if (ecma_op_object_is_fast_array (obj_p)) + { + return NULL; + } + + ecma_string_t *internal_string_p = ecma_get_internal_string (LIT_INTERNAL_MAGIC_STRING_CLASS_PRIVATE_ELEMENTS); + ecma_property_t *prop_p = ecma_find_named_property (class_object_p, internal_string_p); + + if (prop_p == NULL) + { + return NULL; + } + + ecma_value_t *collection_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_value_t, ECMA_PROPERTY_VALUE_PTR (prop_p)->value); + ecma_value_t *current_p = collection_p + 1; + ecma_value_t *end_p = ecma_compact_collection_end (collection_p); + + while (current_p < end_p) + { + current_p++; /* skip kind */ + ecma_string_t *private_key_p = ecma_get_prop_name_from_value (*current_p++); + current_p++; /* skip value */ + + JERRY_ASSERT (ecma_prop_name_is_symbol (private_key_p)); + + ecma_string_t *private_key_desc_p = + ecma_get_string_from_value (((ecma_extended_string_t *) private_key_p)->u.symbol_descriptor); + + if (ecma_compare_ecma_strings (private_key_desc_p, search_key_p)) + { + prop_p = ecma_find_named_property (obj_p, private_key_p); + + if (out_private_key_p) + { + *out_private_key_p = private_key_p; + } + + return prop_p; + } + } + + return NULL; +} +``` diff --git a/tasks/csa159/pair_137374/pre_functions.txt b/tasks/csa159/pair_137374/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..452f72403fd835215a3ec81e11ed5b85f38b4a9e --- /dev/null +++ b/tasks/csa159/pair_137374/pre_functions.txt @@ -0,0 +1,47 @@ +### File: jerry-core/vm/opcodes.c +```c +static ecma_property_t * +opfunc_find_private_key (ecma_object_t *class_object_p, /**< class environment */ + ecma_object_t *obj_p, /**< object */ + ecma_string_t *search_key_p, /**< key */ + ecma_string_t **out_private_key_p) /**< [out] private key */ +{ + ecma_string_t *internal_string_p = ecma_get_internal_string (LIT_INTERNAL_MAGIC_STRING_CLASS_PRIVATE_ELEMENTS); + ecma_property_t *prop_p = ecma_find_named_property (class_object_p, internal_string_p); + + if (prop_p == NULL) + { + return NULL; + } + + ecma_value_t *collection_p = ECMA_GET_INTERNAL_VALUE_POINTER (ecma_value_t, ECMA_PROPERTY_VALUE_PTR (prop_p)->value); + ecma_value_t *current_p = collection_p + 1; + ecma_value_t *end_p = ecma_compact_collection_end (collection_p); + + while (current_p < end_p) + { + current_p++; /* skip kind */ + ecma_string_t *private_key_p = ecma_get_prop_name_from_value (*current_p++); + current_p++; /* skip value */ + + JERRY_ASSERT (ecma_prop_name_is_symbol (private_key_p)); + + ecma_string_t *private_key_desc_p = + ecma_get_string_from_value (((ecma_extended_string_t *) private_key_p)->u.symbol_descriptor); + + if (ecma_compare_ecma_strings (private_key_desc_p, search_key_p)) + { + prop_p = ecma_find_named_property (obj_p, private_key_p); + + if (out_private_key_p) + { + *out_private_key_p = private_key_p; + } + + return prop_p; + } + } + + return NULL; +} +``` diff --git a/tasks/csa159/pair_137374/task_prompt.md b/tasks/csa159/pair_137374/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..10e06dbe34190e91fa44d5d0bfb2f20e19ac92d3 --- /dev/null +++ b/tasks/csa159/pair_137374/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: `path_sensitive` + +### Current failure diagnosis + +- The prior rollout reported on absence of a non-fast-array fact at every ecma_find_named_property, so it flagged the class_object_p CLASS_PRIVATE_ELEMENTS lookup in opfunc_find_private_key even though the patch never guards that receiver. +- Differential stayed weak (N_buggy=13, N_patched=12, only one relevant disappearance); 11 of 13 warnings sat outside the patched function and median distance was 300 lines, so sharpness and patched-function locality never reached G6. +- Hard validation, refinement_accepted, and process_score remained failed because the noisy unknown-status policy never produced a clean before/after pair at the obj_p private-key sink. +- PostCall also left concrete (non-symbolic) ecma_op_object_is_fast_array results unrecorded, so some guarded paths could not be proven safe even when the branch outcome was known. + +### Preserve from prior rollouts + +- Keep the accepted path-sensitive CSA level: track ecma_op_object_is_fast_array outcomes through CFG branches in ProgramState to the named-property sink; do not drop to syntax or dominance-only. +- Preserve semantic score at or above the prior adequate threshold (7.0) for the missing-dominating-guard contract. +- Remain anchor_free: no dependence on patch line spans, unique nearby comments, or the added regression-test file. +- Remain hardcoding_free: no special-casing of opfunc_find_private_key, obj_p, or other patch-local identifiers. + +### Required semantic proof + +- Unsafe: a path reaches ecma_find_named_property on a receiver that can be a JerryScript fast array, so the compact element buffer is walked as a named-property list and overruns memory. +- Safe: on every path to that sink the receiver region is constrained not-fast-array, normally because if (ecma_op_object_is_fast_array(recv)) return ... was taken as false and dominates the call. +- The class-environment lookup on class_object_p is outside the vulnerability: that object is not a fast-array candidate; only the user-facing target object (the obj_p argument of the private-key lookup) is. +- After the early-return guard on the user-facing receiver, the private-key sink must be unreachable for fast arrays and must not be reported. + +### Implementation constraints + +- Use check::PreCall on ecma_find_named_property as the sink, check::PostCall to bind ecma_op_object_is_fast_array's return to the argument base MemRegion, and eval::Assume or an equivalent constraint query to store per-region true/false status on each branch. +- Record both symbolic guard symbols and concrete boolean returns; missing FastArrayStatusMap must not by itself mean report. +- Emit only when the sink receiver is a fast-array-capable user object and the current path lacks a proven non-fast-array fact; suppress class-environment and other internally constructed receivers. +- Register a path-sensitive BugType and report at the sink CallEvent range via generateNonFatalErrorNode; no source-text matching, no stmtDominates-only proof, no interprocedural requirement. +- Scope to the stable APIs ecma_find_named_property and ecma_op_object_is_fast_array without encoding patch function names, parameter names, or changed lines. + +### Validation checklist + +- Compile the new checker to a loadable plugin and confirm the registered checker name loads in both pre-patch and post-patch scans. +- Pre-patch: report the unguarded ecma_find_named_property(obj_p, private_key_p) inside opfunc_find_private_key and do not report the class_object_p lookup in that function. +- Post-patch: the obj_p sink disappears because the new guard constrains the fall-through path to non-fast-array; n_disappeared_in_non_patched remains 0. +- Locality: the disappearing warning must sit on the private-key sink in jerry-core/vm/opcodes.c::opfunc_find_private_key, not hundreds of lines away; patched-function warning count should be 1 before and 0 after. +- Re-run differential, sharpness, and refinement until hard_validation passes and objective_gate is at least G6 with process_score above threshold. + +### Avoid and forbidden regressions + +- Do not treat an unbound per-region status as a bug at every unguarded ecma_find_named_property in the tree. +- Do not flag class_object_p or other non-fast-array-capable receivers in the same function as the patch. +- Do not weaken the accepted path_sensitive contract to syntax_only CallDescription matching or control_flow dominance without value constraints. +- Do not reintroduce ProgramStateTrait lookup-type pointer mistakes or ConstraintMap/RangeSet debug API misuse from the failed compile cycles. +- Do not suppress or select reports using patch anchors, unique literals from regression-test-issue-4934.js, or hardcoded line numbers. diff --git a/tasks/csa159/pair_137377/checker_template.cpp b/tasks/csa159/pair_137377/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_137377/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_137377/config.json b/tasks/csa159/pair_137377/config.json new file mode 100644 index 0000000000000000000000000000000000000000..7990eb86d08659fb10d1838910f423d58046cbf6 --- /dev/null +++ b/tasks/csa159/pair_137377/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "jerryscript-project_jerryscript", + "before_commit": "ab2e8217778b95977821ccbcd9a11346f5749fc2", + "after_commit": "1230d4532c215abe8679a3c6ecda6152c502ae60", + "repo_path": "/workspace/repo/jerryscript-project/jerryscript", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/jerryscript-project_jerryscript/aaf0442611e0707a3bc680d30b532b93e30e1066/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/jerryscript-project_jerryscript/aaf0442611e0707a3bc680d30b532b93e30e1066/compile_commands.json", + "changed_files": [ + "jerry-core/parser/js/js-lexer.c" + ], + "commit_message": "Asterisk should be ignored by object initializers. (#3872)\n\nFixes #3869\n\nJerryScript-DCO-1.0-Signed-off-by: Zoltan Herczeg zherczeg.u-szeged@partner.samsung.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_137377/patch.diff b/tasks/csa159/pair_137377/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..564f180b306b8c8df39f9a2eeb4b10c387f43da2 --- /dev/null +++ b/tasks/csa159/pair_137377/patch.diff @@ -0,0 +1,61 @@ +diff --git a/jerry-core/parser/js/js-lexer.c b/jerry-core/parser/js/js-lexer.c +index 2655d711..d0c00a71 100644 +--- a/jerry-core/parser/js/js-lexer.c ++++ b/jerry-core/parser/js/js-lexer.c +@@ -3048,6 +3048,16 @@ lexer_expect_object_literal_id (parser_context_t *context_p, /**< context */ + return; + } + case LIT_CHAR_ASTERISK: ++ { ++ if (ident_opts & (LEXER_OBJ_IDENT_ONLY_IDENTIFIERS | LEXER_OBJ_IDENT_OBJECT_PATTERN)) ++ { ++ break; ++ } ++ ++ context_p->token.type = LEXER_MULTIPLY; ++ lexer_consume_next_character (context_p); ++ return; ++ } + #endif /* ENABLED (JERRY_ES2015) */ + case LIT_CHAR_RIGHT_BRACE: + { +@@ -3057,13 +3067,6 @@ lexer_expect_object_literal_id (parser_context_t *context_p, /**< context */ + } + + context_p->token.type = LEXER_RIGHT_BRACE; +-#if ENABLED (JERRY_ES2015) +- if (context_p->source_p[0] == LIT_CHAR_ASTERISK) +- { +- context_p->token.type = LEXER_MULTIPLY; +- } +-#endif /* ENABLED (JERRY_ES2015) */ +- + lexer_consume_next_character (context_p); + return; + } +diff --git a/tests/jerry/es2015/regresssion-test-issue-3869.js b/tests/jerry/es2015/regresssion-test-issue-3869.js +new file mode 100644 +index 00000000..26cb32f1 +--- /dev/null ++++ b/tests/jerry/es2015/regresssion-test-issue-3869.js +@@ -0,0 +1,20 @@ ++// Copyright JS Foundation and other contributors, http://js.foundation ++// ++// Licensed under the Apache License, Version 2.0 (the "License"); ++// you may not use this file except in compliance with the License. ++// You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, software ++// distributed under the License is distributed on an "AS IS" BASIS ++// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++// See the License for the specific language governing permissions and ++// limitations under the License. ++ ++try { ++ eval('function a ({ *x:x }) {}') ++ assert(false) ++} catch (e) { ++ assert(e instanceof SyntaxError) ++} \ No newline at end of file diff --git a/tasks/csa159/pair_137377/post_functions.txt b/tasks/csa159/pair_137377/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..553799f1f112941260fe2cd5c6532dc7e7e0420d --- /dev/null +++ b/tasks/csa159/pair_137377/post_functions.txt @@ -0,0 +1,160 @@ +### File: jerry-core/parser/js/js-lexer.c +```c +void +lexer_expect_object_literal_id (parser_context_t *context_p, /**< context */ + uint32_t ident_opts) /**< lexer_obj_ident_opts_t option bits */ +{ + lexer_skip_spaces (context_p); + + if (context_p->source_p >= context_p->source_end_p) + { + parser_raise_error (context_p, PARSER_ERR_PROPERTY_IDENTIFIER_EXPECTED); + } + +#if ENABLED (JERRY_ES2015) + int is_class_method = ((ident_opts & LEXER_OBJ_IDENT_CLASS_METHOD) + && !(ident_opts & LEXER_OBJ_IDENT_ONLY_IDENTIFIERS) + && (context_p->token.type != LEXER_KEYW_STATIC)); +#endif /* ENABLED (JERRY_ES2015) */ + + context_p->token.line = context_p->line; + context_p->token.column = context_p->column; + bool create_literal_object = false; + + if (lexer_parse_identifier (context_p, LEXER_PARSE_NO_OPTS)) + { + if (!(ident_opts & (LEXER_OBJ_IDENT_ONLY_IDENTIFIERS | LEXER_OBJ_IDENT_OBJECT_PATTERN))) + { + lexer_skip_spaces (context_p); + context_p->token.flags = (uint8_t) (context_p->token.flags | LEXER_NO_SKIP_SPACES); + + if (context_p->source_p < context_p->source_end_p +#if ENABLED (JERRY_ES2015) + && context_p->source_p[0] != LIT_CHAR_COMMA + && context_p->source_p[0] != LIT_CHAR_RIGHT_BRACE + && context_p->source_p[0] != LIT_CHAR_LEFT_PAREN +#endif /* ENABLED (JERRY_ES2015) */ + && context_p->source_p[0] != LIT_CHAR_COLON) + { + if (lexer_compare_literal_to_string (context_p, "get", 3)) + { + context_p->token.type = LEXER_PROPERTY_GETTER; + return; + } + + if (lexer_compare_literal_to_string (context_p, "set", 3)) + { + context_p->token.type = LEXER_PROPERTY_SETTER; + return; + } + +#if ENABLED (JERRY_ES2015) + if (lexer_compare_literal_to_string (context_p, "async", 5)) + { + context_p->token.type = LEXER_KEYW_ASYNC; + return; + } +#endif /* ENABLED (JERRY_ES2015) */ + } + } + +#if ENABLED (JERRY_ES2015) + if (is_class_method && lexer_compare_literal_to_string (context_p, "static", 6)) + { + context_p->token.type = LEXER_KEYW_STATIC; + return; + } +#endif /* ENABLED (JERRY_ES2015) */ + + create_literal_object = true; + } + else + { + switch (context_p->source_p[0]) + { + case LIT_CHAR_DOUBLE_QUOTE: + case LIT_CHAR_SINGLE_QUOTE: + { + lexer_parse_string (context_p, LEXER_STRING_NO_OPTS); + create_literal_object = true; + break; + } +#if ENABLED (JERRY_ES2015) + case LIT_CHAR_LEFT_SQUARE: + { + lexer_consume_next_character (context_p); + + lexer_next_token (context_p); + parser_parse_expression (context_p, PARSE_EXPR_NO_COMMA); + + if (context_p->token.type != LEXER_RIGHT_SQUARE) + { + parser_raise_error (context_p, PARSER_ERR_RIGHT_SQUARE_EXPECTED); + } + return; + } + case LIT_CHAR_ASTERISK: + { + if (ident_opts & (LEXER_OBJ_IDENT_ONLY_IDENTIFIERS | LEXER_OBJ_IDENT_OBJECT_PATTERN)) + { + break; + } + + context_p->token.type = LEXER_MULTIPLY; + lexer_consume_next_character (context_p); + return; + } +#endif /* ENABLED (JERRY_ES2015) */ + case LIT_CHAR_RIGHT_BRACE: + { + if (ident_opts & LEXER_OBJ_IDENT_ONLY_IDENTIFIERS) + { + break; + } + + context_p->token.type = LEXER_RIGHT_BRACE; + lexer_consume_next_character (context_p); + return; + } + default: + { + const uint8_t *char_p = context_p->source_p; + + if (char_p[0] == LIT_CHAR_DOT) + { + char_p++; + } + + if (char_p < context_p->source_end_p + && char_p[0] >= LIT_CHAR_0 + && char_p[0] <= LIT_CHAR_9) + { + lexer_parse_number (context_p); + lexer_construct_number_object (context_p, false, false); + return; + } + break; + } + } + } + + if (create_literal_object) + { +#if ENABLED (JERRY_ES2015) + if (is_class_method && lexer_compare_literal_to_string (context_p, "constructor", 11)) + { + context_p->token.type = LEXER_CLASS_CONSTRUCTOR; + context_p->token.flags &= (uint8_t) ~LEXER_NO_SKIP_SPACES; + return; + } +#endif /* ENABLED (JERRY_ES2015) */ + + lexer_construct_literal_object (context_p, + &context_p->token.lit_location, + LEXER_STRING_LITERAL); + return; + } + + parser_raise_error (context_p, PARSER_ERR_PROPERTY_IDENTIFIER_EXPECTED); +} +``` diff --git a/tasks/csa159/pair_137377/pre_functions.txt b/tasks/csa159/pair_137377/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..e641fb53882c7679e6a99023f204b92b2188b935 --- /dev/null +++ b/tasks/csa159/pair_137377/pre_functions.txt @@ -0,0 +1,157 @@ +### File: jerry-core/parser/js/js-lexer.c +```c +void +lexer_expect_object_literal_id (parser_context_t *context_p, /**< context */ + uint32_t ident_opts) /**< lexer_obj_ident_opts_t option bits */ +{ + lexer_skip_spaces (context_p); + + if (context_p->source_p >= context_p->source_end_p) + { + parser_raise_error (context_p, PARSER_ERR_PROPERTY_IDENTIFIER_EXPECTED); + } + +#if ENABLED (JERRY_ES2015) + int is_class_method = ((ident_opts & LEXER_OBJ_IDENT_CLASS_METHOD) + && !(ident_opts & LEXER_OBJ_IDENT_ONLY_IDENTIFIERS) + && (context_p->token.type != LEXER_KEYW_STATIC)); +#endif /* ENABLED (JERRY_ES2015) */ + + context_p->token.line = context_p->line; + context_p->token.column = context_p->column; + bool create_literal_object = false; + + if (lexer_parse_identifier (context_p, LEXER_PARSE_NO_OPTS)) + { + if (!(ident_opts & (LEXER_OBJ_IDENT_ONLY_IDENTIFIERS | LEXER_OBJ_IDENT_OBJECT_PATTERN))) + { + lexer_skip_spaces (context_p); + context_p->token.flags = (uint8_t) (context_p->token.flags | LEXER_NO_SKIP_SPACES); + + if (context_p->source_p < context_p->source_end_p +#if ENABLED (JERRY_ES2015) + && context_p->source_p[0] != LIT_CHAR_COMMA + && context_p->source_p[0] != LIT_CHAR_RIGHT_BRACE + && context_p->source_p[0] != LIT_CHAR_LEFT_PAREN +#endif /* ENABLED (JERRY_ES2015) */ + && context_p->source_p[0] != LIT_CHAR_COLON) + { + if (lexer_compare_literal_to_string (context_p, "get", 3)) + { + context_p->token.type = LEXER_PROPERTY_GETTER; + return; + } + + if (lexer_compare_literal_to_string (context_p, "set", 3)) + { + context_p->token.type = LEXER_PROPERTY_SETTER; + return; + } + +#if ENABLED (JERRY_ES2015) + if (lexer_compare_literal_to_string (context_p, "async", 5)) + { + context_p->token.type = LEXER_KEYW_ASYNC; + return; + } +#endif /* ENABLED (JERRY_ES2015) */ + } + } + +#if ENABLED (JERRY_ES2015) + if (is_class_method && lexer_compare_literal_to_string (context_p, "static", 6)) + { + context_p->token.type = LEXER_KEYW_STATIC; + return; + } +#endif /* ENABLED (JERRY_ES2015) */ + + create_literal_object = true; + } + else + { + switch (context_p->source_p[0]) + { + case LIT_CHAR_DOUBLE_QUOTE: + case LIT_CHAR_SINGLE_QUOTE: + { + lexer_parse_string (context_p, LEXER_STRING_NO_OPTS); + create_literal_object = true; + break; + } +#if ENABLED (JERRY_ES2015) + case LIT_CHAR_LEFT_SQUARE: + { + lexer_consume_next_character (context_p); + + lexer_next_token (context_p); + parser_parse_expression (context_p, PARSE_EXPR_NO_COMMA); + + if (context_p->token.type != LEXER_RIGHT_SQUARE) + { + parser_raise_error (context_p, PARSER_ERR_RIGHT_SQUARE_EXPECTED); + } + return; + } + case LIT_CHAR_ASTERISK: +#endif /* ENABLED (JERRY_ES2015) */ + case LIT_CHAR_RIGHT_BRACE: + { + if (ident_opts & LEXER_OBJ_IDENT_ONLY_IDENTIFIERS) + { + break; + } + + context_p->token.type = LEXER_RIGHT_BRACE; +#if ENABLED (JERRY_ES2015) + if (context_p->source_p[0] == LIT_CHAR_ASTERISK) + { + context_p->token.type = LEXER_MULTIPLY; + } +#endif /* ENABLED (JERRY_ES2015) */ + + lexer_consume_next_character (context_p); + return; + } + default: + { + const uint8_t *char_p = context_p->source_p; + + if (char_p[0] == LIT_CHAR_DOT) + { + char_p++; + } + + if (char_p < context_p->source_end_p + && char_p[0] >= LIT_CHAR_0 + && char_p[0] <= LIT_CHAR_9) + { + lexer_parse_number (context_p); + lexer_construct_number_object (context_p, false, false); + return; + } + break; + } + } + } + + if (create_literal_object) + { +#if ENABLED (JERRY_ES2015) + if (is_class_method && lexer_compare_literal_to_string (context_p, "constructor", 11)) + { + context_p->token.type = LEXER_CLASS_CONSTRUCTOR; + context_p->token.flags &= (uint8_t) ~LEXER_NO_SKIP_SPACES; + return; + } +#endif /* ENABLED (JERRY_ES2015) */ + + lexer_construct_literal_object (context_p, + &context_p->token.lit_location, + LEXER_STRING_LITERAL); + return; + } + + parser_raise_error (context_p, PARSER_ERR_PROPERTY_IDENTIFIER_EXPECTED); +} +``` diff --git a/tasks/csa159/pair_137377/task_prompt.md b/tasks/csa159/pair_137377/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..e5a10759be9e0adfb907a757815a4f2a3b9bd9d0 --- /dev/null +++ b/tasks/csa159/pair_137377/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: `control_flow` + +### Current failure diagnosis + +- The rollout did not establish hard validation, objective eligibility, semantic correctness, refinement acceptance, or process quality; score and verification artifacts were missing and semantic status was unavailable. +- The official scan configuration compiles with JERRY_ES2015=0, removing both the vulnerable LEXER_MULTIPLY assignment and the patched guard, so before and after translation units are effectively identical and cannot demonstrate a buggy-only finding. +- The vulnerability depends on whether a rejection guard dominates the token assignment and whether its unsafe branch can reach that assignment; syntax matching alone cannot prove this relation. +- The attempted rollout was marked semantically inadequate by the constraint ledger, so a new synthesis must provide an independently verifiable control-flow proof rather than rely on the previous result or its reported score. + +### Preserve from prior rollouts + +- Do not introduce dependence on patch anchors, including changed lines, patch layout, source locations, or other artifacts unique to the supplied diff. +- Do not introduce patch-local hardcoding; matching must remain based on general semantic entities and relationships rather than reproducing the particular patch text. + +### Required semantic proof + +- Identify the sink as an assignment of the LEXER_MULTIPLY enumerator to the lexer token.type field within lexer_expect_object_literal_id. +- Establish that the sink is unsafe when ident_opts may contain LEXER_OBJ_IDENT_OBJECT_PATTERN, because the pre-patch path can accept an asterisk-prefixed object-pattern property instead of raising the expected parser error. +- Recognize a guard only when it tests the ident_opts parameter with a mask whose resolved value includes LEXER_OBJ_IDENT_OBJECT_PATTERN, regardless of operand order or equivalent zero-comparison polarity. +- Prove that the guard's condition dominates the sink in the function CFG, so every path reaching the assignment passes through the guard. +- Prove that paths where the object-pattern bit is set cannot reach the sink: the sink must be on the bit-clear branch, or the rejecting branch must terminate before the sink without a possible re-entry. +- Report the sink when no such complete dominance and reachability proof exists. + +### Implementation constraints + +- Use a statement callback capable of observing assignment expressions directly, specifically check::PreStmt or an equivalent assignment-observing CSA callback; do not use a call-only callback. +- Resolve the assignment's member chain and RHS through the AST, including token.type, the LEXER_MULTIPLY enumerator, the enclosing lexer_expect_object_literal_id function, and the ident_opts parameter. +- Obtain the object-pattern bit from the declaration of LEXER_OBJ_IDENT_OBJECT_PATTERN rather than embedding its numeric value. +- Use AnalysisDeclContext CFG information and a dominator relation between the guard condition and assignment; account for statement order when both occur in the same CFG block. +- Analyze the rejecting branch structurally and conservatively, including return or break termination, possible enclosing-loop re-entry, and goto-related uncertainty; unknown control flow must not be treated as safe. +- Keep reports localized to the token.type assignment expression and scope findings to the demonstrated project-general semantic pattern. + +### Validation checklist + +- Compile the new checker and its loadable artifact successfully, then run code verification so build and registration failures are surfaced. +- Run before and after scans with JERRY_ES2015=1, or an equivalent configuration that retains the vulnerable and patched code, and require a finding on the vulnerable revision but not on the patched revision. +- Also run the official scan configuration and record that preprocessing may erase the defect; do not interpret an identical 0/0 result there as semantic validation. +- Confirm the report location is the LEXER_MULTIPLY assignment inside lexer_expect_object_literal_id, not another assignment with the same enumerator. +- Check reporting for a mask that omits the object-pattern bit, a non-dominating guard, a rejecting branch that falls through, and a negated guard whose unsafe edge reaches the sink. +- Check suppression for a combined mask with a terminating rejection, reversed mask operands, an object-pattern-only mask with terminating return, and a sink inside the bit-clear branch. +- Check that an equivalent assignment in a differently named function is ignored and that no patch-anchor or patch-local hardcoding invariant regresses. +- Require generated score, verification, cross-validation, and refinement artifacts to be present and non-empty before treating the synthesis as accepted. + +### Avoid and forbidden regressions + +- Do not classify the assignment as vulnerable solely because its syntax or RHS enumerator matches; the assignment is legal when the object-pattern option is clear. +- Do not use path-insensitive textual matching of source lines, comments, preprocessing layout, patch hunks, or hardcoded line numbers. +- Do not accept a guard merely because it appears earlier in source order or dominates only one route to the sink. +- Do not treat a mask that tests only LEXER_OBJ_IDENT_ONLY_IDENTIFIERS as rejecting the object-pattern case. +- Do not suppress a finding when the rejecting branch can fall through, re-enter through an enclosing loop, or be bypassed through unsupported control flow. +- Do not rely on RangeConstraintManager bitwise facts as the sole proof of the object-pattern condition. +- Do not validate correctness using only the official JERRY_ES2015=0 scan, where the relevant code is preprocessed away. +- Do not broaden the checker to unrelated LEXER_MULTIPLY assignments outside lexer_expect_object_literal_id. diff --git a/tasks/csa159/pair_137389/checker_template.cpp b/tasks/csa159/pair_137389/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_137389/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_137389/config.json b/tasks/csa159/pair_137389/config.json new file mode 100644 index 0000000000000000000000000000000000000000..ccd2892f272b8898dcab73f8a639c68a250f76dc --- /dev/null +++ b/tasks/csa159/pair_137389/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "jerryscript-project_jerryscript", + "before_commit": "d681f201c259b092f1aa5736d30785a43cdbca1e", + "after_commit": "8fa7819c1f79c7c28aba7ed8ceb4d00cc007e839", + "repo_path": "/workspace/repo/jerryscript-project/jerryscript", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/jerryscript-project_jerryscript/c51b2682760e062c8735a91635ae1f02634aa74b/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/jerryscript-project_jerryscript/c51b2682760e062c8735a91635ae1f02634aa74b/compile_commands.json", + "changed_files": [ + "jerry-core/ecma/operations/ecma-atomics-object.c" + ], + "commit_message": "Fix memory leak in AtomicModifyWrite (#4944)\n\nThis patch fixes #4894.\n\nJerryScript-DCO-1.0-Signed-off-by: Robert Fancsik robert.fancsik@h-lab.eu", + "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_137389/patch.diff b/tasks/csa159/pair_137389/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..df66d707958435a67b0a021927e8d1f762e5a2a3 --- /dev/null +++ b/tasks/csa159/pair_137389/patch.diff @@ -0,0 +1,38 @@ +diff --git a/jerry-core/ecma/operations/ecma-atomics-object.c b/jerry-core/ecma/operations/ecma-atomics-object.c +index 6e2cfd0e..c42ad875 100644 +--- a/jerry-core/ecma/operations/ecma-atomics-object.c ++++ b/jerry-core/ecma/operations/ecma-atomics-object.c +@@ -192,6 +192,8 @@ ecma_atomic_read_modify_write (ecma_value_t typedarray, /**< typedArray argument + /* 9. */ + uint32_t indexed_position = ecma_number_to_uint32 (idx) * element_size + offset; + ++ ecma_free_value (idx); ++ + JERRY_UNUSED (indexed_position); + JERRY_UNUSED (element_type); + JERRY_UNUSED (val); +diff --git a/tests/jerry/es.next/regression-test-issue-4894.js b/tests/jerry/es.next/regression-test-issue-4894.js +new file mode 100644 +index 00000000..0f2db2c1 +--- /dev/null ++++ b/tests/jerry/es.next/regression-test-issue-4894.js +@@ -0,0 +1,19 @@ ++// Copyright JS Foundation and other contributors, http://js.foundation ++// ++// Licensed under the Apache License, Version 2.0 (the "License"); ++// you may not use this file except in compliance with the License. ++// You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, software ++// distributed under the License is distributed on an "AS IS" BASIS ++// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ++// See the License for the specific language governing permissions and ++// limitations under the License. ++ ++var sab = new SharedArrayBuffer(4); ++var a = new Int32Array(sab); ++ ++/* TODO: replace with the correct value whenever AtomicModifyWrite is properly implemented */ ++assert(Atomics.add(a, -0, 1) === 0); \ No newline at end of file diff --git a/tasks/csa159/pair_137389/post_functions.txt b/tasks/csa159/pair_137389/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..75cdfc444c55d1452351b814c2e3e121be18b99c --- /dev/null +++ b/tasks/csa159/pair_137389/post_functions.txt @@ -0,0 +1,71 @@ +### File: jerry-core/ecma/operations/ecma-atomics-object.c +```c +ecma_value_t +ecma_atomic_read_modify_write (ecma_value_t typedarray, /**< typedArray argument */ + ecma_value_t index, /**< index argument */ + ecma_value_t value, /**< value argument */ + ecma_atomics_op_t op) /**< operation argument */ +{ + /* 1. */ + ecma_value_t buffer = ecma_validate_shared_integer_typedarray (typedarray, false); + + if (ECMA_IS_VALUE_ERROR (buffer)) + { + return buffer; + } + + /* 2. */ + ecma_value_t idx = ecma_validate_atomic_access (typedarray, index); + + if (ECMA_IS_VALUE_ERROR (idx)) + { + return idx; + } + + /* 3. */ + ecma_object_t *typedarray_p = ecma_get_object_from_value (typedarray); + ecma_typedarray_info_t target_info = ecma_typedarray_get_info (typedarray_p); + + /* 4-5. */ + ecma_value_t val = ECMA_VALUE_ERROR; + ecma_number_t tmp; + if (target_info.id == ECMA_BIGINT64_ARRAY || target_info.id == ECMA_BIGUINT64_ARRAY) + { + val = ecma_bigint_to_bigint (value, true); + } + else if (!ECMA_IS_VALUE_ERROR (ecma_op_to_integer (value, &tmp))) + { + val = ecma_make_number_value (tmp); + } + + if (ECMA_IS_VALUE_ERROR (val)) + { + return val; + } + + /* 6. */ + uint8_t element_size = target_info.element_size; + + /* 7. */ + ecma_typedarray_type_t element_type = target_info.id; + + /* 8. */ + uint32_t offset = target_info.offset; + + /* 9. */ + uint32_t indexed_position = ecma_number_to_uint32 (idx) * element_size + offset; + + ecma_free_value (idx); + + JERRY_UNUSED (indexed_position); + JERRY_UNUSED (element_type); + JERRY_UNUSED (val); + JERRY_UNUSED (buffer); + JERRY_UNUSED (op); + + ecma_free_value (val); + + /* 10. */ + return ecma_make_uint32_value (0); +} +``` diff --git a/tasks/csa159/pair_137389/pre_functions.txt b/tasks/csa159/pair_137389/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..6f2cbf75dadd416aea31411901bc4b96119898d1 --- /dev/null +++ b/tasks/csa159/pair_137389/pre_functions.txt @@ -0,0 +1,69 @@ +### File: jerry-core/ecma/operations/ecma-atomics-object.c +```c +ecma_value_t +ecma_atomic_read_modify_write (ecma_value_t typedarray, /**< typedArray argument */ + ecma_value_t index, /**< index argument */ + ecma_value_t value, /**< value argument */ + ecma_atomics_op_t op) /**< operation argument */ +{ + /* 1. */ + ecma_value_t buffer = ecma_validate_shared_integer_typedarray (typedarray, false); + + if (ECMA_IS_VALUE_ERROR (buffer)) + { + return buffer; + } + + /* 2. */ + ecma_value_t idx = ecma_validate_atomic_access (typedarray, index); + + if (ECMA_IS_VALUE_ERROR (idx)) + { + return idx; + } + + /* 3. */ + ecma_object_t *typedarray_p = ecma_get_object_from_value (typedarray); + ecma_typedarray_info_t target_info = ecma_typedarray_get_info (typedarray_p); + + /* 4-5. */ + ecma_value_t val = ECMA_VALUE_ERROR; + ecma_number_t tmp; + if (target_info.id == ECMA_BIGINT64_ARRAY || target_info.id == ECMA_BIGUINT64_ARRAY) + { + val = ecma_bigint_to_bigint (value, true); + } + else if (!ECMA_IS_VALUE_ERROR (ecma_op_to_integer (value, &tmp))) + { + val = ecma_make_number_value (tmp); + } + + if (ECMA_IS_VALUE_ERROR (val)) + { + return val; + } + + /* 6. */ + uint8_t element_size = target_info.element_size; + + /* 7. */ + ecma_typedarray_type_t element_type = target_info.id; + + /* 8. */ + uint32_t offset = target_info.offset; + + /* 9. */ + uint32_t indexed_position = ecma_number_to_uint32 (idx) * element_size + offset; + + JERRY_UNUSED (indexed_position); + JERRY_UNUSED (element_type); + JERRY_UNUSED (val); + JERRY_UNUSED (buffer); + JERRY_UNUSED (op); + + ecma_free_value (val); + + /* 10. */ + return ecma_make_uint32_value (0); +} +``` diff --git a/tasks/csa159/pair_137389/task_prompt.md b/tasks/csa159/pair_137389/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..4c08e0e302365b20a51837459650ed6c8dae0392 --- /dev/null +++ b/tasks/csa159/pair_137389/task_prompt.md @@ -0,0 +1,384 @@ +# 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 + +- Refinement did not converge: the rollout ended with feedback_required and therefore did not establish an accepted, clean synthesis. +- The rollout regressed the accepted mechanism contract by being classified as cross-procedure/overkill; bounded recursive inspection of callee bodies exceeded the minimum intraprocedural path-sensitive protocol required for the defect. +- Producer classification remained insufficiently rigorous because treating a function as owning when any syntactic return constructs an owned value can conflate mixed return paths and does not prove that the analyzed call result is owned. +- Earlier broad ownership approximations based on every ecma_value_t-returning call or analyzer symbol shape could incorrectly track borrowed values such as buffer and could not represent JerryScript ownership semantics precisely. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after analyzer validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve the previously adequate path-sensitive CSA mechanism level and a semantic score at or above the configured threshold. +- Preserve process quality at or above the configured threshold. +- Remain independent of patch anchors, including changed line numbers, diff locations, regression-test text, and commit-specific identifiers. +- Remain free of patch-local hardcoding such as ecma_atomic_read_modify_write, the local name idx, or the specific issue test. +- Retain project-general JerryScript scope for ecma_value_t ownership defects. + +### Required semantic proof + +- Prove on each feasible path that a local ecma_value_t receives a value from a producer with a newly acquired reference and reaches a function exit without a matching release or ownership transfer. +- Distinguish ecma_validate_atomic_access ownership, evidenced by ecma_make_number_value and its allocating path, from ecma_validate_shared_integer_typedarray borrowing, evidenced by ecma_make_object_value merely encoding the existing buffer pointer. +- Treat return of the tracked local, including return idx on the ECMA_IS_VALUE_ERROR path, as ownership transfer rather than a leak. +- Show that the pre-patch successful fall-through keeps the idx obligation live, while the inserted ecma_free_value(idx) discharges that same obligation in the patched source. +- Do not treat ECMA_VALUE_ERROR sentinels, immediate-value constructors, borrowing wrappers, or unproven producers as owned acquisitions. +- Keep the separate val-conversion error path semantically distinct: idx remains unreleased there in both snapshots, so any justified report must persist rather than be credited as the patched differential. + +### Implementation constraints + +- Use ProgramState to maintain per-path ownership obligations keyed by stable local MemRegion identity, not by SymbolRef or the loaded SVal. +- Use check::Bind to associate declaration initialization and reassignment with the receiving local and to create or replace obligations only when ownership is proven. +- Use check::PostCall to discharge an obligation for the evidenced ecma_free_value, ecma_free_value_if_not_object, and ecma_fast_free_value release family. +- Use check::PreStmt to discharge an obligation when the tracked local is returned to the caller, and use check::EndFunction as the deterministic sink for obligations still live at exit. +- Restrict exit reports to locals owned by the function currently being exited so analyzer inlining cannot attribute caller obligations to a callee. +- Represent producer ownership through project-general JerryScript ownership semantics or summaries; do not use bounded recursive callee-body traversal as a substitute for path-correct producer contracts. +- Anchor diagnostics to the relevant acquisition and path endpoint closely enough to identify the unreleased value without relying on patch coordinates. +- Limit scope to local ecma_value_t ownership; no interprocedural ProgramState propagation is required. + +### Validation checklist + +- Compile the checker plugin successfully against the configured Clang Static Analyzer API and verify checker registration and report generation. +- Run the analyzer with the complete JerryScript include and compile flags so no missing-header failure remains unresolved. +- Scan both source snapshots and confirm at least one relevant warning in the buggy snapshot disappears after the inserted ecma_free_value(idx). +- Confirm buffer is never reported merely because its producer returns ecma_value_t or because its runtime representation is symbolic. +- Confirm return idx on the ECMA_IS_VALUE_ERROR path is silent in both snapshots because ownership is transferred. +- Confirm the successful pre-patch fall-through reports the live idx obligation and the corresponding patched path is silent. +- Check the val-conversion error path separately and require consistent behavior across snapshots; it must not be conflated with the fixed fall-through leak. +- Verify warning locality, sparsity, unchanged-source behavior, absence of unrelated disappeared warnings, patch-anchor independence, and acceptance of the refinement round. + +### Avoid and forbidden regressions + +- Do not reduce the design to syntax-only or CFG-only ordering checks; branch-specific ownership transfer requires path-sensitive state. +- Do not infer ownership from the ecma_value_t return type, getAsSymbol success, symbolic-versus-immediate representation, or callee naming alone. +- Do not classify a producer as owning solely because one syntactically collected return expression uses an owning constructor. +- Do not add interprocedural state propagation or bounded recursive return-body inspection when an explicit project ownership contract can model the call. +- Do not use check::PostCall alone for acquisition, because it does not reliably establish the receiving local. +- Do not key obligations by SymbolRef, use check::DeadSymbols as the function-exit sink, or attempt the invalid check::PostStmt callback. +- Do not suppress genuine persistent leaks merely to force the patched snapshot to be globally clean. +- Do not encode function-local names, source lines, patch text, test literals, or other CVE-specific anchors. diff --git a/tasks/csa159/pair_137518/checker_template.cpp b/tasks/csa159/pair_137518/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_137518/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_137518/config.json b/tasks/csa159/pair_137518/config.json new file mode 100644 index 0000000000000000000000000000000000000000..e86ed79cd92ba3129e78ca351dcacfbe08bf0078 --- /dev/null +++ b/tasks/csa159/pair_137518/config.json @@ -0,0 +1,20 @@ +{ + "project_id": "michaelforney_samurai", + "before_commit": "309c9d26cb9f5d0e64ab7c7ea6f73a94af221dd3", + "after_commit": "8b069471005e6c242795b68ad91c3b9000dad40e", + "repo_path": "/workspace/repo/michaelforney/samurai", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/michaelforney_samurai/80320920be3df3e827b127e27281224c32be9903/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/michaelforney_samurai/80320920be3df3e827b127e27281224c32be9903/compile_commands.json", + "changed_files": [ + "env.c", + "scan.c" + ], + "commit_message": "Detect cycles in rule variables\n\nReported by Frederic Cambus in #29.", + "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_137518/patch.diff b/tasks/csa159/pair_137518/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..717d0478cb8307c08afe8a358743bc39efb71e26 --- /dev/null +++ b/tasks/csa159/pair_137518/patch.diff @@ -0,0 +1,47 @@ +diff --git a/env.c b/env.c +index 5916355..51cece8 100644 +--- a/env.c ++++ b/env.c +@@ -204,6 +204,9 @@ edgevar(struct edge *e, char *var, bool escape) + str = treefind(e->rule->bindings, var); + if (!str) + return envvar(e->env->parent, var); ++ if (str->visited) ++ fatal("cycle in rule variable involving '%s'", var); ++ str->visited = true; + n = 0; + for (p = str->parts; p; p = p->next) { + if (p->var) +@@ -211,6 +214,7 @@ edgevar(struct edge *e, char *var, bool escape) + if (p->str) + n += p->str->n; + } ++ str->visited = false; + return merge(str, n); + } + +diff --git a/scan.c b/scan.c +index 4ba9e06..657ce96 100644 +--- a/scan.c ++++ b/scan.c +@@ -297,6 +297,7 @@ out: + return NULL; + str = xmalloc(sizeof(*str)); + str->parts = parts; ++ str->visited = false; + + return str; + } +diff --git a/util.h b/util.h +index b837f70..117dd31 100644 +--- a/util.h ++++ b/util.h +@@ -14,6 +14,8 @@ struct evalstring { + /* used temporarily only in parse.c:parseedge to keep track of + * input/output lists before we allocate the arrays. */ + struct evalstring *next; ++ /* used to detect cycles when evaluating rule variables */ ++ _Bool visited; + }; + + struct evalstringpart { \ No newline at end of file diff --git a/tasks/csa159/pair_137518/post_functions.txt b/tasks/csa159/pair_137518/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..1af1ffcb88e627a1be4387d59ebcb081a6f68ec0 --- /dev/null +++ b/tasks/csa159/pair_137518/post_functions.txt @@ -0,0 +1,91 @@ +### File: env.c +```c +struct string * +edgevar(struct edge *e, char *var, bool escape) +{ + struct string *val; + struct evalstring *str; + struct evalstringpart *p; + size_t n; + + if (strcmp(var, "in") == 0) + return pathlist(e->in, e->inimpidx, ' ', escape); + if (strcmp(var, "in_newline") == 0) + return pathlist(e->in, e->inimpidx, '\n', escape); + if (strcmp(var, "out") == 0) + return pathlist(e->out, e->outimpidx, ' ', escape); + val = treefind(e->env->bindings, var); + if (val) + return val; + str = treefind(e->rule->bindings, var); + if (!str) + return envvar(e->env->parent, var); + if (str->visited) + fatal("cycle in rule variable involving '%s'", var); + str->visited = true; + n = 0; + for (p = str->parts; p; p = p->next) { + if (p->var) + p->str = edgevar(e, p->var, escape); + if (p->str) + n += p->str->n; + } + str->visited = false; + return merge(str, n); +} +``` + +### File: scan.c +```c +struct evalstring * +scanstring(struct scanner *s, bool path) +{ + struct evalstring *str; + struct evalstringpart *parts = NULL, **end = &parts; + + buf.len = 0; + for (;;) { + switch (s->chr) { + case '$': + next(s); + escape(s, &end); + break; + case ':': + case '|': + case ' ': + if (path) + goto out; + /* fallthrough */ + default: + bufadd(&buf, s->chr); + next(s); + break; + case '\r': + case '\n': + case EOF: + goto out; + } + } +out: + if (buf.len > 0) + addstringpart(&end, 0); + if (path) + space(s); + if (!parts) + return NULL; + str = xmalloc(sizeof(*str)); + str->parts = parts; + str->visited = false; + + return str; +} + +void +scanchar(struct scanner *s, int c) +{ + if (s->chr != c) + scanerror(s, "expected '%c'", c); + next(s); + space(s); +} +``` diff --git a/tasks/csa159/pair_137518/pre_functions.txt b/tasks/csa159/pair_137518/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..d5a3bd54841e1e4c259c1c78786b7772923a2cf2 --- /dev/null +++ b/tasks/csa159/pair_137518/pre_functions.txt @@ -0,0 +1,93 @@ +### File: env.c +```c +struct string * +edgevar(struct edge *e, char *var, bool escape) +{ + struct string *val; + struct evalstring *str; + struct evalstringpart *p; + size_t n; + + if (strcmp(var, "in") == 0) + return pathlist(e->in, e->inimpidx, ' ', escape); + if (strcmp(var, "in_newline") == 0) + return pathlist(e->in, e->inimpidx, '\n', escape); + if (strcmp(var, "out") == 0) + return pathlist(e->out, e->outimpidx, ' ', escape); + val = treefind(e->env->bindings, var); + if (val) + return val; + str = treefind(e->rule->bindings, var); + if (!str) + return envvar(e->env->parent, var); + n = 0; + for (p = str->parts; p; p = p->next) { + if (p->var) + p->str = edgevar(e, p->var, escape); + if (p->str) + n += p->str->n; + } + return merge(str, n); +} + +static void +addpool(struct pool *p) +{ + if (treeinsert(&pools, p->name, p)) + fatal("pool '%s' redefined", p->name); +} +``` + +### File: scan.c +```c +struct evalstring * +scanstring(struct scanner *s, bool path) +{ + struct evalstring *str; + struct evalstringpart *parts = NULL, **end = &parts; + + buf.len = 0; + for (;;) { + switch (s->chr) { + case '$': + next(s); + escape(s, &end); + break; + case ':': + case '|': + case ' ': + if (path) + goto out; + /* fallthrough */ + default: + bufadd(&buf, s->chr); + next(s); + break; + case '\r': + case '\n': + case EOF: + goto out; + } + } +out: + if (buf.len > 0) + addstringpart(&end, 0); + if (path) + space(s); + if (!parts) + return NULL; + str = xmalloc(sizeof(*str)); + str->parts = parts; + + return str; +} + +void +scanchar(struct scanner *s, int c) +{ + if (s->chr != c) + scanerror(s, "expected '%c'", c); + next(s); + space(s); +} +``` diff --git a/tasks/csa159/pair_137518/task_prompt.md b/tasks/csa159/pair_137518/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..c666acc089716a89861cf197f7c8ce9c2b0e5196 --- /dev/null +++ b/tasks/csa159/pair_137518/task_prompt.md @@ -0,0 +1,375 @@ +# 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 rollout recognized a direct self-call inside a linked-structure loop, but its local AST and dominance checks did not establish that variable references form an actual cyclic binding graph. +- The implementation modeled a marker protocol around one recursive call without tracking visited state across recursive invocations, so it could not prove that the guard remains effective as evaluation re-enters the same expansion object. +- The accepted scan result was not semantically exact: the checker also accepted structurally similar recursion that might terminate through another mechanism or might not cycle, and the semantic evaluation marked the mechanism inadequate with a score of 6.0. + +### Preserve from prior rollouts + +- Retain successful checker compilation, before/after validation, and code verification. +- Retain objective eligibility gate G6 and the demonstrated differential result of one relevant pre-patch warning disappearing after the patch. +- Retain an accepted or clean refinement outcome. +- Retain at least the previously adequate path-sensitive CSA capability while adding the cross-call state needed for the semantic proof. +- Keep process quality at or above the configured threshold. +- Do not introduce patch-anchor dependence or patch-local hardcoding. + +### Required semantic proof + +- Establish that the vulnerable operation is direct recursive evaluation of a variable reference whose binding leads, through the traversed parts, back to an already active binding or expansion object. +- Track the identity of the active evaluation object across recursive calls and prove that the same object can be re-entered before the original evaluation completes. +- For the pre-patch path, prove that no effective terminating condition prevents that repeated expansion; absence of a merely syntactic guard is insufficient. +- For the patched path, prove that the visited state is initialized, checked before recursive descent, causes termination when already active, and is cleared after normal completion, with the state referring to the same expansion object across calls. +- Suppress reports for genuinely well-founded descent or another proven terminating condition, rather than treating every recursive traversal lacking the specific marker shape as vulnerable. + +### Implementation constraints + +- Use CSA analysis callbacks that preserve and propagate facts through call entry, recursive invocation, and return, with ProgramState or an equivalent interprocedural dataflow representation for active expansion identities and visited status. +- Use AST and CFG evidence to identify the direct recursive sink, the loop over linked evaluation parts, the binding lookup or value extraction that supplies the next recursive reference, and the ordering of guard, descent, and cleanup. +- Require object identity and binding-edge relationships to be established from declarations, expressions, and analyzer regions or symbols; matching field names, types, or source text alone is insufficient. +- Report at the recursive operation that can re-enter an active expansion, with a source location local to that sink and without relying on patch line numbers or changed-function names. +- Keep analysis scoped to generic recursive binding or expansion structures and do not encode edgevar, evalstring, visited, treefind, project identifiers, or patch-specific literals. +- Do not rely solely on a whole-function dominance pattern to substitute for state propagation across recursive calls. + +### Validation checklist + +- Compile the new checker and verify the produced analyzer plugin before scanning. +- Scan the supplied pre-patch sources and confirm exactly the relevant uncontrolled-recursion case is diagnosed. +- Scan the supplied patched sources and confirm the relevant diagnostic disappears, including validation of the visited-field initialization shown in scanstring. +- Verify the report location is at or immediately adjacent to the recursive evaluation operation and remains within the affected function. +- Check that no warnings appear in the supplied non-patched scope and that the differential, sharpness, sparsity, and objective-gate validations remain successful. +- Exercise relevant refinements for cyclic bindings, acyclic chained bindings, repeated but completed evaluations, alternate terminating paths, and unrelated recursive loops. +- Verify the semantic result is accepted at or above the configured threshold and that the refinement outcome remains accepted or clean. + +### Avoid and forbidden regressions + +- Do not use only local AST matching and CFG dominance to infer a cycle across recursive invocations. +- Do not report the broad pattern of recursion inside a linked-structure loop merely because a recognized marker protocol is absent. +- Do not treat a marker check as effective unless its state is tied to the same expansion object and is observed across the recursive call chain. +- Do not substitute an unproven counter, fatal-call heuristic, structural descent assumption, or syntactic guard for evidence that the binding graph terminates. +- Do not regress compile, before/after scan, code verification, refinement, process-score, objective-gate, anchor-free, or hardcoding-free requirements. diff --git a/tasks/csa159/pair_137674/checker_template.cpp b/tasks/csa159/pair_137674/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_137674/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_137674/config.json b/tasks/csa159/pair_137674/config.json new file mode 100644 index 0000000000000000000000000000000000000000..a469ac34ff3a01b88367a407973b3d1f2e966c92 --- /dev/null +++ b/tasks/csa159/pair_137674/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "seccomp_libseccomp", + "before_commit": "3e5a13d65ad16c60c659e0c471673def2c774d2a", + "after_commit": "c5bf78de480b32b324e0f511c88ce533ed280b37", + "repo_path": "/workspace/repo/seccomp/libseccomp", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/seccomp_libseccomp/80a987d6f8d0152def07fa90ace6417d56eea741/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/seccomp_libseccomp/80a987d6f8d0152def07fa90ace6417d56eea741/compile_commands.json", + "changed_files": [ + "src/db.c" + ], + "commit_message": "db: fix 64-bit argument comparisons\n\nOur approach to doing 64-bit comparisons using 32-bit operators was\njust plain wrong, leading to a number of potential problems with\nfilters that used the LT, GT, LE, or GE operators. This patch fixes\nthis problem and a few other related issues that came to light in\nthe course of fixing the core problem.\n\nA special thanks to Jann Horn for bringing this problem to our\nattention.\n\nSigned-off-by: Paul Moore ", + "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_137674/patch.diff b/tasks/csa159/pair_137674/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3aa7f6493eefba18379d799a39ed4e3f84843abd --- /dev/null +++ b/tasks/csa159/pair_137674/patch.diff @@ -0,0 +1,939 @@ +diff --git a/src/db.c b/src/db.c +index da0dc16..64e0924 100644 +--- a/src/db.c ++++ b/src/db.c +@@ -2,6 +2,7 @@ + * Enhanced Seccomp Filter DB + * + * Copyright (c) 2012,2016,2018 Red Hat ++ * Copyright (c) 2019 Cisco Systems, Inc. + * Author: Paul Moore + */ + +@@ -62,6 +63,52 @@ struct db_iter_state { + struct db_sys_list *sx; + }; + ++static unsigned int _db_node_put(struct db_arg_chain_tree **node); ++ ++/** ++ * Define the syscall argument priority for nodes on the same level of the tree ++ * @param a tree node ++ * ++ * Prioritize the syscall argument value, taking into account hi/lo words. ++ * Should only ever really be called by _db_chain_{lt,eq}(). Returns an ++ * arbitrary value indicating priority. ++ * ++ */ ++static unsigned int __db_chain_arg_priority(const struct db_arg_chain_tree *a) ++{ ++ return (a->arg << 1) + (a->arg_h_flg ? 1 : 0); ++} ++ ++/** ++ * Define the "op" priority for nodes on the same level of the tree ++ * @param op the argument operator ++ * ++ * Prioritize the syscall argument comparison operator. Should only ever ++ * really be called by _db_chain_{lt,eq}(). Returns an arbitrary value ++ * indicating priority. ++ * ++ */ ++static unsigned int __db_chain_op_priority(enum scmp_compare op) ++{ ++ /* the distinction between LT/LT and GT/GE is mostly to make the ++ * ordering as repeatable as possible regardless of the order in which ++ * the rules are added */ ++ switch (op) { ++ case SCMP_CMP_MASKED_EQ: ++ case SCMP_CMP_EQ: ++ case SCMP_CMP_NE: ++ return 3; ++ case SCMP_CMP_LE: ++ case SCMP_CMP_LT: ++ return 2; ++ case SCMP_CMP_GE: ++ case SCMP_CMP_GT: ++ return 1; ++ default: ++ return 0; ++ } ++} ++ + /** + * Determine if node "a" is less than node "b" + * @param a tree node +@@ -74,13 +121,41 @@ struct db_iter_state { + static bool _db_chain_lt(const struct db_arg_chain_tree *a, + const struct db_arg_chain_tree *b) + { +- return ((a->arg < b->arg) || +- ((a->arg == b->arg) && +- ((a->op < b->op) || +- ((a->op == b->op) && +- ((a->mask < b->mask) || +- ((a->mask == b->mask) && +- (a->datum < b->datum))))))); ++ unsigned int a_arg, b_arg; ++ unsigned int a_op, b_op; ++ ++ a_arg = __db_chain_arg_priority(a); ++ b_arg = __db_chain_arg_priority(b); ++ if (a_arg < b_arg) ++ return true; ++ else if (a_arg > b_arg) ++ return false; ++ ++ a_op = __db_chain_op_priority(a->op_orig); ++ b_op = __db_chain_op_priority(b->op_orig); ++ if (a_op < b_op) ++ return true; ++ else if (a_op > b_op) ++ return false; ++ ++ /* NOTE: at this point the arg and op priorities are equal */ ++ ++ switch (a->op_orig) { ++ case SCMP_CMP_LE: ++ case SCMP_CMP_LT: ++ /* in order to ensure proper ordering for LT/LE comparisons we ++ * need to invert the argument value so smaller values come ++ * first */ ++ if (a->datum > b->datum) ++ return true; ++ break; ++ default: ++ if (a->datum < b->datum) ++ return true; ++ break; ++ } ++ ++ return false; + } + + /** +@@ -95,7 +170,12 @@ static bool _db_chain_lt(const struct db_arg_chain_tree *a, + static bool _db_chain_eq(const struct db_arg_chain_tree *a, + const struct db_arg_chain_tree *b) + { +- return ((a->arg == b->arg) && (a->op == b->op) && ++ unsigned int a_arg, b_arg; ++ ++ a_arg = __db_chain_arg_priority(a); ++ b_arg = __db_chain_arg_priority(b); ++ ++ return ((a_arg == b_arg) && (a->op == b->op) && + (a->datum == b->datum) && (a->mask == b->mask)); + } + +@@ -124,74 +204,6 @@ static bool _db_chain_zombie(const struct db_arg_chain_tree *iter) + !(iter->act_t_flg) && !(iter->act_f_flg)); + } + +-/** +- * Free a syscall filter argument chain tree +- * @param tree the argument chain list +- * +- * This function frees a tree and returns the number of nodes freed. Functions +- * should not call this directly, _db_tree_put() should be used instead. +- * +- */ +-static unsigned int _db_tree_put(struct db_arg_chain_tree **tree) +-{ +- int cnt = 0; +- struct db_arg_chain_tree *node, *prev, *next; +- +- if (tree == NULL || *tree == NULL) +- return 0; +- node = *tree; +- +- while (node->lvl_nxt != NULL) +- node = node->lvl_nxt; +- +- while (node != NULL) { +- prev = node->lvl_prv; +- next = node->lvl_nxt; +- +- cnt += _db_tree_put(&node->nxt_t); +- cnt += _db_tree_put(&node->nxt_f); +- if (--(node->refcnt) == 0) { +- /* remove the node from the current level */ +- if (prev) +- prev->lvl_nxt = next; +- if (next) +- next->lvl_prv = prev; +- +- /* reset the caller's pointer */ +- if (prev != NULL) +- *tree = prev; +- else +- *tree = next; +- +- /* cleanup and accounting */ +- free(node); +- cnt++; +- } +- +- /* next */ +- node = prev; +- } +- +- return cnt; +-} +- +-/** +- * Release a node reference +- * @param node pointer to a node +- * +- * This function drops a reference to an individual node, unless this is the +- * last reference in which the entire sub-tree is affected. Returns the number +- * of nodes freed. +- * +- */ +-static unsigned int _db_node_put(struct db_arg_chain_tree **node) +-{ +- if ((*node)->refcnt == 1) +- return _db_tree_put(node); +- (*node)->refcnt--; +- return 0; +-} +- + /** + * Get a node reference + * @param node pointer to a node +@@ -202,64 +214,131 @@ static unsigned int _db_node_put(struct db_arg_chain_tree **node) + */ + static struct db_arg_chain_tree *_db_node_get(struct db_arg_chain_tree *node) + { +- node->refcnt++; ++ if (node != NULL) ++ node->refcnt++; + return node; + } + + /** +- * Get a tree reference +- * @param tree pointer to a tree/sub-tree ++ * Garbage collect a level of the tree ++ * @param node tree node + * +- * This function gets references for an entire tree/sub-tree. Returns a +- * pointer to the top of the tree. ++ * Check the entire level on which @node resides, if there is no other part of ++ * the tree which points to a node on this level, remove the entire level. ++ * Returns the number of nodes removed. + * + */ +-static struct db_arg_chain_tree *_db_tree_get(struct db_arg_chain_tree *tree) ++static unsigned int _db_level_clean(struct db_arg_chain_tree *node) + { +- struct db_arg_chain_tree *iter; ++ int cnt = 0; ++ unsigned int links; ++ struct db_arg_chain_tree *n = node; ++ struct db_arg_chain_tree *start; + +- if (tree->nxt_t) { +- iter = tree->nxt_t; +- while (iter->lvl_prv != NULL) +- iter = iter->lvl_prv; +- do { +- _db_tree_get(iter); +- iter = iter->lvl_nxt; +- } while (iter != NULL); +- } ++ while (n->lvl_prv) ++ n = n->lvl_prv; ++ start = n; + +- if (tree->nxt_f) { +- iter = tree->nxt_f; +- while (iter->lvl_prv != NULL) +- iter = iter->lvl_prv; +- do { +- _db_tree_get(iter); +- iter = iter->lvl_nxt; +- } while (iter != NULL); ++ while (n != NULL) { ++ links = 0; ++ if (n->lvl_prv) ++ links++; ++ if (n->lvl_nxt) ++ links++; ++ ++ if (n->refcnt > links) ++ return cnt; ++ ++ n = n->lvl_nxt; + } + +- return _db_node_get(tree); ++ n = start; ++ while (n != NULL) ++ cnt += _db_node_put(&n); ++ ++ return cnt; + } + + /** +- * Get references for a tree level ++ * Free a syscall filter argument chain tree ++ * @param tree the argument chain list ++ * ++ * This function drops a reference to the tree pointed to by @tree and garbage ++ * collects the top level. Returns the number of nodes removed. ++ * ++ */ ++static unsigned int _db_tree_put(struct db_arg_chain_tree **tree) ++{ ++ unsigned int cnt; ++ ++ cnt = _db_node_put(tree); ++ if (*tree) ++ cnt += _db_level_clean(*tree); ++ ++ return cnt; ++} ++ ++/** ++ * Release a node reference + * @param node pointer to a node + * +- * This function gets references for each sub-tree on a the same level as the +- * given node. ++ * This function drops a reference to an individual node, unless this is the ++ * last reference in which the entire sub-tree is affected. Returns the number ++ * of nodes freed. + * + */ +-static void _db_level_get(struct db_arg_chain_tree *node) ++static unsigned int _db_node_put(struct db_arg_chain_tree **node) + { +- struct db_arg_chain_tree *iter = node; ++ unsigned int cnt = 0; ++ struct db_arg_chain_tree *n = *node; ++ struct db_arg_chain_tree *lvl_p, *lvl_n, *nxt_t, *nxt_f; + +- while (iter->lvl_prv != NULL) +- iter = iter->lvl_prv; ++ if (n == NULL) ++ return 0; ++ ++ if (--(n->refcnt) == 0) { ++ lvl_p = n->lvl_prv; ++ lvl_n = n->lvl_nxt; ++ nxt_t = n->nxt_t; ++ nxt_f = n->nxt_f; ++ ++ /* split the current level */ ++ /* NOTE: we still hold a ref for both lvl_p and lvl_n */ ++ if (lvl_p) ++ lvl_p->lvl_nxt = NULL; ++ if (lvl_n) ++ lvl_n->lvl_prv = NULL; ++ ++ /* drop refcnts on the current level */ ++ if (lvl_p) ++ cnt += _db_node_put(&lvl_p); ++ if (lvl_n) ++ cnt += _db_node_put(&lvl_n); ++ ++ /* re-link current level if it still exists */ ++ if (lvl_p) ++ lvl_p->lvl_nxt = _db_node_get(lvl_n); ++ if (lvl_n) ++ lvl_n->lvl_prv = _db_node_get(lvl_p); ++ ++ /* update caller's pointer */ ++ if (lvl_p) ++ *node = lvl_p; ++ else if (lvl_n) ++ *node = lvl_n; ++ else ++ *node = NULL; + +- while (iter) { +- _db_tree_get(iter); +- iter = iter->lvl_nxt; ++ /* drop the next level(s) */ ++ cnt += _db_tree_put(&nxt_t); ++ cnt += _db_tree_put(&nxt_f); ++ ++ /* cleanup and accounting */ ++ free(n); ++ cnt++; + } ++ ++ return cnt; + } + + /** +@@ -321,7 +400,7 @@ remove: + c_iter->lvl_nxt = NULL; + + /* free the node and any sub-trees */ +- cnt += _db_tree_put(&c_iter); ++ cnt += _db_node_put(&c_iter); + + return cnt; + } +@@ -606,12 +685,6 @@ static int _db_tree_add(struct db_arg_chain_tree **existing, + struct db_arg_chain_tree *x_iter = *existing; + struct db_arg_chain_tree *n_iter = new; + +- /* TODO: when we add sub-trees to the current level (see the lt/gt +- * branches below) we need to grab an extra reference for sub-trees at +- * the current as the current level is visible to both the new and +- * existing trees; at some point if would be nice if we didn't have to +- * take this extra reference */ +- + do { + if (_db_chain_eq(x_iter, n_iter)) { + if (n_iter->act_t_flg) { +@@ -625,13 +698,25 @@ static int _db_tree_add(struct db_arg_chain_tree **existing, + return rc; + + /* update with the new action */ +- rc = _db_tree_put(&x_iter->nxt_t); ++ rc = _db_node_put(&x_iter->nxt_t); + x_iter->nxt_t = NULL; + x_iter->act_t = n_iter->act_t; + x_iter->act_t_flg = true; + state->sx->node_cnt -= rc; +- } else if (n_iter->act_t != x_iter->act_t) +- return -EEXIST; ++ } else if (n_iter->act_t != x_iter->act_t) { ++ /* if we are dealing with a 64-bit ++ * comparison, we need to adjust our ++ * action based on the full 64-bit ++ * value to ensure we handle GT/GE ++ * comparisons correctly */ ++ if (n_iter->arg_h_flg && ++ (n_iter->datum_full > ++ x_iter->datum_full)) ++ x_iter->act_t = n_iter->act_t; ++ if (_db_chain_leaf(x_iter) || ++ _db_chain_leaf(n_iter)) ++ return -EEXIST; ++ } + } + if (n_iter->act_f_flg) { + if (!x_iter->act_f_flg) { +@@ -644,13 +729,25 @@ static int _db_tree_add(struct db_arg_chain_tree **existing, + return rc; + + /* update with the new action */ +- rc = _db_tree_put(&x_iter->nxt_f); ++ rc = _db_node_put(&x_iter->nxt_f); + x_iter->nxt_f = NULL; + x_iter->act_f = n_iter->act_f; + x_iter->act_f_flg = true; + state->sx->node_cnt -= rc; +- } else if (n_iter->act_f != x_iter->act_f) +- return -EEXIST; ++ } else if (n_iter->act_f != x_iter->act_f) { ++ /* if we are dealing with a 64-bit ++ * comparison, we need to adjust our ++ * action based on the full 64-bit ++ * value to ensure we handle LT/LE ++ * comparisons correctly */ ++ if (n_iter->arg_h_flg && ++ (n_iter->datum_full < ++ x_iter->datum_full)) ++ x_iter->act_t = n_iter->act_t; ++ if (_db_chain_leaf(x_iter) || ++ _db_chain_leaf(n_iter)) ++ return -EEXIST; ++ } + } + + if (n_iter->nxt_t) { +@@ -663,7 +760,7 @@ static int _db_tree_add(struct db_arg_chain_tree **existing, + return rc; + } else if (!x_iter->act_t_flg) { + /* add a new sub-tree */ +- x_iter->nxt_t = _db_tree_get(n_iter->nxt_t); ++ x_iter->nxt_t = _db_node_get(n_iter->nxt_t); + } else + /* done - existing tree is "shorter" */ + return 0; +@@ -678,7 +775,7 @@ static int _db_tree_add(struct db_arg_chain_tree **existing, + return rc; + } else if (!x_iter->act_f_flg) { + /* add a new sub-tree */ +- x_iter->nxt_f = _db_tree_get(n_iter->nxt_f); ++ x_iter->nxt_f = _db_node_get(n_iter->nxt_f); + } else + /* done - existing tree is "shorter" */ + return 0; +@@ -689,25 +786,27 @@ static int _db_tree_add(struct db_arg_chain_tree **existing, + /* try to move along the current level */ + if (x_iter->lvl_nxt == NULL) { + /* add to the end of this level */ +- _db_level_get(x_iter); +- _db_tree_get(n_iter); +- n_iter->lvl_prv = x_iter; +- x_iter->lvl_nxt = n_iter; ++ n_iter->lvl_prv = _db_node_get(x_iter); ++ x_iter->lvl_nxt = _db_node_get(n_iter); + return 0; + } else + /* next */ + x_iter = x_iter->lvl_nxt; + } else { + /* add before the existing node on this level*/ +- _db_level_get(x_iter); +- _db_tree_get(n_iter); +- if (x_iter->lvl_prv != NULL) +- x_iter->lvl_prv->lvl_nxt = n_iter; +- n_iter->lvl_prv = x_iter->lvl_prv; +- n_iter->lvl_nxt = x_iter; +- x_iter->lvl_prv = n_iter; +- if (*existing == x_iter) +- *existing = n_iter; ++ if (x_iter->lvl_prv != NULL) { ++ x_iter->lvl_prv->lvl_nxt = _db_node_get(n_iter); ++ n_iter->lvl_prv = x_iter->lvl_prv; ++ x_iter->lvl_prv = _db_node_get(n_iter); ++ n_iter->lvl_nxt = x_iter; ++ } else { ++ x_iter->lvl_prv = _db_node_get(n_iter); ++ n_iter->lvl_nxt = _db_node_get(x_iter); ++ } ++ if (*existing == x_iter) { ++ *existing = _db_node_get(n_iter); ++ _db_node_put(&x_iter); ++ } + return 0; + } + } while (x_iter); +@@ -1413,9 +1512,12 @@ static struct db_sys_list *_db_rule_gen_64(const struct arch_def *arch, + unsigned int iter; + struct db_sys_list *s_new; + const struct db_api_arg *chain = rule->args; +- struct db_arg_chain_tree *c_iter_hi = NULL, *c_iter_lo = NULL; +- struct db_arg_chain_tree *c_prev_hi = NULL, *c_prev_lo = NULL; +- bool tf_flag; ++ struct db_arg_chain_tree *c_iter[3] = { NULL, NULL, NULL }; ++ struct db_arg_chain_tree *c_prev[3] = { NULL, NULL, NULL }; ++ enum scmp_compare op_prev = _SCMP_CMP_MIN; ++ unsigned int arg; ++ scmp_datum_t mask; ++ scmp_datum_t datum; + + s_new = zmalloc(sizeof(*s_new)); + if (s_new == NULL) +@@ -1434,84 +1536,311 @@ static struct db_sys_list *_db_rule_gen_64(const struct arch_def *arch, + !_db_arg_cmp_need_lo(&chain[iter])) + continue; + +- c_iter_hi = zmalloc(sizeof(*c_iter_hi)); +- if (c_iter_hi == NULL) ++ c_iter[0] = zmalloc(sizeof(*c_iter[0])); ++ if (c_iter[0] == NULL) + goto gen_64_failure; +- c_iter_lo = zmalloc(sizeof(*c_iter_lo)); +- if (c_iter_lo == NULL) { +- free(c_iter_hi); ++ c_iter[1] = zmalloc(sizeof(*c_iter[1])); ++ if (c_iter[1] == NULL) { ++ free(c_iter[0]); + goto gen_64_failure; + } +- +- /* link this level to the previous level */ +- if (c_prev_lo != NULL) { +- if (!tf_flag) { +- c_prev_lo->nxt_f = _db_node_get(c_iter_hi); +- c_prev_hi->nxt_f = _db_node_get(c_iter_hi); +- } else +- c_prev_lo->nxt_t = _db_node_get(c_iter_hi); +- } else +- s_new->chains = _db_node_get(c_iter_hi); +- s_new->node_cnt += 2; +- +- /* set the arg, op, and datum fields */ +- c_iter_hi->arg = chain[iter].arg; +- c_iter_lo->arg = chain[iter].arg; +- c_iter_hi->arg_offset = arch_arg_offset_hi(arch, +- c_iter_hi->arg); +- c_iter_lo->arg_offset = arch_arg_offset_lo(arch, +- c_iter_lo->arg); ++ c_iter[2] = NULL; ++ ++ arg = chain[iter].arg; ++ mask = chain[iter].mask; ++ datum = chain[iter].datum; ++ ++ /* NOTE: with the idea that a picture is worth a thousand ++ * words, i'm presenting the following diagrams which ++ * show how we should compare 64-bit syscall arguments ++ * using 32-bit comparisons. ++ * ++ * in the diagrams below "A(x)" is the syscall argument ++ * being evaluated and "R(x)" is the syscall argument ++ * value specified in the libseccomp rule. the "ACCEPT" ++ * verdict indicates a rule match and processing should ++ * continue on to the rest of the rule, or the final rule ++ * action should be triggered. the "REJECT" verdict ++ * indicates that the rule does not match and processing ++ * should continue to the next rule or the default ++ * action. ++ * ++ * SCMP_CMP_GT: ++ * +------------------+ ++ * +--| Ah(x) > Rh(x) |------+ ++ * | +------------------+ | ++ * FALSE TRUE A ++ * | | C ++ * +-----------+ +----> C ++ * v +----> E ++ * +------------------+ | P ++ * +--| Ah(x) == Rh(x) |--+ | T ++ * R | +------------------+ | | ++ * E FALSE TRUE | ++ * J <----+ | | ++ * E <----+ +------------+ | ++ * C FALSE v | ++ * T | +------------------+ | ++ * +--| Al(x) > Rl(x) |------+ ++ * +------------------+ ++ * ++ * SCMP_CMP_GE: ++ * +------------------+ ++ * +--| Ah(x) > Rh(x) |------+ ++ * | +------------------+ | ++ * FALSE TRUE A ++ * | | C ++ * +-----------+ +----> C ++ * v +----> E ++ * +------------------+ | P ++ * +--| Ah(x) == Rh(x) |--+ | T ++ * R | +------------------+ | | ++ * E FALSE TRUE | ++ * J <----+ | | ++ * E <----+ +------------+ | ++ * C FALSE v | ++ * T | +------------------+ | ++ * +--| Al(x) >= Rl(x) |------+ ++ * +------------------+ ++ * ++ * SCMP_CMP_LT: ++ * +------------------+ ++ * +--| Ah(x) > Rh(x) |------+ ++ * | +------------------+ | ++ * FALSE TRUE R ++ * | | E ++ * +-----------+ +----> J ++ * v +----> E ++ * +------------------+ | C ++ * +--| Ah(x) == Rh(x) |--+ | T ++ * A | +------------------+ | | ++ * C FALSE TRUE | ++ * C <----+ | | ++ * E <----+ +------------+ | ++ * P FALSE v | ++ * T | +------------------+ | ++ * +--| Al(x) >= Rl(x) |------+ ++ * +------------------+ ++ * ++ * SCMP_CMP_LE: ++ * +------------------+ ++ * +--| Ah(x) > Rh(x) |------+ ++ * | +------------------+ | ++ * FALSE TRUE R ++ * | | E ++ * +-----------+ +----> J ++ * v +----> E ++ * +------------------+ | C ++ * +--| Ah(x) == Rh(x) |--+ | T ++ * A | +------------------+ | | ++ * C FALSE TRUE | ++ * C <----+ | | ++ * E <----+ +------------+ | ++ * P FALSE v | ++ * T | +------------------+ | ++ * +--| Al(x) > Rl(x) |------+ ++ * +------------------+ ++ * ++ * SCMP_CMP_EQ: ++ * +------------------+ ++ * +--| Ah(x) == Rh(x) |--+ ++ * R | +------------------+ | A ++ * E FALSE TRUE C ++ * J <----+ | C ++ * E <----+ +------------+ +----> E ++ * C FALSE v | P ++ * T | +------------------+ | T ++ * +--| Al(x) == Rl(x) |------+ ++ * +------------------+ ++ * ++ * SCMP_CMP_NE: ++ * +------------------+ ++ * +--| Ah(x) == Rh(x) |--+ ++ * A | +------------------+ | R ++ * C FALSE TRUE E ++ * C <----+ | J ++ * E <----+ +------------+ +----> E ++ * P FALSE v | C ++ * T | +------------------+ | T ++ * +--| Al(x) == Rl(x) |------+ ++ * +------------------+ ++ * ++ */ ++ ++ /* setup the level */ + switch (chain[iter].op) { + case SCMP_CMP_GT: +- c_iter_hi->op = SCMP_CMP_GE; +- c_iter_lo->op = SCMP_CMP_GT; +- tf_flag = true; +- break; +- case SCMP_CMP_NE: +- c_iter_hi->op = SCMP_CMP_EQ; +- c_iter_lo->op = SCMP_CMP_EQ; +- tf_flag = false; +- break; ++ case SCMP_CMP_GE: ++ case SCMP_CMP_LE: + case SCMP_CMP_LT: +- c_iter_hi->op = SCMP_CMP_GE; +- c_iter_lo->op = SCMP_CMP_GE; +- tf_flag = false; ++ c_iter[2] = zmalloc(sizeof(*c_iter[2])); ++ if (c_iter[2] == NULL) { ++ free(c_iter[0]); ++ free(c_iter[1]); ++ goto gen_64_failure; ++ } ++ ++ c_iter[0]->arg = arg; ++ c_iter[1]->arg = arg; ++ c_iter[2]->arg = arg; ++ c_iter[0]->arg_h_flg = true; ++ c_iter[1]->arg_h_flg = true; ++ c_iter[2]->arg_h_flg = false; ++ c_iter[0]->arg_offset = arch_arg_offset_hi(arch, arg); ++ c_iter[1]->arg_offset = arch_arg_offset_hi(arch, arg); ++ c_iter[2]->arg_offset = arch_arg_offset_lo(arch, arg); ++ ++ c_iter[0]->mask = D64_HI(mask); ++ c_iter[1]->mask = D64_HI(mask); ++ c_iter[2]->mask = D64_LO(mask); ++ c_iter[0]->datum = D64_HI(datum); ++ c_iter[1]->datum = D64_HI(datum); ++ c_iter[2]->datum = D64_LO(datum); ++ c_iter[0]->datum_full = datum; ++ c_iter[1]->datum_full = datum; ++ c_iter[2]->datum_full = datum; ++ ++ _db_node_mask_fixup(c_iter[0]); ++ _db_node_mask_fixup(c_iter[1]); ++ _db_node_mask_fixup(c_iter[2]); ++ ++ c_iter[0]->op = SCMP_CMP_GT; ++ c_iter[1]->op = SCMP_CMP_EQ; ++ switch (chain[iter].op) { ++ case SCMP_CMP_GT: ++ case SCMP_CMP_LE: ++ c_iter[2]->op = SCMP_CMP_GT; ++ break; ++ case SCMP_CMP_GE: ++ case SCMP_CMP_LT: ++ c_iter[2]->op = SCMP_CMP_GE; ++ break; ++ default: ++ /* we should never get here */ ++ goto gen_64_failure; ++ } ++ c_iter[0]->op_orig = chain[iter].op; ++ c_iter[1]->op_orig = chain[iter].op; ++ c_iter[2]->op_orig = chain[iter].op; ++ ++ c_iter[0]->nxt_f = _db_node_get(c_iter[1]); ++ c_iter[1]->nxt_t = _db_node_get(c_iter[2]); + break; +- case SCMP_CMP_LE: +- c_iter_hi->op = SCMP_CMP_GE; +- c_iter_lo->op = SCMP_CMP_GT; +- tf_flag = false; ++ case SCMP_CMP_EQ: ++ case SCMP_CMP_MASKED_EQ: ++ case SCMP_CMP_NE: ++ c_iter[0]->arg = arg; ++ c_iter[1]->arg = arg; ++ c_iter[0]->arg_h_flg = true; ++ c_iter[1]->arg_h_flg = false; ++ c_iter[0]->arg_offset = arch_arg_offset_hi(arch, arg); ++ c_iter[1]->arg_offset = arch_arg_offset_lo(arch, arg); ++ ++ c_iter[0]->mask = D64_HI(mask); ++ c_iter[1]->mask = D64_LO(mask); ++ c_iter[0]->datum = D64_HI(datum); ++ c_iter[1]->datum = D64_LO(datum); ++ c_iter[0]->datum_full = datum; ++ c_iter[1]->datum_full = datum; ++ ++ _db_node_mask_fixup(c_iter[0]); ++ _db_node_mask_fixup(c_iter[1]); ++ ++ switch (chain[iter].op) { ++ case SCMP_CMP_MASKED_EQ: ++ c_iter[0]->op = SCMP_CMP_MASKED_EQ; ++ c_iter[1]->op = SCMP_CMP_MASKED_EQ; ++ break; ++ default: ++ c_iter[0]->op = SCMP_CMP_EQ; ++ c_iter[1]->op = SCMP_CMP_EQ; ++ } ++ c_iter[0]->op_orig = chain[iter].op; ++ c_iter[1]->op_orig = chain[iter].op; ++ ++ c_iter[0]->nxt_t = _db_node_get(c_iter[1]); + break; + default: +- c_iter_hi->op = chain[iter].op; +- c_iter_lo->op = chain[iter].op; +- tf_flag = true; ++ /* we should never get here */ ++ goto gen_64_failure; + } +- c_iter_hi->mask = D64_HI(chain[iter].mask); +- c_iter_lo->mask = D64_LO(chain[iter].mask); +- c_iter_hi->datum = D64_HI(chain[iter].datum); +- c_iter_lo->datum = D64_LO(chain[iter].datum); + +- /* fixup the mask/datum */ +- _db_node_mask_fixup(c_iter_hi); +- _db_node_mask_fixup(c_iter_lo); ++ /* link this level to the previous level */ ++ if (c_prev[0] != NULL) { ++ switch (op_prev) { ++ case SCMP_CMP_GT: ++ case SCMP_CMP_GE: ++ c_prev[0]->nxt_t = _db_node_get(c_iter[0]); ++ c_prev[2]->nxt_t = _db_node_get(c_iter[0]); ++ break; ++ case SCMP_CMP_EQ: ++ case SCMP_CMP_MASKED_EQ: ++ c_prev[1]->nxt_t = _db_node_get(c_iter[0]); ++ break; ++ case SCMP_CMP_LE: ++ case SCMP_CMP_LT: ++ c_prev[1]->nxt_f = _db_node_get(c_iter[0]); ++ c_prev[2]->nxt_f = _db_node_get(c_iter[0]); ++ break; ++ case SCMP_CMP_NE: ++ c_prev[0]->nxt_f = _db_node_get(c_iter[0]); ++ c_prev[1]->nxt_f = _db_node_get(c_iter[0]); ++ break; ++ default: ++ /* we should never get here */ ++ goto gen_64_failure; ++ } ++ } else ++ s_new->chains = _db_node_get(c_iter[0]); + +- /* link the hi and lo chain nodes */ +- c_iter_hi->nxt_t = _db_node_get(c_iter_lo); ++ /* update the node count */ ++ switch (chain[iter].op) { ++ case SCMP_CMP_NE: ++ case SCMP_CMP_EQ: ++ case SCMP_CMP_MASKED_EQ: ++ s_new->node_cnt += 2; ++ break; ++ default: ++ s_new->node_cnt += 3; ++ } + +- c_prev_hi = c_iter_hi; +- c_prev_lo = c_iter_lo; ++ /* keep pointers to this level */ ++ c_prev[0] = c_iter[0]; ++ c_prev[1] = c_iter[1]; ++ c_prev[2] = c_iter[2]; ++ op_prev = chain[iter].op; + } +- if (c_iter_lo != NULL) { +- /* set the leaf node */ +- if (!tf_flag) { +- c_iter_lo->act_f_flg = true; +- c_iter_lo->act_f = rule->action; +- c_iter_hi->act_f_flg = true; +- c_iter_hi->act_f = rule->action; +- } else { +- c_iter_lo->act_t_flg = true; +- c_iter_lo->act_t = rule->action; ++ if (c_iter[0] != NULL) { ++ /* set the actions on the last layer */ ++ switch (op_prev) { ++ case SCMP_CMP_GT: ++ case SCMP_CMP_GE: ++ c_iter[0]->act_t_flg = true; ++ c_iter[0]->act_t = rule->action; ++ c_iter[2]->act_t_flg = true; ++ c_iter[2]->act_t = rule->action; ++ break; ++ case SCMP_CMP_LE: ++ case SCMP_CMP_LT: ++ c_iter[1]->act_f_flg = true; ++ c_iter[1]->act_f = rule->action; ++ c_iter[2]->act_f_flg = true; ++ c_iter[2]->act_f = rule->action; ++ break; ++ case SCMP_CMP_EQ: ++ case SCMP_CMP_MASKED_EQ: ++ c_iter[1]->act_t_flg = true; ++ c_iter[1]->act_t = rule->action; ++ break; ++ case SCMP_CMP_NE: ++ c_iter[0]->act_f_flg = true; ++ c_iter[0]->act_f = rule->action; ++ c_iter[1]->act_f_flg = true; ++ c_iter[1]->act_f = rule->action; ++ break; ++ default: ++ /* we should never get here */ ++ goto gen_64_failure; + } + } else + s_new->action = rule->action; +@@ -1561,11 +1890,14 @@ static struct db_sys_list *_db_rule_gen_32(const struct arch_def *arch, + if (c_iter == NULL) + goto gen_32_failure; + c_iter->arg = chain[iter].arg; ++ c_iter->arg_h_flg = false; + c_iter->arg_offset = arch_arg_offset(arch, c_iter->arg); + c_iter->op = chain[iter].op; ++ c_iter->op_orig = chain[iter].op; + /* implicitly strips off the upper 32 bit */ + c_iter->mask = chain[iter].mask; + c_iter->datum = chain[iter].datum; ++ c_iter->datum_full = chain[iter].datum; + + /* link in the new node and update the chain */ + if (c_prev != NULL) { +diff --git a/src/db.h b/src/db.h +index 1783ab0..8a64623 100644 +--- a/src/db.h ++++ b/src/db.h +@@ -52,14 +52,18 @@ struct db_api_rule_list { + struct db_arg_chain_tree { + /* argument number (a0 = 0, a1 = 1, etc.) */ + unsigned int arg; ++ /* true to indicate this is the high 32-bit word of a 64-bit value */ ++ bool arg_h_flg; + /* argument bpf offset */ + unsigned int arg_offset; + + /* comparison operator */ + enum scmp_compare op; ++ enum scmp_compare op_orig; + /* syscall argument value */ + uint32_t mask; + uint32_t datum; ++ scmp_datum_t datum_full; + + /* actions */ + bool act_t_flg; \ No newline at end of file diff --git a/tasks/csa159/pair_137674/post_functions.txt b/tasks/csa159/pair_137674/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..446324eedeb1c39c54b9d07b4e09498ae5e84702 --- /dev/null +++ b/tasks/csa159/pair_137674/post_functions.txt @@ -0,0 +1,319 @@ +### File: src/db.c +```c +static unsigned int __db_chain_arg_priority(const struct db_arg_chain_tree *a) +{ + return (a->arg << 1) + (a->arg_h_flg ? 1 : 0); +} + +static unsigned int __db_chain_op_priority(enum scmp_compare op) +{ + /* the distinction between LT/LT and GT/GE is mostly to make the + * ordering as repeatable as possible regardless of the order in which + * the rules are added */ + switch (op) { + case SCMP_CMP_MASKED_EQ: + case SCMP_CMP_EQ: + case SCMP_CMP_NE: + return 3; + case SCMP_CMP_LE: + case SCMP_CMP_LT: + return 2; + case SCMP_CMP_GE: + case SCMP_CMP_GT: + return 1; + default: + return 0; + } +} + +static bool _db_chain_lt(const struct db_arg_chain_tree *a, + const struct db_arg_chain_tree *b) +{ + unsigned int a_arg, b_arg; + unsigned int a_op, b_op; + + a_arg = __db_chain_arg_priority(a); + b_arg = __db_chain_arg_priority(b); + if (a_arg < b_arg) + return true; + else if (a_arg > b_arg) + return false; + + a_op = __db_chain_op_priority(a->op_orig); + b_op = __db_chain_op_priority(b->op_orig); + if (a_op < b_op) + return true; + else if (a_op > b_op) + return false; + + /* NOTE: at this point the arg and op priorities are equal */ + + switch (a->op_orig) { + case SCMP_CMP_LE: + case SCMP_CMP_LT: + /* in order to ensure proper ordering for LT/LE comparisons we + * need to invert the argument value so smaller values come + * first */ + if (a->datum > b->datum) + return true; + break; + default: + if (a->datum < b->datum) + return true; + break; + } + + return false; +} + +static bool _db_chain_eq(const struct db_arg_chain_tree *a, + const struct db_arg_chain_tree *b) +{ + unsigned int a_arg, b_arg; + + a_arg = __db_chain_arg_priority(a); + b_arg = __db_chain_arg_priority(b); + + return ((a_arg == b_arg) && (a->op == b->op) && + (a->datum == b->datum) && (a->mask == b->mask)); +} + +static bool _db_chain_leaf(const struct db_arg_chain_tree *iter) +{ + return (iter->nxt_t == NULL && iter->nxt_f == NULL); +} + +static bool _db_chain_zombie(const struct db_arg_chain_tree *iter) +{ + return (_db_chain_leaf(iter) && + !(iter->act_t_flg) && !(iter->act_f_flg)); +} + +static struct db_arg_chain_tree *_db_node_get(struct db_arg_chain_tree *node) +{ + if (node != NULL) + node->refcnt++; + return node; +} + +static unsigned int _db_level_clean(struct db_arg_chain_tree *node) +{ + int cnt = 0; + unsigned int links; + struct db_arg_chain_tree *n = node; + struct db_arg_chain_tree *start; + + while (n->lvl_prv) + n = n->lvl_prv; + start = n; + + while (n != NULL) { + links = 0; + if (n->lvl_prv) + links++; + if (n->lvl_nxt) + links++; + + if (n->refcnt > links) + return cnt; + + n = n->lvl_nxt; + } + + n = start; + while (n != NULL) + cnt += _db_node_put(&n); + + return cnt; +} + +static unsigned int _db_node_put(struct db_arg_chain_tree **node) +{ + unsigned int cnt = 0; + struct db_arg_chain_tree *n = *node; + struct db_arg_chain_tree *lvl_p, *lvl_n, *nxt_t, *nxt_f; + + if (n == NULL) + return 0; + + if (--(n->refcnt) == 0) { + lvl_p = n->lvl_prv; + lvl_n = n->lvl_nxt; + nxt_t = n->nxt_t; + nxt_f = n->nxt_f; + + /* split the current level */ + /* NOTE: we still hold a ref for both lvl_p and lvl_n */ + if (lvl_p) + lvl_p->lvl_nxt = NULL; + if (lvl_n) + lvl_n->lvl_prv = NULL; + + /* drop refcnts on the current level */ + if (lvl_p) + cnt += _db_node_put(&lvl_p); + if (lvl_n) + cnt += _db_node_put(&lvl_n); + + /* re-link current level if it still exists */ + if (lvl_p) + lvl_p->lvl_nxt = _db_node_get(lvl_n); + if (lvl_n) + lvl_n->lvl_prv = _db_node_get(lvl_p); + + /* update caller's pointer */ + if (lvl_p) + *node = lvl_p; + else if (lvl_n) + *node = lvl_n; + else + *node = NULL; + + /* drop the next level(s) */ + cnt += _db_tree_put(&nxt_t); + cnt += _db_tree_put(&nxt_f); + + /* cleanup and accounting */ + free(n); + cnt++; + } + + return cnt; +} + +static int _db_tree_prune(struct db_arg_chain_tree **existing, + struct db_arg_chain_tree *new, + struct db_iter_state *state) +{ + int cnt = 0; + struct db_iter_state state_nxt; + struct db_iter_state state_new = *state; + struct db_arg_chain_tree *x_iter_next; + struct db_arg_chain_tree *x_iter = *existing; + struct db_arg_chain_tree *n_iter = new; + + /* check if either tree is finished */ + if (n_iter == NULL || x_iter == NULL) + goto prune_return; + + /* bail out if we have a broken match */ + if ((state->flags & _DB_IST_M_MATCHSET) == _DB_IST_MATCH_ONCE) + goto prune_return; + + /* get to the start of the existing level */ + while (x_iter->lvl_prv) + x_iter = x_iter->lvl_prv; + + /* NOTE: a few comments on the code below ... + * 1) we need to take a reference before we go down a level in case + * we end up dropping the sub-tree (see the _db_node_get() calls) + * 2) since the new tree really only has one branch, we can only ever + * match on one branch in the existing tree, if we "hit" then we + * can bail on the other branches */ + + do { + /* store this now in case we remove x_iter */ + x_iter_next = x_iter->lvl_nxt; + + /* compare the two nodes */ + if (_db_chain_eq(x_iter, n_iter)) { + /* we have a match */ + state_new.flags |= _DB_IST_M_MATCHSET; + + /* check if either tree is finished */ + if (_db_chain_leaf(n_iter)) + state_new.flags |= _DB_IST_N_FINISHED; + if (_db_chain_leaf(x_iter)) + state_new.flags |= _DB_IST_X_FINISHED; + + /* don't remove nodes if we have more actions/levels */ + if ((x_iter->act_t_flg || x_iter->nxt_t) && + !(n_iter->act_t_flg || n_iter->nxt_t)) + goto prune_return; + if ((x_iter->act_f_flg || x_iter->nxt_f) && + !(n_iter->act_f_flg || n_iter->nxt_f)) + goto prune_return; + + /* if finished, compare actions */ + if ((state_new.flags & _DB_IST_N_FINISHED) && + (state_new.flags & _DB_IST_X_FINISHED)) { + if (n_iter->act_t_flg != x_iter->act_t_flg) + goto prune_return; + if (n_iter->act_t != x_iter->act_t) + goto prune_return; + + if (n_iter->act_f_flg != x_iter->act_f_flg) + goto prune_return; + if (n_iter->act_f != x_iter->act_f) + goto prune_return; + } + + /* check next level */ + if (n_iter->nxt_t) { + _db_node_get(x_iter); + state_nxt = *state; + state_nxt.flags |= _DB_IST_M_MATCHSET; + cnt += _db_tree_prune(&x_iter->nxt_t, + n_iter->nxt_t, + &state_nxt); + cnt += _db_node_put(&x_iter); + if (state_nxt.flags & _DB_IST_MATCH) { + state_new.flags |= state_nxt.flags; + /* don't return yet, we need to check + * the current node */ + } + if (x_iter == NULL) + goto prune_next_node; + } + if (n_iter->nxt_f) { + _db_node_get(x_iter); + state_nxt = *state; + state_nxt.flags |= _DB_IST_M_MATCHSET; + cnt += _db_tree_prune(&x_iter->nxt_f, + n_iter->nxt_f, + &state_nxt); + cnt += _db_node_put(&x_iter); + if (state_nxt.flags & _DB_IST_MATCH) { + state_new.flags |= state_nxt.flags; + /* don't return yet, we need to check + * the current node */ + } + if (x_iter == NULL) + goto prune_next_node; + } + + /* remove the node? */ + if (!_db_tree_act_check(x_iter, state_new.action) && + (state_new.flags & _DB_IST_MATCH) && + (state_new.flags & _DB_IST_N_FINISHED) && + (state_new.flags & _DB_IST_X_PREFIX)) { + /* yes - the new tree is "shorter" */ + cnt += _db_tree_remove(&state->sx->chains, + x_iter); + if (state->sx->chains == NULL) + goto prune_return; + } else if (!_db_tree_act_check(x_iter, state_new.action) + && (state_new.flags & _DB_IST_MATCH) && + (state_new.flags & _DB_IST_X_FINISHED) && + (state_new.flags & _DB_IST_N_PREFIX)) { + /* no - the new tree is "longer" */ + goto prune_return; + } + } else if (_db_chain_lt(x_iter, n_iter)) { + /* bail if we have a prefix on the new tree */ + if (state->flags & _DB_IST_N_PREFIX) + goto prune_return; + + /* check the next level in the existing tree */ + if (x_iter->nxt_t) { + _db_node_get(x_iter); + state_nxt = *state; + state_nxt.flags &= ~_DB_IST_MATCH; + state_nxt.flags |= _DB_IST_X_PREFIX; + cnt += _db_tree_prune(&x_iter->nxt_t, n_iter, + &state_nxt); + cnt += _db_node_put(&x_iter); + if (state_nxt.flags & _DB_IS + +// ... (18701 more chars) +``` diff --git a/tasks/csa159/pair_137674/pre_functions.txt b/tasks/csa159/pair_137674/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..129ef647359defe250212a6f47f88da4110de07e --- /dev/null +++ b/tasks/csa159/pair_137674/pre_functions.txt @@ -0,0 +1,342 @@ +### File: src/db.c +```c +static bool _db_chain_lt(const struct db_arg_chain_tree *a, + const struct db_arg_chain_tree *b) +{ + return ((a->arg < b->arg) || + ((a->arg == b->arg) && + ((a->op < b->op) || + ((a->op == b->op) && + ((a->mask < b->mask) || + ((a->mask == b->mask) && + (a->datum < b->datum))))))); +} + +static bool _db_chain_eq(const struct db_arg_chain_tree *a, + const struct db_arg_chain_tree *b) +{ + return ((a->arg == b->arg) && (a->op == b->op) && + (a->datum == b->datum) && (a->mask == b->mask)); +} + +static bool _db_chain_zombie(const struct db_arg_chain_tree *iter) +{ + return (_db_chain_leaf(iter) && + !(iter->act_t_flg) && !(iter->act_f_flg)); +} + +static unsigned int _db_tree_put(struct db_arg_chain_tree **tree) +{ + int cnt = 0; + struct db_arg_chain_tree *node, *prev, *next; + + if (tree == NULL || *tree == NULL) + return 0; + node = *tree; + + while (node->lvl_nxt != NULL) + node = node->lvl_nxt; + + while (node != NULL) { + prev = node->lvl_prv; + next = node->lvl_nxt; + + cnt += _db_tree_put(&node->nxt_t); + cnt += _db_tree_put(&node->nxt_f); + if (--(node->refcnt) == 0) { + /* remove the node from the current level */ + if (prev) + prev->lvl_nxt = next; + if (next) + next->lvl_prv = prev; + + /* reset the caller's pointer */ + if (prev != NULL) + *tree = prev; + else + *tree = next; + + /* cleanup and accounting */ + free(node); + cnt++; + } + + /* next */ + node = prev; + } + + return cnt; +} + +static unsigned int _db_node_put(struct db_arg_chain_tree **node) +{ + if ((*node)->refcnt == 1) + return _db_tree_put(node); + (*node)->refcnt--; + return 0; +} + +static struct db_arg_chain_tree *_db_node_get(struct db_arg_chain_tree *node) +{ + node->refcnt++; + return node; +} + +static struct db_arg_chain_tree *_db_tree_get(struct db_arg_chain_tree *tree) +{ + struct db_arg_chain_tree *iter; + + if (tree->nxt_t) { + iter = tree->nxt_t; + while (iter->lvl_prv != NULL) + iter = iter->lvl_prv; + do { + _db_tree_get(iter); + iter = iter->lvl_nxt; + } while (iter != NULL); + } + + if (tree->nxt_f) { + iter = tree->nxt_f; + while (iter->lvl_prv != NULL) + iter = iter->lvl_prv; + do { + _db_tree_get(iter); + iter = iter->lvl_nxt; + } while (iter != NULL); + } + + return _db_node_get(tree); +} + +static void _db_level_get(struct db_arg_chain_tree *node) +{ + struct db_arg_chain_tree *iter = node; + + while (iter->lvl_prv != NULL) + iter = iter->lvl_prv; + + while (iter) { + _db_tree_get(iter); + iter = iter->lvl_nxt; + } +} + +static unsigned int _db_tree_remove(struct db_arg_chain_tree **tree, + struct db_arg_chain_tree *node) +{ + int cnt = 0; + struct db_arg_chain_tree *c_iter; + + if (tree == NULL || *tree == NULL || node == NULL) + return 0; + + c_iter = *tree; + while (c_iter->lvl_prv != NULL) + c_iter = c_iter->lvl_prv; + + do { + /* current node? */ + if (c_iter == node) + goto remove; + + /* check the sub-trees */ + cnt += _db_tree_remove(&(c_iter->nxt_t), node); + cnt += _db_tree_remove(&(c_iter->nxt_f), node); + + /* check for empty/zombie nodes */ + if (_db_chain_zombie(c_iter)) + goto remove; + + /* next node on this level */ + c_iter = c_iter->lvl_nxt; + } while (c_iter != NULL && cnt == 0); + + return cnt; + +remove: + /* reset the tree pointer if needed */ + if (c_iter == *tree) { + if (c_iter->lvl_prv != NULL) + *tree = c_iter->lvl_prv; + else + *tree = c_iter->lvl_nxt; + } + + /* remove the node from the current level */ + if (c_iter->lvl_prv) + c_iter->lvl_prv->lvl_nxt = c_iter->lvl_nxt; + if (c_iter->lvl_nxt) + c_iter->lvl_nxt->lvl_prv = c_iter->lvl_prv; + c_iter->lvl_prv = NULL; + c_iter->lvl_nxt = NULL; + + /* free the node and any sub-trees */ + cnt += _db_tree_put(&c_iter); + + return cnt; +} + +static int _db_tree_add(struct db_arg_chain_tree **existing, + struct db_arg_chain_tree *new, + struct db_iter_state *state) +{ + int rc; + struct db_arg_chain_tree *x_iter = *existing; + struct db_arg_chain_tree *n_iter = new; + + /* TODO: when we add sub-trees to the current level (see the lt/gt + * branches below) we need to grab an extra reference for sub-trees at + * the current as the current level is visible to both the new and + * existing trees; at some point if would be nice if we didn't have to + * take this extra reference */ + + do { + if (_db_chain_eq(x_iter, n_iter)) { + if (n_iter->act_t_flg) { + if (!x_iter->act_t_flg) { + /* new node has a true action */ + + /* do the actions match? */ + rc = _db_tree_act_check(x_iter->nxt_t, + n_iter->act_t); + if (rc != 0) + return rc; + + /* update with the new action */ + rc = _db_tree_put(&x_iter->nxt_t); + x_iter->nxt_t = NULL; + x_iter->act_t = n_iter->act_t; + x_iter->act_t_flg = true; + state->sx->node_cnt -= rc; + } else if (n_iter->act_t != x_iter->act_t) + return -EEXIST; + } + if (n_iter->act_f_flg) { + if (!x_iter->act_f_flg) { + /* new node has a false action */ + + /* do the actions match? */ + rc = _db_tree_act_check(x_iter->nxt_f, + n_iter->act_f); + if (rc != 0) + return rc; + + /* update with the new action */ + rc = _db_tree_put(&x_iter->nxt_f); + x_iter->nxt_f = NULL; + x_iter->act_f = n_iter->act_f; + x_iter->act_f_flg = true; + state->sx->node_cnt -= rc; + } else if (n_iter->act_f != x_iter->act_f) + return -EEXIST; + } + + if (n_iter->nxt_t) { + if (x_iter->nxt_t) { + /* compare the next level */ + rc = _db_tree_add(&x_iter->nxt_t, + n_iter->nxt_t, + state); + if (rc != 0) + return rc; + } else if (!x_iter->act_t_flg) { + /* add a new sub-tree */ + x_iter->nxt_t = _db_tree_get(n_iter->nxt_t); + } else + /* done - existing tree is "shorter" */ + return 0; + } + if (n_iter->nxt_f) { + if (x_iter->nxt_f) { + /* compare the next level */ + rc = _db_tree_add(&x_iter->nxt_f, + n_iter->nxt_f, + state); + if (rc != 0) + return rc; + } else if (!x_iter->act_f_flg) { + /* add a new sub-tree */ + x_iter->nxt_f = _db_tree_get(n_iter->nxt_f); + } else + /* done - existing tree is "shorter" */ + return 0; + } + + return 0; + } else if (!_db_chain_lt(x_iter, n_iter)) { + /* try to move along the current level */ + if (x_iter->lvl_nxt == NULL) { + /* add to the end of this level */ + _db_level_get(x_iter); + _db_tree_get(n_iter); + n_iter->lvl_prv = x_iter; + x_iter->lvl_nxt = n_iter; + return 0; + } else + /* next */ + x_iter = x_iter->lvl_nxt; + } else { + /* add before the existing node on this level*/ + _db_level_get(x_iter); + _db_tree_get(n_iter); + if (x_iter->lvl_prv != NULL) + x_iter->lvl_prv->lvl_nxt = n_iter; + n_iter->lvl_prv = x_iter->lvl_prv; + n_iter->lvl_nxt = x_iter; + x_iter->lvl_prv = n_iter; + if (*existing == x_iter) + *existing = n_iter; + return 0; + } + } while (x_iter); + + return 0; +} + +static struct db_sys_list *_db_rule_gen_64(const struct arch_def *arch, + const struct db_api_rule_list *rule) +{ + unsigned int iter; + struct db_sys_list *s_new; + const struct db_api_arg *chain = rule->args; + struct db_arg_chain_tree *c_iter_hi = NULL, *c_iter_lo = NULL; + struct db_arg_chain_tree *c_prev_hi = NULL, *c_prev_lo = NULL; + bool tf_flag; + + s_new = zmalloc(sizeof(*s_new)); + if (s_new == NULL) + return NULL; + s_new->num = rule->syscall; + s_new->valid = true; + /* run through the argument chain */ + for (iter = 0; iter < ARG_COUNT_MAX; iter++) { + if (chain[iter].valid == 0) + continue; + + /* TODO: handle the case were either hi or lo isn't needed */ + + /* skip generating instruction which are no-ops */ + if (!_db_arg_cmp_need_hi(&chain[iter]) && + !_db_arg_cmp_need_lo(&chain[iter])) + continue; + + c_iter_hi = zmalloc(sizeof(*c_iter_hi)); + if (c_iter_hi == NULL) + goto gen_64_failure; + c_iter_lo = zmalloc(sizeof(*c_iter_lo)); + if (c_iter_lo == NULL) { + free(c_iter_hi); + goto gen_64_failure; + } + + /* link this level to the previous level */ + if (c_prev_lo != NULL) { + if (!tf_flag) { + c_prev_lo->nxt_f = _db_node_get(c_iter_hi); + c_prev_hi->nxt_f = _db_node_get(c_iter_hi); + } else + c + +// ... (3923 more chars) +``` diff --git a/tasks/csa159/pair_137674/task_prompt.md b/tasks/csa159/pair_137674/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_137674/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_137750/checker_template.cpp b/tasks/csa159/pair_137750/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_137750/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_137750/config.json b/tasks/csa159/pair_137750/config.json new file mode 100644 index 0000000000000000000000000000000000000000..08921f9243fb1b284cbf5f4622760f03a699b82f --- /dev/null +++ b/tasks/csa159/pair_137750/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "qemu_qemu", + "before_commit": "6b7d4c55586a849aa8313282d79432917eade3bf", + "after_commit": "11b128f4062dd7f89b14abc8877ff20d41b28be9", + "repo_path": "/workspace/repo/qemu/qemu", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/qemu_qemu/f4b11eee2f562c23b3efc33b96ba4542c9ca81aa/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/qemu_qemu/f4b11eee2f562c23b3efc33b96ba4542c9ca81aa/compile_commands.json", + "changed_files": [ + "block/qcow2.c" + ], + "commit_message": "qcow2: Fix NULL dereference in qcow2_open() error path (CVE-2014-0146)\n\nThe qcow2 code assumes that s->snapshots is non-NULL if s->nb_snapshots\n!= 0. By having the initialisation of both fields separated in\nqcow2_open(), any error occuring in between would cause the error path\nto dereference NULL in qcow2_free_snapshots() if the image had any\nsnapshots.\n\nSigned-off-by: Kevin Wolf \nReviewed-by: Max Reitz \nSigned-off-by: Stefan Hajnoczi ", + "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_137750/patch.diff b/tasks/csa159/pair_137750/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8f13b91a4fa0dbd7fbea6910dff0c9bd5cab8742 --- /dev/null +++ b/tasks/csa159/pair_137750/patch.diff @@ -0,0 +1,58 @@ +diff --git a/block/qcow2.c b/block/qcow2.c +index b64564d171..be48a27afa 100644 +--- a/block/qcow2.c ++++ b/block/qcow2.c +@@ -637,9 +637,6 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags, + goto fail; + } + +- s->snapshots_offset = header.snapshots_offset; +- s->nb_snapshots = header.nb_snapshots; +- + /* read the level 1 table */ + if (header.l1_size > 0x2000000) { + /* 32 MB L1 table is enough for 2 PB images at 64k cluster size +@@ -734,6 +731,10 @@ static int qcow2_open(BlockDriverState *bs, QDict *options, int flags, + bs->backing_file[len] = '\0'; + } + ++ /* Internal snapshots */ ++ s->snapshots_offset = header.snapshots_offset; ++ s->nb_snapshots = header.nb_snapshots; ++ + ret = qcow2_read_snapshots(bs); + if (ret < 0) { + error_setg_errno(errp, -ret, "Could not read snapshots"); +diff --git a/tests/qemu-iotests/080 b/tests/qemu-iotests/080 +index 56f890395c..59e7a441b3 100755 +--- a/tests/qemu-iotests/080 ++++ b/tests/qemu-iotests/080 +@@ -138,6 +138,13 @@ poke_file "$TEST_IMG" "$offset_l1_table_offset" "\x12\x34\x56\x78\x90\xab\xcd\xe + poke_file "$TEST_IMG" "$offset_l1_size" "\x00\x00\x00\x01" + { $QEMU_IO -c "read 0 512" $TEST_IMG; } 2>&1 | _filter_qemu_io | _filter_testdir + ++echo ++echo "== Invalid L1 table (with internal snapshot in the image) ==" ++_make_test_img 64M ++{ $QEMU_IMG snapshot -c foo $TEST_IMG; } 2>&1 | _filter_qemu_io | _filter_testdir ++poke_file "$TEST_IMG" "$offset_l1_size" "\x00\x00\x00\x00" ++_img_info ++ + echo + echo "== Invalid backing file size ==" + _make_test_img 64M +diff --git a/tests/qemu-iotests/080.out b/tests/qemu-iotests/080.out +index 303d6c3465..4d84fbf64b 100644 +--- a/tests/qemu-iotests/080.out ++++ b/tests/qemu-iotests/080.out +@@ -59,6 +59,10 @@ no file open, try 'help open' + qemu-io: can't open device TEST_DIR/t.qcow2: Invalid L1 table offset + no file open, try 'help open' + ++== Invalid L1 table (with internal snapshot in the image) == ++Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 ++qemu-img: Could not open 'TEST_DIR/t.IMGFMT': L1 table is too small ++ + == Invalid backing file size == + Formatting 'TEST_DIR/t.IMGFMT', fmt=IMGFMT size=67108864 + qemu-io: can't open device TEST_DIR/t.qcow2: Backing file name too long \ No newline at end of file diff --git a/tasks/csa159/pair_137750/post_functions.txt b/tasks/csa159/pair_137750/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..05a7f8cbb3c8ca21bbc7b3c68d772a332c4c779d --- /dev/null +++ b/tasks/csa159/pair_137750/post_functions.txt @@ -0,0 +1,242 @@ +### File: block/qcow2.c +```c +static int qcow2_open(BlockDriverState *bs, QDict *options, int flags, + Error **errp) +{ + BDRVQcowState *s = bs->opaque; + unsigned int len, i; + int ret = 0; + QCowHeader header; + QemuOpts *opts; + Error *local_err = NULL; + uint64_t ext_end; + uint64_t l1_vm_state_index; + const char *opt_overlap_check; + int overlap_check_template = 0; + + ret = bdrv_pread(bs->file, 0, &header, sizeof(header)); + if (ret < 0) { + error_setg_errno(errp, -ret, "Could not read qcow2 header"); + goto fail; + } + be32_to_cpus(&header.magic); + be32_to_cpus(&header.version); + be64_to_cpus(&header.backing_file_offset); + be32_to_cpus(&header.backing_file_size); + be64_to_cpus(&header.size); + be32_to_cpus(&header.cluster_bits); + be32_to_cpus(&header.crypt_method); + be64_to_cpus(&header.l1_table_offset); + be32_to_cpus(&header.l1_size); + be64_to_cpus(&header.refcount_table_offset); + be32_to_cpus(&header.refcount_table_clusters); + be64_to_cpus(&header.snapshots_offset); + be32_to_cpus(&header.nb_snapshots); + + if (header.magic != QCOW_MAGIC) { + error_setg(errp, "Image is not in qcow2 format"); + ret = -EINVAL; + goto fail; + } + if (header.version < 2 || header.version > 3) { + report_unsupported(bs, errp, "QCOW version %d", header.version); + ret = -ENOTSUP; + goto fail; + } + + s->qcow_version = header.version; + + /* Initialise cluster size */ + if (header.cluster_bits < MIN_CLUSTER_BITS || + header.cluster_bits > MAX_CLUSTER_BITS) { + error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits); + ret = -EINVAL; + goto fail; + } + + s->cluster_bits = header.cluster_bits; + s->cluster_size = 1 << s->cluster_bits; + s->cluster_sectors = 1 << (s->cluster_bits - 9); + + /* Initialise version 3 header fields */ + if (header.version == 2) { + header.incompatible_features = 0; + header.compatible_features = 0; + header.autoclear_features = 0; + header.refcount_order = 4; + header.header_length = 72; + } else { + be64_to_cpus(&header.incompatible_features); + be64_to_cpus(&header.compatible_features); + be64_to_cpus(&header.autoclear_features); + be32_to_cpus(&header.refcount_order); + be32_to_cpus(&header.header_length); + + if (header.header_length < 104) { + error_setg(errp, "qcow2 header too short"); + ret = -EINVAL; + goto fail; + } + } + + if (header.header_length > s->cluster_size) { + error_setg(errp, "qcow2 header exceeds cluster size"); + ret = -EINVAL; + goto fail; + } + + if (header.header_length > sizeof(header)) { + s->unknown_header_fields_size = header.header_length - sizeof(header); + s->unknown_header_fields = g_malloc(s->unknown_header_fields_size); + ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields, + s->unknown_header_fields_size); + if (ret < 0) { + error_setg_errno(errp, -ret, "Could not read unknown qcow2 header " + "fields"); + goto fail; + } + } + + if (header.backing_file_offset > s->cluster_size) { + error_setg(errp, "Invalid backing file offset"); + ret = -EINVAL; + goto fail; + } + + if (header.backing_file_offset) { + ext_end = header.backing_file_offset; + } else { + ext_end = 1 << header.cluster_bits; + } + + /* Handle feature bits */ + s->incompatible_features = header.incompatible_features; + s->compatible_features = header.compatible_features; + s->autoclear_features = header.autoclear_features; + + if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) { + void *feature_table = NULL; + qcow2_read_extensions(bs, header.header_length, ext_end, + &feature_table, NULL); + report_unsupported_feature(bs, errp, feature_table, + s->incompatible_features & + ~QCOW2_INCOMPAT_MASK); + ret = -ENOTSUP; + g_free(feature_table); + goto fail; + } + + if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) { + /* Corrupt images may not be written to unless they are being repaired + */ + if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) { + error_setg(errp, "qcow2: Image is corrupt; cannot be opened " + "read/write"); + ret = -EACCES; + goto fail; + } + } + + /* Check support for various header values */ + if (header.refcount_order != 4) { + report_unsupported(bs, errp, "%d bit reference counts", + 1 << header.refcount_order); + ret = -ENOTSUP; + goto fail; + } + s->refcount_order = header.refcount_order; + + if (header.crypt_method > QCOW_CRYPT_AES) { + error_setg(errp, "Unsupported encryption method: %i", + header.crypt_method); + ret = -EINVAL; + goto fail; + } + s->crypt_method_header = header.crypt_method; + if (s->crypt_method_header) { + bs->encrypted = 1; + } + + s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */ + s->l2_size = 1 << s->l2_bits; + bs->total_sectors = header.size / 512; + s->csize_shift = (62 - (s->cluster_bits - 8)); + s->csize_mask = (1 << (s->cluster_bits - 8)) - 1; + s->cluster_offset_mask = (1LL << s->csize_shift) - 1; + + s->refcount_table_offset = header.refcount_table_offset; + s->refcount_table_size = + header.refcount_table_clusters << (s->cluster_bits - 3); + + if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) { + error_setg(errp, "Reference count table too large"); + ret = -EINVAL; + goto fail; + } + + ret = validate_table_offset(bs, s->refcount_table_offset, + s->refcount_table_size, sizeof(uint64_t)); + if (ret < 0) { + error_setg(errp, "Invalid reference count table offset"); + goto fail; + } + + /* Snapshot table offset/length */ + if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) { + error_setg(errp, "Too many snapshots"); + ret = -EINVAL; + goto fail; + } + + ret = validate_table_offset(bs, header.snapshots_offset, + header.nb_snapshots, + sizeof(QCowSnapshotHeader)); + if (ret < 0) { + error_setg(errp, "Invalid snapshot table offset"); + goto fail; + } + + /* read the level 1 table */ + if (header.l1_size > 0x2000000) { + /* 32 MB L1 table is enough for 2 PB images at 64k cluster size + * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */ + error_setg(errp, "Active L1 table too large"); + ret = -EFBIG; + goto fail; + } + s->l1_size = header.l1_size; + + l1_vm_state_index = size_to_l1(s, header.size); + if (l1_vm_state_index > INT_MAX) { + error_setg(errp, "Image is too big"); + ret = -EFBIG; + goto fail; + } + s->l1_vm_state_index = l1_vm_state_index; + + /* the L1 table must contain at least enough entries to put + header.size bytes */ + if (s->l1_size < s->l1_vm_state_index) { + error_setg(errp, "L1 table is too small"); + ret = -EINVAL; + goto fail; + } + + ret = validate_table_offset(bs, header.l1_table_offset, + header.l1_size, sizeof(uint64_t)); + if (ret < 0) { + error_setg(errp, "Invalid L1 table offset"); + goto fail; + } + s->l1_table_offset = header.l1_table_offset; + + + if (s->l1_size > 0) { + s->l1_table = g_malloc0( + align_offset(s->l1_size * sizeof(uint64_t), 512)); + ret = bdrv_pread(bs->file, s->l1_table_offset, s->l1_table, + s->l1_size * sizeof(uint64_t)); + if (r + +// ... (5867 more chars) +``` diff --git a/tasks/csa159/pair_137750/pre_functions.txt b/tasks/csa159/pair_137750/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..b34fe549bcebd1fc21666484031011912f9cff53 --- /dev/null +++ b/tasks/csa159/pair_137750/pre_functions.txt @@ -0,0 +1,243 @@ +### File: block/qcow2.c +```c +static int qcow2_open(BlockDriverState *bs, QDict *options, int flags, + Error **errp) +{ + BDRVQcowState *s = bs->opaque; + unsigned int len, i; + int ret = 0; + QCowHeader header; + QemuOpts *opts; + Error *local_err = NULL; + uint64_t ext_end; + uint64_t l1_vm_state_index; + const char *opt_overlap_check; + int overlap_check_template = 0; + + ret = bdrv_pread(bs->file, 0, &header, sizeof(header)); + if (ret < 0) { + error_setg_errno(errp, -ret, "Could not read qcow2 header"); + goto fail; + } + be32_to_cpus(&header.magic); + be32_to_cpus(&header.version); + be64_to_cpus(&header.backing_file_offset); + be32_to_cpus(&header.backing_file_size); + be64_to_cpus(&header.size); + be32_to_cpus(&header.cluster_bits); + be32_to_cpus(&header.crypt_method); + be64_to_cpus(&header.l1_table_offset); + be32_to_cpus(&header.l1_size); + be64_to_cpus(&header.refcount_table_offset); + be32_to_cpus(&header.refcount_table_clusters); + be64_to_cpus(&header.snapshots_offset); + be32_to_cpus(&header.nb_snapshots); + + if (header.magic != QCOW_MAGIC) { + error_setg(errp, "Image is not in qcow2 format"); + ret = -EINVAL; + goto fail; + } + if (header.version < 2 || header.version > 3) { + report_unsupported(bs, errp, "QCOW version %d", header.version); + ret = -ENOTSUP; + goto fail; + } + + s->qcow_version = header.version; + + /* Initialise cluster size */ + if (header.cluster_bits < MIN_CLUSTER_BITS || + header.cluster_bits > MAX_CLUSTER_BITS) { + error_setg(errp, "Unsupported cluster size: 2^%i", header.cluster_bits); + ret = -EINVAL; + goto fail; + } + + s->cluster_bits = header.cluster_bits; + s->cluster_size = 1 << s->cluster_bits; + s->cluster_sectors = 1 << (s->cluster_bits - 9); + + /* Initialise version 3 header fields */ + if (header.version == 2) { + header.incompatible_features = 0; + header.compatible_features = 0; + header.autoclear_features = 0; + header.refcount_order = 4; + header.header_length = 72; + } else { + be64_to_cpus(&header.incompatible_features); + be64_to_cpus(&header.compatible_features); + be64_to_cpus(&header.autoclear_features); + be32_to_cpus(&header.refcount_order); + be32_to_cpus(&header.header_length); + + if (header.header_length < 104) { + error_setg(errp, "qcow2 header too short"); + ret = -EINVAL; + goto fail; + } + } + + if (header.header_length > s->cluster_size) { + error_setg(errp, "qcow2 header exceeds cluster size"); + ret = -EINVAL; + goto fail; + } + + if (header.header_length > sizeof(header)) { + s->unknown_header_fields_size = header.header_length - sizeof(header); + s->unknown_header_fields = g_malloc(s->unknown_header_fields_size); + ret = bdrv_pread(bs->file, sizeof(header), s->unknown_header_fields, + s->unknown_header_fields_size); + if (ret < 0) { + error_setg_errno(errp, -ret, "Could not read unknown qcow2 header " + "fields"); + goto fail; + } + } + + if (header.backing_file_offset > s->cluster_size) { + error_setg(errp, "Invalid backing file offset"); + ret = -EINVAL; + goto fail; + } + + if (header.backing_file_offset) { + ext_end = header.backing_file_offset; + } else { + ext_end = 1 << header.cluster_bits; + } + + /* Handle feature bits */ + s->incompatible_features = header.incompatible_features; + s->compatible_features = header.compatible_features; + s->autoclear_features = header.autoclear_features; + + if (s->incompatible_features & ~QCOW2_INCOMPAT_MASK) { + void *feature_table = NULL; + qcow2_read_extensions(bs, header.header_length, ext_end, + &feature_table, NULL); + report_unsupported_feature(bs, errp, feature_table, + s->incompatible_features & + ~QCOW2_INCOMPAT_MASK); + ret = -ENOTSUP; + g_free(feature_table); + goto fail; + } + + if (s->incompatible_features & QCOW2_INCOMPAT_CORRUPT) { + /* Corrupt images may not be written to unless they are being repaired + */ + if ((flags & BDRV_O_RDWR) && !(flags & BDRV_O_CHECK)) { + error_setg(errp, "qcow2: Image is corrupt; cannot be opened " + "read/write"); + ret = -EACCES; + goto fail; + } + } + + /* Check support for various header values */ + if (header.refcount_order != 4) { + report_unsupported(bs, errp, "%d bit reference counts", + 1 << header.refcount_order); + ret = -ENOTSUP; + goto fail; + } + s->refcount_order = header.refcount_order; + + if (header.crypt_method > QCOW_CRYPT_AES) { + error_setg(errp, "Unsupported encryption method: %i", + header.crypt_method); + ret = -EINVAL; + goto fail; + } + s->crypt_method_header = header.crypt_method; + if (s->crypt_method_header) { + bs->encrypted = 1; + } + + s->l2_bits = s->cluster_bits - 3; /* L2 is always one cluster */ + s->l2_size = 1 << s->l2_bits; + bs->total_sectors = header.size / 512; + s->csize_shift = (62 - (s->cluster_bits - 8)); + s->csize_mask = (1 << (s->cluster_bits - 8)) - 1; + s->cluster_offset_mask = (1LL << s->csize_shift) - 1; + + s->refcount_table_offset = header.refcount_table_offset; + s->refcount_table_size = + header.refcount_table_clusters << (s->cluster_bits - 3); + + if (header.refcount_table_clusters > qcow2_max_refcount_clusters(s)) { + error_setg(errp, "Reference count table too large"); + ret = -EINVAL; + goto fail; + } + + ret = validate_table_offset(bs, s->refcount_table_offset, + s->refcount_table_size, sizeof(uint64_t)); + if (ret < 0) { + error_setg(errp, "Invalid reference count table offset"); + goto fail; + } + + /* Snapshot table offset/length */ + if (header.nb_snapshots > QCOW_MAX_SNAPSHOTS) { + error_setg(errp, "Too many snapshots"); + ret = -EINVAL; + goto fail; + } + + ret = validate_table_offset(bs, header.snapshots_offset, + header.nb_snapshots, + sizeof(QCowSnapshotHeader)); + if (ret < 0) { + error_setg(errp, "Invalid snapshot table offset"); + goto fail; + } + + s->snapshots_offset = header.snapshots_offset; + s->nb_snapshots = header.nb_snapshots; + + /* read the level 1 table */ + if (header.l1_size > 0x2000000) { + /* 32 MB L1 table is enough for 2 PB images at 64k cluster size + * (128 GB for 512 byte clusters, 2 EB for 2 MB clusters) */ + error_setg(errp, "Active L1 table too large"); + ret = -EFBIG; + goto fail; + } + s->l1_size = header.l1_size; + + l1_vm_state_index = size_to_l1(s, header.size); + if (l1_vm_state_index > INT_MAX) { + error_setg(errp, "Image is too big"); + ret = -EFBIG; + goto fail; + } + s->l1_vm_state_index = l1_vm_state_index; + + /* the L1 table must contain at least enough entries to put + header.size bytes */ + if (s->l1_size < s->l1_vm_state_index) { + error_setg(errp, "L1 table is too small"); + ret = -EINVAL; + goto fail; + } + + ret = validate_table_offset(bs, header.l1_table_offset, + header.l1_size, sizeof(uint64_t)); + if (ret < 0) { + error_setg(errp, "Invalid L1 table offset"); + goto fail; + } + s->l1_table_offset = header.l1_table_offset; + + + if (s->l1_size > 0) { + s->l1_table = g_malloc0( + align_offset(s->l1_size * sizeof(uint64_t), 512)); + ret = bdrv_pread(bs->file, s->l1_ta + +// ... (5838 more chars) +``` diff --git a/tasks/csa159/pair_137750/task_prompt.md b/tasks/csa159/pair_137750/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..d93ef76d92bd59953357f6f9adf4a5384152cc82 --- /dev/null +++ b/tasks/csa159/pair_137750/task_prompt.md @@ -0,0 +1,384 @@ +# 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 passed differential validation but failed semantic_mechanism because it recognized a heuristic superset of the defect rather than proving the cross-procedure NULL traversal. +- State keyed only by FieldDecl could not distinguish separate instances of the owning object, allowing a count commit, acquisition, or release on one instance to affect another. +- Count/pointer pairing and acquire/release classification were inferred from names; this did not prove that an acquire writes the pointer or that a release reads or indexes it using the count. +- Any matching non-release call was treated as a successful acquisition before its effects or return path were known, so failed acquisitions could incorrectly discharge the unsafe state. +- The pointer's actual NULL or uninitialized state and the cleanup callee's count-controlled dereference were not established. +- Assigning a provable zero did not clear an older pending fact, and wrappers or uninlined cleanup paths could be missed. + +### Preserve from prior rollouts + +- Preserve successful compilation, 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 + +- Establish a feasible path where a possibly nonzero resource count is stored in a specific long-lived object while the paired pointer region for that same object remains NULL or uninitialized. +- Establish control-flow reachability from that inconsistent state through an intervening validation failure to cleanup, without an operation that restores the count/pointer invariant. +- Analyze or summarize the cleanup callee to prove that it uses the same object's count as a traversal bound and dereferences or indexes the paired pointer. +- Propagate object identity and field effects across caller/callee argument mappings, including the BlockDriverState-to-opaque-state relationship, rather than matching declarations globally. +- Treat acquisition as safe only on paths whose callee effects establish the pointer or otherwise restore the invariant; preserve the unsafe fact on failing or unknown-result paths. +- Show why the patched ordering is clean: no validation exit reaches cleanup after the count commit but before the acquisition operation and its relevant effects. + +### Implementation constraints + +- Use CSA ProgramState plus region-based identity, with facts keyed by the owning base MemRegion and the relevant count and pointer fields; do not key the condition solely by FieldDecl. +- Observe field stores with a region-aware callback such as check::Bind, or an equivalent callback that resolves the concrete base and field regions; zero stores and pointer resets must update or clear prior facts correctly. +- Use call callbacks and interprocedural callee analysis or explicit semantic summaries to propagate argument aliases, pointer writes, return-sensitive acquisition effects, and cleanup traversal behavior. +- Derive count/pointer relationships from structural data use, including a cleanup loop or traversal bounded by the count and indexing/dereferencing the pointer, rather than relying only on spelling conventions. +- Model branches and return constraints so the diagnostic exists only on a feasible error path carrying a nonzero count and a NULL or uninitialized paired pointer to the sink. +- Emit the report at the reachable cleanup call or proven dereference associated with the inconsistent object, with a path note identifying the earlier count commit and the absence of a restoring acquisition. +- Keep scope project-general and independent of changed line numbers, labels, local variable names, commit identifiers, exact patch adjacency, and hard-coded qcow2 function or field lists. + +### Validation checklist + +- Compile the fresh checker against the target Clang Static Analyzer API and verify checker registration and loading. +- Scan the vulnerable source and require a diagnostic in block/qcow2.c::qcow2_open on the path where an internal snapshot count is present, the L1 table check fails, and cleanup traverses the snapshot pointer. +- Scan the patched source and require zero corresponding diagnostics after the count assignment is moved immediately before snapshot acquisition. +- Verify the report is attached to the relevant cleanup call or proven dereference and that the path explanation links it to the count commit, rather than merely reporting a distant assignment. +- Exercise a provably zero count and require no report, including when a prior nonzero fact could otherwise remain stale. +- Exercise successful and failed acquisition paths separately; clear the hazard only where callee effects prove the invariant restored. +- Exercise multiple instances and unrelated count/pointer resources to confirm that facts do not cross object boundaries and unrelated cleanup calls remain clean. +- Re-run before/after code verification, differential and sparsity checks, objective gate G6, and refinement; retain one relevant vulnerable-only warning and no unrelated disappeared warnings. + +### Avoid and forbidden regressions + +- Do not use syntax-only assignment ordering, source-location spans, or CFG adjacency as a substitute for proving that cleanup is reachable with the inconsistent state. +- Do not classify acquisition or release solely from callee-name substrings or generic verbs such as read, free, close, or cleanup. +- Do not assume that calling an acquisition-looking routine initializes the pointer before checking its body effects and return-dependent paths. +- Do not assume a release dereferences the pointer without analyzing or summarizing its count-controlled traversal. +- Do not merge resource state across objects that share the same record fields. +- Do not rely on analyzer inlining happening opportunistically; provide explicit cross-procedure propagation or summaries where needed. +- Do not add special cases for qcow2_open, qcow2_read_snapshots, qcow2_free_snapshots, snapshots, fail labels, test 080, or patch line numbers. diff --git a/tasks/csa159/pair_137751/checker_template.cpp b/tasks/csa159/pair_137751/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_137751/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_137751/config.json b/tasks/csa159/pair_137751/config.json new file mode 100644 index 0000000000000000000000000000000000000000..db121de14d0dc70fa7ff82a6e56129da18cf3724 --- /dev/null +++ b/tasks/csa159/pair_137751/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "qemu_qemu", + "before_commit": "6bf7463615752934d7221e5be9820d9da45ab2de", + "after_commit": "87ad860c622cc8f8916b5232bd8728c08f938fce", + "repo_path": "/workspace/repo/qemu/qemu", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/qemu_qemu/6598f0cdad6acc6674c4f060fa46e537228c2c47/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/qemu_qemu/6598f0cdad6acc6674c4f060fa46e537228c2c47/compile_commands.json", + "changed_files": [ + "hw/block/nvme.c" + ], + "commit_message": "nvme: fix out-of-bounds access to the CMB\n\nBecause the CMB BAR has a min_access_size of 2, if you read the last\nbyte it will try to memcpy *2* bytes from n->cmbuf, causing an off-by-one\nerror. This is CVE-2018-16847.\n\nAnother way to fix this might be to register the CMB as a RAM memory\nregion, which would also be more efficient. However, that might be a\nchange for big-endian machines; I didn't think this through and I don't\nknow how real hardware works. Add a basic testcase for the CMB in case\nsomebody does this change later on.\n\nCc: Keith Busch \nCc: qemu-block@nongnu.org\nReported-by: Li Qiang \nReviewed-by: Li Qiang \nTested-by: Li Qiang \nSigned-off-by: Paolo Bonzini \nReviewed-by: Philippe Mathieu-Daudé \nTested-by: Philippe Mathieu-Daudé \nSigned-off-by: Kevin Wolf ", + "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_137751/patch.diff b/tasks/csa159/pair_137751/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..97614e9b53f72238b84901e5956f5305f1ec4342 --- /dev/null +++ b/tasks/csa159/pair_137751/patch.diff @@ -0,0 +1,114 @@ +diff --git a/hw/block/nvme.c b/hw/block/nvme.c +index 28d284346d..8c35cab2b4 100644 +--- a/hw/block/nvme.c ++++ b/hw/block/nvme.c +@@ -1201,7 +1201,7 @@ static const MemoryRegionOps nvme_cmb_ops = { + .write = nvme_cmb_write, + .endianness = DEVICE_LITTLE_ENDIAN, + .impl = { +- .min_access_size = 2, ++ .min_access_size = 1, + .max_access_size = 8, + }, + }; +diff --git a/tests/Makefile.include b/tests/Makefile.include +index 613242bc6e..fb0b449c02 100644 +--- a/tests/Makefile.include ++++ b/tests/Makefile.include +@@ -730,7 +730,7 @@ tests/test-hmp$(EXESUF): tests/test-hmp.o + tests/machine-none-test$(EXESUF): tests/machine-none-test.o + tests/drive_del-test$(EXESUF): tests/drive_del-test.o $(libqos-virtio-obj-y) + tests/qdev-monitor-test$(EXESUF): tests/qdev-monitor-test.o $(libqos-pc-obj-y) +-tests/nvme-test$(EXESUF): tests/nvme-test.o ++tests/nvme-test$(EXESUF): tests/nvme-test.o $(libqos-pc-obj-y) + tests/pvpanic-test$(EXESUF): tests/pvpanic-test.o + tests/i82801b11-test$(EXESUF): tests/i82801b11-test.o + tests/ac97-test$(EXESUF): tests/ac97-test.o +diff --git a/tests/nvme-test.c b/tests/nvme-test.c +index 7674a446e4..2700ba838a 100644 +--- a/tests/nvme-test.c ++++ b/tests/nvme-test.c +@@ -8,25 +8,73 @@ + */ + + #include "qemu/osdep.h" ++#include "qemu/units.h" + #include "libqtest.h" ++#include "libqos/libqos-pc.h" ++ ++static QOSState *qnvme_start(const char *extra_opts) ++{ ++ QOSState *qs; ++ const char *arch = qtest_get_arch(); ++ const char *cmd = "-drive id=drv0,if=none,file=null-co://,format=raw " ++ "-device nvme,addr=0x4.0,serial=foo,drive=drv0 %s"; ++ ++ if (strcmp(arch, "i386") == 0 || strcmp(arch, "x86_64") == 0) { ++ qs = qtest_pc_boot(cmd, extra_opts ? : ""); ++ global_qtest = qs->qts; ++ return qs; ++ } ++ ++ g_printerr("nvme tests are only available on x86\n"); ++ exit(EXIT_FAILURE); ++} ++ ++static void qnvme_stop(QOSState *qs) ++{ ++ qtest_shutdown(qs); ++} + +-/* Tests only initialization so far. TODO: Replace with functional tests */ + static void nop(void) + { ++ QOSState *qs; ++ ++ qs = qnvme_start(NULL); ++ qnvme_stop(qs); + } + +-int main(int argc, char **argv) ++static void nvmetest_cmb_test(void) + { +- int ret; ++ const int cmb_bar_size = 2 * MiB; ++ QOSState *qs; ++ QPCIDevice *pdev; ++ QPCIBar bar; + +- g_test_init(&argc, &argv, NULL); +- qtest_add_func("/nvme/nop", nop); ++ qs = qnvme_start("-global nvme.cmb_size_mb=2"); ++ pdev = qpci_device_find(qs->pcibus, QPCI_DEVFN(4,0)); ++ g_assert(pdev != NULL); ++ ++ qpci_device_enable(pdev); ++ bar = qpci_iomap(pdev, 2, NULL); ++ ++ qpci_io_writel(pdev, bar, 0, 0xccbbaa99); ++ g_assert_cmpint(qpci_io_readb(pdev, bar, 0), ==, 0x99); ++ g_assert_cmpint(qpci_io_readw(pdev, bar, 0), ==, 0xaa99); ++ ++ /* Test partially out-of-bounds accesses. */ ++ qpci_io_writel(pdev, bar, cmb_bar_size - 1, 0x44332211); ++ g_assert_cmpint(qpci_io_readb(pdev, bar, cmb_bar_size - 1), ==, 0x11); ++ g_assert_cmpint(qpci_io_readw(pdev, bar, cmb_bar_size - 1), !=, 0x2211); ++ g_assert_cmpint(qpci_io_readl(pdev, bar, cmb_bar_size - 1), !=, 0x44332211); ++ g_free(pdev); + +- qtest_start("-drive id=drv0,if=none,file=null-co://,format=raw " +- "-device nvme,drive=drv0,serial=foo"); +- ret = g_test_run(); ++ qnvme_stop(qs); ++} + +- qtest_end(); ++int main(int argc, char **argv) ++{ ++ g_test_init(&argc, &argv, NULL); ++ qtest_add_func("/nvme/nop", nop); ++ qtest_add_func("/nvme/cmb_test", nvmetest_cmb_test); + +- return ret; ++ return g_test_run(); + } \ No newline at end of file diff --git a/tasks/csa159/pair_137751/post_functions.txt b/tasks/csa159/pair_137751/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2046bd73c0da1674274ac57332b7de58192f7e0f --- /dev/null +++ b/tasks/csa159/pair_137751/post_functions.txt @@ -0,0 +1,128 @@ +### File: hw/block/nvme.c +```c +static void nvme_realize(PCIDevice *pci_dev, Error **errp) +{ + NvmeCtrl *n = NVME(pci_dev); + NvmeIdCtrl *id = &n->id_ctrl; + + int i; + int64_t bs_size; + uint8_t *pci_conf; + + if (!n->conf.blk) { + error_setg(errp, "drive property not set"); + return; + } + + bs_size = blk_getlength(n->conf.blk); + if (bs_size < 0) { + error_setg(errp, "could not get backing file size"); + return; + } + + if (!n->serial) { + error_setg(errp, "serial property not set"); + return; + } + blkconf_blocksizes(&n->conf); + if (!blkconf_apply_backend_options(&n->conf, blk_is_read_only(n->conf.blk), + false, errp)) { + return; + } + + pci_conf = pci_dev->config; + pci_conf[PCI_INTERRUPT_PIN] = 1; + pci_config_set_prog_interface(pci_dev->config, 0x2); + pci_config_set_class(pci_dev->config, PCI_CLASS_STORAGE_EXPRESS); + pcie_endpoint_cap_init(&n->parent_obj, 0x80); + + n->num_namespaces = 1; + n->reg_size = pow2ceil(0x1004 + 2 * (n->num_queues + 1) * 4); + n->ns_size = bs_size / (uint64_t)n->num_namespaces; + + n->namespaces = g_new0(NvmeNamespace, n->num_namespaces); + n->sq = g_new0(NvmeSQueue *, n->num_queues); + n->cq = g_new0(NvmeCQueue *, n->num_queues); + + memory_region_init_io(&n->iomem, OBJECT(n), &nvme_mmio_ops, n, + "nvme", n->reg_size); + pci_register_bar(&n->parent_obj, 0, + PCI_BASE_ADDRESS_SPACE_MEMORY | PCI_BASE_ADDRESS_MEM_TYPE_64, + &n->iomem); + msix_init_exclusive_bar(&n->parent_obj, n->num_queues, 4, NULL); + + id->vid = cpu_to_le16(pci_get_word(pci_conf + PCI_VENDOR_ID)); + id->ssvid = cpu_to_le16(pci_get_word(pci_conf + PCI_SUBSYSTEM_VENDOR_ID)); + strpadcpy((char *)id->mn, sizeof(id->mn), "QEMU NVMe Ctrl", ' '); + strpadcpy((char *)id->fr, sizeof(id->fr), "1.0", ' '); + strpadcpy((char *)id->sn, sizeof(id->sn), n->serial, ' '); + id->rab = 6; + id->ieee[0] = 0x00; + id->ieee[1] = 0x02; + id->ieee[2] = 0xb3; + id->oacs = cpu_to_le16(0); + id->frmw = 7 << 1; + id->lpa = 1 << 0; + id->sqes = (0x6 << 4) | 0x6; + id->cqes = (0x4 << 4) | 0x4; + id->nn = cpu_to_le32(n->num_namespaces); + id->oncs = cpu_to_le16(NVME_ONCS_WRITE_ZEROS); + id->psd[0].mp = cpu_to_le16(0x9c4); + id->psd[0].enlat = cpu_to_le32(0x10); + id->psd[0].exlat = cpu_to_le32(0x4); + if (blk_enable_write_cache(n->conf.blk)) { + id->vwc = 1; + } + + n->bar.cap = 0; + NVME_CAP_SET_MQES(n->bar.cap, 0x7ff); + NVME_CAP_SET_CQR(n->bar.cap, 1); + NVME_CAP_SET_AMS(n->bar.cap, 1); + NVME_CAP_SET_TO(n->bar.cap, 0xf); + NVME_CAP_SET_CSS(n->bar.cap, 1); + NVME_CAP_SET_MPSMAX(n->bar.cap, 4); + + n->bar.vs = 0x00010200; + n->bar.intmc = n->bar.intms = 0; + + if (n->cmb_size_mb) { + + NVME_CMBLOC_SET_BIR(n->bar.cmbloc, 2); + NVME_CMBLOC_SET_OFST(n->bar.cmbloc, 0); + + NVME_CMBSZ_SET_SQS(n->bar.cmbsz, 1); + NVME_CMBSZ_SET_CQS(n->bar.cmbsz, 0); + NVME_CMBSZ_SET_LISTS(n->bar.cmbsz, 0); + NVME_CMBSZ_SET_RDS(n->bar.cmbsz, 1); + NVME_CMBSZ_SET_WDS(n->bar.cmbsz, 1); + NVME_CMBSZ_SET_SZU(n->bar.cmbsz, 2); /* MBs */ + NVME_CMBSZ_SET_SZ(n->bar.cmbsz, n->cmb_size_mb); + + n->cmbloc = n->bar.cmbloc; + n->cmbsz = n->bar.cmbsz; + + n->cmbuf = g_malloc0(NVME_CMBSZ_GETSIZE(n->bar.cmbsz)); + memory_region_init_io(&n->ctrl_mem, OBJECT(n), &nvme_cmb_ops, n, + "nvme-cmb", NVME_CMBSZ_GETSIZE(n->bar.cmbsz)); + pci_register_bar(&n->parent_obj, NVME_CMBLOC_BIR(n->bar.cmbloc), + PCI_BASE_ADDRESS_SPACE_MEMORY | PCI_BASE_ADDRESS_MEM_TYPE_64 | + PCI_BASE_ADDRESS_MEM_PREFETCH, &n->ctrl_mem); + + } + + for (i = 0; i < n->num_namespaces; i++) { + NvmeNamespace *ns = &n->namespaces[i]; + NvmeIdNs *id_ns = &ns->id_ns; + id_ns->nsfeat = 0; + id_ns->nlbaf = 0; + id_ns->flbas = 0; + id_ns->mc = 0; + id_ns->dpc = 0; + id_ns->dps = 0; + id_ns->lbaf[0].ds = BDRV_SECTOR_BITS; + id_ns->ncap = id_ns->nuse = id_ns->nsze = + cpu_to_le64(n->ns_size >> + id_ns->lbaf[NVME_ID_NS_FLBAS_INDEX(ns->id_ns.flbas)].ds); + } +} +``` diff --git a/tasks/csa159/pair_137751/pre_functions.txt b/tasks/csa159/pair_137751/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2046bd73c0da1674274ac57332b7de58192f7e0f --- /dev/null +++ b/tasks/csa159/pair_137751/pre_functions.txt @@ -0,0 +1,128 @@ +### File: hw/block/nvme.c +```c +static void nvme_realize(PCIDevice *pci_dev, Error **errp) +{ + NvmeCtrl *n = NVME(pci_dev); + NvmeIdCtrl *id = &n->id_ctrl; + + int i; + int64_t bs_size; + uint8_t *pci_conf; + + if (!n->conf.blk) { + error_setg(errp, "drive property not set"); + return; + } + + bs_size = blk_getlength(n->conf.blk); + if (bs_size < 0) { + error_setg(errp, "could not get backing file size"); + return; + } + + if (!n->serial) { + error_setg(errp, "serial property not set"); + return; + } + blkconf_blocksizes(&n->conf); + if (!blkconf_apply_backend_options(&n->conf, blk_is_read_only(n->conf.blk), + false, errp)) { + return; + } + + pci_conf = pci_dev->config; + pci_conf[PCI_INTERRUPT_PIN] = 1; + pci_config_set_prog_interface(pci_dev->config, 0x2); + pci_config_set_class(pci_dev->config, PCI_CLASS_STORAGE_EXPRESS); + pcie_endpoint_cap_init(&n->parent_obj, 0x80); + + n->num_namespaces = 1; + n->reg_size = pow2ceil(0x1004 + 2 * (n->num_queues + 1) * 4); + n->ns_size = bs_size / (uint64_t)n->num_namespaces; + + n->namespaces = g_new0(NvmeNamespace, n->num_namespaces); + n->sq = g_new0(NvmeSQueue *, n->num_queues); + n->cq = g_new0(NvmeCQueue *, n->num_queues); + + memory_region_init_io(&n->iomem, OBJECT(n), &nvme_mmio_ops, n, + "nvme", n->reg_size); + pci_register_bar(&n->parent_obj, 0, + PCI_BASE_ADDRESS_SPACE_MEMORY | PCI_BASE_ADDRESS_MEM_TYPE_64, + &n->iomem); + msix_init_exclusive_bar(&n->parent_obj, n->num_queues, 4, NULL); + + id->vid = cpu_to_le16(pci_get_word(pci_conf + PCI_VENDOR_ID)); + id->ssvid = cpu_to_le16(pci_get_word(pci_conf + PCI_SUBSYSTEM_VENDOR_ID)); + strpadcpy((char *)id->mn, sizeof(id->mn), "QEMU NVMe Ctrl", ' '); + strpadcpy((char *)id->fr, sizeof(id->fr), "1.0", ' '); + strpadcpy((char *)id->sn, sizeof(id->sn), n->serial, ' '); + id->rab = 6; + id->ieee[0] = 0x00; + id->ieee[1] = 0x02; + id->ieee[2] = 0xb3; + id->oacs = cpu_to_le16(0); + id->frmw = 7 << 1; + id->lpa = 1 << 0; + id->sqes = (0x6 << 4) | 0x6; + id->cqes = (0x4 << 4) | 0x4; + id->nn = cpu_to_le32(n->num_namespaces); + id->oncs = cpu_to_le16(NVME_ONCS_WRITE_ZEROS); + id->psd[0].mp = cpu_to_le16(0x9c4); + id->psd[0].enlat = cpu_to_le32(0x10); + id->psd[0].exlat = cpu_to_le32(0x4); + if (blk_enable_write_cache(n->conf.blk)) { + id->vwc = 1; + } + + n->bar.cap = 0; + NVME_CAP_SET_MQES(n->bar.cap, 0x7ff); + NVME_CAP_SET_CQR(n->bar.cap, 1); + NVME_CAP_SET_AMS(n->bar.cap, 1); + NVME_CAP_SET_TO(n->bar.cap, 0xf); + NVME_CAP_SET_CSS(n->bar.cap, 1); + NVME_CAP_SET_MPSMAX(n->bar.cap, 4); + + n->bar.vs = 0x00010200; + n->bar.intmc = n->bar.intms = 0; + + if (n->cmb_size_mb) { + + NVME_CMBLOC_SET_BIR(n->bar.cmbloc, 2); + NVME_CMBLOC_SET_OFST(n->bar.cmbloc, 0); + + NVME_CMBSZ_SET_SQS(n->bar.cmbsz, 1); + NVME_CMBSZ_SET_CQS(n->bar.cmbsz, 0); + NVME_CMBSZ_SET_LISTS(n->bar.cmbsz, 0); + NVME_CMBSZ_SET_RDS(n->bar.cmbsz, 1); + NVME_CMBSZ_SET_WDS(n->bar.cmbsz, 1); + NVME_CMBSZ_SET_SZU(n->bar.cmbsz, 2); /* MBs */ + NVME_CMBSZ_SET_SZ(n->bar.cmbsz, n->cmb_size_mb); + + n->cmbloc = n->bar.cmbloc; + n->cmbsz = n->bar.cmbsz; + + n->cmbuf = g_malloc0(NVME_CMBSZ_GETSIZE(n->bar.cmbsz)); + memory_region_init_io(&n->ctrl_mem, OBJECT(n), &nvme_cmb_ops, n, + "nvme-cmb", NVME_CMBSZ_GETSIZE(n->bar.cmbsz)); + pci_register_bar(&n->parent_obj, NVME_CMBLOC_BIR(n->bar.cmbloc), + PCI_BASE_ADDRESS_SPACE_MEMORY | PCI_BASE_ADDRESS_MEM_TYPE_64 | + PCI_BASE_ADDRESS_MEM_PREFETCH, &n->ctrl_mem); + + } + + for (i = 0; i < n->num_namespaces; i++) { + NvmeNamespace *ns = &n->namespaces[i]; + NvmeIdNs *id_ns = &ns->id_ns; + id_ns->nsfeat = 0; + id_ns->nlbaf = 0; + id_ns->flbas = 0; + id_ns->mc = 0; + id_ns->dpc = 0; + id_ns->dps = 0; + id_ns->lbaf[0].ds = BDRV_SECTOR_BITS; + id_ns->ncap = id_ns->nuse = id_ns->nsze = + cpu_to_le64(n->ns_size >> + id_ns->lbaf[NVME_ID_NS_FLBAS_INDEX(ns->id_ns.flbas)].ds); + } +} +``` diff --git a/tasks/csa159/pair_137751/task_prompt.md b/tasks/csa159/pair_137751/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..83aa5337a4064020a9ddcf2489418260326ab041 --- /dev/null +++ b/tasks/csa159/pair_137751/task_prompt.md @@ -0,0 +1,367 @@ +# 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 prior rollout used check::ASTDecl syntactic matching of MemoryRegionOps initializers plus memcpy AST shape, which failed semantic_mechanism because it never proved CFG reachability or a missing bounds-guard over the copy sink. +- Hard validation and cross-validation yielded N_buggy=0 N_patched=0 with COMPILE_ERROR on changed files, so pre/post nvme.c never demonstrated the overflow; score_result was missing so objective_gate, refinement_accepted, semantic_score, and process_score stayed unproven. +- Pairing Rec->fields() with InitListExpr inits by index can mis-bind designated .impl/.read/.write fields, and matching ParmVarDecl names addr/size is not a proof that size bytes are copied at the region offset without a dominating remainder check. + +### Preserve from prior rollouts + +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Establish that a MemoryRegionOps object with impl.min_access_size constant > 1 is bound to a read or write handler that forwards the framework access length into a memcpy/memmove of a backing buffer indexed by the region offset. +- Establish on the handler CFG that the copy sink is reachable from entry and is not dominated by a guard ensuring remaining buffer bytes are at least the access size (or at least min_access_size), which is the tail-OOB relation when the framework rounds a last-byte guest access up. +- Safe if min_access_size is 1 or unset/0, because byte accesses then reach the handler at true size and a one-byte tail copy stays in-bounds. +- Safe if every bound handler dispatches to register helpers or otherwise never performs an unguarded size-forwarding copy into a backing buffer at the region offset. + +### Implementation constraints + +- Use CSA entry points that expose handler CFG and sink locations (check::ASTCodeBody, AnalysisDeclContext::getCFG, or PreCall on memcpy/memmove with dominance queries); a VarDecl-only AST walk is not sufficient. +- Join three facts without NVMe-specific names: the ops initializer's impl.min_access_size constant, function pointers in read/write/read_with_attrs/write_with_attrs (use semantic InitListExpr so designated initializers bind), and CFG reachability of an unguarded size-forwarding copy in those callees. +- Emit at most one diagnostic per offending ops object, located at the min_access_size initializer or the unguarded copy sink in the device source, not in tests/nvme-test.c. +- Scope is the QEMU MemoryRegionOps I/O-region API; resolve handlers from the ops initializer and treat QEMU default min_access_size 1 as safe when the field is absent. +- Do not substitute ProgramState symbolic addr/size tracking or a full model of access_with_adjusted_size for a CFG guard/sink query unless a bounds check exists and its dominance is otherwise undecidable. + +### Validation checklist + +- Build the plugin so clang_registerCheckers links and scan_before.sh can compile hw/block/nvme.c without COMPILE_ERROR from missing headers or incompatible flags. +- Before-patch scan of hw/block/nvme.c must report the nvme_cmb_ops min_access_size=2 binding or the nvme_cmb_read/nvme_cmb_write copy sinks. +- After-patch scan (min_access_size lowered to 1) must drop that diagnostic; nvme_mmio_ops and other non-passthrough handlers must stay clean. +- Report location must fall in the changed span around hw/block/nvme.c:1204 or inside the CMB handler bodies, not only in tests/. +- Hard_validation and cross_validation must reach N_buggy>=1, N_patched=0, relevant disappearance on the patched ops, and a clean refinement_accepted run. + +### Avoid and forbidden regressions + +- Do not repeat syntax-only ASTDecl constant-folding of min_access_size plus memcpy AST shape without CFG reachability or dominance of a bounds guard. +- Do not treat a diagnostic glued to the patched min_access_size token as proof if the copy sink was not shown reachable and unguarded. +- Do not key the matcher on parameter names addr/size, nvme_cmb_ops, cmbuf, CVE-2018-16847, or line 1204 as a stand-in for ops-to-handler binding. +- Do not simulate QEMU memory-core rounding with exploit-style guest accesses; min_access_size>1 plus an unguarded size-forwarding copy is the relation to prove. +- Do not regress anchor_free or hardcoding_free. diff --git a/tasks/csa159/pair_137769/checker_template.cpp b/tasks/csa159/pair_137769/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_137769/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_137769/config.json b/tasks/csa159/pair_137769/config.json new file mode 100644 index 0000000000000000000000000000000000000000..e2959ab1c9f2b7cbc6dee60dbcecda290a6fcc13 --- /dev/null +++ b/tasks/csa159/pair_137769/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "qemu_qemu", + "before_commit": "933cc4bb3469b82be2a2095523df400973aa4790", + "after_commit": "25c01bd19d0e4b66f357618aeefda1ef7a41e21a", + "repo_path": "/workspace/repo/qemu/qemu", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/qemu_qemu/6598f0cdad6acc6674c4f060fa46e537228c2c47/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/qemu_qemu/6598f0cdad6acc6674c4f060fa46e537228c2c47/compile_commands.json", + "changed_files": [ + "net/net.c" + ], + "commit_message": "net: drop too large packet early\n\nWe try to detect and drop too large packet (>INT_MAX) in 1592a9947036\n(\"net: ignore packet size greater than INT_MAX\") during packet\ndelivering. Unfortunately, this is not sufficient as we may hit\nanother integer overflow when trying to queue such large packet in\nqemu_net_queue_append_iov():\n\n- size of the allocation may overflow on 32bit\n- packet->size is integer which may overflow even on 64bit\n\nFixing this by moving the check to qemu_sendv_packet_async() which is\nthe entrance of all networking codes and reduce the limit to\nNET_BUFSIZE to be more conservative. This works since:\n\n- For the callers that call qemu_sendv_packet_async() directly, they\n only care about if zero is returned to determine whether to prevent\n the source from producing more packets. A callback will be triggered\n if peer can accept more then source could be enabled. This is\n usually used by high speed networking implementation like virtio-net\n or netmap.\n- For the callers that call qemu_sendv_packet() that calls\n qemu_sendv_packet_async() indirectly, they often ignore the return\n value. In this case qemu will just the drop packets if peer can't\n receive.\n\nQemu will copy the packet if it was queued. So it was safe for both\nkinds of the callers to assume the packet was sent.\n\nSince we move the check from qemu_deliver_packet_iov() to\nqemu_sendv_packet_async(), it would be safer to make\nqemu_deliver_packet_iov() static to prevent any external user in the\nfuture.\n\nThis is a revised patch of CVE-2018-17963.\n\nCc: qemu-stable@nongnu.org\nCc: Li Qiang \nFixes: 1592a9947036 (\"net: ignore packet size greater than INT_MAX\")\nReported-by: Li Qiang \nReviewed-by: Li Qiang \nSigned-off-by: Jason Wang \nReviewed-by: Thomas Huth \nMessage-id: 20181204035347.6148-2-jasowang@redhat.com\nSigned-off-by: Peter Maydell ", + "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_137769/patch.diff b/tasks/csa159/pair_137769/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..811b52e32a6a3b4484b0b8c864868ad741b5c858 --- /dev/null +++ b/tasks/csa159/pair_137769/patch.diff @@ -0,0 +1,79 @@ +diff --git a/include/net/net.h b/include/net/net.h +index 7936d53d2f..ec13702dbf 100644 +--- a/include/net/net.h ++++ b/include/net/net.h +@@ -169,12 +169,6 @@ void qemu_check_nic_model(NICInfo *nd, const char *model); + int qemu_find_nic_model(NICInfo *nd, const char * const *models, + const char *default_model); + +-ssize_t qemu_deliver_packet_iov(NetClientState *sender, +- unsigned flags, +- const struct iovec *iov, +- int iovcnt, +- void *opaque); +- + void print_net_client(Monitor *mon, NetClientState *nc); + void hmp_info_network(Monitor *mon, const QDict *qdict); + void net_socket_rs_init(SocketReadState *rs, +diff --git a/net/net.c b/net/net.c +index 07c194a8f6..1f7d626197 100644 +--- a/net/net.c ++++ b/net/net.c +@@ -231,6 +231,11 @@ static void qemu_net_client_destructor(NetClientState *nc) + { + g_free(nc); + } ++static ssize_t qemu_deliver_packet_iov(NetClientState *sender, ++ unsigned flags, ++ const struct iovec *iov, ++ int iovcnt, ++ void *opaque); + + static void qemu_net_client_setup(NetClientState *nc, + NetClientInfo *info, +@@ -705,22 +710,18 @@ static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov, + return ret; + } + +-ssize_t qemu_deliver_packet_iov(NetClientState *sender, +- unsigned flags, +- const struct iovec *iov, +- int iovcnt, +- void *opaque) ++static ssize_t qemu_deliver_packet_iov(NetClientState *sender, ++ unsigned flags, ++ const struct iovec *iov, ++ int iovcnt, ++ void *opaque) + { + NetClientState *nc = opaque; +- size_t size = iov_size(iov, iovcnt); + int ret; + +- if (size > INT_MAX) { +- return size; +- } + + if (nc->link_down) { +- return size; ++ return iov_size(iov, iovcnt); + } + + if (nc->receive_disabled) { +@@ -745,10 +746,15 @@ ssize_t qemu_sendv_packet_async(NetClientState *sender, + NetPacketSent *sent_cb) + { + NetQueue *queue; ++ size_t size = iov_size(iov, iovcnt); + int ret; + ++ if (size > NET_BUFSIZE) { ++ return size; ++ } ++ + if (sender->link_down || !sender->peer) { +- return iov_size(iov, iovcnt); ++ return size; + } + + /* Let filters handle the packet first */ \ No newline at end of file diff --git a/tasks/csa159/pair_137769/post_functions.txt b/tasks/csa159/pair_137769/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..c0777750e1e4052d9b7477748ae71d87331b2283 --- /dev/null +++ b/tasks/csa159/pair_137769/post_functions.txt @@ -0,0 +1,122 @@ +### File: net/net.c +```c +static char *assign_name(NetClientState *nc1, const char *model) +{ + NetClientState *nc; + int id = 0; + + QTAILQ_FOREACH(nc, &net_clients, next) { + if (nc == nc1) { + continue; + } + if (strcmp(nc->model, model) == 0) { + id++; + } + } + + return g_strdup_printf("%s.%d", model, id); +} + +static void qemu_net_client_destructor(NetClientState *nc) +{ + g_free(nc); +} + +static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov, + int iovcnt, unsigned flags) +{ + uint8_t *buf = NULL; + uint8_t *buffer; + size_t offset; + ssize_t ret; + + if (iovcnt == 1) { + buffer = iov[0].iov_base; + offset = iov[0].iov_len; + } else { + offset = iov_size(iov, iovcnt); + if (offset > NET_BUFSIZE) { + return -1; + } + buf = g_malloc(offset); + buffer = buf; + offset = iov_to_buf(iov, iovcnt, 0, buf, offset); + } + + if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) { + ret = nc->info->receive_raw(nc, buffer, offset); + } else { + ret = nc->info->receive(nc, buffer, offset); + } + + g_free(buf); + return ret; +} + +static ssize_t qemu_deliver_packet_iov(NetClientState *sender, + unsigned flags, + const struct iovec *iov, + int iovcnt, + void *opaque) +{ + NetClientState *nc = opaque; + int ret; + + + if (nc->link_down) { + return iov_size(iov, iovcnt); + } + + if (nc->receive_disabled) { + return 0; + } + + if (nc->info->receive_iov && !(flags & QEMU_NET_PACKET_FLAG_RAW)) { + ret = nc->info->receive_iov(nc, iov, iovcnt); + } else { + ret = nc_sendv_compat(nc, iov, iovcnt, flags); + } + + if (ret == 0) { + nc->receive_disabled = 1; + } + + return ret; +} + +ssize_t qemu_sendv_packet_async(NetClientState *sender, + const struct iovec *iov, int iovcnt, + NetPacketSent *sent_cb) +{ + NetQueue *queue; + size_t size = iov_size(iov, iovcnt); + int ret; + + if (size > NET_BUFSIZE) { + return size; + } + + if (sender->link_down || !sender->peer) { + return size; + } + + /* Let filters handle the packet first */ + ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender, + QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb); + if (ret) { + return ret; + } + + ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender, + QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb); + if (ret) { + return ret; + } + + queue = sender->peer->incoming_queue; + + return qemu_net_queue_send_iov(queue, sender, + QEMU_NET_PACKET_FLAG_NONE, + iov, iovcnt, sent_cb); +} +``` diff --git a/tasks/csa159/pair_137769/pre_functions.txt b/tasks/csa159/pair_137769/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..fbb914c0319a46ed17751cf8dd009aa6394c1db5 --- /dev/null +++ b/tasks/csa159/pair_137769/pre_functions.txt @@ -0,0 +1,148 @@ +### File: net/net.c +```c +static char *assign_name(NetClientState *nc1, const char *model) +{ + NetClientState *nc; + int id = 0; + + QTAILQ_FOREACH(nc, &net_clients, next) { + if (nc == nc1) { + continue; + } + if (strcmp(nc->model, model) == 0) { + id++; + } + } + + return g_strdup_printf("%s.%d", model, id); +} + +static void qemu_net_client_destructor(NetClientState *nc) +{ + g_free(nc); +} + +static void qemu_net_client_setup(NetClientState *nc, + NetClientInfo *info, + NetClientState *peer, + const char *model, + const char *name, + NetClientDestructor *destructor) +{ + nc->info = info; + nc->model = g_strdup(model); + if (name) { + nc->name = g_strdup(name); + } else { + nc->name = assign_name(nc, model); + } + + if (peer) { + assert(!peer->peer); + nc->peer = peer; + peer->peer = nc; + } + QTAILQ_INSERT_TAIL(&net_clients, nc, next); + + nc->incoming_queue = qemu_new_net_queue(qemu_deliver_packet_iov, nc); + nc->destructor = destructor; + QTAILQ_INIT(&nc->filters); +} + +static ssize_t nc_sendv_compat(NetClientState *nc, const struct iovec *iov, + int iovcnt, unsigned flags) +{ + uint8_t *buf = NULL; + uint8_t *buffer; + size_t offset; + ssize_t ret; + + if (iovcnt == 1) { + buffer = iov[0].iov_base; + offset = iov[0].iov_len; + } else { + offset = iov_size(iov, iovcnt); + if (offset > NET_BUFSIZE) { + return -1; + } + buf = g_malloc(offset); + buffer = buf; + offset = iov_to_buf(iov, iovcnt, 0, buf, offset); + } + + if (flags & QEMU_NET_PACKET_FLAG_RAW && nc->info->receive_raw) { + ret = nc->info->receive_raw(nc, buffer, offset); + } else { + ret = nc->info->receive(nc, buffer, offset); + } + + g_free(buf); + return ret; +} + +ssize_t qemu_deliver_packet_iov(NetClientState *sender, + unsigned flags, + const struct iovec *iov, + int iovcnt, + void *opaque) +{ + NetClientState *nc = opaque; + size_t size = iov_size(iov, iovcnt); + int ret; + + if (size > INT_MAX) { + return size; + } + + if (nc->link_down) { + return size; + } + + if (nc->receive_disabled) { + return 0; + } + + if (nc->info->receive_iov && !(flags & QEMU_NET_PACKET_FLAG_RAW)) { + ret = nc->info->receive_iov(nc, iov, iovcnt); + } else { + ret = nc_sendv_compat(nc, iov, iovcnt, flags); + } + + if (ret == 0) { + nc->receive_disabled = 1; + } + + return ret; +} + +ssize_t qemu_sendv_packet_async(NetClientState *sender, + const struct iovec *iov, int iovcnt, + NetPacketSent *sent_cb) +{ + NetQueue *queue; + int ret; + + if (sender->link_down || !sender->peer) { + return iov_size(iov, iovcnt); + } + + /* Let filters handle the packet first */ + ret = filter_receive_iov(sender, NET_FILTER_DIRECTION_TX, sender, + QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb); + if (ret) { + return ret; + } + + ret = filter_receive_iov(sender->peer, NET_FILTER_DIRECTION_RX, sender, + QEMU_NET_PACKET_FLAG_NONE, iov, iovcnt, sent_cb); + if (ret) { + return ret; + } + + queue = sender->peer->incoming_queue; + + return qemu_net_queue_send_iov(queue, sender, + QEMU_NET_PACKET_FLAG_NONE, + iov, iovcnt, sent_cb); +} +``` diff --git a/tasks/csa159/pair_137769/task_prompt.md b/tasks/csa159/pair_137769/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ab5483b6512c35ad365c2aa2c2584631dba93c60 --- /dev/null +++ b/tasks/csa159/pair_137769/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: `control_flow` + +### Current failure diagnosis + +- The independent rollout failed only on refinement_accepted (outcome feedback_required after one round); compile, 1-to-0 differential, G6, and semantic score 8.0 did not make the refinement gate converge. +- The unresolved blocker is that refinement is not accepted or clean, so the size-guard-versus-queue-sink argument remained unproven to the refinement reviewer despite a plausible scan. +- A new synthesis must re-derive CVE-2018-17963 from the original patch and pre/post qemu_sendv_packet_async bodies rather than resume the unaccepted rollout. + +### Preserve from prior rollouts + +- Preserve successful compile, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve the previously adequate CSA mechanism: intra-procedural dominating size guard over the named queue sink (semantic score 8.0, adequate). +- 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 qemu_net_queue_send_iov or qemu_net_queue_append_iov is reached with no dominating upper bound on the total iovec size from iov_size of the same iov/iovcnt arguments passed to the sink. +- Treat the sink as safe only if an IfStmt compares that size-source (a VarDecl initialized from matching iov_size(iov, iovcnt), or a direct iov_size call) to a positive integer constant using >/>= or inverted NET_BUFSIZE) return size;` must dominate that call and suppress the report. +- The pre-patch INT_MAX check in qemu_deliver_packet_iov does not protect the sendv queueing path; that deliver callback is not traversed when packets are queued. + +### Implementation constraints + +- Use check::PreCall at the sink CallEvent so the enclosing function body, size-source bindings, and guard IfStmts can be examined before the call executes. +- Prove protection with CFG dominance (AnalysisDeclContext, CFGStmtMap, same-block statement order or CFGDomTree), not symbolic ProgramState of iov_size, which is an opaque external function. +- Identify sinks by the stable QEMU net-queue API names qemu_net_queue_send_iov and qemu_net_queue_append_iov with iov at argument 3 and iovcnt at argument 4; require those arguments to be matchable variable references. +- Emit the diagnostic on the sink CallExpr source range in the enclosing function, not on the guard and not on qemu_deliver_packet_iov. +- Keep scope project-general to the net iovec queueing API on the net/net.c scan surface; do not encode file paths, patch line numbers, NET_BUFSIZE as a unique literal, or qemu_sendv_packet_async as the only analyzed function. +- Scan include paths must resolve qemu/osdep.h from the local worktree so parse failures cannot masquerade as a clean result. + +### Validation checklist + +- The checker plugin compiles, registers, and loads without error. +- Before-patch scan of net/net.c yields exactly one warning at the qemu_net_queue_send_iov call inside qemu_sendv_packet_async (previously reported at net/net.c:769). +- After-patch scan yields zero warnings once the NET_BUFSIZE comparison-and-return dominates that same call. +- Code verification matches n_buggy=1, n_patched=0, function_membership in qemu_sendv_packet_async, near-patch distance about 17 lines, relevance_ratio 1.0, and no reports in non-patched functions. +- After-commit silence must come from the dominating guard, not from COMPILE_ERROR or missing headers. +- Refinement must be accepted and clean so G6 includes refinement_accepted in addition to the already-passing hard_validation and objective items. + +### Avoid and forbidden regressions + +- Do not copy, repair, resume, or reconstruct the prior checker.cpp or checker.so. +- Do not use check::PostCall or path-sensitive symbolic tracking of iov_size's return value. +- Do not hardcode patch anchors, changed-line sets, or patch-local identifiers as detection features. +- Do not report on downstream g_malloc or packet->size in net/queue.c; those are consequences of the named queue sinks, not additional intra-procedural sinks. +- Do not weaken to syntax-only callee matching without a dominating exit-guard proof, and do not require interprocedural dataflow across functions. +- Do not accept a 0/0 scan caused by missing qemu/osdep.h or invalid include flags as patched-clean. +- Do not regress hard_validation, objective_gate G6, semantic_mechanism, semantic_score, process_score, anchor_free, or hardcoding_free. diff --git a/tasks/csa159/pair_137782/checker_template.cpp b/tasks/csa159/pair_137782/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_137782/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_137782/config.json b/tasks/csa159/pair_137782/config.json new file mode 100644 index 0000000000000000000000000000000000000000..1e869e77bba6ca73ab1dbd872fb8fee9a9ab0e95 --- /dev/null +++ b/tasks/csa159/pair_137782/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "qemu_qemu", + "before_commit": "9f6b2f1c6497adcce4dec9b3bd1f1e78877a03dd", + "after_commit": "fa365d7cd11185237471823a5a33d36765454e16", + "repo_path": "/workspace/repo/qemu/qemu", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/qemu_qemu/82172b751929314a81337aa91deea82e8297af1f/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/qemu_qemu/82172b751929314a81337aa91deea82e8297af1f/compile_commands.json", + "changed_files": [ + "hw/acpi/pcihp.c" + ], + "commit_message": "pcihp: fix possible array out of bounds\n\nPrevent out-of-bounds array access on\nacpi_pcihp_pci_status.\n\nSigned-off-by: Gonglei \nReviewed-by: Peter Crosthwaite \nReviewed-by: Michael S. Tsirkin \nSigned-off-by: Michael S. Tsirkin \nCc: qemu-stable@nongnu.org\nReviewed-by: Marcel Apfelbaum ", + "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_137782/patch.diff b/tasks/csa159/pair_137782/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..41039ef3bbf5a79ed08e567659a9e7a1b4c521e7 --- /dev/null +++ b/tasks/csa159/pair_137782/patch.diff @@ -0,0 +1,12 @@ +diff --git a/hw/acpi/pcihp.c b/hw/acpi/pcihp.c +index fae663af11..34dedf1e8b 100644 +--- a/hw/acpi/pcihp.c ++++ b/hw/acpi/pcihp.c +@@ -231,7 +231,7 @@ static uint64_t pci_read(void *opaque, hwaddr addr, unsigned int size) + uint32_t val = 0; + int bsel = s->hotplug_select; + +- if (bsel < 0 || bsel > ACPI_PCIHP_MAX_HOTPLUG_BUS) { ++ if (bsel < 0 || bsel >= ACPI_PCIHP_MAX_HOTPLUG_BUS) { + return 0; + } \ No newline at end of file diff --git a/tasks/csa159/pair_137782/post_functions.txt b/tasks/csa159/pair_137782/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..93d6a030ce57107bda53bfefbf26247705630d0e --- /dev/null +++ b/tasks/csa159/pair_137782/post_functions.txt @@ -0,0 +1,42 @@ +### File: hw/acpi/pcihp.c +```c +static uint64_t pci_read(void *opaque, hwaddr addr, unsigned int size) +{ + AcpiPciHpState *s = opaque; + uint32_t val = 0; + int bsel = s->hotplug_select; + + if (bsel < 0 || bsel >= ACPI_PCIHP_MAX_HOTPLUG_BUS) { + return 0; + } + + switch (addr) { + case PCI_UP_BASE: + val = s->acpi_pcihp_pci_status[bsel].up; + if (!s->legacy_piix) { + s->acpi_pcihp_pci_status[bsel].up = 0; + } + ACPI_PCIHP_DPRINTF("pci_up_read %" PRIu32 "\n", val); + break; + case PCI_DOWN_BASE: + val = s->acpi_pcihp_pci_status[bsel].down; + ACPI_PCIHP_DPRINTF("pci_down_read %" PRIu32 "\n", val); + break; + case PCI_EJ_BASE: + /* No feature defined yet */ + ACPI_PCIHP_DPRINTF("pci_features_read %" PRIu32 "\n", val); + break; + case PCI_RMV_BASE: + val = s->acpi_pcihp_pci_status[bsel].hotplug_enable; + ACPI_PCIHP_DPRINTF("pci_rmv_read %" PRIu32 "\n", val); + break; + case PCI_SEL_BASE: + val = s->hotplug_select; + ACPI_PCIHP_DPRINTF("pci_sel_read %" PRIu32 "\n", val); + default: + break; + } + + return val; +} +``` diff --git a/tasks/csa159/pair_137782/pre_functions.txt b/tasks/csa159/pair_137782/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..afbd18e554399267adf83a48f1d8fbd17915b39b --- /dev/null +++ b/tasks/csa159/pair_137782/pre_functions.txt @@ -0,0 +1,42 @@ +### File: hw/acpi/pcihp.c +```c +static uint64_t pci_read(void *opaque, hwaddr addr, unsigned int size) +{ + AcpiPciHpState *s = opaque; + uint32_t val = 0; + int bsel = s->hotplug_select; + + if (bsel < 0 || bsel > ACPI_PCIHP_MAX_HOTPLUG_BUS) { + return 0; + } + + switch (addr) { + case PCI_UP_BASE: + val = s->acpi_pcihp_pci_status[bsel].up; + if (!s->legacy_piix) { + s->acpi_pcihp_pci_status[bsel].up = 0; + } + ACPI_PCIHP_DPRINTF("pci_up_read %" PRIu32 "\n", val); + break; + case PCI_DOWN_BASE: + val = s->acpi_pcihp_pci_status[bsel].down; + ACPI_PCIHP_DPRINTF("pci_down_read %" PRIu32 "\n", val); + break; + case PCI_EJ_BASE: + /* No feature defined yet */ + ACPI_PCIHP_DPRINTF("pci_features_read %" PRIu32 "\n", val); + break; + case PCI_RMV_BASE: + val = s->acpi_pcihp_pci_status[bsel].hotplug_enable; + ACPI_PCIHP_DPRINTF("pci_rmv_read %" PRIu32 "\n", val); + break; + case PCI_SEL_BASE: + val = s->hotplug_select; + ACPI_PCIHP_DPRINTF("pci_sel_read %" PRIu32 "\n", val); + default: + break; + } + + return val; +} +``` diff --git a/tasks/csa159/pair_137782/task_prompt.md b/tasks/csa159/pair_137782/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_137782/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_138126/checker_template.cpp b/tasks/csa159/pair_138126/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138126/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_138126/config.json b/tasks/csa159/pair_138126/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f02fb8129cae54772823e0dd97768f652f6ec038 --- /dev/null +++ b/tasks/csa159/pair_138126/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "CESNET_libyang", + "before_commit": "19a0d6778999a2fea68db2fd7407cba1f954d895", + "after_commit": "a1f17693904ed6fecc8902c747fc50a8f20e6af8", + "repo_path": "/workspace/repo/CESNET/libyang", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/CESNET_libyang/19a0d6778999a2fea68db2fd7407cba1f954d895/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/CESNET_libyang/19a0d6778999a2fea68db2fd7407cba1f954d895/compile_commands.json", + "changed_files": [ + "src/parser_yang_bis.c" + ], + "commit_message": "yang parser BUGFIX allocate more patterns than currently needed\n\nFixes #740", + "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_138126/patch.diff b/tasks/csa159/pair_138126/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2bea8734a3904e170d5a0bf5c5b055d119580b9d --- /dev/null +++ b/tasks/csa159/pair_138126/patch.diff @@ -0,0 +1,28 @@ +diff --git a/src/parser_yang_bis.c b/src/parser_yang_bis.c +index 42f285821..495917aee 100644 +--- a/src/parser_yang_bis.c ++++ b/src/parser_yang_bis.c +@@ -4623,6 +4623,9 @@ yyreduce: + !(data_node && data_node->nodetype != LYS_GROUPING && lys_ingrouping(data_node))) { + unsigned int c = 2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1); + YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); ++ ++c; ++ YANG_ADDELEM(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre, c, "patterns"); ++ actual = &(((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.patterns_pcre)[2 * (((struct yang_type *)(yyvsp[-2].backup_token).actual)->type->info.str.pat_count - 1)]; + } + #endif + if (yang_read_pattern(trg->ctx, pattern, actual, (yyvsp[-1].str), (yyvsp[0].ch))) { +diff --git a/src/yang.y.in b/src/yang.y.in +index 25879f6dd..1b88d2340 100644 +--- a/src/yang.y.in ++++ b/src/yang.y.in +@@ -1517,6 +1517,9 @@ pattern_stmt: PATTERN_KEYWORD pattern_sep pattern_arg_str pattern_end {struct l + !(data_node && data_node->nodetype != LYS_GROUPING && lys_ingrouping(data_node))) { + unsigned int c = 2 * (((struct yang_type *)$2.actual)->type->info.str.pat_count - 1); + YANG_ADDELEM(((struct yang_type *)$2.actual)->type->info.str.patterns_pcre, c, "patterns"); ++ ++c; ++ YANG_ADDELEM(((struct yang_type *)$2.actual)->type->info.str.patterns_pcre, c, "patterns"); ++ actual = &(((struct yang_type *)$2.actual)->type->info.str.patterns_pcre)[2 * (((struct yang_type *)$2.actual)->type->info.str.pat_count - 1)]; + } + #endif + if (yang_read_pattern(trg->ctx, pattern, actual, $3, $4)) { \ No newline at end of file diff --git a/tasks/csa159/pair_138126/post_functions.txt b/tasks/csa159/pair_138126/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..751bfed0f373975221d9568e9b674aa9275092ee --- /dev/null +++ b/tasks/csa159/pair_138126/post_functions.txt @@ -0,0 +1,281 @@ +### File: src/parser_yang_bis.c +```c +int +yyparse (void *scanner, struct yang_parameter *param) +{ +/* The lookahead symbol. */ +int yychar; +char *s = NULL, *tmp_s = NULL, *ext_name = NULL; +struct lys_module *trg = NULL; +struct lys_node *tpdf_parent = NULL, *data_node = NULL; +struct lys_ext_instance_complex *ext_instance = NULL; +int is_ext_instance; +void *actual = NULL; +enum yytokentype backup_type, actual_type = MODULE_KEYWORD; +int64_t cnt_val = 0; +int is_value = 0; +void *yang_type = NULL; + + +/* The semantic value of the lookahead symbol. */ +/* Default value used for initialization, for pacifying older GCCs + or non-GCC compilers. */ +YY_INITIAL_VALUE (static YYSTYPE yyval_default;) +YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); + +/* Location data for the lookahead symbol. */ +static YYLTYPE yyloc_default +# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL + = { 1, 1, 1, 1 } +# endif +; +YYLTYPE yylloc = yyloc_default; + + /* Number of syntax errors so far. */ + int yynerrs; + + int yystate; + /* Number of tokens to shift before error messages enabled. */ + int yyerrstatus; + + /* The stacks and their tools: + 'yyss': related to states. + 'yyvs': related to semantic values. + 'yyls': related to locations. + + Refer to the stacks through separate pointers, to allow yyoverflow + to reallocate them elsewhere. */ + + /* The state stack. */ + yytype_int16 yyssa[YYINITDEPTH]; + yytype_int16 *yyss; + yytype_int16 *yyssp; + + /* The semantic value stack. */ + YYSTYPE yyvsa[YYINITDEPTH]; + YYSTYPE *yyvs; + YYSTYPE *yyvsp; + + /* The location stack. */ + YYLTYPE yylsa[YYINITDEPTH]; + YYLTYPE *yyls; + YYLTYPE *yylsp; + + /* The locations where the error started and ended. */ + YYLTYPE yyerror_range[3]; + + YYSIZE_T yystacksize; + + int yyn; + int yyresult; + /* Lookahead token as an internal (translated) token number. */ + int yytoken = 0; + /* The variables used to return semantic value and location from the + action routines. */ + YYSTYPE yyval; + YYLTYPE yyloc; + +#if YYERROR_VERBOSE + /* Buffer for error messages, and its allocated size. */ + char yymsgbuf[128]; + char *yymsg = yymsgbuf; + YYSIZE_T yymsg_alloc = sizeof yymsgbuf; +#endif + +#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) + + /* The number of symbols on the RHS of the reduced rule. + Keep to zero when no symbol should be popped. */ + int yylen = 0; + + yyssp = yyss = yyssa; + yyvsp = yyvs = yyvsa; + yylsp = yyls = yylsa; + yystacksize = YYINITDEPTH; + + YYDPRINTF ((stderr, "Starting parse\n")); + + yystate = 0; + yyerrstatus = 0; + yynerrs = 0; + yychar = YYEMPTY; /* Cause a token to be read. */ + +/* User initialization code. */ + +{ yylloc.last_column = 0; + if (param->flags & EXT_INSTANCE_SUBSTMT) { + is_ext_instance = 1; + ext_instance = (struct lys_ext_instance_complex *)param->actual_node; + ext_name = (char *)param->data_node; + } else { + is_ext_instance = 0; + } + yylloc.last_line = is_ext_instance; /* HACK for flex - return SUBMODULE_KEYWORD or SUBMODULE_EXT_KEYWORD */ + param->value = &s; + param->data_node = (void **)&data_node; + param->actual_node = &actual; + backup_type = NODE; + trg = (param->submodule) ? (struct lys_module *)param->submodule : param->module; + } + + + yylsp[0] = yylloc; + goto yysetstate; + +/*------------------------------------------------------------. +| yynewstate -- Push a new state, which is found in yystate. | +`------------------------------------------------------------*/ + yynewstate: + /* In all cases, when you get here, the value and location stacks + have just been pushed. So pushing a state here evens the stacks. */ + yyssp++; + + yysetstate: + *yyssp = (yytype_int16) yystate; + + if (yyss + yystacksize - 1 <= yyssp) + { + /* Get the current used size of the three stacks, in elements. */ + YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1); + +#ifdef yyoverflow + { + /* Give user a chance to reallocate the stack. Use copies of + these so that the &'s don't force the real ones into + memory. */ + YYSTYPE *yyvs1 = yyvs; + yytype_int16 *yyss1 = yyss; + YYLTYPE *yyls1 = yyls; + + /* Each stack pointer address is followed by the size of the + data in use in that stack, in bytes. This used to be a + conditional around just the two extra args, but that might + be undefined if yyoverflow is a macro. */ + yyoverflow (YY_("memory exhausted"), + &yyss1, yysize * sizeof (*yyssp), + &yyvs1, yysize * sizeof (*yyvsp), + &yyls1, yysize * sizeof (*yylsp), + &yystacksize); + yyss = yyss1; + yyvs = yyvs1; + yyls = yyls1; + } +#else /* no yyoverflow */ +# ifndef YYSTACK_RELOCATE + goto yyexhaustedlab; +# else + /* Extend the stack our own way. */ + if (YYMAXDEPTH <= yystacksize) + goto yyexhaustedlab; + yystacksize *= 2; + if (YYMAXDEPTH < yystacksize) + yystacksize = YYMAXDEPTH; + + { + yytype_int16 *yyss1 = yyss; + union yyalloc *yyptr = + (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); + if (! yyptr) + goto yyexhaustedlab; + YYSTACK_RELOCATE (yyss_alloc, yyss); + YYSTACK_RELOCATE (yyvs_alloc, yyvs); + YYSTACK_RELOCATE (yyls_alloc, yyls); +# undef YYSTACK_RELOCATE + if (yyss1 != yyssa) + YYSTACK_FREE (yyss1); + } +# endif +#endif /* no yyoverflow */ + + yyssp = yyss + yysize - 1; + yyvsp = yyvs + yysize - 1; + yylsp = yyls + yysize - 1; + + YYDPRINTF ((stderr, "Stack size increased to %lu\n", + (unsigned long) yystacksize)); + + if (yyss + yystacksize - 1 <= yyssp) + YYABORT; + } + + YYDPRINTF ((stderr, "Entering state %d\n", yystate)); + + if (yystate == YYFINAL) + YYACCEPT; + + goto yybackup; + +/*-----------. +| yybackup. | +`-----------*/ +yybackup: + + /* Do appropriate processing given the current state. Read a + lookahead token if we need one and don't already have one. */ + + /* First try to decide what to do without reference to lookahead token. */ + yyn = yypact[yystate]; + if (yypact_value_is_default (yyn)) + goto yydefault; + + /* Not known => get a lookahead token if don't already have one. */ + + /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ + if (yychar == YYEMPTY) + { + YYDPRINTF ((stderr, "Reading a token: ")); + yychar = yylex (&yylval, &yylloc, scanner); + } + + if (yychar <= YYEOF) + { + yychar = yytoken = YYEOF; + YYDPRINTF ((stderr, "Now at end of input.\n")); + } + else + { + yytoken = YYTRANSLATE (yychar); + YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); + } + + /* If the proper action on seeing token YYTOKEN is to reduce or to + detect an error, take that action. */ + yyn += yytoken; + if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) + goto yydefault; + yyn = yytable[yyn]; + if (yyn <= 0) + { + if (yytable_value_is_error (yyn)) + goto yyerrlab; + yyn = -yyn; + goto yyreduce; + } + + /* Count tokens shifted since error; after three, turn off error + status. */ + if (yyerrstatus) + yyerrstatus--; + + /* Shift the lookahead token. */ + YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); + + /* Discard the shifted token. */ + yychar = YYEMPTY; + + yystate = yyn; + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + *++yyvsp = yylval; + YY_IGNORE_MAYBE_UNINITIALIZED_END + *++yylsp = yylloc; + goto yynewstate; + + +/*-----------------------------------------------------------. +| yydefault -- do the default action for the current state. | +`-----------------------------------------------------------*/ +yydefault: + yyn = yydefact[yystat + +// ... (219331 more chars) +``` diff --git a/tasks/csa159/pair_138126/pre_functions.txt b/tasks/csa159/pair_138126/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..84da82bf074e7727fe918f1b1d23a5d7104d11f8 --- /dev/null +++ b/tasks/csa159/pair_138126/pre_functions.txt @@ -0,0 +1,281 @@ +### File: src/parser_yang_bis.c +```c +int +yyparse (void *scanner, struct yang_parameter *param) +{ +/* The lookahead symbol. */ +int yychar; +char *s = NULL, *tmp_s = NULL, *ext_name = NULL; +struct lys_module *trg = NULL; +struct lys_node *tpdf_parent = NULL, *data_node = NULL; +struct lys_ext_instance_complex *ext_instance = NULL; +int is_ext_instance; +void *actual = NULL; +enum yytokentype backup_type, actual_type = MODULE_KEYWORD; +int64_t cnt_val = 0; +int is_value = 0; +void *yang_type = NULL; + + +/* The semantic value of the lookahead symbol. */ +/* Default value used for initialization, for pacifying older GCCs + or non-GCC compilers. */ +YY_INITIAL_VALUE (static YYSTYPE yyval_default;) +YYSTYPE yylval YY_INITIAL_VALUE (= yyval_default); + +/* Location data for the lookahead symbol. */ +static YYLTYPE yyloc_default +# if defined YYLTYPE_IS_TRIVIAL && YYLTYPE_IS_TRIVIAL + = { 1, 1, 1, 1 } +# endif +; +YYLTYPE yylloc = yyloc_default; + + /* Number of syntax errors so far. */ + int yynerrs; + + int yystate; + /* Number of tokens to shift before error messages enabled. */ + int yyerrstatus; + + /* The stacks and their tools: + 'yyss': related to states. + 'yyvs': related to semantic values. + 'yyls': related to locations. + + Refer to the stacks through separate pointers, to allow yyoverflow + to reallocate them elsewhere. */ + + /* The state stack. */ + yytype_int16 yyssa[YYINITDEPTH]; + yytype_int16 *yyss; + yytype_int16 *yyssp; + + /* The semantic value stack. */ + YYSTYPE yyvsa[YYINITDEPTH]; + YYSTYPE *yyvs; + YYSTYPE *yyvsp; + + /* The location stack. */ + YYLTYPE yylsa[YYINITDEPTH]; + YYLTYPE *yyls; + YYLTYPE *yylsp; + + /* The locations where the error started and ended. */ + YYLTYPE yyerror_range[3]; + + YYSIZE_T yystacksize; + + int yyn; + int yyresult; + /* Lookahead token as an internal (translated) token number. */ + int yytoken = 0; + /* The variables used to return semantic value and location from the + action routines. */ + YYSTYPE yyval; + YYLTYPE yyloc; + +#if YYERROR_VERBOSE + /* Buffer for error messages, and its allocated size. */ + char yymsgbuf[128]; + char *yymsg = yymsgbuf; + YYSIZE_T yymsg_alloc = sizeof yymsgbuf; +#endif + +#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N), yylsp -= (N)) + + /* The number of symbols on the RHS of the reduced rule. + Keep to zero when no symbol should be popped. */ + int yylen = 0; + + yyssp = yyss = yyssa; + yyvsp = yyvs = yyvsa; + yylsp = yyls = yylsa; + yystacksize = YYINITDEPTH; + + YYDPRINTF ((stderr, "Starting parse\n")); + + yystate = 0; + yyerrstatus = 0; + yynerrs = 0; + yychar = YYEMPTY; /* Cause a token to be read. */ + +/* User initialization code. */ + +{ yylloc.last_column = 0; + if (param->flags & EXT_INSTANCE_SUBSTMT) { + is_ext_instance = 1; + ext_instance = (struct lys_ext_instance_complex *)param->actual_node; + ext_name = (char *)param->data_node; + } else { + is_ext_instance = 0; + } + yylloc.last_line = is_ext_instance; /* HACK for flex - return SUBMODULE_KEYWORD or SUBMODULE_EXT_KEYWORD */ + param->value = &s; + param->data_node = (void **)&data_node; + param->actual_node = &actual; + backup_type = NODE; + trg = (param->submodule) ? (struct lys_module *)param->submodule : param->module; + } + + + yylsp[0] = yylloc; + goto yysetstate; + +/*------------------------------------------------------------. +| yynewstate -- Push a new state, which is found in yystate. | +`------------------------------------------------------------*/ + yynewstate: + /* In all cases, when you get here, the value and location stacks + have just been pushed. So pushing a state here evens the stacks. */ + yyssp++; + + yysetstate: + *yyssp = (yytype_int16) yystate; + + if (yyss + yystacksize - 1 <= yyssp) + { + /* Get the current used size of the three stacks, in elements. */ + YYSIZE_T yysize = (YYSIZE_T) (yyssp - yyss + 1); + +#ifdef yyoverflow + { + /* Give user a chance to reallocate the stack. Use copies of + these so that the &'s don't force the real ones into + memory. */ + YYSTYPE *yyvs1 = yyvs; + yytype_int16 *yyss1 = yyss; + YYLTYPE *yyls1 = yyls; + + /* Each stack pointer address is followed by the size of the + data in use in that stack, in bytes. This used to be a + conditional around just the two extra args, but that might + be undefined if yyoverflow is a macro. */ + yyoverflow (YY_("memory exhausted"), + &yyss1, yysize * sizeof (*yyssp), + &yyvs1, yysize * sizeof (*yyvsp), + &yyls1, yysize * sizeof (*yylsp), + &yystacksize); + yyss = yyss1; + yyvs = yyvs1; + yyls = yyls1; + } +#else /* no yyoverflow */ +# ifndef YYSTACK_RELOCATE + goto yyexhaustedlab; +# else + /* Extend the stack our own way. */ + if (YYMAXDEPTH <= yystacksize) + goto yyexhaustedlab; + yystacksize *= 2; + if (YYMAXDEPTH < yystacksize) + yystacksize = YYMAXDEPTH; + + { + yytype_int16 *yyss1 = yyss; + union yyalloc *yyptr = + (union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize)); + if (! yyptr) + goto yyexhaustedlab; + YYSTACK_RELOCATE (yyss_alloc, yyss); + YYSTACK_RELOCATE (yyvs_alloc, yyvs); + YYSTACK_RELOCATE (yyls_alloc, yyls); +# undef YYSTACK_RELOCATE + if (yyss1 != yyssa) + YYSTACK_FREE (yyss1); + } +# endif +#endif /* no yyoverflow */ + + yyssp = yyss + yysize - 1; + yyvsp = yyvs + yysize - 1; + yylsp = yyls + yysize - 1; + + YYDPRINTF ((stderr, "Stack size increased to %lu\n", + (unsigned long) yystacksize)); + + if (yyss + yystacksize - 1 <= yyssp) + YYABORT; + } + + YYDPRINTF ((stderr, "Entering state %d\n", yystate)); + + if (yystate == YYFINAL) + YYACCEPT; + + goto yybackup; + +/*-----------. +| yybackup. | +`-----------*/ +yybackup: + + /* Do appropriate processing given the current state. Read a + lookahead token if we need one and don't already have one. */ + + /* First try to decide what to do without reference to lookahead token. */ + yyn = yypact[yystate]; + if (yypact_value_is_default (yyn)) + goto yydefault; + + /* Not known => get a lookahead token if don't already have one. */ + + /* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */ + if (yychar == YYEMPTY) + { + YYDPRINTF ((stderr, "Reading a token: ")); + yychar = yylex (&yylval, &yylloc, scanner); + } + + if (yychar <= YYEOF) + { + yychar = yytoken = YYEOF; + YYDPRINTF ((stderr, "Now at end of input.\n")); + } + else + { + yytoken = YYTRANSLATE (yychar); + YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc); + } + + /* If the proper action on seeing token YYTOKEN is to reduce or to + detect an error, take that action. */ + yyn += yytoken; + if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken) + goto yydefault; + yyn = yytable[yyn]; + if (yyn <= 0) + { + if (yytable_value_is_error (yyn)) + goto yyerrlab; + yyn = -yyn; + goto yyreduce; + } + + /* Count tokens shifted since error; after three, turn off error + status. */ + if (yyerrstatus) + yyerrstatus--; + + /* Shift the lookahead token. */ + YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc); + + /* Discard the shifted token. */ + yychar = YYEMPTY; + + yystate = yyn; + YY_IGNORE_MAYBE_UNINITIALIZED_BEGIN + *++yyvsp = yylval; + YY_IGNORE_MAYBE_UNINITIALIZED_END + *++yylsp = yylloc; + goto yynewstate; + + +/*-----------------------------------------------------------. +| yydefault -- do the default action for the current state. | +`-----------------------------------------------------------*/ +yydefault: + yyn = yydefact[yystat + +// ... (218802 more chars) +``` diff --git a/tasks/csa159/pair_138126/task_prompt.md b/tasks/csa159/pair_138126/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..e048f15c32ddcaaa6dbebb6dab23ba59edda1516 --- /dev/null +++ b/tasks/csa159/pair_138126/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: `interprocedural_dataflow` + +### Current failure diagnosis + +- The rollout passed compilation, differential validation, objective eligibility, refinement, and hardcoding checks, but its semantic mechanism was inadequate and its semantic score was below threshold. +- The checker used a fixed callee-name match plus AST and source-order inspection; it never tracked the actual reaching reservation state through the CFG and never established the callee's two-slot write behavior through cross-function evidence. +- Counting every textually preceding append can combine reservations from mutually exclusive branches, fail to distinguish path-dependent definitions, and therefore cannot prove that enough reservations reach the sink on the reported execution. + +### 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 process quality at or above the configured threshold. +- Do not introduce dependence on patch anchors. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Establish that the value passed as the callee's output pointer originates from a single-element append reservation into a specific array region. +- Establish across the call boundary that the callee writes the two-pointer record beginning at that output pointer, covering both the compiled pattern slot and the pcre_extra slot. +- Prove that, along a reachable caller path leading to the sink, the reservations covering the callee's complete write span are insufficient. +- Prove the safe counterpart: a non-append-derived pointer, a path with sufficient reservations, or a re-derived pair base is not reported. + +### Implementation constraints + +- Use a call-site callback such as check::PreCall or an equivalent CSA call event to identify the sink and bind the analyzed argument to the callee's output parameter. +- Use interprocedural information or a documented, semantically equivalent callee contract to establish the output write span; do not infer the span solely from the caller's call spelling. +- Represent reservation facts and the pointer's origin through CSA dataflow so mutually exclusive branches and path-dependent assignments are not merged by source order alone. +- Require CFG reachability and dominance or equivalent path reasoning for reservations counted toward the sink; reservations that do not reach the call must not satisfy the proof. +- Report at the vulnerable call or the precise caller operation that supplies the under-reserved pointer, with a diagnostic range local to that operation. +- Keep the checker general over the append and multi-slot-output relationship within the justified project scope, without matching changed-line text, patch-local names, or source excerpts. + +### Validation checklist + +- Compile the new checker and run code verification successfully. +- Run the repaired before and after scan scripts with generated-file analysis enabled, confirming at least one relevant warning before the fix and none after it. +- Confirm the before-scan diagnostic points to the yang_read_pattern call or its precise under-reserved argument operation and remains within the relevant patched function. +- Confirm the after-scan result suppresses the warning because the second reservation and explicit pair-base derivation provide the required coverage. +- Check that reservations from mutually exclusive branches do not incorrectly discharge the warning and that path-dependent pointer assignments are analyzed by their reaching definitions. +- Confirm no warnings appear in non-patched functions and that the existing objective gate, refinement outcome, process threshold, anchor-free check, and hardcoding-free check remain passing. + +### Avoid and forbidden regressions + +- Do not use source-order counting of all assignments before the call as a substitute for CFG-aware reaching and dominance analysis. +- Do not rely only on a fixed API name and caller AST shape while leaving the callee's write contract unproven. +- Do not replace the required cross-function semantic proof with path-insensitive syntax matching or value-insensitive call matching. +- Do not report merely because an element address is passed; the report requires insufficient reservation for the complete write span on a reachable path. +- Do not regress compile, before/after scan, code verification, objective eligibility, refinement acceptance, process quality, anchor freedom, or hardcoding freedom. diff --git a/tasks/csa159/pair_138203/checker_template.cpp b/tasks/csa159/pair_138203/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138203/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_138203/config.json b/tasks/csa159/pair_138203/config.json new file mode 100644 index 0000000000000000000000000000000000000000..396592345be7597b18bdac1e3f5678e2cfbd4d4b --- /dev/null +++ b/tasks/csa159/pair_138203/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "LibVNC_libvncserver", + "before_commit": "9664466442a63afd3fe51b63d6eded64bdde031b", + "after_commit": "dc78dee51a7e270e537a541a17befdf2073f5314", + "repo_path": "/workspace/repo/LibVNC/libvncserver", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/LibVNC_libvncserver/fb2901aef780d02c19acf0731ac7e104a41d9704/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/LibVNC_libvncserver/fb2901aef780d02c19acf0731ac7e104a41d9704/compile_commands.json", + "changed_files": [ + "src/libvncserver/httpd.c" + ], + "commit_message": "libvncserver: fix NULL pointer dereferences in httpd proxy handlers\n\nhttpProcessInput() passes the return value of strchr() to atoi()\nand strncmp() without checking for NULL. If a CONNECT request\ncontains no colon, or a GET request contains no slash, strchr()\nreturns NULL, leading to a segmentation fault.\n\nAdd NULL checks before using the strchr() return values.", + "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_138203/patch.diff b/tasks/csa159/pair_138203/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9d1375838d1791042c29dcae49f63fa4924c07a3 --- /dev/null +++ b/tasks/csa159/pair_138203/patch.diff @@ -0,0 +1,44 @@ +diff --git a/src/libvncserver/httpd.c b/src/libvncserver/httpd.c +index f4fe51c..7cefadc 100644 +--- a/src/libvncserver/httpd.c ++++ b/src/libvncserver/httpd.c +@@ -353,10 +353,11 @@ httpProcessInput(rfbScreenInfoPtr rfbScreen) + + + /* Process the request. */ +- if(rfbScreen->httpEnableProxyConnect) { ++if(rfbScreen->httpEnableProxyConnect) { + const static char* PROXY_OK_STR = "HTTP/1.0 200 OK\r\nContent-Type: octet-stream\r\nPragma: no-cache\r\n\r\n"; + if(!strncmp(buf, "CONNECT ", 8)) { +- if(atoi(strchr(buf, ':')+1)!=rfbScreen->port) { ++ char *colon = strchr(buf, ':'); ++ if(colon == NULL || atoi(colon+1)!=rfbScreen->port) { + rfbErr("httpd: CONNECT format invalid.\n"); + rfbWriteExact(&cl,INVALID_REQUEST_STR, strlen(INVALID_REQUEST_STR)); + httpCloseSock(rfbScreen); +@@ -369,14 +370,17 @@ httpProcessInput(rfbScreenInfoPtr rfbScreen) + rfbScreen->httpSock = RFB_INVALID_SOCKET; + return; + } +- if (!strncmp(buf, "GET ",4) && !strncmp(strchr(buf,'/'),"/proxied.connection HTTP/1.", 27)) { +- /* proxy connection */ +- rfbLog("httpd: client asked for /proxied.connection\n"); +- rfbWriteExact(&cl,PROXY_OK_STR,strlen(PROXY_OK_STR)); +- rfbNewClientConnection(rfbScreen,rfbScreen->httpSock); +- rfbScreen->httpSock = RFB_INVALID_SOCKET; +- return; +- } ++ if (!strncmp(buf, "GET ",4)) { ++ char *slash = strchr(buf, '/'); ++ if (slash != NULL && !strncmp(slash,"/proxied.connection HTTP/1.", 27)) { ++ /* proxy connection */ ++ rfbLog("httpd: client asked for /proxied.connection\n"); ++ rfbWriteExact(&cl,PROXY_OK_STR,strlen(PROXY_OK_STR)); ++ rfbNewClientConnection(rfbScreen,rfbScreen->httpSock); ++ rfbScreen->httpSock = RFB_INVALID_SOCKET; ++ return; ++ } ++ } + } + + if (strncmp(buf, "GET ", 4)) { \ No newline at end of file diff --git a/tasks/csa159/pair_138203/post_functions.txt b/tasks/csa159/pair_138203/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..c55a9a58f494baba249c58f22db43a2ff21c0ba4 --- /dev/null +++ b/tasks/csa159/pair_138203/post_functions.txt @@ -0,0 +1,300 @@ +### File: src/libvncserver/httpd.c +```c +static void +httpProcessInput(rfbScreenInfoPtr rfbScreen) +{ +#ifdef LIBVNCSERVER_IPv6 + struct sockaddr_storage addr; +#else + struct sockaddr_in addr; +#endif + socklen_t addrlen = sizeof(addr); + char fullFname[512]; + char params[1024]; + char *ptr; + char *fname; + unsigned int maxFnameLen; + FILE* fd; + rfbBool performSubstitutions = FALSE; + char str[256+32]; +#ifndef WIN32 + char* user=getenv("USER"); +#endif + + cl.sock=rfbScreen->httpSock; + + if (strlen(rfbScreen->httpDir) > 255) { + rfbErr("-httpd directory too long\n"); + httpCloseSock(rfbScreen); + return; + } + strcpy(fullFname, rfbScreen->httpDir); + fname = &fullFname[strlen(fullFname)]; + maxFnameLen = 511 - strlen(fullFname); + + buf_filled=0; + + /* Read data from the HTTP client until we get a complete request. */ + while (1) { + ssize_t got; + + if (buf_filled > sizeof (buf)) { + rfbErr("httpProcessInput: HTTP request is too long\n"); + httpCloseSock(rfbScreen); + return; + } + + got = read (rfbScreen->httpSock, buf + buf_filled, + sizeof (buf) - buf_filled - 1); + + if (got <= 0) { + if (got == 0) { + rfbErr("httpd: premature connection close\n"); + } else { +#ifdef WIN32 + errno=WSAGetLastError(); +#endif + if (errno == EAGAIN) { + return; + } + rfbLogPerror("httpProcessInput: read"); + } + httpCloseSock(rfbScreen); + return; + } + + buf_filled += got; + buf[buf_filled] = '\0'; + + /* Is it complete yet (is there a blank line)? */ + if (strstr (buf, "\r\r") || strstr (buf, "\n\n") || + strstr (buf, "\r\n\r\n") || strstr (buf, "\n\r\n\r")) + break; + } + + + /* Process the request. */ +if(rfbScreen->httpEnableProxyConnect) { + const static char* PROXY_OK_STR = "HTTP/1.0 200 OK\r\nContent-Type: octet-stream\r\nPragma: no-cache\r\n\r\n"; + if(!strncmp(buf, "CONNECT ", 8)) { + char *colon = strchr(buf, ':'); + if(colon == NULL || atoi(colon+1)!=rfbScreen->port) { + rfbErr("httpd: CONNECT format invalid.\n"); + rfbWriteExact(&cl,INVALID_REQUEST_STR, strlen(INVALID_REQUEST_STR)); + httpCloseSock(rfbScreen); + return; + } + /* proxy connection */ + rfbLog("httpd: client asked for CONNECT\n"); + rfbWriteExact(&cl,PROXY_OK_STR,strlen(PROXY_OK_STR)); + rfbNewClientConnection(rfbScreen,rfbScreen->httpSock); + rfbScreen->httpSock = RFB_INVALID_SOCKET; + return; + } + if (!strncmp(buf, "GET ",4)) { + char *slash = strchr(buf, '/'); + if (slash != NULL && !strncmp(slash,"/proxied.connection HTTP/1.", 27)) { + /* proxy connection */ + rfbLog("httpd: client asked for /proxied.connection\n"); + rfbWriteExact(&cl,PROXY_OK_STR,strlen(PROXY_OK_STR)); + rfbNewClientConnection(rfbScreen,rfbScreen->httpSock); + rfbScreen->httpSock = RFB_INVALID_SOCKET; + return; + } + } + } + + if (strncmp(buf, "GET ", 4)) { + rfbErr("httpd: no GET line\n"); + httpCloseSock(rfbScreen); + return; + } else { + /* Only use the first line. */ + buf[strcspn(buf, "\n\r")] = '\0'; + } + + if (strlen(buf) > maxFnameLen) { + rfbErr("httpd: GET line too long\n"); + httpCloseSock(rfbScreen); + return; + } + + if (sscanf(buf, "GET %s HTTP/1.", fname) != 1) { + rfbErr("httpd: couldn't parse GET line\n"); + httpCloseSock(rfbScreen); + return; + } + + if (fname[0] != '/') { + rfbErr("httpd: filename didn't begin with '/'\n"); + rfbWriteExact(&cl, NOT_FOUND_STR, strlen(NOT_FOUND_STR)); + httpCloseSock(rfbScreen); + return; + } + + + getpeername(rfbScreen->httpSock, (struct sockaddr *)&addr, &addrlen); +#ifdef LIBVNCSERVER_IPv6 + { + char host[1024]; + if(getnameinfo((struct sockaddr*)&addr, addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST) != 0) { + rfbLogPerror("httpProcessInput: error in getnameinfo"); + } + rfbLog("httpd: get '%s' for %s\n", fname+1, host); + } +#else + rfbLog("httpd: get '%s' for %s\n", fname+1, + inet_ntoa(addr.sin_addr)); +#endif + + /* Extract parameters from the URL string if necessary */ + + params[0] = '\0'; + ptr = strchr(fname, '?'); + if (ptr != NULL) { + *ptr = '\0'; + if (!parseParams(&ptr[1], params, 1024)) { + params[0] = '\0'; + rfbErr("httpd: bad parameters in the URL\n"); + } + } + + /* Basic protection against directory traversal outside webroot */ + + if (strstr(fname, "..")) { + rfbErr("httpd: URL should not contain '..'\n"); + rfbWriteExact(&cl, NOT_FOUND_STR, strlen(NOT_FOUND_STR)); + httpCloseSock(rfbScreen); + return; + } + + /* If we were asked for '/', actually read the file index.vnc */ + + if (strcmp(fname, "/") == 0) { + strcpy(fname, "/index.vnc"); + rfbLog("httpd: defaulting to '%s'\n", fname+1); + } + + /* Substitutions are performed on files ending .vnc */ + + if (strlen(fname) >= 4 && strcmp(&fname[strlen(fname)-4], ".vnc") == 0) { + performSubstitutions = TRUE; + } + + /* Open the file */ + + if ((fd = fopen(fullFname, "r")) == 0) { + rfbLogPerror("httpProcessInput: open"); + rfbWriteExact(&cl, NOT_FOUND_STR, strlen(NOT_FOUND_STR)); + httpCloseSock(rfbScreen); + return; + } + + rfbWriteExact(&cl, OK_STR, strlen(OK_STR)); + char *ext = strrchr(fname, '.'); + char *contentType = ""; + if(ext && strcasecmp(ext, ".vnc") == 0) + contentType = "Content-Type: text/html\r\n"; + else if(ext && strcasecmp(ext, ".css") == 0) + contentType = "Content-Type: text/css\r\n"; + else if(ext && strcasecmp(ext, ".svg") == 0) + contentType = "Content-Type: image/svg+xml\r\n"; + else if(ext && strcasecmp(ext, ".js") == 0) + contentType = "Content-Type: application/javascript\r\n"; + rfbWriteExact(&cl, contentType, strlen(contentType)); + /* end the header */ + rfbWriteExact(&cl, "\r\n", 2); + + while (1) { + int n = fread(buf, 1, BUF_SIZE-1, fd); + if (n < 0) { + rfbLogPerror("httpProcessInput: read"); + fclose(fd); + httpCloseSock(rfbScreen); + return; + } + + if (n == 0) + break; + + if (performSubstitutions) { + + /* Substitute $WIDTH, $HEIGHT, etc with the appropriate values. + This won't quite work properly if the .vnc file is longer than + BUF_SIZE, but it's reasonable to assume that .vnc files will + always be short. */ + + char *ptr = buf; + char *dollar; + buf[n] = 0; /* make sure it's null-terminated */ + + while ((dollar = strchr(ptr, '$'))!=NULL) { + rfbWriteExact(&cl, ptr, (dollar - ptr)); + + ptr = dollar; + + if (compareAndSkip(&ptr, "$WIDTH")) { + + sprintf(str, "%d", rfbScreen->width); + rfbWriteExact(&cl, str, strlen(str)); + + } else if (compareAndSkip(&ptr, "$HEIGHT")) { + + sprintf(str, "%d", rfbScreen->height); + rfbWriteExact(&cl, str, strlen(str)); + + } else if (compareAndSkip(&ptr, "$APPLETWIDTH")) { + + sprintf(str, "%d", rfbScreen->width); + rfbWriteExact(&cl, str, strlen(str)); + + } else if (compareAndSkip(&ptr, "$APPLETHEIGHT")) { + + sprintf(str, "%d", rfbScreen->height + 32); + rfbWriteExact(&cl, str, strlen(str)); + + } else if (compareAndSkip(&ptr, "$PORT")) { + + sprintf(str, "%d", rfbScreen->port); + rfbWriteExact(&cl, str, strlen(str)); + + } else if (compareAndSkip(&ptr, "$DESKTOP")) { + + rfbWriteExact(&cl, rfbScreen->desktopName, strlen(rfbScreen->desktopName)); + + } else if (compareAndSkip(&ptr, "$DISPLAY")) { + + sprintf(str, "%s:%d", rfbScreen->thisHost, rfbScreen->port-5900); + rfbWriteExact(&cl, str, strlen(str)); + + } else if (compareAndSkip(&ptr, "$USER")) { +#ifndef WIN32 + if (user) { + rfbWriteExact(&cl, user, + strlen(user)); + } else +#endif + rfbWriteExact(&cl, "?", 1); + } else if (compareAndSkip(&ptr, "$PARAMS")) { + if (params[0] != '\0') + rfbWriteExact(&cl, params, strlen(params)); + } else { + if (!compareAndSkip(&ptr, "$$")) + ptr++; + + if (rfbWriteExact(&cl, "$", 1) < 0) { + fclose(fd); + httpCloseSock(rfbScreen); + return; + } + } + } + if (rfbWriteExact(&cl, ptr, (&buf[n] - ptr)) < 0) + break; + + } else { + + /* For files not ending .vnc, just write out the buffer + +// ... (112 more chars) +``` diff --git a/tasks/csa159/pair_138203/pre_functions.txt b/tasks/csa159/pair_138203/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..1e20755d06a612a553e2d4cc7f96298ae971ef91 --- /dev/null +++ b/tasks/csa159/pair_138203/pre_functions.txt @@ -0,0 +1,303 @@ +### File: src/libvncserver/httpd.c +```c +static void +httpProcessInput(rfbScreenInfoPtr rfbScreen) +{ +#ifdef LIBVNCSERVER_IPv6 + struct sockaddr_storage addr; +#else + struct sockaddr_in addr; +#endif + socklen_t addrlen = sizeof(addr); + char fullFname[512]; + char params[1024]; + char *ptr; + char *fname; + unsigned int maxFnameLen; + FILE* fd; + rfbBool performSubstitutions = FALSE; + char str[256+32]; +#ifndef WIN32 + char* user=getenv("USER"); +#endif + + cl.sock=rfbScreen->httpSock; + + if (strlen(rfbScreen->httpDir) > 255) { + rfbErr("-httpd directory too long\n"); + httpCloseSock(rfbScreen); + return; + } + strcpy(fullFname, rfbScreen->httpDir); + fname = &fullFname[strlen(fullFname)]; + maxFnameLen = 511 - strlen(fullFname); + + buf_filled=0; + + /* Read data from the HTTP client until we get a complete request. */ + while (1) { + ssize_t got; + + if (buf_filled > sizeof (buf)) { + rfbErr("httpProcessInput: HTTP request is too long\n"); + httpCloseSock(rfbScreen); + return; + } + + got = read (rfbScreen->httpSock, buf + buf_filled, + sizeof (buf) - buf_filled - 1); + + if (got <= 0) { + if (got == 0) { + rfbErr("httpd: premature connection close\n"); + } else { +#ifdef WIN32 + errno=WSAGetLastError(); +#endif + if (errno == EAGAIN) { + return; + } + rfbLogPerror("httpProcessInput: read"); + } + httpCloseSock(rfbScreen); + return; + } + + buf_filled += got; + buf[buf_filled] = '\0'; + + /* Is it complete yet (is there a blank line)? */ + if (strstr (buf, "\r\r") || strstr (buf, "\n\n") || + strstr (buf, "\r\n\r\n") || strstr (buf, "\n\r\n\r")) + break; + } + + + /* Process the request. */ + if(rfbScreen->httpEnableProxyConnect) { + const static char* PROXY_OK_STR = "HTTP/1.0 200 OK\r\nContent-Type: octet-stream\r\nPragma: no-cache\r\n\r\n"; + if(!strncmp(buf, "CONNECT ", 8)) { + if(atoi(strchr(buf, ':')+1)!=rfbScreen->port) { + rfbErr("httpd: CONNECT format invalid.\n"); + rfbWriteExact(&cl,INVALID_REQUEST_STR, strlen(INVALID_REQUEST_STR)); + httpCloseSock(rfbScreen); + return; + } + /* proxy connection */ + rfbLog("httpd: client asked for CONNECT\n"); + rfbWriteExact(&cl,PROXY_OK_STR,strlen(PROXY_OK_STR)); + rfbNewClientConnection(rfbScreen,rfbScreen->httpSock); + rfbScreen->httpSock = RFB_INVALID_SOCKET; + return; + } + if (!strncmp(buf, "GET ",4) && !strncmp(strchr(buf,'/'),"/proxied.connection HTTP/1.", 27)) { + /* proxy connection */ + rfbLog("httpd: client asked for /proxied.connection\n"); + rfbWriteExact(&cl,PROXY_OK_STR,strlen(PROXY_OK_STR)); + rfbNewClientConnection(rfbScreen,rfbScreen->httpSock); + rfbScreen->httpSock = RFB_INVALID_SOCKET; + return; + } + } + + if (strncmp(buf, "GET ", 4)) { + rfbErr("httpd: no GET line\n"); + httpCloseSock(rfbScreen); + return; + } else { + /* Only use the first line. */ + buf[strcspn(buf, "\n\r")] = '\0'; + } + + if (strlen(buf) > maxFnameLen) { + rfbErr("httpd: GET line too long\n"); + httpCloseSock(rfbScreen); + return; + } + + if (sscanf(buf, "GET %s HTTP/1.", fname) != 1) { + rfbErr("httpd: couldn't parse GET line\n"); + httpCloseSock(rfbScreen); + return; + } + + if (fname[0] != '/') { + rfbErr("httpd: filename didn't begin with '/'\n"); + rfbWriteExact(&cl, NOT_FOUND_STR, strlen(NOT_FOUND_STR)); + httpCloseSock(rfbScreen); + return; + } + + + getpeername(rfbScreen->httpSock, (struct sockaddr *)&addr, &addrlen); +#ifdef LIBVNCSERVER_IPv6 + { + char host[1024]; + if(getnameinfo((struct sockaddr*)&addr, addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST) != 0) { + rfbLogPerror("httpProcessInput: error in getnameinfo"); + } + rfbLog("httpd: get '%s' for %s\n", fname+1, host); + } +#else + rfbLog("httpd: get '%s' for %s\n", fname+1, + inet_ntoa(addr.sin_addr)); +#endif + + /* Extract parameters from the URL string if necessary */ + + params[0] = '\0'; + ptr = strchr(fname, '?'); + if (ptr != NULL) { + *ptr = '\0'; + if (!parseParams(&ptr[1], params, 1024)) { + params[0] = '\0'; + rfbErr("httpd: bad parameters in the URL\n"); + } + } + + /* Basic protection against directory traversal outside webroot */ + + if (strstr(fname, "..")) { + rfbErr("httpd: URL should not contain '..'\n"); + rfbWriteExact(&cl, NOT_FOUND_STR, strlen(NOT_FOUND_STR)); + httpCloseSock(rfbScreen); + return; + } + + /* If we were asked for '/', actually read the file index.vnc */ + + if (strcmp(fname, "/") == 0) { + strcpy(fname, "/index.vnc"); + rfbLog("httpd: defaulting to '%s'\n", fname+1); + } + + /* Substitutions are performed on files ending .vnc */ + + if (strlen(fname) >= 4 && strcmp(&fname[strlen(fname)-4], ".vnc") == 0) { + performSubstitutions = TRUE; + } + + /* Open the file */ + + if ((fd = fopen(fullFname, "r")) == 0) { + rfbLogPerror("httpProcessInput: open"); + rfbWriteExact(&cl, NOT_FOUND_STR, strlen(NOT_FOUND_STR)); + httpCloseSock(rfbScreen); + return; + } + + rfbWriteExact(&cl, OK_STR, strlen(OK_STR)); + char *ext = strrchr(fname, '.'); + char *contentType = ""; + if(ext && strcasecmp(ext, ".vnc") == 0) + contentType = "Content-Type: text/html\r\n"; + else if(ext && strcasecmp(ext, ".css") == 0) + contentType = "Content-Type: text/css\r\n"; + else if(ext && strcasecmp(ext, ".svg") == 0) + contentType = "Content-Type: image/svg+xml\r\n"; + else if(ext && strcasecmp(ext, ".js") == 0) + contentType = "Content-Type: application/javascript\r\n"; + rfbWriteExact(&cl, contentType, strlen(contentType)); + /* end the header */ + rfbWriteExact(&cl, "\r\n", 2); + + while (1) { + int n = fread(buf, 1, BUF_SIZE-1, fd); + if (n < 0) { + rfbLogPerror("httpProcessInput: read"); + fclose(fd); + httpCloseSock(rfbScreen); + return; + } + + if (n == 0) + break; + + if (performSubstitutions) { + + /* Substitute $WIDTH, $HEIGHT, etc with the appropriate values. + This won't quite work properly if the .vnc file is longer than + BUF_SIZE, but it's reasonable to assume that .vnc files will + always be short. */ + + char *ptr = buf; + char *dollar; + buf[n] = 0; /* make sure it's null-terminated */ + + while ((dollar = strchr(ptr, '$'))!=NULL) { + rfbWriteExact(&cl, ptr, (dollar - ptr)); + + ptr = dollar; + + if (compareAndSkip(&ptr, "$WIDTH")) { + + sprintf(str, "%d", rfbScreen->width); + rfbWriteExact(&cl, str, strlen(str)); + + } else if (compareAndSkip(&ptr, "$HEIGHT")) { + + sprintf(str, "%d", rfbScreen->height); + rfbWriteExact(&cl, str, strlen(str)); + + } else if (compareAndSkip(&ptr, "$APPLETWIDTH")) { + + sprintf(str, "%d", rfbScreen->width); + rfbWriteExact(&cl, str, strlen(str)); + + } else if (compareAndSkip(&ptr, "$APPLETHEIGHT")) { + + sprintf(str, "%d", rfbScreen->height + 32); + rfbWriteExact(&cl, str, strlen(str)); + + } else if (compareAndSkip(&ptr, "$PORT")) { + + sprintf(str, "%d", rfbScreen->port); + rfbWriteExact(&cl, str, strlen(str)); + + } else if (compareAndSkip(&ptr, "$DESKTOP")) { + + rfbWriteExact(&cl, rfbScreen->desktopName, strlen(rfbScreen->desktopName)); + + } else if (compareAndSkip(&ptr, "$DISPLAY")) { + + sprintf(str, "%s:%d", rfbScreen->thisHost, rfbScreen->port-5900); + rfbWriteExact(&cl, str, strlen(str)); + + } else if (compareAndSkip(&ptr, "$USER")) { +#ifndef WIN32 + if (user) { + rfbWriteExact(&cl, user, + strlen(user)); + } else +#endif + rfbWriteExact(&cl, "?", 1); + } else if (compareAndSkip(&ptr, "$PARAMS")) { + if (params[0] != '\0') + rfbWriteExact(&cl, params, strlen(params)); + } else { + if (!compareAndSkip(&ptr, "$$")) + ptr++; + + if (rfbWriteExact(&cl, "$", 1) < 0) { + fclose(fd); + httpCloseSock(rfbScreen); + return; + } + } + } + if (rfbWriteExact(&cl, ptr, (&buf[n] - ptr)) < 0) + break; + + } else { + + /* For files not ending .vnc, just write out the buffer */ + + if (rfbWriteExact(&cl, buf, n) < 0) + break; + } + } + + fclose(f + +// ... (35 more chars) +``` diff --git a/tasks/csa159/pair_138203/task_prompt.md b/tasks/csa159/pair_138203/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..d308e8d166eba1d916d382a8b2da6ac8545d2f4c --- /dev/null +++ b/tasks/csa159/pair_138203/task_prompt.md @@ -0,0 +1,372 @@ +# 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 the rollout used path-sensitive ProgramState tracking (PostCall/PreCall/BranchCondition/DeadSymbols plus UncheckedSearchPtrs) when the defect is a same-expression AST nesting of a nullable search call under a libc dereference sink. +- refinement_accepted failed: refinement ran one round and ended feedback_required/not_converged rather than accepted/clean, so the mechanism was never refined down to the required syntax-only level. +- BranchCondition removal applied to both successors before the CFG split, so the prior design never proved that a user NULL test rejects only the NULL path at the sink. +- Constraint queries (State->isNull/isNonNull) cannot stand in for a missing user check because CStringChecker already constrains strchr-family results, which is why constraint-only discrimination was already rejected. + +### 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 only when a CallExpr to a NULL-returning C search function (strchr, strrchr, strstr, strcasestr, strpbrk, memchr, memrchr, index, rindex) is a subexpression of a pointer argument to a dereferencing libc sink (atoi/atol/atoll/atof, strncmp/strcmp/strcasecmp, strlen, strcpy/memcpy, and similar), including through ImplicitCastExpr, ParenExpr, and additive pointer arithmetic such as strchr(buf,':')+1. +- The two LibVNC httpProcessInput proxy defects must match that nesting: atoi(strchr(buf, ':')+1) on the CONNECT path and strncmp(strchr(buf, '/'), ...) on the GET /proxied.connection path, with no NULL test of that same search CallExpr in the enclosing expression. +- Treat the patched form as safe because the search CallExpr is no longer nested under the sink: colon/slash are separate statements and the sink appears only beside colon == NULL || atoi(colon+1) or slash != NULL && strncmp(slash, ...). + +### Implementation constraints + +- Implement with an AST-local callback (checkASTCodeBody, RecursiveASTVisitor, or equivalent CallExpr walk). Do not use ProgramState, REGISTER_SET_WITH_PROGRAMSTATE, or path-sensitive check::PostCall/PreCall/BranchCondition/DeadSymbols as the reporting mechanism. +- Identify sources and sinks by FunctionDecl name on general libc APIs; walk child expressions of each sink argument to find a nested search CallExpr, looking through casts, parentheses, and +/- pointer arithmetic. +- Emit the diagnostic at the sink CallExpr (or the nested search subexpression) SourceRange inside the using function so both httpProcessInput sites are local to the patched spans. +- Keep scope project_general: any C/C++ translation unit, no hardcoded file paths, function names, line numbers, or request-string literals from httpd.c. +- Register a named checker via clang_registerCheckers, compile as an LLVM 18 plugin with -fno-rtti, and do not depend on CStringChecker constraints to decide whether a user wrote a NULL check. + +### Validation checklist + +- bash compile.sh must produce checker.so with a clean build. +- CHECKER_NAME= bash scan/scan_before.sh must yield exactly two warnings, both in src/libvncserver/httpd.c::httpProcessInput, one on atoi(strchr(buf, ':')+1) and one on strncmp(strchr(buf, '/'), ...). +- CHECKER_NAME= bash scan/scan_after.sh must yield zero warnings after the colon/slash NULL guards. +- Code verification must keep n_buggy=2, n_patched=0, warnings_near_patch=2, median_distance_lines=0, relevance_ratio=1.0, and no reports outside httpProcessInput. +- The same function must stay clean on already-guarded non-nested uses: ptr = strchr(fname, '?') with ptr != NULL, while ((dollar = strchr(ptr, '$')) != NULL), and ext && strcasecmp(ext, ...). +- Refinement must finish accepted/clean, and semantic_mechanism must classify the checker as syntax_only rather than path-sensitive overkill. + +### Avoid and forbidden regressions + +- Do not rebuild detection around UncheckedSearchPtrs, check::PostCall/PreCall/BranchCondition/DeadSymbols, eval::Assume, or State->isNull/isNonNull. +- Do not treat analyzer-internal branches or CStringChecker non-null constraints as user-written NULL checks. +- Do not hardcode httpd.c, httpProcessInput, CONNECT/GET literals, /proxied.connection, or patch line numbers. +- Do not report core.NullDereference-style *p, unmodelled project-local callees (parseParams, compareAndSkip, rfbWriteExact), or the strchr call when it is not nested under a listed sink. +- Do not copy, resume, or reconstruct the prior SearchResultNullDerefChecker, and do not leave refinement in feedback_required. diff --git a/tasks/csa159/pair_138249/checker_template.cpp b/tasks/csa159/pair_138249/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138249/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_138249/config.json b/tasks/csa159/pair_138249/config.json new file mode 100644 index 0000000000000000000000000000000000000000..cb16adad828be8ebbc85b965609500d5d41399b2 --- /dev/null +++ b/tasks/csa159/pair_138249/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "LibreDWG_libredwg", + "before_commit": "5c19f597ca87363be1bcaf5d7fa06942120a8280", + "after_commit": "fc8c16ccf36dd4d7168231a66489a904a142059c", + "repo_path": "/workspace/repo/LibreDWG/libredwg", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/LibreDWG_libredwg/a75b8ff1d13cfe28ec3b86b82b22082a82e8d519/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/LibreDWG_libredwg/a75b8ff1d13cfe28ec3b86b82b22082a82e8d519/compile_commands.json", + "changed_files": [ + "src/decode_r2007.c" + ], + "commit_message": "add r2007 Page out of bounds check\n\nFixes case 1 of GH #179", + "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_138249/patch.diff b/tasks/csa159/pair_138249/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b9812b9ac92824d807c2b7c87ef24c6f364bc6dd --- /dev/null +++ b/tasks/csa159/pair_138249/patch.diff @@ -0,0 +1,18 @@ +diff --git a/src/decode_r2007.c b/src/decode_r2007.c +index 9e821d3f..5a7449d8 100644 +--- a/src/decode_r2007.c ++++ b/src/decode_r2007.c +@@ -1010,6 +1010,13 @@ read_pages_map (Bit_Chain *dat, int64_t size_comp, int64_t size_uncomp, + pages_destroy (pages); + return NULL; + } ++ if (ptr + 16 > ptr_end) ++ { ++ LOG_ERROR ("Page out of bounds") ++ free (data); ++ pages_destroy (pages); ++ return NULL; ++ } + + page->size = bfr_read_uint64 (ptr); + page->id = bfr_read_int64 (ptr); \ No newline at end of file diff --git a/tasks/csa159/pair_138249/post_functions.txt b/tasks/csa159/pair_138249/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..5749215f4b7d6722f34bc54d9e6f5bc121c163b8 --- /dev/null +++ b/tasks/csa159/pair_138249/post_functions.txt @@ -0,0 +1,67 @@ +### File: src/decode_r2007.c +```c +static r2007_page * +read_pages_map (Bit_Chain *dat, int64_t size_comp, int64_t size_uncomp, + int64_t correction) +{ + BITCODE_RC *data, *ptr, *ptr_end; + r2007_page *pages = NULL, *last_page = NULL, *page; + int64_t offset = 0x480; // dat->byte; + // int64_t index; + + data = read_system_page (dat, size_comp, size_uncomp, correction); + if (!data) + { + LOG_ERROR ("Failed to read system page") + return NULL; + } + + ptr = data; + ptr_end = data + size_uncomp; + + LOG_TRACE ("\n=== System Section (Pages Map) ===\n") + + while (ptr < ptr_end) + { + page = (r2007_page *)malloc (sizeof (r2007_page)); + if (page == NULL) + { + LOG_ERROR ("Out of memory") + free (data); + pages_destroy (pages); + return NULL; + } + if (ptr + 16 > ptr_end) + { + LOG_ERROR ("Page out of bounds") + free (data); + pages_destroy (pages); + return NULL; + } + + page->size = bfr_read_uint64 (ptr); + page->id = bfr_read_int64 (ptr); + page->offset = offset; + offset += page->size; + + // index = page->id > 0 ? page->id : -page->id; + + LOG_TRACE ("Page [%3" PRId64 "]: ", page->id) + LOG_TRACE ("size: %6" PRIu64 " ", page->size) + LOG_TRACE ("id: 0x%04" PRIx64 " ", page->id) + LOG_TRACE ("offset: 0x%" PRIx64 " \n", page->offset) + + page->next = NULL; + + if (pages == NULL) + pages = last_page = page; + else + { + last_page->next = page; + last_page = page; + } + } + free (data); + return pages; +} +``` diff --git a/tasks/csa159/pair_138249/pre_functions.txt b/tasks/csa159/pair_138249/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..ee50884b1caee680fe83bb492625eade6ec1da98 --- /dev/null +++ b/tasks/csa159/pair_138249/pre_functions.txt @@ -0,0 +1,60 @@ +### File: src/decode_r2007.c +```c +static r2007_page * +read_pages_map (Bit_Chain *dat, int64_t size_comp, int64_t size_uncomp, + int64_t correction) +{ + BITCODE_RC *data, *ptr, *ptr_end; + r2007_page *pages = NULL, *last_page = NULL, *page; + int64_t offset = 0x480; // dat->byte; + // int64_t index; + + data = read_system_page (dat, size_comp, size_uncomp, correction); + if (!data) + { + LOG_ERROR ("Failed to read system page") + return NULL; + } + + ptr = data; + ptr_end = data + size_uncomp; + + LOG_TRACE ("\n=== System Section (Pages Map) ===\n") + + while (ptr < ptr_end) + { + page = (r2007_page *)malloc (sizeof (r2007_page)); + if (page == NULL) + { + LOG_ERROR ("Out of memory") + free (data); + pages_destroy (pages); + return NULL; + } + + page->size = bfr_read_uint64 (ptr); + page->id = bfr_read_int64 (ptr); + page->offset = offset; + offset += page->size; + + // index = page->id > 0 ? page->id : -page->id; + + LOG_TRACE ("Page [%3" PRId64 "]: ", page->id) + LOG_TRACE ("size: %6" PRIu64 " ", page->size) + LOG_TRACE ("id: 0x%04" PRIx64 " ", page->id) + LOG_TRACE ("offset: 0x%" PRIx64 " \n", page->offset) + + page->next = NULL; + + if (pages == NULL) + pages = last_page = page; + else + { + last_page->next = page; + last_page = page; + } + } + free (data); + return pages; +} +``` diff --git a/tasks/csa159/pair_138249/task_prompt.md b/tasks/csa159/pair_138249/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cdff61627a95da704aba937199414908528fac39 --- /dev/null +++ b/tasks/csa159/pair_138249/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 passed compilation, differential scanning, objective eligibility, and code verification, but failed the process-score threshold. +- The semantic result was only partial because it associated any same-base pointer comparison with a reusable bound, rather than proving that the comparison represented the actual buffer end. +- For a guard such as ptr + 16 > ptr_end, recording the higher-address operand as the end can produce an unsound bound and suppress unsafe accesses in other code. +- The checker reports a broad class of unproven wide dereferences rather than specifically establishing the two-read, 16-byte page-record relation. +- Detection depends on bfr_read_uint64 and bfr_read_int64 exposing dereference AST nodes through macros or analyzer inlining, so opaque calls can cause the vulnerable source to be missed. + +### 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 path-sensitive CSA mechanism level already accepted as adequate. +- Preserve semantic performance at or above the configured threshold. +- Keep the checker project-general and independent of patch-local anchors. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Establish that a pointer is advanced within a bounded object and that a later multi-byte read consumes more bytes than the remaining valid range on a feasible execution path. +- Relate the exact access start and access size to the actual buffer-end fact, proving that access_start plus access_size is not constrained to be at or before the end. +- Prove that the patched early-return path dominates the reads and makes the unsafe condition infeasible, rather than suppressing the report because of a syntactically similar comparison. +- Model the two adjacent 8-byte reads as a 16-byte record requirement when the available evidence supports that relation, while retaining correct handling of individual wide accesses. +- Require the reported operation to be the concrete read whose bounds cannot be proved, and avoid treating unrelated wide integer dereferences as equivalent defects. + +### Implementation constraints + +- Use ProgramState to retain path-specific facts and ConstraintManager feasibility checks; syntax-only matching is insufficient. +- Use statement callbacks capable of observing both establishment of pointer bounds and the later dereference or read operation, including a supported path for reads that remain call expressions rather than exposed UnaryOperator nodes. +- Track the actual buffer-end relationship separately from a derived precondition such as pointer plus required bytes, and do not infer an end pointer merely from whichever comparison operand has the higher address. +- Associate bounds with stable analyzer memory regions and validated pointer-offset relationships, rejecting unknown or unrelated regions and offset computations. +- Suppress diagnostics only when the current path proves the complete access fits; report when the unsafe negation remains feasible. +- Emit the diagnostic at the concrete read operation with a concise out-of-bounds explanation and preserve project-general scope. +- Do not inspect patch-local names, literals, line numbers, source text, commit details, or the existence of the specific added guard. + +### Validation checklist + +- Compile the new checker successfully against the target Clang Static Analyzer API and retain code verification success. +- Run the before/after scan: detect both vulnerable wide reads in the original source and produce no reports in the patched source. +- Verify report locations are on the two read operations or their supported call-site equivalents and remain near the affected operations. +- Test a path with only a one-element pointer guard and confirm an 8-byte access remains reportable when insufficient bytes remain. +- Test guards proving exactly the required access size and proving the combined 16-byte record size, confirming that the corresponding unsafe paths are suppressed. +- Test a guard proving fewer bytes than an 8-byte read and confirm that the read is not incorrectly suppressed. +- Exercise unrelated same-base pointer comparisons and unrelated wide integer dereferences to check that they do not create false bounds or extra reports. +- Re-run refinement and confirm hard validation, objective eligibility, semantic mechanism, semantic score, anchor-free, hardcoding-free, and accepted-refinement checks remain satisfied. + +### Avoid and forbidden regressions + +- Do not downgrade the design to syntax-only or ordinary control-flow matching; the distinction between vulnerable and patched paths requires path constraints. +- Do not treat every same-base pointer comparison as evidence of a buffer boundary. +- Do not use the higher-address comparison operand as the buffer end without proving what that operand semantically represents. +- Do not rely exclusively on UnaryOperator dereference visibility when the relevant read may remain an opaque helper call. +- Do not report every feasible wide dereference associated with any recorded comparison as the target vulnerability. +- Do not hardcode the patched function, variable names, constants, source locations, macro names, or patch shape. +- Do not regress successful compilation, before/after differential results, G6 eligibility, accepted refinement, or the previously adequate path-sensitive mechanism. diff --git a/tasks/csa159/pair_138263/checker_template.cpp b/tasks/csa159/pair_138263/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138263/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_138263/config.json b/tasks/csa159/pair_138263/config.json new file mode 100644 index 0000000000000000000000000000000000000000..c36d0d4bf1c629dddfba22e116d5cb2b59c05586 --- /dev/null +++ b/tasks/csa159/pair_138263/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "LibreDWG_libredwg", + "before_commit": "8f03865f37f5d4ffd616fef802acc980be54d300", + "after_commit": "e501cb9926c1e9a07a0d1cc997f3e69e9be801c9", + "repo_path": "/workspace/repo/LibreDWG/libredwg", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/LibreDWG_libredwg/26b68f37c6de761e1ca603b5949c1610dc6e873a/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/LibreDWG_libredwg/26b68f37c6de761e1ca603b5949c1610dc6e873a/compile_commands.json", + "changed_files": [ + "src/decode.c" + ], + "commit_message": "decode: fix another decompression overflow\n\nsome regular overflow.\nFixes GH #1242, #1243, Thanks to HackC0der for some fuzzing", + "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_138263/patch.diff b/tasks/csa159/pair_138263/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a33a45b345fe3e72a8f207765862ffc0d20fdd6c --- /dev/null +++ b/tasks/csa159/pair_138263/patch.diff @@ -0,0 +1,19 @@ +diff --git a/src/decode.c b/src/decode.c +index fd8575ad..1bb48962 100644 +--- a/src/decode.c ++++ b/src/decode.c +@@ -1284,6 +1284,14 @@ decompress_R2004_section (Bit_Chain *restrict src, Bit_Chain *restrict dec) + opcode1 = 0x11; + LOG_INSANE (">O %x!\n", opcode1); + } ++ if (end > dec->size || (long)pos < comp_offset ++ || (size_t)(pos - comp_offset) >= dec->size ++ || (size_t)comp_offset > dec->size) ++ { ++ LOG_ERROR ("Invalid decompression bytes %d, offset %d", comp_bytes, ++ comp_offset); ++ return DWG_ERR_VALUEOUTOFBOUNDS; ++ } + // GH #1204: memmove is wrong here: when comp_offset < comp_bytes the + // source and destination overlap and newly-written bytes must be read + // back (LZ77 run-length extension). memmove copies from original bytes. \ No newline at end of file diff --git a/tasks/csa159/pair_138263/post_functions.txt b/tasks/csa159/pair_138263/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..7c02d87c83b0e7c2f3f600884ca65ac501b414b9 --- /dev/null +++ b/tasks/csa159/pair_138263/post_functions.txt @@ -0,0 +1,146 @@ +### File: src/decode.c +```c +int +decompress_R2004_section (Bit_Chain *restrict src, Bit_Chain *restrict dec) +{ + unsigned int lit_length; + int comp_offset, comp_bytes; + size_t pos, end; + unsigned char opcode1 = 0, opcode2; + + if (src->byte > src->size) // bytes left to read from + { + LOG_WARN ("Invalid comp_data_size %" PRIuSIZE " @%" PRIuSIZE, src->size, + src->byte); + return DWG_ERR_VALUEOUTOFBOUNDS; + } + // length of the first sequence of uncompressed or literal data. + // lit_length = read_literal_length (src, opcode1); + // LOG_INSANE ("L: %u\n", lit_length); + // if ((unsigned long)lit_length > dec->size) + // { + // LOG_ERROR ("Invalid literal_length %u > %lu dec.size", lit_length, + // dec->size) + // return DWG_ERR_VALUEOUTOFBOUNDS; + // } + // bit_read_fixed (src, dec->chain, lit_length); + // dec->byte += lit_length; + // bytes_left -= lit_length; + LOG_INSANE ("(%" PRIuSIZE ")\n", dec->byte); + + opcode1 = bit_read_RC (src); + if ((opcode1 & 0xF0) == 0) + opcode1 = copy_bytes (read_literal_length (src, opcode1), src, dec); + + while (src->byte < src->size && dec->byte < dec->size && opcode1 != 0x11) + { + LOG_INSANE ("\n(%" PRIuSIZE ") -O %x\n", dec->byte, opcode1); + comp_bytes = 0; + comp_offset = 0; + if (opcode1 < 0x10 || opcode1 >= 0x40) // oda has <0x10 as unused + { + comp_bytes = (opcode1 >> 4) - 1; + opcode2 = bit_read_RC (src); + LOG_INSANE ("> 2) & 3) | (opcode2 << 2)) + 1; + LOG_INSANE ("o: %d %d\n", comp_bytes, comp_offset); + } + else if (opcode1 < 0x20) // 0x12-0x1f + { + comp_bytes = read_compressed_bytes (src, opcode1, 7); + comp_offset = (opcode1 & 8) << 11; + opcode1 = two_byte_offset (src, 0x4000, &comp_offset); + LOG_INSANE ("= 0x20) + { + comp_bytes = read_compressed_bytes (src, opcode1, 0x1f); + opcode1 = two_byte_offset (src, 1, &comp_offset); + LOG_INSANE ("O %x!\n", opcode1); + break; // Terminates the input stream, everything is ok + } + else + { + LOG_ERROR ("Invalid opcode 0x%x in input stream at pos %" PRIuSIZE, + opcode1, src->byte); + return DWG_ERR_INTERNALERROR; // error in input stream + } + // copy previous offset'ed bytes. + pos = dec->byte; + LOG_INSANE ("co: %d %ld->%" PRIuSIZE "\n", comp_bytes, + (long)pos - comp_offset, pos); + // This seems to be a comp_bytes encoding bug, + // copying past the decompressed_size. rather cap it and stop + // decompression. ACadSharp decompresses all comp_bytes, enlarging the + // buffer (but not using it) + end = pos + comp_bytes; + if (end >= dec->size) + { + LOG_TRACE ("decompress oob: %" PRIuSIZE " >= %" PRIuSIZE "\n", end, + dec->size); + // bit_chain_alloc_size (dec, pos + comp_bytes); + comp_bytes = (int)(dec->size - pos); + end = pos + comp_bytes; + opcode1 = 0x11; + LOG_INSANE (">O %x!\n", opcode1); + } + if (end > dec->size || (long)pos < comp_offset + || (size_t)(pos - comp_offset) >= dec->size + || (size_t)comp_offset > dec->size) + { + LOG_ERROR ("Invalid decompression bytes %d, offset %d", comp_bytes, + comp_offset); + return DWG_ERR_VALUEOUTOFBOUNDS; + } + // GH #1204: memmove is wrong here: when comp_offset < comp_bytes the + // source and destination overlap and newly-written bytes must be read + // back (LZ77 run-length extension). memmove copies from original bytes. + for (; pos < end; pos++) + { +#ifndef NDEBUG + assert ((long)pos >= (long)comp_offset); + assert (pos - comp_offset < dec->size); + assert (pos < dec->size); +#endif + dec->chain[pos] = dec->chain[pos - comp_offset]; + } + dec->byte = end; + // copy "literal data" + lit_length = opcode1 & 3; + if (lit_length == 0) + { + opcode1 = bit_read_RC (src); + LOG_INSANE ("size) + { + opcode1 = copy_bytes (lit_length, src, dec); + LOG_INSANE ("= DWG_LOGLEVEL_INSANE) + { + static int ctr = 0; + char out[80]; + FILE *fp; + snprintf (out, 80, "decomp_%u.bin", ctr++); + fp = fopen (out, "wb"); + fwrite (dec->chain, 1, dec->size, fp); + fclose (fp); + } +#endif + return 0; // Success +} +``` diff --git a/tasks/csa159/pair_138263/pre_functions.txt b/tasks/csa159/pair_138263/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..8859a56319cb763919c32a93e95baf39d46cfc50 --- /dev/null +++ b/tasks/csa159/pair_138263/pre_functions.txt @@ -0,0 +1,138 @@ +### File: src/decode.c +```c +int +decompress_R2004_section (Bit_Chain *restrict src, Bit_Chain *restrict dec) +{ + unsigned int lit_length; + int comp_offset, comp_bytes; + size_t pos, end; + unsigned char opcode1 = 0, opcode2; + + if (src->byte > src->size) // bytes left to read from + { + LOG_WARN ("Invalid comp_data_size %" PRIuSIZE " @%" PRIuSIZE, src->size, + src->byte); + return DWG_ERR_VALUEOUTOFBOUNDS; + } + // length of the first sequence of uncompressed or literal data. + // lit_length = read_literal_length (src, opcode1); + // LOG_INSANE ("L: %u\n", lit_length); + // if ((unsigned long)lit_length > dec->size) + // { + // LOG_ERROR ("Invalid literal_length %u > %lu dec.size", lit_length, + // dec->size) + // return DWG_ERR_VALUEOUTOFBOUNDS; + // } + // bit_read_fixed (src, dec->chain, lit_length); + // dec->byte += lit_length; + // bytes_left -= lit_length; + LOG_INSANE ("(%" PRIuSIZE ")\n", dec->byte); + + opcode1 = bit_read_RC (src); + if ((opcode1 & 0xF0) == 0) + opcode1 = copy_bytes (read_literal_length (src, opcode1), src, dec); + + while (src->byte < src->size && dec->byte < dec->size && opcode1 != 0x11) + { + LOG_INSANE ("\n(%" PRIuSIZE ") -O %x\n", dec->byte, opcode1); + comp_bytes = 0; + comp_offset = 0; + if (opcode1 < 0x10 || opcode1 >= 0x40) // oda has <0x10 as unused + { + comp_bytes = (opcode1 >> 4) - 1; + opcode2 = bit_read_RC (src); + LOG_INSANE ("> 2) & 3) | (opcode2 << 2)) + 1; + LOG_INSANE ("o: %d %d\n", comp_bytes, comp_offset); + } + else if (opcode1 < 0x20) // 0x12-0x1f + { + comp_bytes = read_compressed_bytes (src, opcode1, 7); + comp_offset = (opcode1 & 8) << 11; + opcode1 = two_byte_offset (src, 0x4000, &comp_offset); + LOG_INSANE ("= 0x20) + { + comp_bytes = read_compressed_bytes (src, opcode1, 0x1f); + opcode1 = two_byte_offset (src, 1, &comp_offset); + LOG_INSANE ("O %x!\n", opcode1); + break; // Terminates the input stream, everything is ok + } + else + { + LOG_ERROR ("Invalid opcode 0x%x in input stream at pos %" PRIuSIZE, + opcode1, src->byte); + return DWG_ERR_INTERNALERROR; // error in input stream + } + // copy previous offset'ed bytes. + pos = dec->byte; + LOG_INSANE ("co: %d %ld->%" PRIuSIZE "\n", comp_bytes, + (long)pos - comp_offset, pos); + // This seems to be a comp_bytes encoding bug, + // copying past the decompressed_size. rather cap it and stop + // decompression. ACadSharp decompresses all comp_bytes, enlarging the + // buffer (but not using it) + end = pos + comp_bytes; + if (end >= dec->size) + { + LOG_TRACE ("decompress oob: %" PRIuSIZE " >= %" PRIuSIZE "\n", end, + dec->size); + // bit_chain_alloc_size (dec, pos + comp_bytes); + comp_bytes = (int)(dec->size - pos); + end = pos + comp_bytes; + opcode1 = 0x11; + LOG_INSANE (">O %x!\n", opcode1); + } + // GH #1204: memmove is wrong here: when comp_offset < comp_bytes the + // source and destination overlap and newly-written bytes must be read + // back (LZ77 run-length extension). memmove copies from original bytes. + for (; pos < end; pos++) + { +#ifndef NDEBUG + assert ((long)pos >= (long)comp_offset); + assert (pos - comp_offset < dec->size); + assert (pos < dec->size); +#endif + dec->chain[pos] = dec->chain[pos - comp_offset]; + } + dec->byte = end; + // copy "literal data" + lit_length = opcode1 & 3; + if (lit_length == 0) + { + opcode1 = bit_read_RC (src); + LOG_INSANE ("size) + { + opcode1 = copy_bytes (lit_length, src, dec); + LOG_INSANE ("= DWG_LOGLEVEL_INSANE) + { + static int ctr = 0; + char out[80]; + FILE *fp; + snprintf (out, 80, "decomp_%u.bin", ctr++); + fp = fopen (out, "wb"); + fwrite (dec->chain, 1, dec->size, fp); + fclose (fp); + } +#endif + return 0; // Success +} +``` diff --git a/tasks/csa159/pair_138263/task_prompt.md b/tasks/csa159/pair_138263/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_138263/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_138280/checker_template.cpp b/tasks/csa159/pair_138280/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138280/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_138280/config.json b/tasks/csa159/pair_138280/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0436b3484e901343b4975b7566ac14b2a0c3a1e3 --- /dev/null +++ b/tasks/csa159/pair_138280/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "LibreDWG_libredwg", + "before_commit": "cc9f02ac405fe8d53666984c87ac038e51c53285", + "after_commit": "9b6e0ff9ef02818df034fc42c3bd149a5ff89342", + "repo_path": "/workspace/repo/LibreDWG/libredwg", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/LibreDWG_libredwg/91fdb39d43d84e089ba00ea61f1ab87449d5f444/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/LibreDWG_libredwg/91fdb39d43d84e089ba00ea61f1ab87449d5f444/compile_commands.json", + "changed_files": [ + "src/encode.c" + ], + "commit_message": "encode: avoid hdl_dat double-free\n\nIn case of an handle overflow, such as num_reactors.\nFixes oss-fuzz issue 31724.", + "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_138280/patch.diff b/tasks/csa159/pair_138280/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7e1b6c31fbbba7310a3c1dec0c1fca5748a6e502 --- /dev/null +++ b/tasks/csa159/pair_138280/patch.diff @@ -0,0 +1,83 @@ +diff --git a/src/encode.c b/src/encode.c +index c555c8aa..4af17c62 100644 +--- a/src/encode.c ++++ b/src/encode.c +@@ -731,6 +731,7 @@ static bool env_var_checked_p; + obj_flush_hdlstream (obj, dat, &dat1); /* special accumulated */ \ + bit_chain_free (&dat1); \ + bit_chain_free (&dat2); \ ++ *hdl_dat = *dat; \ + hdl_dat = dat; \ + } \ + else \ +@@ -830,30 +831,35 @@ EXPORT long dwg_add_##token (Dwg_Data * dwg) \ + int error; \ + Bit_Chain _hdl_dat = { 0 }; \ + Bit_Chain *hdl_dat = &_hdl_dat; /* a new copy */ \ +- Bit_Chain *str_dat = dat; /* a ref */ \ ++ Bit_Chain *str_dat = dat; /* a ref */ \ + LOG_INFO ("Encode entity " #token "\n"); \ + bit_chain_init_dat (hdl_dat, 128, dat); \ + error = dwg_encode_entity (obj, dat, hdl_dat, str_dat); \ + if (error) \ + { \ +- if (hdl_dat != dat) \ ++ LOG_HANDLE ("Early DWG_ENTITY exit\n"); \ ++ if (hdl_dat != dat && hdl_dat->chain != dat->chain) \ + bit_chain_free (hdl_dat); \ + return error; \ + } \ + error = dwg_encode_##token##_private (dat, hdl_dat, str_dat, obj); \ +- if (error & DWG_ERR_VALUEOUTOFBOUNDS && hdl_dat != dat) \ +- bit_chain_free (hdl_dat); \ ++ if (error & DWG_ERR_VALUEOUTOFBOUNDS && hdl_dat != dat \ ++ && hdl_dat->chain != dat->chain) \ ++ { \ ++ LOG_HANDLE ("VALUEOUTOFBOUNDS bypassed DWG_ENTITY_END\n"); \ ++ /*bit_chain_free (hdl_dat);*/ \ ++ } \ + return error; \ + } \ + static int dwg_encode_##token##_private ( \ +- Bit_Chain *dat, Bit_Chain *hdl_dat, Bit_Chain *str_dat, \ +- Dwg_Object *restrict obj) \ ++ Bit_Chain *dat, Bit_Chain *hdl_dat, Bit_Chain *str_dat, \ ++ Dwg_Object *restrict obj) \ + { \ + int error = 0; \ + BITCODE_BL vcount, rcount3, rcount4; \ + Dwg_Data *dwg = obj->parent; \ + Dwg_Object_Entity *_ent = obj->tio.entity; \ +- Dwg_Entity_##token *_obj = _ent->tio.token; \ ++ Dwg_Entity_##token *_obj = _ent->tio.token; + + #define DWG_ENTITY_END \ + if (hdl_dat->byte > dat->byte) \ +@@ -861,7 +867,7 @@ EXPORT long dwg_add_##token (Dwg_Data * dwg) \ + dat->byte = hdl_dat->byte; \ + dat->bit = hdl_dat->bit; \ + } \ +- if (hdl_dat != dat) \ ++ if (hdl_dat != dat && hdl_dat->chain != dat->chain) \ + bit_chain_free (hdl_dat); \ + return error; \ + } +@@ -891,7 +897,8 @@ EXPORT long dwg_add_##token (Dwg_Data * dwg) \ + return error; \ + } \ + error = dwg_encode_##token##_private (dat, hdl_dat, str_dat, obj); \ +- if (error & DWG_ERR_VALUEOUTOFBOUNDS && hdl_dat != dat) \ ++ if (error & DWG_ERR_VALUEOUTOFBOUNDS && hdl_dat != dat \ ++ && hdl_dat->chain != dat->chain) \ + bit_chain_free (hdl_dat); \ + return error; \ + } \ +@@ -915,7 +922,7 @@ EXPORT long dwg_add_##token (Dwg_Data * dwg) \ + dat->byte = hdl_dat->byte; \ + dat->bit = hdl_dat->bit; \ + } \ +- if (hdl_dat != dat) \ ++ if (hdl_dat != dat && hdl_dat->chain != dat->chain) \ + bit_chain_free (hdl_dat); \ + return error; \ + } \ No newline at end of file diff --git a/tasks/csa159/pair_138280/post_functions.txt b/tasks/csa159/pair_138280/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2a537656e97a1c581d34ca0ddb0d3a9bd948b322 --- /dev/null +++ b/tasks/csa159/pair_138280/post_functions.txt @@ -0,0 +1,180 @@ +### File: src/encode.c +```c +/*****************************************************************************/ +/* LibreDWG - free implementation of the DWG file format */ +/* */ +/* Copyright (C) 2009-2010,2018-2021 Free Software Foundation, Inc. */ +/* Copyright (C) 2010 Thien-Thi Nguyen */ +/* */ +/* This library is free software, licensed under the terms of the GNU */ +/* General Public License as published by the Free Software Foundation, */ +/* either version 3 of the License, or (at your option) any later version. */ +/* You should have received a copy of the GNU General Public License */ +/* along with this program. If not, see . */ +/*****************************************************************************/ + +/* + * encode.c: encoding functions to write a DWG + * written by Felipe Castro + * modified by Felipe Corrêa da Silva Sances + * modified by Rodrigo Rodrigues da Silva + * modified by Thien-Thi Nguyen + * modified by Till Heuschmann + * modified by Anderson Pierre Cardoso + * modified by Reini Urban + */ + +//#define HAVE_COMPRESS_R2004_SECTION + +#include "config.h" +#ifdef __STDC_ALLOC_LIB__ +# define __STDC_WANT_LIB_EXT2__ 1 /* for strdup */ +#else +# define _USE_BSD 1 +#endif +#include +#include +#include +#include +#include +#include +#ifdef HAVE_CTYPE_H +# include +#endif + +#include "common.h" +#include "bits.h" +#include "dwg.h" +#include "encode.h" +#include "decode.h" +#include "classes.h" +#include "free.h" + +// from dynapi +bool is_dwg_object (const char *name); +bool is_dwg_entity (const char *name); +int dwg_dynapi_entity_size (const char *restrict name); +// from dwg_api +BITCODE_T dwg_add_u8_input (Dwg_Data *restrict dwg, + const char *restrict u8str); +Dwg_Object_APPID *dwg_add_APPID (Dwg_Data *restrict dwg, + const char *restrict name); +unsigned long dwg_obj_generic_handlevalue (void *_obj); + +/* The logging level for the write (encode) path. */ +static unsigned int loglevel; +/* the current version per spec block */ +static unsigned int cur_ver = 0; +static BITCODE_BL rcount1 = 0, rcount2 = 0; + +#ifdef USE_TRACING +/* This flag means we have checked the environment variable + LIBREDWG_TRACE and set `loglevel' appropriately. */ +static bool env_var_checked_p; +#endif /* USE_TRACING */ +#define DWG_LOGLEVEL loglevel + +#include "logging.h" + +/*-------------------------------------------------------------------------------- + * spec MACROS + */ + +#define ACTION encode +#define IS_ENCODER + +#define ANYCODE -1 + +#define LOG_POS \ + LOG_INSANE (" @%lu.%u", obj ? dat->byte - obj->address : dat->byte, dat->bit)\ + LOG_TRACE ("\n") +#define LOG_RPOS \ + LOG_INSANE (" @%lu.%u", dat->byte, dat->bit) \ + LOG_TRACE ("\n") +#define LOG_HPOS \ + LOG_INSANE (" @%lu.%u", \ + obj && hdl_dat->byte > obj->address \ + ? hdl_dat->byte - obj->address \ + : hdl_dat->byte, \ + hdl_dat->bit) \ + LOG_TRACE ("\n") + +#define VALUE(value, type, dxf) \ + { \ + bit_write_##type (dat, value); \ + LOG_TRACE (FORMAT_##type " [" #type " %d]", (BITCODE_##type)value, dxf); \ + LOG_POS \ + } +#define VALUE_RC(value, dxf) VALUE (value, RC, dxf) +#define VALUE_RS(value, dxf) VALUE (value, RS, dxf) +#define VALUE_RL(value, dxf) VALUE (value, RL, dxf) +#define VALUE_BS(value, dxf) VALUE (value, BS, dxf) +#define VALUE_BL(value, dxf) VALUE (value, BL, dxf) +#define VALUE_RD(value, dxf) VALUE (value, RD, dxf) +#define VALUE_BD(value, dxf) VALUE (value, BD, dxf) + +#define FIELD(nam, type) \ + { \ + bit_write_##type (dat, _obj->nam); \ + FIELD_TRACE (nam, type); \ + } +#define FIELDG(nam, type, dxf) \ + { \ + bit_write_##type (dat, _obj->nam); \ + FIELD_G_TRACE (nam, type, dxf); \ + } +#define FIELD_TRACE(nam, type) \ + LOG_TRACE (#nam ": " FORMAT_##type, _obj->nam) \ + LOG_POS +#define FIELD_G_TRACE(nam, type, dxfgroup) \ + LOG_TRACE (#nam ": " FORMAT_##type " [" #type " " #dxfgroup "]", _obj->nam) \ + LOG_POS +#define FIELD_CAST(nam, type, cast, dxf) \ + { \ + bit_write_##type (dat, (BITCODE_##type)_obj->nam); \ + LOG_TRACE (#nam ": " FORMAT_##type " [" #type " " #dxf "]", \ + (BITCODE_##type)_obj->nam); \ + LOG_POS \ + } +#define SUB_FIELD(o, nam, type, dxf) FIELD (o.nam, type) +#define SUB_FIELD_CAST(o, nam, type, cast, dxf) \ + { \ + bit_write_##type (dat, (BITCODE_##type)_obj->o.nam); \ + FIELD_G_TRACE (o.nam, cast, dxf); \ + } + +#define FIELD_VALUE(nam) _obj->nam + +#define FIELD_B(nam, dxf) FIELDG (nam, B, dxf) +#define FIELD_BB(nam, dxf) FIELDG (nam, BB, dxf) +#define FIELD_3B(nam, dxf) FIELDG (nam, 3B, dxf) +#define FIELD_BS(nam, dxf) FIELDG (nam, BS, dxf) +#define FIELD_BSd(nam, dxf) FIELD_CAST (nam, BS, BSd, dxf) +#define FIELD_RSx(nam, dxf) FIELD_CAST (nam, RS, RSx, dxf) +#define FIELD_RLx(nam, dxf) FIELD_CAST (nam, RL, RLx, dxf) +#define FIELD_BLx(nam, dxf) FIELD_CAST (nam, BL, BLx, dxf) +#define FIELD_BLd(nam, dxf) FIELD_CAST (nam, BL, BLd, dxf) +#define FIELD_RLd(nam, dxf) FIELD_CAST (nam, RL, RLd, dxf) +#define FIELD_BL(nam, dxf) FIELDG (nam, BL, dxf) +#define FIELD_BLL(nam, dxf) FIELDG (nam, BLL, dxf) +#define FIELD_BD(nam, dxf) FIELDG (nam, BD, dxf) +#define FIELD_RC(nam, dxf) FIELDG (nam, RC, dxf) +#define FIELD_RS(nam, dxf) FIELDG (nam, RS, dxf) +#define FIELD_RD(nam, dxf) FIELDG (nam, RD, dxf) +#define FIELD_RL(nam, dxf) FIELDG (nam, RL, dxf) +#define FIELD_RLL(nam, dxf) FIELDG (nam, RLL, dxf) +#define FIELD_RLLu(nam, dxf) \ + { \ + bit_write_RLL (dat, _obj->nam); \ + FIELD_G_TRACE (nam, BLL, dxf); \ + } +#define FIELD_MC(nam, dxf) FIELDG (nam, MC, dxf) +#define FIELD_MS(nam, dxf) FIELDG (nam, MS, dxf) +#define FIELD_TV(nam, dxf) \ + { \ + IF_ENCODE_FROM_EARLIER \ + { \ + if (!_obj->nam) + +// ... (177221 more chars) +``` diff --git a/tasks/csa159/pair_138280/pre_functions.txt b/tasks/csa159/pair_138280/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..cfde73a112d470721ea397082a084acd689bbe60 --- /dev/null +++ b/tasks/csa159/pair_138280/pre_functions.txt @@ -0,0 +1,180 @@ +### File: src/encode.c +```c +/*****************************************************************************/ +/* LibreDWG - free implementation of the DWG file format */ +/* */ +/* Copyright (C) 2009-2010,2018-2021 Free Software Foundation, Inc. */ +/* Copyright (C) 2010 Thien-Thi Nguyen */ +/* */ +/* This library is free software, licensed under the terms of the GNU */ +/* General Public License as published by the Free Software Foundation, */ +/* either version 3 of the License, or (at your option) any later version. */ +/* You should have received a copy of the GNU General Public License */ +/* along with this program. If not, see . */ +/*****************************************************************************/ + +/* + * encode.c: encoding functions to write a DWG + * written by Felipe Castro + * modified by Felipe Corrêa da Silva Sances + * modified by Rodrigo Rodrigues da Silva + * modified by Thien-Thi Nguyen + * modified by Till Heuschmann + * modified by Anderson Pierre Cardoso + * modified by Reini Urban + */ + +//#define HAVE_COMPRESS_R2004_SECTION + +#include "config.h" +#ifdef __STDC_ALLOC_LIB__ +# define __STDC_WANT_LIB_EXT2__ 1 /* for strdup */ +#else +# define _USE_BSD 1 +#endif +#include +#include +#include +#include +#include +#include +#ifdef HAVE_CTYPE_H +# include +#endif + +#include "common.h" +#include "bits.h" +#include "dwg.h" +#include "encode.h" +#include "decode.h" +#include "classes.h" +#include "free.h" + +// from dynapi +bool is_dwg_object (const char *name); +bool is_dwg_entity (const char *name); +int dwg_dynapi_entity_size (const char *restrict name); +// from dwg_api +BITCODE_T dwg_add_u8_input (Dwg_Data *restrict dwg, + const char *restrict u8str); +Dwg_Object_APPID *dwg_add_APPID (Dwg_Data *restrict dwg, + const char *restrict name); +unsigned long dwg_obj_generic_handlevalue (void *_obj); + +/* The logging level for the write (encode) path. */ +static unsigned int loglevel; +/* the current version per spec block */ +static unsigned int cur_ver = 0; +static BITCODE_BL rcount1 = 0, rcount2 = 0; + +#ifdef USE_TRACING +/* This flag means we have checked the environment variable + LIBREDWG_TRACE and set `loglevel' appropriately. */ +static bool env_var_checked_p; +#endif /* USE_TRACING */ +#define DWG_LOGLEVEL loglevel + +#include "logging.h" + +/*-------------------------------------------------------------------------------- + * spec MACROS + */ + +#define ACTION encode +#define IS_ENCODER + +#define ANYCODE -1 + +#define LOG_POS \ + LOG_INSANE (" @%lu.%u", obj ? dat->byte - obj->address : dat->byte, dat->bit)\ + LOG_TRACE ("\n") +#define LOG_RPOS \ + LOG_INSANE (" @%lu.%u", dat->byte, dat->bit) \ + LOG_TRACE ("\n") +#define LOG_HPOS \ + LOG_INSANE (" @%lu.%u", \ + obj && hdl_dat->byte > obj->address \ + ? hdl_dat->byte - obj->address \ + : hdl_dat->byte, \ + hdl_dat->bit) \ + LOG_TRACE ("\n") + +#define VALUE(value, type, dxf) \ + { \ + bit_write_##type (dat, value); \ + LOG_TRACE (FORMAT_##type " [" #type " %d]", (BITCODE_##type)value, dxf); \ + LOG_POS \ + } +#define VALUE_RC(value, dxf) VALUE (value, RC, dxf) +#define VALUE_RS(value, dxf) VALUE (value, RS, dxf) +#define VALUE_RL(value, dxf) VALUE (value, RL, dxf) +#define VALUE_BS(value, dxf) VALUE (value, BS, dxf) +#define VALUE_BL(value, dxf) VALUE (value, BL, dxf) +#define VALUE_RD(value, dxf) VALUE (value, RD, dxf) +#define VALUE_BD(value, dxf) VALUE (value, BD, dxf) + +#define FIELD(nam, type) \ + { \ + bit_write_##type (dat, _obj->nam); \ + FIELD_TRACE (nam, type); \ + } +#define FIELDG(nam, type, dxf) \ + { \ + bit_write_##type (dat, _obj->nam); \ + FIELD_G_TRACE (nam, type, dxf); \ + } +#define FIELD_TRACE(nam, type) \ + LOG_TRACE (#nam ": " FORMAT_##type, _obj->nam) \ + LOG_POS +#define FIELD_G_TRACE(nam, type, dxfgroup) \ + LOG_TRACE (#nam ": " FORMAT_##type " [" #type " " #dxfgroup "]", _obj->nam) \ + LOG_POS +#define FIELD_CAST(nam, type, cast, dxf) \ + { \ + bit_write_##type (dat, (BITCODE_##type)_obj->nam); \ + LOG_TRACE (#nam ": " FORMAT_##type " [" #type " " #dxf "]", \ + (BITCODE_##type)_obj->nam); \ + LOG_POS \ + } +#define SUB_FIELD(o, nam, type, dxf) FIELD (o.nam, type) +#define SUB_FIELD_CAST(o, nam, type, cast, dxf) \ + { \ + bit_write_##type (dat, (BITCODE_##type)_obj->o.nam); \ + FIELD_G_TRACE (o.nam, cast, dxf); \ + } + +#define FIELD_VALUE(nam) _obj->nam + +#define FIELD_B(nam, dxf) FIELDG (nam, B, dxf) +#define FIELD_BB(nam, dxf) FIELDG (nam, BB, dxf) +#define FIELD_3B(nam, dxf) FIELDG (nam, 3B, dxf) +#define FIELD_BS(nam, dxf) FIELDG (nam, BS, dxf) +#define FIELD_BSd(nam, dxf) FIELD_CAST (nam, BS, BSd, dxf) +#define FIELD_RSx(nam, dxf) FIELD_CAST (nam, RS, RSx, dxf) +#define FIELD_RLx(nam, dxf) FIELD_CAST (nam, RL, RLx, dxf) +#define FIELD_BLx(nam, dxf) FIELD_CAST (nam, BL, BLx, dxf) +#define FIELD_BLd(nam, dxf) FIELD_CAST (nam, BL, BLd, dxf) +#define FIELD_RLd(nam, dxf) FIELD_CAST (nam, RL, RLd, dxf) +#define FIELD_BL(nam, dxf) FIELDG (nam, BL, dxf) +#define FIELD_BLL(nam, dxf) FIELDG (nam, BLL, dxf) +#define FIELD_BD(nam, dxf) FIELDG (nam, BD, dxf) +#define FIELD_RC(nam, dxf) FIELDG (nam, RC, dxf) +#define FIELD_RS(nam, dxf) FIELDG (nam, RS, dxf) +#define FIELD_RD(nam, dxf) FIELDG (nam, RD, dxf) +#define FIELD_RL(nam, dxf) FIELDG (nam, RL, dxf) +#define FIELD_RLL(nam, dxf) FIELDG (nam, RLL, dxf) +#define FIELD_RLLu(nam, dxf) \ + { \ + bit_write_RLL (dat, _obj->nam); \ + FIELD_G_TRACE (nam, BLL, dxf); \ + } +#define FIELD_MC(nam, dxf) FIELDG (nam, MC, dxf) +#define FIELD_MS(nam, dxf) FIELDG (nam, MS, dxf) +#define FIELD_TV(nam, dxf) \ + { \ + IF_ENCODE_FROM_EARLIER \ + { \ + if (!_obj->nam) + +// ... (176693 more chars) +``` diff --git a/tasks/csa159/pair_138280/task_prompt.md b/tasks/csa159/pair_138280/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..e6f682a99547517cf1d5bacad8056a92041cd07b --- /dev/null +++ b/tasks/csa159/pair_138280/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 + +- Hard validation compiled the plugin and scanned before_commit successfully but emitted 0 warnings, so the implemented match never hit the real overflow-path free in buggy encode wrappers. +- The rollout treated the defect as a local IfStmt AST shape via check::ASTCodeBody and ParentMap then-branch walking; that is not the CFG guard/sink relation of the double-free and was scored semantically inadequate. +- Detection required a DeclRefExpr to EnumConstantDecl DWG_ERR_VALUEOUTOFBOUNDS, but that identifier is a preprocessor macro and is erased to a bitwise test after expansion, so the overflow path was filtered out. +- Objective, refinement, semantic, and process gates never became eligible because score_result was missing and code verification did not establish any relevant before/after reports. + +### Preserve from prior rollouts + +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- In a dwg_encode wrapper, a bit_chain_free sink on a Bit_Chain handle-data pointer must be shown control-dependent on a branch that combines an overflow/error test with Bit_Chain struct-pointer inequality and that does not test chain-buffer distinctness (the chain member). +- CFG reachability/ordering must show that sink can execute after handle-stream flush/release of the same chain (START_HANDLE_STREAM / obj_flush_hdlstream / bit_chain_free of the accumulated handle copy), so the sink can free an already released hdl_dat->chain. +- Patched safety is the absence of that sink or a strengthened guard that also requires hdl_dat->chain != dat->chain, so the free is not taken when the buffers alias. + +### Implementation constraints + +- Use CFG-based guard/sink analysis (function CFG from ASTCodeBody/EndFunction or equivalent, including dominance/control-dependence); do not classify the sink by ParentMap nesting alone. +- Anchor on project types and APIs only: Bit_Chain/_bit_chain pointers, bit_chain_free, and the chain field; do not key off patch lines, commit ids, or a single wrapper token name. +- Identify the overflow/error guard as it exists post-preprocessing (bitwise/error test plus Bit_Chain* comparison). Do not require the token DWG_ERR_VALUEOUTOFBOUNDS to survive as a named enum in the AST. +- Analyze instantiated dwg_encode_* wrapper bodies in src/encode.c after macro expansion; report at the overflow-path bit_chain_free or its controlling branch, not at unexpanded macro definitions. +- Keep scope project-general for the encode-wrapper pattern. Do not use source-text matching and do not require symbolic allocator modeling or interprocedural summaries to accept a site. + +### Validation checklist + +- Plugin must compile and load as a Clang Static Analyzer checker. +- scan_before on before_commit must produce a non-zero warning count on buggy encode wrappers; a clean compile with 0 buggy reports is a failed match. +- scan_after on the patched tree must drop those overflow-path reports (entity free removed or commented out; object free guarded by chain distinctness). +- Reported locations must sit on the DWG_ENTITY/DWG_OBJECT overflow cleanup free or its controlling branch in src/encode.c, near the changed encode-wrapper spans rather than unrelated Bit_Chain frees. +- Sites whose guard already contains a chain-buffer comparison, or that are not reachable overflow-path frees, must remain unreported. +- Hard validation, objective_gate, and refinement_accepted must pass with a non-zero semantic/process score; cross-scan counts alone are not sufficient. + +### Avoid and forbidden regressions + +- Repeating syntax-only AST shape matching that demands bit_chain_free as the syntactic then-child of one IfStmt. +- Looking up DWG_ERR_VALUEOUTOFBOUNDS as EnumConstantDecl or any other pre-expansion spelling that does not exist in the CFG. +- Path-sensitive modeling of bit_chain_init_dat/bit_chain_free as a custom allocator, and PreCall/PreStmt exploration used only to recover the same AST facts. +- Source-text or identifier hardcoding of hdl_dat != dat, commented /*bit_chain_free*/, line numbers, or commit-specific tokens. +- Dropping back to syntax_only because the failed rollout used it, or claiming prior checker sources are reusable. +- Flagging every bit_chain_free in encode.c, including START_HANDLE_STREAM reset frees and already chain-guarded DWG_*_END cleanup. diff --git a/tasks/csa159/pair_138328/checker_template.cpp b/tasks/csa159/pair_138328/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138328/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_138328/config.json b/tasks/csa159/pair_138328/config.json new file mode 100644 index 0000000000000000000000000000000000000000..a2d2126d03b2f1bc5bebc259174cc4b5fc315253 --- /dev/null +++ b/tasks/csa159/pair_138328/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "libssh2_libssh2", + "before_commit": "c07bc647f2b181199561bbccc1a0695caba8822c", + "after_commit": "ff1b155731ff8f790f12d980911d9fd84d0e1598", + "repo_path": "/workspace/repo/libssh2/libssh2", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/libssh2_libssh2/452517d96c2a636fa0e2f31cfa8b463886de7611/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/libssh2_libssh2/452517d96c2a636fa0e2f31cfa8b463886de7611/compile_commands.json", + "changed_files": [ + "src/misc.c" + ], + "commit_message": "Simplified _libssh2_check_length (#350)\n\n* Simplified _libssh2_check_length\n\nmisc.c : _libssh2_check_length()\n\nRemoved cast and improved bounds checking and format.\n\nCredit : Yuriy M. Kaminskiy", + "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_138328/patch.diff b/tasks/csa159/pair_138328/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a3499f4d4ad83f293ed2b6d790ba0eb2055e3958 --- /dev/null +++ b/tasks/csa159/pair_138328/patch.diff @@ -0,0 +1,18 @@ +diff --git a/src/misc.c b/src/misc.c +index 8d80456c..76644a3c 100644 +--- a/src/misc.c ++++ b/src/misc.c +@@ -811,10 +811,9 @@ int _libssh2_get_bignum_bytes(struct string_buf *buf, unsigned char **outbuf) + + int _libssh2_check_length(struct string_buf *buf, size_t len) + { +- if(len > buf->len) +- return 0; +- +- return ((int)(buf->dataptr - buf->data) <= (int)(buf->len - len)) ? 1 : 0; ++ unsigned char *endp = &buf->data[buf->len]; ++ size_t left = endp - buf->dataptr; ++ return ((len <= left) && (left <= buf->len)); + } + + /* Wrappers */ \ No newline at end of file diff --git a/tasks/csa159/pair_138328/post_functions.txt b/tasks/csa159/pair_138328/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2e34f653d478e67b63b0c675cd6a928dd5056054 --- /dev/null +++ b/tasks/csa159/pair_138328/post_functions.txt @@ -0,0 +1,56 @@ +### File: src/misc.c +```c +int _libssh2_get_bignum_bytes(struct string_buf *buf, unsigned char **outbuf) +{ + uint32_t data_len; + uint32_t bn_len; + unsigned char *bnptr; + + if(_libssh2_get_u32(buf, &data_len) != 0) { + return -1; + } + if(!_libssh2_check_length(buf, data_len)) { + return -1; + } + + bn_len = data_len; + bnptr = buf->dataptr; + + /* trim leading zeros */ + while(bn_len > 0 && *bnptr == 0x00) { + bn_len--; + bnptr++; + } + + *outbuf = bnptr; + + buf->dataptr += data_len; + + return bn_len; +} + +int _libssh2_check_length(struct string_buf *buf, size_t len) +{ + unsigned char *endp = &buf->data[buf->len]; + size_t left = endp - buf->dataptr; + return ((len <= left) && (left <= buf->len)); +} + +int _libssh2_bcrypt_pbkdf(const char *pass, + size_t passlen, + const uint8_t *salt, + size_t saltlen, + uint8_t *key, + size_t keylen, + unsigned int rounds) +{ + /* defined in bcrypt_pbkdf.c */ + return bcrypt_pbkdf(pass, + passlen, + salt, + saltlen, + key, + keylen, + rounds); +} +``` diff --git a/tasks/csa159/pair_138328/pre_functions.txt b/tasks/csa159/pair_138328/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..13837386ce088a599d2a79c4f35fe0dee18c807a --- /dev/null +++ b/tasks/csa159/pair_138328/pre_functions.txt @@ -0,0 +1,57 @@ +### File: src/misc.c +```c +int _libssh2_get_bignum_bytes(struct string_buf *buf, unsigned char **outbuf) +{ + uint32_t data_len; + uint32_t bn_len; + unsigned char *bnptr; + + if(_libssh2_get_u32(buf, &data_len) != 0) { + return -1; + } + if(!_libssh2_check_length(buf, data_len)) { + return -1; + } + + bn_len = data_len; + bnptr = buf->dataptr; + + /* trim leading zeros */ + while(bn_len > 0 && *bnptr == 0x00) { + bn_len--; + bnptr++; + } + + *outbuf = bnptr; + + buf->dataptr += data_len; + + return bn_len; +} + +int _libssh2_check_length(struct string_buf *buf, size_t len) +{ + if(len > buf->len) + return 0; + + return ((int)(buf->dataptr - buf->data) <= (int)(buf->len - len)) ? 1 : 0; +} + +int _libssh2_bcrypt_pbkdf(const char *pass, + size_t passlen, + const uint8_t *salt, + size_t saltlen, + uint8_t *key, + size_t keylen, + unsigned int rounds) +{ + /* defined in bcrypt_pbkdf.c */ + return bcrypt_pbkdf(pass, + passlen, + salt, + saltlen, + key, + keylen, + rounds); +} +``` diff --git a/tasks/csa159/pair_138328/task_prompt.md b/tasks/csa159/pair_138328/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..f8a3254cf4e24f878101120ada4a7319203961ca --- /dev/null +++ b/tasks/csa159/pair_138328/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 passed compilation, differential validation, objective gate G6, semantic threshold, process threshold, anchor checks, and hardcoding checks, but refinement remained unaccepted after one round. +- The reported pattern was too broad: any relational guard containing a lossy cast of a subtraction could be diagnosed without proving that the comparison represents a buffer-capacity decision. +- The prior semantic result was only partial because it detected the numeric root cause but did not establish the guard's role in authorizing an operation whose requested length must fit within the remaining buffer. +- Pure guard-expression classification left adjacent false positives possible for narrowed subtraction comparisons unrelated to memory bounds. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Retain at least the previously adequate local AST/type recognition of explicit narrowing or signedness-changing casts applied to subtraction operands. +- Maintain the semantic score at or above the configured threshold. +- Maintain process quality at or above the configured threshold. +- Remain independent of patch anchors such as changed line locations. +- Remain free of patch-local hardcoding, including project identifiers, function names, variable names, and source literals. + +### Required semantic proof + +- Prove that the candidate relational comparison participates in control flow that decides whether a requested length is accepted or rejected as fitting in a buffer. +- Prove that a compared subtraction denotes buffer-position or remaining-capacity arithmetic: pointer displacement within a common buffer representation, or an unsigned extent-minus-request quantity. +- Prove that an explicit conversion to a signed integer loses width or changes an unsigned magnitude into a signed domain before the comparison determines the bounds result. +- Account for the preceding rejection path for requests larger than the total buffer length and analyze the vulnerable comparison on the remaining reachable path. +- Treat the patched full-width relation len <= left && left <= total length as safe because no lossy conversion controls the capacity decision. +- Do not require path-sensitive ProgramState facts or cross-function fact propagation when CFG reachability and local type/operand relationships are sufficient. + +### Implementation constraints + +- Use a CSA function-body callback with access to ASTContext, BugReporter, and the function CFG, such as check::ASTCodeBody through AnalysisManager. +- Relate the narrowing comparison to terminating accept/reject returns or an equivalent local guard outcome using CFG reachability, predecessor/successor structure, or dominance/post-dominance reasoning. +- Inspect relational operators, explicit casts, subtraction operands, canonical types, integer widths, signedness, and pointer arithmetic through Clang AST APIs rather than source text. +- Require evidence that the arithmetic operands belong to a coherent bounds relation involving current position, total extent, requested length, or remaining capacity. +- Emit one deterministic BasicBugReport at the vulnerable relational comparison or lossy conversion, with deduplication scoped by declaration and source location. +- Keep the synthesis cross-project and avoid special cases for libssh2, string_buf, _libssh2_check_length, misc.c, or the patch's line numbers. + +### Validation checklist + +- Compile the checker plugin successfully against the target Clang Static Analyzer API and verify registration and loading. +- Scan the vulnerable source and require exactly one relevant diagnostic in _libssh2_check_length. +- Scan the patched source and require zero diagnostics for the full-width size_t remaining-capacity checks. +- Verify that the diagnostic is located at the vulnerable comparison or its narrowing cast and remains within the changed function with zero patch-line distance where measured. +- Add a positive refinement case with the same semantic bounds relation but different identifiers, function structure, and source locations to demonstrate anchor independence. +- Add negative refinement cases for narrowed subtraction comparisons used in ordering, counters, arithmetic classification, or non-memory guards, and require no reports. +- Add negative cases for non-lossy casts and full-width unsigned buffer comparisons, including the patched two-conjunct form. +- Re-run code verification, differential checks, sparsity checks, semantic scoring, process scoring, objective gate G6, and refinement acceptance. + +### Avoid and forbidden regressions + +- Do not repeat a syntax-only rule that labels every relational guard containing a lossy casted subtraction as a buffer vulnerability. +- Do not infer an out-of-bounds risk solely from explicit-cast, subtraction, and relational-operator shape. +- Do not use check::PreCall tied to the known helper or otherwise encode known caller/callee names. +- Do not introduce ProgramState tracking or interprocedural dataflow unless new evidence shows CFG-local proof is insufficient. +- Do not report the patched full-width unsigned comparisons merely because they contain subtraction-derived values. +- Do not use global source offsets alone for deduplication because offsets can collide across files or translation units. +- Do not weaken the accepted numeric-conversion contract merely to obtain refinement acceptance. diff --git a/tasks/csa159/pair_138462/checker_template.cpp b/tasks/csa159/pair_138462/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138462/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_138462/config.json b/tasks/csa159/pair_138462/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0eefa6615ac824dba7a2f26de62206f39e78b6ef --- /dev/null +++ b/tasks/csa159/pair_138462/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "gpac_gpac", + "before_commit": "422b78ecf79ceeee97104d219cc4f184b1348cec", + "after_commit": "cb3c29809bddfa32686e3deb231a76af67b68e1e", + "repo_path": "/workspace/repo/gpac/gpac", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/gpac_gpac/4f4af3d2fc8819dd96672e22ca7e624c3faf849c/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/gpac_gpac/4f4af3d2fc8819dd96672e22ca7e624c3faf849c/compile_commands.json", + "changed_files": [ + "src/media_tools/dash_client.c" + ], + "commit_message": "null guard on mpd_desc value in dasher (fixes #2763)", + "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_138462/patch.diff b/tasks/csa159/pair_138462/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1d358f3d618a75b6cae1bc7e102e0f65ae1d7a7f --- /dev/null +++ b/tasks/csa159/pair_138462/patch.diff @@ -0,0 +1,13 @@ +diff --git a/src/media_tools/dash_client.c b/src/media_tools/dash_client.c +index 1d3e3996b..5abbdd067 100644 +--- a/src/media_tools/dash_client.c ++++ b/src/media_tools/dash_client.c +@@ -6368,7 +6368,7 @@ static GF_Err gf_dash_setup_period(GF_DashClient *dash) + disabled = 1; + break; + } +- if (!strcmp(mpd_desc->scheme_id_uri, "urn:mpeg:dash:srd:2014")) { ++ if (mpd_desc && mpd_desc->scheme_id_uri && !strcmp(mpd_desc->scheme_id_uri, "urn:mpeg:dash:srd:2014") && mpd_desc->value) { + u32 id, w, h, res; + w = h = 0; + res = sscanf(mpd_desc->value, "%d,%d,%d,%d,%d,%d,%d", &id, &group->srd_x, &group->srd_y, &group->srd_w, &group->srd_h, &w, &h); \ No newline at end of file diff --git a/tasks/csa159/pair_138462/post_functions.txt b/tasks/csa159/pair_138462/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2d9e53970ac557fa8407fb25f717974002665564 --- /dev/null +++ b/tasks/csa159/pair_138462/post_functions.txt @@ -0,0 +1,222 @@ +### File: src/media_tools/dash_client.c +```c +static GF_Err gf_dash_setup_period(GF_DashClient *dash) +{ + GF_MPD_Period *period; + u32 rep_i, as_i, group_i, j, nb_groups_ok; + u32 retry = 10; + + //solve xlink - if + while (retry) { + period = gf_list_get(dash->mpd->periods, dash->active_period_index); + if (!period) return GF_EOS; + if (!period->xlink_href) break; + gf_dash_solve_period_xlink(dash, dash->mpd->periods, dash->active_period_index); + retry --; + } + period = gf_list_get(dash->mpd->periods, dash->active_period_index); + if (period->xlink_href && (dash->route_clock_state!=1) ) { + GF_LOG(GF_LOG_ERROR, GF_LOG_DASH, ("[DASH] Too many xlink indirections on the same period - not supported\n")); + return GF_NOT_SUPPORTED; + } + + if (!period->duration) { + GF_MPD_Period *next_period = gf_list_get(dash->mpd->periods, dash->active_period_index+1); + if (next_period && next_period->start) + period->duration = next_period->start - period->start; + } + + GF_Err e = dash_check_supported_mime(period); + if (e) return e; + + + GF_LOG(GF_LOG_INFO, GF_LOG_DASH, ("[DASH] Setting up period start "LLU" duration "LLU" xlink %s ID %s\n", period->start, period->duration, period->origin_base_url ? period->origin_base_url : "none", period->ID ? period->ID : "none")); + + /*setup all groups*/ + gf_dash_setup_groups(dash); + + nb_groups_ok = 0; + for (group_i=0; group_igroups); group_i++) { + GF_MPD_Representation *rep_sel; + u32 active_rep, nb_rep; + const char *mime_type; + u32 nb_rep_ok = 0; + Bool group_has_video = GF_FALSE; + Bool disabled = GF_FALSE; + Bool cp_supported = GF_FALSE; + GF_DASH_Group *group = gf_list_get(dash->groups, group_i); + Bool active_rep_found; + + active_rep = 0; + nb_rep = gf_list_count(group->adaptation_set->representations); + + //group already setup + if (group->selection != GF_DASH_GROUP_NOT_SETUP) { + if (group->selection > GF_DASH_GROUP_NOT_SELECTABLE) nb_groups_ok++; + continue; + } + if (group->pending_rep) { + rep_sel = group->pending_rep; + goto retry_pending_rep; + } + if (group->download_sidx_pending) { + goto sidx_pending; + } + + if (dash->dbg_grps_index) { + Bool disable = GF_TRUE; + u32 gidx; + for (gidx=0; gidxnb_dbg_grps; gidx++) { + if (group_i == dash->dbg_grps_index[gidx]) { + disable = GF_FALSE; + break; + } + } + if (disable) { + group->selection = GF_DASH_GROUP_NOT_SELECTABLE; + continue; + } + } + + //on HLS get rid of audio only adaptation set if not in fMP4 mode + if (dash->is_m3u8 + && !group->adaptation_set->max_width + && !group->adaptation_set->max_height + && (gf_list_count(dash->groups)>1) + ) { + GF_MPD_Representation *rep = gf_list_get(group->adaptation_set->representations, 0); + if ((!rep->segment_template || !rep->segment_template->initialization) + && (!rep->segment_list || (!rep->segment_list->initialization_segment && !rep->segment_list->xlink_href)) + ) { + group->selection = GF_DASH_GROUP_NOT_SELECTABLE; + continue; + } + } + + if ((nb_rep>1) && !group->adaptation_set->segment_alignment && !group->adaptation_set->subsegment_alignment) { + GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, ("[DASH] AdaptationSet without segmentAlignment flag set - may result in broken adaptation\n")); + } + if (group->adaptation_set->xlink_href) { + GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, ("[DASH] AdaptationSet with xlink:href to %s - ignoring because not supported\n", group->adaptation_set->xlink_href)); + continue; + } + + for (j=0; jadaptation_set->essential_properties); j++) { + GF_MPD_Descriptor *mpd_desc = gf_list_get(group->adaptation_set->essential_properties, j); + if (!mpd_desc->scheme_id_uri) { + GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, ("[DASH] AdaptationSet with unrecognized EssentialProperty (no uri) - ignoring because not supported\n")); + disabled = 1; + break; + } + if (mpd_desc && mpd_desc->scheme_id_uri && !strcmp(mpd_desc->scheme_id_uri, "urn:mpeg:dash:srd:2014") && mpd_desc->value) { + u32 id, w, h, res; + w = h = 0; + res = sscanf(mpd_desc->value, "%d,%d,%d,%d,%d,%d,%d", &id, &group->srd_x, &group->srd_y, &group->srd_w, &group->srd_h, &w, &h); + if (res != 7) { + res = sscanf(mpd_desc->value, "%d,%d,%d,%d,%d", &id, &group->srd_x, &group->srd_y, &group->srd_w, &group->srd_h); + if (res!=5) res=0; + } + if (res) { + group->srd_desc = gf_dash_get_srd_desc(dash, id, GF_TRUE); + if (!w) w = group->srd_x + group->srd_w; + if (!h) h = group->srd_y + group->srd_h; + + if (w>group->srd_desc->srd_fw) + group->srd_desc->srd_fw = w; + if (h>group->srd_desc->srd_fh) + group->srd_desc->srd_fh = h; + } + + } else if (!strcmp(mpd_desc->scheme_id_uri, "http://dashif.org/guidelines/trickmode") ) { + continue; + } else { + //we don't know any defined scheme for now + GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, ("[DASH] AdaptationSet with unrecognized EssentialProperty %s - ignoring because not supported\n", mpd_desc->scheme_id_uri)); + disabled = 1; + break; + } + } + if (disabled) { + continue; + } + + cp_supported = 1; + for (j=0; jadaptation_set->content_protection); j++) { + GF_MPD_Descriptor *mpd_desc = gf_list_get(group->adaptation_set->content_protection, j); + //we don't know any defined scheme for now + if (strcmp(mpd_desc->scheme_id_uri, "urn:mpeg:dash:mp4protection:2011")) { + GF_LOG(GF_LOG_INFO, GF_LOG_DASH, ("[DASH] AdaptationSet with unrecognized ContentProtection %s\n", mpd_desc->scheme_id_uri)); + cp_supported = 0; + } else { + cp_supported = 1; + break; + } + } + if (!cp_supported) { + GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, ("[DASH] AdaptationSet with no supported ContentProtection - ignoring\n")); + continue; + } + + for (j=0; jadaptation_set->supplemental_properties); j++) { + GF_MPD_Descriptor *mpd_desc = gf_list_get(group->adaptation_set->supplemental_properties, j); + if (mpd_desc && mpd_desc->scheme_id_uri && !strcmp(mpd_desc->scheme_id_uri, "urn:mpeg:dash:srd:2014") && mpd_desc->value) { + u32 id, w, h, res; + w = h = 0; + res = sscanf(mpd_desc->value, "%d,%d,%d,%d,%d,%d,%d", &id, &group->srd_x, &group->srd_y, &group->srd_w, &group->srd_h, &w, &h); + if (res != 7) { + res = sscanf(mpd_desc->value, "%d,%d,%d,%d,%d", &id, &group->srd_x, &group->srd_y, &group->srd_w, &group->srd_h); + if (res != 5) res=0; + } + if (res) { + group->srd_desc = gf_dash_get_srd_desc(dash, id, GF_TRUE); + if (!w) w = group->srd_x + group->srd_w; + if (!h) h = group->srd_y + group->srd_h; + + if (w>group->srd_desc->srd_fw) + group->srd_desc->srd_fw = w; + if (h>group->srd_desc->srd_fh) + group->srd_desc->srd_fh = h; + } + } + } + +sidx_pending: + /*translate from single-indexed file to SegmentList*/ + gf_dash_setup_single_index_mode(group); + if (group->download_sidx_pending) { + return GF_NOT_READY; + } + + /* Select the appropriate representation in the given period */ + for (rep_i = 0; rep_i < nb_rep; rep_i++) { + GF_MPD_Representation *rep = gf_list_get(group->adaptation_set->representations, rep_i); + if (rep->width && rep->height) group_has_video = GF_TRUE; + } + + //sort by ascending bandwidth and quality + for (rep_i = 1; rep_i < nb_rep; rep_i++) { + Bool swap=GF_FALSE; + GF_MPD_Representation *r2 = gf_list_get(group->adaptation_set->representations, rep_i); + GF_MPD_Representation *r1 = gf_list_get(group->adaptation_set->representations, rep_i-1); + if (r1->bandwidth > r2->bandwidth) { + swap=GF_TRUE; + } else if ((r1->bandwidth == r2->bandwidth) && (r1->quality_rankingquality_ranking)) { + swap=GF_TRUE; + } + if (swap) { + gf_list_rem(group->adaptation_set->representations, rep_i); + gf_list_insert(group->adaptation_set->representations, r2, rep_i-1); + rep_i=0; + } + } + +select_active_rep: + group->min_representation_bitrate = (u32) -1; + active_rep_found = GF_FALSE; + + for (rep_i = 0; rep_i < nb_rep; rep_i++) { + u32 first_select_mode = dash->first_select_mode; + GF_MPD_Representation *rep = gf_list_get(group->adaptation_set-> + +// ... (7508 more chars) +``` diff --git a/tasks/csa159/pair_138462/pre_functions.txt b/tasks/csa159/pair_138462/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..15ab1fdfffce689d22666dffab81e48fa878c23a --- /dev/null +++ b/tasks/csa159/pair_138462/pre_functions.txt @@ -0,0 +1,224 @@ +### File: src/media_tools/dash_client.c +```c +static GF_Err gf_dash_setup_period(GF_DashClient *dash) +{ + GF_MPD_Period *period; + u32 rep_i, as_i, group_i, j, nb_groups_ok; + u32 retry = 10; + + //solve xlink - if + while (retry) { + period = gf_list_get(dash->mpd->periods, dash->active_period_index); + if (!period) return GF_EOS; + if (!period->xlink_href) break; + gf_dash_solve_period_xlink(dash, dash->mpd->periods, dash->active_period_index); + retry --; + } + period = gf_list_get(dash->mpd->periods, dash->active_period_index); + if (period->xlink_href && (dash->route_clock_state!=1) ) { + GF_LOG(GF_LOG_ERROR, GF_LOG_DASH, ("[DASH] Too many xlink indirections on the same period - not supported\n")); + return GF_NOT_SUPPORTED; + } + + if (!period->duration) { + GF_MPD_Period *next_period = gf_list_get(dash->mpd->periods, dash->active_period_index+1); + if (next_period && next_period->start) + period->duration = next_period->start - period->start; + } + + GF_Err e = dash_check_supported_mime(period); + if (e) return e; + + + GF_LOG(GF_LOG_INFO, GF_LOG_DASH, ("[DASH] Setting up period start "LLU" duration "LLU" xlink %s ID %s\n", period->start, period->duration, period->origin_base_url ? period->origin_base_url : "none", period->ID ? period->ID : "none")); + + /*setup all groups*/ + gf_dash_setup_groups(dash); + + nb_groups_ok = 0; + for (group_i=0; group_igroups); group_i++) { + GF_MPD_Representation *rep_sel; + u32 active_rep, nb_rep; + const char *mime_type; + u32 nb_rep_ok = 0; + Bool group_has_video = GF_FALSE; + Bool disabled = GF_FALSE; + Bool cp_supported = GF_FALSE; + GF_DASH_Group *group = gf_list_get(dash->groups, group_i); + Bool active_rep_found; + + active_rep = 0; + nb_rep = gf_list_count(group->adaptation_set->representations); + + //group already setup + if (group->selection != GF_DASH_GROUP_NOT_SETUP) { + if (group->selection > GF_DASH_GROUP_NOT_SELECTABLE) nb_groups_ok++; + continue; + } + if (group->pending_rep) { + rep_sel = group->pending_rep; + goto retry_pending_rep; + } + if (group->download_sidx_pending) { + goto sidx_pending; + } + + if (dash->dbg_grps_index) { + Bool disable = GF_TRUE; + u32 gidx; + for (gidx=0; gidxnb_dbg_grps; gidx++) { + if (group_i == dash->dbg_grps_index[gidx]) { + disable = GF_FALSE; + break; + } + } + if (disable) { + group->selection = GF_DASH_GROUP_NOT_SELECTABLE; + continue; + } + } + + //on HLS get rid of audio only adaptation set if not in fMP4 mode + if (dash->is_m3u8 + && !group->adaptation_set->max_width + && !group->adaptation_set->max_height + && (gf_list_count(dash->groups)>1) + ) { + GF_MPD_Representation *rep = gf_list_get(group->adaptation_set->representations, 0); + if ((!rep->segment_template || !rep->segment_template->initialization) + && (!rep->segment_list || (!rep->segment_list->initialization_segment && !rep->segment_list->xlink_href)) + ) { + group->selection = GF_DASH_GROUP_NOT_SELECTABLE; + continue; + } + } + + if ((nb_rep>1) && !group->adaptation_set->segment_alignment && !group->adaptation_set->subsegment_alignment) { + GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, ("[DASH] AdaptationSet without segmentAlignment flag set - may result in broken adaptation\n")); + } + if (group->adaptation_set->xlink_href) { + GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, ("[DASH] AdaptationSet with xlink:href to %s - ignoring because not supported\n", group->adaptation_set->xlink_href)); + continue; + } + + for (j=0; jadaptation_set->essential_properties); j++) { + GF_MPD_Descriptor *mpd_desc = gf_list_get(group->adaptation_set->essential_properties, j); + if (!mpd_desc->scheme_id_uri) { + GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, ("[DASH] AdaptationSet with unrecognized EssentialProperty (no uri) - ignoring because not supported\n")); + disabled = 1; + break; + } + if (!strcmp(mpd_desc->scheme_id_uri, "urn:mpeg:dash:srd:2014")) { + u32 id, w, h, res; + w = h = 0; + res = sscanf(mpd_desc->value, "%d,%d,%d,%d,%d,%d,%d", &id, &group->srd_x, &group->srd_y, &group->srd_w, &group->srd_h, &w, &h); + if (res != 7) { + res = sscanf(mpd_desc->value, "%d,%d,%d,%d,%d", &id, &group->srd_x, &group->srd_y, &group->srd_w, &group->srd_h); + if (res!=5) res=0; + } + if (res) { + group->srd_desc = gf_dash_get_srd_desc(dash, id, GF_TRUE); + if (!w) w = group->srd_x + group->srd_w; + if (!h) h = group->srd_y + group->srd_h; + + if (w>group->srd_desc->srd_fw) + group->srd_desc->srd_fw = w; + if (h>group->srd_desc->srd_fh) + group->srd_desc->srd_fh = h; + } + + } else if (!strcmp(mpd_desc->scheme_id_uri, "http://dashif.org/guidelines/trickmode") ) { + continue; + } else { + //we don't know any defined scheme for now + GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, ("[DASH] AdaptationSet with unrecognized EssentialProperty %s - ignoring because not supported\n", mpd_desc->scheme_id_uri)); + disabled = 1; + break; + } + } + if (disabled) { + continue; + } + + cp_supported = 1; + for (j=0; jadaptation_set->content_protection); j++) { + GF_MPD_Descriptor *mpd_desc = gf_list_get(group->adaptation_set->content_protection, j); + //we don't know any defined scheme for now + if (strcmp(mpd_desc->scheme_id_uri, "urn:mpeg:dash:mp4protection:2011")) { + GF_LOG(GF_LOG_INFO, GF_LOG_DASH, ("[DASH] AdaptationSet with unrecognized ContentProtection %s\n", mpd_desc->scheme_id_uri)); + cp_supported = 0; + } else { + cp_supported = 1; + break; + } + } + if (!cp_supported) { + GF_LOG(GF_LOG_WARNING, GF_LOG_DASH, ("[DASH] AdaptationSet with no supported ContentProtection - ignoring\n")); + continue; + } + + for (j=0; jadaptation_set->supplemental_properties); j++) { + GF_MPD_Descriptor *mpd_desc = gf_list_get(group->adaptation_set->supplemental_properties, j); + if (mpd_desc && mpd_desc->scheme_id_uri && !strcmp(mpd_desc->scheme_id_uri, "urn:mpeg:dash:srd:2014") && mpd_desc->value) { + u32 id, w, h, res; + w = h = 0; + res = sscanf(mpd_desc->value, "%d,%d,%d,%d,%d,%d,%d", &id, &group->srd_x, &group->srd_y, &group->srd_w, &group->srd_h, &w, &h); + if (res != 7) { + res = sscanf(mpd_desc->value, "%d,%d,%d,%d,%d", &id, &group->srd_x, &group->srd_y, &group->srd_w, &group->srd_h); + if (res != 5) res=0; + } + if (res) { + group->srd_desc = gf_dash_get_srd_desc(dash, id, GF_TRUE); + if (!w) w = group->srd_x + group->srd_w; + if (!h) h = group->srd_y + group->srd_h; + + if (w>group->srd_desc->srd_fw) + group->srd_desc->srd_fw = w; + if (h>group->srd_desc->srd_fh) + group->srd_desc->srd_fh = h; + } + } + } + +sidx_pending: + /*translate from single-indexed file to SegmentList*/ + gf_dash_setup_single_index_mode(group); + if (group->download_sidx_pending) { + return GF_NOT_READY; + } + + /* Select the appropriate representation in the given period */ + for (rep_i = 0; rep_i < nb_rep; rep_i++) { + GF_MPD_Representation *rep = gf_list_get(group->adaptation_set->representations, rep_i); + if (rep->width && rep->height) group_has_video = GF_TRUE; + } + + //sort by ascending bandwidth and quality + for (rep_i = 1; rep_i < nb_rep; rep_i++) { + Bool swap=GF_FALSE; + GF_MPD_Representation *r2 = gf_list_get(group->adaptation_set->representations, rep_i); + GF_MPD_Representation *r1 = gf_list_get(group->adaptation_set->representations, rep_i-1); + if (r1->bandwidth > r2->bandwidth) { + swap=GF_TRUE; + } else if ((r1->bandwidth == r2->bandwidth) && (r1->quality_rankingquality_ranking)) { + swap=GF_TRUE; + } + if (swap) { + gf_list_rem(group->adaptation_set->representations, rep_i); + gf_list_insert(group->adaptation_set->representations, r2, rep_i-1); + rep_i=0; + } + } + +select_active_rep: + group->min_representation_bitrate = (u32) -1; + active_rep_found = GF_FALSE; + + for (rep_i = 0; rep_i < nb_rep; rep_i++) { + u32 first_select_mode = dash->first_select_mode; + GF_MPD_Representation *rep = gf_list_get(group->adaptation_set->representations, rep_i); + if (rep->playback.disabled) + + +// ... (7450 more chars) +``` diff --git a/tasks/csa159/pair_138462/task_prompt.md b/tasks/csa159/pair_138462/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..c88f28973c1aa0810129c443c74de4038d142f87 --- /dev/null +++ b/tasks/csa159/pair_138462/task_prompt.md @@ -0,0 +1,378 @@ +# 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 did not converge because refinement_accepted failed with outcome feedback_required after one round. +- A validation command observed summary.json as missing, but the rollout recorded no diagnosis, corrective action, or successful retry for that failure. +- The failure was procedural rather than semantic: compilation, differential detection, code verification, and cross-validation succeeded, and the path-sensitive mechanism was judged adequate. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve the previously accepted path-sensitive CSA mechanism and a semantic score at or above the configured threshold. +- Preserve process quality at or above the configured threshold. +- Preserve patch-anchor independence and freedom from patch-local hardcoding. + +### Required semantic proof + +- At a string-reading sink, prove that the consumed pointer argument is a pointer-typed arrow member load whose value may be null on the current execution path. +- Report the vulnerable pre-patch calls because mpd_desc->value is not constrained non-null when passed as argument zero to sscanf. +- Suppress the corresponding post-patch calls because the short-circuit condition mpd_desc && mpd_desc->scheme_id_uri && ... && mpd_desc->value constrains the exact value reaching sscanf to non-null. +- Distinguish possibly-null or definitely-null values from values proven non-null; do not equate absence of a syntactic guard with vulnerability. +- Keep the proof intraprocedural because no fact must propagate across function boundaries for this defect. + +### Implementation constraints + +- Use a path-sensitive sink callback such as check::PreCall so the checker observes the exact argument SVal and ProgramState immediately before the dereferencing call. +- Query the current state's nullness constraint for the sink argument and suppress only when that value is constrained non-null. +- Restrict candidate arguments to pointer-typed arrow MemberExpr field loads after removing parentheses and implicit casts; skip unknown or undefined SVals. +- Model only argument positions that known string-reading callees dereference, including argument zero of sscanf. +- Emit a nonfatal path-sensitive report at the offending argument or call in the patched function, with ranges local to the sink. +- Use semantic callee and expression information rather than source text, changed-line coordinates, function names, variable names, type names, URI literals, or the specific field name from the patch. +- Keep scope project-general and do not add interprocedural result tracking or general taint propagation. + +### Validation checklist + +- Compile the new checker plugin successfully against the supplied Clang Static Analyzer API and verify that its registration is discoverable. +- Scan both supplied revisions with identical analyzer settings and confirm exactly two relevant reports in the buggy revision and zero in the patched revision. +- Confirm both disappearing reports are in src/media_tools/dash_client.c within gf_dash_setup_period and remain near the changed guard and sscanf sinks, with no reports in non-patched functions. +- Inspect analyzer paths to confirm the buggy reports arise from unconstrained mpd_desc->value at sscanf and patched suppression arises from the non-null path constraint on that same SVal. +- Verify successful code verification and cross-validation, including N_buggy=2, N_patched=0, relevance ratio 1.0, and no unrelated disappeared warnings. +- Run the refinement stage through acceptance; when any artifact or validation command fails, record the diagnosis, apply a corrective synthesis step, and rerun to a successful result. +- Verify all required artifacts, including summary output, exist before the final validation command so the prior missing-summary failure cannot recur. +- Recheck that no source coordinates, patch text, mpd_desc, GF_MPD_Descriptor, value, gf_dash_setup_period, or URI literal controls detection. + +### Avoid and forbidden regressions + +- Do not replace ProgramState reasoning with syntax-only matching, source-substring searches, or standalone CFG dominance checks. +- Do not reuse, repair, resume, reconstruct, or depend on the prior checker implementation. +- Do not report every unchecked pointer or every string-call argument without the required field-load and sink-argument semantics. +- Do not suppress merely because any nearby null check exists; the non-null constraint must apply to the exact SVal reaching the sink on that path. +- Do not introduce tracking of gf_list_get results when the vulnerability can be established directly from the sink argument's nullness. +- Do not broaden scope to variadic format parsing such as GF_LOG or unrelated null-dereference classes without source evidence. +- Do not treat a successful scan as sufficient after a validation failure; refinement must finish accepted and clean. diff --git a/tasks/csa159/pair_138473/checker_template.cpp b/tasks/csa159/pair_138473/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138473/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_138473/config.json b/tasks/csa159/pair_138473/config.json new file mode 100644 index 0000000000000000000000000000000000000000..7d9698fcc3928810d979f0781ca345c42cd1e968 --- /dev/null +++ b/tasks/csa159/pair_138473/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "saitoha_libsixel", + "before_commit": "77c8077232baaa3b10638caec47a7aa9d78b2fb4", + "after_commit": "e17c0765ed708186865f0f8badfed44181063776", + "repo_path": "/workspace/repo/saitoha/libsixel", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/saitoha_libsixel/2df64373e58c4f48fbb72032a66473e71fc2a6ce/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/saitoha_libsixel/2df64373e58c4f48fbb72032a66473e71fc2a6ce/compile_commands.json", + "changed_files": [ + "src/frompnm.c" + ], + "commit_message": "fix issue that the width and the deps miss checks", + "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_138473/patch.diff b/tasks/csa159/pair_138473/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..993ad8c7ce45532092926fd758907a2632dd8b42 --- /dev/null +++ b/tasks/csa159/pair_138473/patch.diff @@ -0,0 +1,22 @@ +diff --git a/src/frompnm.c b/src/frompnm.c +index 44529db..86d0c03 100644 +--- a/src/frompnm.c ++++ b/src/frompnm.c +@@ -166,7 +166,7 @@ load_pnm(unsigned char /* in */ *p, + height = 0; + for (; *s >= '0' && *s <= '9'; ++s) { + height = height * 10 + (*s - '0'); +- if (width > PNM_MAX_WIDTH) { ++ if (height > PNM_MAX_HEIGHT) { + status = SIXEL_RUNTIME_ERROR; + sprintf( + message, +@@ -193,7 +193,7 @@ load_pnm(unsigned char /* in */ *p, + for (; *s >= '0' && *s <= '9'; ++s) { + deps = deps * 10 + (*s - '0'); + } +- if (width > PNM_MAX_WIDTH) { ++ if (deps > PNM_MAX_DEPTH) { + status = SIXEL_RUNTIME_ERROR; + sprintf( + message, \ No newline at end of file diff --git a/tasks/csa159/pair_138473/post_functions.txt b/tasks/csa159/pair_138473/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..5fd5f568825b80548e27eab63af2416c3c1e7aac --- /dev/null +++ b/tasks/csa159/pair_138473/post_functions.txt @@ -0,0 +1,266 @@ +### File: src/frompnm.c +```c +SIXELSTATUS +load_pnm(unsigned char /* in */ *p, + int /* in */ length, + sixel_allocator_t /* in */ *allocator, + unsigned char /* out */ **result, + int /* out */ *psx, + int /* out */ *psy, + unsigned char /* out */ **ppalette, + int /* out */ *pncolors, + int /* out */ *ppixelformat) +{ + SIXELSTATUS status = SIXEL_FALSE; + int n; + int i; + int b; + int x; + int y; + int component[3]; + int ascii; + int maps; + int width; + int height; + int deps; + char message[256]; + unsigned char *s; + unsigned char *end; + unsigned char tmp[256]; + + (void) ppalette; + (void) pncolors; + + width = height = 0; + deps = 1; + + end = p + length; + p = pnm_get_line(p, end, tmp); + *result = NULL; + + if (tmp[0] != 'P') { + status = SIXEL_RUNTIME_ERROR; + sixel_helper_set_additional_message( + "load_pnm: first character is not 'P'."); + goto end; + } + + switch(tmp[1]) { + case '1': + /* Portable bitmap - ASCII */ + ascii = 1; + maps = 0; + break; + case '2': + /* Portable graymap - ASCII */ + ascii = 1; + maps = 1; + break; + case '3': + /* Portable pixmap - ASCII */ + ascii = 1; + maps = 2; + break; + case '4': + /* Portable bitmap - Binary */ + ascii = 0; + maps = 0; + break; + case '5': + /* Portable graymap - Binary */ + ascii = 0; + maps = 1; + break; + case '6': + /* Portable pixmap - Binary */ + ascii = 0; + maps = 2; + break; + default: + goto unknown; + } + + p = pnm_get_line(p, end, tmp); + if (p == end) { + /* check empty content */ + /* Issue 71: https://github.com/saitoha/libsixel/issues/71 */ + goto invalid; + } + + s = tmp; + + /* parse width */ + width = 0; + for (; *s >= '0' && *s <= '9'; ++s) { + width = width * 10 + (*s - '0'); + if (width > PNM_MAX_WIDTH) { + status = SIXEL_RUNTIME_ERROR; + sprintf( + message, + "load_pnm: image width exceeds the limit %d.", + PNM_MAX_WIDTH); + sixel_helper_set_additional_message(message); + goto end; + } + } + + while (*s == ' ') { + s++; + } + + /* parse height */ + height = 0; + for (; *s >= '0' && *s <= '9'; ++s) { + height = height * 10 + (*s - '0'); + if (height > PNM_MAX_HEIGHT) { + status = SIXEL_RUNTIME_ERROR; + sprintf( + message, + "load_pnm: image height exceeds the limit %d.", + PNM_MAX_HEIGHT); + sixel_helper_set_additional_message(message); + goto end; + } + } + + while (*s != '\0') { + s++; + } + + if (maps > 0) { + p = pnm_get_line(p, end, tmp); + if (p == end) { + /* check empty content */ + /* Issue 71: https://github.com/saitoha/libsixel/issues/71 */ + goto invalid; + } + s = tmp; + deps = 0; + for (; *s >= '0' && *s <= '9'; ++s) { + deps = deps * 10 + (*s - '0'); + } + if (deps > PNM_MAX_DEPTH) { + status = SIXEL_RUNTIME_ERROR; + sprintf( + message, + "load_pnm: image depth exceeds the limit %d.", + PNM_MAX_DEPTH); + sixel_helper_set_additional_message(message); + goto end; + } + } + + if (width < 1 || height < 1 || deps < 1) { + goto invalid; + } + + *result = (unsigned char *)sixel_allocator_malloc( + allocator, + (size_t)(width * height * 3 + 1)); + + if (*result == NULL) { + sixel_helper_set_additional_message( + "load_pnm: sixel_allocator_malloc() failed."); + status = SIXEL_BAD_ALLOCATION; + goto end; + } + + memset(*result, 0, (size_t)(width * height * 3 + 1)); + + for (y = 0 ; y < height ; y++) { + for (x = 0 ; x < width ; x++) { + b = (maps == 2 ? 3 : 1); + for (i = 0 ; i < b ; i++) { + if (ascii) { + while (*s == '\0') { + if (p >= end) { + break; + } + p = pnm_get_line(p, end, tmp); + s = tmp; + } + n = 0; + if (maps == 0) { + n = *s == '0'; + if (*s != '\0') + s++; + } else { + while (isdigit(*s) && n >= 0) { + n = n * 10 + (*s++ - '0'); + } + while (*s == ' ') { + s++; + } + } + } else { + if (p >= end) { + break; + } + if (maps == 0) { + n = ((*p << (x & 0x7) >> 0x7) & 1) == 0; + if ((x & 0x7) == 0x7) { + p++; + } + } else { + n = *(p++); + } + } + component[i] = n; + } + if (i < b) { + break; + } + + switch(maps) { + case 0: /* bitmap */ + if (component[0] == 0) { + component[0] = component[1] = component[2] = 0; + } else { + component[0] = component[1] = component[2] = 255; + } + break; + case 1: /* graymap */ + component[0] = component[1] = component[2] = component[0] * 255 / deps; + break; + case 2: /* pixmap */ + component[0] = (component[0] * 255 / deps); + component[1] = (component[1] * 255 / deps); + component[2] = (component[2] * 255 / deps); + break; + default: + goto unknown; + } + + *(*result + (y * width + x) * 3 + 0) = component[0]; + *(*result + (y * width + x) * 3 + 1) = component[1]; + *(*result + (y * width + x) * 3 + 2) = component[2]; + } + } + + *psx = width; + *psy = height; + *ppixelformat = SIXEL_PIXELFORMAT_RGB888; + + status = SIXEL_OK; + goto end; + +unknown: + status = SIXEL_RUNTIME_ERROR; + sixel_helper_set_additional_message( + "load_pnm: unknown ppm format."); + sixel_allocator_free(allocator, *result); + *result = NULL; + goto end; + +invalid: + status = SIXEL_RUNTIME_ERROR; + sixel_helper_set_additional_message( + "load_pnm: invalid data detected."); + sixel_allocator_free(allocator, *result); + *result = NULL; + goto end; + +end: + return status; +} +``` diff --git a/tasks/csa159/pair_138473/pre_functions.txt b/tasks/csa159/pair_138473/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..b6179e2af748603c8c81ececb13724eb54bf3348 --- /dev/null +++ b/tasks/csa159/pair_138473/pre_functions.txt @@ -0,0 +1,266 @@ +### File: src/frompnm.c +```c +SIXELSTATUS +load_pnm(unsigned char /* in */ *p, + int /* in */ length, + sixel_allocator_t /* in */ *allocator, + unsigned char /* out */ **result, + int /* out */ *psx, + int /* out */ *psy, + unsigned char /* out */ **ppalette, + int /* out */ *pncolors, + int /* out */ *ppixelformat) +{ + SIXELSTATUS status = SIXEL_FALSE; + int n; + int i; + int b; + int x; + int y; + int component[3]; + int ascii; + int maps; + int width; + int height; + int deps; + char message[256]; + unsigned char *s; + unsigned char *end; + unsigned char tmp[256]; + + (void) ppalette; + (void) pncolors; + + width = height = 0; + deps = 1; + + end = p + length; + p = pnm_get_line(p, end, tmp); + *result = NULL; + + if (tmp[0] != 'P') { + status = SIXEL_RUNTIME_ERROR; + sixel_helper_set_additional_message( + "load_pnm: first character is not 'P'."); + goto end; + } + + switch(tmp[1]) { + case '1': + /* Portable bitmap - ASCII */ + ascii = 1; + maps = 0; + break; + case '2': + /* Portable graymap - ASCII */ + ascii = 1; + maps = 1; + break; + case '3': + /* Portable pixmap - ASCII */ + ascii = 1; + maps = 2; + break; + case '4': + /* Portable bitmap - Binary */ + ascii = 0; + maps = 0; + break; + case '5': + /* Portable graymap - Binary */ + ascii = 0; + maps = 1; + break; + case '6': + /* Portable pixmap - Binary */ + ascii = 0; + maps = 2; + break; + default: + goto unknown; + } + + p = pnm_get_line(p, end, tmp); + if (p == end) { + /* check empty content */ + /* Issue 71: https://github.com/saitoha/libsixel/issues/71 */ + goto invalid; + } + + s = tmp; + + /* parse width */ + width = 0; + for (; *s >= '0' && *s <= '9'; ++s) { + width = width * 10 + (*s - '0'); + if (width > PNM_MAX_WIDTH) { + status = SIXEL_RUNTIME_ERROR; + sprintf( + message, + "load_pnm: image width exceeds the limit %d.", + PNM_MAX_WIDTH); + sixel_helper_set_additional_message(message); + goto end; + } + } + + while (*s == ' ') { + s++; + } + + /* parse height */ + height = 0; + for (; *s >= '0' && *s <= '9'; ++s) { + height = height * 10 + (*s - '0'); + if (width > PNM_MAX_WIDTH) { + status = SIXEL_RUNTIME_ERROR; + sprintf( + message, + "load_pnm: image height exceeds the limit %d.", + PNM_MAX_HEIGHT); + sixel_helper_set_additional_message(message); + goto end; + } + } + + while (*s != '\0') { + s++; + } + + if (maps > 0) { + p = pnm_get_line(p, end, tmp); + if (p == end) { + /* check empty content */ + /* Issue 71: https://github.com/saitoha/libsixel/issues/71 */ + goto invalid; + } + s = tmp; + deps = 0; + for (; *s >= '0' && *s <= '9'; ++s) { + deps = deps * 10 + (*s - '0'); + } + if (width > PNM_MAX_WIDTH) { + status = SIXEL_RUNTIME_ERROR; + sprintf( + message, + "load_pnm: image depth exceeds the limit %d.", + PNM_MAX_DEPTH); + sixel_helper_set_additional_message(message); + goto end; + } + } + + if (width < 1 || height < 1 || deps < 1) { + goto invalid; + } + + *result = (unsigned char *)sixel_allocator_malloc( + allocator, + (size_t)(width * height * 3 + 1)); + + if (*result == NULL) { + sixel_helper_set_additional_message( + "load_pnm: sixel_allocator_malloc() failed."); + status = SIXEL_BAD_ALLOCATION; + goto end; + } + + memset(*result, 0, (size_t)(width * height * 3 + 1)); + + for (y = 0 ; y < height ; y++) { + for (x = 0 ; x < width ; x++) { + b = (maps == 2 ? 3 : 1); + for (i = 0 ; i < b ; i++) { + if (ascii) { + while (*s == '\0') { + if (p >= end) { + break; + } + p = pnm_get_line(p, end, tmp); + s = tmp; + } + n = 0; + if (maps == 0) { + n = *s == '0'; + if (*s != '\0') + s++; + } else { + while (isdigit(*s) && n >= 0) { + n = n * 10 + (*s++ - '0'); + } + while (*s == ' ') { + s++; + } + } + } else { + if (p >= end) { + break; + } + if (maps == 0) { + n = ((*p << (x & 0x7) >> 0x7) & 1) == 0; + if ((x & 0x7) == 0x7) { + p++; + } + } else { + n = *(p++); + } + } + component[i] = n; + } + if (i < b) { + break; + } + + switch(maps) { + case 0: /* bitmap */ + if (component[0] == 0) { + component[0] = component[1] = component[2] = 0; + } else { + component[0] = component[1] = component[2] = 255; + } + break; + case 1: /* graymap */ + component[0] = component[1] = component[2] = component[0] * 255 / deps; + break; + case 2: /* pixmap */ + component[0] = (component[0] * 255 / deps); + component[1] = (component[1] * 255 / deps); + component[2] = (component[2] * 255 / deps); + break; + default: + goto unknown; + } + + *(*result + (y * width + x) * 3 + 0) = component[0]; + *(*result + (y * width + x) * 3 + 1) = component[1]; + *(*result + (y * width + x) * 3 + 2) = component[2]; + } + } + + *psx = width; + *psy = height; + *ppixelformat = SIXEL_PIXELFORMAT_RGB888; + + status = SIXEL_OK; + goto end; + +unknown: + status = SIXEL_RUNTIME_ERROR; + sixel_helper_set_additional_message( + "load_pnm: unknown ppm format."); + sixel_allocator_free(allocator, *result); + *result = NULL; + goto end; + +invalid: + status = SIXEL_RUNTIME_ERROR; + sixel_helper_set_additional_message( + "load_pnm: invalid data detected."); + sixel_allocator_free(allocator, *result); + *result = NULL; + goto end; + +end: + return status; +} +``` diff --git a/tasks/csa159/pair_138473/task_prompt.md b/tasks/csa159/pair_138473/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_138473/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_138485/checker_template.cpp b/tasks/csa159/pair_138485/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138485/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_138485/config.json b/tasks/csa159/pair_138485/config.json new file mode 100644 index 0000000000000000000000000000000000000000..84047c2e0a71e1f3ade7980aa9e71e31cae6cf7c --- /dev/null +++ b/tasks/csa159/pair_138485/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "skvadrik_re2c", + "before_commit": "7b5643476bd99c994c4f51b8143f942982d85521", + "after_commit": "4d9c809355b574f2a58eac119f5e076c48e4d1e2", + "repo_path": "/workspace/repo/skvadrik/re2c", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/skvadrik_re2c/7b689f4231003c33f798db897ce39535e66c33bf/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/skvadrik_re2c/7b689f4231003c33f798db897ce39535e66c33bf/compile_commands.json", + "changed_files": [ + "src/regexp/nullable.cc" + ], + "commit_message": "Rewrite recursion into iteration (nullable RE).\n\nThis is to avoid stack overflow on large RE (especially on instrumented\nbuilds that have larger stack frames, like AddressSanitizer).\n\nPartial fix for #219 \"overflow-1.re test fails on system with small stack\".", + "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_138485/patch.diff b/tasks/csa159/pair_138485/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1b6739eb0dea274431e349094707d80212951094 --- /dev/null +++ b/tasks/csa159/pair_138485/patch.diff @@ -0,0 +1,168 @@ +diff --git a/src/regexp/nullable.cc b/src/regexp/nullable.cc +index 8156b47ef..40bbca79f 100644 +--- a/src/regexp/nullable.cc ++++ b/src/regexp/nullable.cc +@@ -11,43 +11,100 @@ + + + namespace re2c { ++namespace { + +-static bool nullable(const RESpec &spec, const RE *re, bool &trail) ++struct StackItem { ++ const RE *re; // current sub-RE ++ uint8_t succ; // index of the next sucessor to be visited ++}; ++ ++static bool nullable(const RESpec &spec, std::vector &stack, const RE *re0) + { +- if (trail) return true; +- +- switch (re->type) { +- case RE::NIL: return true; +- case RE::SYM: return false; +- case RE::ITER: +- return nullable(spec, re->iter.re, trail); +- case RE::TAG: +- trail |= trailing(spec.tags[re->tag.idx]); +- return true; +- case RE::ALT: +- return nullable(spec, re->alt.re1, trail) +- || nullable(spec, re->alt.re2, trail); +- case RE::CAT: +- return nullable(spec, re->cat.re1, trail) +- && nullable(spec, re->cat.re2, trail); ++ // the "nullable" status of the last sub-RE visited by DFS ++ bool null = false; ++ ++ const StackItem i0 = {re0, 0}; ++ stack.push_back(i0); ++ ++ while (!stack.empty()) { ++ const StackItem i = stack.back(); ++ stack.pop_back(); ++ ++ const RE *re = i.re; ++ if (re->type == RE::NIL) { ++ null = true; ++ } ++ else if (re->type == RE::SYM) { ++ null = false; ++ } ++ else if (re->type == RE::TAG) { ++ null = true; ++ ++ // Trailing context is always in top-level concatenation, and sub-RE ++ // are visited from left to right. Since we are here, sub-RE to the ++ // left of the trailing context is nullable (otherwise we would not ++ // recurse into the right sub-RE), therefore the whole RE is nullable. ++ if (trailing(spec.tags[re->tag.idx])) { ++ DASSERT(stack.size() == 1 && stack.back().re->type == RE::CAT); ++ stack.pop_back(); ++ break; ++ } ++ } ++ else if (re->type == RE::ALT) { ++ if (i.succ == 0) { ++ // recurse into the left sub-RE ++ StackItem k = {re, 1}; ++ stack.push_back(k); ++ StackItem j = {re->alt.re1, 0}; ++ stack.push_back(j); ++ } ++ else if (!null) { ++ // if the left sub-RE is nullable, so is alternative, so stop ++ // recursion; otherwise recurse into the right sub-RE ++ StackItem j = {re->alt.re2, 0}; ++ stack.push_back(j); ++ } ++ } ++ else if (re->type == RE::CAT) { ++ if (i.succ == 0) { ++ // recurse into the left sub-RE ++ StackItem k = {re, 1}; ++ stack.push_back(k); ++ StackItem j = {re->cat.re1, 0}; ++ stack.push_back(j); ++ } ++ else if (null) { ++ // if the left sub-RE is not nullable, neither is concatenation, ++ // so stop recursion; otherwise recurse into the right sub-RE ++ StackItem j = {re->cat.re2, 0}; ++ stack.push_back(j); ++ } ++ } ++ else if (re->type == RE::ITER) { ++ // iteration is nullable if the sub-RE is nullable ++ // (zero repetitions is represented with alternative) ++ StackItem j = {re->iter.re, 0}; ++ stack.push_back(j); ++ } + } +- return false; /* unreachable */ ++ ++ DASSERT(stack.empty()); ++ return null; + } + +-/* +- * warn about rules that match empty string +- * (including rules with nonempty trailing context) +- * false positives on partially self-shadowed rules like [^]? +- */ ++} // anonymous namespace ++ ++// Warn about rules that match empty string (including rules with nonempty ++// trailing context). False positives on partially self-shadowed rules like [^]? + void warn_nullable(const RESpec &spec, const std::string &cond) + { + // rule for <> is special -- it doesn't have a regexp + if (cond == "0") return; + ++ std::vector stack; + const size_t nre = spec.res.size(); + for (size_t i = 0; i < nre; ++i) { +- bool trail = false; +- if (nullable(spec, spec.res[i], trail)) { ++ if (nullable(spec, stack, spec.res[i])) { + spec.msg.warn.match_empty_string(spec.rules[i].code->loc, cond); + } + } +diff --git a/test/messages/nullable.i.c b/test/messages/nullable.i.c +new file mode 100644 +index 000000000..6122bca9f +--- /dev/null ++++ b/test/messages/nullable.i.c +@@ -0,0 +1,20 @@ ++/* Generated by re2c */ ++ ++{ ++ YYCTYPE yych; ++ if (YYLIMIT <= YYCURSOR) YYFILL(1); ++ yych = *YYCURSOR; ++ switch (yych) { ++ case 'b': goto yy3; ++ default: goto yy2; ++ } ++yy2: ++ {} ++yy3: ++ ++YYCURSOR; ++ YYCURSOR -= 1; ++ {} ++} ++ ++messages/nullable.i.re:3:9: warning: rule matches empty string [-Wmatch-empty-string] ++messages/nullable.i.re:4:3: warning: rule matches empty string [-Wmatch-empty-string] +diff --git a/test/messages/nullable.i.re b/test/messages/nullable.i.re +new file mode 100644 +index 000000000..096e82ff1 +--- /dev/null ++++ b/test/messages/nullable.i.re +@@ -0,0 +1,6 @@ ++/*!re2c ++ ++"" / "b" {} ++"" {} ++ ++*/ \ No newline at end of file diff --git a/tasks/csa159/pair_138485/post_functions.txt b/tasks/csa159/pair_138485/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..1eb401c9f22574a7bea0cec2022ddd72e0b874a2 --- /dev/null +++ b/tasks/csa159/pair_138485/post_functions.txt @@ -0,0 +1,104 @@ +### File: src/regexp/nullable.cc +```c +namespace re2c { +namespace { + +struct StackItem { + const RE *re; // current sub-RE + uint8_t succ; // index of the next sucessor to be visited +}; + +static bool nullable(const RESpec &spec, std::vector &stack, const RE *re0) +{ + // the "nullable" status of the last sub-RE visited by DFS + bool null = false; + + const StackItem i0 = {re0, 0}; + stack.push_back(i0); + + while (!stack.empty()) { + const StackItem i = stack.back(); + stack.pop_back(); + + const RE *re = i.re; + if (re->type == RE::NIL) { + null = true; + } + else if (re->type == RE::SYM) { + null = false; + } + else if (re->type == RE::TAG) { + null = true; + + // Trailing context is always in top-level concatenation, and sub-RE + // are visited from left to right. Since we are here, sub-RE to the + // left of the trailing context is nullable (otherwise we would not + // recurse into the right sub-RE), therefore the whole RE is nullable. + if (trailing(spec.tags[re->tag.idx])) { + DASSERT(stack.size() == 1 && stack.back().re->type == RE::CAT); + stack.pop_back(); + break; + } + } + else if (re->type == RE::ALT) { + if (i.succ == 0) { + // recurse into the left sub-RE + StackItem k = {re, 1}; + stack.push_back(k); + StackItem j = {re->alt.re1, 0}; + stack.push_back(j); + } + else if (!null) { + // if the left sub-RE is nullable, so is alternative, so stop + // recursion; otherwise recurse into the right sub-RE + StackItem j = {re->alt.re2, 0}; + stack.push_back(j); + } + } + else if (re->type == RE::CAT) { + if (i.succ == 0) { + // recurse into the left sub-RE + StackItem k = {re, 1}; + stack.push_back(k); + StackItem j = {re->cat.re1, 0}; + stack.push_back(j); + } + else if (null) { + // if the left sub-RE is not nullable, neither is concatenation, + // so stop recursion; otherwise recurse into the right sub-RE + StackItem j = {re->cat.re2, 0}; + stack.push_back(j); + } + } + else if (re->type == RE::ITER) { + // iteration is nullable if the sub-RE is nullable + // (zero repetitions is represented with alternative) + StackItem j = {re->iter.re, 0}; + stack.push_back(j); + } + } + + DASSERT(stack.empty()); + return null; +} + +} // anonymous namespace + +// Warn about rules that match empty string (including rules with nonempty +// trailing context). False positives on partially self-shadowed rules like [^]? +void warn_nullable(const RESpec &spec, const std::string &cond) +{ + // rule for <> is special -- it doesn't have a regexp + if (cond == "0") return; + + std::vector stack; + const size_t nre = spec.res.size(); + for (size_t i = 0; i < nre; ++i) { + if (nullable(spec, stack, spec.res[i])) { + spec.msg.warn.match_empty_string(spec.rules[i].code->loc, cond); + } + } +} + +} +``` diff --git a/tasks/csa159/pair_138485/pre_functions.txt b/tasks/csa159/pair_138485/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..b5112c6c08463a2fc95ad0abc22fedc72790d429 --- /dev/null +++ b/tasks/csa159/pair_138485/pre_functions.txt @@ -0,0 +1,47 @@ +### File: src/regexp/nullable.cc +```c +namespace re2c { + +static bool nullable(const RESpec &spec, const RE *re, bool &trail) +{ + if (trail) return true; + + switch (re->type) { + case RE::NIL: return true; + case RE::SYM: return false; + case RE::ITER: + return nullable(spec, re->iter.re, trail); + case RE::TAG: + trail |= trailing(spec.tags[re->tag.idx]); + return true; + case RE::ALT: + return nullable(spec, re->alt.re1, trail) + || nullable(spec, re->alt.re2, trail); + case RE::CAT: + return nullable(spec, re->cat.re1, trail) + && nullable(spec, re->cat.re2, trail); + } + return false; /* unreachable */ +} + +/* + * warn about rules that match empty string + * (including rules with nonempty trailing context) + * false positives on partially self-shadowed rules like [^]? + */ +void warn_nullable(const RESpec &spec, const std::string &cond) +{ + // rule for <> is special -- it doesn't have a regexp + if (cond == "0") return; + + const size_t nre = spec.res.size(); + for (size_t i = 0; i < nre; ++i) { + bool trail = false; + if (nullable(spec, spec.res[i], trail)) { + spec.msg.warn.match_empty_string(spec.rules[i].code->loc, cond); + } + } +} + +} +``` diff --git a/tasks/csa159/pair_138485/task_prompt.md b/tasks/csa159/pair_138485/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..a45dad8a2fe65ba2cbeadf3a7e6ad35da3bc2806 --- /dev/null +++ b/tasks/csa159/pair_138485/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: `interprocedural_dataflow` + +### Current failure diagnosis + +- The rollout missed the process-quality threshold despite successful compilation, differential detection, code verification, refinement, and an adequate semantic score. +- The safety analysis was under-specified for unsigned counters: decrement after a positive guard can wrap, so strict syntactic decrease alone does not always prove a finite bound. +- The implementation examined only the first discovered controlling guard, which can miss interactions among multiple guards governing the recursive sink. +- The implementation accepted post-decrement and addition of a negative constant although the stated safety contract only justified subtraction by a positive constant or prefix decrement. +- Validation required avoidable recovery cycles for LLVM container limits, the available CallEvent API, analyzer language mode, and malformed refinement input. + +### 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 cross-procedure CSA mechanism level and a semantic score at or above the configured threshold. +- Preserve process quality at or above the configured threshold. +- Remain independent of patch anchors and patch-local hardcoding. + +### Required semantic proof + +- Prove that the call site participates in direct or mutual recursion by establishing that caller and callee belong to the same recursive call-graph cycle using canonical function identities. +- Prove that a recursive argument descends to a child node through at least one member-access step rooted at the recursive function's pointer-to-record parameter and yields a record handle. +- Report only when recursion depth can follow structural nesting and no effective finite depth bound governs the recursive call. +- Treat a bound as effective only when its guard controls every path reaching the sink, establishes a usable positive counter value, and the corresponding parameter slot transfers that same counter with a proven strictly decreasing, non-wrapping operation. +- Do not infer safety merely from termination on finite acyclic structures; the defect is native stack depth proportional to externally determined nesting. +- Recognize the patched worklist traversal as safe because it removes recursive call-cycle edges and therefore removes one native stack frame per tree level. + +### Implementation constraints + +- Use a cross-procedure CSA design, such as check::PreCall with CallEvent plus canonical FunctionDecl call-graph summaries or an equivalent interprocedural dataflow representation. +- Evaluate recursion at the pre-call sink so callee identity, caller LocationContext, argument expressions, and parameter-slot transfer remain available. +- Use CFG reachability or dominance for guard-to-sink reasoning; account for branch containment and dominating early exits instead of accepting a condition merely because it occurs lexically in the function. +- Evaluate all relevant controlling guards and require the guard variable to match the counter transferred in the corresponding recursive argument position. +- Model signedness and overflow sufficiently to reject unsigned wraparound and any transfer that is not proven to make finite progress toward the guarded base case. +- Emit one non-fatal path-sensitive diagnostic per qualifying recursive call expression, with the report and source range anchored at that call. +- Keep scope project-general: use declaration identity, types, call relationships, expression structure, CFG facts, and argument transfer without project names, function names, field names, paths, line numbers, or commit identifiers. + +### Validation checklist + +- Compile against the supplied LLVM/Clang API and constraints on the first validation pass, including supported CallEvent accessors and valid LLVM container template sizes. +- Run the checker in the correct C++ language mode on the vulnerable and patched sources; require five vulnerable reports and zero patched reports. +- Confirm all vulnerable diagnostics are located at the recursive call expressions, with median distance zero from the relevant old patch locations. +- Confirm no warnings occur in non-patched functions and all vulnerable warnings disappear after recursive traversal is replaced by the explicit worklist. +- Test direct self-recursion and mutual recursion with structural child transfer, and require reports when no effective bound exists. +- Test safe dominating guards with matching decreasing counters, including signedness and overflow boundaries, and require suppression only when finite progress is proven. +- Test unrelated guards, non-exiting guards, wrong counter variables, unchanged or increasing transfers, post-decrement ambiguity, negative addition, and multiple controlling guards. +- Run refinement to an accepted or clean outcome and retain G6, hard-validation, semantic, anchor-free, hardcoding-free, and process-score checks. + +### Avoid and forbidden regressions + +- Do not reduce the synthesis to syntax-only or intraprocedural control-flow matching; recursive cycle membership and argument transfer cross function boundaries. +- Do not use check::PostCall or check::BeginFunction when they lose pre-recursion argument evidence or move the diagnostic away from the stack-consuming call. +- Do not use a ProgramState recursion-depth counter as a substitute for proving structural descent and call-cycle membership, because recursive inlining may be pruned and a counter alone does not establish the vulnerability. +- Do not accept any conditional anywhere in the function as a bound without proving that it dominates or otherwise controls every path to the sink. +- Do not accept a syntactically decreasing expression without proving parameter-slot correspondence, progress toward the base case, and absence of wraparound. +- Do not claim that pointer-to-record descent independently proves external-input provenance; retain it only as the evidence-supported structural proxy. +- Do not specialize detection to nullable, RE, RESpec, re2c fields, changed lines, patch text, or other local anchors. +- Do not repeat avoidable compile and validation churn caused by unsupported APIs, invalid language mode, container-limit violations, or malformed test fixtures. diff --git a/tasks/csa159/pair_138511/checker_template.cpp b/tasks/csa159/pair_138511/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138511/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_138511/config.json b/tasks/csa159/pair_138511/config.json new file mode 100644 index 0000000000000000000000000000000000000000..a29cc1953b97eb90cb268b6e79950eeed08ba968 --- /dev/null +++ b/tasks/csa159/pair_138511/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "strukturag_libde265", + "before_commit": "436466daed8cdb6a3ad1fdefa1410140a7d5f9e5", + "after_commit": "c7891e412106130b83f8e8ea8b7f907e9449b658", + "repo_path": "/workspace/repo/strukturag/libde265", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/strukturag_libde265/1d2d118e71449d08e2c9b8f4ab9f3c99655c5641/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/strukturag_libde265/1d2d118e71449d08e2c9b8f4ab9f3c99655c5641/compile_commands.json", + "changed_files": [ + "libde265/image.cc" + ], + "commit_message": "fix reallocation of metadata array when ctb size changes (thanks to Ana K.)", + "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_138511/patch.diff b/tasks/csa159/pair_138511/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c250f6625ec283da74dd2ec9257f2bbbf4077d11 --- /dev/null +++ b/tasks/csa159/pair_138511/patch.diff @@ -0,0 +1,29 @@ +diff --git a/libde265/image.cc b/libde265/image.cc +index d388901..204faa5 100644 +--- a/libde265/image.cc ++++ b/libde265/image.cc +@@ -452,8 +452,9 @@ de265_error de265_image::alloc_image(int w,int h, enum de265_chroma c, + + // CTB info + +- if (ctb_info.width_in_units != sps->PicWidthInCtbsY || +- ctb_info.height_in_units != sps->PicHeightInCtbsY) ++ if (ctb_info.width_in_units != sps->PicWidthInCtbsY || ++ ctb_info.height_in_units != sps->PicHeightInCtbsY || ++ ctb_info.log2unitSize != sps->Log2CtbSizeY) + { + delete[] ctb_progress; + +diff --git a/libde265/image.h b/libde265/image.h +index 2bbe34b..e062fd3 100644 +--- a/libde265/image.h ++++ b/libde265/image.h +@@ -149,7 +149,7 @@ template class MetaDataArray + // private: + DataUnit* data; + int data_size; +- int log2unitSize; ++ uint8_t log2unitSize; + int width_in_units; + int height_in_units; + }; \ No newline at end of file diff --git a/tasks/csa159/pair_138511/post_functions.txt b/tasks/csa159/pair_138511/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..972e2e3c3bcfa1e8217f1ee529219658f9649fec --- /dev/null +++ b/tasks/csa159/pair_138511/post_functions.txt @@ -0,0 +1,250 @@ +### File: libde265/image.cc +```c +de265_error de265_image::alloc_image(int w,int h, enum de265_chroma c, + std::shared_ptr sps, bool allocMetadata, + decoder_context* dctx, + //encoder_context* ectx, + de265_PTS pts, void* user_data, + bool useCustomAllocFunc) +{ + //if (allocMetadata) { assert(sps); } + if (allocMetadata) { assert(sps); } + + if (sps) { this->sps = sps; } + + release(); /* TODO: review code for efficient allocation when arrays are already + allocated to the requested size. Without the release, the old image-data + will not be freed. */ + + static std::atomic s_next_image_ID(0); + ID = s_next_image_ID++; + removed_at_picture_id = std::numeric_limits::max(); + + decctx = dctx; + //encctx = ectx; + + // --- allocate image buffer --- + + chroma_format= c; + + width = w; + height = h; + chroma_width = w; + chroma_height= h; + + this->user_data = user_data; + this->pts = pts; + + de265_image_spec spec; + + uint8_t WinUnitX, WinUnitY; + + switch (chroma_format) { + case de265_chroma_mono: WinUnitX=1; WinUnitY=1; break; + case de265_chroma_420: WinUnitX=2; WinUnitY=2; break; + case de265_chroma_422: WinUnitX=2; WinUnitY=1; break; + case de265_chroma_444: WinUnitX=1; WinUnitY=1; break; + default: + assert(0); + WinUnitX = WinUnitY = 0; + } + + switch (chroma_format) { + case de265_chroma_420: + spec.format = de265_image_format_YUV420P8; + chroma_width = (chroma_width +1)/2; + chroma_height = (chroma_height+1)/2; + SubWidthC = 2; + SubHeightC = 2; + break; + + case de265_chroma_422: + spec.format = de265_image_format_YUV422P8; + chroma_width = (chroma_width+1)/2; + SubWidthC = 2; + SubHeightC = 1; + break; + + case de265_chroma_444: + spec.format = de265_image_format_YUV444P8; + SubWidthC = 1; + SubHeightC = 1; + break; + + case de265_chroma_mono: + spec.format = de265_image_format_mono8; + chroma_width = 0; + chroma_height= 0; + SubWidthC = 1; + SubHeightC = 1; + break; + + default: + assert(false); + break; + } + + if (chroma_format != de265_chroma_mono && sps) { + assert(sps->SubWidthC == SubWidthC); + assert(sps->SubHeightC == SubHeightC); + } + + spec.width = w; + spec.height = h; + spec.alignment = STANDARD_ALIGNMENT; + + + // conformance window cropping + + int left = sps ? sps->conf_win_left_offset : 0; + int right = sps ? sps->conf_win_right_offset : 0; + int top = sps ? sps->conf_win_top_offset : 0; + int bottom = sps ? sps->conf_win_bottom_offset : 0; + + if ((left+right)*WinUnitX >= width) { + return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE; + } + + if ((top+bottom)*WinUnitY >= height) { + return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE; + } + + width_confwin = width - (left+right)*WinUnitX; + height_confwin= height- (top+bottom)*WinUnitY; + chroma_width_confwin = chroma_width -left-right; + chroma_height_confwin= chroma_height-top-bottom; + + spec.crop_left = left *WinUnitX; + spec.crop_right = right*WinUnitX; + spec.crop_top = top *WinUnitY; + spec.crop_bottom= bottom*WinUnitY; + + spec.visible_width = width_confwin; + spec.visible_height= height_confwin; + + + BitDepth_Y = (sps==NULL) ? 8 : sps->BitDepth_Y; + BitDepth_C = (sps==NULL) ? 8 : sps->BitDepth_C; + + bpp_shift[0] = (BitDepth_Y <= 8) ? 0 : 1; + bpp_shift[1] = (BitDepth_C <= 8) ? 0 : 1; + bpp_shift[2] = bpp_shift[1]; + + + // allocate memory and set conformance window pointers + + void* alloc_userdata = NULL; + if (decctx) alloc_userdata = decctx->param_image_allocation_userdata; + // if (encctx) alloc_userdata = encctx->param_image_allocation_userdata; // actually not needed + + /* + if (encctx && useCustomAllocFunc) { + encoder_image_release_func = encctx->release_func; + + // if we do not provide a release function, use our own + + if (encoder_image_release_func == NULL) { + image_allocation_functions = de265_image::default_image_allocation; + } + else { + image_allocation_functions.get_buffer = NULL; + image_allocation_functions.release_buffer = NULL; + } + } + else*/ if (decctx && useCustomAllocFunc) { + image_allocation_functions = decctx->param_image_allocation_functions; + } + else { + image_allocation_functions = de265_image::default_image_allocation; + } + + bool mem_alloc_success = true; + + if (image_allocation_functions.get_buffer != NULL) { + mem_alloc_success = image_allocation_functions.get_buffer(decctx, &spec, this, + alloc_userdata); + + pixels_confwin[0] = pixels[0] + left*WinUnitX + top*WinUnitY*stride; + + if (chroma_format != de265_chroma_mono) { + pixels_confwin[1] = pixels[1] + left + top*chroma_stride; + pixels_confwin[2] = pixels[2] + left + top*chroma_stride; + } + else { + pixels_confwin[1] = NULL; + pixels_confwin[2] = NULL; + } + + // check for memory shortage + + if (!mem_alloc_success) + { + return DE265_ERROR_OUT_OF_MEMORY; + } + } + + //alloc_functions = *allocfunc; + //alloc_userdata = userdata; + + // --- allocate decoding info arrays --- + + if (allocMetadata) { + // intra pred mode + + mem_alloc_success &= intraPredMode.alloc(sps->PicWidthInMinPUs, sps->PicHeightInMinPUs, + sps->Log2MinPUSize); + + mem_alloc_success &= intraPredModeC.alloc(sps->PicWidthInMinPUs, sps->PicHeightInMinPUs, + sps->Log2MinPUSize); + + // cb info + + mem_alloc_success &= cb_info.alloc(sps->PicWidthInMinCbsY, sps->PicHeightInMinCbsY, + sps->Log2MinCbSizeY); + + // pb info + + int puWidth = sps->PicWidthInMinCbsY << (sps->Log2MinCbSizeY -2); + int puHeight = sps->PicHeightInMinCbsY << (sps->Log2MinCbSizeY -2); + + mem_alloc_success &= pb_info.alloc(puWidth,puHeight, 2); + + + // tu info + + mem_alloc_success &= tu_info.alloc(sps->PicWidthInTbsY, sps->PicHeightInTbsY, + sps->Log2MinTrafoSize); + + // deblk info + + int deblk_w = (sps->pic_width_in_luma_samples +3)/4; + int deblk_h = (sps->pic_height_in_luma_samples+3)/4; + + mem_alloc_success &= deblk_info.alloc(deblk_w, deblk_h, 2); + + // CTB info + + if (ctb_info.width_in_units != sps->PicWidthInCtbsY || + ctb_info.height_in_units != sps->PicHeightInCtbsY || + ctb_info.log2unitSize != sps->Log2CtbSizeY) + { + delete[] ctb_progress; + + mem_alloc_success &= ctb_info.alloc(sps->PicWidthInCtbsY, sps->PicHeightInCtbsY, + sps->Log2CtbSizeY); + + ctb_progress = new de265_progress_lock[ ctb_info.data_size ]; + } + + + // check for memory shortage + + if (!mem_alloc_success) + { + return DE265_ERROR_OUT_OF_MEMORY; + } + } + + return DE265_OK; +} +``` diff --git a/tasks/csa159/pair_138511/pre_functions.txt b/tasks/csa159/pair_138511/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..7cff3617afc9dfd3eae12f851e4dac6ec58af8e7 --- /dev/null +++ b/tasks/csa159/pair_138511/pre_functions.txt @@ -0,0 +1,249 @@ +### File: libde265/image.cc +```c +de265_error de265_image::alloc_image(int w,int h, enum de265_chroma c, + std::shared_ptr sps, bool allocMetadata, + decoder_context* dctx, + //encoder_context* ectx, + de265_PTS pts, void* user_data, + bool useCustomAllocFunc) +{ + //if (allocMetadata) { assert(sps); } + if (allocMetadata) { assert(sps); } + + if (sps) { this->sps = sps; } + + release(); /* TODO: review code for efficient allocation when arrays are already + allocated to the requested size. Without the release, the old image-data + will not be freed. */ + + static std::atomic s_next_image_ID(0); + ID = s_next_image_ID++; + removed_at_picture_id = std::numeric_limits::max(); + + decctx = dctx; + //encctx = ectx; + + // --- allocate image buffer --- + + chroma_format= c; + + width = w; + height = h; + chroma_width = w; + chroma_height= h; + + this->user_data = user_data; + this->pts = pts; + + de265_image_spec spec; + + uint8_t WinUnitX, WinUnitY; + + switch (chroma_format) { + case de265_chroma_mono: WinUnitX=1; WinUnitY=1; break; + case de265_chroma_420: WinUnitX=2; WinUnitY=2; break; + case de265_chroma_422: WinUnitX=2; WinUnitY=1; break; + case de265_chroma_444: WinUnitX=1; WinUnitY=1; break; + default: + assert(0); + WinUnitX = WinUnitY = 0; + } + + switch (chroma_format) { + case de265_chroma_420: + spec.format = de265_image_format_YUV420P8; + chroma_width = (chroma_width +1)/2; + chroma_height = (chroma_height+1)/2; + SubWidthC = 2; + SubHeightC = 2; + break; + + case de265_chroma_422: + spec.format = de265_image_format_YUV422P8; + chroma_width = (chroma_width+1)/2; + SubWidthC = 2; + SubHeightC = 1; + break; + + case de265_chroma_444: + spec.format = de265_image_format_YUV444P8; + SubWidthC = 1; + SubHeightC = 1; + break; + + case de265_chroma_mono: + spec.format = de265_image_format_mono8; + chroma_width = 0; + chroma_height= 0; + SubWidthC = 1; + SubHeightC = 1; + break; + + default: + assert(false); + break; + } + + if (chroma_format != de265_chroma_mono && sps) { + assert(sps->SubWidthC == SubWidthC); + assert(sps->SubHeightC == SubHeightC); + } + + spec.width = w; + spec.height = h; + spec.alignment = STANDARD_ALIGNMENT; + + + // conformance window cropping + + int left = sps ? sps->conf_win_left_offset : 0; + int right = sps ? sps->conf_win_right_offset : 0; + int top = sps ? sps->conf_win_top_offset : 0; + int bottom = sps ? sps->conf_win_bottom_offset : 0; + + if ((left+right)*WinUnitX >= width) { + return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE; + } + + if ((top+bottom)*WinUnitY >= height) { + return DE265_ERROR_CODED_PARAMETER_OUT_OF_RANGE; + } + + width_confwin = width - (left+right)*WinUnitX; + height_confwin= height- (top+bottom)*WinUnitY; + chroma_width_confwin = chroma_width -left-right; + chroma_height_confwin= chroma_height-top-bottom; + + spec.crop_left = left *WinUnitX; + spec.crop_right = right*WinUnitX; + spec.crop_top = top *WinUnitY; + spec.crop_bottom= bottom*WinUnitY; + + spec.visible_width = width_confwin; + spec.visible_height= height_confwin; + + + BitDepth_Y = (sps==NULL) ? 8 : sps->BitDepth_Y; + BitDepth_C = (sps==NULL) ? 8 : sps->BitDepth_C; + + bpp_shift[0] = (BitDepth_Y <= 8) ? 0 : 1; + bpp_shift[1] = (BitDepth_C <= 8) ? 0 : 1; + bpp_shift[2] = bpp_shift[1]; + + + // allocate memory and set conformance window pointers + + void* alloc_userdata = NULL; + if (decctx) alloc_userdata = decctx->param_image_allocation_userdata; + // if (encctx) alloc_userdata = encctx->param_image_allocation_userdata; // actually not needed + + /* + if (encctx && useCustomAllocFunc) { + encoder_image_release_func = encctx->release_func; + + // if we do not provide a release function, use our own + + if (encoder_image_release_func == NULL) { + image_allocation_functions = de265_image::default_image_allocation; + } + else { + image_allocation_functions.get_buffer = NULL; + image_allocation_functions.release_buffer = NULL; + } + } + else*/ if (decctx && useCustomAllocFunc) { + image_allocation_functions = decctx->param_image_allocation_functions; + } + else { + image_allocation_functions = de265_image::default_image_allocation; + } + + bool mem_alloc_success = true; + + if (image_allocation_functions.get_buffer != NULL) { + mem_alloc_success = image_allocation_functions.get_buffer(decctx, &spec, this, + alloc_userdata); + + pixels_confwin[0] = pixels[0] + left*WinUnitX + top*WinUnitY*stride; + + if (chroma_format != de265_chroma_mono) { + pixels_confwin[1] = pixels[1] + left + top*chroma_stride; + pixels_confwin[2] = pixels[2] + left + top*chroma_stride; + } + else { + pixels_confwin[1] = NULL; + pixels_confwin[2] = NULL; + } + + // check for memory shortage + + if (!mem_alloc_success) + { + return DE265_ERROR_OUT_OF_MEMORY; + } + } + + //alloc_functions = *allocfunc; + //alloc_userdata = userdata; + + // --- allocate decoding info arrays --- + + if (allocMetadata) { + // intra pred mode + + mem_alloc_success &= intraPredMode.alloc(sps->PicWidthInMinPUs, sps->PicHeightInMinPUs, + sps->Log2MinPUSize); + + mem_alloc_success &= intraPredModeC.alloc(sps->PicWidthInMinPUs, sps->PicHeightInMinPUs, + sps->Log2MinPUSize); + + // cb info + + mem_alloc_success &= cb_info.alloc(sps->PicWidthInMinCbsY, sps->PicHeightInMinCbsY, + sps->Log2MinCbSizeY); + + // pb info + + int puWidth = sps->PicWidthInMinCbsY << (sps->Log2MinCbSizeY -2); + int puHeight = sps->PicHeightInMinCbsY << (sps->Log2MinCbSizeY -2); + + mem_alloc_success &= pb_info.alloc(puWidth,puHeight, 2); + + + // tu info + + mem_alloc_success &= tu_info.alloc(sps->PicWidthInTbsY, sps->PicHeightInTbsY, + sps->Log2MinTrafoSize); + + // deblk info + + int deblk_w = (sps->pic_width_in_luma_samples +3)/4; + int deblk_h = (sps->pic_height_in_luma_samples+3)/4; + + mem_alloc_success &= deblk_info.alloc(deblk_w, deblk_h, 2); + + // CTB info + + if (ctb_info.width_in_units != sps->PicWidthInCtbsY || + ctb_info.height_in_units != sps->PicHeightInCtbsY) + { + delete[] ctb_progress; + + mem_alloc_success &= ctb_info.alloc(sps->PicWidthInCtbsY, sps->PicHeightInCtbsY, + sps->Log2CtbSizeY); + + ctb_progress = new de265_progress_lock[ ctb_info.data_size ]; + } + + + // check for memory shortage + + if (!mem_alloc_success) + { + return DE265_ERROR_OUT_OF_MEMORY; + } + } + + return DE265_OK; +} +``` diff --git a/tasks/csa159/pair_138511/task_prompt.md b/tasks/csa159/pair_138511/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_138511/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_138570/checker_template.cpp b/tasks/csa159/pair_138570/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138570/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_138570/config.json b/tasks/csa159/pair_138570/config.json new file mode 100644 index 0000000000000000000000000000000000000000..769c35f14a78619d58e17012e64db4cc01dec09b --- /dev/null +++ b/tasks/csa159/pair_138570/config.json @@ -0,0 +1,23 @@ +{ + "project_id": "redis_redis", + "before_commit": "50188747cbfe43528d2719399a2a3c9599169445", + "after_commit": "bde62951accfc4bb0a516276fd0b4b307e140ce2", + "repo_path": "/workspace/repo/redis/redis", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/redis_redis/00cfa6ebbc8b04c9d156dca4ff94811523565226/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/redis_redis/00cfa6ebbc8b04c9d156dca4ff94811523565226/compile_commands.json", + "changed_files": [ + "src/anet.c", + "src/cluster_legacy.c", + "src/socket.c", + "src/tls.c", + "src/unix.c" + ], + "commit_message": "Retry accept() even if accepted connection reports an error (CVE-2025-48367)\n\nIn case of accept4() returns an error, we should check errno value and decide if we should retry accept4() without waiting next event loop iteration.", + "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_138570/patch.diff b/tasks/csa159/pair_138570/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b8588776f25e27320ac13ff1ad657fd47f69139c --- /dev/null +++ b/tasks/csa159/pair_138570/patch.diff @@ -0,0 +1,95 @@ +diff --git a/src/anet.c b/src/anet.c +index ad4ac49d8..d79434cef 100644 +--- a/src/anet.c ++++ b/src/anet.c +@@ -787,3 +787,27 @@ int anetIsFifo(char *filepath) { + if (stat(filepath, &sb) == -1) return 0; + return S_ISFIFO(sb.st_mode); + } ++ ++/* This function must be called after accept4() fails. It returns 1 if 'err' ++ * indicates accepted connection faced an error, and it's okay to continue ++ * accepting next connection by calling accept4() again. Other errors either ++ * indicate programming errors, e.g. calling accept() on a closed fd or indicate ++ * a resource limit has been reached, e.g. -EMFILE, open fd limit has been ++ * reached. In the latter case, caller might wait until resources are available. ++ * See accept4() documentation for details. */ ++int anetAcceptFailureNeedsRetry(int err) { ++ if (err == ECONNABORTED) ++ return 1; ++ ++#if defined(__linux__) ++ /* For details, see 'Error Handling' section on ++ * https://man7.org/linux/man-pages/man2/accept.2.html */ ++ if (err == ENETDOWN || err == EPROTO || err == ENOPROTOOPT || ++ err == EHOSTDOWN || err == ENONET || err == EHOSTUNREACH || ++ err == EOPNOTSUPP || err == ENETUNREACH) ++ { ++ return 1; ++ } ++#endif ++ return 0; ++} +diff --git a/src/anet.h b/src/anet.h +index 211421940..1d3aec9cd 100644 +--- a/src/anet.h ++++ b/src/anet.h +@@ -53,5 +53,6 @@ int anetPipe(int fds[2], int read_flags, int write_flags); + int anetSetSockMarkId(char *err, int fd, uint32_t id); + int anetGetError(int fd); + int anetIsFifo(char *filepath); ++int anetAcceptFailureNeedsRetry(int err); + + #endif +diff --git a/src/cluster_legacy.c b/src/cluster_legacy.c +index 88dc99691..6f1635e9e 100644 +--- a/src/cluster_legacy.c ++++ b/src/cluster_legacy.c +@@ -1253,6 +1253,8 @@ void clusterAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) { + while(max--) { + cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); + if (cfd == ANET_ERR) { ++ if (anetAcceptFailureNeedsRetry(errno)) ++ continue; + if (errno != EWOULDBLOCK) + serverLog(LL_VERBOSE, + "Error accepting cluster node: %s", server.neterr); +diff --git a/src/socket.c b/src/socket.c +index 241a54108..226b414f8 100644 +--- a/src/socket.c ++++ b/src/socket.c +@@ -308,6 +308,8 @@ static void connSocketAcceptHandler(aeEventLoop *el, int fd, void *privdata, int + while(max--) { + cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); + if (cfd == ANET_ERR) { ++ if (anetAcceptFailureNeedsRetry(errno)) ++ continue; + if (errno != EWOULDBLOCK) + serverLog(LL_WARNING, + "Accepting client connection: %s", server.neterr); +diff --git a/src/tls.c b/src/tls.c +index 65526c04f..a0733a4b6 100644 +--- a/src/tls.c ++++ b/src/tls.c +@@ -771,6 +771,8 @@ static void tlsAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) + while(max--) { + cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); + if (cfd == ANET_ERR) { ++ if (anetAcceptFailureNeedsRetry(errno)) ++ continue; + if (errno != EWOULDBLOCK) + serverLog(LL_WARNING, + "Accepting client connection: %s", server.neterr); +diff --git a/src/unix.c b/src/unix.c +index b61cb6d49..e26f0d27a 100644 +--- a/src/unix.c ++++ b/src/unix.c +@@ -102,6 +102,8 @@ static void connUnixAcceptHandler(aeEventLoop *el, int fd, void *privdata, int m + while(max--) { + cfd = anetUnixAccept(server.neterr, fd); + if (cfd == ANET_ERR) { ++ if (anetAcceptFailureNeedsRetry(errno)) ++ continue; + if (errno != EWOULDBLOCK) + serverLog(LL_WARNING, + "Accepting client connection: %s", server.neterr); \ No newline at end of file diff --git a/tasks/csa159/pair_138570/post_functions.txt b/tasks/csa159/pair_138570/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..4cc1a64abe8c06829af62c0ddc1d4ac143c0e6b0 --- /dev/null +++ b/tasks/csa159/pair_138570/post_functions.txt @@ -0,0 +1,140 @@ +### File: src/anet.c +```c +int anetIsFifo(char *filepath) { + struct stat sb; + if (stat(filepath, &sb) == -1) return 0; + return S_ISFIFO(sb.st_mode); +} +``` + +### File: src/cluster_legacy.c +```c +void clusterAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) { + int cport, cfd; + int max = MAX_CLUSTER_ACCEPTS_PER_CALL; + char cip[NET_IP_STR_LEN]; + int require_auth = TLS_CLIENT_AUTH_YES; + UNUSED(el); + UNUSED(mask); + UNUSED(privdata); + + /* If the server is starting up, don't accept cluster connections: + * UPDATE messages may interact with the database content. */ + if (server.masterhost == NULL && server.loading) return; + + while(max--) { + cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); + if (cfd == ANET_ERR) { + if (anetAcceptFailureNeedsRetry(errno)) + continue; + if (errno != EWOULDBLOCK) + serverLog(LL_VERBOSE, + "Error accepting cluster node: %s", server.neterr); + return; + } + + connection *conn = connCreateAccepted(server.el, connTypeOfCluster(), cfd, &require_auth); + + /* Make sure connection is not in an error state */ + if (connGetState(conn) != CONN_STATE_ACCEPTING) { + serverLog(LL_VERBOSE, + "Error creating an accepting connection for cluster node: %s", + connGetLastError(conn)); + connClose(conn); + return; + } + connEnableTcpNoDelay(conn); + connKeepAlive(conn,server.cluster_node_timeout / 1000 * 2); + + /* Use non-blocking I/O for cluster messages. */ + serverLog(LL_VERBOSE,"Accepting cluster node connection from %s:%d", cip, cport); + + /* Accept the connection now. connAccept() may call our handler directly + * or schedule it for later depending on connection implementation. + */ + if (connAccept(conn, clusterConnAcceptHandler) == C_ERR) { + if (connGetState(conn) == CONN_STATE_ERROR) + serverLog(LL_VERBOSE, + "Error accepting cluster node connection: %s", + connGetLastError(conn)); + connClose(conn); + return; + } + } +} +``` + +### File: src/socket.c +```c +static void connSocketAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) { + int cport, cfd; + int max = server.max_new_conns_per_cycle; + char cip[NET_IP_STR_LEN]; + UNUSED(mask); + UNUSED(privdata); + + while(max--) { + cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); + if (cfd == ANET_ERR) { + if (anetAcceptFailureNeedsRetry(errno)) + continue; + if (errno != EWOULDBLOCK) + serverLog(LL_WARNING, + "Accepting client connection: %s", server.neterr); + return; + } + serverLog(LL_VERBOSE,"Accepted %s:%d", cip, cport); + acceptCommonHandler(connCreateAcceptedSocket(el,cfd,NULL), 0, cip); + } +} +``` + +### File: src/tls.c +```c +static void tlsAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) { + int cport, cfd; + int max = server.max_new_tls_conns_per_cycle; + char cip[NET_IP_STR_LEN]; + UNUSED(mask); + UNUSED(privdata); + + while(max--) { + cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); + if (cfd == ANET_ERR) { + if (anetAcceptFailureNeedsRetry(errno)) + continue; + if (errno != EWOULDBLOCK) + serverLog(LL_WARNING, + "Accepting client connection: %s", server.neterr); + return; + } + serverLog(LL_VERBOSE,"Accepted %s:%d", cip, cport); + acceptCommonHandler(connCreateAcceptedTLS(el,cfd,&server.tls_auth_clients), 0, cip); + } +} +``` + +### File: src/unix.c +```c +static void connUnixAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) { + int cfd; + int max = server.max_new_conns_per_cycle; + UNUSED(el); + UNUSED(mask); + UNUSED(privdata); + + while(max--) { + cfd = anetUnixAccept(server.neterr, fd); + if (cfd == ANET_ERR) { + if (anetAcceptFailureNeedsRetry(errno)) + continue; + if (errno != EWOULDBLOCK) + serverLog(LL_WARNING, + "Accepting client connection: %s", server.neterr); + return; + } + serverLog(LL_VERBOSE,"Accepted connection to %s", server.unixsocket); + acceptCommonHandler(connCreateAcceptedUnix(el, cfd, NULL),CLIENT_UNIX_SOCKET,NULL); + } +} +``` diff --git a/tasks/csa159/pair_138570/pre_functions.txt b/tasks/csa159/pair_138570/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..bbb440318722b15715fb62fe838b6eef7f9abf31 --- /dev/null +++ b/tasks/csa159/pair_138570/pre_functions.txt @@ -0,0 +1,153 @@ +### File: src/anet.c +```c +int anetSetSockMarkId(char *err, int fd, uint32_t id) { +#ifdef HAVE_SOCKOPTMARKID + if (setsockopt(fd, SOL_SOCKET, SOCKOPTMARKID, (void *)&id, sizeof(id)) == -1) { + anetSetError(err, "setsockopt: %s", strerror(errno)); + return ANET_ERR; + } + return ANET_OK; +#else + UNUSED(fd); + UNUSED(id); + anetSetError(err,"anetSetSockMarkid unsupported on this platform"); + return ANET_OK; +#endif +} + +int anetIsFifo(char *filepath) { + struct stat sb; + if (stat(filepath, &sb) == -1) return 0; + return S_ISFIFO(sb.st_mode); +} + +int anetIsFifo(char *filepath) { + struct stat sb; + if (stat(filepath, &sb) == -1) return 0; + return S_ISFIFO(sb.st_mode); +} +``` + +### File: src/cluster_legacy.c +```c +void clusterAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) { + int cport, cfd; + int max = MAX_CLUSTER_ACCEPTS_PER_CALL; + char cip[NET_IP_STR_LEN]; + int require_auth = TLS_CLIENT_AUTH_YES; + UNUSED(el); + UNUSED(mask); + UNUSED(privdata); + + /* If the server is starting up, don't accept cluster connections: + * UPDATE messages may interact with the database content. */ + if (server.masterhost == NULL && server.loading) return; + + while(max--) { + cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); + if (cfd == ANET_ERR) { + if (errno != EWOULDBLOCK) + serverLog(LL_VERBOSE, + "Error accepting cluster node: %s", server.neterr); + return; + } + + connection *conn = connCreateAccepted(server.el, connTypeOfCluster(), cfd, &require_auth); + + /* Make sure connection is not in an error state */ + if (connGetState(conn) != CONN_STATE_ACCEPTING) { + serverLog(LL_VERBOSE, + "Error creating an accepting connection for cluster node: %s", + connGetLastError(conn)); + connClose(conn); + return; + } + connEnableTcpNoDelay(conn); + connKeepAlive(conn,server.cluster_node_timeout / 1000 * 2); + + /* Use non-blocking I/O for cluster messages. */ + serverLog(LL_VERBOSE,"Accepting cluster node connection from %s:%d", cip, cport); + + /* Accept the connection now. connAccept() may call our handler directly + * or schedule it for later depending on connection implementation. + */ + if (connAccept(conn, clusterConnAcceptHandler) == C_ERR) { + if (connGetState(conn) == CONN_STATE_ERROR) + serverLog(LL_VERBOSE, + "Error accepting cluster node connection: %s", + connGetLastError(conn)); + connClose(conn); + return; + } + } +} +``` + +### File: src/socket.c +```c +static void connSocketAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) { + int cport, cfd; + int max = server.max_new_conns_per_cycle; + char cip[NET_IP_STR_LEN]; + UNUSED(mask); + UNUSED(privdata); + + while(max--) { + cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); + if (cfd == ANET_ERR) { + if (errno != EWOULDBLOCK) + serverLog(LL_WARNING, + "Accepting client connection: %s", server.neterr); + return; + } + serverLog(LL_VERBOSE,"Accepted %s:%d", cip, cport); + acceptCommonHandler(connCreateAcceptedSocket(el,cfd,NULL), 0, cip); + } +} +``` + +### File: src/tls.c +```c +static void tlsAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) { + int cport, cfd; + int max = server.max_new_tls_conns_per_cycle; + char cip[NET_IP_STR_LEN]; + UNUSED(mask); + UNUSED(privdata); + + while(max--) { + cfd = anetTcpAccept(server.neterr, fd, cip, sizeof(cip), &cport); + if (cfd == ANET_ERR) { + if (errno != EWOULDBLOCK) + serverLog(LL_WARNING, + "Accepting client connection: %s", server.neterr); + return; + } + serverLog(LL_VERBOSE,"Accepted %s:%d", cip, cport); + acceptCommonHandler(connCreateAcceptedTLS(el,cfd,&server.tls_auth_clients), 0, cip); + } +} +``` + +### File: src/unix.c +```c +static void connUnixAcceptHandler(aeEventLoop *el, int fd, void *privdata, int mask) { + int cfd; + int max = server.max_new_conns_per_cycle; + UNUSED(el); + UNUSED(mask); + UNUSED(privdata); + + while(max--) { + cfd = anetUnixAccept(server.neterr, fd); + if (cfd == ANET_ERR) { + if (errno != EWOULDBLOCK) + serverLog(LL_WARNING, + "Accepting client connection: %s", server.neterr); + return; + } + serverLog(LL_VERBOSE,"Accepted connection to %s", server.unixsocket); + acceptCommonHandler(connCreateAcceptedUnix(el, cfd, NULL),CLIENT_UNIX_SOCKET,NULL); + } +} +``` diff --git a/tasks/csa159/pair_138570/task_prompt.md b/tasks/csa159/pair_138570/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_138570/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_138644/checker_template.cpp b/tasks/csa159/pair_138644/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138644/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_138644/config.json b/tasks/csa159/pair_138644/config.json new file mode 100644 index 0000000000000000000000000000000000000000..07ada62552328f31828f55737b1e7a629e7131ad --- /dev/null +++ b/tasks/csa159/pair_138644/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "strukturag_libheif", + "before_commit": "fc9ad8469eebf742c119981fa0e4b1eca7888c4a", + "after_commit": "2591939c530c2406dd9c8ab63d0f3a73622358ca", + "repo_path": "/workspace/repo/strukturag/libheif", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/strukturag_libheif/c6883e684723de86f60f544b7c4073c2c80c8dae/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/strukturag_libheif/c6883e684723de86f60f544b7c4073c2c80c8dae/compile_commands.json", + "changed_files": [ + "examples/encoder_png.cc" + ], + "commit_message": "exif: protected against large offset values\n\nResolves #1042", + "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_138644/patch.diff b/tasks/csa159/pair_138644/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b0c98d33b6afb064d1709dbd62fce0e1910e4adb --- /dev/null +++ b/tasks/csa159/pair_138644/patch.diff @@ -0,0 +1,28 @@ +diff --git a/examples/encoder_png.cc b/examples/encoder_png.cc +index a24b0593..8b918f96 100644 +--- a/examples/encoder_png.cc ++++ b/examples/encoder_png.cc +@@ -117,15 +117,16 @@ bool PngEncoder::Encode(const struct heif_image_handle* handle, + if (exifdata) { + if (exifsize > 4) { + uint32_t skip = (exifdata[0]<<24) | (exifdata[1]<<16) | (exifdata[2]<<8) | exifdata[3]; +- skip += 4; ++ if (skip < (exifsize - 4)) { ++ skip += 4; ++ uint8_t* ptr = exifdata + skip; ++ size_t size = exifsize - skip; + +- uint8_t* ptr = exifdata + skip; +- size_t size = exifsize - skip; ++ // libheif by default normalizes the image orientation, so that we have to set the EXIF Orientation to "Horizontal (normal)" ++ modify_exif_orientation_tag_if_it_exists(ptr, (int)size, 1); + +- // libheif by default normalizes the image orientation, so that we have to set the EXIF Orientation to "Horizontal (normal)" +- modify_exif_orientation_tag_if_it_exists(ptr, (int)size, 1); +- +- png_set_eXIf_1(png_ptr, info_ptr, (png_uint_32)size, ptr); ++ png_set_eXIf_1(png_ptr, info_ptr, (png_uint_32)size, ptr); ++ } + } + + free(exifdata); \ No newline at end of file diff --git a/tasks/csa159/pair_138644/post_functions.txt b/tasks/csa159/pair_138644/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..787bbb4706c9366e4dd686fae0d93d503099ce43 --- /dev/null +++ b/tasks/csa159/pair_138644/post_functions.txt @@ -0,0 +1,167 @@ +### File: examples/encoder_png.cc +```c +bool PngEncoder::Encode(const struct heif_image_handle* handle, + const struct heif_image* image, const std::string& filename) +{ + png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, + nullptr, nullptr); + if (!png_ptr) { + fprintf(stderr, "libpng initialization failed (1)\n"); + return false; + } + + png_infop info_ptr = png_create_info_struct(png_ptr); + if (!info_ptr) { + png_destroy_write_struct(&png_ptr, nullptr); + fprintf(stderr, "libpng initialization failed (2)\n"); + return false; + } + + if (m_compression_level != -1) { + png_set_compression_level(png_ptr, m_compression_level); + } + + FILE* fp = fopen(filename.c_str(), "wb"); + if (!fp) { + fprintf(stderr, "Can't open %s: %s\n", filename.c_str(), strerror(errno)); + png_destroy_write_struct(&png_ptr, &info_ptr); + return false; + } + + if (setjmp(png_jmpbuf(png_ptr))) { + png_destroy_write_struct(&png_ptr, &info_ptr); + fclose(fp); + fprintf(stderr, "Error while encoding image\n"); + return false; + } + + png_init_io(png_ptr, fp); + + bool withAlpha = (heif_image_get_chroma_format(image) == heif_chroma_interleaved_RGBA || + heif_image_get_chroma_format(image) == heif_chroma_interleaved_RRGGBBAA_BE); + + int width = heif_image_get_width(image, heif_channel_interleaved); + int height = heif_image_get_height(image, heif_channel_interleaved); + + int bitDepth; + int input_bpp = heif_image_get_bits_per_pixel_range(image, heif_channel_interleaved); + if (input_bpp > 8) { + bitDepth = 16; + } + else { + bitDepth = 8; + } + + const int colorType = withAlpha ? PNG_COLOR_TYPE_RGBA : PNG_COLOR_TYPE_RGB; + + png_set_IHDR(png_ptr, info_ptr, width, height, bitDepth, colorType, + PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); + + // --- write ICC profile + + size_t profile_size = heif_image_handle_get_raw_color_profile_size(handle); + if (profile_size > 0) { + uint8_t* profile_data = static_cast(malloc(profile_size)); + heif_image_handle_get_raw_color_profile(handle, profile_data); + char profile_name[] = "unknown"; + png_set_iCCP(png_ptr, info_ptr, profile_name, PNG_COMPRESSION_TYPE_BASE, +#if PNG_LIBPNG_VER < 10500 + (png_charp)profile_data, +#else + (png_const_bytep) profile_data, +#endif + (png_uint_32) profile_size); + free(profile_data); + } + + + // --- write EXIF metadata + +#ifdef PNG_eXIf_SUPPORTED + size_t exifsize = 0; + uint8_t* exifdata = GetExifMetaData(handle, &exifsize); + if (exifdata) { + if (exifsize > 4) { + uint32_t skip = (exifdata[0]<<24) | (exifdata[1]<<16) | (exifdata[2]<<8) | exifdata[3]; + if (skip < (exifsize - 4)) { + skip += 4; + uint8_t* ptr = exifdata + skip; + size_t size = exifsize - skip; + + // libheif by default normalizes the image orientation, so that we have to set the EXIF Orientation to "Horizontal (normal)" + modify_exif_orientation_tag_if_it_exists(ptr, (int)size, 1); + + png_set_eXIf_1(png_ptr, info_ptr, (png_uint_32)size, ptr); + } + } + + free(exifdata); + } +#endif + + // --- write XMP metadata + +#ifdef PNG_iTXt_SUPPORTED + // spec: https://raw.githubusercontent.com/adobe/xmp-docs/master/XMPSpecifications/XMPSpecificationPart3.pdf + std::vector xmp = get_xmp_metadata(handle); + if (!xmp.empty()) { + // make sure that XMP string is always null terminated. + if (xmp.back() != 0) { + xmp.push_back(0); + } + + // compute XMP string length + size_t text_length = 0; + while (xmp[text_length] != 0) { + text_length++; + } + + png_text xmp_text{}; // important to zero-initialize the structure so that the remaining fields are NULL ! + xmp_text.compression = PNG_ITXT_COMPRESSION_NONE; + xmp_text.key = (char*) "XML:com.adobe.xmp"; + xmp_text.text = (char*) xmp.data(); + xmp_text.text_length = 0; // should be 0 for ITXT according the libpng documentation + xmp_text.itxt_length = text_length; + png_set_text(png_ptr, info_ptr, &xmp_text, 1); + } +#endif + + png_write_info(png_ptr, info_ptr); + + uint8_t** row_pointers = new uint8_t* [height]; + + int stride_rgb; + const uint8_t* row_rgb = heif_image_get_plane_readonly(image, + heif_channel_interleaved, &stride_rgb); + + for (int y = 0; y < height; ++y) { + row_pointers[y] = const_cast(&row_rgb[y * stride_rgb]); + } + + if (bitDepth == 16) { + // shift image data to full 16bit range + + int shift = 16 - input_bpp; + if (shift > 0) { + for (int y = 0; y < height; ++y) { + for (int x = 0; x < stride_rgb; x += 2) { + uint8_t* p = (&row_pointers[y][x]); + int v = (p[0] << 8) | p[1]; + v = (v << shift) | (v >> (16 - shift)); + p[0] = (uint8_t) (v >> 8); + p[1] = (uint8_t) (v & 0xFF); + } + } + } + } + + + png_write_image(png_ptr, row_pointers); + + png_write_end(png_ptr, nullptr); + png_destroy_write_struct(&png_ptr, &info_ptr); + delete[] row_pointers; + fclose(fp); + return true; +} +``` diff --git a/tasks/csa159/pair_138644/pre_functions.txt b/tasks/csa159/pair_138644/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..ace917a1b19bcafc2a9cc6961dde3e978f013479 --- /dev/null +++ b/tasks/csa159/pair_138644/pre_functions.txt @@ -0,0 +1,166 @@ +### File: examples/encoder_png.cc +```c +bool PngEncoder::Encode(const struct heif_image_handle* handle, + const struct heif_image* image, const std::string& filename) +{ + png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, + nullptr, nullptr); + if (!png_ptr) { + fprintf(stderr, "libpng initialization failed (1)\n"); + return false; + } + + png_infop info_ptr = png_create_info_struct(png_ptr); + if (!info_ptr) { + png_destroy_write_struct(&png_ptr, nullptr); + fprintf(stderr, "libpng initialization failed (2)\n"); + return false; + } + + if (m_compression_level != -1) { + png_set_compression_level(png_ptr, m_compression_level); + } + + FILE* fp = fopen(filename.c_str(), "wb"); + if (!fp) { + fprintf(stderr, "Can't open %s: %s\n", filename.c_str(), strerror(errno)); + png_destroy_write_struct(&png_ptr, &info_ptr); + return false; + } + + if (setjmp(png_jmpbuf(png_ptr))) { + png_destroy_write_struct(&png_ptr, &info_ptr); + fclose(fp); + fprintf(stderr, "Error while encoding image\n"); + return false; + } + + png_init_io(png_ptr, fp); + + bool withAlpha = (heif_image_get_chroma_format(image) == heif_chroma_interleaved_RGBA || + heif_image_get_chroma_format(image) == heif_chroma_interleaved_RRGGBBAA_BE); + + int width = heif_image_get_width(image, heif_channel_interleaved); + int height = heif_image_get_height(image, heif_channel_interleaved); + + int bitDepth; + int input_bpp = heif_image_get_bits_per_pixel_range(image, heif_channel_interleaved); + if (input_bpp > 8) { + bitDepth = 16; + } + else { + bitDepth = 8; + } + + const int colorType = withAlpha ? PNG_COLOR_TYPE_RGBA : PNG_COLOR_TYPE_RGB; + + png_set_IHDR(png_ptr, info_ptr, width, height, bitDepth, colorType, + PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); + + // --- write ICC profile + + size_t profile_size = heif_image_handle_get_raw_color_profile_size(handle); + if (profile_size > 0) { + uint8_t* profile_data = static_cast(malloc(profile_size)); + heif_image_handle_get_raw_color_profile(handle, profile_data); + char profile_name[] = "unknown"; + png_set_iCCP(png_ptr, info_ptr, profile_name, PNG_COMPRESSION_TYPE_BASE, +#if PNG_LIBPNG_VER < 10500 + (png_charp)profile_data, +#else + (png_const_bytep) profile_data, +#endif + (png_uint_32) profile_size); + free(profile_data); + } + + + // --- write EXIF metadata + +#ifdef PNG_eXIf_SUPPORTED + size_t exifsize = 0; + uint8_t* exifdata = GetExifMetaData(handle, &exifsize); + if (exifdata) { + if (exifsize > 4) { + uint32_t skip = (exifdata[0]<<24) | (exifdata[1]<<16) | (exifdata[2]<<8) | exifdata[3]; + skip += 4; + + uint8_t* ptr = exifdata + skip; + size_t size = exifsize - skip; + + // libheif by default normalizes the image orientation, so that we have to set the EXIF Orientation to "Horizontal (normal)" + modify_exif_orientation_tag_if_it_exists(ptr, (int)size, 1); + + png_set_eXIf_1(png_ptr, info_ptr, (png_uint_32)size, ptr); + } + + free(exifdata); + } +#endif + + // --- write XMP metadata + +#ifdef PNG_iTXt_SUPPORTED + // spec: https://raw.githubusercontent.com/adobe/xmp-docs/master/XMPSpecifications/XMPSpecificationPart3.pdf + std::vector xmp = get_xmp_metadata(handle); + if (!xmp.empty()) { + // make sure that XMP string is always null terminated. + if (xmp.back() != 0) { + xmp.push_back(0); + } + + // compute XMP string length + size_t text_length = 0; + while (xmp[text_length] != 0) { + text_length++; + } + + png_text xmp_text{}; // important to zero-initialize the structure so that the remaining fields are NULL ! + xmp_text.compression = PNG_ITXT_COMPRESSION_NONE; + xmp_text.key = (char*) "XML:com.adobe.xmp"; + xmp_text.text = (char*) xmp.data(); + xmp_text.text_length = 0; // should be 0 for ITXT according the libpng documentation + xmp_text.itxt_length = text_length; + png_set_text(png_ptr, info_ptr, &xmp_text, 1); + } +#endif + + png_write_info(png_ptr, info_ptr); + + uint8_t** row_pointers = new uint8_t* [height]; + + int stride_rgb; + const uint8_t* row_rgb = heif_image_get_plane_readonly(image, + heif_channel_interleaved, &stride_rgb); + + for (int y = 0; y < height; ++y) { + row_pointers[y] = const_cast(&row_rgb[y * stride_rgb]); + } + + if (bitDepth == 16) { + // shift image data to full 16bit range + + int shift = 16 - input_bpp; + if (shift > 0) { + for (int y = 0; y < height; ++y) { + for (int x = 0; x < stride_rgb; x += 2) { + uint8_t* p = (&row_pointers[y][x]); + int v = (p[0] << 8) | p[1]; + v = (v << shift) | (v >> (16 - shift)); + p[0] = (uint8_t) (v >> 8); + p[1] = (uint8_t) (v & 0xFF); + } + } + } + } + + + png_write_image(png_ptr, row_pointers); + + png_write_end(png_ptr, nullptr); + png_destroy_write_struct(&png_ptr, &info_ptr); + delete[] row_pointers; + fclose(fp); + return true; +} +``` diff --git a/tasks/csa159/pair_138644/task_prompt.md b/tasks/csa159/pair_138644/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_138644/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_138650/checker_template.cpp b/tasks/csa159/pair_138650/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138650/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_138650/config.json b/tasks/csa159/pair_138650/config.json new file mode 100644 index 0000000000000000000000000000000000000000..55f6898df55b7470cc92931b1d569c02376b24c9 --- /dev/null +++ b/tasks/csa159/pair_138650/config.json @@ -0,0 +1,20 @@ +{ + "project_id": "uclouvain_openjpeg", + "before_commit": "162f6199c0cd3ec1c6c6dc65e41b2faab92b2d91", + "after_commit": "1a8318f6c24623189ecb65e049267c6f2e005c0e", + "repo_path": "/workspace/repo/uclouvain/openjpeg", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/uclouvain_openjpeg/b51d088267cb88eb95555ea047755120e36c511b/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/uclouvain_openjpeg/b51d088267cb88eb95555ea047755120e36c511b/compile_commands.json", + "changed_files": [ + "src/lib/openjp2/j2k.c", + "src/lib/openjp2/t2.c" + ], + "commit_message": "Fix Out-of-Bounds Access in function opj_tgt_reset\n\nFix uclouvain/openjpeg#775", + "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_138650/patch.diff b/tasks/csa159/pair_138650/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..106dcb345ce6e9064aa95e3698ce6e1fe32ef7fe --- /dev/null +++ b/tasks/csa159/pair_138650/patch.diff @@ -0,0 +1,47 @@ +diff --git a/src/lib/openjp2/j2k.c b/src/lib/openjp2/j2k.c +index 8086b004..9eaa155e 100644 +--- a/src/lib/openjp2/j2k.c ++++ b/src/lib/openjp2/j2k.c +@@ -8889,6 +8889,10 @@ static OPJ_BOOL opj_j2k_read_SPCod_SPCoc( opj_j2k_t *p_j2k, + + opj_read_bytes(l_current_ptr,&l_tccp->cblksty ,1); /* SPcoc (G) */ + ++l_current_ptr; ++ if (l_tccp->cblksty & 0xC0U) { /* 2 msb are reserved, assume we can't read */ ++ opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element, Invalid code-block style found\n"); ++ return OPJ_FALSE; ++ } + + opj_read_bytes(l_current_ptr,&l_tccp->qmfbid ,1); /* SPcoc (H) */ + ++l_current_ptr; +diff --git a/src/lib/openjp2/t2.c b/src/lib/openjp2/t2.c +index ebc26b2d..5a8d440c 100644 +--- a/src/lib/openjp2/t2.c ++++ b/src/lib/openjp2/t2.c +@@ -868,9 +868,14 @@ static OPJ_BOOL opj_t2_read_packet_header( opj_t2_t* p_t2, + + /* reset tagtrees */ + for (bandno = 0; bandno < l_res->numbands; ++bandno) { +- opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno]; +- + if ( ! ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) ) { ++ opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno]; ++ if (!(p_pi->precno < (l_band->precincts_data_size / sizeof(opj_tcd_precinct_t)))) { ++ opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct\n"); ++ return OPJ_FALSE; ++ } ++ ++ + opj_tgt_reset(l_prc->incltree); + opj_tgt_reset(l_prc->imsbtree); + l_cblk = l_prc->cblks.dec; +diff --git a/tests/nonregression/test_suite.ctest.in b/tests/nonregression/test_suite.ctest.in +index 13112216..e1eb7027 100644 +--- a/tests/nonregression/test_suite.ctest.in ++++ b/tests/nonregression/test_suite.ctest.in +@@ -561,3 +561,6 @@ opj_decompress -i @INPUT_NR_PATH@/issue726.j2k -o @TEMP_PATH@/issue726.png + !opj_decompress -i @INPUT_NR_PATH@/issue733.jp2 -o @TEMP_PATH@/issue733.png + # issue 774 + !opj_decompress -i @INPUT_NR_PATH@/issue774.jp2 -o @TEMP_PATH@/issue774.png ++# issue 775 ++!opj_decompress -i @INPUT_NR_PATH@/issue775.j2k -o @TEMP_PATH@/issue775.png ++!opj_decompress -i @INPUT_NR_PATH@/issue775-2.j2k -o @TEMP_PATH@/issue775-2.png \ No newline at end of file diff --git a/tasks/csa159/pair_138650/post_functions.txt b/tasks/csa159/pair_138650/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..422e861aa281ad804d17caffeca40849003cc348 --- /dev/null +++ b/tasks/csa159/pair_138650/post_functions.txt @@ -0,0 +1,318 @@ +### File: src/lib/openjp2/j2k.c +```c +static OPJ_BOOL opj_j2k_read_SPCod_SPCoc( opj_j2k_t *p_j2k, + OPJ_UINT32 compno, + OPJ_BYTE * p_header_data, + OPJ_UINT32 * p_header_size, + opj_event_mgr_t * p_manager) +{ + OPJ_UINT32 i, l_tmp; + opj_cp_t *l_cp = NULL; + opj_tcp_t *l_tcp = NULL; + opj_tccp_t *l_tccp = NULL; + OPJ_BYTE * l_current_ptr = NULL; + + /* preconditions */ + assert(p_j2k != 00); + assert(p_manager != 00); + assert(p_header_data != 00); + + l_cp = &(p_j2k->m_cp); + l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? + &l_cp->tcps[p_j2k->m_current_tile_number] : + p_j2k->m_specific_param.m_decoder.m_default_tcp; + + /* precondition again */ + assert(compno < p_j2k->m_private_image->numcomps); + + l_tccp = &l_tcp->tccps[compno]; + l_current_ptr = p_header_data; + + /* make sure room is sufficient */ + if (*p_header_size < 5) { + opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n"); + return OPJ_FALSE; + } + + opj_read_bytes(l_current_ptr, &l_tccp->numresolutions ,1); /* SPcox (D) */ + ++l_tccp->numresolutions; /* tccp->numresolutions = read() + 1 */ + if (l_tccp->numresolutions > OPJ_J2K_MAXRLVLS) { + opj_event_msg(p_manager, EVT_ERROR, + "Invalid value for numresolutions : %d, max value is set in openjpeg.h at %d\n", + l_tccp->numresolutions, OPJ_J2K_MAXRLVLS); + return OPJ_FALSE; + } + ++l_current_ptr; + + /* If user wants to remove more resolutions than the codestream contains, return error */ + if (l_cp->m_specific_param.m_dec.m_reduce >= l_tccp->numresolutions) { + opj_event_msg(p_manager, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions to remove is higher than the number " + "of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno); + p_j2k->m_specific_param.m_decoder.m_state |= 0x8000;/* FIXME J2K_DEC_STATE_ERR;*/ + return OPJ_FALSE; + } + + opj_read_bytes(l_current_ptr,&l_tccp->cblkw ,1); /* SPcoc (E) */ + ++l_current_ptr; + l_tccp->cblkw += 2; + + opj_read_bytes(l_current_ptr,&l_tccp->cblkh ,1); /* SPcoc (F) */ + ++l_current_ptr; + l_tccp->cblkh += 2; + + if ((l_tccp->cblkw > 10) || (l_tccp->cblkh > 10) || ((l_tccp->cblkw + l_tccp->cblkh) > 12)) { + opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element, Invalid cblkw/cblkh combination\n"); + return OPJ_FALSE; + } + + + opj_read_bytes(l_current_ptr,&l_tccp->cblksty ,1); /* SPcoc (G) */ + ++l_current_ptr; + if (l_tccp->cblksty & 0xC0U) { /* 2 msb are reserved, assume we can't read */ + opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element, Invalid code-block style found\n"); + return OPJ_FALSE; + } + + opj_read_bytes(l_current_ptr,&l_tccp->qmfbid ,1); /* SPcoc (H) */ + ++l_current_ptr; + + *p_header_size = *p_header_size - 5; + + /* use custom precinct size ? */ + if (l_tccp->csty & J2K_CCP_CSTY_PRT) { + if (*p_header_size < l_tccp->numresolutions) { + opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n"); + return OPJ_FALSE; + } + + for (i = 0; i < l_tccp->numresolutions; ++i) { + opj_read_bytes(l_current_ptr,&l_tmp ,1); /* SPcoc (I_i) */ + ++l_current_ptr; + /* Precinct exponent 0 is only allowed for lowest resolution level (Table A.21) */ + if ((i != 0) && (((l_tmp & 0xf) == 0) || ((l_tmp >> 4) == 0))) { + opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct size\n"); + return OPJ_FALSE; + } + l_tccp->prcw[i] = l_tmp & 0xf; + l_tccp->prch[i] = l_tmp >> 4; + } + + *p_header_size = *p_header_size - l_tccp->numresolutions; + } + else { + /* set default size for the precinct width and height */ + for (i = 0; i < l_tccp->numresolutions; ++i) { + l_tccp->prcw[i] = 15; + l_tccp->prch[i] = 15; + } + } + +#ifdef WIP_REMOVE_MSD + /* INDEX >> */ + if (p_j2k->cstr_info && compno == 0) { + OPJ_UINT32 l_data_size = l_tccp->numresolutions * sizeof(OPJ_UINT32); + + p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkh = l_tccp->cblkh; + p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkw = l_tccp->cblkw; + p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].numresolutions = l_tccp->numresolutions; + p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblksty = l_tccp->cblksty; + p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].qmfbid = l_tccp->qmfbid; + + memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdx,l_tccp->prcw, l_data_size); + memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdy,l_tccp->prch, l_data_size); + } + /* << INDEX */ +#endif + + return OPJ_TRUE; +} +``` + +### File: src/lib/openjp2/t2.c +```c +static OPJ_BOOL opj_t2_read_packet_header( opj_t2_t* p_t2, + opj_tcd_tile_t *p_tile, + opj_tcp_t *p_tcp, + opj_pi_iterator_t *p_pi, + OPJ_BOOL * p_is_data_present, + OPJ_BYTE *p_src_data, + OPJ_UINT32 * p_data_read, + OPJ_UINT32 p_max_length, + opj_packet_info_t *p_pack_info, + opj_event_mgr_t *p_manager) + +{ + /* loop */ + OPJ_UINT32 bandno, cblkno; + OPJ_UINT32 l_nb_code_blocks; + OPJ_UINT32 l_remaining_length; + OPJ_UINT32 l_header_length; + OPJ_UINT32 * l_modified_length_ptr = 00; + OPJ_BYTE *l_current_data = p_src_data; + opj_cp_t *l_cp = p_t2->cp; + opj_bio_t *l_bio = 00; /* BIO component */ + opj_tcd_band_t *l_band = 00; + opj_tcd_cblk_dec_t* l_cblk = 00; + opj_tcd_resolution_t* l_res = &p_tile->comps[p_pi->compno].resolutions[p_pi->resno]; + + OPJ_BYTE *l_header_data = 00; + OPJ_BYTE **l_header_data_start = 00; + + OPJ_UINT32 l_present; + + if (p_pi->layno == 0) { + l_band = l_res->bands; + + /* reset tagtrees */ + for (bandno = 0; bandno < l_res->numbands; ++bandno) { + if ( ! ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) ) { + opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno]; + if (!(p_pi->precno < (l_band->precincts_data_size / sizeof(opj_tcd_precinct_t)))) { + opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct\n"); + return OPJ_FALSE; + } + + + opj_tgt_reset(l_prc->incltree); + opj_tgt_reset(l_prc->imsbtree); + l_cblk = l_prc->cblks.dec; + + l_nb_code_blocks = l_prc->cw * l_prc->ch; + for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { + l_cblk->numsegs = 0; + l_cblk->real_num_segs = 0; + ++l_cblk; + } + } + + ++l_band; + } + } + + /* SOP markers */ + + if (p_tcp->csty & J2K_CP_CSTY_SOP) { + if (p_max_length < 6) { + opj_event_msg(p_manager, EVT_WARNING, "Not enough space for expected SOP marker\n"); + } else if ((*l_current_data) != 0xff || (*(l_current_data + 1) != 0x91)) { + opj_event_msg(p_manager, EVT_WARNING, "Expected SOP marker\n"); + } else { + l_current_data += 6; + } + + /** TODO : check the Nsop value */ + } + + /* + When the marker PPT/PPM is used the packet header are store in PPT/PPM marker + This part deal with this caracteristic + step 1: Read packet header in the saved structure + step 2: Return to codestream for decoding + */ + + l_bio = opj_bio_create(); + if (! l_bio) { + return OPJ_FALSE; + } + + if (l_cp->ppm == 1) { /* PPM */ + l_header_data_start = &l_cp->ppm_data; + l_header_data = *l_header_data_start; + l_modified_length_ptr = &(l_cp->ppm_len); + + } + else if (p_tcp->ppt == 1) { /* PPT */ + l_header_data_start = &(p_tcp->ppt_data); + l_header_data = *l_header_data_start; + l_modified_length_ptr = &(p_tcp->ppt_len); + } + else { /* Normal Case */ + l_header_data_start = &(l_current_data); + l_header_data = *l_header_data_start; + l_remaining_length = (OPJ_UINT32)(p_src_data+p_max_length-l_header_data); + l_modified_length_ptr = &(l_remaining_length); + } + + opj_bio_init_dec(l_bio, l_header_data,*l_modified_length_ptr); + + l_present = opj_bio_read(l_bio, 1); + JAS_FPRINTF(stderr, "present=%d \n", l_present ); + if (!l_present) { + /* TODO MSD: no test to control the output of this function*/ + opj_bio_inalign(l_bio); + l_header_data += opj_bio_numbytes(l_bio); + opj_bio_destroy(l_bio); + + /* EPH markers */ + if (p_tcp->csty & J2K_CP_CSTY_EPH) { + if ((*l_modified_length_ptr - (OPJ_UINT32)(l_header_data - *l_header_data_start)) < 2U) { + opj_event_msg(p_manager, EVT_WARNING, "Not enough space for expected EPH marker\n"); + } else if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) { + opj_event_msg(p_manager, EVT_WARNING, "Expected EPH marker\n"); + } else { + l_header_data += 2; + } + } + + l_header_length = (OPJ_UINT32)(l_header_data - *l_header_data_start); + *l_modified_length_ptr -= l_header_length; + *l_header_data_start += l_header_length; + + /* << INDEX */ + /* End of packet header position. Currently only represents the distance to start of packet + Will be updated later by incrementing with packet start value */ + if (p_pack_info) { + p_pack_info->end_ph_pos = (OPJ_INT32)(l_current_data - p_src_data); + } + /* INDEX >> */ + + * p_is_data_present = OPJ_FALSE; + *p_data_read = (OPJ_UINT32)(l_current_data - p_src_data); + return OPJ_TRUE; + } + + l_band = l_res->bands; + for (bandno = 0; bandno < l_res->numbands; ++bandno) { + opj_tcd_precinct_t *l_prc = &(l_band->precincts[p_pi->precno]); + + if ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) { + ++l_band; + continue; + } + + l_nb_code_blocks = l_prc->cw * l_prc->ch; + l_cblk = l_prc->cblks.dec; + for (cblkno = 0; cblkno < l_nb_code_blocks; cblkno++) { + OPJ_UINT32 l_included,l_increment, l_segno; + OPJ_INT32 n; + + /* if cblk not yet included before --> inclusion tagtree */ + if (!l_cblk->numsegs) { + l_included = opj_tgt_decode(l_bio, l_prc->incltree, cblkno, (OPJ_INT32)(p_pi->layno + 1)); + /* else one bit */ + } + else { + l_included = opj_bio_read(l_bio, 1); + } + + /* if cblk not included */ + if (!l_included) { + l_cblk->numnewpasses = 0; + ++l_cblk; + JAS_FPRINTF(stderr, "included=%d \n", l_included); + continue; + } + + /* if cblk not yet included --> zero-bitplane tagtree */ + if (!l_cblk->numsegs) { + OPJ_UINT32 i = 0; + + while (!opj_tgt_decode(l_bio, l_prc->imsbtree, cblkno, (OPJ_INT32)i)) { + ++i; + } + + l_cblk->numbps = (OPJ_UINT32)l_band->numbps + 1 - i; + + +// ... (4174 more chars) +``` diff --git a/tasks/csa159/pair_138650/pre_functions.txt b/tasks/csa159/pair_138650/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..5aa550f40f42d18e15108bd436b88a29f83fffdd --- /dev/null +++ b/tasks/csa159/pair_138650/pre_functions.txt @@ -0,0 +1,317 @@ +### File: src/lib/openjp2/j2k.c +```c +static OPJ_BOOL opj_j2k_read_SPCod_SPCoc( opj_j2k_t *p_j2k, + OPJ_UINT32 compno, + OPJ_BYTE * p_header_data, + OPJ_UINT32 * p_header_size, + opj_event_mgr_t * p_manager) +{ + OPJ_UINT32 i, l_tmp; + opj_cp_t *l_cp = NULL; + opj_tcp_t *l_tcp = NULL; + opj_tccp_t *l_tccp = NULL; + OPJ_BYTE * l_current_ptr = NULL; + + /* preconditions */ + assert(p_j2k != 00); + assert(p_manager != 00); + assert(p_header_data != 00); + + l_cp = &(p_j2k->m_cp); + l_tcp = (p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_TPH) ? + &l_cp->tcps[p_j2k->m_current_tile_number] : + p_j2k->m_specific_param.m_decoder.m_default_tcp; + + /* precondition again */ + assert(compno < p_j2k->m_private_image->numcomps); + + l_tccp = &l_tcp->tccps[compno]; + l_current_ptr = p_header_data; + + /* make sure room is sufficient */ + if (*p_header_size < 5) { + opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n"); + return OPJ_FALSE; + } + + opj_read_bytes(l_current_ptr, &l_tccp->numresolutions ,1); /* SPcox (D) */ + ++l_tccp->numresolutions; /* tccp->numresolutions = read() + 1 */ + if (l_tccp->numresolutions > OPJ_J2K_MAXRLVLS) { + opj_event_msg(p_manager, EVT_ERROR, + "Invalid value for numresolutions : %d, max value is set in openjpeg.h at %d\n", + l_tccp->numresolutions, OPJ_J2K_MAXRLVLS); + return OPJ_FALSE; + } + ++l_current_ptr; + + /* If user wants to remove more resolutions than the codestream contains, return error */ + if (l_cp->m_specific_param.m_dec.m_reduce >= l_tccp->numresolutions) { + opj_event_msg(p_manager, EVT_ERROR, "Error decoding component %d.\nThe number of resolutions to remove is higher than the number " + "of resolutions of this component\nModify the cp_reduce parameter.\n\n", compno); + p_j2k->m_specific_param.m_decoder.m_state |= 0x8000;/* FIXME J2K_DEC_STATE_ERR;*/ + return OPJ_FALSE; + } + + opj_read_bytes(l_current_ptr,&l_tccp->cblkw ,1); /* SPcoc (E) */ + ++l_current_ptr; + l_tccp->cblkw += 2; + + opj_read_bytes(l_current_ptr,&l_tccp->cblkh ,1); /* SPcoc (F) */ + ++l_current_ptr; + l_tccp->cblkh += 2; + + if ((l_tccp->cblkw > 10) || (l_tccp->cblkh > 10) || ((l_tccp->cblkw + l_tccp->cblkh) > 12)) { + opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element, Invalid cblkw/cblkh combination\n"); + return OPJ_FALSE; + } + + + opj_read_bytes(l_current_ptr,&l_tccp->cblksty ,1); /* SPcoc (G) */ + ++l_current_ptr; + + opj_read_bytes(l_current_ptr,&l_tccp->qmfbid ,1); /* SPcoc (H) */ + ++l_current_ptr; + + *p_header_size = *p_header_size - 5; + + /* use custom precinct size ? */ + if (l_tccp->csty & J2K_CCP_CSTY_PRT) { + if (*p_header_size < l_tccp->numresolutions) { + opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n"); + return OPJ_FALSE; + } + + for (i = 0; i < l_tccp->numresolutions; ++i) { + opj_read_bytes(l_current_ptr,&l_tmp ,1); /* SPcoc (I_i) */ + ++l_current_ptr; + /* Precinct exponent 0 is only allowed for lowest resolution level (Table A.21) */ + if ((i != 0) && (((l_tmp & 0xf) == 0) || ((l_tmp >> 4) == 0))) { + opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct size\n"); + return OPJ_FALSE; + } + l_tccp->prcw[i] = l_tmp & 0xf; + l_tccp->prch[i] = l_tmp >> 4; + } + + *p_header_size = *p_header_size - l_tccp->numresolutions; + } + else { + /* set default size for the precinct width and height */ + for (i = 0; i < l_tccp->numresolutions; ++i) { + l_tccp->prcw[i] = 15; + l_tccp->prch[i] = 15; + } + } + +#ifdef WIP_REMOVE_MSD + /* INDEX >> */ + if (p_j2k->cstr_info && compno == 0) { + OPJ_UINT32 l_data_size = l_tccp->numresolutions * sizeof(OPJ_UINT32); + + p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkh = l_tccp->cblkh; + p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblkw = l_tccp->cblkw; + p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].numresolutions = l_tccp->numresolutions; + p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].cblksty = l_tccp->cblksty; + p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].tccp_info[compno].qmfbid = l_tccp->qmfbid; + + memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdx,l_tccp->prcw, l_data_size); + memcpy(p_j2k->cstr_info->tile[p_j2k->m_current_tile_number].pdy,l_tccp->prch, l_data_size); + } + /* << INDEX */ +#endif + + return OPJ_TRUE; +} +``` + +### File: src/lib/openjp2/t2.c +```c +static OPJ_BOOL opj_t2_read_packet_header( opj_t2_t* p_t2, + opj_tcd_tile_t *p_tile, + opj_tcp_t *p_tcp, + opj_pi_iterator_t *p_pi, + OPJ_BOOL * p_is_data_present, + OPJ_BYTE *p_src_data, + OPJ_UINT32 * p_data_read, + OPJ_UINT32 p_max_length, + opj_packet_info_t *p_pack_info, + opj_event_mgr_t *p_manager) + +{ + /* loop */ + OPJ_UINT32 bandno, cblkno; + OPJ_UINT32 l_nb_code_blocks; + OPJ_UINT32 l_remaining_length; + OPJ_UINT32 l_header_length; + OPJ_UINT32 * l_modified_length_ptr = 00; + OPJ_BYTE *l_current_data = p_src_data; + opj_cp_t *l_cp = p_t2->cp; + opj_bio_t *l_bio = 00; /* BIO component */ + opj_tcd_band_t *l_band = 00; + opj_tcd_cblk_dec_t* l_cblk = 00; + opj_tcd_resolution_t* l_res = &p_tile->comps[p_pi->compno].resolutions[p_pi->resno]; + + OPJ_BYTE *l_header_data = 00; + OPJ_BYTE **l_header_data_start = 00; + + OPJ_UINT32 l_present; + + if (p_pi->layno == 0) { + l_band = l_res->bands; + + /* reset tagtrees */ + for (bandno = 0; bandno < l_res->numbands; ++bandno) { + opj_tcd_precinct_t *l_prc = &l_band->precincts[p_pi->precno]; + + if ( ! ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) ) { + opj_tgt_reset(l_prc->incltree); + opj_tgt_reset(l_prc->imsbtree); + l_cblk = l_prc->cblks.dec; + + l_nb_code_blocks = l_prc->cw * l_prc->ch; + for (cblkno = 0; cblkno < l_nb_code_blocks; ++cblkno) { + l_cblk->numsegs = 0; + l_cblk->real_num_segs = 0; + ++l_cblk; + } + } + + ++l_band; + } + } + + /* SOP markers */ + + if (p_tcp->csty & J2K_CP_CSTY_SOP) { + if (p_max_length < 6) { + opj_event_msg(p_manager, EVT_WARNING, "Not enough space for expected SOP marker\n"); + } else if ((*l_current_data) != 0xff || (*(l_current_data + 1) != 0x91)) { + opj_event_msg(p_manager, EVT_WARNING, "Expected SOP marker\n"); + } else { + l_current_data += 6; + } + + /** TODO : check the Nsop value */ + } + + /* + When the marker PPT/PPM is used the packet header are store in PPT/PPM marker + This part deal with this caracteristic + step 1: Read packet header in the saved structure + step 2: Return to codestream for decoding + */ + + l_bio = opj_bio_create(); + if (! l_bio) { + return OPJ_FALSE; + } + + if (l_cp->ppm == 1) { /* PPM */ + l_header_data_start = &l_cp->ppm_data; + l_header_data = *l_header_data_start; + l_modified_length_ptr = &(l_cp->ppm_len); + + } + else if (p_tcp->ppt == 1) { /* PPT */ + l_header_data_start = &(p_tcp->ppt_data); + l_header_data = *l_header_data_start; + l_modified_length_ptr = &(p_tcp->ppt_len); + } + else { /* Normal Case */ + l_header_data_start = &(l_current_data); + l_header_data = *l_header_data_start; + l_remaining_length = (OPJ_UINT32)(p_src_data+p_max_length-l_header_data); + l_modified_length_ptr = &(l_remaining_length); + } + + opj_bio_init_dec(l_bio, l_header_data,*l_modified_length_ptr); + + l_present = opj_bio_read(l_bio, 1); + JAS_FPRINTF(stderr, "present=%d \n", l_present ); + if (!l_present) { + /* TODO MSD: no test to control the output of this function*/ + opj_bio_inalign(l_bio); + l_header_data += opj_bio_numbytes(l_bio); + opj_bio_destroy(l_bio); + + /* EPH markers */ + if (p_tcp->csty & J2K_CP_CSTY_EPH) { + if ((*l_modified_length_ptr - (OPJ_UINT32)(l_header_data - *l_header_data_start)) < 2U) { + opj_event_msg(p_manager, EVT_WARNING, "Not enough space for expected EPH marker\n"); + } else if ((*l_header_data) != 0xff || (*(l_header_data + 1) != 0x92)) { + opj_event_msg(p_manager, EVT_WARNING, "Expected EPH marker\n"); + } else { + l_header_data += 2; + } + } + + l_header_length = (OPJ_UINT32)(l_header_data - *l_header_data_start); + *l_modified_length_ptr -= l_header_length; + *l_header_data_start += l_header_length; + + /* << INDEX */ + /* End of packet header position. Currently only represents the distance to start of packet + Will be updated later by incrementing with packet start value */ + if (p_pack_info) { + p_pack_info->end_ph_pos = (OPJ_INT32)(l_current_data - p_src_data); + } + /* INDEX >> */ + + * p_is_data_present = OPJ_FALSE; + *p_data_read = (OPJ_UINT32)(l_current_data - p_src_data); + return OPJ_TRUE; + } + + l_band = l_res->bands; + for (bandno = 0; bandno < l_res->numbands; ++bandno) { + opj_tcd_precinct_t *l_prc = &(l_band->precincts[p_pi->precno]); + + if ((l_band->x1-l_band->x0 == 0)||(l_band->y1-l_band->y0 == 0)) { + ++l_band; + continue; + } + + l_nb_code_blocks = l_prc->cw * l_prc->ch; + l_cblk = l_prc->cblks.dec; + for (cblkno = 0; cblkno < l_nb_code_blocks; cblkno++) { + OPJ_UINT32 l_included,l_increment, l_segno; + OPJ_INT32 n; + + /* if cblk not yet included before --> inclusion tagtree */ + if (!l_cblk->numsegs) { + l_included = opj_tgt_decode(l_bio, l_prc->incltree, cblkno, (OPJ_INT32)(p_pi->layno + 1)); + /* else one bit */ + } + else { + l_included = opj_bio_read(l_bio, 1); + } + + /* if cblk not included */ + if (!l_included) { + l_cblk->numnewpasses = 0; + ++l_cblk; + JAS_FPRINTF(stderr, "included=%d \n", l_included); + continue; + } + + /* if cblk not yet included --> zero-bitplane tagtree */ + if (!l_cblk->numsegs) { + OPJ_UINT32 i = 0; + + while (!opj_tgt_decode(l_bio, l_prc->imsbtree, cblkno, (OPJ_INT32)i)) { + ++i; + } + + l_cblk->numbps = (OPJ_UINT32)l_band->numbps + 1 - i; + l_cblk->numlenbits = 3; + } + + /* number of coding passes */ + l_cblk->numnewpasses = opj_t2_getnumpasses(l_bio); + l_increment = opj_t2_getcommacode(l_bio); + + /* length indicator increment */ + l_cblk->numle + +// ... (3832 more chars) +``` diff --git a/tasks/csa159/pair_138650/task_prompt.md b/tasks/csa159/pair_138650/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..5c80db3816cec037bbce11c74bee164f7afe2e82 --- /dev/null +++ b/tasks/csa159/pair_138650/task_prompt.md @@ -0,0 +1,384 @@ +# 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 + +- Process quality remained below threshold despite successful build and differential validation. +- The bounds proof was incomplete: it accepted idx <= capacity even though valid array indexing requires idx < element_count. +- The capacity matcher only detected a reference to precincts_data_size and did not prove conversion from byte capacity to element count by division by sizeof(opj_tcd_precinct_t). +- Patch understanding omitted the independent validation of the two reserved high bits in cblksty within opj_j2k_read_SPCod_SPCoc. +- Implementation required multiple compile-recovery cycles due to a DeclarationName/StringRef mismatch and a missing helper declaration. + +### 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 CSA mechanism level. +- Preserve semantic score at or above the configured threshold. +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- At each relevant precinct-element dereference, prove on the reaching path that the packet-iterator precinct index is strictly less than the number of allocated opj_tcd_precinct_t elements. +- Derive the element count from the same base object's byte-capacity field using precincts_data_size / sizeof(opj_tcd_precinct_t); mere occurrence of the capacity member is insufficient. +- Preserve expression identity between the checked index, the array subscript index, the array base object, and the capacity base object. +- Resolve condition negation, reversed operands, then/else polarity, and rejecting early-return branches so only the path reaching the sink is considered safe. +- Treat equality with the element count as out of bounds; inclusive upper-bound predicates must not establish safety. +- For the separate SPCod/SPCoc change, recognize that a parsed cblksty value is invalid when either reserved high bit selected by 0xC0U is set before subsequent acceptance or use. + +### Implementation constraints + +- Use an intraprocedural path-sensitive CSA design with ProgramState path facts or equivalent analyzer constraint queries, while relating those facts to CFG reachability and dominance. +- Observe the vulnerable precinct use at a dereferencing sink such as the tag-tree operation through the selected precinct element; do not report merely because its address-forming subscript exists. +- Trace sink arguments through member access and local-variable initializers to the originating capacity-tracked array subscript. +- Keep diagnostics local to the unsafe dereference or the invalid parsed-field acceptance point, with no more than one diagnostic for the same sink event. +- Scope matching through AST declarations, record types, member relationships, byte-capacity semantics, and operation behavior rather than source lines, local variable spellings, commit identifiers, test names, or diagnostic literals. +- Handle the precinct bounds defect and the independent cblksty reserved-bit validation as distinct semantic patterns from the supplied patch. +- Use CSA APIs compatible with the target Clang version, including correct declaration-name comparison and complete helper declarations before use. + +### Validation checklist + +- Compile the checker plugin successfully with the target Clang Static Analyzer API and verify registration and loading. +- Scan the unpatched sources and require two relevant diagnostics at the opj_tgt_reset calls in opj_t2_read_packet_header. +- Scan the patched sources and require those two precinct diagnostics to disappear because the strict byte-capacity-to-element-count guard rejects the unsafe path. +- Verify diagnostic locations remain at or immediately adjacent to the vulnerable dereferences rather than at unrelated guards or address computations. +- Add refinement cases showing idx < bytes / sizeof(element) is safe while idx <= bytes / sizeof(element), a bare capacity reference, the wrong sizeof type, a different base object, and a non-dominating check are not accepted as proofs. +- Exercise direct, negated, reversed-operand, then/else, and early-return forms while checking the polarity of the path reaching the sink. +- Validate the cblksty pattern before and after the patch, including reserved bits clear versus either 0x40U or 0x80U set. +- Re-run differential, sparsity, relevance, objective-gate, semantic-score, hardcoding, anchor, and refinement checks and require no forbidden regression. + +### Avoid and forbidden regressions + +- Do not use syntax-only detection at ArraySubscriptExpr, because the patched source still forms the same precinct address before checking it. +- Do not equate textual or structural dominance alone with a numerical in-bounds proof. +- Do not accept inclusive upper bounds for zero-based array indexing. +- Do not accept arbitrary arithmetic that merely contains the capacity member. +- Do not restrict patch understanding to the precinct defect while ignoring the cblksty reserved-bit change. +- Do not depend on patch-local line numbers, local variable names, unique literals, issue identifiers, commit metadata, or test filenames. +- Do not introduce interprocedural taint propagation when the supplied defects can be established within their enclosing functions. +- Do not repeat API experiments known to fail, including direct DeclarationName-to-StringRef comparison or references to undeclared helpers. diff --git a/tasks/csa159/pair_138710/checker_template.cpp b/tasks/csa159/pair_138710/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138710/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_138710/config.json b/tasks/csa159/pair_138710/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b3bdb0f22bce9bda8c70a357d7bba89c81d6042b --- /dev/null +++ b/tasks/csa159/pair_138710/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "ImageMagick_ImageMagick", + "before_commit": "677d7b743fcbd7132ac11dade52a19493f58f647", + "after_commit": "cea1693e2ded51b4cc91c70c54096cbed1691c00", + "repo_path": "/workspace/repo/ImageMagick/ImageMagick", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ImageMagick_ImageMagick/2df29d4377b5882c0b3d63776964c74992bcff69/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ImageMagick_ImageMagick/2df29d4377b5882c0b3d63776964c74992bcff69/compile_commands.json", + "changed_files": [ + "coders/bmp.c" + ], + "commit_message": "Added extra check to resolve issue on 32-bit systems (https://github.com/ImageMagick/ImageMagick/security/advisories/GHSA-9pp9-cfwx-54rm)", + "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_138710/patch.diff b/tasks/csa159/pair_138710/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..04af987b0a54b3008edc285f388f19896a40458a --- /dev/null +++ b/tasks/csa159/pair_138710/patch.diff @@ -0,0 +1,13 @@ +diff --git a/coders/bmp.c b/coders/bmp.c +index e3f09a35d..4ba25c004 100644 +--- a/coders/bmp.c ++++ b/coders/bmp.c +@@ -1117,6 +1117,8 @@ static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + if (bmp_info.compression == BI_RLE4) + bmp_info.bits_per_pixel<<=1; ++ if (BMPOverflowCheck(image->columns,bmp_info.bits_per_pixel) != MagickFalse) ++ ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); + extent=image->columns*bmp_info.bits_per_pixel; + bytes_per_line=4*((extent+31)/32); + if (BMPOverflowCheck(bytes_per_line,image->rows) != MagickFalse) \ No newline at end of file diff --git a/tasks/csa159/pair_138710/post_functions.txt b/tasks/csa159/pair_138710/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2edaecb71c6e57acdfce588c4b2887bc51137a57 --- /dev/null +++ b/tasks/csa159/pair_138710/post_functions.txt @@ -0,0 +1,263 @@ +### File: coders/bmp.c +```c +static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + BMPInfo + bmp_info; + + Image + *image; + + MagickBooleanType + ignore_filesize, + status; + + MagickOffsetType + offset, + profile_data, + profile_size, + start_position; + + MagickSizeType + blob_size; + + MemoryInfo + *pixel_info; + + Quantum + index, + *q; + + size_t + bit, + bytes_per_line, + extent, + length; + + ssize_t + count, + i, + x, + y; + + unsigned char + magick[12], + *p, + *pixels; + + unsigned int + blue, + green, + offset_bits, + red; + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + if (IsEventLogging() != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", + image_info->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + image=AcquireImage(image_info,exception); + image->columns=0; + image->rows=0; + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Determine if this a BMP file. + */ + (void) memset(&bmp_info,0,sizeof(bmp_info)); + bmp_info.ba_offset=0; + start_position=0; + offset_bits=0; + count=ReadBlob(image,2,magick); + if (count != 2) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + blob_size=GetBlobSize(image); + do + { + PixelInfo + quantum_bits; + + PixelPacket + shift; + + /* + Verify BMP identifier. + */ + start_position=TellBlob(image)-2; + bmp_info.ba_offset=0; + while (LocaleNCompare((char *) magick,"BA",2) == 0) + { + bmp_info.file_size=ReadBlobLSBLong(image); + bmp_info.ba_offset=ReadBlobLSBLong(image); + bmp_info.offset_bits=ReadBlobLSBLong(image); + count=ReadBlob(image,2,magick); + if (count != 2) + break; + } + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", + magick[0],magick[1]); + if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && + (LocaleNCompare((char *) magick,"CI",2) != 0))) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + bmp_info.file_size=ReadBlobLSBLong(image); + (void) ReadBlobLSBLong(image); + bmp_info.offset_bits=ReadBlobLSBLong(image); + bmp_info.size=ReadBlobLSBLong(image); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " BMP header size: %u",bmp_info.size); + if (LocaleNCompare((char *) magick,"CI",2) == 0) + { + if ((bmp_info.size != 12) && (bmp_info.size != 40) && + (bmp_info.size != 64)) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + } + if (bmp_info.size > 124) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + /* + Get option to bypass file size check + */ + ignore_filesize=IsStringTrue(GetImageOption(image_info, + "bmp:ignore-filesize")); + if ((ignore_filesize == MagickFalse) && (bmp_info.file_size != 0) && + ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + if (bmp_info.offset_bits < bmp_info.size) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + bmp_info.offset_bits=MagickMax(14+bmp_info.size,bmp_info.offset_bits); + profile_data=0; + profile_size=0; + if (bmp_info.size == 12) + { + /* + OS/2 BMP image file. + */ + (void) CopyMagickString(image->magick,"BMP2",MagickPathExtent); + bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); + bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); + bmp_info.planes=ReadBlobLSBShort(image); + bmp_info.bits_per_pixel=ReadBlobLSBShort(image); + bmp_info.x_pixels=0; + bmp_info.y_pixels=0; + bmp_info.number_colors=0; + bmp_info.compression=BI_RGB; + bmp_info.image_size=0; + bmp_info.alpha_mask=0; + if (image->debug != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Format: OS/2 Bitmap"); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) + bmp_info.height); + } + } + else + { + /* + Microsoft Windows BMP image file. + */ + switch (bmp_info.size) + { + case 40: case 52: case 56: case 64: case 78: case 108: case 124: + { + break; + } + default: + { + if (bmp_info.size < 64) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + break; + } + } + bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); + bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); + bmp_info.planes=ReadBlobLSBShort(image); + bmp_info.bits_per_pixel=ReadBlobLSBShort(image); + bmp_info.compression=ReadBlobLSBLong(image); + if (bmp_info.size > 16) + { + bmp_info.image_size=ReadBlobLSBLong(image); + bmp_info.x_pixels=ReadBlobLSBLong(image); + bmp_info.y_pixels=ReadBlobLSBLong(image); + bmp_info.number_colors=ReadBlobLSBLong(image); + bmp_info.colors_important=ReadBlobLSBLong(image); + } + if (image->debug != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Format: MS Windows bitmap"); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) + bmp_info.height); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); + switch (bmp_info.compression) + { + case BI_RGB: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_RGB"); + break; + } + case BI_RLE4: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_RLE4"); + break; + } + case BI_RLE8: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_RLE8"); + break; + } + case BI_BITFIELDS: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_BITFIELDS"); + break; + } + case BI_ALPHABITFIELDS: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_ALPHABITFIELDS"); + break; + } + case BI_PNG: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_PNG"); + break; + } + case BI_JPEG: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_JPEG"); + break; + } + default: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: UNKNOWN (%u)",bmp_info.compression); + } + } + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Number of colors: %u",bmp_info.number_colors); + } + if ((bmp_info.height < 0) && + (bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) + ThrowReaderException(CoderErr + +// ... (33280 more chars) +``` diff --git a/tasks/csa159/pair_138710/pre_functions.txt b/tasks/csa159/pair_138710/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..dc4332d79ac6ab450bc12b6ea4f8d437533d504c --- /dev/null +++ b/tasks/csa159/pair_138710/pre_functions.txt @@ -0,0 +1,263 @@ +### File: coders/bmp.c +```c +static Image *ReadBMPImage(const ImageInfo *image_info,ExceptionInfo *exception) +{ + BMPInfo + bmp_info; + + Image + *image; + + MagickBooleanType + ignore_filesize, + status; + + MagickOffsetType + offset, + profile_data, + profile_size, + start_position; + + MagickSizeType + blob_size; + + MemoryInfo + *pixel_info; + + Quantum + index, + *q; + + size_t + bit, + bytes_per_line, + extent, + length; + + ssize_t + count, + i, + x, + y; + + unsigned char + magick[12], + *p, + *pixels; + + unsigned int + blue, + green, + offset_bits, + red; + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + if (IsEventLogging() != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", + image_info->filename); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + image=AcquireImage(image_info,exception); + image->columns=0; + image->rows=0; + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Determine if this a BMP file. + */ + (void) memset(&bmp_info,0,sizeof(bmp_info)); + bmp_info.ba_offset=0; + start_position=0; + offset_bits=0; + count=ReadBlob(image,2,magick); + if (count != 2) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + blob_size=GetBlobSize(image); + do + { + PixelInfo + quantum_bits; + + PixelPacket + shift; + + /* + Verify BMP identifier. + */ + start_position=TellBlob(image)-2; + bmp_info.ba_offset=0; + while (LocaleNCompare((char *) magick,"BA",2) == 0) + { + bmp_info.file_size=ReadBlobLSBLong(image); + bmp_info.ba_offset=ReadBlobLSBLong(image); + bmp_info.offset_bits=ReadBlobLSBLong(image); + count=ReadBlob(image,2,magick); + if (count != 2) + break; + } + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule()," Magick: %c%c", + magick[0],magick[1]); + if ((count != 2) || ((LocaleNCompare((char *) magick,"BM",2) != 0) && + (LocaleNCompare((char *) magick,"CI",2) != 0))) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + bmp_info.file_size=ReadBlobLSBLong(image); + (void) ReadBlobLSBLong(image); + bmp_info.offset_bits=ReadBlobLSBLong(image); + bmp_info.size=ReadBlobLSBLong(image); + if (image->debug != MagickFalse) + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " BMP header size: %u",bmp_info.size); + if (LocaleNCompare((char *) magick,"CI",2) == 0) + { + if ((bmp_info.size != 12) && (bmp_info.size != 40) && + (bmp_info.size != 64)) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + } + if (bmp_info.size > 124) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + /* + Get option to bypass file size check + */ + ignore_filesize=IsStringTrue(GetImageOption(image_info, + "bmp:ignore-filesize")); + if ((ignore_filesize == MagickFalse) && (bmp_info.file_size != 0) && + ((MagickSizeType) bmp_info.file_size > GetBlobSize(image))) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + if (bmp_info.offset_bits < bmp_info.size) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + bmp_info.offset_bits=MagickMax(14+bmp_info.size,bmp_info.offset_bits); + profile_data=0; + profile_size=0; + if (bmp_info.size == 12) + { + /* + OS/2 BMP image file. + */ + (void) CopyMagickString(image->magick,"BMP2",MagickPathExtent); + bmp_info.width=(ssize_t) ((short) ReadBlobLSBShort(image)); + bmp_info.height=(ssize_t) ((short) ReadBlobLSBShort(image)); + bmp_info.planes=ReadBlobLSBShort(image); + bmp_info.bits_per_pixel=ReadBlobLSBShort(image); + bmp_info.x_pixels=0; + bmp_info.y_pixels=0; + bmp_info.number_colors=0; + bmp_info.compression=BI_RGB; + bmp_info.image_size=0; + bmp_info.alpha_mask=0; + if (image->debug != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Format: OS/2 Bitmap"); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) + bmp_info.height); + } + } + else + { + /* + Microsoft Windows BMP image file. + */ + switch (bmp_info.size) + { + case 40: case 52: case 56: case 64: case 78: case 108: case 124: + { + break; + } + default: + { + if (bmp_info.size < 64) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + break; + } + } + bmp_info.width=(ssize_t) ReadBlobLSBSignedLong(image); + bmp_info.height=(ssize_t) ReadBlobLSBSignedLong(image); + bmp_info.planes=ReadBlobLSBShort(image); + bmp_info.bits_per_pixel=ReadBlobLSBShort(image); + bmp_info.compression=ReadBlobLSBLong(image); + if (bmp_info.size > 16) + { + bmp_info.image_size=ReadBlobLSBLong(image); + bmp_info.x_pixels=ReadBlobLSBLong(image); + bmp_info.y_pixels=ReadBlobLSBLong(image); + bmp_info.number_colors=ReadBlobLSBLong(image); + bmp_info.colors_important=ReadBlobLSBLong(image); + } + if (image->debug != MagickFalse) + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Format: MS Windows bitmap"); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Geometry: %.20gx%.20g",(double) bmp_info.width,(double) + bmp_info.height); + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Bits per pixel: %.20g",(double) bmp_info.bits_per_pixel); + switch (bmp_info.compression) + { + case BI_RGB: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_RGB"); + break; + } + case BI_RLE4: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_RLE4"); + break; + } + case BI_RLE8: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_RLE8"); + break; + } + case BI_BITFIELDS: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_BITFIELDS"); + break; + } + case BI_ALPHABITFIELDS: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_ALPHABITFIELDS"); + break; + } + case BI_PNG: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_PNG"); + break; + } + case BI_JPEG: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: BI_JPEG"); + break; + } + default: + { + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Compression: UNKNOWN (%u)",bmp_info.compression); + } + } + (void) LogMagickEvent(CoderEvent,GetMagickModule(), + " Number of colors: %u",bmp_info.number_colors); + } + if ((bmp_info.height < 0) && + (bmp_info.compression != BI_RGB) && (bmp_info.compression != BI_BITFIELDS)) + ThrowReaderException(CoderErr + +// ... (33126 more chars) +``` diff --git a/tasks/csa159/pair_138710/task_prompt.md b/tasks/csa159/pair_138710/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_138710/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_138728/checker_template.cpp b/tasks/csa159/pair_138728/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138728/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_138728/config.json b/tasks/csa159/pair_138728/config.json new file mode 100644 index 0000000000000000000000000000000000000000..c99880753ac70d9339533cd733f5372177e62b55 --- /dev/null +++ b/tasks/csa159/pair_138728/config.json @@ -0,0 +1,20 @@ +{ + "project_id": "ImageMagick_ImageMagick", + "before_commit": "8cb2a8ebbe3a8cc6dc4e5475ca54fa23e495c091", + "after_commit": "f86452a8aea37bf2b4bd36127f836dcc5f138b38", + "repo_path": "/workspace/repo/ImageMagick/ImageMagick", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ImageMagick_ImageMagick/03d19de047d7ce79e1f617562c43184ba54fa06e/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ImageMagick_ImageMagick/03d19de047d7ce79e1f617562c43184ba54fa06e/compile_commands.json", + "changed_files": [ + "coders/json.c", + "coders/yaml.c" + ], + "commit_message": "https://github.com/ImageMagick/ImageMagick/security/advisories/GHSA-5592-p365-24xh", + "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_138728/patch.diff b/tasks/csa159/pair_138728/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..eef159ce8bcd20b3d0601df3b45305bf1dbc2c00 --- /dev/null +++ b/tasks/csa159/pair_138728/patch.diff @@ -0,0 +1,59 @@ +diff --git a/coders/json.c b/coders/json.c +index b6bf9f424..1621b2a1c 100644 +--- a/coders/json.c ++++ b/coders/json.c +@@ -1541,15 +1541,16 @@ static MagickBooleanType EncodeImageAttributes(Image *image,FILE *file, + image_info=AcquireImageInfo(); + (void) CloneString(&image_info->size,"64x64"); + (void) FormatLocaleFile(file," \"montageDirectory\": ["); +- p=image->directory; +- while (*p != '\0') ++ for (p=image->directory; *p != '\0'; p++) + { + q=p; +- while ((*q != '\xff') && (*q != '\0')) ++ while ((*q != '\xff') && (*q != '\0') && ++ ((size_t) (q-p) < sizeof(image_info->filename))) + q++; + (void) CopyMagickString(image_info->filename,p,(size_t) (q-p+1)); +- p=q+1; +- JSONFormatLocaleFile(file,"{\n \"name\": %s",image_info->filename); ++ p=q; ++ JSONFormatLocaleFile(file,"{\n \"name\": %s", ++ image_info->filename); + handler=SetWarningHandler((WarningHandler) NULL); + tile=ReadImage(image_info,exception); + (void) SetWarningHandler(handler); +@@ -1559,7 +1560,8 @@ static MagickBooleanType EncodeImageAttributes(Image *image,FILE *file, + continue; + } + (void) FormatLocaleFile(file,",\n \"info\": \"%.20gx%.20g %s\"", +- (double) tile->magick_columns,(double) tile->magick_rows,tile->magick); ++ (double) tile->magick_columns,(double) tile->magick_rows, ++ tile->magick); + (void) SignatureImage(tile,exception); + ResetImagePropertyIterator(tile); + property=GetNextImageProperty(tile); +diff --git a/coders/yaml.c b/coders/yaml.c +index 99e9c72f8..3ef50a717 100644 +--- a/coders/yaml.c ++++ b/coders/yaml.c +@@ -1510,14 +1510,14 @@ static MagickBooleanType EncodeImageAttributes(Image *image,FILE *file, + image_info=AcquireImageInfo(); + (void) CloneString(&image_info->size,"64x64"); + (void) FormatLocaleFile(file," montageDirectory: "); +- p=image->directory; +- while (*p != '\0') ++ for (p=image->directory; *p != '\0'; p++) + { + q=p; +- while ((*q != '\xff') && (*q != '\0')) ++ while ((*q != '\xff') && (*q != '\0') && ++ ((size_t) (q-p) < sizeof(image_info->filename))) + q++; + (void) CopyMagickString(image_info->filename,p,(size_t) (q-p+1)); +- p=q+1; ++ p=q; + YAMLFormatLocaleFile(file,"\n - name: %s", + image_info->filename); + handler=SetWarningHandler((WarningHandler) NULL); \ No newline at end of file diff --git a/tasks/csa159/pair_138728/post_functions.txt b/tasks/csa159/pair_138728/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..77109e839ad62ae8eaa5e26c107eb7f31feb3ccc --- /dev/null +++ b/tasks/csa159/pair_138728/post_functions.txt @@ -0,0 +1,456 @@ +### File: coders/json.c +```c +static MagickBooleanType EncodeImageAttributes(Image *image,FILE *file, + ExceptionInfo *exception) +{ + char + color[MagickPathExtent], + format[MagickPathExtent], + key[MagickPathExtent]; + + ChannelFeatures + *channel_features; + + ChannelMoments + *channel_moments; + + ChannelPerceptualHash + *channel_phash; + + ChannelStatistics + *channel_statistics; + + const char + *artifact, + *locate, + *name, + *property, + *registry, + *value; + + const MagickInfo + *magick_info; + + double + elapsed_time, + scale, + user_time, + version; + + ImageType + type; + + MagickBooleanType + ping; + + size_t + depth, + distance; + + ssize_t + i, + x, + y; + + struct stat + properties; + + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (IsEventLogging() != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); + *format='\0'; + elapsed_time=GetElapsedTime(&image->timer); + user_time=GetUserTime(&image->timer); + GetTimerInfo(&image->timer); + ping=MagickTrue; + if (GetVirtualPixels(image,0,0,1,1,exception) != (const Quantum *) NULL) + ping=MagickFalse; + (void) ping; + (void) SignatureImage(image,exception); + (void) FormatLocaleFile(file,"{\n"); + version=1.0; + artifact=GetImageArtifact(image,"json:version"); + if (artifact != (const char *) NULL) + version=StringToDouble(artifact,(char **) NULL); + if (version >= 1.0) + (void) FormatLocaleFile(file," \"version\": \"%.1f\",\n",version); + if (*image->magick_filename == '\0') + JSONFormatLocaleFile(file," \"image\": {\n \"name\": %s,\n", + image->filename); + else + { + JSONFormatLocaleFile(file," \"image\": {\n \"name\": %s,\n", + image->magick_filename); + if (LocaleCompare(image->magick_filename,image->filename) != 0) + { + char + filename[MagickPathExtent]; + + GetPathComponent(image->magick_filename,TailPath,filename); + JSONFormatLocaleFile(file," \"baseName\": %s,\n",filename); + } + } + properties=(*GetBlobProperties(image)); + if (properties.st_mode != 0) + (void) FormatLocaleFile(file," \"permissions\": %d%d%d,\n", + (properties.st_mode >> 6) & 0x07,(properties.st_mode >> 3) & 0x07, + (properties.st_mode >> 0) & 0x07); + JSONFormatLocaleFile(file," \"format\": %s,\n",image->magick); + magick_info=GetMagickInfo(image->magick,exception); + if ((magick_info != (const MagickInfo *) NULL) && + (GetMagickDescription(magick_info) != (const char *) NULL)) + JSONFormatLocaleFile(file," \"formatDescription\": %s,\n", + GetMagickDescription(magick_info)); + if ((magick_info != (const MagickInfo *) NULL) && + (GetMagickMimeType(magick_info) != (const char *) NULL)) + JSONFormatLocaleFile(file," \"mimeType\": %s,\n",GetMagickMimeType( + magick_info)); + JSONFormatLocaleFile(file," \"class\": %s,\n",CommandOptionToMnemonic( + MagickClassOptions,(ssize_t) image->storage_class)); + (void) FormatLocaleFile(file," \"geometry\": {\n" + " \"width\": %g,\n \"height\": %g,\n" + " \"x\": %g,\n \"y\": %g\n },\n", + (double) image->columns,(double) image->rows,(double) image->tile_offset.x, + (double) image->tile_offset.y); + if ((image->magick_columns != 0) || (image->magick_rows != 0)) + if ((image->magick_columns != image->columns) || + (image->magick_rows != image->rows)) + (void) FormatLocaleFile(file," \"baseGeometry\": {\n" + " \"width\": %g,\n \"height\": %g\n },\n",(double) + image->magick_columns,(double) image->magick_rows); + if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) + { + (void) FormatLocaleFile(file," \"resolution\": {\n" + " \"x\": %g,\n \"y\": %g\n },\n",image->resolution.x, + image->resolution.y); + (void) FormatLocaleFile(file," \"printSize\": {\n" + " \"x\": %.*g,\n \"y\": %.*g\n },\n",GetMagickPrecision(), + image->columns/image->resolution.x,GetMagickPrecision(),(double) + image->rows/image->resolution.y); + } + JSONFormatLocaleFile(file," \"units\": %s,\n",CommandOptionToMnemonic( + MagickResolutionOptions,(ssize_t) image->units)); + type=IdentifyImageCoderType(image,exception); + JSONFormatLocaleFile(file," \"type\": %s,\n",CommandOptionToMnemonic( + MagickTypeOptions,(ssize_t) type)); + if (image->type != type) + JSONFormatLocaleFile(file," \"baseType\": %s,\n", + CommandOptionToMnemonic(MagickTypeOptions,(ssize_t) image->type)); + if (version < 1.0) + JSONFormatLocaleFile(file," \"endianess\": %s,\n", + CommandOptionToMnemonic(MagickEndianOptions,(ssize_t) image->endian)); + else + JSONFormatLocaleFile(file," \"endianness\": %s,\n", + CommandOptionToMnemonic(MagickEndianOptions,(ssize_t) image->endian)); + locate=GetImageArtifact(image,"identify:locate"); + if (locate == (const char *) NULL) + locate=GetImageArtifact(image,"json:locate"); + if (locate != (const char *) NULL) + { + const char + *limit; + + size_t + max_locations; + + StatisticType + statistic_type; + + /* + Display minimum, maximum, or mean pixel locations. + */ + statistic_type=(StatisticType) ParseCommandOption(MagickStatisticOptions, + MagickFalse,locate); + limit=GetImageArtifact(image,"identify:limit"); + if (limit == (const char *) NULL) + limit=GetImageArtifact(image,"json:limit"); + max_locations=0; + if (limit != (const char *) NULL) + max_locations=StringToUnsignedLong(limit); + channel_statistics=GetLocationStatistics(image,statistic_type,exception); + if (channel_statistics == (ChannelStatistics *) NULL) + return(MagickFalse); + (void) FormatLocaleFile(file," \"channel%s\": {\n",locate); + if (image->alpha_trait != UndefinedPixelTrait) + (void) PrintChannelLocations(file,image,AlphaPixelChannel,"alpha", + statistic_type,max_locations,MagickTrue,channel_statistics); + switch (image->colorspace) + { + case RGBColorspace: + default: + { + (void) PrintChannelLocations(file,image,RedPixelChannel,"red", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,GreenPixelChannel,"green", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,BluePixelChannel,"blue", + statistic_type,max_locations,MagickFalse,channel_statistics); + break; + } + case CMYKColorspace: + { + (void) PrintChannelLocations(file,image,CyanPixelChannel,"cyan", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,MagentaPixelChannel, + "magenta",statistic_type,max_locations,MagickTrue, + channel_statistics); + (void) PrintChannelLocations(file,image,YellowPixelChannel,"yellow", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,BlackPixelChannel,"black", + statistic_type,max_locations,MagickFalse,channel_statistics); + break; + } + case LinearGRAYColorspace: + case GRAYColorspace: + { + (void) PrintChannelLocations(file,image,GrayPixelChannel,"gray", + statistic_type,max_locations,MagickFalse,channel_statistics); + break; + } + } + (void) FormatLocaleFile(file," },\n"); + channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( + channel_statistics); + } + /* + Detail channel depth and extrema. + */ + JSONFormatLocaleFile(file," \"colorspace\": %s,\n", + CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t) + image->colorspace)); + channel_statistics=(ChannelStatistics *) NULL; + channe + +// ... (22145 more chars) +``` + +### File: coders/yaml.c +```c +static MagickBooleanType EncodeImageAttributes(Image *image,FILE *file, + ExceptionInfo *exception) +{ + char + color[MagickPathExtent], + format[MagickPathExtent], + key[MagickPathExtent]; + + ChannelFeatures + *channel_features; + + ChannelMoments + *channel_moments; + + ChannelPerceptualHash + *channel_phash; + + ChannelStatistics + *channel_statistics; + + const char + *artifact, + *locate, + *name, + *property, + *registry, + *value; + + const MagickInfo + *magick_info; + + double + elapsed_time, + scale, + user_time, + version; + + ImageType + type; + + MagickBooleanType + ping; + + size_t + depth, + distance; + + ssize_t + i, + x, + y; + + struct stat + properties; + + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (IsEventLogging() != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); + *format='\0'; + elapsed_time=GetElapsedTime(&image->timer); + user_time=GetUserTime(&image->timer); + GetTimerInfo(&image->timer); + ping=MagickTrue; + if (GetVirtualPixels(image,0,0,1,1,exception) != (const Quantum *) NULL) + ping=MagickFalse; + (void) ping; + (void) SignatureImage(image,exception); + (void) FormatLocaleFile(file,"---\n"); + version=1.0; + artifact=GetImageArtifact(image,"yaml:version"); + if (artifact != (const char *) NULL) + version=StringToDouble(artifact,(char **) NULL); + if (version >= 1.0) + (void) FormatLocaleFile(file," version: %.1f\n",version); + if (*image->magick_filename == '\0') + YAMLFormatLocaleFile(file," image: \n name: %s\n", + image->filename); + else + { + YAMLFormatLocaleFile(file," image: \n name: %s\n", + image->magick_filename); + if (LocaleCompare(image->magick_filename,image->filename) != 0) + { + char + filename[MagickPathExtent]; + + GetPathComponent(image->magick_filename,TailPath,filename); + YAMLFormatLocaleFile(file," baseName: %s\n",filename); + } + } + properties=(*GetBlobProperties(image)); + if (properties.st_mode != 0) + (void) FormatLocaleFile(file," permissions: %d%d%d\n", + (properties.st_mode >> 6) & 0x07,(properties.st_mode >> 3) & 0x07, + (properties.st_mode >> 0) & 0x07); + YAMLFormatLocaleFile(file," format: %s\n",image->magick); + magick_info=GetMagickInfo(image->magick,exception); + if ((magick_info != (const MagickInfo *) NULL) && + (GetMagickDescription(magick_info) != (const char *) NULL)) + YAMLFormatLocaleFile(file," formatDescription: %s\n", + GetMagickDescription(magick_info)); + if ((magick_info != (const MagickInfo *) NULL) && + (GetMagickMimeType(magick_info) != (const char *) NULL)) + YAMLFormatLocaleFile(file," mimeType: %s\n",GetMagickMimeType( + magick_info)); + YAMLFormatLocaleFile(file," class: %s\n",CommandOptionToMnemonic( + MagickClassOptions,(ssize_t) image->storage_class)); + (void) FormatLocaleFile(file," geometry: \n" + " width: %g\n height: %g\n" + " x: %g\n y: %g\n \n", + (double) image->columns,(double) image->rows,(double) image->tile_offset.x, + (double) image->tile_offset.y); + if ((image->magick_columns != 0) || (image->magick_rows != 0)) + if ((image->magick_columns != image->columns) || + (image->magick_rows != image->rows)) + (void) FormatLocaleFile(file," baseGeometry: \n" + " width: %g\n height: %g\n \n",(double) + image->magick_columns,(double) image->magick_rows); + if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) + { + (void) FormatLocaleFile(file," resolution: \n" + " x: %g\n y: %g\n \n",image->resolution.x, + image->resolution.y); + (void) FormatLocaleFile(file," printSize: \n" + " x: %.*g\n y: %.*g\n \n",GetMagickPrecision(), + image->columns/image->resolution.x,GetMagickPrecision(),(double) + image->rows/image->resolution.y); + } + YAMLFormatLocaleFile(file," units: %s\n",CommandOptionToMnemonic( + MagickResolutionOptions,(ssize_t) image->units)); + type=IdentifyImageCoderType(image,exception); + YAMLFormatLocaleFile(file," type: %s\n",CommandOptionToMnemonic( + MagickTypeOptions,(ssize_t) type)); + if (image->type != type) + YAMLFormatLocaleFile(file," baseType: %s\n", + CommandOptionToMnemonic(MagickTypeOptions,(ssize_t) image->type)); + if (version < 1.0) + YAMLFormatLocaleFile(file," endianess: %s\n", + CommandOptionToMnemonic(MagickEndianOptions,(ssize_t) image->endian)); + else + YAMLFormatLocaleFile(file," endianness: %s\n", + CommandOptionToMnemonic(MagickEndianOptions,(ssize_t) image->endian)); + locate=GetImageArtifact(image,"identify:locate"); + if (locate == (const char *) NULL) + locate=GetImageArtifact(image,"yaml:locate"); + if (locate != (const char *) NULL) + { + const char + *limit; + + size_t + max_locations; + + StatisticType + statistic_type; + + /* + Display minimum, maximum, or mean pixel locations. + */ + statistic_type=(StatisticType) ParseCommandOption(MagickStatisticOptions, + MagickFalse,locate); + limit=GetImageArtifact(image,"identify:limit"); + if (limit == (const char *) NULL) + limit=GetImageArtifact(image,"yaml:limit"); + max_locations=0; + if (limit != (const char *) NULL) + max_locations=StringToUnsignedLong(limit); + channel_statistics=GetLocationStatistics(image,statistic_type,exception); + if (channel_statistics == (ChannelStatistics *) NULL) + return(MagickFalse); + (void) FormatLocaleFile(file," channel%s: \n",locate); + if (image->alpha_trait != UndefinedPixelTrait) + (void) PrintChannelLocations(file,image,AlphaPixelChannel,"alpha", + statistic_type,max_locations,MagickTrue,channel_statistics); + switch (image->colorspace) + { + case RGBColorspace: + default: + { + (void) PrintChannelLocations(file,image,RedPixelChannel,"red", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,GreenPixelChannel,"green", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,BluePixelChannel,"blue", + statistic_type,max_locations,MagickFalse,channel_statistics); + break; + } + case CMYKColorspace: + { + (void) PrintChannelLocations(file,image,CyanPixelChannel,"cyan", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,MagentaPixelChannel, + "magenta",statistic_type,max_locations,MagickTrue, + channel_statistics); + (void) PrintChannelLocations(file,image,YellowPixelChannel,"yellow", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,BlackPixelChannel,"black", + statistic_type,max_locations,MagickFalse,channel_statistics); + break; + } + case LinearGRAYColorspace: + case GRAYColorspace: + { + (void) PrintChannelLocations(file,image,GrayPixelChannel,"gray", + statistic_type,max_locations,MagickFalse,channel_statistics); + break; + } + } + (void) FormatLocaleFile(file," \n"); + channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( + channel_statistics); + } + /* + Detail channel depth and extrema. + */ + YAMLFormatLocaleFile(file," colorspace: %s\n", + CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t) + image->colorspace)); + channel_statistics=(ChannelStatistics *) NULL; + channel_moments=(ChannelMoments *) NULL; + channel_phash=(ChannelPerceptualHash *) NULL; + channel_features=(ChannelFeatures *) NULL; + channel_statistics=GetImageStatistics( + +// ... (21234 more chars) +``` diff --git a/tasks/csa159/pair_138728/pre_functions.txt b/tasks/csa159/pair_138728/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..41d0d0bc514e49a5816069b96696e4ed64ff890e --- /dev/null +++ b/tasks/csa159/pair_138728/pre_functions.txt @@ -0,0 +1,456 @@ +### File: coders/json.c +```c +static MagickBooleanType EncodeImageAttributes(Image *image,FILE *file, + ExceptionInfo *exception) +{ + char + color[MagickPathExtent], + format[MagickPathExtent], + key[MagickPathExtent]; + + ChannelFeatures + *channel_features; + + ChannelMoments + *channel_moments; + + ChannelPerceptualHash + *channel_phash; + + ChannelStatistics + *channel_statistics; + + const char + *artifact, + *locate, + *name, + *property, + *registry, + *value; + + const MagickInfo + *magick_info; + + double + elapsed_time, + scale, + user_time, + version; + + ImageType + type; + + MagickBooleanType + ping; + + size_t + depth, + distance; + + ssize_t + i, + x, + y; + + struct stat + properties; + + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (IsEventLogging() != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); + *format='\0'; + elapsed_time=GetElapsedTime(&image->timer); + user_time=GetUserTime(&image->timer); + GetTimerInfo(&image->timer); + ping=MagickTrue; + if (GetVirtualPixels(image,0,0,1,1,exception) != (const Quantum *) NULL) + ping=MagickFalse; + (void) ping; + (void) SignatureImage(image,exception); + (void) FormatLocaleFile(file,"{\n"); + version=1.0; + artifact=GetImageArtifact(image,"json:version"); + if (artifact != (const char *) NULL) + version=StringToDouble(artifact,(char **) NULL); + if (version >= 1.0) + (void) FormatLocaleFile(file," \"version\": \"%.1f\",\n",version); + if (*image->magick_filename == '\0') + JSONFormatLocaleFile(file," \"image\": {\n \"name\": %s,\n", + image->filename); + else + { + JSONFormatLocaleFile(file," \"image\": {\n \"name\": %s,\n", + image->magick_filename); + if (LocaleCompare(image->magick_filename,image->filename) != 0) + { + char + filename[MagickPathExtent]; + + GetPathComponent(image->magick_filename,TailPath,filename); + JSONFormatLocaleFile(file," \"baseName\": %s,\n",filename); + } + } + properties=(*GetBlobProperties(image)); + if (properties.st_mode != 0) + (void) FormatLocaleFile(file," \"permissions\": %d%d%d,\n", + (properties.st_mode >> 6) & 0x07,(properties.st_mode >> 3) & 0x07, + (properties.st_mode >> 0) & 0x07); + JSONFormatLocaleFile(file," \"format\": %s,\n",image->magick); + magick_info=GetMagickInfo(image->magick,exception); + if ((magick_info != (const MagickInfo *) NULL) && + (GetMagickDescription(magick_info) != (const char *) NULL)) + JSONFormatLocaleFile(file," \"formatDescription\": %s,\n", + GetMagickDescription(magick_info)); + if ((magick_info != (const MagickInfo *) NULL) && + (GetMagickMimeType(magick_info) != (const char *) NULL)) + JSONFormatLocaleFile(file," \"mimeType\": %s,\n",GetMagickMimeType( + magick_info)); + JSONFormatLocaleFile(file," \"class\": %s,\n",CommandOptionToMnemonic( + MagickClassOptions,(ssize_t) image->storage_class)); + (void) FormatLocaleFile(file," \"geometry\": {\n" + " \"width\": %g,\n \"height\": %g,\n" + " \"x\": %g,\n \"y\": %g\n },\n", + (double) image->columns,(double) image->rows,(double) image->tile_offset.x, + (double) image->tile_offset.y); + if ((image->magick_columns != 0) || (image->magick_rows != 0)) + if ((image->magick_columns != image->columns) || + (image->magick_rows != image->rows)) + (void) FormatLocaleFile(file," \"baseGeometry\": {\n" + " \"width\": %g,\n \"height\": %g\n },\n",(double) + image->magick_columns,(double) image->magick_rows); + if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) + { + (void) FormatLocaleFile(file," \"resolution\": {\n" + " \"x\": %g,\n \"y\": %g\n },\n",image->resolution.x, + image->resolution.y); + (void) FormatLocaleFile(file," \"printSize\": {\n" + " \"x\": %.*g,\n \"y\": %.*g\n },\n",GetMagickPrecision(), + image->columns/image->resolution.x,GetMagickPrecision(),(double) + image->rows/image->resolution.y); + } + JSONFormatLocaleFile(file," \"units\": %s,\n",CommandOptionToMnemonic( + MagickResolutionOptions,(ssize_t) image->units)); + type=IdentifyImageCoderType(image,exception); + JSONFormatLocaleFile(file," \"type\": %s,\n",CommandOptionToMnemonic( + MagickTypeOptions,(ssize_t) type)); + if (image->type != type) + JSONFormatLocaleFile(file," \"baseType\": %s,\n", + CommandOptionToMnemonic(MagickTypeOptions,(ssize_t) image->type)); + if (version < 1.0) + JSONFormatLocaleFile(file," \"endianess\": %s,\n", + CommandOptionToMnemonic(MagickEndianOptions,(ssize_t) image->endian)); + else + JSONFormatLocaleFile(file," \"endianness\": %s,\n", + CommandOptionToMnemonic(MagickEndianOptions,(ssize_t) image->endian)); + locate=GetImageArtifact(image,"identify:locate"); + if (locate == (const char *) NULL) + locate=GetImageArtifact(image,"json:locate"); + if (locate != (const char *) NULL) + { + const char + *limit; + + size_t + max_locations; + + StatisticType + statistic_type; + + /* + Display minimum, maximum, or mean pixel locations. + */ + statistic_type=(StatisticType) ParseCommandOption(MagickStatisticOptions, + MagickFalse,locate); + limit=GetImageArtifact(image,"identify:limit"); + if (limit == (const char *) NULL) + limit=GetImageArtifact(image,"json:limit"); + max_locations=0; + if (limit != (const char *) NULL) + max_locations=StringToUnsignedLong(limit); + channel_statistics=GetLocationStatistics(image,statistic_type,exception); + if (channel_statistics == (ChannelStatistics *) NULL) + return(MagickFalse); + (void) FormatLocaleFile(file," \"channel%s\": {\n",locate); + if (image->alpha_trait != UndefinedPixelTrait) + (void) PrintChannelLocations(file,image,AlphaPixelChannel,"alpha", + statistic_type,max_locations,MagickTrue,channel_statistics); + switch (image->colorspace) + { + case RGBColorspace: + default: + { + (void) PrintChannelLocations(file,image,RedPixelChannel,"red", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,GreenPixelChannel,"green", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,BluePixelChannel,"blue", + statistic_type,max_locations,MagickFalse,channel_statistics); + break; + } + case CMYKColorspace: + { + (void) PrintChannelLocations(file,image,CyanPixelChannel,"cyan", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,MagentaPixelChannel, + "magenta",statistic_type,max_locations,MagickTrue, + channel_statistics); + (void) PrintChannelLocations(file,image,YellowPixelChannel,"yellow", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,BlackPixelChannel,"black", + statistic_type,max_locations,MagickFalse,channel_statistics); + break; + } + case LinearGRAYColorspace: + case GRAYColorspace: + { + (void) PrintChannelLocations(file,image,GrayPixelChannel,"gray", + statistic_type,max_locations,MagickFalse,channel_statistics); + break; + } + } + (void) FormatLocaleFile(file," },\n"); + channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( + channel_statistics); + } + /* + Detail channel depth and extrema. + */ + JSONFormatLocaleFile(file," \"colorspace\": %s,\n", + CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t) + image->colorspace)); + channel_statistics=(ChannelStatistics *) NULL; + channe + +// ... (22062 more chars) +``` + +### File: coders/yaml.c +```c +static MagickBooleanType EncodeImageAttributes(Image *image,FILE *file, + ExceptionInfo *exception) +{ + char + color[MagickPathExtent], + format[MagickPathExtent], + key[MagickPathExtent]; + + ChannelFeatures + *channel_features; + + ChannelMoments + *channel_moments; + + ChannelPerceptualHash + *channel_phash; + + ChannelStatistics + *channel_statistics; + + const char + *artifact, + *locate, + *name, + *property, + *registry, + *value; + + const MagickInfo + *magick_info; + + double + elapsed_time, + scale, + user_time, + version; + + ImageType + type; + + MagickBooleanType + ping; + + size_t + depth, + distance; + + ssize_t + i, + x, + y; + + struct stat + properties; + + assert(image != (Image *) NULL); + assert(image->signature == MagickCoreSignature); + if (IsEventLogging() != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); + *format='\0'; + elapsed_time=GetElapsedTime(&image->timer); + user_time=GetUserTime(&image->timer); + GetTimerInfo(&image->timer); + ping=MagickTrue; + if (GetVirtualPixels(image,0,0,1,1,exception) != (const Quantum *) NULL) + ping=MagickFalse; + (void) ping; + (void) SignatureImage(image,exception); + (void) FormatLocaleFile(file,"---\n"); + version=1.0; + artifact=GetImageArtifact(image,"yaml:version"); + if (artifact != (const char *) NULL) + version=StringToDouble(artifact,(char **) NULL); + if (version >= 1.0) + (void) FormatLocaleFile(file," version: %.1f\n",version); + if (*image->magick_filename == '\0') + YAMLFormatLocaleFile(file," image: \n name: %s\n", + image->filename); + else + { + YAMLFormatLocaleFile(file," image: \n name: %s\n", + image->magick_filename); + if (LocaleCompare(image->magick_filename,image->filename) != 0) + { + char + filename[MagickPathExtent]; + + GetPathComponent(image->magick_filename,TailPath,filename); + YAMLFormatLocaleFile(file," baseName: %s\n",filename); + } + } + properties=(*GetBlobProperties(image)); + if (properties.st_mode != 0) + (void) FormatLocaleFile(file," permissions: %d%d%d\n", + (properties.st_mode >> 6) & 0x07,(properties.st_mode >> 3) & 0x07, + (properties.st_mode >> 0) & 0x07); + YAMLFormatLocaleFile(file," format: %s\n",image->magick); + magick_info=GetMagickInfo(image->magick,exception); + if ((magick_info != (const MagickInfo *) NULL) && + (GetMagickDescription(magick_info) != (const char *) NULL)) + YAMLFormatLocaleFile(file," formatDescription: %s\n", + GetMagickDescription(magick_info)); + if ((magick_info != (const MagickInfo *) NULL) && + (GetMagickMimeType(magick_info) != (const char *) NULL)) + YAMLFormatLocaleFile(file," mimeType: %s\n",GetMagickMimeType( + magick_info)); + YAMLFormatLocaleFile(file," class: %s\n",CommandOptionToMnemonic( + MagickClassOptions,(ssize_t) image->storage_class)); + (void) FormatLocaleFile(file," geometry: \n" + " width: %g\n height: %g\n" + " x: %g\n y: %g\n \n", + (double) image->columns,(double) image->rows,(double) image->tile_offset.x, + (double) image->tile_offset.y); + if ((image->magick_columns != 0) || (image->magick_rows != 0)) + if ((image->magick_columns != image->columns) || + (image->magick_rows != image->rows)) + (void) FormatLocaleFile(file," baseGeometry: \n" + " width: %g\n height: %g\n \n",(double) + image->magick_columns,(double) image->magick_rows); + if ((image->resolution.x != 0.0) && (image->resolution.y != 0.0)) + { + (void) FormatLocaleFile(file," resolution: \n" + " x: %g\n y: %g\n \n",image->resolution.x, + image->resolution.y); + (void) FormatLocaleFile(file," printSize: \n" + " x: %.*g\n y: %.*g\n \n",GetMagickPrecision(), + image->columns/image->resolution.x,GetMagickPrecision(),(double) + image->rows/image->resolution.y); + } + YAMLFormatLocaleFile(file," units: %s\n",CommandOptionToMnemonic( + MagickResolutionOptions,(ssize_t) image->units)); + type=IdentifyImageCoderType(image,exception); + YAMLFormatLocaleFile(file," type: %s\n",CommandOptionToMnemonic( + MagickTypeOptions,(ssize_t) type)); + if (image->type != type) + YAMLFormatLocaleFile(file," baseType: %s\n", + CommandOptionToMnemonic(MagickTypeOptions,(ssize_t) image->type)); + if (version < 1.0) + YAMLFormatLocaleFile(file," endianess: %s\n", + CommandOptionToMnemonic(MagickEndianOptions,(ssize_t) image->endian)); + else + YAMLFormatLocaleFile(file," endianness: %s\n", + CommandOptionToMnemonic(MagickEndianOptions,(ssize_t) image->endian)); + locate=GetImageArtifact(image,"identify:locate"); + if (locate == (const char *) NULL) + locate=GetImageArtifact(image,"yaml:locate"); + if (locate != (const char *) NULL) + { + const char + *limit; + + size_t + max_locations; + + StatisticType + statistic_type; + + /* + Display minimum, maximum, or mean pixel locations. + */ + statistic_type=(StatisticType) ParseCommandOption(MagickStatisticOptions, + MagickFalse,locate); + limit=GetImageArtifact(image,"identify:limit"); + if (limit == (const char *) NULL) + limit=GetImageArtifact(image,"yaml:limit"); + max_locations=0; + if (limit != (const char *) NULL) + max_locations=StringToUnsignedLong(limit); + channel_statistics=GetLocationStatistics(image,statistic_type,exception); + if (channel_statistics == (ChannelStatistics *) NULL) + return(MagickFalse); + (void) FormatLocaleFile(file," channel%s: \n",locate); + if (image->alpha_trait != UndefinedPixelTrait) + (void) PrintChannelLocations(file,image,AlphaPixelChannel,"alpha", + statistic_type,max_locations,MagickTrue,channel_statistics); + switch (image->colorspace) + { + case RGBColorspace: + default: + { + (void) PrintChannelLocations(file,image,RedPixelChannel,"red", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,GreenPixelChannel,"green", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,BluePixelChannel,"blue", + statistic_type,max_locations,MagickFalse,channel_statistics); + break; + } + case CMYKColorspace: + { + (void) PrintChannelLocations(file,image,CyanPixelChannel,"cyan", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,MagentaPixelChannel, + "magenta",statistic_type,max_locations,MagickTrue, + channel_statistics); + (void) PrintChannelLocations(file,image,YellowPixelChannel,"yellow", + statistic_type,max_locations,MagickTrue,channel_statistics); + (void) PrintChannelLocations(file,image,BlackPixelChannel,"black", + statistic_type,max_locations,MagickFalse,channel_statistics); + break; + } + case LinearGRAYColorspace: + case GRAYColorspace: + { + (void) PrintChannelLocations(file,image,GrayPixelChannel,"gray", + statistic_type,max_locations,MagickFalse,channel_statistics); + break; + } + } + (void) FormatLocaleFile(file," \n"); + channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( + channel_statistics); + } + /* + Detail channel depth and extrema. + */ + YAMLFormatLocaleFile(file," colorspace: %s\n", + CommandOptionToMnemonic(MagickColorspaceOptions,(ssize_t) + image->colorspace)); + channel_statistics=(ChannelStatistics *) NULL; + channel_moments=(ChannelMoments *) NULL; + channel_phash=(ChannelPerceptualHash *) NULL; + channel_features=(ChannelFeatures *) NULL; + channel_statistics=GetImageStatistics( + +// ... (21173 more chars) +``` diff --git a/tasks/csa159/pair_138728/task_prompt.md b/tasks/csa159/pair_138728/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..97dd22eac0d15f5b0575fa3b3dcf3beb28f63c5a --- /dev/null +++ b/tasks/csa159/pair_138728/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 failed rollout compiled and completed its buggy-source scan but emitted zero diagnostics in both affected functions, so it never established the required vulnerable-before signal. +- The sink matcher remained unproven against the real call expressions; in particular, destination extent recovery must account for array-to-pointer decay at image_info->filename rather than relying only on the argument's pointer type or resulting region. +- The attempted path-sensitive fact model added complexity without producing observable differential detection, leaving hard validation, cross-validation, refinement, semantic adequacy, and process quality unsatisfied. +- No accepted semantic contract was recorded in the constraint ledger, so the new synthesis must derive and validate its contract directly from the patch and supplied source evidence. + +### Preserve from prior rollouts + +- Compile successfully and retain successful before/after validation and code verification. +- Meet objective eligibility gate G6. +- Maintain semantic score at or above the configured threshold. +- Remain independent of patch anchors. +- Remain free of patch-local hardcoding. + +### Required semantic proof + +- Recognize a CopyMagickString call whose destination expression denotes a fixed-size array of byte extent E and whose length is derived from a pointer distance q-p plus the terminator allowance. +- Establish that q is initialized from p, is advanced by the scan loop, and reaches the sink after that loop without an intervening assignment that invalidates the relationship. +- Report when control flow permits repeated cursor advancement without a loop-continuation comparison that bounds q-p by the destination extent. +- Treat the patched conjunct `(size_t)(q-p) < sizeof(destination)` as the reference fix's intended safety condition only when it is evaluated on every loop-continuation path before the cursor advance. +- Honor guard polarity and short-circuit structure: a bound hidden under disjunction, negation, an unrelated branch, or a loop-body-only test must not prove the scan safe. +- Apply the supplied reference-fix boundary policy explicitly: `< E` may establish the intended cap even though loop exit can leave q-p equal to E. + +### Implementation constraints + +- Use an intraprocedural CSA control-flow design, such as check::ASTCodeBody with the function CFG, to relate initialization, loop guard, cursor update, loop exit, and sink ordering. +- Recover the fixed-array extent from the destination's pre-decay AST expression or underlying typed storage, including member arrays such as image_info->filename; reject pointers, VLAs, incomplete arrays, and unknown extents. +- Normalize casts and parentheses when matching pointer subtraction, constant addition, sizeof-based bounds, and reversed comparison operands. +- Require the relevant bound comparison to control the loop continuation and the cursor advance; use CFG reachability or dominance relationships together with guard polarity rather than textual proximity. +- Invalidate a candidate proof when base or cursor assignments between initialization, loop, and sink can change the analyzed relationship. +- Emit the diagnostic at the vulnerable CopyMagickString call and attach its source range. +- Keep project-general scope around the stable CopyMagickString API and semantic argument roles, without restricting detection to EncodeImageAttributes. +- Do not encode filenames, function names, changed line numbers, literal patch snippets, or the numeric value of MagickPathExtent. + +### Validation checklist + +- Build and load the checker successfully with the target Clang Static Analyzer API. +- Run the buggy revision and verify diagnostics at the CopyMagickString calls in both coders/json.c and coders/yaml.c EncodeImageAttributes. +- Run the patched revision and verify that those diagnostics disappear because the loop-continuation bound is recognized. +- Confirm each buggy diagnostic is located at or immediately associated with the relevant sink call, not merely somewhere in the enclosing function. +- Cross-validate with at least one unbounded synthetic variant and bounded variants covering conjunction order, reversed comparison operands, and casts around q-p. +- Verify that disjunctive, negated, branch-only, loop-body-only, too-large, or unrelated-pair bounds do not suppress a report. +- Verify array-member destinations survive array-to-pointer decay while pointer, VLA, incomplete-array, and unknown-extent destinations remain outside the asserted proof. +- Run refinement and code verification to completion and require accepted refinement, G6 eligibility, nonzero buggy findings, patched disappearance, and no unrelated patch-anchor dependence. + +### Avoid and forbidden regressions + +- Do not reuse the failed ProgramState scan-bound strategy merely because it was previously attempted; path-sensitive state is unnecessary if the local CFG proves the required relation. +- Do not decide safety from the sink-time length SVal alone, because the supplied probe evidence found q-p and length unknown in both revisions. +- Do not use AST co-occurrence or textual presence of a comparison as proof that the guard controls every cursor advance. +- Do not use guard dominance alone without checking comparison polarity, short-circuit semantics, loop membership, and the guarded update. +- Do not suppress solely because q was once assigned p; an unbounded subsequent scan invalidates that zero-distance fact. +- Do not emit debugging output or accept a compile-only result as validation. +- Do not broaden reporting to arbitrary string-copy calls or arbitrary pointer arithmetic unsupported by the supplied vulnerability pattern. diff --git a/tasks/csa159/pair_138746/checker_template.cpp b/tasks/csa159/pair_138746/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138746/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_138746/config.json b/tasks/csa159/pair_138746/config.json new file mode 100644 index 0000000000000000000000000000000000000000..49b09845a7161afee4bd21366f5af5fc43df62b4 --- /dev/null +++ b/tasks/csa159/pair_138746/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "ImageMagick_ImageMagick", + "before_commit": "bc0bbec029e2d6e8dcc4294653907b0dd28fe465", + "after_commit": "81ac8a0d2eb21739842ed18c48c7646b7eef65b8", + "repo_path": "/workspace/repo/ImageMagick/ImageMagick", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ImageMagick_ImageMagick/8c781e209db7d674a77e1f1edd7a51a446b51f68/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ImageMagick_ImageMagick/8c781e209db7d674a77e1f1edd7a51a446b51f68/compile_commands.json", + "changed_files": [ + "coders/miff.c" + ], + "commit_message": "multispectral MIFF images renders all channels in arbitrary order", + "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_138746/patch.diff b/tasks/csa159/pair_138746/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7e5351c6a5ed7ca5b525c02601b50726bf341375 --- /dev/null +++ b/tasks/csa159/pair_138746/patch.diff @@ -0,0 +1,26 @@ +diff --git a/coders/miff.c b/coders/miff.c +index 355455bc5..398f66d0b 100644 +--- a/coders/miff.c ++++ b/coders/miff.c +@@ -1347,10 +1347,10 @@ static Image *ReadMIFFImage(const ImageInfo *image_info, + packet_size+=image->depth/8; + if (image->colorspace == CMYKColorspace) + packet_size+=image->depth/8; ++ if (image->number_meta_channels != 0) ++ packet_size=GetImageChannels(image)*image->depth/8; + if (image->compression == RLECompression) + packet_size++; +- if (image->number_meta_channels != 0) +- packet_size+=image->number_meta_channels*image->depth/8; + compress_extent=MagickMax(MagickMax(BZipMaxExtent(packet_size* + image->columns),LZMAMaxExtent(packet_size*image->columns)), + ZipMaxExtent(packet_size*image->columns)); +@@ -2171,7 +2171,7 @@ static MagickBooleanType WriteMIFFImage(const ImageInfo *image_info, + if (compression == RLECompression) + packet_size++; + if (image->number_meta_channels != 0) +- packet_size+=image->number_meta_channels*image->depth/8; ++ packet_size=GetImageChannels(image)*image->depth/8; + length=MagickMax(BZipMaxExtent(packet_size*image->columns),ZipMaxExtent( + packet_size*image->columns)); + if ((compression == BZipCompression) || (compression == ZipCompression)) \ No newline at end of file diff --git a/tasks/csa159/pair_138746/post_functions.txt b/tasks/csa159/pair_138746/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..e26053a38391916429e8c9a4b506ffee6c814e11 --- /dev/null +++ b/tasks/csa159/pair_138746/post_functions.txt @@ -0,0 +1,286 @@ +### File: coders/miff.c +```c +static Image *ReadMIFFImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ +#define BZipMaxExtent(x) ((x)+((x)/100)+600) +#define LZMAMaxExtent(x) ((x)+((x)/3)+128) +#define ThrowMIFFException(exception,message) \ +{ \ + if (quantum_info != (QuantumInfo *) NULL) \ + quantum_info=DestroyQuantumInfo(quantum_info); \ + if (compress_pixels != (unsigned char *) NULL) \ + compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels); \ + ThrowReaderException((exception),(message)); \ +} +#define ZipMaxExtent(x) ((x)+(((x)+7) >> 3)+(((x)+63) >> 6)+11) + +#if defined(MAGICKCORE_BZLIB_DELEGATE) + bz_stream + bzip_info; +#endif + + char + id[MagickPathExtent], + keyword[MagickPathExtent], + *options; + + double + version; + + GeometryInfo + geometry_info; + + Image + *image; + + int + c; + + LinkedListInfo + *profiles; + +#if defined(MAGICKCORE_LZMA_DELEGATE) + lzma_stream + initialize_lzma = LZMA_STREAM_INIT, + lzma_info = LZMA_STREAM_INIT; + + lzma_allocator + allocator; +#endif + + MagickBooleanType + status; + + PixelInfo + pixel; + + MagickStatusType + flags; + + QuantumFormatType + quantum_format; + + QuantumInfo + *quantum_info; + + QuantumType + quantum_type; + + size_t + colors, + compress_extent, + extent, + length, + packet_size; + + ssize_t + count, + i, + y; + + unsigned char + *compress_pixels, + *pixels; + + +#if defined(MAGICKCORE_ZLIB_DELEGATE) + z_stream + zip_info; +#endif + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + if (IsEventLogging() != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", + image_info->filename); + image=AcquireImage(image_info,exception); + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Decode image header; header terminates one character beyond a ':'. + */ + c=ReadBlobByte(image); + if (c == EOF) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + *id='\0'; + compress_pixels=(unsigned char *) NULL; + quantum_info=(QuantumInfo *) NULL; + (void) memset(keyword,0,sizeof(keyword)); + version=0.0; + (void) version; + do + { + /* + Decode image header; header terminates one character beyond a ':'. + */ + SetGeometryInfo(&geometry_info); + length=MagickPathExtent; + options=AcquireString((char *) NULL); + quantum_format=UndefinedQuantumFormat; + profiles=(LinkedListInfo *) NULL; + colors=0; + image->depth=8UL; + image->compression=NoCompression; + while ((isgraph((int) ((unsigned char) c)) != 0) && (c != (int) ':')) + { + char + *p; + + if (c == (int) '{') + { + char + *comment; + + /* + Read comment-- any text between { }. + */ + length=MagickPathExtent; + comment=AcquireString((char *) NULL); + for (p=comment; comment != (char *) NULL; p++) + { + c=ReadBlobByte(image); + if (c == (int) '\\') + c=ReadBlobByte(image); + else + if ((c == EOF) || (c == (int) '}')) + break; + if ((size_t) (p-comment+1) >= length) + { + *p='\0'; + length<<=1; + comment=(char *) ResizeQuantumMemory(comment, + OverAllocateMemory(length+MagickPathExtent),sizeof(*comment)); + if (comment == (char *) NULL) + break; + p=comment+strlen(comment); + } + *p=(char) c; + } + if (comment == (char *) NULL) + { + options=DestroyString(options); + ThrowMIFFException(ResourceLimitError,"MemoryAllocationFailed"); + } + *p='\0'; + (void) SetImageProperty(image,"comment",comment,exception); + comment=DestroyString(comment); + c=ReadBlobByte(image); + } + else + if (isalnum((int) ((unsigned char) c)) != MagickFalse) + { + /* + Get the keyword. + */ + length=MagickPathExtent-1; + p=keyword; + do + { + if (c == (int) '=') + break; + if ((size_t) (p-keyword) < (MagickPathExtent-1)) + *p++=(char) c; + c=ReadBlobByte(image); + } while (c != EOF); + *p='\0'; + p=options; + while ((isspace((int) ((unsigned char) c)) != 0) && (c != EOF)) + c=ReadBlobByte(image); + if (c == (int) '=') + { + /* + Get the keyword value. + */ + c=ReadBlobByte(image); + while ((c != (int) '{') && (c != (int) '}') && (c != EOF)) + { + if ((size_t) (p-options+1) >= length) + { + *p='\0'; + length<<=1; + options=(char *) ResizeQuantumMemory(options,length+ + MagickPathExtent,sizeof(*options)); + if (options == (char *) NULL) + break; + p=options+strlen(options); + } + *p++=(char) c; + c=ReadBlobByte(image); + if (c == '\\') + { + c=ReadBlobByte(image); + if ((c == (int) '{') || (c == (int) '}')) + { + *p++=(char) c; + c=ReadBlobByte(image); + } + } + if (*options != '{') + if (isspace((int) ((unsigned char) c)) != 0) + break; + } + if (options == (char *) NULL) + ThrowMIFFException(ResourceLimitError, + "MemoryAllocationFailed"); + } + *p='\0'; + if (*options == '{') + (void) CopyMagickString(options,options+1,strlen(options)); + /* + Assign a value to the specified keyword. + */ + switch (*keyword) + { + case 'a': + case 'A': + { + if (LocaleCompare(keyword,"alpha-trait") == 0) + { + ssize_t + alpha_trait; + + alpha_trait=ParseCommandOption(MagickPixelTraitOptions, + MagickFalse,options); + if (alpha_trait < 0) + break; + image->alpha_trait=(PixelTrait) alpha_trait; + break; + } + (void) SetImageProperty(image,keyword,options,exception); + break; + } + case 'b': + case 'B': + { + if (LocaleCompare(keyword,"background-color") == 0) + { + (void) QueryColorCompliance(options,AllCompliance, + &image->background_color,exception); + break; + } + if (LocaleCompare(keyword,"blue-primary") == 0) + { + flags=ParseGeometry(options,&geometry_info); + image->chromaticity.blue_primary.x=geometry_info.rho; + image->chromaticity.blue_primary.y=geometry_info.sigma; + if ((flags & SigmaValue) == 0) + image->chromaticity.blue_primary.y= + image->chromaticity.blue_primary.x; + break; + } + if (LocaleCompare(keyword,"border-color") == 0) + { + + +// ... (65079 more chars) +``` diff --git a/tasks/csa159/pair_138746/pre_functions.txt b/tasks/csa159/pair_138746/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..de03a688a380b296ccbd3eb8cf7c3c20b8282772 --- /dev/null +++ b/tasks/csa159/pair_138746/pre_functions.txt @@ -0,0 +1,286 @@ +### File: coders/miff.c +```c +static Image *ReadMIFFImage(const ImageInfo *image_info, + ExceptionInfo *exception) +{ +#define BZipMaxExtent(x) ((x)+((x)/100)+600) +#define LZMAMaxExtent(x) ((x)+((x)/3)+128) +#define ThrowMIFFException(exception,message) \ +{ \ + if (quantum_info != (QuantumInfo *) NULL) \ + quantum_info=DestroyQuantumInfo(quantum_info); \ + if (compress_pixels != (unsigned char *) NULL) \ + compress_pixels=(unsigned char *) RelinquishMagickMemory(compress_pixels); \ + ThrowReaderException((exception),(message)); \ +} +#define ZipMaxExtent(x) ((x)+(((x)+7) >> 3)+(((x)+63) >> 6)+11) + +#if defined(MAGICKCORE_BZLIB_DELEGATE) + bz_stream + bzip_info; +#endif + + char + id[MagickPathExtent], + keyword[MagickPathExtent], + *options; + + double + version; + + GeometryInfo + geometry_info; + + Image + *image; + + int + c; + + LinkedListInfo + *profiles; + +#if defined(MAGICKCORE_LZMA_DELEGATE) + lzma_stream + initialize_lzma = LZMA_STREAM_INIT, + lzma_info = LZMA_STREAM_INIT; + + lzma_allocator + allocator; +#endif + + MagickBooleanType + status; + + PixelInfo + pixel; + + MagickStatusType + flags; + + QuantumFormatType + quantum_format; + + QuantumInfo + *quantum_info; + + QuantumType + quantum_type; + + size_t + colors, + compress_extent, + extent, + length, + packet_size; + + ssize_t + count, + i, + y; + + unsigned char + *compress_pixels, + *pixels; + + +#if defined(MAGICKCORE_ZLIB_DELEGATE) + z_stream + zip_info; +#endif + + /* + Open image file. + */ + assert(image_info != (const ImageInfo *) NULL); + assert(image_info->signature == MagickCoreSignature); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + if (IsEventLogging() != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", + image_info->filename); + image=AcquireImage(image_info,exception); + status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); + if (status == MagickFalse) + { + image=DestroyImageList(image); + return((Image *) NULL); + } + /* + Decode image header; header terminates one character beyond a ':'. + */ + c=ReadBlobByte(image); + if (c == EOF) + ThrowReaderException(CorruptImageError,"ImproperImageHeader"); + *id='\0'; + compress_pixels=(unsigned char *) NULL; + quantum_info=(QuantumInfo *) NULL; + (void) memset(keyword,0,sizeof(keyword)); + version=0.0; + (void) version; + do + { + /* + Decode image header; header terminates one character beyond a ':'. + */ + SetGeometryInfo(&geometry_info); + length=MagickPathExtent; + options=AcquireString((char *) NULL); + quantum_format=UndefinedQuantumFormat; + profiles=(LinkedListInfo *) NULL; + colors=0; + image->depth=8UL; + image->compression=NoCompression; + while ((isgraph((int) ((unsigned char) c)) != 0) && (c != (int) ':')) + { + char + *p; + + if (c == (int) '{') + { + char + *comment; + + /* + Read comment-- any text between { }. + */ + length=MagickPathExtent; + comment=AcquireString((char *) NULL); + for (p=comment; comment != (char *) NULL; p++) + { + c=ReadBlobByte(image); + if (c == (int) '\\') + c=ReadBlobByte(image); + else + if ((c == EOF) || (c == (int) '}')) + break; + if ((size_t) (p-comment+1) >= length) + { + *p='\0'; + length<<=1; + comment=(char *) ResizeQuantumMemory(comment, + OverAllocateMemory(length+MagickPathExtent),sizeof(*comment)); + if (comment == (char *) NULL) + break; + p=comment+strlen(comment); + } + *p=(char) c; + } + if (comment == (char *) NULL) + { + options=DestroyString(options); + ThrowMIFFException(ResourceLimitError,"MemoryAllocationFailed"); + } + *p='\0'; + (void) SetImageProperty(image,"comment",comment,exception); + comment=DestroyString(comment); + c=ReadBlobByte(image); + } + else + if (isalnum((int) ((unsigned char) c)) != MagickFalse) + { + /* + Get the keyword. + */ + length=MagickPathExtent-1; + p=keyword; + do + { + if (c == (int) '=') + break; + if ((size_t) (p-keyword) < (MagickPathExtent-1)) + *p++=(char) c; + c=ReadBlobByte(image); + } while (c != EOF); + *p='\0'; + p=options; + while ((isspace((int) ((unsigned char) c)) != 0) && (c != EOF)) + c=ReadBlobByte(image); + if (c == (int) '=') + { + /* + Get the keyword value. + */ + c=ReadBlobByte(image); + while ((c != (int) '{') && (c != (int) '}') && (c != EOF)) + { + if ((size_t) (p-options+1) >= length) + { + *p='\0'; + length<<=1; + options=(char *) ResizeQuantumMemory(options,length+ + MagickPathExtent,sizeof(*options)); + if (options == (char *) NULL) + break; + p=options+strlen(options); + } + *p++=(char) c; + c=ReadBlobByte(image); + if (c == '\\') + { + c=ReadBlobByte(image); + if ((c == (int) '{') || (c == (int) '}')) + { + *p++=(char) c; + c=ReadBlobByte(image); + } + } + if (*options != '{') + if (isspace((int) ((unsigned char) c)) != 0) + break; + } + if (options == (char *) NULL) + ThrowMIFFException(ResourceLimitError, + "MemoryAllocationFailed"); + } + *p='\0'; + if (*options == '{') + (void) CopyMagickString(options,options+1,strlen(options)); + /* + Assign a value to the specified keyword. + */ + switch (*keyword) + { + case 'a': + case 'A': + { + if (LocaleCompare(keyword,"alpha-trait") == 0) + { + ssize_t + alpha_trait; + + alpha_trait=ParseCommandOption(MagickPixelTraitOptions, + MagickFalse,options); + if (alpha_trait < 0) + break; + image->alpha_trait=(PixelTrait) alpha_trait; + break; + } + (void) SetImageProperty(image,keyword,options,exception); + break; + } + case 'b': + case 'B': + { + if (LocaleCompare(keyword,"background-color") == 0) + { + (void) QueryColorCompliance(options,AllCompliance, + &image->background_color,exception); + break; + } + if (LocaleCompare(keyword,"blue-primary") == 0) + { + flags=ParseGeometry(options,&geometry_info); + image->chromaticity.blue_primary.x=geometry_info.rho; + image->chromaticity.blue_primary.y=geometry_info.sigma; + if ((flags & SigmaValue) == 0) + image->chromaticity.blue_primary.y= + image->chromaticity.blue_primary.x; + break; + } + if (LocaleCompare(keyword,"border-color") == 0) + { + + +// ... (65089 more chars) +``` diff --git a/tasks/csa159/pair_138746/task_prompt.md b/tasks/csa159/pair_138746/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..7e30068ca7ff34cde3f26253847b5b3a44103ca6 --- /dev/null +++ b/tasks/csa159/pair_138746/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 + +- The rollout failed only the process-quality check: repeated scan failures, parse errors, and a frontend exit 139 were eventually overcome, but the evidence did not show a clear targeted diagnosis-and-repair sequence rather than repeated scans and environmental recovery. +- Patch analysis mislabeled the defect as integer overflow and the fix as an API-signature change; the evidence instead shows a multispectral extent underestimation corrected by replacing a partial-channel accumulation with an authoritative total-channel assignment. +- The prior plan promised Image-base-sensitive propagation, but the described value lattice retained only Partial/Auth flags and definition sites, allowing facts derived from different Image objects to be conflated. +- The partial-term pattern remained broader than the exact invariant and could classify valid additive channel-size arithmetic unless the guard, reaching definition, matching Image base, and concrete sizing use are all established. + +### 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 an adequate CSA mechanism level and a semantic score at or above the configured threshold. +- Preserve anchor independence: detection must not depend on changed-line locations or patch hunk anchors. +- Preserve freedom from patch-local hardcoding. + +### Required semantic proof + +- Prove intraprocedurally that a size definition containing number_meta_channels(I) multiplied by depth(I) and converted to bytes by division by 8 or an equivalent shift is reachable under the nonzero-meta-channel branch for the same Image base I. +- Prove that the partial-channel value reaches a compressed-extent, allocation-size, blob-length, or multispectral sizing consumer, including forwarding through local variables and compound assignments. +- Treat the case as safe when the reaching value at the consumer has been replaced by GetImageChannels(I) multiplied by depth(I) and converted to bytes for the same Image base. +- Keep facts separated by Image base so a guard, partial term, depth access, or authoritative replacement involving one object cannot satisfy or suppress a finding involving another. +- Report only when the surviving definition-to-sink relation represents an underestimated multispectral per-pixel extent, not merely because partial-channel arithmetic and a sizing API occur somewhere in the same function. + +### Implementation constraints + +- Use an intraprocedural body callback such as check::ASTCodeBody with Clang CFG construction, statement mapping, dominance or equivalent branch-region reasoning, and a forward reaching-definition/value-kind dataflow; ProgramState path tracking and interprocedural propagation are unnecessary. +- Model each propagated extent fact with its classification, originating definition, and structurally comparable Image base identity; simple assignment must kill the previous reaching fact, while compound assignment must preserve contributing facts. +- Require CFG ordering and reachability from the candidate definition to the exact sink read, and establish that the matching number_meta_channels nonzero branch governs the definition rather than relying on lexical containment alone. +- Recognize structurally equivalent operand ordering and byte scaling while requiring number_meta_channels and depth, and any GetImageChannels replacement, to refer to the same Image expression. +- Limit sinks to evidence-supported allocation or resize sizes, blob length arguments, compressed-extent values forwarded to allocation, and multispectral sizing uses; do not infer relevance from an arbitrary pixel API elsewhere in the function. +- Anchor each diagnostic at the faulty partial-channel extent definition and emit at most one report per qualifying definition. +- Keep project-general scope through stable Image fields and sizing APIs; do not name coders/miff.c, ReadMIFFImage, WriteMIFFImage, packet_size, source lines, or patch text. + +### Validation checklist + +- Build the checker shared object successfully against the configured Clang Static Analyzer API and verify checker registration and loading without frontend crashes. +- Run deterministic scans of both revisions with identical valid compile flags, retaining stderr evidence that both coders/miff.c inputs parsed and were analyzed rather than interpreting compile failures as zero findings. +- Confirm exactly two relevant diagnostics in the vulnerable revision and zero in the patched revision. +- Confirm the vulnerable diagnostics are located at the two partial-channel definitions in ReadMIFFImage and WriteMIFFImage, with zero-line median distance from the changed statements and no findings in non-patched functions. +- Verify both diagnostics disappear because the authoritative GetImageChannels-based assignment becomes the reaching definition, not because analysis skipped a file, callback, CFG, or sink. +- Add focused refinements for temporary forwarding, compound assignment, authoritative reassignment killing a partial fact, mismatched Image bases, absent/non-dominating guards, and partial arithmetic that never reaches a sizing sink. +- Record each failed validation command, root cause, targeted correction, and successful rerun so recovery demonstrates progress instead of repeated environmental retries. +- Re-run code verification, differential validation, objective gate G6, hardcoding and anchor checks, and refinement acceptance. + +### Avoid and forbidden regressions + +- Do not use syntax-only occurrence matching or function-wide co-occurrence of number_meta_channels arithmetic, GetImageChannels, and a pixel-buffer API. +- Do not use check::PostStmt alone or check::PreCall alone, because neither independently proves the guarded reaching-definition relation. +- Do not escalate to ProgramState-based path-sensitive tracking or interprocedural dataflow when CFG-local reaching definitions and dominance establish the contract. +- Do not collapse Partial/Auth facts across distinct Image bases or allow an authoritative expression for one object to suppress a partial extent for another. +- Do not classify the issue as integer overflow or describe the patch as an API-signature change. +- Do not count zero-warning scans as valid when parsing, include resolution, checker loading, timeout, or frontend stability failed. +- Do not encode file names, function names, packet_size, line numbers, diff literals, or changed-statement anchors as detection predicates. diff --git a/tasks/csa159/pair_138756/checker_template.cpp b/tasks/csa159/pair_138756/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138756/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_138756/config.json b/tasks/csa159/pair_138756/config.json new file mode 100644 index 0000000000000000000000000000000000000000..6819538e0ca090e9cc9fbb6b3e308b13ed47d577 --- /dev/null +++ b/tasks/csa159/pair_138756/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "ImageMagick_ImageMagick", + "before_commit": "ccdc01180276aa2cb3d4a32a611aa4f417061cd8", + "after_commit": "cca607366fb38c2dde019a9088b8415ffba3a835", + "repo_path": "/workspace/repo/ImageMagick/ImageMagick", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ImageMagick_ImageMagick/03d19de047d7ce79e1f617562c43184ba54fa06e/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/ImageMagick_ImageMagick/03d19de047d7ce79e1f617562c43184ba54fa06e/compile_commands.json", + "changed_files": [ + "MagickCore/resize.c" + ], + "commit_message": "https://github.com/ImageMagick/ImageMagick/security/advisories/GHSA-pcvx-ph33-r5vv", + "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_138756/patch.diff b/tasks/csa159/pair_138756/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ee168cef76a2f8c981e4e8d2f153f6ecc5120367 --- /dev/null +++ b/tasks/csa159/pair_138756/patch.diff @@ -0,0 +1,110 @@ +diff --git a/MagickCore/resize.c b/MagickCore/resize.c +index ddb6a16cf..29a66c636 100644 +--- a/MagickCore/resize.c ++++ b/MagickCore/resize.c +@@ -3929,8 +3929,6 @@ MagickExport Image *SampleImage(const Image *image,const size_t columns, + sample_offset; + + ssize_t +- j, +- *x_offset, + y; + + /* +@@ -3974,19 +3972,6 @@ MagickExport Image *SampleImage(const Image *image,const size_t columns, + sample_offset.y=geometry_info.sigma/100.0-MagickEpsilon; + } + } +- /* +- Allocate scan line buffer and column offset buffers. +- */ +- x_offset=(ssize_t *) AcquireQuantumMemory((size_t) sample_image->columns, +- sizeof(*x_offset)); +- if (x_offset == (ssize_t *) NULL) +- { +- sample_image=DestroyImage(sample_image); +- ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); +- } +- for (j=0; j < (ssize_t) sample_image->columns; j++) +- x_offset[j]=(ssize_t) ((((double) j+sample_offset.x)*image->columns)/ +- sample_image->columns); + /* + Sample each row. + */ +@@ -4000,25 +3985,17 @@ MagickExport Image *SampleImage(const Image *image,const size_t columns, + #endif + for (y=0; y < (ssize_t) sample_image->rows; y++) + { +- const Quantum +- *magick_restrict p; +- + Quantum + *magick_restrict q; + + ssize_t +- x, +- y_offset; ++ x; + + if (status == MagickFalse) + continue; +- y_offset=(ssize_t) ((((double) y+sample_offset.y)*image->rows)/ +- sample_image->rows); +- p=GetCacheViewVirtualPixels(image_view,0,y_offset,image->columns,1, +- exception); + q=QueueCacheViewAuthenticPixels(sample_view,0,y,sample_image->columns,1, + exception); +- if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) ++ if (q == (Quantum *) NULL) + { + status=MagickFalse; + continue; +@@ -4028,14 +4005,29 @@ MagickExport Image *SampleImage(const Image *image,const size_t columns, + */ + for (x=0; x < (ssize_t) sample_image->columns; x++) + { ++ const Quantum ++ *magick_restrict p; ++ + ssize_t +- i; ++ i, ++ x_offset, ++ y_offset; + + if (GetPixelWriteMask(sample_image,q) <= (QuantumRange/2)) + { + q+=(ptrdiff_t) GetPixelChannels(sample_image); + continue; + } ++ x_offset=(ssize_t) ((((double) x+sample_offset.x)*image->columns)/ ++ sample_image->columns); ++ y_offset=(ssize_t) ((((double) y+sample_offset.y)*image->rows)/ ++ sample_image->rows); ++ p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,1,1,exception); ++ if (p == (const Quantum *) NULL) ++ { ++ status=MagickFalse; ++ break; ++ } + for (i=0; i < (ssize_t) GetPixelChannels(sample_image); i++) + { + PixelChannel +@@ -4051,8 +4043,7 @@ MagickExport Image *SampleImage(const Image *image,const size_t columns, + if ((traits == UndefinedPixelTrait) || + (image_traits == UndefinedPixelTrait)) + continue; +- SetPixelChannel(sample_image,channel,p[x_offset[x]*(ssize_t) +- GetPixelChannels(image)+i],q); ++ SetPixelChannel(sample_image,channel,p[i],q); + } + q+=(ptrdiff_t) GetPixelChannels(sample_image); + } +@@ -4070,7 +4061,6 @@ MagickExport Image *SampleImage(const Image *image,const size_t columns, + } + image_view=DestroyCacheView(image_view); + sample_view=DestroyCacheView(sample_view); +- x_offset=(ssize_t *) RelinquishMagickMemory(x_offset); + sample_image->type=image->type; + if (status == MagickFalse) + sample_image=DestroyImage(sample_image); \ No newline at end of file diff --git a/tasks/csa159/pair_138756/post_functions.txt b/tasks/csa159/pair_138756/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2fc3652bf04c322596199641782c21f5f7ad2daa --- /dev/null +++ b/tasks/csa159/pair_138756/post_functions.txt @@ -0,0 +1,162 @@ +### File: MagickCore/resize.c +```c +MagickExport Image *SampleImage(const Image *image,const size_t columns, + const size_t rows,ExceptionInfo *exception) +{ +#define SampleImageTag "Sample/Image" + + CacheView + *image_view, + *sample_view; + + Image + *sample_image; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + PointInfo + sample_offset; + + ssize_t + y; + + /* + Initialize sampled image attributes. + */ + assert(image != (const Image *) NULL); + assert(image->signature == MagickCoreSignature); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + if (IsEventLogging() != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); + if ((columns == 0) || (rows == 0)) + ThrowImageException(ImageError,"NegativeOrZeroImageSize"); + if ((columns == image->columns) && (rows == image->rows)) + return(CloneImage(image,0,0,MagickTrue,exception)); + sample_image=CloneImage(image,columns,rows,MagickTrue,exception); + if (sample_image == (Image *) NULL) + return((Image *) NULL); + /* + Set the sampling offset, default is in the mid-point of sample regions. + */ + sample_offset.x=0.5-MagickEpsilon; + sample_offset.y=sample_offset.x; + { + const char + *value; + + value=GetImageArtifact(image,"sample:offset"); + if (value != (char *) NULL) + { + GeometryInfo + geometry_info; + + MagickStatusType + flags; + + (void) ParseGeometry(value,&geometry_info); + flags=ParseGeometry(value,&geometry_info); + sample_offset.x=sample_offset.y=geometry_info.rho/100.0-MagickEpsilon; + if ((flags & SigmaValue) != 0) + sample_offset.y=geometry_info.sigma/100.0-MagickEpsilon; + } + } + /* + Sample each row. + */ + status=MagickTrue; + progress=0; + image_view=AcquireVirtualCacheView(image,exception); + sample_view=AcquireAuthenticCacheView(sample_image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp parallel for schedule(static) shared(status) \ + magick_number_threads(image,sample_image,sample_image->rows,2) +#endif + for (y=0; y < (ssize_t) sample_image->rows; y++) + { + Quantum + *magick_restrict q; + + ssize_t + x; + + if (status == MagickFalse) + continue; + q=QueueCacheViewAuthenticPixels(sample_view,0,y,sample_image->columns,1, + exception); + if (q == (Quantum *) NULL) + { + status=MagickFalse; + continue; + } + /* + Sample each column. + */ + for (x=0; x < (ssize_t) sample_image->columns; x++) + { + const Quantum + *magick_restrict p; + + ssize_t + i, + x_offset, + y_offset; + + if (GetPixelWriteMask(sample_image,q) <= (QuantumRange/2)) + { + q+=(ptrdiff_t) GetPixelChannels(sample_image); + continue; + } + x_offset=(ssize_t) ((((double) x+sample_offset.x)*image->columns)/ + sample_image->columns); + y_offset=(ssize_t) ((((double) y+sample_offset.y)*image->rows)/ + sample_image->rows); + p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,1,1,exception); + if (p == (const Quantum *) NULL) + { + status=MagickFalse; + break; + } + for (i=0; i < (ssize_t) GetPixelChannels(sample_image); i++) + { + PixelChannel + channel; + + PixelTrait + image_traits, + traits; + + channel=GetPixelChannelChannel(sample_image,i); + traits=GetPixelChannelTraits(sample_image,channel); + image_traits=GetPixelChannelTraits(image,channel); + if ((traits == UndefinedPixelTrait) || + (image_traits == UndefinedPixelTrait)) + continue; + SetPixelChannel(sample_image,channel,p[i],q); + } + q+=(ptrdiff_t) GetPixelChannels(sample_image); + } + if (SyncCacheViewAuthenticPixels(sample_view,exception) == MagickFalse) + status=MagickFalse; + if (image->progress_monitor != (MagickProgressMonitor) NULL) + { + MagickBooleanType + proceed; + + proceed=SetImageProgress(image,SampleImageTag,progress++,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + image_view=DestroyCacheView(image_view); + sample_view=DestroyCacheView(sample_view); + sample_image->type=image->type; + if (status == MagickFalse) + sample_image=DestroyImage(sample_image); + return(sample_image); +} +``` diff --git a/tasks/csa159/pair_138756/pre_functions.txt b/tasks/csa159/pair_138756/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..0dd2dad113401584c30d9b546be3af832c0a457a --- /dev/null +++ b/tasks/csa159/pair_138756/pre_functions.txt @@ -0,0 +1,172 @@ +### File: MagickCore/resize.c +```c +MagickExport Image *SampleImage(const Image *image,const size_t columns, + const size_t rows,ExceptionInfo *exception) +{ +#define SampleImageTag "Sample/Image" + + CacheView + *image_view, + *sample_view; + + Image + *sample_image; + + MagickBooleanType + status; + + MagickOffsetType + progress; + + PointInfo + sample_offset; + + ssize_t + j, + *x_offset, + y; + + /* + Initialize sampled image attributes. + */ + assert(image != (const Image *) NULL); + assert(image->signature == MagickCoreSignature); + assert(exception != (ExceptionInfo *) NULL); + assert(exception->signature == MagickCoreSignature); + if (IsEventLogging() != MagickFalse) + (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); + if ((columns == 0) || (rows == 0)) + ThrowImageException(ImageError,"NegativeOrZeroImageSize"); + if ((columns == image->columns) && (rows == image->rows)) + return(CloneImage(image,0,0,MagickTrue,exception)); + sample_image=CloneImage(image,columns,rows,MagickTrue,exception); + if (sample_image == (Image *) NULL) + return((Image *) NULL); + /* + Set the sampling offset, default is in the mid-point of sample regions. + */ + sample_offset.x=0.5-MagickEpsilon; + sample_offset.y=sample_offset.x; + { + const char + *value; + + value=GetImageArtifact(image,"sample:offset"); + if (value != (char *) NULL) + { + GeometryInfo + geometry_info; + + MagickStatusType + flags; + + (void) ParseGeometry(value,&geometry_info); + flags=ParseGeometry(value,&geometry_info); + sample_offset.x=sample_offset.y=geometry_info.rho/100.0-MagickEpsilon; + if ((flags & SigmaValue) != 0) + sample_offset.y=geometry_info.sigma/100.0-MagickEpsilon; + } + } + /* + Allocate scan line buffer and column offset buffers. + */ + x_offset=(ssize_t *) AcquireQuantumMemory((size_t) sample_image->columns, + sizeof(*x_offset)); + if (x_offset == (ssize_t *) NULL) + { + sample_image=DestroyImage(sample_image); + ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); + } + for (j=0; j < (ssize_t) sample_image->columns; j++) + x_offset[j]=(ssize_t) ((((double) j+sample_offset.x)*image->columns)/ + sample_image->columns); + /* + Sample each row. + */ + status=MagickTrue; + progress=0; + image_view=AcquireVirtualCacheView(image,exception); + sample_view=AcquireAuthenticCacheView(sample_image,exception); +#if defined(MAGICKCORE_OPENMP_SUPPORT) + #pragma omp parallel for schedule(static) shared(status) \ + magick_number_threads(image,sample_image,sample_image->rows,2) +#endif + for (y=0; y < (ssize_t) sample_image->rows; y++) + { + const Quantum + *magick_restrict p; + + Quantum + *magick_restrict q; + + ssize_t + x, + y_offset; + + if (status == MagickFalse) + continue; + y_offset=(ssize_t) ((((double) y+sample_offset.y)*image->rows)/ + sample_image->rows); + p=GetCacheViewVirtualPixels(image_view,0,y_offset,image->columns,1, + exception); + q=QueueCacheViewAuthenticPixels(sample_view,0,y,sample_image->columns,1, + exception); + if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) + { + status=MagickFalse; + continue; + } + /* + Sample each column. + */ + for (x=0; x < (ssize_t) sample_image->columns; x++) + { + ssize_t + i; + + if (GetPixelWriteMask(sample_image,q) <= (QuantumRange/2)) + { + q+=(ptrdiff_t) GetPixelChannels(sample_image); + continue; + } + for (i=0; i < (ssize_t) GetPixelChannels(sample_image); i++) + { + PixelChannel + channel; + + PixelTrait + image_traits, + traits; + + channel=GetPixelChannelChannel(sample_image,i); + traits=GetPixelChannelTraits(sample_image,channel); + image_traits=GetPixelChannelTraits(image,channel); + if ((traits == UndefinedPixelTrait) || + (image_traits == UndefinedPixelTrait)) + continue; + SetPixelChannel(sample_image,channel,p[x_offset[x]*(ssize_t) + GetPixelChannels(image)+i],q); + } + q+=(ptrdiff_t) GetPixelChannels(sample_image); + } + if (SyncCacheViewAuthenticPixels(sample_view,exception) == MagickFalse) + status=MagickFalse; + if (image->progress_monitor != (MagickProgressMonitor) NULL) + { + MagickBooleanType + proceed; + + proceed=SetImageProgress(image,SampleImageTag,progress++,image->rows); + if (proceed == MagickFalse) + status=MagickFalse; + } + } + image_view=DestroyCacheView(image_view); + sample_view=DestroyCacheView(sample_view); + x_offset=(ssize_t *) RelinquishMagickMemory(x_offset); + sample_image->type=image->type; + if (status == MagickFalse) + sample_image=DestroyImage(sample_image); + return(sample_image); +} +``` diff --git a/tasks/csa159/pair_138756/task_prompt.md b/tasks/csa159/pair_138756/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..5c632e5c9d480c1b48f3a9beab12136210fde84c --- /dev/null +++ b/tasks/csa159/pair_138756/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: `path_sensitive` + +### Current failure diagnosis + +- The failed rollout used syntactic_ast PreStmt origin sets (pixel-buffer var from GetCacheViewVirtualPixels plus a nested heap-array subscript) and never proved the access was out of bounds. +- It did not track sampling-offset values, sample:offset taint, or the requested pixel-cache region width, so it could not compare the subscript index against the buffer extent. +- The predicate is a superset proxy (row buffer indexed by an AcquireQuantumMemory offset array) that would also match safe clamped uses of the same shape; semantic_mechanism and semantic_score therefore stayed inadequate. + +### 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 process quality at or above the configured threshold. +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- A buffer returned by GetCacheViewVirtualPixels or GetVirtualPixels has a finite extent equal to the requested columns (packed by channel count), not an unbounded array. +- The sink index is derived from a sampling offset fed by the sample:offset artifact/ParseGeometry and is not constrained to [0, requested_columns). +- That unconstrained index used on the full-row cache buffer makes p[offset*GetPixelChannels(image)+channel] an out-of-bounds read. +- Safe if the computed coordinates are passed as the fetch origin of a 1x1 GetCacheViewVirtualPixels call (API validates) and the returned buffer is indexed only by a channel, or if a bound/clamp proves the index is inside the tracked extent. + +### Implementation constraints + +- Use path-sensitive callbacks: check::PostCall (or Bind) to associate pixel-cache returns with the columns/rows arguments, and check::Location or PreStmt on the load/subscript as the sink; ProgramState must carry buffer extent and offset taint/unboundedness. +- At the sink, query constraints/regions to test whether offset*channels+channel can leave the tracked extent; missing clamp is evidence of feasibility, not a substitute for recording the bound. +- Report on the pixel-buffer subscript that feeds SetPixelChannel (the buggy p[x_offset[x]*GetPixelChannels(image)+i] expression), not on allocators or artifact parsing. +- Identify ImageMagick pixel-cache accessors by callee semantics; do not key on SampleImage, x_offset, MagickCore/resize.c paths, or patch line numbers. +- Model GetCacheViewVirtualPixels by its region-to-extent contract; do not analyze its body or require interprocedural inlining. + +### Validation checklist + +- Plugin/checker shared object compiles cleanly under the existing CSA build path. +- Pre-patch MagickCore/resize.c SampleImage yields a warning on the full-row buffer subscript that inlines the unvalidated sampling offset. +- Post-patch SampleImage stays clean: GetCacheViewVirtualPixels(image_view,x_offset,y_offset,1,1) plus p[i] must not report. +- The diagnostic stays inside MagickCore/resize.c::SampleImage on the vulnerable index expression (prior median distance was 0). +- Differential remains n_buggy>=1, n_patched=0, with no warnings disappearing from non-patched functions. +- Re-run refinement and keep an accepted or clean outcome while G6 and process score stay at or above the prior passing thresholds. + +### Avoid and forbidden regressions + +- Do not rebuild FunctionFacts/collectFacts syntactic origin matching of GetCacheViewVirtualPixels plus nested AcquireQuantumMemory subscripts as a stand-in for OOB. +- Do not treat 'pixel buffer indexed by a heap offset array' as the vulnerability condition; require unclamped index versus requested cache width. +- Do not omit the GetCacheViewVirtualPixels columns/rows arguments as the buffer bound. +- Do not flag channel-only indexing of a validated 1x1 fetch, or other uses that pass the computed offset as cache coordinates rather than as a raw row index. +- Do not detect via the removed x_offset heap array or other patch-deleted locals as if their presence were the bug. +- Do not copy, repair, resume, or reconstruct the prior PixelCacheOOBReadChecker. diff --git a/tasks/csa159/pair_138800/checker_template.cpp b/tasks/csa159/pair_138800/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_138800/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_138800/config.json b/tasks/csa159/pair_138800/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b6ea076cc3b9b75be5c86490a42126b881e117a9 --- /dev/null +++ b/tasks/csa159/pair_138800/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "FFmpeg_FFmpeg", + "before_commit": "1dac4d554734b16757b36a0adc71642c5ef2c4e6", + "after_commit": "8312e3fc9041027a33c8bc667bb99740fdf41dd5", + "repo_path": "/workspace/repo/FFmpeg/FFmpeg", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FFmpeg_FFmpeg/bfaefd87dc5c46a4d422cebcff7a9a6dbaad046f/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/FFmpeg_FFmpeg/bfaefd87dc5c46a4d422cebcff7a9a6dbaad046f/compile_commands.json", + "changed_files": [ + "libavformat/ape.c" + ], + "commit_message": "Do not attempt to decode APE file with no frames\n\nThis fixes invalid reads/writes with this sample:\nhttp://packetstorm.linuxsecurity.com/1103-exploits/vlc105-dos.txt", + "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_138800/patch.diff b/tasks/csa159/pair_138800/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..194d05dee9f48c468b6abd440383a0ebabe31711 --- /dev/null +++ b/tasks/csa159/pair_138800/patch.diff @@ -0,0 +1,15 @@ +diff --git a/libavformat/ape.c b/libavformat/ape.c +index 6c269849fd..dd2aeb9ff3 100644 +--- a/libavformat/ape.c ++++ b/libavformat/ape.c +@@ -242,6 +242,10 @@ static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap) + avio_seek(pb, ape->wavheaderlength, SEEK_CUR); + } + ++ if(!ape->totalframes){ ++ av_log(s, AV_LOG_ERROR, "No frames in the file!\n"); ++ return AVERROR(EINVAL); ++ } + if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){ + av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes); + return -1; \ No newline at end of file diff --git a/tasks/csa159/pair_138800/post_functions.txt b/tasks/csa159/pair_138800/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..0dd69998a6d8e3e67e5ec8b1aa71b6b11daa3678 --- /dev/null +++ b/tasks/csa159/pair_138800/post_functions.txt @@ -0,0 +1,187 @@ +### File: libavformat/ape.c +```c +static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap) +{ + AVIOContext *pb = s->pb; + APEContext *ape = s->priv_data; + AVStream *st; + uint32_t tag; + int i; + int total_blocks; + int64_t pts; + + /* TODO: Skip any leading junk such as id3v2 tags */ + ape->junklength = 0; + + tag = avio_rl32(pb); + if (tag != MKTAG('M', 'A', 'C', ' ')) + return -1; + + ape->fileversion = avio_rl16(pb); + + if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) { + av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10); + return -1; + } + + if (ape->fileversion >= 3980) { + ape->padding1 = avio_rl16(pb); + ape->descriptorlength = avio_rl32(pb); + ape->headerlength = avio_rl32(pb); + ape->seektablelength = avio_rl32(pb); + ape->wavheaderlength = avio_rl32(pb); + ape->audiodatalength = avio_rl32(pb); + ape->audiodatalength_high = avio_rl32(pb); + ape->wavtaillength = avio_rl32(pb); + avio_read(pb, ape->md5, 16); + + /* Skip any unknown bytes at the end of the descriptor. + This is for future compatibility */ + if (ape->descriptorlength > 52) + avio_seek(pb, ape->descriptorlength - 52, SEEK_CUR); + + /* Read header data */ + ape->compressiontype = avio_rl16(pb); + ape->formatflags = avio_rl16(pb); + ape->blocksperframe = avio_rl32(pb); + ape->finalframeblocks = avio_rl32(pb); + ape->totalframes = avio_rl32(pb); + ape->bps = avio_rl16(pb); + ape->channels = avio_rl16(pb); + ape->samplerate = avio_rl32(pb); + } else { + ape->descriptorlength = 0; + ape->headerlength = 32; + + ape->compressiontype = avio_rl16(pb); + ape->formatflags = avio_rl16(pb); + ape->channels = avio_rl16(pb); + ape->samplerate = avio_rl32(pb); + ape->wavheaderlength = avio_rl32(pb); + ape->wavtaillength = avio_rl32(pb); + ape->totalframes = avio_rl32(pb); + ape->finalframeblocks = avio_rl32(pb); + + if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) { + avio_seek(pb, 4, SEEK_CUR); /* Skip the peak level */ + ape->headerlength += 4; + } + + if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) { + ape->seektablelength = avio_rl32(pb); + ape->headerlength += 4; + ape->seektablelength *= sizeof(int32_t); + } else + ape->seektablelength = ape->totalframes * sizeof(int32_t); + + if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT) + ape->bps = 8; + else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT) + ape->bps = 24; + else + ape->bps = 16; + + if (ape->fileversion >= 3950) + ape->blocksperframe = 73728 * 4; + else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000)) + ape->blocksperframe = 73728; + else + ape->blocksperframe = 9216; + + /* Skip any stored wav header */ + if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER)) + avio_seek(pb, ape->wavheaderlength, SEEK_CUR); + } + + if(!ape->totalframes){ + av_log(s, AV_LOG_ERROR, "No frames in the file!\n"); + return AVERROR(EINVAL); + } + if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){ + av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes); + return -1; + } + ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame)); + if(!ape->frames) + return AVERROR(ENOMEM); + ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength; + ape->currentframe = 0; + + + ape->totalsamples = ape->finalframeblocks; + if (ape->totalframes > 1) + ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1); + + if (ape->seektablelength > 0) { + ape->seektable = av_malloc(ape->seektablelength); + for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++) + ape->seektable[i] = avio_rl32(pb); + } + + ape->frames[0].pos = ape->firstframe; + ape->frames[0].nblocks = ape->blocksperframe; + ape->frames[0].skip = 0; + for (i = 1; i < ape->totalframes; i++) { + ape->frames[i].pos = ape->seektable[i]; //ape->frames[i-1].pos + ape->blocksperframe; + ape->frames[i].nblocks = ape->blocksperframe; + ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos; + ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3; + } + ape->frames[ape->totalframes - 1].size = ape->finalframeblocks * 4; + ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks; + + for (i = 0; i < ape->totalframes; i++) { + if(ape->frames[i].skip){ + ape->frames[i].pos -= ape->frames[i].skip; + ape->frames[i].size += ape->frames[i].skip; + } + ape->frames[i].size = (ape->frames[i].size + 3) & ~3; + } + + + ape_dumpinfo(s, ape); + + /* try to read APE tags */ + if (!url_is_streamed(pb)) { + ff_ape_parse_tag(s); + avio_seek(pb, 0, SEEK_SET); + } + + av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype); + + /* now we are ready: build format streams */ + st = av_new_stream(s, 0); + if (!st) + return -1; + + total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks; + + st->codec->codec_type = AVMEDIA_TYPE_AUDIO; + st->codec->codec_id = CODEC_ID_APE; + st->codec->codec_tag = MKTAG('A', 'P', 'E', ' '); + st->codec->channels = ape->channels; + st->codec->sample_rate = ape->samplerate; + st->codec->bits_per_coded_sample = ape->bps; + st->codec->frame_size = MAC_SUBFRAME_SIZE; + + st->nb_frames = ape->totalframes; + st->start_time = 0; + st->duration = total_blocks / MAC_SUBFRAME_SIZE; + av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate); + + st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE); + st->codec->extradata_size = APE_EXTRADATA_SIZE; + AV_WL16(st->codec->extradata + 0, ape->fileversion); + AV_WL16(st->codec->extradata + 2, ape->compressiontype); + AV_WL16(st->codec->extradata + 4, ape->formatflags); + + pts = 0; + for (i = 0; i < ape->totalframes; i++) { + ape->frames[i].pts = pts; + av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME); + pts += ape->blocksperframe / MAC_SUBFRAME_SIZE; + } + + return 0; +} +``` diff --git a/tasks/csa159/pair_138800/pre_functions.txt b/tasks/csa159/pair_138800/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..e1b7030dc3bcf5056fa5752b6a3bf51bcf39e53e --- /dev/null +++ b/tasks/csa159/pair_138800/pre_functions.txt @@ -0,0 +1,183 @@ +### File: libavformat/ape.c +```c +static int ape_read_header(AVFormatContext * s, AVFormatParameters * ap) +{ + AVIOContext *pb = s->pb; + APEContext *ape = s->priv_data; + AVStream *st; + uint32_t tag; + int i; + int total_blocks; + int64_t pts; + + /* TODO: Skip any leading junk such as id3v2 tags */ + ape->junklength = 0; + + tag = avio_rl32(pb); + if (tag != MKTAG('M', 'A', 'C', ' ')) + return -1; + + ape->fileversion = avio_rl16(pb); + + if (ape->fileversion < APE_MIN_VERSION || ape->fileversion > APE_MAX_VERSION) { + av_log(s, AV_LOG_ERROR, "Unsupported file version - %d.%02d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10); + return -1; + } + + if (ape->fileversion >= 3980) { + ape->padding1 = avio_rl16(pb); + ape->descriptorlength = avio_rl32(pb); + ape->headerlength = avio_rl32(pb); + ape->seektablelength = avio_rl32(pb); + ape->wavheaderlength = avio_rl32(pb); + ape->audiodatalength = avio_rl32(pb); + ape->audiodatalength_high = avio_rl32(pb); + ape->wavtaillength = avio_rl32(pb); + avio_read(pb, ape->md5, 16); + + /* Skip any unknown bytes at the end of the descriptor. + This is for future compatibility */ + if (ape->descriptorlength > 52) + avio_seek(pb, ape->descriptorlength - 52, SEEK_CUR); + + /* Read header data */ + ape->compressiontype = avio_rl16(pb); + ape->formatflags = avio_rl16(pb); + ape->blocksperframe = avio_rl32(pb); + ape->finalframeblocks = avio_rl32(pb); + ape->totalframes = avio_rl32(pb); + ape->bps = avio_rl16(pb); + ape->channels = avio_rl16(pb); + ape->samplerate = avio_rl32(pb); + } else { + ape->descriptorlength = 0; + ape->headerlength = 32; + + ape->compressiontype = avio_rl16(pb); + ape->formatflags = avio_rl16(pb); + ape->channels = avio_rl16(pb); + ape->samplerate = avio_rl32(pb); + ape->wavheaderlength = avio_rl32(pb); + ape->wavtaillength = avio_rl32(pb); + ape->totalframes = avio_rl32(pb); + ape->finalframeblocks = avio_rl32(pb); + + if (ape->formatflags & MAC_FORMAT_FLAG_HAS_PEAK_LEVEL) { + avio_seek(pb, 4, SEEK_CUR); /* Skip the peak level */ + ape->headerlength += 4; + } + + if (ape->formatflags & MAC_FORMAT_FLAG_HAS_SEEK_ELEMENTS) { + ape->seektablelength = avio_rl32(pb); + ape->headerlength += 4; + ape->seektablelength *= sizeof(int32_t); + } else + ape->seektablelength = ape->totalframes * sizeof(int32_t); + + if (ape->formatflags & MAC_FORMAT_FLAG_8_BIT) + ape->bps = 8; + else if (ape->formatflags & MAC_FORMAT_FLAG_24_BIT) + ape->bps = 24; + else + ape->bps = 16; + + if (ape->fileversion >= 3950) + ape->blocksperframe = 73728 * 4; + else if (ape->fileversion >= 3900 || (ape->fileversion >= 3800 && ape->compressiontype >= 4000)) + ape->blocksperframe = 73728; + else + ape->blocksperframe = 9216; + + /* Skip any stored wav header */ + if (!(ape->formatflags & MAC_FORMAT_FLAG_CREATE_WAV_HEADER)) + avio_seek(pb, ape->wavheaderlength, SEEK_CUR); + } + + if(ape->totalframes > UINT_MAX / sizeof(APEFrame)){ + av_log(s, AV_LOG_ERROR, "Too many frames: %d\n", ape->totalframes); + return -1; + } + ape->frames = av_malloc(ape->totalframes * sizeof(APEFrame)); + if(!ape->frames) + return AVERROR(ENOMEM); + ape->firstframe = ape->junklength + ape->descriptorlength + ape->headerlength + ape->seektablelength + ape->wavheaderlength; + ape->currentframe = 0; + + + ape->totalsamples = ape->finalframeblocks; + if (ape->totalframes > 1) + ape->totalsamples += ape->blocksperframe * (ape->totalframes - 1); + + if (ape->seektablelength > 0) { + ape->seektable = av_malloc(ape->seektablelength); + for (i = 0; i < ape->seektablelength / sizeof(uint32_t); i++) + ape->seektable[i] = avio_rl32(pb); + } + + ape->frames[0].pos = ape->firstframe; + ape->frames[0].nblocks = ape->blocksperframe; + ape->frames[0].skip = 0; + for (i = 1; i < ape->totalframes; i++) { + ape->frames[i].pos = ape->seektable[i]; //ape->frames[i-1].pos + ape->blocksperframe; + ape->frames[i].nblocks = ape->blocksperframe; + ape->frames[i - 1].size = ape->frames[i].pos - ape->frames[i - 1].pos; + ape->frames[i].skip = (ape->frames[i].pos - ape->frames[0].pos) & 3; + } + ape->frames[ape->totalframes - 1].size = ape->finalframeblocks * 4; + ape->frames[ape->totalframes - 1].nblocks = ape->finalframeblocks; + + for (i = 0; i < ape->totalframes; i++) { + if(ape->frames[i].skip){ + ape->frames[i].pos -= ape->frames[i].skip; + ape->frames[i].size += ape->frames[i].skip; + } + ape->frames[i].size = (ape->frames[i].size + 3) & ~3; + } + + + ape_dumpinfo(s, ape); + + /* try to read APE tags */ + if (!url_is_streamed(pb)) { + ff_ape_parse_tag(s); + avio_seek(pb, 0, SEEK_SET); + } + + av_log(s, AV_LOG_DEBUG, "Decoding file - v%d.%02d, compression level %d\n", ape->fileversion / 1000, (ape->fileversion % 1000) / 10, ape->compressiontype); + + /* now we are ready: build format streams */ + st = av_new_stream(s, 0); + if (!st) + return -1; + + total_blocks = (ape->totalframes == 0) ? 0 : ((ape->totalframes - 1) * ape->blocksperframe) + ape->finalframeblocks; + + st->codec->codec_type = AVMEDIA_TYPE_AUDIO; + st->codec->codec_id = CODEC_ID_APE; + st->codec->codec_tag = MKTAG('A', 'P', 'E', ' '); + st->codec->channels = ape->channels; + st->codec->sample_rate = ape->samplerate; + st->codec->bits_per_coded_sample = ape->bps; + st->codec->frame_size = MAC_SUBFRAME_SIZE; + + st->nb_frames = ape->totalframes; + st->start_time = 0; + st->duration = total_blocks / MAC_SUBFRAME_SIZE; + av_set_pts_info(st, 64, MAC_SUBFRAME_SIZE, ape->samplerate); + + st->codec->extradata = av_malloc(APE_EXTRADATA_SIZE); + st->codec->extradata_size = APE_EXTRADATA_SIZE; + AV_WL16(st->codec->extradata + 0, ape->fileversion); + AV_WL16(st->codec->extradata + 2, ape->compressiontype); + AV_WL16(st->codec->extradata + 4, ape->formatflags); + + pts = 0; + for (i = 0; i < ape->totalframes; i++) { + ape->frames[i].pts = pts; + av_add_index_entry(st, ape->frames[i].pos, ape->frames[i].pts, 0, 0, AVINDEX_KEYFRAME); + pts += ape->blocksperframe / MAC_SUBFRAME_SIZE; + } + + return 0; +} +``` diff --git a/tasks/csa159/pair_138800/task_prompt.md b/tasks/csa159/pair_138800/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..40a8a7a8a020b523084cab8189ca67d5d70ab630 --- /dev/null +++ b/tasks/csa159/pair_138800/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: `path_sensitive` + +### Current failure diagnosis + +- The rollout passed compilation, differential validation, code verification, objective eligibility, and score thresholds, but refinement remained unaccepted. +- Allocation capture was semantically too broad: a fresh-looking symbolic pointer return plus a count-times-constant argument did not prove that the call allocated fresh heap storage with that capacity. +- Because non-allocation pointer-returning APIs could satisfy that heuristic, the report condition was a superset of the vulnerability and remained exposed to false positives. + +### 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 the 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 + +- Establish that the tracked pointer is the result of a genuine heap-allocation operation whose fresh storage capacity is determined by N multiplied by a positive element size E; call shape alone is insufficient. +- Establish that the ArraySubscriptExpr base resolves to the same tracked allocation region and that E equals the size of the indexed pointee type, so the allocation has exactly N element slots. +- At the sink, prove through the reaching ProgramState that N == 0 is feasible; suppress the report when path constraints make zero infeasible. +- For index zero, prove that the access targets the first element of an allocation with zero element capacity. +- For an index derived as N minus a positive constant, require N to have unsigned integer type and prove that zero causes unsigned wrap to an out-of-range value. +- Treat the early return on zero as safe only because its surviving analyzer states constrain N to be nonzero, not because a lexical guard exists. + +### Implementation constraints + +- Use a post-call callback to capture only allocation results supported by a generic allocator contract or CSA allocation semantics, and use check::PreStmt for the access sink. +- Carry the allocation-region to count-symbol and element-size association in ProgramState so facts and suppression follow individual paths. +- Recover the sink base from its SVal and underlying region; do not diagnose an unrelated, rebound, or invalidated pointer whose region does not match the recorded allocation. +- Keep the analysis within the function containing the allocation and sink; the evidence does not require interprocedural propagation. +- Attach the diagnostic to the concrete out-of-bounds subscript rather than the allocation, guard, or patch location. +- If duplicate suppression is needed, make it path/state-aware and allocation-specific rather than relying on checker-global mutable identity. +- Keep the design cross-project and independent of FFmpeg names, av_malloc spelling, ape_read_header, source paths, line numbers, log text, commit metadata, or changed-line anchors. + +### Validation checklist + +- Compile and load the synthesized checker successfully, verify registration, and run code verification without analyzer invocation errors. +- Scan the vulnerable source and require a relevant diagnostic in ape_read_header; scan the patched source and require zero diagnostics. +- Verify that the vulnerable report is located on the first reached invalid frames subscript, including the earlier frames[0] access rather than only count-minus-one. +- Use a focused case with a genuine N-times-element-size allocation and base[0] reachable when N is zero; require a report. +- Use the same case with an early return or equivalent path constraint proving N != 0 before the sink; require no report. +- Use a pointer-returning non-allocation API with a count-times-constant argument; require no report. +- Check unsigned N-minus-positive-constant behavior reports when zero is feasible, while the analogous signed-count case remains clean. +- Check that unrelated bases, nonmatching element sizes, and non-patched functions remain clean and that before/after sparsity does not regress. + +### Avoid and forbidden regressions + +- Do not reduce the design to syntax-only matching, textual guard recognition, CFG ordering, or dominance; these cannot establish the symbolic zero feasibility required at the sink. +- Do not classify nearly every pointer-returning call with a scaled argument as an allocator, and do not equate a distinct return symbol with proven fresh heap storage. +- Do not report count-minus-one expressions without proving their base is the corresponding N-element allocation. +- Do not treat signed zero minus one as unsigned wraparound. +- Do not suppress a warning merely because a zero check appears lexically before the access; require the nonzero constraint in the reaching state. +- Do not hardcode allocator, function, type, field, file, line, patch, or diagnostic-text anchors specific to this CVE. diff --git a/tasks/csa159/pair_139579/checker_template.cpp b/tasks/csa159/pair_139579/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_139579/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_139579/config.json b/tasks/csa159/pair_139579/config.json new file mode 100644 index 0000000000000000000000000000000000000000..e2179ea7a3686878fd473ae7ecf377f6b57c9f99 --- /dev/null +++ b/tasks/csa159/pair_139579/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "dccdd92b7b08ddbb7a8dbc1d6daba1f4fbd6bba2", + "after_commit": "44870a9e7a3c24acbb3f888b2a7cc22c9bdf7e7f", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/7ee85054682299babdb32f597b11daeec2d3e9d9/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/7ee85054682299babdb32f597b11daeec2d3e9d9/compile_commands.json", + "changed_files": [ + "drivers/media/usb/dvb-usb-v2/mxl111sf.c" + ], + "commit_message": "media: mxl111sf: change mutex_init() location\n\nSyzbot reported, that mxl111sf_ctrl_msg() uses uninitialized\nmutex. The problem was in wrong mutex_init() location.\n\nPrevious mutex_init(&state->msg_lock) call was in ->init() function, but\ndvb_usbv2_init() has this order of calls:\n\n\tdvb_usbv2_init()\n\t dvb_usbv2_adapter_init()\n\t dvb_usbv2_adapter_frontend_init()\n\t props->frontend_attach()\n\n\t props->init()\n\nSince mxl111sf_* devices call mxl111sf_ctrl_msg() in ->frontend_attach()\ninternally we need to initialize state->msg_lock before\nfrontend_attach(). To achieve it, ->probe() call added to all mxl111sf_*\ndevices, which will simply initiaize mutex.\n\nReported-and-tested-by: syzbot+5ca0bf339f13c4243001@syzkaller.appspotmail.com\n\nFixes: 8572211842af (\"[media] mxl111sf: convert to new DVB USB\")\nSigned-off-by: Pavel Skripkin \nSigned-off-by: Sean Young \nSigned-off-by: Mauro Carvalho Chehab ", + "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_139579/patch.diff b/tasks/csa159/pair_139579/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8c052ac9a5414da503117b1b8573473c390949a1 --- /dev/null +++ b/tasks/csa159/pair_139579/patch.diff @@ -0,0 +1,76 @@ +diff --git a/drivers/media/usb/dvb-usb-v2/mxl111sf.c b/drivers/media/usb/dvb-usb-v2/mxl111sf.c +index 7865fa0a8295..cd5861a30b6f 100644 +--- a/drivers/media/usb/dvb-usb-v2/mxl111sf.c ++++ b/drivers/media/usb/dvb-usb-v2/mxl111sf.c +@@ -931,8 +931,6 @@ static int mxl111sf_init(struct dvb_usb_device *d) + .len = sizeof(eeprom), .buf = eeprom }, + }; + +- mutex_init(&state->msg_lock); +- + ret = get_chip_info(state); + if (mxl_fail(ret)) + pr_err("failed to get chip info during probe"); +@@ -1074,6 +1072,14 @@ static int mxl111sf_get_stream_config_dvbt(struct dvb_frontend *fe, + return 0; + } + ++static int mxl111sf_probe(struct dvb_usb_device *dev) ++{ ++ struct mxl111sf_state *state = d_to_priv(dev); ++ ++ mutex_init(&state->msg_lock); ++ return 0; ++} ++ + static struct dvb_usb_device_properties mxl111sf_props_dvbt = { + .driver_name = KBUILD_MODNAME, + .owner = THIS_MODULE, +@@ -1083,6 +1089,7 @@ static struct dvb_usb_device_properties mxl111sf_props_dvbt = { + .generic_bulk_ctrl_endpoint = 0x02, + .generic_bulk_ctrl_endpoint_response = 0x81, + ++ .probe = mxl111sf_probe, + .i2c_algo = &mxl111sf_i2c_algo, + .frontend_attach = mxl111sf_frontend_attach_dvbt, + .tuner_attach = mxl111sf_attach_tuner, +@@ -1124,6 +1131,7 @@ static struct dvb_usb_device_properties mxl111sf_props_atsc = { + .generic_bulk_ctrl_endpoint = 0x02, + .generic_bulk_ctrl_endpoint_response = 0x81, + ++ .probe = mxl111sf_probe, + .i2c_algo = &mxl111sf_i2c_algo, + .frontend_attach = mxl111sf_frontend_attach_atsc, + .tuner_attach = mxl111sf_attach_tuner, +@@ -1165,6 +1173,7 @@ static struct dvb_usb_device_properties mxl111sf_props_mh = { + .generic_bulk_ctrl_endpoint = 0x02, + .generic_bulk_ctrl_endpoint_response = 0x81, + ++ .probe = mxl111sf_probe, + .i2c_algo = &mxl111sf_i2c_algo, + .frontend_attach = mxl111sf_frontend_attach_mh, + .tuner_attach = mxl111sf_attach_tuner, +@@ -1233,6 +1242,7 @@ static struct dvb_usb_device_properties mxl111sf_props_atsc_mh = { + .generic_bulk_ctrl_endpoint = 0x02, + .generic_bulk_ctrl_endpoint_response = 0x81, + ++ .probe = mxl111sf_probe, + .i2c_algo = &mxl111sf_i2c_algo, + .frontend_attach = mxl111sf_frontend_attach_atsc_mh, + .tuner_attach = mxl111sf_attach_tuner, +@@ -1311,6 +1321,7 @@ static struct dvb_usb_device_properties mxl111sf_props_mercury = { + .generic_bulk_ctrl_endpoint = 0x02, + .generic_bulk_ctrl_endpoint_response = 0x81, + ++ .probe = mxl111sf_probe, + .i2c_algo = &mxl111sf_i2c_algo, + .frontend_attach = mxl111sf_frontend_attach_mercury, + .tuner_attach = mxl111sf_attach_tuner, +@@ -1381,6 +1392,7 @@ static struct dvb_usb_device_properties mxl111sf_props_mercury_mh = { + .generic_bulk_ctrl_endpoint = 0x02, + .generic_bulk_ctrl_endpoint_response = 0x81, + ++ .probe = mxl111sf_probe, + .i2c_algo = &mxl111sf_i2c_algo, + .frontend_attach = mxl111sf_frontend_attach_mercury_mh, + .tuner_attach = mxl111sf_attach_tuner, \ No newline at end of file diff --git a/tasks/csa159/pair_139579/post_functions.txt b/tasks/csa159/pair_139579/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2fc0dc3dbb22b132464c1ed5f3fe42dc21c079c7 --- /dev/null +++ b/tasks/csa159/pair_139579/post_functions.txt @@ -0,0 +1,130 @@ +### File: drivers/media/usb/dvb-usb-v2/mxl111sf.c +```c +static int mxl111sf_init(struct dvb_usb_device *d) +{ + struct mxl111sf_state *state = d_to_priv(d); + int ret; + static u8 eeprom[256]; + u8 reg = 0; + struct i2c_msg msg[2] = { + { .addr = 0xa0 >> 1, .len = 1, .buf = ® }, + { .addr = 0xa0 >> 1, .flags = I2C_M_RD, + .len = sizeof(eeprom), .buf = eeprom }, + }; + + ret = get_chip_info(state); + if (mxl_fail(ret)) + pr_err("failed to get chip info during probe"); + + mutex_init(&state->fe_lock); + + if (state->chip_rev > MXL111SF_V6) + mxl111sf_config_pin_mux_modes(state, PIN_MUX_TS_SPI_IN_MODE_1); + + ret = i2c_transfer(&d->i2c_adap, msg, 2); + if (mxl_fail(ret)) + return 0; + tveeprom_hauppauge_analog(&state->tv, (0x84 == eeprom[0xa0]) ? + eeprom + 0xa0 : eeprom + 0x80); +#if 0 + switch (state->tv.model) { + case 117001: + case 126001: + case 138001: + break; + default: + printk(KERN_WARNING "%s: warning: unknown hauppauge model #%d\n", + __func__, state->tv.model); + } +#endif + return 0; +} + +static int mxl111sf_get_stream_config_dvbt(struct dvb_frontend *fe, + u8 *ts_type, struct usb_data_stream_properties *stream) +{ + pr_debug("%s: fe=%d\n", __func__, fe->id); + + *ts_type = DVB_USB_FE_TS_TYPE_188; + if (dvb_usb_mxl111sf_isoc) + mxl111sf_stream_config_isoc(stream, 4, 96, 564); + else + mxl111sf_stream_config_bulk(stream, 4); + return 0; +} + +static int mxl111sf_probe(struct dvb_usb_device *dev) +{ + struct mxl111sf_state *state = d_to_priv(dev); + + mutex_init(&state->msg_lock); + return 0; +} + +static int mxl111sf_get_stream_config_atsc(struct dvb_frontend *fe, + u8 *ts_type, struct usb_data_stream_properties *stream) +{ + pr_debug("%s: fe=%d\n", __func__, fe->id); + + *ts_type = DVB_USB_FE_TS_TYPE_188; + if (dvb_usb_mxl111sf_isoc) + mxl111sf_stream_config_isoc(stream, 6, 24, 3072); + else + mxl111sf_stream_config_bulk(stream, 6); + return 0; +} + +static int mxl111sf_get_stream_config_mh(struct dvb_frontend *fe, + u8 *ts_type, struct usb_data_stream_properties *stream) +{ + pr_debug("%s: fe=%d\n", __func__, fe->id); + + *ts_type = DVB_USB_FE_TS_TYPE_RAW; + if (dvb_usb_mxl111sf_isoc) + mxl111sf_stream_config_isoc(stream, 5, 96, 200); + else + mxl111sf_stream_config_bulk(stream, 5); + return 0; +} + +static int mxl111sf_streaming_ctrl_atsc_mh(struct dvb_frontend *fe, int onoff) +{ + pr_debug("%s: fe=%d onoff=%d\n", __func__, fe->id, onoff); + + if (fe->id == 0) + return mxl111sf_ep6_streaming_ctrl(fe, onoff); + else if (fe->id == 1) + return mxl111sf_ep4_streaming_ctrl(fe, onoff); + else if (fe->id == 2) + return mxl111sf_ep5_streaming_ctrl(fe, onoff); + return 0; +} + +static int mxl111sf_streaming_ctrl_mercury(struct dvb_frontend *fe, int onoff) +{ + pr_debug("%s: fe=%d onoff=%d\n", __func__, fe->id, onoff); + + if (fe->id == 0) + return mxl111sf_ep6_streaming_ctrl(fe, onoff); + else if (fe->id == 1) + return mxl111sf_ep4_streaming_ctrl(fe, onoff); + else if (fe->id == 2 && dvb_usb_mxl111sf_spi) + return mxl111sf_ep5_streaming_ctrl(fe, onoff); + else if (fe->id == 2 && !dvb_usb_mxl111sf_spi) + return mxl111sf_ep6_streaming_ctrl(fe, onoff); + return 0; +} + +static int mxl111sf_streaming_ctrl_mercury_mh(struct dvb_frontend *fe, int onoff) +{ + pr_debug("%s: fe=%d onoff=%d\n", __func__, fe->id, onoff); + + if (fe->id == 0) + return mxl111sf_ep4_streaming_ctrl(fe, onoff); + else if (fe->id == 1 && dvb_usb_mxl111sf_spi) + return mxl111sf_ep5_streaming_ctrl(fe, onoff); + else if (fe->id == 1 && !dvb_usb_mxl111sf_spi) + return mxl111sf_ep6_streaming_ctrl(fe, onoff); + return 0; +} +``` diff --git a/tasks/csa159/pair_139579/pre_functions.txt b/tasks/csa159/pair_139579/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..979dc7e4a4b59e5ea9ea7333490330a2ea4204da --- /dev/null +++ b/tasks/csa159/pair_139579/pre_functions.txt @@ -0,0 +1,57 @@ +### File: drivers/media/usb/dvb-usb-v2/mxl111sf.c +```c +static int mxl111sf_init(struct dvb_usb_device *d) +{ + struct mxl111sf_state *state = d_to_priv(d); + int ret; + static u8 eeprom[256]; + u8 reg = 0; + struct i2c_msg msg[2] = { + { .addr = 0xa0 >> 1, .len = 1, .buf = ® }, + { .addr = 0xa0 >> 1, .flags = I2C_M_RD, + .len = sizeof(eeprom), .buf = eeprom }, + }; + + mutex_init(&state->msg_lock); + + ret = get_chip_info(state); + if (mxl_fail(ret)) + pr_err("failed to get chip info during probe"); + + mutex_init(&state->fe_lock); + + if (state->chip_rev > MXL111SF_V6) + mxl111sf_config_pin_mux_modes(state, PIN_MUX_TS_SPI_IN_MODE_1); + + ret = i2c_transfer(&d->i2c_adap, msg, 2); + if (mxl_fail(ret)) + return 0; + tveeprom_hauppauge_analog(&state->tv, (0x84 == eeprom[0xa0]) ? + eeprom + 0xa0 : eeprom + 0x80); +#if 0 + switch (state->tv.model) { + case 117001: + case 126001: + case 138001: + break; + default: + printk(KERN_WARNING "%s: warning: unknown hauppauge model #%d\n", + __func__, state->tv.model); + } +#endif + return 0; +} + +static int mxl111sf_get_stream_config_dvbt(struct dvb_frontend *fe, + u8 *ts_type, struct usb_data_stream_properties *stream) +{ + pr_debug("%s: fe=%d\n", __func__, fe->id); + + *ts_type = DVB_USB_FE_TS_TYPE_188; + if (dvb_usb_mxl111sf_isoc) + mxl111sf_stream_config_isoc(stream, 4, 96, 564); + else + mxl111sf_stream_config_bulk(stream, 4); + return 0; +} +``` diff --git a/tasks/csa159/pair_139579/task_prompt.md b/tasks/csa159/pair_139579/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..6eca017e9790ef549b1189ba04fbed6c9842519a --- /dev/null +++ b/tasks/csa159/pair_139579/task_prompt.md @@ -0,0 +1,378 @@ +# 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 + +- Hard validation failed because both disappearing warnings were emitted at a lock site about 868 lines from the patch, outside the patched function and changed spans; the verifier therefore found no patch-relevant disappearing warning. +- The claimed whole-translation-unit mechanism remained unproven: semantic parsing and evidence were unavailable, and the detected implementation signals included no AST visitor, CFG, dominance, region reasoning, symbolic state, or source-text matching. +- The reported 2-to-0 differential was only cross-validation evidence; the duplicated source argument explains the two buggy counts and does not establish two distinct defects. +- No score result was produced, leaving the objective gate, semantic score, process score, and refinement acceptance unresolved. + +### Preserve from prior rollouts + +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Establish that an initialization and an acquisition refer to the same mutex member, using canonical AST declarations and a sufficiently precise object or state-type identity rather than field spelling alone. +- For each relevant device-properties instance, resolve its probe, frontend_attach, and init callback bindings and apply the evidenced lifecycle order: probe precedes frontend_attach, while init follows frontend_attach. +- Prove an interprocedural call or callback path from a pre-init lifecycle phase to the mutex acquisition, and prove that the matching initialization is confined to a later lifecycle phase on the buggy source. +- Treat the patched source as safe only when the matching initialization is in, or is unconditionally reached from, the probe callback registered by every relevant properties table before any acquisition-capable attach path. +- Keep deferred subsystem handlers distinct from synchronous attach paths unless evidence establishes that such a handler can execute before initialization. + +### Implementation constraints + +- Use CSA AST/body collection callbacks to gather complete function bodies and lifecycle-table bindings, then perform the interprocedural graph analysis and reporting at end of translation unit; do not depend on a path-sensitive call being reached to trigger whole-TU work. +- Build CFG-aware intraprocedural summaries for initialization, acquisition, unconditional reachability, and call edges, then propagate those summaries across direct calls and resolved callback bindings. +- Read designated callback bindings from the syntactic form of InitListExpr nodes, because semantic initializer forms may omit DesignatedInitExpr nodes. +- Associate facts with the specific properties table and canonical callback declarations that induce the lifecycle path; do not merge unrelated tables merely because they share slot names or mutex field types. +- Emit the diagnostic at the late mutex_init site in the buggy source, with the enclosing callback as the declaration with issue, so the warning is both semantically actionable and within the removed changed span. +- Recognize kernel mutex initialization and acquisition entry points through callee declarations and AST argument structure, without source-text matching. +- Limit diagnostics to main-file source locations and remain silent when lifecycle order, callback binding, matching initialization, or acquisition reachability cannot be established. +- Keep the scope project-general: stable mutex APIs and dvb-usb lifecycle fields are permitted, but local function names, variable names, line numbers, commit identifiers, and unique patch literals are prohibited. + +### Validation checklist + +- Compile the checker against the target Clang Static Analyzer API, load the resulting plugin, enable the registered checker, and confirm that analysis completes without registration, assertion, or diagnostic-construction failures. +- Scan the buggy source and require one unique diagnostic at the mutex_init removal span inside mxl111sf_init; if the harness passes the source twice, confirm that any count of two is exact duplication rather than two warning sites. +- Scan the patched source and require zero diagnostics after msg_lock initialization moves to mxl111sf_probe and that probe is registered in all six relevant properties tables. +- Verify that the disappearing diagnostic satisfies function_or_precise_changed_span_v2 relevance instead of relying on a distant mutex_lock location. +- Exercise a safe case where initialization occurs directly in probe and another where probe unconditionally calls an initialization helper; both must remain silent. +- Exercise an unsafe case where attach reaches a matching lock while initialization exists only in init; it must report at the late initialization. +- Exercise refinement cases for deferred handlers, absent in-TU initialization, unrelated lifecycle tables, and same-named fields in different record types; none may create unsupported reports. +- Require populated verification and scoring outputs with hard validation, objective eligibility, semantic mechanism, semantic threshold, process quality, and refinement acceptance all established. + +### Avoid and forbidden regressions + +- Do not use check::PreCall merely as an arbitrary one-time trigger for emitting reports discovered by a separate whole-TU scan. +- Do not attach the only diagnostic to the distant acquisition site when the verifiable defect evidence is the initialization placed in the late callback. +- Do not infer vulnerability from the coexistence of a lifecycle table, a mutex_init, and a mutex_lock without proving table-specific ordering and acquisition reachability. +- Do not treat any initialization reachable from any probe in the translation unit as making every properties instance safe. +- Do not identify a mutex solely as RecordName::FieldName when canonical declarations or object provenance can distinguish unrelated storage. +- Do not replace the interprocedural lifecycle proof with syntax-only matching, local CFG ordering, or unvalidated assumptions about framework execution. +- Do not add ProgramState or region tracking unless it is needed for concrete mutex identity; lifecycle slot ordering itself is a structural interprocedural fact. +- Do not count duplicated compiler invocations as independent vulnerability evidence. diff --git a/tasks/csa159/pair_139922/checker_template.cpp b/tasks/csa159/pair_139922/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_139922/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_139922/config.json b/tasks/csa159/pair_139922/config.json new file mode 100644 index 0000000000000000000000000000000000000000..3c831d5c05865f49a758541d0be90b8357f0c16a --- /dev/null +++ b/tasks/csa159/pair_139922/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "2e7be9db125a0bf940c5d65eb5c40d8700f738b5", + "after_commit": "741b23a970a79d5d3a1db2d64fa2c7b375a4febb", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/f26c92386028563a1e988bb277c6c5ce2e8010ee/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/f26c92386028563a1e988bb277c6c5ce2e8010ee/compile_commands.json", + "changed_files": [ + "fs/btrfs/lzo.c" + ], + "commit_message": "btrfs: prevent copying too big compressed lzo segment\n\nCompressed length can be corrupted to be a lot larger than memory\nwe have allocated for buffer.\nThis will cause memcpy in copy_compressed_segment to write outside\nof allocated memory.\n\nThis mostly results in stuck read syscall but sometimes when using\nbtrfs send can get #GP\n\n kernel: general protection fault, probably for non-canonical address 0x841551d5c1000: 0000 [#1] PREEMPT SMP NOPTI\n kernel: CPU: 17 PID: 264 Comm: kworker/u256:7 Tainted: P OE 5.17.0-rc2-1 #12\n kernel: Workqueue: btrfs-endio btrfs_work_helper [btrfs]\n kernel: RIP: 0010:lzo_decompress_bio (./include/linux/fortify-string.h:225 fs/btrfs/lzo.c:322 fs/btrfs/lzo.c:394) btrfs\n Code starting with the faulting instruction\n ===========================================\n 0:* 48 8b 06 mov (%rsi),%rax <-- trapping instruction\n 3: 48 8d 79 08 lea 0x8(%rcx),%rdi\n 7: 48 83 e7 f8 and $0xfffffffffffffff8,%rdi\n b: 48 89 01 mov %rax,(%rcx)\n e: 44 89 f0 mov %r14d,%eax\n 11: 48 8b 54 06 f8 mov -0x8(%rsi,%rax,1),%rdx\n kernel: RSP: 0018:ffffb110812efd50 EFLAGS: 00010212\n kernel: RAX: 0000000000001000 RBX: 000000009ca264c8 RCX: ffff98996e6d8ff8\n kernel: RDX: 0000000000000064 RSI: 000841551d5c1000 RDI: ffffffff9500435d\n kernel: RBP: ffff989a3be856c0 R08: 0000000000000000 R09: 0000000000000000\n kernel: R10: 0000000000000000 R11: 0000000000001000 R12: ffff98996e6d8000\n kernel: R13: 0000000000000008 R14: 0000000000001000 R15: 000841551d5c1000\n kernel: FS: 0000000000000000(0000) GS:ffff98a09d640000(0000) knlGS:0000000000000000\n kernel: CS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\n kernel: CR2: 00001e9f984d9ea8 CR3: 000000014971a000 CR4: 00000000003506e0\n kernel: Call Trace:\n kernel: \n kernel: end_compressed_bio_read (fs/btrfs/compression.c:104 fs/btrfs/compression.c:1363 fs/btrfs/compression.c:323) btrfs\n kernel: end_workqueue_fn (fs/btrfs/disk-io.c:1923) btrfs\n kernel: btrfs_work_helper (fs/btrfs/async-thread.c:326) btrfs\n kernel: process_one_work (./arch/x86/include/asm/jump_label.h:27 ./include/linux/jump_label.h:212 ./include/trace/events/workqueue.h:108 kernel/workqueue.c:2312)\n kernel: worker_thread (./include/linux/list.h:292 kernel/workqueue.c:2455)\n kernel: ? process_one_work (kernel/workqueue.c:2397)\n kernel: kthread (kernel/kthread.c:377)\n kernel: ? kthread_complete_and_exit (kernel/kthread.c:332)\n kernel: ret_from_fork (arch/x86/entry/entry_64.S:301)\n kernel: \n\nCC: stable@vger.kernel.org # 4.9+\nSigned-off-by: Dāvis Mosāns \nReviewed-by: David Sterba \nSigned-off-by: David Sterba ", + "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_139922/patch.diff b/tasks/csa159/pair_139922/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3a65605114eb578513ab1f8a48f709955d3df93f --- /dev/null +++ b/tasks/csa159/pair_139922/patch.diff @@ -0,0 +1,21 @@ +diff --git a/fs/btrfs/lzo.c b/fs/btrfs/lzo.c +index 0fb90cbe7669..e6e28a9c7987 100644 +--- a/fs/btrfs/lzo.c ++++ b/fs/btrfs/lzo.c +@@ -380,6 +380,17 @@ int lzo_decompress_bio(struct list_head *ws, struct compressed_bio *cb) + kunmap(cur_page); + cur_in += LZO_LEN; + ++ if (seg_len > lzo1x_worst_compress(PAGE_SIZE)) { ++ /* ++ * seg_len shouldn't be larger than we have allocated ++ * for workspace->cbuf ++ */ ++ btrfs_err(fs_info, "unexpectedly large lzo segment len %u", ++ seg_len); ++ ret = -EIO; ++ goto out; ++ } ++ + /* Copy the compressed segment payload into workspace */ + copy_compressed_segment(cb, workspace->cbuf, seg_len, &cur_in); \ No newline at end of file diff --git a/tasks/csa159/pair_139922/post_functions.txt b/tasks/csa159/pair_139922/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..4c299aa72dd1284b6c03654c3b4badc8cd5ad107 --- /dev/null +++ b/tasks/csa159/pair_139922/post_functions.txt @@ -0,0 +1,103 @@ +### File: fs/btrfs/lzo.c +```c +int lzo_decompress_bio(struct list_head *ws, struct compressed_bio *cb) +{ + struct workspace *workspace = list_entry(ws, struct workspace, list); + const struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb); + const u32 sectorsize = fs_info->sectorsize; + char *kaddr; + int ret; + /* Compressed data length, can be unaligned */ + u32 len_in; + /* Offset inside the compressed data */ + u32 cur_in = 0; + /* Bytes decompressed so far */ + u32 cur_out = 0; + + kaddr = kmap(cb->compressed_pages[0]); + len_in = read_compress_length(kaddr); + kunmap(cb->compressed_pages[0]); + cur_in += LZO_LEN; + + /* + * LZO header length check + * + * The total length should not exceed the maximum extent length, + * and all sectors should be used. + * If this happens, it means the compressed extent is corrupted. + */ + if (len_in > min_t(size_t, BTRFS_MAX_COMPRESSED, cb->compressed_len) || + round_up(len_in, sectorsize) < cb->compressed_len) { + btrfs_err(fs_info, + "invalid lzo header, lzo len %u compressed len %u", + len_in, cb->compressed_len); + return -EUCLEAN; + } + + /* Go through each lzo segment */ + while (cur_in < len_in) { + struct page *cur_page; + /* Length of the compressed segment */ + u32 seg_len; + u32 sector_bytes_left; + size_t out_len = lzo1x_worst_compress(sectorsize); + + /* + * We should always have enough space for one segment header + * inside current sector. + */ + ASSERT(cur_in / sectorsize == + (cur_in + LZO_LEN - 1) / sectorsize); + cur_page = cb->compressed_pages[cur_in / PAGE_SIZE]; + ASSERT(cur_page); + kaddr = kmap(cur_page); + seg_len = read_compress_length(kaddr + offset_in_page(cur_in)); + kunmap(cur_page); + cur_in += LZO_LEN; + + if (seg_len > lzo1x_worst_compress(PAGE_SIZE)) { + /* + * seg_len shouldn't be larger than we have allocated + * for workspace->cbuf + */ + btrfs_err(fs_info, "unexpectedly large lzo segment len %u", + seg_len); + ret = -EIO; + goto out; + } + + /* Copy the compressed segment payload into workspace */ + copy_compressed_segment(cb, workspace->cbuf, seg_len, &cur_in); + + /* Decompress the data */ + ret = lzo1x_decompress_safe(workspace->cbuf, seg_len, + workspace->buf, &out_len); + if (ret != LZO_E_OK) { + btrfs_err(fs_info, "failed to decompress"); + ret = -EIO; + goto out; + } + + /* Copy the data into inode pages */ + ret = btrfs_decompress_buf2page(workspace->buf, out_len, cb, cur_out); + cur_out += out_len; + + /* All data read, exit */ + if (ret == 0) + goto out; + ret = 0; + + /* Check if the sector has enough space for a segment header */ + sector_bytes_left = sectorsize - (cur_in % sectorsize); + if (sector_bytes_left >= LZO_LEN) + continue; + + /* Skip the padding zeros */ + cur_in += sector_bytes_left; + } +out: + if (!ret) + zero_fill_bio(cb->orig_bio); + return ret; +} +``` diff --git a/tasks/csa159/pair_139922/pre_functions.txt b/tasks/csa159/pair_139922/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..72e2b5f5128f35abc24904084be44af0d4abf573 --- /dev/null +++ b/tasks/csa159/pair_139922/pre_functions.txt @@ -0,0 +1,92 @@ +### File: fs/btrfs/lzo.c +```c +int lzo_decompress_bio(struct list_head *ws, struct compressed_bio *cb) +{ + struct workspace *workspace = list_entry(ws, struct workspace, list); + const struct btrfs_fs_info *fs_info = btrfs_sb(cb->inode->i_sb); + const u32 sectorsize = fs_info->sectorsize; + char *kaddr; + int ret; + /* Compressed data length, can be unaligned */ + u32 len_in; + /* Offset inside the compressed data */ + u32 cur_in = 0; + /* Bytes decompressed so far */ + u32 cur_out = 0; + + kaddr = kmap(cb->compressed_pages[0]); + len_in = read_compress_length(kaddr); + kunmap(cb->compressed_pages[0]); + cur_in += LZO_LEN; + + /* + * LZO header length check + * + * The total length should not exceed the maximum extent length, + * and all sectors should be used. + * If this happens, it means the compressed extent is corrupted. + */ + if (len_in > min_t(size_t, BTRFS_MAX_COMPRESSED, cb->compressed_len) || + round_up(len_in, sectorsize) < cb->compressed_len) { + btrfs_err(fs_info, + "invalid lzo header, lzo len %u compressed len %u", + len_in, cb->compressed_len); + return -EUCLEAN; + } + + /* Go through each lzo segment */ + while (cur_in < len_in) { + struct page *cur_page; + /* Length of the compressed segment */ + u32 seg_len; + u32 sector_bytes_left; + size_t out_len = lzo1x_worst_compress(sectorsize); + + /* + * We should always have enough space for one segment header + * inside current sector. + */ + ASSERT(cur_in / sectorsize == + (cur_in + LZO_LEN - 1) / sectorsize); + cur_page = cb->compressed_pages[cur_in / PAGE_SIZE]; + ASSERT(cur_page); + kaddr = kmap(cur_page); + seg_len = read_compress_length(kaddr + offset_in_page(cur_in)); + kunmap(cur_page); + cur_in += LZO_LEN; + + /* Copy the compressed segment payload into workspace */ + copy_compressed_segment(cb, workspace->cbuf, seg_len, &cur_in); + + /* Decompress the data */ + ret = lzo1x_decompress_safe(workspace->cbuf, seg_len, + workspace->buf, &out_len); + if (ret != LZO_E_OK) { + btrfs_err(fs_info, "failed to decompress"); + ret = -EIO; + goto out; + } + + /* Copy the data into inode pages */ + ret = btrfs_decompress_buf2page(workspace->buf, out_len, cb, cur_out); + cur_out += out_len; + + /* All data read, exit */ + if (ret == 0) + goto out; + ret = 0; + + /* Check if the sector has enough space for a segment header */ + sector_bytes_left = sectorsize - (cur_in % sectorsize); + if (sector_bytes_left >= LZO_LEN) + continue; + + /* Skip the padding zeros */ + cur_in += sector_bytes_left; + } +out: + if (!ret) + zero_fill_bio(cb->orig_bio); + return ret; +} +``` diff --git a/tasks/csa159/pair_139922/task_prompt.md b/tasks/csa159/pair_139922/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_139922/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_140347/checker_template.cpp b/tasks/csa159/pair_140347/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_140347/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_140347/config.json b/tasks/csa159/pair_140347/config.json new file mode 100644 index 0000000000000000000000000000000000000000..eed6ba47543e0fa32ec17fec88863ba421b8d8c6 --- /dev/null +++ b/tasks/csa159/pair_140347/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "e60e8a73235ce5d42a2891c6989e8df1c8888c4a", + "after_commit": "d3b43eb505bffb8e4cdf6800c15660c001553fe6", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/deeb4b5393e106b990607df06261fba0ebb7ebde/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/deeb4b5393e106b990607df06261fba0ebb7ebde/compile_commands.json", + "changed_files": [ + "drivers/rtc/rtc-mt6397.c" + ], + "commit_message": "rtc: mt6397: check return value after calling platform_get_resource()\n\nIt will cause null-ptr-deref if platform_get_resource() returns NULL,\nwe need check the return value.\n\nFixes: fc2979118f3f (\"rtc: mediatek: Add MT6397 RTC driver\")\nSigned-off-by: Yang Yingliang \nReviewed-by: AngeloGioacchino Del Regno \nSigned-off-by: Alexandre Belloni \nLink: https://lore.kernel.org/r/20220505125043.1594771-1-yangyingliang@huawei.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_140347/patch.diff b/tasks/csa159/pair_140347/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..aa18a0bb86c4c9e159f9b90836220a0453d99e02 --- /dev/null +++ b/tasks/csa159/pair_140347/patch.diff @@ -0,0 +1,13 @@ +diff --git a/drivers/rtc/rtc-mt6397.c b/drivers/rtc/rtc-mt6397.c +index 80dc479a6ff0..1d297af80f87 100644 +--- a/drivers/rtc/rtc-mt6397.c ++++ b/drivers/rtc/rtc-mt6397.c +@@ -269,6 +269,8 @@ static int mtk_rtc_probe(struct platform_device *pdev) + return -ENOMEM; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); ++ if (!res) ++ return -EINVAL; + rtc->addr_base = res->start; + + rtc->data = of_device_get_match_data(&pdev->dev); \ No newline at end of file diff --git a/tasks/csa159/pair_140347/post_functions.txt b/tasks/csa159/pair_140347/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..51db5f34500e58b4ff8b92f6a845ca96d27849b8 --- /dev/null +++ b/tasks/csa159/pair_140347/post_functions.txt @@ -0,0 +1,51 @@ +### File: drivers/rtc/rtc-mt6397.c +```c +static int mtk_rtc_probe(struct platform_device *pdev) +{ + struct resource *res; + struct mt6397_chip *mt6397_chip = dev_get_drvdata(pdev->dev.parent); + struct mt6397_rtc *rtc; + int ret; + + rtc = devm_kzalloc(&pdev->dev, sizeof(struct mt6397_rtc), GFP_KERNEL); + if (!rtc) + return -ENOMEM; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + if (!res) + return -EINVAL; + rtc->addr_base = res->start; + + rtc->data = of_device_get_match_data(&pdev->dev); + + rtc->irq = platform_get_irq(pdev, 0); + if (rtc->irq < 0) + return rtc->irq; + + rtc->regmap = mt6397_chip->regmap; + mutex_init(&rtc->lock); + + platform_set_drvdata(pdev, rtc); + + rtc->rtc_dev = devm_rtc_allocate_device(&pdev->dev); + if (IS_ERR(rtc->rtc_dev)) + return PTR_ERR(rtc->rtc_dev); + + ret = devm_request_threaded_irq(&pdev->dev, rtc->irq, NULL, + mtk_rtc_irq_handler_thread, + IRQF_ONESHOT | IRQF_TRIGGER_HIGH, + "mt6397-rtc", rtc); + + if (ret) { + dev_err(&pdev->dev, "Failed to request alarm IRQ: %d: %d\n", + rtc->irq, ret); + return ret; + } + + device_init_wakeup(&pdev->dev, 1); + + rtc->rtc_dev->ops = &mtk_rtc_ops; + + return devm_rtc_register_device(rtc->rtc_dev); +} +``` diff --git a/tasks/csa159/pair_140347/pre_functions.txt b/tasks/csa159/pair_140347/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb1bc6c80d030aa39ad8c1902a12c1ca78d24c65 --- /dev/null +++ b/tasks/csa159/pair_140347/pre_functions.txt @@ -0,0 +1,49 @@ +### File: drivers/rtc/rtc-mt6397.c +```c +static int mtk_rtc_probe(struct platform_device *pdev) +{ + struct resource *res; + struct mt6397_chip *mt6397_chip = dev_get_drvdata(pdev->dev.parent); + struct mt6397_rtc *rtc; + int ret; + + rtc = devm_kzalloc(&pdev->dev, sizeof(struct mt6397_rtc), GFP_KERNEL); + if (!rtc) + return -ENOMEM; + + res = platform_get_resource(pdev, IORESOURCE_MEM, 0); + rtc->addr_base = res->start; + + rtc->data = of_device_get_match_data(&pdev->dev); + + rtc->irq = platform_get_irq(pdev, 0); + if (rtc->irq < 0) + return rtc->irq; + + rtc->regmap = mt6397_chip->regmap; + mutex_init(&rtc->lock); + + platform_set_drvdata(pdev, rtc); + + rtc->rtc_dev = devm_rtc_allocate_device(&pdev->dev); + if (IS_ERR(rtc->rtc_dev)) + return PTR_ERR(rtc->rtc_dev); + + ret = devm_request_threaded_irq(&pdev->dev, rtc->irq, NULL, + mtk_rtc_irq_handler_thread, + IRQF_ONESHOT | IRQF_TRIGGER_HIGH, + "mt6397-rtc", rtc); + + if (ret) { + dev_err(&pdev->dev, "Failed to request alarm IRQ: %d: %d\n", + rtc->irq, ret); + return ret; + } + + device_init_wakeup(&pdev->dev, 1); + + rtc->rtc_dev->ops = &mtk_rtc_ops; + + return devm_rtc_register_device(rtc->rtc_dev); +} +``` diff --git a/tasks/csa159/pair_140347/task_prompt.md b/tasks/csa159/pair_140347/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_140347/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_140531/checker_template.cpp b/tasks/csa159/pair_140531/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_140531/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_140531/config.json b/tasks/csa159/pair_140531/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b4b2867717848ac93ee8501c4a13a87792c710ed --- /dev/null +++ b/tasks/csa159/pair_140531/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "029aa4624a7fe35233bdd3d1354dc7be260380bf", + "after_commit": "9714061423b8b24b8afb31b8eb4df977c63f19c4", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/af88d3c109aa5edfaa11c9a26d9c0ff21ddf501c/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/af88d3c109aa5edfaa11c9a26d9c0ff21ddf501c/compile_commands.json", + "changed_files": [ + "drivers/crypto/qat/qat_common/qat_asym_algs.c" + ], + "commit_message": "crypto: qat - add param check for RSA\n\nReject requests with a source buffer that is bigger than the size of the\nkey. This is to prevent a possible integer underflow that might happen\nwhen copying the source scatterlist into a linear buffer.\n\nCc: stable@vger.kernel.org\nSigned-off-by: Giovanni Cabiddu \nReviewed-by: Adam Guerin \nReviewed-by: Wojciech Ziemba \nSigned-off-by: Herbert Xu ", + "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_140531/patch.diff b/tasks/csa159/pair_140531/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..98911eb14ee68356d9691bdf24e5826c9c54c9f9 --- /dev/null +++ b/tasks/csa159/pair_140531/patch.diff @@ -0,0 +1,26 @@ +diff --git a/drivers/crypto/qat/qat_common/qat_asym_algs.c b/drivers/crypto/qat/qat_common/qat_asym_algs.c +index 25bbd22085c3..947eeff181b4 100644 +--- a/drivers/crypto/qat/qat_common/qat_asym_algs.c ++++ b/drivers/crypto/qat/qat_common/qat_asym_algs.c +@@ -656,6 +656,10 @@ static int qat_rsa_enc(struct akcipher_request *req) + req->dst_len = ctx->key_sz; + return -EOVERFLOW; + } ++ ++ if (req->src_len > ctx->key_sz) ++ return -EINVAL; ++ + memset(msg, '\0', sizeof(*msg)); + ICP_QAT_FW_PKE_HDR_VALID_FLAG_SET(msg->pke_hdr, + ICP_QAT_FW_COMN_REQ_FLAG_SET); +@@ -785,6 +789,10 @@ static int qat_rsa_dec(struct akcipher_request *req) + req->dst_len = ctx->key_sz; + return -EOVERFLOW; + } ++ ++ if (req->src_len > ctx->key_sz) ++ return -EINVAL; ++ + memset(msg, '\0', sizeof(*msg)); + ICP_QAT_FW_PKE_HDR_VALID_FLAG_SET(msg->pke_hdr, + ICP_QAT_FW_COMN_REQ_FLAG_SET); \ No newline at end of file diff --git a/tasks/csa159/pair_140531/post_functions.txt b/tasks/csa159/pair_140531/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..0cdc03c98f6d6b11f3ac04ccd392595d1221e38e --- /dev/null +++ b/tasks/csa159/pair_140531/post_functions.txt @@ -0,0 +1,269 @@ +### File: drivers/crypto/qat/qat_common/qat_asym_algs.c +```c +static int qat_rsa_enc(struct akcipher_request *req) +{ + struct crypto_akcipher *tfm = crypto_akcipher_reqtfm(req); + struct qat_rsa_ctx *ctx = akcipher_tfm_ctx(tfm); + struct qat_crypto_instance *inst = ctx->inst; + struct device *dev = &GET_DEV(inst->accel_dev); + struct qat_asym_request *qat_req = + PTR_ALIGN(akcipher_request_ctx(req), 64); + struct icp_qat_fw_pke_request *msg = &qat_req->req; + u8 *vaddr; + int ret; + + if (unlikely(!ctx->n || !ctx->e)) + return -EINVAL; + + if (req->dst_len < ctx->key_sz) { + req->dst_len = ctx->key_sz; + return -EOVERFLOW; + } + + if (req->src_len > ctx->key_sz) + return -EINVAL; + + memset(msg, '\0', sizeof(*msg)); + ICP_QAT_FW_PKE_HDR_VALID_FLAG_SET(msg->pke_hdr, + ICP_QAT_FW_COMN_REQ_FLAG_SET); + msg->pke_hdr.cd_pars.func_id = qat_rsa_enc_fn_id(ctx->key_sz); + if (unlikely(!msg->pke_hdr.cd_pars.func_id)) + return -EINVAL; + + qat_req->cb = qat_rsa_cb; + qat_req->ctx.rsa = ctx; + qat_req->areq.rsa = req; + msg->pke_hdr.service_type = ICP_QAT_FW_COMN_REQ_CPM_FW_PKE; + msg->pke_hdr.comn_req_flags = + ICP_QAT_FW_COMN_FLAGS_BUILD(QAT_COMN_PTR_TYPE_FLAT, + QAT_COMN_CD_FLD_TYPE_64BIT_ADR); + + qat_req->in.rsa.enc.e = ctx->dma_e; + qat_req->in.rsa.enc.n = ctx->dma_n; + ret = -ENOMEM; + + /* + * src can be of any size in valid range, but HW expects it to be the + * same as modulo n so in case it is different we need to allocate a + * new buf and copy src data. + * In other case we just need to map the user provided buffer. + * Also need to make sure that it is in contiguous buffer. + */ + if (sg_is_last(req->src) && req->src_len == ctx->key_sz) { + qat_req->src_align = NULL; + vaddr = sg_virt(req->src); + } else { + int shift = ctx->key_sz - req->src_len; + + qat_req->src_align = kzalloc(ctx->key_sz, GFP_KERNEL); + if (unlikely(!qat_req->src_align)) + return ret; + + scatterwalk_map_and_copy(qat_req->src_align + shift, req->src, + 0, req->src_len, 0); + vaddr = qat_req->src_align; + } + + qat_req->in.rsa.enc.m = dma_map_single(dev, vaddr, ctx->key_sz, + DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->in.rsa.enc.m))) + goto unmap_src; + + if (sg_is_last(req->dst) && req->dst_len == ctx->key_sz) { + qat_req->dst_align = NULL; + vaddr = sg_virt(req->dst); + } else { + qat_req->dst_align = kzalloc(ctx->key_sz, GFP_KERNEL); + if (unlikely(!qat_req->dst_align)) + goto unmap_src; + vaddr = qat_req->dst_align; + } + + qat_req->out.rsa.enc.c = dma_map_single(dev, vaddr, ctx->key_sz, + DMA_FROM_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->out.rsa.enc.c))) + goto unmap_dst; + + qat_req->in.rsa.in_tab[3] = 0; + qat_req->out.rsa.out_tab[1] = 0; + qat_req->phy_in = dma_map_single(dev, &qat_req->in.rsa.enc.m, + sizeof(qat_req->in.rsa.enc.m), + DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->phy_in))) + goto unmap_dst; + + qat_req->phy_out = dma_map_single(dev, &qat_req->out.rsa.enc.c, + sizeof(qat_req->out.rsa.enc.c), + DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->phy_out))) + goto unmap_in_params; + + msg->pke_mid.src_data_addr = qat_req->phy_in; + msg->pke_mid.dest_data_addr = qat_req->phy_out; + msg->pke_mid.opaque = (u64)(__force long)qat_req; + msg->input_param_count = 3; + msg->output_param_count = 1; + + ret = qat_alg_send_asym_message(qat_req, inst, &req->base); + if (ret == -ENOSPC) + goto unmap_all; + + return ret; + +unmap_all: + if (!dma_mapping_error(dev, qat_req->phy_out)) + dma_unmap_single(dev, qat_req->phy_out, + sizeof(struct qat_rsa_output_params), + DMA_TO_DEVICE); +unmap_in_params: + if (!dma_mapping_error(dev, qat_req->phy_in)) + dma_unmap_single(dev, qat_req->phy_in, + sizeof(struct qat_rsa_input_params), + DMA_TO_DEVICE); +unmap_dst: + if (!dma_mapping_error(dev, qat_req->out.rsa.enc.c)) + dma_unmap_single(dev, qat_req->out.rsa.enc.c, + ctx->key_sz, DMA_FROM_DEVICE); + kfree_sensitive(qat_req->dst_align); +unmap_src: + if (!dma_mapping_error(dev, qat_req->in.rsa.enc.m)) + dma_unmap_single(dev, qat_req->in.rsa.enc.m, ctx->key_sz, + DMA_TO_DEVICE); + kfree_sensitive(qat_req->src_align); + return ret; +} + +static int qat_rsa_dec(struct akcipher_request *req) +{ + struct crypto_akcipher *tfm = crypto_akcipher_reqtfm(req); + struct qat_rsa_ctx *ctx = akcipher_tfm_ctx(tfm); + struct qat_crypto_instance *inst = ctx->inst; + struct device *dev = &GET_DEV(inst->accel_dev); + struct qat_asym_request *qat_req = + PTR_ALIGN(akcipher_request_ctx(req), 64); + struct icp_qat_fw_pke_request *msg = &qat_req->req; + u8 *vaddr; + int ret; + + if (unlikely(!ctx->n || !ctx->d)) + return -EINVAL; + + if (req->dst_len < ctx->key_sz) { + req->dst_len = ctx->key_sz; + return -EOVERFLOW; + } + + if (req->src_len > ctx->key_sz) + return -EINVAL; + + memset(msg, '\0', sizeof(*msg)); + ICP_QAT_FW_PKE_HDR_VALID_FLAG_SET(msg->pke_hdr, + ICP_QAT_FW_COMN_REQ_FLAG_SET); + msg->pke_hdr.cd_pars.func_id = ctx->crt_mode ? + qat_rsa_dec_fn_id_crt(ctx->key_sz) : + qat_rsa_dec_fn_id(ctx->key_sz); + if (unlikely(!msg->pke_hdr.cd_pars.func_id)) + return -EINVAL; + + qat_req->cb = qat_rsa_cb; + qat_req->ctx.rsa = ctx; + qat_req->areq.rsa = req; + msg->pke_hdr.service_type = ICP_QAT_FW_COMN_REQ_CPM_FW_PKE; + msg->pke_hdr.comn_req_flags = + ICP_QAT_FW_COMN_FLAGS_BUILD(QAT_COMN_PTR_TYPE_FLAT, + QAT_COMN_CD_FLD_TYPE_64BIT_ADR); + + if (ctx->crt_mode) { + qat_req->in.rsa.dec_crt.p = ctx->dma_p; + qat_req->in.rsa.dec_crt.q = ctx->dma_q; + qat_req->in.rsa.dec_crt.dp = ctx->dma_dp; + qat_req->in.rsa.dec_crt.dq = ctx->dma_dq; + qat_req->in.rsa.dec_crt.qinv = ctx->dma_qinv; + } else { + qat_req->in.rsa.dec.d = ctx->dma_d; + qat_req->in.rsa.dec.n = ctx->dma_n; + } + ret = -ENOMEM; + + /* + * src can be of any size in valid range, but HW expects it to be the + * same as modulo n so in case it is different we need to allocate a + * new buf and copy src data. + * In other case we just need to map the user provided buffer. + * Also need to make sure that it is in contiguous buffer. + */ + if (sg_is_last(req->src) && req->src_len == ctx->key_sz) { + qat_req->src_align = NULL; + vaddr = sg_virt(req->src); + } else { + int shift = ctx->key_sz - req->src_len; + + qat_req->src_align = kzalloc(ctx->key_sz, GFP_KERNEL); + if (unlikely(!qat_req->src_align)) + return ret; + + scatterwalk_map_and_copy(qat_req->src_align + shift, req->src, + 0, req->src_len, 0); + vaddr = qat_req->src_align; + } + + qat_req->in.rsa.dec.c = dma_map_single(dev, vaddr, ctx->key_sz, + DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->in.rsa.dec.c))) + goto unmap_src; + + if (sg_is_last(req->dst) && req->dst_len == ctx->key_sz) { + qat_req->dst_align = NULL; + vaddr = sg_virt(req->dst); + } else { + qat_req->dst_align = kzalloc(ctx->key_sz, GFP_KERNEL); + if (unlikely(!qat_req->dst_align)) + goto unmap_src; + vaddr = qat_req->dst_align; + } + qat_req->out.rsa.dec.m = dma_map_single(dev, vaddr, ctx->key_sz, + DMA_FROM_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->out.rsa.dec.m))) + goto unmap_dst; + + if (ctx->crt_mode) + qat_req->in.rsa.in_tab[6] = 0; + else + qat_req->in.rsa.in_tab[3] = 0; + qat_req->out.rsa.out_tab[1] = 0; + qat_req->phy_in = dma_map_single(dev, &qat_req->in.rsa.dec.c, + sizeof(qat_req->in.rsa.dec.c), + DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->phy_in))) + goto unmap_dst; + + qat_req->phy_out = dma_map_single(dev, &qat_req->out.rsa.dec.m, + sizeof(qat_req->out.rsa.dec.m), + DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->phy_out))) + goto unmap_in_params; + + msg->pke_mid.src_data_addr = qat_req->phy_in; + msg->pke_mid.dest_data_addr = qat_req->phy_out; + msg->pke_mid.opaque = (u64)(__force long)qat_req; + if (ctx->crt_mode) + msg->input_param_count = 6; + else + msg->input_param_count = 3; + + msg->output_param_count = 1; + + ret = qat_alg_send_asym_message(qat_req, inst, &req->base); + if (ret == -ENOSPC) + goto unmap_all; + + return ret; + +unmap_all: + if (!dma_mapping_error(dev, qat_req->phy_out)) + dma_unmap_single(dev, qat_req->phy_out, + sizeof(struct qat_rsa_output_params), + DMA + +// ... (565 more chars) +``` diff --git a/tasks/csa159/pair_140531/pre_functions.txt b/tasks/csa159/pair_140531/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..32f5f88dd616b65932587ca1bcdde9002f5a6167 --- /dev/null +++ b/tasks/csa159/pair_140531/pre_functions.txt @@ -0,0 +1,264 @@ +### File: drivers/crypto/qat/qat_common/qat_asym_algs.c +```c +static int qat_rsa_enc(struct akcipher_request *req) +{ + struct crypto_akcipher *tfm = crypto_akcipher_reqtfm(req); + struct qat_rsa_ctx *ctx = akcipher_tfm_ctx(tfm); + struct qat_crypto_instance *inst = ctx->inst; + struct device *dev = &GET_DEV(inst->accel_dev); + struct qat_asym_request *qat_req = + PTR_ALIGN(akcipher_request_ctx(req), 64); + struct icp_qat_fw_pke_request *msg = &qat_req->req; + u8 *vaddr; + int ret; + + if (unlikely(!ctx->n || !ctx->e)) + return -EINVAL; + + if (req->dst_len < ctx->key_sz) { + req->dst_len = ctx->key_sz; + return -EOVERFLOW; + } + memset(msg, '\0', sizeof(*msg)); + ICP_QAT_FW_PKE_HDR_VALID_FLAG_SET(msg->pke_hdr, + ICP_QAT_FW_COMN_REQ_FLAG_SET); + msg->pke_hdr.cd_pars.func_id = qat_rsa_enc_fn_id(ctx->key_sz); + if (unlikely(!msg->pke_hdr.cd_pars.func_id)) + return -EINVAL; + + qat_req->cb = qat_rsa_cb; + qat_req->ctx.rsa = ctx; + qat_req->areq.rsa = req; + msg->pke_hdr.service_type = ICP_QAT_FW_COMN_REQ_CPM_FW_PKE; + msg->pke_hdr.comn_req_flags = + ICP_QAT_FW_COMN_FLAGS_BUILD(QAT_COMN_PTR_TYPE_FLAT, + QAT_COMN_CD_FLD_TYPE_64BIT_ADR); + + qat_req->in.rsa.enc.e = ctx->dma_e; + qat_req->in.rsa.enc.n = ctx->dma_n; + ret = -ENOMEM; + + /* + * src can be of any size in valid range, but HW expects it to be the + * same as modulo n so in case it is different we need to allocate a + * new buf and copy src data. + * In other case we just need to map the user provided buffer. + * Also need to make sure that it is in contiguous buffer. + */ + if (sg_is_last(req->src) && req->src_len == ctx->key_sz) { + qat_req->src_align = NULL; + vaddr = sg_virt(req->src); + } else { + int shift = ctx->key_sz - req->src_len; + + qat_req->src_align = kzalloc(ctx->key_sz, GFP_KERNEL); + if (unlikely(!qat_req->src_align)) + return ret; + + scatterwalk_map_and_copy(qat_req->src_align + shift, req->src, + 0, req->src_len, 0); + vaddr = qat_req->src_align; + } + + qat_req->in.rsa.enc.m = dma_map_single(dev, vaddr, ctx->key_sz, + DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->in.rsa.enc.m))) + goto unmap_src; + + if (sg_is_last(req->dst) && req->dst_len == ctx->key_sz) { + qat_req->dst_align = NULL; + vaddr = sg_virt(req->dst); + } else { + qat_req->dst_align = kzalloc(ctx->key_sz, GFP_KERNEL); + if (unlikely(!qat_req->dst_align)) + goto unmap_src; + vaddr = qat_req->dst_align; + } + + qat_req->out.rsa.enc.c = dma_map_single(dev, vaddr, ctx->key_sz, + DMA_FROM_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->out.rsa.enc.c))) + goto unmap_dst; + + qat_req->in.rsa.in_tab[3] = 0; + qat_req->out.rsa.out_tab[1] = 0; + qat_req->phy_in = dma_map_single(dev, &qat_req->in.rsa.enc.m, + sizeof(qat_req->in.rsa.enc.m), + DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->phy_in))) + goto unmap_dst; + + qat_req->phy_out = dma_map_single(dev, &qat_req->out.rsa.enc.c, + sizeof(qat_req->out.rsa.enc.c), + DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->phy_out))) + goto unmap_in_params; + + msg->pke_mid.src_data_addr = qat_req->phy_in; + msg->pke_mid.dest_data_addr = qat_req->phy_out; + msg->pke_mid.opaque = (u64)(__force long)qat_req; + msg->input_param_count = 3; + msg->output_param_count = 1; + + ret = qat_alg_send_asym_message(qat_req, inst, &req->base); + if (ret == -ENOSPC) + goto unmap_all; + + return ret; + +unmap_all: + if (!dma_mapping_error(dev, qat_req->phy_out)) + dma_unmap_single(dev, qat_req->phy_out, + sizeof(struct qat_rsa_output_params), + DMA_TO_DEVICE); +unmap_in_params: + if (!dma_mapping_error(dev, qat_req->phy_in)) + dma_unmap_single(dev, qat_req->phy_in, + sizeof(struct qat_rsa_input_params), + DMA_TO_DEVICE); +unmap_dst: + if (!dma_mapping_error(dev, qat_req->out.rsa.enc.c)) + dma_unmap_single(dev, qat_req->out.rsa.enc.c, + ctx->key_sz, DMA_FROM_DEVICE); + kfree_sensitive(qat_req->dst_align); +unmap_src: + if (!dma_mapping_error(dev, qat_req->in.rsa.enc.m)) + dma_unmap_single(dev, qat_req->in.rsa.enc.m, ctx->key_sz, + DMA_TO_DEVICE); + kfree_sensitive(qat_req->src_align); + return ret; +} + +static int qat_rsa_dec(struct akcipher_request *req) +{ + struct crypto_akcipher *tfm = crypto_akcipher_reqtfm(req); + struct qat_rsa_ctx *ctx = akcipher_tfm_ctx(tfm); + struct qat_crypto_instance *inst = ctx->inst; + struct device *dev = &GET_DEV(inst->accel_dev); + struct qat_asym_request *qat_req = + PTR_ALIGN(akcipher_request_ctx(req), 64); + struct icp_qat_fw_pke_request *msg = &qat_req->req; + u8 *vaddr; + int ret; + + if (unlikely(!ctx->n || !ctx->d)) + return -EINVAL; + + if (req->dst_len < ctx->key_sz) { + req->dst_len = ctx->key_sz; + return -EOVERFLOW; + } + memset(msg, '\0', sizeof(*msg)); + ICP_QAT_FW_PKE_HDR_VALID_FLAG_SET(msg->pke_hdr, + ICP_QAT_FW_COMN_REQ_FLAG_SET); + msg->pke_hdr.cd_pars.func_id = ctx->crt_mode ? + qat_rsa_dec_fn_id_crt(ctx->key_sz) : + qat_rsa_dec_fn_id(ctx->key_sz); + if (unlikely(!msg->pke_hdr.cd_pars.func_id)) + return -EINVAL; + + qat_req->cb = qat_rsa_cb; + qat_req->ctx.rsa = ctx; + qat_req->areq.rsa = req; + msg->pke_hdr.service_type = ICP_QAT_FW_COMN_REQ_CPM_FW_PKE; + msg->pke_hdr.comn_req_flags = + ICP_QAT_FW_COMN_FLAGS_BUILD(QAT_COMN_PTR_TYPE_FLAT, + QAT_COMN_CD_FLD_TYPE_64BIT_ADR); + + if (ctx->crt_mode) { + qat_req->in.rsa.dec_crt.p = ctx->dma_p; + qat_req->in.rsa.dec_crt.q = ctx->dma_q; + qat_req->in.rsa.dec_crt.dp = ctx->dma_dp; + qat_req->in.rsa.dec_crt.dq = ctx->dma_dq; + qat_req->in.rsa.dec_crt.qinv = ctx->dma_qinv; + } else { + qat_req->in.rsa.dec.d = ctx->dma_d; + qat_req->in.rsa.dec.n = ctx->dma_n; + } + ret = -ENOMEM; + + /* + * src can be of any size in valid range, but HW expects it to be the + * same as modulo n so in case it is different we need to allocate a + * new buf and copy src data. + * In other case we just need to map the user provided buffer. + * Also need to make sure that it is in contiguous buffer. + */ + if (sg_is_last(req->src) && req->src_len == ctx->key_sz) { + qat_req->src_align = NULL; + vaddr = sg_virt(req->src); + } else { + int shift = ctx->key_sz - req->src_len; + + qat_req->src_align = kzalloc(ctx->key_sz, GFP_KERNEL); + if (unlikely(!qat_req->src_align)) + return ret; + + scatterwalk_map_and_copy(qat_req->src_align + shift, req->src, + 0, req->src_len, 0); + vaddr = qat_req->src_align; + } + + qat_req->in.rsa.dec.c = dma_map_single(dev, vaddr, ctx->key_sz, + DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->in.rsa.dec.c))) + goto unmap_src; + + if (sg_is_last(req->dst) && req->dst_len == ctx->key_sz) { + qat_req->dst_align = NULL; + vaddr = sg_virt(req->dst); + } else { + qat_req->dst_align = kzalloc(ctx->key_sz, GFP_KERNEL); + if (unlikely(!qat_req->dst_align)) + goto unmap_src; + vaddr = qat_req->dst_align; + } + qat_req->out.rsa.dec.m = dma_map_single(dev, vaddr, ctx->key_sz, + DMA_FROM_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->out.rsa.dec.m))) + goto unmap_dst; + + if (ctx->crt_mode) + qat_req->in.rsa.in_tab[6] = 0; + else + qat_req->in.rsa.in_tab[3] = 0; + qat_req->out.rsa.out_tab[1] = 0; + qat_req->phy_in = dma_map_single(dev, &qat_req->in.rsa.dec.c, + sizeof(qat_req->in.rsa.dec.c), + DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->phy_in))) + goto unmap_dst; + + qat_req->phy_out = dma_map_single(dev, &qat_req->out.rsa.dec.m, + sizeof(qat_req->out.rsa.dec.m), + DMA_TO_DEVICE); + if (unlikely(dma_mapping_error(dev, qat_req->phy_out))) + goto unmap_in_params; + + msg->pke_mid.src_data_addr = qat_req->phy_in; + msg->pke_mid.dest_data_addr = qat_req->phy_out; + msg->pke_mid.opaque = (u64)(__force long)qat_req; + if (ctx->crt_mode) + msg->input_param_count = 6; + else + msg->input_param_count = 3; + + msg->output_param_count = 1; + + ret = qat_alg_send_asym_message(qat_req, inst, &req->base); + if (ret == -ENOSPC) + goto unmap_all; + + return ret; + +unmap_all: + if (!dma_mapping_error(dev, qat_req->phy_out)) + dma_unmap_single(dev, qat_req->phy_out, + sizeof(struct qat_rsa_output_params), + DMA_TO_DEVICE); +unmap_in_params: + if (!dma_mapping_error(dev, qat_req->phy_in)) + dma_unmap_single(dev, qat_r + +// ... (459 more chars) +``` diff --git a/tasks/csa159/pair_140531/task_prompt.md b/tasks/csa159/pair_140531/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..3af74304cfdee82ba231de1bab91bb34c7a80838 --- /dev/null +++ b/tasks/csa159/pair_140531/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 rollout regressed hard validation and fell below objective gate G6, so successful compilation and trustworthy before/after code verification were not established for the current attempt. +- The relational safety logic lost operand orientation by combining facts for (Sub, Min) and (Min, Sub) without normalization; an unsafe Sub > Min fact could therefore be misread as Sub <= Min and suppress a required report. +- The report condition treated failure to prove B <= A as evidence of vulnerability instead of proving a feasible B > A path, producing a structural superset of the defect and weakening false-positive control. +- Refinement remained feedback_required, diagnostic sharpness was poor with no warnings near changed lines, and process quality remained below threshold despite earlier successful scans. + +### 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 and a semantic score at or above the configured threshold. +- Remain independent of patch anchors, changed line numbers, function names, variable names, and other patch-local hardcoding. + +### Required semantic proof + +- On a feasible intra-function path reaching a write sink, prove that the destination offset's exact reaching definition is an unsigned subtraction A - B and that B > A holds on that path. +- Prove that the destination pointer is based on storage whose tracked allocation extent is symbolically equal to A, so the underflowed displacement is outside the A-byte allocation. +- Prove that the matched call writes through the displaced destination with a transfer length that can be nonzero; do not classify read-only pointer use or arithmetic without a memory write. +- Suppress the report when every sink-reaching path establishes B <= A, including fall-through after a dominating rejecting guard such as if (B > A) return. +- Respect definition order and reassignment so only the subtraction definition that actually reaches the pointer-offset use can participate in the proof. + +### Implementation constraints + +- Use path-sensitive ProgramState facts with callbacks capable of observing unsigned subtraction provenance, binds and invalidation, allocation return extents, branch assumptions, dead symbols, and write calls; suitable CSA hooks include check::PostStmt, check::Bind, check::PostCall, eval::Assume, check::DeadSymbols, and check::PreCall. +- Represent relational facts with explicit operand orientation or normalize reversed comparisons before querying them; Sub > Min must never satisfy a Sub <= Min query. +- Use CSA symbolic values, regions, constraints, and call semantics to connect allocation base, extent, offset, and sink arguments through casts and local stores while preserving path and reassignment order. +- Emit the diagnostic at the write sink that completes the out-of-bounds-write proof, with the relevant base, minuend, and subtrahend marked for path diagnostics. +- Keep analysis intra-function and project-general; interprocedural propagation is unnecessary for the supplied defect. +- Recognize write semantics and argument roles without depending on qat_rsa_enc, qat_rsa_dec, shift, ctx, req, source locations, or the added guard text. + +### Validation checklist + +- Build the checker cleanly against the supplied Clang Static Analyzer API and verify registration, loading, and execution before scanning the target sources. +- Scan the unpatched functions and confirm diagnostics for both qat_rsa_enc and qat_rsa_dec at their scatterwalk_map_and_copy write calls. +- Scan the patched functions and confirm the added req->src_len > ctx->key_sz rejecting guards eliminate those corresponding diagnostics. +- Verify that disappeared diagnostics are confined to the patched functions and that unrelated detections do not disappear. +- Add focused relational tests for B > A, B <= A, reversed operand comparisons, negated comparisons, equality, and short-circuit guards. +- Add reaching-definition tests where the offset local is assigned before use, reassigned before use, assigned only after use, and wrapped in casts. +- Check zero-length, unknown-length, read-only-use, mismatched-allocation-extent, and non-underflow subtraction cases to demonstrate that each missing proof obligation prevents a report. +- Repeat hard validation, code verification, objective gate G6 evaluation, and refinement until refinement is accepted and process quality meets threshold. + +### Avoid and forbidden regressions + +- Do not reuse the failed strategy of reporting merely because B <= A is unproven; require affirmative evidence that B > A is feasible. +- Do not merge mirrored relation masks or treat every LT, LE, GT, GE, or EQ bit as equivalent safety evidence. +- Do not use a whole-function, flow-insensitive assignment map that can associate stale or future subtraction definitions with a sink. +- Do not downgrade to syntax-only or dominance-only matching, because those mechanisms cannot establish the required path relation and reaching definition. +- Do not report generic unguarded unsigned subtraction, pointer arithmetic without a write, read-only sinks, or storage whose extent is unrelated to the minuend. +- Do not introduce source-text matching, changed-line anchors, QAT-specific function or variable names, or other patch-local constants. diff --git a/tasks/csa159/pair_140691/checker_template.cpp b/tasks/csa159/pair_140691/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_140691/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_140691/config.json b/tasks/csa159/pair_140691/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0d0bd0c54c298c16c1ee9cd3f62c8afdcb1ba3c6 --- /dev/null +++ b/tasks/csa159/pair_140691/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "f93431c86b631bbca5614c66f966bf3ddb3c2803", + "after_commit": "f638a84afef3dfe10554c51820c16e39a278c915", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/cf67838c4422eab826679b076dad99f96152b4de/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/cf67838c4422eab826679b076dad99f96152b4de/compile_commands.json", + "changed_files": [ + "net/l2tp/l2tp_ip6.c" + ], + "commit_message": "ipv6: Fix signed integer overflow in l2tp_ip6_sendmsg\n\nWhen len >= INT_MAX - transhdrlen, ulen = len + transhdrlen will be\noverflow. To fix, we can follow what udpv6 does and subtract the\ntranshdrlen from the max.\n\nSigned-off-by: Wang Yufen \nLink: https://lore.kernel.org/r/20220607120028.845916-2-wangyufen@huawei.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_140691/patch.diff b/tasks/csa159/pair_140691/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7438a478e10854bd1818d424deab1fa7f7cde124 --- /dev/null +++ b/tasks/csa159/pair_140691/patch.diff @@ -0,0 +1,22 @@ +diff --git a/net/l2tp/l2tp_ip6.c b/net/l2tp/l2tp_ip6.c +index c6ff8bf9b55f..9dbd801ddb98 100644 +--- a/net/l2tp/l2tp_ip6.c ++++ b/net/l2tp/l2tp_ip6.c +@@ -504,14 +504,15 @@ static int l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) + struct ipcm6_cookie ipc6; + int addr_len = msg->msg_namelen; + int transhdrlen = 4; /* zero session-id */ +- int ulen = len + transhdrlen; ++ int ulen; + int err; + + /* Rough check on arithmetic overflow, + * better check is made in ip6_append_data(). + */ +- if (len > INT_MAX) ++ if (len > INT_MAX - transhdrlen) + return -EMSGSIZE; ++ ulen = len + transhdrlen; + + /* Mirror BSD error message compatibility */ + if (msg->msg_flags & MSG_OOB) \ No newline at end of file diff --git a/tasks/csa159/pair_140691/post_functions.txt b/tasks/csa159/pair_140691/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..e61b49ade6e1f38dee7daec5f76d20122fc5b3db --- /dev/null +++ b/tasks/csa159/pair_140691/post_functions.txt @@ -0,0 +1,171 @@ +### File: net/l2tp/l2tp_ip6.c +```c +static int l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) +{ + struct ipv6_txoptions opt_space; + DECLARE_SOCKADDR(struct sockaddr_l2tpip6 *, lsa, msg->msg_name); + struct in6_addr *daddr, *final_p, final; + struct ipv6_pinfo *np = inet6_sk(sk); + struct ipv6_txoptions *opt_to_free = NULL; + struct ipv6_txoptions *opt = NULL; + struct ip6_flowlabel *flowlabel = NULL; + struct dst_entry *dst = NULL; + struct flowi6 fl6; + struct ipcm6_cookie ipc6; + int addr_len = msg->msg_namelen; + int transhdrlen = 4; /* zero session-id */ + int ulen; + int err; + + /* Rough check on arithmetic overflow, + * better check is made in ip6_append_data(). + */ + if (len > INT_MAX - transhdrlen) + return -EMSGSIZE; + ulen = len + transhdrlen; + + /* Mirror BSD error message compatibility */ + if (msg->msg_flags & MSG_OOB) + return -EOPNOTSUPP; + + /* Get and verify the address */ + memset(&fl6, 0, sizeof(fl6)); + + fl6.flowi6_mark = sk->sk_mark; + fl6.flowi6_uid = sk->sk_uid; + + ipcm6_init(&ipc6); + + if (lsa) { + if (addr_len < SIN6_LEN_RFC2133) + return -EINVAL; + + if (lsa->l2tp_family && lsa->l2tp_family != AF_INET6) + return -EAFNOSUPPORT; + + daddr = &lsa->l2tp_addr; + if (np->sndflow) { + fl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK; + if (fl6.flowlabel & IPV6_FLOWLABEL_MASK) { + flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); + if (IS_ERR(flowlabel)) + return -EINVAL; + } + } + + /* Otherwise it will be difficult to maintain + * sk->sk_dst_cache. + */ + if (sk->sk_state == TCP_ESTABLISHED && + ipv6_addr_equal(daddr, &sk->sk_v6_daddr)) + daddr = &sk->sk_v6_daddr; + + if (addr_len >= sizeof(struct sockaddr_in6) && + lsa->l2tp_scope_id && + ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL) + fl6.flowi6_oif = lsa->l2tp_scope_id; + } else { + if (sk->sk_state != TCP_ESTABLISHED) + return -EDESTADDRREQ; + + daddr = &sk->sk_v6_daddr; + fl6.flowlabel = np->flow_label; + } + + if (fl6.flowi6_oif == 0) + fl6.flowi6_oif = READ_ONCE(sk->sk_bound_dev_if); + + if (msg->msg_controllen) { + opt = &opt_space; + memset(opt, 0, sizeof(struct ipv6_txoptions)); + opt->tot_len = sizeof(struct ipv6_txoptions); + ipc6.opt = opt; + + err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, &ipc6); + if (err < 0) { + fl6_sock_release(flowlabel); + return err; + } + if ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) { + flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); + if (IS_ERR(flowlabel)) + return -EINVAL; + } + if (!(opt->opt_nflen | opt->opt_flen)) + opt = NULL; + } + + if (!opt) { + opt = txopt_get(np); + opt_to_free = opt; + } + if (flowlabel) + opt = fl6_merge_options(&opt_space, flowlabel, opt); + opt = ipv6_fixup_options(&opt_space, opt); + ipc6.opt = opt; + + fl6.flowi6_proto = sk->sk_protocol; + if (!ipv6_addr_any(daddr)) + fl6.daddr = *daddr; + else + fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ + if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) + fl6.saddr = np->saddr; + + final_p = fl6_update_dst(&fl6, opt, &final); + + if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) + fl6.flowi6_oif = np->mcast_oif; + else if (!fl6.flowi6_oif) + fl6.flowi6_oif = np->ucast_oif; + + security_sk_classify_flow(sk, flowi6_to_flowi_common(&fl6)); + + if (ipc6.tclass < 0) + ipc6.tclass = np->tclass; + + fl6.flowlabel = ip6_make_flowinfo(ipc6.tclass, fl6.flowlabel); + + dst = ip6_dst_lookup_flow(sock_net(sk), sk, &fl6, final_p); + if (IS_ERR(dst)) { + err = PTR_ERR(dst); + goto out; + } + + if (ipc6.hlimit < 0) + ipc6.hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst); + + if (ipc6.dontfrag < 0) + ipc6.dontfrag = np->dontfrag; + + if (msg->msg_flags & MSG_CONFIRM) + goto do_confirm; + +back_from_confirm: + lock_sock(sk); + err = ip6_append_data(sk, ip_generic_getfrag, msg, + ulen, transhdrlen, &ipc6, + &fl6, (struct rt6_info *)dst, + msg->msg_flags); + if (err) + ip6_flush_pending_frames(sk); + else if (!(msg->msg_flags & MSG_MORE)) + err = l2tp_ip6_push_pending_frames(sk); + release_sock(sk); +done: + dst_release(dst); +out: + fl6_sock_release(flowlabel); + txopt_put(opt_to_free); + + return err < 0 ? err : len; + +do_confirm: + if (msg->msg_flags & MSG_PROBE) + dst_confirm_neigh(dst, &fl6.daddr); + if (!(msg->msg_flags & MSG_PROBE) || len) + goto back_from_confirm; + err = 0; + goto done; +} +``` diff --git a/tasks/csa159/pair_140691/pre_functions.txt b/tasks/csa159/pair_140691/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a135086f9abf7af8f936047d8a9fbf86ee393b3 --- /dev/null +++ b/tasks/csa159/pair_140691/pre_functions.txt @@ -0,0 +1,170 @@ +### File: net/l2tp/l2tp_ip6.c +```c +static int l2tp_ip6_sendmsg(struct sock *sk, struct msghdr *msg, size_t len) +{ + struct ipv6_txoptions opt_space; + DECLARE_SOCKADDR(struct sockaddr_l2tpip6 *, lsa, msg->msg_name); + struct in6_addr *daddr, *final_p, final; + struct ipv6_pinfo *np = inet6_sk(sk); + struct ipv6_txoptions *opt_to_free = NULL; + struct ipv6_txoptions *opt = NULL; + struct ip6_flowlabel *flowlabel = NULL; + struct dst_entry *dst = NULL; + struct flowi6 fl6; + struct ipcm6_cookie ipc6; + int addr_len = msg->msg_namelen; + int transhdrlen = 4; /* zero session-id */ + int ulen = len + transhdrlen; + int err; + + /* Rough check on arithmetic overflow, + * better check is made in ip6_append_data(). + */ + if (len > INT_MAX) + return -EMSGSIZE; + + /* Mirror BSD error message compatibility */ + if (msg->msg_flags & MSG_OOB) + return -EOPNOTSUPP; + + /* Get and verify the address */ + memset(&fl6, 0, sizeof(fl6)); + + fl6.flowi6_mark = sk->sk_mark; + fl6.flowi6_uid = sk->sk_uid; + + ipcm6_init(&ipc6); + + if (lsa) { + if (addr_len < SIN6_LEN_RFC2133) + return -EINVAL; + + if (lsa->l2tp_family && lsa->l2tp_family != AF_INET6) + return -EAFNOSUPPORT; + + daddr = &lsa->l2tp_addr; + if (np->sndflow) { + fl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK; + if (fl6.flowlabel & IPV6_FLOWLABEL_MASK) { + flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); + if (IS_ERR(flowlabel)) + return -EINVAL; + } + } + + /* Otherwise it will be difficult to maintain + * sk->sk_dst_cache. + */ + if (sk->sk_state == TCP_ESTABLISHED && + ipv6_addr_equal(daddr, &sk->sk_v6_daddr)) + daddr = &sk->sk_v6_daddr; + + if (addr_len >= sizeof(struct sockaddr_in6) && + lsa->l2tp_scope_id && + ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL) + fl6.flowi6_oif = lsa->l2tp_scope_id; + } else { + if (sk->sk_state != TCP_ESTABLISHED) + return -EDESTADDRREQ; + + daddr = &sk->sk_v6_daddr; + fl6.flowlabel = np->flow_label; + } + + if (fl6.flowi6_oif == 0) + fl6.flowi6_oif = READ_ONCE(sk->sk_bound_dev_if); + + if (msg->msg_controllen) { + opt = &opt_space; + memset(opt, 0, sizeof(struct ipv6_txoptions)); + opt->tot_len = sizeof(struct ipv6_txoptions); + ipc6.opt = opt; + + err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, &ipc6); + if (err < 0) { + fl6_sock_release(flowlabel); + return err; + } + if ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) { + flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); + if (IS_ERR(flowlabel)) + return -EINVAL; + } + if (!(opt->opt_nflen | opt->opt_flen)) + opt = NULL; + } + + if (!opt) { + opt = txopt_get(np); + opt_to_free = opt; + } + if (flowlabel) + opt = fl6_merge_options(&opt_space, flowlabel, opt); + opt = ipv6_fixup_options(&opt_space, opt); + ipc6.opt = opt; + + fl6.flowi6_proto = sk->sk_protocol; + if (!ipv6_addr_any(daddr)) + fl6.daddr = *daddr; + else + fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ + if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) + fl6.saddr = np->saddr; + + final_p = fl6_update_dst(&fl6, opt, &final); + + if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) + fl6.flowi6_oif = np->mcast_oif; + else if (!fl6.flowi6_oif) + fl6.flowi6_oif = np->ucast_oif; + + security_sk_classify_flow(sk, flowi6_to_flowi_common(&fl6)); + + if (ipc6.tclass < 0) + ipc6.tclass = np->tclass; + + fl6.flowlabel = ip6_make_flowinfo(ipc6.tclass, fl6.flowlabel); + + dst = ip6_dst_lookup_flow(sock_net(sk), sk, &fl6, final_p); + if (IS_ERR(dst)) { + err = PTR_ERR(dst); + goto out; + } + + if (ipc6.hlimit < 0) + ipc6.hlimit = ip6_sk_dst_hoplimit(np, &fl6, dst); + + if (ipc6.dontfrag < 0) + ipc6.dontfrag = np->dontfrag; + + if (msg->msg_flags & MSG_CONFIRM) + goto do_confirm; + +back_from_confirm: + lock_sock(sk); + err = ip6_append_data(sk, ip_generic_getfrag, msg, + ulen, transhdrlen, &ipc6, + &fl6, (struct rt6_info *)dst, + msg->msg_flags); + if (err) + ip6_flush_pending_frames(sk); + else if (!(msg->msg_flags & MSG_MORE)) + err = l2tp_ip6_push_pending_frames(sk); + release_sock(sk); +done: + dst_release(dst); +out: + fl6_sock_release(flowlabel); + txopt_put(opt_to_free); + + return err < 0 ? err : len; + +do_confirm: + if (msg->msg_flags & MSG_PROBE) + dst_confirm_neigh(dst, &fl6.daddr); + if (!(msg->msg_flags & MSG_PROBE) || len) + goto back_from_confirm; + err = 0; + goto done; +} +``` diff --git a/tasks/csa159/pair_140691/task_prompt.md b/tasks/csa159/pair_140691/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..8f37a2a24f375e2c60c0f8efd5ee328a9303a53b --- /dev/null +++ b/tasks/csa159/pair_140691/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: `control_flow` + +### Current failure diagnosis + +- The rollout was rejected because its semantic mechanism was judged inadequate despite producing the expected differential scan results. +- The checker reported at the narrowing conversion before establishing that the converted value survived later rejection paths and reached the security-relevant call. +- Its report condition remained a superset of the vulnerability by treating paths with len > INT_MAX as reportable even though those paths are rejected before use. +- The prior semantic contract requires proving both range feasibility and live reachability at the use site; satisfying only the local conversion pattern is insufficient. + +### Preserve from prior rollouts + +- Retain successful checker compilation, before/after validation, and code verification. +- Retain objective eligibility under gate G6. +- Retain an accepted or clean refinement outcome. +- Retain at least the previously adequate path-sensitive CSA capability. +- Retain the configured semantic-score threshold and process-quality threshold. +- Remain independent of patch anchors, function names, variable names, line numbers, patch text, and unique patch literals. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Establish that a wider unsigned addition is narrowed to a narrower signed integer and that its mathematical value can exceed the destination signed maximum. +- Evaluate the out-of-range condition using the ProgramState constraints present at the eventual use, including constraints established by preceding guards. +- Prove that the narrowed value is live on the analyzed path and is actually supplied as a call argument to the relevant downstream operation. +- Exclude paths rejected before the downstream use, including paths satisfying len > INT_MAX in the vulnerable ordering. +- Prove the patched ordering safe when the guard establishes len <= INT_MAX - transhdrlen before the conversion and call. +- Treat the unsigned addition as non-wrapping for this defect and focus the proof on lossy signed narrowing. + +### Implementation constraints + +- Use path-sensitive CSA state and constraint queries; local AST shape or guard-text matching alone is insufficient. +- Use a candidate-discovery callback for the implicit integral narrowing conversion and a later call/use callback for reachability and reporting, such as PostStmt and PreCall. +- Track enough symbolic identity and conversion facts in ProgramState to match the converted value through ordinary intervening storage and casts to the call argument. +- Perform the overflow-feasibility query in the call-site state rather than only at the conversion site. +- Report at the actual security-relevant call/use location while retaining a source range or path note identifying the narrowing conversion. +- Keep scope project-general for direct unsigned-addition to narrower-signed-conversion cases whose result reaches a call argument; do not require cross-procedure propagation. +- Avoid dependence on the specific l2tp function, ip6_append_data name, parameter names, or the constant 4. + +### Validation checklist + +- Compile the new checker successfully and run code verification. +- Scan both the vulnerable and patched source versions with identical checker configuration. +- Confirm diagnostics are present for the vulnerable version and absent for the patched version. +- Confirm every vulnerable diagnostic is in the patched function or a precise relevant span and that no unrelated files or functions produce warnings. +- Confirm the diagnostic location is the downstream length use or call argument, with the narrowing conversion identified as the responsible arithmetic. +- Exercise a path where len <= INT_MAX but len + transhdrlen exceeds INT_MAX and reaches the call. +- Exercise a path where len > INT_MAX is rejected before the call and verify it is not reported. +- Exercise the patched guard len <= INT_MAX - transhdrlen and verify the constraint query makes the unsafe state infeasible. + +### Avoid and forbidden regressions + +- Do not report solely from a PostStmt conversion callback before checking later control flow and use. +- Do not treat the unsigned addition itself as the defect without proving the subsequent signed narrowing and security-relevant use. +- Do not infer safety or vulnerability from syntactic proximity, dominance of any guard, or a guard-shaped statement without a numeric constraint proof. +- Do not report values that are invalid only on paths terminated before the downstream call. +- Do not replace ProgramState feasibility with source-text matching, fixed line locations, or patch-specific constants. +- Do not broaden the checker into cross-procedure dataflow when the supplied evidence requires only intra-procedural path-sensitive reasoning. +- Do not regress compilation, differential before/after behavior, refinement acceptance, scope sparsity, or anchor-free and hardcoding-free status. diff --git a/tasks/csa159/pair_141072/checker_template.cpp b/tasks/csa159/pair_141072/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_141072/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_141072/config.json b/tasks/csa159/pair_141072/config.json new file mode 100644 index 0000000000000000000000000000000000000000..ff8ef731a0d2b681516b583c4a2315601be3e1c2 --- /dev/null +++ b/tasks/csa159/pair_141072/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "e39c600049d0822284da2cef3bd7ced40dc3524f", + "after_commit": "b3236a64ddd125a455ef5b5316c1b9051b732974", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/f2906aa863381afb0015a9eb7fefad885d4e5a56/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/f2906aa863381afb0015a9eb7fefad885d4e5a56/compile_commands.json", + "changed_files": [ + "drivers/infiniband/hw/qedr/verbs.c" + ], + "commit_message": "RDMA/qedr: Fix potential memory leak in __qedr_alloc_mr()\n\n__qedr_alloc_mr() allocates a memory chunk for \"mr->info.pbl_table\" with\ninit_mr_info(). When rdma_alloc_tid() and rdma_register_tid() fail, \"mr\"\nis released while \"mr->info.pbl_table\" is not released, which will lead\nto a memory leak.\n\nWe should release the \"mr->info.pbl_table\" with qedr_free_pbl() when error\noccurs to fix the memory leak.\n\nFixes: e0290cce6ac0 (\"qedr: Add support for memory registeration verbs\")\nLink: https://lore.kernel.org/r/20220714061505.2342759-1-niejianglei2021@163.com\nSigned-off-by: Jianglei Nie \nAcked-by: Michal Kalderon \nSigned-off-by: Leon Romanovsky ", + "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_141072/patch.diff b/tasks/csa159/pair_141072/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5493bffee419a5b7ba6368476e27fa8cee47b0aa --- /dev/null +++ b/tasks/csa159/pair_141072/patch.diff @@ -0,0 +1,34 @@ +diff --git a/drivers/infiniband/hw/qedr/verbs.c b/drivers/infiniband/hw/qedr/verbs.c +index f0f43b6db89e..3ecb472c9217 100644 +--- a/drivers/infiniband/hw/qedr/verbs.c ++++ b/drivers/infiniband/hw/qedr/verbs.c +@@ -3082,7 +3082,7 @@ static struct qedr_mr *__qedr_alloc_mr(struct ib_pd *ibpd, + else + DP_ERR(dev, "roce alloc tid returned error %d\n", rc); + +- goto err0; ++ goto err1; + } + + /* Index only, 18 bit long, lkey = itid << 8 | key */ +@@ -3106,7 +3106,7 @@ static struct qedr_mr *__qedr_alloc_mr(struct ib_pd *ibpd, + rc = dev->ops->rdma_register_tid(dev->rdma_ctx, &mr->hw_mr); + if (rc) { + DP_ERR(dev, "roce register tid returned an error %d\n", rc); +- goto err1; ++ goto err2; + } + + mr->ibmr.lkey = mr->hw_mr.itid << 8 | mr->hw_mr.key; +@@ -3115,8 +3115,10 @@ static struct qedr_mr *__qedr_alloc_mr(struct ib_pd *ibpd, + DP_DEBUG(dev, QEDR_MSG_MR, "alloc frmr: %x\n", mr->ibmr.lkey); + return mr; + +-err1: ++err2: + dev->ops->rdma_free_tid(dev->rdma_ctx, mr->hw_mr.itid); ++err1: ++ qedr_free_pbl(dev, &mr->info.pbl_info, mr->info.pbl_table); + err0: + kfree(mr); + return ERR_PTR(rc); \ No newline at end of file diff --git a/tasks/csa159/pair_141072/post_functions.txt b/tasks/csa159/pair_141072/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..38bb1664850046c0e30626bc1a6fa008d6c48567 --- /dev/null +++ b/tasks/csa159/pair_141072/post_functions.txt @@ -0,0 +1,74 @@ +### File: drivers/infiniband/hw/qedr/verbs.c +```c +static struct qedr_mr *__qedr_alloc_mr(struct ib_pd *ibpd, + int max_page_list_len) +{ + struct qedr_pd *pd = get_qedr_pd(ibpd); + struct qedr_dev *dev = get_qedr_dev(ibpd->device); + struct qedr_mr *mr; + int rc = -ENOMEM; + + DP_DEBUG(dev, QEDR_MSG_MR, + "qedr_alloc_frmr pd = %d max_page_list_len= %d\n", pd->pd_id, + max_page_list_len); + + mr = kzalloc(sizeof(*mr), GFP_KERNEL); + if (!mr) + return ERR_PTR(rc); + + mr->dev = dev; + mr->type = QEDR_MR_FRMR; + + rc = init_mr_info(dev, &mr->info, max_page_list_len, 1); + if (rc) + goto err0; + + rc = dev->ops->rdma_alloc_tid(dev->rdma_ctx, &mr->hw_mr.itid); + if (rc) { + if (rc == -EINVAL) + DP_ERR(dev, "Out of MR resources\n"); + else + DP_ERR(dev, "roce alloc tid returned error %d\n", rc); + + goto err1; + } + + /* Index only, 18 bit long, lkey = itid << 8 | key */ + mr->hw_mr.tid_type = QED_RDMA_TID_FMR; + mr->hw_mr.key = 0; + mr->hw_mr.pd = pd->pd_id; + mr->hw_mr.local_read = 1; + mr->hw_mr.local_write = 0; + mr->hw_mr.remote_read = 0; + mr->hw_mr.remote_write = 0; + mr->hw_mr.remote_atomic = 0; + mr->hw_mr.mw_bind = false; + mr->hw_mr.pbl_ptr = 0; + mr->hw_mr.pbl_two_level = mr->info.pbl_info.two_layered; + mr->hw_mr.pbl_page_size_log = ilog2(mr->info.pbl_info.pbl_size); + mr->hw_mr.length = 0; + mr->hw_mr.vaddr = 0; + mr->hw_mr.phy_mr = true; + mr->hw_mr.dma_mr = false; + + rc = dev->ops->rdma_register_tid(dev->rdma_ctx, &mr->hw_mr); + if (rc) { + DP_ERR(dev, "roce register tid returned an error %d\n", rc); + goto err2; + } + + mr->ibmr.lkey = mr->hw_mr.itid << 8 | mr->hw_mr.key; + mr->ibmr.rkey = mr->ibmr.lkey; + + DP_DEBUG(dev, QEDR_MSG_MR, "alloc frmr: %x\n", mr->ibmr.lkey); + return mr; + +err2: + dev->ops->rdma_free_tid(dev->rdma_ctx, mr->hw_mr.itid); +err1: + qedr_free_pbl(dev, &mr->info.pbl_info, mr->info.pbl_table); +err0: + kfree(mr); + return ERR_PTR(rc); +} +``` diff --git a/tasks/csa159/pair_141072/pre_functions.txt b/tasks/csa159/pair_141072/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..7c7f1e58d8745e672385e6323e3b51f92826ccb9 --- /dev/null +++ b/tasks/csa159/pair_141072/pre_functions.txt @@ -0,0 +1,88 @@ +### File: drivers/infiniband/hw/qedr/verbs.c +```c +static struct qedr_mr *__qedr_alloc_mr(struct ib_pd *ibpd, + int max_page_list_len) +{ + struct qedr_pd *pd = get_qedr_pd(ibpd); + struct qedr_dev *dev = get_qedr_dev(ibpd->device); + struct qedr_mr *mr; + int rc = -ENOMEM; + + DP_DEBUG(dev, QEDR_MSG_MR, + "qedr_alloc_frmr pd = %d max_page_list_len= %d\n", pd->pd_id, + max_page_list_len); + + mr = kzalloc(sizeof(*mr), GFP_KERNEL); + if (!mr) + return ERR_PTR(rc); + + mr->dev = dev; + mr->type = QEDR_MR_FRMR; + + rc = init_mr_info(dev, &mr->info, max_page_list_len, 1); + if (rc) + goto err0; + + rc = dev->ops->rdma_alloc_tid(dev->rdma_ctx, &mr->hw_mr.itid); + if (rc) { + if (rc == -EINVAL) + DP_ERR(dev, "Out of MR resources\n"); + else + DP_ERR(dev, "roce alloc tid returned error %d\n", rc); + + goto err0; + } + + /* Index only, 18 bit long, lkey = itid << 8 | key */ + mr->hw_mr.tid_type = QED_RDMA_TID_FMR; + mr->hw_mr.key = 0; + mr->hw_mr.pd = pd->pd_id; + mr->hw_mr.local_read = 1; + mr->hw_mr.local_write = 0; + mr->hw_mr.remote_read = 0; + mr->hw_mr.remote_write = 0; + mr->hw_mr.remote_atomic = 0; + mr->hw_mr.mw_bind = false; + mr->hw_mr.pbl_ptr = 0; + mr->hw_mr.pbl_two_level = mr->info.pbl_info.two_layered; + mr->hw_mr.pbl_page_size_log = ilog2(mr->info.pbl_info.pbl_size); + mr->hw_mr.length = 0; + mr->hw_mr.vaddr = 0; + mr->hw_mr.phy_mr = true; + mr->hw_mr.dma_mr = false; + + rc = dev->ops->rdma_register_tid(dev->rdma_ctx, &mr->hw_mr); + if (rc) { + DP_ERR(dev, "roce register tid returned an error %d\n", rc); + goto err1; + } + + mr->ibmr.lkey = mr->hw_mr.itid << 8 | mr->hw_mr.key; + mr->ibmr.rkey = mr->ibmr.lkey; + + DP_DEBUG(dev, QEDR_MSG_MR, "alloc frmr: %x\n", mr->ibmr.lkey); + return mr; + +err1: + dev->ops->rdma_free_tid(dev->rdma_ctx, mr->hw_mr.itid); +err0: + kfree(mr); + return ERR_PTR(rc); +} + +struct ib_mr *qedr_alloc_mr(struct ib_pd *ibpd, enum ib_mr_type mr_type, + u32 max_num_sg) +{ + struct qedr_mr *mr; + + if (mr_type != IB_MR_TYPE_MEM_REG) + return ERR_PTR(-EINVAL); + + mr = __qedr_alloc_mr(ibpd, max_num_sg); + + if (IS_ERR(mr)) + return ERR_PTR(-EINVAL); + + return &mr->ibmr; +} +``` diff --git a/tasks/csa159/pair_141072/task_prompt.md b/tasks/csa159/pair_141072/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..8292e8581e2e3e0d0b4249f8834a1c5677ca70b8 --- /dev/null +++ b/tasks/csa159/pair_141072/task_prompt.md @@ -0,0 +1,371 @@ +# 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 independent rollout compiled and scan_before.sh ran, but n_buggy=0 and n_patched=0, so hard_validation, objective_gate (G3: no diagnostics), and cross-validation all failed. +- Acquire was modeled only by path-sensitive PostCall assume() on init_mr_info's return SVal; unknown/undef returns aborted tracking, so the kfree sink never saw an owned PBL and emitted nothing. +- Refinement was not run, and semantic_mechanism/semantic_score stayed unavailable because no acquire-success-to-kfree relation was ever witnessed on the unpatched CFG. +- Opaque dev->ops->rdma_alloc_tid/rdma_register_tid calls were treated as the way to reach the leaking gotos; the analyzer did not have to explore those exploded-graph splits for the skip of qedr_free_pbl to be visible in the function CFG. + +### Preserve from prior rollouts + +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. +- Keep matching on the stable qedr PBL API pair init_mr_info (acquire into the container info) and qedr_free_pbl (release) plus kfree of that container, not on CVE hunk lines or the patch-only labels err0/err1/err2. + +### Required semantic proof + +- After init_mr_info(dev, &mr->info, ...) takes the success successor, mr owns mr->info.pbl_table; any CFG path from that successor to kfree(mr) that does not call qedr_free_pbl(dev, &mr->info.pbl_info, mr->info.pbl_table) is a CWE-401 leak. +- Unpatched __qedr_alloc_mr sends rdma_alloc_tid failure and rdma_register_tid failure to kfree(mr) without qedr_free_pbl; the patch retargets those paths so qedr_free_pbl precedes kfree. +- Returning mr on the success path is not a leak; only paths that free the container after a successful acquire require the release. +- qedr_free_pbl elsewhere in the same TU (or on a disjoint CFG path) does not make a kfree safe; the release must occur on the acquire-success-to-kfree path under test. + +### Implementation constraints + +- Implement with checkASTCodeBody (or equivalent) over the function CFG: reachability from the init_mr_info success successor to kfree, and whether qedr_free_pbl lies on that path or dominates the sink. +- Bind the container from init_mr_info argument 1 (&container->info) and the immediately following zero/non-zero check on its return; do not require a modeled symbolic return value. +- Report at kfree of that container or at the goto/cleanup block that reaches kfree without qedr_free_pbl; keep the diagnostic inside the allocating function's body. +- Treat rdma_alloc_tid and rdma_register_tid only as CFG branch points whose failure successors reach the sink; do not require inlining or conservative eval of those function-pointer callees. +- Scope is project-general for the init_mr_info/qedr_free_pbl pair in the qedr driver; do not gate detection on the identifier __qedr_alloc_mr or on patched line numbers. +- Do not report when init_mr_info already failed (ownership never taken) or when qedr_free_pbl dominates every acquire-success path that reaches kfree. + +### Validation checklist + +- Plugin must compile and load; scan_before on unpatched drivers/infiniband/hw/qedr/verbs.c must produce n_buggy >= 1 in __qedr_alloc_mr. +- The before_commit diagnostic must land at kfree(mr) or the error-path cleanup/goto that skips qedr_free_pbl after successful init_mr_info, inside drivers/infiniband/hw/qedr/verbs.c::__qedr_alloc_mr and near the changed span. +- scan_after on the patched function must satisfy n_patched < n_buggy and n_patched < 50, with the leak gone once qedr_free_pbl precedes kfree on those error paths. +- A sibling that already releases on every acquire-success-to-kfree path (qedr_reg_user_mr) must stay clean. +- Reconfirm hardcoding_free and anchor_free: no patch line numbers, hunk literals, or err0/err1/err2 names in the checker. + +### Avoid and forbidden regressions + +- Do not rebuild a ProgramState map from PostCall assume(init_mr_info ret==0) plus PreCall kfree lookup; that strategy yielded zero findings. +- Do not drop the acquire when init_mr_info's return SVal is unknown; the subsequent if (rc) CFG already distinguishes success from failure. +- Do not require MemRegion/getBaseRegion identity among &mr->info, &mr->info.pbl_info, and mr before relating acquire, release, and kfree. +- Do not reduce the property to function-level presence or absence of a qedr_free_pbl call. +- Do not wait for exploded-graph splits through opaque ops->rdma_* calls to discover the leaking gotos. +- Do not use llvm.errs tracing or SuppressOnSink as a stand-in for a CFG-local report at the leak sink. diff --git a/tasks/csa159/pair_141289/checker_template.cpp b/tasks/csa159/pair_141289/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_141289/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_141289/config.json b/tasks/csa159/pair_141289/config.json new file mode 100644 index 0000000000000000000000000000000000000000..8feade6d42b1027acb119a03d9dc9f18062d05ed --- /dev/null +++ b/tasks/csa159/pair_141289/config.json @@ -0,0 +1,20 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "deee93d13d385103205879a8a0915036ecd83261", + "after_commit": "3124d320c22f3f4388d9ac5c8f37eaad0cefd6b1", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/88e500affe72fb704c4f201974b5199ca6f51e6c/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/88e500affe72fb704c4f201974b5199ca6f51e6c/compile_commands.json", + "changed_files": [ + "drivers/bluetooth/hci_ldisc.c", + "drivers/bluetooth/hci_serdev.c" + ], + "commit_message": "Bluetooth: hci_{ldisc,serdev}: check percpu_init_rwsem() failure\n\nsyzbot is reporting NULL pointer dereference at hci_uart_tty_close() [1],\nfor rcu_sync_enter() is called without rcu_sync_init() due to\nhci_uart_tty_open() ignoring percpu_init_rwsem() failure.\n\nWhile we are at it, fix that hci_uart_register_device() ignores\npercpu_init_rwsem() failure and hci_uart_unregister_device() does not\ncall percpu_free_rwsem().\n\nLink: https://syzkaller.appspot.com/bug?extid=576dfca25381fb6fbc5f [1]\nReported-by: syzbot \nSigned-off-by: Tetsuo Handa \nFixes: 67d2f8781b9f00d1 (\"Bluetooth: hci_ldisc: Allow sleeping while proto locks are held.\")\nFixes: d73e172816652772 (\"Bluetooth: hci_serdev: Init hci_uart proto_lock to avoid oops\")\nSigned-off-by: Luiz Augusto von Dentz ", + "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_141289/patch.diff b/tasks/csa159/pair_141289/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3ec33129969984621a8e11c9813452e95548e9c1 --- /dev/null +++ b/tasks/csa159/pair_141289/patch.diff @@ -0,0 +1,61 @@ +diff --git a/drivers/bluetooth/hci_ldisc.c b/drivers/bluetooth/hci_ldisc.c +index f537673ede17..865112e96ff9 100644 +--- a/drivers/bluetooth/hci_ldisc.c ++++ b/drivers/bluetooth/hci_ldisc.c +@@ -493,6 +493,11 @@ static int hci_uart_tty_open(struct tty_struct *tty) + BT_ERR("Can't allocate control structure"); + return -ENFILE; + } ++ if (percpu_init_rwsem(&hu->proto_lock)) { ++ BT_ERR("Can't allocate semaphore structure"); ++ kfree(hu); ++ return -ENOMEM; ++ } + + tty->disc_data = hu; + hu->tty = tty; +@@ -505,8 +510,6 @@ static int hci_uart_tty_open(struct tty_struct *tty) + INIT_WORK(&hu->init_ready, hci_uart_init_work); + INIT_WORK(&hu->write_work, hci_uart_write_work); + +- percpu_init_rwsem(&hu->proto_lock); +- + /* Flush any pending characters in the driver */ + tty_driver_flush_buffer(tty); + +diff --git a/drivers/bluetooth/hci_serdev.c b/drivers/bluetooth/hci_serdev.c +index c0e5f42ec6b7..f16fd79bc02b 100644 +--- a/drivers/bluetooth/hci_serdev.c ++++ b/drivers/bluetooth/hci_serdev.c +@@ -310,11 +310,12 @@ int hci_uart_register_device(struct hci_uart *hu, + + serdev_device_set_client_ops(hu->serdev, &hci_serdev_client_ops); + ++ if (percpu_init_rwsem(&hu->proto_lock)) ++ return -ENOMEM; ++ + err = serdev_device_open(hu->serdev); + if (err) +- return err; +- +- percpu_init_rwsem(&hu->proto_lock); ++ goto err_rwsem; + + err = p->open(hu); + if (err) +@@ -389,6 +390,8 @@ int hci_uart_register_device(struct hci_uart *hu, + p->close(hu); + err_open: + serdev_device_close(hu->serdev); ++err_rwsem: ++ percpu_free_rwsem(&hu->proto_lock); + return err; + } + EXPORT_SYMBOL_GPL(hci_uart_register_device); +@@ -410,5 +413,6 @@ void hci_uart_unregister_device(struct hci_uart *hu) + clear_bit(HCI_UART_PROTO_READY, &hu->flags); + serdev_device_close(hu->serdev); + } ++ percpu_free_rwsem(&hu->proto_lock); + } + EXPORT_SYMBOL_GPL(hci_uart_unregister_device); \ No newline at end of file diff --git a/tasks/csa159/pair_141289/post_functions.txt b/tasks/csa159/pair_141289/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..f25b70900b597590cc3b4f1d7bddfbccd32be6c9 --- /dev/null +++ b/tasks/csa159/pair_141289/post_functions.txt @@ -0,0 +1,163 @@ +### File: drivers/bluetooth/hci_ldisc.c +```c +static int hci_uart_tty_open(struct tty_struct *tty) +{ + struct hci_uart *hu; + + BT_DBG("tty %p", tty); + + if (!capable(CAP_NET_ADMIN)) + return -EPERM; + + /* Error if the tty has no write op instead of leaving an exploitable + * hole + */ + if (tty->ops->write == NULL) + return -EOPNOTSUPP; + + hu = kzalloc(sizeof(struct hci_uart), GFP_KERNEL); + if (!hu) { + BT_ERR("Can't allocate control structure"); + return -ENFILE; + } + if (percpu_init_rwsem(&hu->proto_lock)) { + BT_ERR("Can't allocate semaphore structure"); + kfree(hu); + return -ENOMEM; + } + + tty->disc_data = hu; + hu->tty = tty; + tty->receive_room = 65536; + + /* disable alignment support by default */ + hu->alignment = 1; + hu->padding = 0; + + INIT_WORK(&hu->init_ready, hci_uart_init_work); + INIT_WORK(&hu->write_work, hci_uart_write_work); + + /* Flush any pending characters in the driver */ + tty_driver_flush_buffer(tty); + + return 0; +} +``` + +### File: drivers/bluetooth/hci_serdev.c +```c +int hci_uart_register_device(struct hci_uart *hu, + const struct hci_uart_proto *p) +{ + int err; + struct hci_dev *hdev; + + BT_DBG(""); + + serdev_device_set_client_ops(hu->serdev, &hci_serdev_client_ops); + + if (percpu_init_rwsem(&hu->proto_lock)) + return -ENOMEM; + + err = serdev_device_open(hu->serdev); + if (err) + goto err_rwsem; + + err = p->open(hu); + if (err) + goto err_open; + + hu->proto = p; + set_bit(HCI_UART_PROTO_READY, &hu->flags); + + /* Initialize and register HCI device */ + hdev = hci_alloc_dev(); + if (!hdev) { + BT_ERR("Can't allocate HCI device"); + err = -ENOMEM; + goto err_alloc; + } + + hu->hdev = hdev; + + hdev->bus = HCI_UART; + hci_set_drvdata(hdev, hu); + + INIT_WORK(&hu->init_ready, hci_uart_init_work); + INIT_WORK(&hu->write_work, hci_uart_write_work); + + /* Only when vendor specific setup callback is provided, consider + * the manufacturer information valid. This avoids filling in the + * value for Ericsson when nothing is specified. + */ + if (hu->proto->setup) + hdev->manufacturer = hu->proto->manufacturer; + + hdev->open = hci_uart_open; + hdev->close = hci_uart_close; + hdev->flush = hci_uart_flush; + hdev->send = hci_uart_send_frame; + hdev->setup = hci_uart_setup; + if (!hdev->wakeup) + hdev->wakeup = hci_uart_wakeup; + SET_HCIDEV_DEV(hdev, &hu->serdev->dev); + + if (test_bit(HCI_UART_NO_SUSPEND_NOTIFIER, &hu->flags)) + set_bit(HCI_QUIRK_NO_SUSPEND_NOTIFIER, &hdev->quirks); + + if (test_bit(HCI_UART_RAW_DEVICE, &hu->hdev_flags)) + set_bit(HCI_QUIRK_RAW_DEVICE, &hdev->quirks); + + if (test_bit(HCI_UART_EXT_CONFIG, &hu->hdev_flags)) + set_bit(HCI_QUIRK_EXTERNAL_CONFIG, &hdev->quirks); + + if (test_bit(HCI_UART_CREATE_AMP, &hu->hdev_flags)) + hdev->dev_type = HCI_AMP; + else + hdev->dev_type = HCI_PRIMARY; + + if (test_bit(HCI_UART_INIT_PENDING, &hu->hdev_flags)) + return 0; + + if (hci_register_dev(hdev) < 0) { + BT_ERR("Can't register HCI device"); + err = -ENODEV; + goto err_register; + } + + set_bit(HCI_UART_REGISTERED, &hu->flags); + + return 0; + +err_register: + hci_free_dev(hdev); +err_alloc: + clear_bit(HCI_UART_PROTO_READY, &hu->flags); + p->close(hu); +err_open: + serdev_device_close(hu->serdev); +err_rwsem: + percpu_free_rwsem(&hu->proto_lock); + return err; +} + +void hci_uart_unregister_device(struct hci_uart *hu) +{ + struct hci_dev *hdev = hu->hdev; + + cancel_work_sync(&hu->init_ready); + if (test_bit(HCI_UART_REGISTERED, &hu->flags)) + hci_unregister_dev(hdev); + hci_free_dev(hdev); + + cancel_work_sync(&hu->write_work); + + hu->proto->close(hu); + + if (test_bit(HCI_UART_PROTO_READY, &hu->flags)) { + clear_bit(HCI_UART_PROTO_READY, &hu->flags); + serdev_device_close(hu->serdev); + } + percpu_free_rwsem(&hu->proto_lock); +} +``` diff --git a/tasks/csa159/pair_141289/pre_functions.txt b/tasks/csa159/pair_141289/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..236140b23c6cccbdc463cd6926932ec10e674c1c --- /dev/null +++ b/tasks/csa159/pair_141289/pre_functions.txt @@ -0,0 +1,186 @@ +### File: drivers/bluetooth/hci_ldisc.c +```c +static int hci_uart_tty_open(struct tty_struct *tty) +{ + struct hci_uart *hu; + + BT_DBG("tty %p", tty); + + if (!capable(CAP_NET_ADMIN)) + return -EPERM; + + /* Error if the tty has no write op instead of leaving an exploitable + * hole + */ + if (tty->ops->write == NULL) + return -EOPNOTSUPP; + + hu = kzalloc(sizeof(struct hci_uart), GFP_KERNEL); + if (!hu) { + BT_ERR("Can't allocate control structure"); + return -ENFILE; + } + + tty->disc_data = hu; + hu->tty = tty; + tty->receive_room = 65536; + + /* disable alignment support by default */ + hu->alignment = 1; + hu->padding = 0; + + INIT_WORK(&hu->init_ready, hci_uart_init_work); + INIT_WORK(&hu->write_work, hci_uart_write_work); + + percpu_init_rwsem(&hu->proto_lock); + + /* Flush any pending characters in the driver */ + tty_driver_flush_buffer(tty); + + return 0; +} +``` + +### File: drivers/bluetooth/hci_serdev.c +```c +int hci_uart_register_device(struct hci_uart *hu, + const struct hci_uart_proto *p) +{ + int err; + struct hci_dev *hdev; + + BT_DBG(""); + + serdev_device_set_client_ops(hu->serdev, &hci_serdev_client_ops); + + err = serdev_device_open(hu->serdev); + if (err) + return err; + + percpu_init_rwsem(&hu->proto_lock); + + err = p->open(hu); + if (err) + goto err_open; + + hu->proto = p; + set_bit(HCI_UART_PROTO_READY, &hu->flags); + + /* Initialize and register HCI device */ + hdev = hci_alloc_dev(); + if (!hdev) { + BT_ERR("Can't allocate HCI device"); + err = -ENOMEM; + goto err_alloc; + } + + hu->hdev = hdev; + + hdev->bus = HCI_UART; + hci_set_drvdata(hdev, hu); + + INIT_WORK(&hu->init_ready, hci_uart_init_work); + INIT_WORK(&hu->write_work, hci_uart_write_work); + + /* Only when vendor specific setup callback is provided, consider + * the manufacturer information valid. This avoids filling in the + * value for Ericsson when nothing is specified. + */ + if (hu->proto->setup) + hdev->manufacturer = hu->proto->manufacturer; + + hdev->open = hci_uart_open; + hdev->close = hci_uart_close; + hdev->flush = hci_uart_flush; + hdev->send = hci_uart_send_frame; + hdev->setup = hci_uart_setup; + if (!hdev->wakeup) + hdev->wakeup = hci_uart_wakeup; + SET_HCIDEV_DEV(hdev, &hu->serdev->dev); + + if (test_bit(HCI_UART_NO_SUSPEND_NOTIFIER, &hu->flags)) + set_bit(HCI_QUIRK_NO_SUSPEND_NOTIFIER, &hdev->quirks); + + if (test_bit(HCI_UART_RAW_DEVICE, &hu->hdev_flags)) + set_bit(HCI_QUIRK_RAW_DEVICE, &hdev->quirks); + + if (test_bit(HCI_UART_EXT_CONFIG, &hu->hdev_flags)) + set_bit(HCI_QUIRK_EXTERNAL_CONFIG, &hdev->quirks); + + if (test_bit(HCI_UART_CREATE_AMP, &hu->hdev_flags)) + hdev->dev_type = HCI_AMP; + else + hdev->dev_type = HCI_PRIMARY; + + if (test_bit(HCI_UART_INIT_PENDING, &hu->hdev_flags)) + return 0; + + if (hci_register_dev(hdev) < 0) { + BT_ERR("Can't register HCI device"); + err = -ENODEV; + goto err_register; + } + + set_bit(HCI_UART_REGISTERED, &hu->flags); + + return 0; + +err_register: + hci_free_dev(hdev); +err_alloc: + clear_bit(HCI_UART_PROTO_READY, &hu->flags); + p->close(hu); +err_open: + serdev_device_close(hu->serdev); + return err; +} + +err_register: + hci_free_dev(hdev); +err_alloc: + clear_bit(HCI_UART_PROTO_READY, &hu->flags); + p->close(hu); +err_open: + serdev_device_close(hu->serdev); + return err; +} +EXPORT_SYMBOL_GPL(hci_uart_register_device); + +void hci_uart_unregister_device(struct hci_uart *hu) +{ + struct hci_dev *hdev = hu->hdev; + + cancel_work_sync(&hu->init_ready); + if (test_bit(HCI_UART_REGISTERED, &hu->flags)) + hci_unregister_dev(hdev); + hci_free_dev(hdev); + + cancel_work_sync(&hu->write_work); + + hu->proto->close(hu); + + if (test_bit(HCI_UART_PROTO_READY, &hu->flags)) { + clear_bit(HCI_UART_PROTO_READY, &hu->flags); + serdev_device_close(hu->serdev); + } +} + +void hci_uart_unregister_device(struct hci_uart *hu) +{ + struct hci_dev *hdev = hu->hdev; + + cancel_work_sync(&hu->init_ready); + if (test_bit(HCI_UART_REGISTERED, &hu->flags)) + hci_unregister_dev(hdev); + hci_free_dev(hdev); + + cancel_work_sync(&hu->write_work); + + hu->proto->close(hu); + + if (test_bit(HCI_UART_PROTO_READY, &hu->flags)) { + clear_bit(HCI_UART_PROTO_READY, &hu->flags); + serdev_device_close(hu->serdev); + } +} +``` diff --git a/tasks/csa159/pair_141289/task_prompt.md b/tasks/csa159/pair_141289/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..413a17a96f5f052f7d5b177d2d160e13b81f9b35 --- /dev/null +++ b/tasks/csa159/pair_141289/task_prompt.md @@ -0,0 +1,371 @@ +# 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 rollout achieved semantic and objective validation but failed the process-score check, which was below threshold. +- Validation included noisy command failures and one unrecovered analyzer attempt caused by an invalid temporary source/dependency path; an initial diagnostic-location compilation error was recovered later. +- The detection plan weakened semantic precision by treating arbitrary value consumption, such as assignment or passing the value as an argument, as sufficient evidence that initialization failure is safely handled. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6 and an accepted or clean refinement outcome. +- Preserve the previously adequate minimum CSA mechanism for fixed-API matching plus local discarded-return inspection. +- Preserve semantic score at or above the configured threshold. +- Keep the checker project-general and independent of patch anchors, changed line numbers, Bluetooth-specific names, or patch-local literals. + +### Required semantic proof + +- Identify calls to the stable implementation function __percpu_init_rwsem produced by the percpu_init_rwsem() macro. +- Establish that the call's returned failure status is discarded at the enclosing full-expression boundary, so the caller cannot observe initialization failure. +- Treat the patched form as safe only when the status is tested or otherwise propagated in a way that establishes failure handling before subsequent use; mere assignment, argument passing, or unrelated value consumption is insufficient. +- Connect the unchecked initialization to the stated risk that the semaphore remains uninitialized, allowing later lock use to encounter a NULL rcu_sync. + +### Implementation constraints + +- Use check::ASTCodeBody so every analyzed function body is inspected even when path exploration is abandoned before the call. +- Traverse call expressions and match the direct callee by the stable API identity __percpu_init_rwsem, without matching source text or patch-local variable and function names. +- Inspect AST parent context through macro statement-expression and other value-preserving wrappers, reporting only when the value terminates as a discarded expression statement. +- Restrict reports to code in the translation unit being analyzed and attach each diagnostic to the initialization call itself. +- Do not require ProgramState, symbolic constraints, dominance, or interprocedural propagation for this local unchecked-return property. + +### Validation checklist + +- Compile the checker and verify the produced shared object loads successfully with the target Clang Static Analyzer. +- Scan the vulnerable revision and confirm reports for all four expected discarded initialization instances. +- Scan the patched revision and confirm zero reports at both repaired initialization sites and no reports caused solely by the added cleanup calls. +- Verify every diagnostic is located on the __percpu_init_rwsem/percpu_init_rwsem initialization operation and remains within the relevant patched functions or precise changed spans. +- Check that non-patched functions do not produce unrelated warnings and that the checker remains free of patch-anchor and patch-local hardcoding. +- Run the complete before/after validation and code-verification procedures with valid source, dependency, and temporary-path setup, then confirm refinement is accepted or clean. + +### Avoid and forbidden regressions + +- Do not use check::PreCall or another path-sensitive callback as the sole detection mechanism, because asm goto-related path abandonment prevented the attempted callback from observing the calls. +- Do not report every call whose result is merely syntactically consumed; require evidence that failure is tested or propagated as an actual safety decision. +- Do not match source text, changed lines, hu->proto_lock, Bluetooth function names, or other patch-local anchors. +- Do not broaden the checker into a separate lifecycle checker for percpu_free_rwsem(); cleanup is part of the patch but not required for the accepted vulnerability contract. +- Do not regress compilation, before/after differential behavior, false-positive control, objective eligibility, semantic adequacy, or accepted refinement status. diff --git a/tasks/csa159/pair_141329/checker_template.cpp b/tasks/csa159/pair_141329/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_141329/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_141329/config.json b/tasks/csa159/pair_141329/config.json new file mode 100644 index 0000000000000000000000000000000000000000..4c2058f20cc5b53fe37ed25e0950ed716ac22d60 --- /dev/null +++ b/tasks/csa159/pair_141329/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "bb20da18ce936adda6b48aea79a8797c8eee479f", + "after_commit": "448a496f760664d3e2e79466aa1787e6abc922b5", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/88e500affe72fb704c4f201974b5199ca6f51e6c/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/88e500affe72fb704c4f201974b5199ca6f51e6c/compile_commands.json", + "changed_files": [ + "net/bluetooth/hci_sysfs.c" + ], + "commit_message": "Bluetooth: hci_sysfs: Fix attempting to call device_add multiple times\n\ndevice_add shall not be called multiple times as stated in its\ndocumentation:\n\n 'Do not call this routine or device_register() more than once for\n any device structure'\n\nSyzkaller reports a bug as follows [1]:\n------------[ cut here ]------------\nkernel BUG at lib/list_debug.c:33!\ninvalid opcode: 0000 [#1] PREEMPT SMP KASAN\n[...]\nCall Trace:\n \n __list_add include/linux/list.h:69 [inline]\n list_add_tail include/linux/list.h:102 [inline]\n kobj_kset_join lib/kobject.c:164 [inline]\n kobject_add_internal+0x18f/0x8f0 lib/kobject.c:214\n kobject_add_varg lib/kobject.c:358 [inline]\n kobject_add+0x150/0x1c0 lib/kobject.c:410\n device_add+0x368/0x1e90 drivers/base/core.c:3452\n hci_conn_add_sysfs+0x9b/0x1b0 net/bluetooth/hci_sysfs.c:53\n hci_le_cis_estabilished_evt+0x57c/0xae0 net/bluetooth/hci_event.c:6799\n hci_le_meta_evt+0x2b8/0x510 net/bluetooth/hci_event.c:7110\n hci_event_func net/bluetooth/hci_event.c:7440 [inline]\n hci_event_packet+0x63d/0xfd0 net/bluetooth/hci_event.c:7495\n hci_rx_work+0xae7/0x1230 net/bluetooth/hci_core.c:4007\n process_one_work+0x991/0x1610 kernel/workqueue.c:2289\n worker_thread+0x665/0x1080 kernel/workqueue.c:2436\n kthread+0x2e4/0x3a0 kernel/kthread.c:376\n ret_from_fork+0x1f/0x30 arch/x86/entry/entry_64.S:306\n \n\nLink: https://syzkaller.appspot.com/bug?id=da3246e2d33afdb92d66bc166a0934c5b146404a\nSigned-off-by: Luiz Augusto von Dentz \nTested-by: Hawkins Jiawei ", + "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_141329/patch.diff b/tasks/csa159/pair_141329/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..86c093a03fcff2f10ad649d8d21dca6d6db217a9 --- /dev/null +++ b/tasks/csa159/pair_141329/patch.diff @@ -0,0 +1,14 @@ +diff --git a/net/bluetooth/hci_sysfs.c b/net/bluetooth/hci_sysfs.c +index 4e3e0451b08c..08542dfc2dc5 100644 +--- a/net/bluetooth/hci_sysfs.c ++++ b/net/bluetooth/hci_sysfs.c +@@ -48,6 +48,9 @@ void hci_conn_add_sysfs(struct hci_conn *conn) + + BT_DBG("conn %p", conn); + ++ if (device_is_registered(&conn->dev)) ++ return; ++ + dev_set_name(&conn->dev, "%s:%d", hdev->name, conn->handle); + + if (device_add(&conn->dev) < 0) { \ No newline at end of file diff --git a/tasks/csa159/pair_141329/post_functions.txt b/tasks/csa159/pair_141329/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..685e41cd40adb4d3cb52a9fa57df2acf423b44a2 --- /dev/null +++ b/tasks/csa159/pair_141329/post_functions.txt @@ -0,0 +1,21 @@ +### File: net/bluetooth/hci_sysfs.c +```c +void hci_conn_add_sysfs(struct hci_conn *conn) +{ + struct hci_dev *hdev = conn->hdev; + + BT_DBG("conn %p", conn); + + if (device_is_registered(&conn->dev)) + return; + + dev_set_name(&conn->dev, "%s:%d", hdev->name, conn->handle); + + if (device_add(&conn->dev) < 0) { + bt_dev_err(hdev, "failed to register connection device"); + return; + } + + hci_dev_hold(hdev); +} +``` diff --git a/tasks/csa159/pair_141329/pre_functions.txt b/tasks/csa159/pair_141329/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..adef8ee3a210de5d8bea2a176536cff100c9928a --- /dev/null +++ b/tasks/csa159/pair_141329/pre_functions.txt @@ -0,0 +1,18 @@ +### File: net/bluetooth/hci_sysfs.c +```c +void hci_conn_add_sysfs(struct hci_conn *conn) +{ + struct hci_dev *hdev = conn->hdev; + + BT_DBG("conn %p", conn); + + dev_set_name(&conn->dev, "%s:%d", hdev->name, conn->handle); + + if (device_add(&conn->dev) < 0) { + bt_dev_err(hdev, "failed to register connection device"); + return; + } + + hci_dev_hold(hdev); +} +``` diff --git a/tasks/csa159/pair_141329/task_prompt.md b/tasks/csa159/pair_141329/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_141329/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_141364/checker_template.cpp b/tasks/csa159/pair_141364/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_141364/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_141364/config.json b/tasks/csa159/pair_141364/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b6a1504cecaae623acf6e13fadca3a6b248f76f6 --- /dev/null +++ b/tasks/csa159/pair_141364/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "c863a2dcb9b0894d9ac6030c4d1ab2e7867dabcb", + "after_commit": "57569c37f0add1b6489e1a1563c71519daf732cf", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/fc7212fd3100920fea711a80482d967388a4603c/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/fc7212fd3100920fea711a80482d967388a4603c/compile_commands.json", + "changed_files": [ + "drivers/scsi/iscsi_tcp.c" + ], + "commit_message": "scsi: iscsi: iscsi_tcp: Fix null-ptr-deref while calling getpeername()\n\nFix a NULL pointer crash that occurs when we are freeing the socket at the\nsame time we access it via sysfs.\n\nThe problem is that:\n\n 1. iscsi_sw_tcp_conn_get_param() and iscsi_sw_tcp_host_get_param() take\n the frwd_lock and do sock_hold() then drop the frwd_lock. sock_hold()\n does a get on the \"struct sock\".\n\n 2. iscsi_sw_tcp_release_conn() does sockfd_put() which does the last put\n on the \"struct socket\" and that does __sock_release() which sets the\n sock->ops to NULL.\n\n 3. iscsi_sw_tcp_conn_get_param() and iscsi_sw_tcp_host_get_param() then\n call kernel_getpeername() which accesses the NULL sock->ops.\n\nAbove we do a get on the \"struct sock\", but we needed a get on the \"struct\nsocket\". Originally, we just held the frwd_lock the entire time but in\ncommit bcf3a2953d36 (\"scsi: iscsi: iscsi_tcp: Avoid holding spinlock while\ncalling getpeername()\") we switched to refcount based because the network\nlayer changed and started taking a mutex in that path, so we could no\nlonger hold the frwd_lock.\n\nInstead of trying to maintain multiple refcounts, this just has us use a\nmutex for accessing the socket in the interface code paths.\n\nLink: https://lore.kernel.org/r/20220907221700.10302-1-michael.christie@oracle.com\nFixes: bcf3a2953d36 (\"scsi: iscsi: iscsi_tcp: Avoid holding spinlock while calling getpeername()\")\nSigned-off-by: Mike Christie \nSigned-off-by: Martin K. Petersen ", + "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_141364/patch.diff b/tasks/csa159/pair_141364/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..905a82ec8f1340c9f5c66f5cbbfec1e618fa19f1 --- /dev/null +++ b/tasks/csa159/pair_141364/patch.diff @@ -0,0 +1,175 @@ +diff --git a/drivers/scsi/iscsi_tcp.c b/drivers/scsi/iscsi_tcp.c +index 29b1bd755afe..5fb1f364e815 100644 +--- a/drivers/scsi/iscsi_tcp.c ++++ b/drivers/scsi/iscsi_tcp.c +@@ -595,6 +595,8 @@ iscsi_sw_tcp_conn_create(struct iscsi_cls_session *cls_session, + INIT_WORK(&conn->recvwork, iscsi_sw_tcp_recv_data_work); + tcp_sw_conn->queue_recv = iscsi_recv_from_iscsi_q; + ++ mutex_init(&tcp_sw_conn->sock_lock); ++ + tfm = crypto_alloc_ahash("crc32c", 0, CRYPTO_ALG_ASYNC); + if (IS_ERR(tfm)) + goto free_conn; +@@ -629,11 +631,15 @@ iscsi_sw_tcp_conn_create(struct iscsi_cls_session *cls_session, + + static void iscsi_sw_tcp_release_conn(struct iscsi_conn *conn) + { +- struct iscsi_session *session = conn->session; + struct iscsi_tcp_conn *tcp_conn = conn->dd_data; + struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; + struct socket *sock = tcp_sw_conn->sock; + ++ /* ++ * The iscsi transport class will make sure we are not called in ++ * parallel with start, stop, bind and destroys. However, this can be ++ * called twice if userspace does a stop then a destroy. ++ */ + if (!sock) + return; + +@@ -649,9 +655,9 @@ static void iscsi_sw_tcp_release_conn(struct iscsi_conn *conn) + + iscsi_suspend_rx(conn); + +- spin_lock_bh(&session->frwd_lock); ++ mutex_lock(&tcp_sw_conn->sock_lock); + tcp_sw_conn->sock = NULL; +- spin_unlock_bh(&session->frwd_lock); ++ mutex_unlock(&tcp_sw_conn->sock_lock); + sockfd_put(sock); + } + +@@ -703,7 +709,6 @@ iscsi_sw_tcp_conn_bind(struct iscsi_cls_session *cls_session, + struct iscsi_cls_conn *cls_conn, uint64_t transport_eph, + int is_leading) + { +- struct iscsi_session *session = cls_session->dd_data; + struct iscsi_conn *conn = cls_conn->dd_data; + struct iscsi_tcp_conn *tcp_conn = conn->dd_data; + struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; +@@ -723,10 +728,10 @@ iscsi_sw_tcp_conn_bind(struct iscsi_cls_session *cls_session, + if (err) + goto free_socket; + +- spin_lock_bh(&session->frwd_lock); ++ mutex_lock(&tcp_sw_conn->sock_lock); + /* bind iSCSI connection and socket */ + tcp_sw_conn->sock = sock; +- spin_unlock_bh(&session->frwd_lock); ++ mutex_unlock(&tcp_sw_conn->sock_lock); + + /* setup Socket parameters */ + sk = sock->sk; +@@ -763,8 +768,15 @@ static int iscsi_sw_tcp_conn_set_param(struct iscsi_cls_conn *cls_conn, + break; + case ISCSI_PARAM_DATADGST_EN: + iscsi_set_param(cls_conn, param, buf, buflen); ++ ++ mutex_lock(&tcp_sw_conn->sock_lock); ++ if (!tcp_sw_conn->sock) { ++ mutex_unlock(&tcp_sw_conn->sock_lock); ++ return -ENOTCONN; ++ } + tcp_sw_conn->sendpage = conn->datadgst_en ? + sock_no_sendpage : tcp_sw_conn->sock->ops->sendpage; ++ mutex_unlock(&tcp_sw_conn->sock_lock); + break; + case ISCSI_PARAM_MAX_R2T: + return iscsi_tcp_set_max_r2t(conn, buf); +@@ -779,8 +791,8 @@ static int iscsi_sw_tcp_conn_get_param(struct iscsi_cls_conn *cls_conn, + enum iscsi_param param, char *buf) + { + struct iscsi_conn *conn = cls_conn->dd_data; +- struct iscsi_tcp_conn *tcp_conn = conn->dd_data; +- struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; ++ struct iscsi_sw_tcp_conn *tcp_sw_conn; ++ struct iscsi_tcp_conn *tcp_conn; + struct sockaddr_in6 addr; + struct socket *sock; + int rc; +@@ -790,21 +802,36 @@ static int iscsi_sw_tcp_conn_get_param(struct iscsi_cls_conn *cls_conn, + case ISCSI_PARAM_CONN_ADDRESS: + case ISCSI_PARAM_LOCAL_PORT: + spin_lock_bh(&conn->session->frwd_lock); +- if (!tcp_sw_conn || !tcp_sw_conn->sock) { ++ if (!conn->session->leadconn) { + spin_unlock_bh(&conn->session->frwd_lock); + return -ENOTCONN; + } +- sock = tcp_sw_conn->sock; +- sock_hold(sock->sk); ++ /* ++ * The conn has been setup and bound, so just grab a ref ++ * incase a destroy runs while we are in the net layer. ++ */ ++ iscsi_get_conn(conn->cls_conn); + spin_unlock_bh(&conn->session->frwd_lock); + ++ tcp_conn = conn->dd_data; ++ tcp_sw_conn = tcp_conn->dd_data; ++ ++ mutex_lock(&tcp_sw_conn->sock_lock); ++ sock = tcp_sw_conn->sock; ++ if (!sock) { ++ rc = -ENOTCONN; ++ goto sock_unlock; ++ } ++ + if (param == ISCSI_PARAM_LOCAL_PORT) + rc = kernel_getsockname(sock, + (struct sockaddr *)&addr); + else + rc = kernel_getpeername(sock, + (struct sockaddr *)&addr); +- sock_put(sock->sk); ++sock_unlock: ++ mutex_unlock(&tcp_sw_conn->sock_lock); ++ iscsi_put_conn(conn->cls_conn); + if (rc < 0) + return rc; + +@@ -842,17 +869,21 @@ static int iscsi_sw_tcp_host_get_param(struct Scsi_Host *shost, + } + tcp_conn = conn->dd_data; + tcp_sw_conn = tcp_conn->dd_data; +- sock = tcp_sw_conn->sock; +- if (!sock) { +- spin_unlock_bh(&session->frwd_lock); +- return -ENOTCONN; +- } +- sock_hold(sock->sk); ++ /* ++ * The conn has been setup and bound, so just grab a ref ++ * incase a destroy runs while we are in the net layer. ++ */ ++ iscsi_get_conn(conn->cls_conn); + spin_unlock_bh(&session->frwd_lock); + +- rc = kernel_getsockname(sock, +- (struct sockaddr *)&addr); +- sock_put(sock->sk); ++ mutex_lock(&tcp_sw_conn->sock_lock); ++ sock = tcp_sw_conn->sock; ++ if (!sock) ++ rc = -ENOTCONN; ++ else ++ rc = kernel_getsockname(sock, (struct sockaddr *)&addr); ++ mutex_unlock(&tcp_sw_conn->sock_lock); ++ iscsi_put_conn(conn->cls_conn); + if (rc < 0) + return rc; + +diff --git a/drivers/scsi/iscsi_tcp.h b/drivers/scsi/iscsi_tcp.h +index 850a018aefb9..68e14a344904 100644 +--- a/drivers/scsi/iscsi_tcp.h ++++ b/drivers/scsi/iscsi_tcp.h +@@ -28,6 +28,9 @@ struct iscsi_sw_tcp_send { + + struct iscsi_sw_tcp_conn { + struct socket *sock; ++ /* Taken when accessing the sock from the netlink/sysfs interface */ ++ struct mutex sock_lock; ++ + struct work_struct recvwork; + bool queue_recv; \ No newline at end of file diff --git a/tasks/csa159/pair_141364/post_functions.txt b/tasks/csa159/pair_141364/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..586aac2a6991f7144712dfcc5e45ee56bc83d9f7 --- /dev/null +++ b/tasks/csa159/pair_141364/post_functions.txt @@ -0,0 +1,304 @@ +### File: drivers/scsi/iscsi_tcp.c +```c +static struct iscsi_cls_conn * +iscsi_sw_tcp_conn_create(struct iscsi_cls_session *cls_session, + uint32_t conn_idx) +{ + struct iscsi_conn *conn; + struct iscsi_cls_conn *cls_conn; + struct iscsi_tcp_conn *tcp_conn; + struct iscsi_sw_tcp_conn *tcp_sw_conn; + struct crypto_ahash *tfm; + + cls_conn = iscsi_tcp_conn_setup(cls_session, sizeof(*tcp_sw_conn), + conn_idx); + if (!cls_conn) + return NULL; + conn = cls_conn->dd_data; + tcp_conn = conn->dd_data; + tcp_sw_conn = tcp_conn->dd_data; + INIT_WORK(&conn->recvwork, iscsi_sw_tcp_recv_data_work); + tcp_sw_conn->queue_recv = iscsi_recv_from_iscsi_q; + + mutex_init(&tcp_sw_conn->sock_lock); + + tfm = crypto_alloc_ahash("crc32c", 0, CRYPTO_ALG_ASYNC); + if (IS_ERR(tfm)) + goto free_conn; + + tcp_sw_conn->tx_hash = ahash_request_alloc(tfm, GFP_KERNEL); + if (!tcp_sw_conn->tx_hash) + goto free_tfm; + ahash_request_set_callback(tcp_sw_conn->tx_hash, 0, NULL, NULL); + + tcp_sw_conn->rx_hash = ahash_request_alloc(tfm, GFP_KERNEL); + if (!tcp_sw_conn->rx_hash) + goto free_tx_hash; + ahash_request_set_callback(tcp_sw_conn->rx_hash, 0, NULL, NULL); + + tcp_conn->rx_hash = tcp_sw_conn->rx_hash; + + return cls_conn; + +free_tx_hash: + ahash_request_free(tcp_sw_conn->tx_hash); +free_tfm: + crypto_free_ahash(tfm); +free_conn: + iscsi_conn_printk(KERN_ERR, conn, + "Could not create connection due to crc32c " + "loading error. Make sure the crc32c " + "module is built as a module or into the " + "kernel\n"); + iscsi_tcp_conn_teardown(cls_conn); + return NULL; +} + +static void iscsi_sw_tcp_release_conn(struct iscsi_conn *conn) +{ + struct iscsi_tcp_conn *tcp_conn = conn->dd_data; + struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; + struct socket *sock = tcp_sw_conn->sock; + + /* + * The iscsi transport class will make sure we are not called in + * parallel with start, stop, bind and destroys. However, this can be + * called twice if userspace does a stop then a destroy. + */ + if (!sock) + return; + + /* + * Make sure we start socket shutdown now in case userspace is up + * but delayed in releasing the socket. + */ + kernel_sock_shutdown(sock, SHUT_RDWR); + + sock_hold(sock->sk); + iscsi_sw_tcp_conn_restore_callbacks(conn); + sock_put(sock->sk); + + iscsi_suspend_rx(conn); + + mutex_lock(&tcp_sw_conn->sock_lock); + tcp_sw_conn->sock = NULL; + mutex_unlock(&tcp_sw_conn->sock_lock); + sockfd_put(sock); +} + +static void iscsi_sw_tcp_conn_stop(struct iscsi_cls_conn *cls_conn, int flag) +{ + struct iscsi_conn *conn = cls_conn->dd_data; + struct iscsi_tcp_conn *tcp_conn = conn->dd_data; + struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; + struct socket *sock = tcp_sw_conn->sock; + + /* userspace may have goofed up and not bound us */ + if (!sock) + return; + + sock->sk->sk_err = EIO; + wake_up_interruptible(sk_sleep(sock->sk)); + + /* stop xmit side */ + iscsi_suspend_tx(conn); + + /* stop recv side and release socket */ + iscsi_sw_tcp_release_conn(conn); + + iscsi_conn_stop(cls_conn, flag); +} + +static int +iscsi_sw_tcp_conn_bind(struct iscsi_cls_session *cls_session, + struct iscsi_cls_conn *cls_conn, uint64_t transport_eph, + int is_leading) +{ + struct iscsi_conn *conn = cls_conn->dd_data; + struct iscsi_tcp_conn *tcp_conn = conn->dd_data; + struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; + struct sock *sk; + struct socket *sock; + int err; + + /* lookup for existing socket */ + sock = sockfd_lookup((int)transport_eph, &err); + if (!sock) { + iscsi_conn_printk(KERN_ERR, conn, + "sockfd_lookup failed %d\n", err); + return -EEXIST; + } + + err = iscsi_conn_bind(cls_session, cls_conn, is_leading); + if (err) + goto free_socket; + + mutex_lock(&tcp_sw_conn->sock_lock); + /* bind iSCSI connection and socket */ + tcp_sw_conn->sock = sock; + mutex_unlock(&tcp_sw_conn->sock_lock); + + /* setup Socket parameters */ + sk = sock->sk; + sk->sk_reuse = SK_CAN_REUSE; + sk->sk_sndtimeo = 15 * HZ; /* FIXME: make it configurable */ + sk->sk_allocation = GFP_ATOMIC; + sk_set_memalloc(sk); + sock_no_linger(sk); + + iscsi_sw_tcp_conn_set_callbacks(conn); + tcp_sw_conn->sendpage = tcp_sw_conn->sock->ops->sendpage; + /* + * set receive state machine into initial state + */ + iscsi_tcp_hdr_recv_prep(tcp_conn); + return 0; + +free_socket: + sockfd_put(sock); + return err; +} + +static int iscsi_sw_tcp_conn_set_param(struct iscsi_cls_conn *cls_conn, + enum iscsi_param param, char *buf, + int buflen) +{ + struct iscsi_conn *conn = cls_conn->dd_data; + struct iscsi_tcp_conn *tcp_conn = conn->dd_data; + struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; + + switch(param) { + case ISCSI_PARAM_HDRDGST_EN: + iscsi_set_param(cls_conn, param, buf, buflen); + break; + case ISCSI_PARAM_DATADGST_EN: + iscsi_set_param(cls_conn, param, buf, buflen); + + mutex_lock(&tcp_sw_conn->sock_lock); + if (!tcp_sw_conn->sock) { + mutex_unlock(&tcp_sw_conn->sock_lock); + return -ENOTCONN; + } + tcp_sw_conn->sendpage = conn->datadgst_en ? + sock_no_sendpage : tcp_sw_conn->sock->ops->sendpage; + mutex_unlock(&tcp_sw_conn->sock_lock); + break; + case ISCSI_PARAM_MAX_R2T: + return iscsi_tcp_set_max_r2t(conn, buf); + default: + return iscsi_set_param(cls_conn, param, buf, buflen); + } + + return 0; +} + +static int iscsi_sw_tcp_conn_get_param(struct iscsi_cls_conn *cls_conn, + enum iscsi_param param, char *buf) +{ + struct iscsi_conn *conn = cls_conn->dd_data; + struct iscsi_sw_tcp_conn *tcp_sw_conn; + struct iscsi_tcp_conn *tcp_conn; + struct sockaddr_in6 addr; + struct socket *sock; + int rc; + + switch(param) { + case ISCSI_PARAM_CONN_PORT: + case ISCSI_PARAM_CONN_ADDRESS: + case ISCSI_PARAM_LOCAL_PORT: + spin_lock_bh(&conn->session->frwd_lock); + if (!conn->session->leadconn) { + spin_unlock_bh(&conn->session->frwd_lock); + return -ENOTCONN; + } + /* + * The conn has been setup and bound, so just grab a ref + * incase a destroy runs while we are in the net layer. + */ + iscsi_get_conn(conn->cls_conn); + spin_unlock_bh(&conn->session->frwd_lock); + + tcp_conn = conn->dd_data; + tcp_sw_conn = tcp_conn->dd_data; + + mutex_lock(&tcp_sw_conn->sock_lock); + sock = tcp_sw_conn->sock; + if (!sock) { + rc = -ENOTCONN; + goto sock_unlock; + } + + if (param == ISCSI_PARAM_LOCAL_PORT) + rc = kernel_getsockname(sock, + (struct sockaddr *)&addr); + else + rc = kernel_getpeername(sock, + (struct sockaddr *)&addr); +sock_unlock: + mutex_unlock(&tcp_sw_conn->sock_lock); + iscsi_put_conn(conn->cls_conn); + if (rc < 0) + return rc; + + return iscsi_conn_get_addr_param((struct sockaddr_storage *) + &addr, param, buf); + default: + return iscsi_conn_get_param(cls_conn, param, buf); + } + + return 0; +} + +static int iscsi_sw_tcp_host_get_param(struct Scsi_Host *shost, + enum iscsi_host_param param, char *buf) +{ + struct iscsi_sw_tcp_host *tcp_sw_host = iscsi_host_priv(shost); + struct iscsi_session *session = tcp_sw_host->session; + struct iscsi_conn *conn; + struct iscsi_tcp_conn *tcp_conn; + struct iscsi_sw_tcp_conn *tcp_sw_conn; + struct sockaddr_in6 addr; + struct socket *sock; + int rc; + + switch (param) { + case ISCSI_HOST_PARAM_IPADDRESS: + if (!session) + return -ENOTCONN; + + spin_lock_bh(&session->frwd_lock); + conn = session->leadconn; + if (!conn) { + spin_unlock_bh(&session->frwd_lock); + return -ENOTCONN; + } + tcp_conn = conn->dd_data; + tcp_sw_conn = tcp_conn->dd_data; + /* + * The conn has been setup and bound, so just grab a ref + * incase a destroy runs while we are in the net layer. + */ + iscsi_get_conn(conn->cls_conn); + spin_unlock_bh(&session->frwd_lock); + + mutex_lock(&tcp_sw_conn->sock_lock); + sock = tcp_sw_conn->sock; + if (!sock) + rc = -ENOTCONN; + else + rc = kernel_getsockname(sock, (struct sockaddr *)&addr); + mutex_unlock(&tcp_sw_conn->sock_lock); + iscsi_put_conn(conn->cls_conn); + if (rc < 0) + return rc; + + return iscsi_conn_get_addr_param((struct sockaddr_storage *) + &addr, + (enum iscsi_param)param, buf); + default: + return iscsi_host_get_param(shost, param, buf); + } + + return 0; +} +``` diff --git a/tasks/csa159/pair_141364/pre_functions.txt b/tasks/csa159/pair_141364/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..b7f12a242c92afc91eb76174050c1d9af5a86c8a --- /dev/null +++ b/tasks/csa159/pair_141364/pre_functions.txt @@ -0,0 +1,270 @@ +### File: drivers/scsi/iscsi_tcp.c +```c +static struct iscsi_cls_conn * +iscsi_sw_tcp_conn_create(struct iscsi_cls_session *cls_session, + uint32_t conn_idx) +{ + struct iscsi_conn *conn; + struct iscsi_cls_conn *cls_conn; + struct iscsi_tcp_conn *tcp_conn; + struct iscsi_sw_tcp_conn *tcp_sw_conn; + struct crypto_ahash *tfm; + + cls_conn = iscsi_tcp_conn_setup(cls_session, sizeof(*tcp_sw_conn), + conn_idx); + if (!cls_conn) + return NULL; + conn = cls_conn->dd_data; + tcp_conn = conn->dd_data; + tcp_sw_conn = tcp_conn->dd_data; + INIT_WORK(&conn->recvwork, iscsi_sw_tcp_recv_data_work); + tcp_sw_conn->queue_recv = iscsi_recv_from_iscsi_q; + + tfm = crypto_alloc_ahash("crc32c", 0, CRYPTO_ALG_ASYNC); + if (IS_ERR(tfm)) + goto free_conn; + + tcp_sw_conn->tx_hash = ahash_request_alloc(tfm, GFP_KERNEL); + if (!tcp_sw_conn->tx_hash) + goto free_tfm; + ahash_request_set_callback(tcp_sw_conn->tx_hash, 0, NULL, NULL); + + tcp_sw_conn->rx_hash = ahash_request_alloc(tfm, GFP_KERNEL); + if (!tcp_sw_conn->rx_hash) + goto free_tx_hash; + ahash_request_set_callback(tcp_sw_conn->rx_hash, 0, NULL, NULL); + + tcp_conn->rx_hash = tcp_sw_conn->rx_hash; + + return cls_conn; + +free_tx_hash: + ahash_request_free(tcp_sw_conn->tx_hash); +free_tfm: + crypto_free_ahash(tfm); +free_conn: + iscsi_conn_printk(KERN_ERR, conn, + "Could not create connection due to crc32c " + "loading error. Make sure the crc32c " + "module is built as a module or into the " + "kernel\n"); + iscsi_tcp_conn_teardown(cls_conn); + return NULL; +} + +static void iscsi_sw_tcp_release_conn(struct iscsi_conn *conn) +{ + struct iscsi_session *session = conn->session; + struct iscsi_tcp_conn *tcp_conn = conn->dd_data; + struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; + struct socket *sock = tcp_sw_conn->sock; + + if (!sock) + return; + + /* + * Make sure we start socket shutdown now in case userspace is up + * but delayed in releasing the socket. + */ + kernel_sock_shutdown(sock, SHUT_RDWR); + + sock_hold(sock->sk); + iscsi_sw_tcp_conn_restore_callbacks(conn); + sock_put(sock->sk); + + iscsi_suspend_rx(conn); + + spin_lock_bh(&session->frwd_lock); + tcp_sw_conn->sock = NULL; + spin_unlock_bh(&session->frwd_lock); + sockfd_put(sock); +} + +static void iscsi_sw_tcp_conn_destroy(struct iscsi_cls_conn *cls_conn) +{ + struct iscsi_conn *conn = cls_conn->dd_data; + struct iscsi_tcp_conn *tcp_conn = conn->dd_data; + struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; + + iscsi_sw_tcp_release_conn(conn); + + ahash_request_free(tcp_sw_conn->rx_hash); + if (tcp_sw_conn->tx_hash) { + struct crypto_ahash *tfm; + + tfm = crypto_ahash_reqtfm(tcp_sw_conn->tx_hash); + ahash_request_free(tcp_sw_conn->tx_hash); + crypto_free_ahash(tfm); + } + + iscsi_tcp_conn_teardown(cls_conn); +} + +static int +iscsi_sw_tcp_conn_bind(struct iscsi_cls_session *cls_session, + struct iscsi_cls_conn *cls_conn, uint64_t transport_eph, + int is_leading) +{ + struct iscsi_session *session = cls_session->dd_data; + struct iscsi_conn *conn = cls_conn->dd_data; + struct iscsi_tcp_conn *tcp_conn = conn->dd_data; + struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; + struct sock *sk; + struct socket *sock; + int err; + + /* lookup for existing socket */ + sock = sockfd_lookup((int)transport_eph, &err); + if (!sock) { + iscsi_conn_printk(KERN_ERR, conn, + "sockfd_lookup failed %d\n", err); + return -EEXIST; + } + + err = iscsi_conn_bind(cls_session, cls_conn, is_leading); + if (err) + goto free_socket; + + spin_lock_bh(&session->frwd_lock); + /* bind iSCSI connection and socket */ + tcp_sw_conn->sock = sock; + spin_unlock_bh(&session->frwd_lock); + + /* setup Socket parameters */ + sk = sock->sk; + sk->sk_reuse = SK_CAN_REUSE; + sk->sk_sndtimeo = 15 * HZ; /* FIXME: make it configurable */ + sk->sk_allocation = GFP_ATOMIC; + sk_set_memalloc(sk); + sock_no_linger(sk); + + iscsi_sw_tcp_conn_set_callbacks(conn); + tcp_sw_conn->sendpage = tcp_sw_conn->sock->ops->sendpage; + /* + * set receive state machine into initial state + */ + iscsi_tcp_hdr_recv_prep(tcp_conn); + return 0; + +free_socket: + sockfd_put(sock); + return err; +} + +static int iscsi_sw_tcp_conn_set_param(struct iscsi_cls_conn *cls_conn, + enum iscsi_param param, char *buf, + int buflen) +{ + struct iscsi_conn *conn = cls_conn->dd_data; + struct iscsi_tcp_conn *tcp_conn = conn->dd_data; + struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; + + switch(param) { + case ISCSI_PARAM_HDRDGST_EN: + iscsi_set_param(cls_conn, param, buf, buflen); + break; + case ISCSI_PARAM_DATADGST_EN: + iscsi_set_param(cls_conn, param, buf, buflen); + tcp_sw_conn->sendpage = conn->datadgst_en ? + sock_no_sendpage : tcp_sw_conn->sock->ops->sendpage; + break; + case ISCSI_PARAM_MAX_R2T: + return iscsi_tcp_set_max_r2t(conn, buf); + default: + return iscsi_set_param(cls_conn, param, buf, buflen); + } + + return 0; +} + +static int iscsi_sw_tcp_conn_get_param(struct iscsi_cls_conn *cls_conn, + enum iscsi_param param, char *buf) +{ + struct iscsi_conn *conn = cls_conn->dd_data; + struct iscsi_tcp_conn *tcp_conn = conn->dd_data; + struct iscsi_sw_tcp_conn *tcp_sw_conn = tcp_conn->dd_data; + struct sockaddr_in6 addr; + struct socket *sock; + int rc; + + switch(param) { + case ISCSI_PARAM_CONN_PORT: + case ISCSI_PARAM_CONN_ADDRESS: + case ISCSI_PARAM_LOCAL_PORT: + spin_lock_bh(&conn->session->frwd_lock); + if (!tcp_sw_conn || !tcp_sw_conn->sock) { + spin_unlock_bh(&conn->session->frwd_lock); + return -ENOTCONN; + } + sock = tcp_sw_conn->sock; + sock_hold(sock->sk); + spin_unlock_bh(&conn->session->frwd_lock); + + if (param == ISCSI_PARAM_LOCAL_PORT) + rc = kernel_getsockname(sock, + (struct sockaddr *)&addr); + else + rc = kernel_getpeername(sock, + (struct sockaddr *)&addr); + sock_put(sock->sk); + if (rc < 0) + return rc; + + return iscsi_conn_get_addr_param((struct sockaddr_storage *) + &addr, param, buf); + default: + return iscsi_conn_get_param(cls_conn, param, buf); + } + + return 0; +} + +static int iscsi_sw_tcp_host_get_param(struct Scsi_Host *shost, + enum iscsi_host_param param, char *buf) +{ + struct iscsi_sw_tcp_host *tcp_sw_host = iscsi_host_priv(shost); + struct iscsi_session *session = tcp_sw_host->session; + struct iscsi_conn *conn; + struct iscsi_tcp_conn *tcp_conn; + struct iscsi_sw_tcp_conn *tcp_sw_conn; + struct sockaddr_in6 addr; + struct socket *sock; + int rc; + + switch (param) { + case ISCSI_HOST_PARAM_IPADDRESS: + if (!session) + return -ENOTCONN; + + spin_lock_bh(&session->frwd_lock); + conn = session->leadconn; + if (!conn) { + spin_unlock_bh(&session->frwd_lock); + return -ENOTCONN; + } + tcp_conn = conn->dd_data; + tcp_sw_conn = tcp_conn->dd_data; + sock = tcp_sw_conn->sock; + if (!sock) { + spin_unlock_bh(&session->frwd_lock); + return -ENOTCONN; + } + sock_hold(sock->sk); + spin_unlock_bh(&session->frwd_lock); + + rc = kernel_getsockname(sock, + (struct sockaddr *)&addr); + sock_put(sock->sk); + if (rc < 0) + return rc; + + return iscsi_conn_get_addr_param((struct sockaddr_storage *) + &addr, + (enum iscsi_param)param, buf); + default: + return iscsi_host_get_param(shost, param, buf); + } + + return 0; +} +``` diff --git a/tasks/csa159/pair_141364/task_prompt.md b/tasks/csa159/pair_141364/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..71ed88cebe704e6478e2a62d7560b49d380d197a --- /dev/null +++ b/tasks/csa159/pair_141364/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: `control_flow` + +### Current failure diagnosis + +- semantic_mechanism failed: the rollout matched a dominating sock_hold(V->sk) AST/CFG proxy and never proved the TOCTOU window (shared-field socket load, protecting lock released, then net-layer use of the outer struct socket). +- Lock coverage versus the sink was not established, so the checker could not show the socket was used after the field-protecting lock was dropped. +- The unlocked tcp_sw_conn->sock->ops->sendpage sink in iscsi_sw_tcp_conn_set_param was omitted, so the report condition did not cover every sink the patch serializes. +- Semantic status stayed partial because the discriminator was a protection-signature proxy rather than wrong-object lifetime plus use-after-unlock of a shared socket. + +### 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 + +- A local struct socket * V is assigned from a struct-member load of a shared connection/socket field. +- V is then used at a net-layer sink that can dereference sock->ops: kernel_getpeername, kernel_getsockname, or a MemberExpr through sock->ops (sendpage). +- On a CFG path to that sink, the lock that covered the field load is released before the use (unlock dominates the sink; the sink is not in a still-locked region). +- The only refcount that dominates the sink is sock_hold on V->sk (inner struct sock), which does not keep the outer struct socket alive against concurrent sockfd_put/__sock_release. +- Safe code must instead keep a socket lock dominating the sink with no intervening unlock, re-check the socket under that lock, and must not use sock_hold(V->sk) as the sink's lifetime guard. + +### Implementation constraints + +- Intercept kernel_getpeername/kernel_getsockname with check::PreCall; detect sock->ops MemberExpr sinks via enclosing-function AST/CFG or PreStmt, not by file or function name. +- Prove vulnerability with CFG dominance/ordering among field-load, optional sock_hold(V->sk), unlock, and sink; do not use intra-procedural ProgramState nullness of V as the discriminator. +- Report at the sink CallExpr or sock->ops access, attaching source ranges for the sink and the wrong-object hold or the unlock that opens the window. +- Use only kernel-generic APIs and types (sock_hold, kernel_getpeername, kernel_getsockname, struct socket/sock, ops); forbid driver identifiers, paths, CVE ids, and patch line numbers. +- Include complete CFG/ParentMap/Dominators headers so ParentMap and CFGStmtMap use is well-typed. +- Stay intra-procedural: do not model a concurrent release_conn thread; the local use-after-unlock plus wrong-object hold is the CSA-observable race signature. + +### Validation checklist + +- checker.so compiles with zero diagnostics. +- Before-patch scan reports at kernel_getsockname and kernel_getpeername in iscsi_sw_tcp_conn_get_param and at kernel_getsockname in iscsi_sw_tcp_host_get_param. +- After-patch scan is clean on those sinks once sock_hold(sk) is gone and sock_lock plus if (!sock) cover the calls. +- If sock->ops sendpage is in scope, before-scan flags the unlocked ops->sendpage in iscsi_sw_tcp_conn_set_param and after-scan is clean there. +- Every before-warning is in a patched function, near the changed spans, and disappears only in patched code (no non-patched FPs). +- Refinement stays accepted/clean and hard_validation plus G6 remain passing. + +### Avoid and forbidden regressions + +- Do not treat a dominating sock_hold(V->sk) as sufficient without proving lock-release-before-sink ordering. +- Do not try to separate buggy and patched code by symbolic non-NULL of the socket at the sink. +- Do not emit diagnostics on sock_hold in release_conn or other bodies that lack a net-layer/ops sink. +- Do not use source-text matching or patch-local identifiers as a stand-in for CFG guard/sink relations. +- Do not reconstruct, copy, or resume the prior SocketSockHoldUseChecker. +- Do not claim path-sensitive concurrent sockfd_put modeling; CSA cannot observe the other thread. diff --git a/tasks/csa159/pair_141754/checker_template.cpp b/tasks/csa159/pair_141754/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_141754/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_141754/config.json b/tasks/csa159/pair_141754/config.json new file mode 100644 index 0000000000000000000000000000000000000000..ac731ef0888cf3350ba93c14d2acc8b432b56a83 --- /dev/null +++ b/tasks/csa159/pair_141754/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "b8ab8858190a1bba5f4b35ca37b1e4d7577b3a75", + "after_commit": "3027e7b15b02d2d37e3f82d6b8404f6d37e3b8cf", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/826eb9bcc1844990e3c4a7c84846f1c1eaee0ed0/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/826eb9bcc1844990e3c4a7c84846f1c1eaee0ed0/compile_commands.json", + "changed_files": [ + "drivers/net/ethernet/intel/ice/ice_ptp.c" + ], + "commit_message": "ice: Fix some null pointer dereference issues in ice_ptp.c\n\ndevm_kasprintf() returns a pointer to dynamically allocated memory\nwhich can be NULL upon failure.\n\nFixes: d938a8cca88a (\"ice: Auxbus devices & driver for E822 TS\")\nCc: Kunwu Chan \nSuggested-by: Przemek Kitszel \nSigned-off-by: Kunwu Chan \nReviewed-by: Przemek Kitszel \nReviewed-by: Simon Horman \nTested-by: Pucha Himasekhar Reddy (A Contingent worker at Intel)\nSigned-off-by: Tony Nguyen ", + "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_141754/patch.diff b/tasks/csa159/pair_141754/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3ec3fc2fe45518d99e6e8659fcf12730ed634bbe --- /dev/null +++ b/tasks/csa159/pair_141754/patch.diff @@ -0,0 +1,22 @@ +diff --git a/drivers/net/ethernet/intel/ice/ice_ptp.c b/drivers/net/ethernet/intel/ice/ice_ptp.c +index c4fe28017b8d..3b6605c8585e 100644 +--- a/drivers/net/ethernet/intel/ice/ice_ptp.c ++++ b/drivers/net/ethernet/intel/ice/ice_ptp.c +@@ -2863,6 +2863,8 @@ static int ice_ptp_register_auxbus_driver(struct ice_pf *pf) + name = devm_kasprintf(dev, GFP_KERNEL, "ptp_aux_dev_%u_%u_clk%u", + pf->pdev->bus->number, PCI_SLOT(pf->pdev->devfn), + ice_get_ptp_src_clock_index(&pf->hw)); ++ if (!name) ++ return -ENOMEM; + + aux_driver->name = name; + aux_driver->shutdown = ice_ptp_auxbus_shutdown; +@@ -3109,6 +3111,8 @@ static int ice_ptp_create_auxbus_device(struct ice_pf *pf) + name = devm_kasprintf(dev, GFP_KERNEL, "ptp_aux_dev_%u_%u_clk%u", + pf->pdev->bus->number, PCI_SLOT(pf->pdev->devfn), + ice_get_ptp_src_clock_index(&pf->hw)); ++ if (!name) ++ return -ENOMEM; + + aux_dev->name = name; + aux_dev->id = id; \ No newline at end of file diff --git a/tasks/csa159/pair_141754/post_functions.txt b/tasks/csa159/pair_141754/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2c0079b3882133a7bb209755e6fa4bcb69945370 --- /dev/null +++ b/tasks/csa159/pair_141754/post_functions.txt @@ -0,0 +1,84 @@ +### File: drivers/net/ethernet/intel/ice/ice_ptp.c +```c +static int ice_ptp_register_auxbus_driver(struct ice_pf *pf) +{ + struct auxiliary_driver *aux_driver; + struct ice_ptp *ptp; + struct device *dev; + char *name; + int err; + + ptp = &pf->ptp; + dev = ice_pf_to_dev(pf); + aux_driver = &ptp->ports_owner.aux_driver; + INIT_LIST_HEAD(&ptp->ports_owner.ports); + mutex_init(&ptp->ports_owner.lock); + name = devm_kasprintf(dev, GFP_KERNEL, "ptp_aux_dev_%u_%u_clk%u", + pf->pdev->bus->number, PCI_SLOT(pf->pdev->devfn), + ice_get_ptp_src_clock_index(&pf->hw)); + if (!name) + return -ENOMEM; + + aux_driver->name = name; + aux_driver->shutdown = ice_ptp_auxbus_shutdown; + aux_driver->suspend = ice_ptp_auxbus_suspend; + aux_driver->remove = ice_ptp_auxbus_remove; + aux_driver->resume = ice_ptp_auxbus_resume; + aux_driver->probe = ice_ptp_auxbus_probe; + aux_driver->id_table = ice_ptp_auxbus_create_id_table(pf, name); + if (!aux_driver->id_table) + return -ENOMEM; + + err = auxiliary_driver_register(aux_driver); + if (err) { + devm_kfree(dev, aux_driver->id_table); + dev_err(dev, "Failed registering aux_driver, name <%s>\n", + name); + } + + return err; +} + +static int ice_ptp_create_auxbus_device(struct ice_pf *pf) +{ + struct auxiliary_device *aux_dev; + struct ice_ptp *ptp; + struct device *dev; + char *name; + int err; + u32 id; + + ptp = &pf->ptp; + id = ptp->port.port_num; + dev = ice_pf_to_dev(pf); + + aux_dev = &ptp->port.aux_dev; + + name = devm_kasprintf(dev, GFP_KERNEL, "ptp_aux_dev_%u_%u_clk%u", + pf->pdev->bus->number, PCI_SLOT(pf->pdev->devfn), + ice_get_ptp_src_clock_index(&pf->hw)); + if (!name) + return -ENOMEM; + + aux_dev->name = name; + aux_dev->id = id; + aux_dev->dev.release = ice_ptp_release_auxbus_device; + aux_dev->dev.parent = dev; + + err = auxiliary_device_init(aux_dev); + if (err) + goto aux_err; + + err = auxiliary_device_add(aux_dev); + if (err) { + auxiliary_device_uninit(aux_dev); + goto aux_err; + } + + return 0; +aux_err: + dev_err(dev, "Failed to create PTP auxiliary bus device <%s>\n", name); + devm_kfree(dev, name); + return err; +} +``` diff --git a/tasks/csa159/pair_141754/pre_functions.txt b/tasks/csa159/pair_141754/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..766b478646ed9a4d7a4fa9b0fc750e241fb27a09 --- /dev/null +++ b/tasks/csa159/pair_141754/pre_functions.txt @@ -0,0 +1,80 @@ +### File: drivers/net/ethernet/intel/ice/ice_ptp.c +```c +static int ice_ptp_register_auxbus_driver(struct ice_pf *pf) +{ + struct auxiliary_driver *aux_driver; + struct ice_ptp *ptp; + struct device *dev; + char *name; + int err; + + ptp = &pf->ptp; + dev = ice_pf_to_dev(pf); + aux_driver = &ptp->ports_owner.aux_driver; + INIT_LIST_HEAD(&ptp->ports_owner.ports); + mutex_init(&ptp->ports_owner.lock); + name = devm_kasprintf(dev, GFP_KERNEL, "ptp_aux_dev_%u_%u_clk%u", + pf->pdev->bus->number, PCI_SLOT(pf->pdev->devfn), + ice_get_ptp_src_clock_index(&pf->hw)); + + aux_driver->name = name; + aux_driver->shutdown = ice_ptp_auxbus_shutdown; + aux_driver->suspend = ice_ptp_auxbus_suspend; + aux_driver->remove = ice_ptp_auxbus_remove; + aux_driver->resume = ice_ptp_auxbus_resume; + aux_driver->probe = ice_ptp_auxbus_probe; + aux_driver->id_table = ice_ptp_auxbus_create_id_table(pf, name); + if (!aux_driver->id_table) + return -ENOMEM; + + err = auxiliary_driver_register(aux_driver); + if (err) { + devm_kfree(dev, aux_driver->id_table); + dev_err(dev, "Failed registering aux_driver, name <%s>\n", + name); + } + + return err; +} + +static int ice_ptp_create_auxbus_device(struct ice_pf *pf) +{ + struct auxiliary_device *aux_dev; + struct ice_ptp *ptp; + struct device *dev; + char *name; + int err; + u32 id; + + ptp = &pf->ptp; + id = ptp->port.port_num; + dev = ice_pf_to_dev(pf); + + aux_dev = &ptp->port.aux_dev; + + name = devm_kasprintf(dev, GFP_KERNEL, "ptp_aux_dev_%u_%u_clk%u", + pf->pdev->bus->number, PCI_SLOT(pf->pdev->devfn), + ice_get_ptp_src_clock_index(&pf->hw)); + + aux_dev->name = name; + aux_dev->id = id; + aux_dev->dev.release = ice_ptp_release_auxbus_device; + aux_dev->dev.parent = dev; + + err = auxiliary_device_init(aux_dev); + if (err) + goto aux_err; + + err = auxiliary_device_add(aux_dev); + if (err) { + auxiliary_device_uninit(aux_dev); + goto aux_err; + } + + return 0; +aux_err: + dev_err(dev, "Failed to create PTP auxiliary bus device <%s>\n", name); + devm_kfree(dev, name); + return err; +} +``` diff --git a/tasks/csa159/pair_141754/task_prompt.md b/tasks/csa159/pair_141754/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..855ea572d19bb63022ea6436501dde1356ad6399 --- /dev/null +++ b/tasks/csa159/pair_141754/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 rollout was accepted as path-sensitive but did not establish the patched vulnerability semantics. It only tracked allocation results within direct expressions and reported direct dereferences or printf `%s` arguments. +- The actual name value is passed to `ice_ptp_auxbus_create_id_table()` or stored in an auxiliary object and later consumed through auxiliary-device APIs. The checker did not identify these required-name contracts or propagate the nullable fact across function boundaries. +- The checker reported a `dev_err(..., "%s", name)` use even though that formatting path may tolerate a NULL string, creating an adjacent or benign report while missing the patched auxiliary-bus consumption. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Retain path-sensitive constraint reasoning so equivalent NULL checks suppress diagnostics when the NULL state is infeasible. +- Keep semantic quality at or above the configured threshold and preserve process quality at or above its configured threshold. +- Keep the checker independent of patch anchors and patch-local hardcoding. + +### Required semantic proof + +- Prove that a documented NULL-returning allocation result can remain NULL on a feasible path after `devm_kasprintf()` or an equivalent allocator call. +- Prove that the same value, including its propagated aliases or stored field representation, reaches a name-consuming auxiliary-driver or auxiliary-device contract through `ice_ptp_auxbus_create_id_table()`, `auxiliary_device_init()`, `auxiliary_device_add()`, or equivalent generic API behavior. +- Suppress the diagnostic when an explicit or equivalent NULL guard makes the allocation result non-NULL on every path reaching the required consumer. +- Report the unchecked allocation at the relevant consuming contract, rather than treating storage or an arbitrary call argument as proof of a vulnerability. + +### Implementation constraints + +- Track allocator return symbols in ProgramState and retain their nullable feasibility across statements, calls, return values, argument passing, and relevant object-field bindings. +- Use CSA call and binding analysis sufficient to propagate the allocation fact through helper calls and auxiliary object fields; direct intra-function expression matching is insufficient. +- Recognize required pointer or name contracts from generic API or declaration semantics and model the supplied auxiliary-bus consumers without relying on the two patched function names. +- Use ConstraintManager feasibility at the eventual consuming operation to distinguish unchecked NULL paths from paths constrained non-NULL. +- Keep reports localized to the required consuming operation or the precise propagation edge that establishes the invalid contract; do not report a nullable value merely because it is stored or passed to an unrelated call. +- Retain dead-symbol and obsolete binding cleanup so interprocedural tracking does not produce stale diagnostics. +- Keep scope project-general, using documented allocator and consumer contracts rather than file names, line numbers, local variable names, commit identifiers, or patch-specific call-site tables. + +### Validation checklist + +- Compile the new checker and run code verification successfully, preserving the existing hard-validation result. +- Scan both pre-patch and post-patch sources: detect the unchecked allocation defect before the patch and produce no corresponding reports after the added NULL checks. +- Verify that diagnostics are located at the auxiliary name-consuming contract or its precise required use, with reports remaining within the patched functions or their semantically relevant helper path. +- Test propagation through `ice_ptp_auxbus_create_id_table()` and auxiliary-device object fields or equivalent helper boundaries, including the two affected functions. +- Refine false-positive behavior so `dev_err` `%s` formatting alone and non-local storage alone do not trigger a report unless the consumer contract requires a valid non-NULL pointer. +- Check equivalent guard shapes and paths where the pointer is already known non-NULL, ensuring the ConstraintManager suppresses those cases. +- Run relevant unrelated-file or non-patched-function scans to confirm scope control and retain anchor-free and hardcoding-free validation. +- Confirm semantic mechanism and semantic score meet the configured threshold without regressing objective eligibility or process quality. + +### Avoid and forbidden regressions + +- Do not use direct dereference or printf `%s` detection as the complete semantic contract. +- Do not treat every non-local store or ordinary call argument as a NULL-dereference sink. +- Do not assume that a printf `%s` conversion necessarily requires a non-NULL pointer when the observed kernel formatting path may tolerate NULL. +- Do not infer safety from nearby guard syntax, statement placement, dominance alone, or source-text matching instead of path constraints. +- Do not omit propagation through helper functions, return values, API arguments, or auxiliary object fields. +- Do not introduce patch-specific names, file or line anchors, commit references, or a fixed list of the two vulnerable call sites. +- Do not regress compile, before/after scan, code verification, objective gate, semantic threshold, process quality, anchor independence, or hardcoding independence. diff --git a/tasks/csa159/pair_141857/checker_template.cpp b/tasks/csa159/pair_141857/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_141857/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_141857/config.json b/tasks/csa159/pair_141857/config.json new file mode 100644 index 0000000000000000000000000000000000000000..4b78de4a7c8a9d25ccc92eba19048615bebeb4dc --- /dev/null +++ b/tasks/csa159/pair_141857/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "3f489c2067c5824528212b0fc18b28d51332d906", + "after_commit": "9a9ab0d963621d9d12199df9817e66982582d5a5", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/b9873755a6c8ccfce79094c4dce9efa3ecb1a749/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/b9873755a6c8ccfce79094c4dce9efa3ecb1a749/compile_commands.json", + "changed_files": [ + "drivers/android/binder_alloc.c" + ], + "commit_message": "binder: fix race between mmput() and do_exit()\n\nTask A calls binder_update_page_range() to allocate and insert pages on\na remote address space from Task B. For this, Task A pins the remote mm\nvia mmget_not_zero() first. This can race with Task B do_exit() and the\nfinal mmput() refcount decrement will come from Task A.\n\n Task A | Task B\n ------------------+------------------\n mmget_not_zero() |\n | do_exit()\n | exit_mm()\n | mmput()\n mmput() |\n exit_mmap() |\n remove_vma() |\n fput() |\n\nIn this case, the work of ____fput() from Task B is queued up in Task A\nas TWA_RESUME. So in theory, Task A returns to userspace and the cleanup\nwork gets executed. However, Task A instead sleep, waiting for a reply\nfrom Task B that never comes (it's dead).\n\nThis means the binder_deferred_release() is blocked until an unrelated\nbinder event forces Task A to go back to userspace. All the associated\ndeath notifications will also be delayed until then.\n\nIn order to fix this use mmput_async() that will schedule the work in\nthe corresponding mm->async_put_work WQ instead of Task A.\n\nFixes: 457b9a6f09f0 (\"Staging: android: add binder driver\")\nReviewed-by: Alice Ryhl \nSigned-off-by: Carlos Llamas \nLink: https://lore.kernel.org/r/20231201172212.1813387-4-cmllamas@google.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_141857/patch.diff b/tasks/csa159/pair_141857/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8b6b62a67c6369c641983360a6cd394a4e1c9ded --- /dev/null +++ b/tasks/csa159/pair_141857/patch.diff @@ -0,0 +1,22 @@ +diff --git a/drivers/android/binder_alloc.c b/drivers/android/binder_alloc.c +index 9d2eff70c3ba..adcec5ec0959 100644 +--- a/drivers/android/binder_alloc.c ++++ b/drivers/android/binder_alloc.c +@@ -271,7 +271,7 @@ static int binder_update_page_range(struct binder_alloc *alloc, int allocate, + } + if (mm) { + mmap_write_unlock(mm); +- mmput(mm); ++ mmput_async(mm); + } + return 0; + +@@ -304,7 +304,7 @@ static int binder_update_page_range(struct binder_alloc *alloc, int allocate, + err_no_vma: + if (mm) { + mmap_write_unlock(mm); +- mmput(mm); ++ mmput_async(mm); + } + return vma ? -ENOMEM : -ESRCH; + } \ No newline at end of file diff --git a/tasks/csa159/pair_141857/post_functions.txt b/tasks/csa159/pair_141857/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..afb2ca6accca09233df7821a6ff2a332e9a53c06 --- /dev/null +++ b/tasks/csa159/pair_141857/post_functions.txt @@ -0,0 +1,140 @@ +### File: drivers/android/binder_alloc.c +```c +static int binder_update_page_range(struct binder_alloc *alloc, int allocate, + void __user *start, void __user *end) +{ + void __user *page_addr; + unsigned long user_page_addr; + struct binder_lru_page *page; + struct vm_area_struct *vma = NULL; + struct mm_struct *mm = NULL; + bool need_mm = false; + + binder_alloc_debug(BINDER_DEBUG_BUFFER_ALLOC, + "%d: %s pages %pK-%pK\n", alloc->pid, + allocate ? "allocate" : "free", start, end); + + if (end <= start) + return 0; + + trace_binder_update_page_range(alloc, allocate, start, end); + + if (allocate == 0) + goto free_range; + + for (page_addr = start; page_addr < end; page_addr += PAGE_SIZE) { + page = &alloc->pages[(page_addr - alloc->buffer) / PAGE_SIZE]; + if (!page->page_ptr) { + need_mm = true; + break; + } + } + + if (need_mm && mmget_not_zero(alloc->mm)) + mm = alloc->mm; + + if (mm) { + mmap_write_lock(mm); + vma = alloc->vma; + } + + if (!vma && need_mm) { + binder_alloc_debug(BINDER_DEBUG_USER_ERROR, + "%d: binder_alloc_buf failed to map pages in userspace, no vma\n", + alloc->pid); + goto err_no_vma; + } + + for (page_addr = start; page_addr < end; page_addr += PAGE_SIZE) { + int ret; + bool on_lru; + size_t index; + + index = (page_addr - alloc->buffer) / PAGE_SIZE; + page = &alloc->pages[index]; + + if (page->page_ptr) { + trace_binder_alloc_lru_start(alloc, index); + + on_lru = list_lru_del(&binder_alloc_lru, &page->lru); + WARN_ON(!on_lru); + + trace_binder_alloc_lru_end(alloc, index); + continue; + } + + if (WARN_ON(!vma)) + goto err_page_ptr_cleared; + + trace_binder_alloc_page_start(alloc, index); + page->page_ptr = alloc_page(GFP_KERNEL | + __GFP_HIGHMEM | + __GFP_ZERO); + if (!page->page_ptr) { + pr_err("%d: binder_alloc_buf failed for page at %pK\n", + alloc->pid, page_addr); + goto err_alloc_page_failed; + } + page->alloc = alloc; + INIT_LIST_HEAD(&page->lru); + + user_page_addr = (uintptr_t)page_addr; + ret = vm_insert_page(vma, user_page_addr, page[0].page_ptr); + if (ret) { + pr_err("%d: binder_alloc_buf failed to map page at %lx in userspace\n", + alloc->pid, user_page_addr); + goto err_vm_insert_page_failed; + } + + if (index + 1 > alloc->pages_high) + alloc->pages_high = index + 1; + + trace_binder_alloc_page_end(alloc, index); + } + if (mm) { + mmap_write_unlock(mm); + mmput_async(mm); + } + return 0; + +free_range: + for (page_addr = end - PAGE_SIZE; 1; page_addr -= PAGE_SIZE) { + bool ret; + size_t index; + + index = (page_addr - alloc->buffer) / PAGE_SIZE; + page = &alloc->pages[index]; + + trace_binder_free_lru_start(alloc, index); + + ret = list_lru_add(&binder_alloc_lru, &page->lru); + WARN_ON(!ret); + + trace_binder_free_lru_end(alloc, index); + if (page_addr == start) + break; + continue; + +err_vm_insert_page_failed: + __free_page(page->page_ptr); + page->page_ptr = NULL; +err_alloc_page_failed: +err_page_ptr_cleared: + if (page_addr == start) + break; + } +err_no_vma: + if (mm) { + mmap_write_unlock(mm); + mmput_async(mm); + } + return vma ? -ENOMEM : -ESRCH; +} + +static inline void binder_alloc_set_vma(struct binder_alloc *alloc, + struct vm_area_struct *vma) +{ + /* pairs with smp_load_acquire in binder_alloc_get_vma() */ + smp_store_release(&alloc->vma, vma); +} +``` diff --git a/tasks/csa159/pair_141857/pre_functions.txt b/tasks/csa159/pair_141857/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..9f83e24e87cd19c4f4c786dda97d8c2a656988bc --- /dev/null +++ b/tasks/csa159/pair_141857/pre_functions.txt @@ -0,0 +1,140 @@ +### File: drivers/android/binder_alloc.c +```c +static int binder_update_page_range(struct binder_alloc *alloc, int allocate, + void __user *start, void __user *end) +{ + void __user *page_addr; + unsigned long user_page_addr; + struct binder_lru_page *page; + struct vm_area_struct *vma = NULL; + struct mm_struct *mm = NULL; + bool need_mm = false; + + binder_alloc_debug(BINDER_DEBUG_BUFFER_ALLOC, + "%d: %s pages %pK-%pK\n", alloc->pid, + allocate ? "allocate" : "free", start, end); + + if (end <= start) + return 0; + + trace_binder_update_page_range(alloc, allocate, start, end); + + if (allocate == 0) + goto free_range; + + for (page_addr = start; page_addr < end; page_addr += PAGE_SIZE) { + page = &alloc->pages[(page_addr - alloc->buffer) / PAGE_SIZE]; + if (!page->page_ptr) { + need_mm = true; + break; + } + } + + if (need_mm && mmget_not_zero(alloc->mm)) + mm = alloc->mm; + + if (mm) { + mmap_write_lock(mm); + vma = alloc->vma; + } + + if (!vma && need_mm) { + binder_alloc_debug(BINDER_DEBUG_USER_ERROR, + "%d: binder_alloc_buf failed to map pages in userspace, no vma\n", + alloc->pid); + goto err_no_vma; + } + + for (page_addr = start; page_addr < end; page_addr += PAGE_SIZE) { + int ret; + bool on_lru; + size_t index; + + index = (page_addr - alloc->buffer) / PAGE_SIZE; + page = &alloc->pages[index]; + + if (page->page_ptr) { + trace_binder_alloc_lru_start(alloc, index); + + on_lru = list_lru_del(&binder_alloc_lru, &page->lru); + WARN_ON(!on_lru); + + trace_binder_alloc_lru_end(alloc, index); + continue; + } + + if (WARN_ON(!vma)) + goto err_page_ptr_cleared; + + trace_binder_alloc_page_start(alloc, index); + page->page_ptr = alloc_page(GFP_KERNEL | + __GFP_HIGHMEM | + __GFP_ZERO); + if (!page->page_ptr) { + pr_err("%d: binder_alloc_buf failed for page at %pK\n", + alloc->pid, page_addr); + goto err_alloc_page_failed; + } + page->alloc = alloc; + INIT_LIST_HEAD(&page->lru); + + user_page_addr = (uintptr_t)page_addr; + ret = vm_insert_page(vma, user_page_addr, page[0].page_ptr); + if (ret) { + pr_err("%d: binder_alloc_buf failed to map page at %lx in userspace\n", + alloc->pid, user_page_addr); + goto err_vm_insert_page_failed; + } + + if (index + 1 > alloc->pages_high) + alloc->pages_high = index + 1; + + trace_binder_alloc_page_end(alloc, index); + } + if (mm) { + mmap_write_unlock(mm); + mmput(mm); + } + return 0; + +free_range: + for (page_addr = end - PAGE_SIZE; 1; page_addr -= PAGE_SIZE) { + bool ret; + size_t index; + + index = (page_addr - alloc->buffer) / PAGE_SIZE; + page = &alloc->pages[index]; + + trace_binder_free_lru_start(alloc, index); + + ret = list_lru_add(&binder_alloc_lru, &page->lru); + WARN_ON(!ret); + + trace_binder_free_lru_end(alloc, index); + if (page_addr == start) + break; + continue; + +err_vm_insert_page_failed: + __free_page(page->page_ptr); + page->page_ptr = NULL; +err_alloc_page_failed: +err_page_ptr_cleared: + if (page_addr == start) + break; + } +err_no_vma: + if (mm) { + mmap_write_unlock(mm); + mmput(mm); + } + return vma ? -ENOMEM : -ESRCH; +} + +static inline void binder_alloc_set_vma(struct binder_alloc *alloc, + struct vm_area_struct *vma) +{ + /* pairs with smp_load_acquire in binder_alloc_get_vma() */ + smp_store_release(&alloc->vma, vma); +} +``` diff --git a/tasks/csa159/pair_141857/task_prompt.md b/tasks/csa159/pair_141857/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..996ecdd3e7265b3be3944ab0e2eb40217d954da2 --- /dev/null +++ b/tasks/csa159/pair_141857/task_prompt.md @@ -0,0 +1,379 @@ +# 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 used function-wide AST matching, so a pin or assignment anywhere in the body could justify a report without proving that it precedes and reaches the release. +- It did not establish that mmget_not_zero() succeeded on the reporting path, that the corresponding assignment executed, or that the released value was not overwritten before mmput(). +- It could associate operations from mutually exclusive branches and therefore implemented only a flow-insensitive approximation of the conditional acquire/release protocol. +- Standard PostCall, PreCall, and PreStmt path callbacks did not observe the relevant calls because the preceding tracepoint expansion contains asm goto and truncates analyzer exploration; this observability failure remains unresolved for a genuinely path-sensitive design. +- The generalized claim that every mmget_not_zero() reference is foreign is not supported; the source evidence specifically concerns alloc->mm owned by another task. + +### 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 + +- On a feasible reporting path, mmget_not_zero() must return true before the synchronous release and thereby acquire the relevant mm_struct reference. +- The acquired mm value must flow through the executed assignment to the exact value passed to mmput(), with no intervening overwrite, kill, or incompatible alias update. +- The same feasible path must reach mmput() after acquisition; a later acquisition, an unreachable acquisition, or one on a mutually exclusive branch is insufficient. +- The released mm must be established as the remote alloc-owned mm involved in the binder operation rather than merely assumed foreign because mmget_not_zero() was called; current-task-derived values are safe exclusions. +- The checker need only prove the risk that synchronous final teardown can occur in the caller when the owner exits concurrently; it must not claim to prove that this invocation is actually the last reference decrement. + +### Implementation constraints + +- Use path-sensitive ProgramState facts for successful acquisition and value identity, with call or branch callbacks that distinguish the true return of mmget_not_zero() and consume or validate the fact at mmput(). +- Before accepting the design, demonstrate that the selected callbacks observe both the acquisition and release in the real kernel translation unit despite the tracepoint asm-goto boundary; zero-event behavior is not an acceptable implementation basis. +- If normal exploded-graph callbacks remain truncated, use a CSA-supported observation strategy that retains path-state semantics and reaches post-tracepoint statements; do not replace the missing paths with whole-function call collection. +- Model reaching definitions, branch feasibility, and invalidation so assignments after the sink, assignments on incompatible paths, and overwritten locals cannot establish provenance. +- Match the mm lifetime APIs and struct mm_struct type as stable project-level semantics, without encoding binder_update_page_range, binder_alloc.c, local variable names, patch lines, commit identifiers, or unique patch literals. +- Emit the diagnostic at the synchronous mmput() call and keep mmput_async() outside the report condition. + +### Validation checklist + +- Compile and load the synthesized checker successfully with the configured Clang Static Analyzer toolchain and verify checker registration. +- Scan the vulnerable source and retain relevant diagnostics at both synchronous mmput(mm) sites in binder_update_page_range(), with diagnostics located on the release calls. +- Scan the patched source and require zero diagnostics after both releases become mmput_async(mm). +- Run code verification and preserve the established before/after differential, patch-function relevance, zero far warnings, and accepted refinement result. +- Add a case where mmget_not_zero() occurs after mmput() and require no report. +- Add cases where acquisition and release are on mutually exclusive paths or acquisition returns false and require no report. +- Add cases with an intervening overwrite or distinct mm_struct value and require no report, while retaining a report through supported aliases or assignments on the same feasible path. +- Confirm current-task-owned releases and mmput() calls without a proven successful matching pin remain silent. + +### Avoid and forbidden regressions + +- Do not repeat flow-insensitive collection of every pin and assignment in a function body. +- Do not infer successful acquisition from the mere syntactic presence of mmget_not_zero(). +- Do not treat structural expression equivalence alone as proof of ordering, reachability, or a reaching definition. +- Do not fall back to substring matching, exact changed-file or function targeting, source locations, local identifiers, or other patch anchors. +- Do not claim that all mmget_not_zero() references are inherently foreign or that the checker proves the runtime final-reference race itself. diff --git a/tasks/csa159/pair_142288/checker_template.cpp b/tasks/csa159/pair_142288/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_142288/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_142288/config.json b/tasks/csa159/pair_142288/config.json new file mode 100644 index 0000000000000000000000000000000000000000..3b9bddc9ca6e28e1d0dba551003792e125d7c53c --- /dev/null +++ b/tasks/csa159/pair_142288/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "b2fef875aa6f78dfa89a943282d6dbeaf0dd2095", + "after_commit": "004d25060c78fc31f66da0fa439c544dda1ac9d5", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/f0ec58d557d65838974035ffd8a8862cf8166a81/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/f0ec58d557d65838974035ffd8a8862cf8166a81/compile_commands.json", + "changed_files": [ + "drivers/net/ethernet/intel/igb/igb_main.c" + ], + "commit_message": "igb: Fix igb_down hung on surprise removal\n\nIn a setup where a Thunderbolt hub connects to Ethernet and a display\nthrough USB Type-C, users may experience a hung task timeout when they\nremove the cable between the PC and the Thunderbolt hub.\nThis is because the igb_down function is called multiple times when\nthe Thunderbolt hub is unplugged. For example, the igb_io_error_detected\ntriggers the first call, and the igb_remove triggers the second call.\nThe second call to igb_down will block at napi_synchronize.\nHere's the call trace:\n __schedule+0x3b0/0xddb\n ? __mod_timer+0x164/0x5d3\n schedule+0x44/0xa8\n schedule_timeout+0xb2/0x2a4\n ? run_local_timers+0x4e/0x4e\n msleep+0x31/0x38\n igb_down+0x12c/0x22a [igb 6615058754948bfde0bf01429257eb59f13030d4]\n __igb_close+0x6f/0x9c [igb 6615058754948bfde0bf01429257eb59f13030d4]\n igb_close+0x23/0x2b [igb 6615058754948bfde0bf01429257eb59f13030d4]\n __dev_close_many+0x95/0xec\n dev_close_many+0x6e/0x103\n unregister_netdevice_many+0x105/0x5b1\n unregister_netdevice_queue+0xc2/0x10d\n unregister_netdev+0x1c/0x23\n igb_remove+0xa7/0x11c [igb 6615058754948bfde0bf01429257eb59f13030d4]\n pci_device_remove+0x3f/0x9c\n device_release_driver_internal+0xfe/0x1b4\n pci_stop_bus_device+0x5b/0x7f\n pci_stop_bus_device+0x30/0x7f\n pci_stop_bus_device+0x30/0x7f\n pci_stop_and_remove_bus_device+0x12/0x19\n pciehp_unconfigure_device+0x76/0xe9\n pciehp_disable_slot+0x6e/0x131\n pciehp_handle_presence_or_link_change+0x7a/0x3f7\n pciehp_ist+0xbe/0x194\n irq_thread_fn+0x22/0x4d\n ? irq_thread+0x1fd/0x1fd\n irq_thread+0x17b/0x1fd\n ? irq_forced_thread_fn+0x5f/0x5f\n kthread+0x142/0x153\n ? __irq_get_irqchip_state+0x46/0x46\n ? kthread_associate_blkcg+0x71/0x71\n ret_from_fork+0x1f/0x30\n\nIn this case, igb_io_error_detected detaches the network interface\nand requests a PCIE slot reset, however, the PCIE reset callback is\nnot being invoked and thus the Ethernet connection breaks down.\nAs the PCIE error in this case is a non-fatal one, requesting a\nslot reset can be avoided.\nThis patch fixes the task hung issue and preserves Ethernet\nconnection by ignoring non-fatal PCIE errors.\n\nSigned-off-by: Ying Hsu \nTested-by: Pucha Himasekhar Reddy (A Contingent worker at Intel)\nSigned-off-by: Tony Nguyen \nReviewed-by: Simon Horman \nLink: https://lore.kernel.org/r/20230620174732.4145155-1-anthony.l.nguyen@intel.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_142288/patch.diff b/tasks/csa159/pair_142288/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..272dd004949ae9f179c10b0010f0934d8280cab4 --- /dev/null +++ b/tasks/csa159/pair_142288/patch.diff @@ -0,0 +1,16 @@ +diff --git a/drivers/net/ethernet/intel/igb/igb_main.c b/drivers/net/ethernet/intel/igb/igb_main.c +index 9fcac96022d7..9a2561409b06 100644 +--- a/drivers/net/ethernet/intel/igb/igb_main.c ++++ b/drivers/net/ethernet/intel/igb/igb_main.c +@@ -9587,6 +9587,11 @@ static pci_ers_result_t igb_io_error_detected(struct pci_dev *pdev, + struct net_device *netdev = pci_get_drvdata(pdev); + struct igb_adapter *adapter = netdev_priv(netdev); + ++ if (state == pci_channel_io_normal) { ++ dev_warn(&pdev->dev, "Non-correctable non-fatal error reported.\n"); ++ return PCI_ERS_RESULT_CAN_RECOVER; ++ } ++ + netif_device_detach(netdev); + + if (state == pci_channel_io_perm_failure) \ No newline at end of file diff --git a/tasks/csa159/pair_142288/post_functions.txt b/tasks/csa159/pair_142288/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..a5b6bdbc535786b0294def7a2ae367fe4ab22c7d --- /dev/null +++ b/tasks/csa159/pair_142288/post_functions.txt @@ -0,0 +1,26 @@ +### File: drivers/net/ethernet/intel/igb/igb_main.c +```c +static pci_ers_result_t igb_io_error_detected(struct pci_dev *pdev, + pci_channel_state_t state) +{ + struct net_device *netdev = pci_get_drvdata(pdev); + struct igb_adapter *adapter = netdev_priv(netdev); + + if (state == pci_channel_io_normal) { + dev_warn(&pdev->dev, "Non-correctable non-fatal error reported.\n"); + return PCI_ERS_RESULT_CAN_RECOVER; + } + + netif_device_detach(netdev); + + if (state == pci_channel_io_perm_failure) + return PCI_ERS_RESULT_DISCONNECT; + + if (netif_running(netdev)) + igb_down(adapter); + pci_disable_device(pdev); + + /* Request a slot reset. */ + return PCI_ERS_RESULT_NEED_RESET; +} +``` diff --git a/tasks/csa159/pair_142288/pre_functions.txt b/tasks/csa159/pair_142288/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2db7f1a7fd8491f75b584ad7c31704cfbe9b4b4b --- /dev/null +++ b/tasks/csa159/pair_142288/pre_functions.txt @@ -0,0 +1,21 @@ +### File: drivers/net/ethernet/intel/igb/igb_main.c +```c +static pci_ers_result_t igb_io_error_detected(struct pci_dev *pdev, + pci_channel_state_t state) +{ + struct net_device *netdev = pci_get_drvdata(pdev); + struct igb_adapter *adapter = netdev_priv(netdev); + + netif_device_detach(netdev); + + if (state == pci_channel_io_perm_failure) + return PCI_ERS_RESULT_DISCONNECT; + + if (netif_running(netdev)) + igb_down(adapter); + pci_disable_device(pdev); + + /* Request a slot reset. */ + return PCI_ERS_RESULT_NEED_RESET; +} +``` diff --git a/tasks/csa159/pair_142288/task_prompt.md b/tasks/csa159/pair_142288/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_142288/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_142376/checker_template.cpp b/tasks/csa159/pair_142376/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_142376/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_142376/config.json b/tasks/csa159/pair_142376/config.json new file mode 100644 index 0000000000000000000000000000000000000000..e780b6f228b20c1fe96db2135c7ae7ebe10fcd2d --- /dev/null +++ b/tasks/csa159/pair_142376/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "96b45776995653a4971329c7f62ff6aa324027a2", + "after_commit": "18e126e97c961f7a93823795c879d7c085fe5098", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/895ae5bee159d148bac21a82899292c408c1aab1/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/895ae5bee159d148bac21a82899292c408c1aab1/compile_commands.json", + "changed_files": [ + "drivers/firmware/dmi-sysfs.c" + ], + "commit_message": "firmware: dmi-sysfs: Fix null-ptr-deref in dmi_sysfs_register_handle\n\nKASAN reported a null-ptr-deref error:\n\nKASAN: null-ptr-deref in range [0x0000000000000008-0x000000000000000f]\nCPU: 0 PID: 1373 Comm: modprobe\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996)\nRIP: 0010:dmi_sysfs_entry_release\n...\nCall Trace:\n \n kobject_put\n dmi_sysfs_register_handle (drivers/firmware/dmi-sysfs.c:540) dmi_sysfs\n dmi_decode_table (drivers/firmware/dmi_scan.c:133)\n dmi_walk (drivers/firmware/dmi_scan.c:1115)\n dmi_sysfs_init (drivers/firmware/dmi-sysfs.c:149) dmi_sysfs\n do_one_initcall (init/main.c:1296)\n ...\nKernel panic - not syncing: Fatal exception\nKernel Offset: 0x4000000 from 0xffffffff81000000\n---[ end Kernel panic - not syncing: Fatal exception ]---\n\nIt is because previous patch added kobject_put() to release the memory\nwhich will call dmi_sysfs_entry_release() and list_del().\n\nHowever, list_add_tail(entry->list) is called after the error block,\nso the list_head is uninitialized and cannot be deleted.\n\nMove error handling to after list_add_tail to fix this.\n\nFixes: 660ba678f999 (\"firmware: dmi-sysfs: Fix memory leak in dmi_sysfs_register_handle\")\nSigned-off-by: Chen Zhongjin \nLink: https://lore.kernel.org/r/20221111015326.251650-2-chenzhongjin@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_142376/patch.diff b/tasks/csa159/pair_142376/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e6c2f6be1e0ec7c2d8d9e8800ea2d0d0099c18f3 --- /dev/null +++ b/tasks/csa159/pair_142376/patch.diff @@ -0,0 +1,26 @@ +diff --git a/drivers/firmware/dmi-sysfs.c b/drivers/firmware/dmi-sysfs.c +index 9b6ce172175c..ed5aff0a4204 100644 +--- a/drivers/firmware/dmi-sysfs.c ++++ b/drivers/firmware/dmi-sysfs.c +@@ -603,16 +603,16 @@ static void __init dmi_sysfs_register_handle(const struct dmi_header *dh, + *ret = kobject_init_and_add(&entry->kobj, &dmi_sysfs_entry_ktype, NULL, + "%d-%d", dh->type, entry->instance); + +- if (*ret) { +- kobject_put(&entry->kobj); +- return; +- } +- + /* Thread on the global list for cleanup */ + spin_lock(&entry_list_lock); + list_add_tail(&entry->list, &entry_list); + spin_unlock(&entry_list_lock); + ++ if (*ret) { ++ kobject_put(&entry->kobj); ++ return; ++ } ++ + /* Handle specializations by type */ + switch (dh->type) { + case DMI_ENTRY_SYSTEM_EVENT_LOG: \ No newline at end of file diff --git a/tasks/csa159/pair_142376/post_functions.txt b/tasks/csa159/pair_142376/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..f3f28306e40a5c022ee213da57b0a665c8eb4a51 --- /dev/null +++ b/tasks/csa159/pair_142376/post_functions.txt @@ -0,0 +1,62 @@ +### File: drivers/firmware/dmi-sysfs.c +```c +static void __init dmi_sysfs_register_handle(const struct dmi_header *dh, + void *_ret) +{ + struct dmi_sysfs_entry *entry; + int *ret = _ret; + + /* If a previous entry saw an error, short circuit */ + if (*ret) + return; + + /* Allocate and register a new entry into the entries set */ + entry = kzalloc(sizeof(*entry), GFP_KERNEL); + if (!entry) { + *ret = -ENOMEM; + return; + } + + /* Set the key */ + memcpy(&entry->dh, dh, sizeof(*dh)); + entry->instance = instance_counts[dh->type]++; + entry->position = position_count++; + + entry->kobj.kset = dmi_kset; + *ret = kobject_init_and_add(&entry->kobj, &dmi_sysfs_entry_ktype, NULL, + "%d-%d", dh->type, entry->instance); + + /* Thread on the global list for cleanup */ + spin_lock(&entry_list_lock); + list_add_tail(&entry->list, &entry_list); + spin_unlock(&entry_list_lock); + + if (*ret) { + kobject_put(&entry->kobj); + return; + } + + /* Handle specializations by type */ + switch (dh->type) { + case DMI_ENTRY_SYSTEM_EVENT_LOG: + *ret = dmi_system_event_log(entry); + break; + default: + /* No specialization */ + break; + } + if (*ret) + goto out_err; + + /* Create the raw binary file to access the entry */ + *ret = sysfs_create_bin_file(&entry->kobj, &dmi_entry_raw_attr); + if (*ret) + goto out_err; + + return; +out_err: + kobject_put(entry->child); + kobject_put(&entry->kobj); + return; +} +``` diff --git a/tasks/csa159/pair_142376/pre_functions.txt b/tasks/csa159/pair_142376/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..8cf9b17c1d0a17f1f1139672bfc5be4ce96a7bff --- /dev/null +++ b/tasks/csa159/pair_142376/pre_functions.txt @@ -0,0 +1,62 @@ +### File: drivers/firmware/dmi-sysfs.c +```c +static void __init dmi_sysfs_register_handle(const struct dmi_header *dh, + void *_ret) +{ + struct dmi_sysfs_entry *entry; + int *ret = _ret; + + /* If a previous entry saw an error, short circuit */ + if (*ret) + return; + + /* Allocate and register a new entry into the entries set */ + entry = kzalloc(sizeof(*entry), GFP_KERNEL); + if (!entry) { + *ret = -ENOMEM; + return; + } + + /* Set the key */ + memcpy(&entry->dh, dh, sizeof(*dh)); + entry->instance = instance_counts[dh->type]++; + entry->position = position_count++; + + entry->kobj.kset = dmi_kset; + *ret = kobject_init_and_add(&entry->kobj, &dmi_sysfs_entry_ktype, NULL, + "%d-%d", dh->type, entry->instance); + + if (*ret) { + kobject_put(&entry->kobj); + return; + } + + /* Thread on the global list for cleanup */ + spin_lock(&entry_list_lock); + list_add_tail(&entry->list, &entry_list); + spin_unlock(&entry_list_lock); + + /* Handle specializations by type */ + switch (dh->type) { + case DMI_ENTRY_SYSTEM_EVENT_LOG: + *ret = dmi_system_event_log(entry); + break; + default: + /* No specialization */ + break; + } + if (*ret) + goto out_err; + + /* Create the raw binary file to access the entry */ + *ret = sysfs_create_bin_file(&entry->kobj, &dmi_entry_raw_attr); + if (*ret) + goto out_err; + + return; +out_err: + kobject_put(entry->child); + kobject_put(&entry->kobj); + return; +} +``` diff --git a/tasks/csa159/pair_142376/task_prompt.md b/tasks/csa159/pair_142376/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..bf2d97ed9ac48bf1a9116e3f675fbbb91f1ba31e --- /dev/null +++ b/tasks/csa159/pair_142376/task_prompt.md @@ -0,0 +1,375 @@ +# 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 feedback_required after one round); compile, before/after detection, code verification, G6, and semantic adequacy were already proven and are not the repair target. +- Refinement stayed unclean because callee matching used Lexer source-text fallbacks (source_text_matching detected) rather than IdentifierInfo/FunctionDecl identity, even though the 2-before/0-after differential was correct. +- A fresh synthesis must re-establish the accepted path-sensitive alloc-then-put-before-link proof without text matching, patch anchors, or reuse of the prior plugin. + +### Preserve from prior rollouts + +- Preserve successful compile, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve the previously adequate CSA path-sensitive mechanism level; do not weaken it to AST or CFG-only. +- Preserve semantic score at or above the configured threshold (prior adequate score 9.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 + +- Report only when a current-path kernel heap allocation of a record embedding both struct kobject and struct list_head reaches kobject_put on the embedded kobject FieldRegion while every sibling list_head FieldRegion of that same base is still missing from the path's linked/initialized set. +- Treat the patched dmi-sysfs reorder as safe: if list_add/list_add_tail/list_add_rcu/list_add_tail_rcu or INIT_LIST_HEAD already executed on that sibling list_head of the same allocated base, the later kobject_put must be suppressed. +- Keep the pre-patch kobject_init_and_add *ret error-path put as the true positive, and do not flag the post-link out_err kobject_put(&entry->kobj) or kobject_put on non-embedded pointers such as entry->child. + +### Implementation constraints + +- Use check::PostCall on kzalloc-family kernel allocators to record the returned container SymbolRef/base, and check::PreCall to register list_add-family/INIT_LIST_HEAD arg0 list_head FieldRegions and to sink only at kobject_put. +- Carry allocated-container identity and linked list_head FieldRegions in ProgramState GDM sets so the sink compares the kobject FieldRegion base against the allocated set and sibling list FieldRegions against the linked set. +- Emit a PathSensitiveBugReport via generateNonFatalErrorNode anchored at the kobject_put CallEvent source range inside the analyzed function. +- Identify callees only through CallEvent IdentifierInfo or FunctionDecl names; do not use Lexer::getSourceText or other token-text matching. +- Keep scope kernel-general (allocator family, kobject_put, list_add family, INIT_LIST_HEAD, kobject/list_head field types) with no dmi-sysfs file, function, type, or line literals. +- Remain intra-procedural: do not follow kobj_type::release, do not sink on list_del, and do not model kobject refcount arithmetic. + +### Validation checklist + +- Compile the new plugin to a loadable .so with the registered checker name actually used by the scan scripts. +- Before-patch scan of drivers/firmware/dmi-sysfs.c::dmi_sysfs_register_handle must warn at the kobject_put on the kobject_init_and_add *ret error path (pre-patch ~line 607). +- After-patch scan of the same translation unit must yield zero findings from this checker, including the reordered *ret put and the out_err kobject_put(&entry->kobj). +- Diagnostic location must be the kobject_put call expression (median distance 0 from the pre-patch put), not kzalloc, list_add_tail, or kobject_init_and_add. +- No reports in non-patched functions; keep n_patched=0, relevance_ratio=1, sparsity_ratio=1, and G6 all-checks-passed. +- Re-run refinement until accepted/clean with source_text_matching false and no patch-local anchors. + +### Avoid and forbidden regressions + +- Do not copy, repair, resume, or reconstruct the prior checker.cpp/.so; synthesize from the original patch and pre/post functions only. +- Do not substitute CFG dominance, stmtDominates, PostStmt-only sinks, or syntactic guards for path-sensitive container identity. +- Do not analyze list_del in release handlers or propagate facts interprocedurally through kobj_type::release. +- Do not hardcode CVE-2023-53250 identifiers such as dmi_sysfs_register_handle, dmi_sysfs_entry, dmi-sysfs.c, or patch line numbers. +- Do not match callees with Lexer source-text, macro spelling, or startswith/starts_with token heuristics. +- Do not report standalone kobject pointers, containers not allocated on the current path, or records that lack a sibling list_head. +- Do not regress hard_validation, objective_gate, semantic_mechanism, semantic_score, process_score, anchor_free, or hardcoding_free. diff --git a/tasks/csa159/pair_142647/checker_template.cpp b/tasks/csa159/pair_142647/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_142647/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_142647/config.json b/tasks/csa159/pair_142647/config.json new file mode 100644 index 0000000000000000000000000000000000000000..d918774403441e92013c10832a7cdca39b4264d9 --- /dev/null +++ b/tasks/csa159/pair_142647/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "3b1088a09ec9438523c251d8435e78988824bc0d", + "after_commit": "5a78ac33e3cb8822da64dd1af196e83664b332b0", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/298e50ad8eb8fa12ea68bb2da45bb8ef4edcd0ec/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/298e50ad8eb8fa12ea68bb2da45bb8ef4edcd0ec/compile_commands.json", + "changed_files": [ + "drivers/net/wireless/ath/ath11k/ahb.c" + ], + "commit_message": "wifi: ath11k: fix deinitialization of firmware resources\n\nCurrently, in ath11k_ahb_fw_resources_init(), iommu domain\nmapping is done only for the chipsets having fixed firmware\nmemory. Also, for such chipsets, mapping is done only if it\ndoes not have TrustZone support.\n\nDuring deinitialization, only if TrustZone support is not there,\niommu is unmapped back. However, for non fixed firmware memory\nchipsets, TrustZone support is not there and this makes the\ncondition check to true and it tries to unmap the memory which\nwas not mapped during initialization.\n\nThis leads to the following trace -\n\n[ 83.198790] Unable to handle kernel NULL pointer dereference at virtual address 0000000000000008\n[ 83.259537] Modules linked in: ath11k_ahb ath11k qmi_helpers\n.. snip ..\n[ 83.280286] pstate: 20000005 (nzCv daif -PAN -UAO -TCO -DIT -SSBS BTYPE=--)\n[ 83.287228] pc : __iommu_unmap+0x30/0x140\n[ 83.293907] lr : iommu_unmap+0x5c/0xa4\n[ 83.298072] sp : ffff80000b3abad0\n.. snip ..\n[ 83.369175] Call trace:\n[ 83.376282] __iommu_unmap+0x30/0x140\n[ 83.378541] iommu_unmap+0x5c/0xa4\n[ 83.382360] ath11k_ahb_fw_resource_deinit.part.12+0x2c/0xac [ath11k_ahb]\n[ 83.385666] ath11k_ahb_free_resources+0x140/0x17c [ath11k_ahb]\n[ 83.392521] ath11k_ahb_shutdown+0x34/0x40 [ath11k_ahb]\n[ 83.398248] platform_shutdown+0x20/0x2c\n[ 83.403455] device_shutdown+0x16c/0x1c4\n[ 83.407621] kernel_restart_prepare+0x34/0x3c\n[ 83.411529] kernel_restart+0x14/0x74\n[ 83.415781] __do_sys_reboot+0x1c4/0x22c\n[ 83.419427] __arm64_sys_reboot+0x1c/0x24\n[ 83.423420] invoke_syscall+0x44/0xfc\n[ 83.427326] el0_svc_common.constprop.3+0xac/0xe8\n[ 83.430974] do_el0_svc+0xa0/0xa8\n[ 83.435659] el0_svc+0x1c/0x44\n[ 83.438957] el0t_64_sync_handler+0x60/0x144\n[ 83.441910] el0t_64_sync+0x15c/0x160\n[ 83.446343] Code: aa0103f4 f9400001 f90027a1 d2800001 (f94006a0)\n[ 83.449903] ---[ end trace 0000000000000000 ]---\n\nThis can be reproduced by probing an AHB chipset which is not\nhaving a fixed memory region. During reboot (or rmmod) trace\ncan be seen.\n\nFix this issue by adding a condition check on firmware fixed memory\nhw_param as done in the counter initialization function.\n\nTested-on: IPQ8074 hw2.0 AHB WLAN.HK.2.7.0.1-01744-QCAHKSWPL_SILICONZ-1\n\nFixes: f9eec4947add (\"ath11k: Add support for targets without trustzone\")\nSigned-off-by: Aditya Kumar Singh \nSigned-off-by: Kalle Valo \nLink: https://lore.kernel.org/r/20230309095308.24937-1-quic_adisi@quicinc.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_142647/patch.diff b/tasks/csa159/pair_142647/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7c50d247a84c71568999dcc01153d16d6e254a28 --- /dev/null +++ b/tasks/csa159/pair_142647/patch.diff @@ -0,0 +1,16 @@ +diff --git a/drivers/net/wireless/ath/ath11k/ahb.c b/drivers/net/wireless/ath/ath11k/ahb.c +index b549576d0b51..5cbba9a8b6ba 100644 +--- a/drivers/net/wireless/ath/ath11k/ahb.c ++++ b/drivers/net/wireless/ath/ath11k/ahb.c +@@ -1078,6 +1078,12 @@ static int ath11k_ahb_fw_resource_deinit(struct ath11k_base *ab) + struct iommu_domain *iommu; + size_t unmapped_size; + ++ /* Chipsets not requiring MSA would have not initialized ++ * MSA resources, return success in such cases. ++ */ ++ if (!ab->hw_params.fixed_fw_mem) ++ return 0; ++ + if (ab_ahb->fw.use_tz) + return 0; \ No newline at end of file diff --git a/tasks/csa159/pair_142647/post_functions.txt b/tasks/csa159/pair_142647/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..ed82acb597073d0a5fff1c7858bd708e78a65865 --- /dev/null +++ b/tasks/csa159/pair_142647/post_functions.txt @@ -0,0 +1,37 @@ +### File: drivers/net/wireless/ath/ath11k/ahb.c +```c +static int ath11k_ahb_fw_resource_deinit(struct ath11k_base *ab) +{ + struct ath11k_ahb *ab_ahb = ath11k_ahb_priv(ab); + struct iommu_domain *iommu; + size_t unmapped_size; + + /* Chipsets not requiring MSA would have not initialized + * MSA resources, return success in such cases. + */ + if (!ab->hw_params.fixed_fw_mem) + return 0; + + if (ab_ahb->fw.use_tz) + return 0; + + iommu = ab_ahb->fw.iommu_domain; + + unmapped_size = iommu_unmap(iommu, ab_ahb->fw.msa_paddr, ab_ahb->fw.msa_size); + if (unmapped_size != ab_ahb->fw.msa_size) + ath11k_err(ab, "failed to unmap firmware: %zu\n", + unmapped_size); + + unmapped_size = iommu_unmap(iommu, ab_ahb->fw.ce_paddr, ab_ahb->fw.ce_size); + if (unmapped_size != ab_ahb->fw.ce_size) + ath11k_err(ab, "failed to unmap firmware CE memory: %zu\n", + unmapped_size); + + iommu_detach_device(iommu, ab_ahb->fw.dev); + iommu_domain_free(iommu); + + platform_device_unregister(to_platform_device(ab_ahb->fw.dev)); + + return 0; +} +``` diff --git a/tasks/csa159/pair_142647/pre_functions.txt b/tasks/csa159/pair_142647/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..732e97f80d271b1e226b972e278868ce2b1effeb --- /dev/null +++ b/tasks/csa159/pair_142647/pre_functions.txt @@ -0,0 +1,31 @@ +### File: drivers/net/wireless/ath/ath11k/ahb.c +```c +static int ath11k_ahb_fw_resource_deinit(struct ath11k_base *ab) +{ + struct ath11k_ahb *ab_ahb = ath11k_ahb_priv(ab); + struct iommu_domain *iommu; + size_t unmapped_size; + + if (ab_ahb->fw.use_tz) + return 0; + + iommu = ab_ahb->fw.iommu_domain; + + unmapped_size = iommu_unmap(iommu, ab_ahb->fw.msa_paddr, ab_ahb->fw.msa_size); + if (unmapped_size != ab_ahb->fw.msa_size) + ath11k_err(ab, "failed to unmap firmware: %zu\n", + unmapped_size); + + unmapped_size = iommu_unmap(iommu, ab_ahb->fw.ce_paddr, ab_ahb->fw.ce_size); + if (unmapped_size != ab_ahb->fw.ce_size) + ath11k_err(ab, "failed to unmap firmware CE memory: %zu\n", + unmapped_size); + + iommu_detach_device(iommu, ab_ahb->fw.dev); + iommu_domain_free(iommu); + + platform_device_unregister(to_platform_device(ab_ahb->fw.dev)); + + return 0; +} +``` diff --git a/tasks/csa159/pair_142647/task_prompt.md b/tasks/csa159/pair_142647/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_142647/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_142793/checker_template.cpp b/tasks/csa159/pair_142793/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_142793/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_142793/config.json b/tasks/csa159/pair_142793/config.json new file mode 100644 index 0000000000000000000000000000000000000000..be6b54331f42c853a2ec53354194aa6c69101597 --- /dev/null +++ b/tasks/csa159/pair_142793/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "1e346cbb096a5351a637ec1992beffbf330547f0", + "after_commit": "803f3176c5df3b5582c27ea690f204abb60b19b9", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/3dfb8e844fa30cceb4b810613e2c35f628eb3e70/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/3dfb8e844fa30cceb4b810613e2c35f628eb3e70/compile_commands.json", + "changed_files": [ + "drivers/net/wireless/mediatek/mt7601u/dma.c" + ], + "commit_message": "wifi: mt7601u: fix an integer underflow\n\nFix an integer underflow that leads to a null pointer dereference in\n'mt7601u_rx_skb_from_seg()'. The variable 'dma_len' in the URB packet\ncould be manipulated, which could trigger an integer underflow of\n'seg_len' in 'mt7601u_rx_process_seg()'. This underflow subsequently\ncauses the 'bad_frame' checks in 'mt7601u_rx_skb_from_seg()' to be\nbypassed, eventually leading to a dereference of the pointer 'p', which\nis a null pointer.\n\nEnsure that 'dma_len' is greater than 'min_seg_len'.\n\nFound by a modified version of syzkaller.\n\nKASAN: null-ptr-deref in range [0x0000000000000008-0x000000000000000f]\nCPU: 0 PID: 12 Comm: ksoftirqd/0 Tainted: G W O 5.14.0+\n#139\nHardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS\nrel-1.12.1-0-ga5cab58e9a3f-prebuilt.qemu.org 04/01/2014\nRIP: 0010:skb_add_rx_frag+0x143/0x370\nCode: e2 07 83 c2 03 38 ca 7c 08 84 c9 0f 85 86 01 00 00 4c 8d 7d 08 44\n89 68 08 48 b8 00 00 00 00 00 fc ff df 4c 89 fa 48 c1 ea 03 <80> 3c 02\n00 0f 85 cd 01 00 00 48 8b 45 08 a8 01 0f 85 3d 01 00 00\nRSP: 0018:ffffc900000cfc90 EFLAGS: 00010202\nRAX: dffffc0000000000 RBX: ffff888115520dc0 RCX: 0000000000000000\nRDX: 0000000000000001 RSI: ffff8881118430c0 RDI: ffff8881118430f8\nRBP: 0000000000000000 R08: 0000000000000e09 R09: 0000000000000010\nR10: ffff888111843017 R11: ffffed1022308602 R12: 0000000000000000\nR13: 0000000000000e09 R14: 0000000000000010 R15: 0000000000000008\nFS: 0000000000000000(0000) GS:ffff88811a800000(0000)\nknlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 000000004035af40 CR3: 00000001157f2000 CR4: 0000000000750ef0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\nPKRU: 55555554\nCall Trace:\n mt7601u_rx_tasklet+0xc73/0x1270\n ? mt7601u_submit_rx_buf.isra.0+0x510/0x510\n ? tasklet_action_common.isra.0+0x79/0x2f0\n tasklet_action_common.isra.0+0x206/0x2f0\n __do_softirq+0x1b5/0x880\n ? tasklet_unlock+0x30/0x30\n run_ksoftirqd+0x26/0x50\n smpboot_thread_fn+0x34f/0x7d0\n ? smpboot_register_percpu_thread+0x370/0x370\n kthread+0x3a1/0x480\n ? set_kthread_struct+0x120/0x120\n ret_from_fork+0x1f/0x30\nModules linked in: 88XXau(O) 88x2bu(O)\n---[ end trace 57f34f93b4da0f9b ]---\nRIP: 0010:skb_add_rx_frag+0x143/0x370\nCode: e2 07 83 c2 03 38 ca 7c 08 84 c9 0f 85 86 01 00 00 4c 8d 7d 08 44\n89 68 08 48 b8 00 00 00 00 00 fc ff df 4c 89 fa 48 c1 ea 03 <80> 3c 02\n00 0f 85 cd 01 00 00 48 8b 45 08 a8 01 0f 85 3d 01 00 00\nRSP: 0018:ffffc900000cfc90 EFLAGS: 00010202\nRAX: dffffc0000000000 RBX: ffff888115520dc0 RCX: 0000000000000000\nRDX: 0000000000000001 RSI: ffff8881118430c0 RDI: ffff8881118430f8\nRBP: 0000000000000000 R08: 0000000000000e09 R09: 0000000000000010\nR10: ffff888111843017 R11: ffffed1022308602 R12: 0000000000000000\nR13: 0000000000000e09 R14: 0000000000000010 R15: 0000000000000008\nFS: 0000000000000000(0000) GS:ffff88811a800000(0000)\nknlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: 000000004035af40 CR3: 00000001157f2000 CR4: 0000000000750ef0\nDR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000\nDR3: 0000000000000000 DR6: 00000000fffe0ff0 DR7: 0000000000000400\nPKRU: 55555554\n\nSigned-off-by: Jisoo Jang \nAcked-by: Jakub Kicinski \nSigned-off-by: Kalle Valo \nLink: https://lore.kernel.org/r/20221229092906.2328282-1-jisoo.jang@yonsei.ac.kr", + "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_142793/patch.diff b/tasks/csa159/pair_142793/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4c37081cadef9b666c881d5019158de68c6e44d8 --- /dev/null +++ b/tasks/csa159/pair_142793/patch.diff @@ -0,0 +1,14 @@ +diff --git a/drivers/net/wireless/mediatek/mt7601u/dma.c b/drivers/net/wireless/mediatek/mt7601u/dma.c +index 457147394edc..773a1cc2f852 100644 +--- a/drivers/net/wireless/mediatek/mt7601u/dma.c ++++ b/drivers/net/wireless/mediatek/mt7601u/dma.c +@@ -123,7 +123,8 @@ static u16 mt7601u_rx_next_seg_len(u8 *data, u32 data_len) + if (data_len < min_seg_len || + WARN_ON_ONCE(!dma_len) || + WARN_ON_ONCE(dma_len + MT_DMA_HDRS > data_len) || +- WARN_ON_ONCE(dma_len & 0x3)) ++ WARN_ON_ONCE(dma_len & 0x3) || ++ WARN_ON_ONCE(dma_len < min_seg_len)) + return 0; + + return MT_DMA_HDRS + dma_len; \ No newline at end of file diff --git a/tasks/csa159/pair_142793/post_functions.txt b/tasks/csa159/pair_142793/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..6d0aef67dc10b7c56692dc8809b4100d186a550b --- /dev/null +++ b/tasks/csa159/pair_142793/post_functions.txt @@ -0,0 +1,18 @@ +### File: drivers/net/wireless/mediatek/mt7601u/dma.c +```c +static u16 mt7601u_rx_next_seg_len(u8 *data, u32 data_len) +{ + u32 min_seg_len = MT_DMA_HDR_LEN + MT_RX_INFO_LEN + + sizeof(struct mt7601u_rxwi) + MT_FCE_INFO_LEN; + u16 dma_len = get_unaligned_le16(data); + + if (data_len < min_seg_len || + WARN_ON_ONCE(!dma_len) || + WARN_ON_ONCE(dma_len + MT_DMA_HDRS > data_len) || + WARN_ON_ONCE(dma_len & 0x3) || + WARN_ON_ONCE(dma_len < min_seg_len)) + return 0; + + return MT_DMA_HDRS + dma_len; +} +``` diff --git a/tasks/csa159/pair_142793/pre_functions.txt b/tasks/csa159/pair_142793/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..ea8e4055dd0c792caa3c3eb5cdbcaa91d181bb50 --- /dev/null +++ b/tasks/csa159/pair_142793/pre_functions.txt @@ -0,0 +1,54 @@ +### File: drivers/net/wireless/mediatek/mt7601u/dma.c +```c +static u16 mt7601u_rx_next_seg_len(u8 *data, u32 data_len) +{ + u32 min_seg_len = MT_DMA_HDR_LEN + MT_RX_INFO_LEN + + sizeof(struct mt7601u_rxwi) + MT_FCE_INFO_LEN; + u16 dma_len = get_unaligned_le16(data); + + if (data_len < min_seg_len || + WARN_ON_ONCE(!dma_len) || + WARN_ON_ONCE(dma_len + MT_DMA_HDRS > data_len) || + WARN_ON_ONCE(dma_len & 0x3)) + return 0; + + return MT_DMA_HDRS + dma_len; +} + +static void +mt7601u_rx_process_entry(struct mt7601u_dev *dev, struct mt7601u_dma_buf_rx *e) +{ + u32 seg_len, data_len = e->urb->actual_length; + u8 *data = page_address(e->p); + struct page *new_p = NULL; + LIST_HEAD(list); + int cnt = 0; + + if (!test_bit(MT7601U_STATE_INITIALIZED, &dev->state)) + return; + + /* Copy if there is very little data in the buffer. */ + if (data_len > 512) + new_p = dev_alloc_pages(MT_RX_ORDER); + + while ((seg_len = mt7601u_rx_next_seg_len(data, data_len))) { + mt7601u_rx_process_seg(dev, data, seg_len, + new_p ? e->p : NULL, &list); + + data_len -= seg_len; + data += seg_len; + cnt++; + } + + if (cnt > 1) + trace_mt_rx_dma_aggr(dev, cnt, !!new_p); + + netif_receive_skb_list(&list); + + if (new_p) { + /* we have one extra ref from the allocator */ + put_page(e->p); + e->p = new_p; + } +} +``` diff --git a/tasks/csa159/pair_142793/task_prompt.md b/tasks/csa159/pair_142793/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..c74e780f352327641306e1a35ac3ec5c5342540d --- /dev/null +++ b/tasks/csa159/pair_142793/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: `interprocedural_dataflow` + +### Current failure diagnosis + +- The rollout failed only the process-quality threshold; compilation, differential detection, objective gate G6, refinement, code verification, semantic mechanism, and semantic score all passed. +- The semantic argument overstated the vulnerable range: the shown subtraction underflows only when the produced segment length is below the total stripped-header amount, not for every dma_len below min_seg_len. +- The design substituted translation-unit source order for CFG dominance and did not prove that the rejecting branch is the branch taken for an insufficient length. +- Producer-to-consumer matching ignored assignment and call ordering, while consumer matching did not prove that the accumulated subtraction can exceed the produced unsigned length. +- An arbitrary lower-bound-shaped comparison was accepted without proving that its bound is sufficient to prevent the downstream arithmetic underflow. + +### 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 at least the previously accepted cross-procedure CSA mechanism level and the configured semantic-score threshold. +- Remain independent of patch anchors such as changed line numbers, commit identity, or exact diff placement. +- Remain free of patch-local hardcoding such as affected function names, local variable names, and unique constants. + +### Required semantic proof + +- Identify an unsigned packet-derived length L and a producer result P formed from L plus a header contribution H. +- Establish an ordered, feasible producer-to-connector-to-consumer flow in which P reaches the consumer length parameter without an intervening overwrite that breaks the fact. +- Establish that the consumer performs reachable fixed-size header subtraction totaling S from that unsigned length and that some admitted value satisfies P < S, making unsigned wrap possible. +- Treat the producer as safe only when every path from the packet read to the returned value is dominated by a correctly polarized rejecting guard whose accepted-path constraint implies P >= S. +- Recognize the patched guard as sufficient because rejecting dma_len below min_seg_len leaves a lower bound at least as strong as the amount needed to prevent downstream header stripping from underflowing. +- Tie the warning to the missing validation that permits the underflow, rather than merely to the presence of packet parsing or unsigned subtraction. + +### Implementation constraints + +- Use a translation-unit-capable CSA callback such as check::EndOfTranslationUnit to collect function summaries and resolve the cross-function producer, connector, and consumer relationship. +- Use each relevant function's CSA analysis context and CFG to establish statement ordering, reachability, branch polarity, dominance, and overwrite-free local def-use; source-location ordering is not a substitute. +- Summarize producer arithmetic, guard constraints, call arguments, and consumer subtraction amounts structurally, then propagate those summaries across direct calls within the analyzed translation unit. +- Model guards embedded in expressions such as WARN_ON_ONCE by their resulting CFG branches and constraints, without requiring unreliable symbolic inlining of the macro implementation. +- Report at the producer return or its missing-validation vicinity in the affected function so diagnostics remain close to the patch and explain the downstream unsigned-underflow consequence. +- Keep project-general scope based on packet-field reads, unsigned length arithmetic, fixed header stripping, and verified call flow; do not depend on mt7601u identifiers. +- Register a normal CSA checker with stable diagnostic ownership and suppress reports unless the complete source-to-sink proof is present. + +### Validation checklist + +- Build the checker shared object successfully with the supplied compile workflow and run code verification. +- Scan the pre-patch source and confirm nonzero diagnostics for mt7601u_rx_next_seg_len; the established harness baseline is two duplicate analysis reports. +- Scan the patched source and confirm zero diagnostics after the dma_len < min_seg_len rejecting guard is added. +- Confirm every disappearing warning belongs to the changed producer function and is located at or near the segment-length return or missing guard; retain the observed median distance of approximately two lines. +- Add or exercise a case where a lower-bound comparison precedes the return textually but does not dominate it, and require a warning. +- Add or exercise wrong-polarity and insufficient-bound guards, and require warnings because their accepted paths still permit P < S. +- Add or exercise a connector where assignment occurs after the consumer call or the value is overwritten, and require no false producer-to-consumer connection. +- Run refinement and require an accepted or clean result with no unrelated disappeared warnings and patched report count below the validation threshold. + +### Avoid and forbidden regressions + +- Do not reuse a purely syntactic whole-AST approximation that treats source order as dominance. +- Do not use a subtraction-site ProgramState range check that reports identically before and after because WARN_ON_ONCE constraints are not modeled reliably. +- Do not perform a per-function missing-guard scan without proving that the produced value reaches a header-stripping consumer. +- Do not classify every relational comparison involving L as protective without checking bound strength, branch direction, and early-exit behavior. +- Do not connect assignments and calls merely because they occur somewhere in the same function. +- Do not assume any addition involving the packet length or any single unsigned -= operation is sufficient evidence of underflow. +- Do not introduce source-text matching, line anchors, commit references, exact local names, or affected-function-name checks. diff --git a/tasks/csa159/pair_143586/checker_template.cpp b/tasks/csa159/pair_143586/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_143586/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_143586/config.json b/tasks/csa159/pair_143586/config.json new file mode 100644 index 0000000000000000000000000000000000000000..bd234f8472ef32a801ebef60535dc93cb93a95b0 --- /dev/null +++ b/tasks/csa159/pair_143586/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "81ff296a8163ed791fd05a3dba1a826c598a3c84", + "after_commit": "98f681b0f84cfc3a1d83287b77697679e0398306", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/f7fc624be3dbfb78047a1cab795b93c7235fbf1c/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/f7fc624be3dbfb78047a1cab795b93c7235fbf1c/compile_commands.json", + "changed_files": [ + "sound/soc/sof/ipc3-loader.c" + ], + "commit_message": "ASoC: SOF: Add some bounds checking to firmware data\n\nSmatch complains about \"head->full_size - head->header_size\" can\nunderflow. To some extent, we're always going to have to trust the\nfirmware a bit. However, it's easy enough to add a check for negatives,\nand let's add a upper bounds check as well.\n\nFixes: d2458baa799f (\"ASoC: SOF: ipc3-loader: Implement firmware parsing and loading\")\nSigned-off-by: Dan Carpenter \nLink: https://msgid.link/r/5593d147-058c-4de3-a6f5-540ecb96f6f8@moroto.mountain\nSigned-off-by: Mark Brown ", + "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_143586/patch.diff b/tasks/csa159/pair_143586/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6d25de93a4ad4d79cba3f54022fd03c3d1451802 --- /dev/null +++ b/tasks/csa159/pair_143586/patch.diff @@ -0,0 +1,13 @@ +diff --git a/sound/soc/sof/ipc3-loader.c b/sound/soc/sof/ipc3-loader.c +index 28218766d211..6e3ef0672110 100644 +--- a/sound/soc/sof/ipc3-loader.c ++++ b/sound/soc/sof/ipc3-loader.c +@@ -148,6 +148,8 @@ static size_t sof_ipc3_fw_parse_ext_man(struct snd_sof_dev *sdev) + + head = (struct sof_ext_man_header *)fw->data; + remaining = head->full_size - head->header_size; ++ if (remaining < 0 || remaining > sdev->basefw.fw->size) ++ return -EINVAL; + ext_man_size = ipc3_fw_ext_man_size(sdev, fw); + + /* Assert firmware starts with extended manifest */ \ No newline at end of file diff --git a/tasks/csa159/pair_143586/post_functions.txt b/tasks/csa159/pair_143586/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..46c53e4400bbb666d8fe42f75bdb0cd256ed2939 --- /dev/null +++ b/tasks/csa159/pair_143586/post_functions.txt @@ -0,0 +1,94 @@ +### File: sound/soc/sof/ipc3-loader.c +```c +static size_t sof_ipc3_fw_parse_ext_man(struct snd_sof_dev *sdev) +{ + const struct firmware *fw = sdev->basefw.fw; + const struct sof_ext_man_elem_header *elem_hdr; + const struct sof_ext_man_header *head; + ssize_t ext_man_size; + ssize_t remaining; + uintptr_t iptr; + int ret = 0; + + head = (struct sof_ext_man_header *)fw->data; + remaining = head->full_size - head->header_size; + if (remaining < 0 || remaining > sdev->basefw.fw->size) + return -EINVAL; + ext_man_size = ipc3_fw_ext_man_size(sdev, fw); + + /* Assert firmware starts with extended manifest */ + if (ext_man_size <= 0) + return ext_man_size; + + /* incompatible version */ + if (SOF_EXT_MAN_VERSION_INCOMPATIBLE(SOF_EXT_MAN_VERSION, + head->header_version)) { + dev_err(sdev->dev, + "extended manifest version %#x differ from used %#x\n", + head->header_version, SOF_EXT_MAN_VERSION); + return -EINVAL; + } + + /* get first extended manifest element header */ + iptr = (uintptr_t)fw->data + head->header_size; + + while (remaining > sizeof(*elem_hdr)) { + elem_hdr = (struct sof_ext_man_elem_header *)iptr; + + dev_dbg(sdev->dev, "found sof_ext_man header type %d size %#x\n", + elem_hdr->type, elem_hdr->size); + + if (elem_hdr->size < sizeof(*elem_hdr) || + elem_hdr->size > remaining) { + dev_err(sdev->dev, + "invalid sof_ext_man header size, type %d size %#x\n", + elem_hdr->type, elem_hdr->size); + return -EINVAL; + } + + /* process structure data */ + switch (elem_hdr->type) { + case SOF_EXT_MAN_ELEM_FW_VERSION: + ret = ipc3_fw_ext_man_get_version(sdev, elem_hdr); + break; + case SOF_EXT_MAN_ELEM_WINDOW: + ret = ipc3_fw_ext_man_get_windows(sdev, elem_hdr); + break; + case SOF_EXT_MAN_ELEM_CC_VERSION: + ret = ipc3_fw_ext_man_get_cc_info(sdev, elem_hdr); + break; + case SOF_EXT_MAN_ELEM_DBG_ABI: + ret = ipc3_fw_ext_man_get_dbg_abi_info(sdev, elem_hdr); + break; + case SOF_EXT_MAN_ELEM_CONFIG_DATA: + ret = ipc3_fw_ext_man_get_config_data(sdev, elem_hdr); + break; + case SOF_EXT_MAN_ELEM_PLATFORM_CONFIG_DATA: + ret = snd_sof_dsp_parse_platform_ext_manifest(sdev, elem_hdr); + break; + default: + dev_info(sdev->dev, + "unknown sof_ext_man header type %d size %#x\n", + elem_hdr->type, elem_hdr->size); + break; + } + + if (ret < 0) { + dev_err(sdev->dev, + "failed to parse sof_ext_man header type %d size %#x\n", + elem_hdr->type, elem_hdr->size); + return ret; + } + + remaining -= elem_hdr->size; + iptr += elem_hdr->size; + } + + if (remaining) { + dev_err(sdev->dev, "error: sof_ext_man header is inconsistent\n"); + return -EINVAL; + } + + return ext_man_size; +} +``` diff --git a/tasks/csa159/pair_143586/pre_functions.txt b/tasks/csa159/pair_143586/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..94620b75d4c95c7bb715d6ee02f1fedcc8bfbecc --- /dev/null +++ b/tasks/csa159/pair_143586/pre_functions.txt @@ -0,0 +1,92 @@ +### File: sound/soc/sof/ipc3-loader.c +```c +static size_t sof_ipc3_fw_parse_ext_man(struct snd_sof_dev *sdev) +{ + const struct firmware *fw = sdev->basefw.fw; + const struct sof_ext_man_elem_header *elem_hdr; + const struct sof_ext_man_header *head; + ssize_t ext_man_size; + ssize_t remaining; + uintptr_t iptr; + int ret = 0; + + head = (struct sof_ext_man_header *)fw->data; + remaining = head->full_size - head->header_size; + ext_man_size = ipc3_fw_ext_man_size(sdev, fw); + + /* Assert firmware starts with extended manifest */ + if (ext_man_size <= 0) + return ext_man_size; + + /* incompatible version */ + if (SOF_EXT_MAN_VERSION_INCOMPATIBLE(SOF_EXT_MAN_VERSION, + head->header_version)) { + dev_err(sdev->dev, + "extended manifest version %#x differ from used %#x\n", + head->header_version, SOF_EXT_MAN_VERSION); + return -EINVAL; + } + + /* get first extended manifest element header */ + iptr = (uintptr_t)fw->data + head->header_size; + + while (remaining > sizeof(*elem_hdr)) { + elem_hdr = (struct sof_ext_man_elem_header *)iptr; + + dev_dbg(sdev->dev, "found sof_ext_man header type %d size %#x\n", + elem_hdr->type, elem_hdr->size); + + if (elem_hdr->size < sizeof(*elem_hdr) || + elem_hdr->size > remaining) { + dev_err(sdev->dev, + "invalid sof_ext_man header size, type %d size %#x\n", + elem_hdr->type, elem_hdr->size); + return -EINVAL; + } + + /* process structure data */ + switch (elem_hdr->type) { + case SOF_EXT_MAN_ELEM_FW_VERSION: + ret = ipc3_fw_ext_man_get_version(sdev, elem_hdr); + break; + case SOF_EXT_MAN_ELEM_WINDOW: + ret = ipc3_fw_ext_man_get_windows(sdev, elem_hdr); + break; + case SOF_EXT_MAN_ELEM_CC_VERSION: + ret = ipc3_fw_ext_man_get_cc_info(sdev, elem_hdr); + break; + case SOF_EXT_MAN_ELEM_DBG_ABI: + ret = ipc3_fw_ext_man_get_dbg_abi_info(sdev, elem_hdr); + break; + case SOF_EXT_MAN_ELEM_CONFIG_DATA: + ret = ipc3_fw_ext_man_get_config_data(sdev, elem_hdr); + break; + case SOF_EXT_MAN_ELEM_PLATFORM_CONFIG_DATA: + ret = snd_sof_dsp_parse_platform_ext_manifest(sdev, elem_hdr); + break; + default: + dev_info(sdev->dev, + "unknown sof_ext_man header type %d size %#x\n", + elem_hdr->type, elem_hdr->size); + break; + } + + if (ret < 0) { + dev_err(sdev->dev, + "failed to parse sof_ext_man header type %d size %#x\n", + elem_hdr->type, elem_hdr->size); + return ret; + } + + remaining -= elem_hdr->size; + iptr += elem_hdr->size; + } + + if (remaining) { + dev_err(sdev->dev, "error: sof_ext_man header is inconsistent\n"); + return -EINVAL; + } + + return ext_man_size; +} +``` diff --git a/tasks/csa159/pair_143586/task_prompt.md b/tasks/csa159/pair_143586/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..c0f1418f45765c3a6755a372e88b6e966a086734 --- /dev/null +++ b/tasks/csa159/pair_143586/task_prompt.md @@ -0,0 +1,386 @@ +# 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 + +- Refinement was not accepted because the prior semantic condition remained a broad heuristic rather than a proof of an out-of-bounds firmware-buffer walk. +- Safety recognition was too dependent on specifically shaped comparisons and could miss equivalent guards with reversed operands, different relational operators, or safety established by existing operand constraints. +- A comparison could suppress a warning without proving both required bounds, proving that the rejecting branch exits, and proving that only the validated successor reaches the loop. +- The relation between the subtraction-derived bound, the pointer being walked, and the concrete firmware allocation size was not established directly enough. +- The heuristic could report unrelated or already-safe unsigned subtraction loops merely because a subtraction result controlled a constant-bounded dereferencing walk. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve a path-sensitive CSA mechanism adequate for carrying facts across the subtraction, guards, intervening statements, and loop. +- Preserve 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 a runtime unsigned metadata subtraction can produce a wrapped or oversized count and that the resulting value, including through the signed destination and value-preserving casts or assignments, reaches the loop condition. +- Establish that the loop uses that count to permit dereferences through a pointer derived from the firmware data buffer and advances that pointer during iteration. +- Relate the permitted walk extent to the allocation represented by the corresponding firmware data and size, rather than accepting an arbitrary runtime value or merely a common enclosing object. +- Report only on a feasible path reaching the dangerous loop use where constraints do not prove the subtraction result is within the valid lower and allocation-size upper bounds. +- Treat a guard as protective only when its safe successor establishes the needed bound and its invalid successor cannot continue to the dangerous loop. +- Recognize semantically equivalent operand orders and relational forms when determining whether path constraints establish the required bounds. +- Do not report when existing constraints on subtraction operands or equivalent invariants already prove that the resulting walk stays within the firmware allocation. + +### Implementation constraints + +- Use path-sensitive CSA analysis with check::PostStmt or equivalent evaluated-expression callbacks to identify the subtraction value and its later consumption, plus eval::Assume or an equivalent successor-specific callback to model guard branches. +- Carry value identity and validation facts in ProgramState across assignments, casts, intervening control flow, and loop entry; do not infer safety from the lexical presence of a comparison. +- Use CSA constraint queries on the current successor state to prove the normalized lower and upper bounds, including equivalent comparison orientations, instead of assigning proof flags solely from operator shape. +- Use symbolic-region relationships to connect the walked pointer to firmware data and the upper bound to the corresponding firmware allocation size. +- Require the CFG/path relationship that the validated successor reaches the loop while the rejecting successor exits or otherwise cannot reach the dangerous use. +- Keep analysis intra-function because the supplied defect and fix require no interprocedural propagation. +- Anchor the diagnostic at the dangerous loop condition or associated buffer dereference and mark the subtraction-derived symbol as interesting. +- Generalize over declarations, symbols, regions, and control flow without file names, function names, variable names, source lines, commit identifiers, or patch literals. + +### Validation checklist + +- Compile the new checker as a loadable CSA plugin with the target LLVM/Clang API and verify checker registration and analyzer loading. +- Scan both supplied buggy inputs and require the established two relevant diagnostics in sof_ipc3_fw_parse_ext_man with no diagnostics in non-patched functions. +- Scan both supplied patched inputs and require zero diagnostics, with both buggy diagnostics disappearing only because the new bounds-and-exit control flow proves safety. +- Run code verification and retain diagnostics within the patched function and near the dangerous subtraction-to-loop sequence, with no unrelated disappeared warnings. +- Add refinement cases for reversed operands and equivalent strict or non-strict lower- and upper-bound comparisons; all genuinely safe continuations must suppress. +- Add cases where a comparison is unrelated, bounds the wrong value or allocation, or has a rejecting branch that still reaches the loop; these must not suppress. +- Add safe cases where operand constraints independently prevent underflow or prove the walk extent is within the allocation; these must remain clean. +- Add unsafe and unrelated-loop cases to confirm that semantically equivalent unchecked firmware walks report while generic unsigned subtraction loops do not. + +### Avoid and forbidden regressions + +- Do not reduce the mechanism to syntax-only or control-flow-only matching; successor-specific symbolic facts are required. +- Do not treat every relational comparison involving the subtraction as validation. +- Do not recognize only a suspect-on-the-left form or only the exact operators shown in the patch. +- Do not grant a bound proof to both branch successors or to a continuation whose rejecting path can still reach the loop. +- Do not equate shared region ancestry alone with proof that the bound is the size of the allocation actually being walked. +- Do not report every runtime unsigned subtraction used as a constant loop bound without proving the firmware-buffer dereference and advance relationship. +- Do not rely on source text, patch locations, project identifiers, declaration spellings, or exact patch expressions. +- Do not suppress warnings merely to reproduce the observed before/after counts when the required safety relation is unproven. diff --git a/tasks/csa159/pair_144169/checker_template.cpp b/tasks/csa159/pair_144169/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_144169/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_144169/config.json b/tasks/csa159/pair_144169/config.json new file mode 100644 index 0000000000000000000000000000000000000000..07603f5fefc1872dd5ea319d5c775a83c9a51aa6 --- /dev/null +++ b/tasks/csa159/pair_144169/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "c5b324b1a7628c393f99058d2464592791617cc9", + "after_commit": "1b739388aa3f8dfb63a9fca777e6dfa6912d0464", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/31e7f6c015d9eb35e77ae9868801c53ab0ff19ac/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/31e7f6c015d9eb35e77ae9868801c53ab0ff19ac/compile_commands.json", + "changed_files": [ + "drivers/usb/gadget/function/u_audio.c" + ], + "commit_message": "usb: gadget: u_audio: Fix race condition use of controls after free during gadget unbind.\n\nHang on to the control IDs instead of pointers since those are correctly\nhandled with locks.\n\nFixes: 8fe9a03f4331 (\"usb: gadget: u_audio: Rate ctl notifies about current srate (0=stopped)\")\nFixes: c565ad07ef35 (\"usb: gadget: u_audio: Support multiple sampling rates\")\nFixes: 02de698ca812 (\"usb: gadget: u_audio: add bi-directional volume and mute support\")\nSigned-off-by: Chris Wulff \nLink: https://lore.kernel.org/stable/CO1PR17MB5419C2BF44D400E4E620C1ADE1172%40CO1PR17MB5419.namprd17.prod.outlook.com\nLink: https://lore.kernel.org/r/CO1PR17MB5419C2BF44D400E4E620C1ADE1172@CO1PR17MB5419.namprd17.prod.outlook.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_144169/patch.diff b/tasks/csa159/pair_144169/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..aff1f8a30e72423b5734710a47ab2ebbca50f319 --- /dev/null +++ b/tasks/csa159/pair_144169/patch.diff @@ -0,0 +1,82 @@ +diff --git a/drivers/usb/gadget/function/u_audio.c b/drivers/usb/gadget/function/u_audio.c +index 1a634646bd24..efa3e3100333 100644 +--- a/drivers/usb/gadget/function/u_audio.c ++++ b/drivers/usb/gadget/function/u_audio.c +@@ -57,13 +57,13 @@ struct uac_rtd_params { + + /* Volume/Mute controls and their state */ + int fu_id; /* Feature Unit ID */ +- struct snd_kcontrol *snd_kctl_volume; +- struct snd_kcontrol *snd_kctl_mute; ++ struct snd_ctl_elem_id snd_kctl_volume_id; ++ struct snd_ctl_elem_id snd_kctl_mute_id; + s16 volume_min, volume_max, volume_res; + s16 volume; + int mute; + +- struct snd_kcontrol *snd_kctl_rate; /* read-only current rate */ ++ struct snd_ctl_elem_id snd_kctl_rate_id; /* read-only current rate */ + int srate; /* selected samplerate */ + int active; /* playback/capture running */ + +@@ -494,14 +494,13 @@ static inline void free_ep_fback(struct uac_rtd_params *prm, struct usb_ep *ep) + static void set_active(struct uac_rtd_params *prm, bool active) + { + // notifying through the Rate ctrl +- struct snd_kcontrol *kctl = prm->snd_kctl_rate; + unsigned long flags; + + spin_lock_irqsave(&prm->lock, flags); + if (prm->active != active) { + prm->active = active; + snd_ctl_notify(prm->uac->card, SNDRV_CTL_EVENT_MASK_VALUE, +- &kctl->id); ++ &prm->snd_kctl_rate_id); + } + spin_unlock_irqrestore(&prm->lock, flags); + } +@@ -807,7 +806,7 @@ int u_audio_set_volume(struct g_audio *audio_dev, int playback, s16 val) + + if (change) + snd_ctl_notify(uac->card, SNDRV_CTL_EVENT_MASK_VALUE, +- &prm->snd_kctl_volume->id); ++ &prm->snd_kctl_volume_id); + + return 0; + } +@@ -856,7 +855,7 @@ int u_audio_set_mute(struct g_audio *audio_dev, int playback, int val) + + if (change) + snd_ctl_notify(uac->card, SNDRV_CTL_EVENT_MASK_VALUE, +- &prm->snd_kctl_mute->id); ++ &prm->snd_kctl_mute_id); + + return 0; + } +@@ -1331,7 +1330,7 @@ int g_audio_setup(struct g_audio *g_audio, const char *pcm_name, + err = snd_ctl_add(card, kctl); + if (err < 0) + goto snd_fail; +- prm->snd_kctl_mute = kctl; ++ prm->snd_kctl_mute_id = kctl->id; + prm->mute = 0; + } + +@@ -1359,7 +1358,7 @@ int g_audio_setup(struct g_audio *g_audio, const char *pcm_name, + err = snd_ctl_add(card, kctl); + if (err < 0) + goto snd_fail; +- prm->snd_kctl_volume = kctl; ++ prm->snd_kctl_volume_id = kctl->id; + prm->volume = fu->volume_max; + prm->volume_max = fu->volume_max; + prm->volume_min = fu->volume_min; +@@ -1383,7 +1382,7 @@ int g_audio_setup(struct g_audio *g_audio, const char *pcm_name, + err = snd_ctl_add(card, kctl); + if (err < 0) + goto snd_fail; +- prm->snd_kctl_rate = kctl; ++ prm->snd_kctl_rate_id = kctl->id; + } + + strscpy(card->driver, card_name); \ No newline at end of file diff --git a/tasks/csa159/pair_144169/post_functions.txt b/tasks/csa159/pair_144169/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..b0ea8d60c54612b7b84d59e4aede852e8c276dad --- /dev/null +++ b/tasks/csa159/pair_144169/post_functions.txt @@ -0,0 +1,368 @@ +### File: drivers/usb/gadget/function/u_audio.c +```c +static inline void free_ep_fback(struct uac_rtd_params *prm, struct usb_ep *ep) +{ + struct snd_uac_chip *uac = prm->uac; + + if (!prm->fb_ep_enabled) + return; + + if (prm->req_fback) { + if (usb_ep_dequeue(ep, prm->req_fback)) { + kfree(prm->req_fback->buf); + usb_ep_free_request(ep, prm->req_fback); + } + prm->req_fback = NULL; + } + + prm->fb_ep_enabled = false; + + if (usb_ep_disable(ep)) + dev_err(uac->card->dev, "%s:%d Error!\n", __func__, __LINE__); +} + +static void set_active(struct uac_rtd_params *prm, bool active) +{ + // notifying through the Rate ctrl + unsigned long flags; + + spin_lock_irqsave(&prm->lock, flags); + if (prm->active != active) { + prm->active = active; + snd_ctl_notify(prm->uac->card, SNDRV_CTL_EVENT_MASK_VALUE, + &prm->snd_kctl_rate_id); + } + spin_unlock_irqrestore(&prm->lock, flags); +} + +int u_audio_set_capture_srate(struct g_audio *audio_dev, int srate) +{ + struct uac_params *params = &audio_dev->params; + struct snd_uac_chip *uac = audio_dev->uac; + struct uac_rtd_params *prm; + int i; + unsigned long flags; + + dev_dbg(&audio_dev->gadget->dev, "%s: srate %d\n", __func__, srate); + prm = &uac->c_prm; + for (i = 0; i < UAC_MAX_RATES; i++) { + if (params->c_srates[i] == srate) { + spin_lock_irqsave(&prm->lock, flags); + prm->srate = srate; + spin_unlock_irqrestore(&prm->lock, flags); + return 0; + } + if (params->c_srates[i] == 0) + break; + } + + return -EINVAL; +} + +int u_audio_set_volume(struct g_audio *audio_dev, int playback, s16 val) +{ + struct snd_uac_chip *uac = audio_dev->uac; + struct uac_rtd_params *prm; + unsigned long flags; + int change = 0; + + if (playback) + prm = &uac->p_prm; + else + prm = &uac->c_prm; + + spin_lock_irqsave(&prm->lock, flags); + val = clamp(val, prm->volume_min, prm->volume_max); + if (prm->volume != val) { + prm->volume = val; + change = 1; + } + spin_unlock_irqrestore(&prm->lock, flags); + + if (change) + snd_ctl_notify(uac->card, SNDRV_CTL_EVENT_MASK_VALUE, + &prm->snd_kctl_volume_id); + + return 0; +} + +int u_audio_get_mute(struct g_audio *audio_dev, int playback, int *val) +{ + struct snd_uac_chip *uac = audio_dev->uac; + struct uac_rtd_params *prm; + unsigned long flags; + + if (playback) + prm = &uac->p_prm; + else + prm = &uac->c_prm; + + spin_lock_irqsave(&prm->lock, flags); + *val = prm->mute; + spin_unlock_irqrestore(&prm->lock, flags); + + return 0; +} + +int u_audio_set_mute(struct g_audio *audio_dev, int playback, int val) +{ + struct snd_uac_chip *uac = audio_dev->uac; + struct uac_rtd_params *prm; + unsigned long flags; + int change = 0; + int mute; + + if (playback) + prm = &uac->p_prm; + else + prm = &uac->c_prm; + + mute = val ? 1 : 0; + + spin_lock_irqsave(&prm->lock, flags); + if (prm->mute != mute) { + prm->mute = mute; + change = 1; + } + spin_unlock_irqrestore(&prm->lock, flags); + + if (change) + snd_ctl_notify(uac->card, SNDRV_CTL_EVENT_MASK_VALUE, + &prm->snd_kctl_mute_id); + + return 0; +} + +static int u_audio_pitch_info(struct snd_kcontrol *kcontrol, + struct snd_ctl_elem_info *uinfo) +{ + struct uac_rtd_params *prm = snd_kcontrol_chip(kcontrol); + struct snd_uac_chip *uac = prm->uac; + struct g_audio *audio_dev = uac->audio_dev; + struct uac_params *params = &audio_dev->params; + unsigned int pitch_min, pitch_max; + + pitch_min = (1000 - FBACK_SLOW_MAX) * 1000; + pitch_max = (1000 + params->fb_max) * 1000; + + uinfo->type = SNDRV_CTL_ELEM_TYPE_INTEGER; + uinfo->count = 1; + uinfo->value.integer.min = pitch_min; + uinfo->value.integer.max = pitch_max; + uinfo->value.integer.step = 1; + return 0; +} + +int g_audio_setup(struct g_audio *g_audio, const char *pcm_name, + const char *card_name) +{ + struct snd_uac_chip *uac; + struct snd_card *card; + struct snd_pcm *pcm; + struct snd_kcontrol *kctl; + struct uac_params *params; + int p_chmask, c_chmask; + int i, err; + + if (!g_audio) + return -EINVAL; + + uac = kzalloc(sizeof(*uac), GFP_KERNEL); + if (!uac) + return -ENOMEM; + g_audio->uac = uac; + uac->audio_dev = g_audio; + + params = &g_audio->params; + p_chmask = params->p_chmask; + c_chmask = params->c_chmask; + + if (c_chmask) { + struct uac_rtd_params *prm = &uac->c_prm; + + spin_lock_init(&prm->lock); + uac->c_prm.uac = uac; + prm->max_psize = g_audio->out_ep_maxpsize; + prm->srate = params->c_srates[0]; + + prm->reqs = kcalloc(params->req_number, + sizeof(struct usb_request *), + GFP_KERNEL); + if (!prm->reqs) { + err = -ENOMEM; + goto fail; + } + + prm->rbuf = kcalloc(params->req_number, prm->max_psize, + GFP_KERNEL); + if (!prm->rbuf) { + prm->max_psize = 0; + err = -ENOMEM; + goto fail; + } + } + + if (p_chmask) { + struct uac_rtd_params *prm = &uac->p_prm; + + spin_lock_init(&prm->lock); + uac->p_prm.uac = uac; + prm->max_psize = g_audio->in_ep_maxpsize; + prm->srate = params->p_srates[0]; + + prm->reqs = kcalloc(params->req_number, + sizeof(struct usb_request *), + GFP_KERNEL); + if (!prm->reqs) { + err = -ENOMEM; + goto fail; + } + + prm->rbuf = kcalloc(params->req_number, prm->max_psize, + GFP_KERNEL); + if (!prm->rbuf) { + prm->max_psize = 0; + err = -ENOMEM; + goto fail; + } + } + + /* Choose any slot, with no id */ + err = snd_card_new(&g_audio->gadget->dev, + -1, NULL, THIS_MODULE, 0, &card); + if (err < 0) + goto fail; + + uac->card = card; + + /* + * Create first PCM device + * Create a substream only for non-zero channel streams + */ + err = snd_pcm_new(uac->card, pcm_name, 0, + p_chmask ? 1 : 0, c_chmask ? 1 : 0, &pcm); + if (err < 0) + goto snd_fail; + + strscpy(pcm->name, pcm_name); + pcm->private_data = uac; + uac->pcm = pcm; + + snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &uac_pcm_ops); + snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &uac_pcm_ops); + + /* + * Create mixer and controls + * Create only if it's required on USB side + */ + if ((c_chmask && g_audio->in_ep_fback) + || (p_chmask && params->p_fu.id) + || (c_chmask && params->c_fu.id)) + strscpy(card->mixername, card_name); + + if (c_chmask && g_audio->in_ep_fback) { + kctl = snd_ctl_new1(&u_audio_controls[UAC_FBACK_CTRL], + &uac->c_prm); + if (!kctl) { + err = -ENOMEM; + goto snd_fail; + } + + kctl->id.device = pcm->device; + kctl->id.subdevice = 0; + + err = snd_ctl_add(card, kctl); + if (err < 0) + goto snd_fail; + } + + if (p_chmask) { + kctl = snd_ctl_new1(&u_audio_controls[UAC_P_PITCH_CTRL], + &uac->p_prm); + if (!kctl) { + err = -ENOMEM; + goto snd_fail; + } + + kctl->id.device = pcm->device; + kctl->id.subdevice = 0; + + err = snd_ctl_add(card, kctl); + if (err < 0) + goto snd_fail; + } + + for (i = 0; i <= SNDRV_PCM_STREAM_LAST; i++) { + struct uac_rtd_params *prm; + struct uac_fu_params *fu; + char ctrl_name[24]; + char *direction; + + if (!pcm->streams[i].substream_count) + continue; + + if (i == SNDRV_PCM_STREAM_PLAYBACK) { + prm = &uac->p_prm; + fu = ¶ms->p_fu; + direction = "Playback"; + } else { + prm = &uac->c_prm; + fu = ¶ms->c_fu; + direction = "Capture"; + } + + prm->fu_id = fu->id; + + if (fu->mute_present) { + snprintf(ctrl_name, sizeof(ctrl_name), + "PCM %s Switch", direction); + + u_audio_controls[UAC_MUTE_CTRL].name = ctrl_name; + + kctl = snd_ctl_new1(&u_audio_controls[UAC_MUTE_CTRL], + prm); + if (!kctl) { + err = -ENOMEM; + goto snd_fail; + } + + kctl->id.device = pcm->device; + kctl->id.subdevice = 0; + + err = snd_ctl_add(card, kctl); + if (err < 0) + goto snd_fail; + prm->snd_kctl_mute_id = kctl->id; + prm->mute = 0; + } + + if (fu->volume_present) { + snprintf(ctrl_name, sizeof(ctrl_name), + "PCM %s Volume", direction); + + u_audio_controls[UAC_VOLUME_CTRL].name = ctrl_name; + + kctl = snd_ctl_new1(&u_audio_controls[UAC_VOLUME_CTRL], + prm); + if (!kctl) { + err = -ENOMEM; + goto snd_fail; + } + + kctl->id.device = pcm->device; + kctl->id.subdevice = 0; + + + kctl->tlv.c = u_audio_volume_tlv; + kctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_TLV_READ | + SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK; + + err = snd_ctl_add(card, kctl); + if (err < 0) + goto snd_fail; + prm->snd_kctl_volume_id = kctl->id; + prm->volume = fu->volume_max; + prm->volume_max = fu->volume_max; + +// ... (997 more chars) +``` diff --git a/tasks/csa159/pair_144169/pre_functions.txt b/tasks/csa159/pair_144169/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..c8c9d12f2598d357193146ac41f39cfdb23e475f --- /dev/null +++ b/tasks/csa159/pair_144169/pre_functions.txt @@ -0,0 +1,376 @@ +### File: drivers/usb/gadget/function/u_audio.c +```c +static inline void free_ep_fback(struct uac_rtd_params *prm, struct usb_ep *ep) +{ + struct snd_uac_chip *uac = prm->uac; + + if (!prm->fb_ep_enabled) + return; + + if (prm->req_fback) { + if (usb_ep_dequeue(ep, prm->req_fback)) { + kfree(prm->req_fback->buf); + usb_ep_free_request(ep, prm->req_fback); + } + prm->req_fback = NULL; + } + + prm->fb_ep_enabled = false; + + if (usb_ep_disable(ep)) + dev_err(uac->card->dev, "%s:%d Error!\n", __func__, __LINE__); +} + +static void set_active(struct uac_rtd_params *prm, bool active) +{ + // notifying through the Rate ctrl + struct snd_kcontrol *kctl = prm->snd_kctl_rate; + unsigned long flags; + + spin_lock_irqsave(&prm->lock, flags); + if (prm->active != active) { + prm->active = active; + snd_ctl_notify(prm->uac->card, SNDRV_CTL_EVENT_MASK_VALUE, + &kctl->id); + } + spin_unlock_irqrestore(&prm->lock, flags); +} + +int u_audio_set_capture_srate(struct g_audio *audio_dev, int srate) +{ + struct uac_params *params = &audio_dev->params; + struct snd_uac_chip *uac = audio_dev->uac; + struct uac_rtd_params *prm; + int i; + unsigned long flags; + + dev_dbg(&audio_dev->gadget->dev, "%s: srate %d\n", __func__, srate); + prm = &uac->c_prm; + for (i = 0; i < UAC_MAX_RATES; i++) { + if (params->c_srates[i] == srate) { + spin_lock_irqsave(&prm->lock, flags); + prm->srate = srate; + spin_unlock_irqrestore(&prm->lock, flags); + return 0; + } + if (params->c_srates[i] == 0) + break; + } + + return -EINVAL; +} + +int u_audio_set_volume(struct g_audio *audio_dev, int playback, s16 val) +{ + struct snd_uac_chip *uac = audio_dev->uac; + struct uac_rtd_params *prm; + unsigned long flags; + int change = 0; + + if (playback) + prm = &uac->p_prm; + else + prm = &uac->c_prm; + + spin_lock_irqsave(&prm->lock, flags); + val = clamp(val, prm->volume_min, prm->volume_max); + if (prm->volume != val) { + prm->volume = val; + change = 1; + } + spin_unlock_irqrestore(&prm->lock, flags); + + if (change) + snd_ctl_notify(uac->card, SNDRV_CTL_EVENT_MASK_VALUE, + &prm->snd_kctl_volume->id); + + return 0; +} + +int u_audio_get_mute(struct g_audio *audio_dev, int playback, int *val) +{ + struct snd_uac_chip *uac = audio_dev->uac; + struct uac_rtd_params *prm; + unsigned long flags; + + if (playback) + prm = &uac->p_prm; + else + prm = &uac->c_prm; + + spin_lock_irqsave(&prm->lock, flags); + *val = prm->mute; + spin_unlock_irqrestore(&prm->lock, flags); + + return 0; +} + +int u_audio_set_mute(struct g_audio *audio_dev, int playback, int val) +{ + struct snd_uac_chip *uac = audio_dev->uac; + struct uac_rtd_params *prm; + unsigned long flags; + int change = 0; + int mute; + + if (playback) + prm = &uac->p_prm; + else + prm = &uac->c_prm; + + mute = val ? 1 : 0; + + spin_lock_irqsave(&prm->lock, flags); + if (prm->mute != mute) { + prm->mute = mute; + change = 1; + } + spin_unlock_irqrestore(&prm->lock, flags); + + if (change) + snd_ctl_notify(uac->card, SNDRV_CTL_EVENT_MASK_VALUE, + &prm->snd_kctl_mute->id); + + return 0; +} + +int g_audio_setup(struct g_audio *g_audio, const char *pcm_name, + const char *card_name) +{ + struct snd_uac_chip *uac; + struct snd_card *card; + struct snd_pcm *pcm; + struct snd_kcontrol *kctl; + struct uac_params *params; + int p_chmask, c_chmask; + int i, err; + + if (!g_audio) + return -EINVAL; + + uac = kzalloc(sizeof(*uac), GFP_KERNEL); + if (!uac) + return -ENOMEM; + g_audio->uac = uac; + uac->audio_dev = g_audio; + + params = &g_audio->params; + p_chmask = params->p_chmask; + c_chmask = params->c_chmask; + + if (c_chmask) { + struct uac_rtd_params *prm = &uac->c_prm; + + spin_lock_init(&prm->lock); + uac->c_prm.uac = uac; + prm->max_psize = g_audio->out_ep_maxpsize; + prm->srate = params->c_srates[0]; + + prm->reqs = kcalloc(params->req_number, + sizeof(struct usb_request *), + GFP_KERNEL); + if (!prm->reqs) { + err = -ENOMEM; + goto fail; + } + + prm->rbuf = kcalloc(params->req_number, prm->max_psize, + GFP_KERNEL); + if (!prm->rbuf) { + prm->max_psize = 0; + err = -ENOMEM; + goto fail; + } + } + + if (p_chmask) { + struct uac_rtd_params *prm = &uac->p_prm; + + spin_lock_init(&prm->lock); + uac->p_prm.uac = uac; + prm->max_psize = g_audio->in_ep_maxpsize; + prm->srate = params->p_srates[0]; + + prm->reqs = kcalloc(params->req_number, + sizeof(struct usb_request *), + GFP_KERNEL); + if (!prm->reqs) { + err = -ENOMEM; + goto fail; + } + + prm->rbuf = kcalloc(params->req_number, prm->max_psize, + GFP_KERNEL); + if (!prm->rbuf) { + prm->max_psize = 0; + err = -ENOMEM; + goto fail; + } + } + + /* Choose any slot, with no id */ + err = snd_card_new(&g_audio->gadget->dev, + -1, NULL, THIS_MODULE, 0, &card); + if (err < 0) + goto fail; + + uac->card = card; + + /* + * Create first PCM device + * Create a substream only for non-zero channel streams + */ + err = snd_pcm_new(uac->card, pcm_name, 0, + p_chmask ? 1 : 0, c_chmask ? 1 : 0, &pcm); + if (err < 0) + goto snd_fail; + + strscpy(pcm->name, pcm_name); + pcm->private_data = uac; + uac->pcm = pcm; + + snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK, &uac_pcm_ops); + snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, &uac_pcm_ops); + + /* + * Create mixer and controls + * Create only if it's required on USB side + */ + if ((c_chmask && g_audio->in_ep_fback) + || (p_chmask && params->p_fu.id) + || (c_chmask && params->c_fu.id)) + strscpy(card->mixername, card_name); + + if (c_chmask && g_audio->in_ep_fback) { + kctl = snd_ctl_new1(&u_audio_controls[UAC_FBACK_CTRL], + &uac->c_prm); + if (!kctl) { + err = -ENOMEM; + goto snd_fail; + } + + kctl->id.device = pcm->device; + kctl->id.subdevice = 0; + + err = snd_ctl_add(card, kctl); + if (err < 0) + goto snd_fail; + } + + if (p_chmask) { + kctl = snd_ctl_new1(&u_audio_controls[UAC_P_PITCH_CTRL], + &uac->p_prm); + if (!kctl) { + err = -ENOMEM; + goto snd_fail; + } + + kctl->id.device = pcm->device; + kctl->id.subdevice = 0; + + err = snd_ctl_add(card, kctl); + if (err < 0) + goto snd_fail; + } + + for (i = 0; i <= SNDRV_PCM_STREAM_LAST; i++) { + struct uac_rtd_params *prm; + struct uac_fu_params *fu; + char ctrl_name[24]; + char *direction; + + if (!pcm->streams[i].substream_count) + continue; + + if (i == SNDRV_PCM_STREAM_PLAYBACK) { + prm = &uac->p_prm; + fu = ¶ms->p_fu; + direction = "Playback"; + } else { + prm = &uac->c_prm; + fu = ¶ms->c_fu; + direction = "Capture"; + } + + prm->fu_id = fu->id; + + if (fu->mute_present) { + snprintf(ctrl_name, sizeof(ctrl_name), + "PCM %s Switch", direction); + + u_audio_controls[UAC_MUTE_CTRL].name = ctrl_name; + + kctl = snd_ctl_new1(&u_audio_controls[UAC_MUTE_CTRL], + prm); + if (!kctl) { + err = -ENOMEM; + goto snd_fail; + } + + kctl->id.device = pcm->device; + kctl->id.subdevice = 0; + + err = snd_ctl_add(card, kctl); + if (err < 0) + goto snd_fail; + prm->snd_kctl_mute = kctl; + prm->mute = 0; + } + + if (fu->volume_present) { + snprintf(ctrl_name, sizeof(ctrl_name), + "PCM %s Volume", direction); + + u_audio_controls[UAC_VOLUME_CTRL].name = ctrl_name; + + kctl = snd_ctl_new1(&u_audio_controls[UAC_VOLUME_CTRL], + prm); + if (!kctl) { + err = -ENOMEM; + goto snd_fail; + } + + kctl->id.device = pcm->device; + kctl->id.subdevice = 0; + + + kctl->tlv.c = u_audio_volume_tlv; + kctl->vd[0].access |= SNDRV_CTL_ELEM_ACCESS_TLV_READ | + SNDRV_CTL_ELEM_ACCESS_TLV_CALLBACK; + + err = snd_ctl_add(card, kctl); + if (err < 0) + goto snd_fail; + prm->snd_kctl_volume = kctl; + prm->volume = fu->volume_max; + prm->volume_max = fu->volume_max; + prm->volume_min = fu->volume_min; + prm->volume_res = fu->volume_res; + } + + /* Add rate control */ + snprintf(ctrl_name, sizeof(ctrl_name), + "%s Rate", direction); + u_audio_controls[UAC_RATE_CTRL].name = ctrl_name; + + kctl = snd_ctl_new1(&u_audio_controls[UAC_RATE_CTRL], prm); + if (!kctl) { + err = -ENOMEM; + goto snd_fail; + } + + kctl->id.device = pcm->device; + kctl->id.subdevice = 0; + + err = snd_ctl_add(card, kctl); + if (err < 0) + goto snd_fail; + prm->snd_kctl_rate = kctl; + } + + strscpy(card->driver, card_name); + strscpy(card->shortname, card_name); + snprintf + +// ... (405 more chars) +``` diff --git a/tasks/csa159/pair_144169/task_prompt.md b/tasks/csa159/pair_144169/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..178e6bd7cd8e55625a398488e3a0327bb7d10789 --- /dev/null +++ b/tasks/csa159/pair_144169/task_prompt.md @@ -0,0 +1,372 @@ +# 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 rollout used a whole-translation-unit AST approximation classified as syntactic rather than establishing the cross-procedure lifetime relation required by the vulnerability. +- It recognized the pointer representation and patched representation, but did not prove that snd_ctl_add transfers ownership to snd_card, that card teardown frees the control, or that a later dereference can occur after teardown. +- Its rule reported every dereference of a struct snd_kcontrol pointer field or derived local, including independently owned, still-live, or otherwise safely synchronized controls, so semantic precision remained below threshold. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after validation, and code verification. +- Preserve objective eligibility through gate G6. +- Preserve an accepted or clean refinement outcome. +- Preserve process quality at or above the configured threshold. +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Track a control created by snd_ctl_new1 and transferred to a snd_card by snd_ctl_add as card-owned data whose lifetime ends when the card is torn down. +- Propagate the relevant ownership and alias facts across g_audio_setup, set_active, u_audio_set_volume, u_audio_set_mute, and any necessary call boundaries. +- Establish that the reported access dereferences the same card-owned snd_kcontrol object after the teardown/lifetime-ending event is possible, rather than merely observing a pointer of the right type. +- Recognize the patched representation as safe because it copies struct snd_ctl_elem_id by value and later passes the embedded identity without dereferencing a card-owned snd_kcontrol. + +### Implementation constraints + +- Use CSA call and memory-state modeling sufficient to record snd_ctl_new1 creation, snd_ctl_add ownership transfer, card teardown/free, pointer aliases, and later member dereferences. +- Use interprocedural summaries or equivalent cross-function propagation so facts from setup and teardown remain available at the use sites in separate top-level functions. +- Tie diagnostics to the precise dereference MemberExpr or equivalent sink that accesses the potentially freed control, with a path explaining creation, ownership transfer, lifetime end, and use. +- Restrict reports to aliases proven to derive from controls handed to the card and to accesses whose ordering or reachable execution permits use after teardown. +- Keep matching project-general by relying on ownership, lifetime, alias, and dereference semantics rather than names such as snd_kctl_volume, snd_kctl_rate, prm, set_active, line numbers, or patch text. + +### Validation checklist + +- Compile the new checker successfully and retain the existing code-verification success. +- Run the before/after scan: detect the six relevant buggy reports and produce zero reports in the patched source. +- Verify every diagnostic is located at the vulnerable dereference in the relevant changed function, not at setup, type declarations, or unrelated code. +- Confirm reports disappear specifically when the pointer fields and arrow dereferences are replaced by embedded struct snd_ctl_elem_id values. +- Check that controls with no proven snd_ctl_add ownership transfer, no proven lifetime-ending teardown, or no proven post-teardown use do not produce warnings. +- Re-run refinement and confirm the result remains accepted or clean while preserving the process and objective gates. + +### Avoid and forbidden regressions + +- Do not treat a raw struct snd_kcontrol pointer field as sufficient evidence of use-after-free. +- Do not substitute whole-TU AST collection or fixed-pass local propagation for cross-procedure ownership and lifetime analysis. +- Do not report merely because an arrow MemberExpr exists without proving the relevant lifetime-ending event and ordering. +- Do not weaken the semantic contract to preserve the prior six-warning differential result if that produces false positives. +- Do not regress compile, before/after, verification, objective-gate, refinement, process-score, anchor-free, or hardcoding-free results. diff --git a/tasks/csa159/pair_145442/checker_template.cpp b/tasks/csa159/pair_145442/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_145442/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_145442/config.json b/tasks/csa159/pair_145442/config.json new file mode 100644 index 0000000000000000000000000000000000000000..79c81b50a0bfa8f1610426d338089e9cfc6eb6ae --- /dev/null +++ b/tasks/csa159/pair_145442/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "fbf7085b3ad1c7cc0677834c90f985f1b4f77a33", + "after_commit": "60cf6206a1f513512f5d73fa4d3dbbcad2e7dcd6", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/55d42a0c3f9ccd07c199e0ddbe1ba87572d30074/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/55d42a0c3f9ccd07c199e0ddbe1ba87572d30074/compile_commands.json", + "changed_files": [ + "net/vmw_vsock/virtio_transport_common.c" + ], + "commit_message": "virtio/vsock: Improve MSG_ZEROCOPY error handling\n\nAdd a missing kfree_skb() to prevent memory leaks.\n\nFixes: 581512a6dc93 (\"vsock/virtio: MSG_ZEROCOPY flag support\")\nReviewed-by: Stefano Garzarella \nSigned-off-by: Michal Luczaj \nAcked-by: Arseniy Krasnov \nSigned-off-by: Paolo Abeni ", + "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_145442/patch.diff b/tasks/csa159/pair_145442/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..78dfe4a6d58f7f687c307541c4cd3b70011bb75b --- /dev/null +++ b/tasks/csa159/pair_145442/patch.diff @@ -0,0 +1,12 @@ +diff --git a/net/vmw_vsock/virtio_transport_common.c b/net/vmw_vsock/virtio_transport_common.c +index cd075f608d4f..e2e6a30b759b 100644 +--- a/net/vmw_vsock/virtio_transport_common.c ++++ b/net/vmw_vsock/virtio_transport_common.c +@@ -400,6 +400,7 @@ static int virtio_transport_send_pkt_info(struct vsock_sock *vsk, + if (virtio_transport_init_zcopy_skb(vsk, skb, + info->msg, + can_zcopy)) { ++ kfree_skb(skb); + ret = -ENOMEM; + break; + } \ No newline at end of file diff --git a/tasks/csa159/pair_145442/post_functions.txt b/tasks/csa159/pair_145442/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..3db6c8640cf61f20e4d79e6a3381a55855d92e5d --- /dev/null +++ b/tasks/csa159/pair_145442/post_functions.txt @@ -0,0 +1,115 @@ +### File: net/vmw_vsock/virtio_transport_common.c +```c +static int virtio_transport_send_pkt_info(struct vsock_sock *vsk, + struct virtio_vsock_pkt_info *info) +{ + u32 max_skb_len = VIRTIO_VSOCK_MAX_PKT_BUF_SIZE; + u32 src_cid, src_port, dst_cid, dst_port; + const struct virtio_transport *t_ops; + struct virtio_vsock_sock *vvs; + u32 pkt_len = info->pkt_len; + bool can_zcopy = false; + u32 rest_len; + int ret; + + info->type = virtio_transport_get_type(sk_vsock(vsk)); + + t_ops = virtio_transport_get_ops(vsk); + if (unlikely(!t_ops)) + return -EFAULT; + + src_cid = t_ops->transport.get_local_cid(); + src_port = vsk->local_addr.svm_port; + if (!info->remote_cid) { + dst_cid = vsk->remote_addr.svm_cid; + dst_port = vsk->remote_addr.svm_port; + } else { + dst_cid = info->remote_cid; + dst_port = info->remote_port; + } + + vvs = vsk->trans; + + /* virtio_transport_get_credit might return less than pkt_len credit */ + pkt_len = virtio_transport_get_credit(vvs, pkt_len); + + /* Do not send zero length OP_RW pkt */ + if (pkt_len == 0 && info->op == VIRTIO_VSOCK_OP_RW) + return pkt_len; + + if (info->msg) { + /* If zerocopy is not enabled by 'setsockopt()', we behave as + * there is no MSG_ZEROCOPY flag set. + */ + if (!sock_flag(sk_vsock(vsk), SOCK_ZEROCOPY)) + info->msg->msg_flags &= ~MSG_ZEROCOPY; + + if (info->msg->msg_flags & MSG_ZEROCOPY) + can_zcopy = virtio_transport_can_zcopy(t_ops, info, pkt_len); + + if (can_zcopy) + max_skb_len = min_t(u32, VIRTIO_VSOCK_MAX_PKT_BUF_SIZE, + (MAX_SKB_FRAGS * PAGE_SIZE)); + } + + rest_len = pkt_len; + + do { + struct sk_buff *skb; + size_t skb_len; + + skb_len = min(max_skb_len, rest_len); + + skb = virtio_transport_alloc_skb(info, skb_len, can_zcopy, + src_cid, src_port, + dst_cid, dst_port); + if (!skb) { + ret = -ENOMEM; + break; + } + + /* We process buffer part by part, allocating skb on + * each iteration. If this is last skb for this buffer + * and MSG_ZEROCOPY mode is in use - we must allocate + * completion for the current syscall. + */ + if (info->msg && info->msg->msg_flags & MSG_ZEROCOPY && + skb_len == rest_len && info->op == VIRTIO_VSOCK_OP_RW) { + if (virtio_transport_init_zcopy_skb(vsk, skb, + info->msg, + can_zcopy)) { + kfree_skb(skb); + ret = -ENOMEM; + break; + } + } + + virtio_transport_inc_tx_pkt(vvs, skb); + + ret = t_ops->send_pkt(skb); + if (ret < 0) + break; + + /* Both virtio and vhost 'send_pkt()' returns 'skb_len', + * but for reliability use 'ret' instead of 'skb_len'. + * Also if partial send happens (e.g. 'ret' != 'skb_len') + * somehow, we break this loop, but account such returned + * value in 'virtio_transport_put_credit()'. + */ + rest_len -= ret; + + if (WARN_ONCE(ret != skb_len, + "'send_pkt()' returns %i, but %zu expected\n", + ret, skb_len)) + break; + } while (rest_len); + + virtio_transport_put_credit(vvs, rest_len); + + /* Return number of bytes, if any data has been sent. */ + if (rest_len != pkt_len) + ret = pkt_len - rest_len; + + return ret; +} +``` diff --git a/tasks/csa159/pair_145442/pre_functions.txt b/tasks/csa159/pair_145442/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..69a8d55c8bb2ff621cea1b1cfeae68e01c49014e --- /dev/null +++ b/tasks/csa159/pair_145442/pre_functions.txt @@ -0,0 +1,114 @@ +### File: net/vmw_vsock/virtio_transport_common.c +```c +static int virtio_transport_send_pkt_info(struct vsock_sock *vsk, + struct virtio_vsock_pkt_info *info) +{ + u32 max_skb_len = VIRTIO_VSOCK_MAX_PKT_BUF_SIZE; + u32 src_cid, src_port, dst_cid, dst_port; + const struct virtio_transport *t_ops; + struct virtio_vsock_sock *vvs; + u32 pkt_len = info->pkt_len; + bool can_zcopy = false; + u32 rest_len; + int ret; + + info->type = virtio_transport_get_type(sk_vsock(vsk)); + + t_ops = virtio_transport_get_ops(vsk); + if (unlikely(!t_ops)) + return -EFAULT; + + src_cid = t_ops->transport.get_local_cid(); + src_port = vsk->local_addr.svm_port; + if (!info->remote_cid) { + dst_cid = vsk->remote_addr.svm_cid; + dst_port = vsk->remote_addr.svm_port; + } else { + dst_cid = info->remote_cid; + dst_port = info->remote_port; + } + + vvs = vsk->trans; + + /* virtio_transport_get_credit might return less than pkt_len credit */ + pkt_len = virtio_transport_get_credit(vvs, pkt_len); + + /* Do not send zero length OP_RW pkt */ + if (pkt_len == 0 && info->op == VIRTIO_VSOCK_OP_RW) + return pkt_len; + + if (info->msg) { + /* If zerocopy is not enabled by 'setsockopt()', we behave as + * there is no MSG_ZEROCOPY flag set. + */ + if (!sock_flag(sk_vsock(vsk), SOCK_ZEROCOPY)) + info->msg->msg_flags &= ~MSG_ZEROCOPY; + + if (info->msg->msg_flags & MSG_ZEROCOPY) + can_zcopy = virtio_transport_can_zcopy(t_ops, info, pkt_len); + + if (can_zcopy) + max_skb_len = min_t(u32, VIRTIO_VSOCK_MAX_PKT_BUF_SIZE, + (MAX_SKB_FRAGS * PAGE_SIZE)); + } + + rest_len = pkt_len; + + do { + struct sk_buff *skb; + size_t skb_len; + + skb_len = min(max_skb_len, rest_len); + + skb = virtio_transport_alloc_skb(info, skb_len, can_zcopy, + src_cid, src_port, + dst_cid, dst_port); + if (!skb) { + ret = -ENOMEM; + break; + } + + /* We process buffer part by part, allocating skb on + * each iteration. If this is last skb for this buffer + * and MSG_ZEROCOPY mode is in use - we must allocate + * completion for the current syscall. + */ + if (info->msg && info->msg->msg_flags & MSG_ZEROCOPY && + skb_len == rest_len && info->op == VIRTIO_VSOCK_OP_RW) { + if (virtio_transport_init_zcopy_skb(vsk, skb, + info->msg, + can_zcopy)) { + ret = -ENOMEM; + break; + } + } + + virtio_transport_inc_tx_pkt(vvs, skb); + + ret = t_ops->send_pkt(skb); + if (ret < 0) + break; + + /* Both virtio and vhost 'send_pkt()' returns 'skb_len', + * but for reliability use 'ret' instead of 'skb_len'. + * Also if partial send happens (e.g. 'ret' != 'skb_len') + * somehow, we break this loop, but account such returned + * value in 'virtio_transport_put_credit()'. + */ + rest_len -= ret; + + if (WARN_ONCE(ret != skb_len, + "'send_pkt()' returns %i, but %zu expected\n", + ret, skb_len)) + break; + } while (rest_len); + + virtio_transport_put_credit(vvs, rest_len); + + /* Return number of bytes, if any data has been sent. */ + if (rest_len != pkt_len) + ret = pkt_len - rest_len; + + return ret; +} +``` diff --git a/tasks/csa159/pair_145442/task_prompt.md b/tasks/csa159/pair_145442/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..5d5a8c78e3ea0f4a4a8d29c824327f3bbee9b8ed --- /dev/null +++ b/tasks/csa159/pair_145442/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: `path_sensitive` + +### Current failure diagnosis + +- The rollout was not accepted because refinement ended with feedback_required and process quality scored 71.74, despite successful objective and semantic gates. +- The stated bug pattern required abandonment on a loop-break path, but the implementation only proved that an owned skb symbol died; it did not establish that control left the allocating loop through break. +- Broad substring-based ownership-transfer heuristics such as xmit, queue, and receive-related names can discharge ownership without evidence that the specific argument is consumed. +- Validation involved repeated compile, analyzer, and scan failures, and at least two analyzer validation failures were not followed by demonstrated successful recovery. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Retain at least the previously accepted path-sensitive CSA mechanism and a semantic score at or above the configured threshold. +- Retain the demonstrated differential result of two relevant vulnerable-revision warnings and zero patched-revision warnings. +- Keep diagnostics within the patched function and near the repaired failure block, with no warnings in non-patched functions. +- Remain independent of patch anchors and patch-local hardcoding. + +### Required semantic proof + +- On each path, establish that a non-NULL struct sk_buff returned by a recognized kernel skb allocator is owned by the current function. +- Establish that the owned skb reaches an exit from the loop iteration through the init-zcopy failure break without an intervening release, ownership transfer, or return to the caller. +- Treat kfree_skb on the patched failure path as a discharge of the exact tracked skb, causing suppression on that path. +- Treat t_ops->send_pkt(skb) as transfer of the exact tracked skb so the normal path and later breaks after send_pkt are not reported. +- Preserve ownership across non-consuming calls, including virtio_transport_init_zcopy_skb and virtio_transport_inc_tx_pkt. +- Exclude allocator NULL-return paths from ownership and reporting. + +### Implementation constraints + +- Use ProgramState to track ownership per symbolic skb region across analyzer paths; local AST matching or control-flow inspection alone is insufficient under the accepted contract. +- Observe allocation with check::PostCall, release or transfer with check::PreCall, returned ownership with check::PreStmt, and final liveness with check::DeadSymbols. +- Relate the dead owned symbol to CFG evidence that the relevant path exited the loop through a BreakStmt; do not claim loop-break semantics from symbol death alone. +- Resolve direct callees and function-pointer member calls sufficiently to distinguish virtio_transport_init_zcopy_skb from t_ops->send_pkt. +- Discharge ownership only when a recognized consuming operation receives the tracked region as the relevant argument. +- Emit a path-sensitive report at the vulnerable failure block or its canonical leak point while preserving patch-near diagnostic locality and stable report uniquing. +- Scope the synthesis to project-general Linux sk_buff ownership APIs without using the target function name, variable name, source lines, commit identity, or inserted statement as conditions. + +### Validation checklist + +- Compile the checker against the supplied LLVM 18 CSA interfaces and confirm registration and loading with a real analyzer input file. +- Scan both supplied vulnerable inputs and require exactly the established two relevant warnings; scan both patched inputs and require zero warnings. +- Verify that each vulnerable warning belongs to virtio_transport_send_pkt_info and is located at or immediately associated with the init-zcopy failure block repaired by the patch. +- Verify that allocator failure returning NULL does not report. +- Verify that kfree_skb and other explicitly supported release calls discharge only the matching tracked skb. +- Verify that t_ops->send_pkt suppresses reports on the normal path and on breaks occurring after that transfer. +- Verify that non-consuming calls do not escape or discharge the skb and that returning the tracked skb transfers ownership. +- Repeat code verification and refinement until refinement is accepted, recording successful recovery after every failed compile, analyzer, or scan check. + +### Avoid and forbidden regressions + +- Do not use check::PreStmt as the sink; the evidence shows that LLVM 18 does not emit break as a PreStmt event. +- Do not use check::EndFunction as the sole sink because symbol cleanup can lose the NULL constraint and create patched-code false positives. +- Do not treat every unknown-call pointer escape as ownership transfer; that suppresses the true positive at virtio_transport_init_zcopy_skb. +- Do not use custom allocation-site PathDiagnosticLocation uniquing that crashes the LLVM 18 plist diagnostic consumer. +- Do not substitute statement, line, function, variable, commit, or inserted-text matching for the ownership and control-flow proof. +- Do not classify ownership transfer solely through broad callee-name substring matching. +- Do not generalize the diagnostic to every owned skb scope exit while describing it as proof of loop-break abandonment. diff --git a/tasks/csa159/pair_145527/checker_template.cpp b/tasks/csa159/pair_145527/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_145527/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_145527/config.json b/tasks/csa159/pair_145527/config.json new file mode 100644 index 0000000000000000000000000000000000000000..2e28236fe8388feef8e66546bc27c59b3f2e56ae --- /dev/null +++ b/tasks/csa159/pair_145527/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "2481af79671a6603fce201cbbc48f31e488e9fae", + "after_commit": "e56aac6e5a25630645607b6856d4b2a17b2311a5", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/7c561b8c3e83687064c957c394ed9fe49e38fe00/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/7c561b8c3e83687064c957c394ed9fe49e38fe00/compile_commands.json", + "changed_files": [ + "drivers/usb/typec/ucsi/ucsi_ccg.c" + ], + "commit_message": "usb: typec: fix potential array underflow in ucsi_ccg_sync_control()\n\nThe \"command\" variable can be controlled by the user via debugfs. The\nworry is that if con_index is zero then \"&uc->ucsi->connector[con_index\n- 1]\" would be an array underflow.\n\nFixes: 170a6726d0e2 (\"usb: typec: ucsi: add support for separate DP altmode devices\")\nSigned-off-by: Dan Carpenter \nReviewed-by: Heikki Krogerus \nLink: https://lore.kernel.org/r/c69ef0b3-61b0-4dde-98dd-97b97f81d912@stanley.mountain\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_145527/patch.diff b/tasks/csa159/pair_145527/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..65ef146955417e4410353ecf58076b64df85ee4b --- /dev/null +++ b/tasks/csa159/pair_145527/patch.diff @@ -0,0 +1,23 @@ +diff --git a/drivers/usb/typec/ucsi/ucsi_ccg.c b/drivers/usb/typec/ucsi/ucsi_ccg.c +index ba58d11907bc..ec813eb908a7 100644 +--- a/drivers/usb/typec/ucsi/ucsi_ccg.c ++++ b/drivers/usb/typec/ucsi/ucsi_ccg.c +@@ -642,6 +642,10 @@ static int ucsi_ccg_sync_control(struct ucsi *ucsi, u64 command) + uc->has_multiple_dp) { + con_index = (uc->last_cmd_sent >> 16) & + UCSI_CMD_CONNECTOR_MASK; ++ if (con_index == 0) { ++ ret = -EINVAL; ++ goto unlock; ++ } + con = &uc->ucsi->connector[con_index - 1]; + ucsi_ccg_update_set_new_cam_cmd(uc, con, &command); + } +@@ -649,6 +653,7 @@ static int ucsi_ccg_sync_control(struct ucsi *ucsi, u64 command) + ret = ucsi_sync_control_common(ucsi, command); + + pm_runtime_put_sync(uc->dev); ++unlock: + mutex_unlock(&uc->lock); + + return ret; \ No newline at end of file diff --git a/tasks/csa159/pair_145527/post_functions.txt b/tasks/csa159/pair_145527/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..2c7af9a611f54f3020d5e5c8831138d0fa1db5fb --- /dev/null +++ b/tasks/csa159/pair_145527/post_functions.txt @@ -0,0 +1,35 @@ +### File: drivers/usb/typec/ucsi/ucsi_ccg.c +```c +static int ucsi_ccg_sync_control(struct ucsi *ucsi, u64 command) +{ + struct ucsi_ccg *uc = ucsi_get_drvdata(ucsi); + struct ucsi_connector *con; + int con_index; + int ret; + + mutex_lock(&uc->lock); + pm_runtime_get_sync(uc->dev); + + uc->last_cmd_sent = command; + + if (UCSI_COMMAND(uc->last_cmd_sent) == UCSI_SET_NEW_CAM && + uc->has_multiple_dp) { + con_index = (uc->last_cmd_sent >> 16) & + UCSI_CMD_CONNECTOR_MASK; + if (con_index == 0) { + ret = -EINVAL; + goto unlock; + } + con = &uc->ucsi->connector[con_index - 1]; + ucsi_ccg_update_set_new_cam_cmd(uc, con, &command); + } + + ret = ucsi_sync_control_common(ucsi, command); + + pm_runtime_put_sync(uc->dev); +unlock: + mutex_unlock(&uc->lock); + + return ret; +} +``` diff --git a/tasks/csa159/pair_145527/pre_functions.txt b/tasks/csa159/pair_145527/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..e83d092f9d0afa3f48c9cbec91a77cb9a188ff74 --- /dev/null +++ b/tasks/csa159/pair_145527/pre_functions.txt @@ -0,0 +1,30 @@ +### File: drivers/usb/typec/ucsi/ucsi_ccg.c +```c +static int ucsi_ccg_sync_control(struct ucsi *ucsi, u64 command) +{ + struct ucsi_ccg *uc = ucsi_get_drvdata(ucsi); + struct ucsi_connector *con; + int con_index; + int ret; + + mutex_lock(&uc->lock); + pm_runtime_get_sync(uc->dev); + + uc->last_cmd_sent = command; + + if (UCSI_COMMAND(uc->last_cmd_sent) == UCSI_SET_NEW_CAM && + uc->has_multiple_dp) { + con_index = (uc->last_cmd_sent >> 16) & + UCSI_CMD_CONNECTOR_MASK; + con = &uc->ucsi->connector[con_index - 1]; + ucsi_ccg_update_set_new_cam_cmd(uc, con, &command); + } + + ret = ucsi_sync_control_common(ucsi, command); + + pm_runtime_put_sync(uc->dev); + mutex_unlock(&uc->lock); + + return ret; +} +``` diff --git a/tasks/csa159/pair_145527/task_prompt.md b/tasks/csa159/pair_145527/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..257c3cf8126012630676e606a24af7f329f7e4cd --- /dev/null +++ b/tasks/csa159/pair_145527/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: `path_sensitive` + +### Current failure diagnosis + +- The rollout achieved adequate semantic detection and passed compile, differential scan, locality, scope, and hardcoding checks, but refinement_accepted remained false because refinement was not converged and feedback was still required. +- The validation history included two compilation failures before recovery, so the new synthesis must reduce avoidable API and type-construction errors and demonstrate a clean validation sequence. +- The existing evidence establishes plausibility and an adequate semantic score, but not an accepted refinement result; acceptance therefore requires explicit refinement validation rather than relying on the prior scan outcome. + +### Preserve from prior rollouts + +- Preserve successful compilation, before/after validation, and code verification. +- Preserve objective eligibility gate G6. +- Preserve the path-sensitive CSA mechanism level accepted by the semantic contract. +- 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 + +- At a signed array subscript, establish that the index has the structural form x - K where K is a positive integer constant. +- Use the current ProgramState to prove that the negative index range [signed_minimum, -1] remains feasible on the path reaching the subscript; only then report a possible array underflow. +- Demonstrate that the pre-patch masked connector value can equal zero, making con_index - 1 equal -1 and accessing before the connector array. +- Demonstrate that the post-patch zero-value rejection dominates the subscript and makes the negative range infeasible on the surviving path, producing no report. +- Keep unsigned subtraction outside this signed-index-underflow contract. + +### Implementation constraints + +- Use a check::PreStmt callback so the checker observes the index operation together with the path state before the access is committed. +- Use AST structure only to identify a signed integer subtraction with a positive constant right operand; do not match variable names, source text, line numbers, function names, patch literals, or the guard's statement shape. +- Query the built-in CSA constraint manager through ProgramState for feasibility of the signed negative index range; do not replace this proof with a syntactic guard search. +- Report locally at the vulnerable ArraySubscriptExpr and retain expression tracking sufficient to identify the subtraction/index in the diagnostic path. +- Limit the checker to signed integer index expressions and avoid reporting unsigned wraparound as signed underflow. +- Keep the checker project-general and independent of ucsi_ccg, con_index, connector, CVE identifiers, and patch-specific constants. + +### Validation checklist + +- Compile the new checker successfully against the target Clang Static Analyzer API before running scans, with no recoverable compile-error cycle. +- Run the checker on both original and patched source versions and confirm detection in the original version and zero reports in the patched version. +- Verify that the original reports are in ucsi_ccg_sync_control at the signed connector subscript and remain within the relevant changed function or precise patch span. +- Confirm cross-validation produces the expected buggy and patched counts and that no warnings disappear from unrelated functions. +- Check that the zero guard's surviving path carries the constraint that makes the negative index range infeasible, rather than merely observing that the guard exists syntactically. +- Re-run the refinement evaluation and require refinement_accepted to become true while retaining G6, hard-validation, semantic-mechanism, semantic-score, process-score, anchor-free, and hardcoding-free results. + +### Avoid and forbidden regressions + +- Do not use a syntax-only match or a local CFG guard pattern as the vulnerability proof; the same subscript text occurs before and after the patch. +- Do not use check::PostStmt when the required path fact must be evaluated before the access is committed. +- Do not track guards with a redundant custom map when the built-in range constraint manager can propagate the constraint through the derived index. +- Do not report every subtraction or every array subscript without proving signed negative-range feasibility. +- Do not conflate unsigned arithmetic wraparound with signed index underflow. +- Do not add identifiers, literals, line anchors, source strings, or control-flow shapes copied from the patch. +- Do not treat the prior adequate semantic score as sufficient evidence that refinement has been accepted. diff --git a/tasks/csa159/pair_145663/checker_template.cpp b/tasks/csa159/pair_145663/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_145663/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_145663/config.json b/tasks/csa159/pair_145663/config.json new file mode 100644 index 0000000000000000000000000000000000000000..c8c8b3db84756ef793dfe16b641ea42e22930f42 --- /dev/null +++ b/tasks/csa159/pair_145663/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "46f2a11cb82b657fd15bab1c47821b635e03838b", + "after_commit": "7c4f78cdb8e7501e9f92d291a7d956591bf73be9", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/60b4d49b9621db4b000c9065dd6457c9a0eda80b/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/60b4d49b9621db4b000c9065dd6457c9a0eda80b/compile_commands.json", + "changed_files": [ + "net/bluetooth/l2cap_sock.c" + ], + "commit_message": "Bluetooth: L2CAP: do not leave dangling sk pointer on error in l2cap_sock_create()\n\nbt_sock_alloc() allocates the sk object and attaches it to the provided\nsock object. On error l2cap_sock_alloc() frees the sk object, but the\ndangling pointer is still attached to the sock object, which may create\nuse-after-free in other code.\n\nSigned-off-by: Ignat Korchagin \nReviewed-by: Kuniyuki Iwashima \nReviewed-by: Eric Dumazet \nLink: https://patch.msgid.link/20241014153808.51894-3-ignat@cloudflare.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_145663/patch.diff b/tasks/csa159/pair_145663/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..652b689e7b317a39f325918acce828322b3fddc5 --- /dev/null +++ b/tasks/csa159/pair_145663/patch.diff @@ -0,0 +1,11 @@ +diff --git a/net/bluetooth/l2cap_sock.c b/net/bluetooth/l2cap_sock.c +index ba437c6f6ee5..18e89e764f3b 100644 +--- a/net/bluetooth/l2cap_sock.c ++++ b/net/bluetooth/l2cap_sock.c +@@ -1886,6 +1886,7 @@ static struct sock *l2cap_sock_alloc(struct net *net, struct socket *sock, + chan = l2cap_chan_create(); + if (!chan) { + sk_free(sk); ++ sock->sk = NULL; + return NULL; + } \ No newline at end of file diff --git a/tasks/csa159/pair_145663/post_functions.txt b/tasks/csa159/pair_145663/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..c151b879e4ddcd62b7d3e4c76174bccced18a668 --- /dev/null +++ b/tasks/csa159/pair_145663/post_functions.txt @@ -0,0 +1,31 @@ +### File: net/bluetooth/l2cap_sock.c +```c +static struct sock *l2cap_sock_alloc(struct net *net, struct socket *sock, + int proto, gfp_t prio, int kern) +{ + struct sock *sk; + struct l2cap_chan *chan; + + sk = bt_sock_alloc(net, sock, &l2cap_proto, proto, prio, kern); + if (!sk) + return NULL; + + sk->sk_destruct = l2cap_sock_destruct; + sk->sk_sndtimeo = L2CAP_CONN_TIMEOUT; + + INIT_LIST_HEAD(&l2cap_pi(sk)->rx_busy); + + chan = l2cap_chan_create(); + if (!chan) { + sk_free(sk); + sock->sk = NULL; + return NULL; + } + + l2cap_chan_hold(chan); + + l2cap_pi(sk)->chan = chan; + + return sk; +} +``` diff --git a/tasks/csa159/pair_145663/pre_functions.txt b/tasks/csa159/pair_145663/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..71b8375ab276cb4c4217d54f83ccc29f2062aa71 --- /dev/null +++ b/tasks/csa159/pair_145663/pre_functions.txt @@ -0,0 +1,30 @@ +### File: net/bluetooth/l2cap_sock.c +```c +static struct sock *l2cap_sock_alloc(struct net *net, struct socket *sock, + int proto, gfp_t prio, int kern) +{ + struct sock *sk; + struct l2cap_chan *chan; + + sk = bt_sock_alloc(net, sock, &l2cap_proto, proto, prio, kern); + if (!sk) + return NULL; + + sk->sk_destruct = l2cap_sock_destruct; + sk->sk_sndtimeo = L2CAP_CONN_TIMEOUT; + + INIT_LIST_HEAD(&l2cap_pi(sk)->rx_busy); + + chan = l2cap_chan_create(); + if (!chan) { + sk_free(sk); + return NULL; + } + + l2cap_chan_hold(chan); + + l2cap_pi(sk)->chan = chan; + + return sk; +} +``` diff --git a/tasks/csa159/pair_145663/task_prompt.md b/tasks/csa159/pair_145663/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..0201fafcd09a9bae785fbd0a0c7a8d088fca4386 --- /dev/null +++ b/tasks/csa159/pair_145663/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: `control_flow` + +### Current failure diagnosis + +- The prior rollout compiled and scanned successfully but emitted zero diagnostics on both buggy and patched sources, so its attachment/free correlation never established the evidenced vulnerability. +- Hard validation and cross-validation failed because N_buggy=0 and N_patched=0; no disappearing diagnostic or report-location evidence exists. +- The attempted path-sensitive MemRegion model remained semantically unproven; the evidence does not show that allocator return regions, the local sk value, and sk_free arguments were represented by matching regions. +- Refinement was not run, semantic evaluation was unavailable, and the objective gate remained G3, so neither detection behavior nor false-positive control was demonstrated. + +### Preserve from prior rollouts + +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Establish a feasible intra-function CFG path where a recognized attach-allocator result assigned to a struct sock pointer is passed as the same value to sk_free, followed by a return. +- On that path, establish that the associated struct socket::sk carrier is not cleared or rebound after sk_free and before the return. +- Treat a write to the corresponding struct socket::sk between the free and return, including sock->sk = NULL, as preventing the diagnostic on that path. +- Require value identity through local declarations and cast/parenthesis normalization; do not infer vulnerability merely because an allocator, sk_free, and return occur somewhere in the same function. +- Report only when an unsafe path exists; paths that do not reach sk_free or do not proceed from that free to the return are not evidence of the defect. + +### Implementation constraints + +- Use an intra-procedural CSA body callback such as check::ASTCodeBody and analyze the function CFG; local AST matching alone is insufficient because ordering and branch reachability are required. +- Model CFG facts for the allocator-derived struct sock value, its associated struct socket argument, the matching sk_free call, and carrier-field writes; propagate and merge them conservatively across blocks. +- Recognize the attach contract structurally by callable/type information consistent with the evidence, and recognize sk_free by its declaration and struct sock pointer parameter; do not key detection to l2cap_sock_alloc, source lines, commit identifiers, or L2CAP-only symbols. +- Match the freed argument to the allocator-derived local value using declaration/value identity, accounting for implicit casts and parentheses. +- Associate a carrier-field write only with field sk of struct socket and the corresponding socket object; an unrelated sk field or unrelated socket must not suppress a report. +- Emit at most one diagnostic for an unsafe return, located on that ReturnStmt, with an explanatory note at the matching sk_free call. +- Keep analysis intra-procedural; no cross-function fact propagation is required because the attach behavior is represented by the recognized allocator contract at its call site. +- Do not depend on path-sensitive ProgramState or MemRegion identity when CFG ordering and local value identity are sufficient for the supplied source pattern. + +### Validation checklist + +- Compile and load the fresh checker successfully with the target Clang Static Analyzer environment and confirm checker registration. +- Scan the buggy pre-patch source and require at least one diagnostic in l2cap_sock_alloc for the sk_free-to-return error path. +- Scan the patched source and require the buggy diagnostic to disappear because sock->sk = NULL lies between sk_free(sk) and return NULL on that CFG path. +- Verify the primary diagnostic is on or near the vulnerable return and the note identifies the corresponding sk_free call. +- Run cross-validation on both supplied revisions and require N_buggy greater than zero, N_patched lower than N_buggy, and at least one relevant disappearing warning. +- Test refinements for no free, free on an unreachable/different branch, clear after free, rebind after free, unrelated socket-field writes, and freeing a different struct sock value. +- Confirm diagnostics remain sparse outside the patched function and that any remaining warnings satisfy the same allocator/free/uncleared-return relation. +- Complete refinement and hard validation rather than accepting compile success or scan completion as semantic validation. + +### Avoid and forbidden regressions + +- Do not repeat the failed assumption that recording allocator and free MemRegions in ProgramState is adequate without evidence that their identities survive assignment and callback boundaries. +- Do not use syntax-only co-occurrence of allocator, sk_free, field write, and return; it cannot establish their ordering or reachability on one CFG path. +- Do not suppress all findings merely because any sock->sk write exists elsewhere in the function; only a corresponding write after the matching free and before the return is relevant. +- Do not report at function end or caller returns when the unsafe leaving operation is a specific return in the owning function. +- Do not specialize to the changed line, l2cap_sock_alloc, l2cap_chan_create, the commit id, or fixed source locations. +- Do not claim success from a zero-warning run, unavailable semantic score, or unexecuted refinement. diff --git a/tasks/csa159/pair_145933/checker_template.cpp b/tasks/csa159/pair_145933/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_145933/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_145933/config.json b/tasks/csa159/pair_145933/config.json new file mode 100644 index 0000000000000000000000000000000000000000..dde0490552b8ab29047f34e5529fb3c3e3f0d70c --- /dev/null +++ b/tasks/csa159/pair_145933/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "8c28c4993f117e03130a51160229bde7ad388240", + "after_commit": "09c4a610153286cef54d4f0c85398f4e32fc227e", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/40384c840ea1944d7c5a392e8975ed088ecf0b37/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/40384c840ea1944d7c5a392e8975ed088ecf0b37/compile_commands.json", + "changed_files": [ + "drivers/rtc/rtc-tps6594.c" + ], + "commit_message": "rtc: tps6594: Fix integer overflow on 32bit systems\n\nThe problem is this multiply in tps6594_rtc_set_offset()\n\n\ttmp = offset * TICKS_PER_HOUR;\n\nThe \"tmp\" variable is an s64 but \"offset\" is a long in the\n(-277774)-277774 range. On 32bit systems a long can hold numbers up to\napproximately two billion. The number of TICKS_PER_HOUR is really large,\n(32768 * 3600) or roughly a hundred million. When you start multiplying\nby a hundred million it doesn't take long to overflow the two billion\nmark.\n\nProbably the safest way to fix this is to change the type of\nTICKS_PER_HOUR to long long because it's such a large number.\n\nFixes: 9f67c1e63976 (\"rtc: tps6594: Add driver for TPS6594 RTC\")\nSigned-off-by: Dan Carpenter \nLink: https://lore.kernel.org/r/1074175e-5ecb-4e3d-b721-347d794caa90@stanley.mountain\nSigned-off-by: Alexandre Belloni ", + "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_145933/patch.diff b/tasks/csa159/pair_145933/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d98d7edbac3790dc390b700fbefaea49ab788098 --- /dev/null +++ b/tasks/csa159/pair_145933/patch.diff @@ -0,0 +1,13 @@ +diff --git a/drivers/rtc/rtc-tps6594.c b/drivers/rtc/rtc-tps6594.c +index e69667634137..7c6246e3f029 100644 +--- a/drivers/rtc/rtc-tps6594.c ++++ b/drivers/rtc/rtc-tps6594.c +@@ -37,7 +37,7 @@ + #define MAX_OFFSET (277774) + + // Number of ticks per hour +-#define TICKS_PER_HOUR (32768 * 3600) ++#define TICKS_PER_HOUR (32768 * 3600LL) + + // Multiplier for ppb conversions + #define PPB_MULT NANO \ No newline at end of file diff --git a/tasks/csa159/pair_145933/post_functions.txt b/tasks/csa159/pair_145933/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..0f9953b542d7351d07aa12ad6494709f5be3b3c4 --- /dev/null +++ b/tasks/csa159/pair_145933/post_functions.txt @@ -0,0 +1,313 @@ +### File: drivers/rtc/rtc-tps6594.c +```c +// SPDX-License-Identifier: GPL-2.0 +/* + * RTC driver for tps6594 PMIC + * + * Copyright (C) 2023 BayLibre Incorporated - https://www.baylibre.com/ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// Total number of RTC registers needed to set time +#define NUM_TIME_REGS (TPS6594_REG_RTC_WEEKS - TPS6594_REG_RTC_SECONDS + 1) + +// Total number of RTC alarm registers +#define NUM_TIME_ALARM_REGS (NUM_TIME_REGS - 1) + +/* + * Min and max values supported by 'offset' interface (swapped sign). + * After conversion, the values do not exceed the range [-32767, 33767] + * which COMP_REG must conform to. + */ +#define MIN_OFFSET (-277774) +#define MAX_OFFSET (277774) + +// Number of ticks per hour +#define TICKS_PER_HOUR (32768 * 3600LL) + +// Multiplier for ppb conversions +#define PPB_MULT NANO + +struct tps6594_rtc { + struct rtc_device *rtc_dev; + int irq; +}; + +static int tps6594_rtc_alarm_irq_enable(struct device *dev, + unsigned int enabled) +{ + struct tps6594 *tps = dev_get_drvdata(dev->parent); + u8 val; + + val = enabled ? TPS6594_BIT_IT_ALARM : 0; + + return regmap_update_bits(tps->regmap, TPS6594_REG_RTC_INTERRUPTS, + TPS6594_BIT_IT_ALARM, val); +} + +/* Pulse GET_TIME field of RTC_CTRL_1 to store a timestamp in shadow registers. */ +static int tps6594_rtc_shadow_timestamp(struct device *dev, struct tps6594 *tps) +{ + int ret; + + /* + * Set GET_TIME to 0. Next time we set GET_TIME to 1 we will be sure to store + * an up-to-date timestamp. + */ + ret = regmap_clear_bits(tps->regmap, TPS6594_REG_RTC_CTRL_1, + TPS6594_BIT_GET_TIME); + if (ret < 0) + return ret; + + /* + * Copy content of RTC registers to shadow registers or latches to read + * a coherent timestamp. + */ + return regmap_set_bits(tps->regmap, TPS6594_REG_RTC_CTRL_1, + TPS6594_BIT_GET_TIME); +} + +static int tps6594_rtc_read_time(struct device *dev, struct rtc_time *tm) +{ + unsigned char rtc_data[NUM_TIME_REGS]; + struct tps6594 *tps = dev_get_drvdata(dev->parent); + int ret; + + // Check if RTC is running. + ret = regmap_test_bits(tps->regmap, TPS6594_REG_RTC_STATUS, + TPS6594_BIT_RUN); + if (ret < 0) + return ret; + if (ret == 0) + return -EINVAL; + + ret = tps6594_rtc_shadow_timestamp(dev, tps); + if (ret < 0) + return ret; + + // Read shadowed RTC registers. + ret = regmap_bulk_read(tps->regmap, TPS6594_REG_RTC_SECONDS, rtc_data, + NUM_TIME_REGS); + if (ret < 0) + return ret; + + tm->tm_sec = bcd2bin(rtc_data[0]); + tm->tm_min = bcd2bin(rtc_data[1]); + tm->tm_hour = bcd2bin(rtc_data[2]); + tm->tm_mday = bcd2bin(rtc_data[3]); + tm->tm_mon = bcd2bin(rtc_data[4]) - 1; + tm->tm_year = bcd2bin(rtc_data[5]) + 100; + tm->tm_wday = bcd2bin(rtc_data[6]); + + return 0; +} + +static int tps6594_rtc_set_time(struct device *dev, struct rtc_time *tm) +{ + unsigned char rtc_data[NUM_TIME_REGS]; + struct tps6594 *tps = dev_get_drvdata(dev->parent); + int ret; + + rtc_data[0] = bin2bcd(tm->tm_sec); + rtc_data[1] = bin2bcd(tm->tm_min); + rtc_data[2] = bin2bcd(tm->tm_hour); + rtc_data[3] = bin2bcd(tm->tm_mday); + rtc_data[4] = bin2bcd(tm->tm_mon + 1); + rtc_data[5] = bin2bcd(tm->tm_year - 100); + rtc_data[6] = bin2bcd(tm->tm_wday); + + // Stop RTC while updating the RTC time registers. + ret = regmap_clear_bits(tps->regmap, TPS6594_REG_RTC_CTRL_1, + TPS6594_BIT_STOP_RTC); + if (ret < 0) + return ret; + + // Update all the time registers in one shot. + ret = regmap_bulk_write(tps->regmap, TPS6594_REG_RTC_SECONDS, rtc_data, + NUM_TIME_REGS); + if (ret < 0) + return ret; + + // Start back RTC. + return regmap_set_bits(tps->regmap, TPS6594_REG_RTC_CTRL_1, + TPS6594_BIT_STOP_RTC); +} + +static int tps6594_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alm) +{ + unsigned char alarm_data[NUM_TIME_ALARM_REGS]; + u32 int_val; + struct tps6594 *tps = dev_get_drvdata(dev->parent); + int ret; + + ret = regmap_bulk_read(tps->regmap, TPS6594_REG_ALARM_SECONDS, + alarm_data, NUM_TIME_ALARM_REGS); + if (ret < 0) + return ret; + + alm->time.tm_sec = bcd2bin(alarm_data[0]); + alm->time.tm_min = bcd2bin(alarm_data[1]); + alm->time.tm_hour = bcd2bin(alarm_data[2]); + alm->time.tm_mday = bcd2bin(alarm_data[3]); + alm->time.tm_mon = bcd2bin(alarm_data[4]) - 1; + alm->time.tm_year = bcd2bin(alarm_data[5]) + 100; + + ret = regmap_read(tps->regmap, TPS6594_REG_RTC_INTERRUPTS, &int_val); + if (ret < 0) + return ret; + + alm->enabled = int_val & TPS6594_BIT_IT_ALARM; + + return 0; +} + +static int tps6594_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alm) +{ + unsigned char alarm_data[NUM_TIME_ALARM_REGS]; + struct tps6594 *tps = dev_get_drvdata(dev->parent); + int ret; + + // Disable alarm irq before changing the alarm timestamp. + ret = tps6594_rtc_alarm_irq_enable(dev, 0); + if (ret) + return ret; + + alarm_data[0] = bin2bcd(alm->time.tm_sec); + alarm_data[1] = bin2bcd(alm->time.tm_min); + alarm_data[2] = bin2bcd(alm->time.tm_hour); + alarm_data[3] = bin2bcd(alm->time.tm_mday); + alarm_data[4] = bin2bcd(alm->time.tm_mon + 1); + alarm_data[5] = bin2bcd(alm->time.tm_year - 100); + + // Update all the alarm registers in one shot. + ret = regmap_bulk_write(tps->regmap, TPS6594_REG_ALARM_SECONDS, + alarm_data, NUM_TIME_ALARM_REGS); + if (ret < 0) + return ret; + + if (alm->enabled) + ret = tps6594_rtc_alarm_irq_enable(dev, 1); + + return ret; +} + +static int tps6594_rtc_set_calibration(struct device *dev, int calibration) +{ + struct tps6594 *tps = dev_get_drvdata(dev->parent); + __le16 value; + int ret; + + /* + * TPS6594 uses two's complement 16 bit value for compensation of RTC + * crystal inaccuracies. One time every hour when seconds counter + * increments from 0 to 1 compensation value will be added to internal + * RTC counter value. + * + * Valid range for compensation value: [-32767 .. 32767]. + */ + if (calibration < S16_MIN + 1 || calibration > S16_MAX) + return -ERANGE; + + value = cpu_to_le16(calibration); + + // Update all the compensation registers in one shot. + ret = regmap_bulk_write(tps->regmap, TPS6594_REG_RTC_COMP_LSB, &value, + sizeof(value)); + if (ret < 0) + return ret; + + // Enable automatic compensation. + return regmap_set_bits(tps->regmap, TPS6594_REG_RTC_CTRL_1, + TPS6594_BIT_AUTO_COMP); +} + +static int tps6594_rtc_get_calibration(struct device *dev, int *calibration) +{ + struct tps6594 *tps = dev_get_drvdata(dev->parent); + unsigned int ctrl; + __le16 value; + int ret; + + ret = regmap_read(tps->regmap, TPS6594_REG_RTC_CTRL_1, &ctrl); + if (ret < 0) + return ret; + + // If automatic compensation is not enabled report back zero. + if (!(ctrl & TPS6594_BIT_AUTO_COMP)) { + *calibration = 0; + return 0; + } + + ret = regmap_bulk_read(tps->regmap, TPS6594_REG_RTC_COMP_LSB, &value, + sizeof(value)); + if (ret < 0) + return ret; + + *calibration = le16_to_cpu(value); + + return 0; +} + +static int tps6594_rtc_read_offset(struct device *dev, long *offset) +{ + int calibration; + s64 tmp; + int ret; + + ret = tps6594_rtc_get_calibration(dev, &calibration); + if (ret < 0) + return ret; + + // Convert from RTC calibration register format to ppb format. + tmp = calibration * PPB_MULT; + + if (tmp < 0) + tmp -= TICKS_PER_HOUR / 2LL; + else + tmp += TICKS_PER_HOUR / 2LL; + tmp = div_s64(tmp, TICKS_PER_HOUR); + + /* + * SAFETY: + * Computatiion is the reverse operation of the one done in + * `tps6594_rtc_set_offset`. The safety remarks applie here too. + */ + + /* + * Offset value operates in negative way, so swap sign. + * See 8.3.10.5, (32768 - COMP_REG). + */ + *offset = (long)-tmp; + + return 0; +} + +static int tps6594_rtc_set_offset(struct device *dev, long offset) +{ + int calibration; + s64 tmp; + + // Make sure offset value is within supported range. + if (offset < MIN_OFFSET || offset > MAX_OFFSET) + return -ERANGE; + + // Convert from ppb format to RTC calibration register form + +// ... (5073 more chars) +``` diff --git a/tasks/csa159/pair_145933/pre_functions.txt b/tasks/csa159/pair_145933/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..10e4d5383a16da136468d03e3de91a05caf9ff1e --- /dev/null +++ b/tasks/csa159/pair_145933/pre_functions.txt @@ -0,0 +1,313 @@ +### File: drivers/rtc/rtc-tps6594.c +```c +// SPDX-License-Identifier: GPL-2.0 +/* + * RTC driver for tps6594 PMIC + * + * Copyright (C) 2023 BayLibre Incorporated - https://www.baylibre.com/ + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// Total number of RTC registers needed to set time +#define NUM_TIME_REGS (TPS6594_REG_RTC_WEEKS - TPS6594_REG_RTC_SECONDS + 1) + +// Total number of RTC alarm registers +#define NUM_TIME_ALARM_REGS (NUM_TIME_REGS - 1) + +/* + * Min and max values supported by 'offset' interface (swapped sign). + * After conversion, the values do not exceed the range [-32767, 33767] + * which COMP_REG must conform to. + */ +#define MIN_OFFSET (-277774) +#define MAX_OFFSET (277774) + +// Number of ticks per hour +#define TICKS_PER_HOUR (32768 * 3600) + +// Multiplier for ppb conversions +#define PPB_MULT NANO + +struct tps6594_rtc { + struct rtc_device *rtc_dev; + int irq; +}; + +static int tps6594_rtc_alarm_irq_enable(struct device *dev, + unsigned int enabled) +{ + struct tps6594 *tps = dev_get_drvdata(dev->parent); + u8 val; + + val = enabled ? TPS6594_BIT_IT_ALARM : 0; + + return regmap_update_bits(tps->regmap, TPS6594_REG_RTC_INTERRUPTS, + TPS6594_BIT_IT_ALARM, val); +} + +/* Pulse GET_TIME field of RTC_CTRL_1 to store a timestamp in shadow registers. */ +static int tps6594_rtc_shadow_timestamp(struct device *dev, struct tps6594 *tps) +{ + int ret; + + /* + * Set GET_TIME to 0. Next time we set GET_TIME to 1 we will be sure to store + * an up-to-date timestamp. + */ + ret = regmap_clear_bits(tps->regmap, TPS6594_REG_RTC_CTRL_1, + TPS6594_BIT_GET_TIME); + if (ret < 0) + return ret; + + /* + * Copy content of RTC registers to shadow registers or latches to read + * a coherent timestamp. + */ + return regmap_set_bits(tps->regmap, TPS6594_REG_RTC_CTRL_1, + TPS6594_BIT_GET_TIME); +} + +static int tps6594_rtc_read_time(struct device *dev, struct rtc_time *tm) +{ + unsigned char rtc_data[NUM_TIME_REGS]; + struct tps6594 *tps = dev_get_drvdata(dev->parent); + int ret; + + // Check if RTC is running. + ret = regmap_test_bits(tps->regmap, TPS6594_REG_RTC_STATUS, + TPS6594_BIT_RUN); + if (ret < 0) + return ret; + if (ret == 0) + return -EINVAL; + + ret = tps6594_rtc_shadow_timestamp(dev, tps); + if (ret < 0) + return ret; + + // Read shadowed RTC registers. + ret = regmap_bulk_read(tps->regmap, TPS6594_REG_RTC_SECONDS, rtc_data, + NUM_TIME_REGS); + if (ret < 0) + return ret; + + tm->tm_sec = bcd2bin(rtc_data[0]); + tm->tm_min = bcd2bin(rtc_data[1]); + tm->tm_hour = bcd2bin(rtc_data[2]); + tm->tm_mday = bcd2bin(rtc_data[3]); + tm->tm_mon = bcd2bin(rtc_data[4]) - 1; + tm->tm_year = bcd2bin(rtc_data[5]) + 100; + tm->tm_wday = bcd2bin(rtc_data[6]); + + return 0; +} + +static int tps6594_rtc_set_time(struct device *dev, struct rtc_time *tm) +{ + unsigned char rtc_data[NUM_TIME_REGS]; + struct tps6594 *tps = dev_get_drvdata(dev->parent); + int ret; + + rtc_data[0] = bin2bcd(tm->tm_sec); + rtc_data[1] = bin2bcd(tm->tm_min); + rtc_data[2] = bin2bcd(tm->tm_hour); + rtc_data[3] = bin2bcd(tm->tm_mday); + rtc_data[4] = bin2bcd(tm->tm_mon + 1); + rtc_data[5] = bin2bcd(tm->tm_year - 100); + rtc_data[6] = bin2bcd(tm->tm_wday); + + // Stop RTC while updating the RTC time registers. + ret = regmap_clear_bits(tps->regmap, TPS6594_REG_RTC_CTRL_1, + TPS6594_BIT_STOP_RTC); + if (ret < 0) + return ret; + + // Update all the time registers in one shot. + ret = regmap_bulk_write(tps->regmap, TPS6594_REG_RTC_SECONDS, rtc_data, + NUM_TIME_REGS); + if (ret < 0) + return ret; + + // Start back RTC. + return regmap_set_bits(tps->regmap, TPS6594_REG_RTC_CTRL_1, + TPS6594_BIT_STOP_RTC); +} + +static int tps6594_rtc_read_alarm(struct device *dev, struct rtc_wkalrm *alm) +{ + unsigned char alarm_data[NUM_TIME_ALARM_REGS]; + u32 int_val; + struct tps6594 *tps = dev_get_drvdata(dev->parent); + int ret; + + ret = regmap_bulk_read(tps->regmap, TPS6594_REG_ALARM_SECONDS, + alarm_data, NUM_TIME_ALARM_REGS); + if (ret < 0) + return ret; + + alm->time.tm_sec = bcd2bin(alarm_data[0]); + alm->time.tm_min = bcd2bin(alarm_data[1]); + alm->time.tm_hour = bcd2bin(alarm_data[2]); + alm->time.tm_mday = bcd2bin(alarm_data[3]); + alm->time.tm_mon = bcd2bin(alarm_data[4]) - 1; + alm->time.tm_year = bcd2bin(alarm_data[5]) + 100; + + ret = regmap_read(tps->regmap, TPS6594_REG_RTC_INTERRUPTS, &int_val); + if (ret < 0) + return ret; + + alm->enabled = int_val & TPS6594_BIT_IT_ALARM; + + return 0; +} + +static int tps6594_rtc_set_alarm(struct device *dev, struct rtc_wkalrm *alm) +{ + unsigned char alarm_data[NUM_TIME_ALARM_REGS]; + struct tps6594 *tps = dev_get_drvdata(dev->parent); + int ret; + + // Disable alarm irq before changing the alarm timestamp. + ret = tps6594_rtc_alarm_irq_enable(dev, 0); + if (ret) + return ret; + + alarm_data[0] = bin2bcd(alm->time.tm_sec); + alarm_data[1] = bin2bcd(alm->time.tm_min); + alarm_data[2] = bin2bcd(alm->time.tm_hour); + alarm_data[3] = bin2bcd(alm->time.tm_mday); + alarm_data[4] = bin2bcd(alm->time.tm_mon + 1); + alarm_data[5] = bin2bcd(alm->time.tm_year - 100); + + // Update all the alarm registers in one shot. + ret = regmap_bulk_write(tps->regmap, TPS6594_REG_ALARM_SECONDS, + alarm_data, NUM_TIME_ALARM_REGS); + if (ret < 0) + return ret; + + if (alm->enabled) + ret = tps6594_rtc_alarm_irq_enable(dev, 1); + + return ret; +} + +static int tps6594_rtc_set_calibration(struct device *dev, int calibration) +{ + struct tps6594 *tps = dev_get_drvdata(dev->parent); + __le16 value; + int ret; + + /* + * TPS6594 uses two's complement 16 bit value for compensation of RTC + * crystal inaccuracies. One time every hour when seconds counter + * increments from 0 to 1 compensation value will be added to internal + * RTC counter value. + * + * Valid range for compensation value: [-32767 .. 32767]. + */ + if (calibration < S16_MIN + 1 || calibration > S16_MAX) + return -ERANGE; + + value = cpu_to_le16(calibration); + + // Update all the compensation registers in one shot. + ret = regmap_bulk_write(tps->regmap, TPS6594_REG_RTC_COMP_LSB, &value, + sizeof(value)); + if (ret < 0) + return ret; + + // Enable automatic compensation. + return regmap_set_bits(tps->regmap, TPS6594_REG_RTC_CTRL_1, + TPS6594_BIT_AUTO_COMP); +} + +static int tps6594_rtc_get_calibration(struct device *dev, int *calibration) +{ + struct tps6594 *tps = dev_get_drvdata(dev->parent); + unsigned int ctrl; + __le16 value; + int ret; + + ret = regmap_read(tps->regmap, TPS6594_REG_RTC_CTRL_1, &ctrl); + if (ret < 0) + return ret; + + // If automatic compensation is not enabled report back zero. + if (!(ctrl & TPS6594_BIT_AUTO_COMP)) { + *calibration = 0; + return 0; + } + + ret = regmap_bulk_read(tps->regmap, TPS6594_REG_RTC_COMP_LSB, &value, + sizeof(value)); + if (ret < 0) + return ret; + + *calibration = le16_to_cpu(value); + + return 0; +} + +static int tps6594_rtc_read_offset(struct device *dev, long *offset) +{ + int calibration; + s64 tmp; + int ret; + + ret = tps6594_rtc_get_calibration(dev, &calibration); + if (ret < 0) + return ret; + + // Convert from RTC calibration register format to ppb format. + tmp = calibration * PPB_MULT; + + if (tmp < 0) + tmp -= TICKS_PER_HOUR / 2LL; + else + tmp += TICKS_PER_HOUR / 2LL; + tmp = div_s64(tmp, TICKS_PER_HOUR); + + /* + * SAFETY: + * Computatiion is the reverse operation of the one done in + * `tps6594_rtc_set_offset`. The safety remarks applie here too. + */ + + /* + * Offset value operates in negative way, so swap sign. + * See 8.3.10.5, (32768 - COMP_REG). + */ + *offset = (long)-tmp; + + return 0; +} + +static int tps6594_rtc_set_offset(struct device *dev, long offset) +{ + int calibration; + s64 tmp; + + // Make sure offset value is within supported range. + if (offset < MIN_OFFSET || offset > MAX_OFFSET) + return -ERANGE; + + // Convert from ppb format to RTC calibration register format + +// ... (5071 more chars) +``` diff --git a/tasks/csa159/pair_145933/task_prompt.md b/tasks/csa159/pair_145933/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..26f42022bbbfaca7c1a2dd031258b5cf734f9c78 --- /dev/null +++ b/tasks/csa159/pair_145933/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: `control_flow` + +### Current failure diagnosis + +- The syntactic type-and-parent pattern established only a potential overflow-before-widening shape; it did not prove that values admitted by the function's guard can reach the multiplication and exceed its computation type. +- Hard validation failed because the disappearing diagnostics were emitted at multiplication uses hundreds of lines from the changed macro definition, yielding zero function-or-precise-changed-span relevance. +- The observed reduction from four reports to two was insufficient evidence: duplicated translation-unit inputs and unrelated surviving or disappearing sites cannot substitute for a patch-relevant semantic match. +- Semantic and process results were unavailable because code verification failed and no score result was produced, so objective eligibility and refinement acceptance were not established. + +### Preserve from prior rollouts + +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Identify an integer multiplication whose result is subsequently converted or stored into a wider signed integer destination, while the multiplication itself would be evaluated in a narrower type under the relevant ILP32 C integer-conversion rules. +- Use the intraprocedural CFG to prove that a rejecting range check dominates the multiplication, that its rejecting successor exits before the sink, and that the continuation successor reaches the sink with a derivable interval for the runtime operand. +- Evaluate the constant scale factor and prove that at least one value admitted by the dominating guard produces a mathematical product outside the multiplication type's representable range before widening. +- For the patched form, prove that the long-long operand changes the usual arithmetic conversions and that every product in the guard-derived interval is representable in the resulting 64-bit computation type. +- Suppress a diagnostic when the guard-to-sink relation, admitted interval, arithmetic conversion, or concrete overflow witness cannot be established. + +### Implementation constraints + +- Use check::ASTCodeBody, or an equivalent body-level CSA callback exposing the AnalysisDeclContext CFG and BugReporter, so branch structure and the multiplication sink are analyzed together. +- Relate the guard block to the sink block with CFG reachability and dominance; recognize the out-of-range disjunction and early return without relying on textual adjacency. +- Keep interval derivation intraprocedural and CFG-based; ProgramState tracking and interprocedural propagation are unnecessary unless the required facts leave the containing function. +- Model integer constant expressions, signedness, widths, and usual arithmetic conversions explicitly for the ILP32 portability case rather than relying only on the analyzer host target's LP64 expression type. +- Use semantic AST entities and source-manager macro provenance across the project-general scale-before-widening pattern, without depending on a particular driver, function, macro, variable, literal, line, or commit. +- When the risky constant originates in a macro changed by the fix, place the primary diagnostic at its spelling definition span and attach the multiplication as the use-site range or note; otherwise report locally at the responsible operand or operation. +- Deduplicate findings by semantic sink and source origin so repeated presentation of the same translation unit does not inflate evidence. + +### Validation checklist + +- Compile the checker as a loadable shared object against the supplied Clang Static Analyzer API, load it by its registered name, and verify a clean analyzer invocation. +- Run identical official scans on the pre-patch and post-patch sources and compare deduplicated diagnostics rather than raw duplicated counts. +- Confirm that the pre-patch offset conversion produces a diagnostic whose primary location is within the changed TICKS_PER_HOUR definition span and whose associated use identifies the multiplication in tps6594_rtc_set_offset. +- Confirm that the corresponding diagnostic disappears after 3600 becomes 3600LL because the reachable product interval is representable in the multiplication type. +- Evaluate calibration * PPB_MULT consistently in both revisions: retain a report only if its own dominating calibration bounds and constant factor independently prove the same overflow semantics. +- Test rejecting guards, reversed comparisons, parenthesized conditions, non-dominating checks, narrower admitted ranges, and already-wide arithmetic to verify both positive and suppression behavior. +- Require hard-validation relevance to recognize the disappeared warning through the precise changed span, keep patched output below the acceptance threshold, and produce parseable verification and score artifacts. + +### Avoid and forbidden regressions + +- Do not treat a narrow multiplication followed by a wider cast as sufficient evidence without proving a reachable overflowing operand value. +- Do not use the magnitude-at-least-two and operand-width-at-least-32 heuristic as a substitute for representable-range arithmetic. +- Do not assume that long has the host target's width when the vulnerability is specifically exposed by ILP32 portability. +- Do not emit the only primary warning at a distant multiplication when the fix and validation relevance are localized to the macro operand's definition. +- Do not claim that every multiplication performed in long long is safe; safety must be shown for the guard-derived operand interval and constant factor. +- Do not accept a before/after count reduction alone as proof of correctness or patch relevance. diff --git a/tasks/csa159/pair_145957/checker_template.cpp b/tasks/csa159/pair_145957/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_145957/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_145957/config.json b/tasks/csa159/pair_145957/config.json new file mode 100644 index 0000000000000000000000000000000000000000..0f4b6573ac96eb7064dddeb847fcaabbbbf9e687 --- /dev/null +++ b/tasks/csa159/pair_145957/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "5765c7f6e3173eb894889a29963a497aeb721c5e", + "after_commit": "10685681bafce6febb39770f3387621bf5d67d0b", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/adc218676eef25575469234709c2d87185ca223a/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/adc218676eef25575469234709c2d87185ca223a/compile_commands.json", + "changed_files": [ + "net/sched/sch_sfq.c" + ], + "commit_message": "net_sched: sch_sfq: don't allow 1 packet limit\n\nThe current implementation does not work correctly with a limit of\n1. iproute2 actually checks for this and this patch adds the check in\nkernel as well.\n\nThis fixes the following syzkaller reported crash:\n\nUBSAN: array-index-out-of-bounds in net/sched/sch_sfq.c:210:6\nindex 65535 is out of range for type 'struct sfq_head[128]'\nCPU: 0 PID: 2569 Comm: syz-executor101 Not tainted 5.10.0-smp-DEV #1\nHardware name: Google Google Compute Engine/Google Compute Engine, BIOS Google 09/13/2024\nCall Trace:\n __dump_stack lib/dump_stack.c:79 [inline]\n dump_stack+0x125/0x19f lib/dump_stack.c:120\n ubsan_epilogue lib/ubsan.c:148 [inline]\n __ubsan_handle_out_of_bounds+0xed/0x120 lib/ubsan.c:347\n sfq_link net/sched/sch_sfq.c:210 [inline]\n sfq_dec+0x528/0x600 net/sched/sch_sfq.c:238\n sfq_dequeue+0x39b/0x9d0 net/sched/sch_sfq.c:500\n sfq_reset+0x13/0x50 net/sched/sch_sfq.c:525\n qdisc_reset+0xfe/0x510 net/sched/sch_generic.c:1026\n tbf_reset+0x3d/0x100 net/sched/sch_tbf.c:319\n qdisc_reset+0xfe/0x510 net/sched/sch_generic.c:1026\n dev_reset_queue+0x8c/0x140 net/sched/sch_generic.c:1296\n netdev_for_each_tx_queue include/linux/netdevice.h:2350 [inline]\n dev_deactivate_many+0x6dc/0xc20 net/sched/sch_generic.c:1362\n __dev_close_many+0x214/0x350 net/core/dev.c:1468\n dev_close_many+0x207/0x510 net/core/dev.c:1506\n unregister_netdevice_many+0x40f/0x16b0 net/core/dev.c:10738\n unregister_netdevice_queue+0x2be/0x310 net/core/dev.c:10695\n unregister_netdevice include/linux/netdevice.h:2893 [inline]\n __tun_detach+0x6b6/0x1600 drivers/net/tun.c:689\n tun_detach drivers/net/tun.c:705 [inline]\n tun_chr_close+0x104/0x1b0 drivers/net/tun.c:3640\n __fput+0x203/0x840 fs/file_table.c:280\n task_work_run+0x129/0x1b0 kernel/task_work.c:185\n exit_task_work include/linux/task_work.h:33 [inline]\n do_exit+0x5ce/0x2200 kernel/exit.c:931\n do_group_exit+0x144/0x310 kernel/exit.c:1046\n __do_sys_exit_group kernel/exit.c:1057 [inline]\n __se_sys_exit_group kernel/exit.c:1055 [inline]\n __x64_sys_exit_group+0x3b/0x40 kernel/exit.c:1055\n do_syscall_64+0x6c/0xd0\n entry_SYSCALL_64_after_hwframe+0x61/0xcb\nRIP: 0033:0x7fe5e7b52479\nCode: Unable to access opcode bytes at RIP 0x7fe5e7b5244f.\nRSP: 002b:00007ffd3c800398 EFLAGS: 00000246 ORIG_RAX: 00000000000000e7\nRAX: ffffffffffffffda RBX: 0000000000000000 RCX: 00007fe5e7b52479\nRDX: 000000000000003c RSI: 00000000000000e7 RDI: 0000000000000000\nRBP: 00007fe5e7bcd2d0 R08: ffffffffffffffb8 R09: 0000000000000014\nR10: 0000000000000000 R11: 0000000000000246 R12: 00007fe5e7bcd2d0\nR13: 0000000000000000 R14: 00007fe5e7bcdd20 R15: 00007fe5e7b24270\n\nThe crash can be also be reproduced with the following (with a tc\nrecompiled to allow for sfq limits of 1):\n\ntc qdisc add dev dummy0 handle 1: root tbf rate 1Kbit burst 100b lat 1s\n../iproute2-6.9.0/tc/tc qdisc add dev dummy0 handle 2: parent 1:10 sfq limit 1\nifconfig dummy0 up\nping -I dummy0 -f -c2 -W0.1 8.8.8.8\nsleep 1\n\nScenario that triggers the crash:\n\n* the first packet is sent and queued in TBF and SFQ; qdisc qlen is 1\n\n* TBF dequeues: it peeks from SFQ which moves the packet to the\n gso_skb list and keeps qdisc qlen set to 1. TBF is out of tokens so\n it schedules itself for later.\n\n* the second packet is sent and TBF tries to queues it to SFQ. qdisc\n qlen is now 2 and because the SFQ limit is 1 the packet is dropped\n by SFQ. At this point qlen is 1, and all of the SFQ slots are empty,\n however q->tail is not NULL.\n\nAt this point, assuming no more packets are queued, when sch_dequeue\nruns again it will decrement the qlen for the current empty slot\ncausing an underflow and the subsequent out of bounds access.\n\nReported-by: syzbot \nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nSigned-off-by: Octavian Purdila \nReviewed-by: Eric Dumazet \nLink: https://patch.msgid.link/20241204030520.2084663-2-tavip@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_145957/patch.diff b/tasks/csa159/pair_145957/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8e2ed00b1721c0e31515a7991b87f301cd59eaf3 --- /dev/null +++ b/tasks/csa159/pair_145957/patch.diff @@ -0,0 +1,15 @@ +diff --git a/net/sched/sch_sfq.c b/net/sched/sch_sfq.c +index a4b8296a2fa1..65d5b59da583 100644 +--- a/net/sched/sch_sfq.c ++++ b/net/sched/sch_sfq.c +@@ -652,6 +652,10 @@ static int sfq_change(struct Qdisc *sch, struct nlattr *opt, + if (!p) + return -ENOMEM; + } ++ if (ctl->limit == 1) { ++ NL_SET_ERR_MSG_MOD(extack, "invalid limit"); ++ return -EINVAL; ++ } + sch_tree_lock(sch); + if (ctl->quantum) + q->quantum = ctl->quantum; \ No newline at end of file diff --git a/tasks/csa159/pair_145957/post_functions.txt b/tasks/csa159/pair_145957/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..a854de92e7bf6242ee156c231d85a520d5eb47d2 --- /dev/null +++ b/tasks/csa159/pair_145957/post_functions.txt @@ -0,0 +1,87 @@ +### File: net/sched/sch_sfq.c +```c +static int sfq_change(struct Qdisc *sch, struct nlattr *opt, + struct netlink_ext_ack *extack) +{ + struct sfq_sched_data *q = qdisc_priv(sch); + struct tc_sfq_qopt *ctl = nla_data(opt); + struct tc_sfq_qopt_v1 *ctl_v1 = NULL; + unsigned int qlen, dropped = 0; + struct red_parms *p = NULL; + struct sk_buff *to_free = NULL; + struct sk_buff *tail = NULL; + + if (opt->nla_len < nla_attr_size(sizeof(*ctl))) + return -EINVAL; + if (opt->nla_len >= nla_attr_size(sizeof(*ctl_v1))) + ctl_v1 = nla_data(opt); + if (ctl->divisor && + (!is_power_of_2(ctl->divisor) || ctl->divisor > 65536)) + return -EINVAL; + + if ((int)ctl->quantum < 0) { + NL_SET_ERR_MSG_MOD(extack, "invalid quantum"); + return -EINVAL; + } + if (ctl_v1 && !red_check_params(ctl_v1->qth_min, ctl_v1->qth_max, + ctl_v1->Wlog, ctl_v1->Scell_log, NULL)) + return -EINVAL; + if (ctl_v1 && ctl_v1->qth_min) { + p = kmalloc(sizeof(*p), GFP_KERNEL); + if (!p) + return -ENOMEM; + } + if (ctl->limit == 1) { + NL_SET_ERR_MSG_MOD(extack, "invalid limit"); + return -EINVAL; + } + sch_tree_lock(sch); + if (ctl->quantum) + q->quantum = ctl->quantum; + WRITE_ONCE(q->perturb_period, ctl->perturb_period * HZ); + if (ctl->flows) + q->maxflows = min_t(u32, ctl->flows, SFQ_MAX_FLOWS); + if (ctl->divisor) { + q->divisor = ctl->divisor; + q->maxflows = min_t(u32, q->maxflows, q->divisor); + } + if (ctl_v1) { + if (ctl_v1->depth) + q->maxdepth = min_t(u32, ctl_v1->depth, SFQ_MAX_DEPTH); + if (p) { + swap(q->red_parms, p); + red_set_parms(q->red_parms, + ctl_v1->qth_min, ctl_v1->qth_max, + ctl_v1->Wlog, + ctl_v1->Plog, ctl_v1->Scell_log, + NULL, + ctl_v1->max_P); + } + q->flags = ctl_v1->flags; + q->headdrop = ctl_v1->headdrop; + } + if (ctl->limit) { + q->limit = min_t(u32, ctl->limit, q->maxdepth * q->maxflows); + q->maxflows = min_t(u32, q->maxflows, q->limit); + } + + qlen = sch->q.qlen; + while (sch->q.qlen > q->limit) { + dropped += sfq_drop(sch, &to_free); + if (!tail) + tail = to_free; + } + + rtnl_kfree_skbs(to_free, tail); + qdisc_tree_reduce_backlog(sch, qlen - sch->q.qlen, dropped); + + del_timer(&q->perturb_timer); + if (q->perturb_period) { + mod_timer(&q->perturb_timer, jiffies + q->perturb_period); + get_random_bytes(&q->perturbation, sizeof(q->perturbation)); + } + sch_tree_unlock(sch); + kfree(p); + return 0; +} +``` diff --git a/tasks/csa159/pair_145957/pre_functions.txt b/tasks/csa159/pair_145957/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..bfdf4f120ad9ef9d64563963fcb1f3889db8a85e --- /dev/null +++ b/tasks/csa159/pair_145957/pre_functions.txt @@ -0,0 +1,83 @@ +### File: net/sched/sch_sfq.c +```c +static int sfq_change(struct Qdisc *sch, struct nlattr *opt, + struct netlink_ext_ack *extack) +{ + struct sfq_sched_data *q = qdisc_priv(sch); + struct tc_sfq_qopt *ctl = nla_data(opt); + struct tc_sfq_qopt_v1 *ctl_v1 = NULL; + unsigned int qlen, dropped = 0; + struct red_parms *p = NULL; + struct sk_buff *to_free = NULL; + struct sk_buff *tail = NULL; + + if (opt->nla_len < nla_attr_size(sizeof(*ctl))) + return -EINVAL; + if (opt->nla_len >= nla_attr_size(sizeof(*ctl_v1))) + ctl_v1 = nla_data(opt); + if (ctl->divisor && + (!is_power_of_2(ctl->divisor) || ctl->divisor > 65536)) + return -EINVAL; + + if ((int)ctl->quantum < 0) { + NL_SET_ERR_MSG_MOD(extack, "invalid quantum"); + return -EINVAL; + } + if (ctl_v1 && !red_check_params(ctl_v1->qth_min, ctl_v1->qth_max, + ctl_v1->Wlog, ctl_v1->Scell_log, NULL)) + return -EINVAL; + if (ctl_v1 && ctl_v1->qth_min) { + p = kmalloc(sizeof(*p), GFP_KERNEL); + if (!p) + return -ENOMEM; + } + sch_tree_lock(sch); + if (ctl->quantum) + q->quantum = ctl->quantum; + WRITE_ONCE(q->perturb_period, ctl->perturb_period * HZ); + if (ctl->flows) + q->maxflows = min_t(u32, ctl->flows, SFQ_MAX_FLOWS); + if (ctl->divisor) { + q->divisor = ctl->divisor; + q->maxflows = min_t(u32, q->maxflows, q->divisor); + } + if (ctl_v1) { + if (ctl_v1->depth) + q->maxdepth = min_t(u32, ctl_v1->depth, SFQ_MAX_DEPTH); + if (p) { + swap(q->red_parms, p); + red_set_parms(q->red_parms, + ctl_v1->qth_min, ctl_v1->qth_max, + ctl_v1->Wlog, + ctl_v1->Plog, ctl_v1->Scell_log, + NULL, + ctl_v1->max_P); + } + q->flags = ctl_v1->flags; + q->headdrop = ctl_v1->headdrop; + } + if (ctl->limit) { + q->limit = min_t(u32, ctl->limit, q->maxdepth * q->maxflows); + q->maxflows = min_t(u32, q->maxflows, q->limit); + } + + qlen = sch->q.qlen; + while (sch->q.qlen > q->limit) { + dropped += sfq_drop(sch, &to_free); + if (!tail) + tail = to_free; + } + + rtnl_kfree_skbs(to_free, tail); + qdisc_tree_reduce_backlog(sch, qlen - sch->q.qlen, dropped); + + del_timer(&q->perturb_timer); + if (q->perturb_period) { + mod_timer(&q->perturb_timer, jiffies + q->perturb_period); + get_random_bytes(&q->perturbation, sizeof(q->perturbation)); + } + sch_tree_unlock(sch); + kfree(p); + return 0; +} +``` diff --git a/tasks/csa159/pair_145957/task_prompt.md b/tasks/csa159/pair_145957/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..ee1216e96bd09ebe6de58d93fc1cb0ad8e7d77d8 --- /dev/null +++ b/tasks/csa159/pair_145957/task_prompt.md @@ -0,0 +1,371 @@ +# 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 rollout produced successful build and differential scan results, but the semantic mechanism was judged inadequate because it reported a broad proxy: any feasible read of a field named `limit` in any `tc_*_qopt` record, without proving installation into the scheduler state or relation to the dangerous queue operation. +- Refinement was not accepted because semantic quality remained partial, and process evaluation detected patch-local hardcoding despite the reported scan success. +- The implementation used path-sensitive ProgramState reasoning even though the supplied semantic evaluation identified `syntax_only` as the minimum required level for this patch-local validation pattern. + +### 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. + +### Required semantic proof + +- Recognize the vulnerable relation as an integer queue-limit value read from a netlink qdisc option structure and consumed without a syntactically identifiable rejection of the degenerate value `1`. +- Distinguish the actual configuration value consumption from the validation comparison itself, so the rejecting comparison is not reported as an unsafe use. +- Tie the report to a syntactic configuration-to-consumption relation in the relevant qdisc update body rather than treating every field named `limit` in every option structure as vulnerable. +- Remain silent when the option value is syntactically checked against `1` before the configuration assignment or subsequent queue-limit use. + +### Implementation constraints + +- Use an AST-only CSA checker callback or equivalent AST body inspection; do not require ProgramState constraints, symbolic-value feasibility, interprocedural propagation, or modeling of heap round trips. +- Identify the option source and integer limit field through stable type and declaration structure, using the qdisc option convention and field semantics rather than names of patched functions, variables, files, line numbers, commits, or diagnostic strings. +- Require a syntactic relation between the option field and the scheduler-limit assignment or consumption, and reject unrelated reads, logging, comparisons, or benign qdisc fields. +- Keep diagnostics local to the unsafe configuration-use expression and exclude the comparison or branch that performs the minimum-value validation. +- Do not encode the original patch's exact source layout or use patch-local anchors as detection criteria. + +### Validation checklist + +- Rebuild the checker successfully and retain the existing compile and code-verification gates. +- Run the before scan and confirm diagnostics remain on the vulnerable configuration uses in `sfq_change`, with the expected vulnerable presence preserved. +- Run the after scan and confirm the newly added rejection causes all corresponding diagnostics to disappear, including no report on the validation guard itself. +- Verify every report is attached to the relevant limit consumption or assignment rather than the patch location, and retain the observed absence of warnings near changed lines. +- Exercise the refined scope against unrelated option fields and benign `limit` reads to confirm the checker does not report merely because a field has that name. +- Confirm the refinement evaluator accepts the semantic mechanism and that hardcoding-free, anchor-free, objective-gate, semantic-score, and process-score checks remain satisfied. + +### Avoid and forbidden regressions + +- Do not use broad `tc_*_qopt` plus `limit` feasibility as the complete vulnerability proof. +- Do not rely on path-sensitive `assume(value == 1)` checks when an AST relation can establish the required validation pattern. +- Do not claim that dominance, downstream `sfq_dec`, or interprocedural state propagation has been proven when the checker does not model it. +- Do not hardcode `sfq_change`, `ctl`, `q`, `extack`, source lines, commit identifiers, or patch-specific strings. +- Do not regress the successful before/after differential result, report sparsity, report locality, compilation, code verification, or G6 eligibility. diff --git a/tasks/csa159/pair_146000/checker_template.cpp b/tasks/csa159/pair_146000/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_146000/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_146000/config.json b/tasks/csa159/pair_146000/config.json new file mode 100644 index 0000000000000000000000000000000000000000..fb306a6788762ee94fc994f6cefe5769f1dcc04f --- /dev/null +++ b/tasks/csa159/pair_146000/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "3acea81be689b77b3ceac6ff345ff0366734d967", + "after_commit": "e5ca5d7b4d7c29246d957dc45d63610584ae3a54", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/40384c840ea1944d7c5a392e8975ed088ecf0b37/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/40384c840ea1944d7c5a392e8975ed088ecf0b37/compile_commands.json", + "changed_files": [ + "drivers/clk/mmp/clk-pxa1908-apbc.c" + ], + "commit_message": "clk: mmp: pxa1908-apbc: Fix NULL vs IS_ERR() check\n\nThe devm_kzalloc() function returns NULL on error, not error pointers.\nFix the check.\n\nFixes: 51ce55919273 (\"clk: mmp: Add Marvell PXA1908 APBC driver\")\nSigned-off-by: Dan Carpenter \nLink: https://lore.kernel.org/r/d7078eb7-a7d6-4753-b453-8fce15245c34@stanley.mountain\nAcked-by: Duje Mihanović \nSigned-off-by: Stephen Boyd ", + "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_146000/patch.diff b/tasks/csa159/pair_146000/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..949b1ef8c41bc58ec11db5d11c59f5650ea94587 --- /dev/null +++ b/tasks/csa159/pair_146000/patch.diff @@ -0,0 +1,15 @@ +diff --git a/drivers/clk/mmp/clk-pxa1908-apbc.c b/drivers/clk/mmp/clk-pxa1908-apbc.c +index b93d08466198..3fd7b5e644f3 100644 +--- a/drivers/clk/mmp/clk-pxa1908-apbc.c ++++ b/drivers/clk/mmp/clk-pxa1908-apbc.c +@@ -96,8 +96,8 @@ static int pxa1908_apbc_probe(struct platform_device *pdev) + struct pxa1908_clk_unit *pxa_unit; + + pxa_unit = devm_kzalloc(&pdev->dev, sizeof(*pxa_unit), GFP_KERNEL); +- if (IS_ERR(pxa_unit)) +- return PTR_ERR(pxa_unit); ++ if (!pxa_unit) ++ return -ENOMEM; + + pxa_unit->base = devm_platform_ioremap_resource(pdev, 0); + if (IS_ERR(pxa_unit->base)) \ No newline at end of file diff --git a/tasks/csa159/pair_146000/post_functions.txt b/tasks/csa159/pair_146000/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..9fbc7186f50c57ad7caf030f42801786f88e0455 --- /dev/null +++ b/tasks/csa159/pair_146000/post_functions.txt @@ -0,0 +1,21 @@ +### File: drivers/clk/mmp/clk-pxa1908-apbc.c +```c +static int pxa1908_apbc_probe(struct platform_device *pdev) +{ + struct pxa1908_clk_unit *pxa_unit; + + pxa_unit = devm_kzalloc(&pdev->dev, sizeof(*pxa_unit), GFP_KERNEL); + if (!pxa_unit) + return -ENOMEM; + + pxa_unit->base = devm_platform_ioremap_resource(pdev, 0); + if (IS_ERR(pxa_unit->base)) + return PTR_ERR(pxa_unit->base); + + mmp_clk_init(pdev->dev.of_node, &pxa_unit->unit, APBC_NR_CLKS); + + pxa1908_apb_periph_clk_init(pxa_unit); + + return 0; +} +``` diff --git a/tasks/csa159/pair_146000/pre_functions.txt b/tasks/csa159/pair_146000/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..58039d897f8634b2916399a90222454c23cfd821 --- /dev/null +++ b/tasks/csa159/pair_146000/pre_functions.txt @@ -0,0 +1,21 @@ +### File: drivers/clk/mmp/clk-pxa1908-apbc.c +```c +static int pxa1908_apbc_probe(struct platform_device *pdev) +{ + struct pxa1908_clk_unit *pxa_unit; + + pxa_unit = devm_kzalloc(&pdev->dev, sizeof(*pxa_unit), GFP_KERNEL); + if (IS_ERR(pxa_unit)) + return PTR_ERR(pxa_unit); + + pxa_unit->base = devm_platform_ioremap_resource(pdev, 0); + if (IS_ERR(pxa_unit->base)) + return PTR_ERR(pxa_unit->base); + + mmp_clk_init(pdev->dev.of_node, &pxa_unit->unit, APBC_NR_CLKS); + + pxa1908_apb_periph_clk_init(pxa_unit); + + return 0; +} +``` diff --git a/tasks/csa159/pair_146000/task_prompt.md b/tasks/csa159/pair_146000/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..22bc443a760f576755670d58d61732e3ebbd6f2c --- /dev/null +++ b/tasks/csa159/pair_146000/task_prompt.md @@ -0,0 +1,378 @@ +# 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 used function-wide AST set intersection, so it did not prove ordering or CFG reachability from the allocator assignment through the ineffective IS_ERR guard to a later dereference. +- Allocator origin was never killed on reassignment, allowing the check and dereference to refer to a different runtime value than the NULL-returning allocation result. +- The analysis could report dereferences before the check, on mutually exclusive or unreachable paths, or after an independent NULL guard had made the dereference safe. +- Patch-local material in the implementation triggered hardcoding detection despite the intended project-general API pattern. +- Although the observed before/after differential was correct, semantic adequacy and process quality remained below threshold because the reported vulnerability path was not established. + +### 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. +- Remain independent of patch anchors such as changed line numbers, the affected file path, function name, variable name, and affected structure type. + +### Required semantic proof + +- Establish that a pointer value originates from a known NULL-on-failure allocation call and that the same unreassigned value reaches an IS_ERR check. +- Establish that the NULL outcome is not rejected by the IS_ERR-based branch and can continue along a reachable CFG path. +- Establish that the same value reaches a subsequent pointer dereference on that continuation path. +- Suppress the report when every path to the dereference is blocked by a real NULL check, including !V, V == NULL, or an equivalent IS_ERR_OR_NULL guard. +- Do not treat values from ERR_PTR-returning APIs such as devm_platform_ioremap_resource as NULL-allocation sources. + +### Implementation constraints + +- Use a function-local CSA control-flow analysis based on the function CFG, with explicit source, guard, reassignment-kill, and dereference relationships; a whole-body unordered AST collection is insufficient. +- Use appropriate statement or call callbacks to identify NULL-returning allocator results, IS_ERR uses, assignments, NULL guards, and dereference sinks, then consult CFG ordering and reachability before reporting. +- Track value identity across declaration initialization and ordinary assignment, and invalidate the allocator-origin fact when the tracked variable is overwritten before the guard or sink. +- Recognize arrow member access, unary dereference, and array subscript as sinks while preserving the distinction between a variable and a member value such as pxa_unit->base. +- Emit one diagnostic at the ineffective IS_ERR guard, with the allocator origin and reachable dereference used as supporting evidence rather than independent reports. +- Keep scope project-general and derive behavior from stable API semantics; do not match repository paths, patched function names, local identifiers, source lines, CVE text, or diff content. +- No interprocedural propagation is required by the supplied function-local evidence. + +### Validation checklist + +- Compile the fresh checker successfully and verify registration and report emission through the intended CSA interfaces. +- Scan the vulnerable source and confirm a diagnostic for the devm_kzalloc result checked with IS_ERR before its reachable dereference. +- Scan the patched source and confirm no diagnostic when the allocation result is guarded by !pxa_unit. +- Confirm the diagnostic location is the erroneous IS_ERR guard and remains within the patched function with near-zero patch distance. +- Confirm the valid IS_ERR check on the devm_platform_ioremap_resource result is not reported. +- Add focused cases for dereference before the bad check, unreachable or mutually exclusive dereference, reassignment before the sink, and an intervening dominating NULL guard; all must remain clean. +- Add positive CFG variants using declaration initialization or assignment and each supported dereference form. +- Repeat code verification and refinement, requiring the established before/after differential and an accepted or clean refinement result. + +### Avoid and forbidden regressions + +- Do not repeat function-wide membership tests that ignore statement order, reachability, branch direction, or reassignment. +- Do not infer vulnerability merely from the coexistence of a NULL-returning allocator call, IS_ERR call, and dereference in one function. +- Do not classify all allocation-like or mapping APIs as NULL-returning; ERR_PTR-returning APIs are a required negative case. +- Do not use disappearance on the patched revision as a substitute for proving the vulnerable execution relation. +- Do not introduce patch-local hardcoding in matching logic, comments, diagnostic conditions, or scope filters. +- Do not broaden the report to harmless IS_ERR misuse where no reachable dereference of the unchecked NULL value exists. diff --git a/tasks/csa159/pair_146389/checker_template.cpp b/tasks/csa159/pair_146389/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_146389/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_146389/config.json b/tasks/csa159/pair_146389/config.json new file mode 100644 index 0000000000000000000000000000000000000000..3e9abcf815fb8c7dda4f9855105f0eb3e2db7bad --- /dev/null +++ b/tasks/csa159/pair_146389/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "77b2ab31fc65c595ca0a339f6c5b8ef3adfae5c6", + "after_commit": "62531a1effa87bdab12d5104015af72e60d926ff", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/7eb172143d5508b4da468ed59ee857c6e5e01da6/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/7eb172143d5508b4da468ed59ee857c6e5e01da6/compile_commands.json", + "changed_files": [ + "net/switchdev/switchdev.c" + ], + "commit_message": "net: switchdev: Convert blocking notification chain to a raw one\n\nA blocking notification chain uses a read-write semaphore to protect the\nintegrity of the chain. The semaphore is acquired for writing when\nadding / removing notifiers to / from the chain and acquired for reading\nwhen traversing the chain and informing notifiers about an event.\n\nIn case of the blocking switchdev notification chain, recursive\nnotifications are possible which leads to the semaphore being acquired\ntwice for reading and to lockdep warnings being generated [1].\n\nSpecifically, this can happen when the bridge driver processes a\nSWITCHDEV_BRPORT_UNOFFLOADED event which causes it to emit notifications\nabout deferred events when calling switchdev_deferred_process().\n\nFix this by converting the notification chain to a raw notification\nchain in a similar fashion to the netdev notification chain. Protect\nthe chain using the RTNL mutex by acquiring it when modifying the chain.\nEvents are always informed under the RTNL mutex, but add an assertion in\ncall_switchdev_blocking_notifiers() to make sure this is not violated in\nthe future.\n\nMaintain the \"blocking\" prefix as events are always emitted from process\ncontext and listeners are allowed to block.\n\n[1]:\nWARNING: possible recursive locking detected\n6.14.0-rc4-custom-g079270089484 #1 Not tainted\n--------------------------------------------\nip/52731 is trying to acquire lock:\nffffffff850918d8 ((switchdev_blocking_notif_chain).rwsem){++++}-{4:4}, at: blocking_notifier_call_chain+0x58/0xa0\n\nbut task is already holding lock:\nffffffff850918d8 ((switchdev_blocking_notif_chain).rwsem){++++}-{4:4}, at: blocking_notifier_call_chain+0x58/0xa0\n\nother info that might help us debug this:\nPossible unsafe locking scenario:\nCPU0\n----\nlock((switchdev_blocking_notif_chain).rwsem);\nlock((switchdev_blocking_notif_chain).rwsem);\n\n*** DEADLOCK ***\nMay be due to missing lock nesting notation\n3 locks held by ip/52731:\n #0: ffffffff84f795b0 (rtnl_mutex){+.+.}-{4:4}, at: rtnl_newlink+0x727/0x1dc0\n #1: ffffffff8731f628 (&net->rtnl_mutex){+.+.}-{4:4}, at: rtnl_newlink+0x790/0x1dc0\n #2: ffffffff850918d8 ((switchdev_blocking_notif_chain).rwsem){++++}-{4:4}, at: blocking_notifier_call_chain+0x58/0xa0\n\nstack backtrace:\n...\n? __pfx_down_read+0x10/0x10\n? __pfx_mark_lock+0x10/0x10\n? __pfx_switchdev_port_attr_set_deferred+0x10/0x10\nblocking_notifier_call_chain+0x58/0xa0\nswitchdev_port_attr_notify.constprop.0+0xb3/0x1b0\n? __pfx_switchdev_port_attr_notify.constprop.0+0x10/0x10\n? mark_held_locks+0x94/0xe0\n? switchdev_deferred_process+0x11a/0x340\nswitchdev_port_attr_set_deferred+0x27/0xd0\nswitchdev_deferred_process+0x164/0x340\nbr_switchdev_port_unoffload+0xc8/0x100 [bridge]\nbr_switchdev_blocking_event+0x29f/0x580 [bridge]\nnotifier_call_chain+0xa2/0x440\nblocking_notifier_call_chain+0x6e/0xa0\nswitchdev_bridge_port_unoffload+0xde/0x1a0\n...\n\nFixes: f7a70d650b0b6 (\"net: bridge: switchdev: Ensure deferred event delivery on unoffload\")\nSigned-off-by: Amit Cohen \nReviewed-by: Ido Schimmel \nReviewed-by: Simon Horman \nReviewed-by: Vladimir Oltean \nTested-by: Vladimir Oltean \nLink: https://patch.msgid.link/20250305121509.631207-1-amcohen@nvidia.com\nSigned-off-by: Paolo Abeni ", + "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_146389/patch.diff b/tasks/csa159/pair_146389/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1aea936c648506e41acfb69725a7b7a4a2045b98 --- /dev/null +++ b/tasks/csa159/pair_146389/patch.diff @@ -0,0 +1,58 @@ +diff --git a/net/switchdev/switchdev.c b/net/switchdev/switchdev.c +index 6488ead9e464..4d5fbacef496 100644 +--- a/net/switchdev/switchdev.c ++++ b/net/switchdev/switchdev.c +@@ -472,7 +472,7 @@ bool switchdev_port_obj_act_is_deferred(struct net_device *dev, + EXPORT_SYMBOL_GPL(switchdev_port_obj_act_is_deferred); + + static ATOMIC_NOTIFIER_HEAD(switchdev_notif_chain); +-static BLOCKING_NOTIFIER_HEAD(switchdev_blocking_notif_chain); ++static RAW_NOTIFIER_HEAD(switchdev_blocking_notif_chain); + + /** + * register_switchdev_notifier - Register notifier +@@ -518,17 +518,27 @@ EXPORT_SYMBOL_GPL(call_switchdev_notifiers); + + int register_switchdev_blocking_notifier(struct notifier_block *nb) + { +- struct blocking_notifier_head *chain = &switchdev_blocking_notif_chain; ++ struct raw_notifier_head *chain = &switchdev_blocking_notif_chain; ++ int err; ++ ++ rtnl_lock(); ++ err = raw_notifier_chain_register(chain, nb); ++ rtnl_unlock(); + +- return blocking_notifier_chain_register(chain, nb); ++ return err; + } + EXPORT_SYMBOL_GPL(register_switchdev_blocking_notifier); + + int unregister_switchdev_blocking_notifier(struct notifier_block *nb) + { +- struct blocking_notifier_head *chain = &switchdev_blocking_notif_chain; ++ struct raw_notifier_head *chain = &switchdev_blocking_notif_chain; ++ int err; + +- return blocking_notifier_chain_unregister(chain, nb); ++ rtnl_lock(); ++ err = raw_notifier_chain_unregister(chain, nb); ++ rtnl_unlock(); ++ ++ return err; + } + EXPORT_SYMBOL_GPL(unregister_switchdev_blocking_notifier); + +@@ -536,10 +546,11 @@ int call_switchdev_blocking_notifiers(unsigned long val, struct net_device *dev, + struct switchdev_notifier_info *info, + struct netlink_ext_ack *extack) + { ++ ASSERT_RTNL(); + info->dev = dev; + info->extack = extack; +- return blocking_notifier_call_chain(&switchdev_blocking_notif_chain, +- val, info); ++ return raw_notifier_call_chain(&switchdev_blocking_notif_chain, ++ val, info); + } + EXPORT_SYMBOL_GPL(call_switchdev_blocking_notifiers); \ No newline at end of file diff --git a/tasks/csa159/pair_146389/post_functions.txt b/tasks/csa159/pair_146389/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..743ad292f34301366ac23e6f7814ec98c6d435b3 --- /dev/null +++ b/tasks/csa159/pair_146389/post_functions.txt @@ -0,0 +1,77 @@ +### File: net/switchdev/switchdev.c +```c +bool switchdev_port_obj_act_is_deferred(struct net_device *dev, + enum switchdev_notifier_type nt, + const struct switchdev_obj *obj) +{ + struct switchdev_deferred_item *dfitem; + bool found = false; + + ASSERT_RTNL(); + + spin_lock_bh(&deferred_lock); + + list_for_each_entry(dfitem, &deferred, list) { + if (dfitem->dev != dev) + continue; + + if ((dfitem->func == switchdev_port_obj_add_deferred && + nt == SWITCHDEV_PORT_OBJ_ADD) || + (dfitem->func == switchdev_port_obj_del_deferred && + nt == SWITCHDEV_PORT_OBJ_DEL)) { + if (switchdev_obj_eq((const void *)dfitem->data, obj)) { + found = true; + break; + } + } + } + + spin_unlock_bh(&deferred_lock); + + return found; +} + +int call_switchdev_notifiers(unsigned long val, struct net_device *dev, + struct switchdev_notifier_info *info, + struct netlink_ext_ack *extack) +{ + info->dev = dev; + info->extack = extack; + return atomic_notifier_call_chain(&switchdev_notif_chain, val, info); +} + +int register_switchdev_blocking_notifier(struct notifier_block *nb) +{ + struct raw_notifier_head *chain = &switchdev_blocking_notif_chain; + int err; + + rtnl_lock(); + err = raw_notifier_chain_register(chain, nb); + rtnl_unlock(); + + return err; +} + +int unregister_switchdev_blocking_notifier(struct notifier_block *nb) +{ + struct raw_notifier_head *chain = &switchdev_blocking_notif_chain; + int err; + + rtnl_lock(); + err = raw_notifier_chain_unregister(chain, nb); + rtnl_unlock(); + + return err; +} + +int call_switchdev_blocking_notifiers(unsigned long val, struct net_device *dev, + struct switchdev_notifier_info *info, + struct netlink_ext_ack *extack) +{ + ASSERT_RTNL(); + info->dev = dev; + info->extack = extack; + return raw_notifier_call_chain(&switchdev_blocking_notif_chain, + val, info); +} +``` diff --git a/tasks/csa159/pair_146389/pre_functions.txt b/tasks/csa159/pair_146389/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..6cb7f68611ef6e45c9e19fe3f6f51e40c8af5cea --- /dev/null +++ b/tasks/csa159/pair_146389/pre_functions.txt @@ -0,0 +1,66 @@ +### File: net/switchdev/switchdev.c +```c +bool switchdev_port_obj_act_is_deferred(struct net_device *dev, + enum switchdev_notifier_type nt, + const struct switchdev_obj *obj) +{ + struct switchdev_deferred_item *dfitem; + bool found = false; + + ASSERT_RTNL(); + + spin_lock_bh(&deferred_lock); + + list_for_each_entry(dfitem, &deferred, list) { + if (dfitem->dev != dev) + continue; + + if ((dfitem->func == switchdev_port_obj_add_deferred && + nt == SWITCHDEV_PORT_OBJ_ADD) || + (dfitem->func == switchdev_port_obj_del_deferred && + nt == SWITCHDEV_PORT_OBJ_DEL)) { + if (switchdev_obj_eq((const void *)dfitem->data, obj)) { + found = true; + break; + } + } + } + + spin_unlock_bh(&deferred_lock); + + return found; +} + +int call_switchdev_notifiers(unsigned long val, struct net_device *dev, + struct switchdev_notifier_info *info, + struct netlink_ext_ack *extack) +{ + info->dev = dev; + info->extack = extack; + return atomic_notifier_call_chain(&switchdev_notif_chain, val, info); +} + +int register_switchdev_blocking_notifier(struct notifier_block *nb) +{ + struct blocking_notifier_head *chain = &switchdev_blocking_notif_chain; + + return blocking_notifier_chain_register(chain, nb); +} + +int unregister_switchdev_blocking_notifier(struct notifier_block *nb) +{ + struct blocking_notifier_head *chain = &switchdev_blocking_notif_chain; + + return blocking_notifier_chain_unregister(chain, nb); +} + +int call_switchdev_blocking_notifiers(unsigned long val, struct net_device *dev, + struct switchdev_notifier_info *info, + struct netlink_ext_ack *extack) +{ + info->dev = dev; + info->extack = extack; + return blocking_notifier_call_chain(&switchdev_blocking_notif_chain, + val, info); +} +``` diff --git a/tasks/csa159/pair_146389/task_prompt.md b/tasks/csa159/pair_146389/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..8b7ee57c16db49098fcff6dc188f1c1f1f17a761 --- /dev/null +++ b/tasks/csa159/pair_146389/task_prompt.md @@ -0,0 +1,375 @@ +# 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 rollout used a check::PreCall syntactic call-name match and emitted a warning immediately, so it proved only that a blocking notifier API was used. +- It did not establish that a notifier callback re-enters the same chain, that the re-entry occurs on the same execution path and thread, or that the chain's non-recursive rwsem is already held. +- The semantic evaluation therefore classified the result as partial: it detected a risk-indicating API pattern but not the recursive-lock self-deadlock condition, leaving semantic_mechanism and semantic_score failed. + +### 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 process quality at or above the configured threshold. +- Do not introduce patch-anchor dependence. +- Do not introduce patch-local hardcoding. + +### Required semantic proof + +- Prove that a blocking notifier-chain traversal acquires or holds its non-recursive internal rwsem on a path that invokes a notifier callback. +- Prove that the callback path reaches a blocking notifier operation on the same notifier-chain object before the first acquisition is released. +- Require the recursive re-entry to be attributable to the same thread and execution path, rather than treating any two independent blocking-notifier calls as recursion. +- Treat raw and atomic notifier variants as safe with respect to this per-chain rwsem condition, while not claiming safety merely because a call has a different name. +- Distinguish the actual recursive call-chain hazard from registration or unregistration uses that do not have evidence of callback re-entry. + +### Implementation constraints + +- Use interprocedural CSA analysis with call-entry and call-return handling, or equivalent callbacks, to carry notifier-chain and lock facts through callback dispatch and nested function calls. +- Maintain path-sensitive ProgramState facts for the specific chain object, including an active blocking traversal, the associated rwsem ownership, and callback re-entry depth; invalidate or pop them on the matching return. +- Model notifier callback registration and dispatch sufficiently to connect a callback invocation with the chain whose traversal is active, including indirect notifier callback edges when available. +- Emit the diagnostic at the recursive blocking re-entry operation and provide path evidence leading through the original traversal and callback invocation, rather than reporting at every blocking API call. +- Keep applicability project-general for Linux notifier-chain semantics and avoid dependence on switchdev symbols, file paths, changed-line anchors, or patch-specific identifiers. +- Do not report when the analysis cannot establish the same-chain recursive relation; an API-use heuristic is insufficient. + +### Validation checklist + +- Compile the new checker and perform code verification without introducing build or registration errors. +- Scan the pre-patch source and confirm diagnostics occur for the demonstrated recursive blocking-notifier scenario, with the relevant call-chain relation represented in the diagnostic path. +- Scan the patched source and confirm the raw notifier calls protected by RTNL and the ASSERT_RTNL condition do not produce the recursive-rwsem diagnostic. +- Verify report locality at the recursive re-entry site or its precise blocking acquisition, not merely at unrelated notifier registration sites. +- Exercise relevant non-recursive blocking-notifier uses and confirm they are not reported solely because they belong to the blocking API family. +- Exercise raw and atomic notifier operations and confirm they remain excluded without relying on source-text or patch-position matching. +- Run the accepted refinement and objective checks, confirming G6 eligibility, before/after differential behavior, scope sparsity, and the configured process threshold. + +### Avoid and forbidden regressions + +- Do not emit a finding solely from a blocking_notifier_* callee name or declaration match. +- Do not infer recursive locking from the existence of a notifier callback without proving that it re-enters the same chain while the first traversal remains active. +- Do not report all blocking registration, unregistration, or notification operations as equivalent deadlock sites. +- Do not replace the missing interprocedural proof with patch-specific switchdev names, changed-line locations, or assumptions about the known diff. +- Do not suppress findings by matching only the patched raw API spelling; suppression must follow the modeled absence of the blocking rwsem relation. diff --git a/tasks/csa159/pair_147034/checker_template.cpp b/tasks/csa159/pair_147034/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_147034/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_147034/config.json b/tasks/csa159/pair_147034/config.json new file mode 100644 index 0000000000000000000000000000000000000000..3aa77b4b4beb497c8ef061644cba1be31a958f3f --- /dev/null +++ b/tasks/csa159/pair_147034/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "5bc68bd3826e573f9a83c82c5107536cf616fea8", + "after_commit": "f83ac8d30c43fd902af7c84c480f216157b60ef0", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/29d69273fefd0bc2a66b5e22f3a4a4c7a53bfa02/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/29d69273fefd0bc2a66b5e22f3a4a4c7a53bfa02/compile_commands.json", + "changed_files": [ + "drivers/media/test-drivers/vivid/vivid-vid-cap.c" + ], + "commit_message": "media: vivid: Change the siize of the composing\n\nsyzkaller found a bug:\n\nBUG: KASAN: vmalloc-out-of-bounds in tpg_fill_plane_pattern drivers/media/common/v4l2-tpg/v4l2-tpg-core.c:2608 [inline]\nBUG: KASAN: vmalloc-out-of-bounds in tpg_fill_plane_buffer+0x1a9c/0x5af0 drivers/media/common/v4l2-tpg/v4l2-tpg-core.c:2705\nWrite of size 1440 at addr ffffc9000d0ffda0 by task vivid-000-vid-c/5304\n\nCPU: 0 UID: 0 PID: 5304 Comm: vivid-000-vid-c Not tainted 6.14.0-rc2-syzkaller-00039-g09fbf3d50205 #0\nHardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2~bpo12+1 04/01/2014\n\nCall Trace:\n \n __dump_stack lib/dump_stack.c:94 [inline]\n dump_stack_lvl+0x241/0x360 lib/dump_stack.c:120\n print_address_description mm/kasan/report.c:378 [inline]\n print_report+0x169/0x550 mm/kasan/report.c:489\n kasan_report+0x143/0x180 mm/kasan/report.c:602\n kasan_check_range+0x282/0x290 mm/kasan/generic.c:189\n __asan_memcpy+0x40/0x70 mm/kasan/shadow.c:106\n tpg_fill_plane_pattern drivers/media/common/v4l2-tpg/v4l2-tpg-core.c:2608 [inline]\n tpg_fill_plane_buffer+0x1a9c/0x5af0 drivers/media/common/v4l2-tpg/v4l2-tpg-core.c:2705\n vivid_fillbuff drivers/media/test-drivers/vivid/vivid-kthread-cap.c:470 [inline]\n vivid_thread_vid_cap_tick+0xf8e/0x60d0 drivers/media/test-drivers/vivid/vivid-kthread-cap.c:629\n vivid_thread_vid_cap+0x8aa/0xf30 drivers/media/test-drivers/vivid/vivid-kthread-cap.c:767\n kthread+0x7a9/0x920 kernel/kthread.c:464\n ret_from_fork+0x4b/0x80 arch/x86/kernel/process.c:148\n ret_from_fork_asm+0x1a/0x30 arch/x86/entry/entry_64.S:244\n \n\nThe composition size cannot be larger than the size of fmt_cap_rect.\nSo execute v4l2_rect_map_inside() even if has_compose_cap == 0.\n\nFixes: 94a7ad928346 (\"media: vivid: fix compose size exceed boundary\")\nCc: stable@vger.kernel.org\nReported-by: syzbot+365005005522b70a36f2@syzkaller.appspotmail.com\nCloses: https://syzkaller.appspot.com/bug?id=8ed8e8cc30cbe0d86c9a25bd1d6a5775129b8ea3\nSigned-off-by: Denis Arefev \nSigned-off-by: Hans Verkuil ", + "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_147034/patch.diff b/tasks/csa159/pair_147034/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1843df6f5580f28fed8882b2fe9132e6d92371d3 --- /dev/null +++ b/tasks/csa159/pair_147034/patch.diff @@ -0,0 +1,14 @@ +diff --git a/drivers/media/test-drivers/vivid/vivid-vid-cap.c b/drivers/media/test-drivers/vivid/vivid-vid-cap.c +index df726961222b..84e9155b5815 100644 +--- a/drivers/media/test-drivers/vivid/vivid-vid-cap.c ++++ b/drivers/media/test-drivers/vivid/vivid-vid-cap.c +@@ -948,8 +948,8 @@ int vivid_vid_cap_s_selection(struct file *file, void *fh, struct v4l2_selection + if (dev->has_compose_cap) { + v4l2_rect_set_min_size(compose, &min_rect); + v4l2_rect_set_max_size(compose, &max_rect); +- v4l2_rect_map_inside(compose, &fmt); + } ++ v4l2_rect_map_inside(compose, &fmt); + dev->fmt_cap_rect = fmt; + tpg_s_buf_height(&dev->tpg, fmt.height); + } else if (dev->has_compose_cap) { \ No newline at end of file diff --git a/tasks/csa159/pair_147034/post_functions.txt b/tasks/csa159/pair_147034/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..93ec1f102c2184f0ea185764c26aaeb429515399 --- /dev/null +++ b/tasks/csa159/pair_147034/post_functions.txt @@ -0,0 +1,134 @@ +### File: drivers/media/test-drivers/vivid/vivid-vid-cap.c +```c +int vivid_vid_cap_s_selection(struct file *file, void *fh, struct v4l2_selection *s) +{ + struct vivid_dev *dev = video_drvdata(file); + struct v4l2_rect *crop = &dev->crop_cap; + struct v4l2_rect *compose = &dev->compose_cap; + unsigned factor = V4L2_FIELD_HAS_T_OR_B(dev->field_cap) ? 2 : 1; + int ret; + + if (!dev->has_crop_cap && !dev->has_compose_cap) + return -ENOTTY; + if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) + return -EINVAL; + if (vivid_is_webcam(dev)) + return -ENODATA; + + switch (s->target) { + case V4L2_SEL_TGT_CROP: + if (!dev->has_crop_cap) + return -EINVAL; + ret = vivid_vid_adjust_sel(s->flags, &s->r); + if (ret) + return ret; + v4l2_rect_set_min_size(&s->r, &vivid_min_rect); + v4l2_rect_set_max_size(&s->r, &dev->src_rect); + v4l2_rect_map_inside(&s->r, &dev->crop_bounds_cap); + s->r.top /= factor; + s->r.height /= factor; + if (dev->has_scaler_cap) { + struct v4l2_rect fmt = dev->fmt_cap_rect; + struct v4l2_rect max_rect = { + 0, 0, + s->r.width * MAX_ZOOM, + s->r.height * MAX_ZOOM + }; + struct v4l2_rect min_rect = { + 0, 0, + s->r.width / MAX_ZOOM, + s->r.height / MAX_ZOOM + }; + + v4l2_rect_set_min_size(&fmt, &min_rect); + if (!dev->has_compose_cap) + v4l2_rect_set_max_size(&fmt, &max_rect); + if (!v4l2_rect_same_size(&dev->fmt_cap_rect, &fmt) && + vb2_is_busy(&dev->vb_vid_cap_q)) + return -EBUSY; + if (dev->has_compose_cap) { + v4l2_rect_set_min_size(compose, &min_rect); + v4l2_rect_set_max_size(compose, &max_rect); + } + v4l2_rect_map_inside(compose, &fmt); + dev->fmt_cap_rect = fmt; + tpg_s_buf_height(&dev->tpg, fmt.height); + } else if (dev->has_compose_cap) { + struct v4l2_rect fmt = dev->fmt_cap_rect; + + v4l2_rect_set_min_size(&fmt, &s->r); + if (!v4l2_rect_same_size(&dev->fmt_cap_rect, &fmt) && + vb2_is_busy(&dev->vb_vid_cap_q)) + return -EBUSY; + dev->fmt_cap_rect = fmt; + tpg_s_buf_height(&dev->tpg, fmt.height); + v4l2_rect_set_size_to(compose, &s->r); + v4l2_rect_map_inside(compose, &dev->fmt_cap_rect); + } else { + if (!v4l2_rect_same_size(&s->r, &dev->fmt_cap_rect) && + vb2_is_busy(&dev->vb_vid_cap_q)) + return -EBUSY; + v4l2_rect_set_size_to(&dev->fmt_cap_rect, &s->r); + v4l2_rect_set_size_to(compose, &s->r); + v4l2_rect_map_inside(compose, &dev->fmt_cap_rect); + tpg_s_buf_height(&dev->tpg, dev->fmt_cap_rect.height); + } + s->r.top *= factor; + s->r.height *= factor; + *crop = s->r; + break; + case V4L2_SEL_TGT_COMPOSE: + if (!dev->has_compose_cap) + return -EINVAL; + ret = vivid_vid_adjust_sel(s->flags, &s->r); + if (ret) + return ret; + v4l2_rect_set_min_size(&s->r, &vivid_min_rect); + v4l2_rect_set_max_size(&s->r, &dev->fmt_cap_rect); + if (dev->has_scaler_cap) { + struct v4l2_rect max_rect = { + 0, 0, + dev->src_rect.width * MAX_ZOOM, + (dev->src_rect.height / factor) * MAX_ZOOM + }; + + v4l2_rect_set_max_size(&s->r, &max_rect); + if (dev->has_crop_cap) { + struct v4l2_rect min_rect = { + 0, 0, + s->r.width / MAX_ZOOM, + (s->r.height * factor) / MAX_ZOOM + }; + struct v4l2_rect max_rect = { + 0, 0, + s->r.width * MAX_ZOOM, + (s->r.height * factor) * MAX_ZOOM + }; + + v4l2_rect_set_min_size(crop, &min_rect); + v4l2_rect_set_max_size(crop, &max_rect); + v4l2_rect_map_inside(crop, &dev->crop_bounds_cap); + } + } else if (dev->has_crop_cap) { + s->r.top *= factor; + s->r.height *= factor; + v4l2_rect_set_max_size(&s->r, &dev->src_rect); + v4l2_rect_set_size_to(crop, &s->r); + v4l2_rect_map_inside(crop, &dev->crop_bounds_cap); + s->r.top /= factor; + s->r.height /= factor; + } else { + v4l2_rect_set_size_to(&s->r, &dev->src_rect); + s->r.height /= factor; + } + v4l2_rect_map_inside(&s->r, &dev->fmt_cap_rect); + *compose = s->r; + break; + default: + return -EINVAL; + } + + tpg_s_crop_compose(&dev->tpg, crop, compose); + return 0; +} +``` diff --git a/tasks/csa159/pair_147034/pre_functions.txt b/tasks/csa159/pair_147034/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..1a5d4a85f95408a711255ae87dd72207bd45227c --- /dev/null +++ b/tasks/csa159/pair_147034/pre_functions.txt @@ -0,0 +1,134 @@ +### File: drivers/media/test-drivers/vivid/vivid-vid-cap.c +```c +int vivid_vid_cap_s_selection(struct file *file, void *fh, struct v4l2_selection *s) +{ + struct vivid_dev *dev = video_drvdata(file); + struct v4l2_rect *crop = &dev->crop_cap; + struct v4l2_rect *compose = &dev->compose_cap; + unsigned factor = V4L2_FIELD_HAS_T_OR_B(dev->field_cap) ? 2 : 1; + int ret; + + if (!dev->has_crop_cap && !dev->has_compose_cap) + return -ENOTTY; + if (s->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) + return -EINVAL; + if (vivid_is_webcam(dev)) + return -ENODATA; + + switch (s->target) { + case V4L2_SEL_TGT_CROP: + if (!dev->has_crop_cap) + return -EINVAL; + ret = vivid_vid_adjust_sel(s->flags, &s->r); + if (ret) + return ret; + v4l2_rect_set_min_size(&s->r, &vivid_min_rect); + v4l2_rect_set_max_size(&s->r, &dev->src_rect); + v4l2_rect_map_inside(&s->r, &dev->crop_bounds_cap); + s->r.top /= factor; + s->r.height /= factor; + if (dev->has_scaler_cap) { + struct v4l2_rect fmt = dev->fmt_cap_rect; + struct v4l2_rect max_rect = { + 0, 0, + s->r.width * MAX_ZOOM, + s->r.height * MAX_ZOOM + }; + struct v4l2_rect min_rect = { + 0, 0, + s->r.width / MAX_ZOOM, + s->r.height / MAX_ZOOM + }; + + v4l2_rect_set_min_size(&fmt, &min_rect); + if (!dev->has_compose_cap) + v4l2_rect_set_max_size(&fmt, &max_rect); + if (!v4l2_rect_same_size(&dev->fmt_cap_rect, &fmt) && + vb2_is_busy(&dev->vb_vid_cap_q)) + return -EBUSY; + if (dev->has_compose_cap) { + v4l2_rect_set_min_size(compose, &min_rect); + v4l2_rect_set_max_size(compose, &max_rect); + v4l2_rect_map_inside(compose, &fmt); + } + dev->fmt_cap_rect = fmt; + tpg_s_buf_height(&dev->tpg, fmt.height); + } else if (dev->has_compose_cap) { + struct v4l2_rect fmt = dev->fmt_cap_rect; + + v4l2_rect_set_min_size(&fmt, &s->r); + if (!v4l2_rect_same_size(&dev->fmt_cap_rect, &fmt) && + vb2_is_busy(&dev->vb_vid_cap_q)) + return -EBUSY; + dev->fmt_cap_rect = fmt; + tpg_s_buf_height(&dev->tpg, fmt.height); + v4l2_rect_set_size_to(compose, &s->r); + v4l2_rect_map_inside(compose, &dev->fmt_cap_rect); + } else { + if (!v4l2_rect_same_size(&s->r, &dev->fmt_cap_rect) && + vb2_is_busy(&dev->vb_vid_cap_q)) + return -EBUSY; + v4l2_rect_set_size_to(&dev->fmt_cap_rect, &s->r); + v4l2_rect_set_size_to(compose, &s->r); + v4l2_rect_map_inside(compose, &dev->fmt_cap_rect); + tpg_s_buf_height(&dev->tpg, dev->fmt_cap_rect.height); + } + s->r.top *= factor; + s->r.height *= factor; + *crop = s->r; + break; + case V4L2_SEL_TGT_COMPOSE: + if (!dev->has_compose_cap) + return -EINVAL; + ret = vivid_vid_adjust_sel(s->flags, &s->r); + if (ret) + return ret; + v4l2_rect_set_min_size(&s->r, &vivid_min_rect); + v4l2_rect_set_max_size(&s->r, &dev->fmt_cap_rect); + if (dev->has_scaler_cap) { + struct v4l2_rect max_rect = { + 0, 0, + dev->src_rect.width * MAX_ZOOM, + (dev->src_rect.height / factor) * MAX_ZOOM + }; + + v4l2_rect_set_max_size(&s->r, &max_rect); + if (dev->has_crop_cap) { + struct v4l2_rect min_rect = { + 0, 0, + s->r.width / MAX_ZOOM, + (s->r.height * factor) / MAX_ZOOM + }; + struct v4l2_rect max_rect = { + 0, 0, + s->r.width * MAX_ZOOM, + (s->r.height * factor) * MAX_ZOOM + }; + + v4l2_rect_set_min_size(crop, &min_rect); + v4l2_rect_set_max_size(crop, &max_rect); + v4l2_rect_map_inside(crop, &dev->crop_bounds_cap); + } + } else if (dev->has_crop_cap) { + s->r.top *= factor; + s->r.height *= factor; + v4l2_rect_set_max_size(&s->r, &dev->src_rect); + v4l2_rect_set_size_to(crop, &s->r); + v4l2_rect_map_inside(crop, &dev->crop_bounds_cap); + s->r.top /= factor; + s->r.height /= factor; + } else { + v4l2_rect_set_size_to(&s->r, &dev->src_rect); + s->r.height /= factor; + } + v4l2_rect_map_inside(&s->r, &dev->fmt_cap_rect); + *compose = s->r; + break; + default: + return -EINVAL; + } + + tpg_s_crop_compose(&dev->tpg, crop, compose); + return 0; +} +``` diff --git a/tasks/csa159/pair_147034/task_prompt.md b/tasks/csa159/pair_147034/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_147034/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_147222/checker_template.cpp b/tasks/csa159/pair_147222/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_147222/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_147222/config.json b/tasks/csa159/pair_147222/config.json new file mode 100644 index 0000000000000000000000000000000000000000..6e9799efc1ad5a863e424fbf0f73885e3afca99d --- /dev/null +++ b/tasks/csa159/pair_147222/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "fe6f600c43e0931f4fb5e1debb2311b7a6ebabd8", + "after_commit": "734aa85390ea693bb7eaf2240623d41b03705c84", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/82f2b0b97b36ee3fcddf0f0780a9a0825d52fec3/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/82f2b0b97b36ee3fcddf0f0780a9a0825d52fec3/compile_commands.json", + "changed_files": [ + "fs/squashfs/super.c" + ], + "commit_message": "Squashfs: check return result of sb_min_blocksize\n\nSyzkaller reports an \"UBSAN: shift-out-of-bounds in squashfs_bio_read\" bug.\n\nSyzkaller forks multiple processes which after mounting the Squashfs\nfilesystem, issues an ioctl(\"/dev/loop0\", LOOP_SET_BLOCK_SIZE, 0x8000). \nNow if this ioctl occurs at the same time another process is in the\nprocess of mounting a Squashfs filesystem on /dev/loop0, the failure\noccurs. When this happens the following code in squashfs_fill_super()\nfails.\n\n----\nmsblk->devblksize = sb_min_blocksize(sb, SQUASHFS_DEVBLK_SIZE);\nmsblk->devblksize_log2 = ffz(~msblk->devblksize);\n----\n\nsb_min_blocksize() returns 0, which means msblk->devblksize is set to 0.\n\nAs a result, ffz(~msblk->devblksize) returns 64, and msblk->devblksize_log2\nis set to 64.\n\nThis subsequently causes the\n\nUBSAN: shift-out-of-bounds in fs/squashfs/block.c:195:36\nshift exponent 64 is too large for 64-bit type 'u64' (aka\n'unsigned long long')\n\nThis commit adds a check for a 0 return by sb_min_blocksize().\n\nLink: https://lkml.kernel.org/r/20250409024747.876480-1-phillip@squashfs.org.uk\nFixes: 0aa666190509 (\"Squashfs: super block operations\")\nReported-by: syzbot+65761fc25a137b9c8c6e@syzkaller.appspotmail.com\nCloses: https://lore.kernel.org/all/67f0dd7a.050a0220.0a13.0230.GAE@google.com/\nSigned-off-by: Phillip Lougher \nSigned-off-by: Andrew Morton ", + "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_147222/patch.diff b/tasks/csa159/pair_147222/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e4f9ee75046fbcc55684606dd46cdb4b1fe6c75f --- /dev/null +++ b/tasks/csa159/pair_147222/patch.diff @@ -0,0 +1,16 @@ +diff --git a/fs/squashfs/super.c b/fs/squashfs/super.c +index 67c55fe32ce8..992ea0e37257 100644 +--- a/fs/squashfs/super.c ++++ b/fs/squashfs/super.c +@@ -202,6 +202,11 @@ static int squashfs_fill_super(struct super_block *sb, struct fs_context *fc) + msblk->panic_on_errors = (opts->errors == Opt_errors_panic); + + msblk->devblksize = sb_min_blocksize(sb, SQUASHFS_DEVBLK_SIZE); ++ if (!msblk->devblksize) { ++ errorf(fc, "squashfs: unable to set blocksize\n"); ++ return -EINVAL; ++ } ++ + msblk->devblksize_log2 = ffz(~msblk->devblksize); + + mutex_init(&msblk->meta_index_mutex); \ No newline at end of file diff --git a/tasks/csa159/pair_147222/post_functions.txt b/tasks/csa159/pair_147222/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..22d685b584fbbc32506d0b55be986ed8bd731141 --- /dev/null +++ b/tasks/csa159/pair_147222/post_functions.txt @@ -0,0 +1,260 @@ +### File: fs/squashfs/super.c +```c +static int squashfs_fill_super(struct super_block *sb, struct fs_context *fc) +{ + struct squashfs_mount_opts *opts = fc->fs_private; + struct squashfs_sb_info *msblk; + struct squashfs_super_block *sblk = NULL; + struct inode *root; + long long root_inode; + unsigned short flags; + unsigned int fragments; + u64 lookup_table_start, xattr_id_table_start, next_table; + int err; + + TRACE("Entered squashfs_fill_superblock\n"); + + sb->s_fs_info = kzalloc(sizeof(*msblk), GFP_KERNEL); + if (sb->s_fs_info == NULL) { + ERROR("Failed to allocate squashfs_sb_info\n"); + return -ENOMEM; + } + msblk = sb->s_fs_info; + msblk->thread_ops = opts->thread_ops; + + msblk->panic_on_errors = (opts->errors == Opt_errors_panic); + + msblk->devblksize = sb_min_blocksize(sb, SQUASHFS_DEVBLK_SIZE); + if (!msblk->devblksize) { + errorf(fc, "squashfs: unable to set blocksize\n"); + return -EINVAL; + } + + msblk->devblksize_log2 = ffz(~msblk->devblksize); + + mutex_init(&msblk->meta_index_mutex); + + /* + * msblk->bytes_used is checked in squashfs_read_table to ensure reads + * are not beyond filesystem end. But as we're using + * squashfs_read_table here to read the superblock (including the value + * of bytes_used) we need to set it to an initial sensible dummy value + */ + msblk->bytes_used = sizeof(*sblk); + sblk = squashfs_read_table(sb, SQUASHFS_START, sizeof(*sblk)); + + if (IS_ERR(sblk)) { + errorf(fc, "unable to read squashfs_super_block"); + err = PTR_ERR(sblk); + sblk = NULL; + goto failed_mount; + } + + err = -EINVAL; + + /* Check it is a SQUASHFS superblock */ + sb->s_magic = le32_to_cpu(sblk->s_magic); + if (sb->s_magic != SQUASHFS_MAGIC) { + if (!(fc->sb_flags & SB_SILENT)) + errorf(fc, "Can't find a SQUASHFS superblock on %pg", + sb->s_bdev); + goto failed_mount; + } + + if (opts->thread_num == 0) { + msblk->max_thread_num = msblk->thread_ops->max_decompressors(); + } else { + msblk->max_thread_num = opts->thread_num; + } + + /* Check the MAJOR & MINOR versions and lookup compression type */ + msblk->decompressor = supported_squashfs_filesystem( + fc, + le16_to_cpu(sblk->s_major), + le16_to_cpu(sblk->s_minor), + le16_to_cpu(sblk->compression)); + if (msblk->decompressor == NULL) + goto failed_mount; + + /* Check the filesystem does not extend beyond the end of the + block device */ + msblk->bytes_used = le64_to_cpu(sblk->bytes_used); + if (msblk->bytes_used < 0 || + msblk->bytes_used > bdev_nr_bytes(sb->s_bdev)) + goto failed_mount; + + /* Check block size for sanity */ + msblk->block_size = le32_to_cpu(sblk->block_size); + if (msblk->block_size > SQUASHFS_FILE_MAX_SIZE) + goto insanity; + + /* + * Check the system page size is not larger than the filesystem + * block size (by default 128K). This is currently not supported. + */ + if (PAGE_SIZE > msblk->block_size) { + errorf(fc, "Page size > filesystem block size (%d). This is " + "currently not supported!", msblk->block_size); + goto failed_mount; + } + + /* Check block log for sanity */ + msblk->block_log = le16_to_cpu(sblk->block_log); + if (msblk->block_log > SQUASHFS_FILE_MAX_LOG) + goto failed_mount; + + /* Check that block_size and block_log match */ + if (msblk->block_size != (1 << msblk->block_log)) + goto insanity; + + /* Check the root inode for sanity */ + root_inode = le64_to_cpu(sblk->root_inode); + if (SQUASHFS_INODE_OFFSET(root_inode) > SQUASHFS_METADATA_SIZE) + goto insanity; + + msblk->inode_table = le64_to_cpu(sblk->inode_table_start); + msblk->directory_table = le64_to_cpu(sblk->directory_table_start); + msblk->inodes = le32_to_cpu(sblk->inodes); + msblk->fragments = le32_to_cpu(sblk->fragments); + msblk->ids = le16_to_cpu(sblk->no_ids); + flags = le16_to_cpu(sblk->flags); + + TRACE("Found valid superblock on %pg\n", sb->s_bdev); + TRACE("Inodes are %scompressed\n", SQUASHFS_UNCOMPRESSED_INODES(flags) + ? "un" : ""); + TRACE("Data is %scompressed\n", SQUASHFS_UNCOMPRESSED_DATA(flags) + ? "un" : ""); + TRACE("Filesystem size %lld bytes\n", msblk->bytes_used); + TRACE("Block size %d\n", msblk->block_size); + TRACE("Number of inodes %d\n", msblk->inodes); + TRACE("Number of fragments %d\n", msblk->fragments); + TRACE("Number of ids %d\n", msblk->ids); + TRACE("sblk->inode_table_start %llx\n", msblk->inode_table); + TRACE("sblk->directory_table_start %llx\n", msblk->directory_table); + TRACE("sblk->fragment_table_start %llx\n", + (u64) le64_to_cpu(sblk->fragment_table_start)); + TRACE("sblk->id_table_start %llx\n", + (u64) le64_to_cpu(sblk->id_table_start)); + + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_min = 0; + sb->s_time_max = U32_MAX; + sb->s_flags |= SB_RDONLY; + sb->s_op = &squashfs_super_ops; + + msblk->block_cache = squashfs_cache_init("metadata", + SQUASHFS_CACHED_BLKS, SQUASHFS_METADATA_SIZE); + if (IS_ERR(msblk->block_cache)) { + err = PTR_ERR(msblk->block_cache); + goto failed_mount; + } + + /* Allocate read_page block */ + msblk->read_page = squashfs_cache_init("data", + SQUASHFS_READ_PAGES, msblk->block_size); + if (IS_ERR(msblk->read_page)) { + errorf(fc, "Failed to allocate read_page block"); + err = PTR_ERR(msblk->read_page); + goto failed_mount; + } + + if (msblk->devblksize == PAGE_SIZE) { + struct inode *cache = new_inode(sb); + + if (cache == NULL) { + err = -ENOMEM; + goto failed_mount; + } + + set_nlink(cache, 1); + cache->i_size = OFFSET_MAX; + mapping_set_gfp_mask(cache->i_mapping, GFP_NOFS); + + msblk->cache_mapping = cache->i_mapping; + } + + msblk->stream = squashfs_decompressor_setup(sb, flags); + if (IS_ERR(msblk->stream)) { + err = PTR_ERR(msblk->stream); + msblk->stream = NULL; + goto insanity; + } + + /* Handle xattrs */ + sb->s_xattr = squashfs_xattr_handlers; + xattr_id_table_start = le64_to_cpu(sblk->xattr_id_table_start); + if (xattr_id_table_start == SQUASHFS_INVALID_BLK) { + next_table = msblk->bytes_used; + goto allocate_id_index_table; + } + + /* Allocate and read xattr id lookup table */ + msblk->xattr_id_table = squashfs_read_xattr_id_table(sb, + xattr_id_table_start, &msblk->xattr_table, &msblk->xattr_ids); + if (IS_ERR(msblk->xattr_id_table)) { + errorf(fc, "unable to read xattr id index table"); + err = PTR_ERR(msblk->xattr_id_table); + msblk->xattr_id_table = NULL; + if (err != -ENOTSUPP) + goto failed_mount; + } + next_table = msblk->xattr_table; + +allocate_id_index_table: + /* Allocate and read id index table */ + msblk->id_table = squashfs_read_id_index_table(sb, + le64_to_cpu(sblk->id_table_start), next_table, msblk->ids); + if (IS_ERR(msblk->id_table)) { + errorf(fc, "unable to read id index table"); + err = PTR_ERR(msblk->id_table); + msblk->id_table = NULL; + goto failed_mount; + } + next_table = le64_to_cpu(msblk->id_table[0]); + + /* Handle inode lookup table */ + lookup_table_start = le64_to_cpu(sblk->lookup_table_start); + if (lookup_table_start == SQUASHFS_INVALID_BLK) + goto handle_fragments; + + /* Allocate and read inode lookup table */ + msblk->inode_lookup_table = squashfs_read_inode_lookup_table(sb, + lookup_table_start, next_table, msblk->inodes); + if (IS_ERR(msblk->inode_lookup_table)) { + errorf(fc, "unable to read inode lookup table"); + err = PTR_ERR(msblk->inode_lookup_table); + msblk->inode_lookup_table = NULL; + goto failed_mount; + } + next_table = le64_to_cpu(msblk->inode_lookup_table[0]); + + sb->s_export_op = &squashfs_export_ops; + +handle_fragments: + fragments = msblk->fragments; + if (fragments == 0) + goto check_directory_table; + + msblk->fragment_cache = squashfs_cache_init("fragment", + min(SQUASHFS_CACHED_FRAGMENTS, fragments), msblk->block_size); + if (IS_ERR(msblk->fragment_cache)) { + err = PTR_ERR(msblk->fragment_cache); + goto failed_mount; + } + + /* Allocate and read fragment index table */ + msblk->fragment_index = squashfs_read_fragment_index_table(sb, + le64_to_cpu(sblk->fragment_table_start), next_table, fragments); + if (IS_ERR(msblk->fragment_index)) { + errorf(fc, "unable to read fragment index table"); + err = PTR_ERR(msblk->fragment_index); + msblk->fragment_index = NULL; + goto failed_mount; + } + next_table = le64_to_cpu(msblk->fragment_index[0]); + +check_directory_table: + /* Sanity check directory_table */ + +// ... (1164 more chars) +``` diff --git a/tasks/csa159/pair_147222/pre_functions.txt b/tasks/csa159/pair_147222/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..09dc0d55b12ba6deeba55f64fad45d28976025ce --- /dev/null +++ b/tasks/csa159/pair_147222/pre_functions.txt @@ -0,0 +1,261 @@ +### File: fs/squashfs/super.c +```c +static int squashfs_fill_super(struct super_block *sb, struct fs_context *fc) +{ + struct squashfs_mount_opts *opts = fc->fs_private; + struct squashfs_sb_info *msblk; + struct squashfs_super_block *sblk = NULL; + struct inode *root; + long long root_inode; + unsigned short flags; + unsigned int fragments; + u64 lookup_table_start, xattr_id_table_start, next_table; + int err; + + TRACE("Entered squashfs_fill_superblock\n"); + + sb->s_fs_info = kzalloc(sizeof(*msblk), GFP_KERNEL); + if (sb->s_fs_info == NULL) { + ERROR("Failed to allocate squashfs_sb_info\n"); + return -ENOMEM; + } + msblk = sb->s_fs_info; + msblk->thread_ops = opts->thread_ops; + + msblk->panic_on_errors = (opts->errors == Opt_errors_panic); + + msblk->devblksize = sb_min_blocksize(sb, SQUASHFS_DEVBLK_SIZE); + msblk->devblksize_log2 = ffz(~msblk->devblksize); + + mutex_init(&msblk->meta_index_mutex); + + /* + * msblk->bytes_used is checked in squashfs_read_table to ensure reads + * are not beyond filesystem end. But as we're using + * squashfs_read_table here to read the superblock (including the value + * of bytes_used) we need to set it to an initial sensible dummy value + */ + msblk->bytes_used = sizeof(*sblk); + sblk = squashfs_read_table(sb, SQUASHFS_START, sizeof(*sblk)); + + if (IS_ERR(sblk)) { + errorf(fc, "unable to read squashfs_super_block"); + err = PTR_ERR(sblk); + sblk = NULL; + goto failed_mount; + } + + err = -EINVAL; + + /* Check it is a SQUASHFS superblock */ + sb->s_magic = le32_to_cpu(sblk->s_magic); + if (sb->s_magic != SQUASHFS_MAGIC) { + if (!(fc->sb_flags & SB_SILENT)) + errorf(fc, "Can't find a SQUASHFS superblock on %pg", + sb->s_bdev); + goto failed_mount; + } + + if (opts->thread_num == 0) { + msblk->max_thread_num = msblk->thread_ops->max_decompressors(); + } else { + msblk->max_thread_num = opts->thread_num; + } + + /* Check the MAJOR & MINOR versions and lookup compression type */ + msblk->decompressor = supported_squashfs_filesystem( + fc, + le16_to_cpu(sblk->s_major), + le16_to_cpu(sblk->s_minor), + le16_to_cpu(sblk->compression)); + if (msblk->decompressor == NULL) + goto failed_mount; + + /* Check the filesystem does not extend beyond the end of the + block device */ + msblk->bytes_used = le64_to_cpu(sblk->bytes_used); + if (msblk->bytes_used < 0 || + msblk->bytes_used > bdev_nr_bytes(sb->s_bdev)) + goto failed_mount; + + /* Check block size for sanity */ + msblk->block_size = le32_to_cpu(sblk->block_size); + if (msblk->block_size > SQUASHFS_FILE_MAX_SIZE) + goto insanity; + + /* + * Check the system page size is not larger than the filesystem + * block size (by default 128K). This is currently not supported. + */ + if (PAGE_SIZE > msblk->block_size) { + errorf(fc, "Page size > filesystem block size (%d). This is " + "currently not supported!", msblk->block_size); + goto failed_mount; + } + + /* Check block log for sanity */ + msblk->block_log = le16_to_cpu(sblk->block_log); + if (msblk->block_log > SQUASHFS_FILE_MAX_LOG) + goto failed_mount; + + /* Check that block_size and block_log match */ + if (msblk->block_size != (1 << msblk->block_log)) + goto insanity; + + /* Check the root inode for sanity */ + root_inode = le64_to_cpu(sblk->root_inode); + if (SQUASHFS_INODE_OFFSET(root_inode) > SQUASHFS_METADATA_SIZE) + goto insanity; + + msblk->inode_table = le64_to_cpu(sblk->inode_table_start); + msblk->directory_table = le64_to_cpu(sblk->directory_table_start); + msblk->inodes = le32_to_cpu(sblk->inodes); + msblk->fragments = le32_to_cpu(sblk->fragments); + msblk->ids = le16_to_cpu(sblk->no_ids); + flags = le16_to_cpu(sblk->flags); + + TRACE("Found valid superblock on %pg\n", sb->s_bdev); + TRACE("Inodes are %scompressed\n", SQUASHFS_UNCOMPRESSED_INODES(flags) + ? "un" : ""); + TRACE("Data is %scompressed\n", SQUASHFS_UNCOMPRESSED_DATA(flags) + ? "un" : ""); + TRACE("Filesystem size %lld bytes\n", msblk->bytes_used); + TRACE("Block size %d\n", msblk->block_size); + TRACE("Number of inodes %d\n", msblk->inodes); + TRACE("Number of fragments %d\n", msblk->fragments); + TRACE("Number of ids %d\n", msblk->ids); + TRACE("sblk->inode_table_start %llx\n", msblk->inode_table); + TRACE("sblk->directory_table_start %llx\n", msblk->directory_table); + TRACE("sblk->fragment_table_start %llx\n", + (u64) le64_to_cpu(sblk->fragment_table_start)); + TRACE("sblk->id_table_start %llx\n", + (u64) le64_to_cpu(sblk->id_table_start)); + + sb->s_maxbytes = MAX_LFS_FILESIZE; + sb->s_time_min = 0; + sb->s_time_max = U32_MAX; + sb->s_flags |= SB_RDONLY; + sb->s_op = &squashfs_super_ops; + + msblk->block_cache = squashfs_cache_init("metadata", + SQUASHFS_CACHED_BLKS, SQUASHFS_METADATA_SIZE); + if (IS_ERR(msblk->block_cache)) { + err = PTR_ERR(msblk->block_cache); + goto failed_mount; + } + + /* Allocate read_page block */ + msblk->read_page = squashfs_cache_init("data", + SQUASHFS_READ_PAGES, msblk->block_size); + if (IS_ERR(msblk->read_page)) { + errorf(fc, "Failed to allocate read_page block"); + err = PTR_ERR(msblk->read_page); + goto failed_mount; + } + + if (msblk->devblksize == PAGE_SIZE) { + struct inode *cache = new_inode(sb); + + if (cache == NULL) { + err = -ENOMEM; + goto failed_mount; + } + + set_nlink(cache, 1); + cache->i_size = OFFSET_MAX; + mapping_set_gfp_mask(cache->i_mapping, GFP_NOFS); + + msblk->cache_mapping = cache->i_mapping; + } + + msblk->stream = squashfs_decompressor_setup(sb, flags); + if (IS_ERR(msblk->stream)) { + err = PTR_ERR(msblk->stream); + msblk->stream = NULL; + goto insanity; + } + + /* Handle xattrs */ + sb->s_xattr = squashfs_xattr_handlers; + xattr_id_table_start = le64_to_cpu(sblk->xattr_id_table_start); + if (xattr_id_table_start == SQUASHFS_INVALID_BLK) { + next_table = msblk->bytes_used; + goto allocate_id_index_table; + } + + /* Allocate and read xattr id lookup table */ + msblk->xattr_id_table = squashfs_read_xattr_id_table(sb, + xattr_id_table_start, &msblk->xattr_table, &msblk->xattr_ids); + if (IS_ERR(msblk->xattr_id_table)) { + errorf(fc, "unable to read xattr id index table"); + err = PTR_ERR(msblk->xattr_id_table); + msblk->xattr_id_table = NULL; + if (err != -ENOTSUPP) + goto failed_mount; + } + next_table = msblk->xattr_table; + +allocate_id_index_table: + /* Allocate and read id index table */ + msblk->id_table = squashfs_read_id_index_table(sb, + le64_to_cpu(sblk->id_table_start), next_table, msblk->ids); + if (IS_ERR(msblk->id_table)) { + errorf(fc, "unable to read id index table"); + err = PTR_ERR(msblk->id_table); + msblk->id_table = NULL; + goto failed_mount; + } + next_table = le64_to_cpu(msblk->id_table[0]); + + /* Handle inode lookup table */ + lookup_table_start = le64_to_cpu(sblk->lookup_table_start); + if (lookup_table_start == SQUASHFS_INVALID_BLK) + goto handle_fragments; + + /* Allocate and read inode lookup table */ + msblk->inode_lookup_table = squashfs_read_inode_lookup_table(sb, + lookup_table_start, next_table, msblk->inodes); + if (IS_ERR(msblk->inode_lookup_table)) { + errorf(fc, "unable to read inode lookup table"); + err = PTR_ERR(msblk->inode_lookup_table); + msblk->inode_lookup_table = NULL; + goto failed_mount; + } + next_table = le64_to_cpu(msblk->inode_lookup_table[0]); + + sb->s_export_op = &squashfs_export_ops; + +handle_fragments: + fragments = msblk->fragments; + if (fragments == 0) + goto check_directory_table; + + msblk->fragment_cache = squashfs_cache_init("fragment", + min(SQUASHFS_CACHED_FRAGMENTS, fragments), msblk->block_size); + if (IS_ERR(msblk->fragment_cache)) { + err = PTR_ERR(msblk->fragment_cache); + goto failed_mount; + } + + /* Allocate and read fragment index table */ + msblk->fragment_index = squashfs_read_fragment_index_table(sb, + le64_to_cpu(sblk->fragment_table_start), next_table, fragments); + if (IS_ERR(msblk->fragment_index)) { + errorf(fc, "unable to read fragment index table"); + err = PTR_ERR(msblk->fragment_index); + msblk->fragment_index = NULL; + goto failed_mount; + } + next_table = le64_to_cpu(msblk->fragment_index[0]); + +check_directory_table: + /* Sanity check directory_table */ + if (msblk->directory_table > next_table) { + err = -EINVAL; + goto insanity; + } + + /* Sanity check in + +// ... (1062 more chars) +``` diff --git a/tasks/csa159/pair_147222/task_prompt.md b/tasks/csa159/pair_147222/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..99596a9e16804332ed43ccb9a10ab02b4a6c8d19 --- /dev/null +++ b/tasks/csa159/pair_147222/task_prompt.md @@ -0,0 +1,375 @@ +# 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 compiled but emitted zero diagnostics on both buggy and patched builds, so the vulnerability semantics were neither detected before the fix nor shown to disappear after it. +- The attempted sink matching was too representation-specific: it required a global C-function identifier and an argument represented exactly as one UnarySymExpr with UO_Not, despite the stated contract requiring casts, parentheses, leading NOT operators, field loads, and macro or builtin expansion to be handled. +- The source-to-sink association was not demonstrated for the value stored in msblk->devblksize and later loaded at ffz; the absence of verification traces and the unrun refinement left this value-flow match unproven. +- Hard validation, cross-validation, refinement acceptance, semantic mechanism adequacy, objective eligibility, and process quality all remained failed; the next synthesis must establish each rather than rely on compilation alone. + +### Preserve from prior rollouts + +- Do not introduce dependence on patch anchors, changed-line locations, or other artifacts that identify the specific fix. +- Do not introduce patch-local hardcoding; retain project-general Linux applicability based on the semantic source and sink behavior. + +### Required semantic proof + +- Identify a value originating from sb_min_blocksize() whose return may be zero and preserve its symbolic identity through the assignment to msblk->devblksize and the subsequent load used by the bit-scan. +- At the bit-scan use, establish that the dangerous operand is the original value x in ffz(~x), including the analyzer's actual representation of macro expansion, builtin lowering, casts, parentheses, and any equivalent leading complement structure. +- Emit a diagnostic only when the zero valuation of the source value remains feasible on the current execution path at the bit-scan sink. +- Treat the use as safe when path constraints prove the source value non-zero before the sink, including the patched early-return guard that dominates the ffz computation. +- Relate zero input to the undefined bit-scan result and its use as a shift exponent, so the diagnostic describes the actual shift-out-of-bounds vulnerability rather than merely naming an unchecked call. + +### Implementation constraints + +- Use path-sensitive ProgramState and constraint feasibility, with source marking after the sb_min_blocksize call, sink evaluation at the bit-scan operation, and dead-symbol cleanup. +- Implement sink recognition against the analyzer's observed call or expression forms for ffz, variable_ffz, and relevant builtin lowering rather than depending on one exact callee identifier or one exact SVal shape. +- Track the value through ordinary kernel storage and reloads, including the msblk->devblksize field, without requiring source-text matching or a patch-specific assignment location. +- Report at the bit-scan/log2 use where the unsafe value is consumed, with a path-sensitive nonfatal report and source ranges that identify the sink and relevant operand. +- Limit applicability to the documented Linux-kernel semantic family: sb_min_blocksize() values feeding ffz(~x)-style bit scans; do not broaden the rule to unrelated zero checks or direct __ffs(x) patterns. +- Register a complete CSA checker with the required callbacks and verify that the built plugin is the one used by both before and after scans. + +### Validation checklist + +- Compile the new checker and load the resulting shared object in the analyzer without registration, API, or diagnostic-generation errors. +- Run the checker on the unpatched source and confirm at least one relevant diagnostic in squashfs_fill_super at or immediately around the ffz use. +- Run the same checker on the patched source and confirm the diagnostic disappears because the zero path is rejected by the added guard. +- Confirm report locality under the function-or-precise-changed-span policy: the warning must be in the patched function and near the vulnerable bit-scan, not merely near sb_min_blocksize or an unrelated kernel location. +- Cross-validate on the supplied before and after function sets and ensure the result is not dependent on an unavailable trace or on a single patch anchor. +- Exercise relevant refinements for field store/load propagation, macro or builtin sink forms, complement and cast normalization, and non-zero path constraints. +- Check negative cases for values not returned by sb_min_blocksize and for paths where the value is proven non-zero before the sink. +- Verify no unrelated diagnostics are introduced and that the final result satisfies hard validation, semantic mechanism, refinement, objective, and process gates. + +### Avoid and forbidden regressions + +- Do not accept a zero-warning scan as success; it fails the required differential detection even if the checker builds. +- Do not rely on syntactic guard dominance without proving the value constraint at the actual sink path. +- Do not require only a direct UnarySymExpr UO_Not argument or only one global C-function spelling when the kernel's ffz macro may lower differently. +- Do not track only the immediate return symbol if that loses identity across the struct field assignment and reload. +- Do not report every bit scan, every possibly-zero integer, or direct __ffs(x) cases outside the documented ffz(~x) contract. +- Do not use debug output, source-line anchors, changed-line matching, literal patch text, or the specific squashfs function name as the detection mechanism. +- Do not weaken the semantic contract to improve process or objective scores; demonstrate the buggy-before and safe-after path distinction instead. diff --git a/tasks/csa159/pair_147266/checker_template.cpp b/tasks/csa159/pair_147266/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_147266/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_147266/config.json b/tasks/csa159/pair_147266/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f71789ef688d9f575e9379be2fd365e2607ad7ea --- /dev/null +++ b/tasks/csa159/pair_147266/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "62dba28275a9a3104d4e33595c7b3328d4032d8d", + "after_commit": "c489f3283dbfc0f3c00c312149cae90d27552c45", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/d0b3b7b22dfa1f4b515fd3a295b3fd958f9e81af/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/d0b3b7b22dfa1f4b515fd3a295b3fd958f9e81af/compile_commands.json", + "changed_files": [ + "net/atm/clip.c" + ], + "commit_message": "atm: clip: Fix infinite recursive call of clip_push().\n\nsyzbot reported the splat below. [0]\n\nThis happens if we call ioctl(ATMARP_MKIP) more than once.\n\nDuring the first call, clip_mkip() sets clip_push() to vcc->push(),\nand the second call copies it to clip_vcc->old_push().\n\nLater, when the socket is close()d, vcc_destroy_socket() passes\nNULL skb to clip_push(), which calls clip_vcc->old_push(),\ntriggering the infinite recursion.\n\nLet's prevent the second ioctl(ATMARP_MKIP) by checking\nvcc->user_back, which is allocated by the first call as clip_vcc.\n\nNote also that we use lock_sock() to prevent racy calls.\n\n[0]:\nBUG: TASK stack guard page was hit at ffffc9000d66fff8 (stack is ffffc9000d670000..ffffc9000d678000)\nOops: stack guard page: 0000 [#1] SMP KASAN NOPTI\nCPU: 0 UID: 0 PID: 5322 Comm: syz.0.0 Not tainted 6.16.0-rc4-syzkaller #0 PREEMPT(full)\nHardware name: QEMU Standard PC (Q35 + ICH9, 2009), BIOS 1.16.3-debian-1.16.3-2~bpo12+1 04/01/2014\nRIP: 0010:clip_push+0x5/0x720 net/atm/clip.c:191\nCode: e0 8f aa 8c e8 1c ad 5b fa eb ae 66 2e 0f 1f 84 00 00 00 00 00 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 90 f3 0f 1e fa 55 <41> 57 41 56 41 55 41 54 53 48 83 ec 20 48 89 f3 49 89 fd 48 bd 00\nRSP: 0018:ffffc9000d670000 EFLAGS: 00010246\nRAX: 1ffff1100235a4a5 RBX: ffff888011ad2508 RCX: ffff8880003c0000\nRDX: 0000000000000000 RSI: 0000000000000000 RDI: ffff888037f01000\nRBP: dffffc0000000000 R08: ffffffff8fa104f7 R09: 1ffffffff1f4209e\nR10: dffffc0000000000 R11: ffffffff8a99b300 R12: ffffffff8a99b300\nR13: ffff888037f01000 R14: ffff888011ad2500 R15: ffff888037f01578\nFS: 000055557ab6d500(0000) GS:ffff88808d250000(0000) knlGS:0000000000000000\nCS: 0010 DS: 0000 ES: 0000 CR0: 0000000080050033\nCR2: ffffc9000d66fff8 CR3: 0000000043172000 CR4: 0000000000352ef0\nCall Trace:\n \n clip_push+0x6dc/0x720 net/atm/clip.c:200\n clip_push+0x6dc/0x720 net/atm/clip.c:200\n clip_push+0x6dc/0x720 net/atm/clip.c:200\n...\n clip_push+0x6dc/0x720 net/atm/clip.c:200\n clip_push+0x6dc/0x720 net/atm/clip.c:200\n clip_push+0x6dc/0x720 net/atm/clip.c:200\n vcc_destroy_socket net/atm/common.c:183 [inline]\n vcc_release+0x157/0x460 net/atm/common.c:205\n __sock_release net/socket.c:647 [inline]\n sock_close+0xc0/0x240 net/socket.c:1391\n __fput+0x449/0xa70 fs/file_table.c:465\n task_work_run+0x1d1/0x260 kernel/task_work.c:227\n resume_user_mode_work include/linux/resume_user_mode.h:50 [inline]\n exit_to_user_mode_loop+0xec/0x110 kernel/entry/common.c:114\n exit_to_user_mode_prepare include/linux/entry-common.h:330 [inline]\n syscall_exit_to_user_mode_work include/linux/entry-common.h:414 [inline]\n syscall_exit_to_user_mode include/linux/entry-common.h:449 [inline]\n do_syscall_64+0x2bd/0x3b0 arch/x86/entry/syscall_64.c:100\n entry_SYSCALL_64_after_hwframe+0x77/0x7f\nRIP: 0033:0x7ff31c98e929\nCode: ff ff c3 66 2e 0f 1f 84 00 00 00 00 00 0f 1f 40 00 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 a8 ff ff ff f7 d8 64 89 01 48\nRSP: 002b:00007fffb5aa1f78 EFLAGS: 00000246 ORIG_RAX: 00000000000001b4\nRAX: 0000000000000000 RBX: 0000000000012747 RCX: 00007ff31c98e929\nRDX: 0000000000000000 RSI: 000000000000001e RDI: 0000000000000003\nRBP: 00007ff31cbb7ba0 R08: 0000000000000001 R09: 0000000db5aa226f\nR10: 00007ff31c7ff030 R11: 0000000000000246 R12: 00007ff31cbb608c\nR13: 00007ff31cbb6080 R14: ffffffffffffffff R15: 00007fffb5aa2090\n \nModules linked in:\n\nFixes: 1da177e4c3f4 (\"Linux-2.6.12-rc2\")\nReported-by: syzbot+0c77cccd6b7cd917b35a@syzkaller.appspotmail.com\nCloses: https://syzkaller.appspot.com/bug?extid=2371d94d248d126c1eb1\nSigned-off-by: Kuniyuki Iwashima \nReviewed-by: Simon Horman \nLink: https://patch.msgid.link/20250704062416.1613927-4-kuniyu@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_147266/patch.diff b/tasks/csa159/pair_147266/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..765fd2433760af6669915a863fb8abd46fd5c028 --- /dev/null +++ b/tasks/csa159/pair_147266/patch.diff @@ -0,0 +1,13 @@ +diff --git a/net/atm/clip.c b/net/atm/clip.c +index 9c9c6c3d9886..a30c5a270545 100644 +--- a/net/atm/clip.c ++++ b/net/atm/clip.c +@@ -429,6 +429,8 @@ static int clip_mkip(struct atm_vcc *vcc, int timeout) + + if (!vcc->push) + return -EBADFD; ++ if (vcc->user_back) ++ return -EINVAL; + clip_vcc = kmalloc(sizeof(struct clip_vcc), GFP_KERNEL); + if (!clip_vcc) + return -ENOMEM; \ No newline at end of file diff --git a/tasks/csa159/pair_147266/post_functions.txt b/tasks/csa159/pair_147266/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..1450e41c28ac0d5e542b7a8c1df5b785d5964551 --- /dev/null +++ b/tasks/csa159/pair_147266/post_functions.txt @@ -0,0 +1,33 @@ +### File: net/atm/clip.c +```c +static int clip_mkip(struct atm_vcc *vcc, int timeout) +{ + struct clip_vcc *clip_vcc; + + if (!vcc->push) + return -EBADFD; + if (vcc->user_back) + return -EINVAL; + clip_vcc = kmalloc(sizeof(struct clip_vcc), GFP_KERNEL); + if (!clip_vcc) + return -ENOMEM; + pr_debug("%p vcc %p\n", clip_vcc, vcc); + clip_vcc->vcc = vcc; + vcc->user_back = clip_vcc; + set_bit(ATM_VF_IS_CLIP, &vcc->flags); + clip_vcc->entry = NULL; + clip_vcc->xoff = 0; + clip_vcc->encap = 1; + clip_vcc->last_use = jiffies; + clip_vcc->idle_timeout = timeout * HZ; + clip_vcc->old_push = vcc->push; + clip_vcc->old_pop = vcc->pop; + vcc->push = clip_push; + vcc->pop = clip_pop; + + /* re-process everything received between connection setup and MKIP */ + vcc_process_recv_queue(vcc); + + return 0; +} +``` diff --git a/tasks/csa159/pair_147266/pre_functions.txt b/tasks/csa159/pair_147266/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..b15f34efd60f7324e74dfbeefdf4428101ee301a --- /dev/null +++ b/tasks/csa159/pair_147266/pre_functions.txt @@ -0,0 +1,31 @@ +### File: net/atm/clip.c +```c +static int clip_mkip(struct atm_vcc *vcc, int timeout) +{ + struct clip_vcc *clip_vcc; + + if (!vcc->push) + return -EBADFD; + clip_vcc = kmalloc(sizeof(struct clip_vcc), GFP_KERNEL); + if (!clip_vcc) + return -ENOMEM; + pr_debug("%p vcc %p\n", clip_vcc, vcc); + clip_vcc->vcc = vcc; + vcc->user_back = clip_vcc; + set_bit(ATM_VF_IS_CLIP, &vcc->flags); + clip_vcc->entry = NULL; + clip_vcc->xoff = 0; + clip_vcc->encap = 1; + clip_vcc->last_use = jiffies; + clip_vcc->idle_timeout = timeout * HZ; + clip_vcc->old_push = vcc->push; + clip_vcc->old_pop = vcc->pop; + vcc->push = clip_push; + vcc->pop = clip_pop; + + /* re-process everything received between connection setup and MKIP */ + vcc_process_recv_queue(vcc); + + return 0; +} +``` diff --git a/tasks/csa159/pair_147266/task_prompt.md b/tasks/csa159/pair_147266/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..95c6e614a77920bf146f61459fe726d47a50ddae --- /dev/null +++ b/tasks/csa159/pair_147266/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 passed compilation, differential validation, objective gate G6, semantic scoring, anchor checks, and hardcoding checks, but refinement remained unaccepted with outcome feedback_required. +- The candidate marker was inferred as an arbitrary non-function store to another field on the same base object; that does not generally establish that the field represents completed hook initialization. +- Dominance of the marker store alone does not prove that the re-entry guard executes before the hook save and installation operations that create the recursive self-reference. +- The save-before-install relationship was based on AST traversal order rather than an explicit CFG ordering or reachability proof. + +### Preserve from prior rollouts + +- Preserve successful checker compilation, before/after scanning, cross-validation, and code verification. +- Preserve objective eligibility gate G6 and semantic score at or above the configured threshold. +- Preserve the accepted cross-procedure structural relationship between hook installation and dispatch through the saved hook slot. +- Preserve process quality at or above the configured threshold. +- Remain independent of patch anchors, including changed line numbers, source locations, diff text, and nearby textual context. +- Remain free of patch-local hardcoding such as project identifiers, function names, field names, constants, and source-text matching. + +### Required semantic proof + +- Establish that an initialization routine reads a function-pointer field from an object, saves that value in a member slot, and later overwrites the same function-pointer field on the same object with a wrapper. +- Establish from the wrapper's available function body that it can call through the exact saved member slot, so a repeated installation can save the wrapper itself and produce unbounded indirect recursion. +- Prove with CFG relationships that the save can execute before the wrapper installation on a path through the initialization routine; AST visitation or source order alone is insufficient. +- Identify an initialization marker only when its relationship to this installation protocol is structurally justified, including the same object identity and a store representing transition to initialized state. +- Treat the routine as safe only when a non-null test of the exact marker field on the same object has a terminating taken branch and dominates every relevant hook save and installation operation. +- Account for other writes to the marker or hook field that could invalidate the first-installation argument; suppress only when the guard proof remains valid for all paths reaching the vulnerable operations. + +### Implementation constraints + +- Use a CSA per-function-body callback that is actually invoked by AnalysisConsumer, such as check::ASTCodeBody, and obtain the function CFG and dominator information through AnalysisDeclContext. +- Correlate fields, bases, and directly referenced wrapper declarations by AST declaration identity rather than spelling or source text. +- Inspect the TU-defined wrapper body to establish the cross-procedure saved-slot dispatch relation; no general interprocedural ProgramState propagation is required by the evidence. +- Use CFG block reachability, dominance, and within-block execution positions to prove guard, save, marker transition, and installation ordering. +- Attach at most one diagnostic per qualifying routine to the vulnerable hook installation statement, keeping the report within the affected function. +- Keep scope project-general and require the complete save, install, wrapper-dispatch, marker, and missing-guard relationship before reporting. +- Do not depend on ProgramState reaching the hook statements because KASAN-driven kmalloc inlining and asm goto stop ExprEngine exploration in the supplied scan environment. + +### Validation checklist + +- Compile the synthesized checker plugin successfully against the supplied Clang Static Analyzer API and verify checker registration and report construction. +- Scan the unpatched source and confirm diagnostics are produced for clip_mkip; account for the harness analyzing net/atm/clip.c twice when interpreting the expected count of two. +- Scan the patched source and confirm that the added user_back non-null early return suppresses all corresponding diagnostics. +- Run paired cross-validation and code verification, requiring N_buggy=2, N_patched=0, all disappeared findings relevant to clip_mkip, and no findings in non-patched functions. +- Confirm each unpatched diagnostic is attached to the hook installation and remains within the accepted near-patch threshold; the prior median distance was 14 lines. +- Add focused refinement cases showing that an unrelated same-base field store is not accepted as an initialization marker and does not independently trigger the checker. +- Add CFG refinement cases where a guard dominates only the marker store but not the hook save or install, and require that such a guard not suppress the finding. +- Add ordering and identity refinements for branch-only saves, installs preceding saves, different base objects, different saved fields, non-terminating guards, and alternate marker writes. + +### Avoid and forbidden regressions + +- Do not retry the rejected path-sensitive assumeDual design in this scan configuration, where execution does not reach the relevant hook statements. +- Do not use lexical or RecursiveASTVisitor collection order as proof of runtime ordering. +- Do not accept dominance over only the marker assignment as sufficient protection for the hook save and installation. +- Do not classify every non-function assignment to a same-base field as an initialization marker. +- Do not suppress on a guard-shaped statement unless it tests the exact marker/base pair, rejects the initialized value, terminates on the taken branch, and satisfies the required CFG relations. +- Do not report ordinary function-pointer replacement that lacks both a saved predecessor slot and wrapper dispatch through that exact slot. +- Do not introduce names, line numbers, patch text, repository-specific identifiers, or source-string matching to recover the expected differential result. diff --git a/tasks/csa159/pair_147640/checker_template.cpp b/tasks/csa159/pair_147640/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_147640/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_147640/config.json b/tasks/csa159/pair_147640/config.json new file mode 100644 index 0000000000000000000000000000000000000000..f768b48c1e01fac5870ed0b94e29744ab62b491f --- /dev/null +++ b/tasks/csa159/pair_147640/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "fd980bf6e9cdae885105685259421164f843ca55", + "after_commit": "d1547bf460baec718b3398365f8de33d25c5f36f", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/8f5ae30d69d7543eee0d70083daf4de8fe15d585/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/8f5ae30d69d7543eee0d70083daf4de8fe15d585/compile_commands.json", + "changed_files": [ + "net/bridge/br_multicast.c" + ], + "commit_message": "net: bridge: fix soft lockup in br_multicast_query_expired()\n\nWhen set multicast_query_interval to a large value, the local variable\n'time' in br_multicast_send_query() may overflow. If the time is smaller\nthan jiffies, the timer will expire immediately, and then call mod_timer()\nagain, which creates a loop and may trigger the following soft lockup\nissue.\n\n watchdog: BUG: soft lockup - CPU#1 stuck for 221s! [rb_consumer:66]\n CPU: 1 UID: 0 PID: 66 Comm: rb_consumer Not tainted 6.16.0+ #259 PREEMPT(none)\n Call Trace:\n \n __netdev_alloc_skb+0x2e/0x3a0\n br_ip6_multicast_alloc_query+0x212/0x1b70\n __br_multicast_send_query+0x376/0xac0\n br_multicast_send_query+0x299/0x510\n br_multicast_query_expired.constprop.0+0x16d/0x1b0\n call_timer_fn+0x3b/0x2a0\n __run_timers+0x619/0x950\n run_timer_softirq+0x11c/0x220\n handle_softirqs+0x18e/0x560\n __irq_exit_rcu+0x158/0x1a0\n sysvec_apic_timer_interrupt+0x76/0x90\n \n\nThis issue can be reproduced with:\n ip link add br0 type bridge\n echo 1 > /sys/class/net/br0/bridge/multicast_querier\n echo 0xffffffffffffffff >\n \t/sys/class/net/br0/bridge/multicast_query_interval\n ip link set dev br0 up\n\nThe multicast_startup_query_interval can also cause this issue. Similar to\nthe commit 99b40610956a (\"net: bridge: mcast: add and enforce query\ninterval minimum\"), add check for the query interval maximum to fix this\nissue.\n\nLink: https://lore.kernel.org/netdev/20250806094941.1285944-1-wangliang74@huawei.com/\nLink: https://lore.kernel.org/netdev/20250812091818.542238-1-wangliang74@huawei.com/\nFixes: d902eee43f19 (\"bridge: Add multicast count/interval sysfs entries\")\nSuggested-by: Nikolay Aleksandrov \nSigned-off-by: Wang Liang \nReviewed-by: Ido Schimmel \nAcked-by: Nikolay Aleksandrov \nLink: https://patch.msgid.link/20250813021054.1643649-1-wangliang74@huawei.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_147640/patch.diff b/tasks/csa159/pair_147640/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b3840c8eb1dcae029aeada6702417e8cc25bfeb5 --- /dev/null +++ b/tasks/csa159/pair_147640/patch.diff @@ -0,0 +1,46 @@ +diff --git a/net/bridge/br_multicast.c b/net/bridge/br_multicast.c +index 1377f31b719c..8ce145938b02 100644 +--- a/net/bridge/br_multicast.c ++++ b/net/bridge/br_multicast.c +@@ -4818,6 +4818,14 @@ void br_multicast_set_query_intvl(struct net_bridge_mcast *brmctx, + intvl_jiffies = BR_MULTICAST_QUERY_INTVL_MIN; + } + ++ if (intvl_jiffies > BR_MULTICAST_QUERY_INTVL_MAX) { ++ br_info(brmctx->br, ++ "trying to set multicast query interval above maximum, setting to %lu (%ums)\n", ++ jiffies_to_clock_t(BR_MULTICAST_QUERY_INTVL_MAX), ++ jiffies_to_msecs(BR_MULTICAST_QUERY_INTVL_MAX)); ++ intvl_jiffies = BR_MULTICAST_QUERY_INTVL_MAX; ++ } ++ + brmctx->multicast_query_interval = intvl_jiffies; + } + +@@ -4834,6 +4842,14 @@ void br_multicast_set_startup_query_intvl(struct net_bridge_mcast *brmctx, + intvl_jiffies = BR_MULTICAST_STARTUP_QUERY_INTVL_MIN; + } + ++ if (intvl_jiffies > BR_MULTICAST_STARTUP_QUERY_INTVL_MAX) { ++ br_info(brmctx->br, ++ "trying to set multicast startup query interval above maximum, setting to %lu (%ums)\n", ++ jiffies_to_clock_t(BR_MULTICAST_STARTUP_QUERY_INTVL_MAX), ++ jiffies_to_msecs(BR_MULTICAST_STARTUP_QUERY_INTVL_MAX)); ++ intvl_jiffies = BR_MULTICAST_STARTUP_QUERY_INTVL_MAX; ++ } ++ + brmctx->multicast_startup_query_interval = intvl_jiffies; + } + +diff --git a/net/bridge/br_private.h b/net/bridge/br_private.h +index b159aae594c0..8de0904b9627 100644 +--- a/net/bridge/br_private.h ++++ b/net/bridge/br_private.h +@@ -31,6 +31,8 @@ + #define BR_MULTICAST_DEFAULT_HASH_MAX 4096 + #define BR_MULTICAST_QUERY_INTVL_MIN msecs_to_jiffies(1000) + #define BR_MULTICAST_STARTUP_QUERY_INTVL_MIN BR_MULTICAST_QUERY_INTVL_MIN ++#define BR_MULTICAST_QUERY_INTVL_MAX msecs_to_jiffies(86400000) /* 24 hours */ ++#define BR_MULTICAST_STARTUP_QUERY_INTVL_MAX BR_MULTICAST_QUERY_INTVL_MAX + + #define BR_HWDOM_MAX BITS_PER_LONG \ No newline at end of file diff --git a/tasks/csa159/pair_147640/post_functions.txt b/tasks/csa159/pair_147640/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..a450558982c997b67a30cda090bde78a0051cd79 --- /dev/null +++ b/tasks/csa159/pair_147640/post_functions.txt @@ -0,0 +1,50 @@ +### File: net/bridge/br_multicast.c +```c +void br_multicast_set_query_intvl(struct net_bridge_mcast *brmctx, + unsigned long val) +{ + unsigned long intvl_jiffies = clock_t_to_jiffies(val); + + if (intvl_jiffies < BR_MULTICAST_QUERY_INTVL_MIN) { + br_info(brmctx->br, + "trying to set multicast query interval below minimum, setting to %lu (%ums)\n", + jiffies_to_clock_t(BR_MULTICAST_QUERY_INTVL_MIN), + jiffies_to_msecs(BR_MULTICAST_QUERY_INTVL_MIN)); + intvl_jiffies = BR_MULTICAST_QUERY_INTVL_MIN; + } + + if (intvl_jiffies > BR_MULTICAST_QUERY_INTVL_MAX) { + br_info(brmctx->br, + "trying to set multicast query interval above maximum, setting to %lu (%ums)\n", + jiffies_to_clock_t(BR_MULTICAST_QUERY_INTVL_MAX), + jiffies_to_msecs(BR_MULTICAST_QUERY_INTVL_MAX)); + intvl_jiffies = BR_MULTICAST_QUERY_INTVL_MAX; + } + + brmctx->multicast_query_interval = intvl_jiffies; +} + +void br_multicast_set_startup_query_intvl(struct net_bridge_mcast *brmctx, + unsigned long val) +{ + unsigned long intvl_jiffies = clock_t_to_jiffies(val); + + if (intvl_jiffies < BR_MULTICAST_STARTUP_QUERY_INTVL_MIN) { + br_info(brmctx->br, + "trying to set multicast startup query interval below minimum, setting to %lu (%ums)\n", + jiffies_to_clock_t(BR_MULTICAST_STARTUP_QUERY_INTVL_MIN), + jiffies_to_msecs(BR_MULTICAST_STARTUP_QUERY_INTVL_MIN)); + intvl_jiffies = BR_MULTICAST_STARTUP_QUERY_INTVL_MIN; + } + + if (intvl_jiffies > BR_MULTICAST_STARTUP_QUERY_INTVL_MAX) { + br_info(brmctx->br, + "trying to set multicast startup query interval above maximum, setting to %lu (%ums)\n", + jiffies_to_clock_t(BR_MULTICAST_STARTUP_QUERY_INTVL_MAX), + jiffies_to_msecs(BR_MULTICAST_STARTUP_QUERY_INTVL_MAX)); + intvl_jiffies = BR_MULTICAST_STARTUP_QUERY_INTVL_MAX; + } + + brmctx->multicast_startup_query_interval = intvl_jiffies; +} +``` diff --git a/tasks/csa159/pair_147640/pre_functions.txt b/tasks/csa159/pair_147640/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..d99582ac8a4cd92e963e8c6b3bd26f5b08793073 --- /dev/null +++ b/tasks/csa159/pair_147640/pre_functions.txt @@ -0,0 +1,34 @@ +### File: net/bridge/br_multicast.c +```c +void br_multicast_set_query_intvl(struct net_bridge_mcast *brmctx, + unsigned long val) +{ + unsigned long intvl_jiffies = clock_t_to_jiffies(val); + + if (intvl_jiffies < BR_MULTICAST_QUERY_INTVL_MIN) { + br_info(brmctx->br, + "trying to set multicast query interval below minimum, setting to %lu (%ums)\n", + jiffies_to_clock_t(BR_MULTICAST_QUERY_INTVL_MIN), + jiffies_to_msecs(BR_MULTICAST_QUERY_INTVL_MIN)); + intvl_jiffies = BR_MULTICAST_QUERY_INTVL_MIN; + } + + brmctx->multicast_query_interval = intvl_jiffies; +} + +void br_multicast_set_startup_query_intvl(struct net_bridge_mcast *brmctx, + unsigned long val) +{ + unsigned long intvl_jiffies = clock_t_to_jiffies(val); + + if (intvl_jiffies < BR_MULTICAST_STARTUP_QUERY_INTVL_MIN) { + br_info(brmctx->br, + "trying to set multicast startup query interval below minimum, setting to %lu (%ums)\n", + jiffies_to_clock_t(BR_MULTICAST_STARTUP_QUERY_INTVL_MIN), + jiffies_to_msecs(BR_MULTICAST_STARTUP_QUERY_INTVL_MIN)); + intvl_jiffies = BR_MULTICAST_STARTUP_QUERY_INTVL_MIN; + } + + brmctx->multicast_startup_query_interval = intvl_jiffies; +} +``` diff --git a/tasks/csa159/pair_147640/task_prompt.md b/tasks/csa159/pair_147640/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_147640/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_147676/checker_template.cpp b/tasks/csa159/pair_147676/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_147676/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_147676/config.json b/tasks/csa159/pair_147676/config.json new file mode 100644 index 0000000000000000000000000000000000000000..98bf6c7c415653424c72c760b5d60bbb94a0609b --- /dev/null +++ b/tasks/csa159/pair_147676/config.json @@ -0,0 +1,19 @@ +{ + "project_id": "torvalds_linux", + "before_commit": "d9b0ca1334d8a9a03bef45e95825564c56ca3367", + "after_commit": "2747328ba2714f1a7454208dbbc1dc0631990b4a", + "repo_path": "/workspace/repo/torvalds/linux", + "llvm_build_dir": "/opt/llvm", + "before_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/c17b750b3ad9f45f2b6f7e6f7f4679844244f0b9/compile_commands.json", + "after_compile_commands": "/workspace/benchmark/data-pipeline/snapshots/torvalds_linux/c17b750b3ad9f45f2b6f7e6f7f4679844244f0b9/compile_commands.json", + "changed_files": [ + "drivers/net/ethernet/broadcom/bnxt/bnxt.c" + ], + "commit_message": "bnxt_en: Fix memory corruption when FW resources change during ifdown\n\nbnxt_set_dflt_rings() assumes that it is always called before any TC has\nbeen created. So it doesn't take bp->num_tc into account and assumes\nthat it is always 0 or 1.\n\nIn the FW resource or capability change scenario, the FW will return\nflags in bnxt_hwrm_if_change() that will cause the driver to\nreinitialize and call bnxt_cancel_reservations(). This will lead to\nbnxt_init_dflt_ring_mode() calling bnxt_set_dflt_rings() and bp->num_tc\nmay be greater than 1. This will cause bp->tx_ring[] to be sized too\nsmall and cause memory corruption in bnxt_alloc_cp_rings().\n\nFix it by properly scaling the TX rings by bp->num_tc in the code\npaths mentioned above. Add 2 helper functions to determine\nbp->tx_nr_rings and bp->tx_nr_rings_per_tc.\n\nFixes: ec5d31e3c15d (\"bnxt_en: Handle firmware reset status during IF_UP.\")\nReviewed-by: Kalesh AP \nReviewed-by: Andy Gospodarek \nSigned-off-by: Sreekanth Reddy \nSigned-off-by: Michael Chan \nLink: https://patch.msgid.link/20250825175927.459987-2-michael.chan@broadcom.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_147676/patch.diff b/tasks/csa159/pair_147676/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e021d3b6e601d17b07bbca5337701fd4ccdd85c6 --- /dev/null +++ b/tasks/csa159/pair_147676/patch.diff @@ -0,0 +1,66 @@ +diff --git a/drivers/net/ethernet/broadcom/bnxt/bnxt.c b/drivers/net/ethernet/broadcom/bnxt/bnxt.c +index 207a8bb36ae5..1f5c06f1296b 100644 +--- a/drivers/net/ethernet/broadcom/bnxt/bnxt.c ++++ b/drivers/net/ethernet/broadcom/bnxt/bnxt.c +@@ -12851,6 +12851,17 @@ static int bnxt_set_xps_mapping(struct bnxt *bp) + return rc; + } + ++static int bnxt_tx_nr_rings(struct bnxt *bp) ++{ ++ return bp->num_tc ? bp->tx_nr_rings_per_tc * bp->num_tc : ++ bp->tx_nr_rings_per_tc; ++} ++ ++static int bnxt_tx_nr_rings_per_tc(struct bnxt *bp) ++{ ++ return bp->num_tc ? bp->tx_nr_rings / bp->num_tc : bp->tx_nr_rings; ++} ++ + static int __bnxt_open_nic(struct bnxt *bp, bool irq_re_init, bool link_re_init) + { + int rc = 0; +@@ -16325,7 +16336,7 @@ static void bnxt_trim_dflt_sh_rings(struct bnxt *bp) + bp->cp_nr_rings = min_t(int, bp->tx_nr_rings_per_tc, bp->rx_nr_rings); + bp->rx_nr_rings = bp->cp_nr_rings; + bp->tx_nr_rings_per_tc = bp->cp_nr_rings; +- bp->tx_nr_rings = bp->tx_nr_rings_per_tc; ++ bp->tx_nr_rings = bnxt_tx_nr_rings(bp); + } + + static int bnxt_set_dflt_rings(struct bnxt *bp, bool sh) +@@ -16357,7 +16368,7 @@ static int bnxt_set_dflt_rings(struct bnxt *bp, bool sh) + bnxt_trim_dflt_sh_rings(bp); + else + bp->cp_nr_rings = bp->tx_nr_rings_per_tc + bp->rx_nr_rings; +- bp->tx_nr_rings = bp->tx_nr_rings_per_tc; ++ bp->tx_nr_rings = bnxt_tx_nr_rings(bp); + + avail_msix = bnxt_get_max_func_irqs(bp) - bp->cp_nr_rings; + if (avail_msix >= BNXT_MIN_ROCE_CP_RINGS) { +@@ -16370,7 +16381,7 @@ static int bnxt_set_dflt_rings(struct bnxt *bp, bool sh) + rc = __bnxt_reserve_rings(bp); + if (rc && rc != -ENODEV) + netdev_warn(bp->dev, "Unable to reserve tx rings\n"); +- bp->tx_nr_rings_per_tc = bp->tx_nr_rings; ++ bp->tx_nr_rings_per_tc = bnxt_tx_nr_rings_per_tc(bp); + if (sh) + bnxt_trim_dflt_sh_rings(bp); + +@@ -16379,7 +16390,7 @@ static int bnxt_set_dflt_rings(struct bnxt *bp, bool sh) + rc = __bnxt_reserve_rings(bp); + if (rc && rc != -ENODEV) + netdev_warn(bp->dev, "2nd rings reservation failed.\n"); +- bp->tx_nr_rings_per_tc = bp->tx_nr_rings; ++ bp->tx_nr_rings_per_tc = bnxt_tx_nr_rings_per_tc(bp); + } + if (BNXT_CHIP_TYPE_NITRO_A0(bp)) { + bp->rx_nr_rings++; +@@ -16413,7 +16424,7 @@ static int bnxt_init_dflt_ring_mode(struct bnxt *bp) + if (rc) + goto init_dflt_ring_err; + +- bp->tx_nr_rings_per_tc = bp->tx_nr_rings; ++ bp->tx_nr_rings_per_tc = bnxt_tx_nr_rings_per_tc(bp); + + bnxt_set_dflt_rfs(bp); \ No newline at end of file diff --git a/tasks/csa159/pair_147676/post_functions.txt b/tasks/csa159/pair_147676/post_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..c66269e0be897c16de0616f1e8a8a0e98240abd7 --- /dev/null +++ b/tasks/csa159/pair_147676/post_functions.txt @@ -0,0 +1,195 @@ +### File: drivers/net/ethernet/broadcom/bnxt/bnxt.c +```c +static int bnxt_set_xps_mapping(struct bnxt *bp) +{ + int numa_node = dev_to_node(&bp->pdev->dev); + unsigned int q_idx, map_idx, cpu, i; + const struct cpumask *cpu_mask_ptr; + int nr_cpus = num_online_cpus(); + cpumask_t *q_map; + int rc = 0; + + q_map = kcalloc(bp->tx_nr_rings_per_tc, sizeof(*q_map), GFP_KERNEL); + if (!q_map) + return -ENOMEM; + + /* Create CPU mask for all TX queues across MQPRIO traffic classes. + * Each TC has the same number of TX queues. The nth TX queue for each + * TC will have the same CPU mask. + */ + for (i = 0; i < nr_cpus; i++) { + map_idx = i % bp->tx_nr_rings_per_tc; + cpu = cpumask_local_spread(i, numa_node); + cpu_mask_ptr = get_cpu_mask(cpu); + cpumask_or(&q_map[map_idx], &q_map[map_idx], cpu_mask_ptr); + } + + /* Register CPU mask for each TX queue except the ones marked for XDP */ + for (q_idx = 0; q_idx < bp->dev->real_num_tx_queues; q_idx++) { + map_idx = q_idx % bp->tx_nr_rings_per_tc; + rc = netif_set_xps_queue(bp->dev, &q_map[map_idx], q_idx); + if (rc) { + netdev_warn(bp->dev, "Error setting XPS for q:%d\n", + q_idx); + break; + } + } + + kfree(q_map); + + return rc; +} + +static int bnxt_tx_nr_rings(struct bnxt *bp) +{ + return bp->num_tc ? bp->tx_nr_rings_per_tc * bp->num_tc : + bp->tx_nr_rings_per_tc; +} + +static int bnxt_get_dflt_rings(struct bnxt *bp, int *max_rx, int *max_tx, + bool shared) +{ + int rc; + + rc = bnxt_get_max_rings(bp, max_rx, max_tx, shared); + if (rc && (bp->flags & BNXT_FLAG_AGG_RINGS)) { + /* Not enough rings, try disabling agg rings. */ + bp->flags &= ~BNXT_FLAG_AGG_RINGS; + rc = bnxt_get_max_rings(bp, max_rx, max_tx, shared); + if (rc) { + /* set BNXT_FLAG_AGG_RINGS back for consistency */ + bp->flags |= BNXT_FLAG_AGG_RINGS; + return rc; + } + bp->flags |= BNXT_FLAG_NO_AGG_RINGS; + bp->dev->hw_features &= ~(NETIF_F_LRO | NETIF_F_GRO_HW); + bp->dev->features &= ~(NETIF_F_LRO | NETIF_F_GRO_HW); + bnxt_set_ring_params(bp); + } + + if (bp->flags & BNXT_FLAG_ROCE_CAP) { + int max_cp, max_stat, max_irq; + + /* Reserve minimum resources for RoCE */ + max_cp = bnxt_get_max_func_cp_rings(bp); + max_stat = bnxt_get_max_func_stat_ctxs(bp); + max_irq = bnxt_get_max_func_irqs(bp); + if (max_cp <= BNXT_MIN_ROCE_CP_RINGS || + max_irq <= BNXT_MIN_ROCE_CP_RINGS || + max_stat <= BNXT_MIN_ROCE_STAT_CTXS) + return 0; + + max_cp -= BNXT_MIN_ROCE_CP_RINGS; + max_irq -= BNXT_MIN_ROCE_CP_RINGS; + max_stat -= BNXT_MIN_ROCE_STAT_CTXS; + max_cp = min_t(int, max_cp, max_irq); + max_cp = min_t(int, max_cp, max_stat); + rc = bnxt_trim_rings(bp, max_rx, max_tx, max_cp, shared); + if (rc) + rc = 0; + } + return rc; +} + +static void bnxt_trim_dflt_sh_rings(struct bnxt *bp) +{ + bp->cp_nr_rings = min_t(int, bp->tx_nr_rings_per_tc, bp->rx_nr_rings); + bp->rx_nr_rings = bp->cp_nr_rings; + bp->tx_nr_rings_per_tc = bp->cp_nr_rings; + bp->tx_nr_rings = bnxt_tx_nr_rings(bp); +} + +static int bnxt_set_dflt_rings(struct bnxt *bp, bool sh) +{ + int dflt_rings, max_rx_rings, max_tx_rings, rc; + int avail_msix; + + if (!bnxt_can_reserve_rings(bp)) + return 0; + + if (sh) + bp->flags |= BNXT_FLAG_SHARED_RINGS; + dflt_rings = is_kdump_kernel() ? 1 : netif_get_num_default_rss_queues(); + /* Reduce default rings on multi-port cards so that total default + * rings do not exceed CPU count. + */ + if (bp->port_count > 1) { + int max_rings = + max_t(int, num_online_cpus() / bp->port_count, 1); + + dflt_rings = min_t(int, dflt_rings, max_rings); + } + rc = bnxt_get_dflt_rings(bp, &max_rx_rings, &max_tx_rings, sh); + if (rc) + return rc; + bp->rx_nr_rings = min_t(int, dflt_rings, max_rx_rings); + bp->tx_nr_rings_per_tc = min_t(int, dflt_rings, max_tx_rings); + if (sh) + bnxt_trim_dflt_sh_rings(bp); + else + bp->cp_nr_rings = bp->tx_nr_rings_per_tc + bp->rx_nr_rings; + bp->tx_nr_rings = bnxt_tx_nr_rings(bp); + + avail_msix = bnxt_get_max_func_irqs(bp) - bp->cp_nr_rings; + if (avail_msix >= BNXT_MIN_ROCE_CP_RINGS) { + int ulp_num_msix = min(avail_msix, bp->ulp_num_msix_want); + + bnxt_set_ulp_msix_num(bp, ulp_num_msix); + bnxt_set_dflt_ulp_stat_ctxs(bp); + } + + rc = __bnxt_reserve_rings(bp); + if (rc && rc != -ENODEV) + netdev_warn(bp->dev, "Unable to reserve tx rings\n"); + bp->tx_nr_rings_per_tc = bnxt_tx_nr_rings_per_tc(bp); + if (sh) + bnxt_trim_dflt_sh_rings(bp); + + /* Rings may have been trimmed, re-reserve the trimmed rings. */ + if (bnxt_need_reserve_rings(bp)) { + rc = __bnxt_reserve_rings(bp); + if (rc && rc != -ENODEV) + netdev_warn(bp->dev, "2nd rings reservation failed.\n"); + bp->tx_nr_rings_per_tc = bnxt_tx_nr_rings_per_tc(bp); + } + if (BNXT_CHIP_TYPE_NITRO_A0(bp)) { + bp->rx_nr_rings++; + bp->cp_nr_rings++; + } + if (rc) { + bp->tx_nr_rings = 0; + bp->rx_nr_rings = 0; + } + return rc; +} + +static int bnxt_init_dflt_ring_mode(struct bnxt *bp) +{ + int rc; + + if (bp->tx_nr_rings) + return 0; + + bnxt_ulp_irq_stop(bp); + bnxt_clear_int_mode(bp); + rc = bnxt_set_dflt_rings(bp, true); + if (rc) { + if (BNXT_VF(bp) && rc == -ENODEV) + netdev_err(bp->dev, "Cannot configure VF rings while PF is unavailable.\n"); + else + netdev_err(bp->dev, "Not enough rings available.\n"); + goto init_dflt_ring_err; + } + rc = bnxt_init_int_mode(bp); + if (rc) + goto init_dflt_ring_err; + + bp->tx_nr_rings_per_tc = bnxt_tx_nr_rings_per_tc(bp); + + bnxt_set_dflt_rfs(bp); + +init_dflt_ring_err: + bnxt_ulp_irq_restart(bp, rc); + return rc; +} +``` diff --git a/tasks/csa159/pair_147676/pre_functions.txt b/tasks/csa159/pair_147676/pre_functions.txt new file mode 100644 index 0000000000000000000000000000000000000000..606ba72f978863e480e4ddb704a28d2f58548a43 --- /dev/null +++ b/tasks/csa159/pair_147676/pre_functions.txt @@ -0,0 +1,242 @@ +### File: drivers/net/ethernet/broadcom/bnxt/bnxt.c +```c +static int bnxt_set_xps_mapping(struct bnxt *bp) +{ + int numa_node = dev_to_node(&bp->pdev->dev); + unsigned int q_idx, map_idx, cpu, i; + const struct cpumask *cpu_mask_ptr; + int nr_cpus = num_online_cpus(); + cpumask_t *q_map; + int rc = 0; + + q_map = kcalloc(bp->tx_nr_rings_per_tc, sizeof(*q_map), GFP_KERNEL); + if (!q_map) + return -ENOMEM; + + /* Create CPU mask for all TX queues across MQPRIO traffic classes. + * Each TC has the same number of TX queues. The nth TX queue for each + * TC will have the same CPU mask. + */ + for (i = 0; i < nr_cpus; i++) { + map_idx = i % bp->tx_nr_rings_per_tc; + cpu = cpumask_local_spread(i, numa_node); + cpu_mask_ptr = get_cpu_mask(cpu); + cpumask_or(&q_map[map_idx], &q_map[map_idx], cpu_mask_ptr); + } + + /* Register CPU mask for each TX queue except the ones marked for XDP */ + for (q_idx = 0; q_idx < bp->dev->real_num_tx_queues; q_idx++) { + map_idx = q_idx % bp->tx_nr_rings_per_tc; + rc = netif_set_xps_queue(bp->dev, &q_map[map_idx], q_idx); + if (rc) { + netdev_warn(bp->dev, "Error setting XPS for q:%d\n", + q_idx); + break; + } + } + + kfree(q_map); + + return rc; +} + +static int __bnxt_open_nic(struct bnxt *bp, bool irq_re_init, bool link_re_init) +{ + int rc = 0; + + netif_carrier_off(bp->dev); + if (irq_re_init) { + /* Reserve rings now if none were reserved at driver probe. */ + rc = bnxt_init_dflt_ring_mode(bp); + if (rc) { + netdev_err(bp->dev, "Failed to reserve default rings at open\n"); + return rc; + } + } + rc = bnxt_reserve_rings(bp, irq_re_init); + if (rc) + return rc; + + rc = bnxt_alloc_mem(bp, irq_re_init); + if (rc) { + netdev_err(bp->dev, "bnxt_alloc_mem err: %x\n", rc); + goto open_err_free_mem; + } + + if (irq_re_init) { + bnxt_init_napi(bp); + rc = bnxt_request_irq(bp); + if (rc) { + netdev_err(bp->dev, "bnxt_request_irq err: %x\n", rc); + goto open_err_irq; + } + } + + rc = bnxt_init_nic(bp, irq_re_init); + if (rc) { + netdev_err(bp->dev, "bnxt_init_nic err: %x\n", rc); + goto open_err_irq; + } + + bnxt_enable_napi(bp); + bnxt_debug_dev_init(bp); + + if (link_re_init) { + mutex_lock(&bp->link_lock); + rc = bnxt_update_phy_setting(bp); + mutex_unlock(&bp->link_lock); + if (rc) { + netdev_warn(bp->dev, "failed to update phy settings\n"); + if (BNXT_SINGLE_PF(bp)) { + bp->link_info.phy_retry = true; + bp->link_info.phy_retry_expires = + jiffies + 5 * HZ; + } + } + } + + if (irq_re_init) { + udp_tunnel_nic_reset_ntf(bp->dev); + rc = bnxt_set_xps_mapping(bp); + if (rc) + netdev_warn(bp->dev, "failed to set xps mapping\n"); + } + + if (bp->tx_nr_rings_xdp < num_possible_cpus()) { + if (!static_key_enabled(&bnxt_xdp_locking_key)) + static_branch_enable(&bnxt_xdp_locking_key); + } else if (static_key_enabled(&bnxt_xdp_locking_key)) { + static_branch_disable(&bnxt_xdp_locking_key); + } + set_bit(BNXT_STATE_OPEN, &bp->state); + bnxt_enable_int(bp); + /* Enable TX queues */ + bnxt_tx_enable(bp); + mod_timer(&bp->timer, jiffies + bp->current_interval); + /* Poll link status and check for SFP+ module status */ + mutex_lock(&bp->link_lock); + bnxt_get_port_module_status(bp); + mutex_unlock(&bp->link_lock); + + /* VF-reps may need to be re-opened after the PF is re-opened */ + if (BNXT_PF(bp)) + bnxt_vf_reps_open(bp); + bnxt_ptp_init_rtc(bp, true); + bnxt_ptp_cfg_tstamp_filters(bp); + if (BNXT_SUPPORTS_MULTI_RSS_CTX(bp)) + bnxt_hwrm_realloc_rss_ctx_vnic(bp); + bnxt_cfg_usr_fltrs(bp); + return 0; + +open_err_irq: + bnxt_del_napi(bp); + +open_err_free_mem: + bnxt_free_skbs(bp); + bnxt_free_irq(bp); + bnxt_free_mem(bp, true); + return rc; +} + +static void bnxt_trim_dflt_sh_rings(struct bnxt *bp) +{ + bp->cp_nr_rings = min_t(int, bp->tx_nr_rings_per_tc, bp->rx_nr_rings); + bp->rx_nr_rings = bp->cp_nr_rings; + bp->tx_nr_rings_per_tc = bp->cp_nr_rings; + bp->tx_nr_rings = bp->tx_nr_rings_per_tc; +} + +static int bnxt_set_dflt_rings(struct bnxt *bp, bool sh) +{ + int dflt_rings, max_rx_rings, max_tx_rings, rc; + int avail_msix; + + if (!bnxt_can_reserve_rings(bp)) + return 0; + + if (sh) + bp->flags |= BNXT_FLAG_SHARED_RINGS; + dflt_rings = is_kdump_kernel() ? 1 : netif_get_num_default_rss_queues(); + /* Reduce default rings on multi-port cards so that total default + * rings do not exceed CPU count. + */ + if (bp->port_count > 1) { + int max_rings = + max_t(int, num_online_cpus() / bp->port_count, 1); + + dflt_rings = min_t(int, dflt_rings, max_rings); + } + rc = bnxt_get_dflt_rings(bp, &max_rx_rings, &max_tx_rings, sh); + if (rc) + return rc; + bp->rx_nr_rings = min_t(int, dflt_rings, max_rx_rings); + bp->tx_nr_rings_per_tc = min_t(int, dflt_rings, max_tx_rings); + if (sh) + bnxt_trim_dflt_sh_rings(bp); + else + bp->cp_nr_rings = bp->tx_nr_rings_per_tc + bp->rx_nr_rings; + bp->tx_nr_rings = bp->tx_nr_rings_per_tc; + + avail_msix = bnxt_get_max_func_irqs(bp) - bp->cp_nr_rings; + if (avail_msix >= BNXT_MIN_ROCE_CP_RINGS) { + int ulp_num_msix = min(avail_msix, bp->ulp_num_msix_want); + + bnxt_set_ulp_msix_num(bp, ulp_num_msix); + bnxt_set_dflt_ulp_stat_ctxs(bp); + } + + rc = __bnxt_reserve_rings(bp); + if (rc && rc != -ENODEV) + netdev_warn(bp->dev, "Unable to reserve tx rings\n"); + bp->tx_nr_rings_per_tc = bp->tx_nr_rings; + if (sh) + bnxt_trim_dflt_sh_rings(bp); + + /* Rings may have been trimmed, re-reserve the trimmed rings. */ + if (bnxt_need_reserve_rings(bp)) { + rc = __bnxt_reserve_rings(bp); + if (rc && rc != -ENODEV) + netdev_warn(bp->dev, "2nd rings reservation failed.\n"); + bp->tx_nr_rings_per_tc = bp->tx_nr_rings; + } + if (BNXT_CHIP_TYPE_NITRO_A0(bp)) { + bp->rx_nr_rings++; + bp->cp_nr_rings++; + } + if (rc) { + bp->tx_nr_rings = 0; + bp->rx_nr_rings = 0; + } + return rc; +} + +static int bnxt_init_dflt_ring_mode(struct bnxt *bp) +{ + int rc; + + if (bp->tx_nr_rings) + return 0; + + bnxt_ulp_irq_stop(bp); + bnxt_clear_int_mode(bp); + rc = bnxt_set_dflt_rings(bp, true); + if (rc) { + if (BNXT_VF(bp) && rc == -ENODEV) + netdev_err(bp->dev, "Cannot configure VF rings while PF is unavailable.\n"); + else + netdev_err(bp->dev, "Not enough rings available.\n"); + goto init_dflt_ring_err; + } + rc = bnxt_init_int_mode(bp); + if (rc) + goto init_dflt_ring_err; + + bp->tx_nr_rings_per_tc = bp->tx_nr_rings; + + bnxt_set_dflt_rfs(bp); + +init_dflt_ring_err: + bnxt_ulp_irq_restart(bp, rc); + return rc; +} +``` diff --git a/tasks/csa159/pair_147676/task_prompt.md b/tasks/csa159/pair_147676/task_prompt.md new file mode 100644 index 0000000000000000000000000000000000000000..cde1e3173ef2fda7bfd7ad9902d2082d56c1c043 --- /dev/null +++ b/tasks/csa159/pair_147676/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_148175/checker_template.cpp b/tasks/csa159/pair_148175/checker_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8a2714fe15d25748ec1f338c809a5629e30e6bfb --- /dev/null +++ b/tasks/csa159/pair_148175/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;