0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /// Unsigned expressions cannot be lesser than zero. Presence of
0003 /// comparisons 'unsigned (<|<=|>|>=) 0' often indicates a bug,
0004 /// usually wrong type of variable.
0005 ///
0006 /// To reduce number of false positives following tests have been added:
0007 /// - parts of range checks are skipped, eg. "if (u < 0 || u > 15) ...",
0008 /// developers prefer to keep such code,
0009 /// - comparisons "<= 0" and "> 0" are performed only on results of
0010 /// signed functions/macros,
0011 /// - hardcoded list of signed functions/macros with always non-negative
0012 /// result is used to avoid false positives difficult to detect by other ways
0013 ///
0014 // Confidence: Average
0015 // Copyright: (C) 2015 Andrzej Hajda, Samsung Electronics Co., Ltd.
0016 // URL: https://coccinelle.gitlabpages.inria.fr/website
0017 // Options: --all-includes
0018
0019 virtual context
0020 virtual org
0021 virtual report
0022
0023 @r_cmp@
0024 position p;
0025 typedef bool, u8, u16, u32, u64;
0026 {unsigned char, unsigned short, unsigned int, unsigned long, unsigned long long,
0027 size_t, bool, u8, u16, u32, u64} v;
0028 expression e;
0029 @@
0030
0031 \( v = e \| &v \)
0032 ...
0033 (\( v@p < 0 \| v@p <= 0 \| v@p >= 0 \| v@p > 0 \))
0034
0035 @r@
0036 position r_cmp.p;
0037 typedef s8, s16, s32, s64;
0038 {char, short, int, long, long long, ssize_t, s8, s16, s32, s64} vs;
0039 expression c, e, v;
0040 identifier f !~ "^(ata_id_queue_depth|btrfs_copy_from_user|dma_map_sg|dma_map_sg_attrs|fls|fls64|gameport_time|get_write_extents|nla_len|ntoh24|of_flat_dt_match|of_get_child_count|uart_circ_chars_pending|[A-Z0-9_]+)$";
0041 @@
0042
0043 (
0044 v = f(...)@vs;
0045 ... when != v = e;
0046 * (\( v@p <=@e 0 \| v@p >@e 0 \))
0047 ... when any
0048 |
0049 (
0050 (\( v@p < 0 \| v@p <= 0 \)) || ... || (\( v >= c \| v > c \))
0051 |
0052 (\( v >= c \| v > c \)) || ... || (\( v@p < 0 \| v@p <= 0 \))
0053 |
0054 (\( v@p >= 0 \| v@p > 0 \)) && ... && (\( v < c \| v <= c \))
0055 |
0056 ((\( v < c \| v <= c \) && ... && \( v@p >= 0 \| v@p > 0 \)))
0057 |
0058 * (\( v@p <@e 0 \| v@p >=@e 0 \))
0059 )
0060 )
0061
0062 @script:python depends on org@
0063 p << r_cmp.p;
0064 e << r.e;
0065 @@
0066
0067 msg = "WARNING: Unsigned expression compared with zero: %s" % (e)
0068 coccilib.org.print_todo(p[0], msg)
0069
0070 @script:python depends on report@
0071 p << r_cmp.p;
0072 e << r.e;
0073 @@
0074
0075 msg = "WARNING: Unsigned expression compared with zero: %s" % (e)
0076 coccilib.report.print_report(p[0], msg)