math: delete old unused code
[smatch.git] / check_kmalloc_wrong_size.c
blobc596da916460c8f675f0dd548dad89e46d14151f
1 /*
2 * smatch/check_kmalloc_wrong_size.c
4 * Copyright (C) 2011 Dan Carpenter.
6 * Licensed under the Open Software License version 1.1
8 */
10 #include "smatch.h"
12 static int my_id;
14 static int get_data_size(struct expression *ptr)
16 struct symbol *type;
17 int ret;
19 type = get_type(ptr);
20 if (!type || type->type != SYM_PTR)
21 return 0;
22 type = get_base_type(type);
23 if (!type)
24 return 0;
25 ret = bits_to_bytes(type->bit_size);
26 if (ret == -1)
27 return 0;
28 return ret;
31 static void check_size_matches(int data_size, struct expression *size_expr)
33 sval_t sval;
35 if (data_size == 1) /* this is generic a buffer */
36 return;
38 if (!get_implied_value(size_expr, &sval))
39 return;
40 if (sval_cmp_val(sval, data_size) != 0)
41 sm_msg("warn: double check that we're allocating correct size: %d vs %s", data_size, sval_to_str(sval));
44 static void match_alloc(const char *fn, struct expression *expr, void *unused)
46 struct expression *call = strip_expr(expr->right);
47 struct expression *arg;
48 int ptr_size;
50 ptr_size = get_data_size(expr->left);
51 if (!ptr_size)
52 return;
54 arg = get_argument_from_call_expr(call->args, 0);
55 arg = strip_expr(arg);
56 if (!arg || arg->type != EXPR_BINOP || arg->op != '*')
57 return;
58 if (expr->left->type == EXPR_SIZEOF)
59 check_size_matches(ptr_size, arg->left);
60 if (expr->right->type == EXPR_SIZEOF)
61 check_size_matches(ptr_size, arg->right);
64 static void match_calloc(const char *fn, struct expression *expr, void *_arg_nr)
66 int arg_nr = PTR_INT(_arg_nr);
67 struct expression *call = strip_expr(expr->right);
68 struct expression *arg;
69 int ptr_size;
71 ptr_size = get_data_size(expr->left);
72 if (!ptr_size)
73 return;
75 arg = get_argument_from_call_expr(call->args, arg_nr);
76 check_size_matches(ptr_size, arg);
79 void check_kmalloc_wrong_size(int id)
81 my_id = id;
83 if (option_project != PROJ_KERNEL) {
84 add_function_assign_hook("malloc", &match_alloc, NULL);
85 add_function_assign_hook("calloc", &match_calloc, INT_PTR(1));
86 return;
89 add_function_assign_hook("kmalloc", &match_alloc, NULL);
90 add_function_assign_hook("kcalloc", &match_calloc, INT_PTR(1));