xref: /netbsd-src/external/gpl3/gcc.old/dist/gcc/c-family/c-format.c (revision cef8759bd76c1b621f8eab8faa6f208faabc2e15)
1 /* Check calls to formatted I/O functions (-Wformat).
2    Copyright (C) 1992-2017 Free Software Foundation, Inc.
3 
4 This file is part of GCC.
5 
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10 
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15 
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19 
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "c-target.h"
25 #include "c-common.h"
26 #include "alloc-pool.h"
27 #include "stringpool.h"
28 #include "c-objc.h"
29 #include "intl.h"
30 #include "langhooks.h"
31 #include "c-format.h"
32 #include "diagnostic.h"
33 #include "substring-locations.h"
34 #include "selftest.h"
35 #include "builtins.h"
36 
37 /* Handle attributes associated with format checking.  */
38 
39 /* This must be in the same order as format_types, except for
40    format_type_error.  Target-specific format types do not have
41    matching enum values.  */
42 enum format_type { printf_format_type, asm_fprintf_format_type,
43 		   gcc_diag_format_type, gcc_tdiag_format_type,
44 		   gcc_cdiag_format_type,
45 		   gcc_cxxdiag_format_type, gcc_gfc_format_type,
46 		   gcc_objc_string_format_type,
47 		   format_type_error = -1};
48 
49 struct function_format_info
50 {
51   int format_type;			/* type of format (printf, scanf, etc.) */
52   unsigned HOST_WIDE_INT format_num;	/* number of format argument */
53   unsigned HOST_WIDE_INT first_arg_num;	/* number of first arg (zero for varargs) */
54 };
55 
56 static bool decode_format_attr (tree, function_format_info *, int);
57 static int decode_format_type (const char *);
58 
59 static bool check_format_string (tree argument,
60 				 unsigned HOST_WIDE_INT format_num,
61 				 int flags, bool *no_add_attrs,
62 				 int expected_format_type);
63 static bool get_constant (tree expr, unsigned HOST_WIDE_INT *value,
64 			  int validated_p);
65 static const char *convert_format_name_to_system_name (const char *attr_name);
66 static bool cmp_attribs (const char *tattr_name, const char *attr_name);
67 
68 static int first_target_format_type;
69 static const char *format_name (int format_num);
70 static int format_flags (int format_num);
71 
72 /* Emit a warning as per format_warning_va, but construct the substring_loc
73    for the character at offset (CHAR_IDX - 1) within a string constant
74    FORMAT_STRING_CST at FMT_STRING_LOC.  */
75 
76 ATTRIBUTE_GCC_DIAG (5,6)
77 static bool
78 format_warning_at_char (location_t fmt_string_loc, tree format_string_cst,
79 			int char_idx, int opt, const char *gmsgid, ...)
80 {
81   va_list ap;
82   va_start (ap, gmsgid);
83   tree string_type = TREE_TYPE (format_string_cst);
84 
85   /* The callers are of the form:
86        format_warning (format_string_loc, format_string_cst,
87 		       format_chars - orig_format_chars,
88       where format_chars has already been incremented, so that
89       CHAR_IDX is one character beyond where the warning should
90       be emitted.  Fix it.  */
91   char_idx -= 1;
92 
93   substring_loc fmt_loc (fmt_string_loc, string_type, char_idx, char_idx,
94 			 char_idx);
95   bool warned = format_warning_va (fmt_loc, NULL, NULL, opt, gmsgid, &ap);
96   va_end (ap);
97 
98   return warned;
99 }
100 
101 /* Check that we have a pointer to a string suitable for use as a format.
102    The default is to check for a char type.
103    For objective-c dialects, this is extended to include references to string
104    objects validated by objc_string_ref_type_p ().
105    Targets may also provide a string object type that can be used within c and
106    c++ and shared with their respective objective-c dialects. In this case the
107    reference to a format string is checked for validity via a hook.
108 
109    The function returns true if strref points to any string type valid for the
110    language dialect and target.  */
111 
112 static bool
113 valid_stringptr_type_p (tree strref)
114 {
115   return (strref != NULL
116 	  && TREE_CODE (strref) == POINTER_TYPE
117 	  && (TYPE_MAIN_VARIANT (TREE_TYPE (strref)) == char_type_node
118 	      || objc_string_ref_type_p (strref)
119 	      || (*targetcm.string_object_ref_type_p) ((const_tree) strref)));
120 }
121 
122 /* Handle a "format_arg" attribute; arguments as in
123    struct attribute_spec.handler.  */
124 tree
125 handle_format_arg_attribute (tree *node, tree ARG_UNUSED (name),
126 			     tree args, int flags, bool *no_add_attrs)
127 {
128   tree type = *node;
129   tree format_num_expr = TREE_VALUE (args);
130   unsigned HOST_WIDE_INT format_num = 0;
131 
132   if (!get_constant (format_num_expr, &format_num, 0))
133     {
134       error ("format string has invalid operand number");
135       *no_add_attrs = true;
136       return NULL_TREE;
137     }
138 
139   if (prototype_p (type))
140     {
141       /* The format arg can be any string reference valid for the language and
142 	target.  We cannot be more specific in this case.  */
143       if (!check_format_string (type, format_num, flags, no_add_attrs, -1))
144 	return NULL_TREE;
145     }
146 
147   if (!valid_stringptr_type_p (TREE_TYPE (type)))
148     {
149       if (!(flags & (int) ATTR_FLAG_BUILT_IN))
150 	error ("function does not return string type");
151       *no_add_attrs = true;
152       return NULL_TREE;
153     }
154 
155   return NULL_TREE;
156 }
157 
158 /* Verify that the format_num argument is actually a string reference suitable,
159    for the language dialect and target (in case the format attribute is in
160    error).  When we know the specific reference type expected, this is also
161    checked.  */
162 static bool
163 check_format_string (tree fntype, unsigned HOST_WIDE_INT format_num,
164 		     int flags, bool *no_add_attrs, int expected_format_type)
165 {
166   unsigned HOST_WIDE_INT i;
167   bool is_objc_sref, is_target_sref, is_char_ref;
168   tree ref;
169   int fmt_flags;
170   function_args_iterator iter;
171 
172   i = 1;
173   FOREACH_FUNCTION_ARGS (fntype, ref, iter)
174     {
175       if (i == format_num)
176 	break;
177       i++;
178     }
179 
180   if (!ref
181       || !valid_stringptr_type_p (ref))
182     {
183       if (!(flags & (int) ATTR_FLAG_BUILT_IN))
184 	error ("format string argument is not a string type");
185       *no_add_attrs = true;
186       return false;
187     }
188 
189   /* We only know that we want a suitable string reference.  */
190   if (expected_format_type < 0)
191     return true;
192 
193   /* Now check that the arg matches the expected type.  */
194   is_char_ref =
195     (TYPE_MAIN_VARIANT (TREE_TYPE (ref)) == char_type_node);
196 
197   fmt_flags = format_flags (expected_format_type);
198   is_objc_sref = is_target_sref = false;
199   if (!is_char_ref)
200     is_objc_sref = objc_string_ref_type_p (ref);
201 
202   if (!(fmt_flags & FMT_FLAG_PARSE_ARG_CONVERT_EXTERNAL))
203     {
204       if (is_char_ref)
205 	return true; /* OK, we expected a char and found one.  */
206       else
207 	{
208 	  /* We expected a char but found an extended string type.  */
209 	  if (is_objc_sref)
210 	    error ("found a %qs reference but the format argument should"
211 		   " be a string", format_name (gcc_objc_string_format_type));
212 	  else
213 	    error ("found a %qT but the format argument should be a string",
214 		   ref);
215 	  *no_add_attrs = true;
216 	  return false;
217 	}
218     }
219 
220   /* We expect a string object type as the format arg.  */
221   if (is_char_ref)
222     {
223       error ("format argument should be a %qs reference but"
224 	     " a string was found", format_name (expected_format_type));
225       *no_add_attrs = true;
226       return false;
227     }
228 
229   /* We will assert that objective-c will support either its own string type
230      or the target-supplied variant.  */
231   if (!is_objc_sref)
232     is_target_sref = (*targetcm.string_object_ref_type_p) ((const_tree) ref);
233 
234   if (expected_format_type == (int) gcc_objc_string_format_type
235       && (is_objc_sref || is_target_sref))
236     return true;
237 
238   /* We will allow a target string ref to match only itself.  */
239   if (first_target_format_type
240       && expected_format_type >= first_target_format_type
241       && is_target_sref)
242     return true;
243   else
244     {
245       error ("format argument should be a %qs reference",
246 	      format_name (expected_format_type));
247       *no_add_attrs = true;
248       return false;
249     }
250 
251   gcc_unreachable ();
252 }
253 
254 /* Verify EXPR is a constant, and store its value.
255    If validated_p is true there should be no errors.
256    Returns true on success, false otherwise.  */
257 static bool
258 get_constant (tree expr, unsigned HOST_WIDE_INT *value, int validated_p)
259 {
260   if (!tree_fits_uhwi_p (expr))
261     {
262       gcc_assert (!validated_p);
263       return false;
264     }
265 
266   *value = TREE_INT_CST_LOW (expr);
267 
268   return true;
269 }
270 
271 /* Decode the arguments to a "format" attribute into a
272    function_format_info structure.  It is already known that the list
273    is of the right length.  If VALIDATED_P is true, then these
274    attributes have already been validated and must not be erroneous;
275    if false, it will give an error message.  Returns true if the
276    attributes are successfully decoded, false otherwise.  */
277 
278 static bool
279 decode_format_attr (tree args, function_format_info *info, int validated_p)
280 {
281   tree format_type_id = TREE_VALUE (args);
282   tree format_num_expr = TREE_VALUE (TREE_CHAIN (args));
283   tree first_arg_num_expr
284     = TREE_VALUE (TREE_CHAIN (TREE_CHAIN (args)));
285 
286   if (TREE_CODE (format_type_id) != IDENTIFIER_NODE)
287     {
288       gcc_assert (!validated_p);
289       error ("unrecognized format specifier");
290       return false;
291     }
292   else
293     {
294       const char *p = IDENTIFIER_POINTER (format_type_id);
295 
296       p = convert_format_name_to_system_name (p);
297 
298       info->format_type = decode_format_type (p);
299 
300       if (!c_dialect_objc ()
301 	   && info->format_type == gcc_objc_string_format_type)
302 	{
303 	  gcc_assert (!validated_p);
304 	  warning (OPT_Wformat_, "%qE is only allowed in Objective-C dialects",
305 		   format_type_id);
306 	  info->format_type = format_type_error;
307 	  return false;
308 	}
309 
310       if (info->format_type == format_type_error)
311 	{
312 	  gcc_assert (!validated_p);
313 	  warning (OPT_Wformat_, "%qE is an unrecognized format function type",
314 		   format_type_id);
315 	  return false;
316 	}
317     }
318 
319   if (!get_constant (format_num_expr, &info->format_num, validated_p))
320     {
321       error ("format string has invalid operand number");
322       return false;
323     }
324 
325   if (!get_constant (first_arg_num_expr, &info->first_arg_num, validated_p))
326     {
327       error ("%<...%> has invalid operand number");
328       return false;
329     }
330 
331   if (info->first_arg_num != 0 && info->first_arg_num <= info->format_num)
332     {
333       gcc_assert (!validated_p);
334       error ("format string argument follows the args to be formatted");
335       return false;
336     }
337 
338   return true;
339 }
340 
341 /* Check a call to a format function against a parameter list.  */
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	(cxx_dialect < cxx11 ? STD_C94 : STD_C99)
346 /* The C standard version we are checking formats against when pedantic.  */
347 #define C_STD_VER		((int) (c_dialect_cxx ()		   \
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_dialect_cxx ()		\
356 				 ? (cxx_dialect < cxx11 ? "ISO C++98" \
357 				    : "ISO C++11")		\
358 				 : ((FEATURE_VER) == STD_EXT	\
359 				    ? "ISO C"			\
360 				    : "ISO C90"))
361 /* Adjust a C standard version, which may be STD_C9L, to account for
362    -Wno-long-long.  Returns other standard versions unchanged.  */
363 #define ADJ_STD(VER)		((int) ((VER) == STD_C9L		      \
364 				       ? (warn_long_long ? STD_C99 : STD_C89) \
365 				       : (VER)))
366 
367 /* Enum describing the kind of specifiers present in the format and
368    requiring an argument.  */
369 enum format_specifier_kind {
370   CF_KIND_FORMAT,
371   CF_KIND_FIELD_WIDTH,
372   CF_KIND_FIELD_PRECISION
373 };
374 
375 static const char *kind_descriptions[] = {
376   N_("format"),
377   N_("field width specifier"),
378   N_("field precision specifier")
379 };
380 
381 /* Structure describing details of a type expected in format checking,
382    and the type to check against it.  */
383 struct format_wanted_type
384 {
385   /* The type wanted.  */
386   tree wanted_type;
387   /* The name of this type to use in diagnostics.  */
388   const char *wanted_type_name;
389   /* Should be type checked just for scalar width identity.  */
390   int scalar_identity_flag;
391   /* The level of indirection through pointers at which this type occurs.  */
392   int pointer_count;
393   /* Whether, when pointer_count is 1, to allow any character type when
394      pedantic, rather than just the character or void type specified.  */
395   int char_lenient_flag;
396   /* Whether the argument, dereferenced once, is written into and so the
397      argument must not be a pointer to a const-qualified type.  */
398   int writing_in_flag;
399   /* Whether the argument, dereferenced once, is read from and so
400      must not be a NULL pointer.  */
401   int reading_from_flag;
402   /* The kind of specifier that this type is used for.  */
403   enum format_specifier_kind kind;
404   /* The starting character of the specifier.  This never includes the
405      initial percent sign.  */
406   const char *format_start;
407   /* The length of the specifier.  */
408   int format_length;
409   /* The actual parameter to check against the wanted type.  */
410   tree param;
411   /* The argument number of that parameter.  */
412   int arg_num;
413   /* The offset location of this argument with respect to the format
414      string location.  */
415   unsigned int offset_loc;
416   /* The next type to check for this format conversion, or NULL if none.  */
417   struct format_wanted_type *next;
418 };
419 
420 /* Convenience macro for format_length_info meaning unused.  */
421 #define NO_FMT NULL, FMT_LEN_none, STD_C89
422 
423 static const format_length_info printf_length_specs[] =
424 {
425   { "h", FMT_LEN_h, STD_C89, "hh", FMT_LEN_hh, STD_C99, 0 },
426   { "l", FMT_LEN_l, STD_C89, "ll", FMT_LEN_ll, STD_C9L, 0 },
427   { "q", FMT_LEN_ll, STD_EXT, NO_FMT, 0 },
428   { "L", FMT_LEN_L, STD_C89, NO_FMT, 0 },
429   { "z", FMT_LEN_z, STD_C99, NO_FMT, 0 },
430   { "Z", FMT_LEN_z, STD_EXT, NO_FMT, 0 },
431   { "t", FMT_LEN_t, STD_C99, NO_FMT, 0 },
432   { "j", FMT_LEN_j, STD_C99, NO_FMT, 0 },
433   { "H", FMT_LEN_H, STD_EXT, NO_FMT, 0 },
434   { "D", FMT_LEN_D, STD_EXT, "DD", FMT_LEN_DD, STD_EXT, 0 },
435   { NO_FMT, NO_FMT, 0 }
436 };
437 
438 /* Length specifiers valid for asm_fprintf.  */
439 static const format_length_info asm_fprintf_length_specs[] =
440 {
441   { "l", FMT_LEN_l, STD_C89, "ll", FMT_LEN_ll, STD_C89, 0 },
442   { "w", FMT_LEN_none, STD_C89, NO_FMT, 0 },
443   { NO_FMT, NO_FMT, 0 }
444 };
445 
446 /* Length specifiers valid for GCC diagnostics.  */
447 static const format_length_info gcc_diag_length_specs[] =
448 {
449   { "l", FMT_LEN_l, STD_C89, "ll", FMT_LEN_ll, STD_C89, 0 },
450   { "w", FMT_LEN_none, STD_C89, NO_FMT, 0 },
451   { NO_FMT, NO_FMT, 0 }
452 };
453 
454 /* The custom diagnostics all accept the same length specifiers.  */
455 #define gcc_tdiag_length_specs gcc_diag_length_specs
456 #define gcc_cdiag_length_specs gcc_diag_length_specs
457 #define gcc_cxxdiag_length_specs gcc_diag_length_specs
458 
459 /* This differs from printf_length_specs only in that "Z" is not accepted.  */
460 static const format_length_info scanf_length_specs[] =
461 {
462   { "h", FMT_LEN_h, STD_C89, "hh", FMT_LEN_hh, STD_C99, 0 },
463   { "l", FMT_LEN_l, STD_C89, "ll", FMT_LEN_ll, STD_C9L, 0 },
464   { "q", FMT_LEN_ll, STD_EXT, NO_FMT, 0 },
465   { "L", FMT_LEN_L, STD_C89, NO_FMT, 0 },
466   { "z", FMT_LEN_z, STD_C99, NO_FMT, 0 },
467   { "t", FMT_LEN_t, STD_C99, NO_FMT, 0 },
468   { "j", FMT_LEN_j, STD_C99, NO_FMT, 0 },
469   { "H", FMT_LEN_H, STD_EXT, NO_FMT, 0 },
470   { "D", FMT_LEN_D, STD_EXT, "DD", FMT_LEN_DD, STD_EXT, 0 },
471   { NO_FMT, NO_FMT, 0 }
472 };
473 
474 
475 /* All tables for strfmon use STD_C89 everywhere, since -pedantic warnings
476    make no sense for a format type not part of any C standard version.  */
477 static const format_length_info strfmon_length_specs[] =
478 {
479   /* A GNU extension.  */
480   { "L", FMT_LEN_L, STD_C89, NO_FMT, 0 },
481   { NO_FMT, NO_FMT, 0 }
482 };
483 
484 
485 /* For now, the Fortran front-end routines only use l as length modifier.  */
486 static const format_length_info gcc_gfc_length_specs[] =
487 {
488   { "l", FMT_LEN_l, STD_C89, NO_FMT, 0 },
489   { NO_FMT, NO_FMT, 0 }
490 };
491 
492 
493 static const format_flag_spec printf_flag_specs[] =
494 {
495   { ' ',  0, 0, N_("' ' flag"),        N_("the ' ' printf flag"),              STD_C89 },
496   { '+',  0, 0, N_("'+' flag"),        N_("the '+' printf flag"),              STD_C89 },
497   { '#',  0, 0, N_("'#' flag"),        N_("the '#' printf flag"),              STD_C89 },
498   { '0',  0, 0, N_("'0' flag"),        N_("the '0' printf flag"),              STD_C89 },
499   { '-',  0, 0, N_("'-' flag"),        N_("the '-' printf flag"),              STD_C89 },
500   { '\'', 0, 0, N_("''' flag"),        N_("the ''' printf flag"),              STD_EXT },
501   { 'I',  0, 0, N_("'I' flag"),        N_("the 'I' printf flag"),              STD_EXT },
502   { 'w',  0, 0, N_("field width"),     N_("field width in printf format"),     STD_C89 },
503   { 'p',  0, 0, N_("precision"),       N_("precision in printf format"),       STD_C89 },
504   { 'L',  0, 0, N_("length modifier"), N_("length modifier in printf format"), STD_C89 },
505   { 0, 0, 0, NULL, NULL, STD_C89 }
506 };
507 
508 
509 static const format_flag_pair printf_flag_pairs[] =
510 {
511   { ' ', '+', 1, 0   },
512   { '0', '-', 1, 0   },
513   { '0', 'p', 1, 'i' },
514   { 0, 0, 0, 0 }
515 };
516 
517 static const format_flag_spec asm_fprintf_flag_specs[] =
518 {
519   { ' ',  0, 0, N_("' ' flag"),        N_("the ' ' printf flag"),              STD_C89 },
520   { '+',  0, 0, N_("'+' flag"),        N_("the '+' printf flag"),              STD_C89 },
521   { '#',  0, 0, N_("'#' flag"),        N_("the '#' printf flag"),              STD_C89 },
522   { '0',  0, 0, N_("'0' flag"),        N_("the '0' printf flag"),              STD_C89 },
523   { '-',  0, 0, N_("'-' flag"),        N_("the '-' printf flag"),              STD_C89 },
524   { 'w',  0, 0, N_("field width"),     N_("field width in printf format"),     STD_C89 },
525   { 'p',  0, 0, N_("precision"),       N_("precision in printf format"),       STD_C89 },
526   { 'L',  0, 0, N_("length modifier"), N_("length modifier in printf format"), STD_C89 },
527   { 0, 0, 0, NULL, NULL, STD_C89 }
528 };
529 
530 static const format_flag_pair asm_fprintf_flag_pairs[] =
531 {
532   { ' ', '+', 1, 0   },
533   { '0', '-', 1, 0   },
534   { '0', 'p', 1, 'i' },
535   { 0, 0, 0, 0 }
536 };
537 
538 static const format_flag_pair gcc_diag_flag_pairs[] =
539 {
540   { 0, 0, 0, 0 }
541 };
542 
543 #define gcc_tdiag_flag_pairs gcc_diag_flag_pairs
544 #define gcc_cdiag_flag_pairs gcc_diag_flag_pairs
545 #define gcc_cxxdiag_flag_pairs gcc_diag_flag_pairs
546 #define gcc_gfc_flag_pairs gcc_diag_flag_pairs
547 
548 static const format_flag_spec gcc_diag_flag_specs[] =
549 {
550   { '+',  0, 0, N_("'+' flag"),        N_("the '+' printf flag"),              STD_C89 },
551   { '#',  0, 0, N_("'#' flag"),        N_("the '#' printf flag"),              STD_C89 },
552   { 'q',  0, 0, N_("'q' flag"),        N_("the 'q' diagnostic flag"),          STD_C89 },
553   { 'p',  0, 0, N_("precision"),       N_("precision in printf format"),       STD_C89 },
554   { 'L',  0, 0, N_("length modifier"), N_("length modifier in printf format"), STD_C89 },
555   { 0, 0, 0, NULL, NULL, STD_C89 }
556 };
557 
558 #define gcc_tdiag_flag_specs gcc_diag_flag_specs
559 #define gcc_cdiag_flag_specs gcc_diag_flag_specs
560 #define gcc_cxxdiag_flag_specs gcc_diag_flag_specs
561 #define gcc_gfc_flag_specs gcc_diag_flag_specs
562 
563 static const format_flag_spec scanf_flag_specs[] =
564 {
565   { '*',  0, 0, N_("assignment suppression"), N_("the assignment suppression scanf feature"), STD_C89 },
566   { 'a',  0, 0, N_("'a' flag"),               N_("the 'a' scanf flag"),                       STD_EXT },
567   { 'm',  0, 0, N_("'m' flag"),               N_("the 'm' scanf flag"),                       STD_EXT },
568   { 'w',  0, 0, N_("field width"),            N_("field width in scanf format"),              STD_C89 },
569   { 'L',  0, 0, N_("length modifier"),        N_("length modifier in scanf format"),          STD_C89 },
570   { '\'', 0, 0, N_("''' flag"),               N_("the ''' scanf flag"),                       STD_EXT },
571   { 'I',  0, 0, N_("'I' flag"),               N_("the 'I' scanf flag"),                       STD_EXT },
572   { 0, 0, 0, NULL, NULL, STD_C89 }
573 };
574 
575 
576 static const format_flag_pair scanf_flag_pairs[] =
577 {
578   { '*', 'L', 0, 0 },
579   { 'a', 'm', 0, 0 },
580   { 0, 0, 0, 0 }
581 };
582 
583 
584 static const format_flag_spec strftime_flag_specs[] =
585 {
586   { '_', 0,   0, N_("'_' flag"),     N_("the '_' strftime flag"),          STD_EXT },
587   { '-', 0,   0, N_("'-' flag"),     N_("the '-' strftime flag"),          STD_EXT },
588   { '0', 0,   0, N_("'0' flag"),     N_("the '0' strftime flag"),          STD_EXT },
589   { '^', 0,   0, N_("'^' flag"),     N_("the '^' strftime flag"),          STD_EXT },
590   { '#', 0,   0, N_("'#' flag"),     N_("the '#' strftime flag"),          STD_EXT },
591   { 'w', 0,   0, N_("field width"),  N_("field width in strftime format"), STD_EXT },
592   { 'E', 0,   0, N_("'E' modifier"), N_("the 'E' strftime modifier"),      STD_C99 },
593   { 'O', 0,   0, N_("'O' modifier"), N_("the 'O' strftime modifier"),      STD_C99 },
594   { 'O', 'o', 0, NULL,               N_("the 'O' modifier"),               STD_EXT },
595   { 0, 0, 0, NULL, NULL, STD_C89 }
596 };
597 
598 
599 static const format_flag_pair strftime_flag_pairs[] =
600 {
601   { 'E', 'O', 0, 0 },
602   { '_', '-', 0, 0 },
603   { '_', '0', 0, 0 },
604   { '-', '0', 0, 0 },
605   { '^', '#', 0, 0 },
606   { 0, 0, 0, 0 }
607 };
608 
609 
610 static const format_flag_spec strfmon_flag_specs[] =
611 {
612   { '=',  0, 1, N_("fill character"),  N_("fill character in strfmon format"),  STD_C89 },
613   { '^',  0, 0, N_("'^' flag"),        N_("the '^' strfmon flag"),              STD_C89 },
614   { '+',  0, 0, N_("'+' flag"),        N_("the '+' strfmon flag"),              STD_C89 },
615   { '(',  0, 0, N_("'(' flag"),        N_("the '(' strfmon flag"),              STD_C89 },
616   { '!',  0, 0, N_("'!' flag"),        N_("the '!' strfmon flag"),              STD_C89 },
617   { '-',  0, 0, N_("'-' flag"),        N_("the '-' strfmon flag"),              STD_C89 },
618   { 'w',  0, 0, N_("field width"),     N_("field width in strfmon format"),     STD_C89 },
619   { '#',  0, 0, N_("left precision"),  N_("left precision in strfmon format"),  STD_C89 },
620   { 'p',  0, 0, N_("right precision"), N_("right precision in strfmon format"), STD_C89 },
621   { 'L',  0, 0, N_("length modifier"), N_("length modifier in strfmon format"), STD_C89 },
622   { 0, 0, 0, NULL, NULL, STD_C89 }
623 };
624 
625 static const format_flag_pair strfmon_flag_pairs[] =
626 {
627   { '+', '(', 0, 0 },
628   { 0, 0, 0, 0 }
629 };
630 
631 
632 static const format_char_info print_char_table[] =
633 {
634   /* C89 conversion specifiers.  */
635   { "di",  0, STD_C89, { T89_I,   T99_SC,  T89_S,   T89_L,   T9L_LL,  TEX_LL,  T99_SST, T99_PD,  T99_IM,  BADLEN,  BADLEN,  BADLEN  }, "-wp0 +'I",  "i",  NULL },
636   { "oxX", 0, STD_C89, { T89_UI,  T99_UC,  T89_US,  T89_UL,  T9L_ULL, TEX_ULL, T99_ST,  T99_UPD, T99_UIM, BADLEN,  BADLEN,  BADLEN }, "-wp0#",     "i",  NULL },
637   { "u",   0, STD_C89, { T89_UI,  T99_UC,  T89_US,  T89_UL,  T9L_ULL, TEX_ULL, T99_ST,  T99_UPD, T99_UIM, BADLEN,  BADLEN,  BADLEN }, "-wp0'I",    "i",  NULL },
638   { "fgG", 0, STD_C89, { T89_D,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T89_LD,  BADLEN,  BADLEN,  BADLEN,  TEX_D32, TEX_D64, TEX_D128 }, "-wp0 +#'I", "",   NULL },
639   { "eE",  0, STD_C89, { T89_D,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T89_LD,  BADLEN,  BADLEN,  BADLEN,  TEX_D32, TEX_D64, TEX_D128 }, "-wp0 +#I",  "",   NULL },
640   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T94_WI,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-w",        "",   NULL },
641   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  T94_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-wp",       "cR", NULL },
642   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-w",        "c",  NULL },
643   { "n",   1, STD_C89, { T89_I,   T99_SC,  T89_S,   T89_L,   T9L_LL,  BADLEN,  T99_SST, T99_PD,  T99_IM,  BADLEN,  BADLEN,  BADLEN }, "",          "W",  NULL },
644   /* C99 conversion specifiers.  */
645   { "F",   0, STD_C99, { T99_D,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T99_LD,  BADLEN,  BADLEN,  BADLEN,  TEX_D32, TEX_D64, TEX_D128 }, "-wp0 +#'I", "",   NULL },
646   { "aA",  0, STD_C99, { T99_D,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T99_LD,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-wp0 +#",   "",   NULL },
647   /* X/Open conversion specifiers.  */
648   { "C",   0, STD_EXT, { TEX_WI,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-w",        "",   NULL },
649   { "S",   1, STD_EXT, { TEX_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-wp",       "R",  NULL },
650   /* GNU conversion specifiers.  */
651   { "m",   0, STD_EXT, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "-wp",       "",   NULL },
652   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
653 };
654 
655 static const format_char_info asm_fprintf_char_table[] =
656 {
657   /* C89 conversion specifiers.  */
658   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp0 +",  "i", NULL },
659   { "oxX", 0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp0#",   "i", NULL },
660   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp0",    "i", NULL },
661   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-w",       "", NULL },
662   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "-wp",    "cR", NULL },
663 
664   /* asm_fprintf conversion specifiers.  */
665   { "O",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
666   { "R",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
667   { "I",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
668   { "L",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
669   { "U",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
670   { "r",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",  "", NULL },
671   { "@",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
672   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
673 };
674 
675 static const format_char_info gcc_diag_char_table[] =
676 {
677   /* C89 conversion specifiers.  */
678   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
679   { "ox",  0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
680   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
681   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
682   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "pq", "cR", NULL },
683   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "c",  NULL },
684 
685   /* Custom conversion specifiers.  */
686 
687   /* These will require a "tree" at runtime.  */
688   { "K",   0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",    "",   NULL },
689 
690   { "r",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",    "cR",   NULL },
691   { "<>'R",0, STD_C89, NOARGUMENTS, "",      "",   NULL },
692   { "m",   0, STD_C89, NOARGUMENTS, "q",     "",   NULL },
693   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
694 };
695 
696 static const format_char_info gcc_tdiag_char_table[] =
697 {
698   /* C89 conversion specifiers.  */
699   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
700   { "ox",  0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
701   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
702   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
703   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "pq", "cR", NULL },
704   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "c",  NULL },
705 
706   /* Custom conversion specifiers.  */
707 
708   /* These will require a "tree" at runtime.  */
709   { "DFKTEV", 0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q+", "",   NULL },
710 
711   { "v",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q#",  "",   NULL },
712 
713   { "r",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",    "cR",   NULL },
714   { "<>'R",0, STD_C89, NOARGUMENTS, "",      "",   NULL },
715   { "m",   0, STD_C89, NOARGUMENTS, "q",     "",   NULL },
716   { "Z",   1, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",    "", &gcc_tdiag_char_table[0] },
717   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
718 };
719 
720 static const format_char_info gcc_cdiag_char_table[] =
721 {
722   /* C89 conversion specifiers.  */
723   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
724   { "ox",  0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
725   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
726   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
727   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "pq", "cR", NULL },
728   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "c",  NULL },
729 
730   /* Custom conversion specifiers.  */
731 
732   /* These will require a "tree" at runtime.  */
733   { "DEFKTV", 0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q+", "",   NULL },
734 
735   { "v",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q#",  "",   NULL },
736 
737   { "r",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",    "cR",   NULL },
738   { "<>'R",0, STD_C89, NOARGUMENTS, "",      "",   NULL },
739   { "m",   0, STD_C89, NOARGUMENTS, "q",     "",   NULL },
740   { "Z",   1, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",    "", &gcc_tdiag_char_table[0] },
741   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
742 };
743 
744 static const format_char_info gcc_cxxdiag_char_table[] =
745 {
746   /* C89 conversion specifiers.  */
747   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   T9L_LL,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
748   { "ox",  0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
749   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  T9L_ULL, BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
750   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
751   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "pq", "cR", NULL },
752   { "p",   1, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "c",  NULL },
753 
754   /* Custom conversion specifiers.  */
755 
756   /* These will require a "tree" at runtime.  */
757   { "ADEFKSTVX",0,STD_C89,{ T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q+#",   "",   NULL },
758 
759   { "v", 0,STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q#",  "",   NULL },
760 
761   /* These accept either an 'int' or an 'enum tree_code' (which is handled as an 'int'.)  */
762   { "CLOPQ",0,STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q",  "",   NULL },
763 
764   { "r",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",    "cR",   NULL },
765   { "<>'R",0, STD_C89, NOARGUMENTS, "",      "",   NULL },
766   { "m",   0, STD_C89, NOARGUMENTS, "q",     "",   NULL },
767   { "Z",   1, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "",    "", &gcc_tdiag_char_table[0] },
768   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
769 };
770 
771 static const format_char_info gcc_gfc_char_table[] =
772 {
773   /* C89 conversion specifiers.  */
774   { "di",  0, STD_C89, { T89_I,   BADLEN,  BADLEN,  T89_L,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q", "", NULL },
775   { "u",   0, STD_C89, { T89_UI,  BADLEN,  BADLEN,  T89_UL,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q", "", NULL },
776   { "c",   0, STD_C89, { T89_I,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q", "", NULL },
777   { "s",   1, STD_C89, { T89_C,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "q", "cR", NULL },
778 
779   /* gfc conversion specifiers.  */
780 
781   { "C",   0, STD_C89, NOARGUMENTS, "",      "",   NULL },
782 
783   /* This will require a "locus" at runtime.  */
784   { "L",   0, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN  }, "", "R", NULL },
785 
786   /* These will require nothing.  */
787   { "<>",0, STD_C89, NOARGUMENTS, "",      "",   NULL },
788   { NULL,  0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
789 };
790 
791 static const format_char_info scan_char_table[] =
792 {
793   /* C89 conversion specifiers.  */
794   { "di",    1, STD_C89, { T89_I,   T99_SC,  T89_S,   T89_L,   T9L_LL,  TEX_LL,  T99_SST, T99_PD,  T99_IM,  BADLEN,  BADLEN,  BADLEN }, "*w'I", "W",   NULL },
795   { "u",     1, STD_C89, { T89_UI,  T99_UC,  T89_US,  T89_UL,  T9L_ULL, TEX_ULL, T99_ST,  T99_UPD, T99_UIM, BADLEN,  BADLEN,  BADLEN }, "*w'I", "W",   NULL },
796   { "oxX",   1, STD_C89, { T89_UI,  T99_UC,  T89_US,  T89_UL,  T9L_ULL, TEX_ULL, T99_ST,  T99_UPD, T99_UIM, BADLEN,  BADLEN,  BADLEN }, "*w",   "W",   NULL },
797   { "efgEG", 1, STD_C89, { T89_F,   BADLEN,  BADLEN,  T89_D,   BADLEN,  T89_LD,  BADLEN,  BADLEN,  BADLEN,  TEX_D32, TEX_D64, TEX_D128 }, "*w'",  "W",   NULL },
798   { "c",     1, STD_C89, { T89_C,   BADLEN,  BADLEN,  T94_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*mw",   "cW",  NULL },
799   { "s",     1, STD_C89, { T89_C,   BADLEN,  BADLEN,  T94_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*amw",  "cW",  NULL },
800   { "[",     1, STD_C89, { T89_C,   BADLEN,  BADLEN,  T94_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*amw",  "cW[", NULL },
801   { "p",     2, STD_C89, { T89_V,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*w",   "W",   NULL },
802   { "n",     1, STD_C89, { T89_I,   T99_SC,  T89_S,   T89_L,   T9L_LL,  BADLEN,  T99_SST, T99_PD,  T99_IM,  BADLEN,  BADLEN,  BADLEN }, "",     "W",   NULL },
803   /* C99 conversion specifiers.  */
804   { "F",   1, STD_C99, { T99_F,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T99_LD,  BADLEN,  BADLEN,  BADLEN,  TEX_D32, TEX_D64, TEX_D128 }, "*w'",  "W",   NULL },
805   { "aA",   1, STD_C99, { T99_F,   BADLEN,  BADLEN,  T99_D,   BADLEN,  T99_LD,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*w'",  "W",   NULL },
806   /* X/Open conversion specifiers.  */
807   { "C",     1, STD_EXT, { TEX_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*mw",   "W",   NULL },
808   { "S",     1, STD_EXT, { TEX_W,   BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN,  BADLEN }, "*amw",  "W",   NULL },
809   { NULL, 0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
810 };
811 
812 static const format_char_info time_char_table[] =
813 {
814   /* C89 conversion specifiers.  */
815   { "ABZab",		0, STD_C89, NOLENGTHS, "^#",     "",   NULL },
816   { "cx",		0, STD_C89, NOLENGTHS, "E",      "3",  NULL },
817   { "HIMSUWdmw",	0, STD_C89, NOLENGTHS, "-_0Ow",  "",   NULL },
818   { "j",		0, STD_C89, NOLENGTHS, "-_0Ow",  "o",  NULL },
819   { "p",		0, STD_C89, NOLENGTHS, "#",      "",   NULL },
820   { "X",		0, STD_C89, NOLENGTHS, "E",      "",   NULL },
821   { "y",		0, STD_C89, NOLENGTHS, "EO-_0w", "4",  NULL },
822   { "Y",		0, STD_C89, NOLENGTHS, "-_0EOw", "o",  NULL },
823   { "%",		0, STD_C89, NOLENGTHS, "",       "",   NULL },
824   /* C99 conversion specifiers.  */
825   { "C",		0, STD_C99, NOLENGTHS, "-_0EOw", "o",  NULL },
826   { "D",		0, STD_C99, NOLENGTHS, "",       "2",  NULL },
827   { "eVu",		0, STD_C99, NOLENGTHS, "-_0Ow",  "",   NULL },
828   { "FRTnrt",		0, STD_C99, NOLENGTHS, "",       "",   NULL },
829   { "g",		0, STD_C99, NOLENGTHS, "O-_0w",  "2o", NULL },
830   { "G",		0, STD_C99, NOLENGTHS, "-_0Ow",  "o",  NULL },
831   { "h",		0, STD_C99, NOLENGTHS, "^#",     "",   NULL },
832   { "z",		0, STD_C99, NOLENGTHS, "O",      "o",  NULL },
833   /* GNU conversion specifiers.  */
834   { "kls",		0, STD_EXT, NOLENGTHS, "-_0Ow",  "",   NULL },
835   { "P",		0, STD_EXT, NOLENGTHS, "",       "",   NULL },
836   { NULL,		0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
837 };
838 
839 static const format_char_info monetary_char_table[] =
840 {
841   { "in", 0, STD_C89, { T89_D, BADLEN, BADLEN, BADLEN, BADLEN, T89_LD, BADLEN, BADLEN, BADLEN, BADLEN, BADLEN, BADLEN }, "=^+(!-w#p", "", NULL },
842   { NULL, 0, STD_C89, NOLENGTHS, NULL, NULL, NULL }
843 };
844 
845 /* This must be in the same order as enum format_type.  */
846 static const format_kind_info format_types_orig[] =
847 {
848   { "gnu_printf",   printf_length_specs,  print_char_table, " +#0-'I", NULL,
849     printf_flag_specs, printf_flag_pairs,
850     FMT_FLAG_ARG_CONVERT|FMT_FLAG_DOLLAR_MULTIPLE|FMT_FLAG_USE_DOLLAR|FMT_FLAG_EMPTY_PREC_OK,
851     'w', 0, 'p', 0, 'L', 0,
852     &integer_type_node, &integer_type_node, format_type_error
853   },
854   { "asm_fprintf",   asm_fprintf_length_specs,  asm_fprintf_char_table, " +#0-", NULL,
855     asm_fprintf_flag_specs, asm_fprintf_flag_pairs,
856     FMT_FLAG_ARG_CONVERT|FMT_FLAG_EMPTY_PREC_OK,
857     'w', 0, 'p', 0, 'L', 0,
858     NULL, NULL, format_type_error
859   },
860   { "gcc_diag",   gcc_diag_length_specs,  gcc_diag_char_table, "q+#", NULL,
861     gcc_diag_flag_specs, gcc_diag_flag_pairs,
862     FMT_FLAG_ARG_CONVERT|FMT_FLAG_M_OK,
863     0, 0, 'p', 0, 'L', 0,
864     NULL, &integer_type_node, format_type_error
865   },
866   { "gcc_tdiag",   gcc_tdiag_length_specs,  gcc_tdiag_char_table, "q+#", NULL,
867     gcc_tdiag_flag_specs, gcc_tdiag_flag_pairs,
868     FMT_FLAG_ARG_CONVERT|FMT_FLAG_M_OK,
869     0, 0, 'p', 0, 'L', 0,
870     NULL, &integer_type_node, format_type_error
871   },
872   { "gcc_cdiag",   gcc_cdiag_length_specs,  gcc_cdiag_char_table, "q+#", NULL,
873     gcc_cdiag_flag_specs, gcc_cdiag_flag_pairs,
874     FMT_FLAG_ARG_CONVERT|FMT_FLAG_M_OK,
875     0, 0, 'p', 0, 'L', 0,
876     NULL, &integer_type_node, format_type_error
877   },
878   { "gcc_cxxdiag",   gcc_cxxdiag_length_specs,  gcc_cxxdiag_char_table, "q+#", NULL,
879     gcc_cxxdiag_flag_specs, gcc_cxxdiag_flag_pairs,
880     FMT_FLAG_ARG_CONVERT|FMT_FLAG_M_OK,
881     0, 0, 'p', 0, 'L', 0,
882     NULL, &integer_type_node, format_type_error
883   },
884   { "gcc_gfc", gcc_gfc_length_specs, gcc_gfc_char_table, "q+#", NULL,
885     gcc_gfc_flag_specs, gcc_gfc_flag_pairs,
886     FMT_FLAG_ARG_CONVERT|FMT_FLAG_M_OK,
887     0, 0, 0, 0, 0, 0,
888     NULL, NULL, format_type_error
889   },
890   { "NSString",   NULL,  NULL, NULL, NULL,
891     NULL, NULL,
892     FMT_FLAG_ARG_CONVERT|FMT_FLAG_PARSE_ARG_CONVERT_EXTERNAL, 0, 0, 0, 0, 0, 0,
893     NULL, NULL, format_type_error
894   },
895   { "gnu_scanf",    scanf_length_specs,   scan_char_table,  "*'I", NULL,
896     scanf_flag_specs, scanf_flag_pairs,
897     FMT_FLAG_ARG_CONVERT|FMT_FLAG_SCANF_A_KLUDGE|FMT_FLAG_USE_DOLLAR|FMT_FLAG_ZERO_WIDTH_BAD|FMT_FLAG_DOLLAR_GAP_POINTER_OK,
898     'w', 0, 0, '*', 'L', 'm',
899     NULL, NULL, format_type_error
900   },
901   { "gnu_strftime", NULL,                 time_char_table,  "_-0^#", "EO",
902     strftime_flag_specs, strftime_flag_pairs,
903     FMT_FLAG_FANCY_PERCENT_OK|FMT_FLAG_M_OK, 'w', 0, 0, 0, 0, 0,
904     NULL, NULL, format_type_error
905   },
906   { "gnu_strfmon",  strfmon_length_specs, monetary_char_table, "=^+(!-", NULL,
907     strfmon_flag_specs, strfmon_flag_pairs,
908     FMT_FLAG_ARG_CONVERT, 'w', '#', 'p', 0, 'L', 0,
909     NULL, NULL, format_type_error
910   },
911   { "gnu_syslog",   printf_length_specs,  print_char_table, " +#0-'I", NULL,
912     printf_flag_specs, printf_flag_pairs,
913     FMT_FLAG_ARG_CONVERT|FMT_FLAG_DOLLAR_MULTIPLE|FMT_FLAG_USE_DOLLAR|FMT_FLAG_EMPTY_PREC_OK|FMT_FLAG_M_OK,
914     'w', 0, 'p', 0, 'L', 0,
915     &integer_type_node, &integer_type_node, printf_format_type
916   },
917 };
918 
919 /* This layer of indirection allows GCC to reassign format_types with
920    new data if necessary, while still allowing the original data to be
921    const.  */
922 static const format_kind_info *format_types = format_types_orig;
923 /* We can modify this one.  We also add target-specific format types
924    to the end of the array.  */
925 static format_kind_info *dynamic_format_types;
926 
927 static int n_format_types = ARRAY_SIZE (format_types_orig);
928 
929 /* Structure detailing the results of checking a format function call
930    where the format expression may be a conditional expression with
931    many leaves resulting from nested conditional expressions.  */
932 struct format_check_results
933 {
934   /* Number of leaves of the format argument that could not be checked
935      as they were not string literals.  */
936   int number_non_literal;
937   /* Number of leaves of the format argument that were null pointers or
938      string literals, but had extra format arguments.  */
939   int number_extra_args;
940   location_t extra_arg_loc;
941   /* Number of leaves of the format argument that were null pointers or
942      string literals, but had extra format arguments and used $ operand
943      numbers.  */
944   int number_dollar_extra_args;
945   /* Number of leaves of the format argument that were wide string
946      literals.  */
947   int number_wide;
948   /* Number of leaves of the format argument that were empty strings.  */
949   int number_empty;
950   /* Number of leaves of the format argument that were unterminated
951      strings.  */
952   int number_unterminated;
953   /* Number of leaves of the format argument that were not counted above.  */
954   int number_other;
955   /* Location of the format string.  */
956   location_t format_string_loc;
957 };
958 
959 struct format_check_context
960 {
961   format_check_results *res;
962   function_format_info *info;
963   tree params;
964 };
965 
966 /* Return the format name (as specified in the original table) for the format
967    type indicated by format_num.  */
968 static const char *
969 format_name (int format_num)
970 {
971   if (format_num >= 0 && format_num < n_format_types)
972     return format_types[format_num].name;
973   gcc_unreachable ();
974 }
975 
976 /* Return the format flags (as specified in the original table) for the format
977    type indicated by format_num.  */
978 static int
979 format_flags (int format_num)
980 {
981   if (format_num >= 0 && format_num < n_format_types)
982     return format_types[format_num].flags;
983   gcc_unreachable ();
984 }
985 
986 static void check_format_info (function_format_info *, tree);
987 static void check_format_arg (void *, tree, unsigned HOST_WIDE_INT);
988 static void check_format_info_main (format_check_results *,
989 				    function_format_info *, const char *,
990 				    location_t, tree,
991 				    int, tree,
992 				    unsigned HOST_WIDE_INT,
993 				    object_allocator<format_wanted_type> &);
994 
995 static void init_dollar_format_checking (int, tree);
996 static int maybe_read_dollar_number (const char **, int,
997 				     tree, tree *, const format_kind_info *);
998 static bool avoid_dollar_number (const char *);
999 static void finish_dollar_format_checking (format_check_results *, int);
1000 
1001 static const format_flag_spec *get_flag_spec (const format_flag_spec *,
1002 					      int, const char *);
1003 
1004 static void check_format_types (const substring_loc &fmt_loc,
1005 				format_wanted_type *,
1006 				const format_kind_info *fki,
1007 				int offset_to_type_start,
1008 				char conversion_char);
1009 static void format_type_warning (const substring_loc &fmt_loc,
1010 				 source_range *param_range,
1011 				 format_wanted_type *, tree,
1012 				 tree,
1013 				 const format_kind_info *fki,
1014 				 int offset_to_type_start,
1015 				 char conversion_char);
1016 
1017 /* Decode a format type from a string, returning the type, or
1018    format_type_error if not valid, in which case the caller should print an
1019    error message.  */
1020 static int
1021 decode_format_type (const char *s)
1022 {
1023   int i;
1024   int slen;
1025 
1026   s = convert_format_name_to_system_name (s);
1027   slen = strlen (s);
1028   for (i = 0; i < n_format_types; i++)
1029     {
1030       int alen;
1031       if (!strcmp (s, format_types[i].name))
1032 	return i;
1033       alen = strlen (format_types[i].name);
1034       if (slen == alen + 4 && s[0] == '_' && s[1] == '_'
1035 	  && s[slen - 1] == '_' && s[slen - 2] == '_'
1036 	  && !strncmp (s + 2, format_types[i].name, alen))
1037 	return i;
1038     }
1039   return format_type_error;
1040 }
1041 
1042 
1043 /* Check the argument list of a call to printf, scanf, etc.
1044    ATTRS are the attributes on the function type.  There are NARGS argument
1045    values in the array ARGARRAY.
1046    Also, if -Wsuggest-attribute=format,
1047    warn for calls to vprintf or vscanf in functions with no such format
1048    attribute themselves.  */
1049 
1050 void
1051 check_function_format (tree attrs, int nargs, tree *argarray)
1052 {
1053   tree a;
1054 
1055   /* See if this function has any format attributes.  */
1056   for (a = attrs; a; a = TREE_CHAIN (a))
1057     {
1058       if (is_attribute_p ("format", TREE_PURPOSE (a)))
1059 	{
1060 	  /* Yup; check it.  */
1061 	  function_format_info info;
1062 	  decode_format_attr (TREE_VALUE (a), &info, /*validated=*/true);
1063 	  if (warn_format)
1064 	    {
1065 	      /* FIXME: Rewrite all the internal functions in this file
1066 		 to use the ARGARRAY directly instead of constructing this
1067 		 temporary list.  */
1068 	      tree params = NULL_TREE;
1069 	      int i;
1070 	      for (i = nargs - 1; i >= 0; i--)
1071 		params = tree_cons (NULL_TREE, argarray[i], params);
1072 	      check_format_info (&info, params);
1073 	    }
1074 	  const format_kind_info *fi = &format_types[info.format_type];
1075 
1076 	  /* Attempt to detect whether the current function might benefit
1077 	     from the format attribute if the called function is decorated
1078 	     with it.  Avoid using calls with string literal formats for
1079 	     guidance since those are unlikely to be viable candidates.  */
1080 	  if (warn_suggest_attribute_format && info.first_arg_num == 0
1081 	      && (fi->flags & (int) FMT_FLAG_ARG_CONVERT)
1082 	      /* c_strlen will fail for a function parameter but succeed
1083 		 for a literal or constant array.  */
1084 	      && !c_strlen (argarray[info.format_num - 1], 1))
1085 	    {
1086 	      tree c;
1087 	      for (c = TYPE_ATTRIBUTES (TREE_TYPE (current_function_decl));
1088 		   c;
1089 		   c = TREE_CHAIN (c))
1090 		{
1091 		  if (!is_attribute_p ("format", TREE_PURPOSE (c)))
1092 		     continue;
1093 		  int format_type = decode_format_type (
1094 		      IDENTIFIER_POINTER (TREE_VALUE (TREE_VALUE (c))));
1095 		  if (format_type == format_type_error)
1096 		     continue;
1097 		  if (format_type == info.format_type ||
1098 		      format_type == fi->parent_format_type)
1099 		    break;
1100 		}
1101 	      if (c == NULL_TREE)
1102 		{
1103 		  /* Check if the current function has a parameter to which
1104 		     the format attribute could be attached; if not, it
1105 		     can't be a candidate for a format attribute, despite
1106 		     the vprintf-like or vscanf-like call.  */
1107 		  tree args;
1108 		  for (args = DECL_ARGUMENTS (current_function_decl);
1109 		       args != 0;
1110 		       args = DECL_CHAIN (args))
1111 		    {
1112 		      if (TREE_CODE (TREE_TYPE (args)) == POINTER_TYPE
1113 			  && (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (args)))
1114 			      == char_type_node))
1115 			break;
1116 		    }
1117 		  if (args != 0)
1118 		    warning (OPT_Wsuggest_attribute_format, "function %qD "
1119 			     "might be a candidate for %qs format attribute",
1120 			     current_function_decl,
1121 			     format_types[info.format_type].name);
1122 		}
1123 	    }
1124 	}
1125     }
1126 }
1127 
1128 
1129 /* Variables used by the checking of $ operand number formats.  */
1130 static char *dollar_arguments_used = NULL;
1131 static char *dollar_arguments_pointer_p = NULL;
1132 static int dollar_arguments_alloc = 0;
1133 static int dollar_arguments_count;
1134 static int dollar_first_arg_num;
1135 static int dollar_max_arg_used;
1136 static int dollar_format_warned;
1137 
1138 /* Initialize the checking for a format string that may contain $
1139    parameter number specifications; we will need to keep track of whether
1140    each parameter has been used.  FIRST_ARG_NUM is the number of the first
1141    argument that is a parameter to the format, or 0 for a vprintf-style
1142    function; PARAMS is the list of arguments starting at this argument.  */
1143 
1144 static void
1145 init_dollar_format_checking (int first_arg_num, tree params)
1146 {
1147   tree oparams = params;
1148 
1149   dollar_first_arg_num = first_arg_num;
1150   dollar_arguments_count = 0;
1151   dollar_max_arg_used = 0;
1152   dollar_format_warned = 0;
1153   if (first_arg_num > 0)
1154     {
1155       while (params)
1156 	{
1157 	  dollar_arguments_count++;
1158 	  params = TREE_CHAIN (params);
1159 	}
1160     }
1161   if (dollar_arguments_alloc < dollar_arguments_count)
1162     {
1163       free (dollar_arguments_used);
1164       free (dollar_arguments_pointer_p);
1165       dollar_arguments_alloc = dollar_arguments_count;
1166       dollar_arguments_used = XNEWVEC (char, dollar_arguments_alloc);
1167       dollar_arguments_pointer_p = XNEWVEC (char, dollar_arguments_alloc);
1168     }
1169   if (dollar_arguments_alloc)
1170     {
1171       memset (dollar_arguments_used, 0, dollar_arguments_alloc);
1172       if (first_arg_num > 0)
1173 	{
1174 	  int i = 0;
1175 	  params = oparams;
1176 	  while (params)
1177 	    {
1178 	      dollar_arguments_pointer_p[i] = (TREE_CODE (TREE_TYPE (TREE_VALUE (params)))
1179 					       == POINTER_TYPE);
1180 	      params = TREE_CHAIN (params);
1181 	      i++;
1182 	    }
1183 	}
1184     }
1185 }
1186 
1187 
1188 /* Look for a decimal number followed by a $ in *FORMAT.  If DOLLAR_NEEDED
1189    is set, it is an error if one is not found; otherwise, it is OK.  If
1190    such a number is found, check whether it is within range and mark that
1191    numbered operand as being used for later checking.  Returns the operand
1192    number if found and within range, zero if no such number was found and
1193    this is OK, or -1 on error.  PARAMS points to the first operand of the
1194    format; PARAM_PTR is made to point to the parameter referred to.  If
1195    a $ format is found, *FORMAT is updated to point just after it.  */
1196 
1197 static int
1198 maybe_read_dollar_number (const char **format,
1199 			  int dollar_needed, tree params, tree *param_ptr,
1200 			  const format_kind_info *fki)
1201 {
1202   int argnum;
1203   int overflow_flag;
1204   const char *fcp = *format;
1205   if (!ISDIGIT (*fcp))
1206     {
1207       if (dollar_needed)
1208 	{
1209 	  warning (OPT_Wformat_, "missing $ operand number in format");
1210 	  return -1;
1211 	}
1212       else
1213 	return 0;
1214     }
1215   argnum = 0;
1216   overflow_flag = 0;
1217   while (ISDIGIT (*fcp))
1218     {
1219       int nargnum;
1220       nargnum = 10 * argnum + (*fcp - '0');
1221       if (nargnum < 0 || nargnum / 10 != argnum)
1222 	overflow_flag = 1;
1223       argnum = nargnum;
1224       fcp++;
1225     }
1226   if (*fcp != '$')
1227     {
1228       if (dollar_needed)
1229 	{
1230 	  warning (OPT_Wformat_, "missing $ operand number in format");
1231 	  return -1;
1232 	}
1233       else
1234 	return 0;
1235     }
1236   *format = fcp + 1;
1237   if (pedantic && !dollar_format_warned)
1238     {
1239       warning (OPT_Wformat_, "%s does not support %%n$ operand number formats",
1240 	       C_STD_NAME (STD_EXT));
1241       dollar_format_warned = 1;
1242     }
1243   if (overflow_flag || argnum == 0
1244       || (dollar_first_arg_num && argnum > dollar_arguments_count))
1245     {
1246       warning (OPT_Wformat_, "operand number out of range in format");
1247       return -1;
1248     }
1249   if (argnum > dollar_max_arg_used)
1250     dollar_max_arg_used = argnum;
1251   /* For vprintf-style functions we may need to allocate more memory to
1252      track which arguments are used.  */
1253   while (dollar_arguments_alloc < dollar_max_arg_used)
1254     {
1255       int nalloc;
1256       nalloc = 2 * dollar_arguments_alloc + 16;
1257       dollar_arguments_used = XRESIZEVEC (char, dollar_arguments_used,
1258 					  nalloc);
1259       dollar_arguments_pointer_p = XRESIZEVEC (char, dollar_arguments_pointer_p,
1260 					       nalloc);
1261       memset (dollar_arguments_used + dollar_arguments_alloc, 0,
1262 	      nalloc - dollar_arguments_alloc);
1263       dollar_arguments_alloc = nalloc;
1264     }
1265   if (!(fki->flags & (int) FMT_FLAG_DOLLAR_MULTIPLE)
1266       && dollar_arguments_used[argnum - 1] == 1)
1267     {
1268       dollar_arguments_used[argnum - 1] = 2;
1269       warning (OPT_Wformat_, "format argument %d used more than once in %s format",
1270 	       argnum, fki->name);
1271     }
1272   else
1273     dollar_arguments_used[argnum - 1] = 1;
1274   if (dollar_first_arg_num)
1275     {
1276       int i;
1277       *param_ptr = params;
1278       for (i = 1; i < argnum && *param_ptr != 0; i++)
1279 	*param_ptr = TREE_CHAIN (*param_ptr);
1280 
1281       /* This case shouldn't be caught here.  */
1282       gcc_assert (*param_ptr);
1283     }
1284   else
1285     *param_ptr = 0;
1286   return argnum;
1287 }
1288 
1289 /* Ensure that FORMAT does not start with a decimal number followed by
1290    a $; give a diagnostic and return true if it does, false otherwise.  */
1291 
1292 static bool
1293 avoid_dollar_number (const char *format)
1294 {
1295   if (!ISDIGIT (*format))
1296     return false;
1297   while (ISDIGIT (*format))
1298     format++;
1299   if (*format == '$')
1300     {
1301       warning (OPT_Wformat_, "$ operand number used after format without operand number");
1302       return true;
1303     }
1304   return false;
1305 }
1306 
1307 
1308 /* Finish the checking for a format string that used $ operand number formats
1309    instead of non-$ formats.  We check for unused operands before used ones
1310    (a serious error, since the implementation of the format function
1311    can't know what types to pass to va_arg to find the later arguments).
1312    and for unused operands at the end of the format (if we know how many
1313    arguments the format had, so not for vprintf).  If there were operand
1314    numbers out of range on a non-vprintf-style format, we won't have reached
1315    here.  If POINTER_GAP_OK, unused arguments are OK if all arguments are
1316    pointers.  */
1317 
1318 static void
1319 finish_dollar_format_checking (format_check_results *res, int pointer_gap_ok)
1320 {
1321   int i;
1322   bool found_pointer_gap = false;
1323   for (i = 0; i < dollar_max_arg_used; i++)
1324     {
1325       if (!dollar_arguments_used[i])
1326 	{
1327 	  if (pointer_gap_ok && (dollar_first_arg_num == 0
1328 				 || dollar_arguments_pointer_p[i]))
1329 	    found_pointer_gap = true;
1330 	  else
1331 	    warning_at (res->format_string_loc, OPT_Wformat_,
1332 			"format argument %d unused before used argument %d in $-style format",
1333 			i + 1, dollar_max_arg_used);
1334 	}
1335     }
1336   if (found_pointer_gap
1337       || (dollar_first_arg_num
1338 	  && dollar_max_arg_used < dollar_arguments_count))
1339     {
1340       res->number_other--;
1341       res->number_dollar_extra_args++;
1342     }
1343 }
1344 
1345 
1346 /* Retrieve the specification for a format flag.  SPEC contains the
1347    specifications for format flags for the applicable kind of format.
1348    FLAG is the flag in question.  If PREDICATES is NULL, the basic
1349    spec for that flag must be retrieved and must exist.  If
1350    PREDICATES is not NULL, it is a string listing possible predicates
1351    for the spec entry; if an entry predicated on any of these is
1352    found, it is returned, otherwise NULL is returned.  */
1353 
1354 static const format_flag_spec *
1355 get_flag_spec (const format_flag_spec *spec, int flag, const char *predicates)
1356 {
1357   int i;
1358   for (i = 0; spec[i].flag_char != 0; i++)
1359     {
1360       if (spec[i].flag_char != flag)
1361 	continue;
1362       if (predicates != NULL)
1363 	{
1364 	  if (spec[i].predicate != 0
1365 	      && strchr (predicates, spec[i].predicate) != 0)
1366 	    return &spec[i];
1367 	}
1368       else if (spec[i].predicate == 0)
1369 	return &spec[i];
1370     }
1371   gcc_assert (predicates);
1372   return NULL;
1373 }
1374 
1375 
1376 /* Check the argument list of a call to printf, scanf, etc.
1377    INFO points to the function_format_info structure.
1378    PARAMS is the list of argument values.  */
1379 
1380 static void
1381 check_format_info (function_format_info *info, tree params)
1382 {
1383   format_check_context format_ctx;
1384   unsigned HOST_WIDE_INT arg_num;
1385   tree format_tree;
1386   format_check_results res;
1387   /* Skip to format argument.  If the argument isn't available, there's
1388      no work for us to do; prototype checking will catch the problem.  */
1389   for (arg_num = 1; ; ++arg_num)
1390     {
1391       if (params == 0)
1392 	return;
1393       if (arg_num == info->format_num)
1394 	break;
1395       params = TREE_CHAIN (params);
1396     }
1397   format_tree = TREE_VALUE (params);
1398   params = TREE_CHAIN (params);
1399   if (format_tree == 0)
1400     return;
1401 
1402   res.number_non_literal = 0;
1403   res.number_extra_args = 0;
1404   res.extra_arg_loc = UNKNOWN_LOCATION;
1405   res.number_dollar_extra_args = 0;
1406   res.number_wide = 0;
1407   res.number_empty = 0;
1408   res.number_unterminated = 0;
1409   res.number_other = 0;
1410   res.format_string_loc = input_location;
1411 
1412   format_ctx.res = &res;
1413   format_ctx.info = info;
1414   format_ctx.params = params;
1415 
1416   check_function_arguments_recurse (check_format_arg, &format_ctx,
1417 				    format_tree, arg_num);
1418 
1419   location_t loc = format_ctx.res->format_string_loc;
1420 
1421   if (res.number_non_literal > 0)
1422     {
1423       /* Functions taking a va_list normally pass a non-literal format
1424 	 string.  These functions typically are declared with
1425 	 first_arg_num == 0, so avoid warning in those cases.  */
1426       if (!(format_types[info->format_type].flags & (int) FMT_FLAG_ARG_CONVERT))
1427 	{
1428 	  /* For strftime-like formats, warn for not checking the format
1429 	     string; but there are no arguments to check.  */
1430 	  warning_at (loc, OPT_Wformat_nonliteral,
1431 		      "format not a string literal, format string not checked");
1432 	}
1433       else if (info->first_arg_num != 0)
1434 	{
1435 	  /* If there are no arguments for the format at all, we may have
1436 	     printf (foo) which is likely to be a security hole.  */
1437 	  while (arg_num + 1 < info->first_arg_num)
1438 	    {
1439 	      if (params == 0)
1440 		break;
1441 	      params = TREE_CHAIN (params);
1442 	      ++arg_num;
1443 	    }
1444 	  if (params == 0 && warn_format_security)
1445 	    warning_at (loc, OPT_Wformat_security,
1446 			"format not a string literal and no format arguments");
1447 	  else if (params == 0 && warn_format_nonliteral)
1448 	    warning_at (loc, OPT_Wformat_nonliteral,
1449 			"format not a string literal and no format arguments");
1450 	  else
1451 	    warning_at (loc, OPT_Wformat_nonliteral,
1452 			"format not a string literal, argument types not checked");
1453 	}
1454     }
1455 
1456   /* If there were extra arguments to the format, normally warn.  However,
1457      the standard does say extra arguments are ignored, so in the specific
1458      case where we have multiple leaves (conditional expressions or
1459      ngettext) allow extra arguments if at least one leaf didn't have extra
1460      arguments, but was otherwise OK (either non-literal or checked OK).
1461      If the format is an empty string, this should be counted similarly to the
1462      case of extra format arguments.  */
1463   if (res.number_extra_args > 0 && res.number_non_literal == 0
1464       && res.number_other == 0)
1465     {
1466       if (res.extra_arg_loc == UNKNOWN_LOCATION)
1467 	res.extra_arg_loc = loc;
1468       warning_at (res.extra_arg_loc, OPT_Wformat_extra_args,
1469 		  "too many arguments for format");
1470     }
1471   if (res.number_dollar_extra_args > 0 && res.number_non_literal == 0
1472       && res.number_other == 0)
1473     warning_at (loc, OPT_Wformat_extra_args, "unused arguments in $-style format");
1474   if (res.number_empty > 0 && res.number_non_literal == 0
1475       && res.number_other == 0)
1476     warning_at (loc, OPT_Wformat_zero_length, "zero-length %s format string",
1477 	     format_types[info->format_type].name);
1478 
1479   if (res.number_wide > 0)
1480     warning_at (loc, OPT_Wformat_, "format is a wide character string");
1481 
1482   if (res.number_unterminated > 0)
1483     warning_at (loc, OPT_Wformat_, "unterminated format string");
1484 }
1485 
1486 /* Callback from check_function_arguments_recurse to check a
1487    format string.  FORMAT_TREE is the format parameter.  ARG_NUM
1488    is the number of the format argument.  CTX points to a
1489    format_check_context.  */
1490 
1491 static void
1492 check_format_arg (void *ctx, tree format_tree,
1493 		  unsigned HOST_WIDE_INT arg_num)
1494 {
1495   format_check_context *format_ctx = (format_check_context *) ctx;
1496   format_check_results *res = format_ctx->res;
1497   function_format_info *info = format_ctx->info;
1498   tree params = format_ctx->params;
1499 
1500   int format_length;
1501   HOST_WIDE_INT offset;
1502   const char *format_chars;
1503   tree array_size = 0;
1504   tree array_init;
1505 
1506   location_t fmt_param_loc = EXPR_LOC_OR_LOC (format_tree, input_location);
1507 
1508   if (VAR_P (format_tree))
1509     {
1510       /* Pull out a constant value if the front end didn't.  */
1511       format_tree = decl_constant_value (format_tree);
1512       STRIP_NOPS (format_tree);
1513     }
1514 
1515   if (integer_zerop (format_tree))
1516     {
1517       /* Skip to first argument to check, so we can see if this format
1518 	 has any arguments (it shouldn't).  */
1519       while (arg_num + 1 < info->first_arg_num)
1520 	{
1521 	  if (params == 0)
1522 	    return;
1523 	  params = TREE_CHAIN (params);
1524 	  ++arg_num;
1525 	}
1526 
1527       if (params == 0)
1528 	res->number_other++;
1529       else
1530 	{
1531 	  if (res->number_extra_args == 0)
1532 	    res->extra_arg_loc = EXPR_LOC_OR_LOC (TREE_VALUE (params),
1533 						  input_location);
1534 	  res->number_extra_args++;
1535 	}
1536       return;
1537     }
1538 
1539   offset = 0;
1540   if (TREE_CODE (format_tree) == POINTER_PLUS_EXPR)
1541     {
1542       tree arg0, arg1;
1543 
1544       arg0 = TREE_OPERAND (format_tree, 0);
1545       arg1 = TREE_OPERAND (format_tree, 1);
1546       STRIP_NOPS (arg0);
1547       STRIP_NOPS (arg1);
1548       if (TREE_CODE (arg1) == INTEGER_CST)
1549 	format_tree = arg0;
1550       else
1551 	{
1552 	  res->number_non_literal++;
1553 	  return;
1554 	}
1555       /* POINTER_PLUS_EXPR offsets are to be interpreted signed.  */
1556       if (!cst_and_fits_in_hwi (arg1))
1557 	{
1558 	  res->number_non_literal++;
1559 	  return;
1560 	}
1561       offset = int_cst_value (arg1);
1562     }
1563   if (TREE_CODE (format_tree) != ADDR_EXPR)
1564     {
1565       res->number_non_literal++;
1566       return;
1567     }
1568   res->format_string_loc = EXPR_LOC_OR_LOC (format_tree, input_location);
1569   format_tree = TREE_OPERAND (format_tree, 0);
1570   if (format_types[info->format_type].flags
1571       & (int) FMT_FLAG_PARSE_ARG_CONVERT_EXTERNAL)
1572     {
1573       bool objc_str = (info->format_type == gcc_objc_string_format_type);
1574       /* We cannot examine this string here - but we can check that it is
1575 	 a valid type.  */
1576       if (TREE_CODE (format_tree) != CONST_DECL
1577 	  || !((objc_str && objc_string_ref_type_p (TREE_TYPE (format_tree)))
1578 		|| (*targetcm.string_object_ref_type_p)
1579 				     ((const_tree) TREE_TYPE (format_tree))))
1580 	{
1581 	  res->number_non_literal++;
1582 	  return;
1583 	}
1584       /* Skip to first argument to check.  */
1585       while (arg_num + 1 < info->first_arg_num)
1586 	{
1587 	  if (params == 0)
1588 	    return;
1589 	  params = TREE_CHAIN (params);
1590 	  ++arg_num;
1591 	}
1592       /* So, we have a valid literal string object and one or more params.
1593 	 We need to use an external helper to parse the string into format
1594 	 info.  For Objective-C variants we provide the resource within the
1595 	 objc tree, for target variants, via a hook.  */
1596       if (objc_str)
1597 	objc_check_format_arg (format_tree, params);
1598       else if (targetcm.check_string_object_format_arg)
1599 	(*targetcm.check_string_object_format_arg) (format_tree, params);
1600       /* Else we can't handle it and retire quietly.  */
1601       return;
1602     }
1603   if (TREE_CODE (format_tree) == ARRAY_REF
1604       && tree_fits_shwi_p (TREE_OPERAND (format_tree, 1))
1605       && (offset += tree_to_shwi (TREE_OPERAND (format_tree, 1))) >= 0)
1606     format_tree = TREE_OPERAND (format_tree, 0);
1607   if (offset < 0)
1608     {
1609       res->number_non_literal++;
1610       return;
1611     }
1612   if (VAR_P (format_tree)
1613       && TREE_CODE (TREE_TYPE (format_tree)) == ARRAY_TYPE
1614       && (array_init = decl_constant_value (format_tree)) != format_tree
1615       && TREE_CODE (array_init) == STRING_CST)
1616     {
1617       /* Extract the string constant initializer.  Note that this may include
1618 	 a trailing NUL character that is not in the array (e.g.
1619 	 const char a[3] = "foo";).  */
1620       array_size = DECL_SIZE_UNIT (format_tree);
1621       format_tree = array_init;
1622     }
1623   if (TREE_CODE (format_tree) != STRING_CST)
1624     {
1625       res->number_non_literal++;
1626       return;
1627     }
1628   if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format_tree))) != char_type_node)
1629     {
1630       res->number_wide++;
1631       return;
1632     }
1633   format_chars = TREE_STRING_POINTER (format_tree);
1634   format_length = TREE_STRING_LENGTH (format_tree);
1635   if (array_size != 0)
1636     {
1637       /* Variable length arrays can't be initialized.  */
1638       gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
1639 
1640       if (tree_fits_shwi_p (array_size))
1641 	{
1642 	  HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
1643 	  if (array_size_value > 0
1644 	      && array_size_value == (int) array_size_value
1645 	      && format_length > array_size_value)
1646 	    format_length = array_size_value;
1647 	}
1648     }
1649   if (offset)
1650     {
1651       if (offset >= format_length)
1652 	{
1653 	  res->number_non_literal++;
1654 	  return;
1655 	}
1656       format_chars += offset;
1657       format_length -= offset;
1658     }
1659   if (format_length < 1 || format_chars[--format_length] != 0)
1660     {
1661       res->number_unterminated++;
1662       return;
1663     }
1664   if (format_length == 0)
1665     {
1666       res->number_empty++;
1667       return;
1668     }
1669 
1670   /* Skip to first argument to check.  */
1671   while (arg_num + 1 < info->first_arg_num)
1672     {
1673       if (params == 0)
1674 	return;
1675       params = TREE_CHAIN (params);
1676       ++arg_num;
1677     }
1678   /* Provisionally increment res->number_other; check_format_info_main
1679      will decrement it if it finds there are extra arguments, but this way
1680      need not adjust it for every return.  */
1681   res->number_other++;
1682   object_allocator <format_wanted_type> fwt_pool ("format_wanted_type pool");
1683   check_format_info_main (res, info, format_chars, fmt_param_loc, format_tree,
1684 			  format_length, params, arg_num, fwt_pool);
1685 }
1686 
1687 /* Support class for argument_parser and check_format_info_main.
1688    Tracks any flag characters that have been applied to the
1689    current argument.  */
1690 
1691 class flag_chars_t
1692 {
1693  public:
1694   flag_chars_t ();
1695   bool has_char_p (char ch) const;
1696   void add_char (char ch);
1697   void validate (const format_kind_info *fki,
1698 		 const format_char_info *fci,
1699 		 const format_flag_spec *flag_specs,
1700 		 const char * const format_chars,
1701 		 tree format_string_cst,
1702 		 location_t format_string_loc,
1703 		 const char * const orig_format_chars,
1704 		 char format_char);
1705   int get_alloc_flag (const format_kind_info *fki);
1706   int assignment_suppression_p (const format_kind_info *fki);
1707 
1708  private:
1709   char m_flag_chars[256];
1710 };
1711 
1712 /* Support struct for argument_parser and check_format_info_main.
1713    Encapsulates any length modifier applied to the current argument.  */
1714 
1715 struct length_modifier
1716 {
1717   length_modifier ()
1718   : chars (NULL), val (FMT_LEN_none), std (STD_C89),
1719     scalar_identity_flag (0)
1720   {
1721   }
1722 
1723   length_modifier (const char *chars_,
1724 		   enum format_lengths val_,
1725 		   enum format_std_version std_,
1726 		   int scalar_identity_flag_)
1727   : chars (chars_), val (val_), std (std_),
1728     scalar_identity_flag (scalar_identity_flag_)
1729   {
1730   }
1731 
1732   const char *chars;
1733   enum format_lengths val;
1734   enum format_std_version std;
1735   int scalar_identity_flag;
1736 };
1737 
1738 /* Parsing one argument within a format string.  */
1739 
1740 class argument_parser
1741 {
1742  public:
1743   argument_parser (function_format_info *info, const char *&format_chars,
1744 		   tree format_string_cst,
1745 		   const char * const orig_format_chars,
1746 		   location_t format_string_loc, flag_chars_t &flag_chars,
1747 		   int &has_operand_number, tree first_fillin_param,
1748 		   object_allocator <format_wanted_type> &fwt_pool_);
1749 
1750   bool read_any_dollar ();
1751 
1752   bool read_format_flags ();
1753 
1754   bool
1755   read_any_format_width (tree &params,
1756 			 unsigned HOST_WIDE_INT &arg_num);
1757 
1758   void
1759   read_any_format_left_precision ();
1760 
1761   bool
1762   read_any_format_precision (tree &params,
1763 			     unsigned HOST_WIDE_INT &arg_num);
1764 
1765   void handle_alloc_chars ();
1766 
1767   length_modifier read_any_length_modifier ();
1768 
1769   void read_any_other_modifier ();
1770 
1771   const format_char_info *find_format_char_info (char format_char);
1772 
1773   void
1774   validate_flag_pairs (const format_char_info *fci,
1775 		       char format_char);
1776 
1777   void
1778   give_y2k_warnings (const format_char_info *fci,
1779 		     char format_char);
1780 
1781   void parse_any_scan_set (const format_char_info *fci);
1782 
1783   bool handle_conversions (const format_char_info *fci,
1784 			   const length_modifier &len_modifier,
1785 			   tree &wanted_type,
1786 			   const char *&wanted_type_name,
1787 			   unsigned HOST_WIDE_INT &arg_num,
1788 			   tree &params,
1789 			   char format_char);
1790 
1791   bool
1792   check_argument_type (const format_char_info *fci,
1793 		       const length_modifier &len_modifier,
1794 		       tree &wanted_type,
1795 		       const char *&wanted_type_name,
1796 		       const bool suppressed,
1797 		       unsigned HOST_WIDE_INT &arg_num,
1798 		       tree &params,
1799 		       const int alloc_flag,
1800 		       const char * const format_start,
1801 		       const char * const type_start,
1802 		       location_t fmt_param_loc,
1803 		       char conversion_char);
1804 
1805  private:
1806   const function_format_info *const info;
1807   const format_kind_info * const fki;
1808   const format_flag_spec * const flag_specs;
1809   const char *start_of_this_format;
1810   const char *&format_chars;
1811   const tree format_string_cst;
1812   const char * const orig_format_chars;
1813   const location_t format_string_loc;
1814   object_allocator <format_wanted_type> &fwt_pool;
1815   flag_chars_t &flag_chars;
1816   int main_arg_num;
1817   tree main_arg_params;
1818   int &has_operand_number;
1819   const tree first_fillin_param;
1820   format_wanted_type width_wanted_type;
1821   format_wanted_type precision_wanted_type;
1822  public:
1823   format_wanted_type main_wanted_type;
1824  private:
1825   format_wanted_type *first_wanted_type;
1826   format_wanted_type *last_wanted_type;
1827 };
1828 
1829 /* flag_chars_t's constructor.  */
1830 
1831 flag_chars_t::flag_chars_t ()
1832 {
1833   m_flag_chars[0] = 0;
1834 }
1835 
1836 /* Has CH been seen as a flag within the current argument?  */
1837 
1838 bool
1839 flag_chars_t::has_char_p (char ch) const
1840 {
1841   return strchr (m_flag_chars, ch) != 0;
1842 }
1843 
1844 /* Add CH to the flags seen within the current argument.  */
1845 
1846 void
1847 flag_chars_t::add_char (char ch)
1848 {
1849   int i = strlen (m_flag_chars);
1850   m_flag_chars[i++] = ch;
1851   m_flag_chars[i] = 0;
1852 }
1853 
1854 /* Validate the individual flags used, removing any that are invalid.  */
1855 
1856 void
1857 flag_chars_t::validate (const format_kind_info *fki,
1858 			const format_char_info *fci,
1859 			const format_flag_spec *flag_specs,
1860 			const char * const format_chars,
1861 			tree format_string_cst,
1862 			location_t format_string_loc,
1863 			const char * const orig_format_chars,
1864 			char format_char)
1865 {
1866   int i;
1867   int d = 0;
1868   for (i = 0; m_flag_chars[i] != 0; i++)
1869     {
1870       const format_flag_spec *s = get_flag_spec (flag_specs,
1871 						 m_flag_chars[i], NULL);
1872       m_flag_chars[i - d] = m_flag_chars[i];
1873       if (m_flag_chars[i] == fki->length_code_char)
1874 	continue;
1875       if (strchr (fci->flag_chars, m_flag_chars[i]) == 0)
1876 	{
1877 	  format_warning_at_char (format_string_loc, format_string_cst,
1878 				  format_chars - orig_format_chars,
1879 				  OPT_Wformat_,
1880 				  "%s used with %<%%%c%> %s format",
1881 				  _(s->name), format_char, fki->name);
1882 	  d++;
1883 	  continue;
1884 	}
1885       if (pedantic)
1886 	{
1887 	  const format_flag_spec *t;
1888 	  if (ADJ_STD (s->std) > C_STD_VER)
1889 	    warning_at (format_string_loc, OPT_Wformat_,
1890 			"%s does not support %s",
1891 			C_STD_NAME (s->std), _(s->long_name));
1892 	  t = get_flag_spec (flag_specs, m_flag_chars[i], fci->flags2);
1893 	  if (t != NULL && ADJ_STD (t->std) > ADJ_STD (s->std))
1894 	    {
1895 	      const char *long_name = (t->long_name != NULL
1896 				       ? t->long_name
1897 				       : s->long_name);
1898 	      if (ADJ_STD (t->std) > C_STD_VER)
1899 		warning_at (format_string_loc, OPT_Wformat_,
1900 			    "%s does not support %s with"
1901 			    " the %<%%%c%> %s format",
1902 			    C_STD_NAME (t->std), _(long_name),
1903 			    format_char, fki->name);
1904 	    }
1905 	}
1906     }
1907   m_flag_chars[i - d] = 0;
1908 }
1909 
1910 /* Determine if an assignment-allocation has been set, requiring
1911    an extra char ** for writing back a dynamically-allocated char *.
1912    This is for handling the optional 'm' character in scanf.  */
1913 
1914 int
1915 flag_chars_t::get_alloc_flag (const format_kind_info *fki)
1916 {
1917   if ((fki->flags & (int) FMT_FLAG_SCANF_A_KLUDGE)
1918       && has_char_p ('a'))
1919     return 1;
1920   if (fki->alloc_char && has_char_p (fki->alloc_char))
1921     return 1;
1922   return 0;
1923 }
1924 
1925 /* Determine if an assignment-suppression character was seen.
1926    ('*' in scanf, for discarding the converted input).  */
1927 
1928 int
1929 flag_chars_t::assignment_suppression_p (const format_kind_info *fki)
1930 {
1931   if (fki->suppression_char
1932       && has_char_p (fki->suppression_char))
1933     return 1;
1934   return 0;
1935 }
1936 
1937 /* Constructor for argument_parser.  Initialize for parsing one
1938    argument within a format string.  */
1939 
1940 argument_parser::
1941 argument_parser (function_format_info *info_, const char *&format_chars_,
1942 		 tree format_string_cst_,
1943 		 const char * const orig_format_chars_,
1944 		 location_t format_string_loc_,
1945 		 flag_chars_t &flag_chars_,
1946 		 int &has_operand_number_,
1947 		 tree first_fillin_param_,
1948 		 object_allocator <format_wanted_type> &fwt_pool_)
1949 : info (info_),
1950   fki (&format_types[info->format_type]),
1951   flag_specs (fki->flag_specs),
1952   start_of_this_format (format_chars_),
1953   format_chars (format_chars_),
1954   format_string_cst (format_string_cst_),
1955   orig_format_chars (orig_format_chars_),
1956   format_string_loc (format_string_loc_),
1957   fwt_pool (fwt_pool_),
1958   flag_chars (flag_chars_),
1959   main_arg_num (0),
1960   main_arg_params (NULL),
1961   has_operand_number (has_operand_number_),
1962   first_fillin_param (first_fillin_param_),
1963   first_wanted_type (NULL),
1964   last_wanted_type (NULL)
1965 {
1966 }
1967 
1968 /* Handle dollars at the start of format arguments, setting up main_arg_params
1969    and main_arg_num.
1970 
1971    Return true if format parsing is to continue, false otherwise.  */
1972 
1973 bool
1974 argument_parser::read_any_dollar ()
1975 {
1976   if ((fki->flags & (int) FMT_FLAG_USE_DOLLAR) && has_operand_number != 0)
1977     {
1978       /* Possibly read a $ operand number at the start of the format.
1979 	 If one was previously used, one is required here.  If one
1980 	 is not used here, we can't immediately conclude this is a
1981 	 format without them, since it could be printf %m or scanf %*.  */
1982       int opnum;
1983       opnum = maybe_read_dollar_number (&format_chars, 0,
1984 					first_fillin_param,
1985 					&main_arg_params, fki);
1986       if (opnum == -1)
1987 	return false;
1988       else if (opnum > 0)
1989 	{
1990 	  has_operand_number = 1;
1991 	  main_arg_num = opnum + info->first_arg_num - 1;
1992 	}
1993     }
1994   else if (fki->flags & FMT_FLAG_USE_DOLLAR)
1995     {
1996       if (avoid_dollar_number (format_chars))
1997 	return false;
1998     }
1999   return true;
2000 }
2001 
2002 /* Read any format flags, but do not yet validate them beyond removing
2003    duplicates, since in general validation depends on the rest of
2004    the format.
2005 
2006    Return true if format parsing is to continue, false otherwise.  */
2007 
2008 bool
2009 argument_parser::read_format_flags ()
2010 {
2011   while (*format_chars != 0
2012 	 && strchr (fki->flag_chars, *format_chars) != 0)
2013     {
2014       const format_flag_spec *s = get_flag_spec (flag_specs,
2015 						 *format_chars, NULL);
2016       if (flag_chars.has_char_p (*format_chars))
2017 	{
2018 	  format_warning_at_char (format_string_loc, format_string_cst,
2019 				  format_chars + 1 - orig_format_chars,
2020 				  OPT_Wformat_,
2021 				  "repeated %s in format", _(s->name));
2022 	}
2023       else
2024 	flag_chars.add_char (*format_chars);
2025 
2026       if (s->skip_next_char)
2027 	{
2028 	  ++format_chars;
2029 	  if (*format_chars == 0)
2030 	    {
2031 	      warning_at (format_string_loc, OPT_Wformat_,
2032 			  "missing fill character at end of strfmon format");
2033 	      return false;
2034 	    }
2035 	}
2036       ++format_chars;
2037     }
2038 
2039   return true;
2040 }
2041 
2042 /* Read any format width, possibly * or *m$.
2043 
2044    Return true if format parsing is to continue, false otherwise.  */
2045 
2046 bool
2047 argument_parser::
2048 read_any_format_width (tree &params,
2049 		       unsigned HOST_WIDE_INT &arg_num)
2050 {
2051   if (!fki->width_char)
2052     return true;
2053 
2054   if (fki->width_type != NULL && *format_chars == '*')
2055     {
2056       flag_chars.add_char (fki->width_char);
2057       /* "...a field width...may be indicated by an asterisk.
2058 	 In this case, an int argument supplies the field width..."  */
2059       ++format_chars;
2060       if (has_operand_number != 0)
2061 	{
2062 	  int opnum;
2063 	  opnum = maybe_read_dollar_number (&format_chars,
2064 					    has_operand_number == 1,
2065 					    first_fillin_param,
2066 					    &params, fki);
2067 	  if (opnum == -1)
2068 	    return false;
2069 	  else if (opnum > 0)
2070 	    {
2071 	      has_operand_number = 1;
2072 	      arg_num = opnum + info->first_arg_num - 1;
2073 	    }
2074 	  else
2075 	    has_operand_number = 0;
2076 	}
2077       else
2078 	{
2079 	  if (avoid_dollar_number (format_chars))
2080 	    return false;
2081 	}
2082       if (info->first_arg_num != 0)
2083 	{
2084 	  tree cur_param;
2085 	  if (params == 0)
2086 	    cur_param = NULL;
2087 	  else
2088 	    {
2089 	      cur_param = TREE_VALUE (params);
2090 	      if (has_operand_number <= 0)
2091 		{
2092 		  params = TREE_CHAIN (params);
2093 		  ++arg_num;
2094 		}
2095 	    }
2096 	  width_wanted_type.wanted_type = *fki->width_type;
2097 	  width_wanted_type.wanted_type_name = NULL;
2098 	  width_wanted_type.pointer_count = 0;
2099 	  width_wanted_type.char_lenient_flag = 0;
2100 	  width_wanted_type.scalar_identity_flag = 0;
2101 	  width_wanted_type.writing_in_flag = 0;
2102 	  width_wanted_type.reading_from_flag = 0;
2103 	  width_wanted_type.kind = CF_KIND_FIELD_WIDTH;
2104 	  width_wanted_type.format_start = format_chars - 1;
2105 	  width_wanted_type.format_length = 1;
2106 	  width_wanted_type.param = cur_param;
2107 	  width_wanted_type.arg_num = arg_num;
2108 	  width_wanted_type.offset_loc =
2109 	    format_chars - orig_format_chars;
2110 	  width_wanted_type.next = NULL;
2111 	  if (last_wanted_type != 0)
2112 	    last_wanted_type->next = &width_wanted_type;
2113 	  if (first_wanted_type == 0)
2114 	    first_wanted_type = &width_wanted_type;
2115 	  last_wanted_type = &width_wanted_type;
2116 	}
2117     }
2118   else
2119     {
2120       /* Possibly read a numeric width.  If the width is zero,
2121 	 we complain if appropriate.  */
2122       int non_zero_width_char = FALSE;
2123       int found_width = FALSE;
2124       while (ISDIGIT (*format_chars))
2125 	{
2126 	  found_width = TRUE;
2127 	  if (*format_chars != '0')
2128 	    non_zero_width_char = TRUE;
2129 	  ++format_chars;
2130 	}
2131       if (found_width && !non_zero_width_char &&
2132 	  (fki->flags & (int) FMT_FLAG_ZERO_WIDTH_BAD))
2133 	warning_at (format_string_loc, OPT_Wformat_,
2134 		    "zero width in %s format", fki->name);
2135       if (found_width)
2136 	flag_chars.add_char (fki->width_char);
2137     }
2138 
2139   return true;
2140 }
2141 
2142 /* Read any format left precision (must be a number, not *).  */
2143 void
2144 argument_parser::read_any_format_left_precision ()
2145 {
2146   if (fki->left_precision_char == 0)
2147     return;
2148   if (*format_chars != '#')
2149     return;
2150 
2151   ++format_chars;
2152   flag_chars.add_char (fki->left_precision_char);
2153   if (!ISDIGIT (*format_chars))
2154     format_warning_at_char (format_string_loc, format_string_cst,
2155 			    format_chars - orig_format_chars,
2156 			    OPT_Wformat_,
2157 			    "empty left precision in %s format", fki->name);
2158   while (ISDIGIT (*format_chars))
2159     ++format_chars;
2160 }
2161 
2162 /* Read any format precision, possibly * or *m$.
2163 
2164    Return true if format parsing is to continue, false otherwise.  */
2165 
2166 bool
2167 argument_parser::
2168 read_any_format_precision (tree &params,
2169 			   unsigned HOST_WIDE_INT &arg_num)
2170 {
2171   if (fki->precision_char == 0)
2172     return true;
2173   if (*format_chars != '.')
2174     return true;
2175 
2176   ++format_chars;
2177   flag_chars.add_char (fki->precision_char);
2178   if (fki->precision_type != NULL && *format_chars == '*')
2179     {
2180       /* "...a...precision...may be indicated by an asterisk.
2181 	 In this case, an int argument supplies the...precision."  */
2182       ++format_chars;
2183       if (has_operand_number != 0)
2184 	{
2185 	  int opnum;
2186 	  opnum = maybe_read_dollar_number (&format_chars,
2187 					    has_operand_number == 1,
2188 					    first_fillin_param,
2189 					    &params, fki);
2190 	  if (opnum == -1)
2191 	    return false;
2192 	  else if (opnum > 0)
2193 	    {
2194 	      has_operand_number = 1;
2195 	      arg_num = opnum + info->first_arg_num - 1;
2196 	    }
2197 	  else
2198 	    has_operand_number = 0;
2199 	}
2200       else
2201 	{
2202 	  if (avoid_dollar_number (format_chars))
2203 	    return false;
2204 	}
2205       if (info->first_arg_num != 0)
2206 	{
2207 	  tree cur_param;
2208 	  if (params == 0)
2209 	    cur_param = NULL;
2210 	  else
2211 	    {
2212 	      cur_param = TREE_VALUE (params);
2213 	      if (has_operand_number <= 0)
2214 		{
2215 		  params = TREE_CHAIN (params);
2216 		  ++arg_num;
2217 		}
2218 	    }
2219 	  precision_wanted_type.wanted_type = *fki->precision_type;
2220 	  precision_wanted_type.wanted_type_name = NULL;
2221 	  precision_wanted_type.pointer_count = 0;
2222 	  precision_wanted_type.char_lenient_flag = 0;
2223 	  precision_wanted_type.scalar_identity_flag = 0;
2224 	  precision_wanted_type.writing_in_flag = 0;
2225 	  precision_wanted_type.reading_from_flag = 0;
2226 	  precision_wanted_type.kind = CF_KIND_FIELD_PRECISION;
2227 	  precision_wanted_type.param = cur_param;
2228 	  precision_wanted_type.format_start = format_chars - 2;
2229 	  precision_wanted_type.format_length = 2;
2230 	  precision_wanted_type.arg_num = arg_num;
2231 	  precision_wanted_type.offset_loc =
2232 	    format_chars - orig_format_chars;
2233 	  precision_wanted_type.next = NULL;
2234 	  if (last_wanted_type != 0)
2235 	    last_wanted_type->next = &precision_wanted_type;
2236 	  if (first_wanted_type == 0)
2237 	    first_wanted_type = &precision_wanted_type;
2238 	  last_wanted_type = &precision_wanted_type;
2239 	}
2240     }
2241   else
2242     {
2243       if (!(fki->flags & (int) FMT_FLAG_EMPTY_PREC_OK)
2244 	  && !ISDIGIT (*format_chars))
2245 	format_warning_at_char (format_string_loc, format_string_cst,
2246 				format_chars - orig_format_chars,
2247 				OPT_Wformat_,
2248 				"empty precision in %s format", fki->name);
2249       while (ISDIGIT (*format_chars))
2250 	++format_chars;
2251     }
2252 
2253   return true;
2254 }
2255 
2256 /* Parse any assignment-allocation flags, which request an extra
2257    char ** for writing back a dynamically-allocated char *.
2258    This is for handling the optional 'm' character in scanf,
2259    and, before C99, 'a' (for compatibility with a non-standard
2260    GNU libc extension).  */
2261 
2262 void
2263 argument_parser::handle_alloc_chars ()
2264 {
2265   if (fki->alloc_char && fki->alloc_char == *format_chars)
2266     {
2267       flag_chars.add_char (fki->alloc_char);
2268       format_chars++;
2269     }
2270 
2271   /* Handle the scanf allocation kludge.  */
2272   if (fki->flags & (int) FMT_FLAG_SCANF_A_KLUDGE)
2273     {
2274       if (*format_chars == 'a' && !flag_isoc99)
2275 	{
2276 	  if (format_chars[1] == 's' || format_chars[1] == 'S'
2277 	      || format_chars[1] == '[')
2278 	    {
2279 	      /* 'a' is used as a flag.  */
2280 	      flag_chars.add_char ('a');
2281 	      format_chars++;
2282 	    }
2283 	}
2284     }
2285 }
2286 
2287 /* Look for length modifiers within the current format argument,
2288    returning a length_modifier instance describing it (or the
2289    default if one is not found).
2290 
2291    Issue warnings about non-standard modifiers.  */
2292 
2293 length_modifier
2294 argument_parser::read_any_length_modifier ()
2295 {
2296   length_modifier result;
2297 
2298   const format_length_info *fli = fki->length_char_specs;
2299   if (!fli)
2300     return result;
2301 
2302   while (fli->name != 0
2303 	 && strncmp (fli->name, format_chars, strlen (fli->name)))
2304     fli++;
2305   if (fli->name != 0)
2306     {
2307       format_chars += strlen (fli->name);
2308       if (fli->double_name != 0 && fli->name[0] == *format_chars)
2309 	{
2310 	  format_chars++;
2311 	  result = length_modifier (fli->double_name, fli->double_index,
2312 				    fli->double_std, 0);
2313 	}
2314       else
2315 	{
2316 	  result = length_modifier (fli->name, fli->index, fli->std,
2317 				    fli->scalar_identity_flag);
2318 	}
2319       flag_chars.add_char (fki->length_code_char);
2320     }
2321   if (pedantic)
2322     {
2323       /* Warn if the length modifier is non-standard.  */
2324       if (ADJ_STD (result.std) > C_STD_VER)
2325 	warning_at (format_string_loc, OPT_Wformat_,
2326 		    "%s does not support the %qs %s length modifier",
2327 		    C_STD_NAME (result.std), result.chars,
2328 		    fki->name);
2329     }
2330 
2331   return result;
2332 }
2333 
2334 /* Read any other modifier (strftime E/O).  */
2335 
2336 void
2337 argument_parser::read_any_other_modifier ()
2338 {
2339   if (fki->modifier_chars == NULL)
2340     return;
2341 
2342   while (*format_chars != 0
2343 	 && strchr (fki->modifier_chars, *format_chars) != 0)
2344     {
2345       if (flag_chars.has_char_p (*format_chars))
2346 	{
2347 	  const format_flag_spec *s = get_flag_spec (flag_specs,
2348 						     *format_chars, NULL);
2349 	  format_warning_at_char (format_string_loc, format_string_cst,
2350 				  format_chars - orig_format_chars,
2351 				  OPT_Wformat_,
2352 				  "repeated %s in format", _(s->name));
2353 	}
2354       else
2355 	flag_chars.add_char (*format_chars);
2356       ++format_chars;
2357     }
2358 }
2359 
2360 /* Return the format_char_info corresponding to FORMAT_CHAR,
2361    potentially issuing a warning if the format char is
2362    not supported in the C standard version we are checking
2363    against.
2364 
2365    Issue a warning and return NULL if it is not found.
2366 
2367    Issue warnings about non-standard modifiers.  */
2368 
2369 const format_char_info *
2370 argument_parser::find_format_char_info (char format_char)
2371 {
2372   const format_char_info *fci = fki->conversion_specs;
2373 
2374   while (fci->format_chars != 0
2375 	 && strchr (fci->format_chars, format_char) == 0)
2376     ++fci;
2377   if (fci->format_chars == 0)
2378     {
2379       format_warning_at_char (format_string_loc, format_string_cst,
2380 			      format_chars - orig_format_chars,
2381 			      OPT_Wformat_,
2382 			      "unknown conversion type character"
2383 			      " %qc in format",
2384 			      format_char);
2385       return NULL;
2386     }
2387 
2388   if (pedantic)
2389     {
2390       if (ADJ_STD (fci->std) > C_STD_VER)
2391 	format_warning_at_char (format_string_loc, format_string_cst,
2392 				format_chars - orig_format_chars,
2393 				OPT_Wformat_,
2394 				"%s does not support the %<%%%c%> %s format",
2395 				C_STD_NAME (fci->std), format_char, fki->name);
2396     }
2397 
2398   return fci;
2399 }
2400 
2401 /* Validate the pairs of flags used.
2402    Issue warnings about incompatible combinations of flags.  */
2403 
2404 void
2405 argument_parser::validate_flag_pairs (const format_char_info *fci,
2406 				      char format_char)
2407 {
2408   const format_flag_pair * const bad_flag_pairs = fki->bad_flag_pairs;
2409 
2410   for (int i = 0; bad_flag_pairs[i].flag_char1 != 0; i++)
2411     {
2412       const format_flag_spec *s, *t;
2413       if (!flag_chars.has_char_p (bad_flag_pairs[i].flag_char1))
2414 	continue;
2415       if (!flag_chars.has_char_p (bad_flag_pairs[i].flag_char2))
2416 	continue;
2417       if (bad_flag_pairs[i].predicate != 0
2418 	  && strchr (fci->flags2, bad_flag_pairs[i].predicate) == 0)
2419 	continue;
2420       s = get_flag_spec (flag_specs, bad_flag_pairs[i].flag_char1, NULL);
2421       t = get_flag_spec (flag_specs, bad_flag_pairs[i].flag_char2, NULL);
2422       if (bad_flag_pairs[i].ignored)
2423 	{
2424 	  if (bad_flag_pairs[i].predicate != 0)
2425 	    warning_at (format_string_loc, OPT_Wformat_,
2426 			"%s ignored with %s and %<%%%c%> %s format",
2427 			_(s->name), _(t->name), format_char,
2428 			fki->name);
2429 	  else
2430 	    warning_at (format_string_loc, OPT_Wformat_,
2431 			"%s ignored with %s in %s format",
2432 			_(s->name), _(t->name), fki->name);
2433 	}
2434       else
2435 	{
2436 	  if (bad_flag_pairs[i].predicate != 0)
2437 	    warning_at (format_string_loc, OPT_Wformat_,
2438 			"use of %s and %s together with %<%%%c%> %s format",
2439 			_(s->name), _(t->name), format_char,
2440 			fki->name);
2441 	  else
2442 	    warning_at (format_string_loc, OPT_Wformat_,
2443 			"use of %s and %s together in %s format",
2444 			_(s->name), _(t->name), fki->name);
2445 	}
2446     }
2447 }
2448 
2449 /* Give Y2K warnings.  */
2450 
2451 void
2452 argument_parser::give_y2k_warnings (const format_char_info *fci,
2453 				    char format_char)
2454 {
2455   if (!warn_format_y2k)
2456     return;
2457 
2458   int y2k_level = 0;
2459   if (strchr (fci->flags2, '4') != 0)
2460     if (flag_chars.has_char_p ('E'))
2461       y2k_level = 3;
2462     else
2463       y2k_level = 2;
2464   else if (strchr (fci->flags2, '3') != 0)
2465     y2k_level = 3;
2466   else if (strchr (fci->flags2, '2') != 0)
2467     y2k_level = 2;
2468   if (y2k_level == 3)
2469     warning_at (format_string_loc, OPT_Wformat_y2k,
2470 		"%<%%%c%> yields only last 2 digits of "
2471 		"year in some locales", format_char);
2472   else if (y2k_level == 2)
2473     warning_at (format_string_loc, OPT_Wformat_y2k,
2474 		"%<%%%c%> yields only last 2 digits of year",
2475 		format_char);
2476 }
2477 
2478 /* Parse any "scan sets" enclosed in square brackets, e.g.
2479    for scanf-style calls.  */
2480 
2481 void
2482 argument_parser::parse_any_scan_set (const format_char_info *fci)
2483 {
2484   if (strchr (fci->flags2, '[') == NULL)
2485     return;
2486 
2487   /* Skip over scan set, in case it happens to have '%' in it.  */
2488   if (*format_chars == '^')
2489     ++format_chars;
2490   /* Find closing bracket; if one is hit immediately, then
2491      it's part of the scan set rather than a terminator.  */
2492   if (*format_chars == ']')
2493     ++format_chars;
2494   while (*format_chars && *format_chars != ']')
2495     ++format_chars;
2496   if (*format_chars != ']')
2497     /* The end of the format string was reached.  */
2498     format_warning_at_char (format_string_loc, format_string_cst,
2499 			    format_chars - orig_format_chars,
2500 			    OPT_Wformat_,
2501 			    "no closing %<]%> for %<%%[%> format");
2502 }
2503 
2504 /* Return true if this argument is to be continued to be parsed,
2505    false to skip to next argument.  */
2506 
2507 bool
2508 argument_parser::handle_conversions (const format_char_info *fci,
2509 				     const length_modifier &len_modifier,
2510 				     tree &wanted_type,
2511 				     const char *&wanted_type_name,
2512 				     unsigned HOST_WIDE_INT &arg_num,
2513 				     tree &params,
2514 				     char format_char)
2515 {
2516   enum format_std_version wanted_type_std;
2517 
2518   if (!(fki->flags & (int) FMT_FLAG_ARG_CONVERT))
2519     return true;
2520 
2521   wanted_type = (fci->types[len_modifier.val].type
2522 		 ? *fci->types[len_modifier.val].type : 0);
2523   wanted_type_name = fci->types[len_modifier.val].name;
2524   wanted_type_std = fci->types[len_modifier.val].std;
2525   if (wanted_type == 0)
2526     {
2527       format_warning_at_char (format_string_loc, format_string_cst,
2528 			      format_chars - orig_format_chars,
2529 			      OPT_Wformat_,
2530 			      "use of %qs length modifier with %qc type"
2531 			      " character has either no effect"
2532 			      " or undefined behavior",
2533 			      len_modifier.chars, format_char);
2534       /* Heuristic: skip one argument when an invalid length/type
2535 	 combination is encountered.  */
2536       arg_num++;
2537       if (params != 0)
2538 	params = TREE_CHAIN (params);
2539       return false;
2540     }
2541   else if (pedantic
2542 	   /* Warn if non-standard, provided it is more non-standard
2543 	      than the length and type characters that may already
2544 	      have been warned for.  */
2545 	   && ADJ_STD (wanted_type_std) > ADJ_STD (len_modifier.std)
2546 	   && ADJ_STD (wanted_type_std) > ADJ_STD (fci->std))
2547     {
2548       if (ADJ_STD (wanted_type_std) > C_STD_VER)
2549 	format_warning_at_char (format_string_loc, format_string_cst,
2550 				format_chars - orig_format_chars,
2551 				OPT_Wformat_,
2552 				"%s does not support the %<%%%s%c%> %s format",
2553 				C_STD_NAME (wanted_type_std),
2554 				len_modifier.chars,
2555 				format_char, fki->name);
2556     }
2557 
2558   return true;
2559 }
2560 
2561 /* Check type of argument against desired type.
2562 
2563    Return true if format parsing is to continue, false otherwise.  */
2564 
2565 bool
2566 argument_parser::
2567 check_argument_type (const format_char_info *fci,
2568 		     const length_modifier &len_modifier,
2569 		     tree &wanted_type,
2570 		     const char *&wanted_type_name,
2571 		     const bool suppressed,
2572 		     unsigned HOST_WIDE_INT &arg_num,
2573 		     tree &params,
2574 		     const int alloc_flag,
2575 		     const char * const format_start,
2576 		     const char * const type_start,
2577 		     location_t fmt_param_loc,
2578 		     char conversion_char)
2579 {
2580   if (info->first_arg_num == 0)
2581     return true;
2582 
2583   if ((fci->pointer_count == 0 && wanted_type == void_type_node)
2584       || suppressed)
2585     {
2586       if (main_arg_num != 0)
2587 	{
2588 	  if (suppressed)
2589 	    warning_at (format_string_loc, OPT_Wformat_,
2590 			"operand number specified with "
2591 			"suppressed assignment");
2592 	  else
2593 	    warning_at (format_string_loc, OPT_Wformat_,
2594 			"operand number specified for format "
2595 			"taking no argument");
2596 	}
2597     }
2598   else
2599     {
2600       format_wanted_type *wanted_type_ptr;
2601 
2602       if (main_arg_num != 0)
2603 	{
2604 	  arg_num = main_arg_num;
2605 	  params = main_arg_params;
2606 	}
2607       else
2608 	{
2609 	  ++arg_num;
2610 	  if (has_operand_number > 0)
2611 	    {
2612 	      warning_at (format_string_loc, OPT_Wformat_,
2613 			  "missing $ operand number in format");
2614 	      return false;
2615 	    }
2616 	  else
2617 	    has_operand_number = 0;
2618 	}
2619 
2620       wanted_type_ptr = &main_wanted_type;
2621       while (fci)
2622 	{
2623 	  tree cur_param;
2624 	  if (params == 0)
2625 	    cur_param = NULL;
2626 	  else
2627 	    {
2628 	      cur_param = TREE_VALUE (params);
2629 	      params = TREE_CHAIN (params);
2630 	    }
2631 
2632 	  wanted_type_ptr->wanted_type = wanted_type;
2633 	  wanted_type_ptr->wanted_type_name = wanted_type_name;
2634 	  wanted_type_ptr->pointer_count = fci->pointer_count + alloc_flag;
2635 	  wanted_type_ptr->char_lenient_flag = 0;
2636 	  if (strchr (fci->flags2, 'c') != 0)
2637 	    wanted_type_ptr->char_lenient_flag = 1;
2638 	  wanted_type_ptr->scalar_identity_flag = 0;
2639 	  if (len_modifier.scalar_identity_flag)
2640 	    wanted_type_ptr->scalar_identity_flag = 1;
2641 	  wanted_type_ptr->writing_in_flag = 0;
2642 	  wanted_type_ptr->reading_from_flag = 0;
2643 	  if (alloc_flag)
2644 	    wanted_type_ptr->writing_in_flag = 1;
2645 	  else
2646 	    {
2647 	      if (strchr (fci->flags2, 'W') != 0)
2648 		wanted_type_ptr->writing_in_flag = 1;
2649 	      if (strchr (fci->flags2, 'R') != 0)
2650 		wanted_type_ptr->reading_from_flag = 1;
2651 	    }
2652 	  wanted_type_ptr->kind = CF_KIND_FORMAT;
2653 	  wanted_type_ptr->param = cur_param;
2654 	  wanted_type_ptr->arg_num = arg_num;
2655 	  wanted_type_ptr->format_start = format_start;
2656 	  wanted_type_ptr->format_length = format_chars - format_start;
2657 	  wanted_type_ptr->offset_loc = format_chars - orig_format_chars;
2658 	  wanted_type_ptr->next = NULL;
2659 	  if (last_wanted_type != 0)
2660 	    last_wanted_type->next = wanted_type_ptr;
2661 	  if (first_wanted_type == 0)
2662 	    first_wanted_type = wanted_type_ptr;
2663 	  last_wanted_type = wanted_type_ptr;
2664 
2665 	  fci = fci->chain;
2666 	  if (fci)
2667 	    {
2668 	      wanted_type_ptr = fwt_pool.allocate ();
2669 	      arg_num++;
2670 	      wanted_type = *fci->types[len_modifier.val].type;
2671 	      wanted_type_name = fci->types[len_modifier.val].name;
2672 	    }
2673 	}
2674     }
2675 
2676   if (first_wanted_type != 0)
2677     {
2678       ptrdiff_t offset_to_format_start = (start_of_this_format - 1) - orig_format_chars;
2679       ptrdiff_t offset_to_format_end = (format_chars - 1) - orig_format_chars;
2680       /* By default, use the end of the range for the caret location.  */
2681       substring_loc fmt_loc (fmt_param_loc, TREE_TYPE (format_string_cst),
2682 			     offset_to_format_end,
2683 			     offset_to_format_start, offset_to_format_end);
2684       ptrdiff_t offset_to_type_start = type_start - orig_format_chars;
2685       check_format_types (fmt_loc, first_wanted_type, fki,
2686 			  offset_to_type_start,
2687 			  conversion_char);
2688     }
2689 
2690   return true;
2691 }
2692 
2693 /* Do the main part of checking a call to a format function.  FORMAT_CHARS
2694    is the NUL-terminated format string (which at this point may contain
2695    internal NUL characters); FORMAT_LENGTH is its length (excluding the
2696    terminating NUL character).  ARG_NUM is one less than the number of
2697    the first format argument to check; PARAMS points to that format
2698    argument in the list of arguments.  */
2699 
2700 static void
2701 check_format_info_main (format_check_results *res,
2702 			function_format_info *info, const char *format_chars,
2703 			location_t fmt_param_loc, tree format_string_cst,
2704 			int format_length, tree params,
2705 			unsigned HOST_WIDE_INT arg_num,
2706 			object_allocator <format_wanted_type> &fwt_pool)
2707 {
2708   const char * const orig_format_chars = format_chars;
2709   const tree first_fillin_param = params;
2710 
2711   const format_kind_info * const fki = &format_types[info->format_type];
2712   const format_flag_spec * const flag_specs = fki->flag_specs;
2713   const location_t format_string_loc = res->format_string_loc;
2714 
2715   /* -1 if no conversions taking an operand have been found; 0 if one has
2716      and it didn't use $; 1 if $ formats are in use.  */
2717   int has_operand_number = -1;
2718 
2719   init_dollar_format_checking (info->first_arg_num, first_fillin_param);
2720 
2721   while (*format_chars != 0)
2722     {
2723       if (*format_chars++ != '%')
2724 	continue;
2725       if (*format_chars == 0)
2726 	{
2727 	  format_warning_at_char (format_string_loc, format_string_cst,
2728 				  format_chars - orig_format_chars,
2729 				  OPT_Wformat_,
2730 				  "spurious trailing %<%%%> in format");
2731 	  continue;
2732 	}
2733       if (*format_chars == '%')
2734 	{
2735 	  ++format_chars;
2736 	  continue;
2737 	}
2738 
2739       flag_chars_t flag_chars;
2740       argument_parser arg_parser (info, format_chars, format_string_cst,
2741 				  orig_format_chars, format_string_loc,
2742 				  flag_chars, has_operand_number,
2743 				  first_fillin_param, fwt_pool);
2744 
2745       if (!arg_parser.read_any_dollar ())
2746 	return;
2747 
2748       if (!arg_parser.read_format_flags ())
2749 	return;
2750 
2751       /* Read any format width, possibly * or *m$.  */
2752       if (!arg_parser.read_any_format_width (params, arg_num))
2753 	return;
2754 
2755       /* Read any format left precision (must be a number, not *).  */
2756       arg_parser.read_any_format_left_precision ();
2757 
2758       /* Read any format precision, possibly * or *m$.  */
2759       if (!arg_parser.read_any_format_precision (params, arg_num))
2760 	return;
2761 
2762       const char *format_start = format_chars;
2763 
2764       arg_parser.handle_alloc_chars ();
2765 
2766       /* The rest of the conversion specification is the length modifier
2767 	 (if any), and the conversion specifier, so this is where the
2768 	 type information starts.  If we need to issue a suggestion
2769 	 about a type mismatch, then we should preserve everything up
2770 	 to here. */
2771       const char *type_start = format_chars;
2772 
2773       /* Read any length modifier, if this kind of format has them.  */
2774       const length_modifier len_modifier
2775 	= arg_parser.read_any_length_modifier ();
2776 
2777       /* Read any modifier (strftime E/O).  */
2778       arg_parser.read_any_other_modifier ();
2779 
2780       char format_char = *format_chars;
2781       if (format_char == 0
2782 	  || (!(fki->flags & (int) FMT_FLAG_FANCY_PERCENT_OK)
2783 	      && format_char == '%'))
2784 	{
2785 	  format_warning_at_char (format_string_loc, format_string_cst,
2786 			     format_chars - orig_format_chars,
2787 			     OPT_Wformat_,
2788 			     "conversion lacks type at end of format");
2789 	  continue;
2790 	}
2791 
2792       if (format_char == 'm' && !(fki->flags & FMT_FLAG_M_OK))
2793         {
2794 	  warning (OPT_Wformat_,
2795 	      "%%m is only allowed in syslog(3) like functions");
2796 	  continue;
2797 	}
2798 
2799       format_chars++;
2800 
2801       const format_char_info * const fci
2802 	= arg_parser.find_format_char_info (format_char);
2803       if (!fci)
2804 	continue;
2805 
2806       flag_chars.validate (fki, fci, flag_specs, format_chars,
2807 			   format_string_cst,
2808 			   format_string_loc, orig_format_chars, format_char);
2809 
2810       const int alloc_flag = flag_chars.get_alloc_flag (fki);
2811       const bool suppressed = flag_chars.assignment_suppression_p (fki);
2812 
2813       /* Validate the pairs of flags used.  */
2814       arg_parser.validate_flag_pairs (fci, format_char);
2815 
2816       arg_parser.give_y2k_warnings (fci, format_char);
2817 
2818       arg_parser.parse_any_scan_set (fci);
2819 
2820       tree wanted_type = NULL;
2821       const char *wanted_type_name = NULL;
2822 
2823       if (!arg_parser.handle_conversions (fci, len_modifier,
2824 					  wanted_type, wanted_type_name,
2825 					  arg_num,
2826 					  params,
2827 					  format_char))
2828 	continue;
2829 
2830       arg_parser.main_wanted_type.next = NULL;
2831 
2832       /* Finally. . .check type of argument against desired type!  */
2833       if (!arg_parser.check_argument_type (fci, len_modifier,
2834 					   wanted_type, wanted_type_name,
2835 					   suppressed,
2836 					   arg_num, params,
2837 					   alloc_flag,
2838 					   format_start, type_start,
2839 					   fmt_param_loc,
2840 					   format_char))
2841 	return;
2842     }
2843 
2844   if (format_chars - orig_format_chars != format_length)
2845     format_warning_at_char (format_string_loc, format_string_cst,
2846 			    format_chars + 1 - orig_format_chars,
2847 			    OPT_Wformat_contains_nul,
2848 			    "embedded %<\\0%> in format");
2849   if (info->first_arg_num != 0 && params != 0
2850       && has_operand_number <= 0)
2851     {
2852       res->number_other--;
2853       res->number_extra_args++;
2854     }
2855   if (has_operand_number > 0)
2856     finish_dollar_format_checking (res, fki->flags & (int) FMT_FLAG_DOLLAR_GAP_POINTER_OK);
2857 }
2858 
2859 /* Check the argument types from a single format conversion (possibly
2860    including width and precision arguments).
2861 
2862    FMT_LOC is the location of the format conversion.
2863 
2864    TYPES is a singly-linked list expressing the parts of the format
2865    conversion that expect argument types, and the arguments they
2866    correspond to.
2867 
2868    OFFSET_TO_TYPE_START is the offset within the execution-charset encoded
2869    format string to where type information begins for the conversion
2870    (the length modifier and conversion specifier).
2871 
2872    CONVERSION_CHAR is the user-provided conversion specifier.
2873 
2874    For example, given:
2875 
2876      sprintf (d, "before %-+*.*lld after", arg3, arg4, arg5);
2877 
2878    then FMT_LOC covers this range:
2879 
2880      sprintf (d, "before %-+*.*lld after", arg3, arg4, arg5);
2881                          ^^^^^^^^^
2882 
2883    and TYPES in this case is a three-entry singly-linked list consisting of:
2884    (1) the check for the field width here:
2885          sprintf (d, "before %-+*.*lld after", arg3, arg4, arg5);
2886                                 ^              ^^^^
2887        against arg3, and
2888    (2) the check for the field precision here:
2889          sprintf (d, "before %-+*.*lld after", arg3, arg4, arg5);
2890                                  ^^                  ^^^^
2891        against arg4, and
2892    (3) the check for the length modifier and conversion char here:
2893          sprintf (d, "before %-+*.*lld after", arg3, arg4, arg5);
2894                                    ^^^                     ^^^^
2895        against arg5.
2896 
2897    OFFSET_TO_TYPE_START is 13, the offset to the "lld" within the
2898    STRING_CST:
2899 
2900                   0000000000111111111122
2901                   0123456789012345678901
2902      sprintf (d, "before %-+*.*lld after", arg3, arg4, arg5);
2903                                ^ ^
2904                                | ` CONVERSION_CHAR: 'd'
2905                                type starts here.  */
2906 
2907 static void
2908 check_format_types (const substring_loc &fmt_loc,
2909 		    format_wanted_type *types, const format_kind_info *fki,
2910 		    int offset_to_type_start,
2911 		    char conversion_char)
2912 {
2913   for (; types != 0; types = types->next)
2914     {
2915       tree cur_param;
2916       tree cur_type;
2917       tree orig_cur_type;
2918       tree wanted_type;
2919       int arg_num;
2920       int i;
2921       int char_type_flag;
2922 
2923       wanted_type = types->wanted_type;
2924       arg_num = types->arg_num;
2925 
2926       /* The following should not occur here.  */
2927       gcc_assert (wanted_type);
2928       gcc_assert (wanted_type != void_type_node || types->pointer_count);
2929 
2930       if (types->pointer_count == 0)
2931 	wanted_type = lang_hooks.types.type_promotes_to (wanted_type);
2932 
2933       wanted_type = TYPE_MAIN_VARIANT (wanted_type);
2934 
2935       cur_param = types->param;
2936       if (!cur_param)
2937         {
2938 	  format_type_warning (fmt_loc, NULL, types, wanted_type, NULL, fki,
2939 			       offset_to_type_start, conversion_char);
2940           continue;
2941         }
2942 
2943       cur_type = TREE_TYPE (cur_param);
2944       if (cur_type == error_mark_node)
2945 	continue;
2946       orig_cur_type = cur_type;
2947       char_type_flag = 0;
2948 
2949       source_range param_range;
2950       source_range *param_range_ptr;
2951       if (CAN_HAVE_LOCATION_P (cur_param))
2952 	{
2953 	  param_range = EXPR_LOCATION_RANGE (cur_param);
2954 	  param_range_ptr = &param_range;
2955 	}
2956       else
2957 	param_range_ptr = NULL;
2958 
2959       STRIP_NOPS (cur_param);
2960 
2961       /* Check the types of any additional pointer arguments
2962 	 that precede the "real" argument.  */
2963       for (i = 0; i < types->pointer_count; ++i)
2964 	{
2965 	  if (TREE_CODE (cur_type) == POINTER_TYPE)
2966 	    {
2967 	      cur_type = TREE_TYPE (cur_type);
2968 	      if (cur_type == error_mark_node)
2969 		break;
2970 
2971 	      /* Check for writing through a NULL pointer.  */
2972 	      if (types->writing_in_flag
2973 		  && i == 0
2974 		  && cur_param != 0
2975 		  && integer_zerop (cur_param))
2976 		warning (OPT_Wformat_, "writing through null pointer "
2977 			 "(argument %d)", arg_num);
2978 
2979 	      /* Check for reading through a NULL pointer.  */
2980 	      if (types->reading_from_flag
2981 		  && i == 0
2982 		  && cur_param != 0
2983 		  && integer_zerop (cur_param))
2984 		warning (OPT_Wformat_, "reading through null pointer "
2985 			 "(argument %d)", arg_num);
2986 
2987 	      if (cur_param != 0 && TREE_CODE (cur_param) == ADDR_EXPR)
2988 		cur_param = TREE_OPERAND (cur_param, 0);
2989 	      else
2990 		cur_param = 0;
2991 
2992 	      /* See if this is an attempt to write into a const type with
2993 		 scanf or with printf "%n".  Note: the writing in happens
2994 		 at the first indirection only, if for example
2995 		 void * const * is passed to scanf %p; passing
2996 		 const void ** is simply passing an incompatible type.  */
2997 	      if (types->writing_in_flag
2998 		  && i == 0
2999 		  && (TYPE_READONLY (cur_type)
3000 		      || (cur_param != 0
3001 			  && (CONSTANT_CLASS_P (cur_param)
3002 			      || (DECL_P (cur_param)
3003 				  && TREE_READONLY (cur_param))))))
3004 		warning (OPT_Wformat_, "writing into constant object "
3005 			 "(argument %d)", arg_num);
3006 
3007 	      /* If there are extra type qualifiers beyond the first
3008 		 indirection, then this makes the types technically
3009 		 incompatible.  */
3010 	      if (i > 0
3011 		  && pedantic
3012 		  && (TYPE_READONLY (cur_type)
3013 		      || TYPE_VOLATILE (cur_type)
3014 		      || TYPE_ATOMIC (cur_type)
3015 		      || TYPE_RESTRICT (cur_type)))
3016 		warning (OPT_Wformat_, "extra type qualifiers in format "
3017 			 "argument (argument %d)",
3018 			 arg_num);
3019 
3020 	    }
3021 	  else
3022 	    {
3023 	      format_type_warning (fmt_loc, param_range_ptr,
3024 				   types, wanted_type, orig_cur_type, fki,
3025 				   offset_to_type_start, conversion_char);
3026 	      break;
3027 	    }
3028 	}
3029 
3030       if (i < types->pointer_count)
3031 	continue;
3032 
3033       cur_type = TYPE_MAIN_VARIANT (cur_type);
3034 
3035       /* Check whether the argument type is a character type.  This leniency
3036 	 only applies to certain formats, flagged with 'c'.  */
3037       if (types->char_lenient_flag)
3038 	char_type_flag = (cur_type == char_type_node
3039 			  || cur_type == signed_char_type_node
3040 			  || cur_type == unsigned_char_type_node);
3041 
3042       /* Check the type of the "real" argument, if there's a type we want.  */
3043       if (lang_hooks.types_compatible_p (wanted_type, cur_type))
3044 	continue;
3045       /* If we want 'void *', allow any pointer type.
3046 	 (Anything else would already have got a warning.)
3047 	 With -Wpedantic, only allow pointers to void and to character
3048 	 types.  */
3049       if (wanted_type == void_type_node
3050 	  && (!pedantic || (i == 1 && char_type_flag)))
3051 	continue;
3052       /* Don't warn about differences merely in signedness, unless
3053 	 -Wpedantic.  With -Wpedantic, warn if the type is a pointer
3054 	 target and not a character type, and for character types at
3055 	 a second level of indirection.  */
3056       if (TREE_CODE (wanted_type) == INTEGER_TYPE
3057 	  && TREE_CODE (cur_type) == INTEGER_TYPE
3058 	  && ((!pedantic && !warn_format_signedness)
3059 	      || (i == 0 && !warn_format_signedness)
3060 	      || (i == 1 && char_type_flag))
3061 	  && (TYPE_UNSIGNED (wanted_type)
3062 	      ? wanted_type == c_common_unsigned_type (cur_type)
3063 	      : wanted_type == c_common_signed_type (cur_type)))
3064 	continue;
3065       /* Don't warn about differences merely in signedness if we know
3066 	 that the current type is integer-promoted and its original type
3067 	 was unsigned such as that it is in the range of WANTED_TYPE.  */
3068       if (TREE_CODE (wanted_type) == INTEGER_TYPE
3069 	  && TREE_CODE (cur_type) == INTEGER_TYPE
3070 	  && warn_format_signedness
3071 	  && TYPE_UNSIGNED (wanted_type)
3072 	  && cur_param != NULL_TREE
3073 	  && TREE_CODE (cur_param) == NOP_EXPR)
3074 	{
3075 	  tree t = TREE_TYPE (TREE_OPERAND (cur_param, 0));
3076 	  if (TYPE_UNSIGNED (t)
3077 	      && cur_type == lang_hooks.types.type_promotes_to (t))
3078 	    continue;
3079 	}
3080       /* Likewise, "signed char", "unsigned char" and "char" are
3081 	 equivalent but the above test won't consider them equivalent.  */
3082       if (wanted_type == char_type_node
3083 	  && (!pedantic || i < 2)
3084 	  && char_type_flag)
3085 	continue;
3086       if (types->scalar_identity_flag
3087 	  && (TREE_CODE (cur_type) == TREE_CODE (wanted_type)
3088 	      || (INTEGRAL_TYPE_P (cur_type)
3089 		  && INTEGRAL_TYPE_P (wanted_type)))
3090 	  && TYPE_PRECISION (cur_type) == TYPE_PRECISION (wanted_type))
3091 	continue;
3092       /* Now we have a type mismatch.  */
3093       format_type_warning (fmt_loc, param_range_ptr, types,
3094 			   wanted_type, orig_cur_type, fki,
3095 			   offset_to_type_start, conversion_char);
3096     }
3097 }
3098 
3099 /* Given type TYPE, attempt to dereference the type N times
3100    (e.g. from ("int ***", 2) to "int *")
3101 
3102    Return the derefenced type, with any qualifiers
3103    such as "const" stripped from the result, or
3104    NULL if unsuccessful (e.g. TYPE is not a pointer type).  */
3105 
3106 static tree
3107 deref_n_times (tree type, int n)
3108 {
3109   gcc_assert (type);
3110 
3111   for (int i = n; i > 0; i--)
3112     {
3113       if (TREE_CODE (type) != POINTER_TYPE)
3114 	return NULL_TREE;
3115       type = TREE_TYPE (type);
3116     }
3117   /* Strip off any "const" etc.  */
3118   return build_qualified_type (type, 0);
3119 }
3120 
3121 /* Lookup the format code for FORMAT_LEN within FLI,
3122    returning the string code for expressing it, or NULL
3123    if it is not found.  */
3124 
3125 static const char *
3126 get_modifier_for_format_len (const format_length_info *fli,
3127 			     enum format_lengths format_len)
3128 {
3129   for (; fli->name; fli++)
3130     {
3131       if (fli->index == format_len)
3132 	return fli->name;
3133       if (fli->double_index == format_len)
3134 	return fli->double_name;
3135     }
3136   return NULL;
3137 }
3138 
3139 #if CHECKING_P
3140 
3141 namespace selftest {
3142 
3143 static void
3144 test_get_modifier_for_format_len ()
3145 {
3146   ASSERT_STREQ ("h",
3147 		get_modifier_for_format_len (printf_length_specs, FMT_LEN_h));
3148   ASSERT_STREQ ("hh",
3149 		get_modifier_for_format_len (printf_length_specs, FMT_LEN_hh));
3150   ASSERT_STREQ ("L",
3151 		get_modifier_for_format_len (printf_length_specs, FMT_LEN_L));
3152   ASSERT_EQ (NULL,
3153 	     get_modifier_for_format_len (printf_length_specs, FMT_LEN_none));
3154 }
3155 
3156 } // namespace selftest
3157 
3158 #endif /* CHECKING_P */
3159 
3160 /* Determine if SPEC_TYPE and ARG_TYPE are sufficiently similar for a
3161    format_type_detail using SPEC_TYPE to be offered as a suggestion for
3162    Wformat type errors where the argument has type ARG_TYPE.  */
3163 
3164 static bool
3165 matching_type_p (tree spec_type, tree arg_type)
3166 {
3167   gcc_assert (spec_type);
3168   gcc_assert (arg_type);
3169 
3170   /* If any of the types requires structural equality, we can't compare
3171      their canonical types.  */
3172   if (TYPE_STRUCTURAL_EQUALITY_P (spec_type)
3173       || TYPE_STRUCTURAL_EQUALITY_P (arg_type))
3174     return false;
3175 
3176   spec_type = TYPE_CANONICAL (spec_type);
3177   arg_type = TYPE_CANONICAL (arg_type);
3178 
3179   if (TREE_CODE (spec_type) == INTEGER_TYPE
3180       && TREE_CODE (arg_type) == INTEGER_TYPE
3181       && (TYPE_UNSIGNED (spec_type)
3182 	  ? spec_type == c_common_unsigned_type (arg_type)
3183 	  : spec_type == c_common_signed_type (arg_type)))
3184     return true;
3185 
3186   return spec_type == arg_type;
3187 }
3188 
3189 /* Subroutine of get_format_for_type.
3190 
3191    Generate a string containing the length modifier and conversion specifier
3192    that should be used to format arguments of type ARG_TYPE within FKI
3193    (effectively the inverse of the checking code).
3194 
3195    If CONVERSION_CHAR is not zero (the first pass), the resulting suggestion
3196    is required to use it, for correcting bogus length modifiers.
3197    If CONVERSION_CHAR is zero (the second pass), then allow any suggestion
3198    that matches ARG_TYPE.
3199 
3200    If successful, returns a non-NULL string which should be freed
3201    by the caller.
3202    Otherwise, returns NULL.  */
3203 
3204 static char *
3205 get_format_for_type_1 (const format_kind_info *fki, tree arg_type,
3206 		       char conversion_char)
3207 {
3208   gcc_assert (arg_type);
3209 
3210   const format_char_info *spec;
3211   for (spec = &fki->conversion_specs[0];
3212        spec->format_chars;
3213        spec++)
3214     {
3215       if (conversion_char)
3216 	if (!strchr (spec->format_chars, conversion_char))
3217 	  continue;
3218 
3219       tree effective_arg_type = deref_n_times (arg_type,
3220 					       spec->pointer_count);
3221       if (!effective_arg_type)
3222 	continue;
3223       for (int i = 0; i < FMT_LEN_MAX; i++)
3224 	{
3225 	  const format_type_detail *ftd = &spec->types[i];
3226 	  if (!ftd->type)
3227 	    continue;
3228 	  if (matching_type_p (*ftd->type, effective_arg_type))
3229 	    {
3230 	      const char *len_modifier
3231 		= get_modifier_for_format_len (fki->length_char_specs,
3232 					       (enum format_lengths)i);
3233 	      if (!len_modifier)
3234 		len_modifier = "";
3235 
3236 	      if (conversion_char)
3237 		/* We found a match, using the given conversion char - the
3238 		   length modifier was incorrect (or absent).
3239 		   Provide a suggestion using the conversion char with the
3240 		   correct length modifier for the type.  */
3241 		return xasprintf ("%s%c", len_modifier, conversion_char);
3242 	      else
3243 		/* 2nd pass: no match was possible using the user-provided
3244 		   conversion char, but we do have a match without using it.
3245 		   Provide a suggestion using the first conversion char
3246 		   listed for the given type.  */
3247 		return xasprintf ("%s%c", len_modifier, spec->format_chars[0]);
3248 	    }
3249 	}
3250    }
3251 
3252   return NULL;
3253 }
3254 
3255 /* Generate a string containing the length modifier and conversion specifier
3256    that should be used to format arguments of type ARG_TYPE within FKI
3257    (effectively the inverse of the checking code).
3258 
3259    If successful, returns a non-NULL string which should be freed
3260    by the caller.
3261    Otherwise, returns NULL.  */
3262 
3263 static char *
3264 get_format_for_type (const format_kind_info *fki, tree arg_type,
3265 		     char conversion_char)
3266 {
3267   gcc_assert (arg_type);
3268   gcc_assert (conversion_char);
3269 
3270   /* First pass: look for a format_char_info containing CONVERSION_CHAR
3271      If we find one, then presumably the length modifier was incorrect
3272      (or absent).  */
3273   char *result = get_format_for_type_1 (fki, arg_type, conversion_char);
3274   if (result)
3275     return result;
3276 
3277   /* Second pass: we didn't find a match for CONVERSION_CHAR, so try
3278      matching just on the type. */
3279   return get_format_for_type_1 (fki, arg_type, '\0');
3280 }
3281 
3282 /* Attempt to get a string for use as a replacement fix-it hint for the
3283    source range in FMT_LOC.
3284 
3285    Preserve all of the text within the range of FMT_LOC up to
3286    OFFSET_TO_TYPE_START, replacing the rest with an appropriate
3287    length modifier and conversion specifier for ARG_TYPE, attempting
3288    to keep the user-provided CONVERSION_CHAR if possible.
3289 
3290    For example, given a long vs long long mismatch for arg5 here:
3291 
3292     000000000111111111122222222223333333333|
3293     123456789012345678901234567890123456789` column numbers
3294                    0000000000111111111122|
3295                    0123456789012345678901` string offsets
3296                           V~~~~~~~~ : range of FMT_LOC, from cols 23-31
3297       sprintf (d, "before %-+*.*lld after", arg3, arg4, arg5);
3298                                 ^ ^
3299                                 | ` CONVERSION_CHAR: 'd'
3300                                 type starts here
3301 
3302    where OFFSET_TO_TYPE_START is 13 (the offset to the "lld" within the
3303    STRING_CST), where the user provided:
3304      %-+*.*lld
3305    the result (assuming "long" argument 5) should be:
3306      %-+*.*ld
3307 
3308    If successful, returns a non-NULL string which should be freed
3309    by the caller.
3310    Otherwise, returns NULL.  */
3311 
3312 static char *
3313 get_corrected_substring (const substring_loc &fmt_loc,
3314 			 format_wanted_type *type, tree arg_type,
3315 			 const format_kind_info *fki,
3316 			 int offset_to_type_start, char conversion_char)
3317 {
3318   /* Attempt to provide hints for argument types, but not for field widths
3319      and precisions.  */
3320   if (!arg_type)
3321     return NULL;
3322   if (type->kind != CF_KIND_FORMAT)
3323     return NULL;
3324 
3325   /* Locate the current code within the source range, rejecting
3326      any awkward cases where the format string occupies more than
3327      one line.
3328      Lookup the place where the type starts (including any length
3329      modifiers), getting it as the caret location.  */
3330   substring_loc type_loc (fmt_loc);
3331   type_loc.set_caret_index (offset_to_type_start);
3332 
3333   location_t fmt_substring_loc;
3334   const char *err = type_loc.get_location (&fmt_substring_loc);
3335   if (err)
3336     return NULL;
3337 
3338   source_range fmt_substring_range
3339     = get_range_from_loc (line_table, fmt_substring_loc);
3340 
3341   expanded_location caret
3342     = expand_location_to_spelling_point (fmt_substring_loc);
3343   expanded_location start
3344     = expand_location_to_spelling_point (fmt_substring_range.m_start);
3345   expanded_location finish
3346     = expand_location_to_spelling_point (fmt_substring_range.m_finish);
3347   if (caret.file != start.file)
3348     return NULL;
3349   if (start.file != finish.file)
3350     return NULL;
3351   if (caret.line != start.line)
3352     return NULL;
3353   if (start.line != finish.line)
3354     return NULL;
3355   if (start.column > caret.column)
3356     return NULL;
3357   if (start.column > finish.column)
3358     return NULL;
3359   if (caret.column > finish.column)
3360     return NULL;
3361 
3362   int line_width;
3363   const char *line = location_get_source_line (start.file, start.line,
3364 					       &line_width);
3365   if (line == NULL)
3366     return NULL;
3367 
3368   /* If we got this far, then we have the line containing the
3369      existing conversion specification.
3370 
3371      Generate a trimmed copy, containing the prefix part of the conversion
3372      specification, up to the (but not including) the length modifier.
3373      In the above example, this would be "%-+*.*".  */
3374   const char *current_content = line + start.column - 1;
3375   int length_up_to_type = caret.column - start.column;
3376   char *prefix = xstrndup (current_content, length_up_to_type);
3377 
3378   /* Now attempt to generate a suggestion for the rest of the specification
3379      (length modifier and conversion char), based on ARG_TYPE and
3380      CONVERSION_CHAR.
3381      In the above example, this would be "ld".  */
3382   char *format_for_type = get_format_for_type (fki, arg_type, conversion_char);
3383   if (!format_for_type)
3384     {
3385       free (prefix);
3386       return NULL;
3387     }
3388 
3389   /* Success.  Generate the resulting suggestion for the whole range of
3390      FMT_LOC by concatenating the two strings.
3391      In the above example, this would be "%-+*.*ld".  */
3392   char *result = concat (prefix, format_for_type, NULL);
3393   free (format_for_type);
3394   free (prefix);
3395   return result;
3396 }
3397 
3398 /* Give a warning about a format argument of different type from that expected.
3399    The range of the diagnostic is taken from WHOLE_FMT_LOC; the caret location
3400    is based on the location of the char at TYPE->offset_loc.
3401    If non-NULL, PARAM_RANGE is the source range of the
3402    relevant argument.  WANTED_TYPE is the type the argument should have,
3403    possibly stripped of pointer dereferences.  The description (such as "field
3404    precision"), the placement in the format string, a possibly more
3405    friendly name of WANTED_TYPE, and the number of pointer dereferences
3406    are taken from TYPE.  ARG_TYPE is the type of the actual argument,
3407    or NULL if it is missing.
3408 
3409    OFFSET_TO_TYPE_START is the offset within the execution-charset encoded
3410    format string to where type information begins for the conversion
3411    (the length modifier and conversion specifier).
3412    CONVERSION_CHAR is the user-provided conversion specifier.
3413 
3414    For example, given a type mismatch for argument 5 here:
3415 
3416     00000000011111111112222222222333333333344444444445555555555|
3417     12345678901234567890123456789012345678901234567890123456789` column numbers
3418                    0000000000111111111122|
3419                    0123456789012345678901` offsets within STRING_CST
3420                           V~~~~~~~~ : range of WHOLE_FMT_LOC, from cols 23-31
3421       sprintf (d, "before %-+*.*lld after", int_expr, int_expr, long_expr);
3422                                 ^ ^                             ^~~~~~~~~
3423                                 | ` CONVERSION_CHAR: 'd'        *PARAM_RANGE
3424                                 type starts here
3425 
3426    OFFSET_TO_TYPE_START is 13, the offset to the "lld" within the
3427    STRING_CST.  */
3428 
3429 static void
3430 format_type_warning (const substring_loc &whole_fmt_loc,
3431 		     source_range *param_range,
3432 		     format_wanted_type *type,
3433 		     tree wanted_type, tree arg_type,
3434 		     const format_kind_info *fki,
3435 		     int offset_to_type_start,
3436 		     char conversion_char)
3437 {
3438   enum format_specifier_kind kind = type->kind;
3439   const char *wanted_type_name = type->wanted_type_name;
3440   const char *format_start = type->format_start;
3441   int format_length = type->format_length;
3442   int pointer_count = type->pointer_count;
3443   int arg_num = type->arg_num;
3444 
3445   char *p;
3446   /* If ARG_TYPE is a typedef with a misleading name (for example,
3447      size_t but not the standard size_t expected by printf %zu), avoid
3448      printing the typedef name.  */
3449   if (wanted_type_name
3450       && arg_type
3451       && TYPE_NAME (arg_type)
3452       && TREE_CODE (TYPE_NAME (arg_type)) == TYPE_DECL
3453       && DECL_NAME (TYPE_NAME (arg_type))
3454       && !strcmp (wanted_type_name,
3455 		  lang_hooks.decl_printable_name (TYPE_NAME (arg_type), 2)))
3456     arg_type = TYPE_MAIN_VARIANT (arg_type);
3457   /* The format type and name exclude any '*' for pointers, so those
3458      must be formatted manually.  For all the types we currently have,
3459      this is adequate, but formats taking pointers to functions or
3460      arrays would require the full type to be built up in order to
3461      print it with %T.  */
3462   p = (char *) alloca (pointer_count + 2);
3463   if (pointer_count == 0)
3464     p[0] = 0;
3465   else if (c_dialect_cxx ())
3466     {
3467       memset (p, '*', pointer_count);
3468       p[pointer_count] = 0;
3469     }
3470   else
3471     {
3472       p[0] = ' ';
3473       memset (p + 1, '*', pointer_count);
3474       p[pointer_count + 1] = 0;
3475     }
3476 
3477   /* WHOLE_FMT_LOC has the caret at the end of the range.
3478      Set the caret to be at the offset from TYPE.  Subtract one
3479      from the offset for the same reason as in format_warning_at_char.  */
3480   substring_loc fmt_loc (whole_fmt_loc);
3481   fmt_loc.set_caret_index (type->offset_loc - 1);
3482 
3483   /* Get a string for use as a replacement fix-it hint for the range in
3484      fmt_loc, or NULL.  */
3485   char *corrected_substring
3486     = get_corrected_substring (fmt_loc, type, arg_type, fki,
3487 			       offset_to_type_start, conversion_char);
3488 
3489   if (wanted_type_name)
3490     {
3491       if (arg_type)
3492 	format_warning_at_substring
3493 	  (fmt_loc, param_range,
3494 	   corrected_substring, OPT_Wformat_,
3495 	   "%s %<%s%.*s%> expects argument of type %<%s%s%>, "
3496 	   "but argument %d has type %qT",
3497 	   gettext (kind_descriptions[kind]),
3498 	   (kind == CF_KIND_FORMAT ? "%" : ""),
3499 	   format_length, format_start,
3500 	   wanted_type_name, p, arg_num, arg_type);
3501       else
3502 	format_warning_at_substring
3503 	  (fmt_loc, param_range,
3504 	   corrected_substring, OPT_Wformat_,
3505 	   "%s %<%s%.*s%> expects a matching %<%s%s%> argument",
3506 	   gettext (kind_descriptions[kind]),
3507 	   (kind == CF_KIND_FORMAT ? "%" : ""),
3508 	   format_length, format_start, wanted_type_name, p);
3509     }
3510   else
3511     {
3512       if (arg_type)
3513 	format_warning_at_substring
3514 	  (fmt_loc, param_range,
3515 	   corrected_substring, OPT_Wformat_,
3516 	   "%s %<%s%.*s%> expects argument of type %<%T%s%>, "
3517 	   "but argument %d has type %qT",
3518 	   gettext (kind_descriptions[kind]),
3519 	   (kind == CF_KIND_FORMAT ? "%" : ""),
3520 	   format_length, format_start,
3521 	   wanted_type, p, arg_num, arg_type);
3522       else
3523 	format_warning_at_substring
3524 	  (fmt_loc, param_range,
3525 	   corrected_substring, OPT_Wformat_,
3526 	   "%s %<%s%.*s%> expects a matching %<%T%s%> argument",
3527 	   gettext (kind_descriptions[kind]),
3528 	   (kind == CF_KIND_FORMAT ? "%" : ""),
3529 	   format_length, format_start, wanted_type, p);
3530     }
3531 
3532   free (corrected_substring);
3533 }
3534 
3535 
3536 /* Given a format_char_info array FCI, and a character C, this function
3537    returns the index into the conversion_specs where that specifier's
3538    data is located.  The character must exist.  */
3539 static unsigned int
3540 find_char_info_specifier_index (const format_char_info *fci, int c)
3541 {
3542   unsigned i;
3543 
3544   for (i = 0; fci->format_chars; i++, fci++)
3545     if (strchr (fci->format_chars, c))
3546       return i;
3547 
3548   /* We shouldn't be looking for a non-existent specifier.  */
3549   gcc_unreachable ();
3550 }
3551 
3552 /* Given a format_length_info array FLI, and a character C, this
3553    function returns the index into the conversion_specs where that
3554    modifier's data is located.  The character must exist.  */
3555 static unsigned int
3556 find_length_info_modifier_index (const format_length_info *fli, int c)
3557 {
3558   unsigned i;
3559 
3560   for (i = 0; fli->name; i++, fli++)
3561     if (strchr (fli->name, c))
3562       return i;
3563 
3564   /* We shouldn't be looking for a non-existent modifier.  */
3565   gcc_unreachable ();
3566 }
3567 
3568 /* Determine the type of HOST_WIDE_INT in the code being compiled for
3569    use in GCC's __asm_fprintf__ custom format attribute.  You must
3570    have set dynamic_format_types before calling this function.  */
3571 static void
3572 init_dynamic_asm_fprintf_info (void)
3573 {
3574   static tree hwi;
3575 
3576   if (!hwi)
3577     {
3578       format_length_info *new_asm_fprintf_length_specs;
3579       unsigned int i;
3580 
3581       /* Find the underlying type for HOST_WIDE_INT.  For the %w
3582 	 length modifier to work, one must have issued: "typedef
3583 	 HOST_WIDE_INT __gcc_host_wide_int__;" in one's source code
3584 	 prior to using that modifier.  */
3585       hwi = maybe_get_identifier ("__gcc_host_wide_int__");
3586       if (!hwi)
3587 	{
3588 	  error ("%<__gcc_host_wide_int__%> is not defined as a type");
3589 	  return;
3590 	}
3591       hwi = identifier_global_value (hwi);
3592       if (!hwi || TREE_CODE (hwi) != TYPE_DECL)
3593 	{
3594 	  error ("%<__gcc_host_wide_int__%> is not defined as a type");
3595 	  return;
3596 	}
3597       hwi = DECL_ORIGINAL_TYPE (hwi);
3598       gcc_assert (hwi);
3599       if (hwi != long_integer_type_node && hwi != long_long_integer_type_node)
3600 	{
3601 	  error ("%<__gcc_host_wide_int__%> is not defined as %<long%>"
3602 		 " or %<long long%>");
3603 	  return;
3604 	}
3605 
3606       /* Create a new (writable) copy of asm_fprintf_length_specs.  */
3607       new_asm_fprintf_length_specs = (format_length_info *)
3608 				     xmemdup (asm_fprintf_length_specs,
3609 					      sizeof (asm_fprintf_length_specs),
3610 					      sizeof (asm_fprintf_length_specs));
3611 
3612       /* HOST_WIDE_INT must be one of 'long' or 'long long'.  */
3613       i = find_length_info_modifier_index (new_asm_fprintf_length_specs, 'w');
3614       if (hwi == long_integer_type_node)
3615 	new_asm_fprintf_length_specs[i].index = FMT_LEN_l;
3616       else if (hwi == long_long_integer_type_node)
3617 	new_asm_fprintf_length_specs[i].index = FMT_LEN_ll;
3618       else
3619 	gcc_unreachable ();
3620 
3621       /* Assign the new data for use.  */
3622       dynamic_format_types[asm_fprintf_format_type].length_char_specs =
3623 	new_asm_fprintf_length_specs;
3624     }
3625 }
3626 
3627 /* Determine the type of a "locus" in the code being compiled for use
3628    in GCC's __gcc_gfc__ custom format attribute.  You must have set
3629    dynamic_format_types before calling this function.  */
3630 static void
3631 init_dynamic_gfc_info (void)
3632 {
3633   static tree locus;
3634 
3635   if (!locus)
3636     {
3637       static format_char_info *gfc_fci;
3638 
3639       /* For the GCC __gcc_gfc__ custom format specifier to work, one
3640 	 must have declared 'locus' prior to using this attribute.  If
3641 	 we haven't seen this declarations then you shouldn't use the
3642 	 specifier requiring that type.  */
3643       if ((locus = maybe_get_identifier ("locus")))
3644 	{
3645 	  locus = identifier_global_value (locus);
3646 	  if (locus)
3647 	    {
3648 	      if (TREE_CODE (locus) != TYPE_DECL
3649 		  || TREE_TYPE (locus) == error_mark_node)
3650 		{
3651 		  error ("%<locus%> is not defined as a type");
3652 		  locus = 0;
3653 		}
3654 	      else
3655 		locus = TREE_TYPE (locus);
3656 	    }
3657 	}
3658 
3659       /* Assign the new data for use.  */
3660 
3661       /* Handle the __gcc_gfc__ format specifics.  */
3662       if (!gfc_fci)
3663 	dynamic_format_types[gcc_gfc_format_type].conversion_specs =
3664 	  gfc_fci = (format_char_info *)
3665 		     xmemdup (gcc_gfc_char_table,
3666 			      sizeof (gcc_gfc_char_table),
3667 			      sizeof (gcc_gfc_char_table));
3668       if (locus)
3669 	{
3670 	  const unsigned i = find_char_info_specifier_index (gfc_fci, 'L');
3671 	  gfc_fci[i].types[0].type = &locus;
3672 	  gfc_fci[i].pointer_count = 1;
3673 	}
3674     }
3675 }
3676 
3677 /* Determine the types of "tree" and "location_t" in the code being
3678    compiled for use in GCC's diagnostic custom format attributes.  You
3679    must have set dynamic_format_types before calling this function.  */
3680 static void
3681 init_dynamic_diag_info (void)
3682 {
3683   static tree t, loc, hwi;
3684 
3685   if (!loc || !t || !hwi)
3686     {
3687       static format_char_info *diag_fci, *tdiag_fci, *cdiag_fci, *cxxdiag_fci;
3688       static format_length_info *diag_ls;
3689       unsigned int i;
3690 
3691       /* For the GCC-diagnostics custom format specifiers to work, one
3692 	 must have declared 'tree' and/or 'location_t' prior to using
3693 	 those attributes.  If we haven't seen these declarations then
3694 	 you shouldn't use the specifiers requiring these types.
3695 	 However we don't force a hard ICE because we may see only one
3696 	 or the other type.  */
3697       if ((loc = maybe_get_identifier ("location_t")))
3698 	{
3699 	  loc = identifier_global_value (loc);
3700 	  if (loc)
3701 	    {
3702 	      if (TREE_CODE (loc) != TYPE_DECL)
3703 		{
3704 		  error ("%<location_t%> is not defined as a type");
3705 		  loc = 0;
3706 		}
3707 	      else
3708 		loc = TREE_TYPE (loc);
3709 	    }
3710 	}
3711 
3712       /* We need to grab the underlying 'union tree_node' so peek into
3713 	 an extra type level.  */
3714       if ((t = maybe_get_identifier ("tree")))
3715 	{
3716 	  t = identifier_global_value (t);
3717 	  if (t)
3718 	    {
3719 	      if (TREE_CODE (t) != TYPE_DECL)
3720 		{
3721 		  error ("%<tree%> is not defined as a type");
3722 		  t = 0;
3723 		}
3724 	      else if (TREE_CODE (TREE_TYPE (t)) != POINTER_TYPE)
3725 		{
3726 		  error ("%<tree%> is not defined as a pointer type");
3727 		  t = 0;
3728 		}
3729 	      else
3730 		t = TREE_TYPE (TREE_TYPE (t));
3731 	    }
3732 	}
3733 
3734       /* Find the underlying type for HOST_WIDE_INT.  For the %w
3735 	 length modifier to work, one must have issued: "typedef
3736 	 HOST_WIDE_INT __gcc_host_wide_int__;" in one's source code
3737 	 prior to using that modifier.  */
3738       if ((hwi = maybe_get_identifier ("__gcc_host_wide_int__")))
3739 	{
3740 	  hwi = identifier_global_value (hwi);
3741 	  if (hwi)
3742 	    {
3743 	      if (TREE_CODE (hwi) != TYPE_DECL)
3744 		{
3745 		  error ("%<__gcc_host_wide_int__%> is not defined as a type");
3746 		  hwi = 0;
3747 		}
3748 	      else
3749 		{
3750 		  hwi = DECL_ORIGINAL_TYPE (hwi);
3751 		  gcc_assert (hwi);
3752 		  if (hwi != long_integer_type_node
3753 		      && hwi != long_long_integer_type_node)
3754 		    {
3755 		      error ("%<__gcc_host_wide_int__%> is not defined"
3756 			     " as %<long%> or %<long long%>");
3757 		      hwi = 0;
3758 		    }
3759 		}
3760 	    }
3761 	}
3762 
3763       /* Assign the new data for use.  */
3764 
3765       /* All the GCC diag formats use the same length specs.  */
3766       if (!diag_ls)
3767 	dynamic_format_types[gcc_diag_format_type].length_char_specs =
3768 	  dynamic_format_types[gcc_tdiag_format_type].length_char_specs =
3769 	  dynamic_format_types[gcc_cdiag_format_type].length_char_specs =
3770 	  dynamic_format_types[gcc_cxxdiag_format_type].length_char_specs =
3771 	  diag_ls = (format_length_info *)
3772 		    xmemdup (gcc_diag_length_specs,
3773 			     sizeof (gcc_diag_length_specs),
3774 			     sizeof (gcc_diag_length_specs));
3775       if (hwi)
3776 	{
3777 	  /* HOST_WIDE_INT must be one of 'long' or 'long long'.  */
3778 	  i = find_length_info_modifier_index (diag_ls, 'w');
3779 	  if (hwi == long_integer_type_node)
3780 	    diag_ls[i].index = FMT_LEN_l;
3781 	  else if (hwi == long_long_integer_type_node)
3782 	    diag_ls[i].index = FMT_LEN_ll;
3783 	  else
3784 	    gcc_unreachable ();
3785 	}
3786 
3787       /* Handle the __gcc_diag__ format specifics.  */
3788       if (!diag_fci)
3789 	dynamic_format_types[gcc_diag_format_type].conversion_specs =
3790 	  diag_fci = (format_char_info *)
3791 		     xmemdup (gcc_diag_char_table,
3792 			      sizeof (gcc_diag_char_table),
3793 			      sizeof (gcc_diag_char_table));
3794       if (t)
3795 	{
3796 	  i = find_char_info_specifier_index (diag_fci, 'K');
3797 	  diag_fci[i].types[0].type = &t;
3798 	  diag_fci[i].pointer_count = 1;
3799 	}
3800 
3801       /* Handle the __gcc_tdiag__ format specifics.  */
3802       if (!tdiag_fci)
3803 	dynamic_format_types[gcc_tdiag_format_type].conversion_specs =
3804 	  tdiag_fci = (format_char_info *)
3805 		      xmemdup (gcc_tdiag_char_table,
3806 			       sizeof (gcc_tdiag_char_table),
3807 			       sizeof (gcc_tdiag_char_table));
3808       if (t)
3809 	{
3810 	  /* All specifiers taking a tree share the same struct.  */
3811 	  i = find_char_info_specifier_index (tdiag_fci, 'D');
3812 	  tdiag_fci[i].types[0].type = &t;
3813 	  tdiag_fci[i].pointer_count = 1;
3814 	  i = find_char_info_specifier_index (tdiag_fci, 'K');
3815 	  tdiag_fci[i].types[0].type = &t;
3816 	  tdiag_fci[i].pointer_count = 1;
3817 	}
3818 
3819       /* Handle the __gcc_cdiag__ format specifics.  */
3820       if (!cdiag_fci)
3821 	dynamic_format_types[gcc_cdiag_format_type].conversion_specs =
3822 	  cdiag_fci = (format_char_info *)
3823 		      xmemdup (gcc_cdiag_char_table,
3824 			       sizeof (gcc_cdiag_char_table),
3825 			       sizeof (gcc_cdiag_char_table));
3826       if (t)
3827 	{
3828 	  /* All specifiers taking a tree share the same struct.  */
3829 	  i = find_char_info_specifier_index (cdiag_fci, 'D');
3830 	  cdiag_fci[i].types[0].type = &t;
3831 	  cdiag_fci[i].pointer_count = 1;
3832 	  i = find_char_info_specifier_index (cdiag_fci, 'K');
3833 	  cdiag_fci[i].types[0].type = &t;
3834 	  cdiag_fci[i].pointer_count = 1;
3835 	}
3836 
3837       /* Handle the __gcc_cxxdiag__ format specifics.  */
3838       if (!cxxdiag_fci)
3839 	dynamic_format_types[gcc_cxxdiag_format_type].conversion_specs =
3840 	  cxxdiag_fci = (format_char_info *)
3841 			xmemdup (gcc_cxxdiag_char_table,
3842 				 sizeof (gcc_cxxdiag_char_table),
3843 				 sizeof (gcc_cxxdiag_char_table));
3844       if (t)
3845 	{
3846 	  /* All specifiers taking a tree share the same struct.  */
3847 	  i = find_char_info_specifier_index (cxxdiag_fci, 'D');
3848 	  cxxdiag_fci[i].types[0].type = &t;
3849 	  cxxdiag_fci[i].pointer_count = 1;
3850 	  i = find_char_info_specifier_index (cxxdiag_fci, 'K');
3851 	  cxxdiag_fci[i].types[0].type = &t;
3852 	  cxxdiag_fci[i].pointer_count = 1;
3853 	}
3854     }
3855 }
3856 
3857 #ifdef TARGET_FORMAT_TYPES
3858 extern const format_kind_info TARGET_FORMAT_TYPES[];
3859 #endif
3860 
3861 #ifdef TARGET_OVERRIDES_FORMAT_ATTRIBUTES
3862 extern const target_ovr_attr TARGET_OVERRIDES_FORMAT_ATTRIBUTES[];
3863 #endif
3864 #ifdef TARGET_OVERRIDES_FORMAT_INIT
3865   extern void TARGET_OVERRIDES_FORMAT_INIT (void);
3866 #endif
3867 
3868 /* Attributes such as "printf" are equivalent to those such as
3869    "gnu_printf" unless this is overridden by a target.  */
3870 static const target_ovr_attr gnu_target_overrides_format_attributes[] =
3871 {
3872   { "gnu_printf",   "printf" },
3873   { "gnu_syslog",   "syslog" },
3874   { "gnu_scanf",    "scanf" },
3875   { "gnu_strftime", "strftime" },
3876   { "gnu_strfmon",  "strfmon" },
3877   { NULL,           NULL }
3878 };
3879 
3880 /* Translate to unified attribute name. This is used in decode_format_type and
3881    decode_format_attr. In attr_name the user specified argument is passed. It
3882    returns the unified format name from TARGET_OVERRIDES_FORMAT_ATTRIBUTES
3883    or the attr_name passed to this function, if there is no matching entry.  */
3884 static const char *
3885 convert_format_name_to_system_name (const char *attr_name)
3886 {
3887   int i;
3888 
3889   if (attr_name == NULL || *attr_name == 0
3890       || strncmp (attr_name, "gcc_", 4) == 0)
3891     return attr_name;
3892 #ifdef TARGET_OVERRIDES_FORMAT_INIT
3893   TARGET_OVERRIDES_FORMAT_INIT ();
3894 #endif
3895 
3896 #ifdef TARGET_OVERRIDES_FORMAT_ATTRIBUTES
3897   /* Check if format attribute is overridden by target.  */
3898   if (TARGET_OVERRIDES_FORMAT_ATTRIBUTES != NULL
3899       && TARGET_OVERRIDES_FORMAT_ATTRIBUTES_COUNT > 0)
3900     {
3901       for (i = 0; i < TARGET_OVERRIDES_FORMAT_ATTRIBUTES_COUNT; ++i)
3902         {
3903           if (cmp_attribs (TARGET_OVERRIDES_FORMAT_ATTRIBUTES[i].named_attr_src,
3904 			   attr_name))
3905             return attr_name;
3906           if (cmp_attribs (TARGET_OVERRIDES_FORMAT_ATTRIBUTES[i].named_attr_dst,
3907 			   attr_name))
3908             return TARGET_OVERRIDES_FORMAT_ATTRIBUTES[i].named_attr_src;
3909         }
3910     }
3911 #endif
3912   /* Otherwise default to gnu format.  */
3913   for (i = 0;
3914        gnu_target_overrides_format_attributes[i].named_attr_src != NULL;
3915        ++i)
3916     {
3917       if (cmp_attribs (gnu_target_overrides_format_attributes[i].named_attr_src,
3918 		       attr_name))
3919         return attr_name;
3920       if (cmp_attribs (gnu_target_overrides_format_attributes[i].named_attr_dst,
3921 		       attr_name))
3922         return gnu_target_overrides_format_attributes[i].named_attr_src;
3923     }
3924 
3925   return attr_name;
3926 }
3927 
3928 /* Return true if TATTR_NAME and ATTR_NAME are the same format attribute,
3929    counting "name" and "__name__" as the same, false otherwise.  */
3930 static bool
3931 cmp_attribs (const char *tattr_name, const char *attr_name)
3932 {
3933   int alen = strlen (attr_name);
3934   int slen = (tattr_name ? strlen (tattr_name) : 0);
3935   if (alen > 4 && attr_name[0] == '_' && attr_name[1] == '_'
3936       && attr_name[alen - 1] == '_' && attr_name[alen - 2] == '_')
3937     {
3938       attr_name += 2;
3939       alen -= 4;
3940     }
3941   if (alen != slen || strncmp (tattr_name, attr_name, alen) != 0)
3942     return false;
3943   return true;
3944 }
3945 
3946 /* Handle a "format" attribute; arguments as in
3947    struct attribute_spec.handler.  */
3948 tree
3949 handle_format_attribute (tree *node, tree ARG_UNUSED (name), tree args,
3950 			 int flags, bool *no_add_attrs)
3951 {
3952   tree type = *node;
3953   function_format_info info;
3954 
3955 #ifdef TARGET_FORMAT_TYPES
3956   /* If the target provides additional format types, we need to
3957      add them to FORMAT_TYPES at first use.  */
3958   if (TARGET_FORMAT_TYPES != NULL && !dynamic_format_types)
3959     {
3960       dynamic_format_types = XNEWVEC (format_kind_info,
3961 				      n_format_types + TARGET_N_FORMAT_TYPES);
3962       memcpy (dynamic_format_types, format_types_orig,
3963 	      sizeof (format_types_orig));
3964       memcpy (&dynamic_format_types[n_format_types], TARGET_FORMAT_TYPES,
3965 	      TARGET_N_FORMAT_TYPES * sizeof (dynamic_format_types[0]));
3966 
3967       format_types = dynamic_format_types;
3968       /* Provide a reference for the first potential external type.  */
3969       first_target_format_type = n_format_types;
3970       n_format_types += TARGET_N_FORMAT_TYPES;
3971     }
3972 #endif
3973 
3974   if (!decode_format_attr (args, &info, 0))
3975     {
3976       *no_add_attrs = true;
3977       return NULL_TREE;
3978     }
3979 
3980   if (prototype_p (type))
3981     {
3982       if (!check_format_string (type, info.format_num, flags,
3983 				no_add_attrs, info.format_type))
3984 	return NULL_TREE;
3985 
3986       if (info.first_arg_num != 0)
3987 	{
3988 	  unsigned HOST_WIDE_INT arg_num = 1;
3989 	  function_args_iterator iter;
3990 	  tree arg_type;
3991 
3992 	  /* Verify that first_arg_num points to the last arg,
3993 	     the ...  */
3994 	  FOREACH_FUNCTION_ARGS (type, arg_type, iter)
3995 	    arg_num++;
3996 
3997 	  if (arg_num != info.first_arg_num)
3998 	    {
3999 	      if (!(flags & (int) ATTR_FLAG_BUILT_IN))
4000 		error ("args to be formatted is not %<...%>");
4001 	      *no_add_attrs = true;
4002 	      return NULL_TREE;
4003 	    }
4004 	}
4005     }
4006 
4007   /* Check if this is a strftime variant. Just for this variant
4008      FMT_FLAG_ARG_CONVERT is not set.  */
4009   if ((format_types[info.format_type].flags & (int) FMT_FLAG_ARG_CONVERT) == 0
4010       && info.first_arg_num != 0)
4011     {
4012       error ("strftime formats cannot format arguments");
4013       *no_add_attrs = true;
4014       return NULL_TREE;
4015     }
4016 
4017   /* If this is a custom GCC-internal format type, we have to
4018      initialize certain bits at runtime.  */
4019   if (info.format_type == asm_fprintf_format_type
4020       || info.format_type == gcc_gfc_format_type
4021       || info.format_type == gcc_diag_format_type
4022       || info.format_type == gcc_tdiag_format_type
4023       || info.format_type == gcc_cdiag_format_type
4024       || info.format_type == gcc_cxxdiag_format_type)
4025     {
4026       /* Our first time through, we have to make sure that our
4027 	 format_type data is allocated dynamically and is modifiable.  */
4028       if (!dynamic_format_types)
4029 	format_types = dynamic_format_types = (format_kind_info *)
4030 	  xmemdup (format_types_orig, sizeof (format_types_orig),
4031 		   sizeof (format_types_orig));
4032 
4033       /* If this is format __asm_fprintf__, we have to initialize
4034 	 GCC's notion of HOST_WIDE_INT for checking %wd.  */
4035       if (info.format_type == asm_fprintf_format_type)
4036 	init_dynamic_asm_fprintf_info ();
4037       /* If this is format __gcc_gfc__, we have to initialize GCC's
4038 	 notion of 'locus' at runtime for %L.  */
4039       else if (info.format_type == gcc_gfc_format_type)
4040 	init_dynamic_gfc_info ();
4041       /* If this is one of the diagnostic attributes, then we have to
4042 	 initialize 'location_t' and 'tree' at runtime.  */
4043       else if (info.format_type == gcc_diag_format_type
4044 	       || info.format_type == gcc_tdiag_format_type
4045 	       || info.format_type == gcc_cdiag_format_type
4046 	       || info.format_type == gcc_cxxdiag_format_type)
4047 	init_dynamic_diag_info ();
4048       else
4049 	gcc_unreachable ();
4050     }
4051 
4052   return NULL_TREE;
4053 }
4054 
4055 #if CHECKING_P
4056 
4057 namespace selftest {
4058 
4059 /* Selftests of location handling.  */
4060 
4061 /* Get the format_kind_info with the given name.  */
4062 
4063 static const format_kind_info *
4064 get_info (const char *name)
4065 {
4066   int idx = decode_format_type (name);
4067   const format_kind_info *fki = &format_types[idx];
4068   ASSERT_STREQ (fki->name, name);
4069   return fki;
4070 }
4071 
4072 /* Verify that get_format_for_type (FKI, TYPE, CONVERSION_CHAR)
4073    is EXPECTED_FORMAT.  */
4074 
4075 static void
4076 assert_format_for_type_streq (const location &loc, const format_kind_info *fki,
4077 			      const char *expected_format, tree type,
4078 			      char conversion_char)
4079 {
4080   gcc_assert (fki);
4081   gcc_assert (expected_format);
4082   gcc_assert (type);
4083 
4084   char *actual_format = get_format_for_type (fki, type, conversion_char);
4085   ASSERT_STREQ_AT (loc, expected_format, actual_format);
4086   free (actual_format);
4087 }
4088 
4089 /* Selftests for get_format_for_type.  */
4090 
4091 #define ASSERT_FORMAT_FOR_TYPE_STREQ(EXPECTED_FORMAT, TYPE, CONVERSION_CHAR) \
4092   assert_format_for_type_streq (SELFTEST_LOCATION, (fki), (EXPECTED_FORMAT), \
4093 				(TYPE), (CONVERSION_CHAR))
4094 
4095 /* Selftest for get_format_for_type for "printf"-style functions.  */
4096 
4097 static void
4098 test_get_format_for_type_printf ()
4099 {
4100   const format_kind_info *fki = get_info ("gnu_printf");
4101   ASSERT_NE (fki, NULL);
4102 
4103   ASSERT_FORMAT_FOR_TYPE_STREQ ("f", double_type_node, 'i');
4104   ASSERT_FORMAT_FOR_TYPE_STREQ ("Lf", long_double_type_node, 'i');
4105   ASSERT_FORMAT_FOR_TYPE_STREQ ("f", double_type_node, 'o');
4106   ASSERT_FORMAT_FOR_TYPE_STREQ ("Lf", long_double_type_node, 'o');
4107   ASSERT_FORMAT_FOR_TYPE_STREQ ("f", double_type_node, 'x');
4108   ASSERT_FORMAT_FOR_TYPE_STREQ ("Lf", long_double_type_node, 'x');
4109   ASSERT_FORMAT_FOR_TYPE_STREQ ("f", double_type_node, 'X');
4110   ASSERT_FORMAT_FOR_TYPE_STREQ ("Lf", long_double_type_node, 'X');
4111   ASSERT_FORMAT_FOR_TYPE_STREQ ("d", integer_type_node, 'd');
4112   ASSERT_FORMAT_FOR_TYPE_STREQ ("i", integer_type_node, 'i');
4113   ASSERT_FORMAT_FOR_TYPE_STREQ ("o", integer_type_node, 'o');
4114   ASSERT_FORMAT_FOR_TYPE_STREQ ("x", integer_type_node, 'x');
4115   ASSERT_FORMAT_FOR_TYPE_STREQ ("X", integer_type_node, 'X');
4116   ASSERT_FORMAT_FOR_TYPE_STREQ ("d", unsigned_type_node, 'd');
4117   ASSERT_FORMAT_FOR_TYPE_STREQ ("i", unsigned_type_node, 'i');
4118   ASSERT_FORMAT_FOR_TYPE_STREQ ("o", unsigned_type_node, 'o');
4119   ASSERT_FORMAT_FOR_TYPE_STREQ ("x", unsigned_type_node, 'x');
4120   ASSERT_FORMAT_FOR_TYPE_STREQ ("X", unsigned_type_node, 'X');
4121   ASSERT_FORMAT_FOR_TYPE_STREQ ("ld", long_integer_type_node, 'd');
4122   ASSERT_FORMAT_FOR_TYPE_STREQ ("li", long_integer_type_node, 'i');
4123   ASSERT_FORMAT_FOR_TYPE_STREQ ("lx", long_integer_type_node, 'x');
4124   ASSERT_FORMAT_FOR_TYPE_STREQ ("lo", long_unsigned_type_node, 'o');
4125   ASSERT_FORMAT_FOR_TYPE_STREQ ("lx", long_unsigned_type_node, 'x');
4126   ASSERT_FORMAT_FOR_TYPE_STREQ ("lld", long_long_integer_type_node, 'd');
4127   ASSERT_FORMAT_FOR_TYPE_STREQ ("lli", long_long_integer_type_node, 'i');
4128   ASSERT_FORMAT_FOR_TYPE_STREQ ("llo", long_long_unsigned_type_node, 'o');
4129   ASSERT_FORMAT_FOR_TYPE_STREQ ("llx", long_long_unsigned_type_node, 'x');
4130   ASSERT_FORMAT_FOR_TYPE_STREQ ("s", build_pointer_type (char_type_node), 'i');
4131 }
4132 
4133 /* Selftest for get_format_for_type for "scanf"-style functions.  */
4134 
4135 static void
4136 test_get_format_for_type_scanf ()
4137 {
4138   const format_kind_info *fki = get_info ("gnu_scanf");
4139   ASSERT_NE (fki, NULL);
4140   ASSERT_FORMAT_FOR_TYPE_STREQ ("d", build_pointer_type (integer_type_node), 'd');
4141   ASSERT_FORMAT_FOR_TYPE_STREQ ("u", build_pointer_type (unsigned_type_node), 'u');
4142   ASSERT_FORMAT_FOR_TYPE_STREQ ("ld",
4143 				build_pointer_type (long_integer_type_node), 'd');
4144   ASSERT_FORMAT_FOR_TYPE_STREQ ("lu",
4145 				build_pointer_type (long_unsigned_type_node), 'u');
4146   ASSERT_FORMAT_FOR_TYPE_STREQ
4147     ("lld", build_pointer_type (long_long_integer_type_node), 'd');
4148   ASSERT_FORMAT_FOR_TYPE_STREQ
4149     ("llu", build_pointer_type (long_long_unsigned_type_node), 'u');
4150   ASSERT_FORMAT_FOR_TYPE_STREQ ("e", build_pointer_type (float_type_node), 'e');
4151   ASSERT_FORMAT_FOR_TYPE_STREQ ("le", build_pointer_type (double_type_node), 'e');
4152 }
4153 
4154 #undef ASSERT_FORMAT_FOR_TYPE_STREQ
4155 
4156 /* Run all of the selftests within this file.  */
4157 
4158 void
4159 c_format_c_tests ()
4160 {
4161   test_get_modifier_for_format_len ();
4162   test_get_format_for_type_printf ();
4163   test_get_format_for_type_scanf ();
4164 }
4165 
4166 } // namespace selftest
4167 
4168 #endif /* CHECKING_P */
4169