1 /*
   2  * Copyright (C) 2010 Dan Carpenter.
   3  *
   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.
   8  *
   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.
  13  *
  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
  16  */
  17 
  18 #include "smatch.h"
  19 
  20 static void match_sprintf(const char *fn, struct expression *expr, void *unused)
  21 {
  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;
  29 
  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);
  33 
  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);
  52 }
  53 
  54 void check_sprintf_overflow(int id)
  55 {
  56         add_function_hook("sprintf", &match_sprintf, NULL);
  57 }