math: array parameters can be NULL
[smatch.git] / check_access_ok_math.c
blob03ec6da247e1d184ada87d8bf3915d6c9b9e2b13
1 /*
2 * Copyright (C) 2010 Dan Carpenter.
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.
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.
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
18 #include "smatch.h"
20 static int my_id;
22 static int can_overflow(struct expression *expr)
24 sval_t max;
25 int uncapped = 0;
27 expr = strip_expr(expr);
29 if (expr->type == EXPR_BINOP) {
30 uncapped += can_overflow(expr->left);
31 uncapped += can_overflow(expr->right);
33 if (uncapped &&
34 (expr->op == '+' || expr->op == '*' || expr->op == SPECIAL_LEFTSHIFT))
35 return 1;
37 return 0;
40 if (get_implied_max(expr, &max))
41 return 0;
42 if (get_absolute_max(expr, &max) && sval_cmp_val(max, 4096) <= 0)
43 return 0;
44 return 1;
47 static void match_size(struct expression *size_expr)
49 char *name;
51 size_expr = strip_expr(size_expr);
52 if (!size_expr)
53 return;
54 if (size_expr->type != EXPR_BINOP) {
55 size_expr = get_assigned_expr(size_expr);
56 if (!size_expr || size_expr->type != EXPR_BINOP)
57 return;
59 if (!can_overflow(size_expr))
60 return;
62 name = expr_to_str(size_expr);
63 sm_warning("math in access_ok() is dangerous '%s'", name);
65 free_string(name);
68 static void match_access_ok(const char *fn, struct expression *expr, void *data)
70 struct expression *size_expr;
72 size_expr = get_argument_from_call_expr(expr->args, 1);
73 match_size(size_expr);
76 static void split_asm_constraints(struct statement *stmt)
78 struct asm_operand *op;
80 FOR_EACH_PTR(stmt->asm_inputs, op) {
81 match_size(op->constraint);
82 } END_FOR_EACH_PTR(op);
85 static void match_asm_stmt(struct statement *stmt)
87 char *name;
89 name = get_macro_name(stmt->pos);
90 if (!name || strcmp(name, "access_ok") != 0)
91 return;
92 split_asm_constraints(stmt);
95 void check_access_ok_math(int id)
97 my_id = id;
98 if (option_project != PROJ_KERNEL)
99 return;
100 if (!option_spammy)
101 return;
102 add_function_hook("__access_ok", &match_access_ok, NULL);
103 add_hook(&match_asm_stmt, ASM_HOOK);