comparison: some small cleanups
[smatch.git] / check_check_deref.c
blobb3609591183c5915790350c5e1f61f98ce0dda76
1 /*
2 * sparse/check_check_deref.c
4 * Copyright (C) 2010 Dan Carpenter.
6 * Licensed under the Open Software License version 1.1
8 */
11 * This is like check_deref_check.c except that it complains about code like:
12 * if (a)
13 * a->foo = 42;
14 * a->bar = 7;
16 * Of course, Smatch has complained about these for forever but the problem is
17 * the old scripts were too messy and complicated and generated too many false
18 * positives.
20 * This check is supposed to be simpler because it only looks for one kind of
21 * null dereference bug instead of every kind. It also gets rid of the false
22 * positives caused by the checks that happen inside macros.
26 #include "smatch.h"
27 #include "smatch_slist.h"
28 #include "smatch_extra.h"
30 static int my_id;
32 STATE(null);
33 STATE(ok);
35 static void is_ok(struct sm_state *sm, struct expression *mod_expr)
37 set_state(my_id, sm->name, sm->sym, &ok);
40 static void check_dereference(struct expression *expr)
42 struct sm_state *sm;
43 struct sm_state *tmp;
45 expr = strip_expr(expr);
46 if (getting_address())
47 return;
48 sm = get_sm_state_expr(my_id, expr);
49 if (!sm)
50 return;
51 if (is_ignored(my_id, sm->name, sm->sym))
52 return;
53 if (implied_not_equal(expr, 0))
54 return;
56 FOR_EACH_PTR(sm->possible, tmp) {
57 if (tmp->state == &merged)
58 continue;
59 if (tmp->state == &ok)
60 continue;
61 if (tmp->state == &null) {
62 sm_msg("error: we previously assumed '%s' could be null (see line %d)",
63 tmp->name, tmp->line);
64 add_ignore(my_id, sm->name, sm->sym);
65 return;
67 } END_FOR_EACH_PTR(tmp);
70 static void match_dereferences(struct expression *expr)
72 if (expr->type != EXPR_PREOP)
73 return;
74 check_dereference(expr->unop);
77 static void match_pointer_as_array(struct expression *expr)
79 if (!is_array(expr))
80 return;
81 check_dereference(expr->unop->left);
84 static void set_param_dereferenced(struct expression *arg, char *unused)
86 check_dereference(arg);
89 static void match_condition(struct expression *expr)
91 if (get_macro_name(expr->pos))
92 return;
94 if (expr->type == EXPR_ASSIGNMENT) {
95 match_condition(expr->right);
96 match_condition(expr->left);
98 set_true_false_states_expr(my_id, expr, &ok, &null);
101 void check_check_deref(int id)
103 my_id = id;
105 add_modification_hook(my_id, &is_ok);
106 add_hook(&match_dereferences, DEREF_HOOK);
107 add_hook(&match_pointer_as_array, OP_HOOK);
108 select_call_implies_hook(DEREFERENCE, &set_param_dereferenced);
109 add_hook(&match_condition, CONDITION_HOOK);