xref: /linux/scripts/coccinelle/misc/struct_size.cocci (revision f6e0a4984c2e7244689ea87b62b433bed9d07e94)
1// SPDX-License-Identifier: GPL-2.0-only
2///
3/// Check for code that could use struct_size().
4///
5// Confidence: Medium
6// Author: Jacob Keller <jacob.e.keller@intel.com>
7// Copyright: (C) 2023 Intel Corporation
8// Options: --no-includes --include-headers
9
10virtual patch
11virtual context
12virtual org
13virtual report
14
15// the overflow Kunit tests have some code which intentionally does not use
16// the macros, so we want to ignore this code when reporting potential
17// issues.
18@overflow_tests@
19identifier f = overflow_size_helpers_test;
20@@
21
22f
23
24//----------------------------------------------------------
25//  For context mode
26//----------------------------------------------------------
27
28@depends on !overflow_tests && context@
29expression E1, E2;
30identifier m;
31@@
32(
33* (sizeof(*E1) + (E2 * sizeof(*E1->m)))
34)
35
36//----------------------------------------------------------
37//  For patch mode
38//----------------------------------------------------------
39
40@depends on !overflow_tests && patch@
41expression E1, E2;
42identifier m;
43@@
44(
45- (sizeof(*E1) + (E2 * sizeof(*E1->m)))
46+ struct_size(E1, m, E2)
47)
48
49//----------------------------------------------------------
50//  For org and report mode
51//----------------------------------------------------------
52
53@r depends on !overflow_tests && (org || report)@
54expression E1, E2;
55identifier m;
56position p;
57@@
58(
59 (sizeof(*E1)@p + (E2 * sizeof(*E1->m)))
60)
61
62@script:python depends on org@
63p << r.p;
64@@
65
66coccilib.org.print_todo(p[0], "WARNING should use struct_size")
67
68@script:python depends on report@
69p << r.p;
70@@
71
72msg="WARNING: Use struct_size"
73coccilib.report.print_report(p[0], msg)
74
75