OSDN Git Service

914d6cc97928293ad5121ed6a14874d1e40fa69b
[pf3gnuchains/gcc-fork.git] / gcc / c-format.c
1 /* Check calls to formatted I/O functions (-Wformat).
2    Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
3    2001, 2002, 2003, 2004 Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 2, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING.  If not, write to the Free
19 Software Foundation, 59 Temple Place - Suite 330, Boston, MA
20 02111-1307, USA.  */
21
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "tm.h"
26 #include "tree.h"
27 #include "flags.h"
28 #include "toplev.h"
29 #include "c-common.h"
30 #include "intl.h"
31 #include "diagnostic.h"
32 #include "langhooks.h"
33 #include "c-format.h"
34 \f
35 /* Set format warning options according to a -Wformat=n option.  */
36
37 void
38 set_Wformat (int setting)
39 {
40   warn_format = setting;
41   warn_format_extra_args = setting;
42   warn_format_zero_length = setting;
43   if (setting != 1)
44     {
45       warn_format_nonliteral = setting;
46       warn_format_security = setting;
47       warn_format_y2k = setting;
48     }
49   /* Make sure not to disable -Wnonnull if -Wformat=0 is specified.  */
50   if (setting)
51     warn_nonnull = setting;
52 }
53
54 \f
55 /* Handle attributes associated with format checking.  */
56
57 /* This must be in the same order as format_types, except for
58    format_type_error.  Target-specific format types do not have
59    matching enum values.  */
60 enum format_type { printf_format_type, asm_fprintf_format_type,
61                    gcc_diag_format_type, gcc_cdiag_format_type,
62                    gcc_cxxdiag_format_type,
63                    scanf_format_type, strftime_format_type,
64                    strfmon_format_type, format_type_error = -1};
65
66 typedef struct function_format_info
67 {
68   int format_type;                      /* type of format (printf, scanf, etc.) */
69   unsigned HOST_WIDE_INT format_num;    /* number of format argument */
70   unsigned HOST_WIDE_INT first_arg_num; /* number of first arg (zero for varargs) */
71 } function_format_info;
72
73 static bool decode_format_attr (tree, function_format_info *, int);
74 static int decode_format_type (const char *);
75
76 static bool check_format_string (tree argument,
77                                  unsigned HOST_WIDE_INT format_num,
78                                  int flags, bool *no_add_attrs);
79 static bool get_constant (tree expr, unsigned HOST_WIDE_INT *value,
80                           int validated_p);
81
82
83 /* Handle a "format_arg" attribute; arguments as in
84    struct attribute_spec.handler.  */
85 tree
86 handle_format_arg_attribute (tree *node, tree ARG_UNUSED (name),
87                              tree args, int flags, bool *no_add_attrs)
88 {
89   tree type = *node;
90   tree format_num_expr = TREE_VALUE (args);
91   unsigned HOST_WIDE_INT format_num = 0;
92   tree argument;
93
94   if (!get_constant (format_num_expr, &format_num, 0))
95     {
96       error ("format string has invalid operand number");
97       *no_add_attrs = true;
98       return NULL_TREE;
99     }
100
101   argument = TYPE_ARG_TYPES (type);
102   if (argument)
103     {
104       if (!check_format_string (argument, format_num, flags, no_add_attrs))
105         return NULL_TREE;
106     }
107
108   if (TREE_CODE (TREE_TYPE (type)) != POINTER_TYPE
109       || (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (type)))
110           != char_type_node))
111     {
112       if (!(flags & (int) ATTR_FLAG_BUILT_IN))
113         error ("function does not return string type");
114       *no_add_attrs = true;
115       return NULL_TREE;
116     }
117
118   return NULL_TREE;
119 }
120
121 /* Verify that the format_num argument is actually a string, in case
122    the format attribute is in error.  */
123 static bool
124 check_format_string (tree argument, unsigned HOST_WIDE_INT format_num,
125                      int flags, bool *no_add_attrs)
126 {
127   unsigned HOST_WIDE_INT i;
128
129   for (i = 1; i != format_num; i++)
130     {
131       if (argument == 0)
132         break;
133       argument = TREE_CHAIN (argument);
134     }
135
136   if (!argument
137       || TREE_CODE (TREE_VALUE (argument)) != POINTER_TYPE
138       || (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_VALUE (argument)))
139           != char_type_node))
140     {
141       if (!(flags & (int) ATTR_FLAG_BUILT_IN))
142         error ("format string argument not a string type");
143       *no_add_attrs = true;
144       return false;
145     }
146
147   return true;
148 }
149
150 /* Strip any conversions from the expression, verify it is a constant,
151    and store its value. If validated_p is true, abort on errors.
152    Returns true on success, false otherwise.  */
153 static bool
154 get_constant (tree expr, unsigned HOST_WIDE_INT *value, int validated_p)
155 {
156   while (TREE_CODE (expr) == NOP_EXPR
157          || TREE_CODE (expr) == CONVERT_EXPR
158          || TREE_CODE (expr) == NON_LVALUE_EXPR)
159     expr = TREE_OPERAND (expr, 0);
160
161   if (TREE_CODE (expr) != INTEGER_CST || TREE_INT_CST_HIGH (expr) != 0)
162     {
163       gcc_assert (!validated_p);
164       return false;
165     }
166
167   *value = TREE_INT_CST_LOW (expr);
168
169   return true;
170 }
171
172 /* Decode the arguments to a "format" attribute into a function_format_info
173    structure.  It is already known that the list is of the right length.
174    If VALIDATED_P is true, then these attributes have already been validated
175    and this function will abort if they are erroneous; if false, it
176    will give an error message.  Returns true if the attributes are
177    successfully decoded, false otherwise.  */
178
179 static bool
180 decode_format_attr (tree args, function_format_info *info, int validated_p)
181 {
182   tree format_type_id = TREE_VALUE (args);
183   tree format_num_expr = TREE_VALUE (TREE_CHAIN (args));
184   tree first_arg_num_expr
185     = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (args)));
186
187   if (TREE_CODE (format_type_id) != IDENTIFIER_NODE)
188     {
189       gcc_assert (!validated_p);
190       error ("unrecognized format specifier");
191       return false;
192     }
193   else
194     {
195       const char *p = IDENTIFIER_POINTER (format_type_id);
196
197       info->format_type = decode_format_type (p);
198
199       if (info->format_type == format_type_error)
200         {
201           gcc_assert (!validated_p);
202           warning ("%qE is an unrecognized format function type",
203                    format_type_id);
204           return false;
205         }
206     }
207
208   if (!get_constant (format_num_expr, &info->format_num, validated_p))
209     {
210       error ("format string has invalid operand number");
211       return false;
212     }
213
214   if (!get_constant (first_arg_num_expr, &info->first_arg_num, validated_p))
215     {
216       error ("%<...%> has invalid operand number");
217       return false;
218     }
219
220   if (info->first_arg_num != 0 && info->first_arg_num <= info->format_num)
221     {
222       gcc_assert (!validated_p);
223       error ("format string argument follows the args to be formatted");
224       return false;
225     }
226
227   return true;
228 }
229 \f
230 /* Check a call to a format function against a parameter list.  */
231
232 /* The C standard version C++ is treated as equivalent to
233    or inheriting from, for the purpose of format features supported.  */
234 #define CPLUSPLUS_STD_VER       STD_C94
235 /* The C standard version we are checking formats against when pedantic.  */
236 #define C_STD_VER               ((int) (c_dialect_cxx ()                   \
237                                  ? CPLUSPLUS_STD_VER                       \
238                                  : (flag_isoc99                            \
239                                     ? STD_C99                              \
240                                     : (flag_isoc94 ? STD_C94 : STD_C89))))
241 /* The name to give to the standard version we are warning about when
242    pedantic.  FEATURE_VER is the version in which the feature warned out
243    appeared, which is higher than C_STD_VER.  */
244 #define C_STD_NAME(FEATURE_VER) (c_dialect_cxx ()               \
245                                  ? "ISO C++"                    \
246                                  : ((FEATURE_VER) == STD_EXT    \
247                                     ? "ISO C"                   \
248                                     : "ISO C90"))
249 /* Adjust a C standard version, which may be STD_C9L, to account for
250    -Wno-long-long.  Returns other standard versions unchanged.  */
251 #define ADJ_STD(VER)            ((int) ((VER) == STD_C9L                      \
252                                        ? (warn_long_long ? STD_C99 : STD_C89) \
253                                        : (VER)))
254
255 /* Structure describing details of a type expected in format checking,
256    and the type to check against it.  */
257 typedef struct format_wanted_type
258 {
259   /* The type wanted.  */
260   tree wanted_type;
261   /* The name of this type to use in diagnostics.  */
262   const char *wanted_type_name;
263   /* The level of indirection through pointers at which this type occurs.  */
264   int pointer_count;
265   /* Whether, when pointer_count is 1, to allow any character type when
266      pedantic, rather than just the character or void type specified.  */
267   int char_lenient_flag;
268   /* Whether the argument, dereferenced once, is written into and so the
269      argument must not be a pointer to a const-qualified type.  */
270   int writing_in_flag;
271   /* Whether the argument, dereferenced once, is read from and so
272      must not be a NULL pointer.  */
273   int reading_from_flag;
274   /* If warnings should be of the form "field precision should have
275      type 'int'", the name to use (in this case "field precision"),
276      otherwise NULL, for "format expects type 'long'" type
277      messages.  */
278   const char *name;
279   /* The actual parameter to check against the wanted type.  */
280   tree param;
281   /* The argument number of that parameter.  */
282   int arg_num;
283   /* The next type to check for this format conversion, or NULL if none.  */
284   struct format_wanted_type *next;
285 } format_wanted_type;
286
287
288 static const format_length_info printf_length_specs[] =
289 {
290   { "h", FMT_LEN_h, STD_C89, "hh", FMT_LEN_hh, STD_C99 },
291   { "l", FMT_LEN_l, STD_C89, "ll", FMT_LEN_ll, STD_C9L },
292   { "q", FMT_LEN_ll, STD_EXT, NULL, 0, 0 },
293   { "L", FMT_LEN_L, STD_C89, NULL, 0, 0 },
294   { "z", FMT_LEN_z, STD_C99, NULL, 0, 0 },
295   { "Z", FMT_LEN_z, STD_EXT, NULL, 0, 0 },
296   { "t", FMT_LEN_t, STD_C99, NULL, 0, 0 },
297   { "j", FMT_LEN_j, STD_C99, NULL, 0, 0 },
298   { NULL, 0, 0, NULL, 0, 0 }
299 };
300
301 /* Length specifiers valid for asm_fprintf.  */
302 static const format_length_info asm_fprintf_length_specs[] =
303 {
304   { "l", FMT_LEN_l, STD_C89, "ll", FMT_LEN_ll, STD_C89 },
305   { "w", FMT_LEN_none, STD_C89, NULL, 0, 0 },
306   { NULL, 0, 0, NULL, 0, 0 }
307 };
308
309 /* Length specifiers valid for GCC diagnostics.  */
310 static const format_length_info gcc_diag_length_specs[] =
311 {
312   { "l", FMT_LEN_l, STD_C89, "ll", FMT_LEN_ll, STD_C89 },
313   { "w", FMT_LEN_none, STD_C89, NULL, 0, 0 },
314   { NULL, 0, 0, NULL, 0, 0 }
315 };
316
317 /* The custom diagnostics all accept the same length specifiers.  */
318 #define gcc_cdiag_length_specs gcc_diag_length_specs
319 #define gcc_cxxdiag_length_specs gcc_diag_length_specs
320
321 /* This differs from printf_length_specs only in that "Z" is not accepted.  */
322 static const format_length_info scanf_length_specs[] =
323 {
324   { "h", FMT_LEN_h, STD_C89, "hh", FMT_LEN_hh, STD_C99 },
325   { "l", FMT_LEN_l, STD_C89, "ll", FMT_LEN_ll, STD_C9L },
326   { "q", FMT_LEN_ll, STD_EXT, NULL, 0, 0 },
327   { "L", FMT_LEN_L, STD_C89, NULL, 0, 0 },
328   { "z", FMT_LEN_z, STD_C99, NULL, 0, 0 },
329   { "t", FMT_LEN_t, STD_C99, NULL, 0, 0 },
330   { "j", FMT_LEN_j, STD_C99, NULL, 0, 0 },
331   { NULL, 0, 0, NULL, 0, 0 }
332 };
333
334
335 /* All tables for strfmon use STD_C89 everywhere, since -pedantic warnings
336    make no sense for a format type not part of any C standard version.  */
337 static const format_length_info strfmon_length_specs[] =
338 {
339   /* A GNU extension.  */
340   { "L", FMT_LEN_L, STD_C89, NULL, 0, 0 },
341   { NULL, 0, 0, NULL, 0, 0 }
342 };
343
344 static const format_flag_spec printf_flag_specs[] =
345 {
346   { ' ',  0, 0, N_("' ' flag"),        N_("the ' ' printf flag"),              STD_C89 },
347   { '+',  0, 0, N_("'+' flag"),        N_("the '+' printf flag"),              STD_C89 },
348   { '#',  0, 0, N_("'#' flag"),        N_("the '#' printf flag"),              STD_C89 },
349   { '0',  0, 0, N_("'0' flag"),        N_("the '0' printf flag"),              STD_C89 },
350   { '-',  0, 0, N_("'-' flag"),        N_("the '-' printf flag"),              STD_C89 },
351   { '\'', 0, 0, N_("''' flag"),        N_("the ''' printf flag"),              STD_EXT },
352   { 'I',  0, 0, N_("'I' flag"),        N_("the 'I' printf flag"),              STD_EXT },
353   { 'w',  0, 0, N_("field width"),     N_("field width in printf format"),     STD_C89 },
354   { 'p',  0, 0, N_("precision"),       N_("precision in printf format"),       STD_C89 },
355   { 'L',  0, 0, N_("length modifier"), N_("length modifier in printf format"), STD_C89 },
356   { 0, 0, 0, NULL, NULL, 0 }
357 };
358
359
360 static const format_flag_pair printf_flag_pairs[] =
361 {
362   { ' ', '+', 1, 0   },
363   { '0', '-', 1, 0   },
364   { '0', 'p', 1, 'i' },
365   { 0, 0, 0, 0 }
366 };
367
368 static const format_flag_spec asm_fprintf_flag_specs[] =
369 {
370   { ' ',  0, 0, N_("' ' flag"),        N_("the ' ' printf flag"),              STD_C89 },
371   { '+',  0, 0, N_("'+' flag"),        N_("the '+' printf flag"),              STD_C89 },
372   { '#',  0, 0, N_("'#' flag"),        N_("the '#' printf flag"),              STD_C89 },
373   { '0',  0, 0, N_("'0' flag"),        N_("the '0' printf flag"),              STD_C89 },
374   { '-',  0, 0, N_("'-' flag"),        N_("the '-' printf flag"),              STD_C89 },
375   { 'w',  0, 0, N_("field width"),     N_("field width in printf format"),     STD_C89 },
376   { 'p',  0, 0, N_("precision"),       N_("precision in printf format"),       STD_C89 },
377   { 'L',  0, 0, N_("length modifier"), N_("length modifier in printf format"), STD_C89 },
378   { 0, 0, 0, NULL, NULL, 0 }
379 };
380
381 static const format_flag_pair asm_fprintf_flag_pairs[] =
382 {
383   { ' ', '+', 1, 0   },
384   { '0', '-', 1, 0   },
385   { '0', 'p', 1, 'i' },
386   { 0, 0, 0, 0 }
387 };
388
389 static const format_flag_pair gcc_diag_flag_pairs[] =
390 {
391   { 0, 0, 0, 0 }
392 };
393
394 #define gcc_cdiag_flag_pairs gcc_diag_flag_pairs
395 #define gcc_cxxdiag_flag_pairs gcc_diag_flag_pairs
396
397 static const format_flag_spec gcc_diag_flag_specs[] =
398 {
399   { 'q',  0, 0, N_("'q' flag"),        N_("the 'q' diagnostic flag"),          STD_C89 },
400   { 'p',  0, 0, N_("precision"),       N_("precision in printf format"),       STD_C89 },
401   { 'L',  0, 0, N_("length modifier"), N_("length modifier in printf format"), STD_C89 },
402   { 0, 0, 0, NULL, NULL, 0 }
403 };
404
405 #define gcc_cdiag_flag_specs gcc_diag_flag_specs
406
407 static const format_flag_spec gcc_cxxdiag_flag_specs[] =
408 {
409   { '+',  0, 0, N_("'+' flag"),        N_("the '+' printf flag"),              STD_C89 },
410   { '#',  0, 0, N_("'#' flag"),        N_("the '#' printf flag"),              STD_C89 },
411   { 'q',  0, 0, N_("'q' flag"),        N_("the 'q' diagnostic flag"),          STD_C89 },
412   { 'p',  0, 0, N_("precision"),       N_("precision in printf format"),       STD_C89 },
413   { 'L',  0, 0, N_("length modifier"), N_("length modifier in printf format"), STD_C89 },
414   { 0, 0, 0, NULL, NULL, 0 }
415 };
416
417 static const format_flag_spec scanf_flag_specs[] =
418 {
419   { '*',  0, 0, N_("assignment suppression"), N_("the assignment suppression scanf feature"), STD_C89 },
420   { 'a',  0, 0, N_("'a' flag"),               N_("the 'a' scanf flag"),                       STD_EXT },
421   { 'w',  0, 0, N_("field width"),            N_("field width in scanf format"),              STD_C89 },
422   { 'L',  0, 0, N_("length modifier"),        N_("length modifier in scanf format"),          STD_C89 },
423   { '\'', 0, 0, N_("''' flag"),               N_("the ''' scanf flag"),                       STD_EXT },
424   { 'I',  0, 0, N_("'I' flag"),               N_("the 'I' scanf flag"),                       STD_EXT },
425   { 0, 0, 0, NULL, NULL, 0 }
426 };
427
428
429 static const format_flag_pair scanf_flag_pairs[] =
430 {
431   { '*', 'L', 0, 0 },
432   { 0, 0, 0, 0 }
433 };
434
435
436 static const format_flag_spec strftime_flag_specs[] =
437 {
438   { '_', 0,   0, N_("'_' flag"),     N_("the '_' strftime flag"),          STD_EXT },
439   { '-', 0,   0, N_("'-' flag"),     N_("the '-' strftime flag"),          STD_EXT },
440   { '0', 0,   0, N_("'0' flag"),     N_("the '0' strftime flag"),          STD_EXT },
441   { '^', 0,   0, N_("'^' flag"),     N_("the '^' strftime flag"),          STD_EXT },
442   { '#', 0,   0, N_("'#' flag"),     N_("the '#' strftime flag"),          STD_EXT },
443   { 'w', 0,   0, N_("field width"),  N_("field width in strftime format"), STD_EXT },
444   { 'E', 0,   0, N_("'E' modifier"), N_("the 'E' strftime modifier"),      STD_C99 },
445   { 'O', 0,   0, N_("'O' modifier"), N_("the 'O' strftime modifier"),      STD_C99 },
446   { 'O', 'o', 0, NULL,               N_("the 'O' modifier"),               STD_EXT },
447   { 0, 0, 0, NULL, NULL, 0 }
448 };
449
450
451 static const format_flag_pair strftime_flag_pairs[] =
452 {
453   { 'E', 'O', 0, 0 },
454   { '_', '-', 0, 0 },
455   { '_', '0', 0, 0 },
456   { '-', '0', 0, 0 },
457   { '^', '#', 0, 0 },
458   { 0, 0, 0, 0 }
459 };
460
461
462 static const format_flag_spec strfmon_flag_specs[] =
463 {
464   { '=',  0, 1, N_("fill character"),  N_("fill character in strfmon format"),  STD_C89 },
465   { '^',  0, 0, N_("'^' flag"),        N_("the '^' strfmon flag"),              STD_C89 },
466   { '+',  0, 0, N_("'+' flag"),        N_("the '+' strfmon flag"),              STD_C89 },
467   { '(',  0, 0, N_("'(' flag"),        N_("the '(' strfmon flag"),              STD_C89 },
468   { '!',  0, 0, N_("'!' flag"),        N_("the '!' strfmon flag"),              STD_C89 },
469   { '-',  0, 0, N_("'-' flag"),        N_("the '-' strfmon flag"),              STD_C89 },
470   { 'w',  0, 0, N_("field width"),     N_("field width in strfmon format"),     STD_C89 },
471   { '#',  0, 0, N_("left precision"),  N_("left precision in strfmon format"),  STD_C89 },
472   { 'p',  0, 0, N_("right precision"), N_("right precision in strfmon format"), STD_C89 },
473   { 'L',  0, 0, N_("length modifier"), N_("length modifier in strfmon format"), STD_C89 },
474   { 0, 0, 0, NULL, NULL, 0 }
475 };
476
477 static const format_flag_pair strfmon_flag_pairs[] =
478 {
479   { '+', '(', 0, 0 },
480   { 0, 0, 0, 0 }
481 };
482
483
484 static const format_char_info print_char_table[] =
485 {
486   /* C89 conversion specifiers.  */
487   { "di",  0, STD_C89, { T89_I,   T99_SC,  T89_S,   T89_L,   T9L_LL,  TEX_LL,  T99_SST, T99_PD,  T99_IM  }, "-wp0 +'I",  "i",  NULL },
488   { "oxX", 0, STD_C89, { T89_UI,  T99_UC,  T89_US,  T89_UL,  T9L_ULL, TEX_ULL, T99_ST,  T99_UPD, T99_UIM }, "-wp0#",     "i",  NULL },
489   { "u",   0, STD_C89, { T89_UI,  T99_UC,  T89_US,  T89_UL,  T9L_ULL, TEX_ULL, T99_ST,  T99_UPD, T99_UIM }, "-wp0'I",    "i",  NULL },
490   { "fgG", 0, STD_C89, { T89_D,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T89_LD,  BADLEN,  BADLEN,  BADLEN  }, "-wp0 +#'I", "",   NULL },
491   { "eE",  0, STD_C89, { T89_D,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T89_LD,  BADLEN,  BADLEN,  BADLEN  }, "-wp0 +#I",  "",   NULL },
492   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T94_WI,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-w",        "",   NULL },
493   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  T94_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp",       "cR", NULL },
494   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-w",        "c",  NULL },
495   { "n",   1, STD_C89, { T89_I,   T99_SC,  T89_S,   T89_L,   T9L_LL,  BADLEN,  T99_SST, T99_PD,  T99_IM  }, "",          "W",  NULL },
496   /* C99 conversion specifiers.  */
497   { "F",   0, STD_C99, { T99_D,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T99_LD,  BADLEN,  BADLEN,  BADLEN  }, "-wp0 +#'I", "",   NULL },
498   { "aA",  0, STD_C99, { T99_D,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T99_LD,  BADLEN,  BADLEN,  BADLEN  }, "-wp0 +#",   "",   NULL },
499   /* X/Open conversion specifiers.  */
500   { "C",   0, STD_EXT, { TEX_WI,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-w",        "",   NULL },
501   { "S",   1, STD_EXT, { TEX_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp",       "R",  NULL },
502   /* GNU conversion specifiers.  */
503   { "m",   0, STD_EXT, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp",       "",   NULL },
504   { NULL,  0, 0, NOLENGTHS, NULL, NULL, NULL }
505 };
506
507 static const format_char_info asm_fprintf_char_table[] =
508 {
509   /* C89 conversion specifiers.  */
510   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp0 +",  "i", NULL },
511   { "oxX", 0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp0#",   "i", NULL },
512   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp0",    "i", NULL },
513   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-w",       "", NULL },
514   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp",    "cR", NULL },
515
516   /* asm_fprintf conversion specifiers.  */
517   { "O",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
518   { "R",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
519   { "I",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
520   { "L",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
521   { "U",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
522   { "r",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",  "", NULL },
523   { "@",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
524   { NULL,  0, 0, NOLENGTHS, NULL, NULL, NULL }
525 };
526
527 static const format_char_info gcc_diag_char_table[] =
528 {
529   /* C89 conversion specifiers.  */
530   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
531   { "ox",  0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
532   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
533   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
534   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "pq", "cR", NULL },
535   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "c",  NULL },
536
537   /* Custom conversion specifiers.  */
538
539   /* %H will require "location_t" at runtime.  */
540   { "H",   0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
541
542   /* These will require a "tree" at runtime.  */
543   { "J", 0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",    "",   NULL },
544
545   { "<>'", 0, STD_C89, NOARGUMENTS, "",      "",   NULL },
546   { "m",   0, STD_C89, NOARGUMENTS, "q",     "",   NULL },
547   { NULL,  0, 0, NOLENGTHS, NULL, NULL, NULL }
548 };
549
550 static const format_char_info gcc_cdiag_char_table[] =
551 {
552   /* C89 conversion specifiers.  */
553   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
554   { "ox",  0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
555   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
556   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
557   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "pq", "cR", NULL },
558   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "c",  NULL },
559
560   /* Custom conversion specifiers.  */
561
562   /* %H will require "location_t" at runtime.  */
563   { "H",   0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
564
565   /* These will require a "tree" at runtime.  */
566   { "DEFJT", 0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q", "",   NULL },
567
568   { "<>'", 0, STD_C89, NOARGUMENTS, "",      "",   NULL },
569   { "m",   0, STD_C89, NOARGUMENTS, "q",     "",   NULL },
570   { NULL,  0, 0, NOLENGTHS, NULL, NULL, NULL }
571 };
572
573 static const format_char_info gcc_cxxdiag_char_table[] =
574 {
575   /* C89 conversion specifiers.  */
576   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
577   { "ox",  0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
578   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
579   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
580   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "pq", "cR", NULL },
581   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "c",  NULL },
582
583   /* Custom conversion specifiers.  */
584
585   /* %H will require "location_t" at runtime.  */
586   { "H",   0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
587
588   /* These will require a "tree" at runtime.  */
589   { "ADEFJTV",0,STD_C89,{ T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q+#",   "",   NULL },
590
591   /* These accept either an 'int' or an 'enum tree_code' (which is handled as an 'int'.)  */
592   { "CLOPQ",0,STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
593
594   { "<>'", 0, STD_C89, NOARGUMENTS, "",      "",   NULL },
595   { "m",   0, STD_C89, NOARGUMENTS, "q",     "",   NULL },
596   { NULL,  0, 0, NOLENGTHS, NULL, NULL, NULL }
597 };
598
599 static const format_char_info scan_char_table[] =
600 {
601   /* C89 conversion specifiers.  */
602   { "di",    1, STD_C89, { T89_I,   T99_SC,  T89_S,   T89_L,   T9L_LL,  TEX_LL,  T99_SST, T99_PD,  T99_IM  }, "*w'I", "W",   NULL },
603   { "u",     1, STD_C89, { T89_UI,  T99_UC,  T89_US,  T89_UL,  T9L_ULL, TEX_ULL, T99_ST,  T99_UPD, T99_UIM }, "*w'I", "W",   NULL },
604   { "oxX",   1, STD_C89, { T89_UI,  T99_UC,  T89_US,  T89_UL,  T9L_ULL, TEX_ULL, T99_ST,  T99_UPD, T99_UIM }, "*w",   "W",   NULL },
605   { "efgEG", 1, STD_C89, { T89_F,   BADLEN,  BADLEN,  T89_D,   BADLEN,  T89_LD,  BADLEN,  BADLEN,  BADLEN  }, "*w'",  "W",   NULL },
606   { "c",     1, STD_C89, { T89_C,   BADLEN,  BADLEN,  T94_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "*w",   "cW",  NULL },
607   { "s",     1, STD_C89, { T89_C,   BADLEN,  BADLEN,  T94_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "*aw",  "cW",  NULL },
608   { "[",     1, STD_C89, { T89_C,   BADLEN,  BADLEN,  T94_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "*aw",  "cW[", NULL },
609   { "p",     2, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "*w",   "W",   NULL },
610   { "n",     1, STD_C89, { T89_I,   T99_SC,  T89_S,   T89_L,   T9L_LL,  BADLEN,  T99_SST, T99_PD,  T99_IM  }, "",     "W",   NULL },
611   /* C99 conversion specifiers.  */
612   { "FaA",   1, STD_C99, { T99_F,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T99_LD,  BADLEN,  BADLEN,  BADLEN  }, "*w'",  "W",   NULL },
613   /* X/Open conversion specifiers.  */
614   { "C",     1, STD_EXT, { TEX_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "*w",   "W",   NULL },
615   { "S",     1, STD_EXT, { TEX_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "*aw",  "W",   NULL },
616   { NULL, 0, 0, NOLENGTHS, NULL, NULL, NULL }
617 };
618
619 static const format_char_info time_char_table[] =
620 {
621   /* C89 conversion specifiers.  */
622   { "ABZab",            0, STD_C89, NOLENGTHS, "^#",     "",   NULL },
623   { "cx",               0, STD_C89, NOLENGTHS, "E",      "3",  NULL },
624   { "HIMSUWdmw",        0, STD_C89, NOLENGTHS, "-_0Ow",  "",   NULL },
625   { "j",                0, STD_C89, NOLENGTHS, "-_0Ow",  "o",  NULL },
626   { "p",                0, STD_C89, NOLENGTHS, "#",      "",   NULL },
627   { "X",                0, STD_C89, NOLENGTHS, "E",      "",   NULL },
628   { "y",                0, STD_C89, NOLENGTHS, "EO-_0w", "4",  NULL },
629   { "Y",                0, STD_C89, NOLENGTHS, "-_0EOw", "o",  NULL },
630   { "%",                0, STD_C89, NOLENGTHS, "",       "",   NULL },
631   /* C99 conversion specifiers.  */
632   { "C",                0, STD_C99, NOLENGTHS, "-_0EOw", "o",  NULL },
633   { "D",                0, STD_C99, NOLENGTHS, "",       "2",  NULL },
634   { "eVu",              0, STD_C99, NOLENGTHS, "-_0Ow",  "",   NULL },
635   { "FRTnrt",           0, STD_C99, NOLENGTHS, "",       "",   NULL },
636   { "g",                0, STD_C99, NOLENGTHS, "O-_0w",  "2o", NULL },
637   { "G",                0, STD_C99, NOLENGTHS, "-_0Ow",  "o",  NULL },
638   { "h",                0, STD_C99, NOLENGTHS, "^#",     "",   NULL },
639   { "z",                0, STD_C99, NOLENGTHS, "O",      "o",  NULL },
640   /* GNU conversion specifiers.  */
641   { "kls",              0, STD_EXT, NOLENGTHS, "-_0Ow",  "",   NULL },
642   { "P",                0, STD_EXT, NOLENGTHS, "",       "",   NULL },
643   { NULL,               0, 0, NOLENGTHS, NULL, NULL, NULL }
644 };
645
646 static const format_char_info monetary_char_table[] =
647 {
648   { "in", 0, STD_C89, { T89_D, BADLEN, BADLEN, BADLEN, BADLEN, T89_LD, BADLEN, BADLEN, BADLEN }, "=^+(!-w#p", "", NULL },
649   { NULL, 0, 0, NOLENGTHS, NULL, NULL, NULL }
650 };
651
652 /* This must be in the same order as enum format_type.  */
653 static const format_kind_info format_types_orig[] =
654 {
655   { "printf",   printf_length_specs,  print_char_table, " +#0-'I", NULL, 
656     printf_flag_specs, printf_flag_pairs,
657     FMT_FLAG_ARG_CONVERT|FMT_FLAG_DOLLAR_MULTIPLE|FMT_FLAG_USE_DOLLAR|FMT_FLAG_EMPTY_PREC_OK,
658     'w', 0, 'p', 0, 'L',
659     &integer_type_node, &integer_type_node
660   },
661   { "asm_fprintf",   asm_fprintf_length_specs,  asm_fprintf_char_table, " +#0-", NULL, 
662     asm_fprintf_flag_specs, asm_fprintf_flag_pairs,
663     FMT_FLAG_ARG_CONVERT|FMT_FLAG_EMPTY_PREC_OK,
664     'w', 0, 'p', 0, 'L',
665     NULL, NULL
666   },
667   { "gcc_diag",   gcc_diag_length_specs,  gcc_diag_char_table, "q", NULL, 
668     gcc_diag_flag_specs, gcc_diag_flag_pairs,
669     FMT_FLAG_ARG_CONVERT,
670     0, 0, 'p', 0, 'L',
671     NULL, &integer_type_node
672   },
673   { "gcc_cdiag",   gcc_cdiag_length_specs,  gcc_cdiag_char_table, "q", NULL, 
674     gcc_cdiag_flag_specs, gcc_cdiag_flag_pairs,
675     FMT_FLAG_ARG_CONVERT,
676     0, 0, 'p', 0, 'L',
677     NULL, &integer_type_node
678   },
679   { "gcc_cxxdiag",   gcc_cxxdiag_length_specs,  gcc_cxxdiag_char_table, "q+#", NULL, 
680     gcc_cxxdiag_flag_specs, gcc_cxxdiag_flag_pairs,
681     FMT_FLAG_ARG_CONVERT,
682     0, 0, 'p', 0, 'L',
683     NULL, &integer_type_node
684   },
685   { "scanf",    scanf_length_specs,   scan_char_table,  "*'I", NULL, 
686     scanf_flag_specs, scanf_flag_pairs,
687     FMT_FLAG_ARG_CONVERT|FMT_FLAG_SCANF_A_KLUDGE|FMT_FLAG_USE_DOLLAR|FMT_FLAG_ZERO_WIDTH_BAD|FMT_FLAG_DOLLAR_GAP_POINTER_OK,
688     'w', 0, 0, '*', 'L',
689     NULL, NULL
690   },
691   { "strftime", NULL,                 time_char_table,  "_-0^#", "EO",
692     strftime_flag_specs, strftime_flag_pairs,
693     FMT_FLAG_FANCY_PERCENT_OK, 'w', 0, 0, 0, 0,
694     NULL, NULL
695   },
696   { "strfmon",  strfmon_length_specs, monetary_char_table, "=^+(!-", NULL, 
697     strfmon_flag_specs, strfmon_flag_pairs,
698     FMT_FLAG_ARG_CONVERT, 'w', '#', 'p', 0, 'L',
699     NULL, NULL
700   }
701 };
702
703 /* This layer of indirection allows GCC to reassign format_types with
704    new data if necessary, while still allowing the original data to be
705    const.  */
706 static const format_kind_info *format_types = format_types_orig;
707 /* We can modify this one.  We also add target-specific format types
708    to the end of the array.  */
709 static format_kind_info *dynamic_format_types;
710
711 static int n_format_types = ARRAY_SIZE (format_types_orig);
712
713 /* Structure detailing the results of checking a format function call
714    where the format expression may be a conditional expression with
715    many leaves resulting from nested conditional expressions.  */
716 typedef struct
717 {
718   /* Number of leaves of the format argument that could not be checked
719      as they were not string literals.  */
720   int number_non_literal;
721   /* Number of leaves of the format argument that were null pointers or
722      string literals, but had extra format arguments.  */
723   int number_extra_args;
724   /* Number of leaves of the format argument that were null pointers or
725      string literals, but had extra format arguments and used $ operand
726      numbers.  */
727   int number_dollar_extra_args;
728   /* Number of leaves of the format argument that were wide string
729      literals.  */
730   int number_wide;
731   /* Number of leaves of the format argument that were empty strings.  */
732   int number_empty;
733   /* Number of leaves of the format argument that were unterminated
734      strings.  */
735   int number_unterminated;
736   /* Number of leaves of the format argument that were not counted above.  */
737   int number_other;
738 } format_check_results;
739
740 typedef struct
741 {
742   format_check_results *res;
743   function_format_info *info;
744   tree params;
745 } format_check_context;
746
747 static void check_format_info (function_format_info *, tree);
748 static void check_format_arg (void *, tree, unsigned HOST_WIDE_INT);
749 static void check_format_info_main (format_check_results *,
750                                     function_format_info *,
751                                     const char *, int, tree,
752                                     unsigned HOST_WIDE_INT);
753
754 static void init_dollar_format_checking (int, tree);
755 static int maybe_read_dollar_number (const char **, int,
756                                      tree, tree *, const format_kind_info *);
757 static bool avoid_dollar_number (const char *);
758 static void finish_dollar_format_checking (format_check_results *, int);
759
760 static const format_flag_spec *get_flag_spec (const format_flag_spec *,
761                                               int, const char *);
762
763 static void check_format_types (format_wanted_type *, const char *, int);
764 static void format_type_warning (const char *, const char *, int, tree,
765                                  int, const char *, tree, int);
766
767 /* Decode a format type from a string, returning the type, or
768    format_type_error if not valid, in which case the caller should print an
769    error message.  */
770 static int
771 decode_format_type (const char *s)
772 {
773   int i;
774   int slen;
775   slen = strlen (s);
776   for (i = 0; i < n_format_types; i++)
777     {
778       int alen;
779       if (!strcmp (s, format_types[i].name))
780         return i;
781       alen = strlen (format_types[i].name);
782       if (slen == alen + 4 && s[0] == '_' && s[1] == '_'
783           && s[slen - 1] == '_' && s[slen - 2] == '_'
784           && !strncmp (s + 2, format_types[i].name, alen))
785         return i;
786     }
787   return format_type_error;
788 }
789
790 \f
791 /* Check the argument list of a call to printf, scanf, etc.
792    ATTRS are the attributes on the function type.
793    PARAMS is the list of argument values.  Also, if -Wmissing-format-attribute,
794    warn for calls to vprintf or vscanf in functions with no such format
795    attribute themselves.  */
796
797 void
798 check_function_format (tree attrs, tree params)
799 {
800   tree a;
801
802   /* See if this function has any format attributes.  */
803   for (a = attrs; a; a = TREE_CHAIN (a))
804     {
805       if (is_attribute_p ("format", TREE_PURPOSE (a)))
806         {
807           /* Yup; check it.  */
808           function_format_info info;
809           decode_format_attr (TREE_VALUE (a), &info, 1);
810           check_format_info (&info, params);
811           if (warn_missing_format_attribute && info.first_arg_num == 0
812               && (format_types[info.format_type].flags
813                   & (int) FMT_FLAG_ARG_CONVERT))
814             {
815               tree c;
816               for (c = TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl));
817                    c;
818                    c = TREE_CHAIN (c))
819                 if (is_attribute_p ("format", TREE_PURPOSE (c))
820                     && (decode_format_type (IDENTIFIER_POINTER
821                                             (TREE_VALUE (TREE_VALUE (c))))
822                         == info.format_type))
823                   break;
824               if (c == NULL_TREE)
825                 {
826                   /* Check if the current function has a parameter to which
827                      the format attribute could be attached; if not, it
828                      can't be a candidate for a format attribute, despite
829                      the vprintf-like or vscanf-like call.  */
830                   tree args;
831                   for (args = DECL_ARGUMENTS (current_function_decl);
832                        args != 0;
833                        args = TREE_CHAIN (args))
834                     {
835                       if (TREE_CODE (TREE_TYPE (args)) == POINTER_TYPE
836                           && (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (args)))
837                               == char_type_node))
838                         break;
839                     }
840                   if (args != 0)
841                     warning ("function might be possible candidate for %qs format attribute",
842                              format_types[info.format_type].name);
843                 }
844             }
845         }
846     }
847 }
848
849
850 /* Variables used by the checking of $ operand number formats.  */
851 static char *dollar_arguments_used = NULL;
852 static char *dollar_arguments_pointer_p = NULL;
853 static int dollar_arguments_alloc = 0;
854 static int dollar_arguments_count;
855 static int dollar_first_arg_num;
856 static int dollar_max_arg_used;
857 static int dollar_format_warned;
858
859 /* Initialize the checking for a format string that may contain $
860    parameter number specifications; we will need to keep track of whether
861    each parameter has been used.  FIRST_ARG_NUM is the number of the first
862    argument that is a parameter to the format, or 0 for a vprintf-style
863    function; PARAMS is the list of arguments starting at this argument.  */
864
865 static void
866 init_dollar_format_checking (int first_arg_num, tree params)
867 {
868   tree oparams = params;
869
870   dollar_first_arg_num = first_arg_num;
871   dollar_arguments_count = 0;
872   dollar_max_arg_used = 0;
873   dollar_format_warned = 0;
874   if (first_arg_num > 0)
875     {
876       while (params)
877         {
878           dollar_arguments_count++;
879           params = TREE_CHAIN (params);
880         }
881     }
882   if (dollar_arguments_alloc < dollar_arguments_count)
883     {
884       if (dollar_arguments_used)
885         free (dollar_arguments_used);
886       if (dollar_arguments_pointer_p)
887         free (dollar_arguments_pointer_p);
888       dollar_arguments_alloc = dollar_arguments_count;
889       dollar_arguments_used = XNEWVEC (char, dollar_arguments_alloc);
890       dollar_arguments_pointer_p = XNEWVEC (char, dollar_arguments_alloc);
891     }
892   if (dollar_arguments_alloc)
893     {
894       memset (dollar_arguments_used, 0, dollar_arguments_alloc);
895       if (first_arg_num > 0)
896         {
897           int i = 0;
898           params = oparams;
899           while (params)
900             {
901               dollar_arguments_pointer_p[i] = (TREE_CODE (TREE_TYPE (TREE_VALUE (params)))
902                                                == POINTER_TYPE);
903               params = TREE_CHAIN (params);
904               i++;
905             }
906         }
907     }
908 }
909
910
911 /* Look for a decimal number followed by a $ in *FORMAT.  If DOLLAR_NEEDED
912    is set, it is an error if one is not found; otherwise, it is OK.  If
913    such a number is found, check whether it is within range and mark that
914    numbered operand as being used for later checking.  Returns the operand
915    number if found and within range, zero if no such number was found and
916    this is OK, or -1 on error.  PARAMS points to the first operand of the
917    format; PARAM_PTR is made to point to the parameter referred to.  If
918    a $ format is found, *FORMAT is updated to point just after it.  */
919
920 static int
921 maybe_read_dollar_number (const char **format,
922                           int dollar_needed, tree params, tree *param_ptr,
923                           const format_kind_info *fki)
924 {
925   int argnum;
926   int overflow_flag;
927   const char *fcp = *format;
928   if (!ISDIGIT (*fcp))
929     {
930       if (dollar_needed)
931         {
932           warning ("missing $ operand number in format");
933           return -1;
934         }
935       else
936         return 0;
937     }
938   argnum = 0;
939   overflow_flag = 0;
940   while (ISDIGIT (*fcp))
941     {
942       int nargnum;
943       nargnum = 10 * argnum + (*fcp - '0');
944       if (nargnum < 0 || nargnum / 10 != argnum)
945         overflow_flag = 1;
946       argnum = nargnum;
947       fcp++;
948     }
949   if (*fcp != '$')
950     {
951       if (dollar_needed)
952         {
953           warning ("missing $ operand number in format");
954           return -1;
955         }
956       else
957         return 0;
958     }
959   *format = fcp + 1;
960   if (pedantic && !dollar_format_warned)
961     {
962       warning ("%s does not support %%n$ operand number formats",
963                C_STD_NAME (STD_EXT));
964       dollar_format_warned = 1;
965     }
966   if (overflow_flag || argnum == 0
967       || (dollar_first_arg_num && argnum > dollar_arguments_count))
968     {
969       warning ("operand number out of range in format");
970       return -1;
971     }
972   if (argnum > dollar_max_arg_used)
973     dollar_max_arg_used = argnum;
974   /* For vprintf-style functions we may need to allocate more memory to
975      track which arguments are used.  */
976   while (dollar_arguments_alloc < dollar_max_arg_used)
977     {
978       int nalloc;
979       nalloc = 2 * dollar_arguments_alloc + 16;
980       dollar_arguments_used = XRESIZEVEC (char, dollar_arguments_used,
981                                           nalloc);
982       dollar_arguments_pointer_p = XRESIZEVEC (char, dollar_arguments_pointer_p,
983                                                nalloc);
984       memset (dollar_arguments_used + dollar_arguments_alloc, 0,
985               nalloc - dollar_arguments_alloc);
986       dollar_arguments_alloc = nalloc;
987     }
988   if (!(fki->flags & (int) FMT_FLAG_DOLLAR_MULTIPLE)
989       && dollar_arguments_used[argnum - 1] == 1)
990     {
991       dollar_arguments_used[argnum - 1] = 2;
992       warning ("format argument %d used more than once in %s format",
993                argnum, fki->name);
994     }
995   else
996     dollar_arguments_used[argnum - 1] = 1;
997   if (dollar_first_arg_num)
998     {
999       int i;
1000       *param_ptr = params;
1001       for (i = 1; i < argnum && *param_ptr != 0; i++)
1002         *param_ptr = TREE_CHAIN (*param_ptr);
1003
1004       /* This case shouldn't be caught here.  */
1005       gcc_assert (*param_ptr);
1006     }
1007   else
1008     *param_ptr = 0;
1009   return argnum;
1010 }
1011
1012 /* Ensure that FORMAT does not start with a decimal number followed by
1013    a $; give a diagnostic and return true if it does, false otherwise.  */
1014
1015 static bool
1016 avoid_dollar_number (const char *format)
1017 {
1018   if (!ISDIGIT (*format))
1019     return false;
1020   while (ISDIGIT (*format))
1021     format++;
1022   if (*format == '$')
1023     {
1024       warning ("$ operand number used after format without operand number");
1025       return true;
1026     }
1027   return false;
1028 }
1029
1030
1031 /* Finish the checking for a format string that used $ operand number formats
1032    instead of non-$ formats.  We check for unused operands before used ones
1033    (a serious error, since the implementation of the format function
1034    can't know what types to pass to va_arg to find the later arguments).
1035    and for unused operands at the end of the format (if we know how many
1036    arguments the format had, so not for vprintf).  If there were operand
1037    numbers out of range on a non-vprintf-style format, we won't have reached
1038    here.  If POINTER_GAP_OK, unused arguments are OK if all arguments are
1039    pointers.  */
1040
1041 static void
1042 finish_dollar_format_checking (format_check_results *res, int pointer_gap_ok)
1043 {
1044   int i;
1045   bool found_pointer_gap = false;
1046   for (i = 0; i < dollar_max_arg_used; i++)
1047     {
1048       if (!dollar_arguments_used[i])
1049         {
1050           if (pointer_gap_ok && (dollar_first_arg_num == 0
1051                                  || dollar_arguments_pointer_p[i]))
1052             found_pointer_gap = true;
1053           else
1054             warning ("format argument %d unused before used argument %d in $-style format",
1055                      i + 1, dollar_max_arg_used);
1056         }
1057     }
1058   if (found_pointer_gap
1059       || (dollar_first_arg_num
1060           && dollar_max_arg_used < dollar_arguments_count))
1061     {
1062       res->number_other--;
1063       res->number_dollar_extra_args++;
1064     }
1065 }
1066
1067
1068 /* Retrieve the specification for a format flag.  SPEC contains the
1069    specifications for format flags for the applicable kind of format.
1070    FLAG is the flag in question.  If PREDICATES is NULL, the basic
1071    spec for that flag must be retrieved and this function aborts if
1072    it cannot be found.  If PREDICATES is not NULL, it is a string listing
1073    possible predicates for the spec entry; if an entry predicated on any
1074    of these is found, it is returned, otherwise NULL is returned.  */
1075
1076 static const format_flag_spec *
1077 get_flag_spec (const format_flag_spec *spec, int flag, const char *predicates)
1078 {
1079   int i;
1080   for (i = 0; spec[i].flag_char != 0; i++)
1081     {
1082       if (spec[i].flag_char != flag)
1083         continue;
1084       if (predicates != NULL)
1085         {
1086           if (spec[i].predicate != 0
1087               && strchr (predicates, spec[i].predicate) != 0)
1088             return &spec[i];
1089         }
1090       else if (spec[i].predicate == 0)
1091         return &spec[i];
1092     }
1093   gcc_assert (predicates);
1094   return NULL;
1095 }
1096
1097
1098 /* Check the argument list of a call to printf, scanf, etc.
1099    INFO points to the function_format_info structure.
1100    PARAMS is the list of argument values.  */
1101
1102 static void
1103 check_format_info (function_format_info *info, tree params)
1104 {
1105   format_check_context format_ctx;
1106   unsigned HOST_WIDE_INT arg_num;
1107   tree format_tree;
1108   format_check_results res;
1109   /* Skip to format argument.  If the argument isn't available, there's
1110      no work for us to do; prototype checking will catch the problem.  */
1111   for (arg_num = 1; ; ++arg_num)
1112     {
1113       if (params == 0)
1114         return;
1115       if (arg_num == info->format_num)
1116         break;
1117       params = TREE_CHAIN (params);
1118     }
1119   format_tree = TREE_VALUE (params);
1120   params = TREE_CHAIN (params);
1121   if (format_tree == 0)
1122     return;
1123
1124   res.number_non_literal = 0;
1125   res.number_extra_args = 0;
1126   res.number_dollar_extra_args = 0;
1127   res.number_wide = 0;
1128   res.number_empty = 0;
1129   res.number_unterminated = 0;
1130   res.number_other = 0;
1131
1132   format_ctx.res = &res;
1133   format_ctx.info = info;
1134   format_ctx.params = params;
1135
1136   check_function_arguments_recurse (check_format_arg, &format_ctx,
1137                                     format_tree, arg_num);
1138
1139   if (res.number_non_literal > 0)
1140     {
1141       /* Functions taking a va_list normally pass a non-literal format
1142          string.  These functions typically are declared with
1143          first_arg_num == 0, so avoid warning in those cases.  */
1144       if (!(format_types[info->format_type].flags & (int) FMT_FLAG_ARG_CONVERT))
1145         {
1146           /* For strftime-like formats, warn for not checking the format
1147              string; but there are no arguments to check.  */
1148           if (warn_format_nonliteral)
1149             warning ("format not a string literal, format string not checked");
1150         }
1151       else if (info->first_arg_num != 0)
1152         {
1153           /* If there are no arguments for the format at all, we may have
1154              printf (foo) which is likely to be a security hole.  */
1155           while (arg_num + 1 < info->first_arg_num)
1156             {
1157               if (params == 0)
1158                 break;
1159               params = TREE_CHAIN (params);
1160               ++arg_num;
1161             }
1162           if (params == 0 && (warn_format_nonliteral || warn_format_security))
1163             warning ("format not a string literal and no format arguments");
1164           else if (warn_format_nonliteral)
1165             warning ("format not a string literal, argument types not checked");
1166         }
1167     }
1168
1169   /* If there were extra arguments to the format, normally warn.  However,
1170      the standard does say extra arguments are ignored, so in the specific
1171      case where we have multiple leaves (conditional expressions or
1172      ngettext) allow extra arguments if at least one leaf didn't have extra
1173      arguments, but was otherwise OK (either non-literal or checked OK).
1174      If the format is an empty string, this should be counted similarly to the
1175      case of extra format arguments.  */
1176   if (res.number_extra_args > 0 && res.number_non_literal == 0
1177       && res.number_other == 0 && warn_format_extra_args)
1178     warning ("too many arguments for format");
1179   if (res.number_dollar_extra_args > 0 && res.number_non_literal == 0
1180       && res.number_other == 0 && warn_format_extra_args)
1181     warning ("unused arguments in $-style format");
1182   if (res.number_empty > 0 && res.number_non_literal == 0
1183       && res.number_other == 0 && warn_format_zero_length)
1184     warning ("zero-length %s format string",
1185              format_types[info->format_type].name);
1186
1187   if (res.number_wide > 0)
1188     warning ("format is a wide character string");
1189
1190   if (res.number_unterminated > 0)
1191     warning ("unterminated format string");
1192 }
1193
1194 /* Callback from check_function_arguments_recurse to check a
1195    format string.  FORMAT_TREE is the format parameter.  ARG_NUM
1196    is the number of the format argument.  CTX points to a
1197    format_check_context.  */
1198
1199 static void
1200 check_format_arg (void *ctx, tree format_tree,
1201                   unsigned HOST_WIDE_INT arg_num)
1202 {
1203   format_check_context *format_ctx = (format_check_context *) ctx;
1204   format_check_results *res = format_ctx->res;
1205   function_format_info *info = format_ctx->info;
1206   tree params = format_ctx->params;
1207
1208   int format_length;
1209   HOST_WIDE_INT offset;
1210   const char *format_chars;
1211   tree array_size = 0;
1212   tree array_init;
1213
1214   if (integer_zerop (format_tree))
1215     {
1216       /* Skip to first argument to check, so we can see if this format
1217          has any arguments (it shouldn't).  */
1218       while (arg_num + 1 < info->first_arg_num)
1219         {
1220           if (params == 0)
1221             return;
1222           params = TREE_CHAIN (params);
1223           ++arg_num;
1224         }
1225
1226       if (params == 0)
1227         res->number_other++;
1228       else
1229         res->number_extra_args++;
1230
1231       return;
1232     }
1233
1234   offset = 0;
1235   if (TREE_CODE (format_tree) == PLUS_EXPR)
1236     {
1237       tree arg0, arg1;
1238
1239       arg0 = TREE_OPERAND (format_tree, 0);
1240       arg1 = TREE_OPERAND (format_tree, 1);
1241       STRIP_NOPS (arg0);
1242       STRIP_NOPS (arg1);
1243       if (TREE_CODE (arg1) == INTEGER_CST)
1244         format_tree = arg0;
1245       else if (TREE_CODE (arg0) == INTEGER_CST)
1246         {
1247           format_tree = arg1;
1248           arg1 = arg0;
1249         }
1250       else
1251         {
1252           res->number_non_literal++;
1253           return;
1254         }
1255       if (!host_integerp (arg1, 0)
1256           || (offset = tree_low_cst (arg1, 0)) < 0)
1257         {
1258           res->number_non_literal++;
1259           return;
1260         }
1261     }
1262   if (TREE_CODE (format_tree) != ADDR_EXPR)
1263     {
1264       res->number_non_literal++;
1265       return;
1266     }
1267   format_tree = TREE_OPERAND (format_tree, 0);
1268   if (TREE_CODE (format_tree) == VAR_DECL
1269       && TREE_CODE (TREE_TYPE (format_tree)) == ARRAY_TYPE
1270       && (array_init = decl_constant_value (format_tree)) != format_tree
1271       && TREE_CODE (array_init) == STRING_CST)
1272     {
1273       /* Extract the string constant initializer.  Note that this may include
1274          a trailing NUL character that is not in the array (e.g.
1275          const char a[3] = "foo";).  */
1276       array_size = DECL_SIZE_UNIT (format_tree);
1277       format_tree = array_init;
1278     }
1279   if (TREE_CODE (format_tree) != STRING_CST)
1280     {
1281       res->number_non_literal++;
1282       return;
1283     }
1284   if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format_tree))) != char_type_node)
1285     {
1286       res->number_wide++;
1287       return;
1288     }
1289   format_chars = TREE_STRING_POINTER (format_tree);
1290   format_length = TREE_STRING_LENGTH (format_tree);
1291   if (array_size != 0)
1292     {
1293       /* Variable length arrays can't be initialized.  */
1294       gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
1295       
1296       if (host_integerp (array_size, 0))
1297         {
1298           HOST_WIDE_INT array_size_value = TREE_INT_CST_LOW (array_size);
1299           if (array_size_value > 0
1300               && array_size_value == (int) array_size_value
1301               && format_length > array_size_value)
1302             format_length = array_size_value;
1303         }
1304     }
1305   if (offset)
1306     {
1307       if (offset >= format_length)
1308         {
1309           res->number_non_literal++;
1310           return;
1311         }
1312       format_chars += offset;
1313       format_length -= offset;
1314     }
1315   if (format_length < 1)
1316     {
1317       res->number_unterminated++;
1318       return;
1319     }
1320   if (format_length == 1)
1321     {
1322       res->number_empty++;
1323       return;
1324     }
1325   if (format_chars[--format_length] != 0)
1326     {
1327       res->number_unterminated++;
1328       return;
1329     }
1330
1331   /* Skip to first argument to check.  */
1332   while (arg_num + 1 < info->first_arg_num)
1333     {
1334       if (params == 0)
1335         return;
1336       params = TREE_CHAIN (params);
1337       ++arg_num;
1338     }
1339   /* Provisionally increment res->number_other; check_format_info_main
1340      will decrement it if it finds there are extra arguments, but this way
1341      need not adjust it for every return.  */
1342   res->number_other++;
1343   check_format_info_main (res, info, format_chars, format_length,
1344                           params, arg_num);
1345 }
1346
1347
1348 /* Do the main part of checking a call to a format function.  FORMAT_CHARS
1349    is the NUL-terminated format string (which at this point may contain
1350    internal NUL characters); FORMAT_LENGTH is its length (excluding the
1351    terminating NUL character).  ARG_NUM is one less than the number of
1352    the first format argument to check; PARAMS points to that format
1353    argument in the list of arguments.  */
1354
1355 static void
1356 check_format_info_main (format_check_results *res,
1357                         function_format_info *info, const char *format_chars,
1358                         int format_length, tree params,
1359                         unsigned HOST_WIDE_INT arg_num)
1360 {
1361   const char *orig_format_chars = format_chars;
1362   tree first_fillin_param = params;
1363
1364   const format_kind_info *fki = &format_types[info->format_type];
1365   const format_flag_spec *flag_specs = fki->flag_specs;
1366   const format_flag_pair *bad_flag_pairs = fki->bad_flag_pairs;
1367
1368   /* -1 if no conversions taking an operand have been found; 0 if one has
1369      and it didn't use $; 1 if $ formats are in use.  */
1370   int has_operand_number = -1;
1371
1372   init_dollar_format_checking (info->first_arg_num, first_fillin_param);
1373
1374   while (1)
1375     {
1376       int i;
1377       int suppressed = FALSE;
1378       const char *length_chars = NULL;
1379       enum format_lengths length_chars_val = FMT_LEN_none;
1380       enum format_std_version length_chars_std = STD_C89;
1381       int format_char;
1382       tree cur_param;
1383       tree wanted_type;
1384       int main_arg_num = 0;
1385       tree main_arg_params = 0;
1386       enum format_std_version wanted_type_std;
1387       const char *wanted_type_name;
1388       format_wanted_type width_wanted_type;
1389       format_wanted_type precision_wanted_type;
1390       format_wanted_type main_wanted_type;
1391       format_wanted_type *first_wanted_type = NULL;
1392       format_wanted_type *last_wanted_type = NULL;
1393       const format_length_info *fli = NULL;
1394       const format_char_info *fci = NULL;
1395       char flag_chars[256];
1396       int aflag = 0;
1397       const char *format_start = format_chars;
1398       if (*format_chars == 0)
1399         {
1400           if (format_chars - orig_format_chars != format_length)
1401             warning ("embedded %<\\0%> in format");
1402           if (info->first_arg_num != 0 && params != 0
1403               && has_operand_number <= 0)
1404             {
1405               res->number_other--;
1406               res->number_extra_args++;
1407             }
1408           if (has_operand_number > 0)
1409             finish_dollar_format_checking (res, fki->flags & (int) FMT_FLAG_DOLLAR_GAP_POINTER_OK);
1410           return;
1411         }
1412       if (*format_chars++ != '%')
1413         continue;
1414       if (*format_chars == 0)
1415         {
1416           warning ("spurious trailing %<%%%> in format");
1417           continue;
1418         }
1419       if (*format_chars == '%')
1420         {
1421           ++format_chars;
1422           continue;
1423         }
1424       flag_chars[0] = 0;
1425
1426       if ((fki->flags & (int) FMT_FLAG_USE_DOLLAR) && has_operand_number != 0)
1427         {
1428           /* Possibly read a $ operand number at the start of the format.
1429              If one was previously used, one is required here.  If one
1430              is not used here, we can't immediately conclude this is a
1431              format without them, since it could be printf %m or scanf %*.  */
1432           int opnum;
1433           opnum = maybe_read_dollar_number (&format_chars, 0,
1434                                             first_fillin_param,
1435                                             &main_arg_params, fki);
1436           if (opnum == -1)
1437             return;
1438           else if (opnum > 0)
1439             {
1440               has_operand_number = 1;
1441               main_arg_num = opnum + info->first_arg_num - 1;
1442             }
1443         }
1444       else if (fki->flags & FMT_FLAG_USE_DOLLAR)
1445         {
1446           if (avoid_dollar_number (format_chars))
1447             return;
1448         }
1449
1450       /* Read any format flags, but do not yet validate them beyond removing
1451          duplicates, since in general validation depends on the rest of
1452          the format.  */
1453       while (*format_chars != 0
1454              && strchr (fki->flag_chars, *format_chars) != 0)
1455         {
1456           const format_flag_spec *s = get_flag_spec (flag_specs,
1457                                                      *format_chars, NULL);
1458           if (strchr (flag_chars, *format_chars) != 0)
1459             {
1460               warning ("repeated %s in format", _(s->name));
1461             }
1462           else
1463             {
1464               i = strlen (flag_chars);
1465               flag_chars[i++] = *format_chars;
1466               flag_chars[i] = 0;
1467             }
1468           if (s->skip_next_char)
1469             {
1470               ++format_chars;
1471               if (*format_chars == 0)
1472                 {
1473                   warning ("missing fill character at end of strfmon format");
1474                   return;
1475                 }
1476             }
1477           ++format_chars;
1478         }
1479
1480       /* Read any format width, possibly * or *m$.  */
1481       if (fki->width_char != 0)
1482         {
1483           if (fki->width_type != NULL && *format_chars == '*')
1484             {
1485               i = strlen (flag_chars);
1486               flag_chars[i++] = fki->width_char;
1487               flag_chars[i] = 0;
1488               /* "...a field width...may be indicated by an asterisk.
1489                  In this case, an int argument supplies the field width..."  */
1490               ++format_chars;
1491               if (has_operand_number != 0)
1492                 {
1493                   int opnum;
1494                   opnum = maybe_read_dollar_number (&format_chars,
1495                                                     has_operand_number == 1,
1496                                                     first_fillin_param,
1497                                                     &params, fki);
1498                   if (opnum == -1)
1499                     return;
1500                   else if (opnum > 0)
1501                     {
1502                       has_operand_number = 1;
1503                       arg_num = opnum + info->first_arg_num - 1;
1504                     }
1505                   else
1506                     has_operand_number = 0;
1507                 }
1508               else
1509                 {
1510                   if (avoid_dollar_number (format_chars))
1511                     return;
1512                 }
1513               if (info->first_arg_num != 0)
1514                 {
1515                   if (params == 0)
1516                     {
1517                       warning ("too few arguments for format");
1518                       return;
1519                     }
1520                   cur_param = TREE_VALUE (params);
1521                   if (has_operand_number <= 0)
1522                     {
1523                       params = TREE_CHAIN (params);
1524                       ++arg_num;
1525                     }
1526                   width_wanted_type.wanted_type = *fki->width_type;
1527                   width_wanted_type.wanted_type_name = NULL;
1528                   width_wanted_type.pointer_count = 0;
1529                   width_wanted_type.char_lenient_flag = 0;
1530                   width_wanted_type.writing_in_flag = 0;
1531                   width_wanted_type.reading_from_flag = 0;
1532                   width_wanted_type.name = _("field width");
1533                   width_wanted_type.param = cur_param;
1534                   width_wanted_type.arg_num = arg_num;
1535                   width_wanted_type.next = NULL;
1536                   if (last_wanted_type != 0)
1537                     last_wanted_type->next = &width_wanted_type;
1538                   if (first_wanted_type == 0)
1539                     first_wanted_type = &width_wanted_type;
1540                   last_wanted_type = &width_wanted_type;
1541                 }
1542             }
1543           else
1544             {
1545               /* Possibly read a numeric width.  If the width is zero,
1546                  we complain if appropriate.  */
1547               int non_zero_width_char = FALSE;
1548               int found_width = FALSE;
1549               while (ISDIGIT (*format_chars))
1550                 {
1551                   found_width = TRUE;
1552                   if (*format_chars != '0')
1553                     non_zero_width_char = TRUE;
1554                   ++format_chars;
1555                 }
1556               if (found_width && !non_zero_width_char &&
1557                   (fki->flags & (int) FMT_FLAG_ZERO_WIDTH_BAD))
1558                 warning ("zero width in %s format", fki->name);
1559               if (found_width)
1560                 {
1561                   i = strlen (flag_chars);
1562                   flag_chars[i++] = fki->width_char;
1563                   flag_chars[i] = 0;
1564                 }
1565             }
1566         }
1567
1568       /* Read any format left precision (must be a number, not *).  */
1569       if (fki->left_precision_char != 0 && *format_chars == '#')
1570         {
1571           ++format_chars;
1572           i = strlen (flag_chars);
1573           flag_chars[i++] = fki->left_precision_char;
1574           flag_chars[i] = 0;
1575           if (!ISDIGIT (*format_chars))
1576             warning ("empty left precision in %s format", fki->name);
1577           while (ISDIGIT (*format_chars))
1578             ++format_chars;
1579         }
1580
1581       /* Read any format precision, possibly * or *m$.  */
1582       if (fki->precision_char != 0 && *format_chars == '.')
1583         {
1584           ++format_chars;
1585           i = strlen (flag_chars);
1586           flag_chars[i++] = fki->precision_char;
1587           flag_chars[i] = 0;
1588           if (fki->precision_type != NULL && *format_chars == '*')
1589             {
1590               /* "...a...precision...may be indicated by an asterisk.
1591                  In this case, an int argument supplies the...precision."  */
1592               ++format_chars;
1593               if (has_operand_number != 0)
1594                 {
1595                   int opnum;
1596                   opnum = maybe_read_dollar_number (&format_chars,
1597                                                     has_operand_number == 1,
1598                                                     first_fillin_param,
1599                                                     &params, fki);
1600                   if (opnum == -1)
1601                     return;
1602                   else if (opnum > 0)
1603                     {
1604                       has_operand_number = 1;
1605                       arg_num = opnum + info->first_arg_num - 1;
1606                     }
1607                   else
1608                     has_operand_number = 0;
1609                 }
1610               else
1611                 {
1612                   if (avoid_dollar_number (format_chars))
1613                     return;
1614                 }
1615               if (info->first_arg_num != 0)
1616                 {
1617                   if (params == 0)
1618                     {
1619                       warning ("too few arguments for format");
1620                       return;
1621                     }
1622                   cur_param = TREE_VALUE (params);
1623                   if (has_operand_number <= 0)
1624                     {
1625                       params = TREE_CHAIN (params);
1626                       ++arg_num;
1627                     }
1628                   precision_wanted_type.wanted_type = *fki->precision_type;
1629                   precision_wanted_type.wanted_type_name = NULL;
1630                   precision_wanted_type.pointer_count = 0;
1631                   precision_wanted_type.char_lenient_flag = 0;
1632                   precision_wanted_type.writing_in_flag = 0;
1633                   precision_wanted_type.reading_from_flag = 0;
1634                   precision_wanted_type.name = _("field precision");
1635                   precision_wanted_type.param = cur_param;
1636                   precision_wanted_type.arg_num = arg_num;
1637                   precision_wanted_type.next = NULL;
1638                   if (last_wanted_type != 0)
1639                     last_wanted_type->next = &precision_wanted_type;
1640                   if (first_wanted_type == 0)
1641                     first_wanted_type = &precision_wanted_type;
1642                   last_wanted_type = &precision_wanted_type;
1643                 }
1644             }
1645           else
1646             {
1647               if (!(fki->flags & (int) FMT_FLAG_EMPTY_PREC_OK)
1648                   && !ISDIGIT (*format_chars))
1649                 warning ("empty precision in %s format", fki->name);
1650               while (ISDIGIT (*format_chars))
1651                 ++format_chars;
1652             }
1653         }
1654
1655       /* Read any length modifier, if this kind of format has them.  */
1656       fli = fki->length_char_specs;
1657       length_chars = NULL;
1658       length_chars_val = FMT_LEN_none;
1659       length_chars_std = STD_C89;
1660       if (fli)
1661         {
1662           while (fli->name != 0 && fli->name[0] != *format_chars)
1663             fli++;
1664           if (fli->name != 0)
1665             {
1666               format_chars++;
1667               if (fli->double_name != 0 && fli->name[0] == *format_chars)
1668                 {
1669                   format_chars++;
1670                   length_chars = fli->double_name;
1671                   length_chars_val = fli->double_index;
1672                   length_chars_std = fli->double_std;
1673                 }
1674               else
1675                 {
1676                   length_chars = fli->name;
1677                   length_chars_val = fli->index;
1678                   length_chars_std = fli->std;
1679                 }
1680               i = strlen (flag_chars);
1681               flag_chars[i++] = fki->length_code_char;
1682               flag_chars[i] = 0;
1683             }
1684           if (pedantic)
1685             {
1686               /* Warn if the length modifier is non-standard.  */
1687               if (ADJ_STD (length_chars_std) > C_STD_VER)
1688                 warning ("%s does not support the %qs %s length modifier",
1689                          C_STD_NAME (length_chars_std), length_chars,
1690                          fki->name);
1691             }
1692         }
1693
1694       /* Read any modifier (strftime E/O).  */
1695       if (fki->modifier_chars != NULL)
1696         {
1697           while (*format_chars != 0
1698                  && strchr (fki->modifier_chars, *format_chars) != 0)
1699             {
1700               if (strchr (flag_chars, *format_chars) != 0)
1701                 {
1702                   const format_flag_spec *s = get_flag_spec (flag_specs,
1703                                                              *format_chars, NULL);
1704                   warning ("repeated %s in format", _(s->name));
1705                 }
1706               else
1707                 {
1708                   i = strlen (flag_chars);
1709                   flag_chars[i++] = *format_chars;
1710                   flag_chars[i] = 0;
1711                 }
1712               ++format_chars;
1713             }
1714         }
1715
1716       /* Handle the scanf allocation kludge.  */
1717       if (fki->flags & (int) FMT_FLAG_SCANF_A_KLUDGE)
1718         {
1719           if (*format_chars == 'a' && !flag_isoc99)
1720             {
1721               if (format_chars[1] == 's' || format_chars[1] == 'S'
1722                   || format_chars[1] == '[')
1723                 {
1724                   /* 'a' is used as a flag.  */
1725                   i = strlen (flag_chars);
1726                   flag_chars[i++] = 'a';
1727                   flag_chars[i] = 0;
1728                   format_chars++;
1729                 }
1730             }
1731         }
1732
1733       format_char = *format_chars;
1734       if (format_char == 0
1735           || (!(fki->flags & (int) FMT_FLAG_FANCY_PERCENT_OK)
1736               && format_char == '%'))
1737         {
1738           warning ("conversion lacks type at end of format");
1739           continue;
1740         }
1741       format_chars++;
1742       fci = fki->conversion_specs;
1743       while (fci->format_chars != 0
1744              && strchr (fci->format_chars, format_char) == 0)
1745           ++fci;
1746       if (fci->format_chars == 0)
1747         {
1748           if (ISGRAPH (format_char))
1749             warning ("unknown conversion type character %qc in format",
1750                      format_char);
1751           else
1752             warning ("unknown conversion type character 0x%x in format",
1753                      format_char);
1754           continue;
1755         }
1756       if (pedantic)
1757         {
1758           if (ADJ_STD (fci->std) > C_STD_VER)
1759             warning ("%s does not support the %<%%%c%> %s format",
1760                      C_STD_NAME (fci->std), format_char, fki->name);
1761         }
1762
1763       /* Validate the individual flags used, removing any that are invalid.  */
1764       {
1765         int d = 0;
1766         for (i = 0; flag_chars[i] != 0; i++)
1767           {
1768             const format_flag_spec *s = get_flag_spec (flag_specs,
1769                                                        flag_chars[i], NULL);
1770             flag_chars[i - d] = flag_chars[i];
1771             if (flag_chars[i] == fki->length_code_char)
1772               continue;
1773             if (strchr (fci->flag_chars, flag_chars[i]) == 0)
1774               {
1775                 warning ("%s used with %<%%%c%> %s format",
1776                          _(s->name), format_char, fki->name);
1777                 d++;
1778                 continue;
1779               }
1780             if (pedantic)
1781               {
1782                 const format_flag_spec *t;
1783                 if (ADJ_STD (s->std) > C_STD_VER)
1784                   warning ("%s does not support %s",
1785                            C_STD_NAME (s->std), _(s->long_name));
1786                 t = get_flag_spec (flag_specs, flag_chars[i], fci->flags2);
1787                 if (t != NULL && ADJ_STD (t->std) > ADJ_STD (s->std))
1788                   {
1789                     const char *long_name = (t->long_name != NULL
1790                                              ? t->long_name
1791                                              : s->long_name);
1792                     if (ADJ_STD (t->std) > C_STD_VER)
1793                       warning ("%s does not support %s with the %<%%%c%> %s format",
1794                                C_STD_NAME (t->std), _(long_name),
1795                                format_char, fki->name);
1796                   }
1797               }
1798           }
1799         flag_chars[i - d] = 0;
1800       }
1801
1802       if ((fki->flags & (int) FMT_FLAG_SCANF_A_KLUDGE)
1803           && strchr (flag_chars, 'a') != 0)
1804         aflag = 1;
1805
1806       if (fki->suppression_char
1807           && strchr (flag_chars, fki->suppression_char) != 0)
1808         suppressed = 1;
1809
1810       /* Validate the pairs of flags used.  */
1811       for (i = 0; bad_flag_pairs[i].flag_char1 != 0; i++)
1812         {
1813           const format_flag_spec *s, *t;
1814           if (strchr (flag_chars, bad_flag_pairs[i].flag_char1) == 0)
1815             continue;
1816           if (strchr (flag_chars, bad_flag_pairs[i].flag_char2) == 0)
1817             continue;
1818           if (bad_flag_pairs[i].predicate != 0
1819               && strchr (fci->flags2, bad_flag_pairs[i].predicate) == 0)
1820             continue;
1821           s = get_flag_spec (flag_specs, bad_flag_pairs[i].flag_char1, NULL);
1822           t = get_flag_spec (flag_specs, bad_flag_pairs[i].flag_char2, NULL);
1823           if (bad_flag_pairs[i].ignored)
1824             {
1825               if (bad_flag_pairs[i].predicate != 0)
1826                 warning ("%s ignored with %s and %<%%%c%> %s format",
1827                          _(s->name), _(t->name), format_char,
1828                          fki->name);
1829               else
1830                 warning ("%s ignored with %s in %s format",
1831                          _(s->name), _(t->name), fki->name);
1832             }
1833           else
1834             {
1835               if (bad_flag_pairs[i].predicate != 0)
1836                 warning ("use of %s and %s together with %<%%%c%> %s format",
1837                          _(s->name), _(t->name), format_char,
1838                          fki->name);
1839               else
1840                 warning ("use of %s and %s together in %s format",
1841                          _(s->name), _(t->name), fki->name);
1842             }
1843         }
1844
1845       /* Give Y2K warnings.  */
1846       if (warn_format_y2k)
1847         {
1848           int y2k_level = 0;
1849           if (strchr (fci->flags2, '4') != 0)
1850             if (strchr (flag_chars, 'E') != 0)
1851               y2k_level = 3;
1852             else
1853               y2k_level = 2;
1854           else if (strchr (fci->flags2, '3') != 0)
1855             y2k_level = 3;
1856           else if (strchr (fci->flags2, '2') != 0)
1857             y2k_level = 2;
1858           if (y2k_level == 3)
1859             warning ("%<%%%c%> yields only last 2 digits of year in some locales",
1860                      format_char);
1861           else if (y2k_level == 2)
1862             warning ("%<%%%c%> yields only last 2 digits of year", format_char);
1863         }
1864
1865       if (strchr (fci->flags2, '[') != 0)
1866         {
1867           /* Skip over scan set, in case it happens to have '%' in it.  */
1868           if (*format_chars == '^')
1869             ++format_chars;
1870           /* Find closing bracket; if one is hit immediately, then
1871              it's part of the scan set rather than a terminator.  */
1872           if (*format_chars == ']')
1873             ++format_chars;
1874           while (*format_chars && *format_chars != ']')
1875             ++format_chars;
1876           if (*format_chars != ']')
1877             /* The end of the format string was reached.  */
1878             warning ("no closing %<]%> for %<%%[%> format");
1879         }
1880
1881       wanted_type = 0;
1882       wanted_type_name = 0;
1883       if (fki->flags & (int) FMT_FLAG_ARG_CONVERT)
1884         {
1885           wanted_type = (fci->types[length_chars_val].type
1886                          ? *fci->types[length_chars_val].type : 0);
1887           wanted_type_name = fci->types[length_chars_val].name;
1888           wanted_type_std = fci->types[length_chars_val].std;
1889           if (wanted_type == 0)
1890             {
1891               warning ("use of %qs length modifier with %qc type character",
1892                        length_chars, format_char);
1893               /* Heuristic: skip one argument when an invalid length/type
1894                  combination is encountered.  */
1895               arg_num++;
1896               if (params == 0)
1897                 {
1898                   warning ("too few arguments for format");
1899                   return;
1900                 }
1901               params = TREE_CHAIN (params);
1902               continue;
1903             }
1904           else if (pedantic
1905                    /* Warn if non-standard, provided it is more non-standard
1906                       than the length and type characters that may already
1907                       have been warned for.  */
1908                    && ADJ_STD (wanted_type_std) > ADJ_STD (length_chars_std)
1909                    && ADJ_STD (wanted_type_std) > ADJ_STD (fci->std))
1910             {
1911               if (ADJ_STD (wanted_type_std) > C_STD_VER)
1912                 warning ("%s does not support the %<%%%s%c%> %s format",
1913                          C_STD_NAME (wanted_type_std), length_chars,
1914                          format_char, fki->name);
1915             }
1916         }
1917
1918       main_wanted_type.next = NULL;
1919
1920       /* Finally. . .check type of argument against desired type!  */
1921       if (info->first_arg_num == 0)
1922         continue;
1923       if ((fci->pointer_count == 0 && wanted_type == void_type_node)
1924           || suppressed)
1925         {
1926           if (main_arg_num != 0)
1927             {
1928               if (suppressed)
1929                 warning ("operand number specified with suppressed assignment");
1930               else
1931                 warning ("operand number specified for format taking no argument");
1932             }
1933         }
1934       else
1935         {
1936           format_wanted_type *wanted_type_ptr;
1937
1938           if (main_arg_num != 0)
1939             {
1940               arg_num = main_arg_num;
1941               params = main_arg_params;
1942             }
1943           else
1944             {
1945               ++arg_num;
1946               if (has_operand_number > 0)
1947                 {
1948                   warning ("missing $ operand number in format");
1949                   return;
1950                 }
1951               else
1952                 has_operand_number = 0;
1953             }
1954
1955           wanted_type_ptr = &main_wanted_type;
1956           while (fci)
1957             {
1958               if (params == 0)
1959                 {
1960                   warning ("too few arguments for format");
1961                   return;
1962                 }
1963
1964               cur_param = TREE_VALUE (params);
1965               params = TREE_CHAIN (params);
1966
1967               wanted_type_ptr->wanted_type = wanted_type;
1968               wanted_type_ptr->wanted_type_name = wanted_type_name;
1969               wanted_type_ptr->pointer_count = fci->pointer_count + aflag;
1970               wanted_type_ptr->char_lenient_flag = 0;
1971               if (strchr (fci->flags2, 'c') != 0)
1972                 wanted_type_ptr->char_lenient_flag = 1;
1973               wanted_type_ptr->writing_in_flag = 0;
1974               wanted_type_ptr->reading_from_flag = 0;
1975               if (aflag)
1976                 wanted_type_ptr->writing_in_flag = 1;
1977               else
1978                 {
1979                   if (strchr (fci->flags2, 'W') != 0)
1980                     wanted_type_ptr->writing_in_flag = 1;
1981                   if (strchr (fci->flags2, 'R') != 0)
1982                     wanted_type_ptr->reading_from_flag = 1;
1983                 }
1984               wanted_type_ptr->name = NULL;
1985               wanted_type_ptr->param = cur_param;
1986               wanted_type_ptr->arg_num = arg_num;
1987               wanted_type_ptr->next = NULL;
1988               if (last_wanted_type != 0)
1989                 last_wanted_type->next = wanted_type_ptr;
1990               if (first_wanted_type == 0)
1991                 first_wanted_type = wanted_type_ptr;
1992               last_wanted_type = wanted_type_ptr;
1993
1994               fci = fci->chain;
1995               if (fci)
1996                 {
1997                   wanted_type_ptr = ggc_alloc (sizeof (main_wanted_type));
1998                   arg_num++;
1999                   wanted_type = *fci->types[length_chars_val].type;
2000                   wanted_type_name = fci->types[length_chars_val].name;
2001                 }
2002             }
2003         }
2004
2005       if (first_wanted_type != 0)
2006         check_format_types (first_wanted_type, format_start,
2007                             format_chars - format_start);
2008
2009       if (main_wanted_type.next != NULL)
2010         {
2011           format_wanted_type *wanted_type_ptr = main_wanted_type.next;
2012           while (wanted_type_ptr)
2013             {
2014               format_wanted_type *next = wanted_type_ptr->next;
2015               ggc_free (wanted_type_ptr);
2016               wanted_type_ptr = next;
2017             }
2018         }
2019     }
2020 }
2021
2022
2023 /* Check the argument types from a single format conversion (possibly
2024    including width and precision arguments).  */
2025 static void
2026 check_format_types (format_wanted_type *types, const char *format_start,
2027                     int format_length)
2028 {
2029   for (; types != 0; types = types->next)
2030     {
2031       tree cur_param;
2032       tree cur_type;
2033       tree orig_cur_type;
2034       tree wanted_type;
2035       int arg_num;
2036       int i;
2037       int char_type_flag;
2038       cur_param = types->param;
2039       cur_type = TREE_TYPE (cur_param);
2040       if (cur_type == error_mark_node)
2041         continue;
2042       orig_cur_type = cur_type;
2043       char_type_flag = 0;
2044       wanted_type = types->wanted_type;
2045       arg_num = types->arg_num;
2046
2047       /* The following should not occur here.  */
2048       gcc_assert (wanted_type);
2049       gcc_assert (wanted_type != void_type_node || types->pointer_count);
2050
2051       if (types->pointer_count == 0)
2052         wanted_type = lang_hooks.types.type_promotes_to (wanted_type);
2053
2054       wanted_type = TYPE_MAIN_VARIANT (wanted_type);
2055
2056       STRIP_NOPS (cur_param);
2057
2058       /* Check the types of any additional pointer arguments
2059          that precede the "real" argument.  */
2060       for (i = 0; i < types->pointer_count; ++i)
2061         {
2062           if (TREE_CODE (cur_type) == POINTER_TYPE)
2063             {
2064               cur_type = TREE_TYPE (cur_type);
2065               if (cur_type == error_mark_node)
2066                 break;
2067
2068               /* Check for writing through a NULL pointer.  */
2069               if (types->writing_in_flag
2070                   && i == 0
2071                   && cur_param != 0
2072                   && integer_zerop (cur_param))
2073                 warning ("writing through null pointer (argument %d)",
2074                          arg_num);
2075
2076               /* Check for reading through a NULL pointer.  */
2077               if (types->reading_from_flag
2078                   && i == 0
2079                   && cur_param != 0
2080                   && integer_zerop (cur_param))
2081                 warning ("reading through null pointer (argument %d)",
2082                          arg_num);
2083
2084               if (cur_param != 0 && TREE_CODE (cur_param) == ADDR_EXPR)
2085                 cur_param = TREE_OPERAND (cur_param, 0);
2086               else
2087                 cur_param = 0;
2088
2089               /* See if this is an attempt to write into a const type with
2090                  scanf or with printf "%n".  Note: the writing in happens
2091                  at the first indirection only, if for example
2092                  void * const * is passed to scanf %p; passing
2093                  const void ** is simply passing an incompatible type.  */
2094               if (types->writing_in_flag
2095                   && i == 0
2096                   && (TYPE_READONLY (cur_type)
2097                       || (cur_param != 0
2098                           && (CONSTANT_CLASS_P (cur_param)
2099                               || (DECL_P (cur_param)
2100                                   && TREE_READONLY (cur_param))))))
2101                 warning ("writing into constant object (argument %d)",
2102                          arg_num);
2103
2104               /* If there are extra type qualifiers beyond the first
2105                  indirection, then this makes the types technically
2106                  incompatible.  */
2107               if (i > 0
2108                   && pedantic
2109                   && (TYPE_READONLY (cur_type)
2110                       || TYPE_VOLATILE (cur_type)
2111                       || TYPE_RESTRICT (cur_type)))
2112                 warning ("extra type qualifiers in format argument "
2113                          "(argument %d)",
2114                          arg_num);
2115
2116             }
2117           else
2118             {
2119               format_type_warning (types->name, format_start, format_length,
2120                                    wanted_type, types->pointer_count,
2121                                    types->wanted_type_name, orig_cur_type,
2122                                    arg_num);
2123               break;
2124             }
2125         }
2126
2127       if (i < types->pointer_count)
2128         continue;
2129
2130       cur_type = TYPE_MAIN_VARIANT (cur_type);
2131
2132       /* Check whether the argument type is a character type.  This leniency
2133          only applies to certain formats, flagged with 'c'.
2134       */
2135       if (types->char_lenient_flag)
2136         char_type_flag = (cur_type == char_type_node
2137                           || cur_type == signed_char_type_node
2138                           || cur_type == unsigned_char_type_node);
2139
2140       /* Check the type of the "real" argument, if there's a type we want.  */
2141       if (wanted_type == cur_type)
2142         continue;
2143       /* If we want 'void *', allow any pointer type.
2144          (Anything else would already have got a warning.)
2145          With -pedantic, only allow pointers to void and to character
2146          types.  */
2147       if (wanted_type == void_type_node
2148           && (!pedantic || (i == 1 && char_type_flag)))
2149         continue;
2150       /* Don't warn about differences merely in signedness, unless
2151          -pedantic.  With -pedantic, warn if the type is a pointer
2152          target and not a character type, and for character types at
2153          a second level of indirection.  */
2154       if (TREE_CODE (wanted_type) == INTEGER_TYPE
2155           && TREE_CODE (cur_type) == INTEGER_TYPE
2156           && (!pedantic || i == 0 || (i == 1 && char_type_flag))
2157           && (TYPE_UNSIGNED (wanted_type)
2158               ? wanted_type == c_common_unsigned_type (cur_type)
2159               : wanted_type == c_common_signed_type (cur_type)))
2160         continue;
2161       /* Likewise, "signed char", "unsigned char" and "char" are
2162          equivalent but the above test won't consider them equivalent.  */
2163       if (wanted_type == char_type_node
2164           && (!pedantic || i < 2)
2165           && char_type_flag)
2166         continue;
2167       /* Now we have a type mismatch.  */
2168       format_type_warning (types->name, format_start, format_length,
2169                            wanted_type, types->pointer_count,
2170                            types->wanted_type_name, orig_cur_type, arg_num);
2171     }
2172 }
2173
2174
2175 /* Give a warning about a format argument of different type from that
2176    expected.  DESCR is a description such as "field precision", or
2177    NULL for an ordinary format.  For an ordinary format, FORMAT_START
2178    points to where the format starts in the format string and
2179    FORMAT_LENGTH is its length.  WANTED_TYPE is the type the argument
2180    should have after POINTER_COUNT pointer dereferences.
2181    WANTED_NAME_NAME is a possibly more friendly name of WANTED_TYPE,
2182    or NULL if the ordinary name of the type should be used.  ARG_TYPE
2183    is the type of the actual argument.  ARG_NUM is the number of that
2184    argument.  */
2185 static void
2186 format_type_warning (const char *descr, const char *format_start,
2187                      int format_length, tree wanted_type, int pointer_count,
2188                      const char *wanted_type_name, tree arg_type, int arg_num)
2189 {
2190   char *p;
2191   /* If ARG_TYPE is a typedef with a misleading name (for example,
2192      size_t but not the standard size_t expected by printf %zu), avoid
2193      printing the typedef name.  */
2194   if (wanted_type_name
2195       && TYPE_NAME (arg_type)
2196       && TREE_CODE (TYPE_NAME (arg_type)) == TYPE_DECL
2197       && DECL_NAME (TYPE_NAME (arg_type))
2198       && !strcmp (wanted_type_name,
2199                   lang_hooks.decl_printable_name (TYPE_NAME (arg_type), 2)))
2200     arg_type = TYPE_MAIN_VARIANT (arg_type);
2201   /* The format type and name exclude any '*' for pointers, so those
2202      must be formatted manually.  For all the types we currently have,
2203      this is adequate, but formats taking pointers to functions or
2204      arrays would require the full type to be built up in order to
2205      print it with %T.  */
2206   p = alloca (pointer_count + 2);
2207   if (pointer_count == 0)
2208     p[0] = 0;
2209   else if (c_dialect_cxx ())
2210     {
2211       memset (p, '*', pointer_count);
2212       p[pointer_count] = 0;
2213     }
2214   else
2215     {
2216       p[0] = ' ';
2217       memset (p + 1, '*', pointer_count);
2218       p[pointer_count + 1] = 0;
2219     }
2220   if (wanted_type_name)
2221     {
2222       if (descr)
2223         warning ("%s should have type %<%s%s%>, but argument %d has type %qT",
2224                  descr, wanted_type_name, p, arg_num, arg_type);
2225       else
2226         warning ("format %q.*s expects type %<%s%s%>, but argument %d has type %qT",
2227                  format_length, format_start, wanted_type_name, p,
2228                  arg_num, arg_type);
2229     }
2230   else
2231     {
2232       if (descr)
2233         warning ("%s should have type %<%T%s%>, but argument %d has type %qT",
2234                  descr, wanted_type, p, arg_num, arg_type);
2235       else
2236         warning ("format %q.*s expects type %<%T%s%>, but argument %d has type %qT",
2237                  format_length, format_start, wanted_type, p, arg_num, arg_type);
2238     }
2239 }
2240
2241
2242 /* Given a format_char_info array FCI, and a character C, this function
2243    returns the index into the conversion_specs where that specifier's
2244    data is located.  If the character isn't found it aborts.  */
2245 static unsigned int
2246 find_char_info_specifier_index (const format_char_info *fci, int c)
2247 {
2248   unsigned i;
2249
2250   for (i = 0; fci->format_chars; i++, fci++)
2251     if (strchr (fci->format_chars, c))
2252       return i;
2253   
2254   /* We shouldn't be looking for a non-existent specifier.  */
2255   gcc_unreachable ();
2256 }
2257
2258 /* Given a format_length_info array FLI, and a character C, this
2259    function returns the index into the conversion_specs where that
2260    modifier's data is located.  If the character isn't found it
2261    aborts.  */
2262 static unsigned int
2263 find_length_info_modifier_index (const format_length_info *fli, int c)
2264 {
2265   unsigned i;
2266
2267   for (i = 0; fli->name; i++, fli++)
2268     if (strchr (fli->name, c))
2269       return i;
2270   
2271   /* We shouldn't be looking for a non-existent modifier.  */
2272   gcc_unreachable ();
2273 }
2274
2275 /* Determine the type of HOST_WIDE_INT in the code being compiled for
2276    use in GCC's __asm_fprintf__ custom format attribute.  You must
2277    have set dynamic_format_types before calling this function.  */
2278 static void
2279 init_dynamic_asm_fprintf_info (void)
2280 {
2281   static tree hwi;
2282
2283   if (!hwi)
2284     {
2285       format_length_info *new_asm_fprintf_length_specs;
2286       unsigned int i;
2287           
2288       /* Find the underlying type for HOST_WIDE_INT.  For the %w
2289          length modifier to work, one must have issued: "typedef
2290          HOST_WIDE_INT __gcc_host_wide_int__;" in one's source code
2291          prior to using that modifier.  */
2292       hwi = maybe_get_identifier ("__gcc_host_wide_int__");
2293       gcc_assert (hwi);
2294       hwi = DECL_ORIGINAL_TYPE (identifier_global_value (hwi));
2295       gcc_assert (hwi);
2296
2297       /* Create a new (writable) copy of asm_fprintf_length_specs.  */
2298       new_asm_fprintf_length_specs = (format_length_info *)
2299                                      xmemdup (asm_fprintf_length_specs,
2300                                               sizeof (asm_fprintf_length_specs),
2301                                               sizeof (asm_fprintf_length_specs));
2302
2303       /* HOST_WIDE_INT must be one of 'long' or 'long long'.  */
2304       i = find_length_info_modifier_index (new_asm_fprintf_length_specs, 'w');
2305       if (hwi == long_integer_type_node)
2306         new_asm_fprintf_length_specs[i].index = FMT_LEN_l;
2307       else if (hwi == long_long_integer_type_node)
2308         new_asm_fprintf_length_specs[i].index = FMT_LEN_ll;
2309       else
2310         gcc_unreachable ();
2311
2312       /* Assign the new data for use.  */
2313       dynamic_format_types[asm_fprintf_format_type].length_char_specs =
2314         new_asm_fprintf_length_specs;
2315     }
2316 }
2317
2318 /* Determine the types of "tree" and "location_t" in the code being
2319    compiled for use in GCC's diagnostic custom format attributes.  You
2320    must have set dynamic_format_types before calling this function.  */
2321 static void
2322 init_dynamic_diag_info (void)
2323 {
2324   static tree t, loc, hwi;
2325
2326   if (!loc || !t || !hwi)
2327     {
2328       static format_char_info *diag_fci, *cdiag_fci, *cxxdiag_fci;
2329       static format_length_info *diag_ls;
2330       unsigned int i;
2331
2332       /* For the GCC-diagnostics custom format specifiers to work, one
2333          must have declared 'tree' and/or 'location_t' prior to using
2334          those attributes.  If we haven't seen these declarations then
2335          you shouldn't use the specifiers requiring these types.
2336          However we don't force a hard ICE because we may see only one
2337          or the other type.  */
2338       if ((loc = maybe_get_identifier ("location_t")))
2339         loc = TREE_TYPE (identifier_global_value (loc));
2340
2341       /* We need to grab the underlying 'union tree_node' so peek into
2342          an extra type level.  */
2343       if ((t = maybe_get_identifier ("tree")))
2344         t = TREE_TYPE (TREE_TYPE (identifier_global_value (t)));
2345     
2346       /* Find the underlying type for HOST_WIDE_INT.  For the %w
2347          length modifier to work, one must have issued: "typedef
2348          HOST_WIDE_INT __gcc_host_wide_int__;" in one's source code
2349          prior to using that modifier.  */
2350       if ((hwi = maybe_get_identifier ("__gcc_host_wide_int__")))
2351         hwi = DECL_ORIGINAL_TYPE (identifier_global_value (hwi));
2352       
2353       /* Assign the new data for use.  */
2354
2355       /* All the GCC diag formats use the same length specs.  */
2356       if (!diag_ls)
2357         dynamic_format_types[gcc_diag_format_type].length_char_specs =
2358           dynamic_format_types[gcc_cdiag_format_type].length_char_specs =
2359           dynamic_format_types[gcc_cxxdiag_format_type].length_char_specs =
2360           diag_ls = (format_length_info *)
2361                     xmemdup (gcc_diag_length_specs,
2362                              sizeof (gcc_diag_length_specs),
2363                              sizeof (gcc_diag_length_specs)); 
2364       if (hwi)
2365         {
2366           /* HOST_WIDE_INT must be one of 'long' or 'long long'.  */
2367           i = find_length_info_modifier_index (diag_ls, 'w');
2368           if (hwi == long_integer_type_node)
2369             diag_ls[i].index = FMT_LEN_l;
2370           else if (hwi == long_long_integer_type_node)
2371             diag_ls[i].index = FMT_LEN_ll;
2372           else
2373             gcc_unreachable ();
2374         }
2375
2376       /* Handle the __gcc_diag__ format specifics.  */
2377       if (!diag_fci)
2378         dynamic_format_types[gcc_diag_format_type].conversion_specs =
2379           diag_fci = (format_char_info *)
2380                      xmemdup (gcc_diag_char_table,
2381                               sizeof (gcc_diag_char_table),
2382                               sizeof (gcc_diag_char_table));
2383       if (loc)
2384         {
2385           i = find_char_info_specifier_index (diag_fci, 'H');
2386           diag_fci[i].types[0].type = &loc;
2387           diag_fci[i].pointer_count = 1;
2388         }
2389       if (t)
2390         {
2391           i = find_char_info_specifier_index (diag_fci, 'J');
2392           diag_fci[i].types[0].type = &t;
2393           diag_fci[i].pointer_count = 1;
2394         }
2395
2396       /* Handle the __gcc_cdiag__ format specifics.  */
2397       if (!cdiag_fci)
2398         dynamic_format_types[gcc_cdiag_format_type].conversion_specs =
2399           cdiag_fci = (format_char_info *)
2400                       xmemdup (gcc_cdiag_char_table,
2401                                sizeof (gcc_cdiag_char_table),
2402                                sizeof (gcc_cdiag_char_table));
2403       if (loc)
2404         {
2405           i = find_char_info_specifier_index (cdiag_fci, 'H');
2406           cdiag_fci[i].types[0].type = &loc;
2407           cdiag_fci[i].pointer_count = 1;
2408         }
2409       if (t)
2410         {
2411           /* All specifiers taking a tree share the same struct.  */
2412           i = find_char_info_specifier_index (cdiag_fci, 'D');
2413           cdiag_fci[i].types[0].type = &t;
2414           cdiag_fci[i].pointer_count = 1;
2415           i = find_char_info_specifier_index (cdiag_fci, 'J');
2416           cdiag_fci[i].types[0].type = &t;
2417           cdiag_fci[i].pointer_count = 1;
2418         }
2419
2420       /* Handle the __gcc_cxxdiag__ format specifics.  */
2421       if (!cxxdiag_fci)
2422         dynamic_format_types[gcc_cxxdiag_format_type].conversion_specs =
2423           cxxdiag_fci = (format_char_info *)
2424                         xmemdup (gcc_cxxdiag_char_table,
2425                                  sizeof (gcc_cxxdiag_char_table),
2426                                  sizeof (gcc_cxxdiag_char_table));
2427       if (loc)
2428         {
2429           i = find_char_info_specifier_index (cxxdiag_fci, 'H');
2430           cxxdiag_fci[i].types[0].type = &loc;
2431           cxxdiag_fci[i].pointer_count = 1;
2432         }
2433       if (t)
2434         {
2435           /* All specifiers taking a tree share the same struct.  */
2436           i = find_char_info_specifier_index (cxxdiag_fci, 'D');
2437           cxxdiag_fci[i].types[0].type = &t;
2438           cxxdiag_fci[i].pointer_count = 1;
2439           i = find_char_info_specifier_index (cxxdiag_fci, 'J');
2440           cxxdiag_fci[i].types[0].type = &t;
2441           cxxdiag_fci[i].pointer_count = 1;
2442         }
2443     }
2444 }
2445
2446 #ifdef TARGET_FORMAT_TYPES
2447 extern const format_kind_info TARGET_FORMAT_TYPES[];
2448 #endif
2449
2450 /* Handle a "format" attribute; arguments as in
2451    struct attribute_spec.handler.  */
2452 tree
2453 handle_format_attribute (tree *node, tree ARG_UNUSED (name), tree args,
2454                          int flags, bool *no_add_attrs)
2455 {
2456   tree type = *node;
2457   function_format_info info;
2458   tree argument;
2459
2460 #ifdef TARGET_FORMAT_TYPES
2461   /* If the target provides additional format types, we need to
2462      add them to FORMAT_TYPES at first use.  */
2463   if (TARGET_FORMAT_TYPES != NULL && !dynamic_format_types)
2464     {
2465       dynamic_format_types = xmalloc ((n_format_types + TARGET_N_FORMAT_TYPES)
2466                                       * sizeof (dynamic_format_types[0]));
2467       memcpy (dynamic_format_types, format_types_orig,
2468               sizeof (format_types_orig));
2469       memcpy (&dynamic_format_types[n_format_types], TARGET_FORMAT_TYPES,
2470               TARGET_N_FORMAT_TYPES * sizeof (dynamic_format_types[0]));
2471
2472       format_types = dynamic_format_types;
2473       n_format_types += TARGET_N_FORMAT_TYPES;
2474     }
2475 #endif
2476
2477   if (!decode_format_attr (args, &info, 0))
2478     {
2479       *no_add_attrs = true;
2480       return NULL_TREE;
2481     }
2482
2483   argument = TYPE_ARG_TYPES (type);
2484   if (argument)
2485     {
2486       if (!check_format_string (argument, info.format_num, flags,
2487                                 no_add_attrs))
2488         return NULL_TREE;
2489
2490       if (info.first_arg_num != 0)
2491         {
2492           unsigned HOST_WIDE_INT arg_num = 1;
2493
2494           /* Verify that first_arg_num points to the last arg,
2495              the ...  */
2496           while (argument)
2497             arg_num++, argument = TREE_CHAIN (argument);
2498
2499           if (arg_num != info.first_arg_num)
2500             {
2501               if (!(flags & (int) ATTR_FLAG_BUILT_IN))
2502                 error ("args to be formatted is not %<...%>");
2503               *no_add_attrs = true;
2504               return NULL_TREE;
2505             }
2506         }
2507     }
2508
2509   if (info.format_type == strftime_format_type && info.first_arg_num != 0)
2510     {
2511       error ("strftime formats cannot format arguments");
2512       *no_add_attrs = true;
2513       return NULL_TREE;
2514     }
2515
2516   /* If this is a custom GCC-internal format type, we have to
2517      initialize certain bits a runtime.  */
2518   if (info.format_type == asm_fprintf_format_type
2519       || info.format_type == gcc_diag_format_type
2520       || info.format_type == gcc_cdiag_format_type
2521       || info.format_type == gcc_cxxdiag_format_type)
2522     {
2523       /* Our first time through, we have to make sure that our
2524          format_type data is allocated dynamically and is modifiable.  */
2525       if (!dynamic_format_types)
2526         format_types = dynamic_format_types = (format_kind_info *)
2527           xmemdup (format_types_orig, sizeof (format_types_orig),
2528                    sizeof (format_types_orig));
2529
2530       /* If this is format __asm_fprintf__, we have to initialize
2531          GCC's notion of HOST_WIDE_INT for checking %wd.  */
2532       if (info.format_type == asm_fprintf_format_type)
2533         init_dynamic_asm_fprintf_info ();
2534       /* If this is one of the diagnostic attributes, then we have to
2535          initialize 'location_t' and 'tree' at runtime.  */
2536       else if (info.format_type == gcc_diag_format_type
2537                || info.format_type == gcc_cdiag_format_type
2538                || info.format_type == gcc_cxxdiag_format_type)
2539         init_dynamic_diag_info ();
2540       else
2541         gcc_unreachable ();
2542     }
2543
2544   return NULL_TREE;
2545 }