Skip to content

Go: Save defer arguments and return values in temporary variables - #23360

Open
owen-mc wants to merge 23 commits into
github:mainfrom
owen-mc:go/defer-temporaries
Open

owen-mc wants to merge 23 commits into
github:mainfrom
owen-mc:go/defer-temporaries

Conversation

@owen-mc

@owen-mc owen-mc commented Dec 4, 2026

Copy link
Copy Markdown
Contributor

Previously, although the Go CFG placed defer-invoke nodes at function exit, it had no temporary variables connecting registration-time expression evaluations (or pre-defer unnamed return expressions) to the exit epilogue. Consequently, a deferred CallNode's callee, receiver, and argument nodes pointed directly to the registration-time expressions in the function body, unnamed ResultNodes pointed to return expressions before deferred calls ran, and deferred PostUpdateNodes took effect synchronously in the body rather than in LIFO order at exit.

Beyond mismodeling deferred mutations, this makes it difficult to handle defer cleanly with the shared VariableCapture library (which will be instantiated in a follow-up PR):

  • VariableCapture reads and updates captured variables at the CFG position of a call's closure input or a function's returned closure node. When those nodes sit at defer registration (or at a pre-defer return), deferred closures read stale registration-time values instead of values written later in the body or by earlier-running defers, and capture side effects take effect in the body instead of the epilogue.
  • Working around this in the data-flow layer alone requires selectively substituting synthetic exit-time nodes for closure- and interface-typed inputs, splitting how closures and non-closures interact with ArgumentNode, PostUpdateNode, ResultNode, FunctionModels, and backward taint flow.

Saving defer inputs and unnamed return values into synthetic temporaries in the CFG and IR places deferred call inputs, PostUpdateNodes, and ResultNodes at their actual execution points in the epilogue while preserving registration-time evaluation, so both ordinary data flow and VariableCapture can treat deferred calls uniformly.

Summary of this PR

  • CFG and IR: Evaluate deferred callees, receivers, and arguments at defer registration into synthetic temporaries (DeferWriteInstruction), restore them in LIFO order before each exit-time invocation (DeferReadInstruction) with panic/recover propagation and process-exit (os.Exit, log.Fatal) bypasses, and save unnamed return expressions into synthetic result temporaries before running deferred calls (WriteUnnamedResultInstruction / ReadUnnamedResultInstruction).
  • SSA and data flow: Track synthetic temporaries with shared SSA, route deferred CallNode inputs and unnamed ResultNodes through their saved values, and split synchronous from deferred PostUpdateNodes so argument and receiver mutations from a defer flow in LIFO order through the epilogue to later-running defers, results, and captures without appearing in the function body.
  • Supporting analyses: Preserve global value numbers across single-source defer and unnamed-result temporaries when safe, update guard and return-property inference to account for deferred mutations and recover(), and extend clear sanitization across deferred calls.
  • Models and queries: Model fmt and bun scan destinations as post-update sources so deferred scans take effect at invocation, and adapt affected framework models (regexp, crypto) and queries (go/unhandled-writable-file-close, go/insecure-hostkeycallback, go/allocation-size-overflow, go/hardcoded-credentials, go/insufficient-key-size) for synthetic defer and result nodes.

Known limitations

  • Epilogue post-update propagation connects uses of the same SsaWithFields access path and direct in-place mutations of named result variables (&res, &res.f, res.ptrMethod()), without general local alias tracking.
  • Heap or pointer mutations made after defer registration to values referenced by already-saved defer inputs are not propagated into the saved temporaries.
  • Dynamically registered defers in loops are approximated via SSA phi nodes, and flow-sensitive closure variable capture is left to the follow-up PR.

Commits are structured to be reviewed commit-by-commit.

owen-mc and others added 12 commits December 4, 2026 12:12
Model Go's runtime defer and return evaluation order directly in the
CFG and IR:

- Evaluate a deferred call's callee, receiver, and arguments at defer
  registration and save them into synthetic TempVariables via
  DeferWriteInstructions.
- Read saved callee, receiver, and arguments via DeferReadInstructions
  before each exit-time defer-invoke node in LIFO order, propagating
  panic/recovery state across the defer chain and routing process-exit
  calls (os.Exit, log.Fatal) directly to ExitSuccessor.
- In functions containing defer, save unnamed return expressions into
  synthetic result temporaries before running deferred calls and read
  them at function exit via ReadUnnamedResultInstructions.
- Unwrap parenthesized and generic-instantiated callees in
  CallExpr.getTarget() and propagate constant values onto
  DeferReadInstructions.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Instantiate shared SSA for synthetic temporaries and route deferred
callees, receivers, arguments, and unnamed results through their saved
values. Adapt summary typing, constants, and path presentation.

Include inline tests for registration-time evaluation, call forms,
conditional and loop registrations, and constant branch pruning.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Separate synchronous and deferred post-update nodes so deferred
mutations do not appear in the function body. Propagate updates to
later-running defers, results, and captures along baseline access paths.

Include end-to-end tests for LIFO updates, named and unnamed returns,
nested access paths, capture isolation, and accepted alias limitations.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Reuse value numbers for single-source saved defer inputs and unnamed
results where types and intervening side effects permit it. Detect
recovered panic paths that can leave unnamed results at zero values.

Keep the focused value-numbering fixtures and expected output here.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Do not treat deferred calls as synchronous exception guards. Account
for deferred result mutations and recovery when inferring return
properties, and recognize suitable post-registration guards.

Include guard, wrapper-inference, and deferred barrier tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Track the slice or map header saved by deferred clear calls. Use
instruction ordering and SSA result-path reachability to sanitize
epilogue uses without clearing earlier body uses or bypassing returns.

Include clearing tests for conditional paths, reassigned headers,
named-result phi nodes, and accepted in-place re-tainting limitations.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Represent Fmt and Bun scan destinations as post-update sources so
deferred input operations taint their destinations only when invoked.

Include scanner source tests and the deferred-input OAuth state case.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Read regexp patterns through node constants and inspect saved deferred
inputs in allocation-size modeling and barrier propagation.

Include the matching regexp and allocation-overflow regression tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Exclude synthetic saved-value copies where crypto models and constant
sources would otherwise count the same value or operation twice.

Include deferred crypto, key-size, and hardcoded-credential fixtures.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Check handled Sync ordering from defer registration. Unwrap saved
receivers and direct SSA copies without following phi inputs, so
syncing one possible handle does not exempt another unsynced handle.

Include ordinary and deferred receiver-merge regressions and controls.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Trace local-flow roots into synthetic result reads when identifying
callbacks that always return nil. Exclude results with uncertain
capture writes or indirect references that may be changed by defers.

Include named, unnamed, captured, and pointer-mutated result tests.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Document registration-time saving, exit-time invocation, and synthetic
call/result nodes in the library pack. Note precision improvements in
the SSH callback and writable-file-close queries in the query pack.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Critical deferred-call modeling flaws can suppress real taint flows, omit valid panic-unwinding paths, and cause XPath-injection false negatives.

4 open issues
What changed in this PR

Improves CodeQL’s Go analysis by preserving registration-time values while modeling deferred calls and their mutations at function exit.

Changes:

  • Save deferred inputs and unnamed return values in synthetic temporaries.
  • Adapt data flow, guards, models, and queries to exit-time execution.
  • Add regression tests, consistency checks, and change notes.
File Description
go/​ql/​test/​query-tests/​Security/​CWE-798/​main.go Tests deferred credential use.
go/​ql/​test/​query-tests/​Security/​CWE-798/​HardcodedCredentials.expected Records the deferred credential alert.
go/​ql/​test/​query-tests/​Security/​CWE-352/​ConstantOauth2State.go Tests deferred terminal scanning.
go/​ql/​test/​query-tests/​Security/​CWE-352/​ConstantOauth2State.expected Updates OAuth state expectations.
go/​ql/​test/​query-tests/​Security/​CWE-327/​WeakSensitiveDataHashing.expected Records deferred hashing alerts.
go/​ql/​test/​query-tests/​Security/​CWE-327/​hashing.go Adds deferred hashing cases.
go/​ql/​test/​query-tests/​Security/​CWE-327/​encryption.go Adds deferred cipher-stream cases.
go/​ql/​test/​query-tests/​Security/​CWE-327/​BrokenCryptoAlgorithm.expected Records cipher-stream results.
go/​ql/​test/​query-tests/​Security/​CWE-326/​InsufficientKeySize.go Tests deferred key generation.
go/​ql/​test/​query-tests/​Security/​CWE-326/​InsufficientKeySize.expected Records deferred key-size alerts.
go/​ql/​test/​query-tests/​Security/​CWE-322/​InsecureHostKeyCallbackExample.go Tests deferred callback behavior.
go/​ql/​test/​query-tests/​Security/​CWE-322/​InsecureHostKeyCallback.expected Updates callback results and paths.
go/​ql/​test/​query-tests/​Security/​CWE-322/​CONSISTENCY/​SsaConsistency.expected Records callback SSA consistency output.
go/​ql/​test/​query-tests/​Security/​CWE-190/​AllocationSizeOverflow.go Tests deferred PEM encoding flow.
go/​ql/​test/​query-tests/​Security/​CWE-190/​AllocationSizeOverflow.expected Records deferred encoding results.
go/​ql/​test/​query-tests/​RedundantCode/​DeadStoreOfLocal/​testdata.go Tests deferred pointer reads.
go/​ql/​test/​query-tests/​InconsistentCode/​UnhandledCloseWritableHandle/​UnhandledCloseWritableHandle.expected Updates writable-close expectations.
go/​ql/​test/​query-tests/​InconsistentCode/​UnhandledCloseWritableHandle/​tests.go Tests close aliases and synchronization.
go/​ql/​test/​query-tests/​InconsistentCode/​UnhandledCloseWritableHandle/​CONSISTENCY/​CfgConsistency.expected Updates deferred receiver labels.
go/​ql/​test/​library-tests/​semmle/​go/​PrintAst/​CONSISTENCY/​CfgConsistency.expected Updates deferred callee labels.
go/​ql/​test/​library-tests/​semmle/​go/​frameworks/​Twirp/​CONSISTENCY/​SsaConsistency.expected Updates deferred argument labels.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​ListOfConstantsSanitizerGuards/​test.go Tests recovery and deferred guard mutations.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​GuardingFunctions/​test.go Tests deferred return-value changes.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​GlobalValueNumbering/​main.go Adds temporary value-numbering cases.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​GlobalValueNumbering/​GlobalValueNumber.expected Records temporary value numbers.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​GlobalValueNumbering/​CONSISTENCY/​CfgConsistency.expected Records looped-defer control flow.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​flowsources/​local/​stdin/​test.go Tests scan post-update sources.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​flowsources/​local/​database/​test_uptrace_bun.go Tests Bun scan output flow.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​Defer/​main.go Adds extensive defer-flow cases.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​Defer/​Flows.ql Runs inline flow assertions.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​Defer/​Flows.expected Adds inline-flow expectation baseline.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​Defer/​ConstValues.ql Checks restored argument constants.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​Defer/​ConstValues.expected Records restored constant values.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​Defer/​CONSISTENCY/​UnexpectedFrontendErrors.expected Records intentional unresolved-name errors.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​Defer/​CONSISTENCY/​SsaConsistency.expected Records defer SSA consistency output.
go/​ql/​test/​library-tests/​semmle/​go/​dataflow/​Defer/​CONSISTENCY/​CfgConsistency.expected Records defer control-flow consistency output.
go/​ql/​test/​library-tests/​semmle/​go/​controlflow/​Guards/​guards.go Tests deferred and recovering guards.
go/​ql/​test/​library-tests/​semmle/​go/​controlflow/​Guards/​Guards.expected Updates guard inference expectations.
go/​ql/​test/​library-tests/​semmle/​go/​controlflow/​ControlFlowGraph/​stmts7.go Tests panic, recovery, and exit ordering.
go/​ql/​test/​library-tests/​semmle/​go/​controlflow/​ControlFlowGraph/​NoretFunctions.expected Updates non-returning function results.
go/​ql/​test/​library-tests/​semmle/​go/​controlflow/​ControlFlowGraph/​CONSISTENCY/​CfgConsistency.expected Updates defer control-flow expectations.
go/​ql/​test/​library-tests/​semmle/​go/​concepts/​Regexp/​stdlib.go Tests deferred regular-expression matching.
go/​ql/​test/​library-tests/​semmle/​go/​concepts/​Regexp/​RegexpPattern.expected Records the restored pattern.
go/​ql/​test/​experimental/​InconsistentCode/​CONSISTENCY/​CfgConsistency.expected Updates looped-defer graph expectations.
go/​ql/​src/​Security/​CWE-798/​HardcodedCredentials.ql Excludes duplicate restored-value sources.
go/​ql/​src/​Security/​CWE-327/​InsecureTLS.ql Excludes restored TLS-version sources.
go/​ql/​src/​Security/​CWE-326/​InsufficientKeySize.ql Excludes restored key-size sources.
go/​ql/​src/​Security/​CWE-322/​InsecureHostKeyCallback.ql Handles synthetic and mutable results.
go/​ql/​src/​InconsistentCode/​UnhandledCloseWritableHandle.ql Tracks receiver copies and registration points.
go/​ql/​src/​change-notes/​2026-12-01-defer-temporaries.md Documents query precision changes.
go/​ql/​lib/​semmle/​go/​security/​AllocationSizeOverflowCustomizations.qll Handles restored inputs and barriers.
go/​ql/​lib/​semmle/​go/​frameworks/​stdlib/​Regexp.qll Reads patterns from synthetic nodes.
go/​ql/​lib/​semmle/​go/​frameworks/​stdlib/​Fmt.qll Models scan destinations after updates.
go/​ql/​lib/​semmle/​go/​frameworks/​CryptoLibraries.qll Adapts crypto models to synthetic nodes.
go/​ql/​lib/​semmle/​go/​frameworks/​Bun.qll Models scan outputs after updates.
go/​ql/​lib/​semmle/​go/​Expr.qll Unwraps callees for target resolution.
go/​ql/​lib/​semmle/​go/​dataflow/​SsaImpl.qll Adds temporary SSA and reachability helpers.
go/​ql/​lib/​semmle/​go/​dataflow/​SSA.qll Tracks deferred receivers and field paths.
go/​ql/​lib/​semmle/​go/​dataflow/​internal/​TaintTrackingUtil.qll Adapts guards and clear sanitization.
go/​ql/​lib/​semmle/​go/​dataflow/​internal/​FlowSummaryImpl.qll Resolves saved receiver qualifier types.
go/​ql/​lib/​semmle/​go/​dataflow/​internal/​DataFlowUtil.qll Adapts barriers and return properties.
go/​ql/​lib/​semmle/​go/​dataflow/​internal/​DataFlowPrivate.qll Propagates temporary and deferred mutation flow.
go/​ql/​lib/​semmle/​go/​dataflow/​internal/​DataFlowNodes.qll Exposes synthetic inputs and result nodes.
go/​ql/​lib/​semmle/​go/​dataflow/​GlobalValueNumbering.qll Preserves safe temporary value numbers.
go/​ql/​lib/​semmle/​go/​controlflow/​IR.qll Defines temporary save and restore instructions.
go/​ql/​lib/​semmle/​go/​controlflow/​Guards.qll Restricts inference around deferred effects.
go/​ql/​lib/​semmle/​go/​controlflow/​ControlFlowGraphImpl.qll Builds registration and exit-time defer sequences.
go/​ql/​lib/​change-notes/​2026-11-28-defer-temporaries.md Documents modeling and API changes.
go/​ql/​consistency-queries/​TempSsaConsistency.ql Adds temporary SSA consistency checks.

Review effort: Max (adaptive)

invInsn.getSavedInstruction()
)
or
deferredPostUpdateFlowStep(nodeFrom, nodeTo)
@owen-mc
owen-mc force-pushed the go/defer-temporaries branch from e5fa174 to 76013b2 Compare December 4, 2026 12:14
Allow synthetic data-flow nodes such as DeferReadInstructions to act as
XPath injection sinks and sanitizers, matching XPath::XPathExpressionString,
XPath::Sanitizer, and the other Go security customization modules.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@owen-mc
owen-mc marked this pull request as ready for review December 4, 2026 14:16
@owen-mc
owen-mc requested a review from a team as a code owner December 4, 2026 14:16
@owen-mc
owen-mc requested a review from aschackmull December 4, 2026 14:16
owen-mc and others added 7 commits December 5, 2026 06:42
In `TempVariable.getType` for `MkUnnamedResultTemp(fd, i)`,
`fd.getType().getResultType(i)` could be evaluated by joining on `i`
before binding `fd`, materializing result types across all function
signatures before filtering to `fd`. Constrain `fd` with
`pragma[only_bind_out]` and `i` with `pragma[only_bind_into]` so `fd`'s
signature is looked up first.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
In `reachableFromDeferSave`, joining
`dr.getSavedInstruction().getBasicBlock()` directly with
`start.getASuccessor()` allowed the optimizer to scan all basic-block
nodes before filtering to instructions saved by `defer` statements.
Delay `getBasicBlock()` via a `pragma[inline_late]` helper so the base
case starts from `DeferReadInstruction`s.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
In `ParameterizedBarrierGuardValue::getABarrierNodeForGuard`, inlining
the `DeferReadInstruction` checks and `globalValueNumber` comparison
inside the parameterized predicate caused a large GVN cross-product when
`guards` had many tuples (such as in `AllocationSizeOverflow`), and
allowed `result.getBasicBlock()` to be evaluated before `result` was
bound. Factor non-parameterized `deferSavedUse` and
`deferSavedDirectVarUse` helpers and delay `globalValueNumber` and
`getBasicBlock` until their inputs are bound.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
`AllocationSizeCheckBarrier` only needs a single step from a
`DeferReadInstruction` to its saved instruction, since a saved
expression is never itself a `DeferReadInstruction`. Express it via a
non-recursive `directAllocationSizeCheckBarrier` helper and bind `dr`
before `getSavedInstruction()` to avoid fixpoint evaluation and scanning
all `DeferReadInstruction`s upfront.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
When `StructType.getOwnField` is called with `name` bound and `this`
unbound (such as during type and method resolution in
`GlobalValueNumbering`), magic-sets can specialize `hasOwnField` on
`name` alone, joining all struct field components and defined type names
matching `name` across the program (+511M tuples on `aws-sdk-go`).
`hasOwnField` is a thin wrapper over `component_types`, so mark it
`pragma[nomagic]` to evaluate it directly without specialization.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Cache `funcHasDefer`, `hasUnnamedResultTemp`, `deferHasSavedReceiver`,
`deferHasSavedCallee`, `deferSavedExprArg`, `deferHasSavedArg`,
`deferMayRecover`, and `deferRecoversPanic` in `CfgCachedStage` (and
express `hasResultSlot` via `hasUnnamedResultTemp` so it participates in
the same stage). Without caching, downstream stages in `IR`, `SsaImpl`,
`DataFlowNodes`, and per-query select clauses repeatedly specialized and
re-evaluated CFG-skipping and AST enclosure helpers outside CFG
construction.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
In `deferSavedCalleeInstruction`, `deferSavedReceiverInstruction`, and
`deferSavedArgInstruction`, static join-order planning lacks row-count
statistics for the newly cached `CfgImpl` predicates and could evaluate
`evalExprInstruction` across all expressions (materializing all
`EvalInstruction` and `ValueExpr` tuples) before filtering to `defer`
statements. Delay `evalExprInstruction` and `selectorBase` until their
input expression is bound, look up tuple-extracted `defer` arguments via
`CfgImpl::deferHasSavedArg`, and cache the three helpers in the same
cached module as `TTempVariable` so callers reuse them directly.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
owen-mc and others added 3 commits December 5, 2026 07:02
`insnHasSyncPostUpdateNode` and `insnHasPostUpdateNode` are independent
of query-specific flow summaries, but `insnHasSyncPostUpdateNode` was
re-evaluated in every query's `getNodeFromSsaNode` / `basicLocalFlowStep`
specialization (11 times across `go-security-and-quality.qls`, +68.6M
tuples on `aws-sdk-go`), and `insnHasPostUpdateNode` was re-evaluated in
each `TNode` variant. Cache both in a shared query-independent module and
reuse `insnHasSyncPostUpdateNode` in `insnHasPostUpdateNode`.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
`DataFlowPrivate::insnReadsSsaDef` was uncached and scanned all
`BasicBlock::getNode` entries and `IR::Instruction.reads` across per-query
data-flow specializations (5 evaluations, +23.4M tuples on `aws-sdk-go`).
Compute it from the already-cached `Impl::ssaDefReachesRead` and `useAt`
relations in `SsaImpl` and merge it into the existing SSA cached stage.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
`tempDefAt`, `tempUseAt`, and `tempDefUseStep` dispatched `writesTemp`
and `readsTemp` on `IR::Instruction` across all basic-block nodes and
evaluated `ReturnInstruction.getResult` unbound in
`WriteUnnamedResultInstruction.getRhs`, materializing all `IR::Instruction`
and `Expr::Literal` tuples (+66.2M tuples in `tempDefUseStep` and +33.6M
in `TempInternal` on `aws-sdk-go`). Restrict `tempDefAt` and `tempUseAt`
to the concrete temporary write/read classes over `ControlFlow::Node`,
bind the return expression in `WriteUnnamedResultInstruction.getRhs`, and
merge `tempDefUseStep` and `TempDataFlowIntegration::localFlowStep` into
the temporary-SSA cached stage.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@owen-mc
owen-mc force-pushed the go/defer-temporaries branch from 998973e to 3729998 Compare December 5, 2026 07:21

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants