free can handle null pointers: if (foo) free(foo);
[smatch.git] / check_puts_argument.c
blob0590a7b7c125b0061cfd3c915659957bfc38ac02
1 /*
2 * sparse/check_puts_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(putted);
22 static struct symbol *this_func;
23 static struct tracker_list *putted_args = NULL;
25 static void match_function_def(struct symbol *sym)
27 this_func = sym;
30 static int parent_is_arg(struct symbol *sym)
32 struct symbol *arg;
34 FOR_EACH_PTR(this_func->ctype.base_type->arguments, arg) {
35 if (sym == arg)
36 return 1;
37 } END_FOR_EACH_PTR(arg);
38 return 0;
41 static void match_put(const char *fn, struct expression *expr, void *info)
43 struct expression *tmp;
44 struct symbol *sym;
45 char *name;
47 tmp = get_argument_from_call_expr(expr->args, 0);
48 tmp = strip_expr(tmp);
49 name = get_variable_from_expr(tmp, &sym);
50 free_string(name);
51 if (parent_is_arg(sym) && sym->ident)
52 set_state(my_id, sym->ident->name, sym, &putted);
55 static int return_count = 0;
56 static void match_return(struct expression *ret_value)
58 struct state_list *slist;
59 struct sm_state *tmp;
60 struct tracker *tracker;
62 if (!return_count) {
63 slist = get_all_states(my_id);
64 FOR_EACH_PTR(slist, tmp) {
65 if (tmp->state == &putted)
66 add_tracker(&putted_args, my_id, tmp->name,
67 tmp->sym);
68 } END_FOR_EACH_PTR(tmp);
69 free_slist(&slist);
70 } else {
71 FOR_EACH_PTR(putted_args, tracker) {
72 tmp = get_sm_state(my_id, tracker->name, tracker->sym);
73 if (tmp && tmp->state != &putted)
74 del_tracker(&putted_args, my_id, tracker->name,
75 tracker->sym);
76 } END_FOR_EACH_PTR(tracker);
81 static void print_arg(struct symbol *sym)
83 struct symbol *arg;
84 int i = 0;
86 FOR_EACH_PTR(this_func->ctype.base_type->arguments, arg) {
87 if (sym == arg) {
88 sm_printf("info: puts_arg %s %d\n", get_function(), i);
89 return;
91 i++;
92 } END_FOR_EACH_PTR(arg);
95 static void match_end_func(struct symbol *sym)
97 struct tracker *tracker;
99 if (is_reachable())
100 match_return(NULL);
102 FOR_EACH_PTR(putted_args, tracker) {
103 print_arg(tracker->sym);
104 } END_FOR_EACH_PTR(tracker);
106 free_trackers_and_list(&putted_args);
107 return_count = 0;
110 void check_puts_argument(int id)
112 if (!option_spammy || option_project == PROJ_KERNEL)
113 return;
115 my_id = id;
116 add_hook(&match_function_def, FUNC_DEF_HOOK);
117 add_function_hook("kobject_put", &match_put, NULL);
118 add_function_hook("kref_put", &match_put, NULL);
119 add_hook(&match_return, RETURN_HOOK);
120 add_hook(&match_end_func, END_FUNC_HOOK);