units: move checks to check_ file and hide under the --spammy option
[smatch.git] / check_kvmalloc_array_zero.c
blobb1960a0fd930685c39e5790da575ba013deb6ddf
1 /*
2 * Copyright (C) 2022 Oracle.
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
19 * This check complains when we have a function used with __GFP_ZERO flag and
20 * we can use a less verbose alternative.
22 * Example: kmalloc_array + __GPF_ZERO = kcalloc
25 #include "smatch.h"
27 static int my_id;
29 struct match_alloc_struct {
30 const char *function;
31 const char *alternative;
32 int flag_pos;
35 struct match_alloc_struct match_alloc_functions[] = {
36 { "kmalloc", "kzalloc", 1 },
37 { "kmalloc_node", "kzalloc_node", 1 },
39 { "kmalloc_array", "kcalloc", 2 },
40 { "kmalloc_array_node", "kcalloc_node", 2 },
42 { "kvmalloc", "kvzalloc", 1 },
43 { "kvmalloc_node", "kvzalloc_node", 1 },
45 { "kvmalloc_array", "kvcalloc", 2 },
47 { "kmem_cache_alloc", "kmem_cache_zalloc", 1 },
48 { NULL, NULL, 0 }
51 static void match_alloc(const char *fn, struct expression *expr, void *_arg)
53 struct match_alloc_struct *entry = match_alloc_functions;
54 unsigned long gfp;
55 int arg_nr = PTR_INT(_arg);
56 struct expression *arg_expr;
57 sval_t sval;
59 arg_expr = get_argument_from_call_expr(expr->args, arg_nr);
60 if (!get_value(arg_expr, &sval))
61 return;
63 if (!macro_to_ul("__GFP_ZERO", &gfp))
64 return;
66 if (sval.uvalue & gfp) {
67 while (entry->function) {
68 if (strcmp(fn, entry->function) == 0) {
69 sm_warning("Please consider using %s instead of %s",
70 entry->alternative, entry->function);
71 break;
73 entry++;
78 void check_kvmalloc_array_zero(int id)
80 struct match_alloc_struct *entry = match_alloc_functions;
82 if (option_project != PROJ_KERNEL)
83 return;
85 my_id = id;
87 while (entry->function) {
88 add_function_hook(entry->function, &match_alloc, INT_PTR(entry->flag_pos));
89 entry++;