1/*
2 * Copyright (C) 2010 Dan Carpenter.
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, see http://www.gnu.org/copyleft/gpl.txt
16 */
17
18/*
19 * Complains about places that return -1 instead of -ENOMEM
20 */
21
22#include "smatch.h"
23#include "smatch_slist.h"
24#include "smatch_extra.h"
25
26static int my_id;
27
28static void match_return(struct expression *ret_value)
29{
30	struct expression *expr;
31	struct sm_state *sm;
32	struct stree *stree;
33	sval_t sval;
34
35	if (!ret_value)
36		return;
37	if (returns_unsigned(cur_func_sym))
38		return;
39	if (returns_pointer(cur_func_sym))
40		return;
41	if (!get_value(ret_value, &sval) || sval.value != -1)
42		return;
43	if (get_macro_name(ret_value->pos))
44		return;
45
46	stree = __get_cur_stree();
47
48	FOR_EACH_MY_SM(SMATCH_EXTRA, stree, sm) {
49		if (!estate_get_single_value(sm->state, &sval) || sval.value != 0)
50			continue;
51		expr = get_assigned_expr_name_sym(sm->name, sm->sym);
52		if (!expr)
53			continue;
54		if (expr->type != EXPR_CALL || expr->fn->type != EXPR_SYMBOL)
55			continue;
56		if (!expr->fn->symbol_name)
57			continue;
58		/* To be honest the correct check is:
59		 * if (strstr(expr->fn->symbol_name->name, "alloc"))
60		 * 	complain();
61		 * But it generates too many warnings and it's too depressing.
62		 */
63		if (strcmp(expr->fn->symbol_name->name, "kmalloc") != 0 &&
64		    strcmp(expr->fn->symbol_name->name, "kzalloc") != 0)
65			continue;
66
67		sm_warning("returning -1 instead of -ENOMEM is sloppy");
68		return;
69
70	} END_FOR_EACH_SM(sm);
71}
72
73void check_return_enomem(int id)
74{
75	if (option_project != PROJ_KERNEL)
76		return;
77
78	my_id = id;
79	add_hook(&match_return, RETURN_HOOK);
80}
81