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 /* The format_warning_at_substring function is not used here in a way
593 that makes using attribute format viable. Suppress the warning. */
595 #pragma GCC diagnostic push
596 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
598 /* For convenience and brevity. */
601 (* const fmtwarn
) (const substring_loc
&, location_t
,
602 const char *, int, const char *, ...)
603 = format_warning_at_substring
;
605 /* Format length modifiers. */
610 FMT_LEN_hh
, // char argument
613 FMT_LEN_ll
, // long long
614 FMT_LEN_L
, // long double (and GNU long long)
616 FMT_LEN_t
, // ptrdiff_t
617 FMT_LEN_j
// intmax_t
621 /* Description of the result of conversion either of a single directive
622 or the whole format string. */
626 /* Construct a FMTRESULT object with all counters initialized
627 to MIN. KNOWNRANGE is set when MIN is valid. */
628 fmtresult (unsigned HOST_WIDE_INT min
= HOST_WIDE_INT_MAX
)
629 : argmin (), argmax (),
630 knownrange (min
< HOST_WIDE_INT_MAX
),
636 range
.unlikely
= min
;
639 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
640 KNOWNRANGE is set when both MIN and MAX are valid. */
641 fmtresult (unsigned HOST_WIDE_INT min
, unsigned HOST_WIDE_INT max
,
642 unsigned HOST_WIDE_INT likely
= HOST_WIDE_INT_MAX
)
643 : argmin (), argmax (),
644 knownrange (min
< HOST_WIDE_INT_MAX
&& max
< HOST_WIDE_INT_MAX
),
649 range
.likely
= max
< likely
? min
: likely
;
650 range
.unlikely
= max
;
653 /* Adjust result upward to reflect the RANGE of values the specified
654 width or precision is known to be in. */
655 fmtresult
& adjust_for_width_or_precision (const HOST_WIDE_INT
[2],
657 unsigned = 0, unsigned = 0);
659 /* Return the maximum number of decimal digits a value of TYPE
660 formats as on output. */
661 static unsigned type_max_digits (tree
, int);
663 /* The range a directive's argument is in. */
666 /* The minimum and maximum number of bytes that a directive
667 results in on output for an argument in the range above. */
670 /* True when the range above is obtained from a known value of
671 a directive's argument or its bounds and not the result of
672 heuristics that depend on warning levels. */
675 /* True when the argument is a null pointer. */
679 /* Adjust result upward to reflect the range ADJUST of values the
680 specified width or precision is known to be in. When non-null,
681 TYPE denotes the type of the directive whose result is being
682 adjusted, BASE gives the base of the directive (octal, decimal,
683 or hex), and ADJ denotes the additional adjustment to the LIKELY
684 counter that may need to be added when ADJUST is a range. */
687 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust
[2],
688 tree type
/* = NULL_TREE */,
689 unsigned base
/* = 0 */,
690 unsigned adj
/* = 0 */)
692 bool minadjusted
= false;
694 /* Adjust the minimum and likely counters. */
697 if (range
.min
< (unsigned HOST_WIDE_INT
)adjust
[0])
699 range
.min
= adjust
[0];
703 /* Adjust the likely counter. */
704 if (range
.likely
< range
.min
)
705 range
.likely
= range
.min
;
707 else if (adjust
[0] == target_int_min ()
708 && (unsigned HOST_WIDE_INT
)adjust
[1] == target_int_max ())
711 /* Adjust the maximum counter. */
714 if (range
.max
< (unsigned HOST_WIDE_INT
)adjust
[1])
716 range
.max
= adjust
[1];
718 /* Set KNOWNRANGE if both the minimum and maximum have been
719 adjusted. Otherwise leave it at what it was before. */
720 knownrange
= minadjusted
;
724 if (warn_level
> 1 && type
)
726 /* For large non-constant width or precision whose range spans
727 the maximum number of digits produced by the directive for
728 any argument, set the likely number of bytes to be at most
729 the number digits plus other adjustment determined by the
730 caller (one for sign or two for the hexadecimal "0x"
732 unsigned dirdigs
= type_max_digits (type
, base
);
733 if (adjust
[0] < dirdigs
&& dirdigs
< adjust
[1]
734 && range
.likely
< dirdigs
)
735 range
.likely
= dirdigs
+ adj
;
737 else if (range
.likely
< (range
.min
? range
.min
: 1))
739 /* Conservatively, set LIKELY to at least MIN but no less than
740 1 unless MAX is zero. */
741 range
.likely
= (range
.min
743 : range
.max
&& (range
.max
< HOST_WIDE_INT_MAX
744 || warn_level
> 1) ? 1 : 0);
747 /* Finally adjust the unlikely counter to be at least as large as
749 if (range
.unlikely
< range
.max
)
750 range
.unlikely
= range
.max
;
755 /* Return the maximum number of digits a value of TYPE formats in
756 BASE on output, not counting base prefix . */
759 fmtresult::type_max_digits (tree type
, int base
)
761 unsigned prec
= TYPE_PRECISION (type
);
763 return (prec
+ 2) / 3;
768 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
769 of 8, 16, 32, and 64 bits. */
770 return prec
* 301 / 1000 + 1;
774 get_int_range (tree
, HOST_WIDE_INT
*, HOST_WIDE_INT
*, bool, HOST_WIDE_INT
);
776 /* Description of a format directive. A directive is either a plain
777 string or a conversion specification that starts with '%'. */
781 /* The 1-based directive number (for debugging). */
784 /* The first character of the directive and its length. */
788 /* A bitmap of flags, one for each character. */
789 unsigned flags
[256 / sizeof (int)];
791 /* The range of values of the specified width, or -1 if not specified. */
792 HOST_WIDE_INT width
[2];
793 /* The range of values of the specified precision, or -1 if not
795 HOST_WIDE_INT prec
[2];
797 /* Length modifier. */
798 format_lengths modifier
;
800 /* Format specifier character. */
803 /* The argument of the directive or null when the directive doesn't
804 take one or when none is available (such as for vararg functions). */
807 /* Format conversion function that given a directive and an argument
808 returns the formatting result. */
809 fmtresult (*fmtfunc
) (const directive
&, tree
);
811 /* Return True when a the format flag CHR has been used. */
812 bool get_flag (char chr
) const
814 unsigned char c
= chr
& 0xff;
815 return (flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
816 & (1U << (c
% (CHAR_BIT
* sizeof *flags
))));
819 /* Make a record of the format flag CHR having been used. */
820 void set_flag (char chr
)
822 unsigned char c
= chr
& 0xff;
823 flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
824 |= (1U << (c
% (CHAR_BIT
* sizeof *flags
)));
827 /* Reset the format flag CHR. */
828 void clear_flag (char chr
)
830 unsigned char c
= chr
& 0xff;
831 flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
832 &= ~(1U << (c
% (CHAR_BIT
* sizeof *flags
)));
835 /* Set both bounds of the width range to VAL. */
836 void set_width (HOST_WIDE_INT val
)
838 width
[0] = width
[1] = val
;
841 /* Set the width range according to ARG, with both bounds being
842 no less than 0. For a constant ARG set both bounds to its value
843 or 0, whichever is greater. For a non-constant ARG in some range
844 set width to its range adjusting each bound to -1 if it's less.
845 For an indeterminate ARG set width to [0, INT_MAX]. */
846 void set_width (tree arg
)
848 get_int_range (arg
, width
, width
+ 1, true, 0);
851 /* Set both bounds of the precision range to VAL. */
852 void set_precision (HOST_WIDE_INT val
)
854 prec
[0] = prec
[1] = val
;
857 /* Set the precision range according to ARG, with both bounds being
858 no less than -1. For a constant ARG set both bounds to its value
859 or -1 whichever is greater. For a non-constant ARG in some range
860 set precision to its range adjusting each bound to -1 if it's less.
861 For an indeterminate ARG set precision to [-1, INT_MAX]. */
862 void set_precision (tree arg
)
864 get_int_range (arg
, prec
, prec
+ 1, false, -1);
867 /* Return true if both width and precision are known to be
868 either constant or in some range, false otherwise. */
869 bool known_width_and_precision () const
871 return ((width
[1] < 0
872 || (unsigned HOST_WIDE_INT
)width
[1] <= target_int_max ())
874 || (unsigned HOST_WIDE_INT
)prec
[1] < target_int_max ()));
878 /* Return the logarithm of X in BASE. */
881 ilog (unsigned HOST_WIDE_INT x
, int base
)
892 /* Return the number of bytes resulting from converting into a string
893 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
894 PLUS indicates whether 1 for a plus sign should be added for positive
895 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
896 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
900 tree_digits (tree x
, int base
, HOST_WIDE_INT prec
, bool plus
, bool prefix
)
902 unsigned HOST_WIDE_INT absval
;
906 if (TYPE_UNSIGNED (TREE_TYPE (x
)))
908 if (tree_fits_uhwi_p (x
))
910 absval
= tree_to_uhwi (x
);
918 if (tree_fits_shwi_p (x
))
920 HOST_WIDE_INT i
= tree_to_shwi (x
);
921 if (HOST_WIDE_INT_MIN
== i
)
923 /* Avoid undefined behavior due to negating a minimum. */
924 absval
= HOST_WIDE_INT_MAX
;
942 int ndigs
= ilog (absval
, base
);
944 res
+= prec
< ndigs
? ndigs
: prec
;
946 /* Adjust a non-zero value for the base prefix, either hexadecimal,
947 or, unless precision has resulted in a leading zero, also octal. */
948 if (prefix
&& absval
&& (base
== 16 || prec
<= ndigs
))
959 /* Given the formatting result described by RES and NAVAIL, the number
960 of available in the destination, return the range of bytes remaining
961 in the destination. */
963 static inline result_range
964 bytes_remaining (unsigned HOST_WIDE_INT navail
, const format_result
&res
)
968 if (HOST_WIDE_INT_MAX
<= navail
)
970 range
.min
= range
.max
= range
.likely
= range
.unlikely
= navail
;
974 /* The lower bound of the available range is the available size
975 minus the maximum output size, and the upper bound is the size
976 minus the minimum. */
977 range
.max
= res
.range
.min
< navail
? navail
- res
.range
.min
: 0;
979 range
.likely
= res
.range
.likely
< navail
? navail
- res
.range
.likely
: 0;
981 if (res
.range
.max
< HOST_WIDE_INT_MAX
)
982 range
.min
= res
.range
.max
< navail
? navail
- res
.range
.max
: 0;
984 range
.min
= range
.likely
;
986 range
.unlikely
= (res
.range
.unlikely
< navail
987 ? navail
- res
.range
.unlikely
: 0);
992 /* Description of a call to a formatted function. */
994 struct sprintf_dom_walker::call_info
996 /* Function call statement. */
999 /* Function called. */
1002 /* Called built-in function code. */
1003 built_in_function fncode
;
1005 /* Format argument and format string extracted from it. */
1009 /* The location of the format argument. */
1012 /* The destination object size for __builtin___xxx_chk functions
1013 typically determined by __builtin_object_size, or -1 if unknown. */
1014 unsigned HOST_WIDE_INT objsize
;
1016 /* Number of the first variable argument. */
1017 unsigned HOST_WIDE_INT argidx
;
1019 /* True for functions like snprintf that specify the size of
1020 the destination, false for others like sprintf that don't. */
1023 /* True for bounded functions like snprintf that specify a zero-size
1024 buffer as a request to compute the size of output without actually
1025 writing any. NOWRITE is cleared in response to the %n directive
1026 which has side-effects similar to writing output. */
1029 /* Return true if the called function's return value is used. */
1030 bool retval_used () const
1032 return gimple_get_lhs (callstmt
);
1035 /* Return the warning option corresponding to the called function. */
1036 int warnopt () const
1038 return bounded
? OPT_Wformat_truncation_
: OPT_Wformat_overflow_
;
1042 /* Return the result of formatting a no-op directive (such as '%n'). */
1045 format_none (const directive
&, tree
)
1051 /* Return the result of formatting the '%%' directive. */
1054 format_percent (const directive
&, tree
)
1061 /* Compute intmax_type_node and uintmax_type_node similarly to how
1062 tree.c builds size_type_node. */
1065 build_intmax_type_nodes (tree
*pintmax
, tree
*puintmax
)
1067 if (strcmp (UINTMAX_TYPE
, "unsigned int") == 0)
1069 *pintmax
= integer_type_node
;
1070 *puintmax
= unsigned_type_node
;
1072 else if (strcmp (UINTMAX_TYPE
, "long unsigned int") == 0)
1074 *pintmax
= long_integer_type_node
;
1075 *puintmax
= long_unsigned_type_node
;
1077 else if (strcmp (UINTMAX_TYPE
, "long long unsigned int") == 0)
1079 *pintmax
= long_long_integer_type_node
;
1080 *puintmax
= long_long_unsigned_type_node
;
1084 for (int i
= 0; i
< NUM_INT_N_ENTS
; i
++)
1085 if (int_n_enabled_p
[i
])
1088 sprintf (name
, "__int%d unsigned", int_n_data
[i
].bitsize
);
1090 if (strcmp (name
, UINTMAX_TYPE
) == 0)
1092 *pintmax
= int_n_trees
[i
].signed_type
;
1093 *puintmax
= int_n_trees
[i
].unsigned_type
;
1101 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1102 in and that is representable in type int.
1103 Return true when the range is a subrange of that of int.
1104 When ARG is null it is as if it had the full range of int.
1105 When ABSOLUTE is true the range reflects the absolute value of
1106 the argument. When ABSOLUTE is false, negative bounds of
1107 the determined range are replaced with NEGBOUND. */
1110 get_int_range (tree arg
, HOST_WIDE_INT
*pmin
, HOST_WIDE_INT
*pmax
,
1111 bool absolute
, HOST_WIDE_INT negbound
)
1113 /* The type of the result. */
1114 const_tree type
= integer_type_node
;
1116 bool knownrange
= false;
1120 *pmin
= tree_to_shwi (TYPE_MIN_VALUE (type
));
1121 *pmax
= tree_to_shwi (TYPE_MAX_VALUE (type
));
1123 else if (TREE_CODE (arg
) == INTEGER_CST
1124 && TYPE_PRECISION (TREE_TYPE (arg
)) <= TYPE_PRECISION (type
))
1126 /* For a constant argument return its value adjusted as specified
1127 by NEGATIVE and NEGBOUND and return true to indicate that the
1129 *pmin
= tree_fits_shwi_p (arg
) ? tree_to_shwi (arg
) : tree_to_uhwi (arg
);
1135 /* True if the argument's range cannot be determined. */
1136 bool unknown
= true;
1138 tree argtype
= TREE_TYPE (arg
);
1140 /* Ignore invalid arguments with greater precision that that
1141 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1142 They will have been detected and diagnosed by -Wformat and
1143 so it's not important to complicate this code to try to deal
1145 if (TREE_CODE (arg
) == SSA_NAME
1146 && INTEGRAL_TYPE_P (argtype
)
1147 && TYPE_PRECISION (argtype
) <= TYPE_PRECISION (type
))
1149 /* Try to determine the range of values of the integer argument. */
1151 enum value_range_type range_type
= get_range_info (arg
, &min
, &max
);
1152 if (range_type
== VR_RANGE
)
1154 HOST_WIDE_INT type_min
1155 = (TYPE_UNSIGNED (argtype
)
1156 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype
))
1157 : tree_to_shwi (TYPE_MIN_VALUE (argtype
)));
1159 HOST_WIDE_INT type_max
= tree_to_uhwi (TYPE_MAX_VALUE (argtype
));
1161 *pmin
= min
.to_shwi ();
1162 *pmax
= max
.to_shwi ();
1166 /* Return true if the adjusted range is a subrange of
1167 the full range of the argument's type. *PMAX may
1168 be less than *PMIN when the argument is unsigned
1169 and its upper bound is in excess of TYPE_MAX. In
1170 that (invalid) case disregard the range and use that
1171 of the expected type instead. */
1172 knownrange
= type_min
< *pmin
|| *pmax
< type_max
;
1179 /* Handle an argument with an unknown range as if none had been
1182 return get_int_range (NULL_TREE
, pmin
, pmax
, absolute
, negbound
);
1185 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1191 *pmin
= *pmax
= -*pmin
;
1194 /* Make sure signed overlow is avoided. */
1195 gcc_assert (*pmin
!= HOST_WIDE_INT_MIN
);
1197 HOST_WIDE_INT tmp
= -*pmin
;
1204 else if (*pmin
< negbound
)
1210 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1211 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1212 the type of the directive's formal argument it's possible for both
1213 to result in the same number of bytes or a range of bytes that's
1214 less than the number of bytes that would result from formatting
1215 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1216 determined by checking for the actual argument being in the range
1217 of the type of the directive. If it isn't it must be assumed to
1218 take on the full range of the directive's type.
1219 Return true when the range has been adjusted to the full range
1220 of DIRTYPE, and false otherwise. */
1223 adjust_range_for_overflow (tree dirtype
, tree
*argmin
, tree
*argmax
)
1225 tree argtype
= TREE_TYPE (*argmin
);
1226 unsigned argprec
= TYPE_PRECISION (argtype
);
1227 unsigned dirprec
= TYPE_PRECISION (dirtype
);
1229 /* If the actual argument and the directive's argument have the same
1230 precision and sign there can be no overflow and so there is nothing
1232 if (argprec
== dirprec
&& TYPE_SIGN (argtype
) == TYPE_SIGN (dirtype
))
1235 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1236 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1238 if (TREE_CODE (*argmin
) == INTEGER_CST
1239 && TREE_CODE (*argmax
) == INTEGER_CST
1240 && (dirprec
>= argprec
1241 || integer_zerop (int_const_binop (RSHIFT_EXPR
,
1242 int_const_binop (MINUS_EXPR
,
1245 size_int (dirprec
)))))
1247 *argmin
= force_fit_type (dirtype
, wi::to_widest (*argmin
), 0, false);
1248 *argmax
= force_fit_type (dirtype
, wi::to_widest (*argmax
), 0, false);
1250 /* If *ARGMIN is still less than *ARGMAX the conversion above
1251 is safe. Otherwise, it has overflowed and would be unsafe. */
1252 if (tree_int_cst_le (*argmin
, *argmax
))
1256 *argmin
= TYPE_MIN_VALUE (dirtype
);
1257 *argmax
= TYPE_MAX_VALUE (dirtype
);
1261 /* Return a range representing the minimum and maximum number of bytes
1262 that the format directive DIR will output for any argument given
1263 the WIDTH and PRECISION (extracted from DIR). This function is
1264 used when the directive argument or its value isn't known. */
1267 format_integer (const directive
&dir
, tree arg
)
1269 tree intmax_type_node
;
1270 tree uintmax_type_node
;
1272 /* Base to format the number in. */
1275 /* True when a conversion is preceded by a prefix indicating the base
1276 of the argument (octal or hexadecimal). */
1277 bool maybebase
= dir
.get_flag ('#');
1279 /* True when a signed conversion is preceded by a sign or space. */
1280 bool maybesign
= false;
1282 /* True for signed conversions (i.e., 'd' and 'i'). */
1285 switch (dir
.specifier
)
1289 /* Space and '+' are only meaningful for signed conversions. */
1290 maybesign
= dir
.get_flag (' ') | dir
.get_flag ('+');
1308 /* The type of the "formal" argument expected by the directive. */
1309 tree dirtype
= NULL_TREE
;
1311 /* Determine the expected type of the argument from the length
1313 switch (dir
.modifier
)
1316 if (dir
.specifier
== 'p')
1317 dirtype
= ptr_type_node
;
1319 dirtype
= sign
? integer_type_node
: unsigned_type_node
;
1323 dirtype
= sign
? short_integer_type_node
: short_unsigned_type_node
;
1327 dirtype
= sign
? signed_char_type_node
: unsigned_char_type_node
;
1331 dirtype
= sign
? long_integer_type_node
: long_unsigned_type_node
;
1337 ? long_long_integer_type_node
1338 : long_long_unsigned_type_node
);
1342 dirtype
= signed_or_unsigned_type_for (!sign
, size_type_node
);
1346 dirtype
= signed_or_unsigned_type_for (!sign
, ptrdiff_type_node
);
1350 build_intmax_type_nodes (&intmax_type_node
, &uintmax_type_node
);
1351 dirtype
= sign
? intmax_type_node
: uintmax_type_node
;
1355 return fmtresult ();
1358 /* The type of the argument to the directive, either deduced from
1359 the actual non-constant argument if one is known, or from
1360 the directive itself when none has been provided because it's
1362 tree argtype
= NULL_TREE
;
1366 /* When the argument has not been provided, use the type of
1367 the directive's argument as an approximation. This will
1368 result in false positives for directives like %i with
1369 arguments with smaller precision (such as short or char). */
1372 else if (TREE_CODE (arg
) == INTEGER_CST
)
1374 /* When a constant argument has been provided use its value
1375 rather than type to determine the length of the output. */
1378 if ((dir
.prec
[0] <= 0 && dir
.prec
[1] >= 0) && integer_zerop (arg
))
1380 /* As a special case, a precision of zero with a zero argument
1381 results in zero bytes except in base 8 when the '#' flag is
1382 specified, and for signed conversions in base 8 and 10 when
1383 either the space or '+' flag has been specified and it results
1384 in just one byte (with width having the normal effect). This
1385 must extend to the case of a specified precision with
1386 an unknown value because it can be zero. */
1387 res
.range
.min
= ((base
== 8 && dir
.get_flag ('#')) || maybesign
);
1388 if (res
.range
.min
== 0 && dir
.prec
[0] != dir
.prec
[1])
1391 res
.range
.likely
= 1;
1395 res
.range
.max
= res
.range
.min
;
1396 res
.range
.likely
= res
.range
.min
;
1401 /* Convert the argument to the type of the directive. */
1402 arg
= fold_convert (dirtype
, arg
);
1404 res
.range
.min
= tree_digits (arg
, base
, dir
.prec
[0],
1405 maybesign
, maybebase
);
1406 if (dir
.prec
[0] == dir
.prec
[1])
1407 res
.range
.max
= res
.range
.min
;
1409 res
.range
.max
= tree_digits (arg
, base
, dir
.prec
[1],
1410 maybesign
, maybebase
);
1411 res
.range
.likely
= res
.range
.min
;
1412 res
.knownrange
= true;
1415 res
.range
.unlikely
= res
.range
.max
;
1417 /* Bump up the counters if WIDTH is greater than LEN. */
1418 res
.adjust_for_width_or_precision (dir
.width
, dirtype
, base
,
1419 (sign
| maybebase
) + (base
== 16));
1420 /* Bump up the counters again if PRECision is greater still. */
1421 res
.adjust_for_width_or_precision (dir
.prec
, dirtype
, base
,
1422 (sign
| maybebase
) + (base
== 16));
1426 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg
))
1427 || TREE_CODE (TREE_TYPE (arg
)) == POINTER_TYPE
)
1428 /* Determine the type of the provided non-constant argument. */
1429 argtype
= TREE_TYPE (arg
);
1431 /* Don't bother with invalid arguments since they likely would
1432 have already been diagnosed, and disable any further checking
1433 of the format string by returning [-1, -1]. */
1434 return fmtresult ();
1438 /* Using either the range the non-constant argument is in, or its
1439 type (either "formal" or actual), create a range of values that
1440 constrain the length of output given the warning level. */
1441 tree argmin
= NULL_TREE
;
1442 tree argmax
= NULL_TREE
;
1445 && TREE_CODE (arg
) == SSA_NAME
1446 && INTEGRAL_TYPE_P (argtype
))
1448 /* Try to determine the range of values of the integer argument
1449 (range information is not available for pointers). */
1451 enum value_range_type range_type
= get_range_info (arg
, &min
, &max
);
1452 if (range_type
== VR_RANGE
)
1454 argmin
= wide_int_to_tree (argtype
, min
);
1455 argmax
= wide_int_to_tree (argtype
, max
);
1457 /* Set KNOWNRANGE if the argument is in a known subrange
1458 of the directive's type and neither width nor precision
1459 is unknown. (KNOWNRANGE may be reset below). */
1461 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype
), argmin
)
1462 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype
), argmax
))
1463 && dir
.known_width_and_precision ());
1465 res
.argmin
= argmin
;
1466 res
.argmax
= argmax
;
1468 else if (range_type
== VR_ANTI_RANGE
)
1470 /* Handle anti-ranges if/when bug 71690 is resolved. */
1472 else if (range_type
== VR_VARYING
)
1474 /* The argument here may be the result of promoting the actual
1475 argument to int. Try to determine the type of the actual
1476 argument before promotion and narrow down its range that
1478 gimple
*def
= SSA_NAME_DEF_STMT (arg
);
1479 if (is_gimple_assign (def
))
1481 tree_code code
= gimple_assign_rhs_code (def
);
1482 if (code
== INTEGER_CST
)
1484 arg
= gimple_assign_rhs1 (def
);
1485 return format_integer (dir
, arg
);
1488 if (code
== NOP_EXPR
)
1490 tree type
= TREE_TYPE (gimple_assign_rhs1 (def
));
1491 if (INTEGRAL_TYPE_P (type
)
1492 || TREE_CODE (type
) == POINTER_TYPE
)
1501 if (TREE_CODE (argtype
) == POINTER_TYPE
)
1503 argmin
= build_int_cst (pointer_sized_int_node
, 0);
1504 argmax
= build_all_ones_cst (pointer_sized_int_node
);
1508 argmin
= TYPE_MIN_VALUE (argtype
);
1509 argmax
= TYPE_MAX_VALUE (argtype
);
1513 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1514 of the directive. If it has been cleared then since ARGMIN and/or
1515 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1516 ARGMAX in the result to include in diagnostics. */
1517 if (adjust_range_for_overflow (dirtype
, &argmin
, &argmax
))
1519 res
.knownrange
= false;
1520 res
.argmin
= argmin
;
1521 res
.argmax
= argmax
;
1524 /* Recursively compute the minimum and maximum from the known range. */
1525 if (TYPE_UNSIGNED (dirtype
) || tree_int_cst_sgn (argmin
) >= 0)
1527 /* For unsigned conversions/directives or signed when
1528 the minimum is positive, use the minimum and maximum to compute
1529 the shortest and longest output, respectively. */
1530 res
.range
.min
= format_integer (dir
, argmin
).range
.min
;
1531 res
.range
.max
= format_integer (dir
, argmax
).range
.max
;
1533 else if (tree_int_cst_sgn (argmax
) < 0)
1535 /* For signed conversions/directives if maximum is negative,
1536 use the minimum as the longest output and maximum as the
1538 res
.range
.min
= format_integer (dir
, argmax
).range
.min
;
1539 res
.range
.max
= format_integer (dir
, argmin
).range
.max
;
1543 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1544 as the shortest output and for the longest output compute the
1545 length of the output of both minimum and maximum and pick the
1547 unsigned HOST_WIDE_INT max1
= format_integer (dir
, argmin
).range
.max
;
1548 unsigned HOST_WIDE_INT max2
= format_integer (dir
, argmax
).range
.max
;
1549 res
.range
.min
= format_integer (dir
, integer_zero_node
).range
.min
;
1550 res
.range
.max
= MAX (max1
, max2
);
1553 /* If the range is known, use the maximum as the likely length. */
1555 res
.range
.likely
= res
.range
.max
;
1558 /* Otherwise, use the minimum. Except for the case where for %#x or
1559 %#o the minimum is just for a single value in the range (0) and
1560 for all other values it is something longer, like 0x1 or 01.
1561 Use the length for value 1 in that case instead as the likely
1563 res
.range
.likely
= res
.range
.min
;
1566 && (tree_int_cst_sgn (argmin
) < 0 || tree_int_cst_sgn (argmax
) > 0))
1568 if (res
.range
.min
== 1)
1569 res
.range
.likely
+= base
== 8 ? 1 : 2;
1570 else if (res
.range
.min
== 2
1572 && (dir
.width
[0] == 2 || dir
.prec
[0] == 2))
1577 res
.range
.unlikely
= res
.range
.max
;
1578 res
.adjust_for_width_or_precision (dir
.width
, dirtype
, base
,
1579 (sign
| maybebase
) + (base
== 16));
1580 res
.adjust_for_width_or_precision (dir
.prec
, dirtype
, base
,
1581 (sign
| maybebase
) + (base
== 16));
1586 /* Return the number of bytes that a format directive consisting of FLAGS,
1587 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1588 would result for argument X under ideal conditions (i.e., if PREC
1589 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1590 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1591 This function works around those problems. */
1593 static unsigned HOST_WIDE_INT
1594 get_mpfr_format_length (mpfr_ptr x
, const char *flags
, HOST_WIDE_INT prec
,
1595 char spec
, char rndspec
)
1599 HOST_WIDE_INT len
= strlen (flags
);
1602 memcpy (fmtstr
+ 1, flags
, len
);
1603 memcpy (fmtstr
+ 1 + len
, ".*R", 3);
1604 fmtstr
[len
+ 4] = rndspec
;
1605 fmtstr
[len
+ 5] = spec
;
1606 fmtstr
[len
+ 6] = '\0';
1608 spec
= TOUPPER (spec
);
1609 if (spec
== 'E' || spec
== 'F')
1611 /* For %e, specify the precision explicitly since mpfr_sprintf
1612 does its own thing just to be different (see MPFR bug 21088). */
1618 /* Avoid passing negative precisions with larger magnitude to MPFR
1619 to avoid exposing its bugs. (A negative precision is supposed
1625 HOST_WIDE_INT p
= prec
;
1627 if (spec
== 'G' && !strchr (flags
, '#'))
1629 /* For G/g without the pound flag, precision gives the maximum number
1630 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1631 a 128 bit IEEE extended precision, 4932. Using twice as much here
1632 should be more than sufficient for any real format. */
1633 if ((IEEE_MAX_10_EXP
* 2) < prec
)
1634 prec
= IEEE_MAX_10_EXP
* 2;
1639 /* Cap precision arbitrarily at 1KB and add the difference
1640 (if any) to the MPFR result. */
1645 len
= mpfr_snprintf (NULL
, 0, fmtstr
, (int)p
, x
);
1647 /* Handle the unlikely (impossible?) error by returning more than
1648 the maximum dictated by the function's return type. */
1650 return target_dir_max () + 1;
1652 /* Adjust the return value by the difference. */
1659 /* Return the number of bytes to format using the format specifier
1660 SPEC and the precision PREC the largest value in the real floating
1663 static unsigned HOST_WIDE_INT
1664 format_floating_max (tree type
, char spec
, HOST_WIDE_INT prec
)
1666 machine_mode mode
= TYPE_MODE (type
);
1668 /* IBM Extended mode. */
1669 if (MODE_COMPOSITE_P (mode
))
1672 /* Get the real type format desription for the target. */
1673 const real_format
*rfmt
= REAL_MODE_FORMAT (mode
);
1676 real_maxval (&rv
, 0, mode
);
1678 /* Convert the GCC real value representation with the precision
1679 of the real type to the mpfr_t format with the GCC default
1680 round-to-nearest mode. */
1682 mpfr_init2 (x
, rfmt
->p
);
1683 mpfr_from_real (x
, &rv
, GMP_RNDN
);
1685 /* Return a value one greater to account for the leading minus sign. */
1686 unsigned HOST_WIDE_INT r
1687 = 1 + get_mpfr_format_length (x
, "", prec
, spec
, 'D');
1692 /* Return a range representing the minimum and maximum number of bytes
1693 that the directive DIR will output for any argument. PREC gives
1694 the adjusted precision range to account for negative precisions
1695 meaning the default 6. This function is used when the directive
1696 argument or its value isn't known. */
1699 format_floating (const directive
&dir
, const HOST_WIDE_INT prec
[2])
1703 switch (dir
.modifier
)
1707 type
= double_type_node
;
1711 type
= long_double_type_node
;
1715 type
= long_double_type_node
;
1719 return fmtresult ();
1722 /* The minimum and maximum number of bytes produced by the directive. */
1725 /* The minimum output as determined by flags. It's always at least 1.
1726 When plus or space are set the output is preceded by either a sign
1728 unsigned flagmin
= (1 /* for the first digit */
1729 + (dir
.get_flag ('+') | dir
.get_flag (' ')));
1731 /* When the pound flag is set the decimal point is included in output
1732 regardless of precision. Whether or not a decimal point is included
1733 otherwise depends on the specification and precision. */
1734 bool radix
= dir
.get_flag ('#');
1736 switch (dir
.specifier
)
1741 HOST_WIDE_INT minprec
= 6 + !radix
/* decimal point */;
1742 if (dir
.prec
[0] <= 0)
1744 else if (dir
.prec
[0] > 0)
1745 minprec
= dir
.prec
[0] + !radix
/* decimal point */;
1747 res
.range
.min
= (2 /* 0x */
1753 res
.range
.max
= format_floating_max (type
, 'a', prec
[1]);
1754 res
.range
.likely
= res
.range
.min
;
1756 /* The unlikely maximum accounts for the longest multibyte
1757 decimal point character. */
1758 res
.range
.unlikely
= res
.range
.max
;
1759 if (dir
.prec
[1] > 0)
1760 res
.range
.unlikely
+= target_mb_len_max () - 1;
1768 /* Minimum output attributable to precision and, when it's
1769 non-zero, decimal point. */
1770 HOST_WIDE_INT minprec
= prec
[0] ? prec
[0] + !radix
: 0;
1772 /* The minimum output is "[-+]1.234567e+00" regardless
1773 of the value of the actual argument. */
1774 res
.range
.min
= (flagmin
1779 res
.range
.max
= format_floating_max (type
, 'e', prec
[1]);
1780 res
.range
.likely
= res
.range
.min
;
1782 /* The unlikely maximum accounts for the longest multibyte
1783 decimal point character. */
1784 if (dir
.prec
[0] != dir
.prec
[1]
1785 || dir
.prec
[0] == -1 || dir
.prec
[0] > 0)
1786 res
.range
.unlikely
= res
.range
.max
+ target_mb_len_max () -1;
1788 res
.range
.unlikely
= res
.range
.max
;
1795 /* Minimum output attributable to precision and, when it's non-zero,
1797 HOST_WIDE_INT minprec
= prec
[0] ? prec
[0] + !radix
: 0;
1799 /* The lower bound when precision isn't specified is 8 bytes
1800 ("1.23456" since precision is taken to be 6). When precision
1801 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1802 when precision is greater than zero, then the lower bound
1803 is 2 plus precision (plus flags). */
1804 res
.range
.min
= flagmin
+ radix
+ minprec
;
1806 /* Compute the upper bound for -TYPE_MAX. */
1807 res
.range
.max
= format_floating_max (type
, 'f', prec
[1]);
1809 /* The minimum output with unknown precision is a single byte
1810 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1811 if (dir
.prec
[0] < 0 && dir
.prec
[1] > 0)
1812 res
.range
.likely
= 3;
1814 res
.range
.likely
= res
.range
.min
;
1816 /* The unlikely maximum accounts for the longest multibyte
1817 decimal point character. */
1818 if (dir
.prec
[0] != dir
.prec
[1]
1819 || dir
.prec
[0] == -1 || dir
.prec
[0] > 0)
1820 res
.range
.unlikely
= res
.range
.max
+ target_mb_len_max () - 1;
1827 /* The %g output depends on precision and the exponent of
1828 the argument. Since the value of the argument isn't known
1829 the lower bound on the range of bytes (not counting flags
1830 or width) is 1 plus radix (i.e., either "0" or "0." for
1831 "%g" and "%#g", respectively, with a zero argument). */
1832 res
.range
.min
= flagmin
+ radix
;
1835 HOST_WIDE_INT maxprec
= dir
.prec
[1];
1836 if (radix
&& maxprec
)
1838 /* When the pound flag (radix) is set, trailing zeros aren't
1839 trimmed and so the longest output is the same as for %e,
1840 except with precision minus 1 (as specified in C11). */
1844 else if (maxprec
< 0)
1850 res
.range
.max
= format_floating_max (type
, spec
, maxprec
);
1852 /* The likely output is either the maximum computed above
1853 minus 1 (assuming the maximum is positive) when precision
1854 is known (or unspecified), or the same minimum as for %e
1855 (which is computed for a non-negative argument). Unlike
1856 for the other specifiers above the likely output isn't
1857 the minimum because for %g that's 1 which is unlikely. */
1859 || (unsigned HOST_WIDE_INT
)dir
.prec
[1] < target_int_max ())
1860 res
.range
.likely
= res
.range
.max
- 1;
1863 HOST_WIDE_INT minprec
= 6 + !radix
/* decimal point */;
1864 res
.range
.likely
= (flagmin
1870 /* The unlikely maximum accounts for the longest multibyte
1871 decimal point character. */
1872 res
.range
.unlikely
= res
.range
.max
+ target_mb_len_max () - 1;
1877 return fmtresult ();
1880 /* Bump up the byte counters if WIDTH is greater. */
1881 res
.adjust_for_width_or_precision (dir
.width
);
1885 /* Return a range representing the minimum and maximum number of bytes
1886 that the directive DIR will write on output for the floating argument
1890 format_floating (const directive
&dir
, tree arg
)
1892 HOST_WIDE_INT prec
[] = { dir
.prec
[0], dir
.prec
[1] };
1893 tree type
= (dir
.modifier
== FMT_LEN_L
|| dir
.modifier
== FMT_LEN_ll
1894 ? long_double_type_node
: double_type_node
);
1896 /* For an indeterminate precision the lower bound must be assumed
1898 if (TOUPPER (dir
.specifier
) == 'A')
1900 /* Get the number of fractional decimal digits needed to represent
1901 the argument without a loss of accuracy. */
1903 = REAL_MODE_FORMAT (TYPE_MODE (type
))->p
;
1905 /* The precision of the IEEE 754 double format is 53.
1906 The precision of all other GCC binary double formats
1908 unsigned maxprec
= fmtprec
<= 56 ? 13 : 15;
1910 /* For %a, leave the minimum precision unspecified to let
1911 MFPR trim trailing zeros (as it and many other systems
1912 including Glibc happen to do) and set the maximum
1913 precision to reflect what it would be with trailing zeros
1914 present (as Solaris and derived systems do). */
1915 if (dir
.prec
[1] < 0)
1917 /* Both bounds are negative implies that precision has
1918 not been specified. */
1922 else if (dir
.prec
[0] < 0)
1924 /* With a negative lower bound and a non-negative upper
1925 bound set the minimum precision to zero and the maximum
1926 to the greater of the maximum precision (i.e., with
1927 trailing zeros present) and the specified upper bound. */
1929 prec
[1] = dir
.prec
[1] < maxprec
? maxprec
: dir
.prec
[1];
1932 else if (dir
.prec
[0] < 0)
1934 if (dir
.prec
[1] < 0)
1936 /* A precision in a strictly negative range is ignored and
1937 the default of 6 is used instead. */
1938 prec
[0] = prec
[1] = 6;
1942 /* For a precision in a partly negative range, the lower bound
1943 must be assumed to be zero and the new upper bound is the
1944 greater of 6 (the default precision used when the specified
1945 precision is negative) and the upper bound of the specified
1948 prec
[1] = dir
.prec
[1] < 6 ? 6 : dir
.prec
[1];
1953 || TREE_CODE (arg
) != REAL_CST
1954 || !useless_type_conversion_p (type
, TREE_TYPE (arg
)))
1955 return format_floating (dir
, prec
);
1957 /* The minimum and maximum number of bytes produced by the directive. */
1960 /* Get the real type format desription for the target. */
1961 const REAL_VALUE_TYPE
*rvp
= TREE_REAL_CST_PTR (arg
);
1962 const real_format
*rfmt
= REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg
)));
1965 char *pfmt
= fmtstr
;
1968 for (const char *pf
= "-+ #0"; *pf
; ++pf
)
1969 if (dir
.get_flag (*pf
))
1975 /* Set up an array to easily iterate over. */
1976 unsigned HOST_WIDE_INT
* const minmax
[] = {
1977 &res
.range
.min
, &res
.range
.max
1980 for (int i
= 0; i
!= sizeof minmax
/ sizeof *minmax
; ++i
)
1982 /* Convert the GCC real value representation with the precision
1983 of the real type to the mpfr_t format rounding down in the
1984 first iteration that computes the minimm and up in the second
1985 that computes the maximum. This order is arbibtrary because
1986 rounding in either direction can result in longer output. */
1988 mpfr_init2 (mpfrval
, rfmt
->p
);
1989 mpfr_from_real (mpfrval
, rvp
, i
? GMP_RNDU
: GMP_RNDD
);
1991 /* Use the MPFR rounding specifier to round down in the first
1992 iteration and then up. In most but not all cases this will
1993 result in the same number of bytes. */
1994 char rndspec
= "DU"[i
];
1996 /* Format it and store the result in the corresponding member
1997 of the result struct. */
1998 *minmax
[i
] = get_mpfr_format_length (mpfrval
, fmtstr
, prec
[i
],
1999 dir
.specifier
, rndspec
);
2000 mpfr_clear (mpfrval
);
2004 /* Make sure the minimum is less than the maximum (MPFR rounding
2005 in the call to mpfr_snprintf can result in the reverse. */
2006 if (res
.range
.max
< res
.range
.min
)
2008 unsigned HOST_WIDE_INT tmp
= res
.range
.min
;
2009 res
.range
.min
= res
.range
.max
;
2010 res
.range
.max
= tmp
;
2013 /* The range is known unless either width or precision is unknown. */
2014 res
.knownrange
= dir
.known_width_and_precision ();
2016 /* For the same floating point constant, unless width or precision
2017 is unknown, use the longer output as the likely maximum since
2018 with round to nearest either is equally likely. Otheriwse, when
2019 precision is unknown, use the greater of the minimum and 3 as
2020 the likely output (for "0.0" since zero precision is unlikely). */
2022 res
.range
.likely
= res
.range
.max
;
2023 else if (res
.range
.min
< 3
2025 && (unsigned HOST_WIDE_INT
)dir
.prec
[1] == target_int_max ())
2026 res
.range
.likely
= 3;
2028 res
.range
.likely
= res
.range
.min
;
2030 res
.range
.unlikely
= res
.range
.max
;
2032 if (res
.range
.max
> 2 && (prec
[0] != 0 || prec
[1] != 0))
2034 /* Unless the precision is zero output longer than 2 bytes may
2035 include the decimal point which must be a single character
2036 up to MB_LEN_MAX in length. This is overly conservative
2037 since in some conversions some constants result in no decimal
2038 point (e.g., in %g). */
2039 res
.range
.unlikely
+= target_mb_len_max () - 1;
2042 res
.adjust_for_width_or_precision (dir
.width
);
2046 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
2047 strings referenced by the expression STR, or (-1, -1) when not known.
2048 Used by the format_string function below. */
2051 get_string_length (tree str
)
2054 return fmtresult ();
2056 if (tree slen
= c_strlen (str
, 1))
2058 /* Simply return the length of the string. */
2059 fmtresult
res (tree_to_shwi (slen
));
2063 /* Determine the length of the shortest and longest string referenced
2064 by STR. Strings of unknown lengths are bounded by the sizes of
2065 arrays that subexpressions of STR may refer to. Pointers that
2066 aren't known to point any such arrays result in LENRANGE[1] set
2069 bool flexarray
= get_range_strlen (str
, lenrange
);
2071 if (lenrange
[0] || lenrange
[1])
2074 = (tree_fits_uhwi_p (lenrange
[0])
2075 ? tree_to_uhwi (lenrange
[0])
2079 = (tree_fits_uhwi_p (lenrange
[1])
2080 ? tree_to_uhwi (lenrange
[1])
2081 : HOST_WIDE_INT_M1U
);
2083 /* get_range_strlen() returns the target value of SIZE_MAX for
2084 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2085 which may be bigger. */
2086 if ((unsigned HOST_WIDE_INT
)min
== target_size_max ())
2087 min
= HOST_WIDE_INT_M1U
;
2088 if ((unsigned HOST_WIDE_INT
)max
== target_size_max ())
2089 max
= HOST_WIDE_INT_M1U
;
2091 fmtresult
res (min
, max
);
2093 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2094 by STR are known to be bounded (though not necessarily by their
2095 actual length but perhaps by their maximum possible length). */
2096 if (res
.range
.max
< target_int_max ())
2098 res
.knownrange
= true;
2099 /* When the the length of the longest string is known and not
2100 excessive use it as the likely length of the string(s). */
2101 res
.range
.likely
= res
.range
.max
;
2105 /* When the upper bound is unknown (it can be zero or excessive)
2106 set the likely length to the greater of 1 and the length of
2107 the shortest string and reset the lower bound to zero. */
2108 res
.range
.likely
= res
.range
.min
? res
.range
.min
: warn_level
> 1;
2112 /* If the range of string length has been estimated from the size
2113 of an array at the end of a struct assume that it's longer than
2114 the array bound says it is in case it's used as a poor man's
2115 flexible array member, such as in struct S { char a[4]; }; */
2116 res
.range
.unlikely
= flexarray
? HOST_WIDE_INT_MAX
: res
.range
.max
;
2121 return get_string_length (NULL_TREE
);
2124 /* Return the minimum and maximum number of characters formatted
2125 by the '%c' format directives and its wide character form for
2126 the argument ARG. ARG can be null (for functions such as
2130 format_character (const directive
&dir
, tree arg
)
2134 res
.knownrange
= true;
2136 if (dir
.modifier
== FMT_LEN_l
)
2138 /* A wide character can result in as few as zero bytes. */
2141 HOST_WIDE_INT min
, max
;
2142 if (get_int_range (arg
, &min
, &max
, false, 0))
2144 if (min
== 0 && max
== 0)
2146 /* The NUL wide character results in no bytes. */
2148 res
.range
.likely
= 0;
2149 res
.range
.unlikely
= 0;
2151 else if (min
> 0 && min
< 128)
2153 /* A wide character in the ASCII range most likely results
2154 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2156 res
.range
.likely
= 1;
2157 res
.range
.unlikely
= target_mb_len_max ();
2161 /* A wide character outside the ASCII range likely results
2162 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2163 res
.range
.max
= target_mb_len_max ();
2164 res
.range
.likely
= 2;
2165 res
.range
.unlikely
= res
.range
.max
;
2170 /* An unknown wide character is treated the same as a wide
2171 character outside the ASCII range. */
2172 res
.range
.max
= target_mb_len_max ();
2173 res
.range
.likely
= 2;
2174 res
.range
.unlikely
= res
.range
.max
;
2179 /* A plain '%c' directive. Its ouput is exactly 1. */
2180 res
.range
.min
= res
.range
.max
= 1;
2181 res
.range
.likely
= res
.range
.unlikely
= 1;
2182 res
.knownrange
= true;
2185 /* Bump up the byte counters if WIDTH is greater. */
2186 return res
.adjust_for_width_or_precision (dir
.width
);
2189 /* Return the minimum and maximum number of characters formatted
2190 by the '%s' format directive and its wide character form for
2191 the argument ARG. ARG can be null (for functions such as
2195 format_string (const directive
&dir
, tree arg
)
2199 /* Compute the range the argument's length can be in. */
2200 fmtresult slen
= get_string_length (arg
);
2201 if (slen
.range
.min
== slen
.range
.max
2202 && slen
.range
.min
< HOST_WIDE_INT_MAX
)
2204 /* The argument is either a string constant or it refers
2205 to one of a number of strings of the same length. */
2207 /* A '%s' directive with a string argument with constant length. */
2208 res
.range
= slen
.range
;
2210 if (dir
.modifier
== FMT_LEN_l
)
2212 /* In the worst case the length of output of a wide string S
2213 is bounded by MB_LEN_MAX * wcslen (S). */
2214 res
.range
.max
*= target_mb_len_max ();
2215 res
.range
.unlikely
= res
.range
.max
;
2216 /* It's likely that the the total length is not more that
2218 res
.range
.likely
= res
.range
.min
* 2;
2220 if (dir
.prec
[1] >= 0
2221 && (unsigned HOST_WIDE_INT
)dir
.prec
[1] < res
.range
.max
)
2223 res
.range
.max
= dir
.prec
[1];
2224 res
.range
.likely
= dir
.prec
[1];
2225 res
.range
.unlikely
= dir
.prec
[1];
2228 if (dir
.prec
[0] < 0 && dir
.prec
[1] > -1)
2230 else if (dir
.prec
[0] >= 0)
2231 res
.range
.likely
= dir
.prec
[0];
2233 /* Even a non-empty wide character string need not convert into
2239 res
.knownrange
= true;
2241 if (dir
.prec
[0] < 0 && dir
.prec
[1] > -1)
2243 else if ((unsigned HOST_WIDE_INT
)dir
.prec
[0] < res
.range
.min
)
2244 res
.range
.min
= dir
.prec
[0];
2246 if ((unsigned HOST_WIDE_INT
)dir
.prec
[1] < res
.range
.max
)
2248 res
.range
.max
= dir
.prec
[1];
2249 res
.range
.likely
= dir
.prec
[1];
2250 res
.range
.unlikely
= dir
.prec
[1];
2254 else if (arg
&& integer_zerop (arg
))
2256 /* Handle null pointer argument. */
2264 /* For a '%s' and '%ls' directive with a non-constant string (either
2265 one of a number of strings of known length or an unknown string)
2266 the minimum number of characters is lesser of PRECISION[0] and
2267 the length of the shortest known string or zero, and the maximum
2268 is the lessser of the length of the longest known string or
2269 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2270 the minimum at level 1 and the greater of the minimum and 1
2271 at level 2. This result is adjust upward for width (if it's
2274 if (dir
.modifier
== FMT_LEN_l
)
2276 /* A wide character converts to as few as zero bytes. */
2278 if (slen
.range
.max
< target_int_max ())
2279 slen
.range
.max
*= target_mb_len_max ();
2281 if (slen
.range
.likely
< target_int_max ())
2282 slen
.range
.likely
*= 2;
2284 if (slen
.range
.likely
< target_int_max ())
2285 slen
.range
.unlikely
*= target_mb_len_max ();
2288 res
.range
= slen
.range
;
2290 if (dir
.prec
[0] >= 0)
2292 /* Adjust the minimum to zero if the string length is unknown,
2293 or at most the lower bound of the precision otherwise. */
2294 if (slen
.range
.min
>= target_int_max ())
2296 else if ((unsigned HOST_WIDE_INT
)dir
.prec
[0] < slen
.range
.min
)
2297 res
.range
.min
= dir
.prec
[0];
2299 /* Make both maxima no greater than the upper bound of precision. */
2300 if ((unsigned HOST_WIDE_INT
)dir
.prec
[1] < slen
.range
.max
2301 || slen
.range
.max
>= target_int_max ())
2303 res
.range
.max
= dir
.prec
[1];
2304 res
.range
.unlikely
= dir
.prec
[1];
2307 /* If precision is constant, set the likely counter to the lesser
2308 of it and the maximum string length. Otherwise, if the lower
2309 bound of precision is greater than zero, set the likely counter
2310 to the minimum. Otherwise set it to zero or one based on
2311 the warning level. */
2312 if (dir
.prec
[0] == dir
.prec
[1])
2314 = ((unsigned HOST_WIDE_INT
)dir
.prec
[0] < slen
.range
.max
2315 ? dir
.prec
[0] : slen
.range
.max
);
2316 else if (dir
.prec
[0] > 0)
2317 res
.range
.likely
= res
.range
.min
;
2319 res
.range
.likely
= warn_level
> 1;
2321 else if (dir
.prec
[1] >= 0)
2324 if ((unsigned HOST_WIDE_INT
)dir
.prec
[1] < slen
.range
.max
)
2325 res
.range
.max
= dir
.prec
[1];
2326 res
.range
.likely
= dir
.prec
[1] ? warn_level
> 1 : 0;
2328 else if (slen
.range
.min
>= target_int_max ())
2331 res
.range
.max
= HOST_WIDE_INT_MAX
;
2332 /* At level 1 strings of unknown length are assumed to be
2333 empty, while at level 1 they are assumed to be one byte
2335 res
.range
.likely
= warn_level
> 1;
2339 /* A string of unknown length unconstrained by precision is
2340 assumed to be empty at level 1 and just one character long
2341 at higher levels. */
2342 if (res
.range
.likely
>= target_int_max ())
2343 res
.range
.likely
= warn_level
> 1;
2346 res
.range
.unlikely
= res
.range
.max
;
2349 /* Bump up the byte counters if WIDTH is greater. */
2350 return res
.adjust_for_width_or_precision (dir
.width
);
2353 /* Format plain string (part of the format string itself). */
2356 format_plain (const directive
&dir
, tree
)
2358 fmtresult
res (dir
.len
);
2362 /* Return true if the RESULT of a directive in a call describe by INFO
2363 should be diagnosed given the AVAILable space in the destination. */
2366 should_warn_p (const sprintf_dom_walker::call_info
&info
,
2367 const result_range
&avail
, const result_range
&result
)
2369 if (result
.max
<= avail
.min
)
2371 /* The least amount of space remaining in the destination is big
2372 enough for the longest output. */
2378 if (warn_format_trunc
== 1 && result
.min
<= avail
.max
2379 && info
.retval_used ())
2381 /* The likely amount of space remaining in the destination is big
2382 enough for the least output and the return value is used. */
2386 if (warn_format_trunc
== 1 && result
.likely
<= avail
.likely
2387 && !info
.retval_used ())
2389 /* The likely amount of space remaining in the destination is big
2390 enough for the likely output and the return value is unused. */
2394 if (warn_format_trunc
== 2
2395 && result
.likely
<= avail
.min
2396 && (result
.max
<= avail
.min
2397 || result
.max
> HOST_WIDE_INT_MAX
))
2399 /* The minimum amount of space remaining in the destination is big
2400 enough for the longest output. */
2406 if (warn_level
== 1 && result
.likely
<= avail
.likely
)
2408 /* The likely amount of space remaining in the destination is big
2409 enough for the likely output. */
2414 && result
.likely
<= avail
.min
2415 && (result
.max
<= avail
.min
2416 || result
.max
> HOST_WIDE_INT_MAX
))
2418 /* The minimum amount of space remaining in the destination is big
2419 enough for the longest output. */
2427 /* At format string location describe by DIRLOC in a call described
2428 by INFO, issue a warning for a directive DIR whose output may be
2429 in excess of the available space AVAIL_RANGE in the destination
2430 given the formatting result FMTRES. This function does nothing
2431 except decide whether to issue a warning for a possible write
2432 past the end or truncation and, if so, format the warning.
2433 Return true if a warning has been issued. */
2436 maybe_warn (substring_loc
&dirloc
, location_t argloc
,
2437 const sprintf_dom_walker::call_info
&info
,
2438 const result_range
&avail_range
, const result_range
&res
,
2439 const directive
&dir
)
2441 if (!should_warn_p (info
, avail_range
, res
))
2444 /* A warning will definitely be issued below. */
2446 /* The maximum byte count to reference in the warning. Larger counts
2447 imply that the upper bound is unknown (and could be anywhere between
2448 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2449 than "between N and X" where X is some huge number. */
2450 unsigned HOST_WIDE_INT maxbytes
= target_dir_max ();
2452 /* True when there is enough room in the destination for the least
2453 amount of a directive's output but not enough for its likely or
2455 bool maybe
= (res
.min
<= avail_range
.max
2456 && (avail_range
.min
< res
.likely
2457 || (res
.max
< HOST_WIDE_INT_MAX
2458 && avail_range
.min
< res
.max
)));
2460 /* Buffer for the directive in the host character set (used when
2461 the source character set is different). */
2464 if (avail_range
.min
== avail_range
.max
)
2466 /* The size of the destination region is exact. */
2467 unsigned HOST_WIDE_INT navail
= avail_range
.max
;
2469 if (target_to_host (*dir
.beg
) != '%')
2471 /* For plain character directives (i.e., the format string itself)
2472 but not others, point the caret at the first character that's
2473 past the end of the destination. */
2474 if (navail
< dir
.len
)
2475 dirloc
.set_caret_index (dirloc
.get_caret_idx () + navail
);
2478 if (*dir
.beg
== '\0')
2480 /* This is the terminating nul. */
2481 gcc_assert (res
.min
== 1 && res
.min
== res
.max
);
2486 ? G_("%qE output may be truncated before the last format "
2488 : G_("%qE output truncated before the last format character"))
2490 ? G_("%qE may write a terminating nul past the end "
2491 "of the destination")
2492 : G_("%qE writing a terminating nul past the end "
2493 "of the destination")));
2495 return fmtwarn (dirloc
, UNKNOWN_LOCATION
, NULL
, info
.warnopt (),
2499 if (res
.min
== res
.max
)
2505 ? G_("%<%.*s%> directive output may be truncated writing "
2506 "%wu byte into a region of size %wu")
2507 : G_("%<%.*s%> directive output truncated writing "
2508 "%wu byte into a region of size %wu"))
2509 : G_("%<%.*s%> directive writing %wu byte "
2510 "into a region of size %wu"))
2513 ? G_("%<%.*s%> directive output may be truncated writing "
2514 "%wu bytes into a region of size %wu")
2515 : G_("%<%.*s%> directive output truncated writing "
2516 "%wu bytes into a region of size %wu"))
2517 : G_("%<%.*s%> directive writing %wu bytes "
2518 "into a region of size %wu")));
2519 return fmtwarn (dirloc
, argloc
, NULL
,
2520 info
.warnopt (), fmtstr
, dir
.len
,
2521 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2525 if (res
.min
== 0 && res
.max
< maxbytes
)
2530 ? G_("%<%.*s%> directive output may be truncated writing "
2531 "up to %wu bytes into a region of size %wu")
2532 : G_("%<%.*s%> directive output truncated writing "
2533 "up to %wu bytes into a region of size %wu"))
2534 : G_("%<%.*s%> directive writing up to %wu bytes "
2535 "into a region of size %wu"));
2536 return fmtwarn (dirloc
, argloc
, NULL
,
2537 info
.warnopt (), fmtstr
, dir
.len
,
2538 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2542 if (res
.min
== 0 && maxbytes
<= res
.max
)
2544 /* This is a special case to avoid issuing the potentially
2546 writing 0 or more bytes into a region of size 0. */
2550 ? G_("%<%.*s%> directive output may be truncated writing "
2551 "likely %wu or more bytes into a region of size %wu")
2552 : G_("%<%.*s%> directive output truncated writing "
2553 "likely %wu or more bytes into a region of size %wu"))
2554 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2555 "into a region of size %wu"));
2556 return fmtwarn (dirloc
, argloc
, NULL
,
2557 info
.warnopt (), fmtstr
, dir
.len
,
2558 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2559 res
.likely
, navail
);
2562 if (res
.max
< maxbytes
)
2567 ? G_("%<%.*s%> directive output may be truncated writing "
2568 "between %wu and %wu bytes into a region of size %wu")
2569 : G_("%<%.*s%> directive output truncated writing "
2570 "between %wu and %wu bytes into a region of size %wu"))
2571 : G_("%<%.*s%> directive writing between %wu and "
2572 "%wu bytes into a region of size %wu"));
2573 return fmtwarn (dirloc
, argloc
, NULL
,
2574 info
.warnopt (), fmtstr
, dir
.len
,
2575 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2576 res
.min
, res
.max
, navail
);
2582 ? G_("%<%.*s%> directive output may be truncated writing "
2583 "%wu or more bytes into a region of size %wu")
2584 : G_("%<%.*s%> directive output truncated writing "
2585 "%wu or more bytes into a region of size %wu"))
2586 : G_("%<%.*s%> directive writing %wu or more bytes "
2587 "into a region of size %wu"));
2588 return fmtwarn (dirloc
, argloc
, NULL
,
2589 info
.warnopt (), fmtstr
, dir
.len
,
2590 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2594 /* The size of the destination region is a range. */
2596 if (target_to_host (*dir
.beg
) != '%')
2598 unsigned HOST_WIDE_INT navail
= avail_range
.max
;
2600 /* For plain character directives (i.e., the format string itself)
2601 but not others, point the caret at the first character that's
2602 past the end of the destination. */
2603 if (navail
< dir
.len
)
2604 dirloc
.set_caret_index (dirloc
.get_caret_idx () + navail
);
2607 if (*dir
.beg
== '\0')
2609 gcc_assert (res
.min
== 1 && res
.min
== res
.max
);
2614 ? G_("%qE output may be truncated before the last format "
2616 : G_("%qE output truncated before the last format character"))
2618 ? G_("%qE may write a terminating nul past the end "
2619 "of the destination")
2620 : G_("%qE writing a terminating nul past the end "
2621 "of the destination")));
2623 return fmtwarn (dirloc
, UNKNOWN_LOCATION
, NULL
, info
.warnopt (), fmtstr
,
2627 if (res
.min
== res
.max
)
2633 ? G_("%<%.*s%> directive output may be truncated writing "
2634 "%wu byte into a region of size between %wu and %wu")
2635 : G_("%<%.*s%> directive output truncated writing "
2636 "%wu byte into a region of size between %wu and %wu"))
2637 : G_("%<%.*s%> directive writing %wu byte "
2638 "into a region of size between %wu and %wu"))
2641 ? G_("%<%.*s%> directive output may be truncated writing "
2642 "%wu bytes into a region of size between %wu and %wu")
2643 : G_("%<%.*s%> directive output truncated writing "
2644 "%wu bytes into a region of size between %wu and %wu"))
2645 : G_("%<%.*s%> directive writing %wu bytes "
2646 "into a region of size between %wu and %wu")));
2648 return fmtwarn (dirloc
, argloc
, NULL
,
2649 info
.warnopt (), fmtstr
, dir
.len
,
2650 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2651 res
.min
, avail_range
.min
, avail_range
.max
);
2654 if (res
.min
== 0 && res
.max
< maxbytes
)
2659 ? G_("%<%.*s%> directive output may be truncated writing "
2660 "up to %wu bytes into a region of size between "
2662 : G_("%<%.*s%> directive output truncated writing "
2663 "up to %wu bytes into a region of size between "
2665 : G_("%<%.*s%> directive writing up to %wu bytes "
2666 "into a region of size between %wu and %wu"));
2667 return fmtwarn (dirloc
, argloc
, NULL
,
2668 info
.warnopt (), fmtstr
, dir
.len
,
2669 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2670 res
.max
, avail_range
.min
, avail_range
.max
);
2673 if (res
.min
== 0 && maxbytes
<= res
.max
)
2675 /* This is a special case to avoid issuing the potentially confusing
2677 writing 0 or more bytes into a region of size between 0 and N. */
2681 ? G_("%<%.*s%> directive output may be truncated writing "
2682 "likely %wu or more bytes into a region of size between "
2684 : G_("%<%.*s%> directive output truncated writing likely "
2685 "%wu or more bytes into a region of size between "
2687 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2688 "into a region of size between %wu and %wu"));
2689 return fmtwarn (dirloc
, argloc
, NULL
,
2690 info
.warnopt (), fmtstr
, dir
.len
,
2691 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2692 res
.likely
, avail_range
.min
, avail_range
.max
);
2695 if (res
.max
< maxbytes
)
2700 ? G_("%<%.*s%> directive output may be truncated writing "
2701 "between %wu and %wu bytes into a region of size "
2702 "between %wu and %wu")
2703 : G_("%<%.*s%> directive output truncated writing "
2704 "between %wu and %wu bytes into a region of size "
2705 "between %wu and %wu"))
2706 : G_("%<%.*s%> directive writing between %wu and "
2707 "%wu bytes into a region of size between %wu and %wu"));
2708 return fmtwarn (dirloc
, argloc
, NULL
,
2709 info
.warnopt (), fmtstr
, dir
.len
,
2710 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2711 res
.min
, res
.max
, avail_range
.min
, avail_range
.max
);
2717 ? G_("%<%.*s%> directive output may be truncated writing "
2718 "%wu or more bytes into a region of size between "
2720 : G_("%<%.*s%> directive output truncated writing "
2721 "%wu or more bytes into a region of size between "
2723 : G_("%<%.*s%> directive writing %wu or more bytes "
2724 "into a region of size between %wu and %wu"));
2725 return fmtwarn (dirloc
, argloc
, NULL
,
2726 info
.warnopt (), fmtstr
, dir
.len
,
2727 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2728 res
.min
, avail_range
.min
, avail_range
.max
);
2731 /* Compute the length of the output resulting from the directive DIR
2732 in a call described by INFO and update the overall result of the call
2733 in *RES. Return true if the directive has been handled. */
2736 format_directive (const sprintf_dom_walker::call_info
&info
,
2737 format_result
*res
, const directive
&dir
)
2739 /* Offset of the beginning of the directive from the beginning
2740 of the format string. */
2741 size_t offset
= dir
.beg
- info
.fmtstr
;
2742 size_t start
= offset
;
2743 size_t length
= offset
+ dir
.len
- !!dir
.len
;
2745 /* Create a location for the whole directive from the % to the format
2747 substring_loc
dirloc (info
.fmtloc
, TREE_TYPE (info
.format
),
2748 offset
, start
, length
);
2750 /* Also get the location of the argument if possible.
2751 This doesn't work for integer literals or function calls. */
2752 location_t argloc
= UNKNOWN_LOCATION
;
2754 argloc
= EXPR_LOCATION (dir
.arg
);
2756 /* Bail when there is no function to compute the output length,
2757 or when minimum length checking has been disabled. */
2758 if (!dir
.fmtfunc
|| res
->range
.min
>= HOST_WIDE_INT_MAX
)
2761 /* Compute the range of lengths of the formatted output. */
2762 fmtresult fmtres
= dir
.fmtfunc (dir
, dir
.arg
);
2764 /* Record whether the output of all directives is known to be
2765 bounded by some maximum, implying that their arguments are
2766 either known exactly or determined to be in a known range
2767 or, for strings, limited by the upper bounds of the arrays
2769 res
->knownrange
&= fmtres
.knownrange
;
2771 if (!fmtres
.knownrange
)
2773 /* Only when the range is known, check it against the host value
2774 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2775 INT_MAX precision, which is the longest possible output of any
2776 single directive). That's the largest valid byte count (though
2777 not valid call to a printf-like function because it can never
2778 return such a count). Otherwise, the range doesn't correspond
2779 to known values of the argument. */
2780 if (fmtres
.range
.max
> target_dir_max ())
2782 /* Normalize the MAX counter to avoid having to deal with it
2783 later. The counter can be less than HOST_WIDE_INT_M1U
2784 when compiling for an ILP32 target on an LP64 host. */
2785 fmtres
.range
.max
= HOST_WIDE_INT_M1U
;
2786 /* Disable exact and maximum length checking after a failure
2787 to determine the maximum number of characters (for example
2788 for wide characters or wide character strings) but continue
2789 tracking the minimum number of characters. */
2790 res
->range
.max
= HOST_WIDE_INT_M1U
;
2793 if (fmtres
.range
.min
> target_dir_max ())
2795 /* Disable exact length checking after a failure to determine
2796 even the minimum number of characters (it shouldn't happen
2797 except in an error) but keep tracking the minimum and maximum
2798 number of characters. */
2803 /* Buffer for the directive in the host character set (used when
2804 the source character set is different). */
2807 int dirlen
= dir
.len
;
2811 fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2812 "%<%.*s%> directive argument is null",
2813 dirlen
, target_to_host (hostdir
, sizeof hostdir
, dir
.beg
));
2815 /* Don't bother processing the rest of the format string. */
2817 res
->range
.min
= HOST_WIDE_INT_M1U
;
2818 res
->range
.max
= HOST_WIDE_INT_M1U
;
2822 /* Compute the number of available bytes in the destination. There
2823 must always be at least one byte of space for the terminating
2824 NUL that's appended after the format string has been processed. */
2825 result_range avail_range
= bytes_remaining (info
.objsize
, *res
);
2827 bool warned
= res
->warned
;
2830 warned
= maybe_warn (dirloc
, argloc
, info
, avail_range
,
2833 /* Bump up the total maximum if it isn't too big. */
2834 if (res
->range
.max
< HOST_WIDE_INT_MAX
2835 && fmtres
.range
.max
< HOST_WIDE_INT_MAX
)
2836 res
->range
.max
+= fmtres
.range
.max
;
2838 /* Raise the total unlikely maximum by the larger of the maximum
2839 and the unlikely maximum. */
2840 unsigned HOST_WIDE_INT save
= res
->range
.unlikely
;
2841 if (fmtres
.range
.max
< fmtres
.range
.unlikely
)
2842 res
->range
.unlikely
+= fmtres
.range
.unlikely
;
2844 res
->range
.unlikely
+= fmtres
.range
.max
;
2846 if (res
->range
.unlikely
< save
)
2847 res
->range
.unlikely
= HOST_WIDE_INT_M1U
;
2849 res
->range
.min
+= fmtres
.range
.min
;
2850 res
->range
.likely
+= fmtres
.range
.likely
;
2852 /* Has the minimum directive output length exceeded the maximum
2853 of 4095 bytes required to be supported? */
2854 bool minunder4k
= fmtres
.range
.min
< 4096;
2855 bool maxunder4k
= fmtres
.range
.max
< 4096;
2856 /* Clear UNDER4K in the overall result if the maximum has exceeded
2857 the 4k (this is necessary to avoid the return valuye optimization
2858 that may not be safe in the maximum case). */
2860 res
->under4k
= false;
2863 /* Only warn at level 2. */
2866 || (!maxunder4k
&& fmtres
.range
.max
< HOST_WIDE_INT_MAX
)))
2868 /* The directive output may be longer than the maximum required
2869 to be handled by an implementation according to 7.21.6.1, p15
2870 of C11. Warn on this only at level 2 but remember this and
2871 prevent folding the return value when done. This allows for
2872 the possibility of the actual libc call failing due to ENOMEM
2873 (like Glibc does under some conditions). */
2875 if (fmtres
.range
.min
== fmtres
.range
.max
)
2876 warned
= fmtwarn (dirloc
, argloc
, NULL
,
2878 "%<%.*s%> directive output of %wu bytes exceeds "
2879 "minimum required size of 4095",
2881 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2887 ? G_("%<%.*s%> directive output between %wu and %wu "
2888 "bytes may exceed minimum required size of 4095")
2889 : G_("%<%.*s%> directive output between %wu and %wu "
2890 "bytes exceeds minimum required size of 4095"));
2892 warned
= fmtwarn (dirloc
, argloc
, NULL
,
2893 info
.warnopt (), fmtstr
, dirlen
,
2894 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2895 fmtres
.range
.min
, fmtres
.range
.max
);
2899 /* Has the likely and maximum directive output exceeded INT_MAX? */
2900 bool likelyximax
= *dir
.beg
&& res
->range
.likely
> target_int_max ();
2901 /* Don't consider the maximum to be in excess when it's the result
2902 of a string of unknown length (i.e., whose maximum has been set
2903 to be greater than or equal to HOST_WIDE_INT_MAX. */
2904 bool maxximax
= (*dir
.beg
2905 && res
->range
.max
> target_int_max ()
2906 && res
->range
.max
< HOST_WIDE_INT_MAX
);
2909 /* Warn for the likely output size at level 1. */
2911 /* But only warn for the maximum at level 2. */
2914 && fmtres
.range
.max
< HOST_WIDE_INT_MAX
)))
2916 /* The directive output causes the total length of output
2917 to exceed INT_MAX bytes. */
2919 if (fmtres
.range
.min
== fmtres
.range
.max
)
2920 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2921 "%<%.*s%> directive output of %wu bytes causes "
2922 "result to exceed %<INT_MAX%>",
2924 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2929 = (fmtres
.range
.min
> target_int_max ()
2930 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2931 "bytes causes result to exceed %<INT_MAX%>")
2932 : G_ ("%<%.*s%> directive output between %wu and %wu "
2933 "bytes may cause result to exceed %<INT_MAX%>"));
2934 warned
= fmtwarn (dirloc
, argloc
, NULL
,
2935 info
.warnopt (), fmtstr
, dirlen
,
2936 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2937 fmtres
.range
.min
, fmtres
.range
.max
);
2941 if (warned
&& fmtres
.range
.min
< fmtres
.range
.likely
2942 && fmtres
.range
.likely
< fmtres
.range
.max
)
2943 /* Some languages have special plural rules even for large values,
2944 but it is periodic with period of 10, 100, 1000 etc. */
2945 inform_n (info
.fmtloc
,
2946 fmtres
.range
.likely
> INT_MAX
2947 ? (fmtres
.range
.likely
% 1000000) + 1000000
2948 : 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 #pragma GCC diagnostic pop
3020 /* Parse a format directive in function call described by INFO starting
3021 at STR and populate DIR structure. Bump up *ARGNO by the number of
3022 arguments extracted for the directive. Return the length of
3026 parse_directive (sprintf_dom_walker::call_info
&info
,
3027 directive
&dir
, format_result
*res
,
3028 const char *str
, unsigned *argno
)
3030 const char *pcnt
= strchr (str
, target_percent
);
3033 if (size_t len
= pcnt
? pcnt
- str
: *str
? strlen (str
) : 1)
3035 /* This directive is either a plain string or the terminating nul
3036 (which isn't really a directive but it simplifies things to
3037 handle it as if it were). */
3039 dir
.fmtfunc
= format_plain
;
3043 fprintf (dump_file
, " Directive %u at offset "
3044 HOST_WIDE_INT_PRINT_UNSIGNED
": \"%.*s\", "
3045 "length = " HOST_WIDE_INT_PRINT_UNSIGNED
"\n",
3047 (unsigned HOST_WIDE_INT
)(size_t)(dir
.beg
- info
.fmtstr
),
3048 (int)dir
.len
, dir
.beg
, (unsigned HOST_WIDE_INT
) dir
.len
);
3054 const char *pf
= pcnt
+ 1;
3056 /* POSIX numbered argument index or zero when none. */
3057 HOST_WIDE_INT dollar
= 0;
3059 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3060 when given by a va_list argument, and a non-negative value
3061 when specified in the format string itself. */
3062 HOST_WIDE_INT width
= -1;
3063 HOST_WIDE_INT precision
= -1;
3065 /* Pointers to the beginning of the width and precision decimal
3066 string (if any) within the directive. */
3067 const char *pwidth
= 0;
3068 const char *pprec
= 0;
3070 /* When the value of the decimal string that specifies width or
3071 precision is out of range, points to the digit that causes
3072 the value to exceed the limit. */
3073 const char *werange
= NULL
;
3074 const char *perange
= NULL
;
3076 /* Width specified via the asterisk. Need not be INTEGER_CST.
3077 For vararg functions set to void_node. */
3078 tree star_width
= NULL_TREE
;
3080 /* Width specified via the asterisk. Need not be INTEGER_CST.
3081 For vararg functions set to void_node. */
3082 tree star_precision
= NULL_TREE
;
3084 if (ISDIGIT (target_to_host (*pf
)))
3086 /* This could be either a POSIX positional argument, the '0'
3087 flag, or a width, depending on what follows. Store it as
3088 width and sort it out later after the next character has
3091 width
= target_strtol10 (&pf
, &werange
);
3093 else if (target_to_host (*pf
) == '*')
3095 /* Similarly to the block above, this could be either a POSIX
3096 positional argument or a width, depending on what follows. */
3097 if (*argno
< gimple_call_num_args (info
.callstmt
))
3098 star_width
= gimple_call_arg (info
.callstmt
, (*argno
)++);
3100 star_width
= void_node
;
3104 if (target_to_host (*pf
) == '$')
3106 /* Handle the POSIX dollar sign which references the 1-based
3107 positional argument number. */
3109 dollar
= width
+ info
.argidx
;
3111 && TREE_CODE (star_width
) == INTEGER_CST
3112 && (TYPE_PRECISION (TREE_TYPE (star_width
))
3113 <= TYPE_PRECISION (integer_type_node
)))
3114 dollar
= width
+ tree_to_shwi (star_width
);
3116 /* Bail when the numbered argument is out of range (it will
3117 have already been diagnosed by -Wformat). */
3119 || dollar
== (int)info
.argidx
3120 || dollar
> gimple_call_num_args (info
.callstmt
))
3125 star_width
= NULL_TREE
;
3130 if (dollar
|| !star_width
)
3136 /* The '0' that has been interpreted as a width above is
3137 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3138 and continue processing other flags. */
3144 /* (Non-zero) width has been seen. The next character
3145 is either a period or a digit. */
3146 goto start_precision
;
3149 /* When either '$' has been seen, or width has not been seen,
3150 the next field is the optional flags followed by an optional
3153 switch (target_to_host (*pf
))
3160 dir
.set_flag (target_to_host (*pf
++));
3169 if (ISDIGIT (target_to_host (*pf
)))
3173 width
= target_strtol10 (&pf
, &werange
);
3175 else if (target_to_host (*pf
) == '*')
3177 if (*argno
< gimple_call_num_args (info
.callstmt
))
3178 star_width
= gimple_call_arg (info
.callstmt
, (*argno
)++);
3181 /* This is (likely) a va_list. It could also be an invalid
3182 call with insufficient arguments. */
3183 star_width
= void_node
;
3187 else if (target_to_host (*pf
) == '\'')
3189 /* The POSIX apostrophe indicating a numeric grouping
3190 in the current locale. Even though it's possible to
3191 estimate the upper bound on the size of the output
3192 based on the number of digits it probably isn't worth
3199 if (target_to_host (*pf
) == '.')
3203 if (ISDIGIT (target_to_host (*pf
)))
3206 precision
= target_strtol10 (&pf
, &perange
);
3208 else if (target_to_host (*pf
) == '*')
3210 if (*argno
< gimple_call_num_args (info
.callstmt
))
3211 star_precision
= gimple_call_arg (info
.callstmt
, (*argno
)++);
3214 /* This is (likely) a va_list. It could also be an invalid
3215 call with insufficient arguments. */
3216 star_precision
= void_node
;
3222 /* The decimal precision or the asterisk are optional.
3223 When neither is dirified it's taken to be zero. */
3228 switch (target_to_host (*pf
))
3231 if (target_to_host (pf
[1]) == 'h')
3234 dir
.modifier
= FMT_LEN_hh
;
3237 dir
.modifier
= FMT_LEN_h
;
3242 dir
.modifier
= FMT_LEN_j
;
3247 dir
.modifier
= FMT_LEN_L
;
3252 if (target_to_host (pf
[1]) == 'l')
3255 dir
.modifier
= FMT_LEN_ll
;
3258 dir
.modifier
= FMT_LEN_l
;
3263 dir
.modifier
= FMT_LEN_t
;
3268 dir
.modifier
= FMT_LEN_z
;
3273 switch (target_to_host (*pf
))
3275 /* Handle a sole '%' character the same as "%%" but since it's
3276 undefined prevent the result from being folded. */
3279 res
->range
.min
= res
->range
.max
= HOST_WIDE_INT_M1U
;
3282 dir
.fmtfunc
= format_percent
;
3293 res
->floating
= true;
3294 dir
.fmtfunc
= format_floating
;
3303 dir
.fmtfunc
= format_integer
;
3307 /* The %p output is implementation-defined. It's possible
3308 to determine this format but due to extensions (edirially
3309 those of the Linux kernel -- see bug 78512) the first %p
3310 in the format string disables any further processing. */
3314 /* %n has side-effects even when nothing is actually printed to
3316 info
.nowrite
= false;
3317 dir
.fmtfunc
= format_none
;
3321 dir
.fmtfunc
= format_character
;
3326 dir
.fmtfunc
= format_string
;
3330 /* Unknown conversion specification. */
3334 dir
.specifier
= target_to_host (*pf
++);
3336 /* Store the length of the format directive. */
3337 dir
.len
= pf
- pcnt
;
3339 /* Buffer for the directive in the host character set (used when
3340 the source character set is different). */
3345 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width
)))
3346 dir
.set_width (star_width
);
3349 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3350 (width is the absolute value of that specified). */
3352 dir
.width
[1] = target_int_max () + 1;
3357 if (width
== LONG_MAX
&& werange
)
3359 size_t begin
= dir
.beg
- info
.fmtstr
+ (pwidth
- pcnt
);
3360 size_t caret
= begin
+ (werange
- pcnt
);
3361 size_t end
= pf
- info
.fmtstr
- 1;
3363 /* Create a location for the width part of the directive,
3364 pointing the caret at the first out-of-range digit. */
3365 substring_loc
dirloc (info
.fmtloc
, TREE_TYPE (info
.format
),
3368 fmtwarn (dirloc
, UNKNOWN_LOCATION
, NULL
,
3369 info
.warnopt (), "%<%.*s%> directive width out of range",
3370 dir
.len
, target_to_host (hostdir
, sizeof hostdir
, dir
.beg
));
3373 dir
.set_width (width
);
3378 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision
)))
3379 dir
.set_precision (star_precision
);
3382 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3383 (unlike width, negative precision is ignored). */
3385 dir
.prec
[1] = target_int_max ();
3390 if (precision
== LONG_MAX
&& perange
)
3392 size_t begin
= dir
.beg
- info
.fmtstr
+ (pprec
- pcnt
) - 1;
3393 size_t caret
= dir
.beg
- info
.fmtstr
+ (perange
- pcnt
) - 1;
3394 size_t end
= pf
- info
.fmtstr
- 2;
3396 /* Create a location for the precision part of the directive,
3397 including the leading period, pointing the caret at the first
3398 out-of-range digit . */
3399 substring_loc
dirloc (info
.fmtloc
, TREE_TYPE (info
.format
),
3402 fmtwarn (dirloc
, UNKNOWN_LOCATION
, NULL
,
3403 info
.warnopt (), "%<%.*s%> directive precision out of range",
3404 dir
.len
, target_to_host (hostdir
, sizeof hostdir
, dir
.beg
));
3407 dir
.set_precision (precision
);
3410 /* Extract the argument if the directive takes one and if it's
3411 available (e.g., the function doesn't take a va_list). Treat
3412 missing arguments the same as va_list, even though they will
3413 have likely already been diagnosed by -Wformat. */
3414 if (dir
.specifier
!= '%'
3415 && *argno
< gimple_call_num_args (info
.callstmt
))
3416 dir
.arg
= gimple_call_arg (info
.callstmt
, dollar
? dollar
: (*argno
)++);
3421 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3424 (unsigned HOST_WIDE_INT
)(size_t)(dir
.beg
- info
.fmtstr
),
3425 (int)dir
.len
, dir
.beg
);
3428 if (dir
.width
[0] == dir
.width
[1])
3429 fprintf (dump_file
, ", width = " HOST_WIDE_INT_PRINT_DEC
,
3433 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3434 ", " HOST_WIDE_INT_PRINT_DEC
"]",
3435 dir
.width
[0], dir
.width
[1]);
3440 if (dir
.prec
[0] == dir
.prec
[1])
3441 fprintf (dump_file
, ", precision = " HOST_WIDE_INT_PRINT_DEC
,
3445 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3446 HOST_WIDE_INT_PRINT_DEC
"]",
3447 dir
.prec
[0], dir
.prec
[1]);
3449 fputc ('\n', dump_file
);
3455 /* Compute the length of the output resulting from the call to a formatted
3456 output function described by INFO and store the result of the call in
3457 *RES. Issue warnings for detected past the end writes. Return true
3458 if the complete format string has been processed and *RES can be relied
3459 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3460 that caused the processing to be terminated early). */
3463 sprintf_dom_walker::compute_format_length (call_info
&info
,
3468 location_t callloc
= gimple_location (info
.callstmt
);
3469 fprintf (dump_file
, "%s:%i: ",
3470 LOCATION_FILE (callloc
), LOCATION_LINE (callloc
));
3471 print_generic_expr (dump_file
, info
.func
, dump_flags
);
3474 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3475 ", fmtstr = \"%s\"\n",
3476 info
.objsize
, info
.fmtstr
);
3479 /* Reset the minimum and maximum byte counters. */
3480 res
->range
.min
= res
->range
.max
= 0;
3482 /* No directive has been seen yet so the length of output is bounded
3483 by the known range [0, 0] (with no conversion producing more than
3484 4K bytes) until determined otherwise. */
3485 res
->knownrange
= true;
3486 res
->under4k
= true;
3487 res
->floating
= false;
3488 res
->warned
= false;
3490 /* 1-based directive counter. */
3493 /* The variadic argument counter. */
3494 unsigned argno
= info
.argidx
;
3496 for (const char *pf
= info
.fmtstr
; ; ++dirno
)
3498 directive dir
= directive ();
3501 size_t n
= parse_directive (info
, dir
, res
, pf
, &argno
);
3503 /* Return failure if the format function fails. */
3504 if (!format_directive (info
, res
, dir
))
3507 /* Return success the directive is zero bytes long and it's
3508 the last think in the format string (i.e., it's the terminating
3509 nul, which isn't really a directive but handling it as one makes
3517 /* The complete format string was processed (with or without warnings). */
3521 /* Return the size of the object referenced by the expression DEST if
3522 available, or -1 otherwise. */
3524 static unsigned HOST_WIDE_INT
3525 get_destination_size (tree dest
)
3527 /* Initialize object size info before trying to compute it. */
3528 init_object_sizes ();
3530 /* Use __builtin_object_size to determine the size of the destination
3531 object. When optimizing, determine the smallest object (such as
3532 a member array as opposed to the whole enclosing object), otherwise
3533 use type-zero object size to determine the size of the enclosing
3534 object (the function fails without optimization in this type). */
3535 int ost
= optimize
> 0;
3536 unsigned HOST_WIDE_INT size
;
3537 if (compute_builtin_object_size (dest
, ost
, &size
))
3540 return HOST_WIDE_INT_M1U
;
3543 /* Return true if the call described by INFO with result RES safe to
3544 optimize (i.e., no undefined behavior), and set RETVAL to the range
3545 of its return values. */
3548 is_call_safe (const sprintf_dom_walker::call_info
&info
,
3549 const format_result
&res
, bool under4k
,
3550 unsigned HOST_WIDE_INT retval
[2])
3552 if (under4k
&& !res
.under4k
)
3555 /* The minimum return value. */
3556 retval
[0] = res
.range
.min
;
3558 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3559 but in cases involving multibyte characters could be as large as
3560 RES.RANGE.UNLIKELY. */
3562 = res
.range
.unlikely
< res
.range
.max
? res
.range
.max
: res
.range
.unlikely
;
3564 /* Adjust the number of bytes which includes the terminating nul
3565 to reflect the return value of the function which does not.
3566 Because the valid range of the function is [INT_MIN, INT_MAX],
3567 a valid range before the adjustment below is [0, INT_MAX + 1]
3568 (the functions only return negative values on error or undefined
3570 if (retval
[0] <= target_int_max () + 1)
3572 if (retval
[1] <= target_int_max () + 1)
3575 /* Avoid the return value optimization when the behavior of the call
3576 is undefined either because any directive may have produced 4K or
3577 more of output, or the return value exceeds INT_MAX, or because
3578 the output overflows the destination object (but leave it enabled
3579 when the function is bounded because then the behavior is well-
3581 if (retval
[0] == retval
[1]
3582 && (info
.bounded
|| retval
[0] < info
.objsize
)
3583 && retval
[0] <= target_int_max ())
3586 if ((info
.bounded
|| retval
[1] < info
.objsize
)
3587 && (retval
[0] < target_int_max ()
3588 && retval
[1] < target_int_max ()))
3591 if (!under4k
&& (info
.bounded
|| retval
[0] < info
.objsize
))
3597 /* Given a suitable result RES of a call to a formatted output function
3598 described by INFO, substitute the result for the return value of
3599 the call. The result is suitable if the number of bytes it represents
3600 is known and exact. A result that isn't suitable for substitution may
3601 have its range set to the range of return values, if that is known.
3602 Return true if the call is removed and gsi_next should not be performed
3606 try_substitute_return_value (gimple_stmt_iterator
*gsi
,
3607 const sprintf_dom_walker::call_info
&info
,
3608 const format_result
&res
)
3610 tree lhs
= gimple_get_lhs (info
.callstmt
);
3612 /* Set to true when the entire call has been removed. */
3613 bool removed
= false;
3615 /* The minimum and maximum return value. */
3616 unsigned HOST_WIDE_INT retval
[2];
3617 bool safe
= is_call_safe (info
, res
, true, retval
);
3620 && retval
[0] == retval
[1]
3621 /* Not prepared to handle possibly throwing calls here; they shouldn't
3622 appear in non-artificial testcases, except when the __*_chk routines
3623 are badly declared. */
3624 && !stmt_ends_bb_p (info
.callstmt
))
3626 tree cst
= build_int_cst (integer_type_node
, retval
[0]);
3628 if (lhs
== NULL_TREE
3631 /* Remove the call to the bounded function with a zero size
3632 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3633 unlink_stmt_vdef (info
.callstmt
);
3634 gsi_remove (gsi
, true);
3637 else if (info
.nowrite
)
3639 /* Replace the call to the bounded function with a zero size
3640 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3642 if (!update_call_from_tree (gsi
, cst
))
3643 gimplify_and_update_call_from_tree (gsi
, cst
);
3644 gimple
*callstmt
= gsi_stmt (*gsi
);
3645 update_stmt (callstmt
);
3649 /* Replace the left-hand side of the call with the constant
3650 result of the formatted function. */
3651 gimple_call_set_lhs (info
.callstmt
, NULL_TREE
);
3652 gimple
*g
= gimple_build_assign (lhs
, cst
);
3653 gsi_insert_after (gsi
, g
, GSI_NEW_STMT
);
3654 update_stmt (info
.callstmt
);
3660 fprintf (dump_file
, " Removing call statement.");
3663 fprintf (dump_file
, " Substituting ");
3664 print_generic_expr (dump_file
, cst
, dump_flags
);
3665 fprintf (dump_file
, " for %s.\n",
3666 info
.nowrite
? "statement" : "return value");
3672 bool setrange
= false;
3675 && (info
.bounded
|| retval
[1] < info
.objsize
)
3676 && (retval
[0] < target_int_max ()
3677 && retval
[1] < target_int_max ()))
3679 /* If the result is in a valid range bounded by the size of
3680 the destination set it so that it can be used for subsequent
3682 int prec
= TYPE_PRECISION (integer_type_node
);
3684 wide_int min
= wi::shwi (retval
[0], prec
);
3685 wide_int max
= wi::shwi (retval
[1], prec
);
3686 set_range_info (lhs
, VR_RANGE
, min
, max
);
3693 const char *inbounds
3694 = (retval
[0] < info
.objsize
3695 ? (retval
[1] < info
.objsize
3696 ? "in" : "potentially out-of")
3699 const char *what
= setrange
? "Setting" : "Discarding";
3700 if (retval
[0] != retval
[1])
3702 " %s %s-bounds return value range ["
3703 HOST_WIDE_INT_PRINT_UNSIGNED
", "
3704 HOST_WIDE_INT_PRINT_UNSIGNED
"].\n",
3705 what
, inbounds
, retval
[0], retval
[1]);
3707 fprintf (dump_file
, " %s %s-bounds return value "
3708 HOST_WIDE_INT_PRINT_UNSIGNED
".\n",
3709 what
, inbounds
, retval
[0]);
3714 fputc ('\n', dump_file
);
3719 /* Try to simplify a s{,n}printf call described by INFO with result
3720 RES by replacing it with a simpler and presumably more efficient
3721 call (such as strcpy). */
3724 try_simplify_call (gimple_stmt_iterator
*gsi
,
3725 const sprintf_dom_walker::call_info
&info
,
3726 const format_result
&res
)
3728 unsigned HOST_WIDE_INT dummy
[2];
3729 if (!is_call_safe (info
, res
, info
.retval_used (), dummy
))
3732 switch (info
.fncode
)
3734 case BUILT_IN_SNPRINTF
:
3735 return gimple_fold_builtin_snprintf (gsi
);
3737 case BUILT_IN_SPRINTF
:
3738 return gimple_fold_builtin_sprintf (gsi
);
3747 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3748 functions and if so, handle it. Return true if the call is removed
3749 and gsi_next should not be performed in the caller. */
3752 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator
*gsi
)
3754 call_info info
= call_info ();
3756 info
.callstmt
= gsi_stmt (*gsi
);
3757 if (!gimple_call_builtin_p (info
.callstmt
, BUILT_IN_NORMAL
))
3760 info
.func
= gimple_call_fndecl (info
.callstmt
);
3761 info
.fncode
= DECL_FUNCTION_CODE (info
.func
);
3763 /* The size of the destination as in snprintf(dest, size, ...). */
3764 unsigned HOST_WIDE_INT dstsize
= HOST_WIDE_INT_M1U
;
3766 /* The size of the destination determined by __builtin_object_size. */
3767 unsigned HOST_WIDE_INT objsize
= HOST_WIDE_INT_M1U
;
3769 /* Buffer size argument number (snprintf and vsnprintf). */
3770 unsigned HOST_WIDE_INT idx_dstsize
= HOST_WIDE_INT_M1U
;
3772 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3773 unsigned HOST_WIDE_INT idx_objsize
= HOST_WIDE_INT_M1U
;
3775 /* Format string argument number (valid for all functions). */
3776 unsigned idx_format
;
3778 switch (info
.fncode
)
3780 case BUILT_IN_SPRINTF
:
3782 // __builtin_sprintf (dst, format, ...)
3787 case BUILT_IN_SPRINTF_CHK
:
3789 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3795 case BUILT_IN_SNPRINTF
:
3797 // __builtin_snprintf (dst, size, format, ...)
3801 info
.bounded
= true;
3804 case BUILT_IN_SNPRINTF_CHK
:
3806 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3811 info
.bounded
= true;
3814 case BUILT_IN_VSNPRINTF
:
3816 // __builtin_vsprintf (dst, size, format, va)
3820 info
.bounded
= true;
3823 case BUILT_IN_VSNPRINTF_CHK
:
3825 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3830 info
.bounded
= true;
3833 case BUILT_IN_VSPRINTF
:
3835 // __builtin_vsprintf (dst, format, va)
3840 case BUILT_IN_VSPRINTF_CHK
:
3842 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3852 /* Set the global warning level for this function. */
3853 warn_level
= info
.bounded
? warn_format_trunc
: warn_format_overflow
;
3855 /* The first argument is a pointer to the destination. */
3856 tree dstptr
= gimple_call_arg (info
.callstmt
, 0);
3858 info
.format
= gimple_call_arg (info
.callstmt
, idx_format
);
3860 /* True when the destination size is constant as opposed to the lower
3861 or upper bound of a range. */
3862 bool dstsize_cst_p
= true;
3864 if (idx_dstsize
== HOST_WIDE_INT_M1U
)
3866 /* For non-bounded functions like sprintf, determine the size
3867 of the destination from the object or pointer passed to it
3868 as the first argument. */
3869 dstsize
= get_destination_size (dstptr
);
3871 else if (tree size
= gimple_call_arg (info
.callstmt
, idx_dstsize
))
3873 /* For bounded functions try to get the size argument. */
3875 if (TREE_CODE (size
) == INTEGER_CST
)
3877 dstsize
= tree_to_uhwi (size
);
3878 /* No object can be larger than SIZE_MAX bytes (half the address
3879 space) on the target.
3880 The functions are defined only for output of at most INT_MAX
3881 bytes. Specifying a bound in excess of that limit effectively
3882 defeats the bounds checking (and on some implementations such
3883 as Solaris cause the function to fail with EINVAL). */
3884 if (dstsize
> target_size_max () / 2)
3886 /* Avoid warning if -Wstringop-overflow is specified since
3887 it also warns for the same thing though only for the
3888 checking built-ins. */
3889 if ((idx_objsize
== HOST_WIDE_INT_M1U
3890 || !warn_stringop_overflow
))
3891 warning_at (gimple_location (info
.callstmt
), info
.warnopt (),
3892 "specified bound %wu exceeds maximum object size "
3894 dstsize
, target_size_max () / 2);
3896 else if (dstsize
> target_int_max ())
3897 warning_at (gimple_location (info
.callstmt
), info
.warnopt (),
3898 "specified bound %wu exceeds %<INT_MAX%>",
3901 else if (TREE_CODE (size
) == SSA_NAME
)
3903 /* Try to determine the range of values of the argument
3904 and use the greater of the two at level 1 and the smaller
3905 of them at level 2. */
3906 value_range
*vr
= evrp_range_analyzer
.get_value_range (size
);
3907 if (vr
->type
== VR_RANGE
3908 && TREE_CODE (vr
->min
) == INTEGER_CST
3909 && TREE_CODE (vr
->max
) == INTEGER_CST
)
3910 dstsize
= (warn_level
< 2
3911 ? TREE_INT_CST_LOW (vr
->max
)
3912 : TREE_INT_CST_LOW (vr
->min
));
3914 /* The destination size is not constant. If the function is
3915 bounded (e.g., snprintf) a lower bound of zero doesn't
3916 necessarily imply it can be eliminated. */
3917 dstsize_cst_p
= false;
3921 if (idx_objsize
!= HOST_WIDE_INT_M1U
)
3922 if (tree size
= gimple_call_arg (info
.callstmt
, idx_objsize
))
3923 if (tree_fits_uhwi_p (size
))
3924 objsize
= tree_to_uhwi (size
);
3926 if (info
.bounded
&& !dstsize
)
3928 /* As a special case, when the explicitly specified destination
3929 size argument (to a bounded function like snprintf) is zero
3930 it is a request to determine the number of bytes on output
3931 without actually producing any. Pretend the size is
3932 unlimited in this case. */
3933 info
.objsize
= HOST_WIDE_INT_MAX
;
3934 info
.nowrite
= dstsize_cst_p
;
3938 /* For calls to non-bounded functions or to those of bounded
3939 functions with a non-zero size, warn if the destination
3941 if (integer_zerop (dstptr
))
3943 /* This is diagnosed with -Wformat only when the null is a constant
3944 pointer. The warning here diagnoses instances where the pointer
3946 location_t loc
= gimple_location (info
.callstmt
);
3947 warning_at (EXPR_LOC_OR_LOC (dstptr
, loc
),
3948 info
.warnopt (), "null destination pointer");
3952 /* Set the object size to the smaller of the two arguments
3953 of both have been specified and they're not equal. */
3954 info
.objsize
= dstsize
< objsize
? dstsize
: objsize
;
3957 && dstsize
< target_size_max () / 2 && objsize
< dstsize
3958 /* Avoid warning if -Wstringop-overflow is specified since
3959 it also warns for the same thing though only for the
3960 checking built-ins. */
3961 && (idx_objsize
== HOST_WIDE_INT_M1U
3962 || !warn_stringop_overflow
))
3964 warning_at (gimple_location (info
.callstmt
), info
.warnopt (),
3965 "specified bound %wu exceeds the size %wu "
3966 "of the destination object", dstsize
, objsize
);
3970 if (integer_zerop (info
.format
))
3972 /* This is diagnosed with -Wformat only when the null is a constant
3973 pointer. The warning here diagnoses instances where the pointer
3975 location_t loc
= gimple_location (info
.callstmt
);
3976 warning_at (EXPR_LOC_OR_LOC (info
.format
, loc
),
3977 info
.warnopt (), "null format string");
3981 info
.fmtstr
= get_format_string (info
.format
, &info
.fmtloc
);
3985 /* The result is the number of bytes output by the formatted function,
3986 including the terminating NUL. */
3987 format_result res
= format_result ();
3989 bool success
= compute_format_length (info
, &res
);
3991 /* When optimizing and the printf return value optimization is enabled,
3992 attempt to substitute the computed result for the return value of
3993 the call. Avoid this optimization when -frounding-math is in effect
3994 and the format string contains a floating point directive. */
3995 bool call_removed
= false;
3996 if (success
&& optimize
> 0)
3998 /* Save a copy of the iterator pointing at the call. The iterator
3999 may change to point past the call in try_substitute_return_value
4000 but the original value is needed in try_simplify_call. */
4001 gimple_stmt_iterator gsi_call
= *gsi
;
4003 if (flag_printf_return_value
4004 && (!flag_rounding_math
|| !res
.floating
))
4005 call_removed
= try_substitute_return_value (gsi
, info
, res
);
4008 try_simplify_call (&gsi_call
, info
, res
);
4011 return call_removed
;
4015 sprintf_dom_walker::before_dom_children (basic_block bb
)
4017 evrp_range_analyzer
.enter (bb
);
4018 for (gimple_stmt_iterator si
= gsi_start_bb (bb
); !gsi_end_p (si
); )
4020 /* Iterate over statements, looking for function calls. */
4021 gimple
*stmt
= gsi_stmt (si
);
4023 /* First record ranges generated by this statement. */
4024 evrp_range_analyzer
.record_ranges_from_stmt (stmt
, false);
4026 if (is_gimple_call (stmt
) && handle_gimple_call (&si
))
4027 /* If handle_gimple_call returns true, the iterator is
4028 already pointing to the next statement. */
4037 sprintf_dom_walker::after_dom_children (basic_block bb
)
4039 evrp_range_analyzer
.leave (bb
);
4042 /* Execute the pass for function FUN. */
4045 pass_sprintf_length::execute (function
*fun
)
4047 init_target_to_host_charmap ();
4049 calculate_dominance_info (CDI_DOMINATORS
);
4051 sprintf_dom_walker sprintf_dom_walker
;
4052 sprintf_dom_walker
.walk (ENTRY_BLOCK_PTR_FOR_FN (fun
));
4054 /* Clean up object size info. */
4055 fini_object_sizes ();
4059 } /* Unnamed namespace. */
4061 /* Return a pointer to a pass object newly constructed from the context
4065 make_pass_sprintf_length (gcc::context
*ctxt
)
4067 return new pass_sprintf_length (ctxt
);