diff mbox series

coccinelle: misc: Check for hard-coded constants

Message ID 20200812233504.31666-1-mab@mab-labs.com (mailing list archive)
State New, archived
Headers show
Series coccinelle: misc: Check for hard-coded constants | expand

Commit Message

Mohammed Billoo Aug. 12, 2020, 11:35 p.m. UTC
This semantic patch looks for variables that are initialized to
constants, arrays that are both declared and indexed with constants.
A false positive will occur  when a variable is initialized to 0, which
must happen for auto variables. This will be resolved in a future patch.

The patch was tested against the following snippet:

int main()
{
    int iarr[54]; /* instance 1 */
    int j = 0;    /* instance 2 */
    int i = 1;    /* instance 3 */
    iarr[0] = 3;  /* instance 4 */
    return 0;
}

and it correctly identified instances 1, 3, and 4. It incorrectly
identified instance 2, which will be addressed in a future patch.
---
 scripts/coccinelle/misc/magic_numbers.cocci | 45 +++++++++++++++++++++
 1 file changed, 45 insertions(+)
 create mode 100644 scripts/coccinelle/misc/magic_numbers.cocci
diff mbox series

Patch

diff --git a/scripts/coccinelle/misc/magic_numbers.cocci b/scripts/coccinelle/misc/magic_numbers.cocci
new file mode 100644
index 000000000000..be6df33d28e4
--- /dev/null
+++ b/scripts/coccinelle/misc/magic_numbers.cocci
@@ -0,0 +1,45 @@ 
+// SPDX-License-Identifier: GPL-2.0-only
+/// Capture and instances of CWE-547 (https://cwe.mitre.org/data/definitions/547.html)
+///
+//# This attempts to capture instances of magic numbers and report them
+
+virtual report
+
+@r1 depends on report@
+type T;
+constant C;
+identifier var;
+position p;
+@@
+* T var@p = C;
+
+@script:python depends on report@
+p << r1.p;
+@@
+coccilib.report.print_report(p[0], "Hard-coded constant, consider using #define")
+
+@r2 depends on report@
+type T;
+identifier var;
+constant C;
+position p;
+@@
+* T var[C];
+
+@script:python depends on report@
+p << r2.p;
+@@
+coccilib.report.print_report(p[0], "Hard-coded constant, consider using #define")
+
+@r3 depends on report@
+type T;
+constant C;
+position p;
+T[] E;
+@@
+* E[C]@p = ... ;
+
+@script:python depends on report@
+p << r3.p;
+@@
+coccilib.report.print_report(p[0], "Hard-coded constant, consider using #define")