Skip to content

Commit e382f7c

Browse files
Improve check for containment in with statement
1 parent 0b293ea commit e382f7c

File tree

2 files changed

+8
-2
lines changed

2 files changed

+8
-2
lines changed

python/ql/src/Resources/FileNotAlwaysClosedQuery.qll

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,12 @@ class WithStatement extends FileClose {
8888
With w;
8989

9090
WithStatement() { this.asExpr() = w.getContextExpr() }
91+
92+
override predicate guardsExceptions(DataFlow::CfgNode fileRaises) {
93+
super.guardsExceptions(fileRaises)
94+
or
95+
w.getBody().contains(fileRaises.asExpr())
96+
}
9197
}
9298

9399
/** Holds if an exception may be raised at `raises` if `file` is a file object. */

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -151,7 +151,7 @@ def not_closed17():
151151
#With statement will close the fp
152152
def closed18(path):
153153
try:
154-
f18 = open(path) # $SPURIOUS: Alert # Dataflow appears to not detect this with statement as guarding the exceptions produced by the `read()` call.
154+
f18 = open(path) # $Alert
155155
except IOError as ex:
156156
print(ex)
157157
raise ex
@@ -301,7 +301,7 @@ def closed30(path):
301301
# - NotWrapper is treated as a wrapper class as a file handle is passed to it
302302
# - thing.do_something() is treated as a call that can raise an exception while a file is open
303303
# - this call is treated as occurring after the open but not as being guarded by the with statement, as it is in the same basic block
304-
# - - this behaviour has been changed fixing the FP
304+
# - - this behavior has been changed fixing the FP
305305

306306
with open(path) as fp: # No longer spurious alert here.
307307
thing = NotWrapper(fp)

0 commit comments

Comments
 (0)