forked from error27/smatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_kmalloc_wrong_size.c
95 lines (79 loc) · 2.53 KB
/
check_kmalloc_wrong_size.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
* Copyright (C) 2011 Dan Carpenter.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see http://www.gnu.org/copyleft/gpl.txt
*/
#include "smatch.h"
static int my_id;
static int get_data_size(struct expression *ptr)
{
struct symbol *type;
type = get_type(ptr);
if (!type || type->type != SYM_PTR)
return 0;
type = get_base_type(type);
if (!type)
return 0;
return type_bytes(type);
}
static void check_size_matches(int data_size, struct expression *size_expr)
{
sval_t sval;
if (data_size == 1) /* this is generic a buffer */
return;
if (!get_implied_value(size_expr, &sval))
return;
if (sval_cmp_val(sval, data_size) != 0)
sm_warning("double check that we're allocating correct size: %d vs %s", data_size, sval_to_str(sval));
}
static void match_alloc(const char *fn, struct expression *expr, void *unused)
{
struct expression *call = strip_expr(expr->right);
struct expression *arg;
int ptr_size;
ptr_size = get_data_size(expr->left);
if (!ptr_size)
return;
arg = get_argument_from_call_expr(call->args, 0);
arg = strip_expr(arg);
if (!arg || arg->type != EXPR_BINOP || arg->op != '*')
return;
if (expr->left->type == EXPR_SIZEOF)
check_size_matches(ptr_size, arg->left);
if (expr->right->type == EXPR_SIZEOF)
check_size_matches(ptr_size, arg->right);
}
static void match_calloc(const char *fn, struct expression *expr, void *_arg_nr)
{
int arg_nr = PTR_INT(_arg_nr);
struct expression *call = strip_expr(expr->right);
struct expression *arg;
int ptr_size;
ptr_size = get_data_size(expr->left);
if (!ptr_size)
return;
arg = get_argument_from_call_expr(call->args, arg_nr);
check_size_matches(ptr_size, arg);
}
void check_kmalloc_wrong_size(int id)
{
my_id = id;
if (option_project != PROJ_KERNEL) {
add_function_assign_hook("malloc", &match_alloc, NULL);
add_function_assign_hook("calloc", &match_calloc, INT_PTR(1));
return;
}
add_function_assign_hook("kmalloc", &match_alloc, NULL);
add_function_assign_hook("kcalloc", &match_calloc, INT_PTR(1));
}