buf_size: fix handling of unknown flexible array sizes
[smatch.git] / check_sprintf_overflow.c
blob46d97942aa960e56d5039d10671dd3bc762a99a0
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 void match_sprintf(const char *fn, struct expression *expr, void *unused)
22 struct expression *dest;
23 struct expression *format_string;
24 struct expression *data;
25 char *data_name = NULL;
26 int dest_size;
27 char *format;
28 int data_size;
30 dest = get_argument_from_call_expr(expr->args, 0);
31 format_string = get_argument_from_call_expr(expr->args, 1);
32 data = get_argument_from_call_expr(expr->args, 2);
34 dest_size = get_array_size_bytes(dest);
35 if (!dest_size)
36 return;
37 format = expr_to_var(format_string);
38 if (!format)
39 return;
40 if (strcmp(format, "\"%s\""))
41 goto free;
42 data_name = expr_to_str(data);
43 data_size = get_size_from_strlen(data);
44 if (!data_size)
45 data_size = get_array_size_bytes(data);
46 if (dest_size < data_size)
47 sm_error("sprintf() copies too much data from '%s': %d vs %d",
48 data_name, data_size, dest_size);
49 free:
50 free_string(data_name);
51 free_string(format);
54 void check_sprintf_overflow(int id)
56 add_function_hook("sprintf", &match_sprintf, NULL);