-
Notifications
You must be signed in to change notification settings - Fork 42
/
check_test_not_null.py
executable file
·316 lines (252 loc) · 11.2 KB
/
check_test_not_null.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#! /usr/bin/env python
"""
This script will detect a test for nullity of a pointer variable that is
dominated by a dereference of the same variable, without intervening assignment
to the variable.
"""
import argparse
import libadalang as lal
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('files', help='The files to analyze',
type=str, nargs='+', metavar='F')
def location(node):
return (node.token_start.sloc_range.start.line,
node.token_start.sloc_range.start.column)
def is_equality_operator(op, polarity):
"""
Check that op is an equality or inequality operator.
:param polarity: Boolean which is True for OpEq and False for OpNeq.
:rtype: bool
"""
if polarity:
return isinstance(op, lal.OpEq)
else:
return isinstance(op, lal.OpNeq)
def get_nullity_test(expr, polarity):
"""
Detect if expr is a test that an object is null or not null, and in that
case return the object being tested.
We make no attempt to detect if this is really an object or an expression.
:param polarity: Boolean which is True to indicate equality to null should
be detected, and False to indicate inequality to null
should be detected.
:rtype: lal.Expr
"""
if (isinstance(expr, lal.BinOp) and
is_equality_operator(expr.f_op, polarity)):
if isinstance(expr.f_left, lal.NullLiteral):
return expr.f_right
if isinstance(expr.f_right, lal.NullLiteral):
return expr.f_left
return None
def get_dereference(expr):
"""
Detect if expr is a dereference of a pointer object, and in that case
return the object being dereferenced.
Without semantic information, we cannot know if the 'object' is an object
or a package, and even if it is an object, if it is of access type. We
consider all these as objects being referenced.
:rtype: expr?
"""
if isinstance(expr, (lal.ExplicitDeref, lal.DottedName)):
return expr.f_prefix
return None
def get_assignment(expr):
"""
Detect if expr is an assignment of an object, and in that case return
the object being assigned.
We make no attempt to detect if this is really an object or an expression.
Without semantic information, we also cannot know when an object is
possibly assigned by being passed as OUT or IN OUT parameter in a call. We
also cannot know if the address of an object is taken.
We could try to detect when the prefix of an object is assigned, thus
assigning also the object as a side-effect, but leave it for a future
version using semantic information.
:rtype: expr?
"""
if isinstance(expr, lal.AssignStmt):
return expr.f_dest
return None
def explore(f, subp):
"""
Explore the content of a subprogram body (which could be also the body of
an expression function), and detect if an object is dereferenced after
being tested for equality with null, without any possible assignment to
the object in between.
Issue a message in that case.
:rtype: none?
"""
def remove_assign(node, nulls):
var = get_assignment(node)
if var is not None and var.text in nulls:
del nulls[var.text]
def add_nulls(node, nulls, polarity):
var = get_nullity_test(node, polarity)
if var is not None:
nulls[var.text] = var
def detect_dereference(node, nulls):
var = get_dereference(node)
if var is not None and var.text in nulls:
fst_line, fst_col = location(nulls[var.text])
snd_line, snd_col = location(node)
print('{}:{}:{}: dereference of null value after test at line'
' {}'.format(f, snd_line, snd_col, fst_line))
def traverse_branch(node, nulls, cond=None, neg_cond=None):
"""
Sub traversal procedure, called by the main traversal procedure
traverse on branches in the control flow.
"""
if node is None:
return
# Copy the dictionary of objects dereferenced, as the objects that are
# null on a path should not be considered as such when paths join,
# e.g. after the if-statement.
branch_nulls = nulls.copy()
if cond:
collect_nulls(cond, branch_nulls, {}, result=True)
if neg_cond:
collect_nulls(neg_cond, branch_nulls, {}, result=False)
# Call traverse recursively
traverse(node, branch_nulls)
# Remove those variables which have been redefined in the branch, which
# we detect by checking whether they are still in the objects known to
# be null for the branch or not.
for k in nulls.keys():
if k not in branch_nulls:
del nulls[k]
def collect_nulls(node, nulls, notnulls, result):
"""
Collect all the tests for nullity and non-nullity of objects that are
guaranteed to hold when `node` evaluates to `result`.
:type node: lal.Expr
:type result: Boolean
"""
# Add the objects tested against null in node to the dictionary nulls
add_nulls(node, nulls, polarity=result)
add_nulls(node, notnulls, polarity=not result)
# Call collect_nulls recursively on sub-nodes
if isinstance(node, lal.UnOp) and isinstance(node.f_op, lal.OpNot):
collect_nulls(node.f_expr, nulls, notnulls, not result)
elif (isinstance(node, lal.BinOp)
and isinstance(node.f_op, (lal.OpAnd, lal.OpAndThen))):
if result:
collect_nulls(node.f_left, nulls, notnulls, result)
collect_nulls(node.f_right, nulls, notnulls, result)
else:
pass # no guarantees if A and B evaluates to False
elif (isinstance(node, lal.BinOp)
and isinstance(node.f_op, (lal.OpOr, lal.OpOrElse))):
if not result:
collect_nulls(node.f_left, nulls, notnulls, result)
collect_nulls(node.f_right, nulls, notnulls, result)
else:
pass # no guarantees if A or B evaluates to True
# Always filter out nulls by notnulls. For example we may have assigned
# an object to null, then performed some call that is not taken into
# account by the checker, then a test that the object is not null.
# The test should be enough to consider the object not null.
for k in notnulls.keys():
if k in nulls:
del nulls[k]
def traverse(node, nulls):
"""
Main recursive traversal procedure.
:param node: Current node in the AST.
:param nulls: Dictionary for the objects equal to null on the path,
mapping their text to the object node in the AST.
"""
if node is None:
return
# Start by checking for dereference in the context of the null tests
# found so far on the path. This may issue a message.
detect_dereference(node, nulls)
# Call traverse or traverse_branch recursively on sub-nodes
if isinstance(node, lal.ObjectDecl):
tdecl = node.f_type_expr.p_designated_type_decl
if tdecl is not None and tdecl.p_is_access_type():
if (node.f_default_expr is None or
node.f_default_expr.is_a(lal.NullLiteral)):
for id in node.f_ids:
nulls[id.text] = id
elif isinstance(node, lal.AssignStmt):
for sub in node:
traverse(sub, nulls)
remove_assign(node, nulls)
# Consider the case where null is explicitly assigned to an object.
# Without semantic information, we don't consider yet the case of
# the declaration of pointer objects without initializer, which are
# implicitly set to null.
if isinstance(node.f_expr, lal.NullLiteral):
nulls[node.f_dest.text] = node.f_dest
elif isinstance(node, lal.PragmaNode) and node.f_id.text == "Assert":
for assoc in node.f_args:
collect_nulls(assoc.f_expr, nulls, {}, result=True)
elif isinstance(node, lal.IfStmt):
traverse(node.f_cond_expr, nulls)
traverse_branch(node.f_then_stmts, nulls, cond=node.f_cond_expr)
# Do not attempt yet to propagate conditions of elsif parts
for sub in node.f_alternatives:
traverse_branch(sub, nulls, neg_cond=node.f_cond_expr)
traverse_branch(node.f_else_stmts, nulls,
neg_cond=node.f_cond_expr)
elif isinstance(node, lal.IfExpr):
traverse(node.f_cond_expr, nulls)
traverse_branch(node.f_then_expr, nulls, cond=node.f_cond_expr)
# Do not attempt yet to propagate conditions of elsif parts
for sub in node.f_elsif_list:
traverse_branch(sub, nulls, neg_cond=node.f_cond_expr)
traverse_branch(node.f_else_expr, nulls, neg_cond=node.f_cond_expr)
elif isinstance(node, lal.CaseStmt):
traverse(node.f_expr, nulls)
for sub in node.f_alternatives:
traverse_branch(sub, nulls)
# Reset null objects inside and after loop, as control may come back
# from the loop body after variables may be reassigned in the loop.
elif isinstance(node, lal.LoopStmt):
traverse(node.f_spec, nulls)
traverse_branch(node.f_stmts, {})
nulls.clear()
elif (isinstance(node, lal.BinOp) and
isinstance(node.f_op, lal.OpAndThen)):
traverse(node.f_left, nulls)
traverse_branch(node.f_right, nulls, cond=node.f_left)
elif (isinstance(node, lal.BinOp) and
isinstance(node.f_op, lal.OpOrElse)):
traverse(node.f_left, nulls)
traverse_branch(node.f_right, nulls, neg_cond=node.f_left)
# Reset null objects for exception handler, as control may come from
# many sources.
elif isinstance(node, lal.ExceptionHandler):
traverse(node.f_stmts, {})
# Ignore local subprograms and packages when exploring the enclosing
# subprogram body.
elif isinstance(node, (lal.SubpBody,
lal.PackageDecl,
lal.GenericPackageDecl,
lal.PackageBody,
lal.ExprFunction)):
pass
else:
for sub in node:
traverse(sub, nulls)
# Skip the toplevel subprogram body so that it is not confused with a
# local one.
def traverse_subp_body(node, nulls):
for sub in node:
traverse(sub, nulls)
traverse_subp_body(subp, {})
def do_file(f):
c = lal.AnalysisContext()
unit = c.get_from_file(f)
if unit.root is None:
print('Could not parse {}:'.format(f))
for diag in unit.diagnostics:
print(' {}'.format(diag))
return
for subp in unit.root.findall((lal.SubpBody, lal.ExprFunction)):
explore(f, subp)
def main(args):
for f in args.files:
do_file(f)
if __name__ == '__main__':
main(parser.parse_args())