OSDN Git Service

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