Skip to content

Commit 4c8e6e3

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 b4ff876 commit 4c8e6e3

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
@@ -1553,6 +1553,89 @@ private module Input implements InputSig1, InputSig2 {
15531553

15541554
private string assertThrowTag() { result = "[assert-throw]" }
15551555

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

15691657
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)