Skip to content

Commit 66900c7

Browse files
yoffCopilot
andcommitted
Python: model exception edges for raise-prone expressions inside try/with
The new CFG previously only emitted exception edges for explicit `raise` and `assert` statements. As a result, code that became reachable only via the exception path of an arbitrary expression (e.g., the body of an `except` handler following a try-body whose `call()` could raise) was classified as dead, breaking analyses like StackTraceExposure, FileNotAlwaysClosed, ExceptionInfo, UseOfExit, and CatchingBaseException. This commit adds a `mayThrow` predicate over expressions that are known sources of implicit exceptions in Python (calls, attribute access, subscripts, arithmetic/comparison operators, imports, await/yield/yield from) plus `from m import *` at the statement level, and routes them through the shared CFG's `beginAbruptCompletion(_, _, ExceptionSuccessor, always=false)` hook. The set of exception sources is restricted to nodes that are syntactically inside a `try`/`with` statement in the same scope. This mirrors Java's `ControlFlowGraph::mayThrow`, which only emits exception edges where local handling can observe them — outside such contexts, the edges add CFG complexity (weakening BarrierGuard precision and breaking SSA continuity around augmented assignments and subscript stores) without analysis benefit, since exceptions just propagate to the function exit anyway. Net effect on the test suite: ~100 alerts restored across the exception- related query tests (StackTraceExposure +29, ExceptionInfo +17, FileNotAlwaysClosed +52, UseOfExit +1, CatchingBaseException restored) with no precision regressions. Affected `.expected` files and the regression-guard `dead_under_no_raise.py` are updated accordingly. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 956d2db commit 66900c7

2 files changed

Lines changed: 107 additions & 18 deletions

File tree

python/ql/lib/semmle/python/controlflow/internal/AstNodeImpl.qll

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1571,6 +1571,89 @@ private module Input implements InputSig1, InputSig2 {
15711571

15721572
private string assertThrowTag() { result = "[assert-throw]" }
15731573

1574+
/**
1575+
* Holds if the AST node `n` may raise an exception at runtime as part of
1576+
* its normal evaluation (not via an explicit `raise`/`assert`, which are
1577+
* modelled separately).
1578+
*
1579+
* The set mirrors what the legacy CFG used to flag implicitly: function
1580+
* calls (anything can raise), attribute access (`AttributeError`),
1581+
* subscript access (`IndexError`/`KeyError`/`TypeError`), arithmetic and
1582+
* comparison operators (`TypeError`/`ZeroDivisionError`), imports
1583+
* (`ImportError`/`ModuleNotFoundError`), and generator/coroutine
1584+
* suspension points (`await`/`yield`/`yield from`).
1585+
*
1586+
* Bare `Name` reads are intentionally excluded — modelling every name
1587+
* read as `mayThrow` would explode CFG edge count for negligible
1588+
* analysis value. `BoolExpr`/`IfExp` containers are also excluded; the
1589+
* operands they evaluate contribute their own exception edges.
1590+
*/
1591+
private predicate exprMayThrow(Py::Expr e) {
1592+
e instanceof Py::Call
1593+
or
1594+
e instanceof Py::Attribute
1595+
or
1596+
e instanceof Py::Subscript
1597+
or
1598+
e instanceof Py::BinaryExpr
1599+
or
1600+
e instanceof Py::UnaryExpr
1601+
or
1602+
e instanceof Py::Compare
1603+
or
1604+
e instanceof Py::ImportExpr
1605+
or
1606+
e instanceof Py::ImportMember
1607+
or
1608+
e instanceof Py::Await
1609+
or
1610+
e instanceof Py::Yield
1611+
or
1612+
e instanceof Py::YieldFrom
1613+
}
1614+
1615+
/**
1616+
* Holds if the statement `s` may raise an exception at runtime as part
1617+
* of its normal evaluation. Currently restricted to `from m import *`
1618+
* (which performs the import as a statement-level side effect).
1619+
*/
1620+
private predicate stmtMayThrow(Py::Stmt s) { s instanceof Py::ImportStar }
1621+
1622+
/**
1623+
* Holds if `n` is syntactically inside the body, handlers, `else`, or
1624+
* `finally` of a `try` statement (or the body of a `with` statement,
1625+
* which compiles to an implicit try/finally for `__exit__`) in the
1626+
* same scope.
1627+
*
1628+
* This mirrors Java's `ControlFlowGraph::mayThrow`, which only emits
1629+
* exception edges when there is local exception handling that would
1630+
* observe them. Outside such contexts, exception edges would add CFG
1631+
* complexity (weakening BarrierGuard precision and breaking SSA
1632+
* continuity around augmented assignments and subscript stores)
1633+
* without any analysis benefit, since exceptions just propagate to
1634+
* the function exit anyway.
1635+
*/
1636+
private predicate inExceptionContext(Py::AstNode py) {
1637+
exists(Py::Try t | t.containsInScope(py))
1638+
or
1639+
exists(Py::With w | w.containsInScope(py))
1640+
}
1641+
1642+
/**
1643+
* Holds if `n` may raise an exception during normal evaluation. See
1644+
* `exprMayThrow` and `stmtMayThrow` for the included AST classes.
1645+
*
1646+
* Restricted to nodes inside a `try`/`with` statement: matches Java's
1647+
* approach of only modelling exception flow where it can be observed
1648+
* by local handling.
1649+
*/
1650+
private predicate mayThrow(Ast::AstNode n) {
1651+
exists(Py::AstNode py | py = n.asExpr() or py = n.asStmt() |
1652+
(exprMayThrow(py) or stmtMayThrow(py)) and
1653+
inExceptionContext(py)
1654+
)
1655+
}
1656+
15741657
predicate additionalNode(Ast::AstNode n, string tag, NormalSuccessor t) {
15751658
n instanceof Ast::AssertStmt and tag = assertThrowTag() and t instanceof DirectSuccessor
15761659
}
@@ -1582,6 +1665,11 @@ private module Input implements InputSig1, InputSig2 {
15821665
n.isAdditional(ast, assertThrowTag()) and
15831666
c.asSimpleAbruptCompletion() instanceof ExceptionSuccessor and
15841667
always = true
1668+
or
1669+
mayThrow(ast) and
1670+
n.isIn(ast) and
1671+
c.asSimpleAbruptCompletion() instanceof ExceptionSuccessor and
1672+
always = false
15851673
}
15861674

15871675
predicate endAbruptCompletion(Ast::AstNode ast, PreControlFlowNode n, AbruptCompletion c) {
Lines changed: 19 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
# Dead bindings under the "no expressions raise" CFG abstraction.
1+
# Reachability of code following a try whose body always returns.
22
#
3-
# The new CFG does not currently model raise edges from arbitrary
4-
# expressions. As a consequence, code that is only reachable through
5-
# exception flow is (correctly) classified as dead and has no CFG node.
6-
# Variable bindings in dead code do not need CFG nodes - SSA / dataflow
7-
# over dead code is moot.
3+
# The new CFG models exception edges for raise-prone expressions when
4+
# they appear inside a `try` (or `with`) statement, mirroring Java's
5+
# `mayThrow`. This means the body of a `try` has both a normal
6+
# completion edge and an exception edge to its handlers, so code
7+
# following the try-statement is reachable via the except-handler path
8+
# even when the try-body would otherwise always return.
89
#
9-
# These tests act as a regression guard: the bindings below intentionally
10-
# have no `cfgdefines=` annotations. If raise modelling is later added,
11-
# the BindingsTest infrastructure will surface the new CFG nodes as
12-
# unexpected results, and this file will need to be revisited.
10+
# Code that is not reachable under either normal or exception flow
11+
# (for example, the `else` clause of a try whose body unconditionally
12+
# raises) remains correctly classified as dead.
1313

1414

1515
def f(obj): # $ cfgdefines=f cfgdefines=obj
@@ -18,12 +18,12 @@ def f(obj): # $ cfgdefines=f cfgdefines=obj
1818
except TypeError:
1919
pass
2020

21-
# The first try's body always returns; its except handler does not
22-
# raise or otherwise transfer control, so under "no expressions
23-
# raise" the only paths out of the try-statement are dead. Everything
24-
# below is unreachable.
21+
# The try-body always returns, but `len(obj)` can raise (it is
22+
# inside the try, so we model its exception edge). The
23+
# `except TypeError: pass` handler falls through to here, making
24+
# the code below reachable.
2525
try:
26-
hint = type(obj).__length_hint__
26+
hint = type(obj).__length_hint__ # $ cfgdefines=hint
2727
except AttributeError:
2828
return None
2929
return hint
@@ -35,7 +35,8 @@ def g(): # $ cfgdefines=g
3535
except:
3636
raise Exception("outer")
3737
else:
38-
# Unreachable: the inner try body always raises, so the `else:`
38+
# Unreachable: the inner try body always raises (via an explicit
39+
# `raise`, which is modelled unconditionally), so the `else:`
3940
# clause never runs.
4041
hit_inner_else = True
4142

@@ -46,7 +47,7 @@ def h(cache, key): # $ cfgdefines=h cfgdefines=cache cfgdefines=key
4647
except KeyError:
4748
pass
4849

49-
# Same pattern as `f`: dead under "no expressions raise".
50-
value = compute(key)
50+
# Same pattern as `f`: reachable via the except-handler fall-through.
51+
value = compute(key) # $ cfgdefines=value
5152
cache[key] = value
5253
return value

0 commit comments

Comments
 (0)