1 /* Copyright (C) 2016-2018 Free Software Foundation, Inc.
2 Contributed by Martin Sebor <msebor@redhat.com>.
4 This file is part of GCC.
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
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
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/>. */
20 /* This file implements the printf-return-value pass. The pass does
21 two things: 1) it analyzes calls to formatted output functions like
22 sprintf looking for possible buffer overflows and calls to bounded
23 functions like snprintf for early truncation (and under the control
24 of the -Wformat-length option issues warnings), and 2) under the
25 control of the -fprintf-return-value option it folds the return
26 value of safe calls into constants, making it possible to eliminate
27 code that depends on the value of those constants.
29 For all functions (bounded or not) the pass uses the size of the
30 destination object. That means that it will diagnose calls to
31 snprintf not on the basis of the size specified by the function's
32 second argument but rathger on the basis of the size the first
33 argument points to (if possible). For bound-checking built-ins
34 like __builtin___snprintf_chk the pass uses the size typically
35 determined by __builtin_object_size and passed to the built-in
36 by the Glibc inline wrapper.
38 The pass handles all forms standard sprintf format directives,
39 including character, integer, floating point, pointer, and strings,
40 with the standard C flags, widths, and precisions. For integers
41 and strings it computes the length of output itself. For floating
42 point it uses MPFR to fornmat known constants with up and down
43 rounding and uses the resulting range of output lengths. For
44 strings it uses the length of string literals and the sizes of
45 character arrays that a character pointer may point to as a bound
46 on the longest string. */
50 #include "coretypes.h"
54 #include "tree-pass.h"
56 #include "gimple-fold.h"
57 #include "gimple-pretty-print.h"
58 #include "diagnostic-core.h"
59 #include "fold-const.h"
60 #include "gimple-iterator.h"
62 #include "tree-object-size.h"
65 #include "tree-ssa-propagate.h"
69 #include "langhooks.h"
72 #include "stor-layout.h"
80 #include "substring-locations.h"
81 #include "diagnostic.h"
83 #include "alloc-pool.h"
84 #include "vr-values.h"
85 #include "gimple-ssa-evrp-analyze.h"
87 /* The likely worst case value of MB_LEN_MAX for the target, large enough
88 for UTF-8. Ideally, this would be obtained by a target hook if it were
89 to be used for optimization but it's good enough as is for warnings. */
90 #define target_mb_len_max() 6
92 /* The maximum number of bytes a single non-string directive can result
93 in. This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
94 LDBL_MAX_10_EXP of 4932. */
95 #define IEEE_MAX_10_EXP 4932
96 #define target_dir_max() (target_int_max () + IEEE_MAX_10_EXP + 2)
100 const pass_data pass_data_sprintf_length
= {
101 GIMPLE_PASS
, // pass type
102 "printf-return-value", // pass name
103 OPTGROUP_NONE
, // optinfo_flags
105 PROP_cfg
, // properties_required
106 0, // properties_provided
107 0, // properties_destroyed
108 0, // properties_start
109 0, // properties_finish
112 /* Set to the warning level for the current function which is equal
113 either to warn_format_trunc for bounded functions or to
114 warn_format_overflow otherwise. */
116 static int warn_level
;
118 struct format_result
;
120 class sprintf_dom_walker
: public dom_walker
123 sprintf_dom_walker () : dom_walker (CDI_DOMINATORS
) {}
124 ~sprintf_dom_walker () {}
126 edge
before_dom_children (basic_block
) FINAL OVERRIDE
;
127 void after_dom_children (basic_block
) FINAL OVERRIDE
;
128 bool handle_gimple_call (gimple_stmt_iterator
*);
131 bool compute_format_length (call_info
&, format_result
*);
132 class evrp_range_analyzer evrp_range_analyzer
;
135 class pass_sprintf_length
: public gimple_opt_pass
137 bool fold_return_value
;
140 pass_sprintf_length (gcc::context
*ctxt
)
141 : gimple_opt_pass (pass_data_sprintf_length
, ctxt
),
142 fold_return_value (false)
145 opt_pass
* clone () { return new pass_sprintf_length (m_ctxt
); }
147 virtual bool gate (function
*);
149 virtual unsigned int execute (function
*);
151 void set_pass_param (unsigned int n
, bool param
)
154 fold_return_value
= param
;
160 pass_sprintf_length::gate (function
*)
162 /* Run the pass iff -Warn-format-overflow or -Warn-format-truncation
163 is specified and either not optimizing and the pass is being invoked
164 early, or when optimizing and the pass is being invoked during
165 optimization (i.e., "late"). */
166 return ((warn_format_overflow
> 0
167 || warn_format_trunc
> 0
168 || flag_printf_return_value
)
169 && (optimize
> 0) == fold_return_value
);
172 /* The minimum, maximum, likely, and unlikely maximum number of bytes
173 of output either a formatting function or an individual directive
178 /* The absolute minimum number of bytes. The result of a successful
179 conversion is guaranteed to be no less than this. (An erroneous
180 conversion can be indicated by MIN > HOST_WIDE_INT_MAX.) */
181 unsigned HOST_WIDE_INT min
;
182 /* The likely maximum result that is used in diagnostics. In most
183 cases MAX is the same as the worst case UNLIKELY result. */
184 unsigned HOST_WIDE_INT max
;
185 /* The likely result used to trigger diagnostics. For conversions
186 that result in a range of bytes [MIN, MAX], LIKELY is somewhere
188 unsigned HOST_WIDE_INT likely
;
189 /* In rare cases (e.g., for nultibyte characters) UNLIKELY gives
190 the worst cases maximum result of a directive. In most cases
191 UNLIKELY == MAX. UNLIKELY is used to control the return value
192 optimization but not in diagnostics. */
193 unsigned HOST_WIDE_INT unlikely
;
196 /* The result of a call to a formatted function. */
200 /* Range of characters written by the formatted function.
201 Setting the minimum to HOST_WIDE_INT_MAX disables all
202 length tracking for the remainder of the format string. */
205 /* True when the range above is obtained from known values of
206 directive arguments, or bounds on the amount of output such
207 as width and precision, and not the result of heuristics that
208 depend on warning levels. It's used to issue stricter diagnostics
209 in cases where strings of unknown lengths are bounded by the arrays
210 they are determined to refer to. KNOWNRANGE must not be used for
211 the return value optimization. */
214 /* True if no individual directive resulted in more than 4095 bytes
215 of output (the total NUMBER_CHARS_{MIN,MAX} might be greater).
216 Implementations are not required to handle directives that produce
217 more than 4K bytes (leading to undefined behavior) and so when one
218 is found it disables the return value optimization. */
221 /* True when a floating point directive has been seen in the format
225 /* True when an intermediate result has caused a warning. Used to
226 avoid issuing duplicate warnings while finishing the processing
227 of a call. WARNED also disables the return value optimization. */
230 /* Preincrement the number of output characters by 1. */
231 format_result
& operator++ ()
236 /* Postincrement the number of output characters by 1. */
237 format_result
operator++ (int)
239 format_result
prev (*this);
244 /* Increment the number of output characters by N. */
245 format_result
& operator+= (unsigned HOST_WIDE_INT
);
249 format_result::operator+= (unsigned HOST_WIDE_INT n
)
251 gcc_assert (n
< HOST_WIDE_INT_MAX
);
253 if (range
.min
< HOST_WIDE_INT_MAX
)
256 if (range
.max
< HOST_WIDE_INT_MAX
)
259 if (range
.likely
< HOST_WIDE_INT_MAX
)
262 if (range
.unlikely
< HOST_WIDE_INT_MAX
)
268 /* Return the value of INT_MIN for the target. */
270 static inline HOST_WIDE_INT
273 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node
));
276 /* Return the value of INT_MAX for the target. */
278 static inline unsigned HOST_WIDE_INT
281 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node
));
284 /* Return the value of SIZE_MAX for the target. */
286 static inline unsigned HOST_WIDE_INT
289 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node
));
292 /* A straightforward mapping from the execution character set to the host
293 character set indexed by execution character. */
295 static char target_to_host_charmap
[256];
297 /* Initialize a mapping from the execution character set to the host
301 init_target_to_host_charmap ()
303 /* If the percent sign is non-zero the mapping has already been
305 if (target_to_host_charmap
['%'])
308 /* Initialize the target_percent character (done elsewhere). */
309 if (!init_target_chars ())
312 /* The subset of the source character set used by printf conversion
313 specifications (strictly speaking, not all letters are used but
314 they are included here for the sake of simplicity). The dollar
315 sign must be included even though it's not in the basic source
317 const char srcset
[] = " 0123456789!\"#%&'()*+,-./:;<=>?[\\]^_{|}~$"
318 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
320 /* Set the mapping for all characters to some ordinary value (i,e.,
321 not none used in printf conversion specifications) and overwrite
322 those that are used by conversion specifications with their
323 corresponding values. */
324 memset (target_to_host_charmap
+ 1, '?', sizeof target_to_host_charmap
- 1);
326 /* Are the two sets of characters the same? */
327 bool all_same_p
= true;
329 for (const char *pc
= srcset
; *pc
; ++pc
)
331 /* Slice off the high end bits in case target characters are
332 signed. All values are expected to be non-nul, otherwise
333 there's a problem. */
334 if (unsigned char tc
= lang_hooks
.to_target_charset (*pc
))
336 target_to_host_charmap
[tc
] = *pc
;
345 /* Set the first element to a non-zero value if the mapping
346 is 1-to-1, otherwise leave it clear (NUL is assumed to be
347 the same in both character sets). */
348 target_to_host_charmap
[0] = all_same_p
;
353 /* Return the host source character corresponding to the character
354 CH in the execution character set if one exists, or some innocuous
355 (non-special, non-nul) source character otherwise. */
357 static inline unsigned char
358 target_to_host (unsigned char ch
)
360 return target_to_host_charmap
[ch
];
363 /* Convert an initial substring of the string TARGSTR consisting of
364 characters in the execution character set into a string in the
365 source character set on the host and store up to HOSTSZ characters
366 in the buffer pointed to by HOSTR. Return HOSTR. */
369 target_to_host (char *hostr
, size_t hostsz
, const char *targstr
)
371 /* Make sure the buffer is reasonably big. */
372 gcc_assert (hostsz
> 4);
374 /* The interesting subset of source and execution characters are
375 the same so no conversion is necessary. However, truncate
376 overlong strings just like the translated strings are. */
377 if (target_to_host_charmap
['\0'] == 1)
379 strncpy (hostr
, targstr
, hostsz
- 4);
380 if (strlen (targstr
) >= hostsz
)
381 strcpy (hostr
+ hostsz
- 4, "...");
385 /* Convert the initial substring of TARGSTR to the corresponding
386 characters in the host set, appending "..." if TARGSTR is too
387 long to fit. Using the static buffer assumes the function is
388 not called in between sequence points (which it isn't). */
389 for (char *ph
= hostr
; ; ++targstr
)
391 *ph
++ = target_to_host (*targstr
);
395 if (size_t (ph
- hostr
) == hostsz
- 4)
406 /* Convert the sequence of decimal digits in the execution character
407 starting at S to a long, just like strtol does. Return the result
408 and set *END to one past the last converted character. On range
409 error set ERANGE to the digit that caused it. */
412 target_strtol10 (const char **ps
, const char **erange
)
414 unsigned HOST_WIDE_INT val
= 0;
417 unsigned char c
= target_to_host (**ps
);
422 /* Check for overflow. */
423 if (val
> (LONG_MAX
- c
) / 10LU)
428 /* Skip the remaining digits. */
430 c
= target_to_host (*++*ps
);
444 /* Return the constant initial value of DECL if available or DECL
445 otherwise. Same as the synonymous function in c/c-typeck.c. */
448 decl_constant_value (tree decl
)
450 if (/* Don't change a variable array bound or initial value to a constant
451 in a place where a variable is invalid. Note that DECL_INITIAL
452 isn't valid for a PARM_DECL. */
453 current_function_decl
!= 0
454 && TREE_CODE (decl
) != PARM_DECL
455 && !TREE_THIS_VOLATILE (decl
)
456 && TREE_READONLY (decl
)
457 && DECL_INITIAL (decl
) != 0
458 && TREE_CODE (DECL_INITIAL (decl
)) != ERROR_MARK
459 /* This is invalid if initial value is not constant.
460 If it has either a function call, a memory reference,
461 or a variable, then re-evaluating it could give different results. */
462 && TREE_CONSTANT (DECL_INITIAL (decl
))
463 /* Check for cases where this is sub-optimal, even though valid. */
464 && TREE_CODE (DECL_INITIAL (decl
)) != CONSTRUCTOR
)
465 return DECL_INITIAL (decl
);
469 /* Given FORMAT, set *PLOC to the source location of the format string
470 and return the format string if it is known or null otherwise. */
473 get_format_string (tree format
, location_t
*ploc
)
477 /* Pull out a constant value if the front end didn't. */
478 format
= decl_constant_value (format
);
482 if (integer_zerop (format
))
484 /* FIXME: Diagnose null format string if it hasn't been diagnosed
485 by -Wformat (the latter diagnoses only nul pointer constants,
486 this pass can do better). */
490 HOST_WIDE_INT offset
= 0;
492 if (TREE_CODE (format
) == POINTER_PLUS_EXPR
)
494 tree arg0
= TREE_OPERAND (format
, 0);
495 tree arg1
= TREE_OPERAND (format
, 1);
499 if (TREE_CODE (arg1
) != INTEGER_CST
)
504 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
505 if (!cst_and_fits_in_hwi (arg1
))
508 offset
= int_cst_value (arg1
);
511 if (TREE_CODE (format
) != ADDR_EXPR
)
514 *ploc
= EXPR_LOC_OR_LOC (format
, input_location
);
516 format
= TREE_OPERAND (format
, 0);
518 if (TREE_CODE (format
) == ARRAY_REF
519 && tree_fits_shwi_p (TREE_OPERAND (format
, 1))
520 && (offset
+= tree_to_shwi (TREE_OPERAND (format
, 1))) >= 0)
521 format
= TREE_OPERAND (format
, 0);
527 tree array_size
= NULL_TREE
;
530 && TREE_CODE (TREE_TYPE (format
)) == ARRAY_TYPE
531 && (array_init
= decl_constant_value (format
)) != format
532 && TREE_CODE (array_init
) == STRING_CST
)
534 /* Extract the string constant initializer. Note that this may
535 include a trailing NUL character that is not in the array (e.g.
536 const char a[3] = "foo";). */
537 array_size
= DECL_SIZE_UNIT (format
);
541 if (TREE_CODE (format
) != STRING_CST
)
544 tree type
= TREE_TYPE (format
);
546 scalar_int_mode char_mode
;
547 if (!is_int_mode (TYPE_MODE (TREE_TYPE (type
)), &char_mode
)
548 || GET_MODE_SIZE (char_mode
) != 1)
550 /* Wide format string. */
554 const char *fmtstr
= TREE_STRING_POINTER (format
);
555 unsigned fmtlen
= TREE_STRING_LENGTH (format
);
559 /* Variable length arrays can't be initialized. */
560 gcc_assert (TREE_CODE (array_size
) == INTEGER_CST
);
562 if (tree_fits_shwi_p (array_size
))
564 HOST_WIDE_INT array_size_value
= tree_to_shwi (array_size
);
565 if (array_size_value
> 0
566 && array_size_value
== (int) array_size_value
567 && fmtlen
> array_size_value
)
568 fmtlen
= array_size_value
;
573 if (offset
>= fmtlen
)
580 if (fmtlen
< 1 || fmtstr
[--fmtlen
] != 0)
582 /* FIXME: Diagnose an unterminated format string if it hasn't been
583 diagnosed by -Wformat. Similarly to a null format pointer,
584 -Wformay diagnoses only nul pointer constants, this pass can
592 /* For convenience and brevity, shorter named entrypoints of
593 format_warning_at_substring and format_warning_at_substring_n.
594 These have to be functions with the attribute so that exgettext
598 ATTRIBUTE_GCC_DIAG (5, 6)
599 fmtwarn (const substring_loc
&fmt_loc
, location_t param_loc
,
600 const char *corrected_substring
, int opt
, const char *gmsgid
, ...)
603 va_start (ap
, gmsgid
);
604 bool warned
= format_warning_va (fmt_loc
, param_loc
, corrected_substring
,
612 ATTRIBUTE_GCC_DIAG (6, 8) ATTRIBUTE_GCC_DIAG (7, 8)
613 fmtwarn_n (const substring_loc
&fmt_loc
, location_t param_loc
,
614 const char *corrected_substring
, int opt
, unsigned HOST_WIDE_INT n
,
615 const char *singular_gmsgid
, const char *plural_gmsgid
, ...)
618 va_start (ap
, plural_gmsgid
);
619 bool warned
= format_warning_n_va (fmt_loc
, param_loc
, corrected_substring
,
620 opt
, n
, singular_gmsgid
, plural_gmsgid
,
627 /* Format length modifiers. */
632 FMT_LEN_hh
, // char argument
635 FMT_LEN_ll
, // long long
636 FMT_LEN_L
, // long double (and GNU long long)
638 FMT_LEN_t
, // ptrdiff_t
639 FMT_LEN_j
// intmax_t
643 /* Description of the result of conversion either of a single directive
644 or the whole format string. */
648 /* Construct a FMTRESULT object with all counters initialized
649 to MIN. KNOWNRANGE is set when MIN is valid. */
650 fmtresult (unsigned HOST_WIDE_INT min
= HOST_WIDE_INT_MAX
)
651 : argmin (), argmax (),
652 knownrange (min
< HOST_WIDE_INT_MAX
),
658 range
.unlikely
= min
;
661 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
662 KNOWNRANGE is set when both MIN and MAX are valid. */
663 fmtresult (unsigned HOST_WIDE_INT min
, unsigned HOST_WIDE_INT max
,
664 unsigned HOST_WIDE_INT likely
= HOST_WIDE_INT_MAX
)
665 : argmin (), argmax (),
666 knownrange (min
< HOST_WIDE_INT_MAX
&& max
< HOST_WIDE_INT_MAX
),
671 range
.likely
= max
< likely
? min
: likely
;
672 range
.unlikely
= max
;
675 /* Adjust result upward to reflect the RANGE of values the specified
676 width or precision is known to be in. */
677 fmtresult
& adjust_for_width_or_precision (const HOST_WIDE_INT
[2],
679 unsigned = 0, unsigned = 0);
681 /* Return the maximum number of decimal digits a value of TYPE
682 formats as on output. */
683 static unsigned type_max_digits (tree
, int);
685 /* The range a directive's argument is in. */
688 /* The minimum and maximum number of bytes that a directive
689 results in on output for an argument in the range above. */
692 /* True when the range above is obtained from a known value of
693 a directive's argument or its bounds and not the result of
694 heuristics that depend on warning levels. */
697 /* True when the argument is a null pointer. */
701 /* Adjust result upward to reflect the range ADJUST of values the
702 specified width or precision is known to be in. When non-null,
703 TYPE denotes the type of the directive whose result is being
704 adjusted, BASE gives the base of the directive (octal, decimal,
705 or hex), and ADJ denotes the additional adjustment to the LIKELY
706 counter that may need to be added when ADJUST is a range. */
709 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust
[2],
710 tree type
/* = NULL_TREE */,
711 unsigned base
/* = 0 */,
712 unsigned adj
/* = 0 */)
714 bool minadjusted
= false;
716 /* Adjust the minimum and likely counters. */
719 if (range
.min
< (unsigned HOST_WIDE_INT
)adjust
[0])
721 range
.min
= adjust
[0];
725 /* Adjust the likely counter. */
726 if (range
.likely
< range
.min
)
727 range
.likely
= range
.min
;
729 else if (adjust
[0] == target_int_min ()
730 && (unsigned HOST_WIDE_INT
)adjust
[1] == target_int_max ())
733 /* Adjust the maximum counter. */
736 if (range
.max
< (unsigned HOST_WIDE_INT
)adjust
[1])
738 range
.max
= adjust
[1];
740 /* Set KNOWNRANGE if both the minimum and maximum have been
741 adjusted. Otherwise leave it at what it was before. */
742 knownrange
= minadjusted
;
746 if (warn_level
> 1 && type
)
748 /* For large non-constant width or precision whose range spans
749 the maximum number of digits produced by the directive for
750 any argument, set the likely number of bytes to be at most
751 the number digits plus other adjustment determined by the
752 caller (one for sign or two for the hexadecimal "0x"
754 unsigned dirdigs
= type_max_digits (type
, base
);
755 if (adjust
[0] < dirdigs
&& dirdigs
< adjust
[1]
756 && range
.likely
< dirdigs
)
757 range
.likely
= dirdigs
+ adj
;
759 else if (range
.likely
< (range
.min
? range
.min
: 1))
761 /* Conservatively, set LIKELY to at least MIN but no less than
762 1 unless MAX is zero. */
763 range
.likely
= (range
.min
765 : range
.max
&& (range
.max
< HOST_WIDE_INT_MAX
766 || warn_level
> 1) ? 1 : 0);
769 /* Finally adjust the unlikely counter to be at least as large as
771 if (range
.unlikely
< range
.max
)
772 range
.unlikely
= range
.max
;
777 /* Return the maximum number of digits a value of TYPE formats in
778 BASE on output, not counting base prefix . */
781 fmtresult::type_max_digits (tree type
, int base
)
783 unsigned prec
= TYPE_PRECISION (type
);
785 return (prec
+ 2) / 3;
790 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
791 of 8, 16, 32, and 64 bits. */
792 return prec
* 301 / 1000 + 1;
796 get_int_range (tree
, HOST_WIDE_INT
*, HOST_WIDE_INT
*, bool, HOST_WIDE_INT
,
797 class vr_values
*vr_values
);
799 /* Description of a format directive. A directive is either a plain
800 string or a conversion specification that starts with '%'. */
804 /* The 1-based directive number (for debugging). */
807 /* The first character of the directive and its length. */
811 /* A bitmap of flags, one for each character. */
812 unsigned flags
[256 / sizeof (int)];
814 /* The range of values of the specified width, or -1 if not specified. */
815 HOST_WIDE_INT width
[2];
816 /* The range of values of the specified precision, or -1 if not
818 HOST_WIDE_INT prec
[2];
820 /* Length modifier. */
821 format_lengths modifier
;
823 /* Format specifier character. */
826 /* The argument of the directive or null when the directive doesn't
827 take one or when none is available (such as for vararg functions). */
830 /* Format conversion function that given a directive and an argument
831 returns the formatting result. */
832 fmtresult (*fmtfunc
) (const directive
&, tree
, vr_values
*);
834 /* Return True when a the format flag CHR has been used. */
835 bool get_flag (char chr
) const
837 unsigned char c
= chr
& 0xff;
838 return (flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
839 & (1U << (c
% (CHAR_BIT
* sizeof *flags
))));
842 /* Make a record of the format flag CHR having been used. */
843 void set_flag (char chr
)
845 unsigned char c
= chr
& 0xff;
846 flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
847 |= (1U << (c
% (CHAR_BIT
* sizeof *flags
)));
850 /* Reset the format flag CHR. */
851 void clear_flag (char chr
)
853 unsigned char c
= chr
& 0xff;
854 flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
855 &= ~(1U << (c
% (CHAR_BIT
* sizeof *flags
)));
858 /* Set both bounds of the width range to VAL. */
859 void set_width (HOST_WIDE_INT val
)
861 width
[0] = width
[1] = val
;
864 /* Set the width range according to ARG, with both bounds being
865 no less than 0. For a constant ARG set both bounds to its value
866 or 0, whichever is greater. For a non-constant ARG in some range
867 set width to its range adjusting each bound to -1 if it's less.
868 For an indeterminate ARG set width to [0, INT_MAX]. */
869 void set_width (tree arg
, vr_values
*vr_values
)
871 get_int_range (arg
, width
, width
+ 1, true, 0, vr_values
);
874 /* Set both bounds of the precision range to VAL. */
875 void set_precision (HOST_WIDE_INT val
)
877 prec
[0] = prec
[1] = val
;
880 /* Set the precision range according to ARG, with both bounds being
881 no less than -1. For a constant ARG set both bounds to its value
882 or -1 whichever is greater. For a non-constant ARG in some range
883 set precision to its range adjusting each bound to -1 if it's less.
884 For an indeterminate ARG set precision to [-1, INT_MAX]. */
885 void set_precision (tree arg
, vr_values
*vr_values
)
887 get_int_range (arg
, prec
, prec
+ 1, false, -1, vr_values
);
890 /* Return true if both width and precision are known to be
891 either constant or in some range, false otherwise. */
892 bool known_width_and_precision () const
894 return ((width
[1] < 0
895 || (unsigned HOST_WIDE_INT
)width
[1] <= target_int_max ())
897 || (unsigned HOST_WIDE_INT
)prec
[1] < target_int_max ()));
901 /* Return the logarithm of X in BASE. */
904 ilog (unsigned HOST_WIDE_INT x
, int base
)
915 /* Return the number of bytes resulting from converting into a string
916 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
917 PLUS indicates whether 1 for a plus sign should be added for positive
918 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
919 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
923 tree_digits (tree x
, int base
, HOST_WIDE_INT prec
, bool plus
, bool prefix
)
925 unsigned HOST_WIDE_INT absval
;
929 if (TYPE_UNSIGNED (TREE_TYPE (x
)))
931 if (tree_fits_uhwi_p (x
))
933 absval
= tree_to_uhwi (x
);
941 if (tree_fits_shwi_p (x
))
943 HOST_WIDE_INT i
= tree_to_shwi (x
);
944 if (HOST_WIDE_INT_MIN
== i
)
946 /* Avoid undefined behavior due to negating a minimum. */
947 absval
= HOST_WIDE_INT_MAX
;
965 int ndigs
= ilog (absval
, base
);
967 res
+= prec
< ndigs
? ndigs
: prec
;
969 /* Adjust a non-zero value for the base prefix, either hexadecimal,
970 or, unless precision has resulted in a leading zero, also octal. */
971 if (prefix
&& absval
&& (base
== 16 || prec
<= ndigs
))
982 /* Given the formatting result described by RES and NAVAIL, the number
983 of available in the destination, return the range of bytes remaining
984 in the destination. */
986 static inline result_range
987 bytes_remaining (unsigned HOST_WIDE_INT navail
, const format_result
&res
)
991 if (HOST_WIDE_INT_MAX
<= navail
)
993 range
.min
= range
.max
= range
.likely
= range
.unlikely
= navail
;
997 /* The lower bound of the available range is the available size
998 minus the maximum output size, and the upper bound is the size
999 minus the minimum. */
1000 range
.max
= res
.range
.min
< navail
? navail
- res
.range
.min
: 0;
1002 range
.likely
= res
.range
.likely
< navail
? navail
- res
.range
.likely
: 0;
1004 if (res
.range
.max
< HOST_WIDE_INT_MAX
)
1005 range
.min
= res
.range
.max
< navail
? navail
- res
.range
.max
: 0;
1007 range
.min
= range
.likely
;
1009 range
.unlikely
= (res
.range
.unlikely
< navail
1010 ? navail
- res
.range
.unlikely
: 0);
1015 /* Description of a call to a formatted function. */
1017 struct sprintf_dom_walker::call_info
1019 /* Function call statement. */
1022 /* Function called. */
1025 /* Called built-in function code. */
1026 built_in_function fncode
;
1028 /* Format argument and format string extracted from it. */
1032 /* The location of the format argument. */
1035 /* The destination object size for __builtin___xxx_chk functions
1036 typically determined by __builtin_object_size, or -1 if unknown. */
1037 unsigned HOST_WIDE_INT objsize
;
1039 /* Number of the first variable argument. */
1040 unsigned HOST_WIDE_INT argidx
;
1042 /* True for functions like snprintf that specify the size of
1043 the destination, false for others like sprintf that don't. */
1046 /* True for bounded functions like snprintf that specify a zero-size
1047 buffer as a request to compute the size of output without actually
1048 writing any. NOWRITE is cleared in response to the %n directive
1049 which has side-effects similar to writing output. */
1052 /* Return true if the called function's return value is used. */
1053 bool retval_used () const
1055 return gimple_get_lhs (callstmt
);
1058 /* Return the warning option corresponding to the called function. */
1059 int warnopt () const
1061 return bounded
? OPT_Wformat_truncation_
: OPT_Wformat_overflow_
;
1065 /* Return the result of formatting a no-op directive (such as '%n'). */
1068 format_none (const directive
&, tree
, vr_values
*)
1074 /* Return the result of formatting the '%%' directive. */
1077 format_percent (const directive
&, tree
, vr_values
*)
1084 /* Compute intmax_type_node and uintmax_type_node similarly to how
1085 tree.c builds size_type_node. */
1088 build_intmax_type_nodes (tree
*pintmax
, tree
*puintmax
)
1090 if (strcmp (UINTMAX_TYPE
, "unsigned int") == 0)
1092 *pintmax
= integer_type_node
;
1093 *puintmax
= unsigned_type_node
;
1095 else if (strcmp (UINTMAX_TYPE
, "long unsigned int") == 0)
1097 *pintmax
= long_integer_type_node
;
1098 *puintmax
= long_unsigned_type_node
;
1100 else if (strcmp (UINTMAX_TYPE
, "long long unsigned int") == 0)
1102 *pintmax
= long_long_integer_type_node
;
1103 *puintmax
= long_long_unsigned_type_node
;
1107 for (int i
= 0; i
< NUM_INT_N_ENTS
; i
++)
1108 if (int_n_enabled_p
[i
])
1111 sprintf (name
, "__int%d unsigned", int_n_data
[i
].bitsize
);
1113 if (strcmp (name
, UINTMAX_TYPE
) == 0)
1115 *pintmax
= int_n_trees
[i
].signed_type
;
1116 *puintmax
= int_n_trees
[i
].unsigned_type
;
1124 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1125 in and that is representable in type int.
1126 Return true when the range is a subrange of that of int.
1127 When ARG is null it is as if it had the full range of int.
1128 When ABSOLUTE is true the range reflects the absolute value of
1129 the argument. When ABSOLUTE is false, negative bounds of
1130 the determined range are replaced with NEGBOUND. */
1133 get_int_range (tree arg
, HOST_WIDE_INT
*pmin
, HOST_WIDE_INT
*pmax
,
1134 bool absolute
, HOST_WIDE_INT negbound
,
1135 class vr_values
*vr_values
)
1137 /* The type of the result. */
1138 const_tree type
= integer_type_node
;
1140 bool knownrange
= false;
1144 *pmin
= tree_to_shwi (TYPE_MIN_VALUE (type
));
1145 *pmax
= tree_to_shwi (TYPE_MAX_VALUE (type
));
1147 else if (TREE_CODE (arg
) == INTEGER_CST
1148 && TYPE_PRECISION (TREE_TYPE (arg
)) <= TYPE_PRECISION (type
))
1150 /* For a constant argument return its value adjusted as specified
1151 by NEGATIVE and NEGBOUND and return true to indicate that the
1153 *pmin
= tree_fits_shwi_p (arg
) ? tree_to_shwi (arg
) : tree_to_uhwi (arg
);
1159 /* True if the argument's range cannot be determined. */
1160 bool unknown
= true;
1162 tree argtype
= TREE_TYPE (arg
);
1164 /* Ignore invalid arguments with greater precision that that
1165 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1166 They will have been detected and diagnosed by -Wformat and
1167 so it's not important to complicate this code to try to deal
1169 if (TREE_CODE (arg
) == SSA_NAME
1170 && INTEGRAL_TYPE_P (argtype
)
1171 && TYPE_PRECISION (argtype
) <= TYPE_PRECISION (type
))
1173 /* Try to determine the range of values of the integer argument. */
1174 value_range
*vr
= vr_values
->get_value_range (arg
);
1175 if (vr
->type
== VR_RANGE
1176 && TREE_CODE (vr
->min
) == INTEGER_CST
1177 && TREE_CODE (vr
->max
) == INTEGER_CST
)
1179 HOST_WIDE_INT type_min
1180 = (TYPE_UNSIGNED (argtype
)
1181 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype
))
1182 : tree_to_shwi (TYPE_MIN_VALUE (argtype
)));
1184 HOST_WIDE_INT type_max
= tree_to_uhwi (TYPE_MAX_VALUE (argtype
));
1186 *pmin
= TREE_INT_CST_LOW (vr
->min
);
1187 *pmax
= TREE_INT_CST_LOW (vr
->max
);
1191 /* Return true if the adjusted range is a subrange of
1192 the full range of the argument's type. *PMAX may
1193 be less than *PMIN when the argument is unsigned
1194 and its upper bound is in excess of TYPE_MAX. In
1195 that (invalid) case disregard the range and use that
1196 of the expected type instead. */
1197 knownrange
= type_min
< *pmin
|| *pmax
< type_max
;
1204 /* Handle an argument with an unknown range as if none had been
1207 return get_int_range (NULL_TREE
, pmin
, pmax
, absolute
,
1208 negbound
, vr_values
);
1211 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1217 *pmin
= *pmax
= -*pmin
;
1220 /* Make sure signed overlow is avoided. */
1221 gcc_assert (*pmin
!= HOST_WIDE_INT_MIN
);
1223 HOST_WIDE_INT tmp
= -*pmin
;
1230 else if (*pmin
< negbound
)
1236 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1237 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1238 the type of the directive's formal argument it's possible for both
1239 to result in the same number of bytes or a range of bytes that's
1240 less than the number of bytes that would result from formatting
1241 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1242 determined by checking for the actual argument being in the range
1243 of the type of the directive. If it isn't it must be assumed to
1244 take on the full range of the directive's type.
1245 Return true when the range has been adjusted to the full range
1246 of DIRTYPE, and false otherwise. */
1249 adjust_range_for_overflow (tree dirtype
, tree
*argmin
, tree
*argmax
)
1251 tree argtype
= TREE_TYPE (*argmin
);
1252 unsigned argprec
= TYPE_PRECISION (argtype
);
1253 unsigned dirprec
= TYPE_PRECISION (dirtype
);
1255 /* If the actual argument and the directive's argument have the same
1256 precision and sign there can be no overflow and so there is nothing
1258 if (argprec
== dirprec
&& TYPE_SIGN (argtype
) == TYPE_SIGN (dirtype
))
1261 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1262 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1264 if (TREE_CODE (*argmin
) == INTEGER_CST
1265 && TREE_CODE (*argmax
) == INTEGER_CST
1266 && (dirprec
>= argprec
1267 || integer_zerop (int_const_binop (RSHIFT_EXPR
,
1268 int_const_binop (MINUS_EXPR
,
1271 size_int (dirprec
)))))
1273 *argmin
= force_fit_type (dirtype
, wi::to_widest (*argmin
), 0, false);
1274 *argmax
= force_fit_type (dirtype
, wi::to_widest (*argmax
), 0, false);
1276 /* If *ARGMIN is still less than *ARGMAX the conversion above
1277 is safe. Otherwise, it has overflowed and would be unsafe. */
1278 if (tree_int_cst_le (*argmin
, *argmax
))
1282 *argmin
= TYPE_MIN_VALUE (dirtype
);
1283 *argmax
= TYPE_MAX_VALUE (dirtype
);
1287 /* Return a range representing the minimum and maximum number of bytes
1288 that the format directive DIR will output for any argument given
1289 the WIDTH and PRECISION (extracted from DIR). This function is
1290 used when the directive argument or its value isn't known. */
1293 format_integer (const directive
&dir
, tree arg
, vr_values
*vr_values
)
1295 tree intmax_type_node
;
1296 tree uintmax_type_node
;
1298 /* Base to format the number in. */
1301 /* True when a conversion is preceded by a prefix indicating the base
1302 of the argument (octal or hexadecimal). */
1303 bool maybebase
= dir
.get_flag ('#');
1305 /* True when a signed conversion is preceded by a sign or space. */
1306 bool maybesign
= false;
1308 /* True for signed conversions (i.e., 'd' and 'i'). */
1311 switch (dir
.specifier
)
1315 /* Space and '+' are only meaningful for signed conversions. */
1316 maybesign
= dir
.get_flag (' ') | dir
.get_flag ('+');
1334 /* The type of the "formal" argument expected by the directive. */
1335 tree dirtype
= NULL_TREE
;
1337 /* Determine the expected type of the argument from the length
1339 switch (dir
.modifier
)
1342 if (dir
.specifier
== 'p')
1343 dirtype
= ptr_type_node
;
1345 dirtype
= sign
? integer_type_node
: unsigned_type_node
;
1349 dirtype
= sign
? short_integer_type_node
: short_unsigned_type_node
;
1353 dirtype
= sign
? signed_char_type_node
: unsigned_char_type_node
;
1357 dirtype
= sign
? long_integer_type_node
: long_unsigned_type_node
;
1363 ? long_long_integer_type_node
1364 : long_long_unsigned_type_node
);
1368 dirtype
= signed_or_unsigned_type_for (!sign
, size_type_node
);
1372 dirtype
= signed_or_unsigned_type_for (!sign
, ptrdiff_type_node
);
1376 build_intmax_type_nodes (&intmax_type_node
, &uintmax_type_node
);
1377 dirtype
= sign
? intmax_type_node
: uintmax_type_node
;
1381 return fmtresult ();
1384 /* The type of the argument to the directive, either deduced from
1385 the actual non-constant argument if one is known, or from
1386 the directive itself when none has been provided because it's
1388 tree argtype
= NULL_TREE
;
1392 /* When the argument has not been provided, use the type of
1393 the directive's argument as an approximation. This will
1394 result in false positives for directives like %i with
1395 arguments with smaller precision (such as short or char). */
1398 else if (TREE_CODE (arg
) == INTEGER_CST
)
1400 /* When a constant argument has been provided use its value
1401 rather than type to determine the length of the output. */
1404 if ((dir
.prec
[0] <= 0 && dir
.prec
[1] >= 0) && integer_zerop (arg
))
1406 /* As a special case, a precision of zero with a zero argument
1407 results in zero bytes except in base 8 when the '#' flag is
1408 specified, and for signed conversions in base 8 and 10 when
1409 either the space or '+' flag has been specified and it results
1410 in just one byte (with width having the normal effect). This
1411 must extend to the case of a specified precision with
1412 an unknown value because it can be zero. */
1413 res
.range
.min
= ((base
== 8 && dir
.get_flag ('#')) || maybesign
);
1414 if (res
.range
.min
== 0 && dir
.prec
[0] != dir
.prec
[1])
1417 res
.range
.likely
= 1;
1421 res
.range
.max
= res
.range
.min
;
1422 res
.range
.likely
= res
.range
.min
;
1427 /* Convert the argument to the type of the directive. */
1428 arg
= fold_convert (dirtype
, arg
);
1430 res
.range
.min
= tree_digits (arg
, base
, dir
.prec
[0],
1431 maybesign
, maybebase
);
1432 if (dir
.prec
[0] == dir
.prec
[1])
1433 res
.range
.max
= res
.range
.min
;
1435 res
.range
.max
= tree_digits (arg
, base
, dir
.prec
[1],
1436 maybesign
, maybebase
);
1437 res
.range
.likely
= res
.range
.min
;
1438 res
.knownrange
= true;
1441 res
.range
.unlikely
= res
.range
.max
;
1443 /* Bump up the counters if WIDTH is greater than LEN. */
1444 res
.adjust_for_width_or_precision (dir
.width
, dirtype
, base
,
1445 (sign
| maybebase
) + (base
== 16));
1446 /* Bump up the counters again if PRECision is greater still. */
1447 res
.adjust_for_width_or_precision (dir
.prec
, dirtype
, base
,
1448 (sign
| maybebase
) + (base
== 16));
1452 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg
))
1453 || TREE_CODE (TREE_TYPE (arg
)) == POINTER_TYPE
)
1454 /* Determine the type of the provided non-constant argument. */
1455 argtype
= TREE_TYPE (arg
);
1457 /* Don't bother with invalid arguments since they likely would
1458 have already been diagnosed, and disable any further checking
1459 of the format string by returning [-1, -1]. */
1460 return fmtresult ();
1464 /* Using either the range the non-constant argument is in, or its
1465 type (either "formal" or actual), create a range of values that
1466 constrain the length of output given the warning level. */
1467 tree argmin
= NULL_TREE
;
1468 tree argmax
= NULL_TREE
;
1471 && TREE_CODE (arg
) == SSA_NAME
1472 && INTEGRAL_TYPE_P (argtype
))
1474 /* Try to determine the range of values of the integer argument
1475 (range information is not available for pointers). */
1476 value_range
*vr
= vr_values
->get_value_range (arg
);
1477 if (vr
->type
== VR_RANGE
1478 && TREE_CODE (vr
->min
) == INTEGER_CST
1479 && TREE_CODE (vr
->max
) == INTEGER_CST
)
1484 /* Set KNOWNRANGE if the argument is in a known subrange
1485 of the directive's type and neither width nor precision
1486 is unknown. (KNOWNRANGE may be reset below). */
1488 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype
), argmin
)
1489 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype
), argmax
))
1490 && dir
.known_width_and_precision ());
1492 res
.argmin
= argmin
;
1493 res
.argmax
= argmax
;
1495 else if (vr
->type
== VR_ANTI_RANGE
)
1497 /* Handle anti-ranges if/when bug 71690 is resolved. */
1499 else if (vr
->type
== VR_VARYING
1500 || vr
->type
== VR_UNDEFINED
)
1502 /* The argument here may be the result of promoting the actual
1503 argument to int. Try to determine the type of the actual
1504 argument before promotion and narrow down its range that
1506 gimple
*def
= SSA_NAME_DEF_STMT (arg
);
1507 if (is_gimple_assign (def
))
1509 tree_code code
= gimple_assign_rhs_code (def
);
1510 if (code
== INTEGER_CST
)
1512 arg
= gimple_assign_rhs1 (def
);
1513 return format_integer (dir
, arg
, vr_values
);
1516 if (code
== NOP_EXPR
)
1518 tree type
= TREE_TYPE (gimple_assign_rhs1 (def
));
1519 if (INTEGRAL_TYPE_P (type
)
1520 || TREE_CODE (type
) == POINTER_TYPE
)
1529 if (TREE_CODE (argtype
) == POINTER_TYPE
)
1531 argmin
= build_int_cst (pointer_sized_int_node
, 0);
1532 argmax
= build_all_ones_cst (pointer_sized_int_node
);
1536 argmin
= TYPE_MIN_VALUE (argtype
);
1537 argmax
= TYPE_MAX_VALUE (argtype
);
1541 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1542 of the directive. If it has been cleared then since ARGMIN and/or
1543 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1544 ARGMAX in the result to include in diagnostics. */
1545 if (adjust_range_for_overflow (dirtype
, &argmin
, &argmax
))
1547 res
.knownrange
= false;
1548 res
.argmin
= argmin
;
1549 res
.argmax
= argmax
;
1552 /* Recursively compute the minimum and maximum from the known range. */
1553 if (TYPE_UNSIGNED (dirtype
) || tree_int_cst_sgn (argmin
) >= 0)
1555 /* For unsigned conversions/directives or signed when
1556 the minimum is positive, use the minimum and maximum to compute
1557 the shortest and longest output, respectively. */
1558 res
.range
.min
= format_integer (dir
, argmin
, vr_values
).range
.min
;
1559 res
.range
.max
= format_integer (dir
, argmax
, vr_values
).range
.max
;
1561 else if (tree_int_cst_sgn (argmax
) < 0)
1563 /* For signed conversions/directives if maximum is negative,
1564 use the minimum as the longest output and maximum as the
1566 res
.range
.min
= format_integer (dir
, argmax
, vr_values
).range
.min
;
1567 res
.range
.max
= format_integer (dir
, argmin
, vr_values
).range
.max
;
1571 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1572 as the shortest output and for the longest output compute the
1573 length of the output of both minimum and maximum and pick the
1575 unsigned HOST_WIDE_INT max1
1576 = format_integer (dir
, argmin
, vr_values
).range
.max
;
1577 unsigned HOST_WIDE_INT max2
1578 = format_integer (dir
, argmax
, vr_values
).range
.max
;
1580 = format_integer (dir
, integer_zero_node
, vr_values
).range
.min
;
1581 res
.range
.max
= MAX (max1
, max2
);
1584 /* If the range is known, use the maximum as the likely length. */
1586 res
.range
.likely
= res
.range
.max
;
1589 /* Otherwise, use the minimum. Except for the case where for %#x or
1590 %#o the minimum is just for a single value in the range (0) and
1591 for all other values it is something longer, like 0x1 or 01.
1592 Use the length for value 1 in that case instead as the likely
1594 res
.range
.likely
= res
.range
.min
;
1597 && (tree_int_cst_sgn (argmin
) < 0 || tree_int_cst_sgn (argmax
) > 0))
1599 if (res
.range
.min
== 1)
1600 res
.range
.likely
+= base
== 8 ? 1 : 2;
1601 else if (res
.range
.min
== 2
1603 && (dir
.width
[0] == 2 || dir
.prec
[0] == 2))
1608 res
.range
.unlikely
= res
.range
.max
;
1609 res
.adjust_for_width_or_precision (dir
.width
, dirtype
, base
,
1610 (sign
| maybebase
) + (base
== 16));
1611 res
.adjust_for_width_or_precision (dir
.prec
, dirtype
, base
,
1612 (sign
| maybebase
) + (base
== 16));
1617 /* Return the number of bytes that a format directive consisting of FLAGS,
1618 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1619 would result for argument X under ideal conditions (i.e., if PREC
1620 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1621 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1622 This function works around those problems. */
1624 static unsigned HOST_WIDE_INT
1625 get_mpfr_format_length (mpfr_ptr x
, const char *flags
, HOST_WIDE_INT prec
,
1626 char spec
, char rndspec
)
1630 HOST_WIDE_INT len
= strlen (flags
);
1633 memcpy (fmtstr
+ 1, flags
, len
);
1634 memcpy (fmtstr
+ 1 + len
, ".*R", 3);
1635 fmtstr
[len
+ 4] = rndspec
;
1636 fmtstr
[len
+ 5] = spec
;
1637 fmtstr
[len
+ 6] = '\0';
1639 spec
= TOUPPER (spec
);
1640 if (spec
== 'E' || spec
== 'F')
1642 /* For %e, specify the precision explicitly since mpfr_sprintf
1643 does its own thing just to be different (see MPFR bug 21088). */
1649 /* Avoid passing negative precisions with larger magnitude to MPFR
1650 to avoid exposing its bugs. (A negative precision is supposed
1656 HOST_WIDE_INT p
= prec
;
1658 if (spec
== 'G' && !strchr (flags
, '#'))
1660 /* For G/g without the pound flag, precision gives the maximum number
1661 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1662 a 128 bit IEEE extended precision, 4932. Using twice as much here
1663 should be more than sufficient for any real format. */
1664 if ((IEEE_MAX_10_EXP
* 2) < prec
)
1665 prec
= IEEE_MAX_10_EXP
* 2;
1670 /* Cap precision arbitrarily at 1KB and add the difference
1671 (if any) to the MPFR result. */
1676 len
= mpfr_snprintf (NULL
, 0, fmtstr
, (int)p
, x
);
1678 /* Handle the unlikely (impossible?) error by returning more than
1679 the maximum dictated by the function's return type. */
1681 return target_dir_max () + 1;
1683 /* Adjust the return value by the difference. */
1690 /* Return the number of bytes to format using the format specifier
1691 SPEC and the precision PREC the largest value in the real floating
1694 static unsigned HOST_WIDE_INT
1695 format_floating_max (tree type
, char spec
, HOST_WIDE_INT prec
)
1697 machine_mode mode
= TYPE_MODE (type
);
1699 /* IBM Extended mode. */
1700 if (MODE_COMPOSITE_P (mode
))
1703 /* Get the real type format desription for the target. */
1704 const real_format
*rfmt
= REAL_MODE_FORMAT (mode
);
1707 real_maxval (&rv
, 0, mode
);
1709 /* Convert the GCC real value representation with the precision
1710 of the real type to the mpfr_t format with the GCC default
1711 round-to-nearest mode. */
1713 mpfr_init2 (x
, rfmt
->p
);
1714 mpfr_from_real (x
, &rv
, GMP_RNDN
);
1716 /* Return a value one greater to account for the leading minus sign. */
1717 unsigned HOST_WIDE_INT r
1718 = 1 + get_mpfr_format_length (x
, "", prec
, spec
, 'D');
1723 /* Return a range representing the minimum and maximum number of bytes
1724 that the directive DIR will output for any argument. PREC gives
1725 the adjusted precision range to account for negative precisions
1726 meaning the default 6. This function is used when the directive
1727 argument or its value isn't known. */
1730 format_floating (const directive
&dir
, const HOST_WIDE_INT prec
[2])
1734 switch (dir
.modifier
)
1738 type
= double_type_node
;
1742 type
= long_double_type_node
;
1746 type
= long_double_type_node
;
1750 return fmtresult ();
1753 /* The minimum and maximum number of bytes produced by the directive. */
1756 /* The minimum output as determined by flags. It's always at least 1.
1757 When plus or space are set the output is preceded by either a sign
1759 unsigned flagmin
= (1 /* for the first digit */
1760 + (dir
.get_flag ('+') | dir
.get_flag (' ')));
1762 /* When the pound flag is set the decimal point is included in output
1763 regardless of precision. Whether or not a decimal point is included
1764 otherwise depends on the specification and precision. */
1765 bool radix
= dir
.get_flag ('#');
1767 switch (dir
.specifier
)
1772 HOST_WIDE_INT minprec
= 6 + !radix
/* decimal point */;
1773 if (dir
.prec
[0] <= 0)
1775 else if (dir
.prec
[0] > 0)
1776 minprec
= dir
.prec
[0] + !radix
/* decimal point */;
1778 res
.range
.min
= (2 /* 0x */
1784 res
.range
.max
= format_floating_max (type
, 'a', prec
[1]);
1785 res
.range
.likely
= res
.range
.min
;
1787 /* The unlikely maximum accounts for the longest multibyte
1788 decimal point character. */
1789 res
.range
.unlikely
= res
.range
.max
;
1790 if (dir
.prec
[1] > 0)
1791 res
.range
.unlikely
+= target_mb_len_max () - 1;
1799 /* Minimum output attributable to precision and, when it's
1800 non-zero, decimal point. */
1801 HOST_WIDE_INT minprec
= prec
[0] ? prec
[0] + !radix
: 0;
1803 /* The minimum output is "[-+]1.234567e+00" regardless
1804 of the value of the actual argument. */
1805 res
.range
.min
= (flagmin
1810 res
.range
.max
= format_floating_max (type
, 'e', prec
[1]);
1811 res
.range
.likely
= res
.range
.min
;
1813 /* The unlikely maximum accounts for the longest multibyte
1814 decimal point character. */
1815 if (dir
.prec
[0] != dir
.prec
[1]
1816 || dir
.prec
[0] == -1 || dir
.prec
[0] > 0)
1817 res
.range
.unlikely
= res
.range
.max
+ target_mb_len_max () -1;
1819 res
.range
.unlikely
= res
.range
.max
;
1826 /* Minimum output attributable to precision and, when it's non-zero,
1828 HOST_WIDE_INT minprec
= prec
[0] ? prec
[0] + !radix
: 0;
1830 /* The lower bound when precision isn't specified is 8 bytes
1831 ("1.23456" since precision is taken to be 6). When precision
1832 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1833 when precision is greater than zero, then the lower bound
1834 is 2 plus precision (plus flags). */
1835 res
.range
.min
= flagmin
+ radix
+ minprec
;
1837 /* Compute the upper bound for -TYPE_MAX. */
1838 res
.range
.max
= format_floating_max (type
, 'f', prec
[1]);
1840 /* The minimum output with unknown precision is a single byte
1841 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1842 if (dir
.prec
[0] < 0 && dir
.prec
[1] > 0)
1843 res
.range
.likely
= 3;
1845 res
.range
.likely
= res
.range
.min
;
1847 /* The unlikely maximum accounts for the longest multibyte
1848 decimal point character. */
1849 if (dir
.prec
[0] != dir
.prec
[1]
1850 || dir
.prec
[0] == -1 || dir
.prec
[0] > 0)
1851 res
.range
.unlikely
= res
.range
.max
+ target_mb_len_max () - 1;
1858 /* The %g output depends on precision and the exponent of
1859 the argument. Since the value of the argument isn't known
1860 the lower bound on the range of bytes (not counting flags
1861 or width) is 1 plus radix (i.e., either "0" or "0." for
1862 "%g" and "%#g", respectively, with a zero argument). */
1863 res
.range
.min
= flagmin
+ radix
;
1866 HOST_WIDE_INT maxprec
= dir
.prec
[1];
1867 if (radix
&& maxprec
)
1869 /* When the pound flag (radix) is set, trailing zeros aren't
1870 trimmed and so the longest output is the same as for %e,
1871 except with precision minus 1 (as specified in C11). */
1875 else if (maxprec
< 0)
1881 res
.range
.max
= format_floating_max (type
, spec
, maxprec
);
1883 /* The likely output is either the maximum computed above
1884 minus 1 (assuming the maximum is positive) when precision
1885 is known (or unspecified), or the same minimum as for %e
1886 (which is computed for a non-negative argument). Unlike
1887 for the other specifiers above the likely output isn't
1888 the minimum because for %g that's 1 which is unlikely. */
1890 || (unsigned HOST_WIDE_INT
)dir
.prec
[1] < target_int_max ())
1891 res
.range
.likely
= res
.range
.max
- 1;
1894 HOST_WIDE_INT minprec
= 6 + !radix
/* decimal point */;
1895 res
.range
.likely
= (flagmin
1901 /* The unlikely maximum accounts for the longest multibyte
1902 decimal point character. */
1903 res
.range
.unlikely
= res
.range
.max
+ target_mb_len_max () - 1;
1908 return fmtresult ();
1911 /* Bump up the byte counters if WIDTH is greater. */
1912 res
.adjust_for_width_or_precision (dir
.width
);
1916 /* Return a range representing the minimum and maximum number of bytes
1917 that the directive DIR will write on output for the floating argument
1921 format_floating (const directive
&dir
, tree arg
, vr_values
*)
1923 HOST_WIDE_INT prec
[] = { dir
.prec
[0], dir
.prec
[1] };
1924 tree type
= (dir
.modifier
== FMT_LEN_L
|| dir
.modifier
== FMT_LEN_ll
1925 ? long_double_type_node
: double_type_node
);
1927 /* For an indeterminate precision the lower bound must be assumed
1929 if (TOUPPER (dir
.specifier
) == 'A')
1931 /* Get the number of fractional decimal digits needed to represent
1932 the argument without a loss of accuracy. */
1934 = REAL_MODE_FORMAT (TYPE_MODE (type
))->p
;
1936 /* The precision of the IEEE 754 double format is 53.
1937 The precision of all other GCC binary double formats
1939 unsigned maxprec
= fmtprec
<= 56 ? 13 : 15;
1941 /* For %a, leave the minimum precision unspecified to let
1942 MFPR trim trailing zeros (as it and many other systems
1943 including Glibc happen to do) and set the maximum
1944 precision to reflect what it would be with trailing zeros
1945 present (as Solaris and derived systems do). */
1946 if (dir
.prec
[1] < 0)
1948 /* Both bounds are negative implies that precision has
1949 not been specified. */
1953 else if (dir
.prec
[0] < 0)
1955 /* With a negative lower bound and a non-negative upper
1956 bound set the minimum precision to zero and the maximum
1957 to the greater of the maximum precision (i.e., with
1958 trailing zeros present) and the specified upper bound. */
1960 prec
[1] = dir
.prec
[1] < maxprec
? maxprec
: dir
.prec
[1];
1963 else if (dir
.prec
[0] < 0)
1965 if (dir
.prec
[1] < 0)
1967 /* A precision in a strictly negative range is ignored and
1968 the default of 6 is used instead. */
1969 prec
[0] = prec
[1] = 6;
1973 /* For a precision in a partly negative range, the lower bound
1974 must be assumed to be zero and the new upper bound is the
1975 greater of 6 (the default precision used when the specified
1976 precision is negative) and the upper bound of the specified
1979 prec
[1] = dir
.prec
[1] < 6 ? 6 : dir
.prec
[1];
1984 || TREE_CODE (arg
) != REAL_CST
1985 || !useless_type_conversion_p (type
, TREE_TYPE (arg
)))
1986 return format_floating (dir
, prec
);
1988 /* The minimum and maximum number of bytes produced by the directive. */
1991 /* Get the real type format desription for the target. */
1992 const REAL_VALUE_TYPE
*rvp
= TREE_REAL_CST_PTR (arg
);
1993 const real_format
*rfmt
= REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg
)));
1996 char *pfmt
= fmtstr
;
1999 for (const char *pf
= "-+ #0"; *pf
; ++pf
)
2000 if (dir
.get_flag (*pf
))
2006 /* Set up an array to easily iterate over. */
2007 unsigned HOST_WIDE_INT
* const minmax
[] = {
2008 &res
.range
.min
, &res
.range
.max
2011 for (int i
= 0; i
!= sizeof minmax
/ sizeof *minmax
; ++i
)
2013 /* Convert the GCC real value representation with the precision
2014 of the real type to the mpfr_t format rounding down in the
2015 first iteration that computes the minimm and up in the second
2016 that computes the maximum. This order is arbibtrary because
2017 rounding in either direction can result in longer output. */
2019 mpfr_init2 (mpfrval
, rfmt
->p
);
2020 mpfr_from_real (mpfrval
, rvp
, i
? GMP_RNDU
: GMP_RNDD
);
2022 /* Use the MPFR rounding specifier to round down in the first
2023 iteration and then up. In most but not all cases this will
2024 result in the same number of bytes. */
2025 char rndspec
= "DU"[i
];
2027 /* Format it and store the result in the corresponding member
2028 of the result struct. */
2029 *minmax
[i
] = get_mpfr_format_length (mpfrval
, fmtstr
, prec
[i
],
2030 dir
.specifier
, rndspec
);
2031 mpfr_clear (mpfrval
);
2035 /* Make sure the minimum is less than the maximum (MPFR rounding
2036 in the call to mpfr_snprintf can result in the reverse. */
2037 if (res
.range
.max
< res
.range
.min
)
2039 unsigned HOST_WIDE_INT tmp
= res
.range
.min
;
2040 res
.range
.min
= res
.range
.max
;
2041 res
.range
.max
= tmp
;
2044 /* The range is known unless either width or precision is unknown. */
2045 res
.knownrange
= dir
.known_width_and_precision ();
2047 /* For the same floating point constant, unless width or precision
2048 is unknown, use the longer output as the likely maximum since
2049 with round to nearest either is equally likely. Otheriwse, when
2050 precision is unknown, use the greater of the minimum and 3 as
2051 the likely output (for "0.0" since zero precision is unlikely). */
2053 res
.range
.likely
= res
.range
.max
;
2054 else if (res
.range
.min
< 3
2056 && (unsigned HOST_WIDE_INT
)dir
.prec
[1] == target_int_max ())
2057 res
.range
.likely
= 3;
2059 res
.range
.likely
= res
.range
.min
;
2061 res
.range
.unlikely
= res
.range
.max
;
2063 if (res
.range
.max
> 2 && (prec
[0] != 0 || prec
[1] != 0))
2065 /* Unless the precision is zero output longer than 2 bytes may
2066 include the decimal point which must be a single character
2067 up to MB_LEN_MAX in length. This is overly conservative
2068 since in some conversions some constants result in no decimal
2069 point (e.g., in %g). */
2070 res
.range
.unlikely
+= target_mb_len_max () - 1;
2073 res
.adjust_for_width_or_precision (dir
.width
);
2077 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
2078 strings referenced by the expression STR, or (-1, -1) when not known.
2079 Used by the format_string function below. */
2082 get_string_length (tree str
)
2085 return fmtresult ();
2087 if (tree slen
= c_strlen (str
, 1))
2089 /* Simply return the length of the string. */
2090 fmtresult
res (tree_to_shwi (slen
));
2094 /* Determine the length of the shortest and longest string referenced
2095 by STR. Strings of unknown lengths are bounded by the sizes of
2096 arrays that subexpressions of STR may refer to. Pointers that
2097 aren't known to point any such arrays result in LENRANGE[1] set
2100 bool flexarray
= get_range_strlen (str
, lenrange
);
2102 if (lenrange
[0] || lenrange
[1])
2105 = (tree_fits_uhwi_p (lenrange
[0])
2106 ? tree_to_uhwi (lenrange
[0])
2110 = (tree_fits_uhwi_p (lenrange
[1])
2111 ? tree_to_uhwi (lenrange
[1])
2112 : HOST_WIDE_INT_M1U
);
2114 /* get_range_strlen() returns the target value of SIZE_MAX for
2115 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2116 which may be bigger. */
2117 if ((unsigned HOST_WIDE_INT
)min
== target_size_max ())
2118 min
= HOST_WIDE_INT_M1U
;
2119 if ((unsigned HOST_WIDE_INT
)max
== target_size_max ())
2120 max
= HOST_WIDE_INT_M1U
;
2122 fmtresult
res (min
, max
);
2124 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2125 by STR are known to be bounded (though not necessarily by their
2126 actual length but perhaps by their maximum possible length). */
2127 if (res
.range
.max
< target_int_max ())
2129 res
.knownrange
= true;
2130 /* When the the length of the longest string is known and not
2131 excessive use it as the likely length of the string(s). */
2132 res
.range
.likely
= res
.range
.max
;
2136 /* When the upper bound is unknown (it can be zero or excessive)
2137 set the likely length to the greater of 1 and the length of
2138 the shortest string and reset the lower bound to zero. */
2139 res
.range
.likely
= res
.range
.min
? res
.range
.min
: warn_level
> 1;
2143 /* If the range of string length has been estimated from the size
2144 of an array at the end of a struct assume that it's longer than
2145 the array bound says it is in case it's used as a poor man's
2146 flexible array member, such as in struct S { char a[4]; }; */
2147 res
.range
.unlikely
= flexarray
? HOST_WIDE_INT_MAX
: res
.range
.max
;
2152 return get_string_length (NULL_TREE
);
2155 /* Return the minimum and maximum number of characters formatted
2156 by the '%c' format directives and its wide character form for
2157 the argument ARG. ARG can be null (for functions such as
2161 format_character (const directive
&dir
, tree arg
, vr_values
*vr_values
)
2165 res
.knownrange
= true;
2167 if (dir
.modifier
== FMT_LEN_l
)
2169 /* A wide character can result in as few as zero bytes. */
2172 HOST_WIDE_INT min
, max
;
2173 if (get_int_range (arg
, &min
, &max
, false, 0, vr_values
))
2175 if (min
== 0 && max
== 0)
2177 /* The NUL wide character results in no bytes. */
2179 res
.range
.likely
= 0;
2180 res
.range
.unlikely
= 0;
2182 else if (min
> 0 && min
< 128)
2184 /* A wide character in the ASCII range most likely results
2185 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2187 res
.range
.likely
= 1;
2188 res
.range
.unlikely
= target_mb_len_max ();
2192 /* A wide character outside the ASCII range likely results
2193 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2194 res
.range
.max
= target_mb_len_max ();
2195 res
.range
.likely
= 2;
2196 res
.range
.unlikely
= res
.range
.max
;
2201 /* An unknown wide character is treated the same as a wide
2202 character outside the ASCII range. */
2203 res
.range
.max
= target_mb_len_max ();
2204 res
.range
.likely
= 2;
2205 res
.range
.unlikely
= res
.range
.max
;
2210 /* A plain '%c' directive. Its ouput is exactly 1. */
2211 res
.range
.min
= res
.range
.max
= 1;
2212 res
.range
.likely
= res
.range
.unlikely
= 1;
2213 res
.knownrange
= true;
2216 /* Bump up the byte counters if WIDTH is greater. */
2217 return res
.adjust_for_width_or_precision (dir
.width
);
2220 /* Return the minimum and maximum number of characters formatted
2221 by the '%s' format directive and its wide character form for
2222 the argument ARG. ARG can be null (for functions such as
2226 format_string (const directive
&dir
, tree arg
, vr_values
*)
2230 /* Compute the range the argument's length can be in. */
2231 fmtresult slen
= get_string_length (arg
);
2232 if (slen
.range
.min
== slen
.range
.max
2233 && slen
.range
.min
< HOST_WIDE_INT_MAX
)
2235 /* The argument is either a string constant or it refers
2236 to one of a number of strings of the same length. */
2238 /* A '%s' directive with a string argument with constant length. */
2239 res
.range
= slen
.range
;
2241 if (dir
.modifier
== FMT_LEN_l
)
2243 /* In the worst case the length of output of a wide string S
2244 is bounded by MB_LEN_MAX * wcslen (S). */
2245 res
.range
.max
*= target_mb_len_max ();
2246 res
.range
.unlikely
= res
.range
.max
;
2247 /* It's likely that the the total length is not more that
2249 res
.range
.likely
= res
.range
.min
* 2;
2251 if (dir
.prec
[1] >= 0
2252 && (unsigned HOST_WIDE_INT
)dir
.prec
[1] < res
.range
.max
)
2254 res
.range
.max
= dir
.prec
[1];
2255 res
.range
.likely
= dir
.prec
[1];
2256 res
.range
.unlikely
= dir
.prec
[1];
2259 if (dir
.prec
[0] < 0 && dir
.prec
[1] > -1)
2261 else if (dir
.prec
[0] >= 0)
2262 res
.range
.likely
= dir
.prec
[0];
2264 /* Even a non-empty wide character string need not convert into
2270 res
.knownrange
= true;
2272 if (dir
.prec
[0] < 0 && dir
.prec
[1] > -1)
2274 else if ((unsigned HOST_WIDE_INT
)dir
.prec
[0] < res
.range
.min
)
2275 res
.range
.min
= dir
.prec
[0];
2277 if ((unsigned HOST_WIDE_INT
)dir
.prec
[1] < res
.range
.max
)
2279 res
.range
.max
= dir
.prec
[1];
2280 res
.range
.likely
= dir
.prec
[1];
2281 res
.range
.unlikely
= dir
.prec
[1];
2285 else if (arg
&& integer_zerop (arg
))
2287 /* Handle null pointer argument. */
2295 /* For a '%s' and '%ls' directive with a non-constant string (either
2296 one of a number of strings of known length or an unknown string)
2297 the minimum number of characters is lesser of PRECISION[0] and
2298 the length of the shortest known string or zero, and the maximum
2299 is the lessser of the length of the longest known string or
2300 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2301 the minimum at level 1 and the greater of the minimum and 1
2302 at level 2. This result is adjust upward for width (if it's
2305 if (dir
.modifier
== FMT_LEN_l
)
2307 /* A wide character converts to as few as zero bytes. */
2309 if (slen
.range
.max
< target_int_max ())
2310 slen
.range
.max
*= target_mb_len_max ();
2312 if (slen
.range
.likely
< target_int_max ())
2313 slen
.range
.likely
*= 2;
2315 if (slen
.range
.likely
< target_int_max ())
2316 slen
.range
.unlikely
*= target_mb_len_max ();
2319 res
.range
= slen
.range
;
2321 if (dir
.prec
[0] >= 0)
2323 /* Adjust the minimum to zero if the string length is unknown,
2324 or at most the lower bound of the precision otherwise. */
2325 if (slen
.range
.min
>= target_int_max ())
2327 else if ((unsigned HOST_WIDE_INT
)dir
.prec
[0] < slen
.range
.min
)
2328 res
.range
.min
= dir
.prec
[0];
2330 /* Make both maxima no greater than the upper bound of precision. */
2331 if ((unsigned HOST_WIDE_INT
)dir
.prec
[1] < slen
.range
.max
2332 || slen
.range
.max
>= target_int_max ())
2334 res
.range
.max
= dir
.prec
[1];
2335 res
.range
.unlikely
= dir
.prec
[1];
2338 /* If precision is constant, set the likely counter to the lesser
2339 of it and the maximum string length. Otherwise, if the lower
2340 bound of precision is greater than zero, set the likely counter
2341 to the minimum. Otherwise set it to zero or one based on
2342 the warning level. */
2343 if (dir
.prec
[0] == dir
.prec
[1])
2345 = ((unsigned HOST_WIDE_INT
)dir
.prec
[0] < slen
.range
.max
2346 ? dir
.prec
[0] : slen
.range
.max
);
2347 else if (dir
.prec
[0] > 0)
2348 res
.range
.likely
= res
.range
.min
;
2350 res
.range
.likely
= warn_level
> 1;
2352 else if (dir
.prec
[1] >= 0)
2355 if ((unsigned HOST_WIDE_INT
)dir
.prec
[1] < slen
.range
.max
)
2356 res
.range
.max
= dir
.prec
[1];
2357 res
.range
.likely
= dir
.prec
[1] ? warn_level
> 1 : 0;
2359 else if (slen
.range
.min
>= target_int_max ())
2362 res
.range
.max
= HOST_WIDE_INT_MAX
;
2363 /* At level 1 strings of unknown length are assumed to be
2364 empty, while at level 1 they are assumed to be one byte
2366 res
.range
.likely
= warn_level
> 1;
2370 /* A string of unknown length unconstrained by precision is
2371 assumed to be empty at level 1 and just one character long
2372 at higher levels. */
2373 if (res
.range
.likely
>= target_int_max ())
2374 res
.range
.likely
= warn_level
> 1;
2377 res
.range
.unlikely
= res
.range
.max
;
2380 /* Bump up the byte counters if WIDTH is greater. */
2381 return res
.adjust_for_width_or_precision (dir
.width
);
2384 /* Format plain string (part of the format string itself). */
2387 format_plain (const directive
&dir
, tree
, vr_values
*)
2389 fmtresult
res (dir
.len
);
2393 /* Return true if the RESULT of a directive in a call describe by INFO
2394 should be diagnosed given the AVAILable space in the destination. */
2397 should_warn_p (const sprintf_dom_walker::call_info
&info
,
2398 const result_range
&avail
, const result_range
&result
)
2400 if (result
.max
<= avail
.min
)
2402 /* The least amount of space remaining in the destination is big
2403 enough for the longest output. */
2409 if (warn_format_trunc
== 1 && result
.min
<= avail
.max
2410 && info
.retval_used ())
2412 /* The likely amount of space remaining in the destination is big
2413 enough for the least output and the return value is used. */
2417 if (warn_format_trunc
== 1 && result
.likely
<= avail
.likely
2418 && !info
.retval_used ())
2420 /* The likely amount of space remaining in the destination is big
2421 enough for the likely output and the return value is unused. */
2425 if (warn_format_trunc
== 2
2426 && result
.likely
<= avail
.min
2427 && (result
.max
<= avail
.min
2428 || result
.max
> HOST_WIDE_INT_MAX
))
2430 /* The minimum amount of space remaining in the destination is big
2431 enough for the longest output. */
2437 if (warn_level
== 1 && result
.likely
<= avail
.likely
)
2439 /* The likely amount of space remaining in the destination is big
2440 enough for the likely output. */
2445 && result
.likely
<= avail
.min
2446 && (result
.max
<= avail
.min
2447 || result
.max
> HOST_WIDE_INT_MAX
))
2449 /* The minimum amount of space remaining in the destination is big
2450 enough for the longest output. */
2458 /* At format string location describe by DIRLOC in a call described
2459 by INFO, issue a warning for a directive DIR whose output may be
2460 in excess of the available space AVAIL_RANGE in the destination
2461 given the formatting result FMTRES. This function does nothing
2462 except decide whether to issue a warning for a possible write
2463 past the end or truncation and, if so, format the warning.
2464 Return true if a warning has been issued. */
2467 maybe_warn (substring_loc
&dirloc
, location_t argloc
,
2468 const sprintf_dom_walker::call_info
&info
,
2469 const result_range
&avail_range
, const result_range
&res
,
2470 const directive
&dir
)
2472 if (!should_warn_p (info
, avail_range
, res
))
2475 /* A warning will definitely be issued below. */
2477 /* The maximum byte count to reference in the warning. Larger counts
2478 imply that the upper bound is unknown (and could be anywhere between
2479 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2480 than "between N and X" where X is some huge number. */
2481 unsigned HOST_WIDE_INT maxbytes
= target_dir_max ();
2483 /* True when there is enough room in the destination for the least
2484 amount of a directive's output but not enough for its likely or
2486 bool maybe
= (res
.min
<= avail_range
.max
2487 && (avail_range
.min
< res
.likely
2488 || (res
.max
< HOST_WIDE_INT_MAX
2489 && avail_range
.min
< res
.max
)));
2491 /* Buffer for the directive in the host character set (used when
2492 the source character set is different). */
2495 if (avail_range
.min
== avail_range
.max
)
2497 /* The size of the destination region is exact. */
2498 unsigned HOST_WIDE_INT navail
= avail_range
.max
;
2500 if (target_to_host (*dir
.beg
) != '%')
2502 /* For plain character directives (i.e., the format string itself)
2503 but not others, point the caret at the first character that's
2504 past the end of the destination. */
2505 if (navail
< dir
.len
)
2506 dirloc
.set_caret_index (dirloc
.get_caret_idx () + navail
);
2509 if (*dir
.beg
== '\0')
2511 /* This is the terminating nul. */
2512 gcc_assert (res
.min
== 1 && res
.min
== res
.max
);
2514 return fmtwarn (dirloc
, UNKNOWN_LOCATION
, NULL
, info
.warnopt (),
2517 ? G_("%qE output may be truncated before the "
2518 "last format character")
2519 : G_("%qE output truncated before the last "
2520 "format character"))
2522 ? G_("%qE may write a terminating nul past the "
2523 "end of the destination")
2524 : G_("%qE writing a terminating nul past the "
2525 "end of the destination")),
2529 if (res
.min
== res
.max
)
2531 const char *d
= target_to_host (hostdir
, sizeof hostdir
, dir
.beg
);
2533 return fmtwarn_n (dirloc
, argloc
, NULL
, info
.warnopt (), res
.min
,
2534 "%<%.*s%> directive writing %wu byte into a "
2535 "region of size %wu",
2536 "%<%.*s%> directive writing %wu bytes into a "
2537 "region of size %wu",
2538 (int) dir
.len
, d
, res
.min
, navail
);
2540 return fmtwarn_n (dirloc
, argloc
, NULL
, info
.warnopt (), res
.min
,
2541 "%<%.*s%> directive output may be truncated "
2542 "writing %wu byte into a region of size %wu",
2543 "%<%.*s%> directive output may be truncated "
2544 "writing %wu bytes into a region of size %wu",
2545 (int) dir
.len
, d
, res
.min
, navail
);
2547 return fmtwarn_n (dirloc
, argloc
, NULL
, info
.warnopt (), res
.min
,
2548 "%<%.*s%> directive output truncated writing "
2549 "%wu byte into a region of size %wu",
2550 "%<%.*s%> directive output truncated writing "
2551 "%wu bytes into a region of size %wu",
2552 (int) dir
.len
, d
, res
.min
, navail
);
2554 if (res
.min
== 0 && res
.max
< maxbytes
)
2555 return fmtwarn (dirloc
, argloc
, NULL
,
2559 ? G_("%<%.*s%> directive output may be truncated "
2560 "writing up to %wu bytes into a region of "
2562 : G_("%<%.*s%> directive output truncated writing "
2563 "up to %wu bytes into a region of size %wu"))
2564 : G_("%<%.*s%> directive writing up to %wu bytes "
2565 "into a region of size %wu"), (int) dir
.len
,
2566 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2569 if (res
.min
== 0 && maxbytes
<= res
.max
)
2570 /* This is a special case to avoid issuing the potentially
2572 writing 0 or more bytes into a region of size 0. */
2573 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2576 ? G_("%<%.*s%> directive output may be truncated "
2577 "writing likely %wu or more bytes into a "
2578 "region of size %wu")
2579 : G_("%<%.*s%> directive output truncated writing "
2580 "likely %wu or more bytes into a region of "
2582 : G_("%<%.*s%> directive writing likely %wu or more "
2583 "bytes into a region of size %wu"), (int) dir
.len
,
2584 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2585 res
.likely
, navail
);
2587 if (res
.max
< maxbytes
)
2588 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2591 ? G_("%<%.*s%> directive output may be truncated "
2592 "writing between %wu and %wu bytes into a "
2593 "region of size %wu")
2594 : G_("%<%.*s%> directive output truncated "
2595 "writing between %wu and %wu bytes into a "
2596 "region of size %wu"))
2597 : G_("%<%.*s%> directive writing between %wu and "
2598 "%wu bytes into a region of size %wu"),
2600 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2601 res
.min
, res
.max
, navail
);
2603 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2606 ? G_("%<%.*s%> directive output may be truncated "
2607 "writing %wu or more bytes into a region of "
2609 : G_("%<%.*s%> directive output truncated writing "
2610 "%wu or more bytes into a region of size %wu"))
2611 : G_("%<%.*s%> directive writing %wu or more bytes "
2612 "into a region of size %wu"), (int) dir
.len
,
2613 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2617 /* The size of the destination region is a range. */
2619 if (target_to_host (*dir
.beg
) != '%')
2621 unsigned HOST_WIDE_INT navail
= avail_range
.max
;
2623 /* For plain character directives (i.e., the format string itself)
2624 but not others, point the caret at the first character that's
2625 past the end of the destination. */
2626 if (navail
< dir
.len
)
2627 dirloc
.set_caret_index (dirloc
.get_caret_idx () + navail
);
2630 if (*dir
.beg
== '\0')
2632 gcc_assert (res
.min
== 1 && res
.min
== res
.max
);
2634 return fmtwarn (dirloc
, UNKNOWN_LOCATION
, NULL
, info
.warnopt (),
2637 ? G_("%qE output may be truncated before the last "
2639 : G_("%qE output truncated before the last format "
2642 ? G_("%qE may write a terminating nul past the end "
2643 "of the destination")
2644 : G_("%qE writing a terminating nul past the end "
2645 "of the destination")), info
.func
);
2648 if (res
.min
== res
.max
)
2650 const char *d
= target_to_host (hostdir
, sizeof hostdir
, dir
.beg
);
2652 return fmtwarn_n (dirloc
, argloc
, NULL
, info
.warnopt (), res
.min
,
2653 "%<%.*s%> directive writing %wu byte into a region "
2654 "of size between %wu and %wu",
2655 "%<%.*s%> directive writing %wu bytes into a region "
2656 "of size between %wu and %wu", (int) dir
.len
, d
,
2657 res
.min
, avail_range
.min
, avail_range
.max
);
2659 return fmtwarn_n (dirloc
, argloc
, NULL
, info
.warnopt (), res
.min
,
2660 "%<%.*s%> directive output may be truncated writing "
2661 "%wu byte into a region of size between %wu and %wu",
2662 "%<%.*s%> directive output may be truncated writing "
2663 "%wu bytes into a region of size between %wu and "
2664 "%wu", (int) dir
.len
, d
, res
.min
, avail_range
.min
,
2667 return fmtwarn_n (dirloc
, argloc
, NULL
, info
.warnopt (), res
.min
,
2668 "%<%.*s%> directive output truncated writing %wu "
2669 "byte into a region of size between %wu and %wu",
2670 "%<%.*s%> directive output truncated writing %wu "
2671 "bytes into a region of size between %wu and %wu",
2672 (int) dir
.len
, d
, res
.min
, avail_range
.min
,
2676 if (res
.min
== 0 && res
.max
< maxbytes
)
2677 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2680 ? G_("%<%.*s%> directive output may be truncated "
2681 "writing up to %wu bytes into a region of size "
2682 "between %wu and %wu")
2683 : G_("%<%.*s%> directive output truncated writing "
2684 "up to %wu bytes into a region of size between "
2686 : G_("%<%.*s%> directive writing up to %wu bytes "
2687 "into a region of size between %wu and %wu"),
2689 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2690 res
.max
, avail_range
.min
, avail_range
.max
);
2692 if (res
.min
== 0 && maxbytes
<= res
.max
)
2693 /* This is a special case to avoid issuing the potentially confusing
2695 writing 0 or more bytes into a region of size between 0 and N. */
2696 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2699 ? G_("%<%.*s%> directive output may be truncated "
2700 "writing likely %wu or more bytes into a region "
2701 "of size between %wu and %wu")
2702 : G_("%<%.*s%> directive output truncated writing "
2703 "likely %wu or more bytes into a region of size "
2704 "between %wu and %wu"))
2705 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2706 "into a region of size between %wu and %wu"),
2708 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2709 res
.likely
, avail_range
.min
, avail_range
.max
);
2711 if (res
.max
< maxbytes
)
2712 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2715 ? G_("%<%.*s%> directive output may be truncated "
2716 "writing between %wu and %wu bytes into a region "
2717 "of size between %wu and %wu")
2718 : G_("%<%.*s%> directive output truncated writing "
2719 "between %wu and %wu bytes into a region of size "
2720 "between %wu and %wu"))
2721 : G_("%<%.*s%> directive writing between %wu and "
2722 "%wu bytes into a region of size between %wu and "
2723 "%wu"), (int) dir
.len
,
2724 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2725 res
.min
, res
.max
, avail_range
.min
, avail_range
.max
);
2727 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2730 ? G_("%<%.*s%> directive output may be truncated writing "
2731 "%wu or more bytes into a region of size between "
2733 : G_("%<%.*s%> directive output truncated writing "
2734 "%wu or more bytes into a region of size between "
2736 : G_("%<%.*s%> directive writing %wu or more bytes "
2737 "into a region of size between %wu and %wu"),
2739 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2740 res
.min
, avail_range
.min
, avail_range
.max
);
2743 /* Compute the length of the output resulting from the directive DIR
2744 in a call described by INFO and update the overall result of the call
2745 in *RES. Return true if the directive has been handled. */
2748 format_directive (const sprintf_dom_walker::call_info
&info
,
2749 format_result
*res
, const directive
&dir
,
2750 class vr_values
*vr_values
)
2752 /* Offset of the beginning of the directive from the beginning
2753 of the format string. */
2754 size_t offset
= dir
.beg
- info
.fmtstr
;
2755 size_t start
= offset
;
2756 size_t length
= offset
+ dir
.len
- !!dir
.len
;
2758 /* Create a location for the whole directive from the % to the format
2760 substring_loc
dirloc (info
.fmtloc
, TREE_TYPE (info
.format
),
2761 offset
, start
, length
);
2763 /* Also get the location of the argument if possible.
2764 This doesn't work for integer literals or function calls. */
2765 location_t argloc
= UNKNOWN_LOCATION
;
2767 argloc
= EXPR_LOCATION (dir
.arg
);
2769 /* Bail when there is no function to compute the output length,
2770 or when minimum length checking has been disabled. */
2771 if (!dir
.fmtfunc
|| res
->range
.min
>= HOST_WIDE_INT_MAX
)
2774 /* Compute the range of lengths of the formatted output. */
2775 fmtresult fmtres
= dir
.fmtfunc (dir
, dir
.arg
, vr_values
);
2777 /* Record whether the output of all directives is known to be
2778 bounded by some maximum, implying that their arguments are
2779 either known exactly or determined to be in a known range
2780 or, for strings, limited by the upper bounds of the arrays
2782 res
->knownrange
&= fmtres
.knownrange
;
2784 if (!fmtres
.knownrange
)
2786 /* Only when the range is known, check it against the host value
2787 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2788 INT_MAX precision, which is the longest possible output of any
2789 single directive). That's the largest valid byte count (though
2790 not valid call to a printf-like function because it can never
2791 return such a count). Otherwise, the range doesn't correspond
2792 to known values of the argument. */
2793 if (fmtres
.range
.max
> target_dir_max ())
2795 /* Normalize the MAX counter to avoid having to deal with it
2796 later. The counter can be less than HOST_WIDE_INT_M1U
2797 when compiling for an ILP32 target on an LP64 host. */
2798 fmtres
.range
.max
= HOST_WIDE_INT_M1U
;
2799 /* Disable exact and maximum length checking after a failure
2800 to determine the maximum number of characters (for example
2801 for wide characters or wide character strings) but continue
2802 tracking the minimum number of characters. */
2803 res
->range
.max
= HOST_WIDE_INT_M1U
;
2806 if (fmtres
.range
.min
> target_dir_max ())
2808 /* Disable exact length checking after a failure to determine
2809 even the minimum number of characters (it shouldn't happen
2810 except in an error) but keep tracking the minimum and maximum
2811 number of characters. */
2816 /* Buffer for the directive in the host character set (used when
2817 the source character set is different). */
2820 int dirlen
= dir
.len
;
2824 fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2825 "%<%.*s%> directive argument is null",
2826 dirlen
, target_to_host (hostdir
, sizeof hostdir
, dir
.beg
));
2828 /* Don't bother processing the rest of the format string. */
2830 res
->range
.min
= HOST_WIDE_INT_M1U
;
2831 res
->range
.max
= HOST_WIDE_INT_M1U
;
2835 /* Compute the number of available bytes in the destination. There
2836 must always be at least one byte of space for the terminating
2837 NUL that's appended after the format string has been processed. */
2838 result_range avail_range
= bytes_remaining (info
.objsize
, *res
);
2840 bool warned
= res
->warned
;
2843 warned
= maybe_warn (dirloc
, argloc
, info
, avail_range
,
2846 /* Bump up the total maximum if it isn't too big. */
2847 if (res
->range
.max
< HOST_WIDE_INT_MAX
2848 && fmtres
.range
.max
< HOST_WIDE_INT_MAX
)
2849 res
->range
.max
+= fmtres
.range
.max
;
2851 /* Raise the total unlikely maximum by the larger of the maximum
2852 and the unlikely maximum. */
2853 unsigned HOST_WIDE_INT save
= res
->range
.unlikely
;
2854 if (fmtres
.range
.max
< fmtres
.range
.unlikely
)
2855 res
->range
.unlikely
+= fmtres
.range
.unlikely
;
2857 res
->range
.unlikely
+= fmtres
.range
.max
;
2859 if (res
->range
.unlikely
< save
)
2860 res
->range
.unlikely
= HOST_WIDE_INT_M1U
;
2862 res
->range
.min
+= fmtres
.range
.min
;
2863 res
->range
.likely
+= fmtres
.range
.likely
;
2865 /* Has the minimum directive output length exceeded the maximum
2866 of 4095 bytes required to be supported? */
2867 bool minunder4k
= fmtres
.range
.min
< 4096;
2868 bool maxunder4k
= fmtres
.range
.max
< 4096;
2869 /* Clear UNDER4K in the overall result if the maximum has exceeded
2870 the 4k (this is necessary to avoid the return valuye optimization
2871 that may not be safe in the maximum case). */
2873 res
->under4k
= false;
2876 /* Only warn at level 2. */
2879 || (!maxunder4k
&& fmtres
.range
.max
< HOST_WIDE_INT_MAX
)))
2881 /* The directive output may be longer than the maximum required
2882 to be handled by an implementation according to 7.21.6.1, p15
2883 of C11. Warn on this only at level 2 but remember this and
2884 prevent folding the return value when done. This allows for
2885 the possibility of the actual libc call failing due to ENOMEM
2886 (like Glibc does under some conditions). */
2888 if (fmtres
.range
.min
== fmtres
.range
.max
)
2889 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2890 "%<%.*s%> directive output of %wu bytes exceeds "
2891 "minimum required size of 4095", dirlen
,
2892 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2895 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2897 ? G_("%<%.*s%> directive output between %wu and %wu "
2898 "bytes may exceed minimum required size of "
2900 : G_("%<%.*s%> directive output between %wu and %wu "
2901 "bytes exceeds minimum required size of 4095"),
2903 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2904 fmtres
.range
.min
, fmtres
.range
.max
);
2907 /* Has the likely and maximum directive output exceeded INT_MAX? */
2908 bool likelyximax
= *dir
.beg
&& res
->range
.likely
> target_int_max ();
2909 /* Don't consider the maximum to be in excess when it's the result
2910 of a string of unknown length (i.e., whose maximum has been set
2911 to be greater than or equal to HOST_WIDE_INT_MAX. */
2912 bool maxximax
= (*dir
.beg
2913 && res
->range
.max
> target_int_max ()
2914 && res
->range
.max
< HOST_WIDE_INT_MAX
);
2917 /* Warn for the likely output size at level 1. */
2919 /* But only warn for the maximum at level 2. */
2922 && fmtres
.range
.max
< HOST_WIDE_INT_MAX
)))
2924 /* The directive output causes the total length of output
2925 to exceed INT_MAX bytes. */
2927 if (fmtres
.range
.min
== fmtres
.range
.max
)
2928 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2929 "%<%.*s%> directive output of %wu bytes causes "
2930 "result to exceed %<INT_MAX%>", dirlen
,
2931 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2934 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2935 fmtres
.range
.min
> target_int_max ()
2936 ? G_ ("%<%.*s%> directive output between %wu and "
2937 "%wu bytes causes result to exceed "
2939 : G_ ("%<%.*s%> directive output between %wu and "
2940 "%wu bytes may cause result to exceed "
2941 "%<INT_MAX%>"), dirlen
,
2942 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2943 fmtres
.range
.min
, fmtres
.range
.max
);
2946 if (warned
&& fmtres
.range
.min
< fmtres
.range
.likely
2947 && fmtres
.range
.likely
< fmtres
.range
.max
)
2948 inform_n (info
.fmtloc
, fmtres
.range
.likely
,
2949 "assuming directive output of %wu byte",
2950 "assuming directive output of %wu bytes",
2951 fmtres
.range
.likely
);
2953 if (warned
&& fmtres
.argmin
)
2955 if (fmtres
.argmin
== fmtres
.argmax
)
2956 inform (info
.fmtloc
, "directive argument %qE", fmtres
.argmin
);
2957 else if (fmtres
.knownrange
)
2958 inform (info
.fmtloc
, "directive argument in the range [%E, %E]",
2959 fmtres
.argmin
, fmtres
.argmax
);
2961 inform (info
.fmtloc
,
2962 "using the range [%E, %E] for directive argument",
2963 fmtres
.argmin
, fmtres
.argmax
);
2966 res
->warned
|= warned
;
2968 if (!dir
.beg
[0] && res
->warned
&& info
.objsize
< HOST_WIDE_INT_MAX
)
2970 /* If a warning has been issued for buffer overflow or truncation
2971 (but not otherwise) help the user figure out how big a buffer
2974 location_t callloc
= gimple_location (info
.callstmt
);
2976 unsigned HOST_WIDE_INT min
= res
->range
.min
;
2977 unsigned HOST_WIDE_INT max
= res
->range
.max
;
2982 ? G_("%qE output %wu byte into a destination of size %wu")
2983 : G_("%qE output %wu bytes into a destination of size %wu")),
2984 info
.func
, min
, info
.objsize
);
2985 else if (max
< HOST_WIDE_INT_MAX
)
2987 "%qE output between %wu and %wu bytes into "
2988 "a destination of size %wu",
2989 info
.func
, min
, max
, info
.objsize
);
2990 else if (min
< res
->range
.likely
&& res
->range
.likely
< max
)
2992 "%qE output %wu or more bytes (assuming %wu) into "
2993 "a destination of size %wu",
2994 info
.func
, min
, res
->range
.likely
, info
.objsize
);
2997 "%qE output %wu or more bytes into a destination of size %wu",
2998 info
.func
, min
, info
.objsize
);
3001 if (dump_file
&& *dir
.beg
)
3005 HOST_WIDE_INT_PRINT_DEC
", " HOST_WIDE_INT_PRINT_DEC
", "
3006 HOST_WIDE_INT_PRINT_DEC
", " HOST_WIDE_INT_PRINT_DEC
" ("
3007 HOST_WIDE_INT_PRINT_DEC
", " HOST_WIDE_INT_PRINT_DEC
", "
3008 HOST_WIDE_INT_PRINT_DEC
", " HOST_WIDE_INT_PRINT_DEC
")\n",
3009 fmtres
.range
.min
, fmtres
.range
.likely
,
3010 fmtres
.range
.max
, fmtres
.range
.unlikely
,
3011 res
->range
.min
, res
->range
.likely
,
3012 res
->range
.max
, res
->range
.unlikely
);
3018 /* Parse a format directive in function call described by INFO starting
3019 at STR and populate DIR structure. Bump up *ARGNO by the number of
3020 arguments extracted for the directive. Return the length of
3024 parse_directive (sprintf_dom_walker::call_info
&info
,
3025 directive
&dir
, format_result
*res
,
3026 const char *str
, unsigned *argno
,
3027 vr_values
*vr_values
)
3029 const char *pcnt
= strchr (str
, target_percent
);
3032 if (size_t len
= pcnt
? pcnt
- str
: *str
? strlen (str
) : 1)
3034 /* This directive is either a plain string or the terminating nul
3035 (which isn't really a directive but it simplifies things to
3036 handle it as if it were). */
3038 dir
.fmtfunc
= format_plain
;
3042 fprintf (dump_file
, " Directive %u at offset "
3043 HOST_WIDE_INT_PRINT_UNSIGNED
": \"%.*s\", "
3044 "length = " HOST_WIDE_INT_PRINT_UNSIGNED
"\n",
3046 (unsigned HOST_WIDE_INT
)(size_t)(dir
.beg
- info
.fmtstr
),
3047 (int)dir
.len
, dir
.beg
, (unsigned HOST_WIDE_INT
) dir
.len
);
3053 const char *pf
= pcnt
+ 1;
3055 /* POSIX numbered argument index or zero when none. */
3056 HOST_WIDE_INT dollar
= 0;
3058 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3059 when given by a va_list argument, and a non-negative value
3060 when specified in the format string itself. */
3061 HOST_WIDE_INT width
= -1;
3062 HOST_WIDE_INT precision
= -1;
3064 /* Pointers to the beginning of the width and precision decimal
3065 string (if any) within the directive. */
3066 const char *pwidth
= 0;
3067 const char *pprec
= 0;
3069 /* When the value of the decimal string that specifies width or
3070 precision is out of range, points to the digit that causes
3071 the value to exceed the limit. */
3072 const char *werange
= NULL
;
3073 const char *perange
= NULL
;
3075 /* Width specified via the asterisk. Need not be INTEGER_CST.
3076 For vararg functions set to void_node. */
3077 tree star_width
= NULL_TREE
;
3079 /* Width specified via the asterisk. Need not be INTEGER_CST.
3080 For vararg functions set to void_node. */
3081 tree star_precision
= NULL_TREE
;
3083 if (ISDIGIT (target_to_host (*pf
)))
3085 /* This could be either a POSIX positional argument, the '0'
3086 flag, or a width, depending on what follows. Store it as
3087 width and sort it out later after the next character has
3090 width
= target_strtol10 (&pf
, &werange
);
3092 else if (target_to_host (*pf
) == '*')
3094 /* Similarly to the block above, this could be either a POSIX
3095 positional argument or a width, depending on what follows. */
3096 if (*argno
< gimple_call_num_args (info
.callstmt
))
3097 star_width
= gimple_call_arg (info
.callstmt
, (*argno
)++);
3099 star_width
= void_node
;
3103 if (target_to_host (*pf
) == '$')
3105 /* Handle the POSIX dollar sign which references the 1-based
3106 positional argument number. */
3108 dollar
= width
+ info
.argidx
;
3110 && TREE_CODE (star_width
) == INTEGER_CST
3111 && (TYPE_PRECISION (TREE_TYPE (star_width
))
3112 <= TYPE_PRECISION (integer_type_node
)))
3113 dollar
= width
+ tree_to_shwi (star_width
);
3115 /* Bail when the numbered argument is out of range (it will
3116 have already been diagnosed by -Wformat). */
3118 || dollar
== (int)info
.argidx
3119 || dollar
> gimple_call_num_args (info
.callstmt
))
3124 star_width
= NULL_TREE
;
3129 if (dollar
|| !star_width
)
3135 /* The '0' that has been interpreted as a width above is
3136 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3137 and continue processing other flags. */
3143 /* (Non-zero) width has been seen. The next character
3144 is either a period or a digit. */
3145 goto start_precision
;
3148 /* When either '$' has been seen, or width has not been seen,
3149 the next field is the optional flags followed by an optional
3152 switch (target_to_host (*pf
))
3159 dir
.set_flag (target_to_host (*pf
++));
3168 if (ISDIGIT (target_to_host (*pf
)))
3172 width
= target_strtol10 (&pf
, &werange
);
3174 else if (target_to_host (*pf
) == '*')
3176 if (*argno
< gimple_call_num_args (info
.callstmt
))
3177 star_width
= gimple_call_arg (info
.callstmt
, (*argno
)++);
3180 /* This is (likely) a va_list. It could also be an invalid
3181 call with insufficient arguments. */
3182 star_width
= void_node
;
3186 else if (target_to_host (*pf
) == '\'')
3188 /* The POSIX apostrophe indicating a numeric grouping
3189 in the current locale. Even though it's possible to
3190 estimate the upper bound on the size of the output
3191 based on the number of digits it probably isn't worth
3198 if (target_to_host (*pf
) == '.')
3202 if (ISDIGIT (target_to_host (*pf
)))
3205 precision
= target_strtol10 (&pf
, &perange
);
3207 else if (target_to_host (*pf
) == '*')
3209 if (*argno
< gimple_call_num_args (info
.callstmt
))
3210 star_precision
= gimple_call_arg (info
.callstmt
, (*argno
)++);
3213 /* This is (likely) a va_list. It could also be an invalid
3214 call with insufficient arguments. */
3215 star_precision
= void_node
;
3221 /* The decimal precision or the asterisk are optional.
3222 When neither is dirified it's taken to be zero. */
3227 switch (target_to_host (*pf
))
3230 if (target_to_host (pf
[1]) == 'h')
3233 dir
.modifier
= FMT_LEN_hh
;
3236 dir
.modifier
= FMT_LEN_h
;
3241 dir
.modifier
= FMT_LEN_j
;
3246 dir
.modifier
= FMT_LEN_L
;
3251 if (target_to_host (pf
[1]) == 'l')
3254 dir
.modifier
= FMT_LEN_ll
;
3257 dir
.modifier
= FMT_LEN_l
;
3262 dir
.modifier
= FMT_LEN_t
;
3267 dir
.modifier
= FMT_LEN_z
;
3272 switch (target_to_host (*pf
))
3274 /* Handle a sole '%' character the same as "%%" but since it's
3275 undefined prevent the result from being folded. */
3278 res
->range
.min
= res
->range
.max
= HOST_WIDE_INT_M1U
;
3281 dir
.fmtfunc
= format_percent
;
3292 res
->floating
= true;
3293 dir
.fmtfunc
= format_floating
;
3302 dir
.fmtfunc
= format_integer
;
3306 /* The %p output is implementation-defined. It's possible
3307 to determine this format but due to extensions (edirially
3308 those of the Linux kernel -- see bug 78512) the first %p
3309 in the format string disables any further processing. */
3313 /* %n has side-effects even when nothing is actually printed to
3315 info
.nowrite
= false;
3316 dir
.fmtfunc
= format_none
;
3320 dir
.fmtfunc
= format_character
;
3325 dir
.fmtfunc
= format_string
;
3329 /* Unknown conversion specification. */
3333 dir
.specifier
= target_to_host (*pf
++);
3335 /* Store the length of the format directive. */
3336 dir
.len
= pf
- pcnt
;
3338 /* Buffer for the directive in the host character set (used when
3339 the source character set is different). */
3344 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width
)))
3345 dir
.set_width (star_width
, vr_values
);
3348 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3349 (width is the absolute value of that specified). */
3351 dir
.width
[1] = target_int_max () + 1;
3356 if (width
== LONG_MAX
&& werange
)
3358 size_t begin
= dir
.beg
- info
.fmtstr
+ (pwidth
- pcnt
);
3359 size_t caret
= begin
+ (werange
- pcnt
);
3360 size_t end
= pf
- info
.fmtstr
- 1;
3362 /* Create a location for the width part of the directive,
3363 pointing the caret at the first out-of-range digit. */
3364 substring_loc
dirloc (info
.fmtloc
, TREE_TYPE (info
.format
),
3367 fmtwarn (dirloc
, UNKNOWN_LOCATION
, NULL
, info
.warnopt (),
3368 "%<%.*s%> directive width out of range", (int) dir
.len
,
3369 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
));
3372 dir
.set_width (width
);
3377 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision
)))
3378 dir
.set_precision (star_precision
, vr_values
);
3381 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3382 (unlike width, negative precision is ignored). */
3384 dir
.prec
[1] = target_int_max ();
3389 if (precision
== LONG_MAX
&& perange
)
3391 size_t begin
= dir
.beg
- info
.fmtstr
+ (pprec
- pcnt
) - 1;
3392 size_t caret
= dir
.beg
- info
.fmtstr
+ (perange
- pcnt
) - 1;
3393 size_t end
= pf
- info
.fmtstr
- 2;
3395 /* Create a location for the precision part of the directive,
3396 including the leading period, pointing the caret at the first
3397 out-of-range digit . */
3398 substring_loc
dirloc (info
.fmtloc
, TREE_TYPE (info
.format
),
3401 fmtwarn (dirloc
, UNKNOWN_LOCATION
, NULL
, info
.warnopt (),
3402 "%<%.*s%> directive precision out of range", (int) dir
.len
,
3403 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
));
3406 dir
.set_precision (precision
);
3409 /* Extract the argument if the directive takes one and if it's
3410 available (e.g., the function doesn't take a va_list). Treat
3411 missing arguments the same as va_list, even though they will
3412 have likely already been diagnosed by -Wformat. */
3413 if (dir
.specifier
!= '%'
3414 && *argno
< gimple_call_num_args (info
.callstmt
))
3415 dir
.arg
= gimple_call_arg (info
.callstmt
, dollar
? dollar
: (*argno
)++);
3420 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3423 (unsigned HOST_WIDE_INT
)(size_t)(dir
.beg
- info
.fmtstr
),
3424 (int)dir
.len
, dir
.beg
);
3427 if (dir
.width
[0] == dir
.width
[1])
3428 fprintf (dump_file
, ", width = " HOST_WIDE_INT_PRINT_DEC
,
3432 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3433 ", " HOST_WIDE_INT_PRINT_DEC
"]",
3434 dir
.width
[0], dir
.width
[1]);
3439 if (dir
.prec
[0] == dir
.prec
[1])
3440 fprintf (dump_file
, ", precision = " HOST_WIDE_INT_PRINT_DEC
,
3444 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3445 HOST_WIDE_INT_PRINT_DEC
"]",
3446 dir
.prec
[0], dir
.prec
[1]);
3448 fputc ('\n', dump_file
);
3454 /* Compute the length of the output resulting from the call to a formatted
3455 output function described by INFO and store the result of the call in
3456 *RES. Issue warnings for detected past the end writes. Return true
3457 if the complete format string has been processed and *RES can be relied
3458 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3459 that caused the processing to be terminated early). */
3462 sprintf_dom_walker::compute_format_length (call_info
&info
,
3467 location_t callloc
= gimple_location (info
.callstmt
);
3468 fprintf (dump_file
, "%s:%i: ",
3469 LOCATION_FILE (callloc
), LOCATION_LINE (callloc
));
3470 print_generic_expr (dump_file
, info
.func
, dump_flags
);
3473 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3474 ", fmtstr = \"%s\"\n",
3475 info
.objsize
, info
.fmtstr
);
3478 /* Reset the minimum and maximum byte counters. */
3479 res
->range
.min
= res
->range
.max
= 0;
3481 /* No directive has been seen yet so the length of output is bounded
3482 by the known range [0, 0] (with no conversion producing more than
3483 4K bytes) until determined otherwise. */
3484 res
->knownrange
= true;
3485 res
->under4k
= true;
3486 res
->floating
= false;
3487 res
->warned
= false;
3489 /* 1-based directive counter. */
3492 /* The variadic argument counter. */
3493 unsigned argno
= info
.argidx
;
3495 for (const char *pf
= info
.fmtstr
; ; ++dirno
)
3497 directive dir
= directive ();
3500 size_t n
= parse_directive (info
, dir
, res
, pf
, &argno
,
3501 evrp_range_analyzer
.get_vr_values ());
3503 /* Return failure if the format function fails. */
3504 if (!format_directive (info
, res
, dir
,
3505 evrp_range_analyzer
.get_vr_values ()))
3508 /* Return success the directive is zero bytes long and it's
3509 the last think in the format string (i.e., it's the terminating
3510 nul, which isn't really a directive but handling it as one makes
3518 /* The complete format string was processed (with or without warnings). */
3522 /* Return the size of the object referenced by the expression DEST if
3523 available, or -1 otherwise. */
3525 static unsigned HOST_WIDE_INT
3526 get_destination_size (tree dest
)
3528 /* Initialize object size info before trying to compute it. */
3529 init_object_sizes ();
3531 /* Use __builtin_object_size to determine the size of the destination
3532 object. When optimizing, determine the smallest object (such as
3533 a member array as opposed to the whole enclosing object), otherwise
3534 use type-zero object size to determine the size of the enclosing
3535 object (the function fails without optimization in this type). */
3536 int ost
= optimize
> 0;
3537 unsigned HOST_WIDE_INT size
;
3538 if (compute_builtin_object_size (dest
, ost
, &size
))
3541 return HOST_WIDE_INT_M1U
;
3544 /* Return true if the call described by INFO with result RES safe to
3545 optimize (i.e., no undefined behavior), and set RETVAL to the range
3546 of its return values. */
3549 is_call_safe (const sprintf_dom_walker::call_info
&info
,
3550 const format_result
&res
, bool under4k
,
3551 unsigned HOST_WIDE_INT retval
[2])
3553 if (under4k
&& !res
.under4k
)
3556 /* The minimum return value. */
3557 retval
[0] = res
.range
.min
;
3559 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3560 but in cases involving multibyte characters could be as large as
3561 RES.RANGE.UNLIKELY. */
3563 = res
.range
.unlikely
< res
.range
.max
? res
.range
.max
: res
.range
.unlikely
;
3565 /* Adjust the number of bytes which includes the terminating nul
3566 to reflect the return value of the function which does not.
3567 Because the valid range of the function is [INT_MIN, INT_MAX],
3568 a valid range before the adjustment below is [0, INT_MAX + 1]
3569 (the functions only return negative values on error or undefined
3571 if (retval
[0] <= target_int_max () + 1)
3573 if (retval
[1] <= target_int_max () + 1)
3576 /* Avoid the return value optimization when the behavior of the call
3577 is undefined either because any directive may have produced 4K or
3578 more of output, or the return value exceeds INT_MAX, or because
3579 the output overflows the destination object (but leave it enabled
3580 when the function is bounded because then the behavior is well-
3582 if (retval
[0] == retval
[1]
3583 && (info
.bounded
|| retval
[0] < info
.objsize
)
3584 && retval
[0] <= target_int_max ())
3587 if ((info
.bounded
|| retval
[1] < info
.objsize
)
3588 && (retval
[0] < target_int_max ()
3589 && retval
[1] < target_int_max ()))
3592 if (!under4k
&& (info
.bounded
|| retval
[0] < info
.objsize
))
3598 /* Given a suitable result RES of a call to a formatted output function
3599 described by INFO, substitute the result for the return value of
3600 the call. The result is suitable if the number of bytes it represents
3601 is known and exact. A result that isn't suitable for substitution may
3602 have its range set to the range of return values, if that is known.
3603 Return true if the call is removed and gsi_next should not be performed
3607 try_substitute_return_value (gimple_stmt_iterator
*gsi
,
3608 const sprintf_dom_walker::call_info
&info
,
3609 const format_result
&res
)
3611 tree lhs
= gimple_get_lhs (info
.callstmt
);
3613 /* Set to true when the entire call has been removed. */
3614 bool removed
= false;
3616 /* The minimum and maximum return value. */
3617 unsigned HOST_WIDE_INT retval
[2];
3618 bool safe
= is_call_safe (info
, res
, true, retval
);
3621 && retval
[0] == retval
[1]
3622 /* Not prepared to handle possibly throwing calls here; they shouldn't
3623 appear in non-artificial testcases, except when the __*_chk routines
3624 are badly declared. */
3625 && !stmt_ends_bb_p (info
.callstmt
))
3627 tree cst
= build_int_cst (integer_type_node
, retval
[0]);
3629 if (lhs
== NULL_TREE
3632 /* Remove the call to the bounded function with a zero size
3633 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3634 unlink_stmt_vdef (info
.callstmt
);
3635 gsi_remove (gsi
, true);
3638 else if (info
.nowrite
)
3640 /* Replace the call to the bounded function with a zero size
3641 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3643 if (!update_call_from_tree (gsi
, cst
))
3644 gimplify_and_update_call_from_tree (gsi
, cst
);
3645 gimple
*callstmt
= gsi_stmt (*gsi
);
3646 update_stmt (callstmt
);
3650 /* Replace the left-hand side of the call with the constant
3651 result of the formatted function. */
3652 gimple_call_set_lhs (info
.callstmt
, NULL_TREE
);
3653 gimple
*g
= gimple_build_assign (lhs
, cst
);
3654 gsi_insert_after (gsi
, g
, GSI_NEW_STMT
);
3655 update_stmt (info
.callstmt
);
3661 fprintf (dump_file
, " Removing call statement.");
3664 fprintf (dump_file
, " Substituting ");
3665 print_generic_expr (dump_file
, cst
, dump_flags
);
3666 fprintf (dump_file
, " for %s.\n",
3667 info
.nowrite
? "statement" : "return value");
3673 bool setrange
= false;
3676 && (info
.bounded
|| retval
[1] < info
.objsize
)
3677 && (retval
[0] < target_int_max ()
3678 && retval
[1] < target_int_max ()))
3680 /* If the result is in a valid range bounded by the size of
3681 the destination set it so that it can be used for subsequent
3683 int prec
= TYPE_PRECISION (integer_type_node
);
3685 wide_int min
= wi::shwi (retval
[0], prec
);
3686 wide_int max
= wi::shwi (retval
[1], prec
);
3687 set_range_info (lhs
, VR_RANGE
, min
, max
);
3694 const char *inbounds
3695 = (retval
[0] < info
.objsize
3696 ? (retval
[1] < info
.objsize
3697 ? "in" : "potentially out-of")
3700 const char *what
= setrange
? "Setting" : "Discarding";
3701 if (retval
[0] != retval
[1])
3703 " %s %s-bounds return value range ["
3704 HOST_WIDE_INT_PRINT_UNSIGNED
", "
3705 HOST_WIDE_INT_PRINT_UNSIGNED
"].\n",
3706 what
, inbounds
, retval
[0], retval
[1]);
3708 fprintf (dump_file
, " %s %s-bounds return value "
3709 HOST_WIDE_INT_PRINT_UNSIGNED
".\n",
3710 what
, inbounds
, retval
[0]);
3715 fputc ('\n', dump_file
);
3720 /* Try to simplify a s{,n}printf call described by INFO with result
3721 RES by replacing it with a simpler and presumably more efficient
3722 call (such as strcpy). */
3725 try_simplify_call (gimple_stmt_iterator
*gsi
,
3726 const sprintf_dom_walker::call_info
&info
,
3727 const format_result
&res
)
3729 unsigned HOST_WIDE_INT dummy
[2];
3730 if (!is_call_safe (info
, res
, info
.retval_used (), dummy
))
3733 switch (info
.fncode
)
3735 case BUILT_IN_SNPRINTF
:
3736 return gimple_fold_builtin_snprintf (gsi
);
3738 case BUILT_IN_SPRINTF
:
3739 return gimple_fold_builtin_sprintf (gsi
);
3748 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3749 functions and if so, handle it. Return true if the call is removed
3750 and gsi_next should not be performed in the caller. */
3753 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator
*gsi
)
3755 call_info info
= call_info ();
3757 info
.callstmt
= gsi_stmt (*gsi
);
3758 if (!gimple_call_builtin_p (info
.callstmt
, BUILT_IN_NORMAL
))
3761 info
.func
= gimple_call_fndecl (info
.callstmt
);
3762 info
.fncode
= DECL_FUNCTION_CODE (info
.func
);
3764 /* The size of the destination as in snprintf(dest, size, ...). */
3765 unsigned HOST_WIDE_INT dstsize
= HOST_WIDE_INT_M1U
;
3767 /* The size of the destination determined by __builtin_object_size. */
3768 unsigned HOST_WIDE_INT objsize
= HOST_WIDE_INT_M1U
;
3770 /* Buffer size argument number (snprintf and vsnprintf). */
3771 unsigned HOST_WIDE_INT idx_dstsize
= HOST_WIDE_INT_M1U
;
3773 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3774 unsigned HOST_WIDE_INT idx_objsize
= HOST_WIDE_INT_M1U
;
3776 /* Format string argument number (valid for all functions). */
3777 unsigned idx_format
;
3779 switch (info
.fncode
)
3781 case BUILT_IN_SPRINTF
:
3783 // __builtin_sprintf (dst, format, ...)
3788 case BUILT_IN_SPRINTF_CHK
:
3790 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3796 case BUILT_IN_SNPRINTF
:
3798 // __builtin_snprintf (dst, size, format, ...)
3802 info
.bounded
= true;
3805 case BUILT_IN_SNPRINTF_CHK
:
3807 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3812 info
.bounded
= true;
3815 case BUILT_IN_VSNPRINTF
:
3817 // __builtin_vsprintf (dst, size, format, va)
3821 info
.bounded
= true;
3824 case BUILT_IN_VSNPRINTF_CHK
:
3826 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3831 info
.bounded
= true;
3834 case BUILT_IN_VSPRINTF
:
3836 // __builtin_vsprintf (dst, format, va)
3841 case BUILT_IN_VSPRINTF_CHK
:
3843 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3853 /* Set the global warning level for this function. */
3854 warn_level
= info
.bounded
? warn_format_trunc
: warn_format_overflow
;
3856 /* The first argument is a pointer to the destination. */
3857 tree dstptr
= gimple_call_arg (info
.callstmt
, 0);
3859 info
.format
= gimple_call_arg (info
.callstmt
, idx_format
);
3861 /* True when the destination size is constant as opposed to the lower
3862 or upper bound of a range. */
3863 bool dstsize_cst_p
= true;
3865 if (idx_dstsize
== HOST_WIDE_INT_M1U
)
3867 /* For non-bounded functions like sprintf, determine the size
3868 of the destination from the object or pointer passed to it
3869 as the first argument. */
3870 dstsize
= get_destination_size (dstptr
);
3872 else if (tree size
= gimple_call_arg (info
.callstmt
, idx_dstsize
))
3874 /* For bounded functions try to get the size argument. */
3876 if (TREE_CODE (size
) == INTEGER_CST
)
3878 dstsize
= tree_to_uhwi (size
);
3879 /* No object can be larger than SIZE_MAX bytes (half the address
3880 space) on the target.
3881 The functions are defined only for output of at most INT_MAX
3882 bytes. Specifying a bound in excess of that limit effectively
3883 defeats the bounds checking (and on some implementations such
3884 as Solaris cause the function to fail with EINVAL). */
3885 if (dstsize
> target_size_max () / 2)
3887 /* Avoid warning if -Wstringop-overflow is specified since
3888 it also warns for the same thing though only for the
3889 checking built-ins. */
3890 if ((idx_objsize
== HOST_WIDE_INT_M1U
3891 || !warn_stringop_overflow
))
3892 warning_at (gimple_location (info
.callstmt
), info
.warnopt (),
3893 "specified bound %wu exceeds maximum object size "
3895 dstsize
, target_size_max () / 2);
3897 else if (dstsize
> target_int_max ())
3898 warning_at (gimple_location (info
.callstmt
), info
.warnopt (),
3899 "specified bound %wu exceeds %<INT_MAX%>",
3902 else if (TREE_CODE (size
) == SSA_NAME
)
3904 /* Try to determine the range of values of the argument
3905 and use the greater of the two at level 1 and the smaller
3906 of them at level 2. */
3907 value_range
*vr
= evrp_range_analyzer
.get_value_range (size
);
3908 if (vr
->type
== VR_RANGE
3909 && TREE_CODE (vr
->min
) == INTEGER_CST
3910 && TREE_CODE (vr
->max
) == INTEGER_CST
)
3911 dstsize
= (warn_level
< 2
3912 ? TREE_INT_CST_LOW (vr
->max
)
3913 : TREE_INT_CST_LOW (vr
->min
));
3915 /* The destination size is not constant. If the function is
3916 bounded (e.g., snprintf) a lower bound of zero doesn't
3917 necessarily imply it can be eliminated. */
3918 dstsize_cst_p
= false;
3922 if (idx_objsize
!= HOST_WIDE_INT_M1U
)
3923 if (tree size
= gimple_call_arg (info
.callstmt
, idx_objsize
))
3924 if (tree_fits_uhwi_p (size
))
3925 objsize
= tree_to_uhwi (size
);
3927 if (info
.bounded
&& !dstsize
)
3929 /* As a special case, when the explicitly specified destination
3930 size argument (to a bounded function like snprintf) is zero
3931 it is a request to determine the number of bytes on output
3932 without actually producing any. Pretend the size is
3933 unlimited in this case. */
3934 info
.objsize
= HOST_WIDE_INT_MAX
;
3935 info
.nowrite
= dstsize_cst_p
;
3939 /* For calls to non-bounded functions or to those of bounded
3940 functions with a non-zero size, warn if the destination
3942 if (integer_zerop (dstptr
))
3944 /* This is diagnosed with -Wformat only when the null is a constant
3945 pointer. The warning here diagnoses instances where the pointer
3947 location_t loc
= gimple_location (info
.callstmt
);
3948 warning_at (EXPR_LOC_OR_LOC (dstptr
, loc
),
3949 info
.warnopt (), "null destination pointer");
3953 /* Set the object size to the smaller of the two arguments
3954 of both have been specified and they're not equal. */
3955 info
.objsize
= dstsize
< objsize
? dstsize
: objsize
;
3958 && dstsize
< target_size_max () / 2 && objsize
< dstsize
3959 /* Avoid warning if -Wstringop-overflow is specified since
3960 it also warns for the same thing though only for the
3961 checking built-ins. */
3962 && (idx_objsize
== HOST_WIDE_INT_M1U
3963 || !warn_stringop_overflow
))
3965 warning_at (gimple_location (info
.callstmt
), info
.warnopt (),
3966 "specified bound %wu exceeds the size %wu "
3967 "of the destination object", dstsize
, objsize
);
3971 if (integer_zerop (info
.format
))
3973 /* This is diagnosed with -Wformat only when the null is a constant
3974 pointer. The warning here diagnoses instances where the pointer
3976 location_t loc
= gimple_location (info
.callstmt
);
3977 warning_at (EXPR_LOC_OR_LOC (info
.format
, loc
),
3978 info
.warnopt (), "null format string");
3982 info
.fmtstr
= get_format_string (info
.format
, &info
.fmtloc
);
3986 /* The result is the number of bytes output by the formatted function,
3987 including the terminating NUL. */
3988 format_result res
= format_result ();
3990 bool success
= compute_format_length (info
, &res
);
3992 /* When optimizing and the printf return value optimization is enabled,
3993 attempt to substitute the computed result for the return value of
3994 the call. Avoid this optimization when -frounding-math is in effect
3995 and the format string contains a floating point directive. */
3996 bool call_removed
= false;
3997 if (success
&& optimize
> 0)
3999 /* Save a copy of the iterator pointing at the call. The iterator
4000 may change to point past the call in try_substitute_return_value
4001 but the original value is needed in try_simplify_call. */
4002 gimple_stmt_iterator gsi_call
= *gsi
;
4004 if (flag_printf_return_value
4005 && (!flag_rounding_math
|| !res
.floating
))
4006 call_removed
= try_substitute_return_value (gsi
, info
, res
);
4009 try_simplify_call (&gsi_call
, info
, res
);
4012 return call_removed
;
4016 sprintf_dom_walker::before_dom_children (basic_block bb
)
4018 evrp_range_analyzer
.enter (bb
);
4019 for (gimple_stmt_iterator si
= gsi_start_bb (bb
); !gsi_end_p (si
); )
4021 /* Iterate over statements, looking for function calls. */
4022 gimple
*stmt
= gsi_stmt (si
);
4024 /* First record ranges generated by this statement. */
4025 evrp_range_analyzer
.record_ranges_from_stmt (stmt
, false);
4027 if (is_gimple_call (stmt
) && handle_gimple_call (&si
))
4028 /* If handle_gimple_call returns true, the iterator is
4029 already pointing to the next statement. */
4038 sprintf_dom_walker::after_dom_children (basic_block bb
)
4040 evrp_range_analyzer
.leave (bb
);
4043 /* Execute the pass for function FUN. */
4046 pass_sprintf_length::execute (function
*fun
)
4048 init_target_to_host_charmap ();
4050 calculate_dominance_info (CDI_DOMINATORS
);
4052 sprintf_dom_walker sprintf_dom_walker
;
4053 sprintf_dom_walker
.walk (ENTRY_BLOCK_PTR_FOR_FN (fun
));
4055 /* Clean up object size info. */
4056 fini_object_sizes ();
4060 } /* Unnamed namespace. */
4062 /* Return a pointer to a pass object newly constructed from the context
4066 make_pass_sprintf_length (gcc::context
*ctxt
)
4068 return new pass_sprintf_length (ctxt
);