Update ChangeLog and version files for release
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blobd3771ddcc67b5eb77dfa61c169b32b1b88a332e7
1 /* Copyright (C) 2016-2017 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
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
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. */
48 #include "config.h"
49 #include "system.h"
50 #include "coretypes.h"
51 #include "backend.h"
52 #include "tree.h"
53 #include "gimple.h"
54 #include "tree-pass.h"
55 #include "ssa.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"
61 #include "tree-ssa.h"
62 #include "tree-object-size.h"
63 #include "params.h"
64 #include "tree-cfg.h"
65 #include "tree-ssa-propagate.h"
66 #include "calls.h"
67 #include "cfgloop.h"
68 #include "intl.h"
70 #include "builtins.h"
71 #include "stor-layout.h"
73 #include "realmpfr.h"
74 #include "target.h"
76 #include "cpplib.h"
77 #include "input.h"
78 #include "toplev.h"
79 #include "substring-locations.h"
80 #include "diagnostic.h"
82 /* The likely worst case value of MB_LEN_MAX for the target, large enough
83 for UTF-8. Ideally, this would be obtained by a target hook if it were
84 to be used for optimization but it's good enough as is for warnings. */
85 #define target_mb_len_max() 6
87 /* The maximum number of bytes a single non-string directive can result
88 in. This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
89 LDBL_MAX_10_EXP of 4932. */
90 #define IEEE_MAX_10_EXP 4932
91 #define target_dir_max() (target_int_max () + IEEE_MAX_10_EXP + 2)
93 namespace {
95 const pass_data pass_data_sprintf_length = {
96 GIMPLE_PASS, // pass type
97 "printf-return-value", // pass name
98 OPTGROUP_NONE, // optinfo_flags
99 TV_NONE, // tv_id
100 PROP_cfg, // properties_required
101 0, // properties_provided
102 0, // properties_destroyed
103 0, // properties_start
104 0, // properties_finish
107 /* Set to the warning level for the current function which is equal
108 either to warn_format_trunc for bounded functions or to
109 warn_format_overflow otherwise. */
111 static int warn_level;
113 struct format_result;
115 class pass_sprintf_length : public gimple_opt_pass
117 bool fold_return_value;
119 public:
120 pass_sprintf_length (gcc::context *ctxt)
121 : gimple_opt_pass (pass_data_sprintf_length, ctxt),
122 fold_return_value (false)
125 opt_pass * clone () { return new pass_sprintf_length (m_ctxt); }
127 virtual bool gate (function *);
129 virtual unsigned int execute (function *);
131 void set_pass_param (unsigned int n, bool param)
133 gcc_assert (n == 0);
134 fold_return_value = param;
137 bool handle_gimple_call (gimple_stmt_iterator *);
139 struct call_info;
140 bool compute_format_length (call_info &, format_result *);
143 bool
144 pass_sprintf_length::gate (function *)
146 /* Run the pass iff -Warn-format-overflow or -Warn-format-truncation
147 is specified and either not optimizing and the pass is being invoked
148 early, or when optimizing and the pass is being invoked during
149 optimization (i.e., "late"). */
150 return ((warn_format_overflow > 0
151 || warn_format_trunc > 0
152 || flag_printf_return_value)
153 && (optimize > 0) == fold_return_value);
156 /* The minimum, maximum, likely, and unlikely maximum number of bytes
157 of output either a formatting function or an individual directive
158 can result in. */
160 struct result_range
162 /* The absolute minimum number of bytes. The result of a successful
163 conversion is guaranteed to be no less than this. (An erroneous
164 conversion can be indicated by MIN > HOST_WIDE_INT_MAX.) */
165 unsigned HOST_WIDE_INT min;
166 /* The likely maximum result that is used in diagnostics. In most
167 cases MAX is the same as the worst case UNLIKELY result. */
168 unsigned HOST_WIDE_INT max;
169 /* The likely result used to trigger diagnostics. For conversions
170 that result in a range of bytes [MIN, MAX], LIKELY is somewhere
171 in that range. */
172 unsigned HOST_WIDE_INT likely;
173 /* In rare cases (e.g., for nultibyte characters) UNLIKELY gives
174 the worst cases maximum result of a directive. In most cases
175 UNLIKELY == MAX. UNLIKELY is used to control the return value
176 optimization but not in diagnostics. */
177 unsigned HOST_WIDE_INT unlikely;
180 /* The result of a call to a formatted function. */
182 struct format_result
184 /* Range of characters written by the formatted function.
185 Setting the minimum to HOST_WIDE_INT_MAX disables all
186 length tracking for the remainder of the format string. */
187 result_range range;
189 /* True when the range above is obtained from known values of
190 directive arguments, or bounds on the amount of output such
191 as width and precision, and not the result of heuristics that
192 depend on warning levels. It's used to issue stricter diagnostics
193 in cases where strings of unknown lengths are bounded by the arrays
194 they are determined to refer to. KNOWNRANGE must not be used for
195 the return value optimization. */
196 bool knownrange;
198 /* True if no individual directive resulted in more than 4095 bytes
199 of output (the total NUMBER_CHARS_{MIN,MAX} might be greater).
200 Implementations are not required to handle directives that produce
201 more than 4K bytes (leading to undefined behavior) and so when one
202 is found it disables the return value optimization. */
203 bool under4k;
205 /* True when a floating point directive has been seen in the format
206 string. */
207 bool floating;
209 /* True when an intermediate result has caused a warning. Used to
210 avoid issuing duplicate warnings while finishing the processing
211 of a call. WARNED also disables the return value optimization. */
212 bool warned;
214 /* Preincrement the number of output characters by 1. */
215 format_result& operator++ ()
217 return *this += 1;
220 /* Postincrement the number of output characters by 1. */
221 format_result operator++ (int)
223 format_result prev (*this);
224 *this += 1;
225 return prev;
228 /* Increment the number of output characters by N. */
229 format_result& operator+= (unsigned HOST_WIDE_INT);
232 format_result&
233 format_result::operator+= (unsigned HOST_WIDE_INT n)
235 gcc_assert (n < HOST_WIDE_INT_MAX);
237 if (range.min < HOST_WIDE_INT_MAX)
238 range.min += n;
240 if (range.max < HOST_WIDE_INT_MAX)
241 range.max += n;
243 if (range.likely < HOST_WIDE_INT_MAX)
244 range.likely += n;
246 if (range.unlikely < HOST_WIDE_INT_MAX)
247 range.unlikely += n;
249 return *this;
252 /* Return the value of INT_MIN for the target. */
254 static inline HOST_WIDE_INT
255 target_int_min ()
257 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
260 /* Return the value of INT_MAX for the target. */
262 static inline unsigned HOST_WIDE_INT
263 target_int_max ()
265 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
268 /* Return the value of SIZE_MAX for the target. */
270 static inline unsigned HOST_WIDE_INT
271 target_size_max ()
273 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
276 /* Return the constant initial value of DECL if available or DECL
277 otherwise. Same as the synonymous function in c/c-typeck.c. */
279 static tree
280 decl_constant_value (tree decl)
282 if (/* Don't change a variable array bound or initial value to a constant
283 in a place where a variable is invalid. Note that DECL_INITIAL
284 isn't valid for a PARM_DECL. */
285 current_function_decl != 0
286 && TREE_CODE (decl) != PARM_DECL
287 && !TREE_THIS_VOLATILE (decl)
288 && TREE_READONLY (decl)
289 && DECL_INITIAL (decl) != 0
290 && TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK
291 /* This is invalid if initial value is not constant.
292 If it has either a function call, a memory reference,
293 or a variable, then re-evaluating it could give different results. */
294 && TREE_CONSTANT (DECL_INITIAL (decl))
295 /* Check for cases where this is sub-optimal, even though valid. */
296 && TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)
297 return DECL_INITIAL (decl);
298 return decl;
301 /* Given FORMAT, set *PLOC to the source location of the format string
302 and return the format string if it is known or null otherwise. */
304 static const char*
305 get_format_string (tree format, location_t *ploc)
307 if (VAR_P (format))
309 /* Pull out a constant value if the front end didn't. */
310 format = decl_constant_value (format);
311 STRIP_NOPS (format);
314 if (integer_zerop (format))
316 /* FIXME: Diagnose null format string if it hasn't been diagnosed
317 by -Wformat (the latter diagnoses only nul pointer constants,
318 this pass can do better). */
319 return NULL;
322 HOST_WIDE_INT offset = 0;
324 if (TREE_CODE (format) == POINTER_PLUS_EXPR)
326 tree arg0 = TREE_OPERAND (format, 0);
327 tree arg1 = TREE_OPERAND (format, 1);
328 STRIP_NOPS (arg0);
329 STRIP_NOPS (arg1);
331 if (TREE_CODE (arg1) != INTEGER_CST)
332 return NULL;
334 format = arg0;
336 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
337 if (!cst_and_fits_in_hwi (arg1))
338 return NULL;
340 offset = int_cst_value (arg1);
343 if (TREE_CODE (format) != ADDR_EXPR)
344 return NULL;
346 *ploc = EXPR_LOC_OR_LOC (format, input_location);
348 format = TREE_OPERAND (format, 0);
350 if (TREE_CODE (format) == ARRAY_REF
351 && tree_fits_shwi_p (TREE_OPERAND (format, 1))
352 && (offset += tree_to_shwi (TREE_OPERAND (format, 1))) >= 0)
353 format = TREE_OPERAND (format, 0);
355 if (offset < 0)
356 return NULL;
358 tree array_init;
359 tree array_size = NULL_TREE;
361 if (VAR_P (format)
362 && TREE_CODE (TREE_TYPE (format)) == ARRAY_TYPE
363 && (array_init = decl_constant_value (format)) != format
364 && TREE_CODE (array_init) == STRING_CST)
366 /* Extract the string constant initializer. Note that this may
367 include a trailing NUL character that is not in the array (e.g.
368 const char a[3] = "foo";). */
369 array_size = DECL_SIZE_UNIT (format);
370 format = array_init;
373 if (TREE_CODE (format) != STRING_CST)
374 return NULL;
376 if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format))) != char_type_node)
378 /* Wide format string. */
379 return NULL;
382 const char *fmtstr = TREE_STRING_POINTER (format);
383 unsigned fmtlen = TREE_STRING_LENGTH (format);
385 if (array_size)
387 /* Variable length arrays can't be initialized. */
388 gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
390 if (tree_fits_shwi_p (array_size))
392 HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
393 if (array_size_value > 0
394 && array_size_value == (int) array_size_value
395 && fmtlen > array_size_value)
396 fmtlen = array_size_value;
399 if (offset)
401 if (offset >= fmtlen)
402 return NULL;
404 fmtstr += offset;
405 fmtlen -= offset;
408 if (fmtlen < 1 || fmtstr[--fmtlen] != 0)
410 /* FIXME: Diagnose an unterminated format string if it hasn't been
411 diagnosed by -Wformat. Similarly to a null format pointer,
412 -Wformay diagnoses only nul pointer constants, this pass can
413 do better). */
414 return NULL;
417 return fmtstr;
420 /* The format_warning_at_substring function is not used here in a way
421 that makes using attribute format viable. Suppress the warning. */
423 #pragma GCC diagnostic push
424 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
426 /* For convenience and brevity. */
428 static bool
429 (* const fmtwarn) (const substring_loc &, const source_range *,
430 const char *, int, const char *, ...)
431 = format_warning_at_substring;
433 /* Format length modifiers. */
435 enum format_lengths
437 FMT_LEN_none,
438 FMT_LEN_hh, // char argument
439 FMT_LEN_h, // short
440 FMT_LEN_l, // long
441 FMT_LEN_ll, // long long
442 FMT_LEN_L, // long double (and GNU long long)
443 FMT_LEN_z, // size_t
444 FMT_LEN_t, // ptrdiff_t
445 FMT_LEN_j // intmax_t
449 /* Description of the result of conversion either of a single directive
450 or the whole format string. */
452 struct fmtresult
454 /* Construct a FMTRESULT object with all counters initialized
455 to MIN. KNOWNRANGE is set when MIN is valid. */
456 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
457 : argmin (), argmax (),
458 knownrange (min < HOST_WIDE_INT_MAX),
459 nullp ()
461 range.min = min;
462 range.max = min;
463 range.likely = min;
464 range.unlikely = min;
467 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
468 KNOWNRANGE is set when both MIN and MAX are valid. */
469 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
470 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
471 : argmin (), argmax (),
472 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
473 nullp ()
475 range.min = min;
476 range.max = max;
477 range.likely = max < likely ? min : likely;
478 range.unlikely = max;
481 /* Adjust result upward to reflect the RANGE of values the specified
482 width or precision is known to be in. */
483 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
484 tree = NULL_TREE,
485 unsigned = 0, unsigned = 0);
487 /* Return the maximum number of decimal digits a value of TYPE
488 formats as on output. */
489 static unsigned type_max_digits (tree, int);
491 /* The range a directive's argument is in. */
492 tree argmin, argmax;
494 /* The minimum and maximum number of bytes that a directive
495 results in on output for an argument in the range above. */
496 result_range range;
498 /* True when the range above is obtained from a known value of
499 a directive's argument or its bounds and not the result of
500 heuristics that depend on warning levels. */
501 bool knownrange;
503 /* True when the argument is a null pointer. */
504 bool nullp;
507 /* Adjust result upward to reflect the range ADJUST of values the
508 specified width or precision is known to be in. When non-null,
509 TYPE denotes the type of the directive whose result is being
510 adjusted, BASE gives the base of the directive (octal, decimal,
511 or hex), and ADJ denotes the additional adjustment to the LIKELY
512 counter that may need to be added when ADJUST is a range. */
514 fmtresult&
515 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
516 tree type /* = NULL_TREE */,
517 unsigned base /* = 0 */,
518 unsigned adj /* = 0 */)
520 bool minadjusted = false;
522 /* Adjust the minimum and likely counters. */
523 if (adjust[0] >= 0)
525 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
527 range.min = adjust[0];
528 minadjusted = true;
531 /* Adjust the likely counter. */
532 if (range.likely < range.min)
533 range.likely = range.min;
535 else if (adjust[0] == target_int_min ()
536 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
537 knownrange = false;
539 /* Adjust the maximum counter. */
540 if (adjust[1] > 0)
542 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
544 range.max = adjust[1];
546 /* Set KNOWNRANGE if both the minimum and maximum have been
547 adjusted. Otherwise leave it at what it was before. */
548 knownrange = minadjusted;
552 if (warn_level > 1 && type)
554 /* For large non-constant width or precision whose range spans
555 the maximum number of digits produced by the directive for
556 any argument, set the likely number of bytes to be at most
557 the number digits plus other adjustment determined by the
558 caller (one for sign or two for the hexadecimal "0x"
559 prefix). */
560 unsigned dirdigs = type_max_digits (type, base);
561 if (adjust[0] < dirdigs && dirdigs < adjust[1]
562 && range.likely < dirdigs)
563 range.likely = dirdigs + adj;
565 else if (range.likely < (range.min ? range.min : 1))
567 /* Conservatively, set LIKELY to at least MIN but no less than
568 1 unless MAX is zero. */
569 range.likely = (range.min
570 ? range.min
571 : range.max && (range.max < HOST_WIDE_INT_MAX
572 || warn_level > 1) ? 1 : 0);
575 /* Finally adjust the unlikely counter to be at least as large as
576 the maximum. */
577 if (range.unlikely < range.max)
578 range.unlikely = range.max;
580 return *this;
583 /* Return the maximum number of digits a value of TYPE formats in
584 BASE on output, not counting base prefix . */
586 unsigned
587 fmtresult::type_max_digits (tree type, int base)
589 unsigned prec = TYPE_PRECISION (type);
590 if (base == 8)
591 return (prec + 2) / 3;
593 if (base == 16)
594 return prec / 4;
596 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
597 of 8, 16, 32, and 64 bits. */
598 return prec * 301 / 1000 + 1;
601 static bool
602 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT);
604 /* Description of a format directive. A directive is either a plain
605 string or a conversion specification that starts with '%'. */
607 struct directive
609 /* The 1-based directive number (for debugging). */
610 unsigned dirno;
612 /* The first character of the directive and its length. */
613 const char *beg;
614 size_t len;
616 /* A bitmap of flags, one for each character. */
617 unsigned flags[256 / sizeof (int)];
619 /* The range of values of the specified width, or -1 if not specified. */
620 HOST_WIDE_INT width[2];
621 /* The range of values of the specified precision, or -1 if not
622 specified. */
623 HOST_WIDE_INT prec[2];
625 /* Length modifier. */
626 format_lengths modifier;
628 /* Format specifier character. */
629 char specifier;
631 /* The argument of the directive or null when the directive doesn't
632 take one or when none is available (such as for vararg functions). */
633 tree arg;
635 /* Format conversion function that given a directive and an argument
636 returns the formatting result. */
637 fmtresult (*fmtfunc) (const directive &, tree);
639 /* Return True when a the format flag CHR has been used. */
640 bool get_flag (char chr) const
642 unsigned char c = chr & 0xff;
643 return (flags[c / (CHAR_BIT * sizeof *flags)]
644 & (1U << (c % (CHAR_BIT * sizeof *flags))));
647 /* Make a record of the format flag CHR having been used. */
648 void set_flag (char chr)
650 unsigned char c = chr & 0xff;
651 flags[c / (CHAR_BIT * sizeof *flags)]
652 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
655 /* Reset the format flag CHR. */
656 void clear_flag (char chr)
658 unsigned char c = chr & 0xff;
659 flags[c / (CHAR_BIT * sizeof *flags)]
660 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
663 /* Set both bounds of the width range to VAL. */
664 void set_width (HOST_WIDE_INT val)
666 width[0] = width[1] = val;
669 /* Set the width range according to ARG, with both bounds being
670 no less than 0. For a constant ARG set both bounds to its value
671 or 0, whichever is greater. For a non-constant ARG in some range
672 set width to its range adjusting each bound to -1 if it's less.
673 For an indeterminate ARG set width to [0, INT_MAX]. */
674 void set_width (tree arg)
676 get_int_range (arg, width, width + 1, true, 0);
679 /* Set both bounds of the precision range to VAL. */
680 void set_precision (HOST_WIDE_INT val)
682 prec[0] = prec[1] = val;
685 /* Set the precision range according to ARG, with both bounds being
686 no less than -1. For a constant ARG set both bounds to its value
687 or -1 whichever is greater. For a non-constant ARG in some range
688 set precision to its range adjusting each bound to -1 if it's less.
689 For an indeterminate ARG set precision to [-1, INT_MAX]. */
690 void set_precision (tree arg)
692 get_int_range (arg, prec, prec + 1, false, -1);
695 /* Return true if both width and precision are known to be
696 either constant or in some range, false otherwise. */
697 bool known_width_and_precision () const
699 return ((width[1] < 0
700 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
701 && (prec[1] < 0
702 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
706 /* Return the logarithm of X in BASE. */
708 static int
709 ilog (unsigned HOST_WIDE_INT x, int base)
711 int res = 0;
714 ++res;
715 x /= base;
716 } while (x);
717 return res;
720 /* Return the number of bytes resulting from converting into a string
721 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
722 PLUS indicates whether 1 for a plus sign should be added for positive
723 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
724 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
725 be represented. */
727 static HOST_WIDE_INT
728 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
730 unsigned HOST_WIDE_INT absval;
732 HOST_WIDE_INT res;
734 if (TYPE_UNSIGNED (TREE_TYPE (x)))
736 if (tree_fits_uhwi_p (x))
738 absval = tree_to_uhwi (x);
739 res = plus;
741 else
742 return -1;
744 else
746 if (tree_fits_shwi_p (x))
748 HOST_WIDE_INT i = tree_to_shwi (x);
749 if (HOST_WIDE_INT_MIN == i)
751 /* Avoid undefined behavior due to negating a minimum. */
752 absval = HOST_WIDE_INT_MAX;
753 res = 1;
755 else if (i < 0)
757 absval = -i;
758 res = 1;
760 else
762 absval = i;
763 res = plus;
766 else
767 return -1;
770 int ndigs = ilog (absval, base);
772 res += prec < ndigs ? ndigs : prec;
774 /* Adjust a non-zero value for the base prefix, either hexadecimal,
775 or, unless precision has resulted in a leading zero, also octal. */
776 if (prefix && absval && (base == 16 || prec <= ndigs))
778 if (base == 8)
779 res += 1;
780 else if (base == 16)
781 res += 2;
784 return res;
787 /* Given the formatting result described by RES and NAVAIL, the number
788 of available in the destination, return the range of bytes remaining
789 in the destination. */
791 static inline result_range
792 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
794 result_range range;
796 if (HOST_WIDE_INT_MAX <= navail)
798 range.min = range.max = range.likely = range.unlikely = navail;
799 return range;
802 /* The lower bound of the available range is the available size
803 minus the maximum output size, and the upper bound is the size
804 minus the minimum. */
805 range.max = res.range.min < navail ? navail - res.range.min : 0;
807 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
809 if (res.range.max < HOST_WIDE_INT_MAX)
810 range.min = res.range.max < navail ? navail - res.range.max : 0;
811 else
812 range.min = range.likely;
814 range.unlikely = (res.range.unlikely < navail
815 ? navail - res.range.unlikely : 0);
817 return range;
820 /* Description of a call to a formatted function. */
822 struct pass_sprintf_length::call_info
824 /* Function call statement. */
825 gimple *callstmt;
827 /* Function called. */
828 tree func;
830 /* Called built-in function code. */
831 built_in_function fncode;
833 /* Format argument and format string extracted from it. */
834 tree format;
835 const char *fmtstr;
837 /* The location of the format argument. */
838 location_t fmtloc;
840 /* The destination object size for __builtin___xxx_chk functions
841 typically determined by __builtin_object_size, or -1 if unknown. */
842 unsigned HOST_WIDE_INT objsize;
844 /* Number of the first variable argument. */
845 unsigned HOST_WIDE_INT argidx;
847 /* True for functions like snprintf that specify the size of
848 the destination, false for others like sprintf that don't. */
849 bool bounded;
851 /* True for bounded functions like snprintf that specify a zero-size
852 buffer as a request to compute the size of output without actually
853 writing any. NOWRITE is cleared in response to the %n directive
854 which has side-effects similar to writing output. */
855 bool nowrite;
857 /* Return true if the called function's return value is used. */
858 bool retval_used () const
860 return gimple_get_lhs (callstmt);
863 /* Return the warning option corresponding to the called function. */
864 int warnopt () const
866 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
870 /* Return the result of formatting a no-op directive (such as '%n'). */
872 static fmtresult
873 format_none (const directive &, tree)
875 fmtresult res (0);
876 return res;
879 /* Return the result of formatting the '%%' directive. */
881 static fmtresult
882 format_percent (const directive &, tree)
884 fmtresult res (1);
885 return res;
889 /* Compute intmax_type_node and uintmax_type_node similarly to how
890 tree.c builds size_type_node. */
892 static void
893 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
895 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
897 *pintmax = integer_type_node;
898 *puintmax = unsigned_type_node;
900 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
902 *pintmax = long_integer_type_node;
903 *puintmax = long_unsigned_type_node;
905 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
907 *pintmax = long_long_integer_type_node;
908 *puintmax = long_long_unsigned_type_node;
910 else
912 for (int i = 0; i < NUM_INT_N_ENTS; i++)
913 if (int_n_enabled_p[i])
915 char name[50];
916 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
918 if (strcmp (name, UINTMAX_TYPE) == 0)
920 *pintmax = int_n_trees[i].signed_type;
921 *puintmax = int_n_trees[i].unsigned_type;
922 return;
925 gcc_unreachable ();
929 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
930 in and that is representable in type int.
931 Return true when the range is a subrange of that of int.
932 When ARG is null it is as if it had the full range of int.
933 When ABSOLUTE is true the range reflects the absolute value of
934 the argument. When ABSOLUTE is false, negative bounds of
935 the determined range are replaced with NEGBOUND. */
937 static bool
938 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
939 bool absolute, HOST_WIDE_INT negbound)
941 /* The type of the result. */
942 const_tree type = integer_type_node;
944 bool knownrange = false;
946 if (!arg)
948 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
949 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
951 else if (TREE_CODE (arg) == INTEGER_CST
952 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
954 /* For a constant argument return its value adjusted as specified
955 by NEGATIVE and NEGBOUND and return true to indicate that the
956 result is known. */
957 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
958 *pmax = *pmin;
959 knownrange = true;
961 else
963 /* True if the argument's range cannot be determined. */
964 bool unknown = true;
966 tree argtype = TREE_TYPE (arg);
968 /* Ignore invalid arguments with greater precision that that
969 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
970 They will have been detected and diagnosed by -Wformat and
971 so it's not important to complicate this code to try to deal
972 with them again. */
973 if (TREE_CODE (arg) == SSA_NAME
974 && INTEGRAL_TYPE_P (argtype)
975 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
977 /* Try to determine the range of values of the integer argument. */
978 wide_int min, max;
979 enum value_range_type range_type = get_range_info (arg, &min, &max);
980 if (range_type == VR_RANGE)
982 HOST_WIDE_INT type_min
983 = (TYPE_UNSIGNED (argtype)
984 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
985 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
987 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
989 *pmin = min.to_shwi ();
990 *pmax = max.to_shwi ();
992 if (*pmin < *pmax)
994 /* Return true if the adjusted range is a subrange of
995 the full range of the argument's type. *PMAX may
996 be less than *PMIN when the argument is unsigned
997 and its upper bound is in excess of TYPE_MAX. In
998 that (invalid) case disregard the range and use that
999 of the expected type instead. */
1000 knownrange = type_min < *pmin || *pmax < type_max;
1002 unknown = false;
1007 /* Handle an argument with an unknown range as if none had been
1008 provided. */
1009 if (unknown)
1010 return get_int_range (NULL_TREE, pmin, pmax, absolute, negbound);
1013 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1014 if (absolute)
1016 if (*pmin < 0)
1018 if (*pmin == *pmax)
1019 *pmin = *pmax = -*pmin;
1020 else
1022 /* Make sure signed overlow is avoided. */
1023 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1025 HOST_WIDE_INT tmp = -*pmin;
1026 *pmin = 0;
1027 if (*pmax < tmp)
1028 *pmax = tmp;
1032 else if (*pmin < negbound)
1033 *pmin = negbound;
1035 return knownrange;
1038 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1039 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1040 the type of the directive's formal argument it's possible for both
1041 to result in the same number of bytes or a range of bytes that's
1042 less than the number of bytes that would result from formatting
1043 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1044 determined by checking for the actual argument being in the range
1045 of the type of the directive. If it isn't it must be assumed to
1046 take on the full range of the directive's type.
1047 Return true when the range has been adjusted to the full range
1048 of DIRTYPE, and false otherwise. */
1050 static bool
1051 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1053 tree argtype = TREE_TYPE (*argmin);
1054 unsigned argprec = TYPE_PRECISION (argtype);
1055 unsigned dirprec = TYPE_PRECISION (dirtype);
1057 /* If the actual argument and the directive's argument have the same
1058 precision and sign there can be no overflow and so there is nothing
1059 to adjust. */
1060 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1061 return false;
1063 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1064 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1066 if (TREE_CODE (*argmin) == INTEGER_CST
1067 && TREE_CODE (*argmax) == INTEGER_CST
1068 && (dirprec >= argprec
1069 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1070 int_const_binop (MINUS_EXPR,
1071 *argmax,
1072 *argmin),
1073 size_int (dirprec)))))
1075 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1076 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1078 /* If *ARGMIN is still less than *ARGMAX the conversion above
1079 is safe. Otherwise, it has overflowed and would be unsafe. */
1080 if (tree_int_cst_le (*argmin, *argmax))
1081 return false;
1084 *argmin = TYPE_MIN_VALUE (dirtype);
1085 *argmax = TYPE_MAX_VALUE (dirtype);
1086 return true;
1089 /* Return a range representing the minimum and maximum number of bytes
1090 that the format directive DIR will output for any argument given
1091 the WIDTH and PRECISION (extracted from DIR). This function is
1092 used when the directive argument or its value isn't known. */
1094 static fmtresult
1095 format_integer (const directive &dir, tree arg)
1097 tree intmax_type_node;
1098 tree uintmax_type_node;
1100 /* Base to format the number in. */
1101 int base;
1103 /* True when a conversion is preceded by a prefix indicating the base
1104 of the argument (octal or hexadecimal). */
1105 bool maybebase = dir.get_flag ('#');
1107 /* True when a signed conversion is preceded by a sign or space. */
1108 bool maybesign = false;
1110 /* True for signed conversions (i.e., 'd' and 'i'). */
1111 bool sign = false;
1113 switch (dir.specifier)
1115 case 'd':
1116 case 'i':
1117 /* Space and '+' are only meaningful for signed conversions. */
1118 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1119 sign = true;
1120 base = 10;
1121 break;
1122 case 'u':
1123 base = 10;
1124 break;
1125 case 'o':
1126 base = 8;
1127 break;
1128 case 'X':
1129 case 'x':
1130 base = 16;
1131 break;
1132 default:
1133 gcc_unreachable ();
1136 /* The type of the "formal" argument expected by the directive. */
1137 tree dirtype = NULL_TREE;
1139 /* Determine the expected type of the argument from the length
1140 modifier. */
1141 switch (dir.modifier)
1143 case FMT_LEN_none:
1144 if (dir.specifier == 'p')
1145 dirtype = ptr_type_node;
1146 else
1147 dirtype = sign ? integer_type_node : unsigned_type_node;
1148 break;
1150 case FMT_LEN_h:
1151 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1152 break;
1154 case FMT_LEN_hh:
1155 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1156 break;
1158 case FMT_LEN_l:
1159 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1160 break;
1162 case FMT_LEN_L:
1163 case FMT_LEN_ll:
1164 dirtype = (sign
1165 ? long_long_integer_type_node
1166 : long_long_unsigned_type_node);
1167 break;
1169 case FMT_LEN_z:
1170 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1171 break;
1173 case FMT_LEN_t:
1174 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1175 break;
1177 case FMT_LEN_j:
1178 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1179 dirtype = sign ? intmax_type_node : uintmax_type_node;
1180 break;
1182 default:
1183 return fmtresult ();
1186 /* The type of the argument to the directive, either deduced from
1187 the actual non-constant argument if one is known, or from
1188 the directive itself when none has been provided because it's
1189 a va_list. */
1190 tree argtype = NULL_TREE;
1192 if (!arg)
1194 /* When the argument has not been provided, use the type of
1195 the directive's argument as an approximation. This will
1196 result in false positives for directives like %i with
1197 arguments with smaller precision (such as short or char). */
1198 argtype = dirtype;
1200 else if (TREE_CODE (arg) == INTEGER_CST)
1202 /* When a constant argument has been provided use its value
1203 rather than type to determine the length of the output. */
1204 fmtresult res;
1206 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1208 /* As a special case, a precision of zero with a zero argument
1209 results in zero bytes except in base 8 when the '#' flag is
1210 specified, and for signed conversions in base 8 and 10 when
1211 either the space or '+' flag has been specified and it results
1212 in just one byte (with width having the normal effect). This
1213 must extend to the case of a specified precision with
1214 an unknown value because it can be zero. */
1215 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1216 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1218 res.range.max = 1;
1219 res.range.likely = 1;
1221 else
1223 res.range.max = res.range.min;
1224 res.range.likely = res.range.min;
1227 else
1229 /* Convert the argument to the type of the directive. */
1230 arg = fold_convert (dirtype, arg);
1232 res.range.min = tree_digits (arg, base, dir.prec[0],
1233 maybesign, maybebase);
1234 if (dir.prec[0] == dir.prec[1])
1235 res.range.max = res.range.min;
1236 else
1237 res.range.max = tree_digits (arg, base, dir.prec[1],
1238 maybesign, maybebase);
1239 res.range.likely = res.range.min;
1242 res.range.unlikely = res.range.max;
1244 /* Bump up the counters if WIDTH is greater than LEN. */
1245 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1246 (sign | maybebase) + (base == 16));
1247 /* Bump up the counters again if PRECision is greater still. */
1248 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1249 (sign | maybebase) + (base == 16));
1251 return res;
1253 else if (TREE_CODE (TREE_TYPE (arg)) == INTEGER_TYPE
1254 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1255 /* Determine the type of the provided non-constant argument. */
1256 argtype = TREE_TYPE (arg);
1257 else
1258 /* Don't bother with invalid arguments since they likely would
1259 have already been diagnosed, and disable any further checking
1260 of the format string by returning [-1, -1]. */
1261 return fmtresult ();
1263 fmtresult res;
1265 /* Using either the range the non-constant argument is in, or its
1266 type (either "formal" or actual), create a range of values that
1267 constrain the length of output given the warning level. */
1268 tree argmin = NULL_TREE;
1269 tree argmax = NULL_TREE;
1271 if (arg
1272 && TREE_CODE (arg) == SSA_NAME
1273 && TREE_CODE (argtype) == INTEGER_TYPE)
1275 /* Try to determine the range of values of the integer argument
1276 (range information is not available for pointers). */
1277 wide_int min, max;
1278 enum value_range_type range_type = get_range_info (arg, &min, &max);
1279 if (range_type == VR_RANGE)
1281 argmin = wide_int_to_tree (argtype, min);
1282 argmax = wide_int_to_tree (argtype, max);
1284 /* Set KNOWNRANGE if the argument is in a known subrange
1285 of the directive's type and neither width nor precision
1286 is unknown. (KNOWNRANGE may be reset below). */
1287 res.knownrange
1288 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1289 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1290 && dir.known_width_and_precision ());
1292 res.argmin = argmin;
1293 res.argmax = argmax;
1295 else if (range_type == VR_ANTI_RANGE)
1297 /* Handle anti-ranges if/when bug 71690 is resolved. */
1299 else if (range_type == VR_VARYING)
1301 /* The argument here may be the result of promoting the actual
1302 argument to int. Try to determine the type of the actual
1303 argument before promotion and narrow down its range that
1304 way. */
1305 gimple *def = SSA_NAME_DEF_STMT (arg);
1306 if (is_gimple_assign (def))
1308 tree_code code = gimple_assign_rhs_code (def);
1309 if (code == INTEGER_CST)
1311 arg = gimple_assign_rhs1 (def);
1312 return format_integer (dir, arg);
1315 if (code == NOP_EXPR)
1317 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1318 if (TREE_CODE (type) == INTEGER_TYPE
1319 || TREE_CODE (type) == POINTER_TYPE)
1320 argtype = type;
1326 if (!argmin)
1328 if (TREE_CODE (argtype) == POINTER_TYPE)
1330 argmin = build_int_cst (pointer_sized_int_node, 0);
1331 argmax = build_all_ones_cst (pointer_sized_int_node);
1333 else
1335 argmin = TYPE_MIN_VALUE (argtype);
1336 argmax = TYPE_MAX_VALUE (argtype);
1340 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1341 of the directive. If it has been cleared then since ARGMIN and/or
1342 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1343 ARGMAX in the result to include in diagnostics. */
1344 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1346 res.knownrange = false;
1347 res.argmin = argmin;
1348 res.argmax = argmax;
1351 /* Recursively compute the minimum and maximum from the known range. */
1352 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1354 /* For unsigned conversions/directives or signed when
1355 the minimum is positive, use the minimum and maximum to compute
1356 the shortest and longest output, respectively. */
1357 res.range.min = format_integer (dir, argmin).range.min;
1358 res.range.max = format_integer (dir, argmax).range.max;
1360 else if (tree_int_cst_sgn (argmax) < 0)
1362 /* For signed conversions/directives if maximum is negative,
1363 use the minimum as the longest output and maximum as the
1364 shortest output. */
1365 res.range.min = format_integer (dir, argmax).range.min;
1366 res.range.max = format_integer (dir, argmin).range.max;
1368 else
1370 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1371 as the shortest output and for the longest output compute the
1372 length of the output of both minimum and maximum and pick the
1373 longer. */
1374 unsigned HOST_WIDE_INT max1 = format_integer (dir, argmin).range.max;
1375 unsigned HOST_WIDE_INT max2 = format_integer (dir, argmax).range.max;
1376 res.range.min = format_integer (dir, integer_zero_node).range.min;
1377 res.range.max = MAX (max1, max2);
1380 /* If the range is known, use the maximum as the likely length. */
1381 if (res.knownrange)
1382 res.range.likely = res.range.max;
1383 else
1385 /* Otherwise, use the minimum. Except for the case where for %#x or
1386 %#o the minimum is just for a single value in the range (0) and
1387 for all other values it is something longer, like 0x1 or 01.
1388 Use the length for value 1 in that case instead as the likely
1389 length. */
1390 res.range.likely = res.range.min;
1391 if (maybebase
1392 && base != 10
1393 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1395 if (res.range.min == 1)
1396 res.range.likely += base == 8 ? 1 : 2;
1397 else if (res.range.min == 2
1398 && base == 16
1399 && (dir.width[0] == 2 || dir.prec[0] == 2))
1400 ++res.range.likely;
1404 res.range.unlikely = res.range.max;
1405 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1406 (sign | maybebase) + (base == 16));
1407 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1408 (sign | maybebase) + (base == 16));
1410 return res;
1413 /* Return the number of bytes that a format directive consisting of FLAGS,
1414 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1415 would result for argument X under ideal conditions (i.e., if PREC
1416 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1417 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1418 This function works around those problems. */
1420 static unsigned HOST_WIDE_INT
1421 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1422 char spec, char rndspec)
1424 char fmtstr[40];
1426 HOST_WIDE_INT len = strlen (flags);
1428 fmtstr[0] = '%';
1429 memcpy (fmtstr + 1, flags, len);
1430 memcpy (fmtstr + 1 + len, ".*R", 3);
1431 fmtstr[len + 4] = rndspec;
1432 fmtstr[len + 5] = spec;
1433 fmtstr[len + 6] = '\0';
1435 spec = TOUPPER (spec);
1436 if (spec == 'E' || spec == 'F')
1438 /* For %e, specify the precision explicitly since mpfr_sprintf
1439 does its own thing just to be different (see MPFR bug 21088). */
1440 if (prec < 0)
1441 prec = 6;
1443 else
1445 /* Avoid passing negative precisions with larger magnitude to MPFR
1446 to avoid exposing its bugs. (A negative precision is supposed
1447 to be ignored.) */
1448 if (prec < 0)
1449 prec = -1;
1452 HOST_WIDE_INT p = prec;
1454 if (spec == 'G' && !strchr (flags, '#'))
1456 /* For G/g without the pound flag, precision gives the maximum number
1457 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1458 a 128 bit IEEE extended precision, 4932. Using twice as much here
1459 should be more than sufficient for any real format. */
1460 if ((IEEE_MAX_10_EXP * 2) < prec)
1461 prec = IEEE_MAX_10_EXP * 2;
1462 p = prec;
1464 else
1466 /* Cap precision arbitrarily at 1KB and add the difference
1467 (if any) to the MPFR result. */
1468 if (prec > 1024)
1469 p = 1024;
1472 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1474 /* Handle the unlikely (impossible?) error by returning more than
1475 the maximum dictated by the function's return type. */
1476 if (len < 0)
1477 return target_dir_max () + 1;
1479 /* Adjust the return value by the difference. */
1480 if (p < prec)
1481 len += prec - p;
1483 return len;
1486 /* Return the number of bytes to format using the format specifier
1487 SPEC and the precision PREC the largest value in the real floating
1488 TYPE. */
1490 static unsigned HOST_WIDE_INT
1491 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1493 machine_mode mode = TYPE_MODE (type);
1495 /* IBM Extended mode. */
1496 if (MODE_COMPOSITE_P (mode))
1497 mode = DFmode;
1499 /* Get the real type format desription for the target. */
1500 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1501 REAL_VALUE_TYPE rv;
1503 real_maxval (&rv, 0, mode);
1505 /* Convert the GCC real value representation with the precision
1506 of the real type to the mpfr_t format with the GCC default
1507 round-to-nearest mode. */
1508 mpfr_t x;
1509 mpfr_init2 (x, rfmt->p);
1510 mpfr_from_real (x, &rv, GMP_RNDN);
1512 /* Return a value one greater to account for the leading minus sign. */
1513 unsigned HOST_WIDE_INT r
1514 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1515 mpfr_clear (x);
1516 return r;
1519 /* Return a range representing the minimum and maximum number of bytes
1520 that the directive DIR will output for any argument. PREC gives
1521 the adjusted precision range to account for negative precisions
1522 meaning the default 6. This function is used when the directive
1523 argument or its value isn't known. */
1525 static fmtresult
1526 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1528 tree type;
1530 switch (dir.modifier)
1532 case FMT_LEN_l:
1533 case FMT_LEN_none:
1534 type = double_type_node;
1535 break;
1537 case FMT_LEN_L:
1538 type = long_double_type_node;
1539 break;
1541 case FMT_LEN_ll:
1542 type = long_double_type_node;
1543 break;
1545 default:
1546 return fmtresult ();
1549 /* The minimum and maximum number of bytes produced by the directive. */
1550 fmtresult res;
1552 /* The minimum output as determined by flags. It's always at least 1.
1553 When plus or space are set the output is preceded by either a sign
1554 or a space. */
1555 unsigned flagmin = (1 /* for the first digit */
1556 + (dir.get_flag ('+') | dir.get_flag (' ')));
1558 /* When the pound flag is set the decimal point is included in output
1559 regardless of precision. Whether or not a decimal point is included
1560 otherwise depends on the specification and precision. */
1561 bool radix = dir.get_flag ('#');
1563 switch (dir.specifier)
1565 case 'A':
1566 case 'a':
1568 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1569 if (dir.prec[0] <= 0)
1570 minprec = 0;
1571 else if (dir.prec[0] > 0)
1572 minprec = dir.prec[0] + !radix /* decimal point */;
1574 res.range.min = (2 /* 0x */
1575 + flagmin
1576 + radix
1577 + minprec
1578 + 3 /* p+0 */);
1580 res.range.max = format_floating_max (type, 'a', prec[1]);
1581 res.range.likely = res.range.min;
1583 /* The unlikely maximum accounts for the longest multibyte
1584 decimal point character. */
1585 res.range.unlikely = res.range.max;
1586 if (dir.prec[1] > 0)
1587 res.range.unlikely += target_mb_len_max () - 1;
1589 break;
1592 case 'E':
1593 case 'e':
1595 /* Minimum output attributable to precision and, when it's
1596 non-zero, decimal point. */
1597 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1599 /* The minimum output is "[-+]1.234567e+00" regardless
1600 of the value of the actual argument. */
1601 res.range.min = (flagmin
1602 + radix
1603 + minprec
1604 + 2 /* e+ */ + 2);
1606 res.range.max = format_floating_max (type, 'e', prec[1]);
1607 res.range.likely = res.range.min;
1609 /* The unlikely maximum accounts for the longest multibyte
1610 decimal point character. */
1611 if (dir.prec[0] != dir.prec[1]
1612 || dir.prec[0] == -1 || dir.prec[0] > 0)
1613 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1614 else
1615 res.range.unlikely = res.range.max;
1616 break;
1619 case 'F':
1620 case 'f':
1622 /* Minimum output attributable to precision and, when it's non-zero,
1623 decimal point. */
1624 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1626 /* The lower bound when precision isn't specified is 8 bytes
1627 ("1.23456" since precision is taken to be 6). When precision
1628 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1629 when precision is greater than zero, then the lower bound
1630 is 2 plus precision (plus flags). */
1631 res.range.min = flagmin + radix + minprec;
1633 /* Compute the upper bound for -TYPE_MAX. */
1634 res.range.max = format_floating_max (type, 'f', prec[1]);
1636 /* The minimum output with unknown precision is a single byte
1637 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1638 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1639 res.range.likely = 3;
1640 else
1641 res.range.likely = res.range.min;
1643 /* The unlikely maximum accounts for the longest multibyte
1644 decimal point character. */
1645 if (dir.prec[0] != dir.prec[1]
1646 || dir.prec[0] == -1 || dir.prec[0] > 0)
1647 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1648 break;
1651 case 'G':
1652 case 'g':
1654 /* The %g output depends on precision and the exponent of
1655 the argument. Since the value of the argument isn't known
1656 the lower bound on the range of bytes (not counting flags
1657 or width) is 1 plus radix (i.e., either "0" or "0." for
1658 "%g" and "%#g", respectively, with a zero argument). */
1659 res.range.min = flagmin + radix;
1661 char spec = 'g';
1662 HOST_WIDE_INT maxprec = dir.prec[1];
1663 if (radix && maxprec)
1665 /* When the pound flag (radix) is set, trailing zeros aren't
1666 trimmed and so the longest output is the same as for %e,
1667 except with precision minus 1 (as specified in C11). */
1668 spec = 'e';
1669 if (maxprec > 0)
1670 --maxprec;
1671 else if (maxprec < 0)
1672 maxprec = 5;
1674 else
1675 maxprec = prec[1];
1677 res.range.max = format_floating_max (type, spec, maxprec);
1679 /* The likely output is either the maximum computed above
1680 minus 1 (assuming the maximum is positive) when precision
1681 is known (or unspecified), or the same minimum as for %e
1682 (which is computed for a non-negative argument). Unlike
1683 for the other specifiers above the likely output isn't
1684 the minimum because for %g that's 1 which is unlikely. */
1685 if (dir.prec[1] < 0
1686 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1687 res.range.likely = res.range.max - 1;
1688 else
1690 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1691 res.range.likely = (flagmin
1692 + radix
1693 + minprec
1694 + 2 /* e+ */ + 2);
1697 /* The unlikely maximum accounts for the longest multibyte
1698 decimal point character. */
1699 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1700 break;
1703 default:
1704 return fmtresult ();
1707 /* Bump up the byte counters if WIDTH is greater. */
1708 res.adjust_for_width_or_precision (dir.width);
1709 return res;
1712 /* Return a range representing the minimum and maximum number of bytes
1713 that the directive DIR will write on output for the floating argument
1714 ARG. */
1716 static fmtresult
1717 format_floating (const directive &dir, tree arg)
1719 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1721 /* For an indeterminate precision the lower bound must be assumed
1722 to be zero. */
1723 if (TOUPPER (dir.specifier) == 'A')
1725 /* Get the number of fractional decimal digits needed to represent
1726 the argument without a loss of accuracy. */
1727 tree type = arg ? TREE_TYPE (arg) :
1728 (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1729 ? long_double_type_node : double_type_node);
1731 unsigned fmtprec
1732 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1734 /* The precision of the IEEE 754 double format is 53.
1735 The precision of all other GCC binary double formats
1736 is 56 or less. */
1737 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1739 /* For %a, leave the minimum precision unspecified to let
1740 MFPR trim trailing zeros (as it and many other systems
1741 including Glibc happen to do) and set the maximum
1742 precision to reflect what it would be with trailing zeros
1743 present (as Solaris and derived systems do). */
1744 if (dir.prec[1] < 0)
1746 /* Both bounds are negative implies that precision has
1747 not been specified. */
1748 prec[0] = maxprec;
1749 prec[1] = -1;
1751 else if (dir.prec[0] < 0)
1753 /* With a negative lower bound and a non-negative upper
1754 bound set the minimum precision to zero and the maximum
1755 to the greater of the maximum precision (i.e., with
1756 trailing zeros present) and the specified upper bound. */
1757 prec[0] = 0;
1758 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1761 else if (dir.prec[0] < 0)
1763 if (dir.prec[1] < 0)
1765 /* A precision in a strictly negative range is ignored and
1766 the default of 6 is used instead. */
1767 prec[0] = prec[1] = 6;
1769 else
1771 /* For a precision in a partly negative range, the lower bound
1772 must be assumed to be zero and the new upper bound is the
1773 greater of 6 (the default precision used when the specified
1774 precision is negative) and the upper bound of the specified
1775 range. */
1776 prec[0] = 0;
1777 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1781 if (!arg || TREE_CODE (arg) != REAL_CST)
1782 return format_floating (dir, prec);
1784 /* The minimum and maximum number of bytes produced by the directive. */
1785 fmtresult res;
1787 /* Get the real type format desription for the target. */
1788 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1789 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1791 char fmtstr [40];
1792 char *pfmt = fmtstr;
1794 /* Append flags. */
1795 for (const char *pf = "-+ #0"; *pf; ++pf)
1796 if (dir.get_flag (*pf))
1797 *pfmt++ = *pf;
1799 *pfmt = '\0';
1802 /* Set up an array to easily iterate over. */
1803 unsigned HOST_WIDE_INT* const minmax[] = {
1804 &res.range.min, &res.range.max
1807 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1809 /* Convert the GCC real value representation with the precision
1810 of the real type to the mpfr_t format rounding down in the
1811 first iteration that computes the minimm and up in the second
1812 that computes the maximum. This order is arbibtrary because
1813 rounding in either direction can result in longer output. */
1814 mpfr_t mpfrval;
1815 mpfr_init2 (mpfrval, rfmt->p);
1816 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1818 /* Use the MPFR rounding specifier to round down in the first
1819 iteration and then up. In most but not all cases this will
1820 result in the same number of bytes. */
1821 char rndspec = "DU"[i];
1823 /* Format it and store the result in the corresponding member
1824 of the result struct. */
1825 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1826 dir.specifier, rndspec);
1827 mpfr_clear (mpfrval);
1831 /* Make sure the minimum is less than the maximum (MPFR rounding
1832 in the call to mpfr_snprintf can result in the reverse. */
1833 if (res.range.max < res.range.min)
1835 unsigned HOST_WIDE_INT tmp = res.range.min;
1836 res.range.min = res.range.max;
1837 res.range.max = tmp;
1840 /* The range is known unless either width or precision is unknown. */
1841 res.knownrange = dir.known_width_and_precision ();
1843 /* For the same floating point constant, unless width or precision
1844 is unknown, use the longer output as the likely maximum since
1845 with round to nearest either is equally likely. Otheriwse, when
1846 precision is unknown, use the greater of the minimum and 3 as
1847 the likely output (for "0.0" since zero precision is unlikely). */
1848 if (res.knownrange)
1849 res.range.likely = res.range.max;
1850 else if (res.range.min < 3
1851 && dir.prec[0] < 0
1852 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
1853 res.range.likely = 3;
1854 else
1855 res.range.likely = res.range.min;
1857 res.range.unlikely = res.range.max;
1859 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
1861 /* Unless the precision is zero output longer than 2 bytes may
1862 include the decimal point which must be a single character
1863 up to MB_LEN_MAX in length. This is overly conservative
1864 since in some conversions some constants result in no decimal
1865 point (e.g., in %g). */
1866 res.range.unlikely += target_mb_len_max () - 1;
1869 res.adjust_for_width_or_precision (dir.width);
1870 return res;
1873 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1874 strings referenced by the expression STR, or (-1, -1) when not known.
1875 Used by the format_string function below. */
1877 static fmtresult
1878 get_string_length (tree str)
1880 if (!str)
1881 return fmtresult ();
1883 if (tree slen = c_strlen (str, 1))
1885 /* Simply return the length of the string. */
1886 fmtresult res (tree_to_shwi (slen));
1887 return res;
1890 /* Determine the length of the shortest and longest string referenced
1891 by STR. Strings of unknown lengths are bounded by the sizes of
1892 arrays that subexpressions of STR may refer to. Pointers that
1893 aren't known to point any such arrays result in LENRANGE[1] set
1894 to SIZE_MAX. */
1895 tree lenrange[2];
1896 bool flexarray = get_range_strlen (str, lenrange);
1898 if (lenrange [0] || lenrange [1])
1900 HOST_WIDE_INT min
1901 = (tree_fits_uhwi_p (lenrange[0])
1902 ? tree_to_uhwi (lenrange[0])
1903 : 0);
1905 HOST_WIDE_INT max
1906 = (tree_fits_uhwi_p (lenrange[1])
1907 ? tree_to_uhwi (lenrange[1])
1908 : HOST_WIDE_INT_M1U);
1910 /* get_range_strlen() returns the target value of SIZE_MAX for
1911 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
1912 which may be bigger. */
1913 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
1914 min = HOST_WIDE_INT_M1U;
1915 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
1916 max = HOST_WIDE_INT_M1U;
1918 fmtresult res (min, max);
1920 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
1921 by STR are known to be bounded (though not necessarily by their
1922 actual length but perhaps by their maximum possible length). */
1923 if (res.range.max < target_int_max ())
1925 res.knownrange = true;
1926 /* When the the length of the longest string is known and not
1927 excessive use it as the likely length of the string(s). */
1928 res.range.likely = res.range.max;
1930 else
1932 /* When the upper bound is unknown (it can be zero or excessive)
1933 set the likely length to the greater of 1 and the length of
1934 the shortest string and reset the lower bound to zero. */
1935 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
1936 res.range.min = 0;
1939 /* If the range of string length has been estimated from the size
1940 of an array at the end of a struct assume that it's longer than
1941 the array bound says it is in case it's used as a poor man's
1942 flexible array member, such as in struct S { char a[4]; }; */
1943 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
1945 return res;
1948 return get_string_length (NULL_TREE);
1951 /* Return the minimum and maximum number of characters formatted
1952 by the '%c' format directives and its wide character form for
1953 the argument ARG. ARG can be null (for functions such as
1954 vsprinf). */
1956 static fmtresult
1957 format_character (const directive &dir, tree arg)
1959 fmtresult res;
1961 res.knownrange = true;
1963 if (dir.modifier == FMT_LEN_l)
1965 /* A wide character can result in as few as zero bytes. */
1966 res.range.min = 0;
1968 HOST_WIDE_INT min, max;
1969 if (get_int_range (arg, &min, &max, false, 0))
1971 if (min == 0 && max == 0)
1973 /* The NUL wide character results in no bytes. */
1974 res.range.max = 0;
1975 res.range.likely = 0;
1976 res.range.unlikely = 0;
1978 else if (min > 0 && min < 128)
1980 /* A wide character in the ASCII range most likely results
1981 in a single byte, and only unlikely in up to MB_LEN_MAX. */
1982 res.range.max = 1;
1983 res.range.likely = 1;
1984 res.range.unlikely = target_mb_len_max ();
1986 else
1988 /* A wide character outside the ASCII range likely results
1989 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
1990 res.range.max = target_mb_len_max ();
1991 res.range.likely = 2;
1992 res.range.unlikely = res.range.max;
1995 else
1997 /* An unknown wide character is treated the same as a wide
1998 character outside the ASCII range. */
1999 res.range.max = target_mb_len_max ();
2000 res.range.likely = 2;
2001 res.range.unlikely = res.range.max;
2004 else
2006 /* A plain '%c' directive. Its ouput is exactly 1. */
2007 res.range.min = res.range.max = 1;
2008 res.range.likely = res.range.unlikely = 1;
2009 res.knownrange = true;
2012 /* Bump up the byte counters if WIDTH is greater. */
2013 return res.adjust_for_width_or_precision (dir.width);
2016 /* Return the minimum and maximum number of characters formatted
2017 by the '%s' format directive and its wide character form for
2018 the argument ARG. ARG can be null (for functions such as
2019 vsprinf). */
2021 static fmtresult
2022 format_string (const directive &dir, tree arg)
2024 fmtresult res;
2026 /* Compute the range the argument's length can be in. */
2027 fmtresult slen = get_string_length (arg);
2028 if (slen.range.min == slen.range.max
2029 && slen.range.min < HOST_WIDE_INT_MAX)
2031 /* The argument is either a string constant or it refers
2032 to one of a number of strings of the same length. */
2034 /* A '%s' directive with a string argument with constant length. */
2035 res.range = slen.range;
2037 if (dir.modifier == FMT_LEN_l)
2039 /* In the worst case the length of output of a wide string S
2040 is bounded by MB_LEN_MAX * wcslen (S). */
2041 res.range.max *= target_mb_len_max ();
2042 res.range.unlikely = res.range.max;
2043 /* It's likely that the the total length is not more that
2044 2 * wcslen (S).*/
2045 res.range.likely = res.range.min * 2;
2047 if (dir.prec[1] >= 0
2048 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2050 res.range.max = dir.prec[1];
2051 res.range.likely = dir.prec[1];
2052 res.range.unlikely = dir.prec[1];
2055 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2056 res.range.min = 0;
2057 else if (dir.prec[0] >= 0)
2058 res.range.likely = dir.prec[0];
2060 /* Even a non-empty wide character string need not convert into
2061 any bytes. */
2062 res.range.min = 0;
2064 else
2066 res.knownrange = true;
2068 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2069 res.range.min = 0;
2070 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2071 res.range.min = dir.prec[0];
2073 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2075 res.range.max = dir.prec[1];
2076 res.range.likely = dir.prec[1];
2077 res.range.unlikely = dir.prec[1];
2081 else if (arg && integer_zerop (arg))
2083 /* Handle null pointer argument. */
2085 fmtresult res (0);
2086 res.nullp = true;
2087 return res;
2089 else
2091 /* For a '%s' and '%ls' directive with a non-constant string (either
2092 one of a number of strings of known length or an unknown string)
2093 the minimum number of characters is lesser of PRECISION[0] and
2094 the length of the shortest known string or zero, and the maximum
2095 is the lessser of the length of the longest known string or
2096 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2097 the minimum at level 1 and the greater of the minimum and 1
2098 at level 2. This result is adjust upward for width (if it's
2099 specified). */
2101 if (dir.modifier == FMT_LEN_l)
2103 /* A wide character converts to as few as zero bytes. */
2104 slen.range.min = 0;
2105 if (slen.range.max < target_int_max ())
2106 slen.range.max *= target_mb_len_max ();
2108 if (slen.range.likely < target_int_max ())
2109 slen.range.likely *= 2;
2111 if (slen.range.likely < target_int_max ())
2112 slen.range.unlikely *= target_mb_len_max ();
2115 res.range = slen.range;
2117 if (dir.prec[0] >= 0)
2119 /* Adjust the minimum to zero if the string length is unknown,
2120 or at most the lower bound of the precision otherwise. */
2121 if (slen.range.min >= target_int_max ())
2122 res.range.min = 0;
2123 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2124 res.range.min = dir.prec[0];
2126 /* Make both maxima no greater than the upper bound of precision. */
2127 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2128 || slen.range.max >= target_int_max ())
2130 res.range.max = dir.prec[1];
2131 res.range.unlikely = dir.prec[1];
2134 /* If precision is constant, set the likely counter to the lesser
2135 of it and the maximum string length. Otherwise, if the lower
2136 bound of precision is greater than zero, set the likely counter
2137 to the minimum. Otherwise set it to zero or one based on
2138 the warning level. */
2139 if (dir.prec[0] == dir.prec[1])
2140 res.range.likely
2141 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2142 ? dir.prec[0] : slen.range.max);
2143 else if (dir.prec[0] > 0)
2144 res.range.likely = res.range.min;
2145 else
2146 res.range.likely = warn_level > 1;
2148 else if (dir.prec[1] >= 0)
2150 res.range.min = 0;
2151 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2152 res.range.max = dir.prec[1];
2153 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2155 else if (slen.range.min >= target_int_max ())
2157 res.range.min = 0;
2158 res.range.max = HOST_WIDE_INT_MAX;
2159 /* At level 1 strings of unknown length are assumed to be
2160 empty, while at level 1 they are assumed to be one byte
2161 long. */
2162 res.range.likely = warn_level > 1;
2164 else
2166 /* A string of unknown length unconstrained by precision is
2167 assumed to be empty at level 1 and just one character long
2168 at higher levels. */
2169 if (res.range.likely >= target_int_max ())
2170 res.range.likely = warn_level > 1;
2173 res.range.unlikely = res.range.max;
2176 /* Bump up the byte counters if WIDTH is greater. */
2177 return res.adjust_for_width_or_precision (dir.width);
2180 /* Format plain string (part of the format string itself). */
2182 static fmtresult
2183 format_plain (const directive &dir, tree)
2185 fmtresult res (dir.len);
2186 return res;
2189 /* Return true if the RESULT of a directive in a call describe by INFO
2190 should be diagnosed given the AVAILable space in the destination. */
2192 static bool
2193 should_warn_p (const pass_sprintf_length::call_info &info,
2194 const result_range &avail, const result_range &result)
2196 if (result.max <= avail.min)
2198 /* The least amount of space remaining in the destination is big
2199 enough for the longest output. */
2200 return false;
2203 if (info.bounded)
2205 if (warn_format_trunc == 1 && result.min <= avail.max
2206 && info.retval_used ())
2208 /* The likely amount of space remaining in the destination is big
2209 enough for the least output and the return value is used. */
2210 return false;
2213 if (warn_format_trunc == 1 && result.likely <= avail.likely
2214 && !info.retval_used ())
2216 /* The likely amount of space remaining in the destination is big
2217 enough for the likely output and the return value is unused. */
2218 return false;
2221 if (warn_format_trunc == 2
2222 && result.likely <= avail.min
2223 && (result.max <= avail.min
2224 || result.max > HOST_WIDE_INT_MAX))
2226 /* The minimum amount of space remaining in the destination is big
2227 enough for the longest output. */
2228 return false;
2231 else
2233 if (warn_level == 1 && result.likely <= avail.likely)
2235 /* The likely amount of space remaining in the destination is big
2236 enough for the likely output. */
2237 return false;
2240 if (warn_level == 2
2241 && result.likely <= avail.min
2242 && (result.max <= avail.min
2243 || result.max > HOST_WIDE_INT_MAX))
2245 /* The minimum amount of space remaining in the destination is big
2246 enough for the longest output. */
2247 return false;
2251 return true;
2254 /* At format string location describe by DIRLOC in a call described
2255 by INFO, issue a warning for a directive DIR whose output may be
2256 in excess of the available space AVAIL_RANGE in the destination
2257 given the formatting result FMTRES. This function does nothing
2258 except decide whether to issue a warning for a possible write
2259 past the end or truncation and, if so, format the warning.
2260 Return true if a warning has been issued. */
2262 static bool
2263 maybe_warn (substring_loc &dirloc, source_range *pargrange,
2264 const pass_sprintf_length::call_info &info,
2265 const result_range &avail_range, const result_range &res,
2266 const directive &dir)
2268 if (!should_warn_p (info, avail_range, res))
2269 return false;
2271 /* A warning will definitely be issued below. */
2273 /* The maximum byte count to reference in the warning. Larger counts
2274 imply that the upper bound is unknown (and could be anywhere between
2275 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2276 than "between N and X" where X is some huge number. */
2277 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2279 /* True when there is enough room in the destination for the least
2280 amount of a directive's output but not enough for its likely or
2281 maximum output. */
2282 bool maybe = (res.min <= avail_range.max
2283 && (avail_range.min < res.likely
2284 || (res.max < HOST_WIDE_INT_MAX
2285 && avail_range.min < res.max)));
2287 if (avail_range.min == avail_range.max)
2289 /* The size of the destination region is exact. */
2290 unsigned HOST_WIDE_INT navail = avail_range.max;
2292 if (*dir.beg != '%')
2294 /* For plain character directives (i.e., the format string itself)
2295 but not others, point the caret at the first character that's
2296 past the end of the destination. */
2297 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2300 if (*dir.beg == '\0')
2302 /* This is the terminating nul. */
2303 gcc_assert (res.min == 1 && res.min == res.max);
2305 const char *fmtstr
2306 = (info.bounded
2307 ? (maybe
2308 ? G_("%qE output may be truncated before the last format "
2309 "character")
2310 : G_("%qE output truncated before the last format character"))
2311 : (maybe
2312 ? G_("%qE may write a terminating nul past the end "
2313 "of the destination")
2314 : G_("%qE writing a terminating nul past the end "
2315 "of the destination")));
2317 return fmtwarn (dirloc, NULL, NULL, info.warnopt (), fmtstr,
2318 info.func);
2321 if (res.min == res.max)
2323 const char* fmtstr
2324 = (res.min == 1
2325 ? (info.bounded
2326 ? (maybe
2327 ? G_("%<%.*s%> directive output may be truncated writing "
2328 "%wu byte into a region of size %wu")
2329 : G_("%<%.*s%> directive output truncated writing "
2330 "%wu byte into a region of size %wu"))
2331 : G_("%<%.*s%> directive writing %wu byte "
2332 "into a region of size %wu"))
2333 : (info.bounded
2334 ? (maybe
2335 ? G_("%<%.*s%> directive output may be truncated writing "
2336 "%wu bytes into a region of size %wu")
2337 : G_("%<%.*s%> directive output truncated writing "
2338 "%wu bytes into a region of size %wu"))
2339 : G_("%<%.*s%> directive writing %wu bytes "
2340 "into a region of size %wu")));
2341 return fmtwarn (dirloc, pargrange, NULL,
2342 info.warnopt (), fmtstr,
2343 dir.len, dir.beg, res.min,
2344 navail);
2347 if (res.min == 0 && res.max < maxbytes)
2349 const char* fmtstr
2350 = (info.bounded
2351 ? (maybe
2352 ? G_("%<%.*s%> directive output may be truncated writing "
2353 "up to %wu bytes into a region of size %wu")
2354 : G_("%<%.*s%> directive output truncated writing "
2355 "up to %wu bytes into a region of size %wu"))
2356 : G_("%<%.*s%> directive writing up to %wu bytes "
2357 "into a region of size %wu"));
2358 return fmtwarn (dirloc, pargrange, NULL,
2359 info.warnopt (), fmtstr,
2360 dir.len, dir.beg,
2361 res.max, navail);
2364 if (res.min == 0 && maxbytes <= res.max)
2366 /* This is a special case to avoid issuing the potentially
2367 confusing warning:
2368 writing 0 or more bytes into a region of size 0. */
2369 const char* fmtstr
2370 = (info.bounded
2371 ? (maybe
2372 ? G_("%<%.*s%> directive output may be truncated writing "
2373 "likely %wu or more bytes into a region of size %wu")
2374 : G_("%<%.*s%> directive output truncated writing "
2375 "likely %wu or more bytes into a region of size %wu"))
2376 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2377 "into a region of size %wu"));
2378 return fmtwarn (dirloc, pargrange, NULL,
2379 info.warnopt (), fmtstr,
2380 dir.len, dir.beg,
2381 res.likely, navail);
2384 if (res.max < maxbytes)
2386 const char* fmtstr
2387 = (info.bounded
2388 ? (maybe
2389 ? G_("%<%.*s%> directive output may be truncated writing "
2390 "between %wu and %wu bytes into a region of size %wu")
2391 : G_("%<%.*s%> directive output truncated writing "
2392 "between %wu and %wu bytes into a region of size %wu"))
2393 : G_("%<%.*s%> directive writing between %wu and "
2394 "%wu bytes into a region of size %wu"));
2395 return fmtwarn (dirloc, pargrange, NULL,
2396 info.warnopt (), fmtstr,
2397 dir.len, dir.beg,
2398 res.min, res.max,
2399 navail);
2402 const char* fmtstr
2403 = (info.bounded
2404 ? (maybe
2405 ? G_("%<%.*s%> directive output may be truncated writing "
2406 "%wu or more bytes into a region of size %wu")
2407 : G_("%<%.*s%> directive output truncated writing "
2408 "%wu or more bytes into a region of size %wu"))
2409 : G_("%<%.*s%> directive writing %wu or more bytes "
2410 "into a region of size %wu"));
2411 return fmtwarn (dirloc, pargrange, NULL,
2412 info.warnopt (), fmtstr,
2413 dir.len, dir.beg,
2414 res.min, navail);
2417 /* The size of the destination region is a range. */
2419 if (*dir.beg != '%')
2421 unsigned HOST_WIDE_INT navail = avail_range.max;
2423 /* For plain character directives (i.e., the format string itself)
2424 but not others, point the caret at the first character that's
2425 past the end of the destination. */
2426 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2429 if (*dir.beg == '\0')
2431 gcc_assert (res.min == 1 && res.min == res.max);
2433 const char *fmtstr
2434 = (info.bounded
2435 ? (maybe
2436 ? G_("%qE output may be truncated before the last format "
2437 "character")
2438 : G_("%qE output truncated before the last format character"))
2439 : (maybe
2440 ? G_("%qE may write a terminating nul past the end "
2441 "of the destination")
2442 : G_("%qE writing a terminating nul past the end "
2443 "of the destination")));
2445 return fmtwarn (dirloc, NULL, NULL, info.warnopt (), fmtstr,
2446 info.func);
2449 if (res.min == res.max)
2451 const char* fmtstr
2452 = (res.min == 1
2453 ? (info.bounded
2454 ? (maybe
2455 ? G_("%<%.*s%> directive output may be truncated writing "
2456 "%wu byte into a region of size between %wu and %wu")
2457 : G_("%<%.*s%> directive output truncated writing "
2458 "%wu byte into a region of size between %wu and %wu"))
2459 : G_("%<%.*s%> directive writing %wu byte "
2460 "into a region of size between %wu and %wu"))
2461 : (info.bounded
2462 ? (maybe
2463 ? G_("%<%.*s%> directive output may be truncated writing "
2464 "%wu bytes into a region of size between %wu and %wu")
2465 : G_("%<%.*s%> directive output truncated writing "
2466 "%wu bytes into a region of size between %wu and %wu"))
2467 : G_("%<%.*s%> directive writing %wu bytes "
2468 "into a region of size between %wu and %wu")));
2470 return fmtwarn (dirloc, pargrange, NULL,
2471 info.warnopt (), fmtstr,
2472 dir.len, dir.beg, res.min,
2473 avail_range.min, avail_range.max);
2476 if (res.min == 0 && res.max < maxbytes)
2478 const char* fmtstr
2479 = (info.bounded
2480 ? (maybe
2481 ? G_("%<%.*s%> directive output may be truncated writing "
2482 "up to %wu bytes into a region of size between "
2483 "%wu and %wu")
2484 : G_("%<%.*s%> directive output truncated writing "
2485 "up to %wu bytes into a region of size between "
2486 "%wu and %wu"))
2487 : G_("%<%.*s%> directive writing up to %wu bytes "
2488 "into a region of size between %wu and %wu"));
2489 return fmtwarn (dirloc, pargrange, NULL,
2490 info.warnopt (), fmtstr,
2491 dir.len, dir.beg, res.max,
2492 avail_range.min, avail_range.max);
2495 if (res.min == 0 && maxbytes <= res.max)
2497 /* This is a special case to avoid issuing the potentially confusing
2498 warning:
2499 writing 0 or more bytes into a region of size between 0 and N. */
2500 const char* fmtstr
2501 = (info.bounded
2502 ? (maybe
2503 ? G_("%<%.*s%> directive output may be truncated writing "
2504 "likely %wu or more bytes into a region of size between "
2505 "%wu and %wu")
2506 : G_("%<%.*s%> directive output truncated writing likely "
2507 "%wu or more bytes into a region of size between "
2508 "%wu and %wu"))
2509 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2510 "into a region of size between %wu and %wu"));
2511 return fmtwarn (dirloc, pargrange, NULL,
2512 info.warnopt (), fmtstr,
2513 dir.len, dir.beg, res.likely,
2514 avail_range.min, avail_range.max);
2517 if (res.max < maxbytes)
2519 const char* fmtstr
2520 = (info.bounded
2521 ? (maybe
2522 ? G_("%<%.*s%> directive output may be truncated writing "
2523 "between %wu and %wu bytes into a region of size "
2524 "between %wu and %wu")
2525 : G_("%<%.*s%> directive output truncated writing "
2526 "between %wu and %wu bytes into a region of size "
2527 "between %wu and %wu"))
2528 : G_("%<%.*s%> directive writing between %wu and "
2529 "%wu bytes into a region of size between %wu and %wu"));
2530 return fmtwarn (dirloc, pargrange, NULL,
2531 info.warnopt (), fmtstr,
2532 dir.len, dir.beg,
2533 res.min, res.max,
2534 avail_range.min, avail_range.max);
2537 const char* fmtstr
2538 = (info.bounded
2539 ? (maybe
2540 ? G_("%<%.*s%> directive output may be truncated writing "
2541 "%wu or more bytes into a region of size between "
2542 "%wu and %wu")
2543 : G_("%<%.*s%> directive output truncated writing "
2544 "%wu or more bytes into a region of size between "
2545 "%wu and %wu"))
2546 : G_("%<%.*s%> directive writing %wu or more bytes "
2547 "into a region of size between %wu and %wu"));
2548 return fmtwarn (dirloc, pargrange, NULL,
2549 info.warnopt (), fmtstr,
2550 dir.len, dir.beg,
2551 res.min,
2552 avail_range.min, avail_range.max);
2555 /* Compute the length of the output resulting from the directive DIR
2556 in a call described by INFO and update the overall result of the call
2557 in *RES. Return true if the directive has been handled. */
2559 static bool
2560 format_directive (const pass_sprintf_length::call_info &info,
2561 format_result *res, const directive &dir)
2563 /* Offset of the beginning of the directive from the beginning
2564 of the format string. */
2565 size_t offset = dir.beg - info.fmtstr;
2566 size_t start = offset;
2567 size_t length = offset + dir.len - !!dir.len;
2569 /* Create a location for the whole directive from the % to the format
2570 specifier. */
2571 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2572 offset, start, length);
2574 /* Also create a location range for the argument if possible.
2575 This doesn't work for integer literals or function calls. */
2576 source_range argrange;
2577 source_range *pargrange;
2578 if (dir.arg && CAN_HAVE_LOCATION_P (dir.arg))
2580 argrange = EXPR_LOCATION_RANGE (dir.arg);
2581 pargrange = &argrange;
2583 else
2584 pargrange = NULL;
2586 /* Bail when there is no function to compute the output length,
2587 or when minimum length checking has been disabled. */
2588 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2589 return false;
2591 /* Compute the range of lengths of the formatted output. */
2592 fmtresult fmtres = dir.fmtfunc (dir, dir.arg);
2594 /* Record whether the output of all directives is known to be
2595 bounded by some maximum, implying that their arguments are
2596 either known exactly or determined to be in a known range
2597 or, for strings, limited by the upper bounds of the arrays
2598 they refer to. */
2599 res->knownrange &= fmtres.knownrange;
2601 if (!fmtres.knownrange)
2603 /* Only when the range is known, check it against the host value
2604 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2605 INT_MAX precision, which is the longest possible output of any
2606 single directive). That's the largest valid byte count (though
2607 not valid call to a printf-like function because it can never
2608 return such a count). Otherwise, the range doesn't correspond
2609 to known values of the argument. */
2610 if (fmtres.range.max > target_dir_max ())
2612 /* Normalize the MAX counter to avoid having to deal with it
2613 later. The counter can be less than HOST_WIDE_INT_M1U
2614 when compiling for an ILP32 target on an LP64 host. */
2615 fmtres.range.max = HOST_WIDE_INT_M1U;
2616 /* Disable exact and maximum length checking after a failure
2617 to determine the maximum number of characters (for example
2618 for wide characters or wide character strings) but continue
2619 tracking the minimum number of characters. */
2620 res->range.max = HOST_WIDE_INT_M1U;
2623 if (fmtres.range.min > target_dir_max ())
2625 /* Disable exact length checking after a failure to determine
2626 even the minimum number of characters (it shouldn't happen
2627 except in an error) but keep tracking the minimum and maximum
2628 number of characters. */
2629 return true;
2633 int dirlen = dir.len;
2635 if (fmtres.nullp)
2637 fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
2638 "%<%.*s%> directive argument is null",
2639 dirlen, dir.beg);
2641 /* Don't bother processing the rest of the format string. */
2642 res->warned = true;
2643 res->range.min = HOST_WIDE_INT_M1U;
2644 res->range.max = HOST_WIDE_INT_M1U;
2645 return false;
2648 /* Compute the number of available bytes in the destination. There
2649 must always be at least one byte of space for the terminating
2650 NUL that's appended after the format string has been processed. */
2651 result_range avail_range = bytes_remaining (info.objsize, *res);
2653 bool warned = res->warned;
2655 if (!warned)
2656 warned = maybe_warn (dirloc, pargrange, info, avail_range,
2657 fmtres.range, dir);
2659 /* Bump up the total maximum if it isn't too big. */
2660 if (res->range.max < HOST_WIDE_INT_MAX
2661 && fmtres.range.max < HOST_WIDE_INT_MAX)
2662 res->range.max += fmtres.range.max;
2664 /* Raise the total unlikely maximum by the larger of the maximum
2665 and the unlikely maximum. */
2666 unsigned HOST_WIDE_INT save = res->range.unlikely;
2667 if (fmtres.range.max < fmtres.range.unlikely)
2668 res->range.unlikely += fmtres.range.unlikely;
2669 else
2670 res->range.unlikely += fmtres.range.max;
2672 if (res->range.unlikely < save)
2673 res->range.unlikely = HOST_WIDE_INT_M1U;
2675 res->range.min += fmtres.range.min;
2676 res->range.likely += fmtres.range.likely;
2678 /* Has the minimum directive output length exceeded the maximum
2679 of 4095 bytes required to be supported? */
2680 bool minunder4k = fmtres.range.min < 4096;
2681 bool maxunder4k = fmtres.range.max < 4096;
2682 /* Clear UNDER4K in the overall result if the maximum has exceeded
2683 the 4k (this is necessary to avoid the return valuye optimization
2684 that may not be safe in the maximum case). */
2685 if (!maxunder4k)
2686 res->under4k = false;
2688 if (!warned
2689 /* Only warn at level 2. */
2690 && 1 < warn_level
2691 && (!minunder4k
2692 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2694 /* The directive output may be longer than the maximum required
2695 to be handled by an implementation according to 7.21.6.1, p15
2696 of C11. Warn on this only at level 2 but remember this and
2697 prevent folding the return value when done. This allows for
2698 the possibility of the actual libc call failing due to ENOMEM
2699 (like Glibc does under some conditions). */
2701 if (fmtres.range.min == fmtres.range.max)
2702 warned = fmtwarn (dirloc, pargrange, NULL,
2703 info.warnopt (),
2704 "%<%.*s%> directive output of %wu bytes exceeds "
2705 "minimum required size of 4095",
2706 dirlen, dir.beg, fmtres.range.min);
2707 else
2709 const char *fmtstr
2710 = (minunder4k
2711 ? G_("%<%.*s%> directive output between %wu and %wu "
2712 "bytes may exceed minimum required size of 4095")
2713 : G_("%<%.*s%> directive output between %wu and %wu "
2714 "bytes exceeds minimum required size of 4095"));
2716 warned = fmtwarn (dirloc, pargrange, NULL,
2717 info.warnopt (), fmtstr,
2718 dirlen, dir.beg,
2719 fmtres.range.min, fmtres.range.max);
2723 /* Has the likely and maximum directive output exceeded INT_MAX? */
2724 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2725 /* Don't consider the maximum to be in excess when it's the result
2726 of a string of unknown length (i.e., whose maximum has been set
2727 to be greater than or equal to HOST_WIDE_INT_MAX. */
2728 bool maxximax = (*dir.beg
2729 && res->range.max > target_int_max ()
2730 && res->range.max < HOST_WIDE_INT_MAX);
2732 if (!warned
2733 /* Warn for the likely output size at level 1. */
2734 && (likelyximax
2735 /* But only warn for the maximum at level 2. */
2736 || (1 < warn_level
2737 && maxximax
2738 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2740 /* The directive output causes the total length of output
2741 to exceed INT_MAX bytes. */
2743 if (fmtres.range.min == fmtres.range.max)
2744 warned = fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
2745 "%<%.*s%> directive output of %wu bytes causes "
2746 "result to exceed %<INT_MAX%>",
2747 dirlen, dir.beg, fmtres.range.min);
2748 else
2750 const char *fmtstr
2751 = (fmtres.range.min > target_int_max ()
2752 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2753 "bytes causes result to exceed %<INT_MAX%>")
2754 : G_ ("%<%.*s%> directive output between %wu and %wu "
2755 "bytes may cause result to exceed %<INT_MAX%>"));
2756 warned = fmtwarn (dirloc, pargrange, NULL,
2757 info.warnopt (), fmtstr,
2758 dirlen, dir.beg,
2759 fmtres.range.min, fmtres.range.max);
2763 if (warned && fmtres.range.min < fmtres.range.likely
2764 && fmtres.range.likely < fmtres.range.max)
2766 inform (info.fmtloc,
2767 (1 == fmtres.range.likely
2768 ? G_("assuming directive output of %wu byte")
2769 : G_("assuming directive output of %wu bytes")),
2770 fmtres.range.likely);
2773 if (warned && fmtres.argmin)
2775 if (fmtres.argmin == fmtres.argmax)
2776 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2777 else if (fmtres.knownrange)
2778 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2779 fmtres.argmin, fmtres.argmax);
2780 else
2781 inform (info.fmtloc,
2782 "using the range [%E, %E] for directive argument",
2783 fmtres.argmin, fmtres.argmax);
2786 res->warned |= warned;
2788 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2790 /* If a warning has been issued for buffer overflow or truncation
2791 (but not otherwise) help the user figure out how big a buffer
2792 they need. */
2794 location_t callloc = gimple_location (info.callstmt);
2796 unsigned HOST_WIDE_INT min = res->range.min;
2797 unsigned HOST_WIDE_INT max = res->range.max;
2799 if (min == max)
2800 inform (callloc,
2801 (min == 1
2802 ? G_("%qE output %wu byte into a destination of size %wu")
2803 : G_("%qE output %wu bytes into a destination of size %wu")),
2804 info.func, min, info.objsize);
2805 else if (max < HOST_WIDE_INT_MAX)
2806 inform (callloc,
2807 "%qE output between %wu and %wu bytes into "
2808 "a destination of size %wu",
2809 info.func, min, max, info.objsize);
2810 else if (min < res->range.likely && res->range.likely < max)
2811 inform (callloc,
2812 "%qE output %wu or more bytes (assuming %wu) into "
2813 "a destination of size %wu",
2814 info.func, min, res->range.likely, info.objsize);
2815 else
2816 inform (callloc,
2817 "%qE output %wu or more bytes into a destination of size %wu",
2818 info.func, min, info.objsize);
2821 if (dump_file && *dir.beg)
2823 fprintf (dump_file, " Result: %lli, %lli, %lli, %lli "
2824 "(%lli, %lli, %lli, %lli)\n",
2825 (long long)fmtres.range.min,
2826 (long long)fmtres.range.likely,
2827 (long long)fmtres.range.max,
2828 (long long)fmtres.range.unlikely,
2829 (long long)res->range.min,
2830 (long long)res->range.likely,
2831 (long long)res->range.max,
2832 (long long)res->range.unlikely);
2835 return true;
2838 #pragma GCC diagnostic pop
2840 /* Parse a format directive in function call described by INFO starting
2841 at STR and populate DIR structure. Bump up *ARGNO by the number of
2842 arguments extracted for the directive. Return the length of
2843 the directive. */
2845 static size_t
2846 parse_directive (pass_sprintf_length::call_info &info,
2847 directive &dir, format_result *res,
2848 const char *str, unsigned *argno)
2850 const char *pcnt = strchr (str, '%');
2851 dir.beg = str;
2853 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
2855 /* This directive is either a plain string or the terminating nul
2856 (which isn't really a directive but it simplifies things to
2857 handle it as if it were). */
2858 dir.len = len;
2859 dir.fmtfunc = format_plain;
2861 if (dump_file)
2863 fprintf (dump_file, " Directive %u at offset %llu: \"%.*s\", "
2864 "length = %llu\n",
2865 dir.dirno,
2866 (unsigned long long)(size_t)(dir.beg - info.fmtstr),
2867 (int)dir.len, dir.beg, (unsigned long long)dir.len);
2870 return len - !*str;
2873 const char *pf = pcnt + 1;
2875 /* POSIX numbered argument index or zero when none. */
2876 unsigned dollar = 0;
2878 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
2879 when given by a va_list argument, and a non-negative value
2880 when specified in the format string itself. */
2881 HOST_WIDE_INT width = -1;
2882 HOST_WIDE_INT precision = -1;
2884 /* Width specified via the asterisk. Need not be INTEGER_CST.
2885 For vararg functions set to void_node. */
2886 tree star_width = NULL_TREE;
2888 /* Width specified via the asterisk. Need not be INTEGER_CST.
2889 For vararg functions set to void_node. */
2890 tree star_precision = NULL_TREE;
2892 if (ISDIGIT (*pf))
2894 /* This could be either a POSIX positional argument, the '0'
2895 flag, or a width, depending on what follows. Store it as
2896 width and sort it out later after the next character has
2897 been seen. */
2898 char *end;
2899 width = strtol (pf, &end, 10);
2900 pf = end;
2902 else if ('*' == *pf)
2904 /* Similarly to the block above, this could be either a POSIX
2905 positional argument or a width, depending on what follows. */
2906 if (*argno < gimple_call_num_args (info.callstmt))
2907 star_width = gimple_call_arg (info.callstmt, (*argno)++);
2908 else
2909 star_width = void_node;
2910 ++pf;
2913 if (*pf == '$')
2915 /* Handle the POSIX dollar sign which references the 1-based
2916 positional argument number. */
2917 if (width != -1)
2918 dollar = width + info.argidx;
2919 else if (star_width
2920 && TREE_CODE (star_width) == INTEGER_CST
2921 && (TYPE_PRECISION (TREE_TYPE (star_width))
2922 <= TYPE_PRECISION (integer_type_node)))
2923 dollar = width + tree_to_shwi (star_width);
2925 /* Bail when the numbered argument is out of range (it will
2926 have already been diagnosed by -Wformat). */
2927 if (dollar == 0
2928 || dollar == info.argidx
2929 || dollar > gimple_call_num_args (info.callstmt))
2930 return false;
2932 --dollar;
2934 star_width = NULL_TREE;
2935 width = -1;
2936 ++pf;
2939 if (dollar || !star_width)
2941 if (width != -1)
2943 if (width == 0)
2945 /* The '0' that has been interpreted as a width above is
2946 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
2947 and continue processing other flags. */
2948 width = -1;
2949 dir.set_flag ('0');
2951 else if (!dollar)
2953 /* (Non-zero) width has been seen. The next character
2954 is either a period or a digit. */
2955 goto start_precision;
2958 /* When either '$' has been seen, or width has not been seen,
2959 the next field is the optional flags followed by an optional
2960 width. */
2961 for ( ; ; ) {
2962 switch (*pf)
2964 case ' ':
2965 case '0':
2966 case '+':
2967 case '-':
2968 case '#':
2969 dir.set_flag (*pf++);
2970 break;
2972 default:
2973 goto start_width;
2977 start_width:
2978 if (ISDIGIT (*pf))
2980 char *end;
2981 width = strtol (pf, &end, 10);
2982 pf = end;
2984 else if ('*' == *pf)
2986 if (*argno < gimple_call_num_args (info.callstmt))
2987 star_width = gimple_call_arg (info.callstmt, (*argno)++);
2988 else
2990 /* This is (likely) a va_list. It could also be an invalid
2991 call with insufficient arguments. */
2992 star_width = void_node;
2994 ++pf;
2996 else if ('\'' == *pf)
2998 /* The POSIX apostrophe indicating a numeric grouping
2999 in the current locale. Even though it's possible to
3000 estimate the upper bound on the size of the output
3001 based on the number of digits it probably isn't worth
3002 continuing. */
3003 return 0;
3007 start_precision:
3008 if ('.' == *pf)
3010 ++pf;
3012 if (ISDIGIT (*pf))
3014 char *end;
3015 precision = strtol (pf, &end, 10);
3016 pf = end;
3018 else if ('*' == *pf)
3020 if (*argno < gimple_call_num_args (info.callstmt))
3021 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3022 else
3024 /* This is (likely) a va_list. It could also be an invalid
3025 call with insufficient arguments. */
3026 star_precision = void_node;
3028 ++pf;
3030 else
3032 /* The decimal precision or the asterisk are optional.
3033 When neither is dirified it's taken to be zero. */
3034 precision = 0;
3038 switch (*pf)
3040 case 'h':
3041 if (pf[1] == 'h')
3043 ++pf;
3044 dir.modifier = FMT_LEN_hh;
3046 else
3047 dir.modifier = FMT_LEN_h;
3048 ++pf;
3049 break;
3051 case 'j':
3052 dir.modifier = FMT_LEN_j;
3053 ++pf;
3054 break;
3056 case 'L':
3057 dir.modifier = FMT_LEN_L;
3058 ++pf;
3059 break;
3061 case 'l':
3062 if (pf[1] == 'l')
3064 ++pf;
3065 dir.modifier = FMT_LEN_ll;
3067 else
3068 dir.modifier = FMT_LEN_l;
3069 ++pf;
3070 break;
3072 case 't':
3073 dir.modifier = FMT_LEN_t;
3074 ++pf;
3075 break;
3077 case 'z':
3078 dir.modifier = FMT_LEN_z;
3079 ++pf;
3080 break;
3083 switch (*pf)
3085 /* Handle a sole '%' character the same as "%%" but since it's
3086 undefined prevent the result from being folded. */
3087 case '\0':
3088 --pf;
3089 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3090 /* FALLTHRU */
3091 case '%':
3092 dir.fmtfunc = format_percent;
3093 break;
3095 case 'a':
3096 case 'A':
3097 case 'e':
3098 case 'E':
3099 case 'f':
3100 case 'F':
3101 case 'g':
3102 case 'G':
3103 res->floating = true;
3104 dir.fmtfunc = format_floating;
3105 break;
3107 case 'd':
3108 case 'i':
3109 case 'o':
3110 case 'u':
3111 case 'x':
3112 case 'X':
3113 dir.fmtfunc = format_integer;
3114 break;
3116 case 'p':
3117 /* The %p output is implementation-defined. It's possible
3118 to determine this format but due to extensions (edirially
3119 those of the Linux kernel -- see bug 78512) the first %p
3120 in the format string disables any further processing. */
3121 return false;
3123 case 'n':
3124 /* %n has side-effects even when nothing is actually printed to
3125 any buffer. */
3126 info.nowrite = false;
3127 dir.fmtfunc = format_none;
3128 break;
3130 case 'c':
3131 dir.fmtfunc = format_character;
3132 break;
3134 case 'S':
3135 case 's':
3136 dir.fmtfunc = format_string;
3137 break;
3139 default:
3140 /* Unknown conversion specification. */
3141 return 0;
3144 dir.specifier = *pf++;
3146 if (star_width)
3148 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3149 dir.set_width (star_width);
3150 else
3152 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3153 (width is the absolute value of that specified). */
3154 dir.width[0] = 0;
3155 dir.width[1] = target_int_max () + 1;
3158 else
3159 dir.set_width (width);
3161 if (star_precision)
3163 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3164 dir.set_precision (star_precision);
3165 else
3167 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3168 (unlike width, negative precision is ignored). */
3169 dir.prec[0] = -1;
3170 dir.prec[1] = target_int_max ();
3173 else
3174 dir.set_precision (precision);
3176 /* Extract the argument if the directive takes one and if it's
3177 available (e.g., the function doesn't take a va_list). Treat
3178 missing arguments the same as va_list, even though they will
3179 have likely already been diagnosed by -Wformat. */
3180 if (dir.specifier != '%'
3181 && *argno < gimple_call_num_args (info.callstmt))
3182 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3184 /* Return the length of the format directive. */
3185 dir.len = pf - pcnt;
3187 if (dump_file)
3189 fprintf (dump_file, " Directive %u at offset %llu: \"%.*s\"",
3190 dir.dirno, (unsigned long long)(size_t)(dir.beg - info.fmtstr),
3191 (int)dir.len, dir.beg);
3192 if (star_width)
3194 if (dir.width[0] == dir.width[1])
3195 fprintf (dump_file, ", width = %lli", (long long)dir.width[0]);
3196 else
3197 fprintf (dump_file, ", width in range [%lli, %lli]",
3198 (long long)dir.width[0], (long long)dir.width[1]);
3201 if (star_precision)
3203 if (dir.prec[0] == dir.prec[1])
3204 fprintf (dump_file, ", precision = %lli", (long long)dir.prec[0]);
3205 else
3206 fprintf (dump_file, ", precision in range [%lli, %lli]",
3207 (long long)dir.prec[0], (long long)dir.prec[1]);
3209 fputc ('\n', dump_file);
3212 return dir.len;
3215 /* Compute the length of the output resulting from the call to a formatted
3216 output function described by INFO and store the result of the call in
3217 *RES. Issue warnings for detected past the end writes. Return true
3218 if the complete format string has been processed and *RES can be relied
3219 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3220 that caused the processing to be terminated early). */
3222 bool
3223 pass_sprintf_length::compute_format_length (call_info &info,
3224 format_result *res)
3226 if (dump_file)
3228 location_t callloc = gimple_location (info.callstmt);
3229 fprintf (dump_file, "%s:%i: ",
3230 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3231 print_generic_expr (dump_file, info.func, dump_flags);
3233 fprintf (dump_file, ": objsize = %llu, fmtstr = \"%s\"\n",
3234 (unsigned long long)info.objsize, info.fmtstr);
3237 /* Reset the minimum and maximum byte counters. */
3238 res->range.min = res->range.max = 0;
3240 /* No directive has been seen yet so the length of output is bounded
3241 by the known range [0, 0] (with no conversion producing more than
3242 4K bytes) until determined otherwise. */
3243 res->knownrange = true;
3244 res->under4k = true;
3245 res->floating = false;
3246 res->warned = false;
3248 /* 1-based directive counter. */
3249 unsigned dirno = 1;
3251 /* The variadic argument counter. */
3252 unsigned argno = info.argidx;
3254 for (const char *pf = info.fmtstr; ; ++dirno)
3256 directive dir = directive ();
3257 dir.dirno = dirno;
3259 size_t n = parse_directive (info, dir, res, pf, &argno);
3261 /* Return failure if the format function fails. */
3262 if (!format_directive (info, res, dir))
3263 return false;
3265 /* Return success the directive is zero bytes long and it's
3266 the last think in the format string (i.e., it's the terminating
3267 nul, which isn't really a directive but handling it as one makes
3268 things simpler). */
3269 if (!n)
3270 return *pf == '\0';
3272 pf += n;
3275 /* The complete format string was processed (with or without warnings). */
3276 return true;
3279 /* Return the size of the object referenced by the expression DEST if
3280 available, or -1 otherwise. */
3282 static unsigned HOST_WIDE_INT
3283 get_destination_size (tree dest)
3285 /* Initialize object size info before trying to compute it. */
3286 init_object_sizes ();
3288 /* Use __builtin_object_size to determine the size of the destination
3289 object. When optimizing, determine the smallest object (such as
3290 a member array as opposed to the whole enclosing object), otherwise
3291 use type-zero object size to determine the size of the enclosing
3292 object (the function fails without optimization in this type). */
3293 int ost = optimize > 0;
3294 unsigned HOST_WIDE_INT size;
3295 if (compute_builtin_object_size (dest, ost, &size))
3296 return size;
3298 return HOST_WIDE_INT_M1U;
3301 /* Given a suitable result RES of a call to a formatted output function
3302 described by INFO, substitute the result for the return value of
3303 the call. The result is suitable if the number of bytes it represents
3304 is known and exact. A result that isn't suitable for substitution may
3305 have its range set to the range of return values, if that is known.
3306 Return true if the call is removed and gsi_next should not be performed
3307 in the caller. */
3309 static bool
3310 try_substitute_return_value (gimple_stmt_iterator *gsi,
3311 const pass_sprintf_length::call_info &info,
3312 const format_result &res)
3314 tree lhs = gimple_get_lhs (info.callstmt);
3316 /* Set to true when the entire call has been removed. */
3317 bool removed = false;
3319 /* The minimum return value. */
3320 unsigned HOST_WIDE_INT minretval = res.range.min;
3322 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3323 but in cases involving multibyte characters could be as large as
3324 RES.RANGE.UNLIKELY. */
3325 unsigned HOST_WIDE_INT maxretval
3326 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3328 /* Adjust the number of bytes which includes the terminating nul
3329 to reflect the return value of the function which does not.
3330 Because the valid range of the function is [INT_MIN, INT_MAX],
3331 a valid range before the adjustment below is [0, INT_MAX + 1]
3332 (the functions only return negative values on error or undefined
3333 behavior). */
3334 if (minretval <= target_int_max () + 1)
3335 --minretval;
3336 if (maxretval <= target_int_max () + 1)
3337 --maxretval;
3339 /* Avoid the return value optimization when the behavior of the call
3340 is undefined either because any directive may have produced 4K or
3341 more of output, or the return value exceeds INT_MAX, or because
3342 the output overflows the destination object (but leave it enabled
3343 when the function is bounded because then the behavior is well-
3344 defined). */
3345 if (res.under4k
3346 && minretval == maxretval
3347 && (info.bounded || minretval < info.objsize)
3348 && minretval <= target_int_max ()
3349 /* Not prepared to handle possibly throwing calls here; they shouldn't
3350 appear in non-artificial testcases, except when the __*_chk routines
3351 are badly declared. */
3352 && !stmt_ends_bb_p (info.callstmt))
3354 tree cst = build_int_cst (integer_type_node, minretval);
3356 if (lhs == NULL_TREE
3357 && info.nowrite)
3359 /* Remove the call to the bounded function with a zero size
3360 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3361 unlink_stmt_vdef (info.callstmt);
3362 gsi_remove (gsi, true);
3363 removed = true;
3365 else if (info.nowrite)
3367 /* Replace the call to the bounded function with a zero size
3368 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3369 of the function. */
3370 if (!update_call_from_tree (gsi, cst))
3371 gimplify_and_update_call_from_tree (gsi, cst);
3372 gimple *callstmt = gsi_stmt (*gsi);
3373 update_stmt (callstmt);
3375 else if (lhs)
3377 /* Replace the left-hand side of the call with the constant
3378 result of the formatted function. */
3379 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3380 gimple *g = gimple_build_assign (lhs, cst);
3381 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3382 update_stmt (info.callstmt);
3385 if (dump_file)
3387 if (removed)
3388 fprintf (dump_file, " Removing call statement.");
3389 else
3391 fprintf (dump_file, " Substituting ");
3392 print_generic_expr (dump_file, cst, dump_flags);
3393 fprintf (dump_file, " for %s.\n",
3394 info.nowrite ? "statement" : "return value");
3398 else if (lhs)
3400 bool setrange = false;
3402 if ((info.bounded || maxretval < info.objsize)
3403 && res.under4k
3404 && (minretval < target_int_max ()
3405 && maxretval < target_int_max ()))
3407 /* If the result is in a valid range bounded by the size of
3408 the destination set it so that it can be used for subsequent
3409 optimizations. */
3410 int prec = TYPE_PRECISION (integer_type_node);
3412 wide_int min = wi::shwi (minretval, prec);
3413 wide_int max = wi::shwi (maxretval, prec);
3414 set_range_info (lhs, VR_RANGE, min, max);
3416 setrange = true;
3419 if (dump_file)
3421 const char *inbounds
3422 = (minretval < info.objsize
3423 ? (maxretval < info.objsize
3424 ? "in" : "potentially out-of")
3425 : "out-of");
3427 const char *what = setrange ? "Setting" : "Discarding";
3428 if (minretval != maxretval)
3429 fprintf (dump_file,
3430 " %s %s-bounds return value range [%llu, %llu].\n",
3431 what, inbounds,
3432 (unsigned long long)minretval,
3433 (unsigned long long)maxretval);
3434 else
3435 fprintf (dump_file, " %s %s-bounds return value %llu.\n",
3436 what, inbounds, (unsigned long long)minretval);
3440 if (dump_file)
3441 fputc ('\n', dump_file);
3443 return removed;
3446 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3447 functions and if so, handle it. Return true if the call is removed
3448 and gsi_next should not be performed in the caller. */
3450 bool
3451 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator *gsi)
3453 call_info info = call_info ();
3455 info.callstmt = gsi_stmt (*gsi);
3456 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3457 return false;
3459 info.func = gimple_call_fndecl (info.callstmt);
3460 info.fncode = DECL_FUNCTION_CODE (info.func);
3462 /* The size of the destination as in snprintf(dest, size, ...). */
3463 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3465 /* The size of the destination determined by __builtin_object_size. */
3466 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3468 /* Buffer size argument number (snprintf and vsnprintf). */
3469 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3471 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3472 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3474 /* Format string argument number (valid for all functions). */
3475 unsigned idx_format;
3477 switch (info.fncode)
3479 case BUILT_IN_SPRINTF:
3480 // Signature:
3481 // __builtin_sprintf (dst, format, ...)
3482 idx_format = 1;
3483 info.argidx = 2;
3484 break;
3486 case BUILT_IN_SPRINTF_CHK:
3487 // Signature:
3488 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3489 idx_objsize = 2;
3490 idx_format = 3;
3491 info.argidx = 4;
3492 break;
3494 case BUILT_IN_SNPRINTF:
3495 // Signature:
3496 // __builtin_snprintf (dst, size, format, ...)
3497 idx_dstsize = 1;
3498 idx_format = 2;
3499 info.argidx = 3;
3500 info.bounded = true;
3501 break;
3503 case BUILT_IN_SNPRINTF_CHK:
3504 // Signature:
3505 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3506 idx_dstsize = 1;
3507 idx_objsize = 3;
3508 idx_format = 4;
3509 info.argidx = 5;
3510 info.bounded = true;
3511 break;
3513 case BUILT_IN_VSNPRINTF:
3514 // Signature:
3515 // __builtin_vsprintf (dst, size, format, va)
3516 idx_dstsize = 1;
3517 idx_format = 2;
3518 info.argidx = -1;
3519 info.bounded = true;
3520 break;
3522 case BUILT_IN_VSNPRINTF_CHK:
3523 // Signature:
3524 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3525 idx_dstsize = 1;
3526 idx_objsize = 3;
3527 idx_format = 4;
3528 info.argidx = -1;
3529 info.bounded = true;
3530 break;
3532 case BUILT_IN_VSPRINTF:
3533 // Signature:
3534 // __builtin_vsprintf (dst, format, va)
3535 idx_format = 1;
3536 info.argidx = -1;
3537 break;
3539 case BUILT_IN_VSPRINTF_CHK:
3540 // Signature:
3541 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3542 idx_format = 3;
3543 idx_objsize = 2;
3544 info.argidx = -1;
3545 break;
3547 default:
3548 return false;
3551 /* Set the global warning level for this function. */
3552 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3554 /* The first argument is a pointer to the destination. */
3555 tree dstptr = gimple_call_arg (info.callstmt, 0);
3557 info.format = gimple_call_arg (info.callstmt, idx_format);
3559 /* True when the destination size is constant as opposed to the lower
3560 or upper bound of a range. */
3561 bool dstsize_cst_p = true;
3563 if (idx_dstsize == HOST_WIDE_INT_M1U)
3565 /* For non-bounded functions like sprintf, determine the size
3566 of the destination from the object or pointer passed to it
3567 as the first argument. */
3568 dstsize = get_destination_size (dstptr);
3570 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3572 /* For bounded functions try to get the size argument. */
3574 if (TREE_CODE (size) == INTEGER_CST)
3576 dstsize = tree_to_uhwi (size);
3577 /* No object can be larger than SIZE_MAX bytes (half the address
3578 space) on the target.
3579 The functions are defined only for output of at most INT_MAX
3580 bytes. Specifying a bound in excess of that limit effectively
3581 defeats the bounds checking (and on some implementations such
3582 as Solaris cause the function to fail with EINVAL). */
3583 if (dstsize > target_size_max () / 2)
3585 /* Avoid warning if -Wstringop-overflow is specified since
3586 it also warns for the same thing though only for the
3587 checking built-ins. */
3588 if ((idx_objsize == HOST_WIDE_INT_M1U
3589 || !warn_stringop_overflow))
3590 warning_at (gimple_location (info.callstmt), info.warnopt (),
3591 "specified bound %wu exceeds maximum object size "
3592 "%wu",
3593 dstsize, target_size_max () / 2);
3595 else if (dstsize > target_int_max ())
3596 warning_at (gimple_location (info.callstmt), info.warnopt (),
3597 "specified bound %wu exceeds %<INT_MAX %>",
3598 dstsize);
3600 else if (TREE_CODE (size) == SSA_NAME)
3602 /* Try to determine the range of values of the argument
3603 and use the greater of the two at level 1 and the smaller
3604 of them at level 2. */
3605 wide_int min, max;
3606 enum value_range_type range_type
3607 = get_range_info (size, &min, &max);
3608 if (range_type == VR_RANGE)
3610 dstsize
3611 = (warn_level < 2
3612 ? wi::fits_uhwi_p (max) ? max.to_uhwi () : max.to_shwi ()
3613 : wi::fits_uhwi_p (min) ? min.to_uhwi () : min.to_shwi ());
3616 /* The destination size is not constant. If the function is
3617 bounded (e.g., snprintf) a lower bound of zero doesn't
3618 necessarily imply it can be eliminated. */
3619 dstsize_cst_p = false;
3623 if (idx_objsize != HOST_WIDE_INT_M1U)
3624 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3625 if (tree_fits_uhwi_p (size))
3626 objsize = tree_to_uhwi (size);
3628 if (info.bounded && !dstsize)
3630 /* As a special case, when the explicitly specified destination
3631 size argument (to a bounded function like snprintf) is zero
3632 it is a request to determine the number of bytes on output
3633 without actually producing any. Pretend the size is
3634 unlimited in this case. */
3635 info.objsize = HOST_WIDE_INT_MAX;
3636 info.nowrite = dstsize_cst_p;
3638 else
3640 /* For calls to non-bounded functions or to those of bounded
3641 functions with a non-zero size, warn if the destination
3642 pointer is null. */
3643 if (integer_zerop (dstptr))
3645 /* This is diagnosed with -Wformat only when the null is a constant
3646 pointer. The warning here diagnoses instances where the pointer
3647 is not constant. */
3648 location_t loc = gimple_location (info.callstmt);
3649 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3650 info.warnopt (), "null destination pointer");
3651 return false;
3654 /* Set the object size to the smaller of the two arguments
3655 of both have been specified and they're not equal. */
3656 info.objsize = dstsize < objsize ? dstsize : objsize;
3658 if (info.bounded
3659 && dstsize < target_size_max () / 2 && objsize < dstsize
3660 /* Avoid warning if -Wstringop-overflow is specified since
3661 it also warns for the same thing though only for the
3662 checking built-ins. */
3663 && (idx_objsize == HOST_WIDE_INT_M1U
3664 || !warn_stringop_overflow))
3666 warning_at (gimple_location (info.callstmt), info.warnopt (),
3667 "specified bound %wu exceeds the size %wu "
3668 "of the destination object", dstsize, objsize);
3672 if (integer_zerop (info.format))
3674 /* This is diagnosed with -Wformat only when the null is a constant
3675 pointer. The warning here diagnoses instances where the pointer
3676 is not constant. */
3677 location_t loc = gimple_location (info.callstmt);
3678 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3679 info.warnopt (), "null format string");
3680 return false;
3683 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3684 if (!info.fmtstr)
3685 return false;
3687 /* The result is the number of bytes output by the formatted function,
3688 including the terminating NUL. */
3689 format_result res = format_result ();
3691 bool success = compute_format_length (info, &res);
3693 /* When optimizing and the printf return value optimization is enabled,
3694 attempt to substitute the computed result for the return value of
3695 the call. Avoid this optimization when -frounding-math is in effect
3696 and the format string contains a floating point directive. */
3697 if (success
3698 && optimize > 0
3699 && flag_printf_return_value
3700 && (!flag_rounding_math || !res.floating))
3701 return try_substitute_return_value (gsi, info, res);
3703 return false;
3706 /* Execute the pass for function FUN. */
3708 unsigned int
3709 pass_sprintf_length::execute (function *fun)
3711 basic_block bb;
3712 FOR_EACH_BB_FN (bb, fun)
3714 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
3716 /* Iterate over statements, looking for function calls. */
3717 gimple *stmt = gsi_stmt (si);
3719 if (is_gimple_call (stmt) && handle_gimple_call (&si))
3720 /* If handle_gimple_call returns true, the iterator is
3721 already pointing to the next statement. */
3722 continue;
3724 gsi_next (&si);
3728 /* Clean up object size info. */
3729 fini_object_sizes ();
3731 return 0;
3734 } /* Unnamed namespace. */
3736 /* Return a pointer to a pass object newly constructed from the context
3737 CTXT. */
3739 gimple_opt_pass *
3740 make_pass_sprintf_length (gcc::context *ctxt)
3742 return new pass_sprintf_length (ctxt);