Skip to content

Commit

Permalink
divide_condition: warn about if (foo / 4) {
Browse files Browse the repository at this point in the history
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 <[email protected]>
  • Loading branch information
error27 committed Nov 24, 2022
1 parent 7fc2cbd commit 07aefcd
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
46 changes: 46 additions & 0 deletions check_divide_condition.c
Original file line number Diff line number Diff line change
@@ -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);
}
1 change: 1 addition & 0 deletions check_list.h
Original file line number Diff line number Diff line change
Expand Up @@ -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) */
Expand Down

0 comments on commit 07aefcd

Please sign in to comment.