From d9727b1d3ae9faf94d3082db876129213b07d130 Mon Sep 17 00:00:00 2001 From: Druzhkov Sergei Date: Tue, 1 Dec 2026 12:34:11 +0300 Subject: [PATCH] Document extensible static checker proposal --- docs/check/DESIGN.md | 106 ++++++++++++++++++++++++++++++ docs/check/EDGE_CASES.md | 76 ++++++++++++++++++++++ docs/check/IMPLEMENTATION.md | 117 ++++++++++++++++++++++++++++++++++ docs/check/INTERPROCEDURAL.md | 82 ++++++++++++++++++++++++ docs/check/README.md | 15 +++++ docs/check/RULES.md | 55 ++++++++++++++++ 6 files changed, 451 insertions(+) create mode 100644 docs/check/DESIGN.md create mode 100644 docs/check/EDGE_CASES.md create mode 100644 docs/check/IMPLEMENTATION.md create mode 100644 docs/check/INTERPROCEDURAL.md create mode 100644 docs/check/README.md create mode 100644 docs/check/RULES.md diff --git a/docs/check/DESIGN.md b/docs/check/DESIGN.md new file mode 100644 index 00000000..f99b2863 --- /dev/null +++ b/docs/check/DESIGN.md @@ -0,0 +1,106 @@ +# Static checker design + +The checker pass answers questions about the state immediately before an operation, using facts from the current function and its resolved call contexts. It checks whether an evaluated pointer access can receive null and whether a release can consume an object already released. The same program points, pointer values, and model resolution support both checks. + +## Pipeline + +Run checks after call resolution and before SQLite export. The Andersen solver continues to provide flow-insensitive may-alias information and candidate callees. The checker computes its own state over the CFG. A PAG location can represent multiple runtime objects, and an empty points-to set establishes neither nullness nor absence of an alias. Use candidate alias information to conservatively invalidate state. Base definite pointer identity on evidence in the checker state. [Analysis properties](../ANALYSIS.md#properties) · [Pointer analysis](../POINTERS.md) + +```mermaid +flowchart LR + Lower["Lower typed operations and call sites"] --> Merge["Merge body variants"] + Merge --> Solve["Build PAG and solve"] + Merge --> Check["Run enabled checks"] + Solve --> Check + Models["Function models"] --> Solve + Models --> Check + Solve --> Export["Export SQLite"] + Check --> Export +``` + +Keep check graphs and their state opt-in. Use a read-only view of source-level invocation targets and selected alias facts. The first implementation tracks local copies, transfers known identities and exact exposed slots across calls, and invalidates escaped state conservatively. If a later check needs PAG aliases, project the selected facts while solver state is available, keeping that projection independent of debug export. [Invocation targets](INTERPROCEDURAL.md#synchronous-call-candidates) · [Solver result and options](../../crates/trace-analysis/src/solver.rs) + +## Operation graph + +Extend the node-ownership mechanism in `CfgRecorder` to record operations during lowering and place them using the existing CFG traversal. Use a checker graph in `trace-ir` owned by a function body variant. Project the call-sequencing graph from the shared traversal before applying its existing call-only compaction and deduplication. Checker graph compaction must preserve operation order, predicates, and gap coverage. [CFG builder](../../crates/trace-parse/src/cfg_build.rs) · [Call sequencing representation](../USAGE.md#representation) + +| Initial IR | Required semantics | +| --- | --- | +| Local assignment | Typed destination and source, including pointer copies, addresses, explicit null, and temporaries. Bind the value computed at the evaluation point. Commit a new binding only on a successor where the store executed. | +| Pointer access | Evaluated raw-pointer read or write through `*`, `->`, or a supported subscript. Carry the pointer operand and source span even when the existing PAG lowering emits no corresponding load or store. | +| Invocation | One occurrence with explicit actuals, optional result, and alternative `CallSiteId` records. Synthetic IPC edges have no synchronous invocation effect. | +| Allocation and release | Ordinary C++ `new` and `delete` for trivial objects, including scalar and array forms. Throwing `new` produces a non-null pointer on normal completion. A null `delete` operand leaves resource state alone. Library acquisitions and releases enter via invocation effects. | +| Predicates and exits | True and false edges carry typed tests on values evaluated at the branch. Start with truthiness and null equality or inequality. Retain short-circuit evaluation, loop back edges, return operands, exceptional outcomes, and ordered handler types. | +| Coverage gaps | Mark unsupported or omitted operations, unresolved control flow, and operand order the checker cannot evaluate precisely. Skip operations in unevaluated operands. | + +Use graph-local typed operation and block IDs. Keep original source spans from LineMap, including columns. For calls written in macro replacement lists, preserve spelling and expansion spans and use the expansion for execution ownership. Two operations can share a source span, so event identity comes from lowering and graph placement. Classify each operand's evaluation from its syntax, types, and language mode. The existing call-only walk classifies some operands by their recorded call sites, which provides no evaluation evidence for an expression containing zero calls. [Call source locations](../ANALYSIS.md#call-source-locations) · [CFG operand handling](../../crates/trace-parse/src/cfg_build.rs) · [Sequencing gaps](../USAGE.md#boundaries-and-gaps) + +Preserve the distinction between sequenced operations, indeterminately sequenced operand groups, and unsequenced effects. For the first release, evaluate independent operands in a stable order when their read, write, and control effects commute. For interacting operands without a guaranteed order, invalidate affected facts and mark the group partial. Any later enumeration must preserve each language's operand grouping and sequencing rules. [C11 draft, clauses 5.1.2.3 and 6.5](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) · [C++17 draft, sections on execution and calls](https://www.open-std.org/JTC1/SC22/WG21/docs/papers/2017/n4659.pdf) + +Remap checker graphs with the unit's function, variable, call-site, and file maps. Use the existing body retention rules for dependency roots, discarded duplicates, and suppressed weak definitions. Compare the remapped operations, operands, predicates, call bindings, and gaps when deduplicating body variants. Identical call projections can represent different checker graphs. Analyze each retained variant within its link target and record its owner and configuration identity in findings. Apply post-merge replacement and alternative-site updates to the checker invocation through the same occurrence ownership used by sequencing. A dropped operand or call record leaves an explicit gap where the graph depended on it. The graph owns the minimal operands it needs after PAG construction. [Sequencing merge](../USAGE.md#merge) · [Unit merge](../../crates/trace-parse/src/merge.rs) · [Program lifecycle](../../crates/trace-ir/src/program.rs) + +## Abstract state and rule interface + +Use a forward worklist with a bounded abstract state. Track unreachable control flow separately from reachable states containing unknown values. Branch refinement intersects the current value with the test on that edge. An assignment replaces the value of a known local destination. An indirect write updates every affected candidate conservatively when its target is ambiguous. A join keeps facts sound across predecessors. In particular, a definite fact must hold on every represented incoming alternative. [Clang dataflow analysis](https://clang.llvm.org/docs/DataFlowAnalysisIntro.html) + +- **Pointer values.** Track null, non-null addresses or resource identities where known, and unknown values. Recognize null constants in pointer contexts, including C++ `nullptr` and typed uses of C `NULL` or zero. Keep nullable allocation success and failure separate so only success creates a live object. +- **Resource values.** Track a resource kind, an identity in the current abstract state, and live, released, or unknown lifetime state. Copies carry the same identity, including copies passed as arguments. Distinguish a proven release-compatible base pointer from an interior, one-past, or unknown offset. An address or PAG location may be reused across acquisitions. Exact identities require an acquisition proven to execute at most once in the analyzed activation, accounting for repeatable call sites. A resource acquired before a loop can still be released twice inside it. Reassigning a pointer changes that pointer's value while other aliases retain their identity. [C11 draft, clause 7.22.3](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) · [C++ deallocation](https://eel.is/c++draft/expr.delete) +- **Bounded alternatives.** Retain a small number of distinct states at a program point so a branch predicate and its effects can stay correlated across a join. On overflow, widen at that point to a merged state and keep it in merged mode for the rest of the solve. Start with a per-point cap of eight alternatives and a per-body limit of 50,000 transfers, subject to corpus measurement. Treat widening that loses required evidence as a coverage reason. +- **Unknown effects.** An unmodeled call receiving a pointer by value can affect its reachable object. A call that sees a local slot through a pointer or reference may change the slot. Previously escaped aliases may be reachable by a later call with zero arguments. Invalidate the reachable state the call may change and preserve independent facts such as an unescaped local pointer's binding. After a gap that could add unknown predecessors, withhold definite confidence wherever the gap could bypass a proof. If those destinations cannot be bounded, mark the variant incomplete and withhold its findings. + +Keep the rule interface internal to `trace-analysis` initially. A registered rule declares its ID, subscribed operations or exits, and required domains. It evaluates a pre-operation state and returns a violation predicate and evidence requirements. Shared domain code owns transfer and branch refinement, including termination of an alternative after a modeled operation that establishes undefined behavior. Rule selection controls reporting. For a new stateful rule, add a domain with an initial state, transfers, and a join. Keep worklist scheduling, effect application, coverage accounting, and finding emission common. [Clang's transfer and branch interfaces](https://clang.llvm.org/doxygen/DataflowAnalysis_8h_source.html) + +Replay subscribed operations against the converged states to produce findings. Record a bounded provenance chain through the transfers that supplied the relevant facts. Retain branch outcomes, assignments or copies, and the acquisition or prior release as applicable. Compare only abstract facts for convergence, and select equivalent provenance deterministically. For a possible finding, require supporting facts from one consistent retained alternative. Trace truncation may shorten that explanation, but the evidence must still identify the operation and the fact that violates its contract. + +## C++ declaration signatures + +Exact checker contracts require two earlier decisions to be correct. Registration must keep distinct overloads in separate `Function` entries, and call resolution must select the appropriate entry. Today the flow type `TypeDesc::Ptr` erases pointer qualifications, and `Function::reference_params` records whether a parameter binds a reference. A declaration of `pool_free(int *)` can therefore absorb the definition of `pool_free(const int *)`. Matching a contract after that merge has already lost the distinction. [Type representation](../../crates/trace-ir/src/types.rs) · [Symbol registration](../../crates/trace-ir/src/symbol.rs) + +1. **Represent declaration types.** In `trace-ir`, add a shared declaration signature to function metadata. Each explicit parameter records its declared type shape before reference-to-address lowering, const and volatile qualification at the represented type layers, and whether it is a value, lvalue reference, or rvalue reference. Reuse interned type shapes and resolve the signature once per declaration. Record member qualification and variadic shape in that same view. Use explicit unknown metadata for declarations the parser cannot characterize. The PAG consumes flow types, and call wiring obtains its reference-binding flag from the declaration metadata where available. +2. **Lower and normalize signatures.** Use the same declarator lowering for prototypes and definitions, including unnamed parameters and out-of-class definitions. Capture qualifications and reference kinds before building flow types, even when the TU has only one declaration of a name. Resolve aliases and reference collapsing. Apply the language's parameter adjustments, including array/function decay and removal of top-level cv on by-value parameters. Preserve pointee and referent qualification. The canonical signature compares `int *const` and `int *` as the same by-value parameter, while `const int *`, `T &`, and `T &&` retain their distinctions. Use explicit parameter positions that exclude the implicit object argument and preserve pack boundaries. [Parameter type adjustments](https://eel.is/c++draft/dcl.fct) · [References and reference collapsing](https://eel.is/c++draft/dcl.ref) +3. **Use one signature view for symbol identity.** Extend the existing `SymbolTable::explicit_params` view and use it in `redeclaration_compatible` and signature-aware redirects and override matching. Reject known qualification or reference-kind mismatches before any tolerant spelling or arity fallback. Keep scope, C linkage, target ownership, and weak-definition selection in the existing resolver. Remap signature types with the unit's type map before registration and preserve them when a declaration adopts a definition, including shared-header and target merge. Track unresolved identity when information is insufficient to establish which overload owns a body. Carry the supported signature distinctions through exported linking facts for signature-aware reconstruction, with older facts represented as incomplete where they lack this metadata. [Link targets and weak symbols](../ANALYSIS.md#link-targets-and-weak-symbols) · [Linking metadata compatibility](../SQLITE_SCHEMA.md#version-and-capability-contract) +4. **Rank the call using its actuals.** In `trace-parse`, extend the argument description consumed by `viable_overloads` and `rank_overloads` with qualification and value category. Reuse expression typing for locals, casts, and reference-returning expressions. For supported standard conversions, distinguish identity from an added pointer qualification, reject known invalid qualifications and reference bindings, and use lvalue or rvalue category to rank `T &` and `T &&`. A named rvalue-reference variable is an lvalue when used by name. Keep viable candidates when argument metadata is incomplete. Carry that ambiguity to the checker when it affects the transfer. Use the same ranking for call targets and call result typing. [Overload code](../../crates/trace-parse/src/lower.rs) · [Conversion ranking](https://eel.is/c++draft/over.ics.rank) · [Reference binding](https://eel.is/c++draft/over.ics.ref) + +## Function effects + +Extend `FnModelSet` and the existing `--models` loader with checker contracts in a separate `[[check_model]]` table. Ordinary `[[model]]` entries replace the same-name solver model. Separate registration lets checker contracts be overridden or disabled independently. Use the shared scope and link-target resolver to identify candidate declarations, then match each contract by qualified name and exact signature. Apply library contracts only to applicable library declarations or explicitly configured equivalents. Treat user-declared contracts as analysis assumptions and record the selected contract in evidence. [Function model matching and configuration](../MODELS.md#model-matching) · [Model registration code](../../crates/trace-analysis/src/summaries.rs) + +The required `signature.params` array lists explicit parameter types in order. Use `[]` for a zero-parameter declaration. Optional `variadic`, `member_cv`, and `member_ref` fields default to non-variadic and unqualified. Resolve each selector in the declaration's scope and compare it against the shared [declaration signature](#c-declaration-signatures). Validate effect indices against the selected declaration. A missing or unsupported signature prevents an exact model match. Infer from a body when its binding is established. When overload selection itself is uncertain, keep the applicable alternatives and an opaque outcome for missing candidates. Later files replace the same qualified-name and canonical-signature entry. An empty effect list disables that exact entry and permits body inference. + +| Effect | Transfer | +| --- | --- | +| Acquire | A successful result produces a live resource identity of a named kind. Specify the failure value or outcome when applicable. | +| Release | Check the named argument's identity and state, then transition the resource on a valid release. Specify the resource kind and what null or another invalid sentinel means for the API. | +| Require non-null | Check a pointer argument at entry. Then apply the call's inferred or modeled post-call effects, or opaque invalidation when the effects are unknown. | + +Preconditions run before transfer. A precondition-only model uses the retained body when eligible and otherwise invalidates the opaque call's reachable footprint. A replacement transfer requires `complete_effects = true` and an explicit supported outcome description. This is a claim that the declared effects cover the relevant return, resource transitions, and writes, with no additional tracked writes. It also states whether the call can throw. A precondition alone cannot supply that transfer. Select one transfer for each target so the engine applies a release only once. [Call transfer](INTERPROCEDURAL.md#call-transfer-and-summary) + +A project can describe a custom pool with the proposed TOML fields below. The release effect binds to explicit parameter zero on the `int *` overload. An overload taking `const int *` can have its own contract or use body inference. + +```toml +version = 1 + +[[check_model]] +name = "project::pool_alloc" +signature = { params = [] } +complete_effects = true +may_throw = false +effects = [{ kind = "acquire", resource = "project_pool", failure = "null" }] + +[[check_model]] +name = "project::pool_free" +signature = { params = ["int *"] } +complete_effects = true +may_throw = false +effects = [{ kind = "release", resource = "project_pool", param = 0, null = "noop" }] +``` + +Apply each target and outcome to the same evaluated argument state before joining successors. The first release infers effects from resolved synchronous callees with retained bodies and supports complete contracts for external APIs and overrides. Unresolved, unsupported, and budget-limited cases use conservative fallbacks with coverage reasons. [Interprocedural design](INTERPROCEDURAL.md#call-transfer-and-summary) · [Execution contexts](../MODELS.md#execution-contexts) + +## Findings and coverage + +- **Definite** means the violation holds on every reachable incoming abstract alternative at the operation in the analyzed body or call context, with modeled control flow and complete facts needed for the proof. For double free this includes the same resource identity and prior release. +- **Possible** means a retained, consistent abstract alternative supports the violation, while other incoming states or coverage prevent the definite claim. Include the evidence and a reason when relevant precision was lost. An abstract alternative may still be infeasible in the full program. +- **Incomplete coverage** records the applicable limit by rule and body variant, with an operation when available. Track gaps separately from abstract values so an independent, fully supported proof can survive an unrelated gap. Unknown input alone supplies no violation evidence. Withhold findings for a body stopped before convergence and for an unbounded control-flow gap. The [edge-case matrix](EDGE_CASES.md) specifies how the initial rules handle these conditions. + +Use original spans, a rule ID, a confidence level, body identity, proof scope, and ordered evidence steps. Keep deterministic evidence and ordering across job counts. Expose findings and coverage through a shared SQLite export and inspect API, with a capability marker for enabled rule IDs. This supports a distinct result for a completed run with zero findings, a partial run, and a database built without checks. [Cross-call evidence](INTERPROCEDURAL.md#findings-across-calls) · [Implementation plan](IMPLEMENTATION.md) diff --git a/docs/check/EDGE_CASES.md b/docs/check/EDGE_CASES.md new file mode 100644 index 00000000..d9b4b779 --- /dev/null +++ b/docs/check/EDGE_CASES.md @@ -0,0 +1,76 @@ +# Static checker edge cases + +This matrix defines the first release's behavior for `null-deref` and `double-free` and provides regression cases for the shared framework. **Complete** means the selected rule covered the relevant operations in its advertised subset. **Partial** means a named limit affected coverage. A partial body can still produce a finding at an independent operation when the proof and reachability are supported. The [design](DESIGN.md#findings-and-coverage) defines confidence and when to withhold findings. + +## Pointer values and evaluated operations + +| Case | Required behavior | +| --- | --- | +| Typed `nullptr`, literal zero, and macro-expanded C `NULL` | Recognize supported null pointer conversions under the TU's language and standard. Keep the expanded operand and source provenance. A macro named `NULL` with an unrecognized value and an arbitrary integer-to-pointer cast supply no null evidence. | +| Unknown parameter, uninitialized local, and unmodeled return | Keep unknown values distinct from explicit null and unreachable state. Mark a relevant missing return contract partial. An uninitialized read belongs to its own rule. Track an uninitialized pointer as unknown with a coverage reason where needed. | +| Copies, casts, and updates | Copy the evaluated value, including its resource identity when known. A cast preserves identity only for a supported address-preserving conversion. A write to one slot leaves value copies in other slots intact. References to the same slot observe the write. A later guard refines the tested value at that point. | +| Attachment of a guard to stale state | In `if (p) { p = nullptr; return *p; }`, report a definite finding at the dereference. In a version that copies `p` after the guard and changes only the original slot, the copy retains its non-null value. | +| Raw reads and writes | Emit a checked access for supported `*p`, `p->field`, and `p[0]`, including scalar destinations and RHS forms with no PAG load or store. A member call with an implicit object or a call through a function pointer needs a dedicated access form or a coverage reason. | +| Address formation and pointer arithmetic | In C, `&*p` evaluates the pointer expression without an indirection. C `&p[i]` uses pointer arithmetic. Keep the arithmetic separate from a memory access. Spellings such as `&p->field`, nonzero offsets, and C++ address formation outside the supported subset get a coverage gap when their semantics are uncertain. | +| Unevaluated expressions with zero calls | Skip raw accesses in plain `sizeof(*p)` for a non-VLA C type, and in C++ `sizeof(*p)`, `decltype(*p)`, and `noexcept(*p)`. Skip the C `_Generic` controlling expression and run only a known selected association. An unresolved association gets partial coverage. | +| Potentially evaluated operands | A C `sizeof` involving variably modified types requires evaluation classification. For C++ `typeid`, distinguish unevaluated operands and evaluation of polymorphic glvalues, including the special exception behavior for null indirection. Record a gap for unresolved VLA or polymorphic cases. | +| Scope, hidden storage, and overloaded operators | Use declaration identity for shadowed locals and nested lambda captures. Globals, local statics, general aggregate fields, volatile or atomic pointer loads, and overloaded pointer-like operators need their own memory or call effects. Unsupported relevant reads become unknown with a coverage reason. | + +[C11 draft, clauses 6.3.2.3, 6.5.1.1, 6.5.3.2, and 6.5.3.4](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) · [C++ evaluation contexts](https://eel.is/c++draft/expr.context) · [C++ type identification](https://eel.is/c++draft/expr.typeid) + +## Control flow and evaluation order + +| Case | Required behavior | +| --- | --- | +| Constant, contradictory, and short-circuit tests | Prune provably unreachable operations. In `p && *p` or `!p \|\| *p`, the RHS sees the non-null alternative. In `!p && *p`, the RHS sees the null alternative. An overloaded logical operator follows its call semantics. | +| Sequenced expressions and assignments | Observe the order in a built-in comma expression and the selected branch of `?:`. Check C++17 assignment operand order separately from C and earlier C++. An explicit release of an already released object ends that supported alternative before subsequent operations. | +| Competing argument effects | In C++17 `consume((p = nullptr), *p)` with an initially live pointer, the arguments can be evaluated in either order. The initial checker marks interference partial and withholds a finding based solely on an assumed order. Also test earlier C++ and C, where conflicting effects may be unsequenced. | +| Loop exits and jumps | Check zero iterations, a back edge, `continue`, `break`, and a switch case with fallthrough. Use the visited predecessor's state and preserve branch alternatives. Model a direct `goto` only when its destination and traversed scope transitions are known. | +| Exceptional successor and cleanup | In `try { p = new int; } catch (...) { ... }`, the handler sees the old binding when allocation throws. A destructor or cleanup that can mutate a tracked pointer or release a resource has an effect when modeled and a gap otherwise. Preserve edges for known `throw` and known nonreturning calls. | +| Ordered exception handlers | Match a known thrown type to the first applicable handler. Preserve an unmatched outcome for outer unwinding. Mark uncertain handler selection partial wherever reachability depends on it. [Exceptional dispatch](INTERPROCEDURAL.md#exceptional-dispatch) | +| Unknown control transfer | Computed `goto`, `setjmp`/`longjmp`, inline assembly with unknown destinations, coroutine suspension, and recovery nodes can introduce predecessor paths absent from the graph. Downgrade affected paths to partial. Withhold the variant's findings if possible re-entry points cannot be bounded. | + +[C++17 draft, sections on execution and evaluation](https://www.open-std.org/JTC1/SC22/WG21/docs/papers/2017/n4659.pdf) · [C++ function-call sequencing](https://eel.is/c++draft/expr.call) · [Pathologist CFG boundaries](../USAGE.md#boundaries-and-gaps) + +## Allocation and release + +| Case | Required behavior | +| --- | --- | +| Nullable allocation | Retain a null failure outcome and a distinct live success outcome. An unchecked `malloc` followed by a supported raw access gives a possible null finding. A null guard removes that outcome from the surviving branch. Only success establishes a resource identity. | +| Null release and overwrite | `free(NULL)` and ordinary `delete` of a null pointer leave resource state alone. A later write of null into one alias leaves the original object's release state available to a previously copied alias. | +| Proven base versus interior pointer | Require a release-compatible base pointer to establish a valid release. Test `p + 1`, a member address, and a one-past pointer followed by `free(p)`. Expect zero double-free findings and the applicable coverage reason. A future invalid-release rule can report the first operation. | +| Wrong family, stack address, and borrowed pointer | A scalar `delete` on an array allocation, `free` on stack storage, or a release of unknown ownership cannot seed a same-object double-free proof. Use a distinct invalid-release rule when available. A matching array `delete[]` follows the normal release contract. | +| Unknown incoming pointer | Two releases of an incoming non-null parameter with unknown allocation provenance have partial coverage in standalone analysis. A known live object imported from a caller supplies the identity and original live state for that context. | +| Repeatable sites and reused addresses | Treat an acquisition inside a CFG cycle as a summary. Releasing once per freshly allocated object in a loop yields zero double-free findings from site equality. Releasing a known pre-loop object twice can produce a finding with back-edge evidence. Different acquisitions may reuse the same address while remaining distinct resource identities. | +| Replacement allocation and other aliases | After `p = allocate()` returns a second object, `p` refers to the replacement. A copy retained before the assignment still refers to the first object. Test both pointers at the next release. | +| C++ allocation variants | Ordinary throwing `new` has a normal live outcome and an exceptional outcome without the initial store. For `new(std::nothrow)`, placement `new`, custom `operator new/delete`, and nontrivial construction or destruction, require a matching effect or record partial coverage. | +| Zero size and resizing | A zero-size `malloc` or `calloc` result can be null or releasable. Neither lifetime nor non-nullness establishes a payload extent. Treat `realloc` as a gap initially. A future model needs correlated success and failure, invalidation of old aliases on success, and the applicable policy for size zero. | + +[C11 draft, clause 7.22.3](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf) · [C++ allocation](https://eel.is/c++draft/expr.new) · [C++ deallocation](https://eel.is/c++draft/expr.delete) + +## Calls and effects + +| Case | Required behavior | +| --- | --- | +| Argument values and results | In `p = replace(p)`, the model sees the evaluated old actual and binds the return value after the call normally completes. Preserve explicit argument positions across missing operands, hidden receivers, and defaults. A required omitted argument or default expression outside the supported subset gets a gap. | +| Shadowing, overloads, and link targets | Use the same selected definition or declaration as resolution in that TU and link target. Test standard global and `std::` forms where provenance establishes the contract, a shadowing project function, a mismatched overload, and a strong definition that replaces a weak one. | +| Two overloads with compatible effect parameters | Declare `project::pool_free(int *)` and define `project::pool_free(const int *)` as a no-op. Keep them distinct through registration and TU merge. Only the mutable overload receives the release contract, even though both arguments satisfy the effect's type requirements. An empty override for its signature leaves any separately configured overload and the solver effects in place. [Signature acceptance cases](IMPLEMENTATION.md#signature-identity-and-call-resolution) | +| Candidate outcomes and partial solve | Calls to a release target and to a no-op target are alternatives. A later release can have a possible finding from the first target, with that target named in evidence. Include an unknown alternative for unresolved indirect or virtual dispatch and where a partial solve cannot establish candidate completeness. | +| Unknown effects and escape | A by-value pointer can expose the pointee without exposing its caller-local slot. A reference or pointer-to-pointer can also expose the slot. A prior store to shared memory can expose an alias to a later call with no pointer arguments. Invalidate those reachable facts. Preserve an independent binding such as a separate local assigned null after the call. | +| Configuration validation and overrides | Reject missing or malformed signature selectors, conflicting contracts for one canonical signature within a file, and invalid parameter indices when the signature is known. An empty checker effect list disables the matching signature and permits eligible body inference. Both a checker override and an empty checker model preserve unrelated solver effects on the same symbol. | +| Preconditions and exposed state | A non-null precondition on an out-parameter applies at entry. The inferred body still writes through that parameter. When the body is unavailable and only the precondition is modeled, invalidate the exposed slot. [Function effects](DESIGN.md#function-effects) | +| Synthetic and asynchronous edges | IPC and task-start edges supply no synchronous memory effect from the remote or deferred body. Record a coverage gap when shared escaped state can be affected. Synchronous wrapper effects, if modeled, still apply at the initiating call. | +| Deferred callable with no execution context | Discard `std::bind(dispose, p)` for a known live allocation, then release `p` once. Verify the graph still has the bind site's reachability edge to `dispose` and no execution context there. The checker excludes that edge from synchronous candidates and reports zero double frees. A companion fixture calls `dispose` through a resolved function pointer and checks that its release takes effect. [Synchronous call candidates](INTERPROCEDURAL.md#synchronous-call-candidates) | + +## Source, merge, and output + +| Case | Required behavior | +| --- | --- | +| Macro provenance and ignored macros | Two effects from one expansion can have the same LineMap position and different operation IDs. Preserve call spelling and outer expansion coordinates where available. A relevant omitted effect in a dependency or ignored macro records a gap. | +| Distinct headers and configurations | Test a header with identical call sequencing but different assignments, equivalent definitions across multiple TUs, and a body compiled under different language modes or link targets. Analyze each distinct retained variant without borrowing an effect from another variant. | +| Post-merge call replacement | If resolution attaches an alternate target or replaces a call record, update each checker invocation by occurrence and leave one invocation transfer. A removed required operand becomes unknown with a gap. | +| Complete, partial, and unavailable export | An enabled rule with zero applicable bodies yields an empty complete result. A disabled or unavailable rule differs from an enabled rule with zero findings. A partial reason is visible even when filtering findings returns zero rows. A marker with missing required structures raises a read error. | +| Deterministic widening and trace truncation | Reorder otherwise equivalent predecessors and target records in an engine fixture. Confidence depends on the state, and equivalent evidence is selected deterministically. Force a trace limit and verify that the evidence retains the primary operation and causative step. A transfer budget stop withholds the stopped body's findings. | +| Unsupported unrelated operation | Put an opaque call before an independent local null assignment and access. Expect a definite null finding if the opaque call cannot re-enter later in the body and the dereference is reachable. The coverage reason still appears for any affected rule and body. | + +Run these as small engine and lowering fixtures and carry representative cases through export and inspection. The [interprocedural fixtures](INTERPROCEDURAL.md#interprocedural-acceptance-fixtures) cover call transfer and context-specific exceptions. The [implementation plan](IMPLEMENTATION.md#acceptance-criteria) adds release-level compatibility, determinism, and corpus checks. diff --git a/docs/check/IMPLEMENTATION.md b/docs/check/IMPLEMENTATION.md new file mode 100644 index 00000000..7200a5de --- /dev/null +++ b/docs/check/IMPLEMENTATION.md @@ -0,0 +1,117 @@ +# Static checker implementation plan + +The first release delivers opt-in interprocedural checks for null dereference and double free, inferred effects for resolved in-tree calls, configurable contracts for external APIs and overrides, and queryable findings. Use-after-free is the extension acceptance test. The [design](DESIGN.md) defines state and confidence. The [interprocedural design](INTERPROCEDURAL.md) defines call transfer and summaries. The [rule catalog](RULES.md) describes follow-up candidates. + +## Milestones + +### 0 Approve scope and capture baselines + +- Obtain explicit design approval for the flow-sensitive checker pass under the [contributor guide](../../AGENTS.md#do-not). Review the operation-level IR boundary, supported calls, summary budgets, variant identity, and the scope of confidence levels. +- Capture the pre-change call graph, arg-flow, PAG, and sequencing outputs for representative fixtures. Record comparable release-build timing and peak memory for canonical HiView and Camera inputs. Use the project's pinned revisions and compiler setup. [Pinned evaluation profiles](../EVAL_REPORT.md#pinned-evaluation-profiles-and-master-comparison--2026-11-19) + +### 1 Correct C++ signature identity and overload resolution + +- Land the [declaration-signature changes](DESIGN.md#c-declaration-signatures) as an independently testable prerequisite for all analyses. Document the signature representation and overload behavior in [IR.md](../IR.md) and [CXX.md](../CXX.md). Add qualified parameter types and reference kinds in `trace-ir`, then capture them from declarations before flow lowering. +- Pass the same canonical signature into registration and call ranking. Teach `SymbolTable::redeclaration_compatible` and related signature comparisons to reject known mismatches even in their tolerant paths. Remap signature types before TU and target registration. Update the linking facts used by `trace-merge` and test current and older metadata against the applicable coverage contract. [Linking metadata](../SQLITE_SCHEMA.md#merger-inputs-and-output) +- Carry argument qualification and value category into `viable_overloads` and `rank_overloads` in `lower.rs`. Test the parameter cases below by extending [cpp_overload_diff.py](../../scripts/cpp_overload_diff.py) and checking the resolved edges against Clang. Run the canonical debug corpus checks and review changed declaration identities, call targets, and their downstream effects. +- Capture the **corrected baseline** with this prerequisite in place before adding the checker pass. Review the prerequisite's output differences against the pre-change baseline and record expected changes and their fixture or corpus evidence. Compare affected relations using semantic identity where overload splitting changes numeric IDs. [Release verification](#release-verification) + +### 2 Lower operations and merge checker graphs + +- Add the graph, typed IDs, operands, and predicates in `trace-ir`. Document the IR in [IR.md](../IR.md) before adding the types. Keep storage proportional to the recorded operations, blocks, and immediate order edges. +- In `trace-parse`, add an opt-in recording flag at the same indexing boundary as call sequencing. Extend `CfgRecorder` to associate typed operations with lowering nodes and to roll back those records with speculative lowering. Use the existing CFG walk for placement and project the call-sequencing view when requested. +- Record local declaration initializers and pointer assignments, evaluated raw-pointer accesses, call inputs and results, allocation and release, branch tests, and exits. Capture thrown types when available and ordered handler descriptors. Begin with plain pointer locals, `*`, raw-pointer `->`, supported subscripts, and C++ scalar and array allocations of trivial objects. Flag class cleanup, overloaded operators, and complex memory operations when they can affect an enabled check. +- Remap checker graphs in unit and target merge, including types used for exception dispatch and post-merge call-site replacements and alternative sites. Preserve variant differences visible in operands, predicates, callee bindings, and gaps. Apply the body retention rules and ensure checker data survives active header and configuration indexing modes. [Unit merge](../../crates/trace-parse/src/merge.rs) · [Existing sequencing merge](../USAGE.md#merge) +- Verify operation ordering, original spans, remapping, and disabled-mode compatibility before relying on the graphs in `trace-analysis`. + +### 3 Implement the engine and function models + +- Put the bounded worklist and domains in a checker module in `trace-analysis`. The engine takes a graph and a read-only context for call resolution and models. Unit tests can construct graphs without parsing or SQLite. +- Implement entry state, local assignment, edge refinement, join, convergence, and coverage accounting. Add identity for acquisitions outside cycles, conservative summary handling within cycles, and invalidation for opaque calls and memory. Use deterministic point and candidate ordering with configurable internal budgets for tests. +- Add and validate selectors against the shared declaration signature from milestone 1. Implement entry preconditions and complete effects in `summaries.rs`. Wire separate `[[check_model]]` registration through `--models` and seed applicable contracts for `malloc`, `calloc`, and `free`. Document contract semantics and per-overload overrides in [MODELS.md](../MODELS.md). +- Use trusted non-null, allocation, and release contracts in focused fixtures. Treat complex effects such as `realloc`, class destructors outside the initial subset, indirect writes with untracked aliases, and calls that may escape synchronously modeled control flow as coverage gaps where they affect the result. + +### 4 Infer effects across function calls + +- Add a call transfer in `trace-analysis` over the solver's source-level candidates. Capture those candidates before callback and IPC augmentation. Preserve target, TU, and configuration scope and group alternative records from one invocation. Apply entry preconditions alongside the selected complete contract, retained body, or opaque memory transfer. [Synchronous call candidates](INTERPROCEDURAL.md#synchronous-call-candidates) +- Map actual raw pointer values, resource identities, and exact exposed slots into formals. Run the same body worklist on the projected input. Return normal and typed or unknown exceptional outcomes with correlated resource and slot effects and coverage. Apply effects to the matching caller and dispatch exceptions by ordered handler matching. [Exceptional dispatch](INTERPROCEDURAL.md#exceptional-dispatch) +- Cache converged summaries by normalized input and retained variant. Bind imported identities back to the caller and instantiate fresh exported identities at the call occurrence. Rebind provenance on every use. Bound call depth, active recursion, distinct contexts per variant, and total transfers with explicit coverage for each fallback. [Summary and budget contract](INTERPROCEDURAL.md#recursion-and-bounded-work) + +### 5 Implement the first rules and verify extension + +- Register `null-deref` on supported evaluated pointer accesses and `double-free` on release effects and supported `delete` operations. Keep the common pointer and resource transfers active for any rule that needs them. +- Generate findings after convergence from pre-operation facts. Carry call and return evidence across summary application, preserve the location of the primary operation, and label contextual findings. If the trace exceeds its storage budget, retain the primary operation, causative step, and any invocation needed to explain the proof scope. +- Register `use-after-free` as an extension check. Its implementation should add the rule predicate, evidence selection, and fixtures using the existing access and release state. This milestone demonstrates extension through the checker interface before committing to a public plugin API. + +### 6 Wire the CLI and export + +- In `trace-cli`, add an opt-in rule list and an inspection command. A proposed interface is `trace analyze --checks null-deref,double-free -o ` and `trace inspect checks --rule double-free --format json`. Validate names before indexing and deduplicate selections deterministically. Enable checker recording independently of `--sequencing`. +- Run the pass from the analysis API after the Andersen solve. Return typed results to callers and leave rendering and storage to the CLI and database layers. Existing C ABI entry points keep their current behavior and contracts during the first release. +- In `trace-db`, add optional `check_findings`, `check_evidence`, and `check_coverage` relations and a marker with enabled rule IDs and run status in `analysis_run.options_json`. Keep findings joinable to the complete function relation, including lambda bodies. A finding stores rule ID, confidence, proof scope, owner, variant, operation ID within that variant, original span, and message. Evidence rows store an ordered role, span, and detail, including invocation and return steps when applicable. Coverage rows identify the affected rule, body, context or call boundary when applicable, reason, and operation when available. Write the marker and relations in the existing export transaction in both minimal and full modes. [SQLite capability contract](../SQLITE_SCHEMA.md#version-and-capability-contract) +- Return status, findings, and applicable coverage in structured inspection output. A rule filter selects the rule's coverage as well as its findings. Confidence and source filters can hide findings without changing whether the selected rule ran or encountered a gap. Distinguish disabled or unavailable, completed with zero findings, and partial. Treat inconsistent markers and tables as a read error. Initial `trace-merge` outputs have check capability unavailable because the merged database represents reconstructed call graphs. Document flags and semantics in the [root README](../../README.md) and [schema reference](../SQLITE_SCHEMA.md). + +### 7 Evaluate and expand + +- Run the acceptance cases below, workspace tests, and canonical debug evaluation. Compare checked and unchecked exports at fixed inputs and options. Record corpus timing, incremental peak memory, finding counts by rule and confidence, cache reuse, and context, depth, and transfer cutoffs in [EVAL_REPORT.md](../EVAL_REPORT.md). +- Review a reproducible sample by rule and confidence on both corpora. Record confirmed problems, false positives, and cases requiring context. Investigate uncorrelated evidence and false definite findings before expanding the supported subset. +- After the extension test, add a null-argument rule that uses entry preconditions and an allocation-family mismatch rule. Try modeled streams next. Use reviewed false negatives to prioritize richer alias and ownership effects, indirect call coverage, or fixpoint summaries for recursive call-graph components. + +## Acceptance criteria + +Each positive fixture checks the exact rule, body variant, original source line and column, confidence, proof scope, and required evidence. Each clean fixture checks for zero relevant findings and the expected coverage status. Each fallback fixture checks the affected rule and reason and whether evidence survives independently of the gap. Cover the [edge-case matrix](EDGE_CASES.md) and [interprocedural fixtures](INTERPROCEDURAL.md#interprocedural-acceptance-fixtures) at the lowest layer that can verify them. Carry a contextual callee finding and a caller finding caused by an inferred effect across TUs through the CLI and SQLite. Use test-local scratch trees and databases as specified in the [contributor guide](../../AGENTS.md#tests). + +### Signature identity and call resolution + +| Fixture | Expected result | +| --- | --- | +| Declare `project::pool_free(int *)` and define the no-op `project::pool_free(const int *)`. Add both complete definitions in a companion fixture. Exercise same-TU and cross-TU registration and repeat with checks disabled. | Distinct `FnId` values and the correct declaration or body ownership. Mutable and const pointer actuals resolve to the same overloads as Clang. Apply the release contract only to the mutable overload, and verify a per-signature override or disable. | +| Declare `f(T &)` and `f(T &&)` and define them in another TU. Call with a named object, a named rvalue-reference variable, a temporary, and an xvalue cast. | The prototypes merge with their own definitions and the calls agree with Clang. The two named arguments select the lvalue overload. The temporary and xvalue select the rvalue overload. A contract for one reference kind binds only to that overload. | +| Redeclare a by-value `int *` parameter as `int *const`. Repeat with an alias for the pointer type, adjusted array parameters, and a reference alias that collapses to an lvalue reference. | Each equivalent redeclaration retains one function identity. Pointee or referent qualifications and uncollapsed reference-kind differences distinguish overloads. | +| Compare qualification addition, invalid qualifier removal, and a call whose qualified actual or reference category is unknown. | Known calls select the same overload as Clang, including an exact mutable pointer match over a qualification conversion. Uncertain calls retain applicable candidates and incomplete coverage wherever a missing candidate could affect a finding. | +| Reconstruct dispatch from newer linking facts, then repeat with an older input that lacks qualification or reference-kind metadata. | New facts retain the known overload distinction. Older facts remain readable and carry incomplete signature information at that boundary. | + +### Rule behavior + +| Fixture | Expected result | +| --- | --- | +| Assign `nullptr` then write through `*p`. Repeat with C `NULL` and pointer-context zero. | One definite null dereference at the write with the null source as evidence. | +| Read `p->field` on the branch where `p == nullptr`. | One definite null dereference at the member access. Trace includes the null branch. | +| Assign null on one branch and a valid address on the other. Dereference after the join. | One possible finding, supported by the null assignment and its branch. | +| Check `if (!p) return;` and then dereference. Also exercise `p && *p` and a dead branch. | Zero null-dereference findings with complete coverage. | +| Refer to `*p` inside supported unevaluated operands, including C++ `sizeof` on a non-VLA type. | Zero findings from the unevaluated expression. | +| Dereference a parameter with an unconstrained pointer value and no null evidence. | Zero findings. A branch that explicitly tests and takes the null case supplies evidence in the companion fixture. | +| Allocate successfully, copy `q = p`, then release `p` and `q`. | One definite double-free finding at the second release with the first release as evidence. | +| On one branch release `p`, then release it at a join reached by both arms. | One possible finding supported by the earlier release on that branch. | +| Release `p` once in each of two mutually exclusive branches. | Zero double-free findings with complete coverage. | +| Release `p`, set `p` to null, and release it again. In a companion fixture, retain `q = p` before the reset and release `q` after it. | Zero findings for releasing null and one definite finding for releasing the retained alias. | +| Release a pre-loop allocation on consecutive iterations of a loop with a tracked repeated path. Compare with allocation and one release inside each iteration. | One possible double free for the pre-loop allocation with repeat-path evidence. Zero double-free findings from conflating loop allocations, with summary loss recorded if it obscures precise state. | +| Use `new` and `delete` on a supported trivial type. Run the matching double-release and null-delete cases. | Same release-state behavior as the analogous C cases. | +| Replace a release with a qualified project wrapper described by `--models`. Include a same-spelled unrelated function and an incompatible signature. | The wrapper participates in findings. Only the selected applicable declaration receives the contract. | +| Dereference a retained alias after release. Compare with a version assigning that alias a fresh live value before the access. | Use-after-free finds the first case with release evidence. The second case yields zero use-after-free findings using the same IR and transfer functions. | + +### Framework behavior + +| Area | Required result | +| --- | --- | +| Operation order | Assignment, call result, branch, and dereference fixtures identify their actual evaluation points. Interfering unordered operands leave coverage evidence if order is abstracted away. | +| Control flow and state | Test unreachable versus unknown, monotone transfer, join and widening behavior, and termination on cyclic graphs. A pair of contradictory tests on an unchanged tracked value yields zero findings from the infeasible path. | +| Variant isolation | Analyze a header under two configurations with identical call order and different null assignments. Produce only the findings supported by the respective variants. Equivalent checker bodies deduplicate across TUs. Link-target and suppressed-weak fixtures exercise the same body retention rules as the main pipeline. | +| Calls and alias effects | A valid model can preserve a known local pointer. An opaque call receiving its address invalidates affected state and records coverage. Calls with multiple alternatives form separate transfers, including an unknown alternative when candidate resolution is incomplete. A partial Andersen solve never establishes exhaustive target coverage. Overriding or disabling a checker contract leaves the existing call graph and solver effects identical. | +| Source identity | Macro-generated findings preserve original spelling and expansion attribution as applicable. Two evaluated operations sharing a mapped source span remain individually identifiable. | +| Coverage and limits | Force an unsupported construct, an omitted call, an alternative-cap overflow, and a worklist-budget stop. Exercise the solver's wall-clock cutoff separately and verify partial candidate coverage when it fires. Report the matching reason. Withhold stopped-body findings and still report an independently converged body's results. Unaffected facts retain usable evidence. | +| Rule composition | Run the two initial rules and the extension rule separately and together. Each of the three gives the same findings and confidence for the same bodies and budgets. Count transfers independently of the number of reporting rules. The use-after-free extension uses the existing graph, resolution, worklist, and lifetime transfer. | +| Reproducibility | Disable the wall-clock solver cap with `--solve-budget-secs 0`. Use an unlimited or fixed `--solve-budget-pops` setting and control the `TRACE_SOLVE_BUDGET_POPS` override. Repeated runs and different `--jobs` must then produce identical normalized findings, evidence, coverage, and existing analysis relations for the same inputs. Ignore run metadata such as timestamps. | +| Export compatibility | Export findings and coverage in both minimal and full mode. Compare established call graph, arg-flow, PAG, and sequencing results with checks off against the corrected baseline from milestone 1. Compare the same relations with checks on and off in the completed build at identical settings. This includes the call-sequencing projection when sequencing is enabled. | +| Inspect behavior | Rule and confidence filters agree in text and JSON. Both show the primary callee or caller location and the call steps for a contextual proof. An old or merged database reports the capability unavailable. A completed zero-finding run returns an empty result with complete status. A partial run reports coverage even when findings are empty. | + +### Release verification + +Run the workspace suite and canonical debug checks at the signature prerequisite and after checker integration. Review and recapture expectations for justified overload-resolution changes in the prerequisite. Require checker integration to match the corrected expectations and compare the existing relations with checks off and on. Use the pinned corpus setup. [Pinned evaluation profiles](../EVAL_REPORT.md#pinned-evaluation-profiles-and-master-comparison--2026-11-19) + +```powershell +cargo test --workspace +cargo build -p trace-cli +python scripts/eval_check.py --bin target/debug/trace.exe --corpus-base target/eval-corpora --outdir target/eval-debug-canonical --expected scripts/eval_expected_canonical.json hiview camera +``` + +For release-build measurements, compare the pre-change baseline with the corrected baseline to measure the signature prerequisite. Then compare the corrected baseline, the completed binary with checks off, and the completed binary with both initial rules enabled. Use the same inputs, solver settings, job count, and machine. Record the median of at least three runs per case, peak RSS, and the percentage of bodies with partial checker coverage. The proposed disabled-mode gate is within 5% of the corrected baseline's median elapsed time and peak RSS on both corpora. For enabled checks, record the cost and review the body budgets and coverage before setting a release target. [Memory profiling](../MEMORY_PROFILE.md#reproduce-and-inspect) diff --git a/docs/check/INTERPROCEDURAL.md b/docs/check/INTERPROCEDURAL.md new file mode 100644 index 00000000..b3e5a92e --- /dev/null +++ b/docs/check/INTERPROCEDURAL.md @@ -0,0 +1,82 @@ +# Interprocedural checker design + +The first release follows resolved synchronous calls into retained C and C++ bodies, including calls across translation units in the same link target. A caller can supply a known null value to a helper, learn a pointer result from a helper, or observe that a helper released an object. The same operation graph and rule predicates apply on both sides of a call. + +## First release scope + +| Across a call | Required support | +| --- | --- | +| Arguments | Carry evaluated raw pointer arguments, nullness, and resource identity into supported formals. Preserve identity when two formals receive the same object. | +| Returns | Carry a known null value, an alias of an input, or a fresh allocation back on the matching normal return. Retain separate alternatives when different return paths have different effects. | +| Side effects | Propagate release of an imported resource back to every caller alias of that object. Propagate a write through a modeled pointer-to-pointer or reference when the actual denotes one exact tracked caller slot. | +| Callee paths | Use facts about actuals to refine branches in the callee. A call can supply evidence for a finding whose primary operation is inside that callee. | +| Boundaries | Use explicit checker contracts on applicable declarations. Track exact or partial exception dispatch and treat unresolved calls, ambiguous body variants, unsupported memory effects, and deferred work according to their coverage. | + +For example, the allocation and first release in the following C code are inferred from bodies. The diagnostic belongs at the second `free`, with evidence through both calls. + +```c +#include + +static int *make_item(void) { return malloc(sizeof(int)); } +static void dispose(int *p) { free(p); } + +void example(void) { + int *p = make_item(); + if (!p) return; + dispose(p); + free(p); +} +``` + +## Call transfer and summary + +1. Resolve the synchronous invocation within the caller's link target and configuration. For each candidate, apply any entry preconditions. Select a complete modeled transfer or infer effects from the retained body variant using the resolved declaration, TU and variant provenance. Use an opaque outcome where those effects or the candidate set are incomplete. Candidate records for one invocation are alternatives with the same input. [Function effects](DESIGN.md#function-effects) · [Link targets and weak symbols](../ANALYSIS.md#link-targets-and-weak-symbols) +2. Project the caller state onto the callee's explicit formals, supported receiver if available, exact exposed slots, and reachable tracked resources. Canonicalize object and slot identities by input position and alias relation. Treat by-value formals as new slots. A write to such a formal affects the callee's copy, and a release through it affects the shared object. An unsupported read or write invalidates affected state through the usual opaque-effect transfer. +3. Run the existing worklist on the callee graph with those facts. Compute normal and exceptional outcomes with changed input slots, resource states, and coverage. Keep return values on their normal outcomes and retain the exception type or an explicit unknown type on each exceptional outcome. Record a violation inside the callee as a finding template with local source spans and references to the input facts that support it. A proven nonreturning outcome has no normal continuation. +4. Apply each outcome back to the invocation that produced it. Map input slots and resources through that invocation's binding. Commit a return assignment on the normal successor after applying callee effects. Exceptional successors carry only effects of their corresponding paths. Preserve caller state outside the callee's effect footprint. Instantiate any fresh exported identity relative to this invocation. Two independent calls to the same allocator wrapper produce two distinct objects. An origin inside a loop or reached from a repeatable call occurrence is summarized whenever the caller cannot establish a single instance. + +The initial implementation uses a demand-driven cache of abstract input and output states. Cache by retained body variant and normalized input state, including modeled values, alias relations, affected resource states, and relevant coverage. Keep provenance symbolic in cached summaries. On a cache hit, bind input evidence to this caller and keep the original callee spans. A new domain defines how to project its inputs and remap its effects through the same call binding. The worklist, cache, and evidence machinery serve every rule. + +## Synchronous call candidates + +Take the checker candidate view from the solver's source-level call resolution before `callback_edges` and synthetic IPC edges are appended. The current solver can expose that prefix through its internal API and use the full edge list for existing graph consumers. This retains genuine indirect calls even when the same site and target also appear in an invocation model. Exclude edges whose only origin is callback modeling. These can have `ResolutionKind::Indirect` and no `execution_contexts` row, as when a `std::bind` object is built and discarded. Apply the wrapper's own transfer at the construction site. Follow a callback synchronously at a resolved invocation in an analyzed body. [Solver callback edge construction](../../crates/trace-analysis/src/solver.rs) · [Callable wrappers](../MODELS.md#callable-wrappers) + +## Exceptional dispatch + +Record the checker graph's handlers in source order, with canonical catch types and the catch-all marker. Dispatch a typed exceptional outcome to the first matching handler under C++ handler rules. If no handler matches, continue unwinding to the outer landing or function boundary. A rethrow uses the active exception type when known. A throw that escapes a known nonthrowing function terminates that alternative. Keep memory effects paired with the exception that produced them. [CFG builder](../../crates/trace-parse/src/cfg_build.rs) · [C++ handler matching and order](https://eel.is/c++draft/except.handle) + +For an unknown thrown type or unresolved match, preserve each feasible first handler and any feasible propagation to the outer scope. Mark destinations that depend on imprecise dispatch as partial and withhold definite confidence there. A catch-all that is the only feasible destination can be selected exactly even for an unknown type. A shared call-sequencing landing with edges to each handler supplies topology for this transfer. The checker uses the ordered type predicates to determine reachability. + +## Recursion and bounded work + +Analyze each retained body from an unconstrained entry and analyze supported call contexts on demand as those roots reach calls. Use stable root, call, and candidate order. Bound active call depth, distinct abstract inputs per body variant, and aggregate checker transfers. Proposed initial limits are eight active calls, eight specialized inputs per variant, and a run-wide transfer cap to be calibrated on the pinned corpora. These are in addition to the per-body worklist limit. Record effective budgets and cutoff counts for corpus evaluation. [Clang's interprocedural depth and budget controls](https://clang.llvm.org/docs/analyzer/developer-docs/IPA.html) + +- **Recursive re-entry.** On a reachable call to a body variant already active on the analysis stack, apply the opaque call transfer and record a recursion gap before consulting the cache. This covers direct and mutual recursion and retains any base case reached before re-entry. A later improvement can solve summaries to a fixpoint over recursive call-graph components. +- **Unavailable or uncertain calls.** Complete modeled effects and supported bodies give outcomes. When target completeness or body selection is uncertain, include a conservative unknown outcome for the missing possibilities. Invalidate affected exposed slots and resource facts and preserve independent caller state. Treat shared state reachable by deferred work according to the existing execution-context boundary. +- **Exhausted context, depth, or transfer budget.** Fall back at a call that exceeds its context or depth limit and propagate the reason through the summary. Reuse only converged outcomes independent of an active stack or a transient budget cutoff. A callee that stops before convergence supplies the opaque effect if its caller can continue. A run-wide transfer cutoff records coverage for stopped and unscheduled roots. Independent converged findings remain available. + +## Findings across calls + +Retain the primary operation in the function where it executes. The trace carries the call and return steps needed to connect caller evidence to a callee operation or callee effects to a later caller operation. For example, when a caller passes null to `read_item(p)`, a definite finding inside `read_item` is definite **for that invocation context**. If a single invocation can supply null or a valid pointer, the report must carry the input condition for any contextual definite claim. The call as a whole can support a possible finding. + +Store whether the confidence applies to the standalone body or to a concrete analyzed call context. A standalone proof can subsume an equivalent contextual report. Deduplicate remaining reports by rule, operation, variant, and canonical proof scope. Pick evidence deterministically for equivalent proofs and retain the call step that explains the context. Propagate callee coverage to the dependent caller rule while retaining the boundary and its reason. + +## Interprocedural acceptance fixtures + +| Fixture | Expected result | +| --- | --- | +| Caller acquires a known live resource, calls an unmodeled in-tree release wrapper, then releases the original pointer. | One definite finding at the caller's second release. Evidence shows the invocation and actual release in the wrapper. | +| A wrapper releases only when its pointer argument is null. Another wrapper releases on a separate unknown condition. | The first wrapper leaves a known live non-null resource intact. The second can produce a possible finding on a later release, with the releases on one consistent path. | +| A callee releases its input and returns null on one branch, and returns the live input on the other. The caller releases the result only if it is non-null. | The caller observes the correlated outcome. The guarded release yields zero double-free findings. An unguarded dereference of the result can produce a possible null finding. | +| Two calls return objects from the same allocator wrapper. Release each once, including a fixture that calls the wrapper repeatedly in a loop. | Zero double-free findings from reusing an allocation site's identity. | +| Two formals receive the same live pointer, and the callee releases both. A companion call passes two distinct live objects. | One contextual definite finding in the first case. Zero findings in the distinct-object case. | +| Pass null and non-null pointers from different callers to the same dereferencing helper. | A definite finding scoped to the null caller's invocation. No report from the non-null call. | +| Pass a pointer to a dereferencing helper after another helper released it. | The use-after-free extension reports the access in the dereferencing helper and traces the release through the other helper. | +| A callee sets one exact caller slot to null via an out-parameter or C++ reference. Compare with assigning null to a by-value formal. | Only the out-parameter or reference can make the caller's later access definitely null. An ambiguous out-slot records partial coverage. | +| Calls from two TUs resolve to different internal functions with the same spelling. A separate fixture has a known cross-TU external definition. | Use each caller's actual retained definition and configuration. Follow the known cross-TU body and do not mix effects from the other target or variant. | +| A release helper has a normal outcome and a throw before release. Another helper releases before throwing. | Each successor sees the lifetime state for its own exit. A throwing outcome bypasses assignment of the normal result. | +| A helper throws an `int`. The caller places a null dereference in both `catch (double)` and the following `catch (int)`. A companion fixture throws through an opaque call. | The typed outcome reaches only the integer handler, which yields the sole definite finding. The unknown outcome marks affected handler edges partial and yields no definite finding based on imprecise dispatch. | +| Two callers share an abstract input shape, but supply different source evidence. | Reuse the summary and bind each reported call's evidence to the correct invocation. | +| Direct recursion, mutual recursion, missing definitions, and forced call depth or context limits. | Analysis terminates. The affected boundary and reason are visible and fallback creates no definite finding from a missing effect. A complete independent proof remains visible. | +| A complete checker contract overrides an inferred in-tree effect. Disable that contract in a companion fixture. | The selected contract supplies the effect once in the first case. The second case follows the retained body when available. | +| Give `init(int **out, int *in)` a precondition on `out`. The body writes `*out = in`. Invoke it as `init(&p, &value)` when `p` starts null, then dereference `p`. Repeat with only a declaration for `init`. | The body version infers the write and reports zero null dereferences with complete coverage. The declaration version invalidates the caller slot and records partial coverage, yielding no definite finding from the old null value. | diff --git a/docs/check/README.md b/docs/check/README.md new file mode 100644 index 00000000..6429df03 --- /dev/null +++ b/docs/check/README.md @@ -0,0 +1,15 @@ +# Static checker framework + +**Status** — Design proposal. + +Pathologist can use its C and C++ lowering, call graph, and function models to check properties that depend on execution order across function calls. The first release infers effects from resolved in-tree bodies for null dereference and double free. Use-after-free tests whether a third rule can reuse the same operations, object identities, and lifetime state. + +| Document | Contents | +| --- | --- | +| [Design](DESIGN.md) | Operation-level IR, body variants, abstract interpretation, function effects, and reporting | +| [Interprocedural design](INTERPROCEDURAL.md) | Call and return transfer, inferred effects, recursion limits, and cross-function acceptance cases | +| [Edge cases](EDGE_CASES.md) | Supported behavior, conservative fallbacks, and regression cases for the initial release | +| [Rule catalog](RULES.md) | Candidate checks, examples, required facts, and suggested delivery order | +| [Implementation plan](IMPLEMENTATION.md) | Milestones, crate ownership, acceptance fixtures, and release checks | + +The design calls for an opt-in pass after the existing Andersen solve. Explicit design approval is required before flow-sensitive implementation under the [contributor guide](../../AGENTS.md#do-not). diff --git a/docs/check/RULES.md b/docs/check/RULES.md new file mode 100644 index 00000000..1c3f2022 --- /dev/null +++ b/docs/check/RULES.md @@ -0,0 +1,55 @@ +# Static check rule catalog + +Choose early rules that exercise different properties of the same operation graph. Null dereference checks a value at an access. Double free checks a resource transition. Use-after-free combines those two pieces. File streams then test whether new API contracts can reuse the resource layer. + +## Rules that reuse the initial pass + +| Rule | Example | Required facts | +| --- | --- | --- | +| Null dereference | `if (!p) return *p;` | Evaluated access and edge refinement. Distinguish a null pointer from an unknown value. | +| Double free | `q = p; free(p); free(q);` | Same resource instance on both releases, release order, and API handling of null. | +| Use after free | `q = p; free(p); return *q;` | Pointer access and release state for the same instance. Keep the first release as evidence. | +| Null argument | `takes_nonnull(nullptr);` | Resolved callee, explicit actual position, and a non-null parameter contract. | +| Mismatched deallocation | `auto p = new int[2]; delete p;` | Allocation and release families. Keep C heap, scalar `new`, array `new[]`, and modeled custom families distinct. | +| Release of non-heap storage | `int n; free(&n);` | Address origin for the value and a release contract limited to heap objects. | + +The initial delivery ships the first two rules. Use-after-free serves as the first extension test. The next three can use the same traversal and state while expanding the relevant contracts. Clang and GCC document analogous checks for pointer access, heap lifetime, argument contracts, and deallocation families. [Clang checker reference](https://clang.llvm.org/docs/analyzer/checkers.html) · [GCC analyzer options](https://gcc.gnu.org/onlinedocs/gcc-14.1.0/gcc/Static-Analyzer-Options.html) + +## Rules that extend resource tracking + +| Rule | Example | Additional capability | +| --- | --- | --- | +| Double close | Close a successfully opened stream twice through copied `FILE *` values. | Model stream identity and `fclose` outcomes. Reuse the release transition and let the stream rule name the violation. | +| Use after close | Read from a closed stream or descriptor. | Model operations that require a live resource. For descriptors, track integer handles, the failure sentinel, aliasing, and reuse of the same integer by a later open. | +| Resource leak | Acquire a stream, then return on an error branch while it is still owned locally. | Track ownership and escape, including transfer by return or out-parameter. Check exit paths and account for cleanup and destructor effects. | +| Unchecked status before use | Read through an output pointer after calling an API that initializes it only on success. | Condition facts on return outcomes, retain the relationship between status and output, and check the dependent operation. | +| Unlock without ownership | On a failed try-lock branch, call unlock on the same mutex. | Track successfully acquired state under the API's return convention and match the mutex identity. | +| Repeated lock acquisition | Lock a known non-recursive mutex twice in one execution context. | Track mutex type and ownership locally. Recursive locks and cross-thread ordering require separate semantics. | +| Borrowed value outlives its owner | Use a pointer from a vector's `data()` after a mutation that can invalidate the storage. | Model borrowed values, relevant mutation outcomes, and the lifetime of the backing storage. | +| Unbalanced retain and release | Release a locally managed reference twice without a matching retain. | Track ownership obligations or a bounded count domain. Model transfer, origin, and conditional decrement semantics. | + +Start resource generalization with streams. A descriptor protocol needs integer handle identity and sentinel semantics, and a leaked-resource finding needs an ownership model. Clang documents stream and lock rules, and GCC documents descriptor rules. [Clang checker reference](https://clang.llvm.org/docs/analyzer/checkers.html) · [GCC descriptor checks](https://gcc.gnu.org/onlinedocs/gcc-14.1.0/gcc/Static-Analyzer-Options.html) + +## Rules that add analysis domains + +| Rule | Example | Additional capability | +| --- | --- | --- | +| Read before initialization | `int x; if (ok) x = 1; return x;` | Declaration, write, and read operations for scalar locals. Distinguish uninitialized state from an initialized value of unknown contents. | +| Escaping stack address | `int x; return &x;` | Local storage identity and return or escape operations. Using a pointer beyond an inner scope also requires scope-exit lifetime events. | +| Division by zero | `if (n == 0) return total / n;` | Typed integer values, comparisons, and division operands. A zero/non-zero domain is sufficient for this example. | +| Out-of-bounds access | `int a[4]; if (i == 4) a[i] = 1;` | Integer ranges, array extent, access width, and subscripts. Dynamic bounds also require tracking allocation sizes and pointer offsets. | +| Dead store | `x = 1; x = 2; return x;` | Backward liveness over the operation graph, including observable writes and alias effects. Add backward traversal when a rule needs it. | +| Unsanitized size at allocation | Pass externally supplied length to a modeled allocation API without applying the required validation. | Configured sources and sinks, propagation through operations, and validation facts tied to the relevant value and its bounds. | +| Lock order cycle | Two functions take the same pair of mutexes in opposite order under execution contexts that may overlap. | Per-body lock-order summaries, shared mutex identity, and cross-context reasoning. Pathologist's execution context facts can seed this analysis. | + +For new domains, define the typed operations, entry facts, transfer, join, loss-of-precision behavior, and required evidence. Test that branch refinement removes false positives and that unknown inputs do not invent a violation. GCC and Clang list comparable analyses for uninitialized values, bounds, integer errors, resource state, and tainted sizes. [GCC analyzer options](https://gcc.gnu.org/onlinedocs/gcc-14.1.0/gcc/Static-Analyzer-Options.html) · [Clang checker reference](https://clang.llvm.org/docs/analyzer/checkers.html) · [Pathologist execution contexts](../MODELS.md#execution-contexts) + +## Examples that test extensibility + +**One operation, two checks.** With `q = p; free(p); return *q;`, the dereference operation supplies the receiver for both null dereference and use-after-free. The two rules query different properties. The positive use-after-free fixture guards against allocation failure before the copy and release. A companion fixture overwrites `q` with a fresh live pointer before the access and expects zero use-after-free findings. + +**One resource transition, different APIs.** Model a project pool's acquire and release functions with the same effects as a built-in pair, using a distinct resource kind. The checker should find two releases of a successful acquisition through an alias. A companion fixture uses two distinct acquisitions and expects zero double-release findings. Moving on to streams then exercises custom success values and a live-resource access requirement. + +**One rule across two bodies.** Move the first release or the dereference into an in-tree helper. The rule queries the same resource state or pointer value supplied by the inferred summary or call input. Evidence links the violation to its caller and callee. [Cross-function acceptance cases](INTERPROCEDURAL.md#interprocedural-acceptance-fixtures) + +**One control-flow graph, a different domain.** For `int x; if (ready) x = 1; return x;`, uninitialized-value checking uses the same branch and join machinery. Its evidence is the declaration and the branch that bypassed the write. A companion fixture writes `x` on both arms and expects zero findings.