From 07aefcd03e6e2cdbef97f11e1ad1a5daa39ba25d Mon Sep 17 00:00:00 2001 From: Dan Carpenter Date: Thu, 24 Nov 2022 13:14:10 +0300 Subject: [PATCH] divide_condition: warn about if (foo / 4) { The condition "if (foo / 4) {" could be replaced with "if (foo >= 4) {" which is what Smatch suggests, but a lot of them should be instead replaced with "if ((foo % 4) == 0) {". Signed-off-by: Dan Carpenter --- check_divide_condition.c | 46 ++++++++++++++++++++++++++++++++++++++++ check_list.h | 1 + 2 files changed, 47 insertions(+) create mode 100644 check_divide_condition.c diff --git a/check_divide_condition.c b/check_divide_condition.c new file mode 100644 index 000000000..9a0cf5b18 --- /dev/null +++ b/check_divide_condition.c @@ -0,0 +1,46 @@ +/* + * Copyright (C) 2022 Dan Carpenter. + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, see http://www.gnu.org/copyleft/gpl.txt + */ + +#include "smatch.h" +#include "smatch_extra.h" + +static int my_id; + +static void match_condition1(struct expression *expr) +{ + char *left, *right; + + if (expr->type != EXPR_BINOP || expr->op != '/') + return; + + if (get_macro_name(expr->pos)) + return; + + left = expr_to_str(expr->left); + right = expr_to_str(expr->right); + sm_warning("replace divide condition '%s / %s' with '%s >= %s'", + left, right, left, right); + free_string(left); + free_string(right); +} + +void check_divide_condition(int id) +{ + my_id = id; + + add_hook(&match_condition1, CONDITION_HOOK); +} diff --git a/check_list.h b/check_list.h index d83047067..8eea87724 100644 --- a/check_list.h +++ b/check_list.h @@ -186,6 +186,7 @@ CK(register_param_bits_set) CK(register_param_bits_clear) CK(check_do_while_loop_limit) CK(check_ida_alloc) +CK(check_divide_condition) /* <- your test goes here */ /* CK(register_template) */