*new* check_macros: find macro precedence bugs
[smatch.git] / check_snprintf.c
blob5f1586b6646ef03b4772f3cae9cd431e37c7baab
1 /*
2 * sparse/check_snprintf.c
4 * Copyright (C) 2010 Dan Carpenter.
6 * Licensed under the Open Software License version 1.1
8 */
10 #include "smatch.h"
11 #include "smatch_slist.h"
12 #include "smatch_extra.h"
14 static int my_id;
16 static void ok_to_use(const char *name, struct symbol *sym, struct expression *expr, void *unused)
18 delete_state(my_id, name, sym);
21 static void match_snprintf(const char *fn, struct expression *expr, void *info)
23 struct expression *call;
24 struct expression *arg;
25 long long buflen;
27 call = strip_expr(expr->right);
28 arg = get_argument_from_call_expr(call->args, 1);
29 if (!get_fuzzy_max(arg, &buflen))
30 return;
31 set_state_expr(my_id, expr->left, alloc_state_num(buflen));
34 static int get_old_buflen(struct sm_state *sm)
36 struct sm_state *tmp;
37 int ret = 0;
39 FOR_EACH_PTR(sm->possible, tmp) {
40 if ((int)tmp->state->data > ret)
41 ret = (int)tmp->state->data;
42 } END_FOR_EACH_PTR(tmp);
43 return ret;
46 static void match_call(struct expression *expr)
48 struct expression *arg;
49 struct sm_state *sm;
50 int old_buflen;
51 long long max;
53 FOR_EACH_PTR(expr->args, arg) {
54 sm = get_sm_state_expr(my_id, arg);
55 if (!sm)
56 continue;
57 old_buflen = get_old_buflen(sm);
58 if (!old_buflen)
59 return;
60 if (get_absolute_max(arg, &max) && max > old_buflen)
61 sm_msg("warn: '%s' returned from snprintf() might be larger than %d",
62 sm->name, old_buflen);
63 } END_FOR_EACH_PTR(arg);
66 void check_snprintf(int id)
68 if (option_project != PROJ_KERNEL)
69 return;
71 my_id = id;
72 add_hook(&match_call, FUNCTION_CALL_HOOK);
73 add_function_assign_hook("snprintf", &match_snprintf, NULL);
74 set_default_modification_hook(my_id, ok_to_use);