From cc1d45e33933ce459a740b7142c514e96c1590a3 Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Sun, 29 Nov 2026 10:22:28 +0000
Subject: [PATCH 01/17] Go: Lower defer evaluations and unnamed returns in CFG
and IR
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>
---
go/ql/lib/semmle/go/Expr.qll | 14 +-
.../go/controlflow/ControlFlowGraphImpl.qll | 442 +++++++++++++++---
go/ql/lib/semmle/go/controlflow/IR.qll | 383 ++++++++++++++-
.../CONSISTENCY/CfgConsistency.expected | 11 +-
.../CONSISTENCY/CfgConsistency.expected | 4 +-
.../CONSISTENCY/CfgConsistency.expected | 8 +-
.../ControlFlowNode_getASuccessor.expected | 348 ++++++++++++--
.../ControlFlowGraph/NoretFunctions.expected | 5 +
.../go/controlflow/ControlFlowGraph/stmts7.go | 48 ++
.../Twirp/CONSISTENCY/SsaConsistency.expected | 16 +-
10 files changed, 1159 insertions(+), 120 deletions(-)
diff --git a/go/ql/lib/semmle/go/Expr.qll b/go/ql/lib/semmle/go/Expr.qll
index e3db6bd12650..36c2641cae95 100644
--- a/go/ql/lib/semmle/go/Expr.qll
+++ b/go/ql/lib/semmle/go/Expr.qll
@@ -840,6 +840,16 @@ class ConversionExpr extends CallOrConversionExpr {
override string getAPrimaryQlClass() { result = "ConversionExpr" }
}
+private Expr unwrapCalleeExpr(Expr e) {
+ result = unwrapCalleeExpr(e.(ParenExpr).getExpr())
+ or
+ result = unwrapCalleeExpr(e.(GenericFunctionInstantiationExpr).getBase())
+ or
+ not e instanceof ParenExpr and
+ not e instanceof GenericFunctionInstantiationExpr and
+ result = e
+}
+
/**
* A function call expression.
*
@@ -923,8 +933,10 @@ class CallExpr extends CallOrConversionExpr {
*/
SignatureType getCalleeType() { result = this.getCalleeExpr().getType() }
+ private Expr getUnwrappedCalleeExpr() { result = unwrapCalleeExpr(this.getChildExpr(0)) }
+
/** Gets the declared target of this call. */
- Function getTarget() { this.getCalleeExpr() = result.getAReference() }
+ Function getTarget() { this.getUnwrappedCalleeExpr() = result.getAReference() }
/** Holds if this call has an ellipsis after its last argument. */
predicate hasEllipsis() { has_ellipsis(this) }
diff --git a/go/ql/lib/semmle/go/controlflow/ControlFlowGraphImpl.qll b/go/ql/lib/semmle/go/controlflow/ControlFlowGraphImpl.qll
index ccd031ecb48a..4572a0dead74 100644
--- a/go/ql/lib/semmle/go/controlflow/ControlFlowGraphImpl.qll
+++ b/go/ql/lib/semmle/go/controlflow/ControlFlowGraphImpl.qll
@@ -32,6 +32,38 @@ module CfgImpl {
Input1::implicitFieldSelection(e, index, implicitField)
}
+ /** Holds if `fd` contains at least one `defer` statement. */
+ predicate funcHasDefer(Go::FuncDef fd) { Input1::funcHasDefer(fd) }
+
+ /**
+ * Holds if `fd` has an unnamed result at index `i` that needs a synthetic
+ * temporary because `fd` contains a `defer` statement.
+ */
+ predicate hasUnnamedResultTemp(Go::FuncDef fd, int i) { Input1::hasUnnamedResultTemp(fd, i) }
+
+ /** Gets `e` stripped of enclosing parentheses and generic instantiation arguments. */
+ Go::Expr unwrapCallee(Go::Expr e) { result = Input1::unwrapCallee(e) }
+
+ /** Holds if `d` saves a dynamically evaluated callee at registration. */
+ predicate deferHasSavedCallee(Go::DeferStmt d) { Input1::deferHasSavedCallee(d) }
+
+ /** Holds if `d` saves a method-call receiver at registration. */
+ predicate deferHasSavedReceiver(Go::DeferStmt d) { Input1::deferHasSavedReceiver(d) }
+
+ /** Holds if `d` saves syntactic argument `arg` at index `i` (when not tuple-spread). */
+ predicate deferSavedExprArg(Go::DeferStmt d, int i, Go::Expr arg) {
+ Input1::deferSavedExprArg(d, i, arg)
+ }
+
+ /** Holds if `d` saves an argument (either syntactic or tuple-extracted) at index `i`. */
+ predicate deferHasSavedArg(Go::DeferStmt d, int i) { Input1::deferHasSavedArg(d, i) }
+
+ /** Holds if `d` may recover a panic in its enclosing function. */
+ predicate deferMayRecover(Go::DeferStmt d) { Input1::deferMayRecover(d) }
+
+ /** Holds if `d` may be entered while panicking and recover that panic. */
+ predicate deferRecoversPanic(Go::DeferStmt d) { Input1::deferRecoversPanic(d) }
+
/**
* Holds if `root` is a constant root: a constant expression (with any
* enclosing parentheses stripped) whose parent expression is not itself
@@ -118,6 +150,9 @@ module CfgImpl {
insideConstantRoot(e.(Go::Expr))
}
+ /** Holds if `e` is skipped during CFG construction. */
+ additional predicate isSkipped(AstNode e) { skipCfg(e) }
+
AstNode getChild(AstNode n, int index) {
(
not n instanceof Go::FuncDef and
@@ -534,7 +569,7 @@ module CfgImpl {
// Result write nodes in return statements
exists(int i, Go::ReturnStmt ret |
n = ret and
- exists(ret.getEnclosingFunction().getResultVar(i)) and
+ hasResultSlot(ret.getEnclosingFunction(), i) and
exists(ret.getAnExpr()) and
tag = "result-write:" + i.toString()
)
@@ -543,7 +578,7 @@ module CfgImpl {
exists(int i, Go::FuncDef fd |
n = fd.getBody() and
exists(fd.getBody()) and
- exists(fd.getResultVar(i)) and
+ hasResultSlot(fd, i) and
tag = "result-read:" + i.toString()
)
or
@@ -571,15 +606,23 @@ module CfgImpl {
tag = "implicit-field:" + i.toString()
)
or
- // Deferred-call invocation node, placed at function exit by the final-stage defer steps
- n = any(Go::DeferStmt s).getCall() and tag = "defer-invoke"
+ // Deferred-call registration save nodes and exit-time restore/invocation nodes
+ exists(Go::DeferStmt d | n = d.getCall() |
+ deferHasSavedCallee(d) and tag = ["defer-callee-write", "defer-callee-read"]
+ or
+ deferHasSavedReceiver(d) and tag = ["defer-recv-write", "defer-recv-read"]
+ or
+ exists(int i |
+ deferHasSavedArg(d, i) and
+ tag = ["defer-arg-write:" + i.toString(), "defer-arg-read:" + i.toString()]
+ )
+ or
+ tag = "defer-invoke"
+ )
or
n instanceof Go::DeferStmt and tag = "catch-defer-panic"
or
- not n instanceof Go::DeferStmt and
- mayPanic(n) and
- mayDeferParent(n) and
- tag = "catch-panic"
+ catchesRegistrationPanic(n) and tag = "catch-panic"
or
mayReturn(n) and mayDeferParent(n) and tag = "catch-return"
)
@@ -685,11 +728,22 @@ module CfgImpl {
)
}
+ /**
+ * Holds if `call` invokes a function that terminates the process or
+ * goroutine without panicking (for example `os.Exit` or `log.Fatal`).
+ */
+ private predicate isProcessExitCall(Go::CallExpr call) {
+ exists(Go::Function target | target = call.getTarget() |
+ target.mustNotReturnNormally() and not target.mustPanic()
+ )
+ }
+
additional predicate beginAbruptCompletion(
Ast::AstNode ast, PreControlFlowNode n, AbruptCompletion c, boolean always
) {
ast instanceof Go::CallExpr and
not isGoStmtCall(ast) and
+ not isProcessExitCall(ast) and
(
not exists(ast.(Go::CallExpr).getTarget()) or
ast.(Go::CallExpr).getTarget().mayPanic()
@@ -700,6 +754,7 @@ module CfgImpl {
or
ast instanceof Go::CallExpr and
ast = any(Go::DeferStmt defer).getCall() and
+ not isProcessExitCall(ast) and
(
not exists(ast.(Go::CallExpr).getTarget()) or
ast.(Go::CallExpr).getTarget().mayPanic()
@@ -708,28 +763,38 @@ module CfgImpl {
c.asSimpleAbruptCompletion() instanceof ExceptionSuccessor and
always = false
or
- // Calls to functions that never return normally (e.g. `os.Exit`, `log.Fatal`,
- // `panic`) must suppress normal flow past the call site. We emit an `always`
- // exception completion so that the shared library's default In->After step
- // is suppressed.
+ // Calls that always panic (e.g. `panic`, `log.Panic`) suppress normal
+ // flow past the call site and unwind through active `defer` statements.
ast instanceof Go::CallExpr and
not isGoStmtCall(ast) and
- exists(Go::Function target | target = ast.(Go::CallExpr).getTarget() |
- target.mustPanic() or target.mustNotReturnNormally()
- ) and
+ ast.(Go::CallExpr).getTarget().mustPanic() and
n.isIn(ast) and
c.asSimpleAbruptCompletion() instanceof ExceptionSuccessor and
always = true
or
ast instanceof Go::CallExpr and
ast = any(Go::DeferStmt defer).getCall() and
- exists(Go::Function target | target = ast.(Go::CallExpr).getTarget() |
- target.mustPanic() or target.mustNotReturnNormally()
- ) and
+ ast.(Go::CallExpr).getTarget().mustPanic() and
n.isAdditional(ast, "defer-invoke") and
c.asSimpleAbruptCompletion() instanceof ExceptionSuccessor and
always = true
or
+ // Calls that terminate without panicking (e.g. `os.Exit`, `log.Fatal`)
+ // bypass `defer` statements and exit immediately.
+ ast instanceof Go::CallExpr and
+ not isGoStmtCall(ast) and
+ isProcessExitCall(ast) and
+ n.isIn(ast) and
+ c.asSimpleAbruptCompletion() instanceof ExitSuccessor and
+ always = true
+ or
+ ast instanceof Go::CallExpr and
+ ast = any(Go::DeferStmt defer).getCall() and
+ isProcessExitCall(ast) and
+ n.isAdditional(ast, "defer-invoke") and
+ c.asSimpleAbruptCompletion() instanceof ExitSuccessor and
+ always = true
+ or
ast instanceof Go::DivExpr and
not ast.(Go::Expr).isConst() and
n.isIn(ast) and
@@ -770,9 +835,7 @@ module CfgImpl {
n.isAdditional(ast, "catch-defer-panic") and
c.getSuccessorType() instanceof ExceptionSuccessor
or
- not ast instanceof Go::DeferStmt and
- mayPanic(ast) and
- mayDeferParent(ast) and
+ catchesRegistrationPanic(ast) and
n.isAdditional(ast, "catch-panic") and
c.getSuccessorType() instanceof ExceptionSuccessor
or
@@ -852,11 +915,99 @@ module CfgImpl {
exists(Ast::AstNode parent | ast = Ast::getChild(parent, _) and mayDefer(parent))
}
+ /**
+ * Holds if `ast` catches panics occurring during normal execution so they
+ * enter the enclosing function's deferred-call epilogue.
+ *
+ * `d.getCall()` itself is excluded because `"defer-invoke"` is attached to
+ * `d.getCall()` and its exit-time panics must bubble to `d`'s
+ * `"catch-defer-panic"` node instead; registration-time panics in subexpressions
+ * of `d.getCall()` are caught on its direct CFG children.
+ */
+ private predicate catchesRegistrationPanic(Ast::AstNode ast) {
+ not ast instanceof Go::DeferStmt and
+ not ast = any(Go::DeferStmt d).getCall() and
+ mayPanic(ast) and
+ (
+ mayDeferParent(ast)
+ or
+ ast = Ast::getChild(any(Go::DeferStmt d).getCall(), _)
+ )
+ }
+
/** Holds if `fd` contains at least one `defer` statement. */
- private predicate funcHasDefer(Go::FuncDef fd) {
+ additional predicate funcHasDefer(Go::FuncDef fd) {
exists(Go::DeferStmt s | s.getEnclosingFunction() = fd)
}
+ /**
+ * Holds if `fd` has a result slot at index `i` that is written on `return`
+ * and read at function exit: either a named result variable, or any result
+ * of a function containing a `defer` statement.
+ */
+ private predicate hasResultSlot(Go::FuncDef fd, int i) {
+ exists(fd.getResultVar(i))
+ or
+ funcHasDefer(fd) and exists(fd.getType().getResultType(i))
+ }
+
+ /**
+ * Holds if `fd` has an unnamed result at index `i` that uses a synthetic
+ * temporary because `fd` contains a `defer` statement.
+ */
+ additional predicate hasUnnamedResultTemp(Go::FuncDef fd, int i) {
+ funcHasDefer(fd) and
+ not exists(fd.getResultVar(i)) and
+ exists(fd.getType().getResultType(i))
+ }
+
+ additional Go::Expr unwrapCallee(Go::Expr e) {
+ result = unwrapCallee(e.(Go::ParenExpr).getExpr())
+ or
+ result = unwrapCallee(e.(Go::GenericFunctionInstantiationExpr).getBase())
+ or
+ not e instanceof Go::ParenExpr and
+ not e instanceof Go::GenericFunctionInstantiationExpr and
+ result = e
+ }
+
+ /** Holds if `d` saves a method-call receiver at registration. */
+ additional predicate deferHasSavedReceiver(Go::DeferStmt d) {
+ exists(Go::SelectorExpr sel |
+ sel = unwrapCallee(d.getCall().getCalleeExpr()) and
+ not Ast::isSkipped(sel) and
+ not Ast::isSkipped(sel.getBase().stripParens()) and
+ sel.getSelector() = any(Go::Method m).getAReference() and
+ sel.getBase().stripParens() instanceof Go::ValueExpr
+ )
+ }
+
+ /** Holds if `d` saves a dynamically evaluated callee at registration. */
+ additional predicate deferHasSavedCallee(Go::DeferStmt d) {
+ not unwrapCallee(d.getCall().getCalleeExpr()) = any(Go::Function fn).getAReference() and
+ not Ast::isSkipped(d.getCall().getCalleeExpr().stripParens())
+ }
+
+ /** Holds if `d` saves syntactic argument `arg` at index `i` (when not tuple-spread). */
+ additional predicate deferSavedExprArg(Go::DeferStmt d, int i, Go::Expr arg) {
+ not extractNodeCondition(d.getCall(), _) and
+ arg =
+ rank[i + 1](Go::Expr a, int j |
+ a = d.getCall().getArgument(j) and
+ not a.stripParens() instanceof Go::TypeExpr
+ |
+ a order by j
+ ) and
+ not Ast::isSkipped(arg.stripParens())
+ }
+
+ /** Holds if `d` saves an argument (either syntactic or tuple-extracted) at index `i`. */
+ additional predicate deferHasSavedArg(Go::DeferStmt d, int i) {
+ extractNodeCondition(d.getCall(), i)
+ or
+ deferSavedExprArg(d, i, _)
+ }
+
/**
* Holds if `n` is the registration node of `defer` statement `s` (the
* post-order node of the statement, reached once its call's arguments have
@@ -872,8 +1023,37 @@ module CfgImpl {
n.isAdditional(s.getCall(), "defer-invoke")
}
+ private string getDeferInvokeTag(Go::DeferStmt d, int ord) {
+ deferHasSavedCallee(d) and result = "defer-callee-read" and ord = -2
+ or
+ deferHasSavedReceiver(d) and result = "defer-recv-read" and ord = -1
+ or
+ exists(int i |
+ deferHasSavedArg(d, i) and
+ result = "defer-arg-read:" + i.toString() and
+ ord = i
+ )
+ or
+ exists(d) and
+ result = "defer-invoke" and
+ ord = 1 + max(int k | k = -1 or deferHasSavedArg(d, k))
+ }
+
+ private string getRankedDeferInvokeTag(Go::DeferStmt d, int rnk) {
+ result = rank[rnk](string tag, int ord | tag = getDeferInvokeTag(d, ord) | tag order by ord)
+ }
+
+ /**
+ * Holds if `n` is the entry node of the exit-time invocation sequence of
+ * `defer` statement `d` (first saved-value restore node, or `defer-invoke`
+ * itself if `d` has no saved values).
+ */
+ private predicate deferInvokeEntry(PreControlFlowNode n, Go::DeferStmt d) {
+ n.isAdditional(d.getCall(), getRankedDeferInvokeTag(d, 1))
+ }
+
/** Holds if invoking deferred call `s` may return normally. */
- private predicate deferInvocationMayReturnNormally(Go::DeferStmt s) {
+ additional predicate deferInvocationMayReturnNormally(Go::DeferStmt s) {
not exists(Go::Function target | target = s.getCall().getTarget() |
target.mustPanic() or target.mustNotReturnNormally()
)
@@ -881,8 +1061,47 @@ module CfgImpl {
/** Holds if invoking deferred call `s` terminates without panic unwinding. */
private predicate deferInvocationStopsUnwinding(Go::DeferStmt s) {
- exists(Go::Function target | target = s.getCall().getTarget() |
- target.mustNotReturnNormally() and not target.mustPanic()
+ isProcessExitCall(s.getCall())
+ }
+
+ /** Holds if invoking deferred call `s` may panic. */
+ additional predicate deferInvocationMayPanic(Go::DeferStmt s) {
+ not deferInvocationStopsUnwinding(s) and
+ (
+ not exists(s.getCall().getTarget()) or
+ s.getCall().getTarget().mayPanic()
+ )
+ }
+
+ /**
+ * Holds if `d` may recover a panic in its enclosing function.
+ *
+ * In Go, `recover` only stops panicking when called directly by a deferred
+ * function (and built-in functions cannot be used as function values).
+ */
+ additional predicate deferMayRecover(Go::DeferStmt d) {
+ exists(Go::CallExpr call | call = d.getCall() |
+ not call.getTarget() instanceof Go::BuiltinFunction and
+ (
+ exists(Go::FuncLit fl, Go::CallExpr rec |
+ fl = unwrapCallee(call.getCalleeExpr()) and
+ rec.getTarget() = Go::Builtin::recover() and
+ rec.getEnclosingFunction() = fl
+ )
+ or
+ not unwrapCallee(call.getCalleeExpr()) instanceof Go::FuncLit and
+ (
+ not exists(call.getTarget().getBody())
+ or
+ call.getTarget().getBody().getFile().hasBuildConstraints()
+ or
+ exists(Go::FuncDecl targetDecl, Go::CallExpr rec |
+ targetDecl = call.getTarget().getFuncDecl() and
+ rec.getTarget() = Go::Builtin::recover() and
+ rec.getEnclosingFunction() = targetDecl
+ )
+ )
+ )
)
}
@@ -921,7 +1140,7 @@ module CfgImpl {
* hence the last to run: its registration node is reachable from the entry
* node without passing through another registration node.
*/
- private predicate firstRegisteredDefer(Go::DeferStmt s, Go::FuncDef fd) {
+ additional predicate firstRegisteredDefer(Go::DeferStmt s, Go::FuncDef fd) {
s.getEnclosingFunction() = fd and
exists(PreControlFlowNode reg, PreControlFlowNode m |
deferRegistration(reg, s) and
@@ -976,18 +1195,89 @@ module CfgImpl {
/**
* Holds if, after running its deferred calls, `fd` should continue at
- * `target` on a normal exit. For functions with result variables this is
- * the start of the result-read epilogue; otherwise it is the function
- * body's `After` node.
+ * `target` on a normal exit. For functions with result slots this is the
+ * start of the result-read epilogue; otherwise it is the function body's
+ * `After` node.
*/
private predicate deferChainExitTarget(Go::FuncDef fd, PreControlFlowNode target) {
- exists(fd.getResultVar(0)) and target.isAdditional(fd.getBody(), "result-read:0")
+ hasResultSlot(fd, 0) and target.isAdditional(fd.getBody(), "result-read:0")
or
- not exists(fd.getResultVar(_)) and target.isAfter(fd.getBody())
+ not hasResultSlot(fd, _) and target.isAfter(fd.getBody())
+ }
+
+ /**
+ * Holds if deferred statement `d` may be entered from a normal exit of its
+ * enclosing function or after a later-registered `defer` finishes normally.
+ */
+ private predicate deferEnteredNormally(Go::DeferStmt d) {
+ exists(PreControlFlowNode n, PreControlFlowNode reg |
+ deferRegistration(reg, d) and
+ reg instanceof EarlyCfg2::ControlFlowNode and
+ normalExitPred(n, d.getEnclosingFunction()) and
+ n = reachableBeforeNextDeferRegistration(reg)
+ )
+ or
+ exists(Go::DeferStmt later |
+ nextRegisteredDefer(later, d) and
+ deferExitsNormally(later)
+ )
+ }
+
+ /**
+ * Holds if deferred statement `d` may be entered while an unrecovered panic
+ * is unwinding.
+ */
+ private predicate deferEnteredPanicking(Go::DeferStmt d) {
+ exists(PreControlFlowNode n, PreControlFlowNode reg |
+ deferRegistration(reg, d) and
+ reg instanceof EarlyCfg2::ControlFlowNode and
+ exceptionalExitPred(n, d.getEnclosingFunction()) and
+ n = reachableBeforeNextDeferRegistration(reg)
+ )
+ or
+ exists(Go::DeferStmt later | nextRegisteredDefer(later, d) |
+ deferExitsWithPriorPanic(later)
+ or
+ (deferEnteredNormally(later) or deferEnteredPanicking(later)) and
+ deferInvocationMayPanic(later)
+ )
+ }
+
+ /**
+ * Holds if `d` may be entered while panicking and recover that panic.
+ */
+ additional predicate deferRecoversPanic(Go::DeferStmt d) {
+ deferEnteredPanicking(d) and
+ deferMayRecover(d) and
+ deferInvocationMayReturnNormally(d)
+ }
+
+ /**
+ * Holds if `d` may finish with normal control flow (either because it was
+ * entered normally and returns normally, or because it recovers a panic).
+ */
+ additional predicate deferExitsNormally(Go::DeferStmt d) {
+ deferInvocationMayReturnNormally(d) and
+ (deferEnteredNormally(d) or deferRecoversPanic(d))
+ }
+
+ /**
+ * Holds if `d` may return normally while an earlier panic remains active.
+ */
+ additional predicate deferExitsWithPriorPanic(Go::DeferStmt d) {
+ deferInvocationMayReturnNormally(d) and
+ deferEnteredPanicking(d)
}
additional predicate finalDeferStep(PreControlFlowNode n1, PreControlFlowNode n2) {
exists(Go::FuncDef fd | funcHasDefer(fd) |
+ // restore saved callee/receiver/arguments in order before invoking the deferred call
+ exists(Go::DeferStmt d, int rnk |
+ d.getEnclosingFunction() = fd and
+ n1.isAdditional(d.getCall(), getRankedDeferInvokeTag(d, rnk)) and
+ n2.isAdditional(d.getCall(), getRankedDeferInvokeTag(d, rnk + 1))
+ )
+ or
// an exit predecessor with no active defer flows straight to the exit target
normalExitPred(n1, fd) and
n1 = reachableBeforeNextDeferRegistration(funcEntry(fd)) and
@@ -999,57 +1289,56 @@ module CfgImpl {
d.getEnclosingFunction() = fd and
normalExitPred(n1, fd) and
n1 = reachableBeforeNextDeferRegistration(reg) and
- deferInvoke(n2, d)
+ deferInvokeEntry(n2, d)
)
or
// deferred invocations chain in last-in-first-out order
exists(Go::DeferStmt laterRegistered, Go::DeferStmt earlierRegistered |
laterRegistered.getEnclosingFunction() = fd and
nextRegisteredDefer(laterRegistered, earlierRegistered) and
- not deferInvocationStopsUnwinding(laterRegistered) and
+ (deferExitsNormally(laterRegistered) or deferExitsWithPriorPanic(laterRegistered)) and
deferInvoke(n1, laterRegistered) and
- deferInvoke(n2, earlierRegistered)
+ deferInvokeEntry(n2, earlierRegistered)
)
or
// a panic in a deferred invocation continues unwinding through earlier defers
exists(Go::DeferStmt laterRegistered, Go::DeferStmt earlierRegistered |
laterRegistered.getEnclosingFunction() = fd and
nextRegisteredDefer(laterRegistered, earlierRegistered) and
- not deferInvocationStopsUnwinding(laterRegistered) and
+ (deferEnteredNormally(laterRegistered) or deferEnteredPanicking(laterRegistered)) and
+ deferInvocationMayPanic(laterRegistered) and
n1.isAdditional(laterRegistered, "catch-defer-panic") and
- deferInvoke(n2, earlierRegistered)
+ deferInvokeEntry(n2, earlierRegistered)
)
or
// the invocation of the first-registered (last to run) defer flows to the exit target
exists(Go::DeferStmt firstD |
firstRegisteredDefer(firstD, fd) and
- deferInvocationMayReturnNormally(firstD) and
+ deferExitsNormally(firstD) and
deferInvoke(n1, firstD) and
deferChainExitTarget(fd, n2)
)
or
- // a panic in the first-registered defer finishes at the exceptional exit
+ // a panic in or unwinding through the first-registered defer finishes at the exceptional exit
exists(Go::DeferStmt firstD |
firstRegisteredDefer(firstD, fd) and
+ (
+ (deferEnteredNormally(firstD) or deferEnteredPanicking(firstD)) and
+ deferInvocationMayPanic(firstD)
+ or
+ deferExitsWithPriorPanic(firstD)
+ ) and
n1.isAdditional(firstD, "catch-defer-panic") and
n2.(ExceptionalExitNodeImpl).getEnclosingCallable() = fd
)
or
- // a non-panicking, non-returning deferred call stops unwinding immediately
- exists(Go::DeferStmt d |
- d.getEnclosingFunction() = fd and
- deferInvocationStopsUnwinding(d) and
- n1.isAdditional(d, "catch-defer-panic") and
- n2.(ExceptionalExitNodeImpl).getEnclosingCallable() = fd
- )
- or
// a possible panic with active defers flows to the last-registered active defer
exists(Go::DeferStmt d, PreControlFlowNode reg |
deferRegistration(reg, d) and
d.getEnclosingFunction() = fd and
exceptionalExitPred(n1, fd) and
n1 = reachableBeforeNextDeferRegistration(reg) and
- deferInvoke(n2, d)
+ deferInvokeEntry(n2, d)
)
or
// a possible panic with no active defer flows to the exceptional exit
@@ -1198,15 +1487,30 @@ module CfgImpl {
/** Gets a result-write epilogue tag and its order. */
private string getResultWriteEpilogueTag(Ast::AstNode node, int ord) {
- exists(int i, Go::ReturnStmt ret, Go::ResultVariable rv |
+ exists(int i, Go::ReturnStmt ret |
node = ret and
- ret.getEnclosingFunction().getResultVar(i) = rv and
+ hasResultSlot(ret.getEnclosingFunction(), i) and
exists(ret.getAnExpr()) and
result = "result-write:" + i.toString() and
ord = 2 * i + 1
)
}
+ /** Gets a deferred-call registration save tag and its order. */
+ private string getDeferWriteEpilogueTag(Ast::AstNode node, int ord) {
+ exists(Go::DeferStmt d | node = d.getCall() |
+ deferHasSavedCallee(d) and result = "defer-callee-write" and ord = -2
+ or
+ deferHasSavedReceiver(d) and result = "defer-recv-write" and ord = -1
+ or
+ exists(int i |
+ deferHasSavedArg(d, i) and
+ result = "defer-arg-write:" + i.toString() and
+ ord = 2 * i + 1
+ )
+ )
+ }
+
/** Gets an epilogue tag and its order. */
private string getEpilogueTag(Ast::AstNode node, int ord) {
result = getExtractionEpilogueTag(node, ord)
@@ -1214,6 +1518,8 @@ module CfgImpl {
result = getAssignmentEpilogueTag(node, ord)
or
result = getResultWriteEpilogueTag(node, ord)
+ or
+ result = getDeferWriteEpilogueTag(node, ord)
}
private string getRankedEpilogueTag(Ast::AstNode node, int rnk) {
@@ -1275,6 +1581,18 @@ module CfgImpl {
n2.isAfter(call) and
not beginAbruptCompletion(call, n1, _, true)
)
+ or
+ // Deferred call registration: evaluate callee/receiver/arguments, extract
+ // any spread tuple elements, and save them into synthetic temporaries
+ // before registering the `defer` statement.
+ exists(Go::DeferStmt d, Go::CallExpr call |
+ call = d.getCall() and
+ exists(getFirstEpilogueTag(call))
+ |
+ epilogueStep(call, n1, n2)
+ or
+ n1.isAdditional(call, getLastEpilogueTag(call)) and n2.isAfter(call)
+ )
}
/**
@@ -1656,7 +1974,7 @@ module CfgImpl {
)
)
or
- exists(int j | exists(fd.getResultVar(j + 1)) |
+ exists(int j | hasResultSlot(fd, j) and hasResultSlot(fd, j + 1) |
n1.isAdditional(fd.getBody(), "result-read:" + j.toString()) and
n2.isAdditional(fd.getBody(), "result-read:" + (j + 1).toString())
)
@@ -1667,8 +1985,8 @@ module CfgImpl {
n2.isAdditional(fd.getBody(), "result-read:0")
or
exists(int j |
- exists(fd.getResultVar(j)) and
- not exists(fd.getResultVar(j + 1)) and
+ hasResultSlot(fd, j) and
+ not hasResultSlot(fd, j + 1) and
n1.isAdditional(fd.getBody(), "result-read:" + j.toString()) and
n2.isAfter(fd.getBody())
)
@@ -1697,7 +2015,11 @@ module CfgImpl {
exists(Go::FuncDef fd |
ast = fd.getBody() and
c.getSuccessorType() instanceof ReturnSuccessor and
- exists(fd.getResultVar(0)) and
+ Input1::funcHasDefer(fd) and
+ (
+ exists(fd.getResultVar(0)) or
+ exists(fd.getType().getResultType(0))
+ ) and
n.isAdditional(fd.getBody(), "result-read:0")
)
}
@@ -1711,6 +2033,20 @@ module CfgImpl {
Ast::AstNode ast, PreControlFlowNode n, AbruptCompletion c, boolean always
) {
Input1::beginAbruptCompletion(ast, n, c, always)
+ or
+ // An unrecovered panic entering the defer chain exits exceptionally after
+ // the first-registered (last-to-run) defer finishes, even if that defer's
+ // callee cannot panic itself (for example `defer clear(s)`).
+ exists(Go::DeferStmt firstD, Go::FuncDef fd |
+ firstD.getEnclosingFunction() = fd and
+ Input1::firstRegisteredDefer(firstD, fd) and
+ Input1::deferExitsWithPriorPanic(firstD) and
+ not Input1::deferInvocationMayPanic(firstD) and
+ ast = firstD.getCall() and
+ n.isAdditional(ast, "defer-invoke") and
+ c.asSimpleAbruptCompletion() instanceof ExceptionSuccessor and
+ if Input1::deferExitsNormally(firstD) then always = false else always = true
+ )
}
predicate endAbruptCompletion(Ast::AstNode ast, PreControlFlowNode n, AbruptCompletion c) {
diff --git a/go/ql/lib/semmle/go/controlflow/IR.qll b/go/ql/lib/semmle/go/controlflow/IR.qll
index fd67de61f4c2..aad346d6c942 100644
--- a/go/ql/lib/semmle/go/controlflow/IR.qll
+++ b/go/ql/lib/semmle/go/controlflow/IR.qll
@@ -106,6 +106,20 @@ module IR {
/** Holds if this instruction updates variable or constant `v` to the value of `rhs`. */
predicate writes(ValueEntity v, Instruction rhs) { this.writesField(_, v, rhs) }
+ /**
+ * INTERNAL: Do not use.
+ *
+ * Holds if this instruction reads synthetic temporary variable `v`.
+ */
+ predicate readsTemp(TempVariable v) { none() }
+
+ /**
+ * INTERNAL: Do not use.
+ *
+ * Holds if this instruction updates synthetic temporary variable `v` to `rhs`.
+ */
+ predicate writesTemp(TempVariable v, Instruction rhs) { none() }
+
/** Holds if this instruction reads the value of field `f` on the value of `base`. */
predicate readsField(Instruction base, Field f) { none() }
@@ -192,6 +206,14 @@ module IR {
or
this instanceof ReadResultInstruction and result = "result read"
or
+ this instanceof WriteUnnamedResultInstruction and result = "result write"
+ or
+ this instanceof ReadUnnamedResultInstruction and result = "result read"
+ or
+ this instanceof DeferWriteInstruction and result = "defer save"
+ or
+ this instanceof DeferReadInstruction and result = "defer restore"
+ or
this instanceof InitParameterInstruction and result = "parameter initialization"
or
this instanceof GetNextEntryInstruction and result = "next key-value pair"
@@ -306,7 +328,7 @@ module IR {
result = implicitDerefInstruction(base)
or
not exists(implicitDerefInstruction(base)) and
- result = evalExprInstruction(base)
+ result = evalExprInstruction(base.stripParens())
)
}
@@ -374,7 +396,7 @@ module IR {
result = implicitDerefInstruction(e.getBase())
or
not exists(implicitDerefInstruction(e.getBase())) and
- result = evalExprInstruction(e.getBase())
+ result = evalExprInstruction(e.getBase().stripParens())
)
}
@@ -420,7 +442,7 @@ module IR {
result = implicitDerefInstruction(sel.getBase())
or
not exists(implicitDerefInstruction(sel.getBase())) and
- result = evalExprInstruction(sel.getBase())
+ result = evalExprInstruction(sel.getBase().stripParens())
)
}
@@ -736,7 +758,7 @@ module IR {
or
result.(GetNextEntryInstruction).isAdditional(s, "next")
or
- result = evalExprInstruction(s.(ReturnStmt).getExpr())
+ result = evalExprInstruction(s.(ReturnStmt).getExpr().stripParens())
or
result = evalExprInstruction(s.(CallExpr).getArgument(0).stripParens())
}
@@ -895,7 +917,7 @@ module IR {
/** Gets the instruction whose result is the (unique) result returned by this statement. */
Instruction getResult() {
not this.returnsMultipleResults() and
- result = evalExprInstruction(ret.getExpr())
+ result = evalExprInstruction(ret.getExpr().stripParens())
}
/** Gets the instruction whose result is the `i`th result returned by this statement. */
@@ -904,7 +926,7 @@ module IR {
result.(ExtractTupleElementInstruction).extractsElement(_, i)
or
not exists(ExtractTupleElementInstruction ext | ext.isAdditional(ret, _)) and
- result = evalExprInstruction(ret.getExpr(i))
+ result = evalExprInstruction(ret.getExpr(i).stripParens())
}
}
@@ -952,6 +974,342 @@ module IR {
override Type getResultType() { result = var.getType() }
}
+ private Instruction deferSavedCalleeInstruction(DeferStmt d) {
+ CfgImpl::deferHasSavedCallee(d) and
+ result = evalExprInstruction(d.getCall().getCalleeExpr().stripParens())
+ }
+
+ private Instruction deferSavedReceiverInstruction(DeferStmt d) {
+ CfgImpl::deferHasSavedReceiver(d) and
+ result = selectorBase(CfgImpl::unwrapCallee(d.getCall().getCalleeExpr()))
+ }
+
+ private Instruction deferSavedArgInstruction(DeferStmt d, int i) {
+ exists(CallExpr call | call = d.getCall() |
+ call.getArgument(0).stripParens().getType() instanceof TupleType and
+ call.getNumArgument() = 1 and
+ result = extractTupleElement(evalExprInstruction(call.getArgument(0).stripParens()), i)
+ or
+ exists(Expr arg |
+ CfgImpl::deferSavedExprArg(d, i, arg) and
+ result = evalExprInstruction(arg.stripParens())
+ )
+ )
+ }
+
+ /**
+ * INTERNAL: Do not use.
+ *
+ * A synthetic temporary variable used to save `defer` callees, receivers,
+ * and arguments at registration time, or unnamed function results before
+ * `defer` execution.
+ */
+ cached
+ private newtype TTempVariable =
+ /** A synthetic temporary variable holding the saved callee of `d`. */
+ MkDeferCalleeTemp(DeferStmt d) { exists(deferSavedCalleeInstruction(d)) } or
+ /** A synthetic temporary variable holding the saved receiver of `d`. */
+ MkDeferReceiverTemp(DeferStmt d) { exists(deferSavedReceiverInstruction(d)) } or
+ /** A synthetic temporary variable holding the saved `i`th argument of `d`. */
+ MkDeferArgTemp(DeferStmt d, int i) { exists(deferSavedArgInstruction(d, i)) } or
+ /** A synthetic temporary variable holding the `i`th unnamed result of `fd`. */
+ MkUnnamedResultTemp(FuncDef fd, int i) { CfgImpl::hasUnnamedResultTemp(fd, i) }
+
+ /**
+ * INTERNAL: Do not use.
+ *
+ * A synthetic temporary variable used in functions with `defer` statements.
+ */
+ class TempVariable extends TTempVariable {
+ /** Gets the function enclosing this synthetic temporary variable. */
+ FuncDef getEnclosingFunction() {
+ exists(DeferStmt d |
+ this = MkDeferCalleeTemp(d) or
+ this = MkDeferReceiverTemp(d) or
+ this = MkDeferArgTemp(d, _)
+ |
+ result = d.getEnclosingFunction()
+ )
+ or
+ this = MkUnnamedResultTemp(result, _)
+ }
+
+ /** Gets the type of values stored in this synthetic temporary variable. */
+ Type getType() {
+ exists(DeferStmt d | this = MkDeferCalleeTemp(d) |
+ result = deferSavedCalleeInstruction(d).getResultType()
+ )
+ or
+ exists(DeferStmt d | this = MkDeferReceiverTemp(d) |
+ result = deferSavedReceiverInstruction(d).getResultType()
+ )
+ or
+ exists(DeferStmt d, int i | this = MkDeferArgTemp(d, i) |
+ result = deferSavedArgInstruction(d, i).getResultType()
+ )
+ or
+ exists(FuncDef fd, int i | this = MkUnnamedResultTemp(fd, i) |
+ result = fd.getType().getResultType(i)
+ )
+ }
+
+ /** Gets a textual representation of this synthetic temporary variable. */
+ string toString() {
+ this = MkDeferCalleeTemp(_) and result = "defer callee temp"
+ or
+ this = MkDeferReceiverTemp(_) and result = "defer receiver temp"
+ or
+ exists(int i | this = MkDeferArgTemp(_, i) and result = "defer arg " + i + " temp")
+ or
+ exists(int i | this = MkUnnamedResultTemp(_, i) and result = "unnamed result " + i + " temp")
+ }
+
+ /** Gets the source location of this synthetic temporary variable. */
+ Location getLocation() {
+ exists(DeferStmt d |
+ this = MkDeferCalleeTemp(d) and result = deferSavedCalleeInstruction(d).getLocation()
+ or
+ this = MkDeferReceiverTemp(d) and result = deferSavedReceiverInstruction(d).getLocation()
+ or
+ exists(int i | this = MkDeferArgTemp(d, i) |
+ result = deferSavedArgInstruction(d, i).getLocation()
+ )
+ )
+ or
+ exists(FuncDef fd | this = MkUnnamedResultTemp(fd, _) and result = fd.getLocation())
+ }
+ }
+
+ /**
+ * INTERNAL: Do not use.
+ *
+ * An instruction that saves a callee, receiver, or argument of a `defer`
+ * statement into a synthetic temporary at registration time.
+ */
+ abstract class DeferWriteInstruction extends Instruction {
+ DeferStmt d;
+
+ /** Gets the `defer` statement whose value is saved. */
+ DeferStmt getDeferStmt() { result = d }
+
+ /** Gets the synthetic temporary variable written by this instruction. */
+ abstract TempVariable getTempVariable();
+
+ /** Gets the instruction computing the saved value. */
+ abstract Instruction getRhs();
+
+ override predicate writesTemp(TempVariable v, Instruction rhs) {
+ v = this.getTempVariable() and rhs = this.getRhs()
+ }
+
+ override Type getResultType() { result = this.getRhs().getResultType() }
+ }
+
+ /** INTERNAL: Do not use. Saves a deferred callee at registration. */
+ class DeferWriteCalleeInstruction extends DeferWriteInstruction {
+ DeferWriteCalleeInstruction() {
+ exists(MkDeferCalleeTemp(d)) and
+ this.isAdditional(d.getCall(), "defer-callee-write")
+ }
+
+ override TempVariable getTempVariable() { result = MkDeferCalleeTemp(d) }
+
+ override Instruction getRhs() { result = deferSavedCalleeInstruction(d) }
+ }
+
+ /** INTERNAL: Do not use. Saves a deferred method receiver at registration. */
+ class DeferWriteReceiverInstruction extends DeferWriteInstruction {
+ DeferWriteReceiverInstruction() {
+ exists(MkDeferReceiverTemp(d)) and
+ this.isAdditional(d.getCall(), "defer-recv-write")
+ }
+
+ override TempVariable getTempVariable() { result = MkDeferReceiverTemp(d) }
+
+ override Instruction getRhs() { result = deferSavedReceiverInstruction(d) }
+ }
+
+ /** INTERNAL: Do not use. Saves a deferred call argument at registration. */
+ class DeferWriteArgInstruction extends DeferWriteInstruction {
+ int i;
+
+ DeferWriteArgInstruction() {
+ exists(MkDeferArgTemp(d, i)) and
+ this.isAdditional(d.getCall(), "defer-arg-write:" + i.toString())
+ }
+
+ /** Gets the argument index. */
+ int getIndex() { result = i }
+
+ override TempVariable getTempVariable() { result = MkDeferArgTemp(d, i) }
+
+ override Instruction getRhs() { result = deferSavedArgInstruction(d, i) }
+ }
+
+ private BasicBlock reachableFromDeferSave(BasicBlock start) {
+ exists(DeferReadInstruction dr | start = dr.getSavedInstruction().getBasicBlock()) and
+ result = start.getASuccessor()
+ or
+ result = reachableFromDeferSave(start).getASuccessor()
+ }
+
+ /**
+ * INTERNAL: Do not use.
+ *
+ * An instruction that restores a saved callee, receiver, or argument of a
+ * `defer` statement right before the deferred call runs at function exit.
+ */
+ abstract class DeferReadInstruction extends Instruction {
+ DeferStmt d;
+
+ /** Gets the `defer` statement whose saved value is restored. */
+ DeferStmt getDeferStmt() { result = d }
+
+ /** Gets the synthetic temporary variable read by this instruction. */
+ abstract TempVariable getTempVariable();
+
+ /** Gets the instruction whose value was saved at registration time. */
+ abstract Instruction getSavedInstruction();
+
+ /**
+ * Holds if the registration-time instruction saved by this read lies on a
+ * control-flow cycle, meaning the `defer` may be registered multiple times.
+ */
+ predicate isSavedInLoop() {
+ exists(BasicBlock bb |
+ bb = this.getSavedInstruction().getBasicBlock() and
+ reachableFromDeferSave(bb) = bb
+ )
+ }
+
+ override predicate readsTemp(TempVariable v) { v = this.getTempVariable() }
+
+ override Type getResultType() { result = this.getSavedInstruction().getResultType() }
+
+ override float getFloatValue() { result = this.getSavedInstruction().getFloatValue() }
+
+ override int getIntValue() { result = this.getSavedInstruction().getIntValue() }
+
+ override predicate hasComplexValue(float real, float imag) {
+ this.getSavedInstruction().hasComplexValue(real, imag)
+ }
+
+ override string getExactValue() { result = this.getSavedInstruction().getExactValue() }
+
+ override string getStringValue() { result = this.getSavedInstruction().getStringValue() }
+
+ override boolean getBoolValue() { result = this.getSavedInstruction().getBoolValue() }
+
+ override predicate isConst() { this.getSavedInstruction().isConst() }
+
+ override predicate isPlatformIndependentConstant() {
+ this.getSavedInstruction().isPlatformIndependentConstant()
+ }
+ }
+
+ /** INTERNAL: Do not use. Restores a deferred callee before invocation. */
+ class DeferReadCalleeInstruction extends DeferReadInstruction {
+ DeferReadCalleeInstruction() {
+ exists(MkDeferCalleeTemp(d)) and
+ this.isAdditional(d.getCall(), "defer-callee-read")
+ }
+
+ override TempVariable getTempVariable() { result = MkDeferCalleeTemp(d) }
+
+ override Instruction getSavedInstruction() { result = deferSavedCalleeInstruction(d) }
+ }
+
+ /** INTERNAL: Do not use. Restores a deferred method receiver before invocation. */
+ class DeferReadReceiverInstruction extends DeferReadInstruction {
+ DeferReadReceiverInstruction() {
+ exists(MkDeferReceiverTemp(d)) and
+ this.isAdditional(d.getCall(), "defer-recv-read")
+ }
+
+ override TempVariable getTempVariable() { result = MkDeferReceiverTemp(d) }
+
+ override Instruction getSavedInstruction() { result = deferSavedReceiverInstruction(d) }
+ }
+
+ /** INTERNAL: Do not use. Restores a deferred argument before invocation. */
+ class DeferReadArgInstruction extends DeferReadInstruction {
+ int i;
+
+ DeferReadArgInstruction() {
+ exists(MkDeferArgTemp(d, i)) and
+ this.isAdditional(d.getCall(), "defer-arg-read:" + i.toString())
+ }
+
+ /** Gets the argument index. */
+ int getIndex() { result = i }
+
+ override TempVariable getTempVariable() { result = MkDeferArgTemp(d, i) }
+
+ override Instruction getSavedInstruction() { result = deferSavedArgInstruction(d, i) }
+ }
+
+ /**
+ * INTERNAL: Do not use.
+ *
+ * An instruction that saves an unnamed returned value into a synthetic
+ * temporary before deferred calls run.
+ */
+ class WriteUnnamedResultInstruction extends Instruction {
+ int idx;
+ ReturnStmt retStmt;
+ FuncDef fd;
+
+ WriteUnnamedResultInstruction() {
+ this.isAdditional(retStmt, "result-write:" + idx.toString()) and
+ fd = retStmt.getEnclosingFunction() and
+ CfgImpl::hasUnnamedResultTemp(fd, idx) and
+ exists(retStmt.getAnExpr())
+ }
+
+ private ReturnInstruction getReturnInstruction() { result.getReturnStmt() = retStmt }
+
+ /** Gets the instruction computing the returned value. */
+ Instruction getRhs() { result = this.getReturnInstruction().getResult(idx) }
+
+ /** Gets the enclosing function. */
+ FuncDef getFunction() { result = fd }
+
+ /** Gets the result index. */
+ int getIndex() { result = idx }
+
+ override predicate writesTemp(TempVariable v, Instruction rhs) {
+ v = MkUnnamedResultTemp(fd, idx) and rhs = this.getRhs()
+ }
+
+ override Type getResultType() { result = fd.getType().getResultType(idx) }
+ }
+
+ /**
+ * INTERNAL: Do not use.
+ *
+ * An instruction that reads the final value of an unnamed result temporary
+ * after deferred calls have run.
+ */
+ class ReadUnnamedResultInstruction extends Instruction {
+ int idx;
+ FuncDef fd;
+
+ ReadUnnamedResultInstruction() {
+ this.isAdditional(fd.getBody(), "result-read:" + idx.toString()) and
+ CfgImpl::hasUnnamedResultTemp(fd, idx)
+ }
+
+ /** Gets the enclosing function. */
+ FuncDef getFunction() { result = fd }
+
+ /** Gets the result index. */
+ int getIndex() { result = idx }
+
+ override predicate readsTemp(TempVariable v) { v = MkUnnamedResultTemp(fd, idx) }
+
+ override Type getResultType() { result = fd.getType().getResultType(idx) }
+ }
+
/** An instruction initializing a parameter to the corresponding argument. */
class InitParameterInstruction extends WriteInstruction {
Parameter parm;
@@ -1382,4 +1740,17 @@ module IR {
Instruction lookThroughImplicitFieldRead(Instruction insn) {
result = insn.(ImplicitFieldReadInstruction).getBaseInstruction()
}
+
+ /** INTERNAL: Do not use. Gets the instruction restoring the saved callee of `d`. */
+ DeferReadCalleeInstruction deferReadCalleeInstruction(DeferStmt d) { result.getDeferStmt() = d }
+
+ /** INTERNAL: Do not use. Gets the instruction restoring the saved receiver of `d`. */
+ DeferReadReceiverInstruction deferReadReceiverInstruction(DeferStmt d) {
+ result.getDeferStmt() = d
+ }
+
+ /** INTERNAL: Do not use. Gets the instruction restoring the `i`th saved argument of `d`. */
+ DeferReadArgInstruction deferReadArgInstruction(DeferStmt d, int i) {
+ result.getDeferStmt() = d and result.getIndex() = i
+ }
}
diff --git a/go/ql/test/experimental/InconsistentCode/CONSISTENCY/CfgConsistency.expected b/go/ql/test/experimental/InconsistentCode/CONSISTENCY/CfgConsistency.expected
index 3c00017bbfca..5312f7ea887c 100644
--- a/go/ql/test/experimental/InconsistentCode/CONSISTENCY/CfgConsistency.expected
+++ b/go/ql/test/experimental/InconsistentCode/CONSISTENCY/CfgConsistency.expected
@@ -1,14 +1,11 @@
consistencyOverview
| multipleSuccessors | 8 |
-| selfLoop | 1 |
multipleSuccessors
| DeferInLoop.go:6:2:13:2 | After range statement | successor | DeferInLoop.go:5:36:14:1 | After block statement |
-| DeferInLoop.go:6:2:13:2 | After range statement | successor | DeferInLoop.go:8:9:8:20 | defer-invoke call to Close |
+| DeferInLoop.go:6:2:13:2 | After range statement | successor | DeferInLoop.go:8:9:8:20 | defer-recv-read call to Close |
| DeferInLoop.go:7:3:7:32 | catch-panic ... := ... | successor | DeferInLoop.go:5:1:14:1 | Exceptional Exit |
-| DeferInLoop.go:7:3:7:32 | catch-panic ... := ... | successor | DeferInLoop.go:8:9:8:20 | defer-invoke call to Close |
+| DeferInLoop.go:7:3:7:32 | catch-panic ... := ... | successor | DeferInLoop.go:8:9:8:20 | defer-recv-read call to Close |
| DeferInLoop.go:8:3:8:20 | catch-defer-panic defer statement | successor | DeferInLoop.go:5:1:14:1 | Exceptional Exit |
-| DeferInLoop.go:8:3:8:20 | catch-defer-panic defer statement | successor | DeferInLoop.go:8:9:8:20 | defer-invoke call to Close |
+| DeferInLoop.go:8:3:8:20 | catch-defer-panic defer statement | successor | DeferInLoop.go:8:9:8:20 | defer-recv-read call to Close |
| DeferInLoop.go:8:9:8:20 | defer-invoke call to Close | successor | DeferInLoop.go:5:36:14:1 | After block statement |
-| DeferInLoop.go:8:9:8:20 | defer-invoke call to Close | successor | DeferInLoop.go:8:9:8:20 | defer-invoke call to Close |
-selfLoop
-| DeferInLoop.go:8:9:8:20 | defer-invoke call to Close | successor |
+| DeferInLoop.go:8:9:8:20 | defer-invoke call to Close | successor | DeferInLoop.go:8:9:8:20 | defer-recv-read call to Close |
diff --git a/go/ql/test/library-tests/semmle/go/PrintAst/CONSISTENCY/CfgConsistency.expected b/go/ql/test/library-tests/semmle/go/PrintAst/CONSISTENCY/CfgConsistency.expected
index bedab226be6e..f1efca1f37cc 100644
--- a/go/ql/test/library-tests/semmle/go/PrintAst/CONSISTENCY/CfgConsistency.expected
+++ b/go/ql/test/library-tests/semmle/go/PrintAst/CONSISTENCY/CfgConsistency.expected
@@ -8,5 +8,5 @@ multipleSuccessors
| input.go:50:2:59:2 | select statement | successor | input.go:53:2:55:16 | comm clause |
| input.go:50:2:59:2 | select statement | successor | input.go:56:2:57:15 | comm clause |
| input.go:50:2:59:2 | select statement | successor | input.go:58:2:58:16 | comm clause |
-| input.go:71:2:71:10 | catch-return return statement | successor | input.go:67:9:67:35 | defer-invoke function call |
-| input.go:71:2:71:10 | catch-return return statement | successor | input.go:69:9:69:36 | defer-invoke function call |
+| input.go:71:2:71:10 | catch-return return statement | successor | input.go:67:9:67:35 | defer-callee-read function call |
+| input.go:71:2:71:10 | catch-return return statement | successor | input.go:69:9:69:36 | defer-callee-read function call |
diff --git a/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/CONSISTENCY/CfgConsistency.expected b/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/CONSISTENCY/CfgConsistency.expected
index d856f64ab253..b392aa55314c 100644
--- a/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/CONSISTENCY/CfgConsistency.expected
+++ b/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/CONSISTENCY/CfgConsistency.expected
@@ -1,6 +1,6 @@
consistencyOverview
| deadEnd | 1 |
-| multipleSuccessors | 24 |
+| multipleSuccessors | 26 |
| selfLoop | 1 |
deadEnd
| stmts.go:61:2:61:10 | select statement |
@@ -23,11 +23,13 @@ multipleSuccessors
| stmts7.go:75:1:76:20 | After labeled statement | successor | stmts7.go:74:8:74:21 | defer-invoke call to recoverPanic |
| stmts7.go:75:1:76:20 | catch-panic labeled statement | successor | stmts7.go:70:1:77:1 | Exceptional Exit |
| stmts7.go:75:1:76:20 | catch-panic labeled statement | successor | stmts7.go:74:8:74:21 | defer-invoke call to recoverPanic |
+| stmts7.go:130:2:130:26 | catch-panic expression statement | successor | stmts7.go:126:1:131:1 | Exceptional Exit |
+| stmts7.go:130:2:130:26 | catch-panic expression statement | successor | stmts7.go:128:9:128:16 | defer-arg-read:0 call to clear |
| stmts.go:50:2:59:2 | select statement | successor | stmts.go:51:2:52:31 | comm clause |
| stmts.go:50:2:59:2 | select statement | successor | stmts.go:53:2:55:16 | comm clause |
| stmts.go:50:2:59:2 | select statement | successor | stmts.go:56:2:57:15 | comm clause |
| stmts.go:50:2:59:2 | select statement | successor | stmts.go:58:2:58:16 | comm clause |
-| stmts.go:71:2:71:10 | catch-return return statement | successor | stmts.go:67:9:67:35 | defer-invoke function call |
-| stmts.go:71:2:71:10 | catch-return return statement | successor | stmts.go:69:9:69:36 | defer-invoke function call |
+| stmts.go:71:2:71:10 | catch-return return statement | successor | stmts.go:67:9:67:35 | defer-callee-read function call |
+| stmts.go:71:2:71:10 | catch-return return statement | successor | stmts.go:69:9:69:36 | defer-callee-read function call |
selfLoop
| stmts7.go:66:9:66:22 | defer-invoke call to recoverPanic | successor |
diff --git a/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/ControlFlowNode_getASuccessor.expected b/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/ControlFlowNode_getASuccessor.expected
index 6c80c1a9b99e..4a863329c8fa 100644
--- a/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/ControlFlowNode_getASuccessor.expected
+++ b/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/ControlFlowNode_getASuccessor.expected
@@ -248,11 +248,17 @@
| epilogues.go:60:8:60:12 | selection of log | epilogues.go:60:8:60:12 | After selection of log |
| epilogues.go:60:8:60:33 | After call to log | epilogues.go:60:2:60:33 | defer statement |
| epilogues.go:60:8:60:33 | call to log | epilogues.go:60:8:60:12 | Before selection of log |
+| epilogues.go:60:8:60:33 | defer-arg-read:0 call to log | epilogues.go:60:8:60:33 | defer-arg-read:1 call to log |
+| epilogues.go:60:8:60:33 | defer-arg-read:1 call to log | epilogues.go:60:8:60:33 | defer-invoke call to log |
+| epilogues.go:60:8:60:33 | defer-arg-write:0 call to log | epilogues.go:60:8:60:33 | defer-arg-write:1 call to log |
+| epilogues.go:60:8:60:33 | defer-arg-write:1 call to log | epilogues.go:60:8:60:33 | After call to log |
| epilogues.go:60:8:60:33 | defer-invoke call to log | epilogues.go:59:54:62:1 | After block statement |
| epilogues.go:60:8:60:33 | defer-invoke call to log | epilogues.go:60:2:60:33 | catch-defer-panic defer statement |
+| epilogues.go:60:8:60:33 | defer-recv-read call to log | epilogues.go:60:8:60:33 | defer-arg-read:0 call to log |
+| epilogues.go:60:8:60:33 | defer-recv-write call to log | epilogues.go:60:8:60:33 | defer-arg-write:0 call to log |
| epilogues.go:60:14:60:20 | "count" | epilogues.go:60:23:60:32 | Before call to len |
| epilogues.go:60:23:60:25 | len | epilogues.go:60:27:60:31 | items |
-| epilogues.go:60:23:60:32 | After call to len | epilogues.go:60:8:60:33 | After call to log |
+| epilogues.go:60:23:60:32 | After call to len | epilogues.go:60:8:60:33 | defer-recv-write call to log |
| epilogues.go:60:23:60:32 | Before call to len | epilogues.go:60:23:60:25 | len |
| epilogues.go:60:23:60:32 | call to len | epilogues.go:60:23:60:32 | After call to len |
| epilogues.go:60:27:60:31 | items | epilogues.go:60:23:60:32 | call to len |
@@ -260,11 +266,11 @@
| epilogues.go:61:2:61:12 | Before selection of Println | epilogues.go:61:2:61:12 | selection of Println |
| epilogues.go:61:2:61:12 | selection of Println | epilogues.go:61:2:61:12 | After selection of Println |
| epilogues.go:61:2:61:38 | After call to Println | epilogues.go:61:2:61:38 | After expression statement |
-| epilogues.go:61:2:61:38 | After expression statement | epilogues.go:60:8:60:33 | defer-invoke call to log |
+| epilogues.go:61:2:61:38 | After expression statement | epilogues.go:60:8:60:33 | defer-recv-read call to log |
| epilogues.go:61:2:61:38 | Before call to Println | epilogues.go:61:2:61:12 | Before selection of Println |
| epilogues.go:61:2:61:38 | call to Println | epilogues.go:61:2:61:38 | After call to Println |
| epilogues.go:61:2:61:38 | call to Println | epilogues.go:61:2:61:38 | catch-panic expression statement |
-| epilogues.go:61:2:61:38 | catch-panic expression statement | epilogues.go:60:8:60:33 | defer-invoke call to log |
+| epilogues.go:61:2:61:38 | catch-panic expression statement | epilogues.go:60:8:60:33 | defer-recv-read call to log |
| epilogues.go:61:2:61:38 | expression statement | epilogues.go:61:2:61:38 | Before call to Println |
| epilogues.go:61:14:61:25 | "processing" | epilogues.go:61:28:61:37 | Before call to len |
| epilogues.go:61:28:61:30 | len | epilogues.go:61:32:61:36 | items |
@@ -300,35 +306,45 @@
| epilogues.go:68:8:68:17 | selection of logValue | epilogues.go:68:8:68:17 | After selection of logValue |
| epilogues.go:68:8:68:24 | After call to logValue | epilogues.go:68:2:68:24 | defer statement |
| epilogues.go:68:8:68:24 | call to logValue | epilogues.go:68:8:68:17 | Before selection of logValue |
+| epilogues.go:68:8:68:24 | defer-arg-read:0 call to logValue | epilogues.go:68:8:68:24 | defer-invoke call to logValue |
+| epilogues.go:68:8:68:24 | defer-arg-write:0 call to logValue | epilogues.go:68:8:68:24 | After call to logValue |
| epilogues.go:68:8:68:24 | defer-invoke call to logValue | epilogues.go:66:43:71:1 | After block statement |
| epilogues.go:68:8:68:24 | defer-invoke call to logValue | epilogues.go:68:2:68:24 | catch-defer-panic defer statement |
-| epilogues.go:68:19:68:23 | "bye" | epilogues.go:68:8:68:24 | After call to logValue |
+| epilogues.go:68:8:68:24 | defer-recv-read call to logValue | epilogues.go:68:8:68:24 | defer-arg-read:0 call to logValue |
+| epilogues.go:68:8:68:24 | defer-recv-write call to logValue | epilogues.go:68:8:68:24 | defer-arg-write:0 call to logValue |
+| epilogues.go:68:19:68:23 | "bye" | epilogues.go:68:8:68:24 | defer-recv-write call to logValue |
| epilogues.go:69:2:69:25 | After defer statement | epilogues.go:70:2:70:20 | expression statement |
| epilogues.go:69:2:69:25 | Before defer statement | epilogues.go:69:8:69:25 | call to log |
-| epilogues.go:69:2:69:25 | catch-defer-panic defer statement | epilogues.go:68:8:68:24 | defer-invoke call to logValue |
+| epilogues.go:69:2:69:25 | catch-defer-panic defer statement | epilogues.go:68:8:68:24 | defer-recv-read call to logValue |
| epilogues.go:69:2:69:25 | defer statement | epilogues.go:69:2:69:25 | After defer statement |
| epilogues.go:69:8:69:15 | After selection of log | epilogues.go:69:17:69:21 | "ptr" |
| epilogues.go:69:8:69:15 | Before selection of log | epilogues.go:69:9:69:10 | Before &... |
| epilogues.go:69:8:69:15 | selection of log | epilogues.go:69:8:69:15 | After selection of log |
| epilogues.go:69:8:69:25 | After call to log | epilogues.go:69:2:69:25 | defer statement |
| epilogues.go:69:8:69:25 | call to log | epilogues.go:69:8:69:15 | Before selection of log |
-| epilogues.go:69:8:69:25 | defer-invoke call to log | epilogues.go:68:8:68:24 | defer-invoke call to logValue |
+| epilogues.go:69:8:69:25 | defer-arg-read:0 call to log | epilogues.go:69:8:69:25 | defer-arg-read:1 call to log |
+| epilogues.go:69:8:69:25 | defer-arg-read:1 call to log | epilogues.go:69:8:69:25 | defer-invoke call to log |
+| epilogues.go:69:8:69:25 | defer-arg-write:0 call to log | epilogues.go:69:8:69:25 | defer-arg-write:1 call to log |
+| epilogues.go:69:8:69:25 | defer-arg-write:1 call to log | epilogues.go:69:8:69:25 | After call to log |
+| epilogues.go:69:8:69:25 | defer-invoke call to log | epilogues.go:68:8:68:24 | defer-recv-read call to logValue |
| epilogues.go:69:8:69:25 | defer-invoke call to log | epilogues.go:69:2:69:25 | catch-defer-panic defer statement |
+| epilogues.go:69:8:69:25 | defer-recv-read call to log | epilogues.go:69:8:69:25 | defer-arg-read:0 call to log |
+| epilogues.go:69:8:69:25 | defer-recv-write call to log | epilogues.go:69:8:69:25 | defer-arg-write:0 call to log |
| epilogues.go:69:9:69:10 | &... | epilogues.go:69:9:69:10 | After &... |
| epilogues.go:69:9:69:10 | After &... | epilogues.go:69:8:69:15 | selection of log |
| epilogues.go:69:9:69:10 | Before &... | epilogues.go:69:10:69:10 | l |
| epilogues.go:69:10:69:10 | l | epilogues.go:69:9:69:10 | &... |
| epilogues.go:69:17:69:21 | "ptr" | epilogues.go:69:24:69:24 | 7 |
-| epilogues.go:69:24:69:24 | 7 | epilogues.go:69:8:69:25 | After call to log |
+| epilogues.go:69:24:69:24 | 7 | epilogues.go:69:8:69:25 | defer-recv-write call to log |
| epilogues.go:70:2:70:12 | After selection of Println | epilogues.go:70:14:70:19 | "body" |
| epilogues.go:70:2:70:12 | Before selection of Println | epilogues.go:70:2:70:12 | selection of Println |
| epilogues.go:70:2:70:12 | selection of Println | epilogues.go:70:2:70:12 | After selection of Println |
| epilogues.go:70:2:70:20 | After call to Println | epilogues.go:70:2:70:20 | After expression statement |
-| epilogues.go:70:2:70:20 | After expression statement | epilogues.go:69:8:69:25 | defer-invoke call to log |
+| epilogues.go:70:2:70:20 | After expression statement | epilogues.go:69:8:69:25 | defer-recv-read call to log |
| epilogues.go:70:2:70:20 | Before call to Println | epilogues.go:70:2:70:12 | Before selection of Println |
| epilogues.go:70:2:70:20 | call to Println | epilogues.go:70:2:70:20 | After call to Println |
| epilogues.go:70:2:70:20 | call to Println | epilogues.go:70:2:70:20 | catch-panic expression statement |
-| epilogues.go:70:2:70:20 | catch-panic expression statement | epilogues.go:69:8:69:25 | defer-invoke call to log |
+| epilogues.go:70:2:70:20 | catch-panic expression statement | epilogues.go:69:8:69:25 | defer-recv-read call to log |
| epilogues.go:70:2:70:20 | expression statement | epilogues.go:70:2:70:20 | Before call to Println |
| epilogues.go:70:14:70:19 | "body" | epilogues.go:70:2:70:20 | call to Println |
| epilogues.go:77:1:82:1 | Entry | epilogues.go:77:22:77:22 | x |
@@ -347,6 +363,12 @@
| epilogues.go:78:8:80:2 | Normal Exit | epilogues.go:78:8:80:2 | Exit |
| epilogues.go:78:8:80:2 | function literal | epilogues.go:80:4:80:9 | "done" |
| epilogues.go:78:8:80:15 | After function call | epilogues.go:78:2:80:15 | defer statement |
+| epilogues.go:78:8:80:15 | defer-arg-read:0 function call | epilogues.go:78:8:80:15 | defer-arg-read:1 function call |
+| epilogues.go:78:8:80:15 | defer-arg-read:1 function call | epilogues.go:78:8:80:15 | defer-invoke function call |
+| epilogues.go:78:8:80:15 | defer-arg-write:0 function call | epilogues.go:78:8:80:15 | defer-arg-write:1 function call |
+| epilogues.go:78:8:80:15 | defer-arg-write:1 function call | epilogues.go:78:8:80:15 | After function call |
+| epilogues.go:78:8:80:15 | defer-callee-read function call | epilogues.go:78:8:80:15 | defer-arg-read:0 function call |
+| epilogues.go:78:8:80:15 | defer-callee-write function call | epilogues.go:78:8:80:15 | defer-arg-write:0 function call |
| epilogues.go:78:8:80:15 | defer-invoke function call | epilogues.go:77:29:82:1 | After block statement |
| epilogues.go:78:8:80:15 | defer-invoke function call | epilogues.go:78:2:80:15 | catch-defer-panic defer statement |
| epilogues.go:78:8:80:15 | function call | epilogues.go:78:8:80:2 | function literal |
@@ -368,18 +390,18 @@
| epilogues.go:80:4:80:9 | "done" | epilogues.go:80:12:80:14 | Before ...+... |
| epilogues.go:80:12:80:12 | x | epilogues.go:80:14:80:14 | 1 |
| epilogues.go:80:12:80:14 | ...+... | epilogues.go:80:12:80:14 | After ...+... |
-| epilogues.go:80:12:80:14 | After ...+... | epilogues.go:78:8:80:15 | After function call |
+| epilogues.go:80:12:80:14 | After ...+... | epilogues.go:78:8:80:15 | defer-callee-write function call |
| epilogues.go:80:12:80:14 | Before ...+... | epilogues.go:80:12:80:12 | x |
| epilogues.go:80:14:80:14 | 1 | epilogues.go:80:12:80:14 | ...+... |
| epilogues.go:81:2:81:12 | After selection of Println | epilogues.go:81:14:81:19 | "body" |
| epilogues.go:81:2:81:12 | Before selection of Println | epilogues.go:81:2:81:12 | selection of Println |
| epilogues.go:81:2:81:12 | selection of Println | epilogues.go:81:2:81:12 | After selection of Println |
| epilogues.go:81:2:81:23 | After call to Println | epilogues.go:81:2:81:23 | After expression statement |
-| epilogues.go:81:2:81:23 | After expression statement | epilogues.go:78:8:80:15 | defer-invoke function call |
+| epilogues.go:81:2:81:23 | After expression statement | epilogues.go:78:8:80:15 | defer-callee-read function call |
| epilogues.go:81:2:81:23 | Before call to Println | epilogues.go:81:2:81:12 | Before selection of Println |
| epilogues.go:81:2:81:23 | call to Println | epilogues.go:81:2:81:23 | After call to Println |
| epilogues.go:81:2:81:23 | call to Println | epilogues.go:81:2:81:23 | catch-panic expression statement |
-| epilogues.go:81:2:81:23 | catch-panic expression statement | epilogues.go:78:8:80:15 | defer-invoke function call |
+| epilogues.go:81:2:81:23 | catch-panic expression statement | epilogues.go:78:8:80:15 | defer-callee-read function call |
| epilogues.go:81:2:81:23 | expression statement | epilogues.go:81:2:81:23 | Before call to Println |
| epilogues.go:81:14:81:19 | "body" | epilogues.go:81:22:81:22 | x |
| epilogues.go:81:22:81:22 | x | epilogues.go:81:2:81:23 | call to Println |
@@ -398,8 +420,10 @@
| epilogues.go:88:2:92:4 | defer statement | epilogues.go:88:2:92:4 | After defer statement |
| epilogues.go:88:8:92:2 | Entry | epilogues.go:88:15:92:2 | block statement |
| epilogues.go:88:8:92:2 | Normal Exit | epilogues.go:88:8:92:2 | Exit |
-| epilogues.go:88:8:92:2 | function literal | epilogues.go:88:8:92:4 | After function call |
+| epilogues.go:88:8:92:2 | function literal | epilogues.go:88:8:92:4 | defer-callee-write function call |
| epilogues.go:88:8:92:4 | After function call | epilogues.go:88:2:92:4 | defer statement |
+| epilogues.go:88:8:92:4 | defer-callee-read function call | epilogues.go:88:8:92:4 | defer-invoke function call |
+| epilogues.go:88:8:92:4 | defer-callee-write function call | epilogues.go:88:8:92:4 | After function call |
| epilogues.go:88:8:92:4 | defer-invoke function call | epilogues.go:87:42:98:1 | result-read:0 block statement |
| epilogues.go:88:8:92:4 | defer-invoke function call | epilogues.go:88:2:92:4 | catch-defer-panic defer statement |
| epilogues.go:88:8:92:4 | function call | epilogues.go:88:8:92:2 | function literal |
@@ -430,7 +454,7 @@
| epilogues.go:90:13:90:14 | After -... | epilogues.go:90:4:90:14 | assign:0 ... = ... |
| epilogues.go:90:13:90:14 | Before -... | epilogues.go:90:13:90:14 | -... |
| epilogues.go:93:2:95:2 | After if statement | epilogues.go:96:2:96:15 | ... = ... |
-| epilogues.go:93:2:95:2 | catch-panic if statement | epilogues.go:88:8:92:4 | defer-invoke function call |
+| epilogues.go:93:2:95:2 | catch-panic if statement | epilogues.go:88:8:92:4 | defer-callee-read function call |
| epilogues.go:93:2:95:2 | if statement | epilogues.go:93:5:93:9 | Before ...<... |
| epilogues.go:93:5:93:5 | x | epilogues.go:93:9:93:9 | 0 |
| epilogues.go:93:5:93:9 | ...<... | epilogues.go:93:5:93:9 | After ...<... [false] |
@@ -454,7 +478,7 @@
| epilogues.go:96:11:96:15 | Before ...*... | epilogues.go:96:11:96:11 | x |
| epilogues.go:96:15:96:15 | x | epilogues.go:96:11:96:15 | ...*... |
| epilogues.go:97:2:97:14 | Before return statement | epilogues.go:97:9:97:14 | result |
-| epilogues.go:97:2:97:14 | catch-return return statement | epilogues.go:88:8:92:4 | defer-invoke function call |
+| epilogues.go:97:2:97:14 | catch-return return statement | epilogues.go:88:8:92:4 | defer-callee-read function call |
| epilogues.go:97:2:97:14 | result-write:0 return statement | epilogues.go:97:2:97:14 | return statement |
| epilogues.go:97:2:97:14 | return statement | epilogues.go:97:2:97:14 | catch-return return statement |
| epilogues.go:97:9:97:14 | result | epilogues.go:97:2:97:14 | result-write:0 return statement |
@@ -2293,28 +2317,33 @@
| stmts7.go:26:16:26:23 | callback | stmts7.go:26:40:31:1 | block statement |
| stmts7.go:26:40:31:1 | After block statement | stmts7.go:26:1:31:1 | Normal Exit |
| stmts7.go:26:40:31:1 | block statement | stmts7.go:27:2:27:20 | Before defer statement |
+| stmts7.go:26:40:31:1 | result-read:0 block statement | stmts7.go:26:40:31:1 | After block statement |
| stmts7.go:27:2:27:20 | After defer statement | stmts7.go:28:2:28:23 | Before defer statement |
| stmts7.go:27:2:27:20 | Before defer statement | stmts7.go:27:8:27:20 | call to fn |
| stmts7.go:27:2:27:20 | catch-defer-panic defer statement | stmts7.go:26:1:31:1 | Exceptional Exit |
| stmts7.go:27:2:27:20 | defer statement | stmts7.go:27:2:27:20 | After defer statement |
| stmts7.go:27:8:27:15 | callback | stmts7.go:27:8:27:18 | selection of fn |
-| stmts7.go:27:8:27:18 | After selection of fn | stmts7.go:27:8:27:20 | After call to fn |
+| stmts7.go:27:8:27:18 | After selection of fn | stmts7.go:27:8:27:20 | defer-callee-write call to fn |
| stmts7.go:27:8:27:18 | Before selection of fn | stmts7.go:27:8:27:15 | callback |
| stmts7.go:27:8:27:18 | selection of fn | stmts7.go:27:8:27:18 | After selection of fn |
| stmts7.go:27:8:27:20 | After call to fn | stmts7.go:27:2:27:20 | defer statement |
| stmts7.go:27:8:27:20 | call to fn | stmts7.go:27:8:27:18 | Before selection of fn |
-| stmts7.go:27:8:27:20 | defer-invoke call to fn | stmts7.go:26:40:31:1 | After block statement |
+| stmts7.go:27:8:27:20 | defer-callee-read call to fn | stmts7.go:27:8:27:20 | defer-invoke call to fn |
+| stmts7.go:27:8:27:20 | defer-callee-write call to fn | stmts7.go:27:8:27:20 | After call to fn |
+| stmts7.go:27:8:27:20 | defer-invoke call to fn | stmts7.go:26:40:31:1 | result-read:0 block statement |
| stmts7.go:27:8:27:20 | defer-invoke call to fn | stmts7.go:27:2:27:20 | catch-defer-panic defer statement |
| stmts7.go:28:2:28:23 | After defer statement | stmts7.go:29:2:29:31 | expression statement |
| stmts7.go:28:2:28:23 | Before defer statement | stmts7.go:28:8:28:23 | call to fn |
-| stmts7.go:28:2:28:23 | catch-defer-panic defer statement | stmts7.go:27:8:27:20 | defer-invoke call to fn |
+| stmts7.go:28:2:28:23 | catch-defer-panic defer statement | stmts7.go:27:8:27:20 | defer-callee-read call to fn |
| stmts7.go:28:2:28:23 | defer statement | stmts7.go:28:2:28:23 | After defer statement |
-| stmts7.go:28:8:28:21 | After selection of fn | stmts7.go:28:8:28:23 | After call to fn |
+| stmts7.go:28:8:28:21 | After selection of fn | stmts7.go:28:8:28:23 | defer-callee-write call to fn |
| stmts7.go:28:8:28:21 | Before selection of fn | stmts7.go:28:9:28:17 | Before &... |
| stmts7.go:28:8:28:21 | selection of fn | stmts7.go:28:8:28:21 | After selection of fn |
| stmts7.go:28:8:28:23 | After call to fn | stmts7.go:28:2:28:23 | defer statement |
| stmts7.go:28:8:28:23 | call to fn | stmts7.go:28:8:28:21 | Before selection of fn |
-| stmts7.go:28:8:28:23 | defer-invoke call to fn | stmts7.go:27:8:27:20 | defer-invoke call to fn |
+| stmts7.go:28:8:28:23 | defer-callee-read call to fn | stmts7.go:28:8:28:23 | defer-invoke call to fn |
+| stmts7.go:28:8:28:23 | defer-callee-write call to fn | stmts7.go:28:8:28:23 | After call to fn |
+| stmts7.go:28:8:28:23 | defer-invoke call to fn | stmts7.go:27:8:27:20 | defer-callee-read call to fn |
| stmts7.go:28:8:28:23 | defer-invoke call to fn | stmts7.go:28:2:28:23 | catch-defer-panic defer statement |
| stmts7.go:28:9:28:17 | &... | stmts7.go:28:9:28:17 | After &... |
| stmts7.go:28:9:28:17 | After &... | stmts7.go:28:9:28:17 | implicit-deref &... |
@@ -2329,13 +2358,14 @@
| stmts7.go:29:2:29:31 | Before call to Println | stmts7.go:29:2:29:12 | Before selection of Println |
| stmts7.go:29:2:29:31 | call to Println | stmts7.go:29:2:29:31 | After call to Println |
| stmts7.go:29:2:29:31 | call to Println | stmts7.go:29:2:29:31 | catch-panic expression statement |
-| stmts7.go:29:2:29:31 | catch-panic expression statement | stmts7.go:28:8:28:23 | defer-invoke call to fn |
+| stmts7.go:29:2:29:31 | catch-panic expression statement | stmts7.go:28:8:28:23 | defer-callee-read call to fn |
| stmts7.go:29:2:29:31 | expression statement | stmts7.go:29:2:29:31 | Before call to Println |
| stmts7.go:29:14:29:30 | "print something" | stmts7.go:29:2:29:31 | call to Println |
| stmts7.go:30:2:30:13 | Before return statement | stmts7.go:30:9:30:13 | false |
-| stmts7.go:30:2:30:13 | catch-return return statement | stmts7.go:28:8:28:23 | defer-invoke call to fn |
+| stmts7.go:30:2:30:13 | catch-return return statement | stmts7.go:28:8:28:23 | defer-callee-read call to fn |
+| stmts7.go:30:2:30:13 | result-write:0 return statement | stmts7.go:30:2:30:13 | return statement |
| stmts7.go:30:2:30:13 | return statement | stmts7.go:30:2:30:13 | catch-return return statement |
-| stmts7.go:30:9:30:13 | false | stmts7.go:30:2:30:13 | return statement |
+| stmts7.go:30:9:30:13 | false | stmts7.go:30:2:30:13 | result-write:0 return statement |
| stmts7.go:33:1:36:1 | Entry | stmts7.go:33:24:36:1 | block statement |
| stmts7.go:33:1:36:1 | Exceptional Exit | stmts7.go:33:1:36:1 | Exit |
| stmts7.go:33:1:36:1 | function declaration | stmts7.go:38:1:41:1 | function declaration |
@@ -2368,29 +2398,32 @@
| stmts7.go:39:8:39:21 | call to recoverPanic | stmts7.go:39:8:39:19 | recoverPanic |
| stmts7.go:39:8:39:21 | defer-invoke call to recoverPanic | stmts7.go:38:22:41:1 | After block statement |
| stmts7.go:39:8:39:21 | defer-invoke call to recoverPanic | stmts7.go:39:2:39:21 | catch-defer-panic defer statement |
-| stmts7.go:40:2:40:30 | After defer statement | stmts7.go:40:8:40:30 | defer-invoke call to panic |
+| stmts7.go:40:2:40:30 | After defer statement | stmts7.go:40:8:40:30 | defer-arg-read:0 call to panic |
| stmts7.go:40:2:40:30 | Before defer statement | stmts7.go:40:8:40:30 | call to panic |
| stmts7.go:40:2:40:30 | catch-defer-panic defer statement | stmts7.go:39:8:39:21 | defer-invoke call to recoverPanic |
| stmts7.go:40:2:40:30 | defer statement | stmts7.go:40:2:40:30 | After defer statement |
| stmts7.go:40:8:40:12 | panic | stmts7.go:40:14:40:29 | "deferred panic" |
| stmts7.go:40:8:40:30 | After call to panic | stmts7.go:40:2:40:30 | defer statement |
| stmts7.go:40:8:40:30 | call to panic | stmts7.go:40:8:40:12 | panic |
-| stmts7.go:40:8:40:30 | defer-invoke call to panic | stmts7.go:39:8:39:21 | defer-invoke call to recoverPanic |
+| stmts7.go:40:8:40:30 | defer-arg-read:0 call to panic | stmts7.go:40:8:40:30 | defer-invoke call to panic |
+| stmts7.go:40:8:40:30 | defer-arg-write:0 call to panic | stmts7.go:40:8:40:30 | After call to panic |
| stmts7.go:40:8:40:30 | defer-invoke call to panic | stmts7.go:40:2:40:30 | catch-defer-panic defer statement |
-| stmts7.go:40:14:40:29 | "deferred panic" | stmts7.go:40:8:40:30 | After call to panic |
+| stmts7.go:40:14:40:29 | "deferred panic" | stmts7.go:40:8:40:30 | defer-arg-write:0 call to panic |
| stmts7.go:43:1:45:1 | Entry | stmts7.go:43:27:45:1 | block statement |
| stmts7.go:43:1:45:1 | Exceptional Exit | stmts7.go:43:1:45:1 | Exit |
| stmts7.go:43:1:45:1 | function declaration | stmts7.go:47:1:50:1 | function declaration |
| stmts7.go:43:27:45:1 | block statement | stmts7.go:44:2:44:36 | Before defer statement |
-| stmts7.go:44:2:44:36 | After defer statement | stmts7.go:44:8:44:36 | defer-invoke call to panic |
+| stmts7.go:44:2:44:36 | After defer statement | stmts7.go:44:8:44:36 | defer-arg-read:0 call to panic |
| stmts7.go:44:2:44:36 | Before defer statement | stmts7.go:44:8:44:36 | call to panic |
| stmts7.go:44:2:44:36 | catch-defer-panic defer statement | stmts7.go:43:1:45:1 | Exceptional Exit |
| stmts7.go:44:2:44:36 | defer statement | stmts7.go:44:2:44:36 | After defer statement |
| stmts7.go:44:8:44:12 | panic | stmts7.go:44:14:44:35 | "final deferred panic" |
| stmts7.go:44:8:44:36 | After call to panic | stmts7.go:44:2:44:36 | defer statement |
| stmts7.go:44:8:44:36 | call to panic | stmts7.go:44:8:44:12 | panic |
+| stmts7.go:44:8:44:36 | defer-arg-read:0 call to panic | stmts7.go:44:8:44:36 | defer-invoke call to panic |
+| stmts7.go:44:8:44:36 | defer-arg-write:0 call to panic | stmts7.go:44:8:44:36 | After call to panic |
| stmts7.go:44:8:44:36 | defer-invoke call to panic | stmts7.go:44:2:44:36 | catch-defer-panic defer statement |
-| stmts7.go:44:14:44:35 | "final deferred panic" | stmts7.go:44:8:44:36 | After call to panic |
+| stmts7.go:44:14:44:35 | "final deferred panic" | stmts7.go:44:8:44:36 | defer-arg-write:0 call to panic |
| stmts7.go:47:1:50:1 | Entry | stmts7.go:47:35:50:1 | block statement |
| stmts7.go:47:1:50:1 | Exceptional Exit | stmts7.go:47:1:50:1 | Exit |
| stmts7.go:47:1:50:1 | function declaration | stmts7.go:52:1:55:1 | function declaration |
@@ -2401,17 +2434,18 @@
| stmts7.go:48:8:48:19 | recoverPanic | stmts7.go:48:8:48:21 | After call to recoverPanic |
| stmts7.go:48:8:48:21 | After call to recoverPanic | stmts7.go:48:2:48:21 | defer statement |
| stmts7.go:48:8:48:21 | call to recoverPanic | stmts7.go:48:8:48:19 | recoverPanic |
-| stmts7.go:49:2:49:17 | After defer statement | stmts7.go:49:8:49:17 | defer-invoke call to Exit |
+| stmts7.go:49:2:49:17 | After defer statement | stmts7.go:49:8:49:17 | defer-arg-read:0 call to Exit |
| stmts7.go:49:2:49:17 | Before defer statement | stmts7.go:49:8:49:17 | call to Exit |
-| stmts7.go:49:2:49:17 | catch-defer-panic defer statement | stmts7.go:47:1:50:1 | Exceptional Exit |
| stmts7.go:49:2:49:17 | defer statement | stmts7.go:49:2:49:17 | After defer statement |
| stmts7.go:49:8:49:14 | After selection of Exit | stmts7.go:49:16:49:16 | 1 |
| stmts7.go:49:8:49:14 | Before selection of Exit | stmts7.go:49:8:49:14 | selection of Exit |
| stmts7.go:49:8:49:14 | selection of Exit | stmts7.go:49:8:49:14 | After selection of Exit |
| stmts7.go:49:8:49:17 | After call to Exit | stmts7.go:49:2:49:17 | defer statement |
| stmts7.go:49:8:49:17 | call to Exit | stmts7.go:49:8:49:14 | Before selection of Exit |
-| stmts7.go:49:8:49:17 | defer-invoke call to Exit | stmts7.go:49:2:49:17 | catch-defer-panic defer statement |
-| stmts7.go:49:16:49:16 | 1 | stmts7.go:49:8:49:17 | After call to Exit |
+| stmts7.go:49:8:49:17 | defer-arg-read:0 call to Exit | stmts7.go:49:8:49:17 | defer-invoke call to Exit |
+| stmts7.go:49:8:49:17 | defer-arg-write:0 call to Exit | stmts7.go:49:8:49:17 | After call to Exit |
+| stmts7.go:49:8:49:17 | defer-invoke call to Exit | stmts7.go:47:1:50:1 | Exceptional Exit |
+| stmts7.go:49:16:49:16 | 1 | stmts7.go:49:8:49:17 | defer-arg-write:0 call to Exit |
| stmts7.go:52:1:55:1 | Entry | stmts7.go:52:31:52:36 | values |
| stmts7.go:52:1:55:1 | Exceptional Exit | stmts7.go:52:1:55:1 | Exit |
| stmts7.go:52:1:55:1 | Normal Exit | stmts7.go:52:1:55:1 | Exit |
@@ -2557,7 +2591,7 @@
| stmts7.go:79:1:85:1 | Entry | stmts7.go:79:23:79:32 | panicEarly |
| stmts7.go:79:1:85:1 | Exceptional Exit | stmts7.go:79:1:85:1 | Exit |
| stmts7.go:79:1:85:1 | Normal Exit | stmts7.go:79:1:85:1 | Exit |
-| stmts7.go:79:1:85:1 | function declaration | stmts7.go:0:0:0:0 | After stmts7.go |
+| stmts7.go:79:1:85:1 | function declaration | stmts7.go:87:1:89:1 | function declaration |
| stmts7.go:79:23:79:32 | panicEarly | stmts7.go:79:40:85:1 | block statement |
| stmts7.go:79:40:85:1 | After block statement | stmts7.go:79:1:85:1 | Normal Exit |
| stmts7.go:79:40:85:1 | block statement | stmts7.go:80:2:82:2 | if statement |
@@ -2589,6 +2623,234 @@
| stmts7.go:84:2:84:14 | catch-panic expression statement | stmts7.go:83:8:83:21 | defer-invoke call to recoverPanic |
| stmts7.go:84:2:84:14 | expression statement | stmts7.go:84:2:84:14 | Before call to panic |
| stmts7.go:84:8:84:13 | "late" | stmts7.go:84:2:84:14 | call to panic |
+| stmts7.go:87:1:89:1 | Entry | stmts7.go:87:19:87:19 | _ |
+| stmts7.go:87:1:89:1 | Exceptional Exit | stmts7.go:87:1:89:1 | Exit |
+| stmts7.go:87:1:89:1 | function declaration | stmts7.go:91:1:94:1 | function declaration |
+| stmts7.go:87:19:87:19 | _ | stmts7.go:87:26:89:1 | block statement |
+| stmts7.go:87:26:89:1 | block statement | stmts7.go:88:2:88:24 | expression statement |
+| stmts7.go:88:2:88:6 | panic | stmts7.go:88:8:88:23 | "deferred panic" |
+| stmts7.go:88:2:88:24 | Before call to panic | stmts7.go:88:2:88:6 | panic |
+| stmts7.go:88:2:88:24 | call to panic | stmts7.go:87:1:89:1 | Exceptional Exit |
+| stmts7.go:88:2:88:24 | expression statement | stmts7.go:88:2:88:24 | Before call to panic |
+| stmts7.go:88:8:88:23 | "deferred panic" | stmts7.go:88:2:88:24 | call to panic |
+| stmts7.go:91:1:94:1 | Entry | stmts7.go:91:36:91:37 | xs |
+| stmts7.go:91:1:94:1 | Exceptional Exit | stmts7.go:91:1:94:1 | Exit |
+| stmts7.go:91:1:94:1 | Normal Exit | stmts7.go:91:1:94:1 | Exit |
+| stmts7.go:91:1:94:1 | function declaration | stmts7.go:96:1:96:27 | function declaration |
+| stmts7.go:91:36:91:37 | xs | stmts7.go:91:46:94:1 | block statement |
+| stmts7.go:91:46:94:1 | After block statement | stmts7.go:91:1:94:1 | Normal Exit |
+| stmts7.go:91:46:94:1 | block statement | stmts7.go:92:2:92:21 | Before defer statement |
+| stmts7.go:92:2:92:21 | After defer statement | stmts7.go:93:2:93:26 | Before defer statement |
+| stmts7.go:92:2:92:21 | Before defer statement | stmts7.go:92:8:92:21 | call to recoverPanic |
+| stmts7.go:92:2:92:21 | catch-defer-panic defer statement | stmts7.go:91:1:94:1 | Exceptional Exit |
+| stmts7.go:92:2:92:21 | defer statement | stmts7.go:92:2:92:21 | After defer statement |
+| stmts7.go:92:8:92:19 | recoverPanic | stmts7.go:92:8:92:21 | After call to recoverPanic |
+| stmts7.go:92:8:92:21 | After call to recoverPanic | stmts7.go:92:2:92:21 | defer statement |
+| stmts7.go:92:8:92:21 | call to recoverPanic | stmts7.go:92:8:92:19 | recoverPanic |
+| stmts7.go:92:8:92:21 | defer-invoke call to recoverPanic | stmts7.go:91:46:94:1 | After block statement |
+| stmts7.go:92:8:92:21 | defer-invoke call to recoverPanic | stmts7.go:92:2:92:21 | catch-defer-panic defer statement |
+| stmts7.go:93:2:93:26 | After defer statement | stmts7.go:93:8:93:26 | defer-arg-read:0 call to panicWithArg |
+| stmts7.go:93:2:93:26 | Before defer statement | stmts7.go:93:8:93:26 | call to panicWithArg |
+| stmts7.go:93:2:93:26 | catch-defer-panic defer statement | stmts7.go:92:8:92:21 | defer-invoke call to recoverPanic |
+| stmts7.go:93:2:93:26 | defer statement | stmts7.go:93:2:93:26 | After defer statement |
+| stmts7.go:93:8:93:19 | panicWithArg | stmts7.go:93:21:93:25 | Before index expression |
+| stmts7.go:93:8:93:26 | After call to panicWithArg | stmts7.go:93:2:93:26 | defer statement |
+| stmts7.go:93:8:93:26 | call to panicWithArg | stmts7.go:93:8:93:19 | panicWithArg |
+| stmts7.go:93:8:93:26 | defer-arg-read:0 call to panicWithArg | stmts7.go:93:8:93:26 | defer-invoke call to panicWithArg |
+| stmts7.go:93:8:93:26 | defer-arg-write:0 call to panicWithArg | stmts7.go:93:8:93:26 | After call to panicWithArg |
+| stmts7.go:93:8:93:26 | defer-invoke call to panicWithArg | stmts7.go:92:8:92:21 | defer-invoke call to recoverPanic |
+| stmts7.go:93:8:93:26 | defer-invoke call to panicWithArg | stmts7.go:93:2:93:26 | catch-defer-panic defer statement |
+| stmts7.go:93:21:93:22 | xs | stmts7.go:93:24:93:24 | 0 |
+| stmts7.go:93:21:93:25 | After index expression | stmts7.go:93:8:93:26 | defer-arg-write:0 call to panicWithArg |
+| stmts7.go:93:21:93:25 | Before index expression | stmts7.go:93:21:93:22 | xs |
+| stmts7.go:93:21:93:25 | catch-panic index expression | stmts7.go:92:8:92:21 | defer-invoke call to recoverPanic |
+| stmts7.go:93:21:93:25 | index expression | stmts7.go:93:21:93:25 | After index expression |
+| stmts7.go:93:21:93:25 | index expression | stmts7.go:93:21:93:25 | catch-panic index expression |
+| stmts7.go:93:24:93:24 | 0 | stmts7.go:93:21:93:25 | index expression |
+| stmts7.go:96:1:96:27 | Entry | stmts7.go:96:26:96:27 | block statement |
+| stmts7.go:96:1:96:27 | Normal Exit | stmts7.go:96:1:96:27 | Exit |
+| stmts7.go:96:1:96:27 | function declaration | stmts7.go:98:1:102:1 | function declaration |
+| stmts7.go:96:26:96:27 | block statement | stmts7.go:96:1:96:27 | Normal Exit |
+| stmts7.go:98:1:102:1 | Entry | stmts7.go:98:32:98:32 | s |
+| stmts7.go:98:1:102:1 | Exceptional Exit | stmts7.go:98:1:102:1 | Exit |
+| stmts7.go:98:1:102:1 | function declaration | stmts7.go:104:1:112:1 | function declaration |
+| stmts7.go:98:32:98:32 | s | stmts7.go:98:46:102:1 | block statement |
+| stmts7.go:98:46:102:1 | block statement | stmts7.go:99:2:99:15 | Before defer statement |
+| stmts7.go:99:2:99:15 | After defer statement | stmts7.go:100:2:100:26 | Before defer statement |
+| stmts7.go:99:2:99:15 | Before defer statement | stmts7.go:99:8:99:15 | call to clear |
+| stmts7.go:99:2:99:15 | catch-defer-panic defer statement | stmts7.go:98:1:102:1 | Exceptional Exit |
+| stmts7.go:99:2:99:15 | defer statement | stmts7.go:99:2:99:15 | After defer statement |
+| stmts7.go:99:8:99:12 | clear | stmts7.go:99:14:99:14 | s |
+| stmts7.go:99:8:99:15 | After call to clear | stmts7.go:99:2:99:15 | defer statement |
+| stmts7.go:99:8:99:15 | call to clear | stmts7.go:99:8:99:12 | clear |
+| stmts7.go:99:8:99:15 | defer-arg-read:0 call to clear | stmts7.go:99:8:99:15 | defer-invoke call to clear |
+| stmts7.go:99:8:99:15 | defer-arg-write:0 call to clear | stmts7.go:99:8:99:15 | After call to clear |
+| stmts7.go:99:8:99:15 | defer-invoke call to clear | stmts7.go:99:2:99:15 | catch-defer-panic defer statement |
+| stmts7.go:99:14:99:14 | s | stmts7.go:99:8:99:15 | defer-arg-write:0 call to clear |
+| stmts7.go:100:2:100:26 | After defer statement | stmts7.go:101:2:101:21 | expression statement |
+| stmts7.go:100:2:100:26 | Before defer statement | stmts7.go:100:8:100:26 | call to nonRecoverCleanup |
+| stmts7.go:100:2:100:26 | catch-defer-panic defer statement | stmts7.go:99:8:99:15 | defer-arg-read:0 call to clear |
+| stmts7.go:100:2:100:26 | defer statement | stmts7.go:100:2:100:26 | After defer statement |
+| stmts7.go:100:8:100:24 | nonRecoverCleanup | stmts7.go:100:8:100:26 | After call to nonRecoverCleanup |
+| stmts7.go:100:8:100:26 | After call to nonRecoverCleanup | stmts7.go:100:2:100:26 | defer statement |
+| stmts7.go:100:8:100:26 | call to nonRecoverCleanup | stmts7.go:100:8:100:24 | nonRecoverCleanup |
+| stmts7.go:100:8:100:26 | defer-invoke call to nonRecoverCleanup | stmts7.go:99:8:99:15 | defer-arg-read:0 call to clear |
+| stmts7.go:100:8:100:26 | defer-invoke call to nonRecoverCleanup | stmts7.go:100:2:100:26 | catch-defer-panic defer statement |
+| stmts7.go:101:2:101:6 | panic | stmts7.go:101:8:101:20 | "unrecovered" |
+| stmts7.go:101:2:101:21 | Before call to panic | stmts7.go:101:2:101:6 | panic |
+| stmts7.go:101:2:101:21 | call to panic | stmts7.go:101:2:101:21 | catch-panic expression statement |
+| stmts7.go:101:2:101:21 | catch-panic expression statement | stmts7.go:100:8:100:26 | defer-invoke call to nonRecoverCleanup |
+| stmts7.go:101:2:101:21 | expression statement | stmts7.go:101:2:101:21 | Before call to panic |
+| stmts7.go:101:8:101:20 | "unrecovered" | stmts7.go:101:2:101:21 | call to panic |
+| stmts7.go:104:1:112:1 | Entry | stmts7.go:104:32:104:35 | cond |
+| stmts7.go:104:1:112:1 | Exceptional Exit | stmts7.go:104:1:112:1 | Exit |
+| stmts7.go:104:1:112:1 | function declaration | stmts7.go:114:1:118:1 | function declaration |
+| stmts7.go:104:32:104:35 | cond | stmts7.go:104:47:112:1 | block statement |
+| stmts7.go:104:47:112:1 | block statement | stmts7.go:105:2:108:2 | if statement |
+| stmts7.go:105:2:108:2 | After if statement | stmts7.go:109:2:109:21 | Before defer statement |
+| stmts7.go:105:2:108:2 | if statement | stmts7.go:105:5:105:8 | cond |
+| stmts7.go:105:5:105:8 | After cond [false] | stmts7.go:105:2:108:2 | After if statement |
+| stmts7.go:105:5:105:8 | After cond [true] | stmts7.go:105:10:108:2 | block statement |
+| stmts7.go:105:5:105:8 | cond | stmts7.go:105:5:105:8 | After cond [false] |
+| stmts7.go:105:5:105:8 | cond | stmts7.go:105:5:105:8 | After cond [true] |
+| stmts7.go:105:10:108:2 | block statement | stmts7.go:106:3:106:22 | Before defer statement |
+| stmts7.go:106:3:106:22 | After defer statement | stmts7.go:107:3:107:14 | expression statement |
+| stmts7.go:106:3:106:22 | Before defer statement | stmts7.go:106:9:106:22 | call to recoverPanic |
+| stmts7.go:106:3:106:22 | defer statement | stmts7.go:106:3:106:22 | After defer statement |
+| stmts7.go:106:9:106:20 | recoverPanic | stmts7.go:106:9:106:22 | After call to recoverPanic |
+| stmts7.go:106:9:106:22 | After call to recoverPanic | stmts7.go:106:3:106:22 | defer statement |
+| stmts7.go:106:9:106:22 | call to recoverPanic | stmts7.go:106:9:106:20 | recoverPanic |
+| stmts7.go:107:3:107:14 | Before call to Exit | stmts7.go:107:4:107:10 | Before selection of Exit |
+| stmts7.go:107:3:107:14 | call to Exit | stmts7.go:104:1:112:1 | Exceptional Exit |
+| stmts7.go:107:3:107:14 | expression statement | stmts7.go:107:3:107:14 | Before call to Exit |
+| stmts7.go:107:4:107:10 | After selection of Exit | stmts7.go:107:13:107:13 | 1 |
+| stmts7.go:107:4:107:10 | Before selection of Exit | stmts7.go:107:4:107:10 | selection of Exit |
+| stmts7.go:107:4:107:10 | selection of Exit | stmts7.go:107:4:107:10 | After selection of Exit |
+| stmts7.go:107:13:107:13 | 1 | stmts7.go:107:3:107:14 | call to Exit |
+| stmts7.go:109:2:109:21 | After defer statement | stmts7.go:110:2:110:19 | Before defer statement |
+| stmts7.go:109:2:109:21 | Before defer statement | stmts7.go:109:8:109:21 | call to recoverPanic |
+| stmts7.go:109:2:109:21 | defer statement | stmts7.go:109:2:109:21 | After defer statement |
+| stmts7.go:109:8:109:19 | recoverPanic | stmts7.go:109:8:109:21 | After call to recoverPanic |
+| stmts7.go:109:8:109:21 | After call to recoverPanic | stmts7.go:109:2:109:21 | defer statement |
+| stmts7.go:109:8:109:21 | call to recoverPanic | stmts7.go:109:8:109:19 | recoverPanic |
+| stmts7.go:110:2:110:19 | After defer statement | stmts7.go:111:2:111:9 | Before return statement |
+| stmts7.go:110:2:110:19 | Before defer statement | stmts7.go:110:8:110:19 | call to Exit |
+| stmts7.go:110:2:110:19 | defer statement | stmts7.go:110:2:110:19 | After defer statement |
+| stmts7.go:110:8:110:19 | After call to Exit | stmts7.go:110:2:110:19 | defer statement |
+| stmts7.go:110:8:110:19 | call to Exit | stmts7.go:110:9:110:15 | Before selection of Exit |
+| stmts7.go:110:8:110:19 | defer-arg-read:0 call to Exit | stmts7.go:110:8:110:19 | defer-invoke call to Exit |
+| stmts7.go:110:8:110:19 | defer-arg-write:0 call to Exit | stmts7.go:110:8:110:19 | After call to Exit |
+| stmts7.go:110:8:110:19 | defer-invoke call to Exit | stmts7.go:104:1:112:1 | Exceptional Exit |
+| stmts7.go:110:9:110:15 | After selection of Exit | stmts7.go:110:18:110:18 | 1 |
+| stmts7.go:110:9:110:15 | Before selection of Exit | stmts7.go:110:9:110:15 | selection of Exit |
+| stmts7.go:110:9:110:15 | selection of Exit | stmts7.go:110:9:110:15 | After selection of Exit |
+| stmts7.go:110:18:110:18 | 1 | stmts7.go:110:8:110:19 | defer-arg-write:0 call to Exit |
+| stmts7.go:111:2:111:9 | Before return statement | stmts7.go:111:9:111:9 | 0 |
+| stmts7.go:111:2:111:9 | catch-return return statement | stmts7.go:110:8:110:19 | defer-arg-read:0 call to Exit |
+| stmts7.go:111:2:111:9 | result-write:0 return statement | stmts7.go:111:2:111:9 | return statement |
+| stmts7.go:111:2:111:9 | return statement | stmts7.go:111:2:111:9 | catch-return return statement |
+| stmts7.go:111:9:111:9 | 0 | stmts7.go:111:2:111:9 | result-write:0 return statement |
+| stmts7.go:114:1:118:1 | Entry | stmts7.go:114:58:118:1 | block statement |
+| stmts7.go:114:1:118:1 | Exceptional Exit | stmts7.go:114:1:118:1 | Exit |
+| stmts7.go:114:1:118:1 | function declaration | stmts7.go:120:1:124:1 | function declaration |
+| stmts7.go:114:58:118:1 | block statement | stmts7.go:115:2:115:31 | Before defer statement |
+| stmts7.go:115:2:115:31 | After defer statement | stmts7.go:116:2:116:21 | Before defer statement |
+| stmts7.go:115:2:115:31 | Before defer statement | stmts7.go:115:8:115:31 | call to panic |
+| stmts7.go:115:2:115:31 | catch-defer-panic defer statement | stmts7.go:114:1:118:1 | Exceptional Exit |
+| stmts7.go:115:2:115:31 | defer statement | stmts7.go:115:2:115:31 | After defer statement |
+| stmts7.go:115:8:115:31 | After call to panic | stmts7.go:115:2:115:31 | defer statement |
+| stmts7.go:115:8:115:31 | call to panic | stmts7.go:115:9:115:13 | panic |
+| stmts7.go:115:8:115:31 | defer-arg-read:0 call to panic | stmts7.go:115:8:115:31 | defer-invoke call to panic |
+| stmts7.go:115:8:115:31 | defer-arg-write:0 call to panic | stmts7.go:115:8:115:31 | After call to panic |
+| stmts7.go:115:8:115:31 | defer-invoke call to panic | stmts7.go:115:2:115:31 | catch-defer-panic defer statement |
+| stmts7.go:115:9:115:13 | panic | stmts7.go:115:16:115:30 | "earlier panic" |
+| stmts7.go:115:16:115:30 | "earlier panic" | stmts7.go:115:8:115:31 | defer-arg-write:0 call to panic |
+| stmts7.go:116:2:116:21 | After defer statement | stmts7.go:117:2:117:20 | expression statement |
+| stmts7.go:116:2:116:21 | Before defer statement | stmts7.go:116:8:116:21 | call to recoverPanic |
+| stmts7.go:116:2:116:21 | catch-defer-panic defer statement | stmts7.go:115:8:115:31 | defer-arg-read:0 call to panic |
+| stmts7.go:116:2:116:21 | defer statement | stmts7.go:116:2:116:21 | After defer statement |
+| stmts7.go:116:8:116:19 | recoverPanic | stmts7.go:116:8:116:21 | After call to recoverPanic |
+| stmts7.go:116:8:116:21 | After call to recoverPanic | stmts7.go:116:2:116:21 | defer statement |
+| stmts7.go:116:8:116:21 | call to recoverPanic | stmts7.go:116:8:116:19 | recoverPanic |
+| stmts7.go:116:8:116:21 | defer-invoke call to recoverPanic | stmts7.go:115:8:115:31 | defer-arg-read:0 call to panic |
+| stmts7.go:116:8:116:21 | defer-invoke call to recoverPanic | stmts7.go:116:2:116:21 | catch-defer-panic defer statement |
+| stmts7.go:117:2:117:6 | panic | stmts7.go:117:8:117:19 | "body panic" |
+| stmts7.go:117:2:117:20 | Before call to panic | stmts7.go:117:2:117:6 | panic |
+| stmts7.go:117:2:117:20 | call to panic | stmts7.go:117:2:117:20 | catch-panic expression statement |
+| stmts7.go:117:2:117:20 | catch-panic expression statement | stmts7.go:116:8:116:21 | defer-invoke call to recoverPanic |
+| stmts7.go:117:2:117:20 | expression statement | stmts7.go:117:2:117:20 | Before call to panic |
+| stmts7.go:117:8:117:19 | "body panic" | stmts7.go:117:2:117:20 | call to panic |
+| stmts7.go:120:1:124:1 | Entry | stmts7.go:120:53:124:1 | block statement |
+| stmts7.go:120:1:124:1 | Exceptional Exit | stmts7.go:120:1:124:1 | Exit |
+| stmts7.go:120:1:124:1 | Normal Exit | stmts7.go:120:1:124:1 | Exit |
+| stmts7.go:120:1:124:1 | function declaration | stmts7.go:126:1:131:1 | function declaration |
+| stmts7.go:120:53:124:1 | After block statement | stmts7.go:120:1:124:1 | Normal Exit |
+| stmts7.go:120:53:124:1 | block statement | stmts7.go:121:2:121:21 | Before defer statement |
+| stmts7.go:120:53:124:1 | result-read:0 block statement | stmts7.go:120:53:124:1 | After block statement |
+| stmts7.go:121:2:121:21 | After defer statement | stmts7.go:122:2:122:32 | Before defer statement |
+| stmts7.go:121:2:121:21 | Before defer statement | stmts7.go:121:8:121:21 | call to recoverPanic |
+| stmts7.go:121:2:121:21 | catch-defer-panic defer statement | stmts7.go:120:1:124:1 | Exceptional Exit |
+| stmts7.go:121:2:121:21 | defer statement | stmts7.go:121:2:121:21 | After defer statement |
+| stmts7.go:121:8:121:19 | recoverPanic | stmts7.go:121:8:121:21 | After call to recoverPanic |
+| stmts7.go:121:8:121:21 | After call to recoverPanic | stmts7.go:121:2:121:21 | defer statement |
+| stmts7.go:121:8:121:21 | call to recoverPanic | stmts7.go:121:8:121:19 | recoverPanic |
+| stmts7.go:121:8:121:21 | defer-invoke call to recoverPanic | stmts7.go:120:53:124:1 | result-read:0 block statement |
+| stmts7.go:121:8:121:21 | defer-invoke call to recoverPanic | stmts7.go:121:2:121:21 | catch-defer-panic defer statement |
+| stmts7.go:122:2:122:32 | After defer statement | stmts7.go:123:2:123:9 | Before return statement |
+| stmts7.go:122:2:122:32 | Before defer statement | stmts7.go:122:8:122:32 | call to panic |
+| stmts7.go:122:2:122:32 | catch-defer-panic defer statement | stmts7.go:121:8:121:21 | defer-invoke call to recoverPanic |
+| stmts7.go:122:2:122:32 | defer statement | stmts7.go:122:2:122:32 | After defer statement |
+| stmts7.go:122:8:122:32 | After call to panic | stmts7.go:122:2:122:32 | defer statement |
+| stmts7.go:122:8:122:32 | call to panic | stmts7.go:122:9:122:13 | panic |
+| stmts7.go:122:8:122:32 | defer-arg-read:0 call to panic | stmts7.go:122:8:122:32 | defer-invoke call to panic |
+| stmts7.go:122:8:122:32 | defer-arg-write:0 call to panic | stmts7.go:122:8:122:32 | After call to panic |
+| stmts7.go:122:8:122:32 | defer-invoke call to panic | stmts7.go:122:2:122:32 | catch-defer-panic defer statement |
+| stmts7.go:122:9:122:13 | panic | stmts7.go:122:16:122:31 | "deferred panic" |
+| stmts7.go:122:16:122:31 | "deferred panic" | stmts7.go:122:8:122:32 | defer-arg-write:0 call to panic |
+| stmts7.go:123:2:123:9 | Before return statement | stmts7.go:123:9:123:9 | 1 |
+| stmts7.go:123:2:123:9 | catch-return return statement | stmts7.go:122:8:122:32 | defer-arg-read:0 call to panic |
+| stmts7.go:123:2:123:9 | result-write:0 return statement | stmts7.go:123:2:123:9 | return statement |
+| stmts7.go:123:2:123:9 | return statement | stmts7.go:123:2:123:9 | catch-return return statement |
+| stmts7.go:123:9:123:9 | 1 | stmts7.go:123:2:123:9 | result-write:0 return statement |
+| stmts7.go:126:1:131:1 | Entry | stmts7.go:126:41:126:42 | xs |
+| stmts7.go:126:1:131:1 | Exceptional Exit | stmts7.go:126:1:131:1 | Exit |
+| stmts7.go:126:1:131:1 | function declaration | stmts7.go:0:0:0:0 | After stmts7.go |
+| stmts7.go:126:41:126:42 | xs | stmts7.go:126:54:131:1 | block statement |
+| stmts7.go:126:54:131:1 | block statement | stmts7.go:127:2:129:2 | range statement |
+| stmts7.go:127:2:129:2 | After range element | stmts7.go:127:23:129:2 | block statement |
+| stmts7.go:127:2:129:2 | After range statement | stmts7.go:130:2:130:26 | expression statement |
+| stmts7.go:127:2:129:2 | [LoopHeader] range statement | stmts7.go:127:2:129:2 | After range statement |
+| stmts7.go:127:2:129:2 | [LoopHeader] range statement | stmts7.go:127:2:129:2 | range element |
+| stmts7.go:127:2:129:2 | extract:0 range element | stmts7.go:127:2:129:2 | extract:1 range element |
+| stmts7.go:127:2:129:2 | extract:1 range element | stmts7.go:127:2:129:2 | After range element |
+| stmts7.go:127:2:129:2 | next range element | stmts7.go:127:2:129:2 | extract:0 range element |
+| stmts7.go:127:2:129:2 | range element | stmts7.go:127:2:129:2 | next range element |
+| stmts7.go:127:2:129:2 | range statement | stmts7.go:127:20:127:21 | xs |
+| stmts7.go:127:20:127:21 | After xs [empty] | stmts7.go:127:2:129:2 | After range statement |
+| stmts7.go:127:20:127:21 | After xs [non-empty] | stmts7.go:127:2:129:2 | range element |
+| stmts7.go:127:20:127:21 | xs | stmts7.go:127:20:127:21 | After xs [empty] |
+| stmts7.go:127:20:127:21 | xs | stmts7.go:127:20:127:21 | After xs [non-empty] |
+| stmts7.go:127:23:129:2 | After block statement | stmts7.go:127:2:129:2 | [LoopHeader] range statement |
+| stmts7.go:127:23:129:2 | block statement | stmts7.go:128:3:128:16 | Before defer statement |
+| stmts7.go:128:3:128:16 | After defer statement | stmts7.go:127:23:129:2 | After block statement |
+| stmts7.go:128:3:128:16 | Before defer statement | stmts7.go:128:9:128:16 | call to clear |
+| stmts7.go:128:3:128:16 | catch-defer-panic defer statement | stmts7.go:126:1:131:1 | Exceptional Exit |
+| stmts7.go:128:3:128:16 | defer statement | stmts7.go:128:3:128:16 | After defer statement |
+| stmts7.go:128:9:128:13 | clear | stmts7.go:128:15:128:15 | s |
+| stmts7.go:128:9:128:16 | After call to clear | stmts7.go:128:3:128:16 | defer statement |
+| stmts7.go:128:9:128:16 | call to clear | stmts7.go:128:9:128:13 | clear |
+| stmts7.go:128:9:128:16 | defer-arg-read:0 call to clear | stmts7.go:128:9:128:16 | defer-invoke call to clear |
+| stmts7.go:128:9:128:16 | defer-arg-write:0 call to clear | stmts7.go:128:9:128:16 | After call to clear |
+| stmts7.go:128:9:128:16 | defer-invoke call to clear | stmts7.go:128:3:128:16 | catch-defer-panic defer statement |
+| stmts7.go:128:9:128:16 | defer-invoke call to clear | stmts7.go:128:9:128:16 | defer-arg-read:0 call to clear |
+| stmts7.go:128:15:128:15 | s | stmts7.go:128:9:128:16 | defer-arg-write:0 call to clear |
+| stmts7.go:130:2:130:6 | panic | stmts7.go:130:8:130:25 | "unrecovered loop" |
+| stmts7.go:130:2:130:26 | Before call to panic | stmts7.go:130:2:130:6 | panic |
+| stmts7.go:130:2:130:26 | call to panic | stmts7.go:130:2:130:26 | catch-panic expression statement |
+| stmts7.go:130:2:130:26 | catch-panic expression statement | stmts7.go:126:1:131:1 | Exceptional Exit |
+| stmts7.go:130:2:130:26 | catch-panic expression statement | stmts7.go:128:9:128:16 | defer-arg-read:0 call to clear |
+| stmts7.go:130:2:130:26 | expression statement | stmts7.go:130:2:130:26 | Before call to panic |
+| stmts7.go:130:8:130:25 | "unrecovered loop" | stmts7.go:130:2:130:26 | call to panic |
| stmts8.go:0:0:0:0 | After stmts8.go | stmts8.go:0:0:0:0 | Normal Exit |
| stmts8.go:0:0:0:0 | Entry | stmts8.go:0:0:0:0 | stmts8.go |
| stmts8.go:0:0:0:0 | Normal Exit | stmts8.go:0:0:0:0 | Exit |
@@ -2865,6 +3127,7 @@
| stmts.go:65:12:65:12 | x | stmts.go:65:23:72:1 | block statement |
| stmts.go:65:23:72:1 | After block statement | stmts.go:65:1:72:1 | Normal Exit |
| stmts.go:65:23:72:1 | block statement | stmts.go:66:2:70:2 | if statement |
+| stmts.go:65:23:72:1 | result-read:0 block statement | stmts.go:65:23:72:1 | After block statement |
| stmts.go:66:2:70:2 | After if statement | stmts.go:71:2:71:10 | Before return statement |
| stmts.go:66:2:70:2 | if statement | stmts.go:66:5:66:9 | Before ...>... |
| stmts.go:66:5:66:5 | x | stmts.go:66:9:66:9 | 0 |
@@ -2883,9 +3146,11 @@
| stmts.go:67:9:67:33 | Entry | stmts.go:67:16:67:33 | block statement |
| stmts.go:67:9:67:33 | Exceptional Exit | stmts.go:67:9:67:33 | Exit |
| stmts.go:67:9:67:33 | Normal Exit | stmts.go:67:9:67:33 | Exit |
-| stmts.go:67:9:67:33 | function literal | stmts.go:67:9:67:35 | After function call |
+| stmts.go:67:9:67:33 | function literal | stmts.go:67:9:67:35 | defer-callee-write function call |
| stmts.go:67:9:67:35 | After function call | stmts.go:67:3:67:35 | defer statement |
-| stmts.go:67:9:67:35 | defer-invoke function call | stmts.go:65:23:72:1 | After block statement |
+| stmts.go:67:9:67:35 | defer-callee-read function call | stmts.go:67:9:67:35 | defer-invoke function call |
+| stmts.go:67:9:67:35 | defer-callee-write function call | stmts.go:67:9:67:35 | After function call |
+| stmts.go:67:9:67:35 | defer-invoke function call | stmts.go:65:23:72:1 | result-read:0 block statement |
| stmts.go:67:9:67:35 | defer-invoke function call | stmts.go:67:3:67:35 | catch-defer-panic defer statement |
| stmts.go:67:9:67:35 | function call | stmts.go:67:9:67:33 | function literal |
| stmts.go:67:16:67:33 | After block statement | stmts.go:67:9:67:33 | Normal Exit |
@@ -2909,9 +3174,11 @@
| stmts.go:69:9:69:34 | Entry | stmts.go:69:16:69:34 | block statement |
| stmts.go:69:9:69:34 | Exceptional Exit | stmts.go:69:9:69:34 | Exit |
| stmts.go:69:9:69:34 | Normal Exit | stmts.go:69:9:69:34 | Exit |
-| stmts.go:69:9:69:34 | function literal | stmts.go:69:9:69:36 | After function call |
+| stmts.go:69:9:69:34 | function literal | stmts.go:69:9:69:36 | defer-callee-write function call |
| stmts.go:69:9:69:36 | After function call | stmts.go:69:3:69:36 | defer statement |
-| stmts.go:69:9:69:36 | defer-invoke function call | stmts.go:65:23:72:1 | After block statement |
+| stmts.go:69:9:69:36 | defer-callee-read function call | stmts.go:69:9:69:36 | defer-invoke function call |
+| stmts.go:69:9:69:36 | defer-callee-write function call | stmts.go:69:9:69:36 | After function call |
+| stmts.go:69:9:69:36 | defer-invoke function call | stmts.go:65:23:72:1 | result-read:0 block statement |
| stmts.go:69:9:69:36 | defer-invoke function call | stmts.go:69:3:69:36 | catch-defer-panic defer statement |
| stmts.go:69:9:69:36 | function call | stmts.go:69:9:69:34 | function literal |
| stmts.go:69:16:69:34 | After block statement | stmts.go:69:9:69:34 | Normal Exit |
@@ -2930,10 +3197,11 @@
| stmts.go:69:30:69:31 | Before -... | stmts.go:69:31:69:31 | x |
| stmts.go:69:31:69:31 | x | stmts.go:69:30:69:31 | -... |
| stmts.go:71:2:71:10 | Before return statement | stmts.go:71:9:71:10 | 42 |
-| stmts.go:71:2:71:10 | catch-return return statement | stmts.go:67:9:67:35 | defer-invoke function call |
-| stmts.go:71:2:71:10 | catch-return return statement | stmts.go:69:9:69:36 | defer-invoke function call |
+| stmts.go:71:2:71:10 | catch-return return statement | stmts.go:67:9:67:35 | defer-callee-read function call |
+| stmts.go:71:2:71:10 | catch-return return statement | stmts.go:69:9:69:36 | defer-callee-read function call |
+| stmts.go:71:2:71:10 | result-write:0 return statement | stmts.go:71:2:71:10 | return statement |
| stmts.go:71:2:71:10 | return statement | stmts.go:71:2:71:10 | catch-return return statement |
-| stmts.go:71:9:71:10 | 42 | stmts.go:71:2:71:10 | return statement |
+| stmts.go:71:9:71:10 | 42 | stmts.go:71:2:71:10 | result-write:0 return statement |
| stmts.go:75:1:109:1 | Entry | stmts.go:75:12:75:12 | x |
| stmts.go:75:1:109:1 | Exceptional Exit | stmts.go:75:1:109:1 | Exit |
| stmts.go:75:1:109:1 | Normal Exit | stmts.go:75:1:109:1 | Exit |
diff --git a/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/NoretFunctions.expected b/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/NoretFunctions.expected
index 52306e9a9878..0501226f6038 100644
--- a/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/NoretFunctions.expected
+++ b/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/NoretFunctions.expected
@@ -18,5 +18,10 @@
| stmts7.go:33:6:33:20 | deferBeforeExit | github.com/github/codeql-go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph.deferBeforeExit |
| stmts7.go:43:6:43:23 | finalDeferredPanic | github.com/github/codeql-go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph.finalDeferredPanic |
| stmts7.go:47:6:47:31 | deferredExitStopsRemaining | github.com/github/codeql-go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph.deferredExitStopsRemaining |
+| stmts7.go:87:6:87:17 | panicWithArg | github.com/github/codeql-go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph.panicWithArg |
+| stmts7.go:98:6:98:30 | panicAfterNonRecoverDefer | github.com/github/codeql-go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph.panicAfterNonRecoverDefer |
+| stmts7.go:104:6:104:30 | parenthesizedExitAndPanic | github.com/github/codeql-go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph.parenthesizedExitAndPanic |
+| stmts7.go:114:6:114:50 | recoveredBodyPanicBeforeEarlierPanickingDefer | github.com/github/codeql-go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph.recoveredBodyPanicBeforeEarlierPanickingDefer |
+| stmts7.go:126:6:126:39 | loopNonPanickingDeferWithBodyPanic | github.com/github/codeql-go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph.loopNonPanickingDeferWithBodyPanic |
| stmts.go:10:6:10:10 | test5 | github.com/github/codeql-go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph.test5 |
| stmts.go:46:6:46:10 | test6 | github.com/github/codeql-go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph.test6 |
diff --git a/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/stmts7.go b/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/stmts7.go
index 64d5db51563d..ace28cf47897 100644
--- a/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/stmts7.go
+++ b/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/stmts7.go
@@ -83,3 +83,51 @@ func panicAroundDefer(panicEarly bool) {
defer recoverPanic()
panic("late")
}
+
+func panicWithArg(_ int) {
+ panic("deferred panic")
+}
+
+func deferredPanicWithPanickingArg(xs []int) {
+ defer recoverPanic()
+ defer panicWithArg(xs[0])
+}
+
+func nonRecoverCleanup() {}
+
+func panicAfterNonRecoverDefer(s []byte) int {
+ defer clear(s)
+ defer nonRecoverCleanup()
+ panic("unrecovered")
+}
+
+func parenthesizedExitAndPanic(cond bool) int {
+ if cond {
+ defer recoverPanic()
+ (os.Exit)(1)
+ }
+ defer recoverPanic()
+ defer (os.Exit)(1)
+ return 0
+}
+
+func recoveredBodyPanicBeforeEarlierPanickingDefer() int {
+ defer (panic)("earlier panic")
+ defer recoverPanic()
+ panic("body panic")
+}
+
+func recoveredDeferredPanicAllowsNormalReturn() int {
+ defer recoverPanic()
+ defer (panic)("deferred panic")
+ return 1
+}
+
+func loopNonPanickingDeferWithBodyPanic(xs [][]byte) {
+ for _, s := range xs {
+ defer clear(s)
+ }
+ panic("unrecovered loop")
+}
+
+
diff --git a/go/ql/test/library-tests/semmle/go/frameworks/Twirp/CONSISTENCY/SsaConsistency.expected b/go/ql/test/library-tests/semmle/go/frameworks/Twirp/CONSISTENCY/SsaConsistency.expected
index 440d65afa578..4c0837482560 100644
--- a/go/ql/test/library-tests/semmle/go/frameworks/Twirp/CONSISTENCY/SsaConsistency.expected
+++ b/go/ql/test/library-tests/semmle/go/frameworks/Twirp/CONSISTENCY/SsaConsistency.expected
@@ -32,23 +32,23 @@ phiWithoutTwoPriorRefs
| rpc/notes/service.twirp.go:446:1:527:1 | SSA phi(handler) | rpc/notes/service.twirp.go:446:1:527:1 | Normal Exit | rpc/notes/service.twirp.go:468:2:468:8 | handler | 1 |
| rpc/notes/service.twirp.go:446:1:527:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:446:1:527:1 | Exceptional Exit | rpc/notes/service.twirp.go:461:2:461:11 | reqContent | 1 |
| rpc/notes/service.twirp.go:446:1:527:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:446:1:527:1 | Normal Exit | rpc/notes/service.twirp.go:461:2:461:11 | reqContent | 1 |
-| rpc/notes/service.twirp.go:494:9:494:48 | SSA phi(err) | rpc/notes/service.twirp.go:494:9:494:48 | defer-invoke call to ensurePanicResponses | rpc/notes/service.twirp.go:447:6:447:8 | err | 1 |
-| rpc/notes/service.twirp.go:494:9:494:48 | SSA phi(respContent) | rpc/notes/service.twirp.go:494:9:494:48 | defer-invoke call to ensurePanicResponses | rpc/notes/service.twirp.go:492:6:492:16 | respContent | 1 |
+| rpc/notes/service.twirp.go:494:9:494:48 | SSA phi(err) | rpc/notes/service.twirp.go:494:9:494:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:447:6:447:8 | err | 1 |
+| rpc/notes/service.twirp.go:494:9:494:48 | SSA phi(respContent) | rpc/notes/service.twirp.go:494:9:494:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:492:6:492:16 | respContent | 1 |
| rpc/notes/service.twirp.go:529:1:606:1 | SSA phi(handler) | rpc/notes/service.twirp.go:529:1:606:1 | Exceptional Exit | rpc/notes/service.twirp.go:549:2:549:8 | handler | 1 |
| rpc/notes/service.twirp.go:529:1:606:1 | SSA phi(handler) | rpc/notes/service.twirp.go:529:1:606:1 | Normal Exit | rpc/notes/service.twirp.go:549:2:549:8 | handler | 1 |
| rpc/notes/service.twirp.go:529:1:606:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:529:1:606:1 | Exceptional Exit | rpc/notes/service.twirp.go:543:2:543:11 | reqContent | 1 |
| rpc/notes/service.twirp.go:529:1:606:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:529:1:606:1 | Normal Exit | rpc/notes/service.twirp.go:543:2:543:11 | reqContent | 1 |
-| rpc/notes/service.twirp.go:575:9:575:48 | SSA phi(err) | rpc/notes/service.twirp.go:575:9:575:48 | defer-invoke call to ensurePanicResponses | rpc/notes/service.twirp.go:530:6:530:8 | err | 1 |
-| rpc/notes/service.twirp.go:575:9:575:48 | SSA phi(respContent) | rpc/notes/service.twirp.go:575:9:575:48 | defer-invoke call to ensurePanicResponses | rpc/notes/service.twirp.go:573:6:573:16 | respContent | 1 |
+| rpc/notes/service.twirp.go:575:9:575:48 | SSA phi(err) | rpc/notes/service.twirp.go:575:9:575:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:530:6:530:8 | err | 1 |
+| rpc/notes/service.twirp.go:575:9:575:48 | SSA phi(respContent) | rpc/notes/service.twirp.go:575:9:575:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:573:6:573:16 | respContent | 1 |
| rpc/notes/service.twirp.go:626:1:707:1 | SSA phi(handler) | rpc/notes/service.twirp.go:626:1:707:1 | Exceptional Exit | rpc/notes/service.twirp.go:648:2:648:8 | handler | 1 |
| rpc/notes/service.twirp.go:626:1:707:1 | SSA phi(handler) | rpc/notes/service.twirp.go:626:1:707:1 | Normal Exit | rpc/notes/service.twirp.go:648:2:648:8 | handler | 1 |
| rpc/notes/service.twirp.go:626:1:707:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:626:1:707:1 | Exceptional Exit | rpc/notes/service.twirp.go:641:2:641:11 | reqContent | 1 |
| rpc/notes/service.twirp.go:626:1:707:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:626:1:707:1 | Normal Exit | rpc/notes/service.twirp.go:641:2:641:11 | reqContent | 1 |
-| rpc/notes/service.twirp.go:674:9:674:48 | SSA phi(err) | rpc/notes/service.twirp.go:674:9:674:48 | defer-invoke call to ensurePanicResponses | rpc/notes/service.twirp.go:627:6:627:8 | err | 1 |
-| rpc/notes/service.twirp.go:674:9:674:48 | SSA phi(respContent) | rpc/notes/service.twirp.go:674:9:674:48 | defer-invoke call to ensurePanicResponses | rpc/notes/service.twirp.go:672:6:672:16 | respContent | 1 |
+| rpc/notes/service.twirp.go:674:9:674:48 | SSA phi(err) | rpc/notes/service.twirp.go:674:9:674:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:627:6:627:8 | err | 1 |
+| rpc/notes/service.twirp.go:674:9:674:48 | SSA phi(respContent) | rpc/notes/service.twirp.go:674:9:674:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:672:6:672:16 | respContent | 1 |
| rpc/notes/service.twirp.go:709:1:786:1 | SSA phi(handler) | rpc/notes/service.twirp.go:709:1:786:1 | Exceptional Exit | rpc/notes/service.twirp.go:729:2:729:8 | handler | 1 |
| rpc/notes/service.twirp.go:709:1:786:1 | SSA phi(handler) | rpc/notes/service.twirp.go:709:1:786:1 | Normal Exit | rpc/notes/service.twirp.go:729:2:729:8 | handler | 1 |
| rpc/notes/service.twirp.go:709:1:786:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:709:1:786:1 | Exceptional Exit | rpc/notes/service.twirp.go:723:2:723:11 | reqContent | 1 |
| rpc/notes/service.twirp.go:709:1:786:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:709:1:786:1 | Normal Exit | rpc/notes/service.twirp.go:723:2:723:11 | reqContent | 1 |
-| rpc/notes/service.twirp.go:755:9:755:48 | SSA phi(err) | rpc/notes/service.twirp.go:755:9:755:48 | defer-invoke call to ensurePanicResponses | rpc/notes/service.twirp.go:710:6:710:8 | err | 1 |
-| rpc/notes/service.twirp.go:755:9:755:48 | SSA phi(respContent) | rpc/notes/service.twirp.go:755:9:755:48 | defer-invoke call to ensurePanicResponses | rpc/notes/service.twirp.go:753:6:753:16 | respContent | 1 |
+| rpc/notes/service.twirp.go:755:9:755:48 | SSA phi(err) | rpc/notes/service.twirp.go:755:9:755:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:710:6:710:8 | err | 1 |
+| rpc/notes/service.twirp.go:755:9:755:48 | SSA phi(respContent) | rpc/notes/service.twirp.go:755:9:755:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:753:6:753:16 | respContent | 1 |
From e62a999e37e10764cdc1b3a1a816f397bedc6887 Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Tue, 1 Dec 2026 20:51:45 +0000
Subject: [PATCH 02/17] Go: Connect saved defer values to SSA and data flow
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>
---
.../consistency-queries/TempSsaConsistency.ql | 4 +
go/ql/lib/semmle/go/dataflow/SsaImpl.qll | 125 +++++++++
.../go/dataflow/internal/DataFlowNodes.qll | 108 +++++++-
.../go/dataflow/internal/DataFlowPrivate.qll | 45 ++-
.../go/dataflow/internal/FlowSummaryImpl.qll | 20 +-
.../Defer/CONSISTENCY/CfgConsistency.expected | 17 ++
.../Defer/CONSISTENCY/SsaConsistency.expected | 0
.../UnexpectedFrontendErrors.expected | 3 +
.../semmle/go/dataflow/Defer/Flows.expected | 0
.../semmle/go/dataflow/Defer/Flows.ql | 3 +
.../semmle/go/dataflow/Defer/main.go | 261 ++++++++++++++++++
11 files changed, 557 insertions(+), 29 deletions(-)
create mode 100644 go/ql/consistency-queries/TempSsaConsistency.ql
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/UnexpectedFrontendErrors.expected
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/Defer/Flows.expected
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/Defer/Flows.ql
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go
diff --git a/go/ql/consistency-queries/TempSsaConsistency.ql b/go/ql/consistency-queries/TempSsaConsistency.ql
new file mode 100644
index 000000000000..e41e5e04c26f
--- /dev/null
+++ b/go/ql/consistency-queries/TempSsaConsistency.ql
@@ -0,0 +1,4 @@
+import go
+import semmle.go.dataflow.SsaImpl
+import TempConsistency
+import TempDataFlowIntegration::DfConsistency
diff --git a/go/ql/lib/semmle/go/dataflow/SsaImpl.qll b/go/ql/lib/semmle/go/dataflow/SsaImpl.qll
index e8d0ad6ed9f3..2aa30f98559c 100644
--- a/go/ql/lib/semmle/go/dataflow/SsaImpl.qll
+++ b/go/ql/lib/semmle/go/dataflow/SsaImpl.qll
@@ -268,3 +268,128 @@ predicate adjacentUseUse(IR::Instruction use1, IR::Instruction use2) {
use2 = bb2.getNode(i2)
)
}
+
+cached
+private module TempInternal {
+ /** Holds if the `i`th node of `bb` writes `rhs` to synthetic temporary `v`. */
+ cached
+ predicate tempDefAt(BasicBlock bb, int i, IR::TempVariable v, IR::Instruction rhs) {
+ bb.getNode(i).(IR::Instruction).writesTemp(v, rhs)
+ }
+
+ /** Holds if the `i`th node of `bb` reads synthetic temporary `v`. */
+ cached
+ predicate tempUseAt(BasicBlock bb, int i, IR::TempVariable v) {
+ bb.getNode(i).(IR::Instruction).readsTemp(v)
+ }
+
+ private predicate tempEntryNode(FuncDef f, BasicBlock bb, int i) {
+ f = bb.getScope() and
+ bb.getNode(i).(ControlFlow::Node).isEntryNode()
+ }
+
+ /** SSA input for synthetic temporary variables. */
+ cached
+ module TempSsaInput implements SsaImplCommon::InputSig {
+ class SourceVariable = IR::TempVariable;
+
+ cached
+ predicate variableWrite(BasicBlock bb, int i, SourceVariable v, boolean certain) {
+ (
+ tempDefAt(bb, i, v, _)
+ or
+ // Uninitialized entry definition so conditional/loop `defer`s and
+ // `panic`/`recover` paths satisfy SSA dominance without bogus values.
+ tempEntryNode(v.getEnclosingFunction(), bb, i)
+ ) and
+ certain = true
+ }
+
+ cached
+ predicate variableRead(BasicBlock bb, int i, SourceVariable v, boolean certain) {
+ tempUseAt(bb, i, v) and certain = true
+ }
+
+ cached
+ predicate ssaCachedStageRevRef() { TempDataFlowIntegrationImpl::ssaCachedStageRevRef2() }
+ }
+}
+
+import TempInternal
+private import SsaImplCommon::Make as TempImpl
+
+private module TempDataFlowIntegrationInput implements TempImpl::DataFlowIntegrationInputSig {
+ private import codeql.util.Void
+
+ predicate ssaDefHasSource(TempImpl::WriteDefinition def) {
+ exists(BasicBlock bb, int i, IR::TempVariable v |
+ def.definesAt(v, bb, i) and
+ tempDefAt(bb, i, v, _)
+ )
+ }
+
+ predicate allowFlowIntoUncertainDef(TempImpl::UncertainWriteDefinition def) { none() }
+
+ class GuardValue = Void;
+
+ class Guard extends Void {
+ string toString() { none() }
+
+ predicate hasValueBranchEdge(BasicBlock bb1, BasicBlock bb2, GuardValue val) { none() }
+
+ predicate valueControlsBranchEdge(BasicBlock bb1, BasicBlock bb2, GuardValue val) { none() }
+ }
+
+ predicate guardDirectlyControlsBlock(Guard guard, BasicBlock bb, GuardValue val) { none() }
+
+ predicate supportBarrierGuardsOnPhiEdges() { none() }
+
+ predicate includeWriteDefsInFlowStep() { none() }
+}
+
+private module TempDataFlowIntegrationImpl =
+ TempImpl::DataFlowIntegration;
+
+/** Provides SSA nodes and local flow steps for synthetic temporary variables. */
+cached
+module TempDataFlowIntegration {
+ import TempDataFlowIntegrationImpl
+
+ /**
+ * Holds if the value of `v` flows from `nodeFrom` to `nodeTo` in one local SSA step.
+ */
+ cached
+ predicate localFlowStep(IR::TempVariable v, Node nodeFrom, Node nodeTo, boolean isUseStep) {
+ TempDataFlowIntegrationImpl::localFlowStep(v, nodeFrom, nodeTo, isUseStep)
+ }
+}
+
+module TempConsistency = TempImpl::Consistency;
+
+private TempImpl::WriteDefinition getATempOriginWrite(TempImpl::Definition def) {
+ result = def
+ or
+ exists(TempImpl::Definition inp |
+ TempImpl::phiHasInputFromBlock(def, inp, _) and
+ result = getATempOriginWrite(inp)
+ )
+}
+
+/**
+ * Holds if `rhs` is saved into a synthetic temporary variable and reaches
+ * `read` (possibly through phi nodes).
+ */
+cached
+predicate tempDefUseStep(IR::Instruction rhs, IR::Instruction read) {
+ exists(
+ IR::TempVariable v, TempImpl::Definition def, TempImpl::WriteDefinition w, BasicBlock bbDef,
+ int iDef, BasicBlock bbRead, int iRead
+ |
+ TempImpl::ssaDefReachesRead(v, def, bbRead, iRead) and
+ read = bbRead.getNode(iRead) and
+ read.readsTemp(v) and
+ w = getATempOriginWrite(def) and
+ w.definesAt(v, bbDef, iDef) and
+ tempDefAt(bbDef, iDef, v, rhs)
+ )
+}
diff --git a/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll b/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
index b21739f9f98c..033af916c407 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
@@ -2,6 +2,7 @@ overlay[local?]
module;
private import go
+private import semmle.go.controlflow.ControlFlowGraphImpl
private import semmle.go.dataflow.FunctionInputsAndOutputs
private import semmle.go.dataflow.FlowSummary
private import semmle.go.dataflow.SsaImpl as SsaImpl
@@ -11,11 +12,14 @@ private import semmle.go.dataflow.ExternalFlow
private module SsaFlow = SsaImpl::DataFlowIntegration;
+private module TempSsaFlow = SsaImpl::TempDataFlowIntegration;
+
cached
private newtype TNode =
MkInstructionNode(IR::Instruction insn) or
MkSsaNode(SsaDefinition ssa) or
MkSsaSynthReadNode(SsaFlow::SsaSynthReadNode ssa) or
+ MkTempSsaNode(TempSsaFlow::SsaNode ssa) or
MkGlobalFunctionNode(Function f) or
MkImplicitVarargsSlice(IR::EvalInstruction ins) {
// We only use CallExprs with an EvalInstruction to guarantee reachability.
@@ -72,6 +76,50 @@ module Private {
n.(SsaFlow::WriteDefSourceNode).getDefinition().(SsaExplicitWrite).getDefinition().getRhs()
}
+ /** An SSA node for a synthetic temporary variable (such as a phi merge). */
+ class TempSsaNode extends Node, MkTempSsaNode {
+ private TempSsaFlow::SsaNode ssa;
+
+ TempSsaNode() { this = MkTempSsaNode(ssa) }
+
+ TempSsaFlow::SsaNode getSsaNode() { result = ssa }
+
+ override ControlFlow::Root getRoot() { result = ssa.getBasicBlock().getScope() }
+
+ override BasicBlock getBasicBlock() { result = ssa.getBasicBlock() }
+
+ override Type getType() { result = ssa.getSourceVariable().getType() }
+
+ override string getNodeKind() { result = "temp SSA node" }
+
+ override string toString() { result = ssa.toString() }
+
+ override Location getLocation() { result = ssa.getLocation() }
+ }
+
+ /** Gets the Go data-flow node corresponding to temporary SSA node `n`. */
+ Node getNodeFromTempSsaNode(TempSsaFlow::Node n) {
+ result.(TempSsaNode).getSsaNode() = n
+ or
+ exists(IR::Instruction insn, IR::TempVariable v |
+ n.(TempSsaFlow::ReadNode).readsAt(insn, v) and
+ insn.readsTemp(v) and
+ result.asInstruction() = insn
+ )
+ or
+ exists(IR::Instruction insn, IR::TempVariable v |
+ n.(TempSsaFlow::PostUpdateReadNode).readsAt(insn, v) and
+ insn.readsTemp(v) and
+ result.(PostUpdateNode).getPreUpdateNode().asInstruction() = insn
+ )
+ or
+ exists(BasicBlock bb, int i, IR::TempVariable v, IR::Instruction rhs |
+ n.(TempSsaFlow::WriteDefSourceNode).getDefinition().definesAt(v, bb, i) and
+ SsaImpl::tempDefAt(bb, i, v, rhs) and
+ result.asInstruction() = rhs
+ )
+ }
+
/** Gets the callable in which this node occurs. */
DataFlowCallable nodeGetEnclosingCallable(Node n) {
result.asCallable() = n.getEnclosingCallable()
@@ -216,7 +264,7 @@ module Public {
Type getTypeBound() { result = this.getType() }
/** Gets the floating-point value this data-flow node contains, if any. */
- float getFloatValue() { result = this.asExpr().getFloatValue() }
+ float getFloatValue() { result = this.asInstruction().getFloatValue() }
/**
* Gets the integer value this data-flow node contains, if any.
@@ -290,9 +338,19 @@ module Public {
override string getNodeKind() { result = insn.getInsnKind() }
- override string toString() { result = insn.toString() }
+ override string toString() {
+ result = insn.(IR::DeferReadInstruction).getSavedInstruction().toString()
+ or
+ not insn instanceof IR::DeferReadInstruction and
+ result = insn.toString()
+ }
- override Location getLocation() { result = insn.getLocation() }
+ override Location getLocation() {
+ result = insn.(IR::DeferReadInstruction).getSavedInstruction().getLocation()
+ or
+ not insn instanceof IR::DeferReadInstruction and
+ result = insn.getLocation()
+ }
}
/**
@@ -578,7 +636,14 @@ module Public {
string getCalleeName() { result = expr.getCalleeName() }
/** Gets the data flow node specifying the function to be called. */
- Node getCalleeNode() { result = DataFlow::exprNode(expr.getCalleeExpr()) }
+ Node getCalleeNode() {
+ exists(DeferStmt d | d.getCall() = expr |
+ result = DataFlow::instructionNode(IR::deferReadCalleeInstruction(d))
+ )
+ or
+ not exists(DeferStmt d | d.getCall() = expr and exists(IR::deferReadCalleeInstruction(d))) and
+ result = DataFlow::exprNode(CfgImpl::unwrapCallee(expr.getCalleeExpr()))
+ }
/** Gets the underlying call. */
CallExpr getCall() { result = this.getExpr() }
@@ -589,6 +654,11 @@ module Public {
* considered separate.
*/
Node getSyntacticArgument(int i) {
+ exists(DeferStmt d | d.getCall() = expr |
+ result = DataFlow::instructionNode(IR::deferReadArgInstruction(d, i))
+ )
+ or
+ not exists(DeferStmt d | d.getCall() = expr) and
if expr.getArgument(0).getType() instanceof TupleType
then result = DataFlow::extractTupleElement(DataFlow::exprNode(expr.getArgument(0)), i)
else
@@ -694,7 +764,14 @@ module Public {
* In this case we use local flow to try to find the receiver (`file` in
* the above example).
*/
- Node getReceiver() { result = this.getACalleeSource().(MethodReadNode).getReceiver() }
+ Node getReceiver() {
+ exists(DeferStmt d | d.getCall() = expr |
+ result = DataFlow::instructionNode(IR::deferReadReceiverInstruction(d))
+ )
+ or
+ not exists(DeferStmt d | d.getCall() = expr and exists(IR::deferReadReceiverInstruction(d))) and
+ result = this.getACalleeSource().(MethodReadNode).getReceiver()
+ }
/** Holds if this call has an ellipsis after its last argument. */
predicate hasEllipsis() { expr.hasEllipsis() }
@@ -973,23 +1050,30 @@ module Public {
/**
* A node whose value is returned as a result from a function.
*
- * If the function declares named result variables, this is a node representing
- * the current value of one of those variables at function exit. Otherwise, this
- * is a node corresponding to an expression in a return statement.
+ * If the function declares named result variables or contains `defer`
+ * statements, this is a synthetic instruction node reading the result at
+ * function exit after deferred calls have run. Otherwise, this is a node
+ * corresponding to an expression in a `return` statement.
*/
class ResultNode extends InstructionNode {
int i;
ResultNode() {
exists(FuncDef fd |
- // If the function has named result variables, then the
- // `IR::ReadResultInstruction` nodes at the end of the function are
- // the correct result nodes. Otherwise, the returned expressions are
- // the result nodes.
+ // If the function has named result variables or `defer` statements,
+ // the result-read instructions at function exit are the result nodes.
+ // Otherwise, the returned expressions are the result nodes.
not exists(fd.getAResultVar()) and
+ not CfgImpl::funcHasDefer(fd) and
exists(IR::ReturnInstruction ret | ret.getRoot() = fd | insn = ret.getResult(i))
or
insn.(IR::ReadResultInstruction).reads(fd.getResultVar(i))
+ or
+ exists(IR::ReadUnnamedResultInstruction rr |
+ insn = rr and
+ rr.getFunction() = fd and
+ rr.getIndex() = i
+ )
)
}
diff --git a/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll b/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll
index 1344031700c3..daaec5e244eb 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll
@@ -75,6 +75,20 @@ predicate basicLocalFlowStep(Node nodeFrom, Node nodeTo) {
nodeFrom = getNodeFromSsaNode(pred) and
nodeTo = getNodeFromSsaNode(succ)
)
+ or
+ exists(SsaImpl::TempDataFlowIntegration::Node pred, SsaImpl::TempDataFlowIntegration::Node succ |
+ SsaImpl::TempDataFlowIntegration::localFlowStep(_, pred, succ, _) and
+ nodeFrom = getNodeFromTempSsaNode(pred) and
+ nodeTo = getNodeFromTempSsaNode(succ)
+ )
+}
+
+private SsaDefinition insnReadsSsaDef(IR::Instruction insn) {
+ exists(SsaSourceVariable v, BasicBlock bb, int i |
+ insn = bb.getNode(i) and
+ insn.reads(v) and
+ SsaImpl::ssaDefReachesRead(v, result, bb, i)
+ )
}
pragma[noinline]
@@ -337,23 +351,24 @@ class DataFlowCall extends Expr {
Location getLocation() { result = super.getLocation() }
}
-/** Holds if `e` is an expression that always has the same Boolean value `val`. */
-private predicate constantBooleanExpr(Expr e, boolean val) {
- e.getBoolValue() = val
+/** Holds if `insn` is an instruction that always has the same Boolean value `val`. */
+private predicate constantBooleanInstruction(IR::Instruction insn, boolean val) {
+ insn.getBoolValue() = val
or
- exists(SsaExplicitWrite def, Expr src |
- e = def.getARead() and
- IR::evalExprInstruction(src) = def.getDefinition().getRhs() and
- constantBooleanExpr(src, val)
+ exists(SsaExplicitWrite def |
+ def = insnReadsSsaDef(insn) and
+ constantBooleanInstruction(def.getDefinition().getRhs(), val)
)
+ or
+ constantBooleanInstruction(insn.(IR::DeferReadInstruction).getSavedInstruction(), val)
}
/** An argument that always has the same Boolean value. */
-private class ConstantBooleanArgumentNode extends ArgumentNode, ExprNode {
- ConstantBooleanArgumentNode() { constantBooleanExpr(this.getExpr(), _) }
+private class ConstantBooleanArgumentNode extends ArgumentNode {
+ ConstantBooleanArgumentNode() { constantBooleanInstruction(this.asInstruction(), _) }
- /** Gets the Boolean value of this expression. */
- boolean getBooleanValue() { constantBooleanExpr(this.getExpr(), result) }
+ /** Gets the Boolean value of this argument. */
+ boolean getBooleanValue() { constantBooleanInstruction(this.asInstruction(), result) }
}
/**
@@ -416,7 +431,15 @@ predicate nodeIsHidden(Node n) {
or
n instanceof SsaSynthReadNode
or
+ n instanceof TempSsaNode
+ or
n.(SsaNode).getDefinition() instanceof SsaImpl::PhiNode
+ or
+ n.asInstruction() instanceof IR::DeferReadInstruction
+ or
+ n.(PostUpdateNode).getPreUpdateNode().asInstruction() instanceof IR::DeferReadInstruction
+ or
+ n.asInstruction() instanceof IR::ReadUnnamedResultInstruction
}
class LambdaCallKind = Unit;
diff --git a/go/ql/lib/semmle/go/dataflow/internal/FlowSummaryImpl.qll b/go/ql/lib/semmle/go/dataflow/internal/FlowSummaryImpl.qll
index 28b82adb11f7..528e5064eaef 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/FlowSummaryImpl.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/FlowSummaryImpl.qll
@@ -391,12 +391,20 @@ module SourceSinkInterpretationInput implements
* navigate to any embedded struct types that truly host `field`.
*/
private Type getSyntacticQualifierBaseType(DataFlow::Node n) {
- exists(DataFlow::Node n2 |
- // look through implicit dereference, if there is one
- not exists(n.asInstruction().(IR::EvalImplicitDerefInstruction).getOperand()) and
- n2 = n
- or
- n2.asExpr() = n.asInstruction().(IR::EvalImplicitDerefInstruction).getOperand()
+ exists(DataFlow::Node n1, DataFlow::Node n2 |
+ (
+ n1.asInstruction() = n.asInstruction().(IR::DeferReadInstruction).getSavedInstruction()
+ or
+ not n.asInstruction() instanceof IR::DeferReadInstruction and
+ n1 = n
+ ) and
+ (
+ // look through implicit dereference, if there is one
+ not exists(n1.asInstruction().(IR::EvalImplicitDerefInstruction).getOperand()) and
+ n2 = n1
+ or
+ n2 = DataFlow::exprNode(n1.asInstruction().(IR::EvalImplicitDerefInstruction).getOperand())
+ )
|
result = lookThroughPointerType(skipImplicitFieldReads(n2).getType())
)
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected
new file mode 100644
index 000000000000..67751a1624de
--- /dev/null
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected
@@ -0,0 +1,17 @@
+consistencyOverview
+| multipleSuccessors | 14 |
+multipleSuccessors
+| main.go:174:2:174:6 | After ... = ... | successor | main.go:168:38:175:1 | After block statement |
+| main.go:174:2:174:6 | After ... = ... | successor | main.go:171:9:171:18 | defer-arg-read:0 call to sinkVal |
+| main.go:184:2:184:13 | catch-panic ... = ... | successor | main.go:177:1:186:1 | Exceptional Exit |
+| main.go:184:2:184:13 | catch-panic ... = ... | successor | main.go:180:9:182:6 | defer-callee-read function call |
+| main.go:185:2:185:6 | After ... = ... | successor | main.go:177:59:186:1 | After block statement |
+| main.go:185:2:185:6 | After ... = ... | successor | main.go:180:9:182:6 | defer-callee-read function call |
+| main.go:189:2:194:2 | After for statement | successor | main.go:188:27:195:1 | After block statement |
+| main.go:189:2:194:2 | After for statement | successor | main.go:191:9:193:6 | defer-callee-read function call |
+| main.go:190:3:190:15 | catch-panic ... := ... | successor | main.go:188:1:195:1 | Exceptional Exit |
+| main.go:190:3:190:15 | catch-panic ... := ... | successor | main.go:191:9:193:6 | defer-callee-read function call |
+| main.go:191:3:193:6 | catch-defer-panic defer statement | successor | main.go:188:1:195:1 | Exceptional Exit |
+| main.go:191:3:193:6 | catch-defer-panic defer statement | successor | main.go:191:9:193:6 | defer-callee-read function call |
+| main.go:191:9:193:6 | defer-invoke function call | successor | main.go:188:27:195:1 | After block statement |
+| main.go:191:9:193:6 | defer-invoke function call | successor | main.go:191:9:193:6 | defer-callee-read function call |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/UnexpectedFrontendErrors.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/UnexpectedFrontendErrors.expected
new file mode 100644
index 000000000000..052f44249172
--- /dev/null
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/UnexpectedFrontendErrors.expected
@@ -0,0 +1,3 @@
+| main.go:199:8:199:8 | undefined: unresolvedCallee |
+| main.go:199:35:199:35 | undefined: unresolvedArg |
+| main.go:200:8:200:8 | undefined: missingPkg |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/Flows.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/Flows.expected
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/Flows.ql b/go/ql/test/library-tests/semmle/go/dataflow/Defer/Flows.ql
new file mode 100644
index 000000000000..946f7d3ab85c
--- /dev/null
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/Flows.ql
@@ -0,0 +1,3 @@
+import go
+import utils.test.InlineFlowTest
+import DefaultFlowTest
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go b/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go
new file mode 100644
index 000000000000..02dac36d9624
--- /dev/null
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go
@@ -0,0 +1,261 @@
+package main
+
+func source() string {
+ return "tainted"
+}
+
+func sink(any) {}
+
+func sinkVal(s string) {
+ sink(s) // $ hasValueFlow="s"
+}
+
+func noopVal(string) {}
+
+type holder struct {
+ x string
+}
+
+func (h *holder) sinkField() {
+ sink(h.x) // $ hasValueFlow="selection of x"
+}
+
+func (h *holder) setField(v string) {
+ h.x = v
+}
+
+func setHolder(h *holder, v string) {
+ h.x = v
+}
+
+func sinkHolder(h *holder) {
+ sink(h.x) // $ hasValueFlow="selection of x"
+}
+
+// 1. Argument evaluated at defer registration, not at function exit.
+func testDeferArgSavedAtRegistration() {
+ x := source()
+ defer func(v string) {
+ sink(v) // $ hasValueFlow="v"
+ }(x)
+ x = "clean"
+ _ = x
+}
+
+func testDeferArgReassignedAfterNoFlow() {
+ x := "clean"
+ defer func(v string) {
+ sink(v)
+ }(x)
+ x = source()
+ _ = x
+}
+
+// 2. Callee variable evaluated at defer registration.
+func testDeferCalleeSavedAtRegistration() {
+ fn := func(v string) {
+ sink(v) // $ hasValueFlow="v"
+ }
+ defer fn(source())
+ fn = noopVal
+ _ = fn
+}
+
+func testDeferCalleeReassignedAfterNoFlow() {
+ fn := noopVal
+ defer fn(source())
+ fn = func(v string) {
+ sink(v)
+ }
+ _ = fn
+}
+
+// 3. Method receiver evaluated at defer registration.
+func testDeferReceiverSavedAtRegistration() {
+ h := &holder{x: source()}
+ defer h.sinkField()
+ h = &holder{x: "clean"}
+ _ = h
+}
+
+func testDeferReceiverReassignedAfterNoFlow() {
+ h := &holder{x: "clean"}
+ defer func(r *holder) {
+ sink(r.x)
+ }(h)
+ h = &holder{x: source()}
+ _ = h
+}
+
+// 4. Interface receiver evaluated at defer registration.
+type runner interface {
+ run(string)
+}
+
+type sinkRunner struct{}
+
+func (sinkRunner) run(v string) {
+ sink(v) // $ hasValueFlow="v"
+}
+
+type noopRunner struct{}
+
+func (noopRunner) run(string) {}
+
+type otherSinkRunner struct{}
+
+func (otherSinkRunner) run(v string) {
+ sink(v)
+}
+
+func testDeferInterfaceReceiver() {
+ var r runner = sinkRunner{}
+ defer r.run(source())
+ r = noopRunner{}
+ _ = r
+}
+
+func testDeferInterfaceReceiverReassignedAfterNoFlow() {
+ var r runner = noopRunner{}
+ defer r.run(source())
+ r = otherSinkRunner{}
+ _ = r
+}
+
+// 5. Bound method value assigned to variable and deferred.
+func testDeferBoundMethodValue() {
+ h := &holder{x: source()}
+ f := h.sinkField
+ defer f()
+ clean := &holder{x: "clean"}
+ f = clean.sinkField
+ _ = f
+}
+
+// 6. Spread multi-value call in defer.
+func sourceAndClean() (string, string) {
+ return source(), "clean"
+}
+
+func testDeferSpreadTuple() {
+ defer func(a, b string) {
+ sink(a) // $ hasValueFlow="a"
+ sink(b)
+ }(sourceAndClean())
+}
+
+// 7. Variadic call in defer.
+func testDeferVariadic() {
+ x := source()
+ defer func(prefix string, rest ...string) {
+ sink(prefix)
+ sink(rest[0]) // $ hasValueFlow="index expression"
+ }("clean", x)
+ x = "clean"
+ _ = x
+}
+
+func testDeferVariadicReassignedAfterNoFlow() {
+ x := "clean"
+ defer func(prefix string, rest ...string) {
+ sink(rest[0])
+ }("clean", x)
+ x = source()
+ _ = x
+}
+
+// 8. Conditional and loop defers.
+func testConditionalDefer(cond bool) {
+ x := source()
+ if cond {
+ defer sinkVal(x)
+ }
+ x = "clean"
+ _ = x
+}
+
+func testConditionalDeferReassignedAfterNoFlow(cond bool) {
+ x := "clean"
+ if cond {
+ defer func(v string) {
+ sink(v)
+ }(x)
+ }
+ x = source()
+ _ = x
+}
+
+func testLoopDefer(n int) {
+ for i := 0; i < n; i++ {
+ x := source()
+ defer func(v string) {
+ sink(v) // $ hasValueFlow="v"
+ }(x)
+ }
+}
+
+// 15. Unreachable and unresolved defer statements (CFG/IR/SSA consistency).
+func testUnreachableAndUnresolvedDefer(fn func(string), h *holder) {
+ defer unresolvedCallee(source(), unresolvedArg)
+ defer missingPkg.Cleanup(source())
+ return
+ defer fn(source())
+ defer h.setField(source())
+}
+
+// 19. Constant boolean argument branch pruning on deferred calls.
+func deferBoolFalseHelper(doSink bool, v string) {
+ if doSink {
+ sink(v)
+ }
+}
+
+func deferBoolTrueHelper(doSink bool, v string) {
+ if doSink {
+ sink(v) // $ hasValueFlow="v"
+ }
+}
+
+func testDeferConstantBoolPruning() {
+ defer deferBoolFalseHelper(false, source())
+
+ flagFalse := false
+ defer deferBoolFalseHelper(flagFalse, source())
+ flagFalse = true
+
+ flagTrue := true
+ defer deferBoolTrueHelper(flagTrue, source())
+ flagTrue = false
+}
+
+// 22. Nested address expressions, value-copy capture isolation, and bool receiver pruning.
+type deferBoolFlag bool
+
+func (f deferBoolFlag) maybeSinkFalse(v string) {
+ if bool(f) {
+ sink(v)
+ }
+}
+
+func (f deferBoolFlag) maybeSinkTrue(v string) {
+ if bool(f) {
+ sink(v) // $ hasValueFlow="v"
+ }
+}
+
+func testDeferBoolReceiverPruning() {
+ fFalse := deferBoolFlag(false)
+ defer fFalse.maybeSinkFalse(source())
+ fTrue := deferBoolFlag(true)
+ defer fTrue.maybeSinkTrue(source())
+}
+
+func genericDeferSink[T any](v T) {
+ sink(v) // $ hasValueFlow="v"
+}
+
+func testDeferParenthesizedAndGenericCallee() {
+ defer (genericDeferSink[string])(source())
+}
+
+func main() {}
From 1ecbeb524a43b9365229468e55afcdb390025dff Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Tue, 1 Dec 2026 20:53:06 +0000
Subject: [PATCH 03/17] Go: Propagate deferred mutations through the epilogue
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>
---
go/ql/lib/semmle/go/dataflow/SSA.qll | 5 +
.../go/dataflow/internal/DataFlowNodes.qll | 85 ++-
.../go/dataflow/internal/DataFlowPrivate.qll | 137 ++++
.../Defer/CONSISTENCY/CfgConsistency.expected | 28 +-
.../Defer/CONSISTENCY/SsaConsistency.expected | 6 +
.../UnexpectedFrontendErrors.expected | 6 +-
.../go/dataflow/Defer/ConstValues.expected | 1 +
.../semmle/go/dataflow/Defer/ConstValues.ql | 6 +
.../semmle/go/dataflow/Defer/main.go | 602 ++++++++++++++++++
.../DeadStoreOfLocal/testdata.go | 24 +
10 files changed, 876 insertions(+), 24 deletions(-)
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/Defer/ConstValues.expected
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/Defer/ConstValues.ql
diff --git a/go/ql/lib/semmle/go/dataflow/SSA.qll b/go/ql/lib/semmle/go/dataflow/SSA.qll
index 0138dddea976..f6212e72ba2b 100644
--- a/go/ql/lib/semmle/go/dataflow/SSA.qll
+++ b/go/ql/lib/semmle/go/dataflow/SSA.qll
@@ -31,6 +31,11 @@ class SsaSourceVariable extends LocalVariable {
mrn.getMethod().getReceiverType() instanceof PointerType
)
or
+ exists(IR::DeferReadReceiverInstruction dr |
+ dr.getSavedInstruction() = this.getARead().asInstruction() and
+ dr.getDeferStmt().getCall().getTarget().(Method).getReceiverType() instanceof PointerType
+ )
+ or
// variables where there is an unresolved reference with the same name in the same
// scope or a nested scope, suggesting that name resolution information may be incomplete
exists(FunctionScope scope, FuncDef inner |
diff --git a/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll b/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
index 033af916c407..2d96515f1596 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
@@ -69,6 +69,7 @@ module Private {
exists(IR::Instruction insn, SsaSourceVariable v |
n.(SsaFlow::PostUpdateReadNode).readsAt(insn, v) and
insn.reads(v) and
+ insnHasSyncPostUpdateNode(insn) and
result.(PostUpdateNode).getPreUpdateNode().asInstruction() = insn
)
or
@@ -908,6 +909,38 @@ module Public {
result = insn.(IR::ComponentReadInstruction).getBase()
}
+ /**
+ * Holds if `insn` is the instruction saved at `defer` registration for an
+ * argument or receiver of `d`.
+ */
+ predicate isDeferSavedArgOrReceiver(DeferStmt d, IR::Instruction insn) {
+ exists(IR::DeferReadInstruction invInsn |
+ (
+ invInsn instanceof IR::DeferReadArgInstruction or
+ invInsn instanceof IR::DeferReadReceiverInstruction
+ ) and
+ invInsn.getDeferStmt() = d and
+ insn = invInsn.getSavedInstruction()
+ )
+ }
+
+ /**
+ * Holds if `insn` lies on the access path of an instruction saved at `defer`
+ * registration for an argument or receiver of `d`.
+ */
+ predicate isOnDeferSavedAccessPath(DeferStmt d, IR::Instruction insn) {
+ isDeferSavedArgOrReceiver(d, insn)
+ or
+ exists(IR::Instruction succ | isOnDeferSavedAccessPath(d, succ) |
+ insn = getAccessPathPredecessorInsn(succ)
+ or
+ exists(AddressExpr ae |
+ succ = IR::evalExprInstruction(ae) and
+ insn = IR::evalExprInstruction(ae.getOperand().stripParens())
+ )
+ )
+ }
+
/**
* Holds if `tp` is a type that may (directly or indirectly) reference a memory location.
*
@@ -942,14 +975,17 @@ module Public {
abstract Node getPreUpdateNode();
}
- private predicate insnDirectlyHasPostUpdateNode(IR::Instruction insn) {
- exists(Expr e | insn = IR::evalExprInstruction(e.stripParens()) |
- e instanceof AddressExpr or
- e = any(AddressExpr ae).getOperand()
+ private predicate insnDirectlyHasSyncPostUpdateNode(IR::Instruction insn) {
+ exists(AddressExpr ae |
+ not isOnDeferSavedAccessPath(_, IR::evalExprInstruction(ae)) and
+ (
+ insn = IR::evalExprInstruction(ae) or
+ insn = IR::evalExprInstruction(ae.getOperand().stripParens())
+ )
)
or
(
- exists(CallExpr ce |
+ exists(CallExpr ce | not exists(DeferStmt d | d.getCall() = ce) |
ce.getArgument(0).stripParens().getType() instanceof TupleType and
insn = IR::extractTupleElement(IR::evalExprInstruction(ce.getArgument(0).stripParens()), _)
or
@@ -957,8 +993,9 @@ module Public {
insn = IR::evalExprInstruction(ce.getAnArgument().stripParens())
)
or
- // Receiver of a method call
+ // Receiver of a non-deferred method call
exists(CallExpr call, IR::MethodReadInstruction methodRead |
+ not exists(DeferStmt d | d.getCall() = call) and
methodRead = IR::evalExprInstruction(call.getCalleeExpr().stripParens()) and
insn = methodRead.getReceiver()
)
@@ -972,9 +1009,43 @@ module Public {
insn = IR::evalExprInstruction(any(SendStmt s).getChannel().stripParens())
}
+ /**
+ * Holds if `insn` has a post-update node for a state update that occurs
+ * synchronously when `insn` is evaluated.
+ */
+ predicate insnHasSyncPostUpdateNode(IR::Instruction insn) {
+ insnDirectlyHasSyncPostUpdateNode(insn)
+ or
+ exists(IR::Instruction succ |
+ insnHasSyncPostUpdateNode(succ) and
+ insn = getAccessPathPredecessorInsn(succ)
+ )
+ }
+
+ private predicate insnDirectlyHasDeferredPostUpdateNode(IR::Instruction insn) {
+ exists(AddressExpr ae |
+ isOnDeferSavedAccessPath(_, IR::evalExprInstruction(ae)) and
+ (
+ insn = IR::evalExprInstruction(ae) or
+ insn = IR::evalExprInstruction(ae.getOperand().stripParens())
+ )
+ )
+ or
+ (
+ insn = IR::deferReadArgInstruction(_, _)
+ or
+ insn = IR::deferReadReceiverInstruction(_)
+ or
+ isDeferSavedArgOrReceiver(_, insn)
+ ) and
+ mutableType(insn.getResultType())
+ }
+
/** Holds if the node corresponding to `insn` has a post-update node. */
predicate insnHasPostUpdateNode(IR::Instruction insn) {
- insnDirectlyHasPostUpdateNode(insn)
+ insnDirectlyHasSyncPostUpdateNode(insn)
+ or
+ insnDirectlyHasDeferredPostUpdateNode(insn)
or
exists(IR::Instruction succ |
insnHasPostUpdateNode(succ) and
diff --git a/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll b/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll
index daaec5e244eb..7c8bd675e69b 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll
@@ -81,6 +81,18 @@ predicate basicLocalFlowStep(Node nodeFrom, Node nodeTo) {
nodeFrom = getNodeFromTempSsaNode(pred) and
nodeTo = getNodeFromTempSsaNode(succ)
)
+ or
+ exists(IR::DeferReadInstruction invInsn |
+ (
+ invInsn instanceof IR::DeferReadArgInstruction or
+ invInsn instanceof IR::DeferReadReceiverInstruction
+ ) and
+ nodeFrom.(DataFlow::PostUpdateNode).getPreUpdateNode().asInstruction() = invInsn and
+ nodeTo.(DataFlow::PostUpdateNode).getPreUpdateNode().asInstruction() =
+ invInsn.getSavedInstruction()
+ )
+ or
+ deferredPostUpdateFlowStep(nodeFrom, nodeTo)
}
private SsaDefinition insnReadsSsaDef(IR::Instruction insn) {
@@ -91,6 +103,119 @@ private SsaDefinition insnReadsSsaDef(IR::Instruction insn) {
)
}
+private ControlFlow::Node epilogueNodeAfterDefer(DeferStmt d) {
+ result = IR::evalExprInstruction(d.getCall()).getASuccessor()
+ or
+ exists(ControlFlow::Node mid |
+ mid = epilogueNodeAfterDefer(d) and
+ (
+ mid instanceof IR::DeferReadInstruction or
+ mid = IR::evalExprInstruction(any(DeferStmt d2).getCall()) or
+ mid.isAdditional(any(DeferStmt d2), "catch-defer-panic") or
+ mid instanceof IR::ReadResultInstruction or
+ mid instanceof IR::ReadUnnamedResultInstruction
+ ) and
+ result = mid.getASuccessor()
+ )
+}
+
+private predicate deferReceiverTakesImplicitAddress(DeferStmt d, IR::Instruction savedInsn) {
+ exists(IR::DeferReadReceiverInstruction invInsn |
+ invInsn.getDeferStmt() = d and
+ savedInsn = invInsn.getSavedInstruction() and
+ d.getCall().getTarget().(Method).getReceiverType() instanceof PointerType and
+ not savedInsn.getResultType().getUnderlyingType() instanceof PointerType and
+ not savedInsn.(IR::ImplicitFieldReadInstruction).getField().getType().getUnderlyingType()
+ instanceof PointerType
+ )
+}
+
+/**
+ * Holds if `anc` is on a saved access path of `d` where `d` mutates `anc` in
+ * place (via `&` or an implicit pointer-receiver address without crossing a
+ * pointer, slice, map, or channel indirection).
+ */
+private predicate deferMutatesInPlace(DeferStmt d, IR::Instruction anc) {
+ exists(AddressExpr ae |
+ DataFlow::isDeferSavedArgOrReceiver(d, IR::evalExprInstruction(ae)) and
+ (
+ anc = IR::evalExprInstruction(ae) or
+ anc = IR::evalExprInstruction(ae.getOperand().stripParens())
+ )
+ )
+ or
+ deferReceiverTakesImplicitAddress(d, anc)
+ or
+ exists(IR::Instruction child | deferMutatesInPlace(d, child) |
+ exists(IR::FieldReadInstruction fr |
+ fr = child and
+ not fr.getBase().getResultType().getUnderlyingType() instanceof PointerType and
+ not fr.(IR::ImplicitFieldReadInstruction).getField().getType().getUnderlyingType() instanceof
+ PointerType and
+ anc = fr.getBase()
+ )
+ or
+ exists(IR::ElementReadInstruction er |
+ er = child and
+ er.getBase().getResultType().getUnderlyingType() instanceof ArrayType and
+ anc = er.getBase()
+ )
+ )
+}
+
+/**
+ * Holds if `nodeFrom` is a post-update node along the saved access path of
+ * `d`'s receiver or argument, and `nodeTo` is a subsequent epilogue read of
+ * the mutated state (either a later-running `defer` or a function result read).
+ */
+predicate deferredPostUpdateFlowStepForDefer(DeferStmt d, Node nodeFrom, Node nodeTo) {
+ exists(IR::Instruction anc, IR::Instruction laterRead |
+ DataFlow::isOnDeferSavedAccessPath(d, anc) and
+ nodeFrom.(DataFlow::PostUpdateNode).getPreUpdateNode().asInstruction() = anc and
+ laterRead = epilogueNodeAfterDefer(d) and
+ nodeTo = instructionNode(laterRead)
+ |
+ not deferMutatesInPlace(d, anc) and
+ exists(SsaWithFields var, Node laterUse |
+ instructionNode(anc) = var.getAUse() and
+ laterUse = var.getAUse()
+ |
+ laterUse = nodeTo
+ or
+ laterUse.asInstruction() = laterRead.(IR::DeferReadInstruction).getSavedInstruction()
+ or
+ laterRead instanceof IR::ReadUnnamedResultInstruction and
+ SsaImpl::tempDefUseStep(laterUse.asInstruction(), laterRead)
+ or
+ exists(SsaDefinition readDef, SsaExplicitWrite ult |
+ laterRead instanceof IR::ReadResultInstruction and
+ not laterRead instanceof IR::ReadUnnamedResultInstruction and
+ nodeTo.(DataFlow::ReadNode).readsSsaDefinition(readDef) and
+ ult = readDef.getAnUltimateDefinition() and
+ laterUse.asInstruction() = ult.getDefinition().(IR::WriteResultInstruction).getRhs()
+ )
+ )
+ or
+ exists(ResultVariable rv |
+ deferMutatesInPlace(d, anc) and
+ anc.reads(rv) and
+ laterRead instanceof IR::ReadResultInstruction and
+ not laterRead instanceof IR::ReadUnnamedResultInstruction and
+ laterRead.reads(rv)
+ )
+ )
+}
+
+/**
+ * Holds if `nodeFrom` is a post-update node along the saved access path of a
+ * deferred call's receiver or argument, and `nodeTo` is a subsequent epilogue
+ * read of the mutated state (either a later-running `defer` or a function
+ * result read).
+ */
+private predicate deferredPostUpdateFlowStep(Node nodeFrom, Node nodeTo) {
+ deferredPostUpdateFlowStepForDefer(_, nodeFrom, nodeTo)
+}
+
pragma[noinline]
private Field getASparselyUsedChannelTypedField() {
result.getType() instanceof ChanType and
@@ -133,6 +258,18 @@ predicate jumpStep(Node n1, Node n2) {
n1 = instructionNode(lastUse) or
n1.(DataFlow::PostUpdateNode).getPreUpdateNode() = instructionNode(lastUse)
)
+ or
+ exists(DeferStmt d, IR::Instruction anc |
+ DataFlow::isOnDeferSavedAccessPath(d, anc) and
+ n1.(DataFlow::PostUpdateNode).getPreUpdateNode().asInstruction() = anc and
+ (
+ not deferMutatesInPlace(d, anc) and
+ insnReadsSsaDef(anc).getAnUltimateDefinition() = def
+ or
+ deferMutatesInPlace(d, anc) and
+ anc.reads(def.getSourceVariable())
+ )
+ )
)
or
// If a channel-typed field is referenced exactly once in the context of
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected
index 67751a1624de..234eea2269a2 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected
@@ -1,17 +1,17 @@
consistencyOverview
| multipleSuccessors | 14 |
multipleSuccessors
-| main.go:174:2:174:6 | After ... = ... | successor | main.go:168:38:175:1 | After block statement |
-| main.go:174:2:174:6 | After ... = ... | successor | main.go:171:9:171:18 | defer-arg-read:0 call to sinkVal |
-| main.go:184:2:184:13 | catch-panic ... = ... | successor | main.go:177:1:186:1 | Exceptional Exit |
-| main.go:184:2:184:13 | catch-panic ... = ... | successor | main.go:180:9:182:6 | defer-callee-read function call |
-| main.go:185:2:185:6 | After ... = ... | successor | main.go:177:59:186:1 | After block statement |
-| main.go:185:2:185:6 | After ... = ... | successor | main.go:180:9:182:6 | defer-callee-read function call |
-| main.go:189:2:194:2 | After for statement | successor | main.go:188:27:195:1 | After block statement |
-| main.go:189:2:194:2 | After for statement | successor | main.go:191:9:193:6 | defer-callee-read function call |
-| main.go:190:3:190:15 | catch-panic ... := ... | successor | main.go:188:1:195:1 | Exceptional Exit |
-| main.go:190:3:190:15 | catch-panic ... := ... | successor | main.go:191:9:193:6 | defer-callee-read function call |
-| main.go:191:3:193:6 | catch-defer-panic defer statement | successor | main.go:188:1:195:1 | Exceptional Exit |
-| main.go:191:3:193:6 | catch-defer-panic defer statement | successor | main.go:191:9:193:6 | defer-callee-read function call |
-| main.go:191:9:193:6 | defer-invoke function call | successor | main.go:188:27:195:1 | After block statement |
-| main.go:191:9:193:6 | defer-invoke function call | successor | main.go:191:9:193:6 | defer-callee-read function call |
+| main.go:179:2:179:6 | After ... = ... | successor | main.go:173:38:180:1 | After block statement |
+| main.go:179:2:179:6 | After ... = ... | successor | main.go:176:9:176:18 | defer-arg-read:0 call to sinkVal |
+| main.go:189:2:189:13 | catch-panic ... = ... | successor | main.go:182:1:191:1 | Exceptional Exit |
+| main.go:189:2:189:13 | catch-panic ... = ... | successor | main.go:185:9:187:6 | defer-callee-read function call |
+| main.go:190:2:190:6 | After ... = ... | successor | main.go:182:59:191:1 | After block statement |
+| main.go:190:2:190:6 | After ... = ... | successor | main.go:185:9:187:6 | defer-callee-read function call |
+| main.go:194:2:199:2 | After for statement | successor | main.go:193:27:200:1 | After block statement |
+| main.go:194:2:199:2 | After for statement | successor | main.go:196:9:198:6 | defer-callee-read function call |
+| main.go:195:3:195:15 | catch-panic ... := ... | successor | main.go:193:1:200:1 | Exceptional Exit |
+| main.go:195:3:195:15 | catch-panic ... := ... | successor | main.go:196:9:198:6 | defer-callee-read function call |
+| main.go:196:3:198:6 | catch-defer-panic defer statement | successor | main.go:193:1:200:1 | Exceptional Exit |
+| main.go:196:3:198:6 | catch-defer-panic defer statement | successor | main.go:196:9:198:6 | defer-callee-read function call |
+| main.go:196:9:198:6 | defer-invoke function call | successor | main.go:193:27:200:1 | After block statement |
+| main.go:196:9:198:6 | defer-invoke function call | successor | main.go:196:9:198:6 | defer-callee-read function call |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
index e69de29bb2d1..fd9dc7ccee93 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
@@ -0,0 +1,6 @@
+uselessPhiNode
+| main.go:251:8:253:2 | SSA phi(res) | 1 |
+| main.go:798:2:800:2 | SSA phi(s2) | 1 |
+phiWithoutTwoPriorRefs
+| main.go:251:8:253:2 | SSA phi(res) | main.go:251:8:253:2 | Exit | main.go:250:33:250:35 | res | 1 |
+| main.go:798:2:800:2 | SSA phi(s2) | main.go:798:2:800:2 | Exit | main.go:795:2:795:3 | s2 | 1 |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/UnexpectedFrontendErrors.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/UnexpectedFrontendErrors.expected
index 052f44249172..4663b0fc4909 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/UnexpectedFrontendErrors.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/UnexpectedFrontendErrors.expected
@@ -1,3 +1,3 @@
-| main.go:199:8:199:8 | undefined: unresolvedCallee |
-| main.go:199:35:199:35 | undefined: unresolvedArg |
-| main.go:200:8:200:8 | undefined: missingPkg |
+| main.go:344:8:344:8 | undefined: unresolvedCallee |
+| main.go:344:35:344:35 | undefined: unresolvedArg |
+| main.go:345:8:345:8 | undefined: missingPkg |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/ConstValues.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/ConstValues.expected
new file mode 100644
index 000000000000..9ef54e8ac9f0
--- /dev/null
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/ConstValues.expected
@@ -0,0 +1 @@
+| 3.5 | abc | true | 7 |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/ConstValues.ql b/go/ql/test/library-tests/semmle/go/dataflow/Defer/ConstValues.ql
new file mode 100644
index 000000000000..f71ef1bcdbd5
--- /dev/null
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/ConstValues.ql
@@ -0,0 +1,6 @@
+import go
+
+from DataFlow::CallNode c
+where c.getTarget().getName() = "takeDeferConstFloat"
+select c.getArgument(0).getFloatValue(), c.getArgument(1).getStringValue(),
+ c.getArgument(2).getBoolValue(), c.getArgument(3).getIntValue()
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go b/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go
index 02dac36d9624..72b9ec0b3b7f 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go
@@ -1,5 +1,10 @@
package main
+import (
+ "bytes"
+ "encoding/json"
+)
+
func source() string {
return "tainted"
}
@@ -194,6 +199,146 @@ func testLoopDefer(n int) {
}
}
+// 9. Unnamed return values in functions with defer.
+func unnamedReturnValue() string {
+ x := source()
+ defer noopVal("done")
+ return x
+}
+
+func unnamedReturnMutatedByDeferArg() *holder {
+ h := &holder{}
+ defer setHolder(h, source())
+ sink(h.x) // body runs before defer: no flow
+ return h
+}
+
+func unnamedReturnMutatedByDeferReceiver() *holder {
+ h := &holder{}
+ defer h.setField(source())
+ sink(h.x) // body runs before defer: no flow
+ return h
+}
+
+func unnamedReturnReassignedAfterDefer() *holder {
+ h := &holder{}
+ defer setHolder(h, source())
+ h = &holder{}
+ return h
+}
+
+func testUnnamedReturns() {
+ sink(unnamedReturnValue()) // $ hasValueFlow="call to unnamedReturnValue"
+ sink(unnamedReturnMutatedByDeferArg().x) // $ hasValueFlow="selection of x"
+ sink(unnamedReturnMutatedByDeferReceiver().x) // $ hasValueFlow="selection of x"
+ sink(unnamedReturnReassignedAfterDefer().x)
+}
+
+// 10. Named return values with defer.
+func namedReturnNaked() (h *holder) {
+ h = &holder{}
+ defer setHolder(h, source())
+ return
+}
+
+func namedReturnFromLocal() (res *holder) {
+ h := &holder{}
+ defer setHolder(h, source())
+ return h
+}
+
+func namedReturnClosureWrite() (res string) {
+ defer func() {
+ res = source()
+ }()
+ return "clean"
+}
+
+func testNamedReturns() {
+ sink(namedReturnNaked().x) // $ hasValueFlow="selection of x"
+ sink(namedReturnFromLocal().x) // $ hasValueFlow="selection of x"
+ sink(namedReturnClosureWrite()) // $ hasValueFlow="call to namedReturnClosureWrite"
+}
+
+// 11. LIFO ordering between multiple defers.
+func testDeferLifoFlow() {
+ h := &holder{}
+ defer sinkHolder(h) // registered first -> runs second (sees mutation)
+ defer setHolder(h, source()) // registered second -> runs first (mutates h.x)
+}
+
+func testDeferLifoReverseNoFlow() {
+ h := &holder{}
+ defer setHolder(h, source()) // registered first -> runs second (too late)
+ defer func(p *holder) { // registered second -> runs first (h.x still clean)
+ sink(p.x)
+ }(h)
+}
+
+// 12. Parameter out-flow when mutated by defer inside callee.
+func fillHolderDeferred(h *holder) {
+ defer setHolder(h, source())
+}
+
+func testParamMutatedByDefer() {
+ h := &holder{}
+ fillHolderDeferred(h)
+ sink(h.x) // $ hasValueFlow="selection of x"
+}
+
+// 13. Address-of variable (&res) mutated by deferred call (taint tracking).
+type jsonBox struct {
+ Val string
+}
+
+func noopJsonBox(*jsonBox) {}
+
+func deferUnmarshalNamedResult() (res jsonBox) {
+ defer json.Unmarshal([]byte(source()), &res)
+ return
+}
+
+func deferUnmarshalOverridesExplicitNamedReturn() (res jsonBox) {
+ defer json.Unmarshal([]byte(source()), &res)
+ return jsonBox{}
+}
+
+func deferUnmarshalUnnamedResultNoFlow() jsonBox {
+ var res jsonBox
+ defer json.Unmarshal([]byte(source()), &res)
+ return res // copied before defer runs: no flow
+}
+
+func deferNoopPtrClearedBeforeReturn() (res jsonBox) {
+ res.Val = source()
+ defer noopJsonBox(&res)
+ res = jsonBox{}
+ return
+}
+
+func testDeferAddressOfVariableTaint() {
+ sink(deferUnmarshalNamedResult().Val) // $ hasTaintFlow="selection of Val"
+ sink(deferUnmarshalOverridesExplicitNamedReturn().Val) // $ hasTaintFlow="selection of Val"
+ sink(deferUnmarshalUnnamedResultNoFlow().Val)
+ sink(deferNoopPtrClearedBeforeReturn().Val)
+}
+
+// 14. Deferred promoted method with flow summary.
+type embeddedBuffer struct {
+ *bytes.Buffer
+}
+
+func deferPromotedWriteTo() *bytes.Buffer {
+ in := embeddedBuffer{Buffer: bytes.NewBufferString(source())}
+ out := &bytes.Buffer{}
+ defer in.WriteTo(out)
+ return out
+}
+
+func testDeferPromotedSummary() {
+ sink(deferPromotedWriteTo().String()) // $ hasTaintFlow="call to String"
+}
+
// 15. Unreachable and unresolved defer statements (CFG/IR/SSA consistency).
func testUnreachableAndUnresolvedDefer(fn func(string), h *holder) {
defer unresolvedCallee(source(), unresolvedArg)
@@ -203,6 +348,184 @@ func testUnreachableAndUnresolvedDefer(fn func(string), h *holder) {
defer h.setField(source())
}
+// 16. Nested access paths, promoted methods, implicit deref, &o.Inner, parameters, and globals.
+type innerNode struct {
+ val string
+}
+
+func (i *innerNode) setVal(v string) {
+ i.val = v
+}
+
+func setInnerNode(i *innerNode, v string) {
+ i.val = v
+}
+
+func sinkInnerNode(i *innerNode) {
+ sink(i.val) // $ hasValueFlow="selection of val"
+}
+
+type midNode struct {
+ in *innerNode
+}
+
+type embeddedPtrNode struct {
+ *innerNode
+}
+
+type outerNode struct {
+ mid midNode
+ midPt *midNode
+ mids []midNode
+ emb embeddedPtrNode
+}
+
+func deferNestedFieldRecv() outerNode {
+ o := outerNode{mid: midNode{in: &innerNode{}}}
+ defer o.mid.in.setVal(source())
+ sink(o.mid.in.val) // body runs before defer: no flow
+ return o
+}
+
+func deferNestedPtrFieldRecv() outerNode {
+ o := outerNode{midPt: &midNode{in: &innerNode{}}}
+ defer o.midPt.in.setVal(source())
+ return o
+}
+
+func deferNestedSliceRecv() outerNode {
+ o := outerNode{mids: []midNode{{in: &innerNode{}}}}
+ defer o.mids[0].in.setVal(source())
+ return o
+}
+
+func deferPromotedPtrRecv() outerNode {
+ o := outerNode{emb: embeddedPtrNode{innerNode: &innerNode{}}}
+ defer o.emb.setVal(source())
+ return o
+}
+
+func deferNestedFieldArg() outerNode {
+ o := outerNode{mid: midNode{in: &innerNode{}}}
+ defer setInnerNode(o.mid.in, source())
+ return o
+}
+
+func mutateOuterParamDeferred(o *outerNode) {
+ defer o.mid.in.setVal(source())
+}
+
+type sliceWrapper struct {
+ items []string
+}
+
+func (w sliceWrapper) setFirst(v string) {
+ w.items[0] = v
+}
+
+func deferImplicitDerefValueRecv() *sliceWrapper {
+ w := &sliceWrapper{items: make([]string, 1)}
+ defer w.setFirst(source())
+ return w
+}
+
+var globalDeferHolder = &holder{}
+
+func writeGlobalInDefer() {
+ defer globalDeferHolder.setField(source())
+}
+
+func testDeferredAccessPaths() {
+ sink(deferNestedFieldRecv().mid.in.val) // $ hasValueFlow="selection of val"
+ sink(deferNestedPtrFieldRecv().midPt.in.val) // $ hasValueFlow="selection of val"
+ sink(deferNestedSliceRecv().mids[0].in.val) // $ hasValueFlow="selection of val"
+ sink(deferPromotedPtrRecv().emb.val) // $ hasValueFlow="selection of val"
+ sink(deferNestedFieldArg().mid.in.val) // $ hasValueFlow="selection of val"
+
+ o := &outerNode{mid: midNode{in: &innerNode{}}}
+ mutateOuterParamDeferred(o)
+ sink(o.mid.in.val) // $ hasValueFlow="selection of val"
+
+ sink(deferImplicitDerefValueRecv().items[0]) // $ hasValueFlow="index expression"
+
+ writeGlobalInDefer()
+ sink(globalDeferHolder.x) // $ hasValueFlow="selection of x"
+}
+
+func testDeferredNestedLifo() {
+ o := outerNode{mid: midNode{in: &innerNode{}}}
+ defer sinkInnerNode(o.mid.in) // runs second: sees mutation
+ defer o.mid.in.setVal(source()) // runs first
+}
+
+func testDeferredNestedLifoNoFlow() {
+ o := outerNode{mid: midNode{in: &innerNode{}}}
+ defer o.mid.in.setVal(source()) // runs second: too late
+ defer func(in *innerNode) { // runs first
+ sink(in.val)
+ }(o.mid.in)
+}
+
+type jsonNestedOuter struct {
+ Inner jsonBox
+ Clean string
+}
+
+func sinkJsonBoxPtr(p *jsonBox) {
+ sink(p.Val) // $ MISSING: hasTaintFlow="selection of Val"
+}
+
+func deferAddressOfFieldNamed() (o jsonNestedOuter) {
+ defer json.Unmarshal([]byte(source()), &o.Inner)
+ sink(o.Inner.Val) // body runs before defer: no flow
+ return
+}
+
+func deferAddressOfFieldUnnamedNoFlow() jsonNestedOuter {
+ var o jsonNestedOuter
+ defer json.Unmarshal([]byte(source()), &o.Inner)
+ return o // copied by value before defer runs: no flow
+}
+
+func deferAddressOfFieldReturnPtr() *jsonBox {
+ var o jsonNestedOuter
+ defer json.Unmarshal([]byte(source()), &o.Inner)
+ return &o.Inner
+}
+
+func testDeferredAddressOfField() {
+ res := deferAddressOfFieldNamed()
+ sink(res.Inner.Val) // $ hasTaintFlow="selection of Val"
+ sink(res.Clean)
+
+ sink(deferAddressOfFieldUnnamedNoFlow().Inner.Val)
+ sink(deferAddressOfFieldReturnPtr().Val) // $ MISSING: hasTaintFlow="selection of Val"
+
+ var o jsonNestedOuter
+ defer sinkJsonBoxPtr(&o.Inner)
+ defer json.Unmarshal([]byte(source()), &o.Inner)
+}
+
+// 17. Value variable mutated via implicit pointer-receiver address.
+func deferValueBufferNamed() (b bytes.Buffer) {
+ defer b.WriteString(source())
+ return
+}
+
+func deferValueBufferUnnamedNoFlow() bytes.Buffer {
+ var b bytes.Buffer
+ defer b.WriteString(source())
+ return b // copied before defer runs: no flow
+}
+
+func testDeferredImplicitAddrReceiver() {
+ b1 := deferValueBufferNamed()
+ sink(b1.String()) // $ hasTaintFlow="call to String"
+
+ b2 := deferValueBufferUnnamedNoFlow()
+ sink(b2.String())
+}
+
// 19. Constant boolean argument branch pruning on deferred calls.
func deferBoolFalseHelper(doSink bool, v string) {
if doSink {
@@ -228,6 +551,119 @@ func testDeferConstantBoolPruning() {
flagTrue = false
}
+// 20. Element access paths, named-result return expressions, local aliases, and float constants.
+func (i *innerNode) sinkValMethod() {
+ sink(i.val) // $ MISSING: hasValueFlow="selection of val"
+}
+
+func deferSliceElemReturned() *innerNode {
+ items := []*innerNode{{}}
+ defer items[0].setVal(source())
+ return items[0]
+}
+
+func deferNamedResultReturnField() (res *innerNode) {
+ o := outerNode{mid: midNode{in: &innerNode{}}}
+ defer o.mid.in.setVal(source())
+ return o.mid.in
+}
+
+func deferNamedResultReturnAddr() (res *jsonBox) {
+ var o jsonNestedOuter
+ defer json.Unmarshal([]byte(source()), &o.Inner)
+ return &o.Inner
+}
+
+func deferLocalAliasFieldReturned() *innerNode {
+ o := outerNode{mid: midNode{in: &innerNode{}}}
+ p := o.mid.in
+ defer o.mid.in.setVal(source())
+ return p
+}
+
+func takeDeferConstFloat(f float64, s string, b bool, n int) {}
+
+func testDeferElementAndOriginPaths() {
+ sink(deferSliceElemReturned().val) // $ MISSING: hasValueFlow="selection of val"
+ sink(deferNamedResultReturnField().val) // $ hasValueFlow="selection of val"
+ sink(deferNamedResultReturnAddr().Val) // $ MISSING: hasTaintFlow="selection of Val"
+ sink(deferLocalAliasFieldReturned().val) // $ MISSING: hasValueFlow="selection of val"
+
+ var arr [2]innerNode
+ defer arr[0].sinkValMethod()
+ defer arr[0].setVal(source())
+
+ defer takeDeferConstFloat(3.5, "abc", true, 7)
+}
+
+// 21. Symmetric explicit-& / implicit-receiver lvalue mutations and panicking defers.
+type holderWithInnerVal struct {
+ in innerNode
+}
+
+func sinkInnerNodeFromImplicit(p *innerNode) {
+ sink(p.val) // $ MISSING: hasValueFlow="selection of val"
+}
+
+func (i *innerNode) sinkValPtrField() {
+ sink(i.val) // $ MISSING: hasValueFlow="selection of val"
+}
+
+func (i *innerNode) sinkValSliceElem() {
+ sink(i.val) // $ MISSING: hasValueFlow="selection of val"
+}
+
+func (i *innerNode) sinkValFromExplicitAddr() {
+ sink(i.val) // $ MISSING: hasValueFlow="selection of val"
+}
+
+func (i *innerNode) sinkValReassignedNoFlow() {
+ sink(i.val)
+}
+
+func deferImplicitReceiverReturnAddr() *innerNode {
+ var o holderWithInnerVal
+ defer o.in.setVal(source())
+ return &o.in
+}
+
+func setHolderAndPanic(h *holder, v string) {
+ h.x = v
+ panic("boom")
+}
+
+func testSymmetricAddrAndPanickingDefer() {
+ sink(deferImplicitReceiverReturnAddr().val) // $ MISSING: hasValueFlow="selection of val"
+
+ p := &holderWithInnerVal{}
+ defer p.in.sinkValPtrField()
+ defer p.in.setVal(source())
+
+ pReassigned := &holderWithInnerVal{}
+ defer pReassigned.in.sinkValReassignedNoFlow()
+ pReassigned = &holderWithInnerVal{}
+ defer pReassigned.in.setVal(source())
+
+ items := make([]innerNode, 1)
+ defer items[0].sinkValSliceElem()
+ defer items[0].setVal(source())
+
+ var o1 holderWithInnerVal
+ defer sinkInnerNodeFromImplicit(&o1.in)
+ defer o1.in.setVal(source())
+
+ var o2 holderWithInnerVal
+ defer o2.in.sinkValFromExplicitAddr()
+ defer setInnerNode(&o2.in, source())
+
+ h := &holder{}
+ defer func(q *holder) {
+ _ = recover()
+ sink(q.x) // $ hasValueFlow="selection of x"
+ }(h)
+ defer setHolderAndPanic(h, source())
+}
+
// 22. Nested address expressions, value-copy capture isolation, and bool receiver pruning.
type deferBoolFlag bool
@@ -243,6 +679,61 @@ func (f deferBoolFlag) maybeSinkTrue(v string) {
}
}
+func deferNestedAddrNamedResult() (box jsonBox) {
+ defer json.Unmarshal([]byte(source()), &*(&box))
+ return jsonBox{}
+}
+
+func syncUnmarshalAndMakeSlice(p *jsonBox, v string) []innerNode {
+ json.Unmarshal([]byte(v), p)
+ return make([]innerNode, 1)
+}
+
+func testNestedAddrNoSyncLeak() {
+ var boxSync jsonBox
+ defer json.Unmarshal([]byte(source()), &*(&boxSync))
+ sink(boxSync.Val)
+}
+
+func testNestedAddrLifoAndSyncSubCall() {
+ sink(deferNestedAddrNamedResult().Val) // $ MISSING: hasTaintFlow="selection of Val"
+
+ var arrLifo [1]innerNode
+ defer arrLifo[0].sinkValFromExplicitAddr()
+ defer setInnerNode(&(&arrLifo)[0], source())
+
+ var syncBox jsonBox
+ defer syncUnmarshalAndMakeSlice(&syncBox, source())[0].setVal("safe")
+ sink(syncBox.Val) // $ hasTaintFlow="selection of Val"
+}
+
+func testValueCopyCaptureIsolation() {
+ orig := jsonBox{Val: "safe"}
+ copied := orig
+ defer func() {
+ sink(orig.Val)
+ }()
+ defer json.Unmarshal([]byte(source()), &copied)
+}
+
+func testDirectCaptureInPlaceMutation() {
+ captured := jsonBox{Val: "safe"}
+ defer func() {
+ sink(captured.Val) // $ hasTaintFlow="selection of Val"
+ }()
+ captured = jsonBox{Val: "safe2"}
+ defer json.Unmarshal([]byte(source()), &captured)
+}
+
+func testSharedPtrCopyCaptureMutation() {
+ origPtr := midNode{in: &innerNode{}}
+ copiedPtr := origPtr
+ defer func() {
+ sink(origPtr.in.val) // $ MISSING: hasValueFlow="selection of val"
+ }()
+ defer copiedPtr.in.setVal(source())
+}
+
func testDeferBoolReceiverPruning() {
fFalse := deferBoolFlag(false)
defer fFalse.maybeSinkFalse(source())
@@ -250,6 +741,24 @@ func testDeferBoolReceiverPruning() {
defer fTrue.maybeSinkTrue(source())
}
+func panicWithInt(_ int) {
+ panic("boom")
+}
+
+func testDeferPanicWithPanickingArg(xs []int) {
+ x := "safe"
+ defer func() {
+ recover()
+ sink(x) // $ hasValueFlow="x"
+ }()
+ defer panicWithInt(xs[0])
+ x = source()
+}
+
+type byteSliceBox struct {
+ buf []byte
+}
+
func genericDeferSink[T any](v T) {
sink(v) // $ hasValueFlow="v"
}
@@ -258,4 +767,97 @@ func testDeferParenthesizedAndGenericCallee() {
defer (genericDeferSink[string])(source())
}
+func sinkStringPtrPostReg(p *string) {
+ sink(*p) // $ MISSING: hasValueFlow="star expression"
+}
+
+func sinkStringPtrTaintPostReg(p *string) {
+ sink(*p) // $ MISSING: hasTaintFlow="star expression"
+}
+
+type postRegHolder struct {
+ val string
+}
+
+func (h *postRegHolder) sinkValPtr() {
+ sink(h.val) // $ MISSING: hasValueFlow="selection of val"
+}
+
+func sinkStringPtrCleanPostReg(p *string) {
+ sink(*p)
+}
+
+func testDeferExplicitAddrAndImplicitPtrReceiverPostReg() {
+ s1 := "clean"
+ defer sinkStringPtrPostReg(&s1)
+ s1 = source()
+
+ s2 := "clean"
+ _ = s2
+ defer sinkStringPtrPostReg(&s2)
+ func() {
+ s2 = source()
+ }()
+
+ var box1 postRegHolder
+ defer sinkStringPtrPostReg(&box1.val)
+ box1.val = source()
+
+ var box2 postRegHolder
+ defer (box2.sinkValPtr)()
+ box2.val = source()
+
+ var box3 postRegHolder
+ defer box3.sinkValPtr()
+ box3 = postRegHolder{val: source()}
+
+ var box4 postRegHolder
+ defer sinkStringPtrPostReg(&box4.val)
+ box4 = postRegHolder{val: source()}
+
+ ptrReassigned := &postRegHolder{val: "clean"}
+ defer sinkStringPtrCleanPostReg(&ptrReassigned.val)
+ ptrReassigned = &postRegHolder{}
+ ptrReassigned.val = source()
+
+ sJson := "clean"
+ defer sinkStringPtrTaintPostReg(&sJson)
+ json.Unmarshal([]byte(source()), &sJson)
+}
+
+func sinkBytesTaintPostReg(b []byte) {
+ sink(string(b)) // $ MISSING: hasTaintFlow="type conversion"
+}
+
+func sinkBytesCleanPostReg(b []byte) {
+ sink(string(b))
+}
+
+func sinkMapValPostReg(m map[string]string) {
+ sink(m["k"]) // $ MISSING: hasValueFlow="index expression"
+}
+
+func sinkByteBoxTaintPostReg(box byteSliceBox) {
+ sink(string(box.buf)) // $ MISSING: hasTaintFlow="type conversion"
+}
+
+func testDeferSavedByValuePostRegMutations() {
+ b1 := make([]byte, 8)
+ defer sinkBytesTaintPostReg(b1)
+ copy(b1, []byte(source()))
+
+ bReassigned := make([]byte, 8)
+ defer sinkBytesCleanPostReg(bReassigned)
+ bReassigned = []byte(source())
+ _ = bReassigned
+
+ m := make(map[string]string)
+ defer sinkMapValPostReg(m)
+ m["k"] = source()
+
+ box := byteSliceBox{buf: make([]byte, 8)}
+ defer sinkByteBoxTaintPostReg(box)
+ copy(box.buf, []byte(source()))
+}
+
func main() {}
diff --git a/go/ql/test/query-tests/RedundantCode/DeadStoreOfLocal/testdata.go b/go/ql/test/query-tests/RedundantCode/DeadStoreOfLocal/testdata.go
index da7d6db82c34..8cef4bec660a 100644
--- a/go/ql/test/query-tests/RedundantCode/DeadStoreOfLocal/testdata.go
+++ b/go/ql/test/query-tests/RedundantCode/DeadStoreOfLocal/testdata.go
@@ -633,3 +633,27 @@ func _(v1, v2 int32) (int32, int32) {
}
func anyFunctionMightPanic()
+
+type deadStorePtrRecvBox struct {
+ f int
+}
+
+func (b *deadStorePtrRecvBox) use() {
+ _ = b.f
+}
+
+func useDeadStoreIntPtr(p *int) {
+ _ = *p
+}
+
+func _() {
+ var b deadStorePtrRecvBox
+ defer b.use()
+ b = deadStorePtrRecvBox{f: 1}
+}
+
+func _() {
+ x := 0
+ defer useDeadStoreIntPtr(&x)
+ x = 1
+}
From 9b47b7cc5e8cd1ba533522a4e73e626b403dfe6f Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Tue, 1 Dec 2026 20:54:24 +0000
Subject: [PATCH 04/17] Go: Preserve value numbers across defer temporaries
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>
---
.../go/dataflow/GlobalValueNumbering.qll | 33 +++++++++
go/ql/lib/semmle/go/dataflow/SsaImpl.qll | 23 +++++++
.../CONSISTENCY/CfgConsistency.expected | 11 +++
.../GlobalValueNumber.expected | 56 +++++++++++++++
.../go/dataflow/GlobalValueNumbering/main.go | 68 +++++++++++++++++++
5 files changed, 191 insertions(+)
diff --git a/go/ql/lib/semmle/go/dataflow/GlobalValueNumbering.qll b/go/ql/lib/semmle/go/dataflow/GlobalValueNumbering.qll
index 8b56ad224c73..561f8f8916c7 100644
--- a/go/ql/lib/semmle/go/dataflow/GlobalValueNumbering.qll
+++ b/go/ql/lib/semmle/go/dataflow/GlobalValueNumbering.qll
@@ -40,6 +40,7 @@ module;
*/
import go
+private import semmle.go.dataflow.SsaImpl as SsaImpl
/**
* Holds if the result is a control flow node that might change the
@@ -516,6 +517,35 @@ private predicate ssaInit(SsaExplicitWrite ssa, DataFlow::Node rhs) {
ssa.getDefinition().getRhs() = rhs.asInstruction()
}
+private DataFlow::Node deferOrResultSavedNode(DataFlow::Node nd) {
+ not analyzableConst(nd) and
+ (
+ exists(IR::DeferReadInstruction dr, IR::Instruction saved |
+ dr = nd.asInstruction() and
+ not dr.isSavedInLoop() and
+ saved = unique( | | dr.getSavedInstruction()) and
+ (
+ dr.getResultType().getUnderlyingType() instanceof BasicType or
+ dr.getResultType().getUnderlyingType() instanceof SignatureType or
+ mostRecentSideEffectUnique(dr) = mostRecentSideEffectUnique(saved)
+ ) and
+ result = DataFlow::instructionNode(saved)
+ )
+ or
+ exists(IR::ReadUnnamedResultInstruction rr, IR::Instruction rhs |
+ rr = nd.asInstruction() and
+ not SsaImpl::unnamedResultMayBeZeroedByRecover(rr) and
+ rhs = unique(IR::Instruction r | SsaImpl::tempDefUseStep(r, rr)) and
+ (
+ rr.getResultType().getUnderlyingType() instanceof BasicType or
+ rr.getResultType().getUnderlyingType() instanceof SignatureType or
+ mostRecentSideEffectUnique(rr) = mostRecentSideEffectUnique(rhs)
+ ) and
+ result = DataFlow::instructionNode(rhs)
+ )
+ )
+}
+
/** Gets the global value number of data-flow node `nd`. */
cached
GVN globalValueNumber(DataFlow::Node nd) {
@@ -579,6 +609,8 @@ GVN globalValueNumber(DataFlow::Node nd) {
result = MkDeref(p, dominator)
)
or
+ result = globalValueNumber(deferOrResultSavedNode(nd))
+ or
not analyzableExpr(nd) and
result = MkUnanalyzable(nd)
or
@@ -609,6 +641,7 @@ GVN globalValueNumber(DataFlow::Node nd) {
*/
private predicate analyzableExpr(DataFlow::Node e) {
analyzableConst(e) or
+ exists(deferOrResultSavedNode(e)) or
any(DataFlow::SsaNode ssa).getAUse() = e or
e instanceof DataFlow::SsaNode or
analyzableOtherVariable(e, _, _) or
diff --git a/go/ql/lib/semmle/go/dataflow/SsaImpl.qll b/go/ql/lib/semmle/go/dataflow/SsaImpl.qll
index 2aa30f98559c..0bb58d379dbb 100644
--- a/go/ql/lib/semmle/go/dataflow/SsaImpl.qll
+++ b/go/ql/lib/semmle/go/dataflow/SsaImpl.qll
@@ -393,3 +393,26 @@ predicate tempDefUseStep(IR::Instruction rhs, IR::Instruction read) {
tempDefAt(bbDef, iDef, v, rhs)
)
}
+
+/**
+ * Holds if unnamed result read `rr` can be reached along a `panic` path without
+ * an explicit `return` assignment and a deferred call in `rr.getFunction()` may
+ * recover that panic, leaving the result at its zero value.
+ */
+predicate unnamedResultMayBeZeroedByRecover(IR::ReadUnnamedResultInstruction rr) {
+ exists(DeferStmt d |
+ d.getEnclosingFunction() = rr.getFunction() and
+ CfgImpl::deferRecoversPanic(d)
+ ) and
+ exists(
+ IR::TempVariable v, TempImpl::Definition def, TempImpl::WriteDefinition w, BasicBlock bbDef,
+ int iDef, BasicBlock bbRead, int iRead
+ |
+ TempImpl::ssaDefReachesRead(v, def, bbRead, iRead) and
+ rr = bbRead.getNode(iRead) and
+ rr.readsTemp(v) and
+ w = getATempOriginWrite(def) and
+ w.definesAt(v, bbDef, iDef) and
+ not tempDefAt(bbDef, iDef, v, _)
+ )
+}
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/CONSISTENCY/CfgConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/CONSISTENCY/CfgConsistency.expected
index e69de29bb2d1..80445d85b19f 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/CONSISTENCY/CfgConsistency.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/CONSISTENCY/CfgConsistency.expected
@@ -0,0 +1,11 @@
+consistencyOverview
+| multipleSuccessors | 8 |
+multipleSuccessors
+| main.go:50:2:53:2 | After range statement | successor | main.go:49:33:54:1 | After block statement |
+| main.go:50:2:53:2 | After range statement | successor | main.go:52:9:52:22 | defer-arg-read:0 call to Println |
+| main.go:51:3:51:13 | catch-panic ... := ... | successor | main.go:49:1:54:1 | Exceptional Exit |
+| main.go:51:3:51:13 | catch-panic ... := ... | successor | main.go:52:9:52:22 | defer-arg-read:0 call to Println |
+| main.go:52:3:52:22 | catch-defer-panic defer statement | successor | main.go:49:1:54:1 | Exceptional Exit |
+| main.go:52:3:52:22 | catch-defer-panic defer statement | successor | main.go:52:9:52:22 | defer-arg-read:0 call to Println |
+| main.go:52:9:52:22 | defer-invoke call to Println | successor | main.go:49:33:54:1 | After block statement |
+| main.go:52:9:52:22 | defer-invoke call to Println | successor | main.go:52:9:52:22 | defer-arg-read:0 call to Println |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/GlobalValueNumber.expected b/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/GlobalValueNumber.expected
index b8d5333c8411..af1659fa2213 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/GlobalValueNumber.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/GlobalValueNumber.expected
@@ -6,7 +6,9 @@
| main.go:12:14:12:14 | x | main.go:10:7:10:7 | 0 |
| main.go:12:17:12:17 | y | main.go:10:7:10:7 | 0 |
| main.go:14:2:14:7 | SSA def(z) | main.go:14:7:14:7 | 1 |
+| main.go:14:2:14:7 | SSA def(z) | main.go:73:19:73:19 | 1 |
| main.go:14:7:14:7 | 1 | main.go:14:7:14:7 | 1 |
+| main.go:14:7:14:7 | 1 | main.go:73:19:73:19 | 1 |
| main.go:15:2:15:9 | call to bump | main.go:15:2:15:9 | call to bump |
| main.go:16:2:16:21 | call to Println | main.go:16:2:16:21 | call to Println |
| main.go:16:14:16:14 | x | main.go:10:7:10:7 | 0 |
@@ -15,6 +17,9 @@
| main.go:18:8:18:24 | call to make | main.go:18:8:18:24 | call to make |
| main.go:18:23:18:23 | 3 | main.go:18:23:18:23 | 3 |
| main.go:19:5:19:5 | 2 | main.go:19:5:19:5 | 2 |
+| main.go:19:5:19:5 | 2 | main.go:84:8:84:8 | 2 |
+| main.go:19:5:19:5 | 2 | main.go:90:8:90:8 | 2 |
+| main.go:19:5:19:5 | 2 | main.go:101:9:101:9 | 2 |
| main.go:19:10:19:24 | "Hello, world!" | main.go:19:10:19:24 | "Hello, world!" |
| main.go:20:2:20:16 | call to Println | main.go:20:2:20:16 | call to Println |
| main.go:23:23:26:1 | result-read:0 block statement | main.go:24:8:24:8 | 4 |
@@ -33,6 +38,57 @@
| main.go:36:9:36:9 | 8 | main.go:36:9:36:9 | 8 |
| main.go:38:2:38:9 | SSA def(res) | main.go:38:9:38:9 | 9 |
| main.go:38:9:38:9 | 9 | main.go:38:9:38:9 | 9 |
+| main.go:41:25:45:1 | result-read:0 block statement | main.go:42:7:42:12 | call to test |
+| main.go:42:2:42:12 | SSA def(v) | main.go:42:7:42:12 | call to test |
+| main.go:42:7:42:12 | call to test | main.go:42:7:42:12 | call to test |
+| main.go:43:8:43:21 | defer-invoke call to Println | main.go:43:8:43:21 | call to Println |
+| main.go:43:20:43:20 | v | main.go:42:7:42:12 | call to test |
+| main.go:43:20:43:20 | v | main.go:42:7:42:12 | call to test |
+| main.go:44:9:44:9 | v | main.go:42:7:42:12 | call to test |
+| main.go:51:3:51:13 | SSA def(v) | main.go:51:8:51:13 | call to test |
+| main.go:51:8:51:13 | call to test | main.go:51:8:51:13 | call to test |
+| main.go:52:9:52:22 | defer-invoke call to Println | main.go:52:9:52:22 | call to Println |
+| main.go:52:21:52:21 | v | main.go:51:8:51:13 | call to test |
+| main.go:57:8:57:29 | defer-invoke function call | main.go:57:8:57:29 | function call |
+| main.go:57:17:57:25 | call to recover | main.go:57:17:57:25 | call to recover |
+| main.go:59:9:59:10 | 42 | main.go:59:9:59:10 | 42 |
+| main.go:62:64:66:1 | result-read:0 block statement | main.go:65:9:65:10 | 43 |
+| main.go:63:8:63:23 | defer-invoke call to noopGvnCleanup | main.go:63:8:63:23 | call to noopGvnCleanup |
+| main.go:63:8:63:23 | defer-invoke call to noopGvnCleanup | main.go:95:8:95:23 | call to noopGvnCleanup |
+| main.go:65:9:65:10 | 43 | main.go:65:9:65:10 | 43 |
+| main.go:73:9:73:20 | struct literal | main.go:73:9:73:20 | struct literal |
+| main.go:73:19:73:19 | 1 | main.go:14:7:14:7 | 1 |
+| main.go:73:19:73:19 | 1 | main.go:73:19:73:19 | 1 |
+| main.go:79:8:79:33 | defer-invoke call to useGvnBox | main.go:79:8:79:33 | call to useGvnBox |
+| main.go:79:18:79:32 | call to makeGvnValBox | main.go:79:18:79:32 | call to makeGvnValBox |
+| main.go:79:18:79:32 | call to makeGvnValBox | main.go:79:18:79:32 | call to makeGvnValBox |
+| main.go:83:8:83:33 | defer-invoke call to useGvnBox | main.go:83:8:83:33 | call to useGvnBox |
+| main.go:83:18:83:32 | call to makeGvnValBox | main.go:83:18:83:32 | call to makeGvnValBox |
+| main.go:84:8:84:8 | 2 | main.go:19:5:19:5 | 2 |
+| main.go:84:8:84:8 | 2 | main.go:84:8:84:8 | 2 |
+| main.go:84:8:84:8 | 2 | main.go:90:8:90:8 | 2 |
+| main.go:84:8:84:8 | 2 | main.go:101:9:101:9 | 2 |
+| main.go:87:58:92:1 | result-read:0 block statement | main.go:88:7:88:12 | call to test |
+| main.go:88:2:88:12 | SSA def(x) | main.go:88:7:88:12 | call to test |
+| main.go:88:7:88:12 | call to test | main.go:88:7:88:12 | call to test |
+| main.go:89:8:89:21 | defer-invoke call to Println | main.go:89:8:89:21 | call to Println |
+| main.go:89:20:89:20 | x | main.go:88:7:88:12 | call to test |
+| main.go:89:20:89:20 | x | main.go:88:7:88:12 | call to test |
+| main.go:90:8:90:8 | 2 | main.go:19:5:19:5 | 2 |
+| main.go:90:8:90:8 | 2 | main.go:84:8:84:8 | 2 |
+| main.go:90:8:90:8 | 2 | main.go:90:8:90:8 | 2 |
+| main.go:90:8:90:8 | 2 | main.go:101:9:101:9 | 2 |
+| main.go:91:9:91:9 | x | main.go:88:7:88:12 | call to test |
+| main.go:94:51:97:1 | result-read:0 block statement | main.go:96:9:96:23 | call to makeGvnValBox |
+| main.go:95:8:95:23 | defer-invoke call to noopGvnCleanup | main.go:63:8:63:23 | call to noopGvnCleanup |
+| main.go:95:8:95:23 | defer-invoke call to noopGvnCleanup | main.go:95:8:95:23 | call to noopGvnCleanup |
+| main.go:96:9:96:23 | call to makeGvnValBox | main.go:96:9:96:23 | call to makeGvnValBox |
+| main.go:100:8:102:4 | defer-invoke function call | main.go:100:8:102:4 | function call |
+| main.go:101:9:101:9 | 2 | main.go:19:5:19:5 | 2 |
+| main.go:101:9:101:9 | 2 | main.go:84:8:84:8 | 2 |
+| main.go:101:9:101:9 | 2 | main.go:90:8:90:8 | 2 |
+| main.go:101:9:101:9 | 2 | main.go:101:9:101:9 | 2 |
+| main.go:103:9:103:23 | call to makeGvnValBox | main.go:103:9:103:23 | call to makeGvnValBox |
| regressions.go:5:11:5:31 | call to Sizeof | regressions.go:5:11:5:31 | call to Sizeof |
| regressions.go:7:11:7:15 | false | regressions.go:7:11:7:15 | false |
| regressions.go:9:11:9:12 | !... | regressions.go:11:11:11:14 | true |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/main.go b/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/main.go
index 85d28aa4a958..c1b7e8860b30 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/main.go
+++ b/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/main.go
@@ -37,3 +37,71 @@ func test3() (res int) {
}()
return 9
}
+
+func testDeferGvn() int {
+ v := test()
+ defer fmt.Println(v)
+ return v
+}
+
+func noopGvnCleanup() {}
+
+func testDeferLoopGvn(xs []int) {
+ for range xs {
+ v := test()
+ defer fmt.Println(v)
+ }
+}
+
+func testDeferRecoverUnnamedResultGvn(xs []int, idx int) int {
+ defer func() { recover() }()
+ _ = xs[idx]
+ return 42
+}
+
+func testDeferNoRecoverUnnamedResultGvn(xs []int, idx int) int {
+ defer noopGvnCleanup()
+ _ = xs[idx]
+ return 43
+}
+
+type gvnBox struct {
+ v int
+}
+
+func makeGvnValBox() gvnBox {
+ return gvnBox{v: 1}
+}
+
+func useGvnBox(_ gvnBox) {}
+
+func testDeferStructUnmutatedGvn() {
+ defer useGvnBox(makeGvnValBox())
+}
+
+func testDeferStructMutatedGvn(p *gvnBox) {
+ defer useGvnBox(makeGvnValBox())
+ p.v = 2
+}
+
+func testDeferBasicTypeAfterSideEffectGvn(p *gvnBox) int {
+ x := test()
+ defer fmt.Println(x)
+ p.v = 2
+ return x
+}
+
+func testUnnamedResultStructUnmutatedGvn() gvnBox {
+ defer noopGvnCleanup()
+ return makeGvnValBox()
+}
+
+func testUnnamedResultStructMutatedByDeferGvn(p *gvnBox) gvnBox {
+ defer func() {
+ p.v = 2
+ }()
+ return makeGvnValBox()
+}
+
+
+
From 6c85608b419f1ed663708639406b659a88456a4a Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Tue, 1 Dec 2026 20:55:27 +0000
Subject: [PATCH 05/17] Go: Adapt guards and return inference for defer
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>
---
go/ql/lib/semmle/go/controlflow/Guards.qll | 28 +++++--
.../go/dataflow/internal/DataFlowUtil.qll | 57 +++++++++++++-
.../dataflow/internal/TaintTrackingUtil.qll | 34 ++++++++-
.../go/controlflow/Guards/Guards.expected | 15 +++-
.../semmle/go/controlflow/Guards/guards.go | 26 +++++++
.../Defer/CONSISTENCY/CfgConsistency.expected | 38 ++++++----
.../Defer/CONSISTENCY/SsaConsistency.expected | 8 +-
.../UnexpectedFrontendErrors.expected | 6 +-
.../semmle/go/dataflow/Defer/main.go | 29 +++++++
.../go/dataflow/GuardingFunctions/test.go | 75 +++++++++++++++++++
.../ListOfConstantsSanitizerGuards/test.go | 56 ++++++++++++++
11 files changed, 338 insertions(+), 34 deletions(-)
diff --git a/go/ql/lib/semmle/go/controlflow/Guards.qll b/go/ql/lib/semmle/go/controlflow/Guards.qll
index c9cf0f9978bf..f24d6d420ce7 100644
--- a/go/ql/lib/semmle/go/controlflow/Guards.qll
+++ b/go/ql/lib/semmle/go/controlflow/Guards.qll
@@ -242,6 +242,14 @@ private module GuardsInput implements
private predicate hasOnlyPositionMappedReturns() {
forall(G::ReturnStmt ret | ret.getEnclosingFunction() = this.getFunction().getFuncDecl() |
ret.getNumExpr() = this.getFunction().getNumResult()
+ ) and
+ not exists(G::DeferStmt d |
+ d.getEnclosingFunction() = this.getFunction().getFuncDecl() and
+ CfgImpl::deferRecoversPanic(d)
+ ) and
+ not exists(G::ResultVariable rv | rv = this.getFunction().getResult(this.getResultIndex()) |
+ rv.(GoSsa::SsaSourceVariable).isCaptured() or
+ rv.(GoSsa::SsaSourceVariable).mayHaveIndirectReferences()
)
}
@@ -251,7 +259,7 @@ private module GuardsInput implements
this.getResultIndex() >= 0 and
this.hasOnlyPositionMappedReturns() and
ret.getEnclosingFunction() = this.getFunction().getFuncDecl() and
- result = ret.getExpr(this.getResultIndex())
+ result = ret.getExpr(this.getResultIndex()).stripParens()
)
}
}
@@ -267,6 +275,7 @@ private module GuardsInput implements
private predicate nonOverridableCall(
Expr resultExpr, G::CallExpr call, NonOverridableMethod method
) {
+ not exists(G::DeferStmt d | d.getCall() = call) and
call.getTarget() = method.getFunction() and
(
method.getResultIndex() = -1 and
@@ -284,7 +293,8 @@ private module GuardsInput implements
private predicate hasExplicitReceiverArgument(G::CallExpr call) {
call.getTarget() instanceof G::Method and
- call.getCalleeExpr().(G::SelectorExpr).getBase() instanceof G::TypeExpr
+ CfgImpl::unwrapCallee(call.getCalleeExpr()).(G::SelectorExpr).getBase().stripParens() instanceof
+ G::TypeExpr
}
/**
@@ -293,10 +303,10 @@ private module GuardsInput implements
*/
private Expr getDirectReceiverArgument(G::CallExpr call) {
exists(G::SelectorExpr sel, IR::MethodReadInstruction read |
- sel = call.getCalleeExpr() and
+ sel = CfgImpl::unwrapCallee(call.getCalleeExpr()) and
read.getExpr() = sel and
read.getReceiver() = IR::evalExprInstruction(result) and
- result = sel.getBase() and
+ result = sel.getBase().stripParens() and
result.getType() = call.getTarget().getParameter(-1).getType()
)
}
@@ -317,11 +327,11 @@ private module GuardsInput implements
result = getDirectReceiverArgument(call)
or
apos != -1 and
- result = call.getArgument(apos)
+ result = call.getArgument(apos).stripParens()
)
or
hasExplicitReceiverArgument(call) and
- result = call.getArgument(apos + 1)
+ result = call.getArgument(apos + 1).stripParens()
) and
not (
call.hasImplicitVarargs() and
@@ -338,9 +348,11 @@ private module LogicInput implements GuardsImpl::LogicInputSig {
import GoSsa::Ssa
predicate implicitReturnDefinition(GuardsInput::NonOverridableMethod method, SsaDefinition def) {
- exists(IR::ReadResultInstruction read, BasicBlock bb, int i |
+ exists(IR::ReadResultInstruction read, ResultVariable rv, BasicBlock bb, int i |
method.getResultIndex() >= 0 and
- read.reads(method.getFunction().getResult(method.getResultIndex())) and
+ rv = method.getFunction().getResult(method.getResultIndex()) and
+ not rv.(GoSsa::SsaSourceVariable).mayHaveIndirectReferences() and
+ read.reads(rv) and
read = bb.getNode(i) and
SsaImpl::ssaDefReachesRead(def.getSourceVariable(), def, bb, i)
)
diff --git a/go/ql/lib/semmle/go/dataflow/internal/DataFlowUtil.qll b/go/ql/lib/semmle/go/dataflow/internal/DataFlowUtil.qll
index cbe985f3bb61..27c061349aa1 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/DataFlowUtil.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/DataFlowUtil.qll
@@ -5,9 +5,11 @@ overlay[local?]
module;
private import go
+private import semmle.go.controlflow.ControlFlowGraphImpl
private import semmle.go.controlflow.Guards
private import semmle.go.dataflow.FunctionInputsAndOutputs
private import semmle.go.dataflow.ExternalFlow
+private import semmle.go.dataflow.SsaImpl as SsaImpl
private import DataFlowPrivate
private import FlowSummaryImpl as FlowSummaryImpl
private import codeql.util.Unit
@@ -400,7 +402,28 @@ module ParameterizedBarrierGuardValue<
Node getABarrierNodeForGuard(Node guardCheck, P param) {
exists(Guard guard, GuardValue value, SsaWithFields var |
guards(guardCheck, guard, value, _, var, param) and
- result = pragma[only_bind_out](var).getAUse() and
+ (
+ result = pragma[only_bind_out](var).getAUse()
+ or
+ exists(IR::DeferReadInstruction dr, DataFlow::Node savedNode |
+ result.asInstruction() = dr and
+ not dr.isSavedInLoop() and
+ savedNode = DataFlow::instructionNode(dr.getSavedInstruction()) and
+ savedNode = pragma[only_bind_out](var).getAUse() and
+ (
+ exists(SsaSourceVariable v |
+ v = var.getBaseDefinition().getSourceVariable() and
+ savedNode.asInstruction().reads(v) and
+ not v.mayHaveIndirectReferences()
+ )
+ or
+ exists(DataFlow::Node guardedNode |
+ guards(guardCheck, guard, value, guardedNode, var, param) and
+ globalValueNumber(savedNode) = globalValueNumber(guardedNode)
+ )
+ )
+ )
+ ) and
guardControlsBlock(guard, result.getBasicBlock(), value)
)
}
@@ -483,7 +506,37 @@ predicate certainlyReturnsNonNil(Function f, FunctionOutput output) {
f in [Builtin::new(), Builtin::make()]
or
exists(FuncDecl fd | fd = f.getFuncDecl() |
- forex(DataFlow::Node ret | ret = output.getEntryNode(fd) | isCertainlyNotNil(ret))
+ forex(DataFlow::Node ret | ret = output.getEntryNode(fd) | isCertainlyNotNil(ret)) and
+ not exists(int i | output.isResult(i) |
+ exists(IR::ReadUnnamedResultInstruction rr |
+ rr.getFunction() = fd and
+ rr.getIndex() = i and
+ SsaImpl::unnamedResultMayBeZeroedByRecover(rr)
+ )
+ or
+ exists(ResultVariable rv, DataFlow::ReadNode rrNode |
+ rv = fd.getResultVar(i) and
+ rrNode.asInstruction().(IR::ReadResultInstruction).reads(rv)
+ |
+ deferredPostUpdateFlowStepForDefer(_, _, rrNode)
+ or
+ rv.(SsaSourceVariable).mayHaveIndirectReferences()
+ or
+ exists(SsaDefinition def, SsaDefinition ult |
+ rrNode.readsSsaDefinition(def) and
+ ult = def.getAnUltimateDefinition()
+ |
+ ult instanceof SsaUncertainWrite
+ or
+ ult.(SsaExplicitWrite).getDefinition() instanceof IR::EvalImplicitInitInstruction and
+ (
+ exists(ReturnStmt r | r.getEnclosingFunction() = fd and not exists(r.getAnExpr()))
+ or
+ exists(DeferStmt d | d.getEnclosingFunction() = fd and CfgImpl::deferRecoversPanic(d))
+ )
+ )
+ )
+ )
)
)
}
diff --git a/go/ql/lib/semmle/go/dataflow/internal/TaintTrackingUtil.qll b/go/ql/lib/semmle/go/dataflow/internal/TaintTrackingUtil.qll
index e985383c8cf4..f33b45b14493 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/TaintTrackingUtil.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/TaintTrackingUtil.qll
@@ -5,9 +5,11 @@ overlay[local?]
module;
private import go
+private import semmle.go.controlflow.ControlFlowGraphImpl
private import FlowSummaryImpl as FlowSummaryImpl
private import codeql.util.Unit
private import DataFlowPrivate as DataFlowPrivate
+private import semmle.go.dataflow.SsaImpl as SsaImpl
/**
* Holds if taint can flow from `src` to `sink` in zero or more
@@ -411,7 +413,37 @@ private predicate mustPassConstantCaseTestToReach(
predicate functionEnsuresInputIsConstant(
Function f, FunctionInput inp, FunctionOutput outp, DataFlow::Property p
) {
- exists(FuncDecl fd | fd.getFunction() = f |
+ exists(FuncDecl fd |
+ fd.getFunction() = f and
+ not exists(int i | outp.isResult(i) |
+ (p.isBoolean(false) or p.isNil()) and
+ exists(IR::ReadUnnamedResultInstruction rr |
+ rr.getFunction() = fd and
+ rr.getIndex() = i and
+ SsaImpl::unnamedResultMayBeZeroedByRecover(rr)
+ )
+ or
+ exists(ResultVariable rv, DataFlow::ReadNode rrNode |
+ rv = fd.getResultVar(i) and
+ rrNode.asInstruction().(IR::ReadResultInstruction).reads(rv)
+ |
+ exists(IR::ReturnInstruction ri |
+ ri.getRoot() = fd and not exists(ri.getReturnStmt().getAnExpr())
+ )
+ or
+ exists(DeferStmt d | d.getEnclosingFunction() = fd and CfgImpl::deferRecoversPanic(d))
+ or
+ DataFlowPrivate::deferredPostUpdateFlowStepForDefer(_, _, rrNode)
+ or
+ rv.(SsaSourceVariable).mayHaveIndirectReferences()
+ or
+ exists(SsaDefinition def |
+ rrNode.readsSsaDefinition(def) and
+ def.getAnUltimateDefinition() instanceof SsaUncertainWrite
+ )
+ )
+ )
+ |
exists(boolean b |
p.isBoolean(b) and
forex(DataFlow::Node ret, IR::ReturnInstruction ri |
diff --git a/go/ql/test/library-tests/semmle/go/controlflow/Guards/Guards.expected b/go/ql/test/library-tests/semmle/go/controlflow/Guards/Guards.expected
index b67aa8ba4e44..11f01fdf4832 100644
--- a/go/ql/test/library-tests/semmle/go/controlflow/Guards/Guards.expected
+++ b/go/ql/test/library-tests/semmle/go/controlflow/Guards/Guards.expected
@@ -47,6 +47,9 @@ controlsResult
| guards.go:296:5:296:18 | call to check | indirect wrapper | true |
| guards.go:306:5:306:20 | call to hasArgs | implicit variadic wrapper | true |
| guards.go:309:5:309:24 | call to hasArgs | explicit variadic wrapper | true |
+| guards.go:410:5:410:44 | !... | recover wrapper false branch | true |
+| guards.go:410:6:410:44 | call to isNotNilWithRecoverWrapper | recover wrapper false branch | false |
+| guards.go:413:5:413:52 | call to isNotNilWithSafeClosureDeferWrapper | safe closure defer wrapper | true |
valueControlsResult
| guards.go:12:7:12:11 | value | negative | Upper bound -1 |
| guards.go:12:7:12:11 | value | positive | Lower bound 0 |
@@ -187,6 +190,12 @@ valueControlsResult
| guards.go:333:25:333:31 | pointer | after single-result assertion | not null |
| guards.go:345:2:345:33 | call to ensureNotNilWithResults | after multi-result assertion | no exception |
| guards.go:345:26:345:32 | pointer | after multi-result assertion | not null |
+| guards.go:410:5:410:44 | !... | recover wrapper false branch | true |
+| guards.go:410:6:410:44 | call to isNotNilWithRecoverWrapper | recover wrapper false branch | false |
+| guards.go:410:6:410:44 | call to isNotNilWithRecoverWrapper | recover wrapper false branch | no exception |
+| guards.go:413:5:413:52 | call to isNotNilWithSafeClosureDeferWrapper | safe closure defer wrapper | no exception |
+| guards.go:413:5:413:52 | call to isNotNilWithSafeClosureDeferWrapper | safe closure defer wrapper | true |
+| guards.go:413:44:413:50 | pointer | safe closure defer wrapper | not null |
ensuresEqResult
| guards.go:14:7:14:16 | ...==... | 0 = value | true |
| guards.go:14:7:14:16 | ...==... | value = 0 | true |
@@ -260,6 +269,10 @@ ensuresEqResult
| guards.go:383:5:383:34 | ...==... | nil = call to modelNullGuard | true |
| guards.go:386:5:386:37 | ...!=... | call to modelNotNullGuard = nil | false |
| guards.go:386:5:386:37 | ...!=... | nil = call to modelNotNullGuard | false |
+| guards.go:401:9:401:22 | ...!=... | nil = pointer | false |
+| guards.go:401:9:401:22 | ...!=... | pointer = nil | false |
+| guards.go:406:10:406:23 | ...!=... | nil = pointer | false |
+| guards.go:406:10:406:23 | ...!=... | pointer = nil | false |
ensuresValueResult
| guards.go:23:7:23:7 | 0 | tagged one or two | 0 != value | no match |
| guards.go:23:7:23:7 | 0 | tagged one or two | value != 0 | no match |
@@ -282,4 +295,4 @@ modelBarrierResult
| guards.go:387:31:387:37 | pointer | model not null | model-not-null |
| guards.go:390:34:390:40 | pointer | model no exception | model-no-exception |
legacyConditionGuardCount
-| 92 |
+| 96 |
diff --git a/go/ql/test/library-tests/semmle/go/controlflow/Guards/guards.go b/go/ql/test/library-tests/semmle/go/controlflow/Guards/guards.go
index 147afd8dbe23..9f3fd96e3c4f 100644
--- a/go/ql/test/library-tests/semmle/go/controlflow/Guards/guards.go
+++ b/go/ql/test/library-tests/semmle/go/controlflow/Guards/guards.go
@@ -389,3 +389,29 @@ func modelGuards(pointer *int) {
modelExceptionGuard(pointer)
valueSink("model no exception", pointer) // model-no-exception barrier
}
+
+func deferredExceptionGuardDoesNotGuardBody(pointer *int) {
+ defer ensureNotNil(pointer)
+ sink("after deferred assertion") // No pointer fact: assertion runs at function exit.
+}
+
+func isNotNilWithRecoverWrapper(pointer *int, xs []int) bool {
+ defer func() { recover() }()
+ _ = xs[0]
+ return pointer != nil
+}
+
+func isNotNilWithSafeClosureDeferWrapper(pointer *int) bool {
+ defer func() {}()
+ return (pointer != nil)
+}
+
+func deferGuardWrappers(pointer *int, xs []int) {
+ if !isNotNilWithRecoverWrapper(pointer, xs) {
+ sink("recover wrapper false branch") // No pointer == nil fact: panic recovery may return false.
+ }
+ if (isNotNilWithSafeClosureDeferWrapper)((pointer)) {
+ sink("safe closure defer wrapper") // pointer is not null
+ }
+}
+
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected
index 234eea2269a2..64d4a1056a2e 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected
@@ -1,17 +1,25 @@
consistencyOverview
-| multipleSuccessors | 14 |
+| multipleSuccessors | 22 |
multipleSuccessors
-| main.go:179:2:179:6 | After ... = ... | successor | main.go:173:38:180:1 | After block statement |
-| main.go:179:2:179:6 | After ... = ... | successor | main.go:176:9:176:18 | defer-arg-read:0 call to sinkVal |
-| main.go:189:2:189:13 | catch-panic ... = ... | successor | main.go:182:1:191:1 | Exceptional Exit |
-| main.go:189:2:189:13 | catch-panic ... = ... | successor | main.go:185:9:187:6 | defer-callee-read function call |
-| main.go:190:2:190:6 | After ... = ... | successor | main.go:182:59:191:1 | After block statement |
-| main.go:190:2:190:6 | After ... = ... | successor | main.go:185:9:187:6 | defer-callee-read function call |
-| main.go:194:2:199:2 | After for statement | successor | main.go:193:27:200:1 | After block statement |
-| main.go:194:2:199:2 | After for statement | successor | main.go:196:9:198:6 | defer-callee-read function call |
-| main.go:195:3:195:15 | catch-panic ... := ... | successor | main.go:193:1:200:1 | Exceptional Exit |
-| main.go:195:3:195:15 | catch-panic ... := ... | successor | main.go:196:9:198:6 | defer-callee-read function call |
-| main.go:196:3:198:6 | catch-defer-panic defer statement | successor | main.go:193:1:200:1 | Exceptional Exit |
-| main.go:196:3:198:6 | catch-defer-panic defer statement | successor | main.go:196:9:198:6 | defer-callee-read function call |
-| main.go:196:9:198:6 | defer-invoke function call | successor | main.go:193:27:200:1 | After block statement |
-| main.go:196:9:198:6 | defer-invoke function call | successor | main.go:196:9:198:6 | defer-callee-read function call |
+| main.go:180:2:180:6 | After ... = ... | successor | main.go:174:38:181:1 | After block statement |
+| main.go:180:2:180:6 | After ... = ... | successor | main.go:177:9:177:18 | defer-arg-read:0 call to sinkVal |
+| main.go:190:2:190:13 | catch-panic ... = ... | successor | main.go:183:1:192:1 | Exceptional Exit |
+| main.go:190:2:190:13 | catch-panic ... = ... | successor | main.go:186:9:188:6 | defer-callee-read function call |
+| main.go:191:2:191:6 | After ... = ... | successor | main.go:183:59:192:1 | After block statement |
+| main.go:191:2:191:6 | After ... = ... | successor | main.go:186:9:188:6 | defer-callee-read function call |
+| main.go:195:2:200:2 | After for statement | successor | main.go:194:27:201:1 | After block statement |
+| main.go:195:2:200:2 | After for statement | successor | main.go:197:9:199:6 | defer-callee-read function call |
+| main.go:196:3:196:15 | catch-panic ... := ... | successor | main.go:194:1:201:1 | Exceptional Exit |
+| main.go:196:3:196:15 | catch-panic ... := ... | successor | main.go:197:9:199:6 | defer-callee-read function call |
+| main.go:197:3:199:6 | catch-defer-panic defer statement | successor | main.go:194:1:201:1 | Exceptional Exit |
+| main.go:197:3:199:6 | catch-defer-panic defer statement | successor | main.go:197:9:199:6 | defer-callee-read function call |
+| main.go:197:9:199:6 | defer-invoke function call | successor | main.go:194:27:201:1 | After block statement |
+| main.go:197:9:199:6 | defer-invoke function call | successor | main.go:197:9:199:6 | defer-callee-read function call |
+| main.go:780:2:788:2 | After for statement | successor | main.go:779:53:789:1 | After block statement |
+| main.go:780:2:788:2 | After for statement | successor | main.go:782:9:782:17 | defer-arg-read:0 call to sink |
+| main.go:781:3:781:22 | catch-panic ... := ... | successor | main.go:779:1:789:1 | Exceptional Exit |
+| main.go:781:3:781:22 | catch-panic ... := ... | successor | main.go:782:9:782:17 | defer-arg-read:0 call to sink |
+| main.go:782:3:782:17 | catch-defer-panic defer statement | successor | main.go:779:1:789:1 | Exceptional Exit |
+| main.go:782:3:782:17 | catch-defer-panic defer statement | successor | main.go:782:9:782:17 | defer-arg-read:0 call to sink |
+| main.go:782:9:782:17 | defer-invoke call to sink | successor | main.go:779:53:789:1 | After block statement |
+| main.go:782:9:782:17 | defer-invoke call to sink | successor | main.go:782:9:782:17 | defer-arg-read:0 call to sink |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
index fd9dc7ccee93..6d80bc2af4d8 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
@@ -1,6 +1,6 @@
uselessPhiNode
-| main.go:251:8:253:2 | SSA phi(res) | 1 |
-| main.go:798:2:800:2 | SSA phi(s2) | 1 |
+| main.go:252:8:254:2 | SSA phi(res) | 1 |
+| main.go:827:2:829:2 | SSA phi(s2) | 1 |
phiWithoutTwoPriorRefs
-| main.go:251:8:253:2 | SSA phi(res) | main.go:251:8:253:2 | Exit | main.go:250:33:250:35 | res | 1 |
-| main.go:798:2:800:2 | SSA phi(s2) | main.go:798:2:800:2 | Exit | main.go:795:2:795:3 | s2 | 1 |
+| main.go:252:8:254:2 | SSA phi(res) | main.go:252:8:254:2 | Exit | main.go:251:33:251:35 | res | 1 |
+| main.go:827:2:829:2 | SSA phi(s2) | main.go:827:2:829:2 | Exit | main.go:824:2:824:3 | s2 | 1 |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/UnexpectedFrontendErrors.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/UnexpectedFrontendErrors.expected
index 4663b0fc4909..d57c228cf00f 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/UnexpectedFrontendErrors.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/UnexpectedFrontendErrors.expected
@@ -1,3 +1,3 @@
-| main.go:344:8:344:8 | undefined: unresolvedCallee |
-| main.go:344:35:344:35 | undefined: unresolvedArg |
-| main.go:345:8:345:8 | undefined: missingPkg |
+| main.go:345:8:345:8 | undefined: unresolvedCallee |
+| main.go:345:35:345:35 | undefined: unresolvedArg |
+| main.go:346:8:346:8 | undefined: missingPkg |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go b/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go
index 72b9ec0b3b7f..9b1d723c7a98 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go
@@ -3,6 +3,7 @@ package main
import (
"bytes"
"encoding/json"
+ "os"
)
func source() string {
@@ -759,6 +760,34 @@ type byteSliceBox struct {
buf []byte
}
+func testDeferBarrierGuardAfterRegistration() {
+ cmd := source() + ""
+ defer sink(cmd)
+ if cmd != "safe1" {
+ os.Exit(1)
+ }
+}
+
+func testDeferBarrierGuardWithReturnNotSanitized() {
+ cmd := source() + ""
+ defer sink(cmd) // $ hasTaintFlow="cmd"
+ if cmd != "safe1" {
+ return
+ }
+}
+
+func testDeferBarrierGuardInLoopNotSanitized(n int) {
+ for i := 0; i < n; i++ {
+ cmd := source() + ""
+ defer sink(cmd) // $ hasTaintFlow="cmd"
+ if i == 1 {
+ if cmd != "safe1" {
+ os.Exit(1)
+ }
+ }
+ }
+}
+
func genericDeferSink[T any](v T) {
sink(v) // $ hasValueFlow="v"
}
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/GuardingFunctions/test.go b/go/ql/test/library-tests/semmle/go/dataflow/GuardingFunctions/test.go
index 55115d4ba737..c2e51ec4c3df 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/GuardingFunctions/test.go
+++ b/go/ql/test/library-tests/semmle/go/dataflow/GuardingFunctions/test.go
@@ -390,6 +390,62 @@ func (multiGuard) validate(p string) (string, error) {
return p, nil
}
+func clearRetStructPtr(r **retStruct) {
+ *r = nil
+}
+
+func makeRetStructWithDeferredNil() (r *retStruct) {
+ defer func() { r = nil }()
+ return &retStruct{"overwritten"}
+}
+
+func makeRetStructWithDeferredPtrClear() (r *retStruct) {
+ defer clearRetStructPtr(&r)
+ return &retStruct{"overwritten"}
+}
+
+func makeRetStructWithRecoverNil(xs []int) *retStruct {
+ defer func() { recover() }()
+ _ = xs[0]
+ return &retStruct{"panics before return"}
+}
+
+func noopDeferCleanup() {}
+
+func makeRetStructWithSafeDefer(xs []int) *retStruct {
+ defer noopDeferCleanup()
+ _ = xs[0]
+ return &retStruct{"safe"}
+}
+
+func fakeGuardViaDeferredNil(p string) *retStruct {
+ if isBad(p) {
+ return makeRetStructWithDeferredNil()
+ }
+ return nil
+}
+
+func fakeGuardViaDeferredPtrClear(p string) *retStruct {
+ if isBad(p) {
+ return makeRetStructWithDeferredPtrClear()
+ }
+ return nil
+}
+
+func fakeGuardViaRecoverNil(p string, xs []int) *retStruct {
+ if isBad(p) {
+ return makeRetStructWithRecoverNil(xs)
+ }
+ return nil
+}
+
+func realGuardViaSafeDefer(p string, xs []int) *retStruct {
+ if isBad(p) {
+ return makeRetStructWithSafeDefer(xs)
+ }
+ return nil
+}
+
// Finally, actually test the functions -- try sinking a tainted value in the is-true/false
// or is-nil/non-nil case for each candidate:
@@ -981,4 +1037,23 @@ func test() {
}
}
+ {
+ xs := []int{1}
+ s := source()
+ if fakeGuardViaDeferredNil(s) == nil {
+ sink(s) // $ hasValueFlow="s"
+ }
+ if fakeGuardViaDeferredPtrClear(s) == nil {
+ sink(s) // $ hasValueFlow="s"
+ }
+ if fakeGuardViaRecoverNil(s, xs) == nil {
+ sink(s) // $ hasValueFlow="s"
+ }
+ if realGuardViaSafeDefer(s, xs) == nil {
+ sink(s)
+ } else {
+ sink(s) // $ hasValueFlow="s"
+ }
+ }
+
}
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/ListOfConstantsSanitizerGuards/test.go b/go/ql/test/library-tests/semmle/go/dataflow/ListOfConstantsSanitizerGuards/test.go
index d0935eeccd88..b0dad34cf31e 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/ListOfConstantsSanitizerGuards/test.go
+++ b/go/ql/test/library-tests/semmle/go/dataflow/ListOfConstantsSanitizerGuards/test.go
@@ -127,6 +127,44 @@ func switchStatementOverRandomString(s string) bool {
}
}
+func setBoolPtr(p *bool, v bool) {
+ *p = v
+}
+
+func noopSwitchCleanup() {}
+
+func switchReturningFalseWithRecover(s string, xs []int) bool {
+ defer func() { recover() }()
+ _ = xs[0]
+ switch s {
+ case "string literal":
+ return false
+ default:
+ return true
+ }
+}
+
+func switchNamedReturningTrueWithDeferredMutation(s string) (ok bool) {
+ defer setBoolPtr(&ok, true)
+ switch s {
+ case "string literal":
+ return true
+ default:
+ return false
+ }
+}
+
+func switchReturningFalseWithSafeDefer(s string, xs []int) bool {
+ defer noopSwitchCleanup()
+ _ = xs[0]
+ switch s {
+ case "string literal":
+ return false
+ default:
+ return true
+ }
+}
+
// Tests
func main() {
@@ -197,4 +235,22 @@ func main() {
}
}
+ {
+ xs := []int{1}
+ s := source()
+ if switchReturningFalseWithRecover(s, xs) {
+ sink(s) // $ hasTaintFlow="s"
+ } else {
+ sink(s) // $ hasTaintFlow="s"
+ }
+ if switchNamedReturningTrueWithDeferredMutation(s) {
+ sink(s) // $ hasTaintFlow="s"
+ }
+ if switchReturningFalseWithSafeDefer(s, xs) {
+ sink(s) // $ hasTaintFlow="s"
+ } else {
+ sink(s)
+ }
+ }
+
}
From 6c8b09f65391c8d83e9b4b87bac12a08266613db Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Tue, 1 Dec 2026 20:56:37 +0000
Subject: [PATCH 06/17] Go: Model clear sanitization across deferred calls
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>
---
go/ql/lib/semmle/go/dataflow/SSA.qll | 6 +
go/ql/lib/semmle/go/dataflow/SsaImpl.qll | 79 +++++
.../dataflow/internal/TaintTrackingUtil.qll | 143 +++++++-
.../Defer/CONSISTENCY/CfgConsistency.expected | 38 ++-
.../Defer/CONSISTENCY/SsaConsistency.expected | 8 +-
.../semmle/go/dataflow/Defer/main.go | 320 ++++++++++++++++++
6 files changed, 580 insertions(+), 14 deletions(-)
diff --git a/go/ql/lib/semmle/go/dataflow/SSA.qll b/go/ql/lib/semmle/go/dataflow/SSA.qll
index f6212e72ba2b..c44084dc7ffb 100644
--- a/go/ql/lib/semmle/go/dataflow/SSA.qll
+++ b/go/ql/lib/semmle/go/dataflow/SSA.qll
@@ -234,6 +234,12 @@ class SsaWithFields extends TSsaWithFields {
/** Gets a use that refers to this SSA variable with fields. */
DataFlow::Node getAUse() { this = accessPath(result.asInstruction()) }
+ /** Gets the base SSA-with-fields variable if this represents a field step. */
+ SsaWithFields getQualifier() { this = TStep(result, _) }
+
+ /** Gets the field accessed by the final step of this SSA-with-fields variable, if any. */
+ Field getField() { this = TStep(_, result) }
+
/** Gets the type of this SSA variable with fields. */
Type getType() {
exists(SsaDefinition def | this = TRoot(def) | result = def.getSourceVariable().getType())
diff --git a/go/ql/lib/semmle/go/dataflow/SsaImpl.qll b/go/ql/lib/semmle/go/dataflow/SsaImpl.qll
index 0bb58d379dbb..08824c12e8d4 100644
--- a/go/ql/lib/semmle/go/dataflow/SsaImpl.qll
+++ b/go/ql/lib/semmle/go/dataflow/SsaImpl.qll
@@ -416,3 +416,82 @@ predicate unnamedResultMayBeZeroedByRecover(IR::ReadUnnamedResultInstruction rr)
not tempDefAt(bbDef, iDef, v, _)
)
}
+
+private predicate isClearInstruction(IR::Instruction clearInstr) {
+ exists(CallExpr ce |
+ ce.getTarget() = Builtin::clear() and
+ clearInstr = IR::evalExprInstruction(ce)
+ )
+}
+
+private predicate tempWriteReachesDefWithoutClear(
+ TempImpl::Definition def, IR::Instruction rhs, IR::Instruction clearInstr
+) {
+ isClearInstruction(clearInstr) and
+ def.getBasicBlock().getScope() = clearInstr.getRoot() and
+ (
+ exists(IR::TempVariable v, BasicBlock bbDef, int iDef |
+ def.(TempImpl::WriteDefinition).definesAt(v, bbDef, iDef) and
+ tempDefAt(bbDef, iDef, v, rhs) and
+ not clearInstr.dominatesNode(bbDef.getNode(iDef))
+ )
+ or
+ exists(TempImpl::Definition inp, BasicBlock predBb |
+ TempImpl::phiHasInputFromBlock(def, inp, predBb) and
+ tempWriteReachesDefWithoutClear(inp, rhs, clearInstr) and
+ not clearInstr.getBasicBlock().dominates(predBb)
+ )
+ )
+}
+
+/**
+ * Holds if `rhs` is saved into an unnamed result temporary and can reach `rr`
+ * along a control-flow path that does not execute `clearInstr`.
+ */
+predicate tempWriteReachesReadWithoutClear(
+ IR::Instruction rhs, IR::ReadUnnamedResultInstruction rr, IR::Instruction clearInstr
+) {
+ exists(IR::TempVariable v, TempImpl::Definition def, BasicBlock bbRead, int iRead |
+ TempImpl::ssaDefReachesRead(v, def, bbRead, iRead) and
+ rr = bbRead.getNode(iRead) and
+ rr.readsTemp(v) and
+ tempWriteReachesDefWithoutClear(def, rhs, clearInstr) and
+ not clearInstr.dominatesNode(rr)
+ )
+}
+
+private predicate ssaWriteReachesDefWithoutClear(
+ Impl::Definition def, Impl::Definition writeDef, IR::Instruction clearInstr
+) {
+ isClearInstruction(clearInstr) and
+ def.getBasicBlock().getScope() = clearInstr.getRoot() and
+ (
+ exists(BasicBlock bbDef, int iDef |
+ def = writeDef and
+ writeDef.(Impl::WriteDefinition).definesAt(_, bbDef, iDef) and
+ not clearInstr.dominatesNode(bbDef.getNode(iDef))
+ )
+ or
+ exists(Impl::Definition inp, BasicBlock predBb |
+ Impl::phiHasInputFromBlock(def, inp, predBb) and
+ ssaWriteReachesDefWithoutClear(inp, writeDef, clearInstr) and
+ not clearInstr.getBasicBlock().dominates(predBb)
+ )
+ )
+}
+
+/**
+ * Holds if `writeDef` can reach result read `rr` along a control-flow path that
+ * does not execute `clearInstr`.
+ */
+predicate ssaWriteReachesReadWithoutClear(
+ Ssa::SsaDefinition writeDef, IR::ReadResultInstruction rr, IR::Instruction clearInstr
+) {
+ exists(SsaSourceVariable v, Impl::Definition def, BasicBlock bbRead, int iRead |
+ Impl::ssaDefReachesRead(v, def, bbRead, iRead) and
+ rr = bbRead.getNode(iRead) and
+ rr.reads(v) and
+ ssaWriteReachesDefWithoutClear(def, writeDef, clearInstr) and
+ not clearInstr.dominatesNode(rr)
+ )
+}
diff --git a/go/ql/lib/semmle/go/dataflow/internal/TaintTrackingUtil.qll b/go/ql/lib/semmle/go/dataflow/internal/TaintTrackingUtil.qll
index f33b45b14493..fcecc001845c 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/TaintTrackingUtil.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/TaintTrackingUtil.qll
@@ -516,18 +516,155 @@ class ListOfConstantsComparisonSanitizerGuard extends TaintTracking::DefaultTain
}
}
+private predicate isNilSliceOrMapNode(DataFlow::Node n) {
+ exprRefersToNil(n.asExpr())
+ or
+ exists(ConversionExpr ce |
+ ce = n.asExpr() and
+ exprRefersToNil(ce.getOperand().stripParens())
+ )
+}
+
+/**
+ * Holds if `use` is guaranteed to refer to the same slice or map header that
+ * `clearUse` evaluated for `var` (where `isDeferredClear` indicates whether
+ * `clearUse` was evaluated earlier at `defer clear(...)` registration time).
+ */
+private predicate sameClearedValue(
+ SsaWithFields var, DataFlow::Node clearUse, boolean isDeferredClear, DataFlow::Node use
+) {
+ clearUse = var.getAUse() and
+ use = var.getAUse() and
+ (
+ isDeferredClear = false
+ or
+ isDeferredClear = true and
+ (
+ exists(SsaSourceVariable v |
+ v = var.getBaseDefinition().getSourceVariable() and
+ clearUse.asInstruction().reads(v) and
+ not v.mayHaveIndirectReferences()
+ )
+ or
+ exists(SsaSourceVariable v |
+ exists(var.getField()) and
+ v = var.getBaseDefinition().getSourceVariable() and
+ not v.mayHaveIndirectReferences() and
+ not v.isCaptured() and
+ forall(SsaWithFields q | q = var.getQualifier+() |
+ not q.getType().getUnderlyingType() instanceof PointerType
+ ) and
+ forall(SsaWithFields step, DataFlow::Write w |
+ step = var.getQualifier*() and
+ w.getRoot() = clearUse.getRoot() and
+ w.writesFieldPreUpdate(_, step.getField(), _)
+ |
+ w.dominatesNode(clearUse.asInstruction()) and
+ w != clearUse.asInstruction()
+ )
+ )
+ or
+ globalValueNumber(clearUse) = globalValueNumber(use)
+ )
+ )
+}
+
+/**
+ * Holds if ultimate definition `ult` of a named result read `rr` is cleared by
+ * `call` (evaluating `clearUse` for `var`) along every path to `rr`.
+ */
+bindingset[var, clearUse, isDeferredClear, arg, call, rr, ult]
+pragma[inline]
+private predicate namedResultUltCleared(
+ SsaWithFields var, DataFlow::Node clearUse, boolean isDeferredClear, DataFlow::Node arg,
+ DataFlow::CallNode call, IR::ReadResultInstruction rr, SsaDefinition ult
+) {
+ not SsaImpl::ssaWriteReachesReadWithoutClear(ult, rr, call.asInstruction()) and
+ not arg.asInstruction().(IR::DeferReadArgInstruction).isSavedInLoop() and
+ (
+ ult = var.getBaseDefinition().getAnUltimateDefinition() and
+ not exists(var.getField()) and
+ sameClearedValue(var, clearUse, isDeferredClear, clearUse)
+ or
+ exists(DataFlow::Node rhsNode |
+ rhsNode.asInstruction() = ult.(SsaExplicitWrite).getDefinition().getRhs() and
+ sameClearedValue(var, clearUse, isDeferredClear, rhsNode)
+ )
+ )
+}
+
/**
* The `clear` built-in function deletes or zeroes out all elements of a map or slice
* and therefore acts as a general sanitizer for taint flow to any uses dominated by it.
*/
private class ClearSanitizer extends DefaultTaintSanitizer {
ClearSanitizer() {
- exists(SsaWithFields var, DataFlow::CallNode call, DataFlow::Node arg | this = var.getAUse() |
+ exists(
+ SsaWithFields var, DataFlow::CallNode call, DataFlow::Node arg, DataFlow::Node clearUse,
+ boolean isDeferredClear
+ |
call = Builtin::clear().getACall() and
arg = call.getAnArgument() and
- arg = var.getAUse() and
+ (
+ not arg.asInstruction() instanceof IR::DeferReadArgInstruction and
+ clearUse = arg and
+ isDeferredClear = false
+ or
+ clearUse.asInstruction() =
+ arg.asInstruction().(IR::DeferReadArgInstruction).getSavedInstruction() and
+ isDeferredClear = true
+ ) and
+ clearUse = var.getAUse() and
arg != this and
- arg.getBasicBlock().(ReachableBasicBlock).dominates(this.getBasicBlock())
+ call.getBasicBlock() instanceof ReachableBasicBlock and
+ call.getEnclosingCallable() = this.getEnclosingCallable()
+ |
+ not this.asInstruction() instanceof IR::ReadResultInstruction and
+ call.asInstruction().dominatesNode(this.asInstruction()) and
+ call.asInstruction() != this.asInstruction() and
+ sameClearedValue(var, clearUse, isDeferredClear, this)
+ or
+ exists(IR::DeferReadInstruction dr |
+ this.asInstruction() = dr and
+ call.asInstruction().dominatesNode(dr) and
+ call.asInstruction() != dr and
+ not dr.isSavedInLoop() and
+ sameClearedValue(var, clearUse, isDeferredClear,
+ DataFlow::instructionNode(dr.getSavedInstruction()))
+ )
+ or
+ exists(IR::ReadUnnamedResultInstruction rr |
+ this.asInstruction() = rr and
+ exists(IR::Instruction retRhs | SsaImpl::tempDefUseStep(retRhs, rr) |
+ sameClearedValue(var, clearUse, isDeferredClear, DataFlow::instructionNode(retRhs)) and
+ not SsaImpl::tempWriteReachesReadWithoutClear(retRhs, rr, call.asInstruction())
+ ) and
+ forex(IR::Instruction retRhs | SsaImpl::tempDefUseStep(retRhs, rr) |
+ sameClearedValue(var, clearUse, isDeferredClear, DataFlow::instructionNode(retRhs)) and
+ not SsaImpl::tempWriteReachesReadWithoutClear(retRhs, rr, call.asInstruction())
+ or
+ isNilSliceOrMapNode(DataFlow::instructionNode(retRhs))
+ )
+ )
+ or
+ exists(IR::ReadResultInstruction rr, SsaDefinition def |
+ this.asInstruction() = rr and
+ not rr instanceof IR::ReadUnnamedResultInstruction and
+ this.(DataFlow::ReadNode).readsSsaDefinition(def) and
+ exists(SsaDefinition ult | ult = def.getAnUltimateDefinition() |
+ namedResultUltCleared(var, clearUse, isDeferredClear, arg, call, rr, ult)
+ ) and
+ forall(SsaDefinition ult | ult = def.getAnUltimateDefinition() |
+ ult.(SsaExplicitWrite).getDefinition() instanceof IR::EvalImplicitInitInstruction
+ or
+ exists(DataFlow::Node rhsNode |
+ rhsNode.asInstruction() = ult.(SsaExplicitWrite).getDefinition().getRhs() and
+ isNilSliceOrMapNode(rhsNode)
+ )
+ or
+ namedResultUltCleared(var, clearUse, isDeferredClear, arg, call, rr, ult)
+ )
+ )
)
}
}
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected
index 64d4a1056a2e..e647075a272e 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/CfgConsistency.expected
@@ -1,5 +1,5 @@
consistencyOverview
-| multipleSuccessors | 22 |
+| multipleSuccessors | 42 |
multipleSuccessors
| main.go:180:2:180:6 | After ... = ... | successor | main.go:174:38:181:1 | After block statement |
| main.go:180:2:180:6 | After ... = ... | successor | main.go:177:9:177:18 | defer-arg-read:0 call to sinkVal |
@@ -15,11 +15,31 @@ multipleSuccessors
| main.go:197:3:199:6 | catch-defer-panic defer statement | successor | main.go:197:9:199:6 | defer-callee-read function call |
| main.go:197:9:199:6 | defer-invoke function call | successor | main.go:194:27:201:1 | After block statement |
| main.go:197:9:199:6 | defer-invoke function call | successor | main.go:197:9:199:6 | defer-callee-read function call |
-| main.go:780:2:788:2 | After for statement | successor | main.go:779:53:789:1 | After block statement |
-| main.go:780:2:788:2 | After for statement | successor | main.go:782:9:782:17 | defer-arg-read:0 call to sink |
-| main.go:781:3:781:22 | catch-panic ... := ... | successor | main.go:779:1:789:1 | Exceptional Exit |
-| main.go:781:3:781:22 | catch-panic ... := ... | successor | main.go:782:9:782:17 | defer-arg-read:0 call to sink |
-| main.go:782:3:782:17 | catch-defer-panic defer statement | successor | main.go:779:1:789:1 | Exceptional Exit |
-| main.go:782:3:782:17 | catch-defer-panic defer statement | successor | main.go:782:9:782:17 | defer-arg-read:0 call to sink |
-| main.go:782:9:782:17 | defer-invoke call to sink | successor | main.go:779:53:789:1 | After block statement |
-| main.go:782:9:782:17 | defer-invoke call to sink | successor | main.go:782:9:782:17 | defer-arg-read:0 call to sink |
+| main.go:555:2:555:9 | catch-return return statement | successor | main.go:550:46:556:1 | result-read:0 block statement |
+| main.go:555:2:555:9 | catch-return return statement | successor | main.go:553:9:553:16 | defer-arg-read:0 call to clear |
+| main.go:920:3:920:22 | catch-panic ... := ... | successor | main.go:913:1:933:1 | Exceptional Exit |
+| main.go:920:3:920:22 | catch-panic ... := ... | successor | main.go:922:9:922:28 | defer-arg-read:0 call to sinkBytesAsString |
+| main.go:921:3:921:27 | catch-panic expression statement | successor | main.go:913:1:933:1 | Exceptional Exit |
+| main.go:921:3:921:27 | catch-panic expression statement | successor | main.go:922:9:922:28 | defer-arg-read:0 call to sinkBytesAsString |
+| main.go:922:3:922:28 | catch-defer-panic defer statement | successor | main.go:913:1:933:1 | Exceptional Exit |
+| main.go:922:3:922:28 | catch-defer-panic defer statement | successor | main.go:922:9:922:28 | defer-arg-read:0 call to sinkBytesAsString |
+| main.go:922:9:922:28 | defer-invoke call to sinkBytesAsString | successor | main.go:913:48:933:1 | After block statement |
+| main.go:922:9:922:28 | defer-invoke call to sinkBytesAsString | successor | main.go:922:9:922:28 | defer-arg-read:0 call to sinkBytesAsString |
+| main.go:929:2:929:42 | catch-panic expression statement | successor | main.go:913:1:933:1 | Exceptional Exit |
+| main.go:929:2:929:42 | catch-panic expression statement | successor | main.go:922:9:922:28 | defer-arg-read:0 call to sinkBytesAsString |
+| main.go:930:2:930:45 | catch-panic expression statement | successor | main.go:913:1:933:1 | Exceptional Exit |
+| main.go:930:2:930:45 | catch-panic expression statement | successor | main.go:922:9:922:28 | defer-arg-read:0 call to sinkBytesAsString |
+| main.go:931:2:931:52 | catch-panic expression statement | successor | main.go:913:1:933:1 | Exceptional Exit |
+| main.go:931:2:931:52 | catch-panic expression statement | successor | main.go:922:9:922:28 | defer-arg-read:0 call to sinkBytesAsString |
+| main.go:932:2:932:44 | After expression statement | successor | main.go:913:48:933:1 | After block statement |
+| main.go:932:2:932:44 | After expression statement | successor | main.go:922:9:922:28 | defer-arg-read:0 call to sinkBytesAsString |
+| main.go:932:2:932:44 | catch-panic expression statement | successor | main.go:913:1:933:1 | Exceptional Exit |
+| main.go:932:2:932:44 | catch-panic expression statement | successor | main.go:922:9:922:28 | defer-arg-read:0 call to sinkBytesAsString |
+| main.go:952:2:960:2 | After for statement | successor | main.go:951:53:961:1 | After block statement |
+| main.go:952:2:960:2 | After for statement | successor | main.go:954:9:954:17 | defer-arg-read:0 call to sink |
+| main.go:953:3:953:22 | catch-panic ... := ... | successor | main.go:951:1:961:1 | Exceptional Exit |
+| main.go:953:3:953:22 | catch-panic ... := ... | successor | main.go:954:9:954:17 | defer-arg-read:0 call to sink |
+| main.go:954:3:954:17 | catch-defer-panic defer statement | successor | main.go:951:1:961:1 | Exceptional Exit |
+| main.go:954:3:954:17 | catch-defer-panic defer statement | successor | main.go:954:9:954:17 | defer-arg-read:0 call to sink |
+| main.go:954:9:954:17 | defer-invoke call to sink | successor | main.go:951:53:961:1 | After block statement |
+| main.go:954:9:954:17 | defer-invoke call to sink | successor | main.go:954:9:954:17 | defer-arg-read:0 call to sink |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
index 6d80bc2af4d8..ef57e8491657 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
@@ -1,6 +1,10 @@
uselessPhiNode
| main.go:252:8:254:2 | SSA phi(res) | 1 |
-| main.go:827:2:829:2 | SSA phi(s2) | 1 |
+| main.go:999:2:1001:2 | SSA phi(s2) | 1 |
+| main.go:1131:1:1138:1 | SSA phi(b) | 1 |
+| main.go:1140:1:1147:1 | SSA phi(b) | 1 |
phiWithoutTwoPriorRefs
| main.go:252:8:254:2 | SSA phi(res) | main.go:252:8:254:2 | Exit | main.go:251:33:251:35 | res | 1 |
-| main.go:827:2:829:2 | SSA phi(s2) | main.go:827:2:829:2 | Exit | main.go:824:2:824:3 | s2 | 1 |
+| main.go:999:2:1001:2 | SSA phi(s2) | main.go:999:2:1001:2 | Exit | main.go:996:2:996:3 | s2 | 1 |
+| main.go:1131:1:1138:1 | SSA phi(b) | main.go:1131:1:1138:1 | Exceptional Exit | main.go:1132:2:1132:2 | b | 1 |
+| main.go:1140:1:1147:1 | SSA phi(b) | main.go:1140:1:1147:1 | Exceptional Exit | main.go:1141:2:1141:2 | b | 1 |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go b/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go
index 9b1d723c7a98..50da09e5e03c 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go
+++ b/go/ql/test/library-tests/semmle/go/dataflow/Defer/main.go
@@ -527,6 +527,81 @@ func testDeferredImplicitAddrReceiver() {
sink(b2.String())
}
+// 18. Built-in clear() in defer statements.
+func taintedBytes() []byte {
+ b := make([]byte, 8)
+ _, _ = bytes.NewBufferString(source()).Read(b)
+ return b
+}
+
+func deferClearUnnamed() []byte {
+ b := taintedBytes()
+ defer clear(b)
+ sink(string(b)) // $ hasTaintFlow="type conversion"
+ return b
+}
+
+func deferClearNamed() (b []byte) {
+ b = taintedBytes()
+ defer clear(b)
+ return
+}
+
+func deferClearConditional(cond bool) []byte {
+ b := taintedBytes()
+ if cond {
+ defer clear(b)
+ }
+ return b
+}
+
+func deferClearAfterEarlyReturn(cond bool) []byte {
+ b := taintedBytes()
+ if cond {
+ return b
+ }
+ defer clear(b)
+ return b
+}
+
+func deferClearReturnStringBeforeClear() string {
+ b := taintedBytes()
+ defer clear(b)
+ return string(b) // evaluated before defer clear(b) runs: still tainted
+}
+
+func deferClearReassignedNamed() (b []byte) {
+ b = taintedBytes()
+ defer clear(b)
+ b = taintedBytes() // new slice assigned after defer registration: not cleared
+ return
+}
+
+func sinkBytesCleared(b []byte) {
+ sink(string(b))
+}
+
+func sinkBytesNotCleared(b []byte) {
+ sink(string(b)) // $ hasTaintFlow="type conversion"
+}
+
+func testDeferClear() {
+ sink(string(deferClearUnnamed()))
+ sink(string(deferClearNamed()))
+ sink(string(deferClearConditional(false))) // $ hasTaintFlow="type conversion"
+ sink(string(deferClearAfterEarlyReturn(false))) // $ hasTaintFlow="type conversion"
+ sink(deferClearReturnStringBeforeClear()) // $ hasTaintFlow="call to deferClearReturnStringBeforeClear"
+ sink(string(deferClearReassignedNamed())) // $ hasTaintFlow="type conversion"
+
+ b1 := taintedBytes()
+ defer sinkBytesCleared(b1) // runs after clear(b1): sanitized
+ defer clear(b1)
+
+ b2 := taintedBytes()
+ defer clear(b2)
+ defer sinkBytesNotCleared(b2) // runs before clear(b2): not sanitized
+}
+
// 19. Constant boolean argument branch pruning on deferred calls.
func deferBoolFalseHelper(doSink bool, v string) {
if doSink {
@@ -756,10 +831,107 @@ func testDeferPanicWithPanickingArg(xs []int) {
x = source()
}
+func deferClearNamedExplicit() (b []byte) {
+ b = make([]byte, 8)
+ copy(b, []byte(source()))
+ defer clear(b)
+ return b
+}
+
+func deferClearMultiBranchNil(cond bool) []byte {
+ if cond {
+ return nil
+ }
+ b := make([]byte, 8)
+ copy(b, []byte(source()))
+ defer clear(b)
+ return b
+}
+
+func deferClearNamedMultiBranchNil(cond bool) (b []byte) {
+ if cond {
+ return nil
+ }
+ b = make([]byte, 8)
+ copy(b, []byte(source()))
+ defer clear(b)
+ return b
+}
+
+func deferClearEarlyReturnNotSanitized(cond bool) []byte {
+ b := make([]byte, 8)
+ copy(b, []byte(source()))
+ if cond {
+ return b
+ }
+ defer clear(b)
+ return b
+}
+
+func sinkBytesAsString(b []byte) {
+ sink(string(b)) // $ hasTaintFlow="type conversion"
+}
+
type byteSliceBox struct {
buf []byte
}
+func copyFromString(dst []byte, s string) {
+ copy(dst, []byte(s))
+}
+
+func deferClearFieldReassigned() []byte {
+ var box byteSliceBox
+ box.buf = make([]byte, 8)
+ defer clear(box.buf)
+ box.buf = make([]byte, 8)
+ copy(box.buf, []byte(source()))
+ return box.buf
+}
+
+func deferClearIndirectReassigned() []byte {
+ bInd := make([]byte, 8)
+ defer clear(bInd)
+ json.Unmarshal([]byte(source()), &bInd)
+ return bInd
+}
+
+func deferClearOverwrittenByEarlierDefer() []byte {
+ b := make([]byte, 8)
+ defer copyFromString(b, source())
+ defer clear(b)
+ return b
+}
+
+func syncClearOverwrittenByDefer() []byte {
+ b := make([]byte, 8)
+ defer copyFromString(b, source())
+ clear(b)
+ return b
+}
+
+func testDeferClearEdgeCases(cond bool, n int) {
+ sink(string(deferClearNamedExplicit()))
+ sink(string(deferClearMultiBranchNil(cond)))
+ sink(string(deferClearNamedMultiBranchNil(cond)))
+ sink(string(deferClearEarlyReturnNotSanitized(cond))) // $ hasTaintFlow="type conversion"
+
+ for i := 0; i < n; i++ {
+ b := make([]byte, 8)
+ copy(b, []byte(source()))
+ defer sinkBytesAsString(b)
+ if i == 1 {
+ clear(b)
+ return
+ }
+ }
+
+ sink(string(deferClearFieldReassigned())) // $ hasTaintFlow="type conversion"
+ sink(string(deferClearIndirectReassigned())) // $ hasTaintFlow="type conversion"
+ sink(string(deferClearOverwrittenByEarlierDefer())) // $ MISSING: hasTaintFlow="type conversion"
+ sink(string(syncClearOverwrittenByDefer())) // $ MISSING: hasTaintFlow="type conversion"
+}
+
func testDeferBarrierGuardAfterRegistration() {
cmd := source() + ""
defer sink(cmd)
@@ -889,4 +1061,152 @@ func testDeferSavedByValuePostRegMutations() {
copy(box.buf, []byte(source()))
}
+func inspectBytesReadOnly(b []byte) int {
+ return len(b)
+}
+
+func deferClearStructFieldSameHeader() []byte {
+ box := byteSliceBox{buf: make([]byte, 8)}
+ defer clear(box.buf)
+ copy(box.buf, []byte(source()))
+ return box.buf
+}
+
+func syncClearMutatedAfterward() []byte {
+ b := make([]byte, 8)
+ copy(b, []byte(source()))
+ clear(b)
+ copy(b, []byte(source()))
+ return b
+}
+
+func syncClearReadOnlyCallAfterward() []byte {
+ b := make([]byte, 8)
+ copy(b, []byte(source()))
+ clear(b)
+ _ = inspectBytesReadOnly(b)
+ return b
+}
+
+func syncClearLoopReTainted(n int) {
+ b := make([]byte, 8)
+ for i := 0; i < n; i++ {
+ clear(b)
+ copy(b, []byte(source()))
+ if i == 1 {
+ sink(string(b)) // $ MISSING: hasTaintFlow="type conversion"
+ }
+ }
+}
+
+func inspectByteBoxPtrReadOnly(p *byteSliceBox) int {
+ return len(p.buf)
+}
+
+func mutateBytesDedicatedDefer(b []byte) {
+ copy(b, []byte(source()))
+}
+
+func deferClearWithReadOnlyLaterDefer() []byte {
+ b := taintedBytes()
+ defer inspectBytesReadOnly(b)
+ defer clear(b)
+ return b
+}
+
+func deferClearStructWithReadOnlyPtrLaterDefer() []byte {
+ box := byteSliceBox{buf: taintedBytes()}
+ defer inspectByteBoxPtrReadOnly(&box)
+ defer clear(box.buf)
+ return box.buf
+}
+
+func deferClearOverwrittenByDedicatedHelper() []byte {
+ b := make([]byte, 8)
+ defer mutateBytesDedicatedDefer(b)
+ defer clear(b)
+ return b
+}
+
+func deferClearWithReadOnlyClosureLaterDefer() []byte {
+ b := taintedBytes()
+ defer func() {
+ _ = len(b)
+ }()
+ defer clear(b)
+ return b
+}
+
+func deferClearWithMutatingClosureLaterDefer() []byte {
+ b := taintedBytes()
+ defer func() {
+ copy(b, []byte(source()))
+ }()
+ defer clear(b)
+ return b
+}
+
+func syncClearMutatedViaStructPtr() []byte {
+ box := byteSliceBox{buf: taintedBytes()}
+ clear(box.buf)
+ p := &box
+ copy(p.buf, []byte(source()))
+ return box.buf
+}
+
+func syncClearNamedPhi(cond bool) (b []byte) {
+ if cond {
+ b = taintedBytes()
+ } else {
+ b = taintedBytes()
+ }
+ clear(b)
+ return
+}
+
+func deferClearNamedPhi(cond bool) (b []byte) {
+ if cond {
+ b = taintedBytes()
+ } else {
+ b = taintedBytes()
+ }
+ defer clear(b)
+ return
+}
+
+func deferClearNamedMultiBranchNilNaked(cond bool) (b []byte) {
+ if cond {
+ return nil
+ }
+ b = taintedBytes()
+ defer clear(b)
+ return
+}
+
+func deferClearNamedCondReassign(cond bool) (b []byte) {
+ b = taintedBytes()
+ defer clear(b)
+ if cond {
+ b = taintedBytes()
+ }
+ return
+}
+
+func testAdditionalClearSanitizerCases(cond bool, n int) {
+ sink(string(deferClearStructFieldSameHeader()))
+ sink(string(syncClearMutatedAfterward())) // $ MISSING: hasTaintFlow="type conversion"
+ sink(string(syncClearReadOnlyCallAfterward()))
+ syncClearLoopReTainted(n)
+ sink(string(deferClearWithReadOnlyLaterDefer()))
+ sink(string(deferClearStructWithReadOnlyPtrLaterDefer()))
+ sink(string(deferClearOverwrittenByDedicatedHelper())) // $ MISSING: hasTaintFlow="type conversion"
+ sink(string(deferClearWithReadOnlyClosureLaterDefer()))
+ sink(string(deferClearWithMutatingClosureLaterDefer())) // $ MISSING: hasTaintFlow="type conversion"
+ sink(string(syncClearMutatedViaStructPtr())) // $ MISSING: hasTaintFlow="type conversion"
+ sink(string(syncClearNamedPhi(cond)))
+ sink(string(deferClearNamedPhi(cond)))
+ sink(string(deferClearNamedMultiBranchNilNaked(cond)))
+ sink(string(deferClearNamedCondReassign(cond))) // $ hasTaintFlow="type conversion"
+}
+
func main() {}
From e98f194d3ce71abf3d16b2abbc2a0d77896914a6 Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Tue, 1 Dec 2026 20:57:59 +0000
Subject: [PATCH 07/17] Go: Model deferred scanner output sources
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>
---
go/ql/lib/semmle/go/frameworks/Bun.qll | 4 ++--
go/ql/lib/semmle/go/frameworks/stdlib/Fmt.qll | 3 ++-
.../local/database/test_uptrace_bun.go | 9 +++++++++
.../dataflow/flowsources/local/stdin/test.go | 16 ++++++++++++++++
.../CWE-352/ConstantOauth2State.expected | 14 ++++++++------
.../Security/CWE-352/ConstantOauth2State.go | 18 ++++++++++++++++++
6 files changed, 55 insertions(+), 9 deletions(-)
diff --git a/go/ql/lib/semmle/go/frameworks/Bun.qll b/go/ql/lib/semmle/go/frameworks/Bun.qll
index 8637c8f5704f..2a5ba2963c6b 100644
--- a/go/ql/lib/semmle/go/frameworks/Bun.qll
+++ b/go/ql/lib/semmle/go/frameworks/Bun.qll
@@ -20,7 +20,7 @@ private module Bun {
cn.getTarget().(Method).hasQualifiedName(packagePath(), "RawQuery", ["Exec", "Scan"]) and
i >= 1
|
- this = cn.getSyntacticArgument(i)
+ this.(DataFlow::PostUpdateNode).getPreUpdateNode() = cn.getSyntacticArgument(i)
)
}
@@ -38,7 +38,7 @@ private module Bun {
.hasQualifiedName(packagePath(), "SelectQuery", ["Exec", "Scan", "ScanAndCount"]) and
i >= 1
|
- this = cn.getSyntacticArgument(i)
+ this.(DataFlow::PostUpdateNode).getPreUpdateNode() = cn.getSyntacticArgument(i)
)
}
diff --git a/go/ql/lib/semmle/go/frameworks/stdlib/Fmt.qll b/go/ql/lib/semmle/go/frameworks/stdlib/Fmt.qll
index 3a596bd9e770..46ae8495e473 100644
--- a/go/ql/lib/semmle/go/frameworks/stdlib/Fmt.qll
+++ b/go/ql/lib/semmle/go/frameworks/stdlib/Fmt.qll
@@ -94,7 +94,8 @@ module Fmt {
private class ScannerSource extends SourceNode {
ScannerSource() {
// All of the arguments which are sources are varargs.
- this.asExpr() = any(Scanner s).getACall().getAnImplicitVarargsArgument().asExpr()
+ this.(DataFlow::PostUpdateNode).getPreUpdateNode() =
+ any(Scanner s).getACall().getAnImplicitVarargsArgument()
}
override string getThreatModel() { result = "stdin" }
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/flowsources/local/database/test_uptrace_bun.go b/go/ql/test/library-tests/semmle/go/dataflow/flowsources/local/database/test_uptrace_bun.go
index dc8b5c7e3662..a0290a3abb1c 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/flowsources/local/database/test_uptrace_bun.go
+++ b/go/ql/test/library-tests/semmle/go/dataflow/flowsources/local/database/test_uptrace_bun.go
@@ -38,6 +38,11 @@ func Test_bun_db(db bun.DB) {
db.QueryRowContext(ctx, "SELECT * FROM users") // $ source
}
+func bunDeferredRawQueryScan(ctx context.Context, q bun.RawQuery) (res []User) {
+ defer q.Scan(ctx, &res) // $ source
+ return nil
+}
+
func Test_bun_rawquery(q bun.RawQuery) {
ctx := context.Background()
@@ -45,6 +50,8 @@ func Test_bun_rawquery(q bun.RawQuery) {
q.Exec(ctx, &u1) // $ source
var u2 []User
q.Scan(ctx, &u2) // $ source
+ sink(u2) // $ hasTaintFlow="u2"
+ sink(bunDeferredRawQueryScan(ctx, q)) // $ hasTaintFlow="call to bunDeferredRawQueryScan"
}
func Test_bun_selectquery(q bun.SelectQuery) {
@@ -57,10 +64,12 @@ func Test_bun_selectquery(q bun.SelectQuery) {
q.Model(&u2).Scan(ctx) // $ source
var u3 map[string]interface{}
q.Scan(ctx, &u3) // $ source
+ sink(u3) // $ hasTaintFlow="u3"
var u4 []User
q.Model(&u4).ScanAndCount(ctx) // $ source
var u5 map[string]interface{}
q.ScanAndCount(ctx, &u5) // $ source
+ sink(u5) // $ hasTaintFlow="u5"
ignore(rows)
}
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/flowsources/local/stdin/test.go b/go/ql/test/library-tests/semmle/go/dataflow/flowsources/local/stdin/test.go
index 8a2830b73e3c..0b6afc0464ca 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/flowsources/local/stdin/test.go
+++ b/go/ql/test/library-tests/semmle/go/dataflow/flowsources/local/stdin/test.go
@@ -46,3 +46,19 @@ func scanl() {
fmt.Scanln(&s) // $ source
sink(s) // $ hasTaintFlow="s"
}
+
+func scanPtr() {
+ p := new(string)
+ fmt.Scan(p) // $ source
+ sink(*p) // $ hasTaintFlow="star expression"
+}
+
+func deferScanNamed() (res string) {
+ defer fmt.Scan(&res) // $ source
+ sink(res) // body runs before defer: no flow
+ return
+}
+
+func useDeferScanNamed() {
+ sink(deferScanNamed()) // $ hasTaintFlow="call to deferScanNamed"
+}
diff --git a/go/ql/test/query-tests/Security/CWE-352/ConstantOauth2State.expected b/go/ql/test/query-tests/Security/CWE-352/ConstantOauth2State.expected
index d1c82f01713f..4c7fc6b4acd2 100644
--- a/go/ql/test/query-tests/Security/CWE-352/ConstantOauth2State.expected
+++ b/go/ql/test/query-tests/Security/CWE-352/ConstantOauth2State.expected
@@ -1,3 +1,9 @@
+#select
+| ConstantOauth2State.go:35:26:35:32 | "state" | ConstantOauth2State.go:35:26:35:32 | "state" | ConstantOauth2State.go:35:26:35:32 | "state" | Using a constant $@ to create oauth2 URLs. | ConstantOauth2State.go:35:26:35:32 | "state" | state string |
+| ConstantOauth2State.go:50:26:50:41 | stateStringConst | ConstantOauth2State.go:20:26:20:32 | "state" | ConstantOauth2State.go:50:26:50:41 | stateStringConst | Using a constant $@ to create oauth2 URLs. | ConstantOauth2State.go:20:26:20:32 | "state" | state string |
+| ConstantOauth2State.go:65:26:65:39 | stateStringVar | ConstantOauth2State.go:22:22:22:28 | "state" | ConstantOauth2State.go:65:26:65:39 | stateStringVar | Using a constant $@ to create oauth2 URLs. | ConstantOauth2State.go:22:22:22:28 | "state" | state string |
+| ConstantOauth2State.go:81:26:81:30 | state | ConstantOauth2State.go:86:9:86:15 | "state" | ConstantOauth2State.go:81:26:81:30 | state | Using a constant $@ to create oauth2 URLs. | ConstantOauth2State.go:86:9:86:15 | "state" | state string |
+| ConstantOauth2State.go:232:26:232:41 | stateStringConst | ConstantOauth2State.go:20:26:20:32 | "state" | ConstantOauth2State.go:232:26:232:41 | stateStringConst | Using a constant $@ to create oauth2 URLs. | ConstantOauth2State.go:20:26:20:32 | "state" | state string |
edges
| ConstantOauth2State.go:20:26:20:32 | "state" | ConstantOauth2State.go:50:26:50:41 | stateStringConst | provenance | |
| ConstantOauth2State.go:20:26:20:32 | "state" | ConstantOauth2State.go:147:26:147:41 | stateStringConst | provenance | |
@@ -8,6 +14,7 @@ edges
| ConstantOauth2State.go:20:26:20:32 | "state" | ConstantOauth2State.go:249:26:249:41 | stateStringConst | provenance | |
| ConstantOauth2State.go:20:26:20:32 | "state" | ConstantOauth2State.go:266:26:266:41 | stateStringConst | provenance | |
| ConstantOauth2State.go:20:26:20:32 | "state" | ConstantOauth2State.go:282:26:282:41 | stateStringConst | provenance | |
+| ConstantOauth2State.go:20:26:20:32 | "state" | ConstantOauth2State.go:323:26:323:41 | stateStringConst | provenance | |
| ConstantOauth2State.go:22:22:22:28 | "state" | ConstantOauth2State.go:65:26:65:39 | stateStringVar | provenance | |
| ConstantOauth2State.go:80:11:80:25 | call to newFixedState | ConstantOauth2State.go:81:26:81:30 | state | provenance | |
| ConstantOauth2State.go:86:9:86:15 | "state" | ConstantOauth2State.go:80:11:80:25 | call to newFixedState | provenance | |
@@ -28,10 +35,5 @@ nodes
| ConstantOauth2State.go:249:26:249:41 | stateStringConst | semmle.label | stateStringConst |
| ConstantOauth2State.go:266:26:266:41 | stateStringConst | semmle.label | stateStringConst |
| ConstantOauth2State.go:282:26:282:41 | stateStringConst | semmle.label | stateStringConst |
+| ConstantOauth2State.go:323:26:323:41 | stateStringConst | semmle.label | stateStringConst |
subpaths
-#select
-| ConstantOauth2State.go:35:26:35:32 | "state" | ConstantOauth2State.go:35:26:35:32 | "state" | ConstantOauth2State.go:35:26:35:32 | "state" | Using a constant $@ to create oauth2 URLs. | ConstantOauth2State.go:35:26:35:32 | "state" | state string |
-| ConstantOauth2State.go:50:26:50:41 | stateStringConst | ConstantOauth2State.go:20:26:20:32 | "state" | ConstantOauth2State.go:50:26:50:41 | stateStringConst | Using a constant $@ to create oauth2 URLs. | ConstantOauth2State.go:20:26:20:32 | "state" | state string |
-| ConstantOauth2State.go:65:26:65:39 | stateStringVar | ConstantOauth2State.go:22:22:22:28 | "state" | ConstantOauth2State.go:65:26:65:39 | stateStringVar | Using a constant $@ to create oauth2 URLs. | ConstantOauth2State.go:22:22:22:28 | "state" | state string |
-| ConstantOauth2State.go:81:26:81:30 | state | ConstantOauth2State.go:86:9:86:15 | "state" | ConstantOauth2State.go:81:26:81:30 | state | Using a constant $@ to create oauth2 URLs. | ConstantOauth2State.go:86:9:86:15 | "state" | state string |
-| ConstantOauth2State.go:232:26:232:41 | stateStringConst | ConstantOauth2State.go:20:26:20:32 | "state" | ConstantOauth2State.go:232:26:232:41 | stateStringConst | Using a constant $@ to create oauth2 URLs. | ConstantOauth2State.go:20:26:20:32 | "state" | state string |
diff --git a/go/ql/test/query-tests/Security/CWE-352/ConstantOauth2State.go b/go/ql/test/query-tests/Security/CWE-352/ConstantOauth2State.go
index 817c76c8bfa9..4360da9e6389 100644
--- a/go/ql/test/query-tests/Security/CWE-352/ConstantOauth2State.go
+++ b/go/ql/test/query-tests/Security/CWE-352/ConstantOauth2State.go
@@ -308,3 +308,21 @@ func okConstantOnlySuppliedAlongsideError(w http.ResponseWriter) {
_ = url
}
}
+
+func okWithDeferredFscanStdin(w http.ResponseWriter) {
+ conf := &oauth2.Config{
+ ClientID: "YOUR_CLIENT_ID",
+ ClientSecret: "YOUR_CLIENT_SECRET",
+ Scopes: []string{"SCOPE1", "SCOPE2"},
+ Endpoint: oauth2.Endpoint{
+ AuthURL: "https://provider.com/o/oauth2/auth",
+ TokenURL: "https://provider.com/o/oauth2/token",
+ },
+ }
+
+ url := conf.AuthCodeURL(stateStringConst) // OK because interactive terminal reads from os.Stdin
+ fmt.Printf("Visit the URL for the auth dialog: %v", url)
+
+ var code string
+ defer fmt.Fscan(os.Stdin, &code)
+}
From d20cbd46ad02a18253eb66eafe9be28e30ca9573 Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Tue, 1 Dec 2026 20:58:41 +0000
Subject: [PATCH 08/17] Go: Adapt regexp and allocation models for saved inputs
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>
---
.../semmle/go/frameworks/stdlib/Regexp.qll | 2 +-
.../AllocationSizeOverflowCustomizations.qll | 19 ++++++++++++++-
.../go/concepts/Regexp/RegexpPattern.expected | 1 +
.../semmle/go/concepts/Regexp/stdlib.go | 2 ++
.../CWE-190/AllocationSizeOverflow.expected | 23 ++++++++++++++-----
.../CWE-190/AllocationSizeOverflow.go | 20 +++++++++++++++-
6 files changed, 58 insertions(+), 9 deletions(-)
diff --git a/go/ql/lib/semmle/go/frameworks/stdlib/Regexp.qll b/go/ql/lib/semmle/go/frameworks/stdlib/Regexp.qll
index f13f35810e54..1668f007dc8a 100644
--- a/go/ql/lib/semmle/go/frameworks/stdlib/Regexp.qll
+++ b/go/ql/lib/semmle/go/frameworks/stdlib/Regexp.qll
@@ -53,7 +53,7 @@ module Regexp {
override DataFlow::Node getAParse() { result = this.getCall() }
- override string getPattern() { result = this.asExpr().getStringValue() }
+ override string getPattern() { result = this.getStringValue() }
override DataFlow::Node getAUse() {
strArg = -2 and
diff --git a/go/ql/lib/semmle/go/security/AllocationSizeOverflowCustomizations.qll b/go/ql/lib/semmle/go/security/AllocationSizeOverflowCustomizations.qll
index 789aaec04a16..d0ae1f959fb0 100644
--- a/go/ql/lib/semmle/go/security/AllocationSizeOverflowCustomizations.qll
+++ b/go/ql/lib/semmle/go/security/AllocationSizeOverflowCustomizations.qll
@@ -50,7 +50,7 @@ module AllocationSizeOverflow {
// Binding order tweak: start with marshalling function calls then work outwards:
pragma[only_bind_into](call) = marshal.getACall() and
// rule out cases where we can tell that the result will always be small
- exists(FunctionInput inp | inp = marshal.getAnInput() | isBig(inp.getNode(call).asExpr())) and
+ exists(FunctionInput inp | inp = marshal.getAnInput() | isBigNode(inp.getNode(call))) and
this = marshal.getOutput().getNode(call)
)
}
@@ -85,6 +85,10 @@ module AllocationSizeOverflow {
class AllocationSizeCheckBarrier extends DataFlow::Node {
AllocationSizeCheckBarrier() {
this = DataFlow::BarrierGuard::getABarrierNode()
+ or
+ DataFlow::instructionNode(this.asInstruction()
+ .(IR::DeferReadInstruction)
+ .getSavedInstruction()) instanceof AllocationSizeCheckBarrier
}
}
@@ -186,6 +190,19 @@ module AllocationSizeOverflow {
isBig(e.(CompositeLit).getAnElement())
}
+ /** Holds if `n` is a data-flow node whose values might marshal to relatively large blobs. */
+ private predicate isBigNode(DataFlow::Node n) {
+ isBig(n.asExpr())
+ or
+ exists(IR::DeferReadInstruction dr | dr = n.asInstruction() |
+ isBig(dr.getSavedInstruction().(IR::EvalInstruction).getExpr())
+ or
+ not dr.getSavedInstruction() instanceof IR::EvalInstruction and
+ not isSmallType(dr.getResultType()) and
+ not dr.isConst()
+ )
+ }
+
/**
* Holds if the value of `pred` can flow into `succ` in one step, either through a call to `len`
* or through an arithmetic operation (other than remainder).
diff --git a/go/ql/test/library-tests/semmle/go/concepts/Regexp/RegexpPattern.expected b/go/ql/test/library-tests/semmle/go/concepts/Regexp/RegexpPattern.expected
index 7019de4934ed..3e1425ed7fdd 100644
--- a/go/ql/test/library-tests/semmle/go/concepts/Regexp/RegexpPattern.expected
+++ b/go/ql/test/library-tests/semmle/go/concepts/Regexp/RegexpPattern.expected
@@ -20,3 +20,4 @@
| stdlib.go:18:21:18:22 | "" | | stdlib.go:18:21:18:22 | "" |
| stdlib.go:19:26:19:36 | "mustPosix" | mustPosix | stdlib.go:19:2:19:37 | call to MustCompilePOSIX |
| stdlib.go:19:26:19:36 | "mustPosix" | mustPosix | stdlib.go:19:26:19:36 | "mustPosix" |
+| stdlib.go:33:27:33:39 | "deferredPat" | deferredPat | stdlib.go:33:27:33:39 | "deferredPat" |
diff --git a/go/ql/test/library-tests/semmle/go/concepts/Regexp/stdlib.go b/go/ql/test/library-tests/semmle/go/concepts/Regexp/stdlib.go
index beb0c0c452e7..f2804087c64c 100644
--- a/go/ql/test/library-tests/semmle/go/concepts/Regexp/stdlib.go
+++ b/go/ql/test/library-tests/semmle/go/concepts/Regexp/stdlib.go
@@ -29,4 +29,6 @@ func main() {
re.MatchReader(bufio.NewReader(file))
re.String()
+
+ defer regexp.MatchString("deferredPat", "baaa")
}
diff --git a/go/ql/test/query-tests/Security/CWE-190/AllocationSizeOverflow.expected b/go/ql/test/query-tests/Security/CWE-190/AllocationSizeOverflow.expected
index f21d5dd184b8..ba234f9c5161 100644
--- a/go/ql/test/query-tests/Security/CWE-190/AllocationSizeOverflow.expected
+++ b/go/ql/test/query-tests/Security/CWE-190/AllocationSizeOverflow.expected
@@ -1,5 +1,6 @@
#select
-| AllocationSizeOverflow.go:10:10:10:22 | call to len | AllocationSizeOverflow.go:6:2:6:33 | extract:0 ... := ... | AllocationSizeOverflow.go:10:10:10:22 | call to len | This operation, which is used in an $@, involves a $@ and might overflow. | AllocationSizeOverflow.go:11:25:11:28 | size | allocation | AllocationSizeOverflow.go:6:2:6:33 | extract:0 ... := ... | potentially large value |
+| AllocationSizeOverflow.go:14:10:14:22 | call to len | AllocationSizeOverflow.go:10:2:10:33 | extract:0 ... := ... | AllocationSizeOverflow.go:14:10:14:22 | call to len | This operation, which is used in an $@, involves a $@ and might overflow. | AllocationSizeOverflow.go:15:25:15:28 | size | allocation | AllocationSizeOverflow.go:10:2:10:33 | extract:0 ... := ... | potentially large value |
+| AllocationSizeOverflow.go:28:10:28:21 | call to len | AllocationSizeOverflow.go:22:19:22:21 | buf [postupdate] | AllocationSizeOverflow.go:28:10:28:21 | call to len | This operation, which is used in an $@, involves a $@ and might overflow. | AllocationSizeOverflow.go:29:25:29:28 | size | allocation | AllocationSizeOverflow.go:22:19:22:21 | buf [postupdate] | potentially large value |
| tst2.go:10:22:10:30 | call to len | tst2.go:9:2:9:37 | extract:0 ... := ... | tst2.go:10:22:10:30 | call to len | This operation, which is used in an $@, involves a $@ and might overflow. | tst2.go:10:22:10:32 | ...+... | allocation | tst2.go:9:2:9:37 | extract:0 ... := ... | potentially large value |
| tst2.go:15:22:15:30 | call to len | tst2.go:14:2:14:29 | extract:0 ... := ... | tst2.go:15:22:15:30 | call to len | This operation, which is used in an $@, involves a $@ and might overflow. | tst2.go:15:22:15:32 | ...+... | allocation | tst2.go:14:2:14:29 | extract:0 ... := ... | potentially large value |
| tst3.go:7:22:7:34 | call to len | tst3.go:6:2:6:31 | extract:0 ... := ... | tst3.go:7:22:7:34 | call to len | This operation, which is used in an $@, involves a $@ and might overflow. | tst3.go:7:22:7:36 | ...+... | allocation | tst3.go:6:2:6:31 | extract:0 ... := ... | potentially large value |
@@ -10,8 +11,12 @@
| tst.go:27:26:27:38 | call to len | tst.go:26:2:26:31 | extract:0 ... = ... | tst.go:27:26:27:38 | call to len | This operation, which is used in an $@, involves a $@ and might overflow. | tst.go:27:26:27:40 | ...+... | allocation | tst.go:26:2:26:31 | extract:0 ... = ... | potentially large value |
| tst.go:35:22:35:34 | call to len | tst.go:34:2:34:30 | extract:0 ... = ... | tst.go:35:22:35:34 | call to len | This operation, which is used in an $@, involves a $@ and might overflow. | tst.go:35:22:35:36 | ...+... | allocation | tst.go:34:2:34:30 | extract:0 ... = ... | potentially large value |
edges
-| AllocationSizeOverflow.go:6:2:6:33 | extract:0 ... := ... | AllocationSizeOverflow.go:10:14:10:21 | jsonData | provenance | |
-| AllocationSizeOverflow.go:10:14:10:21 | jsonData | AllocationSizeOverflow.go:10:10:10:22 | call to len | provenance | Config |
+| AllocationSizeOverflow.go:10:2:10:33 | extract:0 ... := ... | AllocationSizeOverflow.go:14:14:14:21 | jsonData | provenance | |
+| AllocationSizeOverflow.go:14:14:14:21 | jsonData | AllocationSizeOverflow.go:14:10:14:22 | call to len | provenance | Config |
+| AllocationSizeOverflow.go:22:19:22:21 | buf [postupdate] | AllocationSizeOverflow.go:27:13:27:32 | call to encodePemDeferred | provenance | |
+| AllocationSizeOverflow.go:27:13:27:32 | call to encodePemDeferred | AllocationSizeOverflow.go:27:13:27:40 | call to Bytes | provenance | MaD:2 |
+| AllocationSizeOverflow.go:27:13:27:40 | call to Bytes | AllocationSizeOverflow.go:28:14:28:20 | pemData | provenance | |
+| AllocationSizeOverflow.go:28:14:28:20 | pemData | AllocationSizeOverflow.go:28:10:28:21 | call to len | provenance | Config |
| tst2.go:9:2:9:37 | extract:0 ... := ... | tst2.go:10:26:10:29 | data | provenance | Src:MaD:1 |
| tst2.go:10:26:10:29 | data | tst2.go:10:22:10:30 | call to len | provenance | Config |
| tst2.go:14:2:14:29 | extract:0 ... := ... | tst2.go:15:26:15:29 | data | provenance | |
@@ -35,10 +40,16 @@ edges
| tst.go:35:26:35:33 | jsonData | tst.go:35:22:35:34 | call to len | provenance | Config |
models
| 1 | Source: io/ioutil; ; false; ReadFile; ; ; ReturnValue[0]; file; manual |
+| 2 | Summary: bytes; Buffer; true; Bytes; ; ; Argument[receiver]; ReturnValue; taint; manual |
nodes
-| AllocationSizeOverflow.go:6:2:6:33 | extract:0 ... := ... | semmle.label | extract:0 ... := ... |
-| AllocationSizeOverflow.go:10:10:10:22 | call to len | semmle.label | call to len |
-| AllocationSizeOverflow.go:10:14:10:21 | jsonData | semmle.label | jsonData |
+| AllocationSizeOverflow.go:10:2:10:33 | extract:0 ... := ... | semmle.label | extract:0 ... := ... |
+| AllocationSizeOverflow.go:14:10:14:22 | call to len | semmle.label | call to len |
+| AllocationSizeOverflow.go:14:14:14:21 | jsonData | semmle.label | jsonData |
+| AllocationSizeOverflow.go:22:19:22:21 | buf [postupdate] | semmle.label | buf [postupdate] |
+| AllocationSizeOverflow.go:27:13:27:32 | call to encodePemDeferred | semmle.label | call to encodePemDeferred |
+| AllocationSizeOverflow.go:27:13:27:40 | call to Bytes | semmle.label | call to Bytes |
+| AllocationSizeOverflow.go:28:10:28:21 | call to len | semmle.label | call to len |
+| AllocationSizeOverflow.go:28:14:28:20 | pemData | semmle.label | pemData |
| tst2.go:9:2:9:37 | extract:0 ... := ... | semmle.label | extract:0 ... := ... |
| tst2.go:10:22:10:30 | call to len | semmle.label | call to len |
| tst2.go:10:26:10:29 | data | semmle.label | data |
diff --git a/go/ql/test/query-tests/Security/CWE-190/AllocationSizeOverflow.go b/go/ql/test/query-tests/Security/CWE-190/AllocationSizeOverflow.go
index c717cf6fd710..240cd0fb9b5e 100644
--- a/go/ql/test/query-tests/Security/CWE-190/AllocationSizeOverflow.go
+++ b/go/ql/test/query-tests/Security/CWE-190/AllocationSizeOverflow.go
@@ -1,6 +1,10 @@
package main
-import "encoding/json"
+import (
+ "bytes"
+ "encoding/json"
+ "encoding/pem"
+)
func encryptValue(v interface{}) ([]byte, error) {
jsonData, err := json.Marshal(v) // $ Source
@@ -12,3 +16,17 @@ func encryptValue(v interface{}) ([]byte, error) {
copy(buffer, jsonData)
return encryptBuffer(buffer)
}
+
+func encodePemDeferred(b *pem.Block) *bytes.Buffer {
+ buf := &bytes.Buffer{}
+ defer pem.Encode(buf, b) // $ Source
+ return buf
+}
+
+func encryptDeferredPem(b *pem.Block) ([]byte, error) {
+ pemData := encodePemDeferred(b).Bytes()
+ size := len(pemData) + (len(pemData) % 16) // $ Alert
+ buffer := make([]byte, size)
+ copy(buffer, pemData)
+ return encryptBuffer(buffer)
+}
From c58c5f11d6cba79f5f536b7cd575d1a6ca07ca30 Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Tue, 1 Dec 2026 20:59:38 +0000
Subject: [PATCH 09/17] Go: Avoid duplicate alerts on synthetic defer values
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>
---
go/ql/lib/semmle/go/frameworks/CryptoLibraries.qll | 5 +++++
go/ql/src/Security/CWE-326/InsufficientKeySize.ql | 5 ++++-
go/ql/src/Security/CWE-327/InsecureTLS.ql | 3 ++-
go/ql/src/Security/CWE-798/HardcodedCredentials.ql | 2 ++
.../Security/CWE-326/InsufficientKeySize.expected | 7 +++++++
.../Security/CWE-326/InsufficientKeySize.go | 5 +++++
.../Security/CWE-327/BrokenCryptoAlgorithm.expected | 8 ++++++++
.../CWE-327/WeakSensitiveDataHashing.expected | 8 ++++++++
.../test/query-tests/Security/CWE-327/encryption.go | 12 ++++++++++++
go/ql/test/query-tests/Security/CWE-327/hashing.go | 6 ++++++
.../Security/CWE-798/HardcodedCredentials.expected | 1 +
go/ql/test/query-tests/Security/CWE-798/main.go | 1 +
12 files changed, 61 insertions(+), 2 deletions(-)
diff --git a/go/ql/lib/semmle/go/frameworks/CryptoLibraries.qll b/go/ql/lib/semmle/go/frameworks/CryptoLibraries.qll
index f8714e8602ad..7a2652c16e2c 100644
--- a/go/ql/lib/semmle/go/frameworks/CryptoLibraries.qll
+++ b/go/ql/lib/semmle/go/frameworks/CryptoLibraries.qll
@@ -385,6 +385,8 @@ private module Crypto {
DataFlow::Node inputNode;
StreamReader() {
+ not this.asInstruction() instanceof IR::DeferReadInstruction and
+ not this.asInstruction() instanceof IR::ReadUnnamedResultInstruction and
lookThroughPointerType(this.getType()).hasQualifiedName("crypto/cipher", "StreamReader") and
exists(DataFlow::Write wS, DataFlow::Node baseS, Field fS |
fS.hasQualifiedName("crypto/cipher", "StreamReader", "S") and
@@ -412,6 +414,8 @@ private module Crypto {
DataFlow::Node encryptionFlowTarget;
StreamWriter() {
+ not this.(DataFlow::PostUpdateNode).getPreUpdateNode().asInstruction() instanceof
+ IR::DeferReadInstruction and
lookThroughPointerType(this.getType()).hasQualifiedName("crypto/cipher", "StreamWriter") and
exists(DataFlow::Write w, DataFlow::Node base, Field f |
w.writesField(base, f, encryptionFlowTarget) and
@@ -459,6 +463,7 @@ private class FlowToIoWriter extends HashOperation instanceof DataFlow::Node {
DataFlow::Node input;
FlowToIoWriter() {
+ not this.asInstruction() instanceof IR::DeferReadInstruction and
this.getType().implements("io", "Writer") and
HashFlow::flow(init, this) and
// If we have `h.Write(taint)` or `io.WriteString(h, taint)` then it's
diff --git a/go/ql/src/Security/CWE-326/InsufficientKeySize.ql b/go/ql/src/Security/CWE-326/InsufficientKeySize.ql
index 6fa421baaeb3..ccd5d5675bd1 100644
--- a/go/ql/src/Security/CWE-326/InsufficientKeySize.ql
+++ b/go/ql/src/Security/CWE-326/InsufficientKeySize.ql
@@ -13,7 +13,10 @@
import go
module Config implements DataFlow::ConfigSig {
- predicate isSource(DataFlow::Node source) { source.getIntValue() < 2048 }
+ predicate isSource(DataFlow::Node source) {
+ source.getIntValue() < 2048 and
+ not source.asInstruction() instanceof IR::DeferReadInstruction
+ }
predicate isSink(DataFlow::Node sink) {
exists(DataFlow::CallNode c |
diff --git a/go/ql/src/Security/CWE-327/InsecureTLS.ql b/go/ql/src/Security/CWE-327/InsecureTLS.ql
index 764ec6d093a8..c4a5fff6e75b 100644
--- a/go/ql/src/Security/CWE-327/InsecureTLS.ql
+++ b/go/ql/src/Security/CWE-327/InsecureTLS.ql
@@ -51,7 +51,8 @@ module TlsVersionFlowConfig implements DataFlow::ConfigSig {
additional predicate intIsSource(DataFlow::Node source, int val) {
val = source.getIntValue() and
val = getATlsVersion() and
- not DataFlow::isReturnedWithError(source)
+ not DataFlow::isReturnedWithError(source) and
+ not source.asInstruction() instanceof IR::DeferReadInstruction
}
/**
diff --git a/go/ql/src/Security/CWE-798/HardcodedCredentials.ql b/go/ql/src/Security/CWE-798/HardcodedCredentials.ql
index d14f24966bef..147fb24969d4 100644
--- a/go/ql/src/Security/CWE-798/HardcodedCredentials.ql
+++ b/go/ql/src/Security/CWE-798/HardcodedCredentials.ql
@@ -36,6 +36,7 @@ predicate sensitiveAssignment(
DataFlow::Node source, DataFlow::Node sink, SensitiveExpr::Classification type
) {
exists(string val | val = source.getStringValue() and val != "" |
+ not source.asInstruction() instanceof IR::DeferReadInstruction and
DataFlow::localFlow(source, sink) and
isSensitive(sink, type) and
// allow obvious dummy/test values
@@ -45,6 +46,7 @@ predicate sensitiveAssignment(
}
predicate hardcodedPrivateKey(DataFlow::Node node, SensitiveExpr::Classification type) {
+ not node.asInstruction() instanceof IR::DeferReadInstruction and
node.getStringValue()
.regexpMatch("(?s)-+BEGIN\\b.*\\bPRIVATE KEY-+.+-+END\\b.*\\bPRIVATE KEY-+\n?") and
type = SensitiveExpr::certificate()
diff --git a/go/ql/test/query-tests/Security/CWE-326/InsufficientKeySize.expected b/go/ql/test/query-tests/Security/CWE-326/InsufficientKeySize.expected
index 6ab8df627811..0b0236d98092 100644
--- a/go/ql/test/query-tests/Security/CWE-326/InsufficientKeySize.expected
+++ b/go/ql/test/query-tests/Security/CWE-326/InsufficientKeySize.expected
@@ -2,9 +2,11 @@
| InsufficientKeySize.go:9:31:9:34 | 1024 | InsufficientKeySize.go:9:31:9:34 | 1024 | InsufficientKeySize.go:9:31:9:34 | 1024 | The size of this RSA key should be at least 2048 bits. |
| InsufficientKeySize.go:14:31:14:34 | size | InsufficientKeySize.go:13:10:13:13 | 1024 | InsufficientKeySize.go:14:31:14:34 | size | The size of this RSA key should be at least 2048 bits. |
| InsufficientKeySize.go:26:31:26:34 | size | InsufficientKeySize.go:18:7:18:10 | 1024 | InsufficientKeySize.go:26:31:26:34 | size | The size of this RSA key should be at least 2048 bits. |
+| InsufficientKeySize.go:26:31:26:34 | size | InsufficientKeySize.go:85:13:85:16 | 1024 | InsufficientKeySize.go:26:31:26:34 | size | The size of this RSA key should be at least 2048 bits. |
| InsufficientKeySize.go:32:32:32:38 | keyBits | InsufficientKeySize.go:30:13:30:16 | 1024 | InsufficientKeySize.go:32:32:32:38 | keyBits | The size of this RSA key should be at least 2048 bits. |
| InsufficientKeySize.go:47:32:47:38 | keyBits | InsufficientKeySize.go:44:13:44:16 | 1024 | InsufficientKeySize.go:47:32:47:38 | keyBits | The size of this RSA key should be at least 2048 bits. |
| InsufficientKeySize.go:67:31:67:37 | keyBits | InsufficientKeySize.go:61:21:61:24 | 1024 | InsufficientKeySize.go:67:31:67:37 | keyBits | The size of this RSA key should be at least 2048 bits. |
+| InsufficientKeySize.go:84:37:84:40 | 1024 | InsufficientKeySize.go:84:37:84:40 | 1024 | InsufficientKeySize.go:84:37:84:40 | 1024 | The size of this RSA key should be at least 2048 bits. |
edges
| InsufficientKeySize.go:13:10:13:13 | 1024 | InsufficientKeySize.go:14:31:14:34 | size | provenance | |
| InsufficientKeySize.go:18:7:18:10 | 1024 | InsufficientKeySize.go:25:11:25:14 | SSA param(size) | provenance | |
@@ -12,6 +14,8 @@ edges
| InsufficientKeySize.go:30:13:30:16 | 1024 | InsufficientKeySize.go:32:32:32:38 | keyBits | provenance | |
| InsufficientKeySize.go:44:13:44:16 | 1024 | InsufficientKeySize.go:47:32:47:38 | keyBits | provenance | |
| InsufficientKeySize.go:61:21:61:24 | 1024 | InsufficientKeySize.go:67:31:67:37 | keyBits | provenance | |
+| InsufficientKeySize.go:84:37:84:40 | 1024 | InsufficientKeySize.go:84:37:84:40 | 1024 | provenance | |
+| InsufficientKeySize.go:85:13:85:16 | 1024 | InsufficientKeySize.go:25:11:25:14 | SSA param(size) | provenance | |
nodes
| InsufficientKeySize.go:9:31:9:34 | 1024 | semmle.label | 1024 |
| InsufficientKeySize.go:13:10:13:13 | 1024 | semmle.label | 1024 |
@@ -25,4 +29,7 @@ nodes
| InsufficientKeySize.go:47:32:47:38 | keyBits | semmle.label | keyBits |
| InsufficientKeySize.go:61:21:61:24 | 1024 | semmle.label | 1024 |
| InsufficientKeySize.go:67:31:67:37 | keyBits | semmle.label | keyBits |
+| InsufficientKeySize.go:84:37:84:40 | 1024 | semmle.label | 1024 |
+| InsufficientKeySize.go:84:37:84:40 | 1024 | semmle.label | 1024 |
+| InsufficientKeySize.go:85:13:85:16 | 1024 | semmle.label | 1024 |
subpaths
diff --git a/go/ql/test/query-tests/Security/CWE-326/InsufficientKeySize.go b/go/ql/test/query-tests/Security/CWE-326/InsufficientKeySize.go
index 6c28a054b654..a1fb30777d07 100644
--- a/go/ql/test/query-tests/Security/CWE-326/InsufficientKeySize.go
+++ b/go/ql/test/query-tests/Security/CWE-326/InsufficientKeySize.go
@@ -79,3 +79,8 @@ func foo11(customOptionSupplied bool, nonConstantKeyBits int) {
rsa.GenerateKey(rand.Reader, keyBits) // GOOD
}
}
+
+func foo12() {
+ defer rsa.GenerateKey(rand.Reader, 1024) // $ Alert // BAD
+ defer foo5(1024) // $ Source // BAD
+}
diff --git a/go/ql/test/query-tests/Security/CWE-327/BrokenCryptoAlgorithm.expected b/go/ql/test/query-tests/Security/CWE-327/BrokenCryptoAlgorithm.expected
index 17c258a601bd..5053360c6bb8 100644
--- a/go/ql/test/query-tests/Security/CWE-327/BrokenCryptoAlgorithm.expected
+++ b/go/ql/test/query-tests/Security/CWE-327/BrokenCryptoAlgorithm.expected
@@ -27,3 +27,11 @@
| encryption.go:111:2:111:45 | call to XORKeyStream | $@ is broken or weak, and should not be used. | encryption.go:74:2:74:40 | extract:0 ... := ... | The cryptographic algorithm TRIPLEDES |
| encryption.go:115:2:115:45 | call to XORKeyStream | $@ is broken or weak, and should not be used. | encryption.go:74:2:74:40 | extract:0 ... := ... | The cryptographic algorithm TRIPLEDES |
| encryption.go:166:2:166:33 | call to XORKeyStream | $@ is broken or weak, and should not be used. | encryption.go:166:2:166:33 | call to XORKeyStream | The cryptographic algorithm RC4 |
+| encryption.go:173:21:173:68 | &... [postupdate] | $@ is broken or weak, and should not be used. | encryption.go:170:2:170:31 | extract:0 ... := ... | The cryptographic algorithm DES |
+| encryption.go:173:22:173:68 | struct literal | $@ is broken or weak, and should not be used. | encryption.go:170:2:170:31 | extract:0 ... := ... | The cryptographic algorithm DES |
+| encryption.go:173:22:173:68 | struct literal [postupdate] | $@ is broken or weak, and should not be used. | encryption.go:170:2:170:31 | extract:0 ... := ... | The cryptographic algorithm DES |
+| encryption.go:174:16:174:30 | ctrStreamWriter [postupdate] | $@ is broken or weak, and should not be used. | encryption.go:170:2:170:31 | extract:0 ... := ... | The cryptographic algorithm DES |
+| encryption.go:176:2:176:77 | SSA def(sr) | $@ is broken or weak, and should not be used. | encryption.go:170:2:170:31 | extract:0 ... := ... | The cryptographic algorithm DES |
+| encryption.go:176:8:176:77 | struct literal | $@ is broken or weak, and should not be used. | encryption.go:170:2:170:31 | extract:0 ... := ... | The cryptographic algorithm DES |
+| encryption.go:177:27:177:28 | sr | $@ is broken or weak, and should not be used. | encryption.go:170:2:170:31 | extract:0 ... := ... | The cryptographic algorithm DES |
+| encryption.go:178:9:178:10 | sr | $@ is broken or weak, and should not be used. | encryption.go:170:2:170:31 | extract:0 ... := ... | The cryptographic algorithm DES |
diff --git a/go/ql/test/query-tests/Security/CWE-327/WeakSensitiveDataHashing.expected b/go/ql/test/query-tests/Security/CWE-327/WeakSensitiveDataHashing.expected
index e2ee4bdd7a72..9307652d8afd 100644
--- a/go/ql/test/query-tests/Security/CWE-327/WeakSensitiveDataHashing.expected
+++ b/go/ql/test/query-tests/Security/CWE-327/WeakSensitiveDataHashing.expected
@@ -8,8 +8,12 @@
| hashing.go:30:16:30:30 | secretByteSlice | hashing.go:30:16:30:30 | secretByteSlice | hashing.go:30:16:30:30 | secretByteSlice | $@ is used in a hashing algorithm (MD4) that is insecure. | hashing.go:30:16:30:30 | secretByteSlice | Sensitive data (secret) |
| hashing.go:31:22:31:36 | secretByteSlice | hashing.go:31:22:31:36 | secretByteSlice | hashing.go:31:22:31:36 | secretByteSlice | $@ is used in a hashing algorithm (RIPEMD160) that is insecure. | hashing.go:31:22:31:36 | secretByteSlice | Sensitive data (secret) |
| hashing.go:82:23:82:38 | type conversion | hashing.go:82:30:82:37 | password | hashing.go:82:23:82:38 | type conversion | $@ is used in a hashing algorithm (SHA256) that is insecure for password hashing, since it is not a computationally expensive hash function. | hashing.go:82:30:82:37 | password | Sensitive data (password) |
+| hashing.go:95:16:95:30 | secretByteSlice | hashing.go:95:16:95:30 | secretByteSlice | hashing.go:95:16:95:30 | secretByteSlice | $@ is used in a hashing algorithm (MD5) that is insecure. | hashing.go:95:16:95:30 | secretByteSlice | Sensitive data (secret) |
+| hashing.go:96:26:96:37 | secretString | hashing.go:96:26:96:37 | secretString | hashing.go:96:26:96:37 | secretString | $@ is used in a hashing algorithm (MD5) that is insecure. | hashing.go:96:26:96:37 | secretString | Sensitive data (secret) |
edges
| hashing.go:82:30:82:37 | password | hashing.go:82:23:82:38 | type conversion | provenance | |
+| hashing.go:95:16:95:30 | secretByteSlice | hashing.go:95:16:95:30 | secretByteSlice | provenance | |
+| hashing.go:96:26:96:37 | secretString | hashing.go:96:26:96:37 | secretString | provenance | |
nodes
| hashing.go:22:8:22:22 | secretByteSlice | semmle.label | secretByteSlice |
| hashing.go:23:10:23:24 | secretByteSlice | semmle.label | secretByteSlice |
@@ -21,4 +25,8 @@ nodes
| hashing.go:31:22:31:36 | secretByteSlice | semmle.label | secretByteSlice |
| hashing.go:82:23:82:38 | type conversion | semmle.label | type conversion |
| hashing.go:82:30:82:37 | password | semmle.label | password |
+| hashing.go:95:16:95:30 | secretByteSlice | semmle.label | secretByteSlice |
+| hashing.go:95:16:95:30 | secretByteSlice | semmle.label | secretByteSlice |
+| hashing.go:96:26:96:37 | secretString | semmle.label | secretString |
+| hashing.go:96:26:96:37 | secretString | semmle.label | secretString |
subpaths
diff --git a/go/ql/test/query-tests/Security/CWE-327/encryption.go b/go/ql/test/query-tests/Security/CWE-327/encryption.go
index e6cc712474f4..ad12bdf52327 100644
--- a/go/ql/test/query-tests/Security/CWE-327/encryption.go
+++ b/go/ql/test/query-tests/Security/CWE-327/encryption.go
@@ -165,3 +165,15 @@ func CipherRc4() {
c, _ := rc4.NewCipher(nil)
c.XORKeyStream(dst, getUserID()) // $ Alert[go/weak-cryptographic-algorithm] CryptographicOperation="RC4. init from 0 lines above."
}
+
+func DeferredStreamCipher() cipher.StreamReader {
+ block, _ := des.NewCipher(nil)
+ ctrStream := cipher.NewCTR(block, nil)
+
+ ctrStreamWriter := &cipher.StreamWriter{S: ctrStream, W: os.Stdout} // $ Alert[go/weak-cryptographic-algorithm] CryptographicOperation="DES. blockMode: CTR. init from 2,3 lines above."
+ defer io.Copy(ctrStreamWriter, bytes.NewReader(secretByteSlice)) // $ Alert[go/weak-cryptographic-algorithm] CryptographicOperation="DES. blockMode: CTR. init from 3,4 lines above."
+
+ sr := cipher.StreamReader{S: ctrStream, R: bytes.NewReader(secretByteSlice)} // $ Alert[go/weak-cryptographic-algorithm] CryptographicOperation="DES. blockMode: CTR. init from 5,6 lines above."
+ defer io.Copy(os.Stdout, sr) // $ Alert[go/weak-cryptographic-algorithm] CryptographicOperation="DES. blockMode: CTR. init from 6,7 lines above."
+ return sr // $ Alert[go/weak-cryptographic-algorithm] CryptographicOperation="DES. blockMode: CTR. init from 7,8 lines above."
+}
diff --git a/go/ql/test/query-tests/Security/CWE-327/hashing.go b/go/ql/test/query-tests/Security/CWE-327/hashing.go
index 002e94568a2a..9eefcedff6ed 100644
--- a/go/ql/test/query-tests/Security/CWE-327/hashing.go
+++ b/go/ql/test/query-tests/Security/CWE-327/hashing.go
@@ -89,3 +89,9 @@ func GetPasswordHashGood(password string) []byte {
key, _ := pbkdf2.Key(sha512.New, password, salt, 4096, 32)
return key
}
+
+func DeferredWeakHashes() {
+ h := md5.New()
+ defer h.Write(secretByteSlice) // $ Alert[go/weak-sensitive-data-hashing] CryptographicOperation="MD5. init from 1 lines above."
+ defer io.WriteString(h, secretString) // $ Alert[go/weak-sensitive-data-hashing] CryptographicOperation="MD5. init from 2 lines above."
+}
diff --git a/go/ql/test/query-tests/Security/CWE-798/HardcodedCredentials.expected b/go/ql/test/query-tests/Security/CWE-798/HardcodedCredentials.expected
index 0526c0ba604a..4263055898d1 100644
--- a/go/ql/test/query-tests/Security/CWE-798/HardcodedCredentials.expected
+++ b/go/ql/test/query-tests/Security/CWE-798/HardcodedCredentials.expected
@@ -25,4 +25,5 @@
| main.go:44:14:44:19 | "p4ss" | Hard-coded $@. | main.go:44:14:44:19 | "p4ss" | password |
| main.go:48:13:48:15 | tmp | Hard-coded $@. | main.go:44:14:44:19 | "p4ss" | password |
| main.go:50:15:50:21 | "p4ss2" | Hard-coded $@. | main.go:50:15:50:21 | "p4ss2" | password |
+| main.go:61:20:61:40 | totallyNotAPrivateKey | Hard-coded private key. | main.go:61:20:61:40 | totallyNotAPrivateKey | certificate |
| sanitizer.go:18:44:18:46 | key | Hard-coded $@. | sanitizer.go:17:16:17:25 | `some_key` | secret |
diff --git a/go/ql/test/query-tests/Security/CWE-798/main.go b/go/ql/test/query-tests/Security/CWE-798/main.go
index 7934c0d842fd..313ccaad8097 100644
--- a/go/ql/test/query-tests/Security/CWE-798/main.go
+++ b/go/ql/test/query-tests/Security/CWE-798/main.go
@@ -58,4 +58,5 @@ func main() {
fmt.Println(certsDir)
accountParameter := "ACCOUNT" // OK
fmt.Println(accountParameter)
+ defer fmt.Println(totallyNotAPrivateKey) // $ Alert // NOT OK
}
From 0b0d55b7e8fd4c20f7fd2fc91c7b69f90c9d52f1 Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Tue, 1 Dec 2026 21:00:31 +0000
Subject: [PATCH 10/17] Go: Preserve receiver identity in deferred file-close
checks
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>
---
.../UnhandledCloseWritableHandle.ql | 25 ++++--
.../CONSISTENCY/CfgConsistency.expected | 6 +-
.../UnhandledCloseWritableHandle.expected | 12 +++
.../UnhandledCloseWritableHandle/tests.go | 88 +++++++++++++++++++
4 files changed, 122 insertions(+), 9 deletions(-)
diff --git a/go/ql/src/InconsistentCode/UnhandledCloseWritableHandle.ql b/go/ql/src/InconsistentCode/UnhandledCloseWritableHandle.ql
index 778d90a82ae2..04d815c1721a 100644
--- a/go/ql/src/InconsistentCode/UnhandledCloseWritableHandle.ql
+++ b/go/ql/src/InconsistentCode/UnhandledCloseWritableHandle.ql
@@ -114,6 +114,13 @@ predicate isHandledSync(DataFlow::Node sink, DataFlow::CallNode syncCall) {
not unhandledCall(syncCall)
}
+/** Gets an immediate copy source of `receiver`, without following SSA phi inputs. */
+private DataFlow::Node receiverCopySource(DataFlow::Node receiver) {
+ exists(DataFlow::SsaNode ssa | ssa.getAUse() = receiver | result = ssa.getInit())
+ or
+ result.asInstruction() = receiver.asInstruction().(IR::DeferReadInstruction).getSavedInstruction()
+}
+
module UnhandledFileCloseConfig implements DataFlow::ConfigSig {
predicate isSource(DataFlow::Node source) { isWritableFileHandle(source, _) }
@@ -130,19 +137,25 @@ module UnhandledFileCloseConfig implements DataFlow::ConfigSig {
// check that the call to `os.File.Sync` is handled
isHandledSync(syncReceiver, syncCall) and
// check that `os.File.Sync` is called on the same object as `os.File.Close`
- exists(DataFlow::SsaNode ssa | ssa.getAUse() = sink and ssa.getAUse() = syncReceiver)
+ exists(DataFlow::SsaNode ssa |
+ ssa.getAUse() = receiverCopySource*(sink) and ssa.getAUse() = syncReceiver
+ )
|
if exists(DeferStmt defer | defer.getCall() = closeCall.asExpr())
then
// When the call to `os.File.Close` is deferred it runs when the enclosing function
- // returns, but the receiver of the deferred call is evaluated where the `defer`
- // statement appears. It is therefore enough for the handled call to `os.File.Sync`
- // to post-dominate that point, since that guarantees `os.File.Sync` runs before the
- // deferred `os.File.Close` on every path on which the `os.File.Close` is registered.
+ // returns, but the `defer` statement is registered where it appears. It is therefore
+ // enough for the handled call to `os.File.Sync` to post-dominate that registration
+ // point, since that guarantees `os.File.Sync` runs before the deferred `os.File.Close`
+ // on every path on which the `os.File.Close` is registered.
// We cannot reuse the domination check below because the control-flow graph splices
// the deferred call in at the function exit, where it may be reachable along paths
// that do not pass through the call to `os.File.Sync`.
- postDominatesNode(syncCall.asInstruction(), sink.asInstruction())
+ exists(DeferStmt defer, ControlFlow::Node reg |
+ defer.getCall() = closeCall.asExpr() and
+ reg.isIn(defer) and
+ postDominatesNode(syncCall.asInstruction(), reg)
+ )
else
// Otherwise the call to `os.File.Close` is executed where it appears, so we require
// the handled call to `os.File.Sync` to dominate it.
diff --git a/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/CONSISTENCY/CfgConsistency.expected b/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/CONSISTENCY/CfgConsistency.expected
index 2ce97565d12d..e26dfe030ec4 100644
--- a/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/CONSISTENCY/CfgConsistency.expected
+++ b/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/CONSISTENCY/CfgConsistency.expected
@@ -2,8 +2,8 @@ consistencyOverview
| multipleSuccessors | 6 |
multipleSuccessors
| tests.go:96:2:104:2 | After if statement | successor | tests.go:94:30:105:1 | After block statement |
-| tests.go:96:2:104:2 | After if statement | successor | tests.go:99:9:99:17 | defer-invoke call to Close |
+| tests.go:96:2:104:2 | After if statement | successor | tests.go:99:9:99:17 | defer-recv-read call to Close |
| tests.go:119:2:119:6 | After ... = ... | successor | tests.go:107:31:120:1 | After block statement |
-| tests.go:119:2:119:6 | After ... = ... | successor | tests.go:112:9:112:17 | defer-invoke call to Close |
+| tests.go:119:2:119:6 | After ... = ... | successor | tests.go:112:9:112:17 | defer-recv-read call to Close |
| tests.go:124:2:136:2 | After if statement | successor | tests.go:122:46:137:1 | After block statement |
-| tests.go:124:2:136:2 | After if statement | successor | tests.go:126:9:126:17 | defer-invoke call to Close |
+| tests.go:124:2:136:2 | After if statement | successor | tests.go:126:9:126:17 | defer-recv-read call to Close |
diff --git a/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected b/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected
index e51c2db4e8bb..559121b23778 100644
--- a/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected
+++ b/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected
@@ -8,6 +8,9 @@
| tests.go:126:9:126:9 | f | tests.go:124:5:124:78 | extract:0 ... := ... | tests.go:126:9:126:9 | f | File handle may be writable as a result of data flow from a $@ and closing it may result in data loss upon failure, which is not handled explicitly. | tests.go:124:15:124:78 | call to OpenFile | call to OpenFile |
| tests.go:145:3:145:3 | f | tests.go:141:5:141:78 | extract:0 ... := ... | tests.go:145:3:145:3 | f | File handle may be writable as a result of data flow from a $@ and closing it may result in data loss upon failure, which is not handled explicitly. | tests.go:141:15:141:78 | call to OpenFile | call to OpenFile |
| tests.go:166:8:166:8 | f | tests.go:162:2:162:74 | extract:0 ... := ... | tests.go:166:8:166:8 | f | File handle may be writable as a result of data flow from a $@ and closing it may result in data loss upon failure, which is not handled explicitly. | tests.go:162:12:162:74 | call to OpenFile | call to OpenFile |
+| tests.go:189:8:189:9 | f2 | tests.go:176:2:176:76 | extract:0 ... := ... | tests.go:189:8:189:9 | f2 | File handle may be writable as a result of data flow from a $@ and closing it may result in data loss upon failure, which is not handled explicitly. | tests.go:176:13:176:76 | call to OpenFile | call to OpenFile |
+| tests.go:215:2:215:7 | chosen | tests.go:204:2:204:75 | extract:0 ... := ... | tests.go:215:2:215:7 | chosen | File handle may be writable as a result of data flow from a $@ and closing it may result in data loss upon failure, which is not handled explicitly. | tests.go:204:12:204:75 | call to OpenFile | call to OpenFile |
+| tests.go:228:8:228:13 | chosen | tests.go:220:2:220:75 | extract:0 ... := ... | tests.go:228:8:228:13 | chosen | File handle may be writable as a result of data flow from a $@ and closing it may result in data loss upon failure, which is not handled explicitly. | tests.go:220:12:220:75 | call to OpenFile | call to OpenFile |
edges
| tests.go:9:24:9:24 | SSA param(f) | tests.go:10:8:10:8 | f | provenance | |
| tests.go:13:32:13:32 | SSA param(f) | tests.go:14:13:16:2 | SSA implicit def(f) | provenance | |
@@ -25,6 +28,9 @@ edges
| tests.go:124:5:124:78 | extract:0 ... := ... | tests.go:126:9:126:9 | f | provenance | Src:MaD:1 |
| tests.go:141:5:141:78 | extract:0 ... := ... | tests.go:145:3:145:3 | f | provenance | Src:MaD:1 |
| tests.go:162:2:162:74 | extract:0 ... := ... | tests.go:166:8:166:8 | f | provenance | Src:MaD:1 |
+| tests.go:176:2:176:76 | extract:0 ... := ... | tests.go:189:8:189:9 | f2 | provenance | Src:MaD:1 |
+| tests.go:204:2:204:75 | extract:0 ... := ... | tests.go:215:2:215:7 | chosen | provenance | Src:MaD:1 |
+| tests.go:220:2:220:75 | extract:0 ... := ... | tests.go:228:8:228:13 | chosen | provenance | Src:MaD:1 |
models
| 1 | Source: os; ; false; OpenFile; ; ; ReturnValue[0]; file; manual |
nodes
@@ -49,4 +55,10 @@ nodes
| tests.go:145:3:145:3 | f | semmle.label | f |
| tests.go:162:2:162:74 | extract:0 ... := ... | semmle.label | extract:0 ... := ... |
| tests.go:166:8:166:8 | f | semmle.label | f |
+| tests.go:176:2:176:76 | extract:0 ... := ... | semmle.label | extract:0 ... := ... |
+| tests.go:189:8:189:9 | f2 | semmle.label | f2 |
+| tests.go:204:2:204:75 | extract:0 ... := ... | semmle.label | extract:0 ... := ... |
+| tests.go:215:2:215:7 | chosen | semmle.label | chosen |
+| tests.go:220:2:220:75 | extract:0 ... := ... | semmle.label | extract:0 ... := ... |
+| tests.go:228:8:228:13 | chosen | semmle.label | chosen |
subpaths
diff --git a/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/tests.go b/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/tests.go
index 94027e18d9d4..89b1be866725 100644
--- a/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/tests.go
+++ b/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/tests.go
@@ -171,3 +171,91 @@ func copyFile(destFile string, mode os.FileMode, src io.Reader) error {
}
return f.Sync()
}
+
+func deferredCloseSyncOnlyInOneBranch(cond bool) error {
+ f1, err := os.OpenFile("foo.txt", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) // $ Source
+ if err != nil {
+ return err
+ }
+ var f2 *os.File
+ if cond {
+ f2 = f1
+ if err := f1.Sync(); err != nil {
+ return err
+ }
+ } else {
+ f2 = f1
+ }
+ defer f2.Close() // $ Alert
+ return nil
+}
+
+func deferredCloseAliasWithSync() error {
+ f1, err := os.OpenFile("foo.txt", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
+ if err != nil {
+ return err
+ }
+ f2 := f1
+ defer f2.Close() // OK: f1.Sync() post-dominates the defer registration
+ return f1.Sync()
+}
+
+func closeMergedReceiverWithPartialSync(other *os.File, cond bool) error {
+ f, err := os.OpenFile("foo.txt", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) // $ Source
+ if err != nil {
+ return err
+ }
+ chosen := other
+ if cond {
+ chosen = f
+ }
+ if err := other.Sync(); err != nil {
+ return err
+ }
+ chosen.Close() // $ Alert
+ return nil
+}
+
+func deferredCloseMergedReceiverWithPartialSync(other *os.File, cond bool) error {
+ f, err := os.OpenFile("foo.txt", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666) // $ Source
+ if err != nil {
+ return err
+ }
+ chosen := other
+ if cond {
+ chosen = f
+ }
+ defer chosen.Close() // $ Alert
+ return other.Sync()
+}
+
+func closeMergedReceiverWithSync(other *os.File, cond bool) error {
+ f, err := os.OpenFile("foo.txt", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
+ if err != nil {
+ return err
+ }
+ chosen := other
+ if cond {
+ chosen = f
+ }
+ alias := chosen
+ if err := chosen.Sync(); err != nil {
+ return err
+ }
+ alias.Close() // OK: the copied receiver is the same merged handle that was synced
+ return nil
+}
+
+func deferredCloseMergedReceiverWithSync(other *os.File, cond bool) error {
+ f, err := os.OpenFile("foo.txt", os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
+ if err != nil {
+ return err
+ }
+ chosen := other
+ if cond {
+ chosen = f
+ }
+ alias := chosen
+ defer alias.Close() // OK: the copied receiver is the same merged handle that is synced
+ return chosen.Sync()
+}
From d6d23c6ba4dc21a0960224a247f996469555b702 Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Tue, 1 Dec 2026 21:01:18 +0000
Subject: [PATCH 11/17] Go: Trace deferred SSH callback return values
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>
---
.../CWE-322/InsecureHostKeyCallback.ql | 19 ++++++-
.../CONSISTENCY/SsaConsistency.expected | 4 ++
.../CWE-322/InsecureHostKeyCallback.expected | 44 ++++++++++-------
.../CWE-322/InsecureHostKeyCallbackExample.go | 49 +++++++++++++++++++
4 files changed, 97 insertions(+), 19 deletions(-)
create mode 100644 go/ql/test/query-tests/Security/CWE-322/CONSISTENCY/SsaConsistency.expected
diff --git a/go/ql/src/Security/CWE-322/InsecureHostKeyCallback.ql b/go/ql/src/Security/CWE-322/InsecureHostKeyCallback.ql
index 87c5a2184b04..82eb2124cbf5 100644
--- a/go/ql/src/Security/CWE-322/InsecureHostKeyCallback.ql
+++ b/go/ql/src/Security/CWE-322/InsecureHostKeyCallback.ql
@@ -46,10 +46,25 @@ class InsecureHostKeyCallbackFunc extends HostKeyCallbackFunc {
this = any(InsecureIgnoreHostKey f).getACall().getAResult()
or
// Or a callback function in the source code (named or anonymous) that always returns nil.
- forex(DataFlow::ResultNode returnValue |
+ not exists(DataFlow::ResultNode returnValue |
returnValue = this.(DataFlow::FunctionNode).getAResult()
|
- returnValue = Builtin::nil().getARead()
+ exists(DataFlow::SsaNode uncertain |
+ uncertain.getDefinition() instanceof SsaUncertainWrite and
+ DataFlow::localFlow(uncertain, returnValue)
+ )
+ or
+ exists(ResultVariable rv |
+ returnValue.asInstruction().(IR::ReadResultInstruction).reads(rv) and
+ rv.(SsaSourceVariable).mayHaveIndirectReferences()
+ )
+ ) and
+ forex(DataFlow::ResultNode returnValue, DataFlow::Node prev |
+ returnValue = this.(DataFlow::FunctionNode).getAResult() and
+ DataFlow::localFlow(prev, returnValue) and
+ not DataFlow::localFlowStep(_, prev)
+ |
+ prev = Builtin::nil().getARead()
)
}
}
diff --git a/go/ql/test/query-tests/Security/CWE-322/CONSISTENCY/SsaConsistency.expected b/go/ql/test/query-tests/Security/CWE-322/CONSISTENCY/SsaConsistency.expected
new file mode 100644
index 000000000000..c8f4be1e602a
--- /dev/null
+++ b/go/ql/test/query-tests/Security/CWE-322/CONSISTENCY/SsaConsistency.expected
@@ -0,0 +1,4 @@
+uselessPhiNode
+| InsecureHostKeyCallbackExample.go:152:11:154:5 | SSA phi(err) | 1 |
+phiWithoutTwoPriorRefs
+| InsecureHostKeyCallbackExample.go:152:11:154:5 | SSA phi(err) | InsecureHostKeyCallbackExample.go:152:11:154:5 | Exit | InsecureHostKeyCallbackExample.go:151:63:151:65 | err | 1 |
diff --git a/go/ql/test/query-tests/Security/CWE-322/InsecureHostKeyCallback.expected b/go/ql/test/query-tests/Security/CWE-322/InsecureHostKeyCallback.expected
index 1396427faa0b..560564920783 100644
--- a/go/ql/test/query-tests/Security/CWE-322/InsecureHostKeyCallback.expected
+++ b/go/ql/test/query-tests/Security/CWE-322/InsecureHostKeyCallback.expected
@@ -3,6 +3,7 @@
| InsecureHostKeyCallbackExample.go:26:20:26:46 | call to InsecureIgnoreHostKey | InsecureHostKeyCallbackExample.go:26:20:26:46 | call to InsecureIgnoreHostKey | InsecureHostKeyCallbackExample.go:26:20:26:46 | call to InsecureIgnoreHostKey | Configuring SSH ClientConfig with insecure HostKeyCallback implementation from $@. | InsecureHostKeyCallbackExample.go:26:20:26:46 | call to InsecureIgnoreHostKey | this source |
| InsecureHostKeyCallbackExample.go:39:20:39:27 | callback | InsecureHostKeyCallbackExample.go:32:3:34:3 | function literal | InsecureHostKeyCallbackExample.go:39:20:39:27 | callback | Configuring SSH ClientConfig with insecure HostKeyCallback implementation from $@. | InsecureHostKeyCallbackExample.go:32:3:34:3 | function literal | this source |
| InsecureHostKeyCallbackExample.go:52:20:52:48 | type conversion | InsecureHostKeyCallbackExample.go:45:3:47:3 | function literal | InsecureHostKeyCallbackExample.go:52:20:52:48 | type conversion | Configuring SSH ClientConfig with insecure HostKeyCallback implementation from $@. | InsecureHostKeyCallbackExample.go:45:3:47:3 | function literal | this source |
+| InsecureHostKeyCallbackExample.go:103:20:107:5 | type conversion | InsecureHostKeyCallbackExample.go:104:4:107:4 | function literal | InsecureHostKeyCallbackExample.go:103:20:107:5 | type conversion | Configuring SSH ClientConfig with insecure HostKeyCallback implementation from $@. | InsecureHostKeyCallbackExample.go:104:4:107:4 | function literal | this source |
edges
| InsecureHostKeyCallbackExample.go:16:4:18:4 | function literal | InsecureHostKeyCallbackExample.go:15:20:18:5 | type conversion | provenance | |
| InsecureHostKeyCallbackExample.go:31:14:34:4 | type conversion | InsecureHostKeyCallbackExample.go:39:20:39:27 | callback | provenance | |
@@ -11,15 +12,18 @@ edges
| InsecureHostKeyCallbackExample.go:58:39:58:46 | SSA param(callback) | InsecureHostKeyCallbackExample.go:62:20:62:27 | callback | provenance | |
| InsecureHostKeyCallbackExample.go:68:48:68:55 | SSA param(callback) | InsecureHostKeyCallbackExample.go:78:28:78:35 | callback | provenance | |
| InsecureHostKeyCallbackExample.go:94:3:94:43 | extract:0 ... := ... | InsecureHostKeyCallbackExample.go:95:28:95:35 | callback | provenance | |
-| InsecureHostKeyCallbackExample.go:102:22:105:4 | type conversion | InsecureHostKeyCallbackExample.go:107:35:107:50 | insecureCallback | provenance | |
-| InsecureHostKeyCallbackExample.go:103:3:105:3 | function literal | InsecureHostKeyCallbackExample.go:102:22:105:4 | type conversion | provenance | |
-| InsecureHostKeyCallbackExample.go:107:35:107:50 | insecureCallback | InsecureHostKeyCallbackExample.go:58:39:58:46 | SSA param(callback) | provenance | |
-| InsecureHostKeyCallbackExample.go:109:31:115:4 | type conversion | InsecureHostKeyCallbackExample.go:117:35:117:59 | potentiallySecureCallback | provenance | |
-| InsecureHostKeyCallbackExample.go:109:31:115:4 | type conversion | InsecureHostKeyCallbackExample.go:120:44:120:68 | potentiallySecureCallback | provenance | |
-| InsecureHostKeyCallbackExample.go:110:3:115:3 | function literal | InsecureHostKeyCallbackExample.go:109:31:115:4 | type conversion | provenance | |
-| InsecureHostKeyCallbackExample.go:117:35:117:59 | potentiallySecureCallback | InsecureHostKeyCallbackExample.go:58:39:58:46 | SSA param(callback) | provenance | |
-| InsecureHostKeyCallbackExample.go:118:35:118:61 | call to InsecureIgnoreHostKey | InsecureHostKeyCallbackExample.go:58:39:58:46 | SSA param(callback) | provenance | |
-| InsecureHostKeyCallbackExample.go:120:44:120:68 | potentiallySecureCallback | InsecureHostKeyCallbackExample.go:68:48:68:55 | SSA param(callback) | provenance | |
+| InsecureHostKeyCallbackExample.go:104:4:107:4 | function literal | InsecureHostKeyCallbackExample.go:103:20:107:5 | type conversion | provenance | |
+| InsecureHostKeyCallbackExample.go:114:22:117:4 | type conversion | InsecureHostKeyCallbackExample.go:119:35:119:50 | insecureCallback | provenance | |
+| InsecureHostKeyCallbackExample.go:115:3:117:3 | function literal | InsecureHostKeyCallbackExample.go:114:22:117:4 | type conversion | provenance | |
+| InsecureHostKeyCallbackExample.go:119:35:119:50 | insecureCallback | InsecureHostKeyCallbackExample.go:58:39:58:46 | SSA param(callback) | provenance | |
+| InsecureHostKeyCallbackExample.go:121:31:127:4 | type conversion | InsecureHostKeyCallbackExample.go:129:35:129:59 | potentiallySecureCallback | provenance | |
+| InsecureHostKeyCallbackExample.go:121:31:127:4 | type conversion | InsecureHostKeyCallbackExample.go:132:44:132:68 | potentiallySecureCallback | provenance | |
+| InsecureHostKeyCallbackExample.go:122:3:127:3 | function literal | InsecureHostKeyCallbackExample.go:121:31:127:4 | type conversion | provenance | |
+| InsecureHostKeyCallbackExample.go:129:35:129:59 | potentiallySecureCallback | InsecureHostKeyCallbackExample.go:58:39:58:46 | SSA param(callback) | provenance | |
+| InsecureHostKeyCallbackExample.go:130:35:130:61 | call to InsecureIgnoreHostKey | InsecureHostKeyCallbackExample.go:58:39:58:46 | SSA param(callback) | provenance | |
+| InsecureHostKeyCallbackExample.go:132:44:132:68 | potentiallySecureCallback | InsecureHostKeyCallbackExample.go:68:48:68:55 | SSA param(callback) | provenance | |
+| InsecureHostKeyCallbackExample.go:151:4:156:4 | function literal | InsecureHostKeyCallbackExample.go:150:20:156:5 | type conversion | provenance | |
+| InsecureHostKeyCallbackExample.go:165:4:168:4 | function literal | InsecureHostKeyCallbackExample.go:164:20:168:5 | type conversion | provenance | |
nodes
| InsecureHostKeyCallbackExample.go:15:20:18:5 | type conversion | semmle.label | type conversion |
| InsecureHostKeyCallbackExample.go:16:4:18:4 | function literal | semmle.label | function literal |
@@ -37,12 +41,18 @@ nodes
| InsecureHostKeyCallbackExample.go:92:28:92:54 | call to InsecureIgnoreHostKey | semmle.label | call to InsecureIgnoreHostKey |
| InsecureHostKeyCallbackExample.go:94:3:94:43 | extract:0 ... := ... | semmle.label | extract:0 ... := ... |
| InsecureHostKeyCallbackExample.go:95:28:95:35 | callback | semmle.label | callback |
-| InsecureHostKeyCallbackExample.go:102:22:105:4 | type conversion | semmle.label | type conversion |
-| InsecureHostKeyCallbackExample.go:103:3:105:3 | function literal | semmle.label | function literal |
-| InsecureHostKeyCallbackExample.go:107:35:107:50 | insecureCallback | semmle.label | insecureCallback |
-| InsecureHostKeyCallbackExample.go:109:31:115:4 | type conversion | semmle.label | type conversion |
-| InsecureHostKeyCallbackExample.go:110:3:115:3 | function literal | semmle.label | function literal |
-| InsecureHostKeyCallbackExample.go:117:35:117:59 | potentiallySecureCallback | semmle.label | potentiallySecureCallback |
-| InsecureHostKeyCallbackExample.go:118:35:118:61 | call to InsecureIgnoreHostKey | semmle.label | call to InsecureIgnoreHostKey |
-| InsecureHostKeyCallbackExample.go:120:44:120:68 | potentiallySecureCallback | semmle.label | potentiallySecureCallback |
+| InsecureHostKeyCallbackExample.go:103:20:107:5 | type conversion | semmle.label | type conversion |
+| InsecureHostKeyCallbackExample.go:104:4:107:4 | function literal | semmle.label | function literal |
+| InsecureHostKeyCallbackExample.go:114:22:117:4 | type conversion | semmle.label | type conversion |
+| InsecureHostKeyCallbackExample.go:115:3:117:3 | function literal | semmle.label | function literal |
+| InsecureHostKeyCallbackExample.go:119:35:119:50 | insecureCallback | semmle.label | insecureCallback |
+| InsecureHostKeyCallbackExample.go:121:31:127:4 | type conversion | semmle.label | type conversion |
+| InsecureHostKeyCallbackExample.go:122:3:127:3 | function literal | semmle.label | function literal |
+| InsecureHostKeyCallbackExample.go:129:35:129:59 | potentiallySecureCallback | semmle.label | potentiallySecureCallback |
+| InsecureHostKeyCallbackExample.go:130:35:130:61 | call to InsecureIgnoreHostKey | semmle.label | call to InsecureIgnoreHostKey |
+| InsecureHostKeyCallbackExample.go:132:44:132:68 | potentiallySecureCallback | semmle.label | potentiallySecureCallback |
+| InsecureHostKeyCallbackExample.go:150:20:156:5 | type conversion | semmle.label | type conversion |
+| InsecureHostKeyCallbackExample.go:151:4:156:4 | function literal | semmle.label | function literal |
+| InsecureHostKeyCallbackExample.go:164:20:168:5 | type conversion | semmle.label | type conversion |
+| InsecureHostKeyCallbackExample.go:165:4:168:4 | function literal | semmle.label | function literal |
subpaths
diff --git a/go/ql/test/query-tests/Security/CWE-322/InsecureHostKeyCallbackExample.go b/go/ql/test/query-tests/Security/CWE-322/InsecureHostKeyCallbackExample.go
index 1d5b17ebd8d4..5de64c35fee9 100644
--- a/go/ql/test/query-tests/Security/CWE-322/InsecureHostKeyCallbackExample.go
+++ b/go/ql/test/query-tests/Security/CWE-322/InsecureHostKeyCallbackExample.go
@@ -96,6 +96,18 @@ func potentialInsecureSSHClientConfigUsingKnownHosts(x bool) {
}
}
+func insecureSSHClientConfigWithDefer() {
+ _ = &ssh.ClientConfig{
+ User: "user",
+ Auth: []ssh.AuthMethod{nil},
+ HostKeyCallback: ssh.HostKeyCallback( // BAD
+ func(hostname string, remote net.Addr, key ssh.PublicKey) error {
+ defer fmt.Println(hostname)
+ return nil
+ }), // $ Source Alert
+ }
+}
+
func main() {
fmt.Printf("Hello insecure SSH client config!\n")
@@ -119,3 +131,40 @@ func main() {
potentialInsecureSSHClientConfigTwoWrites(potentiallySecureCallback)
}
+
+func verifyHostKey(hostname string, remote net.Addr, key ssh.PublicKey) error {
+ if hostname == "localhost" {
+ return nil
+ }
+ return fmt.Errorf("ssh: Unexpected host for key")
+}
+
+func setHostKeyErr(err *error, hostname string, remote net.Addr, key ssh.PublicKey) {
+ *err = verifyHostKey(hostname, remote, key)
+}
+
+func secureSSHClientConfigDeferredNamedErr() {
+ _ = &ssh.ClientConfig{
+ User: "user",
+ Auth: []ssh.AuthMethod{nil},
+ HostKeyCallback: ssh.HostKeyCallback( // GOOD
+ func(hostname string, remote net.Addr, key ssh.PublicKey) (err error) {
+ defer func() {
+ err = verifyHostKey(hostname, remote, key)
+ }()
+ return nil
+ }),
+ }
+}
+
+func secureSSHClientConfigDeferredNamedErrPtr() {
+ _ = &ssh.ClientConfig{
+ User: "user",
+ Auth: []ssh.AuthMethod{nil},
+ HostKeyCallback: ssh.HostKeyCallback( // GOOD
+ func(hostname string, remote net.Addr, key ssh.PublicKey) (err error) {
+ defer setHostKeyErr(&err, hostname, remote, key)
+ return nil
+ }),
+ }
+}
From 76013b245576ce99a0cc097f5097abea16e65a3f Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Tue, 1 Dec 2026 21:02:03 +0000
Subject: [PATCH 12/17] Go: Document defer modeling and query precision changes
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>
---
go/ql/lib/change-notes/2026-11-28-defer-temporaries.md | 4 ++++
go/ql/src/change-notes/2026-12-01-defer-temporaries.md | 4 ++++
2 files changed, 8 insertions(+)
create mode 100644 go/ql/lib/change-notes/2026-11-28-defer-temporaries.md
create mode 100644 go/ql/src/change-notes/2026-12-01-defer-temporaries.md
diff --git a/go/ql/lib/change-notes/2026-11-28-defer-temporaries.md b/go/ql/lib/change-notes/2026-11-28-defer-temporaries.md
new file mode 100644
index 000000000000..752393c93b37
--- /dev/null
+++ b/go/ql/lib/change-notes/2026-11-28-defer-temporaries.md
@@ -0,0 +1,4 @@
+---
+category: minorAnalysis
+---
+* Improved control-flow, IR, SSA, and data-flow modeling of `defer` statements by saving evaluated callees, receivers, and arguments into synthetic temporaries at `defer` registration, reading them before deferred invocation, and saving unnamed `return` values across deferred calls. Mutations performed by deferred calls on arguments and receivers now propagate to function results and subsequent deferred calls in LIFO order rather than appearing in the function body before the `defer` runs. As a result, `CallNode.getArgument`, `CallNode.getSyntacticArgument`, `CallNode.getCalleeNode`, `MethodCallNode.getReceiver`, and `ResultNode` in functions containing `defer` may now return synthetic `InstructionNode`s rather than `ExprNode`s.
diff --git a/go/ql/src/change-notes/2026-12-01-defer-temporaries.md b/go/ql/src/change-notes/2026-12-01-defer-temporaries.md
new file mode 100644
index 000000000000..fdbe0d41fb9b
--- /dev/null
+++ b/go/ql/src/change-notes/2026-12-01-defer-temporaries.md
@@ -0,0 +1,4 @@
+---
+category: minorAnalysis
+---
+* Improved the precision of the queries `go/insecure-hostkeycallback` ("Use of insecure HostKeyCallback implementation") and `go/unhandled-writable-file-close` ("Writable file handle closed without error handling"), which may lead to more results or fewer false positives.
From 892427ee074e848c955e5c915f851911e23a869e Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Fri, 4 Dec 2026 12:32:48 +0000
Subject: [PATCH 13/17] Go: Widen XPathInjection Sink and Sanitizer to
DataFlow::Node
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>
---
.../semmle/go/security/XPathInjectionCustomizations.qll | 4 ++--
.../query-tests/Security/CWE-643/XPathInjection.expected | 9 +++++++++
go/ql/test/query-tests/Security/CWE-643/tst.go | 9 +++++++++
3 files changed, 20 insertions(+), 2 deletions(-)
diff --git a/go/ql/lib/semmle/go/security/XPathInjectionCustomizations.qll b/go/ql/lib/semmle/go/security/XPathInjectionCustomizations.qll
index 2c56af871455..ccd87ae0732c 100644
--- a/go/ql/lib/semmle/go/security/XPathInjectionCustomizations.qll
+++ b/go/ql/lib/semmle/go/security/XPathInjectionCustomizations.qll
@@ -17,12 +17,12 @@ module XPathInjection {
/**
* A data flow sink for untrusted user input used in an XPath expression.
*/
- abstract class Sink extends DataFlow::ExprNode { }
+ abstract class Sink extends DataFlow::Node { }
/**
* A sanitizer for untrusted user input used in an XPath expression.
*/
- abstract class Sanitizer extends DataFlow::ExprNode { }
+ abstract class Sanitizer extends DataFlow::Node { }
/** A source of untrusted data, used in an XPath expression. */
private class ThreatModelFlowAsSource extends Source instanceof ActiveThreatModelSource { }
diff --git a/go/ql/test/query-tests/Security/CWE-643/XPathInjection.expected b/go/ql/test/query-tests/Security/CWE-643/XPathInjection.expected
index 0d492788c51d..1e1a98692cb4 100644
--- a/go/ql/test/query-tests/Security/CWE-643/XPathInjection.expected
+++ b/go/ql/test/query-tests/Security/CWE-643/XPathInjection.expected
@@ -42,6 +42,8 @@
| tst.go:123:27:123:122 | ...+... | tst.go:116:14:116:19 | selection of Form | tst.go:123:27:123:122 | ...+... | XPath expression depends on a $@. | tst.go:116:14:116:19 | selection of Form | user-provided value |
| tst.go:144:17:144:87 | type conversion | tst.go:139:14:139:19 | selection of Form | tst.go:144:17:144:87 | type conversion | XPath expression depends on a $@. | tst.go:139:14:139:19 | selection of Form | user-provided value |
| tst.go:146:23:146:85 | ...+... | tst.go:139:14:139:19 | selection of Form | tst.go:146:23:146:85 | ...+... | XPath expression depends on a $@. | tst.go:139:14:139:19 | selection of Form | user-provided value |
+| tst.go:153:22:153:84 | ...+... | tst.go:151:14:151:19 | selection of Form | tst.go:153:22:153:84 | ...+... | XPath expression depends on a $@. | tst.go:151:14:151:19 | selection of Form | user-provided value |
+| tst.go:154:20:154:78 | ...+... | tst.go:151:14:151:19 | selection of Form | tst.go:154:20:154:78 | ...+... | XPath expression depends on a $@. | tst.go:151:14:151:19 | selection of Form | user-provided value |
edges
| XPathInjection.go:13:14:13:19 | selection of Form | XPathInjection.go:13:14:13:35 | call to Get | provenance | Src:MaD:36 MaD:37 |
| XPathInjection.go:13:14:13:35 | call to Get | XPathInjection.go:16:29:16:91 | ...+... | provenance | Sink:MaD:1 |
@@ -100,6 +102,9 @@ edges
| tst.go:139:14:139:35 | call to Get | tst.go:145:41:145:103 | ...+... | provenance | |
| tst.go:139:14:139:35 | call to Get | tst.go:146:23:146:85 | ...+... | provenance | Sink:MaD:26 |
| tst.go:145:41:145:103 | ...+... | tst.go:145:23:145:104 | call to NewReader | provenance | MaD:38 Sink:MaD:25 |
+| tst.go:151:14:151:19 | selection of Form | tst.go:151:14:151:35 | call to Get | provenance | Src:MaD:36 MaD:37 |
+| tst.go:151:14:151:35 | call to Get | tst.go:153:22:153:84 | ...+... | provenance | Sink:MaD:20 |
+| tst.go:151:14:151:35 | call to Get | tst.go:154:20:154:78 | ...+... | provenance | Sink:MaD:29 |
models
| 1 | Sink: github.com/ChrisTrenkamp/goxpath; ; false; MustParse; ; ; Argument[0]; xpath-injection; manual |
| 2 | Sink: github.com/ChrisTrenkamp/goxpath; ; false; Parse; ; ; Argument[0]; xpath-injection; manual |
@@ -201,4 +206,8 @@ nodes
| tst.go:145:23:145:104 | call to NewReader | semmle.label | call to NewReader |
| tst.go:145:41:145:103 | ...+... | semmle.label | ...+... |
| tst.go:146:23:146:85 | ...+... | semmle.label | ...+... |
+| tst.go:151:14:151:19 | selection of Form | semmle.label | selection of Form |
+| tst.go:151:14:151:35 | call to Get | semmle.label | call to Get |
+| tst.go:153:22:153:84 | ...+... | semmle.label | ...+... |
+| tst.go:154:20:154:78 | ...+... | semmle.label | ...+... |
subpaths
diff --git a/go/ql/test/query-tests/Security/CWE-643/tst.go b/go/ql/test/query-tests/Security/CWE-643/tst.go
index cf15ceeb0334..f4613e2e7caf 100644
--- a/go/ql/test/query-tests/Security/CWE-643/tst.go
+++ b/go/ql/test/query-tests/Security/CWE-643/tst.go
@@ -145,3 +145,12 @@ func testLestratGoLibxml2(r *http.Request) {
_, _ = p.ParseReader(strings.NewReader("//users/user[login/text()='" + username + "']/home_dir/text()"))
_, _ = p.ParseString("//users/user[login/text()='" + username + "']/home_dir/text()") // $ Alert
}
+
+func testDeferredXPath(r *http.Request, n gokogiriXml.Node) {
+ r.ParseForm()
+ username := r.Form.Get("username") // $ Source
+
+ defer xpath.Compile("//users/user[login/text()='" + username + "']/home_dir/text()") // $ Alert
+ defer n.EvalXPath("//users/user[login/text()='"+username+"']/home_dir/text()", nil) // $ Alert
+ defer xpath.Compile("//users/user[login/text()='safe']/home_dir/text()")
+}
From a6966822651e45977aa5ef0d91d4f9792092c943 Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Fri, 27 Nov 2026 12:19:11 +0000
Subject: [PATCH 14/17] Go: Implement shared variable capture
Use the shared variable capture library for inter-procedural capture flow while keeping internal capture nodes hidden and preserving ordinary SSA local flow. Recognize named, generic, and summarized function values and method values as lambda targets, and track closure aliases through local SSA, nested captured variables, conversions, and type assertions.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
.../VariableCaptureConsistency.ql | 1 +
.../2026-10-21-variable-capture.md | 5 +
.../go/dataflow/internal/DataFlowDispatch.qll | 5 +-
.../go/dataflow/internal/DataFlowNodes.qll | 92 +++-
.../go/dataflow/internal/DataFlowPrivate.qll | 139 ++++---
.../go/dataflow/internal/DataFlowUtil.qll | 36 +-
.../dataflow/internal/TaintTrackingUtil.qll | 17 +-
.../go/dataflow/internal/VariableCapture.qll | 208 +++++++++
.../go/dataflow/PostUpdateNodes/test.expected | 2 +
.../HiddenNodes.expected | 21 +
.../SSADataFlowIntegration/HiddenNodes.ql | 9 +-
.../HiddenNodesStateful.expected | 49 +++
.../HiddenNodesStateful.ql | 9 +-
.../VariableCapture/ArgumentNodes.expected | 0
.../dataflow/VariableCapture/ArgumentNodes.ql | 69 +++
.../CONSISTENCY/SsaConsistency.expected | 52 +++
.../dataflow/VariableCapture/Flows.expected | 5 +
.../go/dataflow/VariableCapture/Flows.ql | 40 ++
.../VariableCapture/LocalFlow.expected | 0
.../go/dataflow/VariableCapture/LocalFlow.ql | 28 ++
.../go/dataflow/VariableCapture/test.go | 393 ++++++++++++++++++
.../frameworks/Twirp/RequestForgery.expected | 6 +-
.../UnhandledCloseWritableHandle.expected | 6 +-
23 files changed, 1102 insertions(+), 90 deletions(-)
create mode 100644 go/ql/consistency-queries/VariableCaptureConsistency.ql
create mode 100644 go/ql/lib/change-notes/2026-10-21-variable-capture.md
create mode 100644 go/ql/lib/semmle/go/dataflow/internal/VariableCapture.qll
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.expected
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.ql
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/CONSISTENCY/SsaConsistency.expected
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/Flows.expected
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/Flows.ql
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/LocalFlow.expected
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/LocalFlow.ql
create mode 100644 go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/test.go
diff --git a/go/ql/consistency-queries/VariableCaptureConsistency.ql b/go/ql/consistency-queries/VariableCaptureConsistency.ql
new file mode 100644
index 000000000000..412474627cf2
--- /dev/null
+++ b/go/ql/consistency-queries/VariableCaptureConsistency.ql
@@ -0,0 +1 @@
+import semmle.go.dataflow.internal.VariableCapture::Flow::ConsistencyChecks
diff --git a/go/ql/lib/change-notes/2026-10-21-variable-capture.md b/go/ql/lib/change-notes/2026-10-21-variable-capture.md
new file mode 100644
index 000000000000..3a5fc7ca0622
--- /dev/null
+++ b/go/ql/lib/change-notes/2026-10-21-variable-capture.md
@@ -0,0 +1,5 @@
+---
+category: minorAnalysis
+---
+* Data flow through captured variables now uses the shared variable capture library, keeping captures associated with their closure objects rather than using context-insensitive jumps.
+* `DataFlow::ArgumentNode` now includes the closure argument at position `-2` for calls through function values.
diff --git a/go/ql/lib/semmle/go/dataflow/internal/DataFlowDispatch.qll b/go/ql/lib/semmle/go/dataflow/internal/DataFlowDispatch.qll
index 80f9a8db0a1a..71c622c4105e 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/DataFlowDispatch.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/DataFlowDispatch.qll
@@ -40,9 +40,6 @@ private predicate hasUnknownSource(DataFlow::Node nd) {
(
not basicLocalFlowStep(_, nd)
or
- // Uncertain writes may also receive values through non-local capture flow.
- nd.(DataFlow::SsaNode).getDefinition() instanceof SsaUncertainWrite
- or
exists(DataFlow::Node pred | basicLocalFlowStep(pred, nd) and hasUnknownSource(pred))
)
}
@@ -124,7 +121,7 @@ DataFlowCallable viableCallable(DataFlowCall ma) {
}
private int parameterPosition() {
- result = [-1 .. any(DataFlowCallable c).getType().getNumParameter()]
+ result = [-2 .. any(DataFlowCallable c).getType().getNumParameter()]
}
/** A parameter position represented by an integer. */
diff --git a/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll b/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
index 2d96515f1596..f3d2880f3f8a 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
@@ -9,6 +9,7 @@ private import semmle.go.dataflow.SsaImpl as SsaImpl
private import DataFlowPrivate
private import FlowSummaryImpl as FlowSummaryImpl
private import semmle.go.dataflow.ExternalFlow
+private import VariableCapture as VariableCapture
private module SsaFlow = SsaImpl::DataFlowIntegration;
@@ -27,7 +28,11 @@ private newtype TNode =
} or
MkSliceElementNode(SliceExpr se) or
MkFlowSummaryNode(FlowSummaryImpl::Private::SummaryNode sn) or
- MkDefaultPostUpdateNode(IR::Instruction insn) { insnHasPostUpdateNode(insn) }
+ MkDefaultPostUpdateNode(IR::Instruction insn) { insnHasPostUpdateNode(insn) } or
+ MkCaptureNode(VariableCapture::Flow::SynthesizedCaptureNode capture) or
+ MkCapturedVariablesParameterNode(FuncLit function) {
+ exists(VariableCapture::Flow::ThisParameterNode parameter | parameter.getCallable() = function)
+ }
/** Nodes intended for only use inside the data-flow libraries. */
module Private {
@@ -202,6 +207,69 @@ module Private {
none()
}
}
+
+ /** A synthesized access to captured storage. */
+ class CaptureNode extends Node, MkCaptureNode {
+ VariableCapture::Flow::SynthesizedCaptureNode getSynthesizedCaptureNode() {
+ this = MkCaptureNode(result)
+ }
+
+ override ControlFlow::Root getRoot() {
+ result = this.getSynthesizedCaptureNode().getEnclosingCallable()
+ }
+
+ override BasicBlock getBasicBlock() {
+ result = this.getSynthesizedCaptureNode().getBasicBlock()
+ }
+
+ override Type getType() {
+ exists(VariableCapture::CapturedVariable v |
+ this.getSynthesizedCaptureNode().isVariableAccess(v) and
+ result = v.getType()
+ )
+ or
+ this.getSynthesizedCaptureNode().isInstanceAccess() and
+ result = this.getRoot().(FuncLit).getType()
+ }
+
+ override string getNodeKind() { result = "captured variable" }
+
+ override string toString() { result = this.getSynthesizedCaptureNode().toString() }
+
+ override Location getLocation() { result = this.getSynthesizedCaptureNode().getLocation() }
+ }
+
+ /** The closure object passed implicitly when invoking a function literal that captures variables. */
+ class CapturedVariablesParameterNode extends ParameterNode, MkCapturedVariablesParameterNode {
+ FuncLit getFunction() { this = MkCapturedVariablesParameterNode(result) }
+
+ override predicate isParameterOf(DataFlowCallable c, int i) {
+ c.asCallable().getFuncDef() = this.getFunction() and i = -2
+ }
+
+ override ControlFlow::Root getRoot() { result = this.getFunction() }
+
+ override Type getType() { result = this.getFunction().getType() }
+
+ override string getNodeKind() { result = "captured variables parameter" }
+
+ override string toString() { result = "captured variables" }
+
+ override Location getLocation() { result = this.getFunction().getLocation() }
+ }
+
+ private class CapturePostUpdateNode extends CaptureNode, PostUpdateNode {
+ CaptureNode pre;
+
+ CapturePostUpdateNode() {
+ VariableCapture::Flow::capturePostUpdateNode(this.getSynthesizedCaptureNode(),
+ pre.getSynthesizedCaptureNode())
+ }
+
+ override Node getPreUpdateNode() { result = pre }
+
+ override string toString() { result = pre.toString() + " [postupdate]" }
+ }
}
/** Nodes intended for use outside the data-flow libraries. */
@@ -564,10 +632,13 @@ module Public {
* pointless recomputation of `getACallee()` each recursive iteration.
*/
private DataFlow::Node getACalleeSource(DataFlow::CallNode cn) {
- result = cn.getCalleeNode() or
- basicLocalFlowStep(result, getACalleeSource(cn)) or
- jumpStep(result, getACalleeSource(cn)) or
- result.asExpr() = getACalleeSource(cn).asExpr().(GenericFunctionInstantiationExpr).getBase()
+ result = cn.getCalleeNode()
+ or
+ basicLocalFlowStep(result, getACalleeSource(cn))
+ or
+ jumpStep(result, getACalleeSource(cn))
+ or
+ additionalLambdaFlowStep(result, getACalleeSource(cn), _)
}
/** A data flow node that represents a call. */
@@ -976,6 +1047,12 @@ module Public {
}
private predicate insnDirectlyHasSyncPostUpdateNode(IR::Instruction insn) {
+ exists(CallExpr call |
+ not exists(DeferStmt d | d.getCall() = call) and
+ isLambdaCall(call) and
+ insn = IR::evalExprInstruction(CfgImpl::unwrapCallee(call.getCalleeExpr()))
+ )
+ or
exists(AddressExpr ae |
not isOnDeferSavedAccessPath(_, IR::evalExprInstruction(ae)) and
(
@@ -1072,7 +1149,7 @@ module Public {
}
/**
- * A data-flow node that occurs as an argument in a call, including receiver arguments.
+ * A data-flow node that occurs as an argument in a call, including receiver and closure arguments.
*/
class ArgumentNode extends Node {
CallNode c;
@@ -1083,7 +1160,8 @@ module Public {
/**
* Holds if this argument occurs at the given position in the given call.
*
- * The receiver argument is considered to have index `-1`.
+ * The receiver argument has index `-1`. The closure object of a call through
+ * a function value has index `-2`.
*
* Note that we currently do not track receiver arguments into calls to interface methods.
*/
diff --git a/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll b/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll
index 7c8bd675e69b..e2400bb01e8d 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll
@@ -11,6 +11,7 @@ private import FlowSummaryImpl as FlowSummaryImpl
private import semmle.go.dataflow.FlowSummary as FlowSummary
private import semmle.go.dataflow.ExternalFlow
private import codeql.util.Unit
+private import VariableCapture as VariableCapture
import DataFlowNodes::Private
private newtype TReturnKind =
@@ -45,6 +46,26 @@ OutNode getAnOutNode(DataFlowCall call, ReturnKind kind) {
)
}
+/** Holds if a type assertion carries the asserted value from `nodeFrom` to `nodeTo`. */
+predicate typeAssertionFlowStep(IR::Instruction nodeFrom, IR::Instruction nodeTo) {
+ exists(IR::Instruction evalAssert, TypeAssertExpr assert |
+ nodeFrom = IR::evalExprInstruction(assert.getExpr().stripParens()) and
+ evalAssert = IR::evalExprInstruction(assert) and
+ if exists(IR::extractTupleElement(evalAssert, _))
+ then nodeTo = IR::extractTupleElement(evalAssert, 0)
+ else nodeTo = evalAssert
+ )
+}
+
+/** Holds if ordinary SSA carries variable `v` from `nodeFrom` to `nodeTo`. */
+predicate ssaLocalFlowStep(SsaSourceVariable v, Node nodeFrom, Node nodeTo) {
+ exists(SsaImpl::DataFlowIntegration::Node pred, SsaImpl::DataFlowIntegration::Node succ |
+ SsaImpl::DataFlowIntegration::localFlowStep(v, pred, succ, _) and
+ nodeFrom = getNodeFromSsaNode(pred) and
+ nodeTo = getNodeFromSsaNode(succ)
+ )
+}
+
/**
* Holds if data flows from `nodeFrom` to `nodeTo` in exactly one local
* (intra-procedural) step, not taking function models into account.
@@ -59,23 +80,15 @@ predicate basicLocalFlowStep(Node nodeFrom, Node nodeTo) {
nodeTo = exprNode(succ)
)
or
- // Type assertion: if in the context `checked, ok := e.(*Type)` (in which
- // case tuple-extraction instructions exist), flow from `e` to `e.(*Type)[0]`;
- // otherwise flow from `e` to `e.(*Type)`.
- exists(IR::Instruction evalAssert, TypeAssertExpr assert |
- nodeFrom.asExpr() = assert.getExpr() and
- evalAssert = IR::evalExprInstruction(assert) and
- if exists(IR::extractTupleElement(evalAssert, _))
- then nodeTo.asInstruction() = IR::extractTupleElement(evalAssert, 0)
- else nodeTo.asInstruction() = evalAssert
- )
+ typeAssertionFlowStep(nodeFrom.asInstruction(), nodeTo.asInstruction())
or
- exists(SsaImpl::DataFlowIntegration::Node pred, SsaImpl::DataFlowIntegration::Node succ |
- SsaImpl::DataFlowIntegration::localFlowStep(_, pred, succ, _) and
- nodeFrom = getNodeFromSsaNode(pred) and
- nodeTo = getNodeFromSsaNode(succ)
+ exists(SsaSourceVariable v |
+ not v instanceof VariableCapture::CapturedVariable and
+ ssaLocalFlowStep(v, nodeFrom, nodeTo)
)
or
+ VariableCapture::localFlowStep(nodeFrom, nodeTo)
+ or
exists(SsaImpl::TempDataFlowIntegration::Node pred, SsaImpl::TempDataFlowIntegration::Node succ |
SsaImpl::TempDataFlowIntegration::localFlowStep(_, pred, succ, _) and
nodeFrom = getNodeFromTempSsaNode(pred) and
@@ -243,35 +256,6 @@ predicate jumpStep(Node n1, Node n2) {
isValueEntityRead(v, n2)
)
or
- exists(SsaExplicitWrite def, SsaUncertainWrite succ |
- succ.getSourceVariable() = def.getSourceVariable() and
- n2 = ssaNode(succ)
- |
- not SsaImpl::firstUse(def, _) and n1 = ssaNode(def)
- or
- exists(IR::Instruction lastUse |
- exists(IR::Instruction firstUse |
- SsaImpl::firstUse(def, firstUse) and lastUse = getAnAdjacentUse*(firstUse)
- ) and
- not exists(getAnAdjacentUse(lastUse))
- |
- n1 = instructionNode(lastUse) or
- n1.(DataFlow::PostUpdateNode).getPreUpdateNode() = instructionNode(lastUse)
- )
- or
- exists(DeferStmt d, IR::Instruction anc |
- DataFlow::isOnDeferSavedAccessPath(d, anc) and
- n1.(DataFlow::PostUpdateNode).getPreUpdateNode().asInstruction() = anc and
- (
- not deferMutatesInPlace(d, anc) and
- insnReadsSsaDef(anc).getAnUltimateDefinition() = def
- or
- deferMutatesInPlace(d, anc) and
- anc.reads(def.getSourceVariable())
- )
- )
- )
- or
// If a channel-typed field is referenced exactly once in the context of
// a send statement and once in a receive expression, assume the two are linked.
exists(
@@ -314,6 +298,8 @@ predicate storeStep(Node node1, ContentSet cs, Node node2) {
c = any(DataFlow::PointerContent pc | pc.getPointerType() = node2.getType())
or
containerStoreStep(node1, node2, c)
+ or
+ VariableCapture::storeStep(node1, c, node2)
)
or
FlowSummaryImpl::Private::Steps::summaryStoreStep(node1.(FlowSummaryNode).getSummaryNode(), cs,
@@ -337,6 +323,8 @@ predicate readStep(Node node1, ContentSet cs, Node node2) {
)
or
containerReadStep(node1, node2, c)
+ or
+ VariableCapture::readStep(node1, c, node2)
)
or
FlowSummaryImpl::Private::Steps::summaryReadStep(node1.(FlowSummaryNode).getSummaryNode(), cs,
@@ -351,14 +339,11 @@ predicate readStep(Node node1, ContentSet cs, Node node2) {
* Holds if values stored inside content `c` are cleared at node `n`.
*/
predicate clearsContent(Node n, ContentSet c) {
- // Because our post-update nodes are shared between multiple pre-update
- // nodes, attempting to clear content causes summary stores into arg in
- // particular to malfunction.
- none()
- // c instanceof FieldContent and
- // FlowSummaryImpl::Private::Steps::summaryStoresIntoArg(c, n)
- // or
- // FlowSummaryImpl::Private::Steps::summaryClearsContent(n, c)
+ // TODO: Add summaryClearsContent for FlowSummaryNodes and clearing for definite field
+ // overwrites. First establish with regression tests that use-use flow cannot bypass
+ // summary clearing via pre-update nodes, and that overwrite rules only clear content
+ // that is definitely replaced, rather than merely stored into.
+ VariableCapture::clearsContent(n, c.asOneContent())
}
/**
@@ -471,7 +456,7 @@ class DataFlowCall extends Expr {
/**
* Gets the nth argument for this call.
*/
- Node getArgument(int n) { result = call.getArgument(n) }
+ ArgumentNode getArgument(int n) { result.argumentOf(this, n) }
/** Gets the data flow node corresponding to this call. */
ExprNode getNode() { result = call }
@@ -551,15 +536,28 @@ predicate forceHighPrecision(Content c) {
c instanceof ArrayContent or c instanceof CollectionContent
}
+/** Holds if `call` invokes a function value rather than a named function or method. */
+predicate isLambdaCall(CallExpr call) { not exists(call.getTarget()) }
+
/**
* Gets the `i`th argument of call `c`, where the receiver of a method call
- * counts as argument -1.
+ * counts as argument -1 and the closure object of a lambda call counts as argument -2.
*/
Node getArgument(CallNode c, int i) {
result = c.getArgument(i)
or
result = c.(MethodCallNode).getReceiver() and
i = -1
+ or
+ isLambdaCall(c.getCall()) and
+ result = c.getCalleeNode() and
+ i = -2
+}
+
+/** Holds if `n` is an implementation node used only for inter-procedural capture flow. */
+predicate isInternalCaptureNode(Node n) {
+ n instanceof CaptureNode or
+ n instanceof CapturedVariablesParameterNode
}
/** Holds if `n` should be hidden from path explanations. */
@@ -577,18 +575,44 @@ predicate nodeIsHidden(Node n) {
n.(PostUpdateNode).getPreUpdateNode().asInstruction() instanceof IR::DeferReadInstruction
or
n.asInstruction() instanceof IR::ReadUnnamedResultInstruction
+ or
+ isInternalCaptureNode(n)
}
class LambdaCallKind = Unit;
/** Holds if `creation` is an expression that creates a lambda of kind `kind` for `c`. */
-predicate lambdaCreation(Node creation, LambdaCallKind kind, DataFlowCallable c) { none() }
+predicate lambdaCreation(Node creation, LambdaCallKind kind, DataFlowCallable c) {
+ exists(Callable callable | callable = [c.asCallable(), c.asSummarizedCallable()] |
+ creation.asExpr() = callable.asFuncLit()
+ or
+ creation = callable.asFunction().getARead()
+ or
+ exists(Method declared, Method actual |
+ creation = declared.getARead() and
+ actual.implements(declared) and
+ callable.asFunction() = actual
+ )
+ ) and
+ exists(kind)
+}
/** Holds if `call` is a lambda call of kind `kind` where `receiver` is the lambda expression. */
-predicate lambdaCall(DataFlowCall call, LambdaCallKind kind, Node receiver) { none() }
+predicate lambdaCall(DataFlowCall call, LambdaCallKind kind, Node receiver) {
+ isLambdaCall(call.(CallExpr)) and
+ receiver = getArgument(call.getNode(), -2) and
+ exists(kind)
+}
/** Extra data-flow steps needed for lambda flow analysis. */
-predicate additionalLambdaFlowStep(Node nodeFrom, Node nodeTo, boolean preservesValue) { none() }
+predicate additionalLambdaFlowStep(Node nodeFrom, Node nodeTo, boolean preservesValue) {
+ (
+ VariableCapture::flowInsensitiveStep(nodeFrom, nodeTo)
+ or
+ nodeFrom.asExpr() = nodeTo.asExpr().(GenericFunctionInstantiationExpr).getBase()
+ ) and
+ preservesValue = true
+}
predicate knownSourceModel(Node source, string model) { sourceNode(source, _, model) }
@@ -604,6 +628,9 @@ class DataFlowSecondLevelScope = Unit;
* by default as a heuristic.
*/
predicate allowParameterReturnInSelf(ParameterNode p) {
+ VariableCapture::Flow::heuristicAllowInstanceParameterReturnInSelf(p.(CapturedVariablesParameterNode)
+ .getFunction())
+ or
exists(DataFlowCallable c, int pos |
p.isParameterOf(c, pos) and
FlowSummaryImpl::Private::summaryAllowParameterReturnInSelf(c.asSummarizedCallable(), pos)
diff --git a/go/ql/lib/semmle/go/dataflow/internal/DataFlowUtil.qll b/go/ql/lib/semmle/go/dataflow/internal/DataFlowUtil.qll
index 27c061349aa1..255554c93754 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/DataFlowUtil.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/DataFlowUtil.qll
@@ -13,6 +13,7 @@ private import semmle.go.dataflow.SsaImpl as SsaImpl
private import DataFlowPrivate
private import FlowSummaryImpl as FlowSummaryImpl
private import codeql.util.Unit
+private import VariableCapture as VariableCapture
import DataFlowNodes::Public
/**
@@ -119,14 +120,20 @@ predicate isReturnedWithError(Node node) {
/**
* Holds if data flows from `nodeFrom` to `nodeTo` in exactly one local
- * (intra-procedural) step.
+ * (intra-procedural) step, excluding internal capture-storage nodes.
*/
predicate localFlowStep(Node nodeFrom, Node nodeTo) {
- simpleLocalFlowStep(nodeFrom, nodeTo, _)
- or
- // Simple flow through library code is included in the exposed local
- // step relation, even though flow is technically inter-procedural
- FlowSummaryImpl::Private::Steps::summaryThroughStepValue(nodeFrom, nodeTo, _)
+ not isInternalCaptureNode(nodeFrom) and
+ not isInternalCaptureNode(nodeTo) and
+ (
+ simpleLocalFlowStep(nodeFrom, nodeTo, _)
+ or
+ exists(VariableCapture::CapturedVariable v | ssaLocalFlowStep(v, nodeFrom, nodeTo))
+ or
+ // Simple flow through library code is included in the exposed local
+ // step relation, even though flow is technically inter-procedural
+ FlowSummaryImpl::Private::Steps::summaryThroughStepValue(nodeFrom, nodeTo, _)
+ )
}
/**
@@ -162,7 +169,8 @@ private newtype TContent =
TPointerContent(PointerType p) or
TMapKeyContent() or
TMapValueContent() or
- TSyntheticFieldContent(SyntheticField s)
+ TSyntheticFieldContent(SyntheticField s) or
+ TCapturedVariableContent(VariableCapture::CapturedVariable v)
/**
* A reference contained in an object. Examples include instance fields, the
@@ -247,6 +255,20 @@ class SyntheticFieldContent extends Content, TSyntheticFieldContent {
override string toString() { result = s.toString() }
}
+/** A variable stored in a closure object. */
+class CapturedVariableContent extends Content, TCapturedVariableContent {
+ VariableCapture::CapturedVariable v;
+
+ CapturedVariableContent() { this = TCapturedVariableContent(v) }
+
+ /** Gets the captured variable. */
+ VariableCapture::CapturedVariable getVariable() { result = v }
+
+ override string toString() { result = "captured " + v.getName() }
+
+ override Location getLocation() { result = v.getLocation() }
+}
+
private newtype TContentSet =
TOneContent(Content c) or
TAllContent()
diff --git a/go/ql/lib/semmle/go/dataflow/internal/TaintTrackingUtil.qll b/go/ql/lib/semmle/go/dataflow/internal/TaintTrackingUtil.qll
index fcecc001845c..5bed3605a2fe 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/TaintTrackingUtil.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/TaintTrackingUtil.qll
@@ -30,14 +30,19 @@ predicate localExprTaint(Expr src, Expr sink) {
}
/**
- * Holds if taint can flow in one local step from `src` to `sink`.
+ * Holds if taint can flow in one local step from `src` to `sink`,
+ * excluding internal capture-storage nodes.
*/
predicate localTaintStep(DataFlow::Node src, DataFlow::Node sink) {
- DataFlow::localFlowStep(src, sink) or
- localAdditionalTaintStep(src, sink, _) or
- // Simple flow through library code is included in the exposed local
- // step relation, even though flow is technically inter-procedural
- FlowSummaryImpl::Private::Steps::summaryThroughStepTaint(src, sink, _)
+ not DataFlowPrivate::isInternalCaptureNode(src) and
+ not DataFlowPrivate::isInternalCaptureNode(sink) and
+ (
+ DataFlow::localFlowStep(src, sink) or
+ localAdditionalTaintStep(src, sink, _) or
+ // Simple flow through library code is included in the exposed local
+ // step relation, even though flow is technically inter-procedural
+ FlowSummaryImpl::Private::Steps::summaryThroughStepTaint(src, sink, _)
+ )
}
private Type getElementType(Type containerType) {
diff --git a/go/ql/lib/semmle/go/dataflow/internal/VariableCapture.qll b/go/ql/lib/semmle/go/dataflow/internal/VariableCapture.qll
new file mode 100644
index 000000000000..0307e9deb790
--- /dev/null
+++ b/go/ql/lib/semmle/go/dataflow/internal/VariableCapture.qll
@@ -0,0 +1,208 @@
+/** Provides flow through variables captured by Go function literals. */
+overlay[local?]
+module;
+
+private import go
+private import semmle.go.controlflow.ControlFlowGraphImpl
+private import semmle.go.dataflow.SsaImpl as SsaImpl
+private import codeql.dataflow.VariableCapture as Shared
+private import DataFlowPrivate
+private import DataFlowUtil
+
+private predicate flowInsensitiveInstructionStep(IR::Instruction nodeFrom, IR::Instruction nodeTo) {
+ exists(SsaSourceVariable v, IR::WriteInstruction write |
+ v.isCaptured() and
+ write.writes(v, nodeFrom) and
+ nodeTo.reads(v)
+ )
+}
+
+/**
+ * Holds if a captured variable may carry a function value from `nodeFrom` to `nodeTo`.
+ * Only used for discovering call targets, not ordinary value flow.
+ */
+predicate flowInsensitiveStep(Node nodeFrom, Node nodeTo) {
+ flowInsensitiveInstructionStep(nodeFrom.asInstruction(), nodeTo.asInstruction())
+ or
+ flowInsensitiveInstructionStep(IR::initParamInstruction(nodeFrom.asParameter()),
+ nodeTo.asInstruction())
+}
+
+bindingset[outer, inner]
+pragma[inline_late]
+private predicate strictlyEnclosesFunction(ControlFlow::Root outer, ControlFlow::Root inner) {
+ outer = inner.getEnclosingFunction+()
+}
+
+private predicate closureSsaDef(SsaExplicitWrite write, SsaDefinition def) {
+ reachesClosureInstruction(write.getDefinition().getRhs()) and
+ def = write
+ or
+ exists(SsaDefinition prev | closureSsaDef(write, prev) |
+ prev = def.(SsaPhiDefinition).getAnInput() or
+ prev = def.(SsaUncertainWrite).getPriorDefinition()
+ )
+}
+
+bindingset[def]
+pragma[inline_late]
+private predicate ssaDefReachesReadNode(SsaDefinition def, IR::Instruction read) {
+ exists(SsaSourceVariable v, BasicBlock bb, int i |
+ v = def.getSourceVariable() and
+ SsaImpl::ssaDefReachesRead(v, def, bb, i) and
+ SsaImpl::useAt(bb, i, v) and
+ read = bb.getNode(i)
+ )
+}
+
+private predicate closureDirectInstructionStep(IR::Instruction nodeFrom, IR::Instruction nodeTo) {
+ exists(SsaDefinition def, SsaExplicitWrite write |
+ closureSsaDef(write, def) and
+ nodeFrom = write.getDefinition().getRhs() and
+ ssaDefReachesReadNode(def, nodeTo)
+ )
+ or
+ reachesClosureInstruction(nodeFrom) and
+ (
+ typeAssertionFlowStep(nodeFrom, nodeTo)
+ or
+ exists(ConversionExpr conv |
+ nodeFrom = IR::evalExprInstruction(conv.getOperand().stripParens()) and
+ nodeTo = IR::evalExprInstruction(conv)
+ )
+ )
+}
+
+private predicate closureCapturedInstructionStep(IR::Instruction nodeFrom, IR::Instruction nodeTo) {
+ reachesClosureInstruction(nodeFrom) and
+ flowInsensitiveInstructionStep(nodeFrom, nodeTo) and
+ strictlyEnclosesFunction(nodeFrom.getRoot(), nodeTo.getRoot())
+}
+
+private predicate reachesClosureInstruction(IR::Instruction insn) {
+ insn.(IR::EvalInstruction).getExpr() instanceof FuncLit
+ or
+ closureDirectInstructionStep(_, insn)
+ or
+ closureCapturedInstructionStep(_, insn)
+}
+
+private module CaptureInput implements Shared::InputSig {
+ class Callable extends ControlFlow::Root {
+ predicate isConstructor() { none() }
+ }
+
+ Callable basicBlockGetEnclosingCallable(BasicBlock bb) { result = bb.getScope() }
+
+ class CapturedVariable extends SsaSourceVariable {
+ CapturedVariable() { this.isCaptured() }
+
+ Callable getCallable() { result = this.getDeclaringFunction() }
+ }
+
+ class CapturedParameter extends CapturedVariable instanceof Parameter { }
+
+ class Expr extends IR::Instruction {
+ predicate hasCfgNode(BasicBlock bb, int i) { this = bb.getNode(i) }
+ }
+
+ class VariableWrite extends IR::WriteInstruction {
+ CapturedVariable v;
+
+ VariableWrite() {
+ this.writes(v, _) and
+ not this instanceof IR::InitParameterInstruction
+ }
+
+ CapturedVariable getVariable() { result = v }
+
+ predicate hasCfgNode(BasicBlock bb, int i) { this = bb.getNode(i) }
+ }
+
+ class VariableRead extends Expr {
+ CapturedVariable v;
+
+ VariableRead() { this.reads(v) }
+
+ CapturedVariable getVariable() { result = v }
+ }
+
+ private predicate closureFlowStep(IR::Instruction nodeFrom, IR::Instruction nodeTo) {
+ closureDirectInstructionStep(nodeFrom, nodeTo)
+ or
+ closureCapturedInstructionStep(nodeFrom, nodeTo)
+ }
+
+ private predicate closureFlowReaches(ClosureExpr ce, Expr e) {
+ closureFlowStep(ce, e)
+ or
+ exists(Expr mid |
+ closureFlowReaches(ce, mid) and
+ closureFlowStep(mid, e)
+ )
+ }
+
+ private predicate escapesCurrentCallable(IR::Instruction insn) {
+ reachesClosureInstruction(insn) and
+ exists(CapturedVariable v, IR::WriteInstruction write |
+ write.writes(v, insn) and
+ v.getDeclaringFunction() != insn.getRoot()
+ )
+ }
+
+ class ClosureExpr extends Expr {
+ ClosureExpr() { this.(IR::EvalInstruction).getExpr() instanceof FuncLit }
+
+ predicate hasBody(Callable body) { body = this.(IR::EvalInstruction).getExpr() }
+
+ predicate hasAliasedAccess(Expr e) {
+ closureFlowReaches(this, e) and
+ (
+ not closureFlowStep(e, _)
+ or
+ escapesCurrentCallable(e)
+ )
+ }
+ }
+}
+
+class CapturedVariable = CaptureInput::CapturedVariable;
+
+module Flow = Shared::Flow;
+
+private Flow::ClosureNode asClosureNode(Node n) {
+ result = n.(CaptureNode).getSynthesizedCaptureNode()
+ or
+ result.(Flow::ExprNode).getExpr() = n.asInstruction()
+ or
+ exists(IR::Instruction insn |
+ insn = n.(PostUpdateNode).getPreUpdateNode().asInstruction() and
+ DataFlow::insnHasSyncPostUpdateNode(insn) and
+ result.(Flow::ExprPostUpdateNode).getExpr() = insn
+ )
+ or
+ result.(Flow::ParameterNode).getParameter() = n.asParameter()
+ or
+ result.(Flow::ThisParameterNode).getCallable() = n.(CapturedVariablesParameterNode).getFunction()
+ or
+ exists(IR::WriteInstruction vw |
+ vw = pragma[only_bind_out](result.(Flow::VariableWriteSourceNode).getVariableWrite()) and
+ vw.getRhs() = n.asInstruction()
+ )
+}
+
+predicate storeStep(Node nodeFrom, CapturedVariableContent c, Node nodeTo) {
+ Flow::storeStep(asClosureNode(nodeFrom), c.getVariable(), asClosureNode(nodeTo))
+}
+
+predicate readStep(Node nodeFrom, CapturedVariableContent c, Node nodeTo) {
+ Flow::readStep(asClosureNode(nodeFrom), c.getVariable(), asClosureNode(nodeTo))
+}
+
+predicate clearsContent(Node n, CapturedVariableContent c) {
+ Flow::clearsContent(asClosureNode(n), c.getVariable())
+}
+
+predicate localFlowStep(Node nodeFrom, Node nodeTo) {
+ Flow::localFlowStep(asClosureNode(nodeFrom), asClosureNode(nodeTo))
+}
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/PostUpdateNodes/test.expected b/go/ql/test/library-tests/semmle/go/dataflow/PostUpdateNodes/test.expected
index 1ae48fb09b08..7f23c2792a99 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/PostUpdateNodes/test.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/PostUpdateNodes/test.expected
@@ -22,7 +22,9 @@
| test.go:29:6:29:6 | a | test.go:29:6:29:6 | a [postupdate] |
| test.go:30:2:30:2 | c | test.go:30:2:30:2 | c [postupdate] |
| test.go:30:7:30:7 | a | test.go:30:7:30:7 | a [postupdate] |
+| test.go:35:2:35:2 | f | test.go:35:2:35:2 | f [postupdate] |
| test.go:35:4:35:4 | a | test.go:35:4:35:4 | a [postupdate] |
+| test.go:36:2:36:3 | fp | test.go:36:2:36:3 | fp [postupdate] |
| test.go:36:5:36:5 | a | test.go:36:5:36:5 | a [postupdate] |
| test.go:40:2:40:2 | c | test.go:40:2:40:2 | c [postupdate] |
| test.go:40:2:40:2 | implicit-deref c | test.go:40:2:40:2 | implicit-deref c [postupdate] |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodes.expected b/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodes.expected
index f02230e95de8..c5db2c603e2c 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodes.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodes.expected
@@ -14,6 +14,13 @@ edges
| main.go:38:2:38:18 | SSA def(value) | main.go:40:8:40:12 | value | provenance | |
| main.go:38:2:38:18 | SSA def(value) | main.go:43:7:43:11 | value | provenance | |
| main.go:38:11:38:18 | call to source | main.go:38:2:38:18 | SSA def(value) | provenance | |
+| main.go:58:11:58:18 | call to source | main.go:60:2:60:4 | set [postupdate] [captured value] | provenance | |
+| main.go:60:2:60:4 | set [postupdate] [captured value] | main.go:61:7:61:11 | value | provenance | |
+| main.go:65:11:65:18 | call to source | main.go:69:7:69:11 | value | provenance | |
+| main.go:65:11:65:18 | call to source | main.go:69:7:69:11 | value | provenance | |
+| main.go:69:7:69:11 | value | main.go:70:2:70:5 | read [captured value] | provenance | |
+| main.go:70:2:70:5 | read [captured value] | main.go:67:8:67:12 | value | provenance | |
+| main.go:74:11:74:18 | call to source | main.go:81:7:81:11 | value | provenance | |
nodes
| main.go:10:2:10:18 | SSA def(value) | semmle.label | SSA def(value) |
| main.go:10:11:10:18 | call to source | semmle.label | call to source |
@@ -31,6 +38,16 @@ nodes
| main.go:38:11:38:18 | call to source | semmle.label | call to source |
| main.go:40:8:40:12 | value | semmle.label | value |
| main.go:43:7:43:11 | value | semmle.label | value |
+| main.go:58:11:58:18 | call to source | semmle.label | call to source |
+| main.go:60:2:60:4 | set [postupdate] [captured value] | semmle.label | set [postupdate] [captured value] |
+| main.go:61:7:61:11 | value | semmle.label | value |
+| main.go:65:11:65:18 | call to source | semmle.label | call to source |
+| main.go:67:8:67:12 | value | semmle.label | value |
+| main.go:69:7:69:11 | value | semmle.label | value |
+| main.go:69:7:69:11 | value | semmle.label | value |
+| main.go:70:2:70:5 | read [captured value] | semmle.label | read [captured value] |
+| main.go:74:11:74:18 | call to source | semmle.label | call to source |
+| main.go:81:7:81:11 | value | semmle.label | value |
subpaths
#select
| main.go:12:8:12:12 | value | main.go:10:11:10:18 | call to source | main.go:12:8:12:12 | value | neverSkip |
@@ -41,3 +58,7 @@ subpaths
| main.go:31:8:31:12 | value | main.go:26:11:26:18 | call to source | main.go:31:8:31:12 | value | neverSkip |
| main.go:40:8:40:12 | value | main.go:38:11:38:18 | call to source | main.go:40:8:40:12 | value | neverSkip |
| main.go:43:7:43:11 | value | main.go:38:11:38:18 | call to source | main.go:43:7:43:11 | value | neverSkip |
+| main.go:61:7:61:11 | value | main.go:58:11:58:18 | call to source | main.go:61:7:61:11 | value | neverSkip |
+| main.go:67:8:67:12 | value | main.go:65:11:65:18 | call to source | main.go:67:8:67:12 | value | neverSkip |
+| main.go:69:7:69:11 | value | main.go:65:11:65:18 | call to source | main.go:69:7:69:11 | value | neverSkip |
+| main.go:81:7:81:11 | value | main.go:74:11:74:18 | call to source | main.go:81:7:81:11 | value | neverSkip |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodes.ql b/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodes.ql
index 9a9e817a7b8b..ccd3ba4bd187 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodes.ql
+++ b/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodes.ql
@@ -4,14 +4,19 @@
import go
+private predicate inTestCallable(DataFlow::Node node) {
+ node.getRoot().getEnclosingFunction*().(FuncDecl).getFunction().getName() =
+ ["readMerge", "writeMerge", "loop", "capturedWrite", "capturedRead", "uncertainUpdate"]
+}
+
private predicate sourceNode(DataFlow::Node node) {
node.(DataFlow::CallNode).getTarget().getName() = "source" and
- node.getEnclosingCallable().getName() = ["readMerge", "writeMerge", "loop"]
+ inTestCallable(node)
}
private predicate sinkNode(DataFlow::Node node) {
node = any(DataFlow::CallNode call | call.getTarget().getName() = "sink").getArgument(0) and
- node.getEnclosingCallable().getName() = ["readMerge", "writeMerge", "loop"]
+ inTestCallable(node)
}
module NeverSkipConfig implements DataFlow::ConfigSig {
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodesStateful.expected b/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodesStateful.expected
index 5334bfcb062a..1d8b4c0b0aaf 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodesStateful.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodesStateful.expected
@@ -51,6 +51,32 @@ edges
| main.go:38:11:38:18 | call to source | main.go:38:11:38:18 | call to source | provenance | Config |
| main.go:40:8:40:12 | value | main.go:40:8:40:12 | value | provenance | Config |
| main.go:43:7:43:11 | value | main.go:43:7:43:11 | value | provenance | Config |
+| main.go:58:11:58:18 | call to source | main.go:58:11:58:18 | call to source | provenance | Config |
+| main.go:58:11:58:18 | call to source | main.go:60:2:60:4 | set [postupdate] [captured value] | provenance | |
+| main.go:58:11:58:18 | call to source | main.go:60:2:60:4 | set [postupdate] [captured value] | provenance | |
+| main.go:60:2:60:4 | set [postupdate] [captured value] | main.go:61:7:61:11 | value | provenance | |
+| main.go:60:2:60:4 | set [postupdate] [captured value] | main.go:61:7:61:11 | value | provenance | |
+| main.go:60:2:60:4 | set [postupdate] [captured value] | main.go:61:7:61:11 | value | provenance | Config |
+| main.go:61:7:61:11 | value | main.go:61:7:61:11 | value | provenance | Config |
+| main.go:65:11:65:18 | call to source | main.go:65:11:65:18 | call to source | provenance | Config |
+| main.go:65:11:65:18 | call to source | main.go:69:7:69:11 | value | provenance | |
+| main.go:65:11:65:18 | call to source | main.go:69:7:69:11 | value | provenance | |
+| main.go:65:11:65:18 | call to source | main.go:69:7:69:11 | value | provenance | |
+| main.go:65:11:65:18 | call to source | main.go:69:7:69:11 | value | provenance | Config |
+| main.go:65:11:65:18 | call to source | main.go:69:7:69:11 | value | provenance | Config |
+| main.go:67:8:67:12 | value | main.go:67:8:67:12 | value | provenance | Config |
+| main.go:69:7:69:11 | value | main.go:69:7:69:11 | value | provenance | Config |
+| main.go:69:7:69:11 | value | main.go:69:7:69:11 | value | provenance | Config |
+| main.go:69:7:69:11 | value | main.go:70:2:70:5 | read [captured value] | provenance | |
+| main.go:69:7:69:11 | value | main.go:70:2:70:5 | read [captured value] | provenance | |
+| main.go:69:7:69:11 | value | main.go:70:2:70:5 | read [captured value] | provenance | Config |
+| main.go:70:2:70:5 | read [captured value] | main.go:67:8:67:12 | value | provenance | |
+| main.go:70:2:70:5 | read [captured value] | main.go:67:8:67:12 | value | provenance | |
+| main.go:74:11:74:18 | call to source | main.go:74:11:74:18 | call to source | provenance | Config |
+| main.go:74:11:74:18 | call to source | main.go:81:7:81:11 | value | provenance | |
+| main.go:74:11:74:18 | call to source | main.go:81:7:81:11 | value | provenance | |
+| main.go:74:11:74:18 | call to source | main.go:81:7:81:11 | value | provenance | Config |
+| main.go:81:7:81:11 | value | main.go:81:7:81:11 | value | provenance | Config |
nodes
| main.go:10:2:10:18 | SSA def(value) | semmle.label | SSA def(value) |
| main.go:10:2:10:18 | SSA def(value) | semmle.label | SSA def(value) |
@@ -82,6 +108,25 @@ nodes
| main.go:40:8:40:12 | value | semmle.label | value |
| main.go:43:7:43:11 | value | semmle.label | value |
| main.go:43:7:43:11 | value | semmle.label | value |
+| main.go:58:11:58:18 | call to source | semmle.label | call to source |
+| main.go:58:11:58:18 | call to source | semmle.label | call to source |
+| main.go:60:2:60:4 | set [postupdate] [captured value] | semmle.label | set [postupdate] [captured value] |
+| main.go:60:2:60:4 | set [postupdate] [captured value] | semmle.label | set [postupdate] [captured value] |
+| main.go:61:7:61:11 | value | semmle.label | value |
+| main.go:61:7:61:11 | value | semmle.label | value |
+| main.go:65:11:65:18 | call to source | semmle.label | call to source |
+| main.go:65:11:65:18 | call to source | semmle.label | call to source |
+| main.go:67:8:67:12 | value | semmle.label | value |
+| main.go:67:8:67:12 | value | semmle.label | value |
+| main.go:69:7:69:11 | value | semmle.label | value |
+| main.go:69:7:69:11 | value | semmle.label | value |
+| main.go:69:7:69:11 | value | semmle.label | value |
+| main.go:70:2:70:5 | read [captured value] | semmle.label | read [captured value] |
+| main.go:70:2:70:5 | read [captured value] | semmle.label | read [captured value] |
+| main.go:74:11:74:18 | call to source | semmle.label | call to source |
+| main.go:74:11:74:18 | call to source | semmle.label | call to source |
+| main.go:81:7:81:11 | value | semmle.label | value |
+| main.go:81:7:81:11 | value | semmle.label | value |
subpaths
#select
| main.go:12:8:12:12 | value | main.go:10:11:10:18 | call to source | main.go:12:8:12:12 | value | stateful |
@@ -92,3 +137,7 @@ subpaths
| main.go:31:8:31:12 | value | main.go:26:11:26:18 | call to source | main.go:31:8:31:12 | value | stateful |
| main.go:40:8:40:12 | value | main.go:38:11:38:18 | call to source | main.go:40:8:40:12 | value | stateful |
| main.go:43:7:43:11 | value | main.go:38:11:38:18 | call to source | main.go:43:7:43:11 | value | stateful |
+| main.go:61:7:61:11 | value | main.go:58:11:58:18 | call to source | main.go:61:7:61:11 | value | stateful |
+| main.go:67:8:67:12 | value | main.go:65:11:65:18 | call to source | main.go:67:8:67:12 | value | stateful |
+| main.go:69:7:69:11 | value | main.go:65:11:65:18 | call to source | main.go:69:7:69:11 | value | stateful |
+| main.go:81:7:81:11 | value | main.go:74:11:74:18 | call to source | main.go:81:7:81:11 | value | stateful |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodesStateful.ql b/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodesStateful.ql
index 6a6437638aff..229f5ac002d1 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodesStateful.ql
+++ b/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/HiddenNodesStateful.ql
@@ -4,14 +4,19 @@
import go
+private predicate inTestCallable(DataFlow::Node node) {
+ node.getRoot().getEnclosingFunction*().(FuncDecl).getFunction().getName() =
+ ["readMerge", "writeMerge", "loop", "capturedWrite", "capturedRead", "uncertainUpdate"]
+}
+
private predicate sourceNode(DataFlow::Node node) {
node.(DataFlow::CallNode).getTarget().getName() = "source" and
- node.getEnclosingCallable().getName() = ["readMerge", "writeMerge", "loop"]
+ inTestCallable(node)
}
private predicate sinkNode(DataFlow::Node node) {
node = any(DataFlow::CallNode call | call.getTarget().getName() = "sink").getArgument(0) and
- node.getEnclosingCallable().getName() = ["readMerge", "writeMerge", "loop"]
+ inTestCallable(node)
}
module StatefulConfig implements DataFlow::StateConfigSig {
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.expected b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.expected
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.ql b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.ql
new file mode 100644
index 000000000000..042fac250a1b
--- /dev/null
+++ b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.ql
@@ -0,0 +1,69 @@
+import go
+private import semmle.go.dataflow.internal.DataFlowPrivate as Impl
+private import semmle.go.dataflow.internal.DataFlowNodes::Private as Nodes
+import utils.test.InlineExpectationsTest
+
+module ArgumentNodesTest implements TestSig {
+ string getARelevantTag() {
+ result =
+ [
+ "closure-args", "callee-post", "closure-post", "argument-post", "syntactic-arg",
+ "receiver-post", "closure-params"
+ ]
+ }
+
+ predicate hasActualResult(Location location, string element, string tag, string value) {
+ exists(DataFlow::CallNode call |
+ call.getEnclosingCallable().getName() = "closureArgumentNodes" and
+ location = call.getLocation() and
+ element = call.toString()
+ |
+ tag = "closure-args" and
+ value =
+ count(DataFlow::ArgumentNode argument | argument.argumentOf(call.asExpr(), -2)).toString()
+ or
+ tag = "callee-post" and
+ value =
+ count(DataFlow::PostUpdateNode post | post.getPreUpdateNode() = call.getCalleeNode())
+ .toString()
+ or
+ tag = "closure-post" and
+ value =
+ count(DataFlow::PostUpdateNode post | post.getPreUpdateNode() = Impl::getArgument(call, -2))
+ .toString()
+ or
+ tag = "argument-post" and
+ call.getTarget().getName() = "callback" and
+ value =
+ count(DataFlow::PostUpdateNode post | post.getPreUpdateNode() = Impl::getArgument(call, 0))
+ .toString()
+ or
+ tag = "syntactic-arg" and
+ call.getTarget().getName() = "callback" and
+ value =
+ count(DataFlow::ArgumentNode argument |
+ argument.argumentOf(call.asExpr(), 0) and
+ argument.getACorrespondingSyntacticArgument() = call.getSyntacticArgument(0)
+ ).toString()
+ or
+ tag = "receiver-post" and
+ call instanceof DataFlow::MethodCallNode and
+ value =
+ count(DataFlow::PostUpdateNode post |
+ post.getPreUpdateNode() = call.(DataFlow::MethodCallNode).getReceiver()
+ ).toString()
+ )
+ or
+ exists(FuncLit function |
+ DataFlow::exprNode(function).getEnclosingCallable().getName() = "closureArgumentNodes" and
+ location = function.getLocation() and
+ element = function.toString() and
+ tag = "closure-params" and
+ value =
+ count(Nodes::CapturedVariablesParameterNode parameter | parameter.getFunction() = function)
+ .toString()
+ )
+ }
+}
+
+import MakeTest
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/CONSISTENCY/SsaConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/CONSISTENCY/SsaConsistency.expected
new file mode 100644
index 000000000000..3531df0a8982
--- /dev/null
+++ b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/CONSISTENCY/SsaConsistency.expected
@@ -0,0 +1,52 @@
+uselessPhiNode
+| test.go:10:1:14:1 | SSA phi(x) | 1 |
+| test.go:16:1:21:1 | SSA phi(x) | 1 |
+| test.go:32:7:32:29 | SSA phi(x) | 1 |
+| test.go:39:9:39:31 | SSA phi(x) | 1 |
+| test.go:45:1:51:1 | SSA phi(x) | 1 |
+| test.go:64:1:70:1 | SSA phi(x) | 1 |
+| test.go:72:1:78:1 | SSA phi(x) | 1 |
+| test.go:82:1:86:1 | SSA phi(x) | 1 |
+| test.go:88:1:93:1 | SSA phi(x) | 1 |
+| test.go:89:2:92:2 | SSA phi(x) | 1 |
+| test.go:120:8:120:30 | SSA phi(x) | 1 |
+| test.go:128:7:128:29 | SSA phi(x) | 1 |
+| test.go:146:1:149:1 | SSA phi(x) | 1 |
+| test.go:209:1:215:1 | SSA phi(f) | 1 |
+| test.go:209:1:215:1 | SSA phi(x) | 1 |
+| test.go:219:9:224:2 | SSA phi(f) | 1 |
+| test.go:231:9:236:2 | SSA phi(f) | 1 |
+| test.go:231:9:236:2 | SSA phi(y) | 1 |
+| test.go:252:1:257:1 | SSA phi(x) | 1 |
+| test.go:303:19:303:41 | SSA phi(x) | 1 |
+| test.go:309:1:326:1 | SSA phi(x) | 1 |
+| test.go:339:3:344:3 | SSA phi(y) | 1 |
+| test.go:352:9:359:2 | SSA phi(y) | 1 |
+| test.go:353:3:358:3 | SSA phi(y) | 1 |
+| test.go:382:9:390:2 | SSA phi(y) | 1 |
+phiWithoutTwoPriorRefs
+| test.go:10:1:14:1 | SSA phi(x) | test.go:10:1:14:1 | Exceptional Exit | test.go:11:2:11:2 | x | 1 |
+| test.go:16:1:21:1 | SSA phi(x) | test.go:16:1:21:1 | Exceptional Exit | test.go:17:2:17:2 | x | 1 |
+| test.go:32:7:32:29 | SSA phi(x) | test.go:32:7:32:29 | Exit | test.go:31:2:31:2 | x | 1 |
+| test.go:39:9:39:31 | SSA phi(x) | test.go:39:9:39:31 | Exit | test.go:38:2:38:2 | x | 1 |
+| test.go:45:1:51:1 | SSA phi(x) | test.go:45:1:51:1 | Exceptional Exit | test.go:46:2:46:2 | x | 1 |
+| test.go:64:1:70:1 | SSA phi(x) | test.go:64:1:70:1 | Exceptional Exit | test.go:65:2:65:2 | x | 1 |
+| test.go:72:1:78:1 | SSA phi(x) | test.go:72:1:78:1 | Exceptional Exit | test.go:73:2:73:2 | x | 1 |
+| test.go:82:1:86:1 | SSA phi(x) | test.go:82:1:86:1 | Exceptional Exit | test.go:83:2:83:2 | x | 1 |
+| test.go:88:1:93:1 | SSA phi(x) | test.go:88:1:93:1 | Exceptional Exit | test.go:89:9:89:9 | x | 1 |
+| test.go:89:2:92:2 | SSA phi(x) | test.go:89:2:92:2 | After range statement | test.go:89:9:89:9 | x | 1 |
+| test.go:120:8:120:30 | SSA phi(x) | test.go:120:8:120:30 | Exit | test.go:118:2:118:2 | x | 1 |
+| test.go:128:7:128:29 | SSA phi(x) | test.go:128:7:128:29 | Exit | test.go:127:24:127:24 | x | 1 |
+| test.go:146:1:149:1 | SSA phi(x) | test.go:146:1:149:1 | Exceptional Exit | test.go:147:2:147:2 | x | 1 |
+| test.go:209:1:215:1 | SSA phi(f) | test.go:209:1:215:1 | Exceptional Exit | test.go:211:2:211:2 | f | 1 |
+| test.go:209:1:215:1 | SSA phi(x) | test.go:209:1:215:1 | Exceptional Exit | test.go:210:2:210:2 | x | 1 |
+| test.go:219:9:224:2 | SSA phi(f) | test.go:219:9:224:2 | Exit | test.go:218:6:218:6 | f | 1 |
+| test.go:231:9:236:2 | SSA phi(f) | test.go:231:9:236:2 | Exit | test.go:230:6:230:6 | f | 1 |
+| test.go:231:9:236:2 | SSA phi(y) | test.go:231:9:236:2 | Exit | test.go:232:3:232:3 | y | 1 |
+| test.go:252:1:257:1 | SSA phi(x) | test.go:252:1:257:1 | Exit | test.go:253:2:253:2 | x | 1 |
+| test.go:303:19:303:41 | SSA phi(x) | test.go:303:19:303:41 | Exit | test.go:302:2:302:2 | x | 1 |
+| test.go:309:1:326:1 | SSA phi(x) | test.go:309:1:326:1 | Exceptional Exit | test.go:322:2:322:2 | x | 1 |
+| test.go:339:3:344:3 | SSA phi(y) | test.go:339:3:344:3 | After if statement | test.go:340:4:340:4 | y | 1 |
+| test.go:352:9:359:2 | SSA phi(y) | test.go:352:9:359:2 | Exit | test.go:354:4:354:4 | y | 1 |
+| test.go:353:3:358:3 | SSA phi(y) | test.go:353:3:358:3 | After if statement | test.go:354:4:354:4 | y | 1 |
+| test.go:382:9:390:2 | SSA phi(y) | test.go:382:9:390:2 | Exceptional Exit | test.go:383:3:383:3 | y | 1 |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/Flows.expected b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/Flows.expected
new file mode 100644
index 000000000000..ba92f6ffeb0d
--- /dev/null
+++ b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/Flows.expected
@@ -0,0 +1,5 @@
+testFailures
+spuriousConstructionClearing
+exposedCaptureNode
+ambiguousCapturePostUpdate
+unscopedCaptureNode
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/Flows.ql b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/Flows.ql
new file mode 100644
index 000000000000..c2279ca42298
--- /dev/null
+++ b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/Flows.ql
@@ -0,0 +1,40 @@
+import utils.test.InlineFlowTest
+import ValueFlowTest
+private import semmle.go.dataflow.internal.VariableCapture as Capture
+private import semmle.go.dataflow.internal.DataFlowUtil as Util
+private import semmle.go.dataflow.internal.DataFlowNodes::Private as Nodes
+private import semmle.go.dataflow.internal.DataFlowPrivate as PrivateFlow
+
+query predicate spuriousConstructionClearing(DataFlow::Node construction, string variable) {
+ construction.asExpr() instanceof FuncLit and
+ exists(Util::CapturedVariableContent content |
+ Capture::clearsContent(construction, content) and
+ variable = content.getVariable().getName()
+ )
+}
+
+query predicate exposedCaptureNode(string relation, DataFlow::Node node) {
+ (
+ node instanceof Nodes::CaptureNode or
+ node instanceof Nodes::CapturedVariablesParameterNode
+ ) and
+ (
+ relation = "flow" and
+ (DataFlow::localFlowStep(node, _) or DataFlow::localFlowStep(_, node))
+ or
+ relation = "taint" and
+ (TaintTracking::localTaintStep(node, _) or TaintTracking::localTaintStep(_, node))
+ )
+}
+
+query predicate ambiguousCapturePostUpdate(DataFlow::PostUpdateNode node) {
+ node instanceof Nodes::CaptureNode and
+ node.toString() = node.getPreUpdateNode().toString()
+}
+
+query predicate unscopedCaptureNode(Nodes::CaptureNode node) {
+ not exists(PrivateFlow::NodeRegion region |
+ region.contains(node) and
+ region.(BasicBlock).getScope() = node.getRoot()
+ )
+}
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/LocalFlow.expected b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/LocalFlow.expected
new file mode 100644
index 000000000000..e69de29bb2d1
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/LocalFlow.ql b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/LocalFlow.ql
new file mode 100644
index 000000000000..e0f5f898be75
--- /dev/null
+++ b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/LocalFlow.ql
@@ -0,0 +1,28 @@
+import go
+import utils.test.InlineExpectationsTest
+
+module LocalFlowTest implements TestSig {
+ string getARelevantTag() { result = ["local-flow", "local-taint"] }
+
+ predicate hasActualResult(Location location, string element, string tag, string value) {
+ exists(DataFlow::CallNode call, DataFlow::Node sink |
+ call.getEnclosingCallable().getName() = "localCapturedFlow" and
+ call.getTarget().getName() = "sink" and
+ sink = call.getArgument(0) and
+ location = sink.getLocation() and
+ element = sink.toString() and
+ tag = getARelevantTag() and
+ value =
+ count(DataFlow::CallNode source |
+ source.getTarget().getName() = "source" and
+ (
+ tag = "local-flow" and DataFlow::localFlow(source, sink)
+ or
+ tag = "local-taint" and TaintTracking::localTaint(source, sink)
+ )
+ ).toString()
+ )
+ }
+}
+
+import MakeTest
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/test.go b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/test.go
new file mode 100644
index 000000000000..0f92500c6086
--- /dev/null
+++ b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/test.go
@@ -0,0 +1,393 @@
+package capture
+
+import "strings"
+
+func source() string { return "" }
+func sink(string) {}
+
+var packageClosure = func() {}
+
+func direct() {
+ x := source()
+ f := func() { sink(x) } // $ hasValueFlow="x"
+ f()
+}
+
+func overwritten() {
+ x := source()
+ f := func() { sink(x) }
+ x = "safe"
+ f()
+}
+
+func assignedAfterCreation() {
+ x := "safe"
+ f := func() { sink(x) } // $ hasValueFlow="x"
+ x = source()
+ f()
+}
+
+func writeBack() {
+ x := "safe"
+ f := func() { x = source() }
+ f()
+ sink(x) // $ hasValueFlow="x"
+}
+
+func siblingClosures() {
+ x := "safe"
+ set := func() { x = source() }
+ get := func() { sink(x) } // $ hasValueFlow="x"
+ set()
+ get()
+}
+
+func nested() {
+ x := source()
+ f := func() func() {
+ return func() { sink(x) } // $ hasValueFlow="x"
+ }
+ f()()
+}
+
+func captureParameter(x string) func() string {
+ return func() string { return x }
+}
+
+func separateInvocations() {
+ bad := captureParameter(source())
+ good := captureParameter("safe")
+ sink(bad()) // $ hasValueFlow="call to bad"
+ sink(good())
+}
+
+func copyBetweenCaptures() {
+ x := source()
+ y := "safe"
+ f := func() { y = x }
+ f()
+ sink(y) // $ hasValueFlow="y"
+}
+
+func multipleWrites() {
+ x := source()
+ x = "safe"
+ sink(x)
+ f := func() { sink(x) }
+ f()
+}
+
+func tuple() (string, bool) { return source(), true }
+
+func tupleWrite() {
+ x, _ := tuple()
+ f := func() { sink(x) } // $ hasValueFlow="x"
+ f()
+}
+
+func rangeWrite() {
+ for _, x := range []string{source()} {
+ f := func() { sink(x) } // $ hasValueFlow="x"
+ f()
+ }
+}
+
+type receiver struct{ value string }
+
+func (r receiver) closure() func() string {
+ return func() string { return r.value }
+}
+
+func capturedReceiver() {
+ r := receiver{source()}
+ sink(r.closure()()) // $ hasValueFlow="function call"
+}
+
+func aliasedClosure(branch bool) {
+ x := "safe"
+ f := func() { sink(x) } // $ hasValueFlow="x"
+ g := func() {}
+ if branch {
+ g = f
+ }
+ x = source()
+ g()
+}
+
+func nestedWriteBack() {
+ x := "safe"
+ f := func() {
+ g := func() { x = source() }
+ g()
+ }
+ f()
+ sink(x) // $ hasValueFlow="x"
+}
+
+func capturedResult() (x string) {
+ f := func() { x = source() }
+ f()
+ return
+}
+
+func namedResult() {
+ sink(capturedResult()) // $ hasValueFlow="call to capturedResult"
+}
+
+func mutateCapturedPointer() {
+ x := &receiver{}
+ f := func() { x.value = source() }
+ f()
+ sink(x.value) // $ hasValueFlow="selection of value"
+}
+
+func callback(f func()) { f() }
+
+func passedClosure() {
+ x := source()
+ callback(func() { sink(x) }) // $ hasValueFlow="x"
+}
+
+func capturedCallee() {
+ handler := sink
+ func() {
+ handler(source()) // $ hasValueFlow="call to source"
+ }()
+}
+
+func returnedWriter() (func(string), func() string) {
+ x := "safe"
+ return func(s string) { x = s }, func() string { return x }
+}
+
+func sharedEscapedStorage() {
+ set, get := returnedWriter()
+ set(source())
+ sink(get()) // $ MISSING: hasValueFlow="call to get"
+}
+
+func apply(f func(string) string, s string) string { return f(s) }
+
+func identity(s string) string { return s }
+func constant(string) string { return "safe" }
+
+func genericIdentity[T any](s T) T { return s }
+
+func (receiver) identity(s string) string { return s }
+
+func namedAndLiteralTargets() {
+ sink(apply(func(s string) string { return s }, "safe"))
+ sink(apply(identity, source())) // $ hasValueFlow="call to apply"
+ sink(apply(constant, source()))
+ sink(apply(receiver{}.identity, source())) // $ hasValueFlow="call to apply"
+ sink(apply(genericIdentity[string], source())) // $ hasValueFlow="call to apply"
+ sink(apply(strings.Clone, source())) // $ hasValueFlow="call to apply"
+}
+
+type identityMethod interface{ identity(string) string }
+
+func interfaceMethodValue(r identityMethod) {
+ sink(apply(r.identity, source())) // $ hasValueFlow="call to apply"
+}
+
+func capturedClosureAlias() {
+ x := "safe"
+ f := func() { sink(x) } // $ hasValueFlow="x"
+ g := func() { f() }
+ x = source()
+ g()
+}
+
+func capturedCallbackAlias() {
+ x := "safe"
+ f := func() { sink(x) } // $ hasValueFlow="x"
+ g := func() { callback(f) }
+ x = source()
+ g()
+}
+
+func overwrittenCapturedClosureAlias() {
+ x := source()
+ f := func() { sink(x) }
+ g := func() { f() }
+ x = "safe"
+ g()
+}
+
+func innerClosureEscapeViaCapturedVar() {
+ var f func()
+ set := func() {
+ y := "safe"
+ g := func() { sink(y) } // $ hasValueFlow="y"
+ y = source()
+ f = g
+ }
+ set()
+ f()
+}
+
+func overwrittenInnerClosureEscapeViaCapturedVar() {
+ var f func()
+ set := func() {
+ y := source()
+ g := func() { sink(y) }
+ y = "safe"
+ f = g
+ }
+ set()
+ f()
+}
+
+func makeNamedResultClosure() (f func() string) {
+ x := "safe"
+ f = func() string { return x }
+ x = source()
+ return
+}
+
+func namedResultClosure() {
+ sink(makeNamedResultClosure()()) // $ hasValueFlow="function call"
+}
+
+func makeOverwrittenNamedResultClosure() (f func() string) {
+ x := source()
+ f = func() string { return x }
+ x = "safe"
+ return
+}
+
+func overwrittenNamedResultClosure() {
+ sink(makeOverwrittenNamedResultClosure()())
+}
+
+func applyCaptured(f func(string) string, s string) string {
+ _ = f
+ return func() string { return f(s) }()
+}
+
+func capturedNamedAndLiteralTargets() {
+ sink(applyCaptured(func(s string) string { return s }, "safe"))
+ sink(applyCaptured(identity, source())) // $ hasValueFlow="call to applyCaptured"
+ // Captured callback targets are discovered without distinguishing calls to applyCaptured.
+ sink(applyCaptured(constant, source())) // $ SPURIOUS: hasValueFlow="call to applyCaptured"
+}
+
+func assertedClosure() {
+ x := "safe"
+ var stored any = func() { sink(x) } // $ hasValueFlow="x"
+ f := stored.(func())
+ x = source()
+ f()
+}
+
+func overwrittenAssertedClosure() {
+ x := source()
+ var stored any = func() { sink(x) }
+ f := stored.(func())
+ x = "safe"
+ f()
+}
+
+func checkedAssertedClosure() {
+ x := "safe"
+ var stored any = func() { sink(x) } // $ hasValueFlow="x"
+ f, ok := stored.(func())
+ if ok {
+ x = source()
+ f()
+ }
+}
+
+func assertedClosureWriteBack() {
+ x := "safe"
+ var stored any = func() { x = source() }
+ f := stored.(func())
+ f()
+ sink(x) // $ hasValueFlow="x"
+}
+
+func closureArgumentNodes() {
+ constant("safe") // $ closure-args,callee-post,closure-post=0
+ genericIdentity[string]("safe") // $ closure-args,callee-post,closure-post=0
+ r := receiver{}
+ r.identity("safe") // $ closure-args,callee-post,closure-post=0 receiver-post=1
+
+ f := func() {} // $ closure-params=0
+ f() // $ closure-args,callee-post,closure-post=1
+ named := constant
+ named("safe") // $ closure-args,callee-post,closure-post=1
+ method := r.identity
+ method("safe") // $ closure-args,callee-post,closure-post=1
+
+ x := "safe"
+ g := func() { _ = x } // $ closure-params=1
+ g() // $ closure-args,callee-post,closure-post=1
+ callback(g) // $ closure-args,callee-post,closure-post=0 argument-post,syntactic-arg=1
+}
+
+func localCapturedFlow() {
+ x := source()
+ _ = func() { _ = x }
+ sink(x) // $ hasValueFlow="x" local-flow,local-taint=1
+ x = "safe"
+ sink(x) // $ local-flow,local-taint=0
+}
+
+func lazyInitCapturedClosureVar() {
+ var f func()
+ set := func() {
+ if f == nil {
+ y := "safe"
+ g := func() { sink(y) } // $ hasValueFlow="y"
+ y = source()
+ f = g
+ }
+ }
+ set()
+ f()
+}
+
+func overwrittenLazyInitCapturedClosureVar() {
+ var f func()
+ set := func() {
+ if f == nil {
+ y := source()
+ g := func() { sink(y) }
+ y = "safe"
+ f = g
+ }
+ }
+ set()
+ f()
+}
+
+func innerClosureEscapeWithLocalCall(cond bool) {
+ var f func()
+ set := func() {
+ y := "safe"
+ g := func() { sink(y) } // $ hasValueFlow="y"
+ y = source()
+ f = g
+ if cond {
+ y = "safe"
+ f()
+ }
+ }
+ set()
+ f()
+}
+
+func overwrittenInnerClosureEscapeWithLocalCall(cond bool) {
+ var f func()
+ set := func() {
+ y := source()
+ g := func() { sink(y) }
+ y = "safe"
+ f = g
+ if cond {
+ f()
+ }
+ }
+ set()
+ f()
+}
diff --git a/go/ql/test/library-tests/semmle/go/frameworks/Twirp/RequestForgery.expected b/go/ql/test/library-tests/semmle/go/frameworks/Twirp/RequestForgery.expected
index 2f57254847eb..9e06df0f25ee 100644
--- a/go/ql/test/library-tests/semmle/go/frameworks/Twirp/RequestForgery.expected
+++ b/go/ql/test/library-tests/semmle/go/frameworks/Twirp/RequestForgery.expected
@@ -5,8 +5,8 @@ edges
| rpc/notes/service.twirp.go:538:2:538:33 | extract:0 ... := ... | rpc/notes/service.twirp.go:544:27:544:29 | buf | provenance | |
| rpc/notes/service.twirp.go:538:25:538:32 | selection of Body | rpc/notes/service.twirp.go:538:2:538:33 | extract:0 ... := ... | provenance | Src:MaD:1 MaD:3 |
| rpc/notes/service.twirp.go:544:27:544:29 | buf | rpc/notes/service.twirp.go:544:32:544:41 | reqContent [postupdate] | provenance | MaD:2 |
-| rpc/notes/service.twirp.go:544:32:544:41 | reqContent [postupdate] | rpc/notes/service.twirp.go:574:2:577:2 | SSA implicit def(reqContent) | provenance | |
-| rpc/notes/service.twirp.go:574:2:577:2 | SSA implicit def(reqContent) | rpc/notes/service.twirp.go:576:35:576:44 | reqContent | provenance | |
+| rpc/notes/service.twirp.go:544:32:544:41 | reqContent [postupdate] | rpc/notes/service.twirp.go:574:2:577:2 | function literal [captured reqContent] | provenance | |
+| rpc/notes/service.twirp.go:574:2:577:2 | function literal [captured reqContent] | rpc/notes/service.twirp.go:576:35:576:44 | reqContent | provenance | |
| rpc/notes/service.twirp.go:576:35:576:44 | reqContent | server/main.go:19:56:19:61 | SSA param(params) | provenance | |
| server/main.go:19:56:19:61 | SSA param(params) | server/main.go:30:38:30:48 | selection of Text | provenance | |
| server/main.go:19:56:19:61 | SSA param(params) | server/main.go:30:38:30:48 | selection of Text | provenance | |
@@ -19,7 +19,7 @@ nodes
| rpc/notes/service.twirp.go:538:25:538:32 | selection of Body | semmle.label | selection of Body |
| rpc/notes/service.twirp.go:544:27:544:29 | buf | semmle.label | buf |
| rpc/notes/service.twirp.go:544:32:544:41 | reqContent [postupdate] | semmle.label | reqContent [postupdate] |
-| rpc/notes/service.twirp.go:574:2:577:2 | SSA implicit def(reqContent) | semmle.label | SSA implicit def(reqContent) |
+| rpc/notes/service.twirp.go:574:2:577:2 | function literal [captured reqContent] | semmle.label | function literal [captured reqContent] |
| rpc/notes/service.twirp.go:576:35:576:44 | reqContent | semmle.label | reqContent |
| server/main.go:19:56:19:61 | SSA param(params) | semmle.label | SSA param(params) |
| server/main.go:19:56:19:61 | SSA param(params) | semmle.label | SSA param(params) |
diff --git a/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected b/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected
index 559121b23778..ae7bba58ef1f 100644
--- a/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected
+++ b/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected
@@ -13,8 +13,8 @@
| tests.go:228:8:228:13 | chosen | tests.go:220:2:220:75 | extract:0 ... := ... | tests.go:228:8:228:13 | chosen | File handle may be writable as a result of data flow from a $@ and closing it may result in data loss upon failure, which is not handled explicitly. | tests.go:220:12:220:75 | call to OpenFile | call to OpenFile |
edges
| tests.go:9:24:9:24 | SSA param(f) | tests.go:10:8:10:8 | f | provenance | |
-| tests.go:13:32:13:32 | SSA param(f) | tests.go:14:13:16:2 | SSA implicit def(f) | provenance | |
-| tests.go:14:13:16:2 | SSA implicit def(f) | tests.go:15:3:15:3 | f | provenance | |
+| tests.go:13:32:13:32 | SSA param(f) | tests.go:18:8:18:11 | cont [captured f] | provenance | |
+| tests.go:18:8:18:11 | cont [captured f] | tests.go:15:3:15:3 | f | provenance | |
| tests.go:32:5:32:78 | extract:0 ... := ... | tests.go:33:21:33:21 | f | provenance | Src:MaD:1 |
| tests.go:32:5:32:78 | extract:0 ... := ... | tests.go:34:29:34:29 | f | provenance | Src:MaD:1 |
| tests.go:33:21:33:21 | f | tests.go:9:24:9:24 | SSA param(f) | provenance | |
@@ -37,8 +37,8 @@ nodes
| tests.go:9:24:9:24 | SSA param(f) | semmle.label | SSA param(f) |
| tests.go:10:8:10:8 | f | semmle.label | f |
| tests.go:13:32:13:32 | SSA param(f) | semmle.label | SSA param(f) |
-| tests.go:14:13:16:2 | SSA implicit def(f) | semmle.label | SSA implicit def(f) |
| tests.go:15:3:15:3 | f | semmle.label | f |
+| tests.go:18:8:18:11 | cont [captured f] | semmle.label | cont [captured f] |
| tests.go:32:5:32:78 | extract:0 ... := ... | semmle.label | extract:0 ... := ... |
| tests.go:33:21:33:21 | f | semmle.label | f |
| tests.go:34:29:34:29 | f | semmle.label | f |
From 92c30c1a12cb8caa05ddeb74c5f2c07c89b6fa8a Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Fri, 27 Nov 2026 12:20:25 +0000
Subject: [PATCH 15/17] Go: Support receiver nodes without SSA definitions
Recognize both SSA-backed and instruction-backed receiver parameters so receiver lookup works when a receiver is unused or read only inside a closure. Document the hierarchy change and test that receiver lookup APIs agree without changing captured-receiver flow.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
.../change-notes/2026-11-26-receiver-nodes.md | 4 +++
.../go/dataflow/internal/DataFlowNodes.qll | 21 +++++++++++---
.../dataflow/VariableCapture/ArgumentNodes.ql | 29 ++++++++++++++++++-
.../go/dataflow/VariableCapture/test.go | 8 ++++-
4 files changed, 56 insertions(+), 6 deletions(-)
create mode 100644 go/ql/lib/change-notes/2026-11-26-receiver-nodes.md
diff --git a/go/ql/lib/change-notes/2026-11-26-receiver-nodes.md b/go/ql/lib/change-notes/2026-11-26-receiver-nodes.md
new file mode 100644
index 000000000000..37d53722b3c3
--- /dev/null
+++ b/go/ql/lib/change-notes/2026-11-26-receiver-nodes.md
@@ -0,0 +1,4 @@
+---
+category: breaking
+---
+* `DataFlow::ReceiverNode` now extends `DataFlow::ParameterNode` rather than `DataFlow::SsaParameterNode`, so receiver lookup also works for receivers that are unused or read only inside closures. Queries that need SSA-specific methods must narrow the node to `DataFlow::SsaParameterNode`.
diff --git a/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll b/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
index f3d2880f3f8a..26b81c97e52a 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
@@ -916,7 +916,11 @@ module Public {
}
}
- /** A representation of a parameter initialization, defined in source via an SSA node. */
+ /**
+ * A parameter initialization without a live SSA definition.
+ *
+ * This includes unused parameters and parameters whose only reads are inside closures.
+ */
class UnusedParameterNode extends ParameterNode, InstructionNode {
override IR::InitParameterInstruction insn;
Parameter parm;
@@ -949,15 +953,24 @@ module Public {
}
}
- /** A representation of a receiver initialization. */
- class ReceiverNode extends SsaParameterNode {
- override ReceiverVariable parm;
+ /**
+ * A receiver initialization, represented by either an SSA node or a parameter
+ * initialization instruction.
+ */
+ class ReceiverNode extends ParameterNode {
+ ReceiverVariable parm;
+
+ ReceiverNode() { parm = this.asParameter() }
/** Gets the receiver variable this node initializes. */
ReceiverVariable asReceiverVariable() { result = parm }
/** Holds if this node initializes the receiver variable of `m`. */
predicate isReceiverOf(MethodDecl m) { parm.isReceiverOf(m) }
+
+ override predicate isParameterOf(DataFlowCallable c, int i) {
+ parm.isParameterOf(c.asCallable().getFuncDef(), i)
+ }
}
/**
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.ql b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.ql
index 042fac250a1b..8153cddc1788 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.ql
+++ b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.ql
@@ -8,7 +8,8 @@ module ArgumentNodesTest implements TestSig {
result =
[
"closure-args", "callee-post", "closure-post", "argument-post", "syntactic-arg",
- "receiver-post", "closure-params"
+ "receiver-post", "closure-params", "receiver-node", "function-receiver", "input-receiver",
+ "receiver-agreement"
]
}
@@ -63,6 +64,32 @@ module ArgumentNodesTest implements TestSig {
count(Nodes::CapturedVariablesParameterNode parameter | parameter.getFunction() = function)
.toString()
)
+ or
+ exists(MethodDecl method, DataFlow::FunctionNode function |
+ method.getName() = ["closure", "directReceiver", "unusedReceiver"] and
+ function.getFunction() = method.getFunction() and
+ location = method.getReceiver().getLocation() and
+ element = method.getReceiver().toString()
+ |
+ tag = "receiver-node" and
+ value = count(DataFlow::receiverNode(method.getReceiver())).toString()
+ or
+ tag = "function-receiver" and
+ value = count(function.getReceiver()).toString()
+ or
+ tag = "input-receiver" and
+ value = count(FunctionInput::receiver().getExitNode(method)).toString()
+ or
+ tag = "receiver-agreement" and
+ value =
+ count(DataFlow::ReceiverNode node |
+ node = DataFlow::receiverNode(method.getReceiver()) and
+ node = DataFlow::parameterNode(method.getReceiver()) and
+ node = function.getReceiver() and
+ node = FunctionInput::receiver().getExitNode(method) and
+ node.isReceiverOf(method)
+ ).toString()
+ )
}
}
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/test.go b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/test.go
index 0f92500c6086..887ae9577c0e 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/test.go
+++ b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/test.go
@@ -94,7 +94,7 @@ func rangeWrite() {
type receiver struct{ value string }
-func (r receiver) closure() func() string {
+func (r receiver) closure() func() string { // $ receiver-node,function-receiver,input-receiver,receiver-agreement=1
return func() string { return r.value }
}
@@ -391,3 +391,9 @@ func overwrittenInnerClosureEscapeWithLocalCall(cond bool) {
set()
f()
}
+
+func (r receiver) directReceiver() string { // $ receiver-node,function-receiver,input-receiver,receiver-agreement=1
+ return r.value
+}
+
+func (r receiver) unusedReceiver() {} // $ receiver-node,function-receiver,input-receiver,receiver-agreement=1
From 1ee0eebd925e95fe9ba5a1b50650e2b406d02f7a Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Fri, 27 Nov 2026 12:21:56 +0000
Subject: [PATCH 16/17] Go: Remove uncertain exit reads for captured variables
Drop synthetic uncertain exit reads now that shared capture builds its own SSA graph, and exclude captured variables from DeadStoreOfLocal to avoid false positives when escaped closures observe later assignments.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
go/ql/lib/semmle/go/dataflow/SsaImpl.qll | 21 ---
.../src/RedundantCode/DeadStoreOfLocal.qhelp | 4 +
go/ql/src/RedundantCode/DeadStoreOfLocal.ql | 2 +
.../2026-11-26-captured-dead-stores.md | 4 +
.../CONSISTENCY/SsaConsistency.expected | 4 -
.../CONSISTENCY/SsaConsistency.expected | 4 -
.../Defer/CONSISTENCY/SsaConsistency.expected | 10 --
.../dataflow/FlowSteps/LocalFlowStep.expected | 1 -
.../GlobalValueNumber.expected | 1 -
.../go/dataflow/SSA/SsaDefinition.expected | 2 -
.../go/dataflow/SSA/SsaWithFields.expected | 2 -
.../CONSISTENCY/SsaConsistency.expected | 8 --
.../semmle/go/dataflow/SSAReadKinds/main.go | 2 +-
.../CONSISTENCY/SsaConsistency.expected | 52 --------
.../Twirp/CONSISTENCY/SsaConsistency.expected | 54 --------
.../UnhandledCloseWritableHandle.expected | 8 +-
.../DeadStoreOfLocal/testdata.go | 122 ++++++++++++++++++
.../CONSISTENCY/SsaConsistency.expected | 4 -
.../CONSISTENCY/SsaConsistency.expected | 4 -
19 files changed, 137 insertions(+), 172 deletions(-)
create mode 100644 go/ql/src/change-notes/2026-11-26-captured-dead-stores.md
delete mode 100644 go/ql/test/experimental/CWE-942/CONSISTENCY/SsaConsistency.expected
delete mode 100644 go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/CONSISTENCY/SsaConsistency.expected
delete mode 100644 go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
delete mode 100644 go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/CONSISTENCY/SsaConsistency.expected
delete mode 100644 go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/CONSISTENCY/SsaConsistency.expected
delete mode 100644 go/ql/test/library-tests/semmle/go/frameworks/Twirp/CONSISTENCY/SsaConsistency.expected
delete mode 100644 go/ql/test/query-tests/Security/CWE-322/CONSISTENCY/SsaConsistency.expected
delete mode 100644 go/ql/test/query-tests/Security/CWE-643/CONSISTENCY/SsaConsistency.expected
diff --git a/go/ql/lib/semmle/go/dataflow/SsaImpl.qll b/go/ql/lib/semmle/go/dataflow/SsaImpl.qll
index 08824c12e8d4..781cbebe34ab 100644
--- a/go/ql/lib/semmle/go/dataflow/SsaImpl.qll
+++ b/go/ql/lib/semmle/go/dataflow/SsaImpl.qll
@@ -97,31 +97,10 @@ private module Internal {
/**
* Holds if the `i`th node of basic block `bb` reads source variable `v`.
- *
- * We add a synthetic uncertain read at the exit node of every function
- * that references a captured variable `v`. This ensures that definitions
- * of captured variables are included in the SSA graph even when the
- * variable is not locally read in that function scope (but may be read
- * by another function sharing the same closure).
*/
cached
predicate variableRead(BasicBlock bb, int i, SourceVariable v, boolean certain) {
useAt(bb, i, v) and certain = true
- or
- v.isCaptured() and
- exists(FuncDef f |
- f = bb.getScope() and
- bb.getLastNode().(ControlFlow::Node).isExitNode() and
- i = bb.length() - 1 and
- certain = false
- |
- // The declaring function: captures may be read after calls to closures
- f = v.getDeclaringFunction()
- or
- // Any function that writes `v`: the write may be observed by the
- // declaring function or another closure sharing the same variable
- any(IR::Instruction def | def.writes(v, _)).getRoot() = f
- )
}
cached
diff --git a/go/ql/src/RedundantCode/DeadStoreOfLocal.qhelp b/go/ql/src/RedundantCode/DeadStoreOfLocal.qhelp
index 9e9aa12da8a1..3b8e0b368cab 100644
--- a/go/ql/src/RedundantCode/DeadStoreOfLocal.qhelp
+++ b/go/ql/src/RedundantCode/DeadStoreOfLocal.qhelp
@@ -9,6 +9,10 @@ A value is assigned to a variable, but either it is never read, or its value is
always overwritten before being read. This means that the original assignment
has no effect, and could indicate a logic error or incomplete code.
+
+Variables captured by closures are excluded because escaped closures may read
+values assigned after the closure was created.
+
diff --git a/go/ql/src/RedundantCode/DeadStoreOfLocal.ql b/go/ql/src/RedundantCode/DeadStoreOfLocal.ql
index f53f6f664b68..01310a95f4d8 100644
--- a/go/ql/src/RedundantCode/DeadStoreOfLocal.ql
+++ b/go/ql/src/RedundantCode/DeadStoreOfLocal.ql
@@ -33,6 +33,8 @@ from IR::WriteInstruction def, SsaSourceVariable target, IR::Instruction rhs, Ex
where
def.writes(target, rhs) and
not exists(SsaExplicitWrite ssa | ssa.getDefinition() = def) and
+ // Escaped closures may observe writes that have no corresponding SSA read.
+ not target.isCaptured() and
// exclude assignments in dead code
def.getBasicBlock() instanceof ReachableBasicBlock and
// exclude assignments with default values or simple expressions
diff --git a/go/ql/src/change-notes/2026-11-26-captured-dead-stores.md b/go/ql/src/change-notes/2026-11-26-captured-dead-stores.md
new file mode 100644
index 000000000000..187abb623b1b
--- /dev/null
+++ b/go/ql/src/change-notes/2026-11-26-captured-dead-stores.md
@@ -0,0 +1,4 @@
+---
+category: minorAnalysis
+---
+* The query `go/useless-assignment-to-local` ("Useless assignment to local variable") no longer reports assignments to variables captured by closures, avoiding false positives when escaped closures observe later assignments.
diff --git a/go/ql/test/experimental/CWE-942/CONSISTENCY/SsaConsistency.expected b/go/ql/test/experimental/CWE-942/CONSISTENCY/SsaConsistency.expected
deleted file mode 100644
index e0aed12c69e4..000000000000
--- a/go/ql/test/experimental/CWE-942/CONSISTENCY/SsaConsistency.expected
+++ /dev/null
@@ -1,4 +0,0 @@
-uselessPhiNode
-| CorsMisconfiguration.go:13:1:229:1 | SSA phi(allowedOrigins) | 1 |
-phiWithoutTwoPriorRefs
-| CorsMisconfiguration.go:13:1:229:1 | SSA phi(allowedOrigins) | CorsMisconfiguration.go:13:1:229:1 | Exceptional Exit | CorsMisconfiguration.go:94:3:94:16 | allowedOrigins | 1 |
diff --git a/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/CONSISTENCY/SsaConsistency.expected b/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/CONSISTENCY/SsaConsistency.expected
deleted file mode 100644
index a810e3bd97cf..000000000000
--- a/go/ql/test/library-tests/semmle/go/controlflow/ControlFlowGraph/CONSISTENCY/SsaConsistency.expected
+++ /dev/null
@@ -1,4 +0,0 @@
-uselessPhiNode
-| epilogues.go:89:3:91:3 | SSA phi(result) | 1 |
-phiWithoutTwoPriorRefs
-| epilogues.go:89:3:91:3 | SSA phi(result) | epilogues.go:89:3:91:3 | After if statement | epilogues.go:87:30:87:35 | result | 1 |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
deleted file mode 100644
index ef57e8491657..000000000000
--- a/go/ql/test/library-tests/semmle/go/dataflow/Defer/CONSISTENCY/SsaConsistency.expected
+++ /dev/null
@@ -1,10 +0,0 @@
-uselessPhiNode
-| main.go:252:8:254:2 | SSA phi(res) | 1 |
-| main.go:999:2:1001:2 | SSA phi(s2) | 1 |
-| main.go:1131:1:1138:1 | SSA phi(b) | 1 |
-| main.go:1140:1:1147:1 | SSA phi(b) | 1 |
-phiWithoutTwoPriorRefs
-| main.go:252:8:254:2 | SSA phi(res) | main.go:252:8:254:2 | Exit | main.go:251:33:251:35 | res | 1 |
-| main.go:999:2:1001:2 | SSA phi(s2) | main.go:999:2:1001:2 | Exit | main.go:996:2:996:3 | s2 | 1 |
-| main.go:1131:1:1138:1 | SSA phi(b) | main.go:1131:1:1138:1 | Exceptional Exit | main.go:1132:2:1132:2 | b | 1 |
-| main.go:1140:1:1147:1 | SSA phi(b) | main.go:1140:1:1147:1 | Exceptional Exit | main.go:1141:2:1141:2 | b | 1 |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/FlowSteps/LocalFlowStep.expected b/go/ql/test/library-tests/semmle/go/dataflow/FlowSteps/LocalFlowStep.expected
index b75558e4b142..4b8305175e44 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/FlowSteps/LocalFlowStep.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/FlowSteps/LocalFlowStep.expected
@@ -17,7 +17,6 @@
| main.go:10:12:10:12 | y | main.go:10:17:10:17 | y |
| main.go:10:17:10:27 | ...>=... | main.go:10:7:10:27 | After ...&&... |
| main.go:11:14:11:14 | z | main.go:11:9:11:15 | type conversion |
-| main.go:15:9:15:9 | 0 | main.go:15:2:15:9 | SSA def(acc) |
| main.go:16:9:19:2 | SSA implicit def(acc) | main.go:17:3:17:5 | acc |
| main.go:17:3:17:7 | SSA def(acc) | main.go:18:10:18:12 | acc |
| main.go:17:3:17:7 | increment statement | main.go:17:3:17:7 | SSA def(acc) |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/GlobalValueNumber.expected b/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/GlobalValueNumber.expected
index af1659fa2213..d7b23db096b7 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/GlobalValueNumber.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/GlobalValueNumbering/GlobalValueNumber.expected
@@ -34,7 +34,6 @@
| main.go:33:24:39:1 | zero-init:0 block statement | main.go:10:7:10:7 | 0 |
| main.go:34:8:34:8 | 7 | main.go:34:8:34:8 | 7 |
| main.go:35:8:37:4 | defer-invoke function call | main.go:35:8:37:4 | function call |
-| main.go:36:3:36:9 | SSA def(res) | main.go:36:9:36:9 | 8 |
| main.go:36:9:36:9 | 8 | main.go:36:9:36:9 | 8 |
| main.go:38:2:38:9 | SSA def(res) | main.go:38:9:38:9 | 9 |
| main.go:38:9:38:9 | 9 | main.go:38:9:38:9 | 9 |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/SSA/SsaDefinition.expected b/go/ql/test/library-tests/semmle/go/dataflow/SSA/SsaDefinition.expected
index 0fbf6c51908d..ee2ea20986b7 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/SSA/SsaDefinition.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/SSA/SsaDefinition.expected
@@ -35,7 +35,6 @@
| main.go:95:22:95:28 | SSA param(wrapper) |
| main.go:96:2:96:7 | SSA def(x) |
| main.go:97:2:99:3 | SSA implicit def(x) |
-| main.go:98:3:98:7 | SSA def(x) |
| main.go:103:20:103:26 | SSA param(wrapper) |
| main.go:104:2:104:7 | SSA def(x) |
| main.go:105:16:108:2 | SSA implicit def(x) |
@@ -45,7 +44,6 @@
| main.go:114:2:117:3 | SSA implicit def(x) |
| main.go:114:16:117:2 | SSA implicit def(x) |
| main.go:115:3:115:12 | SSA def(y) |
-| main.go:116:3:116:7 | SSA def(x) |
| main.go:129:2:133:2 | SSA phi(p) |
| main.go:130:3:130:24 | SSA def(p) |
| main.go:132:3:132:24 | SSA def(p) |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/SSA/SsaWithFields.expected b/go/ql/test/library-tests/semmle/go/dataflow/SSA/SsaWithFields.expected
index fcd2bf9cb333..8f3965b052bb 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/SSA/SsaWithFields.expected
+++ b/go/ql/test/library-tests/semmle/go/dataflow/SSA/SsaWithFields.expected
@@ -36,7 +36,6 @@
| main.go:95:22:95:28 | (SSA param(wrapper)).s | wrapper.s |
| main.go:96:2:96:7 | (SSA def(x)) | x |
| main.go:97:2:99:3 | (SSA implicit def(x)) | x |
-| main.go:98:3:98:7 | (SSA def(x)) | x |
| main.go:103:20:103:26 | (SSA param(wrapper)) | wrapper |
| main.go:103:20:103:26 | (SSA param(wrapper)).s | wrapper.s |
| main.go:104:2:104:7 | (SSA def(x)) | x |
@@ -48,7 +47,6 @@
| main.go:114:2:117:3 | (SSA implicit def(x)) | x |
| main.go:114:16:117:2 | (SSA implicit def(x)) | x |
| main.go:115:3:115:12 | (SSA def(y)) | y |
-| main.go:116:3:116:7 | (SSA def(x)) | x |
| main.go:129:2:133:2 | (SSA phi(p)) | p |
| main.go:129:2:133:2 | (SSA phi(p)).a | p.a |
| main.go:129:2:133:2 | (SSA phi(p)).b | p.b |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/CONSISTENCY/SsaConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/CONSISTENCY/SsaConsistency.expected
deleted file mode 100644
index 59855fa55900..000000000000
--- a/go/ql/test/library-tests/semmle/go/dataflow/SSADataFlowIntegration/CONSISTENCY/SsaConsistency.expected
+++ /dev/null
@@ -1,8 +0,0 @@
-uselessPhiNode
-| main.go:57:9:59:2 | SSA phi(value) | 1 |
-| main.go:64:1:71:1 | SSA phi(value) | 1 |
-| main.go:76:3:78:3 | SSA phi(value) | 1 |
-phiWithoutTwoPriorRefs
-| main.go:57:9:59:2 | SSA phi(value) | main.go:57:9:59:2 | Exit | main.go:56:2:56:6 | value | 1 |
-| main.go:64:1:71:1 | SSA phi(value) | main.go:64:1:71:1 | Exceptional Exit | main.go:65:2:65:6 | value | 1 |
-| main.go:76:3:78:3 | SSA phi(value) | main.go:76:3:78:3 | After if statement | main.go:74:2:74:6 | value | 1 |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/SSAReadKinds/main.go b/go/ql/test/library-tests/semmle/go/dataflow/SSAReadKinds/main.go
index 13a768ab3a47..ace4a2d84802 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/SSAReadKinds/main.go
+++ b/go/ql/test/library-tests/semmle/go/dataflow/SSAReadKinds/main.go
@@ -16,7 +16,7 @@ func explicitAndImplicitResult() (result int) { // $ explicit=1 $ implicit=1 $ f
return
}
-func capture(value int) func() int { // $ explicit=1 $ implicit=1 $ flow=1 $ access-path=1
+func capture(value int) func() int { // $ explicit=1 $ implicit=0 $ flow=1 $ access-path=1
return func() int {
return value
}
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/CONSISTENCY/SsaConsistency.expected b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/CONSISTENCY/SsaConsistency.expected
deleted file mode 100644
index 3531df0a8982..000000000000
--- a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/CONSISTENCY/SsaConsistency.expected
+++ /dev/null
@@ -1,52 +0,0 @@
-uselessPhiNode
-| test.go:10:1:14:1 | SSA phi(x) | 1 |
-| test.go:16:1:21:1 | SSA phi(x) | 1 |
-| test.go:32:7:32:29 | SSA phi(x) | 1 |
-| test.go:39:9:39:31 | SSA phi(x) | 1 |
-| test.go:45:1:51:1 | SSA phi(x) | 1 |
-| test.go:64:1:70:1 | SSA phi(x) | 1 |
-| test.go:72:1:78:1 | SSA phi(x) | 1 |
-| test.go:82:1:86:1 | SSA phi(x) | 1 |
-| test.go:88:1:93:1 | SSA phi(x) | 1 |
-| test.go:89:2:92:2 | SSA phi(x) | 1 |
-| test.go:120:8:120:30 | SSA phi(x) | 1 |
-| test.go:128:7:128:29 | SSA phi(x) | 1 |
-| test.go:146:1:149:1 | SSA phi(x) | 1 |
-| test.go:209:1:215:1 | SSA phi(f) | 1 |
-| test.go:209:1:215:1 | SSA phi(x) | 1 |
-| test.go:219:9:224:2 | SSA phi(f) | 1 |
-| test.go:231:9:236:2 | SSA phi(f) | 1 |
-| test.go:231:9:236:2 | SSA phi(y) | 1 |
-| test.go:252:1:257:1 | SSA phi(x) | 1 |
-| test.go:303:19:303:41 | SSA phi(x) | 1 |
-| test.go:309:1:326:1 | SSA phi(x) | 1 |
-| test.go:339:3:344:3 | SSA phi(y) | 1 |
-| test.go:352:9:359:2 | SSA phi(y) | 1 |
-| test.go:353:3:358:3 | SSA phi(y) | 1 |
-| test.go:382:9:390:2 | SSA phi(y) | 1 |
-phiWithoutTwoPriorRefs
-| test.go:10:1:14:1 | SSA phi(x) | test.go:10:1:14:1 | Exceptional Exit | test.go:11:2:11:2 | x | 1 |
-| test.go:16:1:21:1 | SSA phi(x) | test.go:16:1:21:1 | Exceptional Exit | test.go:17:2:17:2 | x | 1 |
-| test.go:32:7:32:29 | SSA phi(x) | test.go:32:7:32:29 | Exit | test.go:31:2:31:2 | x | 1 |
-| test.go:39:9:39:31 | SSA phi(x) | test.go:39:9:39:31 | Exit | test.go:38:2:38:2 | x | 1 |
-| test.go:45:1:51:1 | SSA phi(x) | test.go:45:1:51:1 | Exceptional Exit | test.go:46:2:46:2 | x | 1 |
-| test.go:64:1:70:1 | SSA phi(x) | test.go:64:1:70:1 | Exceptional Exit | test.go:65:2:65:2 | x | 1 |
-| test.go:72:1:78:1 | SSA phi(x) | test.go:72:1:78:1 | Exceptional Exit | test.go:73:2:73:2 | x | 1 |
-| test.go:82:1:86:1 | SSA phi(x) | test.go:82:1:86:1 | Exceptional Exit | test.go:83:2:83:2 | x | 1 |
-| test.go:88:1:93:1 | SSA phi(x) | test.go:88:1:93:1 | Exceptional Exit | test.go:89:9:89:9 | x | 1 |
-| test.go:89:2:92:2 | SSA phi(x) | test.go:89:2:92:2 | After range statement | test.go:89:9:89:9 | x | 1 |
-| test.go:120:8:120:30 | SSA phi(x) | test.go:120:8:120:30 | Exit | test.go:118:2:118:2 | x | 1 |
-| test.go:128:7:128:29 | SSA phi(x) | test.go:128:7:128:29 | Exit | test.go:127:24:127:24 | x | 1 |
-| test.go:146:1:149:1 | SSA phi(x) | test.go:146:1:149:1 | Exceptional Exit | test.go:147:2:147:2 | x | 1 |
-| test.go:209:1:215:1 | SSA phi(f) | test.go:209:1:215:1 | Exceptional Exit | test.go:211:2:211:2 | f | 1 |
-| test.go:209:1:215:1 | SSA phi(x) | test.go:209:1:215:1 | Exceptional Exit | test.go:210:2:210:2 | x | 1 |
-| test.go:219:9:224:2 | SSA phi(f) | test.go:219:9:224:2 | Exit | test.go:218:6:218:6 | f | 1 |
-| test.go:231:9:236:2 | SSA phi(f) | test.go:231:9:236:2 | Exit | test.go:230:6:230:6 | f | 1 |
-| test.go:231:9:236:2 | SSA phi(y) | test.go:231:9:236:2 | Exit | test.go:232:3:232:3 | y | 1 |
-| test.go:252:1:257:1 | SSA phi(x) | test.go:252:1:257:1 | Exit | test.go:253:2:253:2 | x | 1 |
-| test.go:303:19:303:41 | SSA phi(x) | test.go:303:19:303:41 | Exit | test.go:302:2:302:2 | x | 1 |
-| test.go:309:1:326:1 | SSA phi(x) | test.go:309:1:326:1 | Exceptional Exit | test.go:322:2:322:2 | x | 1 |
-| test.go:339:3:344:3 | SSA phi(y) | test.go:339:3:344:3 | After if statement | test.go:340:4:340:4 | y | 1 |
-| test.go:352:9:359:2 | SSA phi(y) | test.go:352:9:359:2 | Exit | test.go:354:4:354:4 | y | 1 |
-| test.go:353:3:358:3 | SSA phi(y) | test.go:353:3:358:3 | After if statement | test.go:354:4:354:4 | y | 1 |
-| test.go:382:9:390:2 | SSA phi(y) | test.go:382:9:390:2 | Exceptional Exit | test.go:383:3:383:3 | y | 1 |
diff --git a/go/ql/test/library-tests/semmle/go/frameworks/Twirp/CONSISTENCY/SsaConsistency.expected b/go/ql/test/library-tests/semmle/go/frameworks/Twirp/CONSISTENCY/SsaConsistency.expected
deleted file mode 100644
index 4c0837482560..000000000000
--- a/go/ql/test/library-tests/semmle/go/frameworks/Twirp/CONSISTENCY/SsaConsistency.expected
+++ /dev/null
@@ -1,54 +0,0 @@
-uselessPhiNode
-| rpc/notes/service.twirp.go:446:1:527:1 | SSA phi(handler) | 1 |
-| rpc/notes/service.twirp.go:446:1:527:1 | SSA phi(handler) | 1 |
-| rpc/notes/service.twirp.go:446:1:527:1 | SSA phi(reqContent) | 1 |
-| rpc/notes/service.twirp.go:446:1:527:1 | SSA phi(reqContent) | 1 |
-| rpc/notes/service.twirp.go:494:9:494:48 | SSA phi(err) | 1 |
-| rpc/notes/service.twirp.go:494:9:494:48 | SSA phi(respContent) | 1 |
-| rpc/notes/service.twirp.go:529:1:606:1 | SSA phi(handler) | 1 |
-| rpc/notes/service.twirp.go:529:1:606:1 | SSA phi(handler) | 1 |
-| rpc/notes/service.twirp.go:529:1:606:1 | SSA phi(reqContent) | 1 |
-| rpc/notes/service.twirp.go:529:1:606:1 | SSA phi(reqContent) | 1 |
-| rpc/notes/service.twirp.go:575:9:575:48 | SSA phi(err) | 1 |
-| rpc/notes/service.twirp.go:575:9:575:48 | SSA phi(respContent) | 1 |
-| rpc/notes/service.twirp.go:626:1:707:1 | SSA phi(handler) | 1 |
-| rpc/notes/service.twirp.go:626:1:707:1 | SSA phi(handler) | 1 |
-| rpc/notes/service.twirp.go:626:1:707:1 | SSA phi(reqContent) | 1 |
-| rpc/notes/service.twirp.go:626:1:707:1 | SSA phi(reqContent) | 1 |
-| rpc/notes/service.twirp.go:674:9:674:48 | SSA phi(err) | 1 |
-| rpc/notes/service.twirp.go:674:9:674:48 | SSA phi(respContent) | 1 |
-| rpc/notes/service.twirp.go:709:1:786:1 | SSA phi(handler) | 1 |
-| rpc/notes/service.twirp.go:709:1:786:1 | SSA phi(handler) | 1 |
-| rpc/notes/service.twirp.go:709:1:786:1 | SSA phi(reqContent) | 1 |
-| rpc/notes/service.twirp.go:709:1:786:1 | SSA phi(reqContent) | 1 |
-| rpc/notes/service.twirp.go:755:9:755:48 | SSA phi(err) | 1 |
-| rpc/notes/service.twirp.go:755:9:755:48 | SSA phi(respContent) | 1 |
-| rpc/notes/service.twirp.go:1203:1:1249:1 | SSA phi(resp) | 1 |
-| rpc/notes/service.twirp.go:1203:156:1249:1 | SSA phi(resp) | 1 |
-| rpc/notes/service.twirp.go:1252:1:1305:1 | SSA phi(resp) | 1 |
-| rpc/notes/service.twirp.go:1252:152:1305:1 | SSA phi(resp) | 1 |
-phiWithoutTwoPriorRefs
-| rpc/notes/service.twirp.go:446:1:527:1 | SSA phi(handler) | rpc/notes/service.twirp.go:446:1:527:1 | Exceptional Exit | rpc/notes/service.twirp.go:468:2:468:8 | handler | 1 |
-| rpc/notes/service.twirp.go:446:1:527:1 | SSA phi(handler) | rpc/notes/service.twirp.go:446:1:527:1 | Normal Exit | rpc/notes/service.twirp.go:468:2:468:8 | handler | 1 |
-| rpc/notes/service.twirp.go:446:1:527:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:446:1:527:1 | Exceptional Exit | rpc/notes/service.twirp.go:461:2:461:11 | reqContent | 1 |
-| rpc/notes/service.twirp.go:446:1:527:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:446:1:527:1 | Normal Exit | rpc/notes/service.twirp.go:461:2:461:11 | reqContent | 1 |
-| rpc/notes/service.twirp.go:494:9:494:48 | SSA phi(err) | rpc/notes/service.twirp.go:494:9:494:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:447:6:447:8 | err | 1 |
-| rpc/notes/service.twirp.go:494:9:494:48 | SSA phi(respContent) | rpc/notes/service.twirp.go:494:9:494:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:492:6:492:16 | respContent | 1 |
-| rpc/notes/service.twirp.go:529:1:606:1 | SSA phi(handler) | rpc/notes/service.twirp.go:529:1:606:1 | Exceptional Exit | rpc/notes/service.twirp.go:549:2:549:8 | handler | 1 |
-| rpc/notes/service.twirp.go:529:1:606:1 | SSA phi(handler) | rpc/notes/service.twirp.go:529:1:606:1 | Normal Exit | rpc/notes/service.twirp.go:549:2:549:8 | handler | 1 |
-| rpc/notes/service.twirp.go:529:1:606:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:529:1:606:1 | Exceptional Exit | rpc/notes/service.twirp.go:543:2:543:11 | reqContent | 1 |
-| rpc/notes/service.twirp.go:529:1:606:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:529:1:606:1 | Normal Exit | rpc/notes/service.twirp.go:543:2:543:11 | reqContent | 1 |
-| rpc/notes/service.twirp.go:575:9:575:48 | SSA phi(err) | rpc/notes/service.twirp.go:575:9:575:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:530:6:530:8 | err | 1 |
-| rpc/notes/service.twirp.go:575:9:575:48 | SSA phi(respContent) | rpc/notes/service.twirp.go:575:9:575:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:573:6:573:16 | respContent | 1 |
-| rpc/notes/service.twirp.go:626:1:707:1 | SSA phi(handler) | rpc/notes/service.twirp.go:626:1:707:1 | Exceptional Exit | rpc/notes/service.twirp.go:648:2:648:8 | handler | 1 |
-| rpc/notes/service.twirp.go:626:1:707:1 | SSA phi(handler) | rpc/notes/service.twirp.go:626:1:707:1 | Normal Exit | rpc/notes/service.twirp.go:648:2:648:8 | handler | 1 |
-| rpc/notes/service.twirp.go:626:1:707:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:626:1:707:1 | Exceptional Exit | rpc/notes/service.twirp.go:641:2:641:11 | reqContent | 1 |
-| rpc/notes/service.twirp.go:626:1:707:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:626:1:707:1 | Normal Exit | rpc/notes/service.twirp.go:641:2:641:11 | reqContent | 1 |
-| rpc/notes/service.twirp.go:674:9:674:48 | SSA phi(err) | rpc/notes/service.twirp.go:674:9:674:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:627:6:627:8 | err | 1 |
-| rpc/notes/service.twirp.go:674:9:674:48 | SSA phi(respContent) | rpc/notes/service.twirp.go:674:9:674:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:672:6:672:16 | respContent | 1 |
-| rpc/notes/service.twirp.go:709:1:786:1 | SSA phi(handler) | rpc/notes/service.twirp.go:709:1:786:1 | Exceptional Exit | rpc/notes/service.twirp.go:729:2:729:8 | handler | 1 |
-| rpc/notes/service.twirp.go:709:1:786:1 | SSA phi(handler) | rpc/notes/service.twirp.go:709:1:786:1 | Normal Exit | rpc/notes/service.twirp.go:729:2:729:8 | handler | 1 |
-| rpc/notes/service.twirp.go:709:1:786:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:709:1:786:1 | Exceptional Exit | rpc/notes/service.twirp.go:723:2:723:11 | reqContent | 1 |
-| rpc/notes/service.twirp.go:709:1:786:1 | SSA phi(reqContent) | rpc/notes/service.twirp.go:709:1:786:1 | Normal Exit | rpc/notes/service.twirp.go:723:2:723:11 | reqContent | 1 |
-| rpc/notes/service.twirp.go:755:9:755:48 | SSA phi(err) | rpc/notes/service.twirp.go:755:9:755:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:710:6:710:8 | err | 1 |
-| rpc/notes/service.twirp.go:755:9:755:48 | SSA phi(respContent) | rpc/notes/service.twirp.go:755:9:755:48 | defer-arg-read:0 call to ensurePanicResponses | rpc/notes/service.twirp.go:753:6:753:16 | respContent | 1 |
diff --git a/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected b/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected
index ae7bba58ef1f..30309ed8ea8e 100644
--- a/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected
+++ b/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected
@@ -13,16 +13,16 @@
| tests.go:228:8:228:13 | chosen | tests.go:220:2:220:75 | extract:0 ... := ... | tests.go:228:8:228:13 | chosen | File handle may be writable as a result of data flow from a $@ and closing it may result in data loss upon failure, which is not handled explicitly. | tests.go:220:12:220:75 | call to OpenFile | call to OpenFile |
edges
| tests.go:9:24:9:24 | SSA param(f) | tests.go:10:8:10:8 | f | provenance | |
-| tests.go:13:32:13:32 | SSA param(f) | tests.go:18:8:18:11 | cont [captured f] | provenance | |
+| tests.go:13:32:13:32 | f | tests.go:18:8:18:11 | cont [captured f] | provenance | |
| tests.go:18:8:18:11 | cont [captured f] | tests.go:15:3:15:3 | f | provenance | |
| tests.go:32:5:32:78 | extract:0 ... := ... | tests.go:33:21:33:21 | f | provenance | Src:MaD:1 |
| tests.go:32:5:32:78 | extract:0 ... := ... | tests.go:34:29:34:29 | f | provenance | Src:MaD:1 |
| tests.go:33:21:33:21 | f | tests.go:9:24:9:24 | SSA param(f) | provenance | |
-| tests.go:34:29:34:29 | f | tests.go:13:32:13:32 | SSA param(f) | provenance | |
+| tests.go:34:29:34:29 | f | tests.go:13:32:13:32 | f | provenance | |
| tests.go:46:5:46:76 | extract:0 ... := ... | tests.go:47:21:47:21 | f | provenance | Src:MaD:1 |
| tests.go:46:5:46:76 | extract:0 ... := ... | tests.go:48:29:48:29 | f | provenance | Src:MaD:1 |
| tests.go:47:21:47:21 | f | tests.go:9:24:9:24 | SSA param(f) | provenance | |
-| tests.go:48:29:48:29 | f | tests.go:13:32:13:32 | SSA param(f) | provenance | |
+| tests.go:48:29:48:29 | f | tests.go:13:32:13:32 | f | provenance | |
| tests.go:55:5:55:78 | extract:0 ... := ... | tests.go:57:3:57:3 | f | provenance | Src:MaD:1 |
| tests.go:67:5:67:76 | extract:0 ... := ... | tests.go:69:3:69:3 | f | provenance | Src:MaD:1 |
| tests.go:124:5:124:78 | extract:0 ... := ... | tests.go:126:9:126:9 | f | provenance | Src:MaD:1 |
@@ -36,7 +36,7 @@ models
nodes
| tests.go:9:24:9:24 | SSA param(f) | semmle.label | SSA param(f) |
| tests.go:10:8:10:8 | f | semmle.label | f |
-| tests.go:13:32:13:32 | SSA param(f) | semmle.label | SSA param(f) |
+| tests.go:13:32:13:32 | f | semmle.label | f |
| tests.go:15:3:15:3 | f | semmle.label | f |
| tests.go:18:8:18:11 | cont [captured f] | semmle.label | cont [captured f] |
| tests.go:32:5:32:78 | extract:0 ... := ... | semmle.label | extract:0 ... := ... |
diff --git a/go/ql/test/query-tests/RedundantCode/DeadStoreOfLocal/testdata.go b/go/ql/test/query-tests/RedundantCode/DeadStoreOfLocal/testdata.go
index 8cef4bec660a..1ac1ef3dac76 100644
--- a/go/ql/test/query-tests/RedundantCode/DeadStoreOfLocal/testdata.go
+++ b/go/ql/test/query-tests/RedundantCode/DeadStoreOfLocal/testdata.go
@@ -657,3 +657,125 @@ func _() {
defer useDeadStoreIntPtr(&x)
x = 1
}
+
+func capturedInitialization() {
+ x := deadStore() // $ MISSING: Alert
+ x = usedValue()
+ read := func() { _ = x }
+ read()
+}
+
+func capturedWriteBack() int {
+ x := 0
+ update := func() { x = usedValue() }
+ update()
+ return x
+}
+
+func usedValue() int { return 1 }
+
+func overwrittenCapturedWrites() int {
+ x := 0
+ update := func() {
+ x = deadStore() // $ MISSING: Alert
+ x = 1
+ x = deadStore() // $ MISSING: Alert
+ if b {
+ x = 2
+ } else {
+ x = 3
+ }
+ for b {
+ x = deadStore() // $ MISSING: Alert
+ x = 4
+ }
+ }
+ update()
+ return x
+}
+
+func overwrittenAfterClosureCreation() {
+ y := usedValue()
+ x := deadStore() // $ MISSING: Alert
+ read := func() { _ = x }
+ x = y
+ read()
+}
+
+func returnedClosureCapturesWrite() func() int {
+ x := usedValue()
+ return func() int { return x }
+}
+
+func conditionallyOverwrittenCapture() int {
+ x := 0
+ update := func() {
+ x = usedValue()
+ if b {
+ x = 1
+ }
+ }
+ update()
+ return x
+}
+
+func observedCapturedWrite() int {
+ x := 0
+ read := func() { _ = x }
+ update := func() {
+ x = usedValue()
+ read()
+ x = 1
+ x = usedValue()
+ _ = x
+ x = 2
+ }
+ update()
+ return x
+}
+
+func panickingCapturedOverwrite(xs []int, i int) {
+ x := 0
+ defer func() { _ = x }()
+ update := func() {
+ x = usedValue()
+ _ = xs[i]
+ x = 1
+ }
+ update()
+}
+
+func deferredReadAfterCapturedOverwrite() int {
+ x := 0
+ update := func() {
+ x = deadStore() // $ MISSING: Alert
+ defer func() { _ = x }()
+ x = 1
+ }
+ update()
+ return x
+}
+
+func storedClosureBeforeWrite() map[string]func() int {
+ var x int
+ handlers := map[string]func() int{"read": func() int { return x }}
+ x = usedValue()
+ return handlers
+}
+
+func registeredClosureBeforeWrite(register func(func() int)) {
+ var x int
+ register(func() int { return x })
+ x = usedValue()
+}
+
+func goroutineBeforeWrite() {
+ var x int
+ ready := make(chan struct{})
+ go func() {
+ <-ready
+ global = x
+ }()
+ x = usedValue()
+ ready <- struct{}{}
+}
diff --git a/go/ql/test/query-tests/Security/CWE-322/CONSISTENCY/SsaConsistency.expected b/go/ql/test/query-tests/Security/CWE-322/CONSISTENCY/SsaConsistency.expected
deleted file mode 100644
index c8f4be1e602a..000000000000
--- a/go/ql/test/query-tests/Security/CWE-322/CONSISTENCY/SsaConsistency.expected
+++ /dev/null
@@ -1,4 +0,0 @@
-uselessPhiNode
-| InsecureHostKeyCallbackExample.go:152:11:154:5 | SSA phi(err) | 1 |
-phiWithoutTwoPriorRefs
-| InsecureHostKeyCallbackExample.go:152:11:154:5 | SSA phi(err) | InsecureHostKeyCallbackExample.go:152:11:154:5 | Exit | InsecureHostKeyCallbackExample.go:151:63:151:65 | err | 1 |
diff --git a/go/ql/test/query-tests/Security/CWE-643/CONSISTENCY/SsaConsistency.expected b/go/ql/test/query-tests/Security/CWE-643/CONSISTENCY/SsaConsistency.expected
deleted file mode 100644
index 403dd165c0b9..000000000000
--- a/go/ql/test/query-tests/Security/CWE-643/CONSISTENCY/SsaConsistency.expected
+++ /dev/null
@@ -1,4 +0,0 @@
-uselessPhiNode
-| XPathInjection.go:11:1:28:1 | SSA phi(username) | 1 |
-phiWithoutTwoPriorRefs
-| XPathInjection.go:11:1:28:1 | SSA phi(username) | XPathInjection.go:11:1:28:1 | Exceptional Exit | XPathInjection.go:13:2:13:9 | username | 1 |
From 453a309d9de2cc65a018ae5e0aabc477fd09af68 Mon Sep 17 00:00:00 2001
From: Owen Mansel-Chan
Date: Fri, 27 Nov 2026 12:27:40 +0000
Subject: [PATCH 17/17] Go: Synchronize deferred captures at invocation
Preserve registration-time callee and argument evaluation while synchronizing captured values and write-back at deferred invocation for closure callees, arguments, interface-boxed closures, and method receivers.
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
---
.../2026-10-21-variable-capture.md | 2 +-
.../go/dataflow/internal/DataFlowNodes.qll | 5 +
.../go/dataflow/internal/DataFlowPrivate.qll | 8 +
.../go/dataflow/internal/VariableCapture.qll | 95 +++-
.../dataflow/VariableCapture/ArgumentNodes.ql | 36 +-
.../go/dataflow/VariableCapture/Flows.ql | 40 +-
.../go/dataflow/VariableCapture/test.go | 468 +++++++++++++++++-
.../UnhandledCloseWritableHandle.expected | 4 +-
8 files changed, 645 insertions(+), 13 deletions(-)
diff --git a/go/ql/lib/change-notes/2026-10-21-variable-capture.md b/go/ql/lib/change-notes/2026-10-21-variable-capture.md
index 3a5fc7ca0622..f05e48ddd6d5 100644
--- a/go/ql/lib/change-notes/2026-10-21-variable-capture.md
+++ b/go/ql/lib/change-notes/2026-10-21-variable-capture.md
@@ -1,5 +1,5 @@
---
category: minorAnalysis
---
-* Data flow through captured variables now uses the shared variable capture library, keeping captures associated with their closure objects rather than using context-insensitive jumps.
+* Data flow through captured variables now uses the shared variable capture library, keeping captures associated with their closure objects rather than using context-insensitive jumps, and synchronizing captured variables for deferred closures at deferred invocation while preserving registration-time argument evaluation.
* `DataFlow::ArgumentNode` now includes the closure argument at position `-2` for calls through function values.
diff --git a/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll b/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
index 26b81c97e52a..a0d56bc46561 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/DataFlowNodes.qll
@@ -1113,6 +1113,11 @@ module Public {
}
private predicate insnDirectlyHasDeferredPostUpdateNode(IR::Instruction insn) {
+ exists(DeferStmt d |
+ isLambdaCall(d.getCall()) and
+ insn = IR::deferReadCalleeInstruction(d)
+ )
+ or
exists(AddressExpr ae |
isOnDeferSavedAccessPath(_, IR::evalExprInstruction(ae)) and
(
diff --git a/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll b/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll
index e2400bb01e8d..6e573663b870 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/DataFlowPrivate.qll
@@ -217,6 +217,14 @@ predicate deferredPostUpdateFlowStepForDefer(DeferStmt d, Node nodeFrom, Node no
laterRead.reads(rv)
)
)
+ or
+ exists(IR::Instruction anc, IR::Instruction laterRead, boolean inPlace |
+ DataFlow::isOnDeferSavedAccessPath(d, anc) and
+ nodeFrom.(DataFlow::PostUpdateNode).getPreUpdateNode().asInstruction() = anc and
+ laterRead = epilogueNodeAfterDefer(d) and
+ (if deferMutatesInPlace(d, anc) then inPlace = true else inPlace = false) and
+ VariableCapture::deferredPostUpdateReachesCaptureTarget(d, anc, inPlace, laterRead, nodeTo)
+ )
}
/**
diff --git a/go/ql/lib/semmle/go/dataflow/internal/VariableCapture.qll b/go/ql/lib/semmle/go/dataflow/internal/VariableCapture.qll
index 0307e9deb790..1f04966abc1b 100644
--- a/go/ql/lib/semmle/go/dataflow/internal/VariableCapture.qll
+++ b/go/ql/lib/semmle/go/dataflow/internal/VariableCapture.qll
@@ -70,6 +70,8 @@ private predicate closureDirectInstructionStep(IR::Instruction nodeFrom, IR::Ins
nodeFrom = IR::evalExprInstruction(conv.getOperand().stripParens()) and
nodeTo = IR::evalExprInstruction(conv)
)
+ or
+ SsaImpl::tempDefUseStep(nodeFrom, nodeTo)
)
}
@@ -177,7 +179,10 @@ private Flow::ClosureNode asClosureNode(Node n) {
or
exists(IR::Instruction insn |
insn = n.(PostUpdateNode).getPreUpdateNode().asInstruction() and
- DataFlow::insnHasSyncPostUpdateNode(insn) and
+ (
+ DataFlow::insnHasSyncPostUpdateNode(insn) or
+ insn instanceof IR::DeferReadInstruction
+ ) and
result.(Flow::ExprPostUpdateNode).getExpr() = insn
)
or
@@ -206,3 +211,91 @@ predicate clearsContent(Node n, CapturedVariableContent c) {
predicate localFlowStep(Node nodeFrom, Node nodeTo) {
Flow::localFlowStep(asClosureNode(nodeFrom), asClosureNode(nodeTo))
}
+
+private predicate deferCaptureSeed(DeferStmt d, IR::Instruction anc, CapturedVariable v) {
+ DataFlow::isOnDeferSavedAccessPath(d, anc) and
+ anc.reads(v)
+}
+
+private predicate directCaptureWriteAt(CapturedVariable v, BasicBlock bb, int i) {
+ exists(CaptureInput::VariableWrite vw |
+ vw.writes(v, _) and
+ vw.hasCfgNode(bb, i)
+ )
+}
+
+private predicate deferSeedReachesBlockStart(
+ DeferStmt d, IR::Instruction anc, CapturedVariable v, BasicBlock bb
+) {
+ exists(BasicBlock startBb, int startIdx |
+ deferCaptureSeed(d, anc, v) and
+ anc = startBb.getNode(startIdx) and
+ not exists(int writeIdx |
+ writeIdx > startIdx and
+ directCaptureWriteAt(v, startBb, writeIdx)
+ ) and
+ bb = startBb.getASuccessor()
+ )
+ or
+ exists(BasicBlock pred |
+ deferSeedReachesBlockStart(d, anc, v, pred) and
+ not directCaptureWriteAt(v, pred, _) and
+ bb = pred.getASuccessor()
+ )
+}
+
+private predicate deferSeedReachesDeferCallWithoutWrite(
+ DeferStmt d, IR::Instruction anc, CapturedVariable v
+) {
+ exists(IR::Instruction deferCall | deferCall = IR::evalExprInstruction(d.getCall()) |
+ exists(BasicBlock bb, int startIdx, int endIdx |
+ deferCaptureSeed(d, anc, v) and
+ anc = bb.getNode(startIdx) and
+ deferCall = bb.getNode(endIdx) and
+ endIdx > startIdx and
+ not exists(int writeIdx |
+ writeIdx > startIdx and
+ writeIdx < endIdx and
+ directCaptureWriteAt(v, bb, writeIdx)
+ )
+ )
+ or
+ exists(BasicBlock bb, int endIdx |
+ deferSeedReachesBlockStart(d, anc, v, bb) and
+ deferCall = bb.getNode(endIdx) and
+ not exists(int writeIdx |
+ writeIdx < endIdx and
+ directCaptureWriteAt(v, bb, writeIdx)
+ )
+ )
+ )
+}
+
+/**
+ * Holds if `target` reads a captured variable `v` at `laterRead` (either into
+ * a closure's `CaptureNode` or at a named `ReadResultInstruction`), and `anc`
+ * on `d`'s saved access path updates `v` without `v` being overwritten before
+ * `d` runs (unless `inPlace` holds, in which case `d` mutates `v` in place).
+ */
+predicate deferredPostUpdateReachesCaptureTarget(
+ DeferStmt d, IR::Instruction anc, boolean inPlace, IR::Instruction laterRead, Node target
+) {
+ exists(CapturedVariable v | deferCaptureSeed(d, anc, v) |
+ exists(Flow::ExprNode closureNode |
+ closureNode.getExpr() = laterRead and
+ Flow::storeStep(target.(CaptureNode).getSynthesizedCaptureNode(), v, closureNode)
+ |
+ inPlace = true
+ or
+ inPlace = false and
+ deferSeedReachesDeferCallWithoutWrite(d, anc, v)
+ )
+ or
+ inPlace = false and
+ laterRead instanceof IR::ReadResultInstruction and
+ not laterRead instanceof IR::ReadUnnamedResultInstruction and
+ laterRead.reads(v) and
+ deferSeedReachesDeferCallWithoutWrite(d, anc, v) and
+ target = instructionNode(laterRead)
+ )
+}
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.ql b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.ql
index 8153cddc1788..0e7eaadfb604 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.ql
+++ b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/ArgumentNodes.ql
@@ -3,13 +3,29 @@ private import semmle.go.dataflow.internal.DataFlowPrivate as Impl
private import semmle.go.dataflow.internal.DataFlowNodes::Private as Nodes
import utils.test.InlineExpectationsTest
+private class ModelCopyToFirstArg extends DataFlow::FunctionModel {
+ ModelCopyToFirstArg() { this.getName() = "modelCopyToFirstArg" }
+
+ override predicate hasDataFlow(FunctionInput inp, FunctionOutput outp) {
+ inp.isParameter(1) and outp.isParameter(0)
+ }
+}
+
+private class ModelTaintToFirstArg extends TaintTracking::FunctionModel {
+ ModelTaintToFirstArg() { this.getName() = "modelTaintToFirstArg" }
+
+ override predicate hasTaintFlow(FunctionInput inp, FunctionOutput outp) {
+ inp.isParameter(1) and outp.isParameter(0)
+ }
+}
+
module ArgumentNodesTest implements TestSig {
string getARelevantTag() {
result =
[
"closure-args", "callee-post", "closure-post", "argument-post", "syntactic-arg",
- "receiver-post", "closure-params", "receiver-node", "function-receiver", "input-receiver",
- "receiver-agreement"
+ "receiver-post", "model-effective-input", "closure-params", "receiver-node",
+ "function-receiver", "input-receiver", "receiver-agreement"
]
}
@@ -34,13 +50,13 @@ module ArgumentNodesTest implements TestSig {
.toString()
or
tag = "argument-post" and
- call.getTarget().getName() = "callback" and
+ call.getTarget().getName() = ["callback", "callbackAny"] and
value =
count(DataFlow::PostUpdateNode post | post.getPreUpdateNode() = Impl::getArgument(call, 0))
.toString()
or
tag = "syntactic-arg" and
- call.getTarget().getName() = "callback" and
+ call.getTarget().getName() = ["callback", "callbackAny"] and
value =
count(DataFlow::ArgumentNode argument |
argument.argumentOf(call.asExpr(), 0) and
@@ -53,6 +69,18 @@ module ArgumentNodesTest implements TestSig {
count(DataFlow::PostUpdateNode post |
post.getPreUpdateNode() = call.(DataFlow::MethodCallNode).getReceiver()
).toString()
+ or
+ tag = "model-effective-input" and
+ call.getTarget().getName() = ["modelCopyToFirstArg", "modelTaintToFirstArg"] and
+ value =
+ count(DataFlow::Node inp |
+ (
+ exists(DataFlow::FunctionModel m | inp = m.getAnInputNode(call))
+ or
+ exists(TaintTracking::FunctionModel m | inp = m.getAnInputNode(call))
+ ) and
+ inp = Impl::getArgument(call, 1)
+ ).toString()
)
or
exists(FuncLit function |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/Flows.ql b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/Flows.ql
index c2279ca42298..df0e63aaa581 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/Flows.ql
+++ b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/Flows.ql
@@ -1,10 +1,48 @@
import utils.test.InlineFlowTest
-import ValueFlowTest
private import semmle.go.dataflow.internal.VariableCapture as Capture
private import semmle.go.dataflow.internal.DataFlowUtil as Util
private import semmle.go.dataflow.internal.DataFlowNodes::Private as Nodes
private import semmle.go.dataflow.internal.DataFlowPrivate as PrivateFlow
+module TaintModelFlowConfig implements DataFlow::ConfigSig {
+ predicate isSource(DataFlow::Node source) {
+ DefaultFlowConfig::isSource(source) and
+ source
+ .asExpr()
+ .getEnclosingFunction*()
+ .(FuncDecl)
+ .getName()
+ .matches("deferredTaintFunctionModel%")
+ }
+
+ predicate isSink(DataFlow::Node sink) {
+ DefaultFlowConfig::isSink(sink) and
+ sink.asExpr()
+ .getEnclosingFunction*()
+ .(FuncDecl)
+ .getName()
+ .matches("deferredTaintFunctionModel%")
+ }
+}
+
+import FlowTest
+
+private class ModelCopyToFirstArg extends DataFlow::FunctionModel {
+ ModelCopyToFirstArg() { this.getName() = "modelCopyToFirstArg" }
+
+ override predicate hasDataFlow(FunctionInput inp, FunctionOutput outp) {
+ inp.isParameter(1) and outp.isParameter(0)
+ }
+}
+
+private class ModelTaintToFirstArg extends TaintTracking::FunctionModel {
+ ModelTaintToFirstArg() { this.getName() = "modelTaintToFirstArg" }
+
+ override predicate hasTaintFlow(FunctionInput inp, FunctionOutput outp) {
+ inp.isParameter(1) and outp.isParameter(0)
+ }
+}
+
query predicate spuriousConstructionClearing(DataFlow::Node construction, string variable) {
construction.asExpr() instanceof FuncLit and
exists(Util::CapturedVariableContent content |
diff --git a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/test.go b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/test.go
index 887ae9577c0e..3734f1db5e58 100644
--- a/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/test.go
+++ b/go/ql/test/library-tests/semmle/go/dataflow/VariableCapture/test.go
@@ -166,6 +166,116 @@ func sharedEscapedStorage() {
sink(get()) // $ MISSING: hasValueFlow="call to get"
}
+func deferredReadAfterRegistration() {
+ x := "safe"
+ defer func() { sink(x) }() // $ hasValueFlow="x"
+ x = source()
+}
+
+func deferredOverwriteAfterRegistration() {
+ x := source()
+ defer func() { sink(x) }()
+ x = "safe"
+}
+
+func deferredResult() (x string) {
+ defer func() { x = source() }()
+ return "safe"
+}
+
+func deferredNamedResult() {
+ sink(deferredResult()) // $ hasValueFlow="call to deferredResult"
+}
+
+func deferredCallsRunInReverseOrder() {
+ x := "safe"
+ defer func() { sink(x) }() // $ hasValueFlow="x"
+ defer func() { x = source() }()
+}
+
+func deferredArgumentsEvaluatedEarly() {
+ x := source()
+ defer func(arg string) {
+ sink(arg) // $ hasValueFlow="arg"
+ sink(x)
+ }(x)
+ x = "safe"
+}
+
+func deferredCapturesReadLate() {
+ x := "safe"
+ defer func(arg string) {
+ sink(arg)
+ sink(x) // $ hasValueFlow="x"
+ }(x)
+ x = source()
+}
+
+func deferredCalleeEvaluatedEarly() {
+ x := "safe"
+ f := func() { sink(x) } // $ hasValueFlow="x"
+ defer f()
+ f = func() {}
+ x = source()
+}
+
+func deferredCalleeIsNotReevaluated() {
+ x := source()
+ f := func() {}
+ defer f()
+ f = func() { sink(x) }
+}
+
+func deferredCallback() {
+ x := "safe"
+ defer callback(func() { sink(x) }) // $ hasValueFlow="x"
+ x = source()
+}
+
+func runBoth(f, g func()) {
+ f()
+ g()
+}
+
+func deferredMultipleCallbacks() {
+ x := "safe"
+ defer runBoth(
+ func() { sink(x) }, // $ hasValueFlow="x"
+ func() { sink(x) }, // $ hasValueFlow="x"
+ )
+ x = source()
+}
+
+func deferredHigherOrderClosure() {
+ x := "safe"
+ run := func(f func()) {
+ sink(x) // $ hasValueFlow="x"
+ f()
+ }
+ defer run(func() { sink(x) }) // $ hasValueFlow="x"
+ x = source()
+}
+
+type runner interface{ run() }
+
+type runnableFunc func()
+
+func (f runnableFunc) run() { f() }
+
+func deferredMethodReceiver() {
+ x := "safe"
+ h := runnableFunc(func() { sink(x) }) // $ hasValueFlow="x"
+ defer h.run()
+ x = source()
+}
+
+func deferredMethodReceiverOverwrite() {
+ x := source()
+ h := runnableFunc(func() { sink(x) })
+ defer h.run()
+ x = "safe"
+}
+
func apply(f func(string) string, s string) string { return f(s) }
func identity(s string) string { return s }
@@ -311,6 +421,8 @@ func closureArgumentNodes() {
genericIdentity[string]("safe") // $ closure-args,callee-post,closure-post=0
r := receiver{}
r.identity("safe") // $ closure-args,callee-post,closure-post=0 receiver-post=1
+ var im identityMethod = r
+ defer im.identity("safe") // $ closure-args,callee-post,closure-post=0 receiver-post=1
f := func() {} // $ closure-params=0
f() // $ closure-args,callee-post,closure-post=1
@@ -320,9 +432,27 @@ func closureArgumentNodes() {
method("safe") // $ closure-args,callee-post,closure-post=1
x := "safe"
- g := func() { _ = x } // $ closure-params=1
- g() // $ closure-args,callee-post,closure-post=1
- callback(g) // $ closure-args,callee-post,closure-post=0 argument-post,syntactic-arg=1
+ g := func() { _ = x } // $ closure-params=1
+ g() // $ closure-args,callee-post,closure-post=1
+ callback(g) // $ closure-args,callee-post,closure-post=0 argument-post,syntactic-arg=1
+ defer constant("safe") // $ closure-args,callee-post,closure-post=0
+ defer f() // $ closure-args,callee-post,closure-post=1
+ defer (f)() // $ closure-args,callee-post,closure-post=1
+ defer callback(g) // $ closure-args,callee-post,closure-post=0 argument-post,syntactic-arg=1
+ defer callback((g)) // $ closure-args,callee-post,closure-post=0 argument-post,syntactic-arg=1
+ callbackAny(g) // $ closure-args,callee-post,closure-post=0 argument-post,syntactic-arg=1
+ defer callbackAny(g) // $ closure-args,callee-post,closure-post=0 argument-post,syntactic-arg=1
+ var nonClosure any = &receiver{}
+ defer callbackAny(nonClosure) // $ closure-args,callee-post,closure-post=0 argument-post,syntactic-arg=1
+ h := runnableFunc(g)
+ h.run() // $ closure-args,callee-post,closure-post=0 receiver-post=1
+ defer h.run() // $ closure-args,callee-post,closure-post=0 receiver-post=1
+ var rh runner = h
+ rh.run() // $ closure-args,callee-post,closure-post=0 receiver-post=1
+ defer rh.run() // $ closure-args,callee-post,closure-post=0 receiver-post=1
+ var dst any
+ defer modelCopyToFirstArg(&dst, g) // $ closure-args,callee-post,closure-post=0 model-effective-input=1
+ defer modelTaintToFirstArg(&dst, g) // $ closure-args,callee-post,closure-post=0 model-effective-input=1
}
func localCapturedFlow() {
@@ -397,3 +527,335 @@ func (r receiver) directReceiver() string { // $ receiver-node,function-receiver
}
func (r receiver) unusedReceiver() {} // $ receiver-node,function-receiver,input-receiver,receiver-agreement=1
+
+func callbackAny(f any) {
+ if fn, ok := f.(func()); ok {
+ fn()
+ }
+}
+
+func deferredInterfaceReadAfterRegistration() {
+ x := "safe"
+ var f any = func() { sink(x) } // $ hasValueFlow="x"
+ defer callbackAny(f)
+ x = source()
+}
+
+func deferredInterfaceOverwriteAfterRegistration() {
+ x := source()
+ var f any = func() { sink(x) }
+ defer callbackAny(f)
+ x = "safe"
+}
+
+func deferredInterfaceArgumentEvaluatedEarly() {
+ x := "safe"
+ var f any = func() { sink(x) } // $ hasValueFlow="x"
+ defer callbackAny(f)
+ f = func() {}
+ x = source()
+}
+
+func deferredInterfaceArgumentIsNotReevaluated() {
+ x := source()
+ var f any = func() {}
+ defer callbackAny(f)
+ f = func() { sink(x) }
+}
+
+func setViaAny(dst any, s string) {
+ dst.(*receiver).value = s
+}
+
+func deferredNonClosureInterfacePostUpdate() {
+ var dst any = &receiver{}
+ defer func() { sink(dst.(*receiver).value) }() // $ hasValueFlow="selection of value"
+ defer setViaAny(dst, source())
+}
+
+func deferredNonClosureInterfaceWithInnerClosureWrite() {
+ var dst any = &receiver{}
+ init := func() {
+ if false {
+ dst = func() {}
+ }
+ }
+ init()
+ defer func() { sink(dst.(*receiver).value) }() // $ hasValueFlow="selection of value"
+ defer setViaAny(dst, source())
+}
+
+func deferredParenthesizedClosure() {
+ x := "safe"
+ f := func() { sink(x) } // $ hasValueFlow="x"
+ defer (f)()
+ x = source()
+}
+
+func deferredParenthesizedCallback() {
+ x := "safe"
+ g := func() { sink(x) } // $ hasValueFlow="x"
+ defer callback((g))
+ x = source()
+}
+
+func deferredParenthesizedReceiver() {
+ x := "safe"
+ h := runnableFunc((func() { sink(x) })) // $ hasValueFlow="x"
+ defer (h).run()
+ x = source()
+}
+
+func modelCopyToFirstArg(dst any, src any)
+func modelTaintToFirstArg(dst any, src any)
+
+func deferredFunctionModelOutParameter(cond bool) {
+ var dst any = &receiver{}
+ if cond {
+ dst = func() {}
+ }
+ defer func() {
+ if s, ok := dst.(string); ok {
+ sink(s) // $ hasValueFlow="s"
+ }
+ }()
+ defer modelCopyToFirstArg(dst, source())
+}
+
+func deferredFunctionModelOutParameterReverseOrder(cond bool) {
+ var dst any = &receiver{}
+ if cond {
+ dst = func() {}
+ }
+ defer modelCopyToFirstArg(dst, source())
+ defer func() {
+ if s, ok := dst.(string); ok {
+ sink(s)
+ }
+ }()
+}
+
+func setViaAnySafe(dst any, s string) {
+ if r, ok := dst.(*receiver); ok {
+ r.value = s
+ }
+}
+
+func deferredMixedInterfacePostUpdate(cond bool) {
+ var dst any = &receiver{}
+ if cond {
+ dst = func() {}
+ }
+ defer func() {
+ if r, ok := dst.(*receiver); ok {
+ sink(r.value) // $ hasValueFlow="selection of value"
+ }
+ }()
+ defer setViaAnySafe(dst, source())
+}
+
+func deferredMixedInterfacePostUpdateReverseOrder(cond bool) {
+ var dst any = &receiver{}
+ if cond {
+ dst = func() {}
+ }
+ defer setViaAnySafe(dst, source())
+ defer func() {
+ if r, ok := dst.(*receiver); ok {
+ sink(r.value)
+ }
+ }()
+}
+
+func deferredMixedInterfaceBodyReadBeforeExit(cond bool) {
+ var dst any = &receiver{}
+ if cond {
+ dst = func() { _ = dst }
+ }
+ defer setViaAnySafe(dst, source())
+ if r, ok := dst.(*receiver); ok {
+ sink(r.value)
+ }
+}
+
+func deferredMixedInterfaceOverwrittenBeforeExit(cond bool) {
+ var dst any = &receiver{}
+ if cond {
+ dst = func() {}
+ }
+ defer func() {
+ if r, ok := dst.(*receiver); ok {
+ sink(r.value)
+ }
+ }()
+ defer setViaAnySafe(dst, source())
+ dst = &receiver{}
+}
+
+func deferredMixedInterfaceInnerClosure(cond bool) {
+ var dst any = &receiver{}
+ inner := func() {
+ if cond {
+ dst = func() {}
+ }
+ defer setViaAnySafe(dst, source())
+ }
+ inner()
+ if r, ok := dst.(*receiver); ok {
+ sink(r.value) // $ hasValueFlow="selection of value"
+ }
+}
+
+func deferredMixedInterfaceNamedReturn(cond bool) (dst any) {
+ dst = &receiver{}
+ if cond {
+ dst = func() { _ = dst }
+ }
+ defer setViaAnySafe(dst, source())
+ return
+}
+
+func useDeferredMixedInterfaceNamedReturn(cond bool) {
+ if r, ok := deferredMixedInterfaceNamedReturn(cond).(*receiver); ok {
+ sink(r.value) // $ hasValueFlow="selection of value"
+ }
+}
+
+func deferredMixedInterfaceExplicitReturn(cond bool) any {
+ var dst any = &receiver{}
+ if cond {
+ dst = func() { _ = dst }
+ }
+ defer setViaAnySafe(dst, source())
+ return dst
+}
+
+func useDeferredMixedInterfaceExplicitReturn(cond bool) {
+ if r, ok := deferredMixedInterfaceExplicitReturn(cond).(*receiver); ok {
+ sink(r.value) // $ hasValueFlow="selection of value"
+ }
+}
+
+func deferredMixedInterfaceExplicitReturnReverseDefer(cond bool) any {
+ var dst any = &receiver{}
+ if cond {
+ dst = func() {}
+ }
+ defer setViaAnySafe(dst, source())
+ defer func() {
+ if r, ok := dst.(*receiver); ok {
+ sink(r.value)
+ }
+ }()
+ return dst
+}
+
+func useDeferredMixedInterfaceExplicitReturnReverseDefer(cond bool) {
+ if r, ok := deferredMixedInterfaceExplicitReturnReverseDefer(cond).(*receiver); ok {
+ sink(r.value) // $ hasValueFlow="selection of value"
+ }
+}
+
+func deferredFunctionModelClosureInput(cond bool) (dst any) {
+ x := "safe"
+ dst = &receiver{}
+ if cond {
+ dst = func() { _ = dst }
+ }
+ src := func() {
+ sink(x) // $ hasValueFlow="x"
+ }
+ defer modelCopyToFirstArg(dst, src)
+ x = source()
+ return
+}
+
+func useDeferredFunctionModelClosureInput(cond bool) {
+ if f, ok := deferredFunctionModelClosureInput(cond).(func()); ok {
+ f()
+ }
+}
+
+func deferredFunctionModelClosureInputOverwrite(cond bool) (dst any) {
+ x := source()
+ dst = &receiver{}
+ if cond {
+ dst = func() { _ = dst }
+ }
+ src := func() {
+ sink(x)
+ }
+ defer modelCopyToFirstArg(dst, src)
+ x = "safe"
+ return
+}
+
+func useDeferredFunctionModelClosureInputOverwrite(cond bool) {
+ if f, ok := deferredFunctionModelClosureInputOverwrite(cond).(func()); ok {
+ f()
+ }
+}
+
+func deferredTaintFunctionModelMixedInput(cond bool) {
+ var dst any = &receiver{}
+ var src any = source()
+ if cond {
+ dst = func() {}
+ src = func() {}
+ }
+ defer func() {
+ if s, ok := dst.(string); ok {
+ sink(s) // $ hasTaintFlow="s"
+ }
+ }()
+ defer modelTaintToFirstArg(dst, src)
+}
+
+func deferredTaintFunctionModelMixedInputReverseOrder(cond bool) {
+ var dst any = &receiver{}
+ var src any = source()
+ if cond {
+ dst = func() {}
+ src = func() {}
+ }
+ defer modelTaintToFirstArg(dst, src)
+ defer func() {
+ if s, ok := dst.(string); ok {
+ sink(s)
+ }
+ }()
+}
+
+type mutator interface{ mutate(string) }
+
+func (r *receiver) mutate(s string) { r.value = s }
+
+type mutatorFunc func(string)
+
+func (f mutatorFunc) mutate(s string) { f(s) }
+
+func deferredMixedInterfaceMethodReceiver(cond bool) {
+ var m mutator = &receiver{}
+ if cond {
+ m = mutatorFunc(func(string) {})
+ }
+ defer func() {
+ if r, ok := m.(*receiver); ok {
+ sink(r.value) // $ hasValueFlow="selection of value"
+ }
+ }()
+ defer m.mutate(source())
+}
+
+func deferredMixedInterfaceMethodReceiverReverseOrder(cond bool) {
+ var m mutator = &receiver{}
+ if cond {
+ m = mutatorFunc(func(string) {})
+ }
+ defer m.mutate(source())
+ defer func() {
+ if r, ok := m.(*receiver); ok {
+ sink(r.value)
+ }
+ }()
+}
diff --git a/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected b/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected
index 30309ed8ea8e..9b44a9f3d683 100644
--- a/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected
+++ b/go/ql/test/query-tests/InconsistentCode/UnhandledCloseWritableHandle/UnhandledCloseWritableHandle.expected
@@ -13,8 +13,7 @@
| tests.go:228:8:228:13 | chosen | tests.go:220:2:220:75 | extract:0 ... := ... | tests.go:228:8:228:13 | chosen | File handle may be writable as a result of data flow from a $@ and closing it may result in data loss upon failure, which is not handled explicitly. | tests.go:220:12:220:75 | call to OpenFile | call to OpenFile |
edges
| tests.go:9:24:9:24 | SSA param(f) | tests.go:10:8:10:8 | f | provenance | |
-| tests.go:13:32:13:32 | f | tests.go:18:8:18:11 | cont [captured f] | provenance | |
-| tests.go:18:8:18:11 | cont [captured f] | tests.go:15:3:15:3 | f | provenance | |
+| tests.go:13:32:13:32 | f | tests.go:15:3:15:3 | f | provenance | |
| tests.go:32:5:32:78 | extract:0 ... := ... | tests.go:33:21:33:21 | f | provenance | Src:MaD:1 |
| tests.go:32:5:32:78 | extract:0 ... := ... | tests.go:34:29:34:29 | f | provenance | Src:MaD:1 |
| tests.go:33:21:33:21 | f | tests.go:9:24:9:24 | SSA param(f) | provenance | |
@@ -38,7 +37,6 @@ nodes
| tests.go:10:8:10:8 | f | semmle.label | f |
| tests.go:13:32:13:32 | f | semmle.label | f |
| tests.go:15:3:15:3 | f | semmle.label | f |
-| tests.go:18:8:18:11 | cont [captured f] | semmle.label | cont [captured f] |
| tests.go:32:5:32:78 | extract:0 ... := ... | semmle.label | extract:0 ... := ... |
| tests.go:33:21:33:21 | f | semmle.label | f |
| tests.go:34:29:34:29 | f | semmle.label | f |