Fix strncat() bugs.
[smatch.git] / check_frees_argument.c
blob708b0fe518963df4b27688a7dc0c63b798ae14fb
1 /*
2 * sparse/check_frees_argument.c
4 * Copyright (C) 2009 Dan Carpenter.
6 * Licensed under the Open Software License version 1.1
8 */
10 /*
11 * This script is for finding functions like hcd_buffer_free() which free
12 * their arguments. After running it, add those functions to check_memory.c
15 #include "smatch.h"
16 #include "smatch_slist.h"
18 static int my_id;
20 STATE(freed);
22 static struct symbol *this_func;
23 static struct tracker_list *freed_args = NULL;
25 static void match_function_def(struct symbol *sym)
27 this_func = sym;
30 static int is_arg(char *name, struct symbol *sym)
32 struct symbol *arg;
33 const char *arg_name;
35 FOR_EACH_PTR(this_func->ctype.base_type->arguments, arg) {
36 arg_name = (arg->ident?arg->ident->name:"-");
37 if (sym == arg && !strcmp(name, arg_name))
38 return 1;
39 } END_FOR_EACH_PTR(arg);
40 return 0;
43 static void match_kfree(const char *fn, struct expression *expr, void *info)
45 struct expression *tmp;
46 struct symbol *sym;
47 char *name;
49 tmp = get_argument_from_call_expr(expr->args, 0);
50 tmp = strip_expr(tmp);
51 name = get_variable_from_expr(tmp, &sym);
52 if (is_arg(name, sym)) {
53 set_state(name, my_id, sym, &freed);
55 free_string(name);
58 static int return_count = 0;
59 static void match_return(struct statement *stmt)
61 struct state_list *slist;
62 struct sm_state *tmp;
63 struct tracker *tracker;
65 if (!return_count) {
66 slist = get_all_states(my_id);
67 FOR_EACH_PTR(slist, tmp) {
68 if (tmp->state == &freed)
69 add_tracker(&freed_args, tmp->name, my_id,
70 tmp->sym);
71 } END_FOR_EACH_PTR(tmp);
72 free_slist(&slist);
73 } else {
74 FOR_EACH_PTR(freed_args, tracker) {
75 tmp = get_sm_state(tracker->name, my_id, tracker->sym);
76 if (tmp && tmp->state != &freed)
77 del_tracker(&freed_args, tracker->name, my_id,
78 tracker->sym);
79 } END_FOR_EACH_PTR(tracker);
84 static void print_arg(struct symbol *sym)
86 struct symbol *arg;
87 int i = 0;
89 FOR_EACH_PTR(this_func->ctype.base_type->arguments, arg) {
90 if (sym == arg) {
91 printf("info: free_arg %s %d\n", get_function(), i);
92 return;
94 i++;
95 } END_FOR_EACH_PTR(arg);
98 static void match_end_func(struct symbol *sym)
100 struct tracker *tracker;
102 if (is_reachable())
103 match_return(NULL);
105 FOR_EACH_PTR(freed_args, tracker) {
106 print_arg(tracker->sym);
107 } END_FOR_EACH_PTR(tracker);
109 free_trackers_and_list(&freed_args);
110 return_count = 0;
113 void check_frees_argument(int id)
115 my_id = id;
116 add_hook(&match_function_def, FUNC_DEF_HOOK);
117 add_function_hook("kfree", &match_kfree, NULL);
118 add_hook(&match_return, RETURN_HOOK);
119 add_hook(&match_end_func, END_FUNC_HOOK);