Repository navigation
Conversation
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>
Contributor
There was a problem hiding this comment.
🟡 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
force-pushed
the
go/defer-temporaries
branch
from
December 4, 2026 12:14
e5fa174 to
76013b2
Compare
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>
Factor non-parameterized DeferReadInstruction helpers and delay globalValueNumber and getBasicBlock joins in ParameterizedBarrierGuardValue::getABarrierNodeForGuard to avoid GVN fanout when guards is large. Also make AllocationSizeCheckBarrier non-recursive and constrain binding order in TempVariable.getType and reachableFromDeferSave. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.


Previously, although the Go CFG placed
defer-invokenodes at function exit, it had no temporary variables connecting registration-time expression evaluations (or pre-deferunnamedreturnexpressions) to the exit epilogue. Consequently, a deferredCallNode's callee, receiver, and argument nodes pointed directly to the registration-time expressions in the function body, unnamedResultNodes pointed toreturnexpressions before deferred calls ran, and deferredPostUpdateNodes took effect synchronously in the body rather than in LIFO order at exit.Beyond mismodeling deferred mutations, this makes it difficult to handle
defercleanly with the sharedVariableCapturelibrary (which will be instantiated in a follow-up PR):VariableCapturereads 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 atdeferregistration (or at a pre-deferreturn), deferred closures read stale registration-time values instead of values written later in the body or by earlier-runningdefers, and capture side effects take effect in the body instead of the epilogue.ArgumentNode,PostUpdateNode,ResultNode,FunctionModels, and backward taint flow.Saving
deferinputs and unnamedreturnvalues into synthetic temporaries in the CFG and IR places deferred call inputs,PostUpdateNodes, andResultNodes at their actual execution points in the epilogue while preserving registration-time evaluation, so both ordinary data flow andVariableCapturecan treat deferred calls uniformly.Summary of this PR
deferregistration into synthetic temporaries (DeferWriteInstruction), restore them in LIFO order before each exit-time invocation (DeferReadInstruction) withpanic/recoverpropagation and process-exit (os.Exit,log.Fatal) bypasses, and save unnamedreturnexpressions into synthetic result temporaries before running deferred calls (WriteUnnamedResultInstruction/ReadUnnamedResultInstruction).CallNodeinputs and unnamedResultNodes through their saved values, and split synchronous from deferredPostUpdateNodes so argument and receiver mutations from adeferflow in LIFO order through the epilogue to later-runningdefers, results, and captures without appearing in the function body.deferand unnamed-result temporaries when safe, update guard and return-property inference to account for deferred mutations andrecover(), and extendclearsanitization across deferred calls.fmtandbunscan 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 syntheticdeferand result nodes.Known limitations
SsaWithFieldsaccess path and direct in-place mutations of named result variables (&res,&res.f,res.ptrMethod()), without general local alias tracking.deferregistration to values referenced by already-saveddeferinputs are not propagated into the saved temporaries.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.