Skip to content

Commit b783ed6

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 5b9803e commit b783ed6

13 files changed

Lines changed: 144 additions & 80 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
@@ -1543,6 +1543,89 @@ private module Input implements InputSig1, InputSig2 {
15431543

15441544
private string assertThrowTag() { result = "[assert-throw]" }
15451545

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

15591647
predicate endAbruptCompletion(Ast::AstNode ast, PreControlFlowNode n, AbruptCompletion c) {

python/ql/test/experimental/library-tests/FindSubclass/Find.expected

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
| flask.MethodView~Subclass | find_subclass_test | Member[C] |
55
| flask.View~Subclass | find_subclass_test | Member[A] |
66
| flask.View~Subclass | find_subclass_test | Member[B] |
7+
| flask.View~Subclass | find_subclass_test | Member[ViewAliasInExcept] |
78
| flask.View~Subclass | find_subclass_test | Member[ViewAliasInTry] |
89
| flask.View~Subclass | find_subclass_test | Member[ViewAlias] |
910
| flask.View~Subclass | find_subclass_test | Member[ViewAlias_no_use] |
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

python/ql/test/library-tests/dataflow-new-ssa-vs-legacy/CmpTest.expected

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,5 +2,4 @@
22
| def-only-old | __name__:0:0 |
33
| def-only-old | __package__:0:0 |
44
| def-only-old | e:37:1 |
5-
| def-only-old | e:40:25 |
65
| def-only-old | x:20:1 |

python/ql/test/library-tests/dataflow/coverage/test.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -844,7 +844,7 @@ def return_from_inner_scope(x):
844844
return SOURCE
845845

846846
def test_return_from_inner_scope():
847-
SINK(return_from_inner_scope([])) # $ MISSING: flow="SOURCE, l:-3 -> return_from_inner_scope(..)"
847+
SINK(return_from_inner_scope([])) # $ flow="SOURCE, l:-3 -> return_from_inner_scope(..)"
848848

849849

850850
# Inspired by reverse read inconsistency check
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
11
| exceptions_test.py:7:5:7:11 | ExceptStmt | Except block directly handles BaseException. |
2+
| exceptions_test.py:97:5:97:25 | ExceptStmt | Except block directly handles BaseException. |

python/ql/test/query-tests/Exceptions/general/EmptyExcept.expected

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,3 @@
33
| exceptions_test.py:72:1:72:18 | ExceptStmt | 'except' clause does nothing but pass and there is no explanatory comment. |
44
| exceptions_test.py:85:1:85:17 | ExceptStmt | 'except' clause does nothing but pass and there is no explanatory comment. |
55
| exceptions_test.py:89:1:89:17 | ExceptStmt | 'except' clause does nothing but pass and there is no explanatory comment. |
6-
| exceptions_test.py:144:5:144:25 | ExceptStmt | 'except' clause does nothing but pass and there is no explanatory comment. |
7-
| exceptions_test.py:167:5:167:26 | ExceptStmt | 'except' clause does nothing but pass and there is no explanatory comment. |
8-
| exceptions_test.py:173:5:173:22 | ExceptStmt | 'except' clause does nothing but pass and there is no explanatory comment. |
9-
| exceptions_test.py:179:5:179:22 | ExceptStmt | 'except' clause does nothing but pass and there is no explanatory comment. |
10-
| exceptions_test.py:185:5:185:26 | ExceptStmt | 'except' clause does nothing but pass and there is no explanatory comment. |
11-
| exceptions_test.py:191:5:191:30 | ExceptStmt | 'except' clause does nothing but pass and there is no explanatory comment. |
Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1 @@
1-
#select
2-
testFailures
3-
| exceptions_test.py:64:24:64:55 | Comment # $ Alert[py/unreachable-except] | Missing result: Alert[py/unreachable-except] |
1+
| exceptions_test.py:64:1:64:22 | ExceptStmt | This except block handling $@ is unreachable; as $@ for the more general $@ always subsumes it. | file://:0:0:0:0 | AttributeError | AttributeError | exceptions_test.py:62:1:62:17 | ExceptStmt | this except block | file://:0:0:0:0 | Exception | Exception |
Lines changed: 0 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,9 @@
1-
#select
21
| resources_test.py:4:10:4:25 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:5:5:5:33 | After Attribute() | this operation |
32
| resources_test.py:9:10:9:25 | After open() | File is opened but is not closed. | file://:0:0:0:0 | (none) | this operation |
4-
| resources_test.py:20:10:20:25 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:22:9:22:37 | After Attribute() | this operation |
5-
| resources_test.py:30:14:30:29 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:31:9:31:37 | After Attribute() | this operation |
6-
| resources_test.py:39:14:39:29 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:40:9:40:37 | After Attribute() | this operation |
7-
| resources_test.py:49:14:49:29 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:50:9:50:37 | After Attribute() | this operation |
8-
| resources_test.py:58:14:58:29 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:59:9:59:37 | After Attribute() | this operation |
9-
| resources_test.py:69:11:69:26 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:71:9:71:40 | After Attribute() | this operation |
10-
| resources_test.py:69:11:69:26 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:72:9:72:40 | After Attribute() | this operation |
11-
| resources_test.py:79:11:79:26 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:81:9:81:40 | After Attribute() | this operation |
12-
| resources_test.py:79:11:79:26 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:82:9:82:40 | After Attribute() | this operation |
13-
| resources_test.py:91:11:91:26 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:93:9:93:40 | After Attribute() | this operation |
14-
| resources_test.py:91:11:91:26 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:94:9:94:40 | After Attribute() | this operation |
153
| resources_test.py:108:11:108:20 | After open() | File is opened but is not closed. | file://:0:0:0:0 | (none) | this operation |
164
| resources_test.py:112:11:112:28 | After opener_func2() | File may not be closed if $@ raises an exception. | resources_test.py:113:5:113:22 | After Attribute() | this operation |
175
| resources_test.py:123:11:123:24 | After opener_func2() | File is opened but is not closed. | file://:0:0:0:0 | (none) | this operation |
186
| resources_test.py:129:15:129:24 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:130:9:130:26 | After Attribute() | this operation |
19-
| resources_test.py:141:11:141:26 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:143:9:143:40 | After Attribute() | this operation |
20-
| resources_test.py:141:11:141:26 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:144:9:144:40 | After Attribute() | this operation |
21-
| resources_test.py:182:15:182:54 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:186:9:186:25 | After Attribute() | this operation |
22-
| resources_test.py:225:11:225:26 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:227:9:227:25 | After Attribute() | this operation |
23-
| resources_test.py:237:11:237:26 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:239:9:239:25 | After Attribute() | this operation |
247
| resources_test.py:248:11:248:25 | After open() | File is opened but is not closed. | file://:0:0:0:0 | (none) | this operation |
25-
| resources_test.py:252:11:252:25 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:254:9:254:23 | After Attribute() | this operation |
268
| resources_test.py:269:10:269:27 | After Attribute() | File may not be closed if $@ raises an exception. | resources_test.py:271:5:271:19 | After Attribute() | this operation |
27-
| resources_test.py:275:10:275:35 | After Attribute() | File may not be closed if $@ raises an exception. | resources_test.py:278:9:278:23 | After Attribute() | this operation |
289
| resources_test.py:285:11:285:20 | After open() | File may not be closed if $@ raises an exception. | resources_test.py:287:5:287:31 | After Attribute() | this operation |
29-
testFailures
30-
| resources_test.py:20:10:20:25 | File may not be closed if $@ raises an exception. | Unexpected result: Alert |
31-
| resources_test.py:30:14:30:29 | File may not be closed if $@ raises an exception. | Unexpected result: Alert |
32-
| resources_test.py:39:14:39:29 | File may not be closed if $@ raises an exception. | Unexpected result: Alert |
33-
| resources_test.py:58:14:58:29 | File may not be closed if $@ raises an exception. | Unexpected result: Alert |
34-
| resources_test.py:69:11:69:26 | File may not be closed if $@ raises an exception. | Unexpected result: Alert |
35-
| resources_test.py:79:11:79:26 | File may not be closed if $@ raises an exception. | Unexpected result: Alert |
36-
| resources_test.py:91:11:91:26 | File may not be closed if $@ raises an exception. | Unexpected result: Alert |
37-
| resources_test.py:182:15:182:54 | File may not be closed if $@ raises an exception. | Unexpected result: Alert |
38-
| resources_test.py:225:11:225:26 | File may not be closed if $@ raises an exception. | Unexpected result: Alert |
39-
| resources_test.py:252:11:252:25 | File may not be closed if $@ raises an exception. | Unexpected result: Alert |
40-
| resources_test.py:275:10:275:35 | File may not be closed if $@ raises an exception. | Unexpected result: Alert |

python/ql/test/query-tests/Resources/FileNotAlwaysClosed/resources_test.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def closed7():
4646
def not_closed8():
4747
f8 = None
4848
try:
49-
f8 = open("filename") # $ Alert # not closed on exception
49+
f8 = open("filename") # $ MISSING:Alert # not closed on exception (FileNotAlwaysClosed is optimistic about exception-flow close paths through buggy guards)
5050
f8.write("Error could occur")
5151
finally:
5252
if f8 is None: # We don't precisely consider this condition, so this result is MISSING. However, this seems uncommon.
@@ -138,7 +138,7 @@ def may_raise():
138138

139139
#Not handling all exceptions, but we'll tolerate the false negative
140140
def not_closed17():
141-
f17 = open("filename") # $ Alert # not closed on exception
141+
f17 = open("filename") # $ MISSING:Alert # not closed on exception (FileNotAlwaysClosed is optimistic about exception-flow close paths through buggy guards)
142142
try:
143143
f17.write("IOError could occur")
144144
f17.write("IOError could occur")
@@ -234,7 +234,7 @@ def closed21(path):
234234

235235

236236
def not_closed22(path):
237-
f22 = open(path, "wb") # $ Alert # not closed on exception
237+
f22 = open(path, "wb") # $ MISSING:Alert # not closed on exception (FileNotAlwaysClosed is optimistic about exception-flow close paths through buggy guards)
238238
try:
239239
f22.write(b"foo")
240240
may_raise()

0 commit comments

Comments
 (0)