Merge branch 'vendor/GCC50'
[dragonfly.git] / contrib / gcc-5.0 / gcc / c-family / c-format.c
1 /* Check calls to formatted I/O functions (-Wformat).
2    Copyright (C) 1992-2015 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "hash-set.h"
25 #include "machmode.h"
26 #include "vec.h"
27 #include "double-int.h"
28 #include "input.h"
29 #include "alias.h"
30 #include "symtab.h"
31 #include "wide-int.h"
32 #include "inchash.h"
33 #include "real.h"
34 #include "tree.h"
35 #include "stringpool.h"
36 #include "flags.h"
37 #include "c-common.h"
38 #include "c-objc.h"
39 #include "intl.h"
40 #include "diagnostic-core.h"
41 #include "langhooks.h"
42 #include "c-format.h"
43 #include "alloc-pool.h"
44 #include "c-target.h"
45
46 /* Handle attributes associated with format checking.  */
47
48 /* This must be in the same order as format_types, except for
49    format_type_error.  Target-specific format types do not have
50    matching enum values.  */
51 enum format_type { printf_format_type, asm_fprintf_format_type,
52                    gcc_diag_format_type, gcc_tdiag_format_type,
53                    gcc_cdiag_format_type,
54                    gcc_cxxdiag_format_type, gcc_gfc_format_type,
55                    gcc_objc_string_format_type,
56                    format_type_error = -1};
57
58 typedef struct function_format_info
59 {
60   int format_type;                      /* type of format (printf, scanf, etc.) */
61   unsigned HOST_WIDE_INT format_num;    /* number of format argument */
62   unsigned HOST_WIDE_INT first_arg_num; /* number of first arg (zero for varargs) */
63 } function_format_info;
64
65 static bool decode_format_attr (tree, function_format_info *, int);
66 static int decode_format_type (const char *);
67
68 static bool check_format_string (tree argument,
69                                  unsigned HOST_WIDE_INT format_num,
70                                  int flags, bool *no_add_attrs,
71                                  int expected_format_type);
72 static bool get_constant (tree expr, unsigned HOST_WIDE_INT *value,
73                           int validated_p);
74 static const char *convert_format_name_to_system_name (const char *attr_name);
75 static bool cmp_attribs (const char *tattr_name, const char *attr_name);
76
77 static int first_target_format_type;
78 static const char *format_name (int format_num);
79 static int format_flags (int format_num);
80
81 /* Check that we have a pointer to a string suitable for use as a format.
82    The default is to check for a char type.
83    For objective-c dialects, this is extended to include references to string
84    objects validated by objc_string_ref_type_p ().  
85    Targets may also provide a string object type that can be used within c and 
86    c++ and shared with their respective objective-c dialects. In this case the
87    reference to a format string is checked for validity via a hook.
88    
89    The function returns true if strref points to any string type valid for the 
90    language dialect and target.  */
91
92 static bool
93 valid_stringptr_type_p (tree strref)
94 {
95   return (strref != NULL
96           && TREE_CODE (strref) == POINTER_TYPE
97           && (TYPE_MAIN_VARIANT (TREE_TYPE (strref)) == char_type_node
98               || objc_string_ref_type_p (strref)
99               || (*targetcm.string_object_ref_type_p) ((const_tree) strref)));
100 }
101
102 /* Handle a "format_arg" attribute; arguments as in
103    struct attribute_spec.handler.  */
104 tree
105 handle_format_arg_attribute (tree *node, tree ARG_UNUSED (name),
106                              tree args, int flags, bool *no_add_attrs)
107 {
108   tree type = *node;
109   tree format_num_expr = TREE_VALUE (args);
110   unsigned HOST_WIDE_INT format_num = 0;
111
112   if (!get_constant (format_num_expr, &format_num, 0))
113     {
114       error ("format string has invalid operand number");
115       *no_add_attrs = true;
116       return NULL_TREE;
117     }
118
119   if (prototype_p (type))
120     {
121       /* The format arg can be any string reference valid for the language and
122          target.  We cannot be more specific in this case.  */
123       if (!check_format_string (type, format_num, flags, no_add_attrs, -1))
124         return NULL_TREE;
125     }
126
127   if (!valid_stringptr_type_p (TREE_TYPE (type)))
128     {
129       if (!(flags & (int) ATTR_FLAG_BUILT_IN))
130         error ("function does not return string type");
131       *no_add_attrs = true;
132       return NULL_TREE;
133     }
134
135   return NULL_TREE;
136 }
137
138 /* Verify that the format_num argument is actually a string reference suitable,
139    for the language dialect and target (in case the format attribute is in 
140    error).  When we know the specific reference type expected, this is also 
141    checked.  */
142 static bool
143 check_format_string (tree fntype, unsigned HOST_WIDE_INT format_num,
144                      int flags, bool *no_add_attrs, int expected_format_type)
145 {
146   unsigned HOST_WIDE_INT i;
147   bool is_objc_sref, is_target_sref, is_char_ref;
148   tree ref;
149   int fmt_flags;
150   function_args_iterator iter;
151
152   i = 1;
153   FOREACH_FUNCTION_ARGS (fntype, ref, iter)
154     {
155       if (i == format_num)
156         break;
157       i++;
158     }
159
160   if (!ref
161       || !valid_stringptr_type_p (ref))
162     {
163       if (!(flags & (int) ATTR_FLAG_BUILT_IN))
164         error ("format string argument is not a string type");
165       *no_add_attrs = true;
166       return false;
167     }
168
169   /* We only know that we want a suitable string reference.  */
170   if (expected_format_type < 0)
171     return true;
172
173   /* Now check that the arg matches the expected type.  */
174   is_char_ref = 
175     (TYPE_MAIN_VARIANT (TREE_TYPE (ref)) == char_type_node);
176
177   fmt_flags = format_flags (expected_format_type);
178   is_objc_sref = is_target_sref = false;
179   if (!is_char_ref)
180     is_objc_sref = objc_string_ref_type_p (ref);
181
182   if (!(fmt_flags & FMT_FLAG_PARSE_ARG_CONVERT_EXTERNAL))
183     {
184       if (is_char_ref)
185         return true; /* OK, we expected a char and found one.  */
186       else
187         {
188           /* We expected a char but found an extended string type.  */
189           if (is_objc_sref)
190             error ("found a %<%s%> reference but the format argument should"
191                    " be a string", format_name (gcc_objc_string_format_type));
192           else
193             error ("found a %qT but the format argument should be a string",
194                    ref);
195           *no_add_attrs = true;
196           return false;
197         }
198     }
199
200   /* We expect a string object type as the format arg.  */
201   if (is_char_ref)
202     {
203       error ("format argument should be a %<%s%> reference but"
204              " a string was found", format_name (expected_format_type));
205       *no_add_attrs = true;
206       return false;
207     }
208   
209   /* We will assert that objective-c will support either its own string type
210      or the target-supplied variant.  */
211   if (!is_objc_sref)
212     is_target_sref = (*targetcm.string_object_ref_type_p) ((const_tree) ref);
213
214   if (expected_format_type == (int) gcc_objc_string_format_type 
215       && (is_objc_sref || is_target_sref))
216     return true;
217
218   /* We will allow a target string ref to match only itself.  */
219   if (first_target_format_type 
220       && expected_format_type >= first_target_format_type
221       && is_target_sref)
222     return true;
223   else
224     {
225       error ("format argument should be a %<%s%> reference", 
226               format_name (expected_format_type));
227       *no_add_attrs = true;
228       return false;
229     }
230
231   gcc_unreachable ();
232 }
233
234 /* Verify EXPR is a constant, and store its value.
235    If validated_p is true there should be no errors.
236    Returns true on success, false otherwise.  */
237 static bool
238 get_constant (tree expr, unsigned HOST_WIDE_INT *value, int validated_p)
239 {
240   if (!tree_fits_uhwi_p (expr))
241     {
242       gcc_assert (!validated_p);
243       return false;
244     }
245
246   *value = TREE_INT_CST_LOW (expr);
247
248   return true;
249 }
250
251 /* Decode the arguments to a "format" attribute into a
252    function_format_info structure.  It is already known that the list
253    is of the right length.  If VALIDATED_P is true, then these
254    attributes have already been validated and must not be erroneous;
255    if false, it will give an error message.  Returns true if the
256    attributes are successfully decoded, false otherwise.  */
257
258 static bool
259 decode_format_attr (tree args, function_format_info *info, int validated_p)
260 {
261   tree format_type_id = TREE_VALUE (args);
262   tree format_num_expr = TREE_VALUE (TREE_CHAIN (args));
263   tree first_arg_num_expr
264     = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (args)));
265
266   if (TREE_CODE (format_type_id) != IDENTIFIER_NODE)
267     {
268       gcc_assert (!validated_p);
269       error ("unrecognized format specifier");
270       return false;
271     }
272   else
273     {
274       const char *p = IDENTIFIER_POINTER (format_type_id);
275
276       p = convert_format_name_to_system_name (p);
277
278       info->format_type = decode_format_type (p);
279       
280       if (!c_dialect_objc ()
281            && info->format_type == gcc_objc_string_format_type)
282         {
283           gcc_assert (!validated_p);
284           warning (OPT_Wformat_, "%qE is only allowed in Objective-C dialects",
285                    format_type_id);
286           info->format_type = format_type_error;
287           return false;
288         }
289
290       if (info->format_type == format_type_error)
291         {
292           gcc_assert (!validated_p);
293           warning (OPT_Wformat_, "%qE is an unrecognized format function type",
294                    format_type_id);
295           return false;
296         }
297     }
298
299   if (!get_constant (format_num_expr, &info->format_num, validated_p))
300     {
301       error ("format string has invalid operand number");
302       return false;
303     }
304
305   if (!get_constant (first_arg_num_expr, &info->first_arg_num, validated_p))
306     {
307       error ("%<...%> has invalid operand number");
308       return false;
309     }
310
311   if (info->first_arg_num != 0 && info->first_arg_num <= info->format_num)
312     {
313       gcc_assert (!validated_p);
314       error ("format string argument follows the args to be formatted");
315       return false;
316     }
317
318   return true;
319 }
320 \f
321 /* Check a call to a format function against a parameter list.  */
322
323 /* The C standard version C++ is treated as equivalent to
324    or inheriting from, for the purpose of format features supported.  */
325 #define CPLUSPLUS_STD_VER       (cxx_dialect < cxx11 ? STD_C94 : STD_C99)
326 /* The C standard version we are checking formats against when pedantic.  */
327 #define C_STD_VER               ((int) (c_dialect_cxx ()                   \
328                                  ? CPLUSPLUS_STD_VER                       \
329                                  : (flag_isoc99                            \
330                                     ? STD_C99                              \
331                                     : (flag_isoc94 ? STD_C94 : STD_C89))))
332 /* The name to give to the standard version we are warning about when
333    pedantic.  FEATURE_VER is the version in which the feature warned out
334    appeared, which is higher than C_STD_VER.  */
335 #define C_STD_NAME(FEATURE_VER) (c_dialect_cxx ()               \
336                                  ? (cxx_dialect < cxx11 ? "ISO C++98" \
337                                     : "ISO C++11")              \
338                                  : ((FEATURE_VER) == STD_EXT    \
339                                     ? "ISO C"                   \
340                                     : "ISO C90"))
341 /* Adjust a C standard version, which may be STD_C9L, to account for
342    -Wno-long-long.  Returns other standard versions unchanged.  */
343 #define ADJ_STD(VER)            ((int) ((VER) == STD_C9L                      \
344                                        ? (warn_long_long ? STD_C99 : STD_C89) \
345                                        : (VER)))
346
347 /* Enum describing the kind of specifiers present in the format and
348    requiring an argument.  */
349 enum format_specifier_kind {
350   CF_KIND_FORMAT,
351   CF_KIND_FIELD_WIDTH,
352   CF_KIND_FIELD_PRECISION
353 };
354
355 static const char *kind_descriptions[] = {
356   N_("format"),
357   N_("field width specifier"),
358   N_("field precision specifier")
359 };
360
361 /* Structure describing details of a type expected in format checking,
362    and the type to check against it.  */
363 typedef struct format_wanted_type
364 {
365   /* The type wanted.  */
366   tree wanted_type;
367   /* The name of this type to use in diagnostics.  */
368   const char *wanted_type_name;
369   /* Should be type checked just for scalar width identity.  */
370   int scalar_identity_flag;
371   /* The level of indirection through pointers at which this type occurs.  */
372   int pointer_count;
373   /* Whether, when pointer_count is 1, to allow any character type when
374      pedantic, rather than just the character or void type specified.  */
375   int char_lenient_flag;
376   /* Whether the argument, dereferenced once, is written into and so the
377      argument must not be a pointer to a const-qualified type.  */
378   int writing_in_flag;
379   /* Whether the argument, dereferenced once, is read from and so
380      must not be a NULL pointer.  */
381   int reading_from_flag;
382   /* The kind of specifier that this type is used for.  */
383   enum format_specifier_kind kind;
384   /* The starting character of the specifier.  This never includes the
385      initial percent sign.  */
386   const char *format_start;
387   /* The length of the specifier.  */
388   int format_length;
389   /* The actual parameter to check against the wanted type.  */
390   tree param;
391   /* The argument number of that parameter.  */
392   int arg_num;
393   /* The next type to check for this format conversion, or NULL if none.  */
394   struct format_wanted_type *next;
395 } format_wanted_type;
396
397 /* Convenience macro for format_length_info meaning unused.  */
398 #define NO_FMT NULL, FMT_LEN_none, STD_C89
399
400 static const format_length_info printf_length_specs[] =
401 {
402   { "h", FMT_LEN_h, STD_C89, "hh", FMT_LEN_hh, STD_C99, 0 },
403   { "l", FMT_LEN_l, STD_C89, "ll", FMT_LEN_ll, STD_C9L, 0 },
404   { "q", FMT_LEN_ll, STD_EXT, NO_FMT, 0 },
405   { "L", FMT_LEN_L, STD_C89, NO_FMT, 0 },
406   { "z", FMT_LEN_z, STD_C99, NO_FMT, 0 },
407   { "Z", FMT_LEN_z, STD_EXT, NO_FMT, 0 },
408   { "t", FMT_LEN_t, STD_C99, NO_FMT, 0 },
409   { "j", FMT_LEN_j, STD_C99, NO_FMT, 0 },
410   { "H", FMT_LEN_H, STD_EXT, NO_FMT, 0 },
411   { "D", FMT_LEN_D, STD_EXT, "DD", FMT_LEN_DD, STD_EXT, 0 },
412   { NO_FMT, NO_FMT, 0 }
413 };
414
415 /* Length specifiers valid for asm_fprintf.  */
416 static const format_length_info asm_fprintf_length_specs[] =
417 {
418   { "l", FMT_LEN_l, STD_C89, "ll", FMT_LEN_ll, STD_C89, 0 },
419   { "w", FMT_LEN_none, STD_C89, NO_FMT, 0 },
420   { NO_FMT, NO_FMT, 0 }
421 };
422
423 /* Length specifiers valid for GCC diagnostics.  */
424 static const format_length_info gcc_diag_length_specs[] =
425 {
426   { "l", FMT_LEN_l, STD_C89, "ll", FMT_LEN_ll, STD_C89, 0 },
427   { "w", FMT_LEN_none, STD_C89, NO_FMT, 0 },
428   { NO_FMT, NO_FMT, 0 }
429 };
430
431 /* The custom diagnostics all accept the same length specifiers.  */
432 #define gcc_tdiag_length_specs gcc_diag_length_specs
433 #define gcc_cdiag_length_specs gcc_diag_length_specs
434 #define gcc_cxxdiag_length_specs gcc_diag_length_specs
435
436 /* This differs from printf_length_specs only in that "Z" is not accepted.  */
437 static const format_length_info scanf_length_specs[] =
438 {
439   { "h", FMT_LEN_h, STD_C89, "hh", FMT_LEN_hh, STD_C99, 0 },
440   { "l", FMT_LEN_l, STD_C89, "ll", FMT_LEN_ll, STD_C9L, 0 },
441   { "q", FMT_LEN_ll, STD_EXT, NO_FMT, 0 },
442   { "L", FMT_LEN_L, STD_C89, NO_FMT, 0 },
443   { "z", FMT_LEN_z, STD_C99, NO_FMT, 0 },
444   { "t", FMT_LEN_t, STD_C99, NO_FMT, 0 },
445   { "j", FMT_LEN_j, STD_C99, NO_FMT, 0 },
446   { "H", FMT_LEN_H, STD_EXT, NO_FMT, 0 },
447   { "D", FMT_LEN_D, STD_EXT, "DD", FMT_LEN_DD, STD_EXT, 0 },
448   { NO_FMT, NO_FMT, 0 }
449 };
450
451
452 /* All tables for strfmon use STD_C89 everywhere, since -pedantic warnings
453    make no sense for a format type not part of any C standard version.  */
454 static const format_length_info strfmon_length_specs[] =
455 {
456   /* A GNU extension.  */
457   { "L", FMT_LEN_L, STD_C89, NO_FMT, 0 },
458   { NO_FMT, NO_FMT, 0 }
459 };
460
461
462 /* For now, the Fortran front-end routines only use l as length modifier.  */
463 static const format_length_info gcc_gfc_length_specs[] =
464 {
465   { "l", FMT_LEN_l, STD_C89, NO_FMT, 0 },
466   { NO_FMT, NO_FMT, 0 }
467 };
468
469
470 static const format_flag_spec printf_flag_specs[] =
471 {
472   { ' ',  0, 0, N_("' ' flag"),        N_("the ' ' printf flag"),              STD_C89 },
473   { '+',  0, 0, N_("'+' flag"),        N_("the '+' printf flag"),              STD_C89 },
474   { '#',  0, 0, N_("'#' flag"),        N_("the '#' printf flag"),              STD_C89 },
475   { '0',  0, 0, N_("'0' flag"),        N_("the '0' printf flag"),              STD_C89 },
476   { '-',  0, 0, N_("'-' flag"),        N_("the '-' printf flag"),              STD_C89 },
477   { '\'', 0, 0, N_("''' flag"),        N_("the ''' printf flag"),              STD_EXT },
478   { 'I',  0, 0, N_("'I' flag"),        N_("the 'I' printf flag"),              STD_EXT },
479   { 'w',  0, 0, N_("field width"),     N_("field width in printf format"),     STD_C89 },
480   { 'p',  0, 0, N_("precision"),       N_("precision in printf format"),       STD_C89 },
481   { 'L',  0, 0, N_("length modifier"), N_("length modifier in printf format"), STD_C89 },
482   { 0, 0, 0, NULL, NULL, STD_C89 }
483 };
484
485
486 static const format_flag_pair printf_flag_pairs[] =
487 {
488   { ' ', '+', 1, 0   },
489   { '0', '-', 1, 0   },
490   { '0', 'p', 1, 'i' },
491   { 0, 0, 0, 0 }
492 };
493
494 static const format_flag_spec asm_fprintf_flag_specs[] =
495 {
496   { ' ',  0, 0, N_("' ' flag"),        N_("the ' ' printf flag"),              STD_C89 },
497   { '+',  0, 0, N_("'+' flag"),        N_("the '+' printf flag"),              STD_C89 },
498   { '#',  0, 0, N_("'#' flag"),        N_("the '#' printf flag"),              STD_C89 },
499   { '0',  0, 0, N_("'0' flag"),        N_("the '0' printf flag"),              STD_C89 },
500   { '-',  0, 0, N_("'-' flag"),        N_("the '-' printf flag"),              STD_C89 },
501   { 'w',  0, 0, N_("field width"),     N_("field width in printf format"),     STD_C89 },
502   { 'p',  0, 0, N_("precision"),       N_("precision in printf format"),       STD_C89 },
503   { 'L',  0, 0, N_("length modifier"), N_("length modifier in printf format"), STD_C89 },
504   { 0, 0, 0, NULL, NULL, STD_C89 }
505 };
506
507 static const format_flag_pair asm_fprintf_flag_pairs[] =
508 {
509   { ' ', '+', 1, 0   },
510   { '0', '-', 1, 0   },
511   { '0', 'p', 1, 'i' },
512   { 0, 0, 0, 0 }
513 };
514
515 static const format_flag_pair gcc_diag_flag_pairs[] =
516 {
517   { 0, 0, 0, 0 }
518 };
519
520 #define gcc_tdiag_flag_pairs gcc_diag_flag_pairs
521 #define gcc_cdiag_flag_pairs gcc_diag_flag_pairs
522 #define gcc_cxxdiag_flag_pairs gcc_diag_flag_pairs
523 #define gcc_gfc_flag_pairs gcc_diag_flag_pairs
524
525 static const format_flag_spec gcc_diag_flag_specs[] =
526 {
527   { '+',  0, 0, N_("'+' flag"),        N_("the '+' printf flag"),              STD_C89 },
528   { '#',  0, 0, N_("'#' flag"),        N_("the '#' printf flag"),              STD_C89 },
529   { 'q',  0, 0, N_("'q' flag"),        N_("the 'q' diagnostic flag"),          STD_C89 },
530   { 'p',  0, 0, N_("precision"),       N_("precision in printf format"),       STD_C89 },
531   { 'L',  0, 0, N_("length modifier"), N_("length modifier in printf format"), STD_C89 },
532   { 0, 0, 0, NULL, NULL, STD_C89 }
533 };
534
535 #define gcc_tdiag_flag_specs gcc_diag_flag_specs
536 #define gcc_cdiag_flag_specs gcc_diag_flag_specs
537 #define gcc_cxxdiag_flag_specs gcc_diag_flag_specs
538 #define gcc_gfc_flag_specs gcc_diag_flag_specs
539
540 static const format_flag_spec scanf_flag_specs[] =
541 {
542   { '*',  0, 0, N_("assignment suppression"), N_("the assignment suppression scanf feature"), STD_C89 },
543   { 'a',  0, 0, N_("'a' flag"),               N_("the 'a' scanf flag"),                       STD_EXT },
544   { 'm',  0, 0, N_("'m' flag"),               N_("the 'm' scanf flag"),                       STD_EXT },
545   { 'w',  0, 0, N_("field width"),            N_("field width in scanf format"),              STD_C89 },
546   { 'L',  0, 0, N_("length modifier"),        N_("length modifier in scanf format"),          STD_C89 },
547   { '\'', 0, 0, N_("''' flag"),               N_("the ''' scanf flag"),                       STD_EXT },
548   { 'I',  0, 0, N_("'I' flag"),               N_("the 'I' scanf flag"),                       STD_EXT },
549   { 0, 0, 0, NULL, NULL, STD_C89 }
550 };
551
552
553 static const format_flag_pair scanf_flag_pairs[] =
554 {
555   { '*', 'L', 0, 0 },
556   { 'a', 'm', 0, 0 },
557   { 0, 0, 0, 0 }
558 };
559
560
561 static const format_flag_spec strftime_flag_specs[] =
562 {
563   { '_', 0,   0, N_("'_' flag"),     N_("the '_' strftime flag"),          STD_EXT },
564   { '-', 0,   0, N_("'-' flag"),     N_("the '-' strftime flag"),          STD_EXT },
565   { '0', 0,   0, N_("'0' flag"),     N_("the '0' strftime flag"),          STD_EXT },
566   { '^', 0,   0, N_("'^' flag"),     N_("the '^' strftime flag"),          STD_EXT },
567   { '#', 0,   0, N_("'#' flag"),     N_("the '#' strftime flag"),          STD_EXT },
568   { 'w', 0,   0, N_("field width"),  N_("field width in strftime format"), STD_EXT },
569   { 'E', 0,   0, N_("'E' modifier"), N_("the 'E' strftime modifier"),      STD_C99 },
570   { 'O', 0,   0, N_("'O' modifier"), N_("the 'O' strftime modifier"),      STD_C99 },
571   { 'O', 'o', 0, NULL,               N_("the 'O' modifier"),               STD_EXT },
572   { 0, 0, 0, NULL, NULL, STD_C89 }
573 };
574
575
576 static const format_flag_pair strftime_flag_pairs[] =
577 {
578   { 'E', 'O', 0, 0 },
579   { '_', '-', 0, 0 },
580   { '_', '0', 0, 0 },
581   { '-', '0', 0, 0 },
582   { '^', '#', 0, 0 },
583   { 0, 0, 0, 0 }
584 };
585
586
587 static const format_flag_spec strfmon_flag_specs[] =
588 {
589   { '=',  0, 1, N_("fill character"),  N_("fill character in strfmon format"),  STD_C89 },
590   { '^',  0, 0, N_("'^' flag"),        N_("the '^' strfmon flag"),              STD_C89 },
591   { '+',  0, 0, N_("'+' flag"),        N_("the '+' strfmon flag"),              STD_C89 },
592   { '(',  0, 0, N_("'(' flag"),        N_("the '(' strfmon flag"),              STD_C89 },
593   { '!',  0, 0, N_("'!' flag"),        N_("the '!' strfmon flag"),              STD_C89 },
594   { '-',  0, 0, N_("'-' flag"),        N_("the '-' strfmon flag"),              STD_C89 },
595   { 'w',  0, 0, N_("field width"),     N_("field width in strfmon format"),     STD_C89 },
596   { '#',  0, 0, N_("left precision"),  N_("left precision in strfmon format"),  STD_C89 },
597   { 'p',  0, 0, N_("right precision"), N_("right precision in strfmon format"), STD_C89 },
598   { 'L',  0, 0, N_("length modifier"), N_("length modifier in strfmon format"), STD_C89 },
599   { 0, 0, 0, NULL, NULL, STD_C89 }
600 };
601
602 static const format_flag_pair strfmon_flag_pairs[] =
603 {
604   { '+', '(', 0, 0 },
605   { 0, 0, 0, 0 }
606 };
607
608
609 static const format_char_info dfly_ext_char_info =
610 { NULL,  1, STD_EXT, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "",      "cR", NULL };
611
612 static const format_char_info print_char_table[] =
613 {
614   /* C89 conversion specifiers.  */
615   { "di",  0, STD_C89, { T89_I,   T99_SC,  T89_S,   T89_L,   T9L_LL,  TEX_LL,  T99_SST, T99_PD,  T99_IM,  BADLEN,  BADLEN,  BADLEN  }, "-wp0 +'I",  "i",  NULL },
616   { "oxX", 0, STD_C89, { T89_UI,  T99_UC,  T89_US,  T89_UL,  T9L_ULL, TEX_ULL, T99_ST,  T99_UPD, T99_UIM, BADLEN,  BADLEN,  BADLEN }, "-wp0#",     "i",  NULL },
617   { "u",   0, STD_C89, { T89_UI,  T99_UC,  T89_US,  T89_UL,  T9L_ULL, TEX_ULL, T99_ST,  T99_UPD, T99_UIM, BADLEN,  BADLEN,  BADLEN }, "-wp0'I",    "i",  NULL },
618   { "fgG", 0, STD_C89, { T89_D,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T89_LD,  BADLEN,  BADLEN,  BADLEN,  TEX_D32, TEX_D64, TEX_D128 }, "-wp0 +#'I", "",   NULL },
619   { "eE",  0, STD_C89, { T89_D,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T89_LD,  BADLEN,  BADLEN,  BADLEN,  TEX_D32, TEX_D64, TEX_D128 }, "-wp0 +#I",  "",   NULL },
620   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T94_WI,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-w",        "",   NULL },
621   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  T94_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-wp",       "cR", NULL },
622   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-w",        "c",  NULL },
623   { "n",   1, STD_C89, { T89_I,   T99_SC,  T89_S,   T89_L,   T9L_LL,  BADLEN,  T99_SST, T99_PD,  T99_IM,  BADLEN,  BADLEN,  BADLEN }, "",          "W",  NULL },
624   /* C99 conversion specifiers.  */
625   { "F",   0, STD_C99, { T99_D,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T99_LD,  BADLEN,  BADLEN,  BADLEN,  TEX_D32, TEX_D64, TEX_D128 }, "-wp0 +#'I", "",   NULL },
626   { "aA",  0, STD_C99, { T99_D,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T99_LD,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-wp0 +#",   "",   NULL },
627   /* X/Open conversion specifiers.  */
628   { "C",   0, STD_EXT, { TEX_WI,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-w",        "",   NULL },
629   { "S",   1, STD_EXT, { TEX_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-wp",       "R",  NULL },
630   /* GNU conversion specifiers.  */
631   { "m",   0, STD_EXT, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-wp",       "",   NULL },
632   /* BSD conversion specifiers.  */
633   /* DragonFly kernel extensions (src/sys/kern/subr_prf.c).
634      The format %b is supported to decode error registers.
635      Its usage is:      printf("reg=%b\n", regval, "<base><arg>*");
636      which produces:    reg=3<BITTWO,BITONE>
637    */
638   { "b",   0, STD_EXT, { T89_I,  BADLEN,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-wp",       "",   &dfly_ext_char_info },
639   { "ry",  0, STD_EXT, { T89_I,  BADLEN,   BADLEN,   T89_L,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-wp0 +#",   "i",  NULL },
640   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
641 };
642
643 static const format_char_info asm_fprintf_char_table[] =
644 {
645   /* C89 conversion specifiers.  */
646   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp0 +",  "i", NULL },
647   { "oxX", 0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp0#",   "i", NULL },
648   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp0",    "i", NULL },
649   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-w",       "", NULL },
650   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp",    "cR", NULL },
651
652   /* asm_fprintf conversion specifiers.  */
653   { "O",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
654   { "R",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
655   { "I",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
656   { "L",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
657   { "U",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
658   { "r",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",  "", NULL },
659   { "@",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
660   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
661 };
662
663 static const format_char_info gcc_diag_char_table[] =
664 {
665   /* C89 conversion specifiers.  */
666   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
667   { "ox",  0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
668   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
669   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
670   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "pq", "cR", NULL },
671   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "c",  NULL },
672
673   /* Custom conversion specifiers.  */
674
675   /* These will require a "tree" at runtime.  */
676   { "K",   0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",    "",   NULL },
677
678   { "r",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",    "cR",   NULL },
679   { "<>'R",0, STD_C89, NOARGUMENTS, "",      "",   NULL },
680   { "m",   0, STD_C89, NOARGUMENTS, "q",     "",   NULL },
681   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
682 };
683
684 static const format_char_info gcc_tdiag_char_table[] =
685 {
686   /* C89 conversion specifiers.  */
687   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
688   { "ox",  0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
689   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
690   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
691   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "pq", "cR", NULL },
692   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "c",  NULL },
693
694   /* Custom conversion specifiers.  */
695
696   /* These will require a "tree" at runtime.  */
697   { "DFKTEV", 0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q+", "",   NULL },
698
699   { "v",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q#",  "",   NULL },
700
701   { "r",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",    "cR",   NULL },
702   { "<>'R",0, STD_C89, NOARGUMENTS, "",      "",   NULL },
703   { "m",   0, STD_C89, NOARGUMENTS, "q",     "",   NULL },
704   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
705 };
706
707 static const format_char_info gcc_cdiag_char_table[] =
708 {
709   /* C89 conversion specifiers.  */
710   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
711   { "ox",  0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
712   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
713   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
714   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "pq", "cR", NULL },
715   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "c",  NULL },
716
717   /* Custom conversion specifiers.  */
718
719   /* These will require a "tree" at runtime.  */
720   { "DEFKTV", 0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q+", "",   NULL },
721
722   { "v",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q#",  "",   NULL },
723
724   { "r",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",    "cR",   NULL },
725   { "<>'R",0, STD_C89, NOARGUMENTS, "",      "",   NULL },
726   { "m",   0, STD_C89, NOARGUMENTS, "q",     "",   NULL },
727   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
728 };
729
730 static const format_char_info gcc_cxxdiag_char_table[] =
731 {
732   /* C89 conversion specifiers.  */
733   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
734   { "ox",  0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
735   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
736   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
737   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "pq", "cR", NULL },
738   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "c",  NULL },
739
740   /* Custom conversion specifiers.  */
741
742   /* These will require a "tree" at runtime.  */
743   { "ADEFKSTVX",0,STD_C89,{ T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q+#",   "",   NULL },
744
745   { "v", 0,STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q#",  "",   NULL },
746
747   /* These accept either an 'int' or an 'enum tree_code' (which is handled as an 'int'.)  */
748   { "CLOPQ",0,STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
749
750   { "r",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",    "cR",   NULL },
751   { "<>'R",0, STD_C89, NOARGUMENTS, "",      "",   NULL },
752   { "m",   0, STD_C89, NOARGUMENTS, "q",     "",   NULL },
753   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
754 };
755
756 static const format_char_info gcc_gfc_char_table[] =
757 {
758   /* C89 conversion specifiers.  */
759   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "", "", NULL },
760   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "", "", NULL },
761   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "", "", NULL },
762   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q", "cR", NULL },
763
764   /* gfc conversion specifiers.  */
765
766   { "C",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
767
768   /* This will require a "locus" at runtime.  */
769   { "L",   0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "", "R", NULL },
770
771   /* These will require nothing.  */
772   { "<>",0, STD_C89, NOARGUMENTS, "",      "",   NULL },
773   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
774 };
775
776 static const format_char_info scan_char_table[] =
777 {
778   /* C89 conversion specifiers.  */
779   { "di",    1, STD_C89, { T89_I,   T99_SC,  T89_S,   T89_L,   T9L_LL,  TEX_LL,  T99_SST, T99_PD,  T99_IM,  BADLEN,  BADLEN,  BADLEN }, "*w'I", "W",   NULL },
780   { "u",     1, STD_C89, { T89_UI,  T99_UC,  T89_US,  T89_UL,  T9L_ULL, TEX_ULL, T99_ST,  T99_UPD, T99_UIM, BADLEN,  BADLEN,  BADLEN }, "*w'I", "W",   NULL },
781   { "oxX",   1, STD_C89, { T89_UI,  T99_UC,  T89_US,  T89_UL,  T9L_ULL, TEX_ULL, T99_ST,  T99_UPD, T99_UIM, BADLEN,  BADLEN,  BADLEN }, "*w",   "W",   NULL },
782   { "efgEG", 1, STD_C89, { T89_F,   BADLEN,  BADLEN,  T89_D,   BADLEN,  T89_LD,  BADLEN,  BADLEN,  BADLEN,  TEX_D32, TEX_D64, TEX_D128 }, "*w'",  "W",   NULL },
783   { "c",     1, STD_C89, { T89_C,   BADLEN,  BADLEN,  T94_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*mw",   "cW",  NULL },
784   { "s",     1, STD_C89, { T89_C,   BADLEN,  BADLEN,  T94_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*amw",  "cW",  NULL },
785   { "[",     1, STD_C89, { T89_C,   BADLEN,  BADLEN,  T94_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*amw",  "cW[", NULL },
786   { "p",     2, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*w",   "W",   NULL },
787   { "n",     1, STD_C89, { T89_I,   T99_SC,  T89_S,   T89_L,   T9L_LL,  BADLEN,  T99_SST, T99_PD,  T99_IM,  BADLEN,  BADLEN,  BADLEN }, "",     "W",   NULL },
788   /* C99 conversion specifiers.  */
789   { "F",   1, STD_C99, { T99_F,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T99_LD,  BADLEN,  BADLEN,  BADLEN,  TEX_D32, TEX_D64, TEX_D128 }, "*w'",  "W",   NULL },
790   { "aA",   1, STD_C99, { T99_F,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T99_LD,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*w'",  "W",   NULL },
791   /* X/Open conversion specifiers.  */
792   { "C",     1, STD_EXT, { TEX_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*mw",   "W",   NULL },
793   { "S",     1, STD_EXT, { TEX_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*amw",  "W",   NULL },
794   { NULL, 0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
795 };
796
797 static const format_char_info time_char_table[] =
798 {
799   /* C89 conversion specifiers.  */
800   { "ABZab",            0, STD_C89, NOLENGTHS, "^#",     "",   NULL },
801   { "cx",               0, STD_C89, NOLENGTHS, "E",      "3",  NULL },
802   { "HIMSUWdmw",        0, STD_C89, NOLENGTHS, "-_0Ow",  "",   NULL },
803   { "j",                0, STD_C89, NOLENGTHS, "-_0Ow",  "o",  NULL },
804   { "p",                0, STD_C89, NOLENGTHS, "#",      "",   NULL },
805   { "X",                0, STD_C89, NOLENGTHS, "E",      "",   NULL },
806   { "y",                0, STD_C89, NOLENGTHS, "EO-_0w", "4",  NULL },
807   { "Y",                0, STD_C89, NOLENGTHS, "-_0EOw", "o",  NULL },
808   { "%",                0, STD_C89, NOLENGTHS, "",       "",   NULL },
809   /* C99 conversion specifiers.  */
810   { "C",                0, STD_C99, NOLENGTHS, "-_0EOw", "o",  NULL },
811   { "D",                0, STD_C99, NOLENGTHS, "",       "2",  NULL },
812   { "eVu",              0, STD_C99, NOLENGTHS, "-_0Ow",  "",   NULL },
813   { "FRTnrt",           0, STD_C99, NOLENGTHS, "",       "",   NULL },
814   { "g",                0, STD_C99, NOLENGTHS, "O-_0w",  "2o", NULL },
815   { "G",                0, STD_C99, NOLENGTHS, "-_0Ow",  "o",  NULL },
816   { "h",                0, STD_C99, NOLENGTHS, "^#",     "",   NULL },
817   { "z",                0, STD_C99, NOLENGTHS, "O",      "o",  NULL },
818   /* GNU conversion specifiers.  */
819   { "kls",              0, STD_EXT, NOLENGTHS, "-_0Ow",  "",   NULL },
820   { "P",                0, STD_EXT, NOLENGTHS, "",       "",   NULL },
821   /* DragonFly/FreeBSD conversion specifiers. */
822   { "+",                0, STD_EXT, NOLENGTHS, "E",      "3",  NULL },
823   { NULL,               0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
824 };
825
826 static const format_char_info monetary_char_table[] =
827 {
828   { "in", 0, STD_C89, { T89_D, BADLEN, BADLEN, BADLEN, BADLEN, T89_LD, BADLEN, BADLEN, BADLEN, BADLEN, BADLEN, BADLEN }, "=^+(!-w#p", "", NULL },
829   { NULL, 0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
830 };
831
832 /* This must be in the same order as enum format_type.  */
833 static const format_kind_info format_types_orig[] =
834 {
835   { "gnu_printf",   printf_length_specs,  print_char_table, " +#0-'I", NULL,
836     printf_flag_specs, printf_flag_pairs,
837     FMT_FLAG_ARG_CONVERT|FMT_FLAG_DOLLAR_MULTIPLE|FMT_FLAG_USE_DOLLAR|FMT_FLAG_EMPTY_PREC_OK,
838     'w', 0, 'p', 0, 'L', 0,
839     &integer_type_node, &integer_type_node
840   },
841   { "asm_fprintf",   asm_fprintf_length_specs,  asm_fprintf_char_table, " +#0-", NULL,
842     asm_fprintf_flag_specs, asm_fprintf_flag_pairs,
843     FMT_FLAG_ARG_CONVERT|FMT_FLAG_EMPTY_PREC_OK,
844     'w', 0, 'p', 0, 'L', 0,
845     NULL, NULL
846   },
847   { "gcc_diag",   gcc_diag_length_specs,  gcc_diag_char_table, "q+#", NULL,
848     gcc_diag_flag_specs, gcc_diag_flag_pairs,
849     FMT_FLAG_ARG_CONVERT,
850     0, 0, 'p', 0, 'L', 0,
851     NULL, &integer_type_node
852   },
853   { "gcc_tdiag",   gcc_tdiag_length_specs,  gcc_tdiag_char_table, "q+#", NULL,
854     gcc_tdiag_flag_specs, gcc_tdiag_flag_pairs,
855     FMT_FLAG_ARG_CONVERT,
856     0, 0, 'p', 0, 'L', 0,
857     NULL, &integer_type_node
858   },
859   { "gcc_cdiag",   gcc_cdiag_length_specs,  gcc_cdiag_char_table, "q+#", NULL,
860     gcc_cdiag_flag_specs, gcc_cdiag_flag_pairs,
861     FMT_FLAG_ARG_CONVERT,
862     0, 0, 'p', 0, 'L', 0,
863     NULL, &integer_type_node
864   },
865   { "gcc_cxxdiag",   gcc_cxxdiag_length_specs,  gcc_cxxdiag_char_table, "q+#", NULL,
866     gcc_cxxdiag_flag_specs, gcc_cxxdiag_flag_pairs,
867     FMT_FLAG_ARG_CONVERT,
868     0, 0, 'p', 0, 'L', 0,
869     NULL, &integer_type_node
870   },
871   { "gcc_gfc", gcc_gfc_length_specs, gcc_gfc_char_table, "q+#", NULL,
872     gcc_gfc_flag_specs, gcc_gfc_flag_pairs,
873     FMT_FLAG_ARG_CONVERT,
874     0, 0, 0, 0, 0, 0,
875     NULL, NULL
876   },
877   { "NSString",   NULL,  NULL, NULL, NULL,
878     NULL, NULL,
879     FMT_FLAG_ARG_CONVERT|FMT_FLAG_PARSE_ARG_CONVERT_EXTERNAL, 0, 0, 0, 0, 0, 0,
880     NULL, NULL
881   },
882   { "gnu_scanf",    scanf_length_specs,   scan_char_table,  "*'I", NULL,
883     scanf_flag_specs, scanf_flag_pairs,
884     FMT_FLAG_ARG_CONVERT|FMT_FLAG_SCANF_A_KLUDGE|FMT_FLAG_USE_DOLLAR|FMT_FLAG_ZERO_WIDTH_BAD|FMT_FLAG_DOLLAR_GAP_POINTER_OK,
885     'w', 0, 0, '*', 'L', 'm',
886     NULL, NULL
887   },
888   { "gnu_strftime", NULL,                 time_char_table,  "_-0^#", "EO",
889     strftime_flag_specs, strftime_flag_pairs,
890     FMT_FLAG_FANCY_PERCENT_OK, 'w', 0, 0, 0, 0, 0,
891     NULL, NULL
892   },
893   { "gnu_strfmon",  strfmon_length_specs, monetary_char_table, "=^+(!-", NULL,
894     strfmon_flag_specs, strfmon_flag_pairs,
895     FMT_FLAG_ARG_CONVERT, 'w', '#', 'p', 0, 'L', 0,
896     NULL, NULL
897   }
898 };
899
900 /* This layer of indirection allows GCC to reassign format_types with
901    new data if necessary, while still allowing the original data to be
902    const.  */
903 static const format_kind_info *format_types = format_types_orig;
904 /* We can modify this one.  We also add target-specific format types
905    to the end of the array.  */
906 static format_kind_info *dynamic_format_types;
907
908 static int n_format_types = ARRAY_SIZE (format_types_orig);
909
910 /* Structure detailing the results of checking a format function call
911    where the format expression may be a conditional expression with
912    many leaves resulting from nested conditional expressions.  */
913 typedef struct
914 {
915   /* Number of leaves of the format argument that could not be checked
916      as they were not string literals.  */
917   int number_non_literal;
918   /* Number of leaves of the format argument that were null pointers or
919      string literals, but had extra format arguments.  */
920   int number_extra_args;
921   location_t extra_arg_loc;
922   /* Number of leaves of the format argument that were null pointers or
923      string literals, but had extra format arguments and used $ operand
924      numbers.  */
925   int number_dollar_extra_args;
926   /* Number of leaves of the format argument that were wide string
927      literals.  */
928   int number_wide;
929   /* Number of leaves of the format argument that were empty strings.  */
930   int number_empty;
931   /* Number of leaves of the format argument that were unterminated
932      strings.  */
933   int number_unterminated;
934   /* Number of leaves of the format argument that were not counted above.  */
935   int number_other;
936   /* Location of the format string.  */
937   location_t format_string_loc;
938 } format_check_results;
939
940 typedef struct
941 {
942   format_check_results *res;
943   function_format_info *info;
944   tree params;
945 } format_check_context;
946
947 /* Return the format name (as specified in the original table) for the format
948    type indicated by format_num.  */
949 static const char *
950 format_name (int format_num)
951 {
952   if (format_num >= 0 && format_num < n_format_types)
953     return format_types[format_num].name;
954   gcc_unreachable ();
955 }
956
957 /* Return the format flags (as specified in the original table) for the format
958    type indicated by format_num.  */
959 static int
960 format_flags (int format_num)
961 {
962   if (format_num >= 0 && format_num < n_format_types)
963     return format_types[format_num].flags;
964   gcc_unreachable ();
965 }
966
967 static void check_format_info (function_format_info *, tree);
968 static void check_format_arg (void *, tree, unsigned HOST_WIDE_INT);
969 static void check_format_info_main (format_check_results *,
970                                     function_format_info *,
971                                     const char *, int, tree,
972                                     unsigned HOST_WIDE_INT, alloc_pool);
973
974 static void init_dollar_format_checking (int, tree);
975 static int maybe_read_dollar_number (const char **, int,
976                                      tree, tree *, const format_kind_info *);
977 static bool avoid_dollar_number (const char *);
978 static void finish_dollar_format_checking (format_check_results *, int);
979
980 static const format_flag_spec *get_flag_spec (const format_flag_spec *,
981                                               int, const char *);
982
983 static void check_format_types (location_t, format_wanted_type *);
984 static void format_type_warning (location_t, format_wanted_type *, tree, tree);
985
986 /* Decode a format type from a string, returning the type, or
987    format_type_error if not valid, in which case the caller should print an
988    error message.  */
989 static int
990 decode_format_type (const char *s)
991 {
992   int i;
993   int slen;
994
995   s = convert_format_name_to_system_name (s);
996   slen = strlen (s);
997   for (i = 0; i < n_format_types; i++)
998     {
999       int alen;
1000       if (!strcmp (s, format_types[i].name))
1001         return i;
1002       alen = strlen (format_types[i].name);
1003       if (slen == alen + 4 && s[0] == '_' && s[1] == '_'
1004           && s[slen - 1] == '_' && s[slen - 2] == '_'
1005           && !strncmp (s + 2, format_types[i].name, alen))
1006         return i;
1007     }
1008   return format_type_error;
1009 }
1010
1011 \f
1012 /* Check the argument list of a call to printf, scanf, etc.
1013    ATTRS are the attributes on the function type.  There are NARGS argument
1014    values in the array ARGARRAY.
1015    Also, if -Wsuggest-attribute=format,
1016    warn for calls to vprintf or vscanf in functions with no such format
1017    attribute themselves.  */
1018
1019 void
1020 check_function_format (tree attrs, int nargs, tree *argarray)
1021 {
1022   tree a;
1023
1024   /* See if this function has any format attributes.  */
1025   for (a = attrs; a; a = TREE_CHAIN (a))
1026     {
1027       if (is_attribute_p ("format", TREE_PURPOSE (a)))
1028         {
1029           /* Yup; check it.  */
1030           function_format_info info;
1031           decode_format_attr (TREE_VALUE (a), &info, /*validated=*/true);
1032           if (warn_format)
1033             {
1034               /* FIXME: Rewrite all the internal functions in this file
1035                  to use the ARGARRAY directly instead of constructing this
1036                  temporary list.  */
1037               tree params = NULL_TREE;
1038               int i;
1039               for (i = nargs - 1; i >= 0; i--)
1040                 params = tree_cons (NULL_TREE, argarray[i], params);
1041               check_format_info (&info, params);
1042             }
1043           if (warn_suggest_attribute_format && info.first_arg_num == 0
1044               && (format_types[info.format_type].flags
1045                   & (int) FMT_FLAG_ARG_CONVERT))
1046             {
1047               tree c;
1048               for (c = TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl));
1049                    c;
1050                    c = TREE_CHAIN (c))
1051                 if (is_attribute_p ("format", TREE_PURPOSE (c))
1052                     && (decode_format_type (IDENTIFIER_POINTER
1053                                             (TREE_VALUE (TREE_VALUE (c))))
1054                         == info.format_type))
1055                   break;
1056               if (c == NULL_TREE)
1057                 {
1058                   /* Check if the current function has a parameter to which
1059                      the format attribute could be attached; if not, it
1060                      can't be a candidate for a format attribute, despite
1061                      the vprintf-like or vscanf-like call.  */
1062                   tree args;
1063                   for (args = DECL_ARGUMENTS (current_function_decl);
1064                        args != 0;
1065                        args = DECL_CHAIN (args))
1066                     {
1067                       if (TREE_CODE (TREE_TYPE (args)) == POINTER_TYPE
1068                           && (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (args)))
1069                               == char_type_node))
1070                         break;
1071                     }
1072                   if (args != 0)
1073                     warning (OPT_Wsuggest_attribute_format, "function might "
1074                              "be possible candidate for %qs format attribute",
1075                              format_types[info.format_type].name);
1076                 }
1077             }
1078         }
1079     }
1080 }
1081
1082
1083 /* Variables used by the checking of $ operand number formats.  */
1084 static char *dollar_arguments_used = NULL;
1085 static char *dollar_arguments_pointer_p = NULL;
1086 static int dollar_arguments_alloc = 0;
1087 static int dollar_arguments_count;
1088 static int dollar_first_arg_num;
1089 static int dollar_max_arg_used;
1090 static int dollar_format_warned;
1091
1092 /* Initialize the checking for a format string that may contain $
1093    parameter number specifications; we will need to keep track of whether
1094    each parameter has been used.  FIRST_ARG_NUM is the number of the first
1095    argument that is a parameter to the format, or 0 for a vprintf-style
1096    function; PARAMS is the list of arguments starting at this argument.  */
1097
1098 static void
1099 init_dollar_format_checking (int first_arg_num, tree params)
1100 {
1101   tree oparams = params;
1102
1103   dollar_first_arg_num = first_arg_num;
1104   dollar_arguments_count = 0;
1105   dollar_max_arg_used = 0;
1106   dollar_format_warned = 0;
1107   if (first_arg_num > 0)
1108     {
1109       while (params)
1110         {
1111           dollar_arguments_count++;
1112           params = TREE_CHAIN (params);
1113         }
1114     }
1115   if (dollar_arguments_alloc < dollar_arguments_count)
1116     {
1117       free (dollar_arguments_used);
1118       free (dollar_arguments_pointer_p);
1119       dollar_arguments_alloc = dollar_arguments_count;
1120       dollar_arguments_used = XNEWVEC (char, dollar_arguments_alloc);
1121       dollar_arguments_pointer_p = XNEWVEC (char, dollar_arguments_alloc);
1122     }
1123   if (dollar_arguments_alloc)
1124     {
1125       memset (dollar_arguments_used, 0, dollar_arguments_alloc);
1126       if (first_arg_num > 0)
1127         {
1128           int i = 0;
1129           params = oparams;
1130           while (params)
1131             {
1132               dollar_arguments_pointer_p[i] = (TREE_CODE (TREE_TYPE (TREE_VALUE (params)))
1133                                                == POINTER_TYPE);
1134               params = TREE_CHAIN (params);
1135               i++;
1136             }
1137         }
1138     }
1139 }
1140
1141
1142 /* Look for a decimal number followed by a $ in *FORMAT.  If DOLLAR_NEEDED
1143    is set, it is an error if one is not found; otherwise, it is OK.  If
1144    such a number is found, check whether it is within range and mark that
1145    numbered operand as being used for later checking.  Returns the operand
1146    number if found and within range, zero if no such number was found and
1147    this is OK, or -1 on error.  PARAMS points to the first operand of the
1148    format; PARAM_PTR is made to point to the parameter referred to.  If
1149    a $ format is found, *FORMAT is updated to point just after it.  */
1150
1151 static int
1152 maybe_read_dollar_number (const char **format,
1153                           int dollar_needed, tree params, tree *param_ptr,
1154                           const format_kind_info *fki)
1155 {
1156   int argnum;
1157   int overflow_flag;
1158   const char *fcp = *format;
1159   if (!ISDIGIT (*fcp))
1160     {
1161       if (dollar_needed)
1162         {
1163           warning (OPT_Wformat_, "missing $ operand number in format");
1164           return -1;
1165         }
1166       else
1167         return 0;
1168     }
1169   argnum = 0;
1170   overflow_flag = 0;
1171   while (ISDIGIT (*fcp))
1172     {
1173       int nargnum;
1174       nargnum = 10 * argnum + (*fcp - '0');
1175       if (nargnum < 0 || nargnum / 10 != argnum)
1176         overflow_flag = 1;
1177       argnum = nargnum;
1178       fcp++;
1179     }
1180   if (*fcp != '$')
1181     {
1182       if (dollar_needed)
1183         {
1184           warning (OPT_Wformat_, "missing $ operand number in format");
1185           return -1;
1186         }
1187       else
1188         return 0;
1189     }
1190   *format = fcp + 1;
1191   if (pedantic && !dollar_format_warned)
1192     {
1193       warning (OPT_Wformat_, "%s does not support %%n$ operand number formats",
1194                C_STD_NAME (STD_EXT));
1195       dollar_format_warned = 1;
1196     }
1197   if (overflow_flag || argnum == 0
1198       || (dollar_first_arg_num && argnum > dollar_arguments_count))
1199     {
1200       warning (OPT_Wformat_, "operand number out of range in format");
1201       return -1;
1202     }
1203   if (argnum > dollar_max_arg_used)
1204     dollar_max_arg_used = argnum;
1205   /* For vprintf-style functions we may need to allocate more memory to
1206      track which arguments are used.  */
1207   while (dollar_arguments_alloc < dollar_max_arg_used)
1208     {
1209       int nalloc;
1210       nalloc = 2 * dollar_arguments_alloc + 16;
1211       dollar_arguments_used = XRESIZEVEC (char, dollar_arguments_used,
1212                                           nalloc);
1213       dollar_arguments_pointer_p = XRESIZEVEC (char, dollar_arguments_pointer_p,
1214                                                nalloc);
1215       memset (dollar_arguments_used + dollar_arguments_alloc, 0,
1216               nalloc - dollar_arguments_alloc);
1217       dollar_arguments_alloc = nalloc;
1218     }
1219   if (!(fki->flags & (int) FMT_FLAG_DOLLAR_MULTIPLE)
1220       && dollar_arguments_used[argnum - 1] == 1)
1221     {
1222       dollar_arguments_used[argnum - 1] = 2;
1223       warning (OPT_Wformat_, "format argument %d used more than once in %s format",
1224                argnum, fki->name);
1225     }
1226   else
1227     dollar_arguments_used[argnum - 1] = 1;
1228   if (dollar_first_arg_num)
1229     {
1230       int i;
1231       *param_ptr = params;
1232       for (i = 1; i < argnum && *param_ptr != 0; i++)
1233         *param_ptr = TREE_CHAIN (*param_ptr);
1234
1235       /* This case shouldn't be caught here.  */
1236       gcc_assert (*param_ptr);
1237     }
1238   else
1239     *param_ptr = 0;
1240   return argnum;
1241 }
1242
1243 /* Ensure that FORMAT does not start with a decimal number followed by
1244    a $; give a diagnostic and return true if it does, false otherwise.  */
1245
1246 static bool
1247 avoid_dollar_number (const char *format)
1248 {
1249   if (!ISDIGIT (*format))
1250     return false;
1251   while (ISDIGIT (*format))
1252     format++;
1253   if (*format == '$')
1254     {
1255       warning (OPT_Wformat_, "$ operand number used after format without operand number");
1256       return true;
1257     }
1258   return false;
1259 }
1260
1261
1262 /* Finish the checking for a format string that used $ operand number formats
1263    instead of non-$ formats.  We check for unused operands before used ones
1264    (a serious error, since the implementation of the format function
1265    can't know what types to pass to va_arg to find the later arguments).
1266    and for unused operands at the end of the format (if we know how many
1267    arguments the format had, so not for vprintf).  If there were operand
1268    numbers out of range on a non-vprintf-style format, we won't have reached
1269    here.  If POINTER_GAP_OK, unused arguments are OK if all arguments are
1270    pointers.  */
1271
1272 static void
1273 finish_dollar_format_checking (format_check_results *res, int pointer_gap_ok)
1274 {
1275   int i;
1276   bool found_pointer_gap = false;
1277   for (i = 0; i < dollar_max_arg_used; i++)
1278     {
1279       if (!dollar_arguments_used[i])
1280         {
1281           if (pointer_gap_ok && (dollar_first_arg_num == 0
1282                                  || dollar_arguments_pointer_p[i]))
1283             found_pointer_gap = true;
1284           else
1285             warning_at (res->format_string_loc, OPT_Wformat_,
1286                         "format argument %d unused before used argument %d in $-style format",
1287                         i + 1, dollar_max_arg_used);
1288         }
1289     }
1290   if (found_pointer_gap
1291       || (dollar_first_arg_num
1292           && dollar_max_arg_used < dollar_arguments_count))
1293     {
1294       res->number_other--;
1295       res->number_dollar_extra_args++;
1296     }
1297 }
1298
1299
1300 /* Retrieve the specification for a format flag.  SPEC contains the
1301    specifications for format flags for the applicable kind of format.
1302    FLAG is the flag in question.  If PREDICATES is NULL, the basic
1303    spec for that flag must be retrieved and must exist.  If
1304    PREDICATES is not NULL, it is a string listing possible predicates
1305    for the spec entry; if an entry predicated on any of these is
1306    found, it is returned, otherwise NULL is returned.  */
1307
1308 static const format_flag_spec *
1309 get_flag_spec (const format_flag_spec *spec, int flag, const char *predicates)
1310 {
1311   int i;
1312   for (i = 0; spec[i].flag_char != 0; i++)
1313     {
1314       if (spec[i].flag_char != flag)
1315         continue;
1316       if (predicates != NULL)
1317         {
1318           if (spec[i].predicate != 0
1319               && strchr (predicates, spec[i].predicate) != 0)
1320             return &spec[i];
1321         }
1322       else if (spec[i].predicate == 0)
1323         return &spec[i];
1324     }
1325   gcc_assert (predicates);
1326   return NULL;
1327 }
1328
1329
1330 /* Check the argument list of a call to printf, scanf, etc.
1331    INFO points to the function_format_info structure.
1332    PARAMS is the list of argument values.  */
1333
1334 static void
1335 check_format_info (function_format_info *info, tree params)
1336 {
1337   format_check_context format_ctx;
1338   unsigned HOST_WIDE_INT arg_num;
1339   tree format_tree;
1340   format_check_results res;
1341   /* Skip to format argument.  If the argument isn't available, there's
1342      no work for us to do; prototype checking will catch the problem.  */
1343   for (arg_num = 1; ; ++arg_num)
1344     {
1345       if (params == 0)
1346         return;
1347       if (arg_num == info->format_num)
1348         break;
1349       params = TREE_CHAIN (params);
1350     }
1351   format_tree = TREE_VALUE (params);
1352   params = TREE_CHAIN (params);
1353   if (format_tree == 0)
1354     return;
1355
1356   res.number_non_literal = 0;
1357   res.number_extra_args = 0;
1358   res.extra_arg_loc = UNKNOWN_LOCATION;
1359   res.number_dollar_extra_args = 0;
1360   res.number_wide = 0;
1361   res.number_empty = 0;
1362   res.number_unterminated = 0;
1363   res.number_other = 0;
1364   res.format_string_loc = input_location;
1365
1366   format_ctx.res = &res;
1367   format_ctx.info = info;
1368   format_ctx.params = params;
1369
1370   check_function_arguments_recurse (check_format_arg, &format_ctx,
1371                                     format_tree, arg_num);
1372
1373   location_t loc = format_ctx.res->format_string_loc;
1374   if (res.extra_arg_loc == UNKNOWN_LOCATION)
1375     res.extra_arg_loc = loc;
1376
1377   if (res.number_non_literal > 0)
1378     {
1379       /* Functions taking a va_list normally pass a non-literal format
1380          string.  These functions typically are declared with
1381          first_arg_num == 0, so avoid warning in those cases.  */
1382       if (!(format_types[info->format_type].flags & (int) FMT_FLAG_ARG_CONVERT))
1383         {
1384           /* For strftime-like formats, warn for not checking the format
1385              string; but there are no arguments to check.  */
1386           warning_at (loc, OPT_Wformat_nonliteral,
1387                       "format not a string literal, format string not checked");
1388         }
1389       else if (info->first_arg_num != 0)
1390         {
1391           /* If there are no arguments for the format at all, we may have
1392              printf (foo) which is likely to be a security hole.  */
1393           while (arg_num + 1 < info->first_arg_num)
1394             {
1395               if (params == 0)
1396                 break;
1397               params = TREE_CHAIN (params);
1398               ++arg_num;
1399             }
1400           if (params == 0 && warn_format_security)
1401             warning_at (loc, OPT_Wformat_security,
1402                         "format not a string literal and no format arguments");
1403           else if (params == 0 && warn_format_nonliteral)
1404             warning_at (loc, OPT_Wformat_nonliteral,
1405                         "format not a string literal and no format arguments");
1406           else
1407             warning_at (loc, OPT_Wformat_nonliteral,
1408                         "format not a string literal, argument types not checked");
1409         }
1410     }
1411
1412   /* If there were extra arguments to the format, normally warn.  However,
1413      the standard does say extra arguments are ignored, so in the specific
1414      case where we have multiple leaves (conditional expressions or
1415      ngettext) allow extra arguments if at least one leaf didn't have extra
1416      arguments, but was otherwise OK (either non-literal or checked OK).
1417      If the format is an empty string, this should be counted similarly to the
1418      case of extra format arguments.  */
1419   if (res.number_extra_args > 0 && res.number_non_literal == 0
1420       && res.number_other == 0)
1421     warning_at (res.extra_arg_loc, OPT_Wformat_extra_args,
1422                 "too many arguments for format");
1423   if (res.number_dollar_extra_args > 0 && res.number_non_literal == 0
1424       && res.number_other == 0)
1425     warning_at (loc, OPT_Wformat_extra_args, "unused arguments in $-style format");
1426   if (res.number_empty > 0 && res.number_non_literal == 0
1427       && res.number_other == 0)
1428     warning_at (loc, OPT_Wformat_zero_length, "zero-length %s format string",
1429              format_types[info->format_type].name);
1430
1431   if (res.number_wide > 0)
1432     warning_at (loc, OPT_Wformat_, "format is a wide character string");
1433
1434   if (res.number_unterminated > 0)
1435     warning_at (loc, OPT_Wformat_, "unterminated format string");
1436 }
1437
1438 /* Callback from check_function_arguments_recurse to check a
1439    format string.  FORMAT_TREE is the format parameter.  ARG_NUM
1440    is the number of the format argument.  CTX points to a
1441    format_check_context.  */
1442
1443 static void
1444 check_format_arg (void *ctx, tree format_tree,
1445                   unsigned HOST_WIDE_INT arg_num)
1446 {
1447   format_check_context *format_ctx = (format_check_context *) ctx;
1448   format_check_results *res = format_ctx->res;
1449   function_format_info *info = format_ctx->info;
1450   tree params = format_ctx->params;
1451
1452   int format_length;
1453   HOST_WIDE_INT offset;
1454   const char *format_chars;
1455   tree array_size = 0;
1456   tree array_init;
1457   alloc_pool fwt_pool;
1458
1459   if (TREE_CODE (format_tree) == VAR_DECL)
1460     {
1461       /* Pull out a constant value if the front end didn't.  */
1462       format_tree = decl_constant_value (format_tree);
1463       STRIP_NOPS (format_tree);
1464     }
1465
1466   if (integer_zerop (format_tree))
1467     {
1468       /* Skip to first argument to check, so we can see if this format
1469          has any arguments (it shouldn't).  */
1470       while (arg_num + 1 < info->first_arg_num)
1471         {
1472           if (params == 0)
1473             return;
1474           params = TREE_CHAIN (params);
1475           ++arg_num;
1476         }
1477
1478       if (params == 0)
1479         res->number_other++;
1480       else 
1481         {
1482           if (res->number_extra_args == 0)
1483             res->extra_arg_loc = EXPR_LOC_OR_LOC (TREE_VALUE (params),
1484                                                   input_location);
1485           res->number_extra_args++;
1486         }
1487       return;
1488     }
1489
1490   offset = 0;
1491   if (TREE_CODE (format_tree) == POINTER_PLUS_EXPR)
1492     {
1493       tree arg0, arg1;
1494
1495       arg0 = TREE_OPERAND (format_tree, 0);
1496       arg1 = TREE_OPERAND (format_tree, 1);
1497       STRIP_NOPS (arg0);
1498       STRIP_NOPS (arg1);
1499       if (TREE_CODE (arg1) == INTEGER_CST)
1500         format_tree = arg0;
1501       else
1502         {
1503           res->number_non_literal++;
1504           return;
1505         }
1506       /* POINTER_PLUS_EXPR offsets are to be interpreted signed.  */
1507       if (!cst_and_fits_in_hwi (arg1))
1508         {
1509           res->number_non_literal++;
1510           return;
1511         }
1512       offset = int_cst_value (arg1);
1513     }
1514   if (TREE_CODE (format_tree) != ADDR_EXPR)
1515     {
1516       res->number_non_literal++;
1517       return;
1518     }
1519   res->format_string_loc = EXPR_LOC_OR_LOC (format_tree, input_location);
1520   format_tree = TREE_OPERAND (format_tree, 0);
1521   if (format_types[info->format_type].flags 
1522       & (int) FMT_FLAG_PARSE_ARG_CONVERT_EXTERNAL)
1523     {
1524       bool objc_str = (info->format_type == gcc_objc_string_format_type);
1525       /* We cannot examine this string here - but we can check that it is
1526          a valid type.  */
1527       if (TREE_CODE (format_tree) != CONST_DECL
1528           || !((objc_str && objc_string_ref_type_p (TREE_TYPE (format_tree)))
1529                 || (*targetcm.string_object_ref_type_p) 
1530                                      ((const_tree) TREE_TYPE (format_tree))))
1531         {
1532           res->number_non_literal++;
1533           return;
1534         }
1535       /* Skip to first argument to check.  */
1536       while (arg_num + 1 < info->first_arg_num)
1537         {
1538           if (params == 0)
1539             return;
1540           params = TREE_CHAIN (params);
1541           ++arg_num;
1542         }
1543       /* So, we have a valid literal string object and one or more params.
1544          We need to use an external helper to parse the string into format
1545          info.  For Objective-C variants we provide the resource within the
1546          objc tree, for target variants, via a hook.  */
1547       if (objc_str)
1548         objc_check_format_arg (format_tree, params);
1549       else if (targetcm.check_string_object_format_arg)
1550         (*targetcm.check_string_object_format_arg) (format_tree, params);
1551       /* Else we can't handle it and retire quietly.  */
1552       return;
1553     }
1554   if (TREE_CODE (format_tree) == ARRAY_REF
1555       && tree_fits_shwi_p (TREE_OPERAND (format_tree, 1))
1556       && (offset += tree_to_shwi (TREE_OPERAND (format_tree, 1))) >= 0)
1557     format_tree = TREE_OPERAND (format_tree, 0);
1558   if (offset < 0)
1559     {
1560       res->number_non_literal++;
1561       return;
1562     }
1563   if (TREE_CODE (format_tree) == VAR_DECL
1564       && TREE_CODE (TREE_TYPE (format_tree)) == ARRAY_TYPE
1565       && (array_init = decl_constant_value (format_tree)) != format_tree
1566       && TREE_CODE (array_init) == STRING_CST)
1567     {
1568       /* Extract the string constant initializer.  Note that this may include
1569          a trailing NUL character that is not in the array (e.g.
1570          const char a[3] = "foo";).  */
1571       array_size = DECL_SIZE_UNIT (format_tree);
1572       format_tree = array_init;
1573     }
1574   if (TREE_CODE (format_tree) != STRING_CST)
1575     {
1576       res->number_non_literal++;
1577       return;
1578     }
1579   if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format_tree))) != char_type_node)
1580     {
1581       res->number_wide++;
1582       return;
1583     }
1584   format_chars = TREE_STRING_POINTER (format_tree);
1585   format_length = TREE_STRING_LENGTH (format_tree);
1586   if (array_size != 0)
1587     {
1588       /* Variable length arrays can't be initialized.  */
1589       gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
1590
1591       if (tree_fits_shwi_p (array_size))
1592         {
1593           HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
1594           if (array_size_value > 0
1595               && array_size_value == (int) array_size_value
1596               && format_length > array_size_value)
1597             format_length = array_size_value;
1598         }
1599     }
1600   if (offset)
1601     {
1602       if (offset >= format_length)
1603         {
1604           res->number_non_literal++;
1605           return;
1606         }
1607       format_chars += offset;
1608       format_length -= offset;
1609     }
1610   if (format_length < 1 || format_chars[--format_length] != 0)
1611     {
1612       res->number_unterminated++;
1613       return;
1614     }
1615   if (format_length == 0)
1616     {
1617       res->number_empty++;
1618       return;
1619     }
1620
1621   /* Skip to first argument to check.  */
1622   while (arg_num + 1 < info->first_arg_num)
1623     {
1624       if (params == 0)
1625         return;
1626       params = TREE_CHAIN (params);
1627       ++arg_num;
1628     }
1629   /* Provisionally increment res->number_other; check_format_info_main
1630      will decrement it if it finds there are extra arguments, but this way
1631      need not adjust it for every return.  */
1632   res->number_other++;
1633   fwt_pool = create_alloc_pool ("format_wanted_type pool",
1634                                 sizeof (format_wanted_type), 10);
1635   check_format_info_main (res, info, format_chars, format_length,
1636                           params, arg_num, fwt_pool);
1637   free_alloc_pool (fwt_pool);
1638 }
1639
1640
1641 /* Do the main part of checking a call to a format function.  FORMAT_CHARS
1642    is the NUL-terminated format string (which at this point may contain
1643    internal NUL characters); FORMAT_LENGTH is its length (excluding the
1644    terminating NUL character).  ARG_NUM is one less than the number of
1645    the first format argument to check; PARAMS points to that format
1646    argument in the list of arguments.  */
1647
1648 static void
1649 check_format_info_main (format_check_results *res,
1650                         function_format_info *info, const char *format_chars,
1651                         int format_length, tree params,
1652                         unsigned HOST_WIDE_INT arg_num, alloc_pool fwt_pool)
1653 {
1654   const char *orig_format_chars = format_chars;
1655   tree first_fillin_param = params;
1656
1657   const format_kind_info *fki = &format_types[info->format_type];
1658   const format_flag_spec *flag_specs = fki->flag_specs;
1659   const format_flag_pair *bad_flag_pairs = fki->bad_flag_pairs;
1660   location_t format_string_loc = res->format_string_loc;
1661
1662   /* -1 if no conversions taking an operand have been found; 0 if one has
1663      and it didn't use $; 1 if $ formats are in use.  */
1664   int has_operand_number = -1;
1665
1666   init_dollar_format_checking (info->first_arg_num, first_fillin_param);
1667
1668   while (*format_chars != 0)
1669     {
1670       int i;
1671       int suppressed = FALSE;
1672       const char *length_chars = NULL;
1673       enum format_lengths length_chars_val = FMT_LEN_none;
1674       enum format_std_version length_chars_std = STD_C89;
1675       int format_char;
1676       tree cur_param;
1677       tree wanted_type;
1678       int main_arg_num = 0;
1679       tree main_arg_params = 0;
1680       enum format_std_version wanted_type_std;
1681       const char *wanted_type_name;
1682       format_wanted_type width_wanted_type;
1683       format_wanted_type precision_wanted_type;
1684       format_wanted_type main_wanted_type;
1685       format_wanted_type *first_wanted_type = NULL;
1686       format_wanted_type *last_wanted_type = NULL;
1687       const format_length_info *fli = NULL;
1688       const format_char_info *fci = NULL;
1689       char flag_chars[256];
1690       int alloc_flag = 0;
1691       int scalar_identity_flag = 0;
1692       const char *format_start;
1693
1694       if (*format_chars++ != '%')
1695         continue;
1696       if (*format_chars == 0)
1697         {
1698           warning_at (format_string_loc, OPT_Wformat_,
1699                       "spurious trailing %<%%%> in format");
1700           continue;
1701         }
1702       if (*format_chars == '%')
1703         {
1704           ++format_chars;
1705           continue;
1706         }
1707       flag_chars[0] = 0;
1708
1709       if ((fki->flags & (int) FMT_FLAG_USE_DOLLAR) && has_operand_number != 0)
1710         {
1711           /* Possibly read a $ operand number at the start of the format.
1712              If one was previously used, one is required here.  If one
1713              is not used here, we can't immediately conclude this is a
1714              format without them, since it could be printf %m or scanf %*.  */
1715           int opnum;
1716           opnum = maybe_read_dollar_number (&format_chars, 0,
1717                                             first_fillin_param,
1718                                             &main_arg_params, fki);
1719           if (opnum == -1)
1720             return;
1721           else if (opnum > 0)
1722             {
1723               has_operand_number = 1;
1724               main_arg_num = opnum + info->first_arg_num - 1;
1725             }
1726         }
1727       else if (fki->flags & FMT_FLAG_USE_DOLLAR)
1728         {
1729           if (avoid_dollar_number (format_chars))
1730             return;
1731         }
1732
1733       /* Read any format flags, but do not yet validate them beyond removing
1734          duplicates, since in general validation depends on the rest of
1735          the format.  */
1736       while (*format_chars != 0
1737              && strchr (fki->flag_chars, *format_chars) != 0)
1738         {
1739           const format_flag_spec *s = get_flag_spec (flag_specs,
1740                                                      *format_chars, NULL);
1741           if (strchr (flag_chars, *format_chars) != 0)
1742             {
1743               warning_at (format_string_loc, OPT_Wformat_,
1744                           "repeated %s in format", _(s->name));
1745             }
1746           else
1747             {
1748               i = strlen (flag_chars);
1749               flag_chars[i++] = *format_chars;
1750               flag_chars[i] = 0;
1751             }
1752           if (s->skip_next_char)
1753             {
1754               ++format_chars;
1755               if (*format_chars == 0)
1756                 {
1757                   warning_at (format_string_loc, OPT_Wformat_,
1758                               "missing fill character at end of strfmon format");
1759                   return;
1760                 }
1761             }
1762           ++format_chars;
1763         }
1764
1765       /* Read any format width, possibly * or *m$.  */
1766       if (fki->width_char != 0)
1767         {
1768           if (fki->width_type != NULL && *format_chars == '*')
1769             {
1770               i = strlen (flag_chars);
1771               flag_chars[i++] = fki->width_char;
1772               flag_chars[i] = 0;
1773               /* "...a field width...may be indicated by an asterisk.
1774                  In this case, an int argument supplies the field width..."  */
1775               ++format_chars;
1776               if (has_operand_number != 0)
1777                 {
1778                   int opnum;
1779                   opnum = maybe_read_dollar_number (&format_chars,
1780                                                     has_operand_number == 1,
1781                                                     first_fillin_param,
1782                                                     &params, fki);
1783                   if (opnum == -1)
1784                     return;
1785                   else if (opnum > 0)
1786                     {
1787                       has_operand_number = 1;
1788                       arg_num = opnum + info->first_arg_num - 1;
1789                     }
1790                   else
1791                     has_operand_number = 0;
1792                 }
1793               else
1794                 {
1795                   if (avoid_dollar_number (format_chars))
1796                     return;
1797                 }
1798               if (info->first_arg_num != 0)
1799                 {
1800                   if (params == 0)
1801                     cur_param = NULL;
1802                   else
1803                     {
1804                       cur_param = TREE_VALUE (params);
1805                       if (has_operand_number <= 0)
1806                         {
1807                           params = TREE_CHAIN (params);
1808                           ++arg_num;
1809                         }
1810                     }
1811                   width_wanted_type.wanted_type = *fki->width_type;
1812                   width_wanted_type.wanted_type_name = NULL;
1813                   width_wanted_type.pointer_count = 0;
1814                   width_wanted_type.char_lenient_flag = 0;
1815                   width_wanted_type.scalar_identity_flag = 0;
1816                   width_wanted_type.writing_in_flag = 0;
1817                   width_wanted_type.reading_from_flag = 0;
1818                   width_wanted_type.kind = CF_KIND_FIELD_WIDTH;
1819                   width_wanted_type.format_start = format_chars - 1;
1820                   width_wanted_type.format_length = 1;
1821                   width_wanted_type.param = cur_param;
1822                   width_wanted_type.arg_num = arg_num;
1823                   width_wanted_type.next = NULL;
1824                   if (last_wanted_type != 0)
1825                     last_wanted_type->next = &width_wanted_type;
1826                   if (first_wanted_type == 0)
1827                     first_wanted_type = &width_wanted_type;
1828                   last_wanted_type = &width_wanted_type;
1829                 }
1830             }
1831           else
1832             {
1833               /* Possibly read a numeric width.  If the width is zero,
1834                  we complain if appropriate.  */
1835               int non_zero_width_char = FALSE;
1836               int found_width = FALSE;
1837               while (ISDIGIT (*format_chars))
1838                 {
1839                   found_width = TRUE;
1840                   if (*format_chars != '0')
1841                     non_zero_width_char = TRUE;
1842                   ++format_chars;
1843                 }
1844               if (found_width && !non_zero_width_char &&
1845                   (fki->flags & (int) FMT_FLAG_ZERO_WIDTH_BAD))
1846                 warning_at (format_string_loc, OPT_Wformat_,
1847                             "zero width in %s format", fki->name);
1848               if (found_width)
1849                 {
1850                   i = strlen (flag_chars);
1851                   flag_chars[i++] = fki->width_char;
1852                   flag_chars[i] = 0;
1853                 }
1854             }
1855         }
1856
1857       /* Read any format left precision (must be a number, not *).  */
1858       if (fki->left_precision_char != 0 && *format_chars == '#')
1859         {
1860           ++format_chars;
1861           i = strlen (flag_chars);
1862           flag_chars[i++] = fki->left_precision_char;
1863           flag_chars[i] = 0;
1864           if (!ISDIGIT (*format_chars))
1865             warning_at (format_string_loc, OPT_Wformat_,
1866                         "empty left precision in %s format", fki->name);
1867           while (ISDIGIT (*format_chars))
1868             ++format_chars;
1869         }
1870
1871       /* Read any format precision, possibly * or *m$.  */
1872       if (fki->precision_char != 0 && *format_chars == '.')
1873         {
1874           ++format_chars;
1875           i = strlen (flag_chars);
1876           flag_chars[i++] = fki->precision_char;
1877           flag_chars[i] = 0;
1878           if (fki->precision_type != NULL && *format_chars == '*')
1879             {
1880               /* "...a...precision...may be indicated by an asterisk.
1881                  In this case, an int argument supplies the...precision."  */
1882               ++format_chars;
1883               if (has_operand_number != 0)
1884                 {
1885                   int opnum;
1886                   opnum = maybe_read_dollar_number (&format_chars,
1887                                                     has_operand_number == 1,
1888                                                     first_fillin_param,
1889                                                     &params, fki);
1890                   if (opnum == -1)
1891                     return;
1892                   else if (opnum > 0)
1893                     {
1894                       has_operand_number = 1;
1895                       arg_num = opnum + info->first_arg_num - 1;
1896                     }
1897                   else
1898                     has_operand_number = 0;
1899                 }
1900               else
1901                 {
1902                   if (avoid_dollar_number (format_chars))
1903                     return;
1904                 }
1905               if (info->first_arg_num != 0)
1906                 {
1907                   if (params == 0)
1908                     cur_param = NULL;
1909                   else
1910                     {
1911                       cur_param = TREE_VALUE (params);
1912                       if (has_operand_number <= 0)
1913                         {
1914                           params = TREE_CHAIN (params);
1915                           ++arg_num;
1916                         }
1917                     }
1918                   precision_wanted_type.wanted_type = *fki->precision_type;
1919                   precision_wanted_type.wanted_type_name = NULL;
1920                   precision_wanted_type.pointer_count = 0;
1921                   precision_wanted_type.char_lenient_flag = 0;
1922                   precision_wanted_type.scalar_identity_flag = 0;
1923                   precision_wanted_type.writing_in_flag = 0;
1924                   precision_wanted_type.reading_from_flag = 0;
1925                   precision_wanted_type.kind = CF_KIND_FIELD_PRECISION;
1926                   precision_wanted_type.param = cur_param;
1927                   precision_wanted_type.format_start = format_chars - 2;
1928                   precision_wanted_type.format_length = 2;
1929                   precision_wanted_type.arg_num = arg_num;
1930                   precision_wanted_type.next = NULL;
1931                   if (last_wanted_type != 0)
1932                     last_wanted_type->next = &precision_wanted_type;
1933                   if (first_wanted_type == 0)
1934                     first_wanted_type = &precision_wanted_type;
1935                   last_wanted_type = &precision_wanted_type;
1936                 }
1937             }
1938           else
1939             {
1940               if (!(fki->flags & (int) FMT_FLAG_EMPTY_PREC_OK)
1941                   && !ISDIGIT (*format_chars))
1942                 warning_at (format_string_loc, OPT_Wformat_,
1943                             "empty precision in %s format", fki->name);
1944               while (ISDIGIT (*format_chars))
1945                 ++format_chars;
1946             }
1947         }
1948
1949       format_start = format_chars;
1950       if (fki->alloc_char && fki->alloc_char == *format_chars)
1951         {
1952           i = strlen (flag_chars);
1953           flag_chars[i++] = fki->alloc_char;
1954           flag_chars[i] = 0;
1955           format_chars++;
1956         }
1957
1958       /* Handle the scanf allocation kludge.  */
1959       if (fki->flags & (int) FMT_FLAG_SCANF_A_KLUDGE)
1960         {
1961           if (*format_chars == 'a' && !flag_isoc99)
1962             {
1963               if (format_chars[1] == 's' || format_chars[1] == 'S'
1964                   || format_chars[1] == '[')
1965                 {
1966                   /* 'a' is used as a flag.  */
1967                   i = strlen (flag_chars);
1968                   flag_chars[i++] = 'a';
1969                   flag_chars[i] = 0;
1970                   format_chars++;
1971                 }
1972             }
1973         }
1974
1975       /* Read any length modifier, if this kind of format has them.  */
1976       fli = fki->length_char_specs;
1977       length_chars = NULL;
1978       length_chars_val = FMT_LEN_none;
1979       length_chars_std = STD_C89;
1980       scalar_identity_flag = 0;
1981       if (fli)
1982         {
1983           while (fli->name != 0
1984                  && strncmp (fli->name, format_chars, strlen (fli->name)))
1985               fli++;
1986           if (fli->name != 0)
1987             {
1988               format_chars += strlen (fli->name);
1989               if (fli->double_name != 0 && fli->name[0] == *format_chars)
1990                 {
1991                   format_chars++;
1992                   length_chars = fli->double_name;
1993                   length_chars_val = fli->double_index;
1994                   length_chars_std = fli->double_std;
1995                 }
1996               else
1997                 {
1998                   length_chars = fli->name;
1999                   length_chars_val = fli->index;
2000                   length_chars_std = fli->std;
2001                   scalar_identity_flag = fli->scalar_identity_flag;
2002                 }
2003               i = strlen (flag_chars);
2004               flag_chars[i++] = fki->length_code_char;
2005               flag_chars[i] = 0;
2006             }
2007           if (pedantic)
2008             {
2009               /* Warn if the length modifier is non-standard.  */
2010               if (ADJ_STD (length_chars_std) > C_STD_VER)
2011                 warning_at (format_string_loc, OPT_Wformat_,
2012                             "%s does not support the %qs %s length modifier",
2013                             C_STD_NAME (length_chars_std), length_chars,
2014                             fki->name);
2015             }
2016         }
2017
2018       /* Read any modifier (strftime E/O).  */
2019       if (fki->modifier_chars != NULL)
2020         {
2021           while (*format_chars != 0
2022                  && strchr (fki->modifier_chars, *format_chars) != 0)
2023             {
2024               if (strchr (flag_chars, *format_chars) != 0)
2025                 {
2026                   const format_flag_spec *s = get_flag_spec (flag_specs,
2027                                                              *format_chars, NULL);
2028                   warning_at (format_string_loc, OPT_Wformat_,
2029                               "repeated %s in format", _(s->name));
2030                 }
2031               else
2032                 {
2033                   i = strlen (flag_chars);
2034                   flag_chars[i++] = *format_chars;
2035                   flag_chars[i] = 0;
2036                 }
2037               ++format_chars;
2038             }
2039         }
2040
2041       format_char = *format_chars;
2042       if (format_char == 0
2043           || (!(fki->flags & (int) FMT_FLAG_FANCY_PERCENT_OK)
2044               && format_char == '%'))
2045         {
2046           warning_at (format_string_loc, OPT_Wformat_,
2047                       "conversion lacks type at end of format");
2048           continue;
2049         }
2050       format_chars++;
2051       fci = fki->conversion_specs;
2052       while (fci->format_chars != 0
2053              && strchr (fci->format_chars, format_char) == 0)
2054           ++fci;
2055       if (fci->format_chars == 0)
2056         {
2057           if (ISGRAPH (format_char))
2058             warning_at (format_string_loc, OPT_Wformat_,
2059                         "unknown conversion type character %qc in format",
2060                         format_char);
2061           else
2062             warning_at (format_string_loc, OPT_Wformat_,
2063                         "unknown conversion type character 0x%x in format",
2064                         format_char);
2065           continue;
2066         }
2067       if (pedantic)
2068         {
2069           if (ADJ_STD (fci->std) > C_STD_VER)
2070             warning_at (format_string_loc, OPT_Wformat_,
2071                         "%s does not support the %<%%%c%> %s format",
2072                         C_STD_NAME (fci->std), format_char, fki->name);
2073         }
2074
2075       /* Validate the individual flags used, removing any that are invalid.  */
2076       {
2077         int d = 0;
2078         for (i = 0; flag_chars[i] != 0; i++)
2079           {
2080             const format_flag_spec *s = get_flag_spec (flag_specs,
2081                                                        flag_chars[i], NULL);
2082             flag_chars[i - d] = flag_chars[i];
2083             if (flag_chars[i] == fki->length_code_char)
2084               continue;
2085             if (strchr (fci->flag_chars, flag_chars[i]) == 0)
2086               {
2087                 warning_at (format_string_loc, 
2088                             OPT_Wformat_, "%s used with %<%%%c%> %s format",
2089                             _(s->name), format_char, fki->name);
2090                 d++;
2091                 continue;
2092               }
2093             if (pedantic)
2094               {
2095                 const format_flag_spec *t;
2096                 if (ADJ_STD (s->std) > C_STD_VER)
2097                   warning_at (format_string_loc, OPT_Wformat_,
2098                               "%s does not support %s",
2099                               C_STD_NAME (s->std), _(s->long_name));
2100                 t = get_flag_spec (flag_specs, flag_chars[i], fci->flags2);
2101                 if (t != NULL && ADJ_STD (t->std) > ADJ_STD (s->std))
2102                   {
2103                     const char *long_name = (t->long_name != NULL
2104                                              ? t->long_name
2105                                              : s->long_name);
2106                     if (ADJ_STD (t->std) > C_STD_VER)
2107                       warning_at (format_string_loc, OPT_Wformat_,
2108                                   "%s does not support %s with the %<%%%c%> %s format",
2109                                   C_STD_NAME (t->std), _(long_name),
2110                                   format_char, fki->name);
2111                   }
2112               }
2113           }
2114         flag_chars[i - d] = 0;
2115       }
2116
2117       if ((fki->flags & (int) FMT_FLAG_SCANF_A_KLUDGE)
2118           && strchr (flag_chars, 'a') != 0)
2119         alloc_flag = 1;
2120       if (fki->alloc_char && strchr (flag_chars, fki->alloc_char) != 0)
2121         alloc_flag = 1;
2122
2123       if (fki->suppression_char
2124           && strchr (flag_chars, fki->suppression_char) != 0)
2125         suppressed = 1;
2126
2127       /* Validate the pairs of flags used.  */
2128       for (i = 0; bad_flag_pairs[i].flag_char1 != 0; i++)
2129         {
2130           const format_flag_spec *s, *t;
2131           if (strchr (flag_chars, bad_flag_pairs[i].flag_char1) == 0)
2132             continue;
2133           if (strchr (flag_chars, bad_flag_pairs[i].flag_char2) == 0)
2134             continue;
2135           if (bad_flag_pairs[i].predicate != 0
2136               && strchr (fci->flags2, bad_flag_pairs[i].predicate) == 0)
2137             continue;
2138           s = get_flag_spec (flag_specs, bad_flag_pairs[i].flag_char1, NULL);
2139           t = get_flag_spec (flag_specs, bad_flag_pairs[i].flag_char2, NULL);
2140           if (bad_flag_pairs[i].ignored)
2141             {
2142               if (bad_flag_pairs[i].predicate != 0)
2143                 warning_at (format_string_loc, OPT_Wformat_,
2144                             "%s ignored with %s and %<%%%c%> %s format",
2145                             _(s->name), _(t->name), format_char,
2146                             fki->name);
2147               else
2148                 warning_at (format_string_loc, OPT_Wformat_,
2149                             "%s ignored with %s in %s format",
2150                             _(s->name), _(t->name), fki->name);
2151             }
2152           else
2153             {
2154               if (bad_flag_pairs[i].predicate != 0)
2155                 warning_at (format_string_loc, OPT_Wformat_,
2156                             "use of %s and %s together with %<%%%c%> %s format",
2157                             _(s->name), _(t->name), format_char,
2158                             fki->name);
2159               else
2160                 warning_at (format_string_loc, OPT_Wformat_,
2161                             "use of %s and %s together in %s format",
2162                             _(s->name), _(t->name), fki->name);
2163             }
2164         }
2165
2166       /* Give Y2K warnings.  */
2167       if (warn_format_y2k)
2168         {
2169           int y2k_level = 0;
2170           if (strchr (fci->flags2, '4') != 0)
2171             if (strchr (flag_chars, 'E') != 0)
2172               y2k_level = 3;
2173             else
2174               y2k_level = 2;
2175           else if (strchr (fci->flags2, '3') != 0)
2176             y2k_level = 3;
2177           else if (strchr (fci->flags2, '2') != 0)
2178             y2k_level = 2;
2179           if (y2k_level == 3)
2180             warning_at (format_string_loc, OPT_Wformat_y2k,
2181                         "%<%%%c%> yields only last 2 digits of "
2182                         "year in some locales", format_char);
2183           else if (y2k_level == 2)
2184             warning_at (format_string_loc, OPT_Wformat_y2k,
2185                         "%<%%%c%> yields only last 2 digits of year",
2186                         format_char);
2187         }
2188
2189       if (strchr (fci->flags2, '[') != 0)
2190         {
2191           /* Skip over scan set, in case it happens to have '%' in it.  */
2192           if (*format_chars == '^')
2193             ++format_chars;
2194           /* Find closing bracket; if one is hit immediately, then
2195              it's part of the scan set rather than a terminator.  */
2196           if (*format_chars == ']')
2197             ++format_chars;
2198           while (*format_chars && *format_chars != ']')
2199             ++format_chars;
2200           if (*format_chars != ']')
2201             /* The end of the format string was reached.  */
2202             warning_at (format_string_loc, OPT_Wformat_,
2203                         "no closing %<]%> for %<%%[%> format");
2204         }
2205
2206       wanted_type = 0;
2207       wanted_type_name = 0;
2208       if (fki->flags & (int) FMT_FLAG_ARG_CONVERT)
2209         {
2210           wanted_type = (fci->types[length_chars_val].type
2211                          ? *fci->types[length_chars_val].type : 0);
2212           wanted_type_name = fci->types[length_chars_val].name;
2213           wanted_type_std = fci->types[length_chars_val].std;
2214           if (wanted_type == 0)
2215             {
2216               warning_at (format_string_loc, OPT_Wformat_,
2217                           "use of %qs length modifier with %qc type character",
2218                           length_chars, format_char);
2219               /* Heuristic: skip one argument when an invalid length/type
2220                  combination is encountered.  */
2221               arg_num++;
2222               if (params != 0)
2223                 params = TREE_CHAIN (params);
2224               continue;
2225             }
2226           else if (pedantic
2227                    /* Warn if non-standard, provided it is more non-standard
2228                       than the length and type characters that may already
2229                       have been warned for.  */
2230                    && ADJ_STD (wanted_type_std) > ADJ_STD (length_chars_std)
2231                    && ADJ_STD (wanted_type_std) > ADJ_STD (fci->std))
2232             {
2233               if (ADJ_STD (wanted_type_std) > C_STD_VER)
2234                 warning_at (format_string_loc, OPT_Wformat_,
2235                             "%s does not support the %<%%%s%c%> %s format",
2236                             C_STD_NAME (wanted_type_std), length_chars,
2237                             format_char, fki->name);
2238             }
2239         }
2240
2241       main_wanted_type.next = NULL;
2242
2243       /* Finally. . .check type of argument against desired type!  */
2244       if (info->first_arg_num == 0)
2245         continue;
2246       if ((fci->pointer_count == 0 && wanted_type == void_type_node)
2247           || suppressed)
2248         {
2249           if (main_arg_num != 0)
2250             {
2251               if (suppressed)
2252                 warning_at (format_string_loc, OPT_Wformat_,
2253                             "operand number specified with "
2254                             "suppressed assignment");
2255               else
2256                 warning_at (format_string_loc, OPT_Wformat_,
2257                             "operand number specified for format "
2258                             "taking no argument");
2259             }
2260         }
2261       else
2262         {
2263           format_wanted_type *wanted_type_ptr;
2264
2265           if (main_arg_num != 0)
2266             {
2267               arg_num = main_arg_num;
2268               params = main_arg_params;
2269             }
2270           else
2271             {
2272               ++arg_num;
2273               if (has_operand_number > 0)
2274                 {
2275                   warning_at (format_string_loc, OPT_Wformat_,
2276                               "missing $ operand number in format");
2277                   return;
2278                 }
2279               else
2280                 has_operand_number = 0;
2281             }
2282
2283           wanted_type_ptr = &main_wanted_type;
2284           while (fci)
2285             {
2286               if (params == 0)
2287                 cur_param = NULL;
2288               else
2289                 {
2290                   cur_param = TREE_VALUE (params);
2291                   params = TREE_CHAIN (params);
2292                 }
2293
2294               wanted_type_ptr->wanted_type = wanted_type;
2295               wanted_type_ptr->wanted_type_name = wanted_type_name;
2296               wanted_type_ptr->pointer_count = fci->pointer_count + alloc_flag;
2297               wanted_type_ptr->char_lenient_flag = 0;
2298               if (strchr (fci->flags2, 'c') != 0)
2299                 wanted_type_ptr->char_lenient_flag = 1;
2300               wanted_type_ptr->scalar_identity_flag = 0;
2301               if (scalar_identity_flag)
2302                 wanted_type_ptr->scalar_identity_flag = 1;
2303               wanted_type_ptr->writing_in_flag = 0;
2304               wanted_type_ptr->reading_from_flag = 0;
2305               if (alloc_flag)
2306                 wanted_type_ptr->writing_in_flag = 1;
2307               else
2308                 {
2309                   if (strchr (fci->flags2, 'W') != 0)
2310                     wanted_type_ptr->writing_in_flag = 1;
2311                   if (strchr (fci->flags2, 'R') != 0)
2312                     wanted_type_ptr->reading_from_flag = 1;
2313                 }
2314               wanted_type_ptr->kind = CF_KIND_FORMAT;
2315               wanted_type_ptr->param = cur_param;
2316               wanted_type_ptr->arg_num = arg_num;
2317               wanted_type_ptr->format_start = format_start;
2318               wanted_type_ptr->format_length = format_chars - format_start;
2319               wanted_type_ptr->next = NULL;
2320               if (last_wanted_type != 0)
2321                 last_wanted_type->next = wanted_type_ptr;
2322               if (first_wanted_type == 0)
2323                 first_wanted_type = wanted_type_ptr;
2324               last_wanted_type = wanted_type_ptr;
2325
2326               fci = fci->chain;
2327               if (fci)
2328                 {
2329                   wanted_type_ptr = (format_wanted_type *)
2330                       pool_alloc (fwt_pool);
2331                   arg_num++;
2332                   wanted_type = *fci->types[length_chars_val].type;
2333                   wanted_type_name = fci->types[length_chars_val].name;
2334                 }
2335             }
2336         }
2337
2338       if (first_wanted_type != 0)
2339         check_format_types (format_string_loc, first_wanted_type);
2340     }
2341
2342   if (format_chars - orig_format_chars != format_length)
2343     warning_at (format_string_loc, OPT_Wformat_contains_nul,
2344                 "embedded %<\\0%> in format");
2345   if (info->first_arg_num != 0 && params != 0
2346       && has_operand_number <= 0)
2347     {
2348       res->number_other--;
2349       res->number_extra_args++;
2350     }
2351   if (has_operand_number > 0)
2352     finish_dollar_format_checking (res, fki->flags & (int) FMT_FLAG_DOLLAR_GAP_POINTER_OK);
2353 }
2354
2355
2356 /* Check the argument types from a single format conversion (possibly
2357    including width and precision arguments).  LOC is the location of
2358    the format string.  */
2359 static void
2360 check_format_types (location_t loc, format_wanted_type *types)
2361 {
2362   for (; types != 0; types = types->next)
2363     {
2364       tree cur_param;
2365       tree cur_type;
2366       tree orig_cur_type;
2367       tree wanted_type;
2368       int arg_num;
2369       int i;
2370       int char_type_flag;
2371
2372       wanted_type = types->wanted_type;
2373       arg_num = types->arg_num;
2374
2375       /* The following should not occur here.  */
2376       gcc_assert (wanted_type);
2377       gcc_assert (wanted_type != void_type_node || types->pointer_count);
2378
2379       if (types->pointer_count == 0)
2380         wanted_type = lang_hooks.types.type_promotes_to (wanted_type);
2381
2382       wanted_type = TYPE_MAIN_VARIANT (wanted_type);
2383
2384       cur_param = types->param;
2385       if (!cur_param)
2386         {
2387           format_type_warning (loc, types, wanted_type, NULL);
2388           continue;
2389         }
2390
2391       cur_type = TREE_TYPE (cur_param);
2392       if (cur_type == error_mark_node)
2393         continue;
2394       orig_cur_type = cur_type;
2395       char_type_flag = 0;
2396
2397       STRIP_NOPS (cur_param);
2398
2399       /* Check the types of any additional pointer arguments
2400          that precede the "real" argument.  */
2401       for (i = 0; i < types->pointer_count; ++i)
2402         {
2403           if (TREE_CODE (cur_type) == POINTER_TYPE)
2404             {
2405               cur_type = TREE_TYPE (cur_type);
2406               if (cur_type == error_mark_node)
2407                 break;
2408
2409               /* Check for writing through a NULL pointer.  */
2410               if (types->writing_in_flag
2411                   && i == 0
2412                   && cur_param != 0
2413                   && integer_zerop (cur_param))
2414                 warning (OPT_Wformat_, "writing through null pointer "
2415                          "(argument %d)", arg_num);
2416
2417               /* Check for reading through a NULL pointer.  */
2418               if (types->reading_from_flag
2419                   && i == 0
2420                   && cur_param != 0
2421                   && integer_zerop (cur_param))
2422                 warning (OPT_Wformat_, "reading through null pointer "
2423                          "(argument %d)", arg_num);
2424
2425               if (cur_param != 0 && TREE_CODE (cur_param) == ADDR_EXPR)
2426                 cur_param = TREE_OPERAND (cur_param, 0);
2427               else
2428                 cur_param = 0;
2429
2430               /* See if this is an attempt to write into a const type with
2431                  scanf or with printf "%n".  Note: the writing in happens
2432                  at the first indirection only, if for example
2433                  void * const * is passed to scanf %p; passing
2434                  const void ** is simply passing an incompatible type.  */
2435               if (types->writing_in_flag
2436                   && i == 0
2437                   && (TYPE_READONLY (cur_type)
2438                       || (cur_param != 0
2439                           && (CONSTANT_CLASS_P (cur_param)
2440                               || (DECL_P (cur_param)
2441                                   && TREE_READONLY (cur_param))))))
2442                 warning (OPT_Wformat_, "writing into constant object "
2443                          "(argument %d)", arg_num);
2444
2445               /* If there are extra type qualifiers beyond the first
2446                  indirection, then this makes the types technically
2447                  incompatible.  */
2448               if (i > 0
2449                   && pedantic
2450                   && (TYPE_READONLY (cur_type)
2451                       || TYPE_VOLATILE (cur_type)
2452                       || TYPE_ATOMIC (cur_type)
2453                       || TYPE_RESTRICT (cur_type)))
2454                 warning (OPT_Wformat_, "extra type qualifiers in format "
2455                          "argument (argument %d)",
2456                          arg_num);
2457
2458             }
2459           else
2460             {
2461               format_type_warning (loc, types, wanted_type, orig_cur_type);
2462               break;
2463             }
2464         }
2465
2466       if (i < types->pointer_count)
2467         continue;
2468
2469       cur_type = TYPE_MAIN_VARIANT (cur_type);
2470
2471       /* Check whether the argument type is a character type.  This leniency
2472          only applies to certain formats, flagged with 'c'.  */
2473       if (types->char_lenient_flag)
2474         char_type_flag = (cur_type == char_type_node
2475                           || cur_type == signed_char_type_node
2476                           || cur_type == unsigned_char_type_node);
2477
2478       /* Check the type of the "real" argument, if there's a type we want.  */
2479       if (lang_hooks.types_compatible_p (wanted_type, cur_type))
2480         continue;
2481       /* If we want 'void *', allow any pointer type.
2482          (Anything else would already have got a warning.)
2483          With -Wpedantic, only allow pointers to void and to character
2484          types.  */
2485       if (wanted_type == void_type_node
2486           && (!pedantic || (i == 1 && char_type_flag)))
2487         continue;
2488       /* Don't warn about differences merely in signedness, unless
2489          -Wpedantic.  With -Wpedantic, warn if the type is a pointer
2490          target and not a character type, and for character types at
2491          a second level of indirection.  */
2492       if (TREE_CODE (wanted_type) == INTEGER_TYPE
2493           && TREE_CODE (cur_type) == INTEGER_TYPE
2494           && ((!pedantic && !warn_format_signedness)
2495               || (i == 0 && !warn_format_signedness)
2496               || (i == 1 && char_type_flag))
2497           && (TYPE_UNSIGNED (wanted_type)
2498               ? wanted_type == c_common_unsigned_type (cur_type)
2499               : wanted_type == c_common_signed_type (cur_type)))
2500         continue;
2501       /* Don't warn about differences merely in signedness if we know
2502          that the current type is integer-promoted and its original type
2503          was unsigned such as that it is in the range of WANTED_TYPE.  */
2504       if (TREE_CODE (wanted_type) == INTEGER_TYPE
2505           && TREE_CODE (cur_type) == INTEGER_TYPE
2506           && warn_format_signedness
2507           && TYPE_UNSIGNED (wanted_type)
2508           && cur_param != NULL_TREE
2509           && TREE_CODE (cur_param) == NOP_EXPR)
2510         {
2511           tree t = TREE_TYPE (TREE_OPERAND (cur_param, 0));
2512           if (TYPE_UNSIGNED (t)
2513               && cur_type == lang_hooks.types.type_promotes_to (t))
2514             continue;
2515         }
2516       /* Likewise, "signed char", "unsigned char" and "char" are
2517          equivalent but the above test won't consider them equivalent.  */
2518       if (wanted_type == char_type_node
2519           && (!pedantic || i < 2)
2520           && char_type_flag)
2521         continue;
2522       if (types->scalar_identity_flag
2523           && (TREE_CODE (cur_type) == TREE_CODE (wanted_type)
2524               || (INTEGRAL_TYPE_P (cur_type)
2525                   && INTEGRAL_TYPE_P (wanted_type)))
2526           && TYPE_PRECISION (cur_type) == TYPE_PRECISION (wanted_type))
2527         continue;
2528       /* Now we have a type mismatch.  */
2529       format_type_warning (loc, types, wanted_type, orig_cur_type);
2530     }
2531 }
2532
2533
2534 /* Give a warning at LOC about a format argument of different type from that
2535    expected.  WANTED_TYPE is the type the argument should have, possibly
2536    stripped of pointer dereferences.  The description (such as "field
2537    precision"), the placement in the format string, a possibly more
2538    friendly name of WANTED_TYPE, and the number of pointer dereferences
2539    are taken from TYPE.  ARG_TYPE is the type of the actual argument,
2540    or NULL if it is missing.  */
2541 static void
2542 format_type_warning (location_t loc, format_wanted_type *type,
2543                      tree wanted_type, tree arg_type)
2544 {
2545   int kind = type->kind;
2546   const char *wanted_type_name = type->wanted_type_name;
2547   const char *format_start = type->format_start;
2548   int format_length = type->format_length;
2549   int pointer_count = type->pointer_count;
2550   int arg_num = type->arg_num;
2551
2552   char *p;
2553   /* If ARG_TYPE is a typedef with a misleading name (for example,
2554      size_t but not the standard size_t expected by printf %zu), avoid
2555      printing the typedef name.  */
2556   if (wanted_type_name
2557       && arg_type
2558       && TYPE_NAME (arg_type)
2559       && TREE_CODE (TYPE_NAME (arg_type)) == TYPE_DECL
2560       && DECL_NAME (TYPE_NAME (arg_type))
2561       && !strcmp (wanted_type_name,
2562                   lang_hooks.decl_printable_name (TYPE_NAME (arg_type), 2)))
2563     arg_type = TYPE_MAIN_VARIANT (arg_type);
2564   /* The format type and name exclude any '*' for pointers, so those
2565      must be formatted manually.  For all the types we currently have,
2566      this is adequate, but formats taking pointers to functions or
2567      arrays would require the full type to be built up in order to
2568      print it with %T.  */
2569   p = (char *) alloca (pointer_count + 2);
2570   if (pointer_count == 0)
2571     p[0] = 0;
2572   else if (c_dialect_cxx ())
2573     {
2574       memset (p, '*', pointer_count);
2575       p[pointer_count] = 0;
2576     }
2577   else
2578     {
2579       p[0] = ' ';
2580       memset (p + 1, '*', pointer_count);
2581       p[pointer_count + 1] = 0;
2582     }
2583
2584   if (wanted_type_name)
2585     {
2586       if (arg_type)
2587         warning_at (loc, OPT_Wformat_,
2588                     "%s %<%s%.*s%> expects argument of type %<%s%s%>, "
2589                     "but argument %d has type %qT",
2590                     gettext (kind_descriptions[kind]),
2591                     (kind == CF_KIND_FORMAT ? "%" : ""),
2592                     format_length, format_start, 
2593                     wanted_type_name, p, arg_num, arg_type);
2594       else
2595         warning_at (loc, OPT_Wformat_,
2596                     "%s %<%s%.*s%> expects a matching %<%s%s%> argument",
2597                     gettext (kind_descriptions[kind]),
2598                     (kind == CF_KIND_FORMAT ? "%" : ""),
2599                     format_length, format_start, wanted_type_name, p);
2600     }
2601   else
2602     {
2603       if (arg_type)
2604         warning_at (loc, OPT_Wformat_,
2605                     "%s %<%s%.*s%> expects argument of type %<%T%s%>, "
2606                     "but argument %d has type %qT",
2607                     gettext (kind_descriptions[kind]),
2608                     (kind == CF_KIND_FORMAT ? "%" : ""),
2609                     format_length, format_start, 
2610                     wanted_type, p, arg_num, arg_type);
2611       else
2612         warning_at (loc, OPT_Wformat_,
2613                     "%s %<%s%.*s%> expects a matching %<%T%s%> argument",
2614                     gettext (kind_descriptions[kind]),
2615                     (kind == CF_KIND_FORMAT ? "%" : ""),
2616                     format_length, format_start, wanted_type, p);
2617     }
2618 }
2619
2620
2621 /* Given a format_char_info array FCI, and a character C, this function
2622    returns the index into the conversion_specs where that specifier's
2623    data is located.  The character must exist.  */
2624 static unsigned int
2625 find_char_info_specifier_index (const format_char_info *fci, int c)
2626 {
2627   unsigned i;
2628
2629   for (i = 0; fci->format_chars; i++, fci++)
2630     if (strchr (fci->format_chars, c))
2631       return i;
2632
2633   /* We shouldn't be looking for a non-existent specifier.  */
2634   gcc_unreachable ();
2635 }
2636
2637 /* Given a format_length_info array FLI, and a character C, this
2638    function returns the index into the conversion_specs where that
2639    modifier's data is located.  The character must exist.  */
2640 static unsigned int
2641 find_length_info_modifier_index (const format_length_info *fli, int c)
2642 {
2643   unsigned i;
2644
2645   for (i = 0; fli->name; i++, fli++)
2646     if (strchr (fli->name, c))
2647       return i;
2648
2649   /* We shouldn't be looking for a non-existent modifier.  */
2650   gcc_unreachable ();
2651 }
2652
2653 /* Determine the type of HOST_WIDE_INT in the code being compiled for
2654    use in GCC's __asm_fprintf__ custom format attribute.  You must
2655    have set dynamic_format_types before calling this function.  */
2656 static void
2657 init_dynamic_asm_fprintf_info (void)
2658 {
2659   static tree hwi;
2660
2661   if (!hwi)
2662     {
2663       format_length_info *new_asm_fprintf_length_specs;
2664       unsigned int i;
2665
2666       /* Find the underlying type for HOST_WIDE_INT.  For the %w
2667          length modifier to work, one must have issued: "typedef
2668          HOST_WIDE_INT __gcc_host_wide_int__;" in one's source code
2669          prior to using that modifier.  */
2670       hwi = maybe_get_identifier ("__gcc_host_wide_int__");
2671       if (!hwi)
2672         {
2673           error ("%<__gcc_host_wide_int__%> is not defined as a type");
2674           return;
2675         }
2676       hwi = identifier_global_value (hwi);
2677       if (!hwi || TREE_CODE (hwi) != TYPE_DECL)
2678         {
2679           error ("%<__gcc_host_wide_int__%> is not defined as a type");
2680           return;
2681         }
2682       hwi = DECL_ORIGINAL_TYPE (hwi);
2683       gcc_assert (hwi);
2684       if (hwi != long_integer_type_node && hwi != long_long_integer_type_node)
2685         {
2686           error ("%<__gcc_host_wide_int__%> is not defined as %<long%>"
2687                  " or %<long long%>");
2688           return;
2689         }
2690
2691       /* Create a new (writable) copy of asm_fprintf_length_specs.  */
2692       new_asm_fprintf_length_specs = (format_length_info *)
2693                                      xmemdup (asm_fprintf_length_specs,
2694                                               sizeof (asm_fprintf_length_specs),
2695                                               sizeof (asm_fprintf_length_specs));
2696
2697       /* HOST_WIDE_INT must be one of 'long' or 'long long'.  */
2698       i = find_length_info_modifier_index (new_asm_fprintf_length_specs, 'w');
2699       if (hwi == long_integer_type_node)
2700         new_asm_fprintf_length_specs[i].index = FMT_LEN_l;
2701       else if (hwi == long_long_integer_type_node)
2702         new_asm_fprintf_length_specs[i].index = FMT_LEN_ll;
2703       else
2704         gcc_unreachable ();
2705
2706       /* Assign the new data for use.  */
2707       dynamic_format_types[asm_fprintf_format_type].length_char_specs =
2708         new_asm_fprintf_length_specs;
2709     }
2710 }
2711
2712 /* Determine the type of a "locus" in the code being compiled for use
2713    in GCC's __gcc_gfc__ custom format attribute.  You must have set
2714    dynamic_format_types before calling this function.  */
2715 static void
2716 init_dynamic_gfc_info (void)
2717 {
2718   static tree locus;
2719
2720   if (!locus)
2721     {
2722       static format_char_info *gfc_fci;
2723
2724       /* For the GCC __gcc_gfc__ custom format specifier to work, one
2725          must have declared 'locus' prior to using this attribute.  If
2726          we haven't seen this declarations then you shouldn't use the
2727          specifier requiring that type.  */
2728       if ((locus = maybe_get_identifier ("locus")))
2729         {
2730           locus = identifier_global_value (locus);
2731           if (locus)
2732             {
2733               if (TREE_CODE (locus) != TYPE_DECL
2734                   || TREE_TYPE (locus) == error_mark_node)
2735                 {
2736                   error ("%<locus%> is not defined as a type");
2737                   locus = 0;
2738                 }
2739               else
2740                 locus = TREE_TYPE (locus);
2741             }
2742         }
2743
2744       /* Assign the new data for use.  */
2745
2746       /* Handle the __gcc_gfc__ format specifics.  */
2747       if (!gfc_fci)
2748         dynamic_format_types[gcc_gfc_format_type].conversion_specs =
2749           gfc_fci = (format_char_info *)
2750                      xmemdup (gcc_gfc_char_table,
2751                               sizeof (gcc_gfc_char_table),
2752                               sizeof (gcc_gfc_char_table));
2753       if (locus)
2754         {
2755           const unsigned i = find_char_info_specifier_index (gfc_fci, 'L');
2756           gfc_fci[i].types[0].type = &locus;
2757           gfc_fci[i].pointer_count = 1;
2758         }
2759     }
2760 }
2761
2762 /* Determine the types of "tree" and "location_t" in the code being
2763    compiled for use in GCC's diagnostic custom format attributes.  You
2764    must have set dynamic_format_types before calling this function.  */
2765 static void
2766 init_dynamic_diag_info (void)
2767 {
2768   static tree t, loc, hwi;
2769
2770   if (!loc || !t || !hwi)
2771     {
2772       static format_char_info *diag_fci, *tdiag_fci, *cdiag_fci, *cxxdiag_fci;
2773       static format_length_info *diag_ls;
2774       unsigned int i;
2775
2776       /* For the GCC-diagnostics custom format specifiers to work, one
2777          must have declared 'tree' and/or 'location_t' prior to using
2778          those attributes.  If we haven't seen these declarations then
2779          you shouldn't use the specifiers requiring these types.
2780          However we don't force a hard ICE because we may see only one
2781          or the other type.  */
2782       if ((loc = maybe_get_identifier ("location_t")))
2783         {
2784           loc = identifier_global_value (loc);
2785           if (loc)
2786             {
2787               if (TREE_CODE (loc) != TYPE_DECL)
2788                 {
2789                   error ("%<location_t%> is not defined as a type");
2790                   loc = 0;
2791                 }
2792               else
2793                 loc = TREE_TYPE (loc);
2794             }
2795         }
2796
2797       /* We need to grab the underlying 'union tree_node' so peek into
2798          an extra type level.  */
2799       if ((t = maybe_get_identifier ("tree")))
2800         {
2801           t = identifier_global_value (t);
2802           if (t)
2803             {
2804               if (TREE_CODE (t) != TYPE_DECL)
2805                 {
2806                   error ("%<tree%> is not defined as a type");
2807                   t = 0;
2808                 }
2809               else if (TREE_CODE (TREE_TYPE (t)) != POINTER_TYPE)
2810                 {
2811                   error ("%<tree%> is not defined as a pointer type");
2812                   t = 0;
2813                 }
2814               else
2815                 t = TREE_TYPE (TREE_TYPE (t));
2816             }
2817         }
2818
2819       /* Find the underlying type for HOST_WIDE_INT.  For the %w
2820          length modifier to work, one must have issued: "typedef
2821          HOST_WIDE_INT __gcc_host_wide_int__;" in one's source code
2822          prior to using that modifier.  */
2823       if ((hwi = maybe_get_identifier ("__gcc_host_wide_int__")))
2824         {
2825           hwi = identifier_global_value (hwi);
2826           if (hwi)
2827             {
2828               if (TREE_CODE (hwi) != TYPE_DECL)
2829                 {
2830                   error ("%<__gcc_host_wide_int__%> is not defined as a type");
2831                   hwi = 0;
2832                 }
2833               else
2834                 {
2835                   hwi = DECL_ORIGINAL_TYPE (hwi);
2836                   gcc_assert (hwi);
2837                   if (hwi != long_integer_type_node
2838                       && hwi != long_long_integer_type_node)
2839                     {
2840                       error ("%<__gcc_host_wide_int__%> is not defined"
2841                              " as %<long%> or %<long long%>");
2842                       hwi = 0;
2843                     }
2844                 }
2845             }
2846         }
2847
2848       /* Assign the new data for use.  */
2849
2850       /* All the GCC diag formats use the same length specs.  */
2851       if (!diag_ls)
2852         dynamic_format_types[gcc_diag_format_type].length_char_specs =
2853           dynamic_format_types[gcc_tdiag_format_type].length_char_specs =
2854           dynamic_format_types[gcc_cdiag_format_type].length_char_specs =
2855           dynamic_format_types[gcc_cxxdiag_format_type].length_char_specs =
2856           diag_ls = (format_length_info *)
2857                     xmemdup (gcc_diag_length_specs,
2858                              sizeof (gcc_diag_length_specs),
2859                              sizeof (gcc_diag_length_specs));
2860       if (hwi)
2861         {
2862           /* HOST_WIDE_INT must be one of 'long' or 'long long'.  */
2863           i = find_length_info_modifier_index (diag_ls, 'w');
2864           if (hwi == long_integer_type_node)
2865             diag_ls[i].index = FMT_LEN_l;
2866           else if (hwi == long_long_integer_type_node)
2867             diag_ls[i].index = FMT_LEN_ll;
2868           else
2869             gcc_unreachable ();
2870         }
2871
2872       /* Handle the __gcc_diag__ format specifics.  */
2873       if (!diag_fci)
2874         dynamic_format_types[gcc_diag_format_type].conversion_specs =
2875           diag_fci = (format_char_info *)
2876                      xmemdup (gcc_diag_char_table,
2877                               sizeof (gcc_diag_char_table),
2878                               sizeof (gcc_diag_char_table));
2879       if (t)
2880         {
2881           i = find_char_info_specifier_index (diag_fci, 'K');
2882           diag_fci[i].types[0].type = &t;
2883           diag_fci[i].pointer_count = 1;
2884         }
2885
2886       /* Handle the __gcc_tdiag__ format specifics.  */
2887       if (!tdiag_fci)
2888         dynamic_format_types[gcc_tdiag_format_type].conversion_specs =
2889           tdiag_fci = (format_char_info *)
2890                       xmemdup (gcc_tdiag_char_table,
2891                                sizeof (gcc_tdiag_char_table),
2892                                sizeof (gcc_tdiag_char_table));
2893       if (t)
2894         {
2895           /* All specifiers taking a tree share the same struct.  */
2896           i = find_char_info_specifier_index (tdiag_fci, 'D');
2897           tdiag_fci[i].types[0].type = &t;
2898           tdiag_fci[i].pointer_count = 1;
2899           i = find_char_info_specifier_index (tdiag_fci, 'K');
2900           tdiag_fci[i].types[0].type = &t;
2901           tdiag_fci[i].pointer_count = 1;
2902         }
2903
2904       /* Handle the __gcc_cdiag__ format specifics.  */
2905       if (!cdiag_fci)
2906         dynamic_format_types[gcc_cdiag_format_type].conversion_specs =
2907           cdiag_fci = (format_char_info *)
2908                       xmemdup (gcc_cdiag_char_table,
2909                                sizeof (gcc_cdiag_char_table),
2910                                sizeof (gcc_cdiag_char_table));
2911       if (t)
2912         {
2913           /* All specifiers taking a tree share the same struct.  */
2914           i = find_char_info_specifier_index (cdiag_fci, 'D');
2915           cdiag_fci[i].types[0].type = &t;
2916           cdiag_fci[i].pointer_count = 1;
2917           i = find_char_info_specifier_index (cdiag_fci, 'K');
2918           cdiag_fci[i].types[0].type = &t;
2919           cdiag_fci[i].pointer_count = 1;
2920         }
2921
2922       /* Handle the __gcc_cxxdiag__ format specifics.  */
2923       if (!cxxdiag_fci)
2924         dynamic_format_types[gcc_cxxdiag_format_type].conversion_specs =
2925           cxxdiag_fci = (format_char_info *)
2926                         xmemdup (gcc_cxxdiag_char_table,
2927                                  sizeof (gcc_cxxdiag_char_table),
2928                                  sizeof (gcc_cxxdiag_char_table));
2929       if (t)
2930         {
2931           /* All specifiers taking a tree share the same struct.  */
2932           i = find_char_info_specifier_index (cxxdiag_fci, 'D');
2933           cxxdiag_fci[i].types[0].type = &t;
2934           cxxdiag_fci[i].pointer_count = 1;
2935           i = find_char_info_specifier_index (cxxdiag_fci, 'K');
2936           cxxdiag_fci[i].types[0].type = &t;
2937           cxxdiag_fci[i].pointer_count = 1;
2938         }
2939     }
2940 }
2941
2942 #ifdef TARGET_FORMAT_TYPES
2943 extern const format_kind_info TARGET_FORMAT_TYPES[];
2944 #endif
2945
2946 #ifdef TARGET_OVERRIDES_FORMAT_ATTRIBUTES
2947 extern const target_ovr_attr TARGET_OVERRIDES_FORMAT_ATTRIBUTES[];
2948 #endif
2949 #ifdef TARGET_OVERRIDES_FORMAT_INIT
2950   extern void TARGET_OVERRIDES_FORMAT_INIT (void);
2951 #endif
2952
2953 /* Attributes such as "printf" are equivalent to those such as
2954    "gnu_printf" unless this is overridden by a target.  */
2955 static const target_ovr_attr gnu_target_overrides_format_attributes[] =
2956 {
2957   { "gnu_printf",   "printf" },
2958   { "gnu_scanf",    "scanf" },
2959   { "gnu_strftime", "strftime" },
2960   { "gnu_strfmon",  "strfmon" },
2961   { NULL,           NULL }
2962 };
2963
2964 /* Translate to unified attribute name. This is used in decode_format_type and
2965    decode_format_attr. In attr_name the user specified argument is passed. It
2966    returns the unified format name from TARGET_OVERRIDES_FORMAT_ATTRIBUTES
2967    or the attr_name passed to this function, if there is no matching entry.  */
2968 static const char *
2969 convert_format_name_to_system_name (const char *attr_name)
2970 {
2971   int i;
2972
2973   if (attr_name == NULL || *attr_name == 0
2974       || strncmp (attr_name, "gcc_", 4) == 0)
2975     return attr_name;
2976 #ifdef TARGET_OVERRIDES_FORMAT_INIT
2977   TARGET_OVERRIDES_FORMAT_INIT ();
2978 #endif
2979
2980 #ifdef TARGET_OVERRIDES_FORMAT_ATTRIBUTES
2981   /* Check if format attribute is overridden by target.  */
2982   if (TARGET_OVERRIDES_FORMAT_ATTRIBUTES != NULL
2983       && TARGET_OVERRIDES_FORMAT_ATTRIBUTES_COUNT > 0)
2984     {
2985       for (i = 0; i < TARGET_OVERRIDES_FORMAT_ATTRIBUTES_COUNT; ++i)
2986         {
2987           if (cmp_attribs (TARGET_OVERRIDES_FORMAT_ATTRIBUTES[i].named_attr_src,
2988                            attr_name))
2989             return attr_name;
2990           if (cmp_attribs (TARGET_OVERRIDES_FORMAT_ATTRIBUTES[i].named_attr_dst,
2991                            attr_name))
2992             return TARGET_OVERRIDES_FORMAT_ATTRIBUTES[i].named_attr_src;
2993         }
2994     }
2995 #endif
2996   /* Otherwise default to gnu format.  */
2997   for (i = 0;
2998        gnu_target_overrides_format_attributes[i].named_attr_src != NULL;
2999        ++i)
3000     {
3001       if (cmp_attribs (gnu_target_overrides_format_attributes[i].named_attr_src,
3002                        attr_name))
3003         return attr_name;
3004       if (cmp_attribs (gnu_target_overrides_format_attributes[i].named_attr_dst,
3005                        attr_name))
3006         return gnu_target_overrides_format_attributes[i].named_attr_src;
3007     }
3008
3009   return attr_name;
3010 }
3011
3012 /* Return true if TATTR_NAME and ATTR_NAME are the same format attribute,
3013    counting "name" and "__name__" as the same, false otherwise.  */
3014 static bool
3015 cmp_attribs (const char *tattr_name, const char *attr_name)
3016 {
3017   int alen = strlen (attr_name);
3018   int slen = (tattr_name ? strlen (tattr_name) : 0);
3019   if (alen > 4 && attr_name[0] == '_' && attr_name[1] == '_'
3020       && attr_name[alen - 1] == '_' && attr_name[alen - 2] == '_')
3021     {
3022       attr_name += 2;
3023       alen -= 4;
3024     }
3025   if (alen != slen || strncmp (tattr_name, attr_name, alen) != 0)
3026     return false;
3027   return true;
3028 }
3029
3030 /* Handle a "format" attribute; arguments as in
3031    struct attribute_spec.handler.  */
3032 tree
3033 handle_format_attribute (tree *node, tree ARG_UNUSED (name), tree args,
3034                          int flags, bool *no_add_attrs)
3035 {
3036   tree type = *node;
3037   function_format_info info;
3038
3039 #ifdef TARGET_FORMAT_TYPES
3040   /* If the target provides additional format types, we need to
3041      add them to FORMAT_TYPES at first use.  */
3042   if (TARGET_FORMAT_TYPES != NULL && !dynamic_format_types)
3043     {
3044       dynamic_format_types = XNEWVEC (format_kind_info,
3045                                       n_format_types + TARGET_N_FORMAT_TYPES);
3046       memcpy (dynamic_format_types, format_types_orig,
3047               sizeof (format_types_orig));
3048       memcpy (&dynamic_format_types[n_format_types], TARGET_FORMAT_TYPES,
3049               TARGET_N_FORMAT_TYPES * sizeof (dynamic_format_types[0]));
3050
3051       format_types = dynamic_format_types;
3052       /* Provide a reference for the first potential external type.  */
3053       first_target_format_type = n_format_types;
3054       n_format_types += TARGET_N_FORMAT_TYPES;
3055     }
3056 #endif
3057
3058   if (!decode_format_attr (args, &info, 0))
3059     {
3060       *no_add_attrs = true;
3061       return NULL_TREE;
3062     }
3063
3064   if (prototype_p (type))
3065     {
3066       if (!check_format_string (type, info.format_num, flags,
3067                                 no_add_attrs, info.format_type))
3068         return NULL_TREE;
3069
3070       if (info.first_arg_num != 0)
3071         {
3072           unsigned HOST_WIDE_INT arg_num = 1;
3073           function_args_iterator iter;
3074           tree arg_type;
3075
3076           /* Verify that first_arg_num points to the last arg,
3077              the ...  */
3078           FOREACH_FUNCTION_ARGS (type, arg_type, iter)
3079             arg_num++;
3080
3081           if (arg_num != info.first_arg_num)
3082             {
3083               if (!(flags & (int) ATTR_FLAG_BUILT_IN))
3084                 error ("args to be formatted is not %<...%>");
3085               *no_add_attrs = true;
3086               return NULL_TREE;
3087             }
3088         }
3089     }
3090
3091   /* Check if this is a strftime variant. Just for this variant
3092      FMT_FLAG_ARG_CONVERT is not set.  */
3093   if ((format_types[info.format_type].flags & (int) FMT_FLAG_ARG_CONVERT) == 0
3094       && info.first_arg_num != 0)
3095     {
3096       error ("strftime formats cannot format arguments");
3097       *no_add_attrs = true;
3098       return NULL_TREE;
3099     }
3100
3101   /* If this is a custom GCC-internal format type, we have to
3102      initialize certain bits at runtime.  */
3103   if (info.format_type == asm_fprintf_format_type
3104       || info.format_type == gcc_gfc_format_type
3105       || info.format_type == gcc_diag_format_type
3106       || info.format_type == gcc_tdiag_format_type
3107       || info.format_type == gcc_cdiag_format_type
3108       || info.format_type == gcc_cxxdiag_format_type)
3109     {
3110       /* Our first time through, we have to make sure that our
3111          format_type data is allocated dynamically and is modifiable.  */
3112       if (!dynamic_format_types)
3113         format_types = dynamic_format_types = (format_kind_info *)
3114           xmemdup (format_types_orig, sizeof (format_types_orig),
3115                    sizeof (format_types_orig));
3116
3117       /* If this is format __asm_fprintf__, we have to initialize
3118          GCC's notion of HOST_WIDE_INT for checking %wd.  */
3119       if (info.format_type == asm_fprintf_format_type)
3120         init_dynamic_asm_fprintf_info ();
3121       /* If this is format __gcc_gfc__, we have to initialize GCC's
3122          notion of 'locus' at runtime for %L.  */
3123       else if (info.format_type == gcc_gfc_format_type)
3124         init_dynamic_gfc_info ();
3125       /* If this is one of the diagnostic attributes, then we have to
3126          initialize 'location_t' and 'tree' at runtime.  */
3127       else if (info.format_type == gcc_diag_format_type
3128                || info.format_type == gcc_tdiag_format_type
3129                || info.format_type == gcc_cdiag_format_type
3130                || info.format_type == gcc_cxxdiag_format_type)
3131         init_dynamic_diag_info ();
3132       else
3133         gcc_unreachable ();
3134     }
3135
3136   return NULL_TREE;
3137 }