buf_size: record static variables in the database
[smatch.git] / check_return_efault.c
blob382080aac692accbd6cd5b27e8ea3c16a4830535
1 /*
2 * smatch/check_return_efault.c
4 * Copyright (C) 2010 Dan Carpenter.
6 * Licensed under the Open Software License version 1.1
8 */
11 * This tries to find places which should probably return -EFAULT
12 * but return the number of bytes to copy instead.
15 #include "smatch.h"
16 #include "smatch_slist.h"
17 #include "smatch_extra.h"
19 static int my_id;
21 STATE(remaining);
22 STATE(ok);
24 static void ok_to_use(struct sm_state *sm)
26 if (sm->state != &ok)
27 set_state(my_id, sm->name, sm->sym, &ok);
30 static void match_copy(const char *fn, struct expression *expr, void *unused)
32 struct expression *call;
33 struct expression *arg;
34 long long max;
36 if (expr->op == SPECIAL_SUB_ASSIGN)
37 return;
38 set_state_expr(my_id, expr->left, &remaining);
40 call = strip_expr(expr->right);
41 if (call->type != EXPR_CALL)
42 return;
43 arg = get_argument_from_call_expr(call->args, 2);
44 if (!get_absolute_max(arg, &max))
45 max = whole_range.max;
46 set_extra_expr_mod(expr->left, alloc_estate_range(0, max));
50 static void match_condition(struct expression *expr)
52 if (!get_state_expr(my_id, expr))
53 return;
54 /* If the variable is zero that's ok */
55 set_true_false_states_expr(my_id, expr, NULL, &ok);
59 * This function is biased in favour of print out errors.
60 * The heuristic to print is:
61 * If we have a potentially positive return from copy_to_user
62 * and there is a possibility that we return negative as well
63 * then complain.
65 static void match_return(struct expression *ret_value)
67 struct smatch_state *state;
68 struct sm_state *sm;
69 long long min;
71 sm = get_sm_state_expr(my_id, ret_value);
72 if (!sm)
73 return;
74 if (!slist_has_state(sm->possible, &remaining))
75 return;
76 state = get_state_expr(SMATCH_EXTRA, ret_value);
77 if (!state)
78 return;
79 if (!get_absolute_min(ret_value, &min))
80 return;
81 if (min == 0)
82 return;
83 sm_msg("warn: maybe return -EFAULT instead of the bytes remaining?");
86 void check_return_efault(int id)
88 if (option_project != PROJ_KERNEL)
89 return;
91 my_id = id;
92 add_function_assign_hook_extra("copy_to_user", &match_copy, NULL);
93 add_function_assign_hook_extra("__copy_to_user", &match_copy, NULL);
94 add_function_assign_hook_extra("copy_from_user", &match_copy, NULL);
95 add_function_assign_hook_extra("__copy_from_user", &match_copy, NULL);
96 add_function_assign_hook_extra("clear_user", &match_copy, NULL);
97 add_hook(&match_condition, CONDITION_HOOK);
98 add_hook(&match_return, RETURN_HOOK);
99 add_modification_hook(my_id, &ok_to_use);