1// SPDX-License-Identifier: GPL-2.0-only
2/// Many iterators have the property that the first argument is always bound
3/// to a real list element, never NULL.
4//# False positives arise for some iterators that do not have this property,
5//# or in cases when the loop cursor is reassigned.  The latter should only
6//# happen when the matched code is on the way to a loop exit (break, goto,
7//# or return).
8///
9// Confidence: Moderate
10// Copyright: (C) 2010-2012 Nicolas Palix.
11// Copyright: (C) 2010-2012 Julia Lawall, INRIA/LIP6.
12// Copyright: (C) 2010-2012 Gilles Muller, INRIA/LiP6.
13// URL: https://coccinelle.gitlabpages.inria.fr/website
14// Comments:
15// Options: --no-includes --include-headers
16
17virtual patch
18virtual context
19virtual org
20virtual report
21
22@depends on patch@
23iterator I;
24expression x,E,E1,E2;
25statement S,S1,S2;
26@@
27
28I(x,...) { <...
29(
30- if (x == NULL && ...) S
31|
32- if (x != NULL || ...)
33  S
34|
35- (x == NULL) ||
36  E
37|
38- (x != NULL) &&
39  E
40|
41- (x == NULL && ...) ? E1 :
42  E2
43|
44- (x != NULL || ...) ?
45  E1
46- : E2
47|
48- if (x == NULL && ...) S1 else
49  S2
50|
51- if (x != NULL || ...)
52  S1
53- else S2
54|
55+ BAD(
56  x == NULL
57+ )
58|
59+ BAD(
60  x != NULL
61+ )
62)
63  ...> }
64
65@r depends on !patch exists@
66iterator I;
67expression x,E;
68position p1,p2;
69@@
70
71*I@p1(x,...)
72{ ... when != x = E
73(
74*  x@p2 == NULL
75|
76*  x@p2 != NULL
77)
78  ... when any
79}
80
81@script:python depends on org@
82p1 << r.p1;
83p2 << r.p2;
84@@
85
86cocci.print_main("iterator-bound variable",p1)
87cocci.print_secs("useless NULL test",p2)
88
89@script:python depends on report@
90p1 << r.p1;
91p2 << r.p2;
92@@
93
94msg = "ERROR: iterator variable bound on line %s cannot be NULL" % (p1[0].line)
95coccilib.report.print_report(p2[0], msg)
96