target-supports.exp (check_effective_target_weak_undefined): Return 0 on hppa*-*...
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blobced1c4c577702e908add6c47f3862eebce0ce027
1 /* Copyright (C) 2016-2019 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 "tree-scalar-evolution.h"
69 #include "tree-ssa-loop.h"
70 #include "intl.h"
71 #include "langhooks.h"
73 #include "attribs.h"
74 #include "builtins.h"
75 #include "stor-layout.h"
77 #include "realmpfr.h"
78 #include "target.h"
80 #include "cpplib.h"
81 #include "input.h"
82 #include "toplev.h"
83 #include "substring-locations.h"
84 #include "diagnostic.h"
85 #include "domwalk.h"
86 #include "alloc-pool.h"
87 #include "vr-values.h"
88 #include "gimple-ssa-evrp-analyze.h"
90 /* The likely worst case value of MB_LEN_MAX for the target, large enough
91 for UTF-8. Ideally, this would be obtained by a target hook if it were
92 to be used for optimization but it's good enough as is for warnings. */
93 #define target_mb_len_max() 6
95 /* The maximum number of bytes a single non-string directive can result
96 in. This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
97 LDBL_MAX_10_EXP of 4932. */
98 #define IEEE_MAX_10_EXP 4932
99 #define target_dir_max() (target_int_max () + IEEE_MAX_10_EXP + 2)
101 namespace {
103 const pass_data pass_data_sprintf_length = {
104 GIMPLE_PASS, // pass type
105 "printf-return-value", // pass name
106 OPTGROUP_NONE, // optinfo_flags
107 TV_NONE, // tv_id
108 PROP_cfg, // properties_required
109 0, // properties_provided
110 0, // properties_destroyed
111 0, // properties_start
112 0, // properties_finish
115 /* Set to the warning level for the current function which is equal
116 either to warn_format_trunc for bounded functions or to
117 warn_format_overflow otherwise. */
119 static int warn_level;
121 struct format_result;
123 class sprintf_dom_walker : public dom_walker
125 public:
126 sprintf_dom_walker ()
127 : dom_walker (CDI_DOMINATORS),
128 evrp_range_analyzer (false) {}
129 ~sprintf_dom_walker () {}
131 edge before_dom_children (basic_block) FINAL OVERRIDE;
132 void after_dom_children (basic_block) FINAL OVERRIDE;
133 bool handle_gimple_call (gimple_stmt_iterator *);
135 struct call_info;
136 bool compute_format_length (call_info &, format_result *);
137 class evrp_range_analyzer evrp_range_analyzer;
140 class pass_sprintf_length : public gimple_opt_pass
142 bool fold_return_value;
144 public:
145 pass_sprintf_length (gcc::context *ctxt)
146 : gimple_opt_pass (pass_data_sprintf_length, ctxt),
147 fold_return_value (false)
150 opt_pass * clone () { return new pass_sprintf_length (m_ctxt); }
152 virtual bool gate (function *);
154 virtual unsigned int execute (function *);
156 void set_pass_param (unsigned int n, bool param)
158 gcc_assert (n == 0);
159 fold_return_value = param;
164 bool
165 pass_sprintf_length::gate (function *)
167 /* Run the pass iff -Warn-format-overflow or -Warn-format-truncation
168 is specified and either not optimizing and the pass is being invoked
169 early, or when optimizing and the pass is being invoked during
170 optimization (i.e., "late"). */
171 return ((warn_format_overflow > 0
172 || warn_format_trunc > 0
173 || flag_printf_return_value)
174 && (optimize > 0) == fold_return_value);
177 /* The minimum, maximum, likely, and unlikely maximum number of bytes
178 of output either a formatting function or an individual directive
179 can result in. */
181 struct result_range
183 /* The absolute minimum number of bytes. The result of a successful
184 conversion is guaranteed to be no less than this. (An erroneous
185 conversion can be indicated by MIN > HOST_WIDE_INT_MAX.) */
186 unsigned HOST_WIDE_INT min;
187 /* The likely maximum result that is used in diagnostics. In most
188 cases MAX is the same as the worst case UNLIKELY result. */
189 unsigned HOST_WIDE_INT max;
190 /* The likely result used to trigger diagnostics. For conversions
191 that result in a range of bytes [MIN, MAX], LIKELY is somewhere
192 in that range. */
193 unsigned HOST_WIDE_INT likely;
194 /* In rare cases (e.g., for nultibyte characters) UNLIKELY gives
195 the worst cases maximum result of a directive. In most cases
196 UNLIKELY == MAX. UNLIKELY is used to control the return value
197 optimization but not in diagnostics. */
198 unsigned HOST_WIDE_INT unlikely;
201 /* The result of a call to a formatted function. */
203 struct format_result
205 /* Range of characters written by the formatted function.
206 Setting the minimum to HOST_WIDE_INT_MAX disables all
207 length tracking for the remainder of the format string. */
208 result_range range;
210 /* True when the range above is obtained from known values of
211 directive arguments, or bounds on the amount of output such
212 as width and precision, and not the result of heuristics that
213 depend on warning levels. It's used to issue stricter diagnostics
214 in cases where strings of unknown lengths are bounded by the arrays
215 they are determined to refer to. KNOWNRANGE must not be used for
216 the return value optimization. */
217 bool knownrange;
219 /* True if no individual directive could fail or result in more than
220 4095 bytes of output (the total NUMBER_CHARS_{MIN,MAX} might be
221 greater). Implementations are not required to handle directives
222 that produce more than 4K bytes (leading to undefined behavior)
223 and so when one is found it disables the return value optimization.
224 Similarly, directives that can fail (such as wide character
225 directives) disable the optimization. */
226 bool posunder4k;
228 /* True when a floating point directive has been seen in the format
229 string. */
230 bool floating;
232 /* True when an intermediate result has caused a warning. Used to
233 avoid issuing duplicate warnings while finishing the processing
234 of a call. WARNED also disables the return value optimization. */
235 bool warned;
237 /* Preincrement the number of output characters by 1. */
238 format_result& operator++ ()
240 return *this += 1;
243 /* Postincrement the number of output characters by 1. */
244 format_result operator++ (int)
246 format_result prev (*this);
247 *this += 1;
248 return prev;
251 /* Increment the number of output characters by N. */
252 format_result& operator+= (unsigned HOST_WIDE_INT);
255 format_result&
256 format_result::operator+= (unsigned HOST_WIDE_INT n)
258 gcc_assert (n < HOST_WIDE_INT_MAX);
260 if (range.min < HOST_WIDE_INT_MAX)
261 range.min += n;
263 if (range.max < HOST_WIDE_INT_MAX)
264 range.max += n;
266 if (range.likely < HOST_WIDE_INT_MAX)
267 range.likely += n;
269 if (range.unlikely < HOST_WIDE_INT_MAX)
270 range.unlikely += n;
272 return *this;
275 /* Return the value of INT_MIN for the target. */
277 static inline HOST_WIDE_INT
278 target_int_min ()
280 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
283 /* Return the value of INT_MAX for the target. */
285 static inline unsigned HOST_WIDE_INT
286 target_int_max ()
288 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
291 /* Return the value of SIZE_MAX for the target. */
293 static inline unsigned HOST_WIDE_INT
294 target_size_max ()
296 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
299 /* A straightforward mapping from the execution character set to the host
300 character set indexed by execution character. */
302 static char target_to_host_charmap[256];
304 /* Initialize a mapping from the execution character set to the host
305 character set. */
307 static bool
308 init_target_to_host_charmap ()
310 /* If the percent sign is non-zero the mapping has already been
311 initialized. */
312 if (target_to_host_charmap['%'])
313 return true;
315 /* Initialize the target_percent character (done elsewhere). */
316 if (!init_target_chars ())
317 return false;
319 /* The subset of the source character set used by printf conversion
320 specifications (strictly speaking, not all letters are used but
321 they are included here for the sake of simplicity). The dollar
322 sign must be included even though it's not in the basic source
323 character set. */
324 const char srcset[] = " 0123456789!\"#%&'()*+,-./:;<=>?[\\]^_{|}~$"
325 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
327 /* Set the mapping for all characters to some ordinary value (i,e.,
328 not none used in printf conversion specifications) and overwrite
329 those that are used by conversion specifications with their
330 corresponding values. */
331 memset (target_to_host_charmap + 1, '?', sizeof target_to_host_charmap - 1);
333 /* Are the two sets of characters the same? */
334 bool all_same_p = true;
336 for (const char *pc = srcset; *pc; ++pc)
338 /* Slice off the high end bits in case target characters are
339 signed. All values are expected to be non-nul, otherwise
340 there's a problem. */
341 if (unsigned char tc = lang_hooks.to_target_charset (*pc))
343 target_to_host_charmap[tc] = *pc;
344 if (tc != *pc)
345 all_same_p = false;
347 else
348 return false;
352 /* Set the first element to a non-zero value if the mapping
353 is 1-to-1, otherwise leave it clear (NUL is assumed to be
354 the same in both character sets). */
355 target_to_host_charmap[0] = all_same_p;
357 return true;
360 /* Return the host source character corresponding to the character
361 CH in the execution character set if one exists, or some innocuous
362 (non-special, non-nul) source character otherwise. */
364 static inline unsigned char
365 target_to_host (unsigned char ch)
367 return target_to_host_charmap[ch];
370 /* Convert an initial substring of the string TARGSTR consisting of
371 characters in the execution character set into a string in the
372 source character set on the host and store up to HOSTSZ characters
373 in the buffer pointed to by HOSTR. Return HOSTR. */
375 static const char*
376 target_to_host (char *hostr, size_t hostsz, const char *targstr)
378 /* Make sure the buffer is reasonably big. */
379 gcc_assert (hostsz > 4);
381 /* The interesting subset of source and execution characters are
382 the same so no conversion is necessary. However, truncate
383 overlong strings just like the translated strings are. */
384 if (target_to_host_charmap['\0'] == 1)
386 strncpy (hostr, targstr, hostsz - 4);
387 if (strlen (targstr) >= hostsz)
388 strcpy (hostr + hostsz - 4, "...");
389 return hostr;
392 /* Convert the initial substring of TARGSTR to the corresponding
393 characters in the host set, appending "..." if TARGSTR is too
394 long to fit. Using the static buffer assumes the function is
395 not called in between sequence points (which it isn't). */
396 for (char *ph = hostr; ; ++targstr)
398 *ph++ = target_to_host (*targstr);
399 if (!*targstr)
400 break;
402 if (size_t (ph - hostr) == hostsz - 4)
404 *ph = '\0';
405 strcat (ph, "...");
406 break;
410 return hostr;
413 /* Convert the sequence of decimal digits in the execution character
414 starting at *PS to a HOST_WIDE_INT, analogously to strtol. Return
415 the result and set *PS to one past the last converted character.
416 On range error set ERANGE to the digit that caused it. */
418 static inline HOST_WIDE_INT
419 target_strtowi (const char **ps, const char **erange)
421 unsigned HOST_WIDE_INT val = 0;
422 for ( ; ; ++*ps)
424 unsigned char c = target_to_host (**ps);
425 if (ISDIGIT (c))
427 c -= '0';
429 /* Check for overflow. */
430 if (val > ((unsigned HOST_WIDE_INT) HOST_WIDE_INT_MAX - c) / 10LU)
432 val = HOST_WIDE_INT_MAX;
433 *erange = *ps;
435 /* Skip the remaining digits. */
437 c = target_to_host (*++*ps);
438 while (ISDIGIT (c));
439 break;
441 else
442 val = val * 10 + c;
444 else
445 break;
448 return val;
451 /* Given FORMAT, set *PLOC to the source location of the format string
452 and return the format string if it is known or null otherwise. */
454 static const char*
455 get_format_string (tree format, location_t *ploc)
457 *ploc = EXPR_LOC_OR_LOC (format, input_location);
459 return c_getstr (format);
462 /* For convenience and brevity, shorter named entrypoints of
463 format_string_diagnostic_t::emit_warning_va and
464 format_string_diagnostic_t::emit_warning_n_va.
465 These have to be functions with the attribute so that exgettext
466 works properly. */
468 static bool
469 ATTRIBUTE_GCC_DIAG (5, 6)
470 fmtwarn (const substring_loc &fmt_loc, location_t param_loc,
471 const char *corrected_substring, int opt, const char *gmsgid, ...)
473 format_string_diagnostic_t diag (fmt_loc, NULL, param_loc, NULL,
474 corrected_substring);
475 va_list ap;
476 va_start (ap, gmsgid);
477 bool warned = diag.emit_warning_va (opt, gmsgid, &ap);
478 va_end (ap);
480 return warned;
483 static bool
484 ATTRIBUTE_GCC_DIAG (6, 8) ATTRIBUTE_GCC_DIAG (7, 8)
485 fmtwarn_n (const substring_loc &fmt_loc, location_t param_loc,
486 const char *corrected_substring, int opt, unsigned HOST_WIDE_INT n,
487 const char *singular_gmsgid, const char *plural_gmsgid, ...)
489 format_string_diagnostic_t diag (fmt_loc, NULL, param_loc, NULL,
490 corrected_substring);
491 va_list ap;
492 va_start (ap, plural_gmsgid);
493 bool warned = diag.emit_warning_n_va (opt, n, singular_gmsgid, plural_gmsgid,
494 &ap);
495 va_end (ap);
497 return warned;
500 /* Format length modifiers. */
502 enum format_lengths
504 FMT_LEN_none,
505 FMT_LEN_hh, // char argument
506 FMT_LEN_h, // short
507 FMT_LEN_l, // long
508 FMT_LEN_ll, // long long
509 FMT_LEN_L, // long double (and GNU long long)
510 FMT_LEN_z, // size_t
511 FMT_LEN_t, // ptrdiff_t
512 FMT_LEN_j // intmax_t
516 /* Description of the result of conversion either of a single directive
517 or the whole format string. */
519 struct fmtresult
521 /* Construct a FMTRESULT object with all counters initialized
522 to MIN. KNOWNRANGE is set when MIN is valid. */
523 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
524 : argmin (), argmax (), nonstr (),
525 knownrange (min < HOST_WIDE_INT_MAX),
526 mayfail (), nullp ()
528 range.min = min;
529 range.max = min;
530 range.likely = min;
531 range.unlikely = min;
534 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
535 KNOWNRANGE is set when both MIN and MAX are valid. */
536 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
537 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
538 : argmin (), argmax (), nonstr (),
539 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
540 mayfail (), nullp ()
542 range.min = min;
543 range.max = max;
544 range.likely = max < likely ? min : likely;
545 range.unlikely = max;
548 /* Adjust result upward to reflect the RANGE of values the specified
549 width or precision is known to be in. */
550 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
551 tree = NULL_TREE,
552 unsigned = 0, unsigned = 0);
554 /* Return the maximum number of decimal digits a value of TYPE
555 formats as on output. */
556 static unsigned type_max_digits (tree, int);
558 /* The range a directive's argument is in. */
559 tree argmin, argmax;
561 /* The minimum and maximum number of bytes that a directive
562 results in on output for an argument in the range above. */
563 result_range range;
565 /* Non-nul when the argument of a string directive is not a nul
566 terminated string. */
567 tree nonstr;
569 /* True when the range above is obtained from a known value of
570 a directive's argument or its bounds and not the result of
571 heuristics that depend on warning levels. */
572 bool knownrange;
574 /* True for a directive that may fail (such as wide character
575 directives). */
576 bool mayfail;
578 /* True when the argument is a null pointer. */
579 bool nullp;
582 /* Adjust result upward to reflect the range ADJUST of values the
583 specified width or precision is known to be in. When non-null,
584 TYPE denotes the type of the directive whose result is being
585 adjusted, BASE gives the base of the directive (octal, decimal,
586 or hex), and ADJ denotes the additional adjustment to the LIKELY
587 counter that may need to be added when ADJUST is a range. */
589 fmtresult&
590 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
591 tree type /* = NULL_TREE */,
592 unsigned base /* = 0 */,
593 unsigned adj /* = 0 */)
595 bool minadjusted = false;
597 /* Adjust the minimum and likely counters. */
598 if (adjust[0] >= 0)
600 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
602 range.min = adjust[0];
603 minadjusted = true;
606 /* Adjust the likely counter. */
607 if (range.likely < range.min)
608 range.likely = range.min;
610 else if (adjust[0] == target_int_min ()
611 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
612 knownrange = false;
614 /* Adjust the maximum counter. */
615 if (adjust[1] > 0)
617 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
619 range.max = adjust[1];
621 /* Set KNOWNRANGE if both the minimum and maximum have been
622 adjusted. Otherwise leave it at what it was before. */
623 knownrange = minadjusted;
627 if (warn_level > 1 && type)
629 /* For large non-constant width or precision whose range spans
630 the maximum number of digits produced by the directive for
631 any argument, set the likely number of bytes to be at most
632 the number digits plus other adjustment determined by the
633 caller (one for sign or two for the hexadecimal "0x"
634 prefix). */
635 unsigned dirdigs = type_max_digits (type, base);
636 if (adjust[0] < dirdigs && dirdigs < adjust[1]
637 && range.likely < dirdigs)
638 range.likely = dirdigs + adj;
640 else if (range.likely < (range.min ? range.min : 1))
642 /* Conservatively, set LIKELY to at least MIN but no less than
643 1 unless MAX is zero. */
644 range.likely = (range.min
645 ? range.min
646 : range.max && (range.max < HOST_WIDE_INT_MAX
647 || warn_level > 1) ? 1 : 0);
650 /* Finally adjust the unlikely counter to be at least as large as
651 the maximum. */
652 if (range.unlikely < range.max)
653 range.unlikely = range.max;
655 return *this;
658 /* Return the maximum number of digits a value of TYPE formats in
659 BASE on output, not counting base prefix . */
661 unsigned
662 fmtresult::type_max_digits (tree type, int base)
664 unsigned prec = TYPE_PRECISION (type);
665 switch (base)
667 case 8:
668 return (prec + 2) / 3;
669 case 10:
670 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
671 of 8, 16, 32, and 64 bits. */
672 return prec * 301 / 1000 + 1;
673 case 16:
674 return prec / 4;
677 gcc_unreachable ();
680 static bool
681 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT,
682 class vr_values *vr_values);
684 /* Description of a format directive. A directive is either a plain
685 string or a conversion specification that starts with '%'. */
687 struct directive
689 /* The 1-based directive number (for debugging). */
690 unsigned dirno;
692 /* The first character of the directive and its length. */
693 const char *beg;
694 size_t len;
696 /* A bitmap of flags, one for each character. */
697 unsigned flags[256 / sizeof (int)];
699 /* The range of values of the specified width, or -1 if not specified. */
700 HOST_WIDE_INT width[2];
701 /* The range of values of the specified precision, or -1 if not
702 specified. */
703 HOST_WIDE_INT prec[2];
705 /* Length modifier. */
706 format_lengths modifier;
708 /* Format specifier character. */
709 char specifier;
711 /* The argument of the directive or null when the directive doesn't
712 take one or when none is available (such as for vararg functions). */
713 tree arg;
715 /* Format conversion function that given a directive and an argument
716 returns the formatting result. */
717 fmtresult (*fmtfunc) (const directive &, tree, vr_values *);
719 /* Return True when a the format flag CHR has been used. */
720 bool get_flag (char chr) const
722 unsigned char c = chr & 0xff;
723 return (flags[c / (CHAR_BIT * sizeof *flags)]
724 & (1U << (c % (CHAR_BIT * sizeof *flags))));
727 /* Make a record of the format flag CHR having been used. */
728 void set_flag (char chr)
730 unsigned char c = chr & 0xff;
731 flags[c / (CHAR_BIT * sizeof *flags)]
732 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
735 /* Reset the format flag CHR. */
736 void clear_flag (char chr)
738 unsigned char c = chr & 0xff;
739 flags[c / (CHAR_BIT * sizeof *flags)]
740 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
743 /* Set both bounds of the width range to VAL. */
744 void set_width (HOST_WIDE_INT val)
746 width[0] = width[1] = val;
749 /* Set the width range according to ARG, with both bounds being
750 no less than 0. For a constant ARG set both bounds to its value
751 or 0, whichever is greater. For a non-constant ARG in some range
752 set width to its range adjusting each bound to -1 if it's less.
753 For an indeterminate ARG set width to [0, INT_MAX]. */
754 void set_width (tree arg, vr_values *vr_values)
756 get_int_range (arg, width, width + 1, true, 0, vr_values);
759 /* Set both bounds of the precision range to VAL. */
760 void set_precision (HOST_WIDE_INT val)
762 prec[0] = prec[1] = val;
765 /* Set the precision range according to ARG, with both bounds being
766 no less than -1. For a constant ARG set both bounds to its value
767 or -1 whichever is greater. For a non-constant ARG in some range
768 set precision to its range adjusting each bound to -1 if it's less.
769 For an indeterminate ARG set precision to [-1, INT_MAX]. */
770 void set_precision (tree arg, vr_values *vr_values)
772 get_int_range (arg, prec, prec + 1, false, -1, vr_values);
775 /* Return true if both width and precision are known to be
776 either constant or in some range, false otherwise. */
777 bool known_width_and_precision () const
779 return ((width[1] < 0
780 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
781 && (prec[1] < 0
782 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
786 /* Return the logarithm of X in BASE. */
788 static int
789 ilog (unsigned HOST_WIDE_INT x, int base)
791 int res = 0;
794 ++res;
795 x /= base;
796 } while (x);
797 return res;
800 /* Return the number of bytes resulting from converting into a string
801 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
802 PLUS indicates whether 1 for a plus sign should be added for positive
803 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
804 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
805 be represented. */
807 static HOST_WIDE_INT
808 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
810 unsigned HOST_WIDE_INT absval;
812 HOST_WIDE_INT res;
814 if (TYPE_UNSIGNED (TREE_TYPE (x)))
816 if (tree_fits_uhwi_p (x))
818 absval = tree_to_uhwi (x);
819 res = plus;
821 else
822 return -1;
824 else
826 if (tree_fits_shwi_p (x))
828 HOST_WIDE_INT i = tree_to_shwi (x);
829 if (HOST_WIDE_INT_MIN == i)
831 /* Avoid undefined behavior due to negating a minimum. */
832 absval = HOST_WIDE_INT_MAX;
833 res = 1;
835 else if (i < 0)
837 absval = -i;
838 res = 1;
840 else
842 absval = i;
843 res = plus;
846 else
847 return -1;
850 int ndigs = ilog (absval, base);
852 res += prec < ndigs ? ndigs : prec;
854 /* Adjust a non-zero value for the base prefix, either hexadecimal,
855 or, unless precision has resulted in a leading zero, also octal. */
856 if (prefix && absval && (base == 16 || prec <= ndigs))
858 if (base == 8)
859 res += 1;
860 else if (base == 16)
861 res += 2;
864 return res;
867 /* Given the formatting result described by RES and NAVAIL, the number
868 of available in the destination, return the range of bytes remaining
869 in the destination. */
871 static inline result_range
872 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
874 result_range range;
876 if (HOST_WIDE_INT_MAX <= navail)
878 range.min = range.max = range.likely = range.unlikely = navail;
879 return range;
882 /* The lower bound of the available range is the available size
883 minus the maximum output size, and the upper bound is the size
884 minus the minimum. */
885 range.max = res.range.min < navail ? navail - res.range.min : 0;
887 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
889 if (res.range.max < HOST_WIDE_INT_MAX)
890 range.min = res.range.max < navail ? navail - res.range.max : 0;
891 else
892 range.min = range.likely;
894 range.unlikely = (res.range.unlikely < navail
895 ? navail - res.range.unlikely : 0);
897 return range;
900 /* Description of a call to a formatted function. */
902 struct sprintf_dom_walker::call_info
904 /* Function call statement. */
905 gimple *callstmt;
907 /* Function called. */
908 tree func;
910 /* Called built-in function code. */
911 built_in_function fncode;
913 /* Format argument and format string extracted from it. */
914 tree format;
915 const char *fmtstr;
917 /* The location of the format argument. */
918 location_t fmtloc;
920 /* The destination object size for __builtin___xxx_chk functions
921 typically determined by __builtin_object_size, or -1 if unknown. */
922 unsigned HOST_WIDE_INT objsize;
924 /* Number of the first variable argument. */
925 unsigned HOST_WIDE_INT argidx;
927 /* True for functions like snprintf that specify the size of
928 the destination, false for others like sprintf that don't. */
929 bool bounded;
931 /* True for bounded functions like snprintf that specify a zero-size
932 buffer as a request to compute the size of output without actually
933 writing any. NOWRITE is cleared in response to the %n directive
934 which has side-effects similar to writing output. */
935 bool nowrite;
937 /* Return true if the called function's return value is used. */
938 bool retval_used () const
940 return gimple_get_lhs (callstmt);
943 /* Return the warning option corresponding to the called function. */
944 int warnopt () const
946 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
949 /* Return true for calls to file formatted functions. */
950 bool is_file_func () const
952 return (fncode == BUILT_IN_FPRINTF
953 || fncode == BUILT_IN_FPRINTF_CHK
954 || fncode == BUILT_IN_FPRINTF_UNLOCKED
955 || fncode == BUILT_IN_VFPRINTF
956 || fncode == BUILT_IN_VFPRINTF_CHK);
959 /* Return true for calls to string formatted functions. */
960 bool is_string_func () const
962 return (fncode == BUILT_IN_SPRINTF
963 || fncode == BUILT_IN_SPRINTF_CHK
964 || fncode == BUILT_IN_SNPRINTF
965 || fncode == BUILT_IN_SNPRINTF_CHK
966 || fncode == BUILT_IN_VSPRINTF
967 || fncode == BUILT_IN_VSPRINTF_CHK
968 || fncode == BUILT_IN_VSNPRINTF
969 || fncode == BUILT_IN_VSNPRINTF_CHK);
973 /* Return the result of formatting a no-op directive (such as '%n'). */
975 static fmtresult
976 format_none (const directive &, tree, vr_values *)
978 fmtresult res (0);
979 return res;
982 /* Return the result of formatting the '%%' directive. */
984 static fmtresult
985 format_percent (const directive &, tree, vr_values *)
987 fmtresult res (1);
988 return res;
992 /* Compute intmax_type_node and uintmax_type_node similarly to how
993 tree.c builds size_type_node. */
995 static void
996 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
998 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
1000 *pintmax = integer_type_node;
1001 *puintmax = unsigned_type_node;
1003 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
1005 *pintmax = long_integer_type_node;
1006 *puintmax = long_unsigned_type_node;
1008 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
1010 *pintmax = long_long_integer_type_node;
1011 *puintmax = long_long_unsigned_type_node;
1013 else
1015 for (int i = 0; i < NUM_INT_N_ENTS; i++)
1016 if (int_n_enabled_p[i])
1018 char name[50];
1019 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
1021 if (strcmp (name, UINTMAX_TYPE) == 0)
1023 *pintmax = int_n_trees[i].signed_type;
1024 *puintmax = int_n_trees[i].unsigned_type;
1025 return;
1028 gcc_unreachable ();
1032 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1033 in and that is representable in type int.
1034 Return true when the range is a subrange of that of int.
1035 When ARG is null it is as if it had the full range of int.
1036 When ABSOLUTE is true the range reflects the absolute value of
1037 the argument. When ABSOLUTE is false, negative bounds of
1038 the determined range are replaced with NEGBOUND. */
1040 static bool
1041 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1042 bool absolute, HOST_WIDE_INT negbound,
1043 class vr_values *vr_values)
1045 /* The type of the result. */
1046 const_tree type = integer_type_node;
1048 bool knownrange = false;
1050 if (!arg)
1052 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1053 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1055 else if (TREE_CODE (arg) == INTEGER_CST
1056 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1058 /* For a constant argument return its value adjusted as specified
1059 by NEGATIVE and NEGBOUND and return true to indicate that the
1060 result is known. */
1061 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1062 *pmax = *pmin;
1063 knownrange = true;
1065 else
1067 /* True if the argument's range cannot be determined. */
1068 bool unknown = true;
1070 tree argtype = TREE_TYPE (arg);
1072 /* Ignore invalid arguments with greater precision that that
1073 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1074 They will have been detected and diagnosed by -Wformat and
1075 so it's not important to complicate this code to try to deal
1076 with them again. */
1077 if (TREE_CODE (arg) == SSA_NAME
1078 && INTEGRAL_TYPE_P (argtype)
1079 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1081 /* Try to determine the range of values of the integer argument. */
1082 value_range *vr = vr_values->get_value_range (arg);
1083 if (range_int_cst_p (vr))
1085 HOST_WIDE_INT type_min
1086 = (TYPE_UNSIGNED (argtype)
1087 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1088 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1090 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1092 *pmin = TREE_INT_CST_LOW (vr->min ());
1093 *pmax = TREE_INT_CST_LOW (vr->max ());
1095 if (*pmin < *pmax)
1097 /* Return true if the adjusted range is a subrange of
1098 the full range of the argument's type. *PMAX may
1099 be less than *PMIN when the argument is unsigned
1100 and its upper bound is in excess of TYPE_MAX. In
1101 that (invalid) case disregard the range and use that
1102 of the expected type instead. */
1103 knownrange = type_min < *pmin || *pmax < type_max;
1105 unknown = false;
1110 /* Handle an argument with an unknown range as if none had been
1111 provided. */
1112 if (unknown)
1113 return get_int_range (NULL_TREE, pmin, pmax, absolute,
1114 negbound, vr_values);
1117 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1118 if (absolute)
1120 if (*pmin < 0)
1122 if (*pmin == *pmax)
1123 *pmin = *pmax = -*pmin;
1124 else
1126 /* Make sure signed overlow is avoided. */
1127 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1129 HOST_WIDE_INT tmp = -*pmin;
1130 *pmin = 0;
1131 if (*pmax < tmp)
1132 *pmax = tmp;
1136 else if (*pmin < negbound)
1137 *pmin = negbound;
1139 return knownrange;
1142 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1143 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1144 the type of the directive's formal argument it's possible for both
1145 to result in the same number of bytes or a range of bytes that's
1146 less than the number of bytes that would result from formatting
1147 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1148 determined by checking for the actual argument being in the range
1149 of the type of the directive. If it isn't it must be assumed to
1150 take on the full range of the directive's type.
1151 Return true when the range has been adjusted to the full range
1152 of DIRTYPE, and false otherwise. */
1154 static bool
1155 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1157 tree argtype = TREE_TYPE (*argmin);
1158 unsigned argprec = TYPE_PRECISION (argtype);
1159 unsigned dirprec = TYPE_PRECISION (dirtype);
1161 /* If the actual argument and the directive's argument have the same
1162 precision and sign there can be no overflow and so there is nothing
1163 to adjust. */
1164 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1165 return false;
1167 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1168 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1170 if (TREE_CODE (*argmin) == INTEGER_CST
1171 && TREE_CODE (*argmax) == INTEGER_CST
1172 && (dirprec >= argprec
1173 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1174 int_const_binop (MINUS_EXPR,
1175 *argmax,
1176 *argmin),
1177 size_int (dirprec)))))
1179 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1180 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1182 /* If *ARGMIN is still less than *ARGMAX the conversion above
1183 is safe. Otherwise, it has overflowed and would be unsafe. */
1184 if (tree_int_cst_le (*argmin, *argmax))
1185 return false;
1188 *argmin = TYPE_MIN_VALUE (dirtype);
1189 *argmax = TYPE_MAX_VALUE (dirtype);
1190 return true;
1193 /* Return a range representing the minimum and maximum number of bytes
1194 that the format directive DIR will output for any argument given
1195 the WIDTH and PRECISION (extracted from DIR). This function is
1196 used when the directive argument or its value isn't known. */
1198 static fmtresult
1199 format_integer (const directive &dir, tree arg, vr_values *vr_values)
1201 tree intmax_type_node;
1202 tree uintmax_type_node;
1204 /* Base to format the number in. */
1205 int base;
1207 /* True when a conversion is preceded by a prefix indicating the base
1208 of the argument (octal or hexadecimal). */
1209 bool maybebase = dir.get_flag ('#');
1211 /* True when a signed conversion is preceded by a sign or space. */
1212 bool maybesign = false;
1214 /* True for signed conversions (i.e., 'd' and 'i'). */
1215 bool sign = false;
1217 switch (dir.specifier)
1219 case 'd':
1220 case 'i':
1221 /* Space and '+' are only meaningful for signed conversions. */
1222 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1223 sign = true;
1224 base = 10;
1225 break;
1226 case 'u':
1227 base = 10;
1228 break;
1229 case 'o':
1230 base = 8;
1231 break;
1232 case 'X':
1233 case 'x':
1234 base = 16;
1235 break;
1236 default:
1237 gcc_unreachable ();
1240 /* The type of the "formal" argument expected by the directive. */
1241 tree dirtype = NULL_TREE;
1243 /* Determine the expected type of the argument from the length
1244 modifier. */
1245 switch (dir.modifier)
1247 case FMT_LEN_none:
1248 if (dir.specifier == 'p')
1249 dirtype = ptr_type_node;
1250 else
1251 dirtype = sign ? integer_type_node : unsigned_type_node;
1252 break;
1254 case FMT_LEN_h:
1255 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1256 break;
1258 case FMT_LEN_hh:
1259 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1260 break;
1262 case FMT_LEN_l:
1263 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1264 break;
1266 case FMT_LEN_L:
1267 case FMT_LEN_ll:
1268 dirtype = (sign
1269 ? long_long_integer_type_node
1270 : long_long_unsigned_type_node);
1271 break;
1273 case FMT_LEN_z:
1274 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1275 break;
1277 case FMT_LEN_t:
1278 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1279 break;
1281 case FMT_LEN_j:
1282 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1283 dirtype = sign ? intmax_type_node : uintmax_type_node;
1284 break;
1286 default:
1287 return fmtresult ();
1290 /* The type of the argument to the directive, either deduced from
1291 the actual non-constant argument if one is known, or from
1292 the directive itself when none has been provided because it's
1293 a va_list. */
1294 tree argtype = NULL_TREE;
1296 if (!arg)
1298 /* When the argument has not been provided, use the type of
1299 the directive's argument as an approximation. This will
1300 result in false positives for directives like %i with
1301 arguments with smaller precision (such as short or char). */
1302 argtype = dirtype;
1304 else if (TREE_CODE (arg) == INTEGER_CST)
1306 /* When a constant argument has been provided use its value
1307 rather than type to determine the length of the output. */
1308 fmtresult res;
1310 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1312 /* As a special case, a precision of zero with a zero argument
1313 results in zero bytes except in base 8 when the '#' flag is
1314 specified, and for signed conversions in base 8 and 10 when
1315 either the space or '+' flag has been specified and it results
1316 in just one byte (with width having the normal effect). This
1317 must extend to the case of a specified precision with
1318 an unknown value because it can be zero. */
1319 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1320 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1322 res.range.max = 1;
1323 res.range.likely = 1;
1325 else
1327 res.range.max = res.range.min;
1328 res.range.likely = res.range.min;
1331 else
1333 /* Convert the argument to the type of the directive. */
1334 arg = fold_convert (dirtype, arg);
1336 res.range.min = tree_digits (arg, base, dir.prec[0],
1337 maybesign, maybebase);
1338 if (dir.prec[0] == dir.prec[1])
1339 res.range.max = res.range.min;
1340 else
1341 res.range.max = tree_digits (arg, base, dir.prec[1],
1342 maybesign, maybebase);
1343 res.range.likely = res.range.min;
1344 res.knownrange = true;
1347 res.range.unlikely = res.range.max;
1349 /* Bump up the counters if WIDTH is greater than LEN. */
1350 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1351 (sign | maybebase) + (base == 16));
1352 /* Bump up the counters again if PRECision is greater still. */
1353 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1354 (sign | maybebase) + (base == 16));
1356 return res;
1358 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1359 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1360 /* Determine the type of the provided non-constant argument. */
1361 argtype = TREE_TYPE (arg);
1362 else
1363 /* Don't bother with invalid arguments since they likely would
1364 have already been diagnosed, and disable any further checking
1365 of the format string by returning [-1, -1]. */
1366 return fmtresult ();
1368 fmtresult res;
1370 /* Using either the range the non-constant argument is in, or its
1371 type (either "formal" or actual), create a range of values that
1372 constrain the length of output given the warning level. */
1373 tree argmin = NULL_TREE;
1374 tree argmax = NULL_TREE;
1376 if (arg
1377 && TREE_CODE (arg) == SSA_NAME
1378 && INTEGRAL_TYPE_P (argtype))
1380 /* Try to determine the range of values of the integer argument
1381 (range information is not available for pointers). */
1382 value_range *vr = vr_values->get_value_range (arg);
1383 if (range_int_cst_p (vr))
1385 argmin = vr->min ();
1386 argmax = vr->max ();
1388 /* Set KNOWNRANGE if the argument is in a known subrange
1389 of the directive's type and neither width nor precision
1390 is unknown. (KNOWNRANGE may be reset below). */
1391 res.knownrange
1392 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1393 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1394 && dir.known_width_and_precision ());
1396 res.argmin = argmin;
1397 res.argmax = argmax;
1399 else if (vr->kind () == VR_ANTI_RANGE)
1401 /* Handle anti-ranges if/when bug 71690 is resolved. */
1403 else if (vr->varying_p () || vr->undefined_p ())
1405 /* The argument here may be the result of promoting the actual
1406 argument to int. Try to determine the type of the actual
1407 argument before promotion and narrow down its range that
1408 way. */
1409 gimple *def = SSA_NAME_DEF_STMT (arg);
1410 if (is_gimple_assign (def))
1412 tree_code code = gimple_assign_rhs_code (def);
1413 if (code == INTEGER_CST)
1415 arg = gimple_assign_rhs1 (def);
1416 return format_integer (dir, arg, vr_values);
1419 if (code == NOP_EXPR)
1421 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1422 if (INTEGRAL_TYPE_P (type)
1423 || TREE_CODE (type) == POINTER_TYPE)
1424 argtype = type;
1430 if (!argmin)
1432 if (TREE_CODE (argtype) == POINTER_TYPE)
1434 argmin = build_int_cst (pointer_sized_int_node, 0);
1435 argmax = build_all_ones_cst (pointer_sized_int_node);
1437 else
1439 argmin = TYPE_MIN_VALUE (argtype);
1440 argmax = TYPE_MAX_VALUE (argtype);
1444 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1445 of the directive. If it has been cleared then since ARGMIN and/or
1446 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1447 ARGMAX in the result to include in diagnostics. */
1448 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1450 res.knownrange = false;
1451 res.argmin = argmin;
1452 res.argmax = argmax;
1455 /* Recursively compute the minimum and maximum from the known range. */
1456 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1458 /* For unsigned conversions/directives or signed when
1459 the minimum is positive, use the minimum and maximum to compute
1460 the shortest and longest output, respectively. */
1461 res.range.min = format_integer (dir, argmin, vr_values).range.min;
1462 res.range.max = format_integer (dir, argmax, vr_values).range.max;
1464 else if (tree_int_cst_sgn (argmax) < 0)
1466 /* For signed conversions/directives if maximum is negative,
1467 use the minimum as the longest output and maximum as the
1468 shortest output. */
1469 res.range.min = format_integer (dir, argmax, vr_values).range.min;
1470 res.range.max = format_integer (dir, argmin, vr_values).range.max;
1472 else
1474 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1475 as the shortest output and for the longest output compute the
1476 length of the output of both minimum and maximum and pick the
1477 longer. */
1478 unsigned HOST_WIDE_INT max1
1479 = format_integer (dir, argmin, vr_values).range.max;
1480 unsigned HOST_WIDE_INT max2
1481 = format_integer (dir, argmax, vr_values).range.max;
1482 res.range.min
1483 = format_integer (dir, integer_zero_node, vr_values).range.min;
1484 res.range.max = MAX (max1, max2);
1487 /* If the range is known, use the maximum as the likely length. */
1488 if (res.knownrange)
1489 res.range.likely = res.range.max;
1490 else
1492 /* Otherwise, use the minimum. Except for the case where for %#x or
1493 %#o the minimum is just for a single value in the range (0) and
1494 for all other values it is something longer, like 0x1 or 01.
1495 Use the length for value 1 in that case instead as the likely
1496 length. */
1497 res.range.likely = res.range.min;
1498 if (maybebase
1499 && base != 10
1500 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1502 if (res.range.min == 1)
1503 res.range.likely += base == 8 ? 1 : 2;
1504 else if (res.range.min == 2
1505 && base == 16
1506 && (dir.width[0] == 2 || dir.prec[0] == 2))
1507 ++res.range.likely;
1511 res.range.unlikely = res.range.max;
1512 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1513 (sign | maybebase) + (base == 16));
1514 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1515 (sign | maybebase) + (base == 16));
1517 return res;
1520 /* Return the number of bytes that a format directive consisting of FLAGS,
1521 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1522 would result for argument X under ideal conditions (i.e., if PREC
1523 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1524 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1525 This function works around those problems. */
1527 static unsigned HOST_WIDE_INT
1528 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1529 char spec, char rndspec)
1531 char fmtstr[40];
1533 HOST_WIDE_INT len = strlen (flags);
1535 fmtstr[0] = '%';
1536 memcpy (fmtstr + 1, flags, len);
1537 memcpy (fmtstr + 1 + len, ".*R", 3);
1538 fmtstr[len + 4] = rndspec;
1539 fmtstr[len + 5] = spec;
1540 fmtstr[len + 6] = '\0';
1542 spec = TOUPPER (spec);
1543 if (spec == 'E' || spec == 'F')
1545 /* For %e, specify the precision explicitly since mpfr_sprintf
1546 does its own thing just to be different (see MPFR bug 21088). */
1547 if (prec < 0)
1548 prec = 6;
1550 else
1552 /* Avoid passing negative precisions with larger magnitude to MPFR
1553 to avoid exposing its bugs. (A negative precision is supposed
1554 to be ignored.) */
1555 if (prec < 0)
1556 prec = -1;
1559 HOST_WIDE_INT p = prec;
1561 if (spec == 'G' && !strchr (flags, '#'))
1563 /* For G/g without the pound flag, precision gives the maximum number
1564 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1565 a 128 bit IEEE extended precision, 4932. Using twice as much here
1566 should be more than sufficient for any real format. */
1567 if ((IEEE_MAX_10_EXP * 2) < prec)
1568 prec = IEEE_MAX_10_EXP * 2;
1569 p = prec;
1571 else
1573 /* Cap precision arbitrarily at 1KB and add the difference
1574 (if any) to the MPFR result. */
1575 if (prec > 1024)
1576 p = 1024;
1579 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1581 /* Handle the unlikely (impossible?) error by returning more than
1582 the maximum dictated by the function's return type. */
1583 if (len < 0)
1584 return target_dir_max () + 1;
1586 /* Adjust the return value by the difference. */
1587 if (p < prec)
1588 len += prec - p;
1590 return len;
1593 /* Return the number of bytes to format using the format specifier
1594 SPEC and the precision PREC the largest value in the real floating
1595 TYPE. */
1597 static unsigned HOST_WIDE_INT
1598 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1600 machine_mode mode = TYPE_MODE (type);
1602 /* IBM Extended mode. */
1603 if (MODE_COMPOSITE_P (mode))
1604 mode = DFmode;
1606 /* Get the real type format desription for the target. */
1607 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1608 REAL_VALUE_TYPE rv;
1610 real_maxval (&rv, 0, mode);
1612 /* Convert the GCC real value representation with the precision
1613 of the real type to the mpfr_t format with the GCC default
1614 round-to-nearest mode. */
1615 mpfr_t x;
1616 mpfr_init2 (x, rfmt->p);
1617 mpfr_from_real (x, &rv, GMP_RNDN);
1619 /* Return a value one greater to account for the leading minus sign. */
1620 unsigned HOST_WIDE_INT r
1621 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1622 mpfr_clear (x);
1623 return r;
1626 /* Return a range representing the minimum and maximum number of bytes
1627 that the directive DIR will output for any argument. PREC gives
1628 the adjusted precision range to account for negative precisions
1629 meaning the default 6. This function is used when the directive
1630 argument or its value isn't known. */
1632 static fmtresult
1633 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1635 tree type;
1637 switch (dir.modifier)
1639 case FMT_LEN_l:
1640 case FMT_LEN_none:
1641 type = double_type_node;
1642 break;
1644 case FMT_LEN_L:
1645 type = long_double_type_node;
1646 break;
1648 case FMT_LEN_ll:
1649 type = long_double_type_node;
1650 break;
1652 default:
1653 return fmtresult ();
1656 /* The minimum and maximum number of bytes produced by the directive. */
1657 fmtresult res;
1659 /* The minimum output as determined by flags. It's always at least 1.
1660 When plus or space are set the output is preceded by either a sign
1661 or a space. */
1662 unsigned flagmin = (1 /* for the first digit */
1663 + (dir.get_flag ('+') | dir.get_flag (' ')));
1665 /* The minimum is 3 for "inf" and "nan" for all specifiers, plus 1
1666 for the plus sign/space with the '+' and ' ' flags, respectively,
1667 unless reduced below. */
1668 res.range.min = 2 + flagmin;
1670 /* When the pound flag is set the decimal point is included in output
1671 regardless of precision. Whether or not a decimal point is included
1672 otherwise depends on the specification and precision. */
1673 bool radix = dir.get_flag ('#');
1675 switch (dir.specifier)
1677 case 'A':
1678 case 'a':
1680 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1681 if (dir.prec[0] <= 0)
1682 minprec = 0;
1683 else if (dir.prec[0] > 0)
1684 minprec = dir.prec[0] + !radix /* decimal point */;
1686 res.range.likely = (2 /* 0x */
1687 + flagmin
1688 + radix
1689 + minprec
1690 + 3 /* p+0 */);
1692 res.range.max = format_floating_max (type, 'a', prec[1]);
1694 /* The unlikely maximum accounts for the longest multibyte
1695 decimal point character. */
1696 res.range.unlikely = res.range.max;
1697 if (dir.prec[1] > 0)
1698 res.range.unlikely += target_mb_len_max () - 1;
1700 break;
1703 case 'E':
1704 case 'e':
1706 /* Minimum output attributable to precision and, when it's
1707 non-zero, decimal point. */
1708 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1710 /* The likely minimum output is "[-+]1.234567e+00" regardless
1711 of the value of the actual argument. */
1712 res.range.likely = (flagmin
1713 + radix
1714 + minprec
1715 + 2 /* e+ */ + 2);
1717 res.range.max = format_floating_max (type, 'e', prec[1]);
1719 /* The unlikely maximum accounts for the longest multibyte
1720 decimal point character. */
1721 if (dir.prec[0] != dir.prec[1]
1722 || dir.prec[0] == -1 || dir.prec[0] > 0)
1723 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1724 else
1725 res.range.unlikely = res.range.max;
1726 break;
1729 case 'F':
1730 case 'f':
1732 /* Minimum output attributable to precision and, when it's non-zero,
1733 decimal point. */
1734 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1736 /* For finite numbers (i.e., not infinity or NaN) the lower bound
1737 when precision isn't specified is 8 bytes ("1.23456" since
1738 precision is taken to be 6). When precision is zero, the lower
1739 bound is 1 byte (e.g., "1"). Otherwise, when precision is greater
1740 than zero, then the lower bound is 2 plus precision (plus flags).
1741 But in all cases, the lower bound is no greater than 3. */
1742 unsigned HOST_WIDE_INT min = flagmin + radix + minprec;
1743 if (min < res.range.min)
1744 res.range.min = min;
1746 /* Compute the upper bound for -TYPE_MAX. */
1747 res.range.max = format_floating_max (type, 'f', prec[1]);
1749 /* The minimum output with unknown precision is a single byte
1750 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1751 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1752 res.range.likely = 3;
1753 else
1754 res.range.likely = min;
1756 /* The unlikely maximum accounts for the longest multibyte
1757 decimal point character. */
1758 if (dir.prec[0] != dir.prec[1]
1759 || dir.prec[0] == -1 || dir.prec[0] > 0)
1760 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1761 break;
1764 case 'G':
1765 case 'g':
1767 /* The %g output depends on precision and the exponent of
1768 the argument. Since the value of the argument isn't known
1769 the lower bound on the range of bytes (not counting flags
1770 or width) is 1 plus radix (i.e., either "0" or "0." for
1771 "%g" and "%#g", respectively, with a zero argument). */
1772 unsigned HOST_WIDE_INT min = flagmin + radix;
1773 if (min < res.range.min)
1774 res.range.min = min;
1776 char spec = 'g';
1777 HOST_WIDE_INT maxprec = dir.prec[1];
1778 if (radix && maxprec)
1780 /* When the pound flag (radix) is set, trailing zeros aren't
1781 trimmed and so the longest output is the same as for %e,
1782 except with precision minus 1 (as specified in C11). */
1783 spec = 'e';
1784 if (maxprec > 0)
1785 --maxprec;
1786 else if (maxprec < 0)
1787 maxprec = 5;
1789 else
1790 maxprec = prec[1];
1792 res.range.max = format_floating_max (type, spec, maxprec);
1794 /* The likely output is either the maximum computed above
1795 minus 1 (assuming the maximum is positive) when precision
1796 is known (or unspecified), or the same minimum as for %e
1797 (which is computed for a non-negative argument). Unlike
1798 for the other specifiers above the likely output isn't
1799 the minimum because for %g that's 1 which is unlikely. */
1800 if (dir.prec[1] < 0
1801 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1802 res.range.likely = res.range.max - 1;
1803 else
1805 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1806 res.range.likely = (flagmin
1807 + radix
1808 + minprec
1809 + 2 /* e+ */ + 2);
1812 /* The unlikely maximum accounts for the longest multibyte
1813 decimal point character. */
1814 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1815 break;
1818 default:
1819 return fmtresult ();
1822 /* Bump up the byte counters if WIDTH is greater. */
1823 res.adjust_for_width_or_precision (dir.width);
1824 return res;
1827 /* Return a range representing the minimum and maximum number of bytes
1828 that the directive DIR will write on output for the floating argument
1829 ARG. */
1831 static fmtresult
1832 format_floating (const directive &dir, tree arg, vr_values *)
1834 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1835 tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1836 ? long_double_type_node : double_type_node);
1838 /* For an indeterminate precision the lower bound must be assumed
1839 to be zero. */
1840 if (TOUPPER (dir.specifier) == 'A')
1842 /* Get the number of fractional decimal digits needed to represent
1843 the argument without a loss of accuracy. */
1844 unsigned fmtprec
1845 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1847 /* The precision of the IEEE 754 double format is 53.
1848 The precision of all other GCC binary double formats
1849 is 56 or less. */
1850 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1852 /* For %a, leave the minimum precision unspecified to let
1853 MFPR trim trailing zeros (as it and many other systems
1854 including Glibc happen to do) and set the maximum
1855 precision to reflect what it would be with trailing zeros
1856 present (as Solaris and derived systems do). */
1857 if (dir.prec[1] < 0)
1859 /* Both bounds are negative implies that precision has
1860 not been specified. */
1861 prec[0] = maxprec;
1862 prec[1] = -1;
1864 else if (dir.prec[0] < 0)
1866 /* With a negative lower bound and a non-negative upper
1867 bound set the minimum precision to zero and the maximum
1868 to the greater of the maximum precision (i.e., with
1869 trailing zeros present) and the specified upper bound. */
1870 prec[0] = 0;
1871 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1874 else if (dir.prec[0] < 0)
1876 if (dir.prec[1] < 0)
1878 /* A precision in a strictly negative range is ignored and
1879 the default of 6 is used instead. */
1880 prec[0] = prec[1] = 6;
1882 else
1884 /* For a precision in a partly negative range, the lower bound
1885 must be assumed to be zero and the new upper bound is the
1886 greater of 6 (the default precision used when the specified
1887 precision is negative) and the upper bound of the specified
1888 range. */
1889 prec[0] = 0;
1890 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1894 if (!arg
1895 || TREE_CODE (arg) != REAL_CST
1896 || !useless_type_conversion_p (type, TREE_TYPE (arg)))
1897 return format_floating (dir, prec);
1899 /* The minimum and maximum number of bytes produced by the directive. */
1900 fmtresult res;
1902 /* Get the real type format desription for the target. */
1903 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1904 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1906 if (!real_isfinite (rvp))
1908 /* The format for Infinity and NaN is "[-]inf"/"[-]infinity"
1909 and "[-]nan" with the choice being implementation-defined
1910 but not locale dependent. */
1911 bool sign = dir.get_flag ('+') || real_isneg (rvp);
1912 res.range.min = 3 + sign;
1914 res.range.likely = res.range.min;
1915 res.range.max = res.range.min;
1916 /* The unlikely maximum is "[-/+]infinity" or "[-/+][qs]nan".
1917 For NaN, the C/POSIX standards specify two formats:
1918 "[-/+]nan"
1920 "[-/+]nan(n-char-sequence)"
1921 No known printf implementation outputs the latter format but AIX
1922 outputs QNaN and SNaN for quiet and signalling NaN, respectively,
1923 so the unlikely maximum reflects that. */
1924 res.range.unlikely = sign + (real_isinf (rvp) ? 8 : 4);
1926 /* The range for infinity and NaN is known unless either width
1927 or precision is unknown. Width has the same effect regardless
1928 of whether the argument is finite. Precision is either ignored
1929 (e.g., Glibc) or can have an effect on the short vs long format
1930 such as inf/infinity (e.g., Solaris). */
1931 res.knownrange = dir.known_width_and_precision ();
1933 /* Adjust the range for width but ignore precision. */
1934 res.adjust_for_width_or_precision (dir.width);
1936 return res;
1939 char fmtstr [40];
1940 char *pfmt = fmtstr;
1942 /* Append flags. */
1943 for (const char *pf = "-+ #0"; *pf; ++pf)
1944 if (dir.get_flag (*pf))
1945 *pfmt++ = *pf;
1947 *pfmt = '\0';
1950 /* Set up an array to easily iterate over. */
1951 unsigned HOST_WIDE_INT* const minmax[] = {
1952 &res.range.min, &res.range.max
1955 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1957 /* Convert the GCC real value representation with the precision
1958 of the real type to the mpfr_t format rounding down in the
1959 first iteration that computes the minimm and up in the second
1960 that computes the maximum. This order is arbibtrary because
1961 rounding in either direction can result in longer output. */
1962 mpfr_t mpfrval;
1963 mpfr_init2 (mpfrval, rfmt->p);
1964 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1966 /* Use the MPFR rounding specifier to round down in the first
1967 iteration and then up. In most but not all cases this will
1968 result in the same number of bytes. */
1969 char rndspec = "DU"[i];
1971 /* Format it and store the result in the corresponding member
1972 of the result struct. */
1973 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1974 dir.specifier, rndspec);
1975 mpfr_clear (mpfrval);
1979 /* Make sure the minimum is less than the maximum (MPFR rounding
1980 in the call to mpfr_snprintf can result in the reverse. */
1981 if (res.range.max < res.range.min)
1983 unsigned HOST_WIDE_INT tmp = res.range.min;
1984 res.range.min = res.range.max;
1985 res.range.max = tmp;
1988 /* The range is known unless either width or precision is unknown. */
1989 res.knownrange = dir.known_width_and_precision ();
1991 /* For the same floating point constant, unless width or precision
1992 is unknown, use the longer output as the likely maximum since
1993 with round to nearest either is equally likely. Otheriwse, when
1994 precision is unknown, use the greater of the minimum and 3 as
1995 the likely output (for "0.0" since zero precision is unlikely). */
1996 if (res.knownrange)
1997 res.range.likely = res.range.max;
1998 else if (res.range.min < 3
1999 && dir.prec[0] < 0
2000 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
2001 res.range.likely = 3;
2002 else
2003 res.range.likely = res.range.min;
2005 res.range.unlikely = res.range.max;
2007 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
2009 /* Unless the precision is zero output longer than 2 bytes may
2010 include the decimal point which must be a single character
2011 up to MB_LEN_MAX in length. This is overly conservative
2012 since in some conversions some constants result in no decimal
2013 point (e.g., in %g). */
2014 res.range.unlikely += target_mb_len_max () - 1;
2017 res.adjust_for_width_or_precision (dir.width);
2018 return res;
2021 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
2022 strings referenced by the expression STR, or (-1, -1) when not known.
2023 Used by the format_string function below. */
2025 static fmtresult
2026 get_string_length (tree str, unsigned eltsize)
2028 if (!str)
2029 return fmtresult ();
2031 /* Determine the length of the shortest and longest string referenced
2032 by STR. Strings of unknown lengths are bounded by the sizes of
2033 arrays that subexpressions of STR may refer to. Pointers that
2034 aren't known to point any such arrays result in LENDATA.MAXLEN
2035 set to SIZE_MAX. */
2036 c_strlen_data lendata = { };
2037 get_range_strlen (str, &lendata, eltsize);
2039 /* Return the default result when nothing is known about the string. */
2040 if (integer_all_onesp (lendata.maxbound)
2041 && integer_all_onesp (lendata.maxlen))
2042 return fmtresult ();
2044 HOST_WIDE_INT min
2045 = (tree_fits_uhwi_p (lendata.minlen)
2046 ? tree_to_uhwi (lendata.minlen)
2047 : 0);
2049 HOST_WIDE_INT max
2050 = (tree_fits_uhwi_p (lendata.maxbound)
2051 ? tree_to_uhwi (lendata.maxbound)
2052 : HOST_WIDE_INT_M1U);
2054 const bool unbounded = integer_all_onesp (lendata.maxlen);
2056 /* Set the max/likely counters to unbounded when a minimum is known
2057 but the maximum length isn't bounded. This implies that STR is
2058 a conditional expression involving a string of known length and
2059 and an expression of unknown/unbounded length. */
2060 if (min
2061 && (unsigned HOST_WIDE_INT)min < HOST_WIDE_INT_M1U
2062 && unbounded)
2063 max = HOST_WIDE_INT_M1U;
2065 /* get_range_strlen() returns the target value of SIZE_MAX for
2066 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2067 which may be bigger. */
2068 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2069 min = HOST_WIDE_INT_M1U;
2070 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2071 max = HOST_WIDE_INT_M1U;
2073 fmtresult res (min, max);
2074 res.nonstr = lendata.decl;
2076 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2077 by STR are known to be bounded (though not necessarily by their
2078 actual length but perhaps by their maximum possible length). */
2079 if (res.range.max < target_int_max ())
2081 res.knownrange = true;
2082 /* When the the length of the longest string is known and not
2083 excessive use it as the likely length of the string(s). */
2084 res.range.likely = res.range.max;
2086 else
2088 /* When the upper bound is unknown (it can be zero or excessive)
2089 set the likely length to the greater of 1 and the length of
2090 the shortest string and reset the lower bound to zero. */
2091 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2092 res.range.min = 0;
2095 res.range.unlikely = unbounded ? HOST_WIDE_INT_MAX : res.range.max;
2097 return res;
2100 /* Return the minimum and maximum number of characters formatted
2101 by the '%c' format directives and its wide character form for
2102 the argument ARG. ARG can be null (for functions such as
2103 vsprinf). */
2105 static fmtresult
2106 format_character (const directive &dir, tree arg, vr_values *vr_values)
2108 fmtresult res;
2110 res.knownrange = true;
2112 if (dir.specifier == 'C'
2113 || dir.modifier == FMT_LEN_l)
2115 /* A wide character can result in as few as zero bytes. */
2116 res.range.min = 0;
2118 HOST_WIDE_INT min, max;
2119 if (get_int_range (arg, &min, &max, false, 0, vr_values))
2121 if (min == 0 && max == 0)
2123 /* The NUL wide character results in no bytes. */
2124 res.range.max = 0;
2125 res.range.likely = 0;
2126 res.range.unlikely = 0;
2128 else if (min >= 0 && min < 128)
2130 /* Be conservative if the target execution character set
2131 is not a 1-to-1 mapping to the source character set or
2132 if the source set is not ASCII. */
2133 bool one_2_one_ascii
2134 = (target_to_host_charmap[0] == 1 && target_to_host ('a') == 97);
2136 /* A wide character in the ASCII range most likely results
2137 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2138 res.range.max = one_2_one_ascii ? 1 : target_mb_len_max ();;
2139 res.range.likely = 1;
2140 res.range.unlikely = target_mb_len_max ();
2141 res.mayfail = !one_2_one_ascii;
2143 else
2145 /* A wide character outside the ASCII range likely results
2146 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2147 res.range.max = target_mb_len_max ();
2148 res.range.likely = 2;
2149 res.range.unlikely = res.range.max;
2150 /* Converting such a character may fail. */
2151 res.mayfail = true;
2154 else
2156 /* An unknown wide character is treated the same as a wide
2157 character outside the ASCII range. */
2158 res.range.max = target_mb_len_max ();
2159 res.range.likely = 2;
2160 res.range.unlikely = res.range.max;
2161 res.mayfail = true;
2164 else
2166 /* A plain '%c' directive. Its ouput is exactly 1. */
2167 res.range.min = res.range.max = 1;
2168 res.range.likely = res.range.unlikely = 1;
2169 res.knownrange = true;
2172 /* Bump up the byte counters if WIDTH is greater. */
2173 return res.adjust_for_width_or_precision (dir.width);
2176 /* Return the minimum and maximum number of characters formatted
2177 by the '%s' format directive and its wide character form for
2178 the argument ARG. ARG can be null (for functions such as
2179 vsprinf). */
2181 static fmtresult
2182 format_string (const directive &dir, tree arg, vr_values *)
2184 fmtresult res;
2186 /* Compute the range the argument's length can be in. */
2187 int count_by = 1;
2188 if (dir.specifier == 'S' || dir.modifier == FMT_LEN_l)
2190 /* Get a node for a C type that will be the same size
2191 as a wchar_t on the target. */
2192 tree node = get_typenode_from_name (MODIFIED_WCHAR_TYPE);
2194 /* Now that we have a suitable node, get the number of
2195 bytes it occupies. */
2196 count_by = int_size_in_bytes (node);
2197 gcc_checking_assert (count_by == 2 || count_by == 4);
2200 fmtresult slen = get_string_length (arg, count_by);
2201 if (slen.range.min == slen.range.max
2202 && slen.range.min < HOST_WIDE_INT_MAX)
2204 /* The argument is either a string constant or it refers
2205 to one of a number of strings of the same length. */
2207 /* A '%s' directive with a string argument with constant length. */
2208 res.range = slen.range;
2210 if (dir.specifier == 'S'
2211 || dir.modifier == FMT_LEN_l)
2213 /* In the worst case the length of output of a wide string S
2214 is bounded by MB_LEN_MAX * wcslen (S). */
2215 res.range.max *= target_mb_len_max ();
2216 res.range.unlikely = res.range.max;
2217 /* It's likely that the the total length is not more that
2218 2 * wcslen (S).*/
2219 res.range.likely = res.range.min * 2;
2221 if (dir.prec[1] >= 0
2222 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2224 res.range.max = dir.prec[1];
2225 res.range.likely = dir.prec[1];
2226 res.range.unlikely = dir.prec[1];
2229 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2230 res.range.min = 0;
2231 else if (dir.prec[0] >= 0)
2232 res.range.likely = dir.prec[0];
2234 /* Even a non-empty wide character string need not convert into
2235 any bytes. */
2236 res.range.min = 0;
2238 /* A non-empty wide character conversion may fail. */
2239 if (slen.range.max > 0)
2240 res.mayfail = true;
2242 else
2244 res.knownrange = true;
2246 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2247 res.range.min = 0;
2248 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2249 res.range.min = dir.prec[0];
2251 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2253 res.range.max = dir.prec[1];
2254 res.range.likely = dir.prec[1];
2255 res.range.unlikely = dir.prec[1];
2259 else if (arg && integer_zerop (arg))
2261 /* Handle null pointer argument. */
2263 fmtresult res (0);
2264 res.nullp = true;
2265 return res;
2267 else
2269 /* For a '%s' and '%ls' directive with a non-constant string (either
2270 one of a number of strings of known length or an unknown string)
2271 the minimum number of characters is lesser of PRECISION[0] and
2272 the length of the shortest known string or zero, and the maximum
2273 is the lessser of the length of the longest known string or
2274 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2275 the minimum at level 1 and the greater of the minimum and 1
2276 at level 2. This result is adjust upward for width (if it's
2277 specified). */
2279 if (dir.specifier == 'S'
2280 || dir.modifier == FMT_LEN_l)
2282 /* A wide character converts to as few as zero bytes. */
2283 slen.range.min = 0;
2284 if (slen.range.max < target_int_max ())
2285 slen.range.max *= target_mb_len_max ();
2287 if (slen.range.likely < target_int_max ())
2288 slen.range.likely *= 2;
2290 if (slen.range.likely < target_int_max ())
2291 slen.range.unlikely *= target_mb_len_max ();
2293 /* A non-empty wide character conversion may fail. */
2294 if (slen.range.max > 0)
2295 res.mayfail = true;
2298 res.range = slen.range;
2300 if (dir.prec[0] >= 0)
2302 /* Adjust the minimum to zero if the string length is unknown,
2303 or at most the lower bound of the precision otherwise. */
2304 if (slen.range.min >= target_int_max ())
2305 res.range.min = 0;
2306 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2307 res.range.min = dir.prec[0];
2309 /* Make both maxima no greater than the upper bound of precision. */
2310 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2311 || slen.range.max >= target_int_max ())
2313 res.range.max = dir.prec[1];
2314 res.range.unlikely = dir.prec[1];
2317 /* If precision is constant, set the likely counter to the lesser
2318 of it and the maximum string length. Otherwise, if the lower
2319 bound of precision is greater than zero, set the likely counter
2320 to the minimum. Otherwise set it to zero or one based on
2321 the warning level. */
2322 if (dir.prec[0] == dir.prec[1])
2323 res.range.likely
2324 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2325 ? dir.prec[0] : slen.range.max);
2326 else if (dir.prec[0] > 0)
2327 res.range.likely = res.range.min;
2328 else
2329 res.range.likely = warn_level > 1;
2331 else if (dir.prec[1] >= 0)
2333 res.range.min = 0;
2334 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2335 res.range.max = dir.prec[1];
2336 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2337 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.unlikely)
2338 res.range.unlikely = dir.prec[1];
2340 else if (slen.range.min >= target_int_max ())
2342 res.range.min = 0;
2343 res.range.max = HOST_WIDE_INT_MAX;
2344 /* At level 1 strings of unknown length are assumed to be
2345 empty, while at level 1 they are assumed to be one byte
2346 long. */
2347 res.range.likely = warn_level > 1;
2348 res.range.unlikely = HOST_WIDE_INT_MAX;
2350 else
2352 /* A string of unknown length unconstrained by precision is
2353 assumed to be empty at level 1 and just one character long
2354 at higher levels. */
2355 if (res.range.likely >= target_int_max ())
2356 res.range.likely = warn_level > 1;
2360 /* If the argument isn't a nul-terminated string and the number
2361 of bytes on output isn't bounded by precision, set NONSTR. */
2362 if (slen.nonstr && slen.range.min < (unsigned HOST_WIDE_INT)dir.prec[0])
2363 res.nonstr = slen.nonstr;
2365 /* Bump up the byte counters if WIDTH is greater. */
2366 return res.adjust_for_width_or_precision (dir.width);
2369 /* Format plain string (part of the format string itself). */
2371 static fmtresult
2372 format_plain (const directive &dir, tree, vr_values *)
2374 fmtresult res (dir.len);
2375 return res;
2378 /* Return true if the RESULT of a directive in a call describe by INFO
2379 should be diagnosed given the AVAILable space in the destination. */
2381 static bool
2382 should_warn_p (const sprintf_dom_walker::call_info &info,
2383 const result_range &avail, const result_range &result)
2385 if (result.max <= avail.min)
2387 /* The least amount of space remaining in the destination is big
2388 enough for the longest output. */
2389 return false;
2392 if (info.bounded)
2394 if (warn_format_trunc == 1 && result.min <= avail.max
2395 && info.retval_used ())
2397 /* The likely amount of space remaining in the destination is big
2398 enough for the least output and the return value is used. */
2399 return false;
2402 if (warn_format_trunc == 1 && result.likely <= avail.likely
2403 && !info.retval_used ())
2405 /* The likely amount of space remaining in the destination is big
2406 enough for the likely output and the return value is unused. */
2407 return false;
2410 if (warn_format_trunc == 2
2411 && result.likely <= avail.min
2412 && (result.max <= avail.min
2413 || result.max > HOST_WIDE_INT_MAX))
2415 /* The minimum amount of space remaining in the destination is big
2416 enough for the longest output. */
2417 return false;
2420 else
2422 if (warn_level == 1 && result.likely <= avail.likely)
2424 /* The likely amount of space remaining in the destination is big
2425 enough for the likely output. */
2426 return false;
2429 if (warn_level == 2
2430 && result.likely <= avail.min
2431 && (result.max <= avail.min
2432 || result.max > HOST_WIDE_INT_MAX))
2434 /* The minimum amount of space remaining in the destination is big
2435 enough for the longest output. */
2436 return false;
2440 return true;
2443 /* At format string location describe by DIRLOC in a call described
2444 by INFO, issue a warning for a directive DIR whose output may be
2445 in excess of the available space AVAIL_RANGE in the destination
2446 given the formatting result FMTRES. This function does nothing
2447 except decide whether to issue a warning for a possible write
2448 past the end or truncation and, if so, format the warning.
2449 Return true if a warning has been issued. */
2451 static bool
2452 maybe_warn (substring_loc &dirloc, location_t argloc,
2453 const sprintf_dom_walker::call_info &info,
2454 const result_range &avail_range, const result_range &res,
2455 const directive &dir)
2457 if (!should_warn_p (info, avail_range, res))
2458 return false;
2460 /* A warning will definitely be issued below. */
2462 /* The maximum byte count to reference in the warning. Larger counts
2463 imply that the upper bound is unknown (and could be anywhere between
2464 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2465 than "between N and X" where X is some huge number. */
2466 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2468 /* True when there is enough room in the destination for the least
2469 amount of a directive's output but not enough for its likely or
2470 maximum output. */
2471 bool maybe = (res.min <= avail_range.max
2472 && (avail_range.min < res.likely
2473 || (res.max < HOST_WIDE_INT_MAX
2474 && avail_range.min < res.max)));
2476 /* Buffer for the directive in the host character set (used when
2477 the source character set is different). */
2478 char hostdir[32];
2480 if (avail_range.min == avail_range.max)
2482 /* The size of the destination region is exact. */
2483 unsigned HOST_WIDE_INT navail = avail_range.max;
2485 if (target_to_host (*dir.beg) != '%')
2487 /* For plain character directives (i.e., the format string itself)
2488 but not others, point the caret at the first character that's
2489 past the end of the destination. */
2490 if (navail < dir.len)
2491 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2494 if (*dir.beg == '\0')
2496 /* This is the terminating nul. */
2497 gcc_assert (res.min == 1 && res.min == res.max);
2499 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2500 info.bounded
2501 ? (maybe
2502 ? G_("%qE output may be truncated before the "
2503 "last format character")
2504 : G_("%qE output truncated before the last "
2505 "format character"))
2506 : (maybe
2507 ? G_("%qE may write a terminating nul past the "
2508 "end of the destination")
2509 : G_("%qE writing a terminating nul past the "
2510 "end of the destination")),
2511 info.func);
2514 if (res.min == res.max)
2516 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2517 if (!info.bounded)
2518 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2519 "%<%.*s%> directive writing %wu byte into a "
2520 "region of size %wu",
2521 "%<%.*s%> directive writing %wu bytes into a "
2522 "region of size %wu",
2523 (int) dir.len, d, res.min, navail);
2524 else if (maybe)
2525 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2526 "%<%.*s%> directive output may be truncated "
2527 "writing %wu byte into a region of size %wu",
2528 "%<%.*s%> directive output may be truncated "
2529 "writing %wu bytes into a region of size %wu",
2530 (int) dir.len, d, res.min, navail);
2531 else
2532 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2533 "%<%.*s%> directive output truncated writing "
2534 "%wu byte into a region of size %wu",
2535 "%<%.*s%> directive output truncated writing "
2536 "%wu bytes into a region of size %wu",
2537 (int) dir.len, d, res.min, navail);
2539 if (res.min == 0 && res.max < maxbytes)
2540 return fmtwarn (dirloc, argloc, NULL,
2541 info.warnopt (),
2542 info.bounded
2543 ? (maybe
2544 ? G_("%<%.*s%> directive output may be truncated "
2545 "writing up to %wu bytes into a region of "
2546 "size %wu")
2547 : G_("%<%.*s%> directive output truncated writing "
2548 "up to %wu bytes into a region of size %wu"))
2549 : G_("%<%.*s%> directive writing up to %wu bytes "
2550 "into a region of size %wu"), (int) dir.len,
2551 target_to_host (hostdir, sizeof hostdir, dir.beg),
2552 res.max, navail);
2554 if (res.min == 0 && maxbytes <= res.max)
2555 /* This is a special case to avoid issuing the potentially
2556 confusing warning:
2557 writing 0 or more bytes into a region of size 0. */
2558 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2559 info.bounded
2560 ? (maybe
2561 ? G_("%<%.*s%> directive output may be truncated "
2562 "writing likely %wu or more bytes into a "
2563 "region of size %wu")
2564 : G_("%<%.*s%> directive output truncated writing "
2565 "likely %wu or more bytes into a region of "
2566 "size %wu"))
2567 : G_("%<%.*s%> directive writing likely %wu or more "
2568 "bytes into a region of size %wu"), (int) dir.len,
2569 target_to_host (hostdir, sizeof hostdir, dir.beg),
2570 res.likely, navail);
2572 if (res.max < maxbytes)
2573 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2574 info.bounded
2575 ? (maybe
2576 ? G_("%<%.*s%> directive output may be truncated "
2577 "writing between %wu and %wu bytes into a "
2578 "region of size %wu")
2579 : G_("%<%.*s%> directive output truncated "
2580 "writing between %wu and %wu bytes into a "
2581 "region of size %wu"))
2582 : G_("%<%.*s%> directive writing between %wu and "
2583 "%wu bytes into a region of size %wu"),
2584 (int) dir.len,
2585 target_to_host (hostdir, sizeof hostdir, dir.beg),
2586 res.min, res.max, navail);
2588 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2589 info.bounded
2590 ? (maybe
2591 ? G_("%<%.*s%> directive output may be truncated "
2592 "writing %wu or more bytes into a region of "
2593 "size %wu")
2594 : G_("%<%.*s%> directive output truncated writing "
2595 "%wu or more bytes into a region of size %wu"))
2596 : G_("%<%.*s%> directive writing %wu or more bytes "
2597 "into a region of size %wu"), (int) dir.len,
2598 target_to_host (hostdir, sizeof hostdir, dir.beg),
2599 res.min, navail);
2602 /* The size of the destination region is a range. */
2604 if (target_to_host (*dir.beg) != '%')
2606 unsigned HOST_WIDE_INT navail = avail_range.max;
2608 /* For plain character directives (i.e., the format string itself)
2609 but not others, point the caret at the first character that's
2610 past the end of the destination. */
2611 if (navail < dir.len)
2612 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2615 if (*dir.beg == '\0')
2617 gcc_assert (res.min == 1 && res.min == res.max);
2619 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2620 info.bounded
2621 ? (maybe
2622 ? G_("%qE output may be truncated before the last "
2623 "format character")
2624 : G_("%qE output truncated before the last format "
2625 "character"))
2626 : (maybe
2627 ? G_("%qE may write a terminating nul past the end "
2628 "of the destination")
2629 : G_("%qE writing a terminating nul past the end "
2630 "of the destination")), info.func);
2633 if (res.min == res.max)
2635 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2636 if (!info.bounded)
2637 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2638 "%<%.*s%> directive writing %wu byte into a region "
2639 "of size between %wu and %wu",
2640 "%<%.*s%> directive writing %wu bytes into a region "
2641 "of size between %wu and %wu", (int) dir.len, d,
2642 res.min, avail_range.min, avail_range.max);
2643 else if (maybe)
2644 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2645 "%<%.*s%> directive output may be truncated writing "
2646 "%wu byte into a region of size between %wu and %wu",
2647 "%<%.*s%> directive output may be truncated writing "
2648 "%wu bytes into a region of size between %wu and "
2649 "%wu", (int) dir.len, d, res.min, avail_range.min,
2650 avail_range.max);
2651 else
2652 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2653 "%<%.*s%> directive output truncated writing %wu "
2654 "byte into a region of size between %wu and %wu",
2655 "%<%.*s%> directive output truncated writing %wu "
2656 "bytes into a region of size between %wu and %wu",
2657 (int) dir.len, d, res.min, avail_range.min,
2658 avail_range.max);
2661 if (res.min == 0 && res.max < maxbytes)
2662 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2663 info.bounded
2664 ? (maybe
2665 ? G_("%<%.*s%> directive output may be truncated "
2666 "writing up to %wu bytes into a region of size "
2667 "between %wu and %wu")
2668 : G_("%<%.*s%> directive output truncated writing "
2669 "up to %wu bytes into a region of size between "
2670 "%wu and %wu"))
2671 : G_("%<%.*s%> directive writing up to %wu bytes "
2672 "into a region of size between %wu and %wu"),
2673 (int) dir.len,
2674 target_to_host (hostdir, sizeof hostdir, dir.beg),
2675 res.max, avail_range.min, avail_range.max);
2677 if (res.min == 0 && maxbytes <= res.max)
2678 /* This is a special case to avoid issuing the potentially confusing
2679 warning:
2680 writing 0 or more bytes into a region of size between 0 and N. */
2681 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2682 info.bounded
2683 ? (maybe
2684 ? G_("%<%.*s%> directive output may be truncated "
2685 "writing likely %wu or more bytes into a region "
2686 "of size between %wu and %wu")
2687 : G_("%<%.*s%> directive output truncated writing "
2688 "likely %wu or more bytes into a region of size "
2689 "between %wu and %wu"))
2690 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2691 "into a region of size between %wu and %wu"),
2692 (int) dir.len,
2693 target_to_host (hostdir, sizeof hostdir, dir.beg),
2694 res.likely, avail_range.min, avail_range.max);
2696 if (res.max < maxbytes)
2697 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2698 info.bounded
2699 ? (maybe
2700 ? G_("%<%.*s%> directive output may be truncated "
2701 "writing between %wu and %wu bytes into a region "
2702 "of size between %wu and %wu")
2703 : G_("%<%.*s%> directive output truncated writing "
2704 "between %wu and %wu bytes into a region of size "
2705 "between %wu and %wu"))
2706 : G_("%<%.*s%> directive writing between %wu and "
2707 "%wu bytes into a region of size between %wu and "
2708 "%wu"), (int) dir.len,
2709 target_to_host (hostdir, sizeof hostdir, dir.beg),
2710 res.min, res.max, avail_range.min, avail_range.max);
2712 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2713 info.bounded
2714 ? (maybe
2715 ? G_("%<%.*s%> directive output may be truncated writing "
2716 "%wu or more bytes into a region of size between "
2717 "%wu and %wu")
2718 : G_("%<%.*s%> directive output truncated writing "
2719 "%wu or more bytes into a region of size between "
2720 "%wu and %wu"))
2721 : G_("%<%.*s%> directive writing %wu or more bytes "
2722 "into a region of size between %wu and %wu"),
2723 (int) dir.len,
2724 target_to_host (hostdir, sizeof hostdir, dir.beg),
2725 res.min, avail_range.min, avail_range.max);
2728 /* Compute the length of the output resulting from the directive DIR
2729 in a call described by INFO and update the overall result of the call
2730 in *RES. Return true if the directive has been handled. */
2732 static bool
2733 format_directive (const sprintf_dom_walker::call_info &info,
2734 format_result *res, const directive &dir,
2735 class vr_values *vr_values)
2737 /* Offset of the beginning of the directive from the beginning
2738 of the format string. */
2739 size_t offset = dir.beg - info.fmtstr;
2740 size_t start = offset;
2741 size_t length = offset + dir.len - !!dir.len;
2743 /* Create a location for the whole directive from the % to the format
2744 specifier. */
2745 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2746 offset, start, length);
2748 /* Also get the location of the argument if possible.
2749 This doesn't work for integer literals or function calls. */
2750 location_t argloc = UNKNOWN_LOCATION;
2751 if (dir.arg)
2752 argloc = EXPR_LOCATION (dir.arg);
2754 /* Bail when there is no function to compute the output length,
2755 or when minimum length checking has been disabled. */
2756 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2757 return false;
2759 /* Compute the range of lengths of the formatted output. */
2760 fmtresult fmtres = dir.fmtfunc (dir, dir.arg, vr_values);
2762 /* Record whether the output of all directives is known to be
2763 bounded by some maximum, implying that their arguments are
2764 either known exactly or determined to be in a known range
2765 or, for strings, limited by the upper bounds of the arrays
2766 they refer to. */
2767 res->knownrange &= fmtres.knownrange;
2769 if (!fmtres.knownrange)
2771 /* Only when the range is known, check it against the host value
2772 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2773 INT_MAX precision, which is the longest possible output of any
2774 single directive). That's the largest valid byte count (though
2775 not valid call to a printf-like function because it can never
2776 return such a count). Otherwise, the range doesn't correspond
2777 to known values of the argument. */
2778 if (fmtres.range.max > target_dir_max ())
2780 /* Normalize the MAX counter to avoid having to deal with it
2781 later. The counter can be less than HOST_WIDE_INT_M1U
2782 when compiling for an ILP32 target on an LP64 host. */
2783 fmtres.range.max = HOST_WIDE_INT_M1U;
2784 /* Disable exact and maximum length checking after a failure
2785 to determine the maximum number of characters (for example
2786 for wide characters or wide character strings) but continue
2787 tracking the minimum number of characters. */
2788 res->range.max = HOST_WIDE_INT_M1U;
2791 if (fmtres.range.min > target_dir_max ())
2793 /* Disable exact length checking after a failure to determine
2794 even the minimum number of characters (it shouldn't happen
2795 except in an error) but keep tracking the minimum and maximum
2796 number of characters. */
2797 return true;
2801 /* Buffer for the directive in the host character set (used when
2802 the source character set is different). */
2803 char hostdir[32];
2805 int dirlen = dir.len;
2807 if (fmtres.nullp)
2809 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2810 "%G%<%.*s%> directive argument is null",
2811 info.callstmt, dirlen,
2812 target_to_host (hostdir, sizeof hostdir, dir.beg));
2814 /* Don't bother processing the rest of the format string. */
2815 res->warned = true;
2816 res->range.min = HOST_WIDE_INT_M1U;
2817 res->range.max = HOST_WIDE_INT_M1U;
2818 return false;
2821 /* Compute the number of available bytes in the destination. There
2822 must always be at least one byte of space for the terminating
2823 NUL that's appended after the format string has been processed. */
2824 result_range avail_range = bytes_remaining (info.objsize, *res);
2826 bool warned = res->warned;
2828 if (!warned)
2829 warned = maybe_warn (dirloc, argloc, info, avail_range,
2830 fmtres.range, dir);
2832 /* Bump up the total maximum if it isn't too big. */
2833 if (res->range.max < HOST_WIDE_INT_MAX
2834 && fmtres.range.max < HOST_WIDE_INT_MAX)
2835 res->range.max += fmtres.range.max;
2837 /* Raise the total unlikely maximum by the larger of the maximum
2838 and the unlikely maximum. */
2839 unsigned HOST_WIDE_INT save = res->range.unlikely;
2840 if (fmtres.range.max < fmtres.range.unlikely)
2841 res->range.unlikely += fmtres.range.unlikely;
2842 else
2843 res->range.unlikely += fmtres.range.max;
2845 if (res->range.unlikely < save)
2846 res->range.unlikely = HOST_WIDE_INT_M1U;
2848 res->range.min += fmtres.range.min;
2849 res->range.likely += fmtres.range.likely;
2851 /* Has the minimum directive output length exceeded the maximum
2852 of 4095 bytes required to be supported? */
2853 bool minunder4k = fmtres.range.min < 4096;
2854 bool maxunder4k = fmtres.range.max < 4096;
2855 /* Clear POSUNDER4K in the overall result if the maximum has exceeded
2856 the 4k (this is necessary to avoid the return value optimization
2857 that may not be safe in the maximum case). */
2858 if (!maxunder4k)
2859 res->posunder4k = false;
2860 /* Also clear POSUNDER4K if the directive may fail. */
2861 if (fmtres.mayfail)
2862 res->posunder4k = false;
2864 if (!warned
2865 /* Only warn at level 2. */
2866 && warn_level > 1
2867 /* Only warn for string functions. */
2868 && info.is_string_func ()
2869 && (!minunder4k
2870 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2872 /* The directive output may be longer than the maximum required
2873 to be handled by an implementation according to 7.21.6.1, p15
2874 of C11. Warn on this only at level 2 but remember this and
2875 prevent folding the return value when done. This allows for
2876 the possibility of the actual libc call failing due to ENOMEM
2877 (like Glibc does with very large precision or width).
2878 Issue the "may exceed" warning only for string functions and
2879 not for fprintf or printf. */
2881 if (fmtres.range.min == fmtres.range.max)
2882 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2883 "%<%.*s%> directive output of %wu bytes exceeds "
2884 "minimum required size of 4095", dirlen,
2885 target_to_host (hostdir, sizeof hostdir, dir.beg),
2886 fmtres.range.min);
2887 else if (!minunder4k)
2888 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2889 "%<%.*s%> directive output between %wu and %wu "
2890 "bytes exceeds minimum required size of 4095",
2891 dirlen,
2892 target_to_host (hostdir, sizeof hostdir, dir.beg),
2893 fmtres.range.min, fmtres.range.max);
2894 else if (!info.retval_used () && info.is_string_func ())
2895 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2896 "%<%.*s%> directive output between %wu and %wu "
2897 "bytes may exceed minimum required size of "
2898 "4095",
2899 dirlen,
2900 target_to_host (hostdir, sizeof hostdir, dir.beg),
2901 fmtres.range.min, fmtres.range.max);
2904 /* Has the likely and maximum directive output exceeded INT_MAX? */
2905 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2906 /* Don't consider the maximum to be in excess when it's the result
2907 of a string of unknown length (i.e., whose maximum has been set
2908 to be greater than or equal to HOST_WIDE_INT_MAX. */
2909 bool maxximax = (*dir.beg
2910 && res->range.max > target_int_max ()
2911 && res->range.max < HOST_WIDE_INT_MAX);
2913 if (!warned
2914 /* Warn for the likely output size at level 1. */
2915 && (likelyximax
2916 /* But only warn for the maximum at level 2. */
2917 || (warn_level > 1
2918 && maxximax
2919 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2921 if (fmtres.range.min > target_int_max ())
2923 /* The directive output exceeds INT_MAX bytes. */
2924 if (fmtres.range.min == fmtres.range.max)
2925 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2926 "%<%.*s%> directive output of %wu bytes exceeds "
2927 "%<INT_MAX%>", dirlen,
2928 target_to_host (hostdir, sizeof hostdir, dir.beg),
2929 fmtres.range.min);
2930 else
2931 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2932 "%<%.*s%> directive output between %wu and "
2933 "%wu bytes exceeds %<INT_MAX%>", dirlen,
2934 target_to_host (hostdir, sizeof hostdir, dir.beg),
2935 fmtres.range.min, fmtres.range.max);
2937 else if (res->range.min > target_int_max ())
2939 /* The directive output is under INT_MAX but causes the result
2940 to exceed INT_MAX bytes. */
2941 if (fmtres.range.min == fmtres.range.max)
2942 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2943 "%<%.*s%> directive output of %wu bytes causes "
2944 "result to exceed %<INT_MAX%>", dirlen,
2945 target_to_host (hostdir, sizeof hostdir, dir.beg),
2946 fmtres.range.min);
2947 else
2948 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2949 "%<%.*s%> directive output between %wu and "
2950 "%wu bytes causes result to exceed %<INT_MAX%>",
2951 dirlen,
2952 target_to_host (hostdir, sizeof hostdir, dir.beg),
2953 fmtres.range.min, fmtres.range.max);
2955 else if ((!info.retval_used () || !info.bounded)
2956 && (info.is_string_func ()))
2957 /* Warn for calls to string functions that either aren't bounded
2958 (sprintf) or whose return value isn't used. */
2959 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2960 "%<%.*s%> directive output between %wu and "
2961 "%wu bytes may cause result to exceed "
2962 "%<INT_MAX%>", dirlen,
2963 target_to_host (hostdir, sizeof hostdir, dir.beg),
2964 fmtres.range.min, fmtres.range.max);
2967 if (!warned && fmtres.nonstr)
2969 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2970 "%<%.*s%> directive argument is not a nul-terminated "
2971 "string",
2972 dirlen,
2973 target_to_host (hostdir, sizeof hostdir, dir.beg));
2974 if (warned && DECL_P (fmtres.nonstr))
2975 inform (DECL_SOURCE_LOCATION (fmtres.nonstr),
2976 "referenced argument declared here");
2977 return false;
2980 if (warned && fmtres.range.min < fmtres.range.likely
2981 && fmtres.range.likely < fmtres.range.max)
2982 inform_n (info.fmtloc, fmtres.range.likely,
2983 "assuming directive output of %wu byte",
2984 "assuming directive output of %wu bytes",
2985 fmtres.range.likely);
2987 if (warned && fmtres.argmin)
2989 if (fmtres.argmin == fmtres.argmax)
2990 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2991 else if (fmtres.knownrange)
2992 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2993 fmtres.argmin, fmtres.argmax);
2994 else
2995 inform (info.fmtloc,
2996 "using the range [%E, %E] for directive argument",
2997 fmtres.argmin, fmtres.argmax);
3000 res->warned |= warned;
3002 if (!dir.beg[0] && res->warned)
3004 location_t callloc = gimple_location (info.callstmt);
3006 unsigned HOST_WIDE_INT min = res->range.min;
3007 unsigned HOST_WIDE_INT max = res->range.max;
3009 if (info.objsize < HOST_WIDE_INT_MAX)
3011 /* If a warning has been issued for buffer overflow or truncation
3012 help the user figure out how big a buffer they need. */
3014 if (min == max)
3015 inform (callloc,
3016 (min == 1
3017 ? G_("%qE output %wu byte into a destination of size %wu")
3018 : G_("%qE output %wu bytes into a destination of size "
3019 "%wu")),
3020 info.func, min, info.objsize);
3021 else if (max < HOST_WIDE_INT_MAX)
3022 inform (callloc,
3023 "%qE output between %wu and %wu bytes into "
3024 "a destination of size %wu",
3025 info.func, min, max, info.objsize);
3026 else if (min < res->range.likely && res->range.likely < max)
3027 inform (callloc,
3028 "%qE output %wu or more bytes (assuming %wu) into "
3029 "a destination of size %wu",
3030 info.func, min, res->range.likely, info.objsize);
3031 else
3032 inform (callloc,
3033 "%qE output %wu or more bytes into a destination of size "
3034 "%wu",
3035 info.func, min, info.objsize);
3037 else if (!info.is_string_func ())
3039 /* If the warning is for a file function function like fprintf
3040 of printf with no destination size just print the computed
3041 result. */
3042 if (min == max)
3043 inform (callloc,
3044 (min == 1
3045 ? G_("%qE output %wu byte")
3046 : G_("%qE output %wu bytes")),
3047 info.func, min);
3048 else if (max < HOST_WIDE_INT_MAX)
3049 inform (callloc,
3050 "%qE output between %wu and %wu bytes",
3051 info.func, min, max);
3052 else if (min < res->range.likely && res->range.likely < max)
3053 inform (callloc,
3054 "%qE output %wu or more bytes (assuming %wu)",
3055 info.func, min, res->range.likely);
3056 else
3057 inform (callloc,
3058 "%qE output %wu or more bytes",
3059 info.func, min);
3063 if (dump_file && *dir.beg)
3065 fprintf (dump_file,
3066 " Result: "
3067 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3068 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
3069 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3070 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
3071 fmtres.range.min, fmtres.range.likely,
3072 fmtres.range.max, fmtres.range.unlikely,
3073 res->range.min, res->range.likely,
3074 res->range.max, res->range.unlikely);
3077 return true;
3080 /* Parse a format directive in function call described by INFO starting
3081 at STR and populate DIR structure. Bump up *ARGNO by the number of
3082 arguments extracted for the directive. Return the length of
3083 the directive. */
3085 static size_t
3086 parse_directive (sprintf_dom_walker::call_info &info,
3087 directive &dir, format_result *res,
3088 const char *str, unsigned *argno,
3089 vr_values *vr_values)
3091 const char *pcnt = strchr (str, target_percent);
3092 dir.beg = str;
3094 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
3096 /* This directive is either a plain string or the terminating nul
3097 (which isn't really a directive but it simplifies things to
3098 handle it as if it were). */
3099 dir.len = len;
3100 dir.fmtfunc = format_plain;
3102 if (dump_file)
3104 fprintf (dump_file, " Directive %u at offset "
3105 HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
3106 "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
3107 dir.dirno,
3108 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3109 (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
3112 return len - !*str;
3115 const char *pf = pcnt + 1;
3117 /* POSIX numbered argument index or zero when none. */
3118 HOST_WIDE_INT dollar = 0;
3120 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3121 when given by a va_list argument, and a non-negative value
3122 when specified in the format string itself. */
3123 HOST_WIDE_INT width = -1;
3124 HOST_WIDE_INT precision = -1;
3126 /* Pointers to the beginning of the width and precision decimal
3127 string (if any) within the directive. */
3128 const char *pwidth = 0;
3129 const char *pprec = 0;
3131 /* When the value of the decimal string that specifies width or
3132 precision is out of range, points to the digit that causes
3133 the value to exceed the limit. */
3134 const char *werange = NULL;
3135 const char *perange = NULL;
3137 /* Width specified via the asterisk. Need not be INTEGER_CST.
3138 For vararg functions set to void_node. */
3139 tree star_width = NULL_TREE;
3141 /* Width specified via the asterisk. Need not be INTEGER_CST.
3142 For vararg functions set to void_node. */
3143 tree star_precision = NULL_TREE;
3145 if (ISDIGIT (target_to_host (*pf)))
3147 /* This could be either a POSIX positional argument, the '0'
3148 flag, or a width, depending on what follows. Store it as
3149 width and sort it out later after the next character has
3150 been seen. */
3151 pwidth = pf;
3152 width = target_strtowi (&pf, &werange);
3154 else if (target_to_host (*pf) == '*')
3156 /* Similarly to the block above, this could be either a POSIX
3157 positional argument or a width, depending on what follows. */
3158 if (*argno < gimple_call_num_args (info.callstmt))
3159 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3160 else
3161 star_width = void_node;
3162 ++pf;
3165 if (target_to_host (*pf) == '$')
3167 /* Handle the POSIX dollar sign which references the 1-based
3168 positional argument number. */
3169 if (width != -1)
3170 dollar = width + info.argidx;
3171 else if (star_width
3172 && TREE_CODE (star_width) == INTEGER_CST
3173 && (TYPE_PRECISION (TREE_TYPE (star_width))
3174 <= TYPE_PRECISION (integer_type_node)))
3175 dollar = width + tree_to_shwi (star_width);
3177 /* Bail when the numbered argument is out of range (it will
3178 have already been diagnosed by -Wformat). */
3179 if (dollar == 0
3180 || dollar == (int)info.argidx
3181 || dollar > gimple_call_num_args (info.callstmt))
3182 return false;
3184 --dollar;
3186 star_width = NULL_TREE;
3187 width = -1;
3188 ++pf;
3191 if (dollar || !star_width)
3193 if (width != -1)
3195 if (width == 0)
3197 /* The '0' that has been interpreted as a width above is
3198 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3199 and continue processing other flags. */
3200 width = -1;
3201 dir.set_flag ('0');
3203 else if (!dollar)
3205 /* (Non-zero) width has been seen. The next character
3206 is either a period or a digit. */
3207 goto start_precision;
3210 /* When either '$' has been seen, or width has not been seen,
3211 the next field is the optional flags followed by an optional
3212 width. */
3213 for ( ; ; ) {
3214 switch (target_to_host (*pf))
3216 case ' ':
3217 case '0':
3218 case '+':
3219 case '-':
3220 case '#':
3221 dir.set_flag (target_to_host (*pf++));
3222 break;
3224 default:
3225 goto start_width;
3229 start_width:
3230 if (ISDIGIT (target_to_host (*pf)))
3232 werange = 0;
3233 pwidth = pf;
3234 width = target_strtowi (&pf, &werange);
3236 else if (target_to_host (*pf) == '*')
3238 if (*argno < gimple_call_num_args (info.callstmt))
3239 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3240 else
3242 /* This is (likely) a va_list. It could also be an invalid
3243 call with insufficient arguments. */
3244 star_width = void_node;
3246 ++pf;
3248 else if (target_to_host (*pf) == '\'')
3250 /* The POSIX apostrophe indicating a numeric grouping
3251 in the current locale. Even though it's possible to
3252 estimate the upper bound on the size of the output
3253 based on the number of digits it probably isn't worth
3254 continuing. */
3255 return 0;
3259 start_precision:
3260 if (target_to_host (*pf) == '.')
3262 ++pf;
3264 if (ISDIGIT (target_to_host (*pf)))
3266 pprec = pf;
3267 precision = target_strtowi (&pf, &perange);
3269 else if (target_to_host (*pf) == '*')
3271 if (*argno < gimple_call_num_args (info.callstmt))
3272 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3273 else
3275 /* This is (likely) a va_list. It could also be an invalid
3276 call with insufficient arguments. */
3277 star_precision = void_node;
3279 ++pf;
3281 else
3283 /* The decimal precision or the asterisk are optional.
3284 When neither is dirified it's taken to be zero. */
3285 precision = 0;
3289 switch (target_to_host (*pf))
3291 case 'h':
3292 if (target_to_host (pf[1]) == 'h')
3294 ++pf;
3295 dir.modifier = FMT_LEN_hh;
3297 else
3298 dir.modifier = FMT_LEN_h;
3299 ++pf;
3300 break;
3302 case 'j':
3303 dir.modifier = FMT_LEN_j;
3304 ++pf;
3305 break;
3307 case 'L':
3308 dir.modifier = FMT_LEN_L;
3309 ++pf;
3310 break;
3312 case 'l':
3313 if (target_to_host (pf[1]) == 'l')
3315 ++pf;
3316 dir.modifier = FMT_LEN_ll;
3318 else
3319 dir.modifier = FMT_LEN_l;
3320 ++pf;
3321 break;
3323 case 't':
3324 dir.modifier = FMT_LEN_t;
3325 ++pf;
3326 break;
3328 case 'z':
3329 dir.modifier = FMT_LEN_z;
3330 ++pf;
3331 break;
3334 switch (target_to_host (*pf))
3336 /* Handle a sole '%' character the same as "%%" but since it's
3337 undefined prevent the result from being folded. */
3338 case '\0':
3339 --pf;
3340 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3341 /* FALLTHRU */
3342 case '%':
3343 dir.fmtfunc = format_percent;
3344 break;
3346 case 'a':
3347 case 'A':
3348 case 'e':
3349 case 'E':
3350 case 'f':
3351 case 'F':
3352 case 'g':
3353 case 'G':
3354 res->floating = true;
3355 dir.fmtfunc = format_floating;
3356 break;
3358 case 'd':
3359 case 'i':
3360 case 'o':
3361 case 'u':
3362 case 'x':
3363 case 'X':
3364 dir.fmtfunc = format_integer;
3365 break;
3367 case 'p':
3368 /* The %p output is implementation-defined. It's possible
3369 to determine this format but due to extensions (edirially
3370 those of the Linux kernel -- see bug 78512) the first %p
3371 in the format string disables any further processing. */
3372 return false;
3374 case 'n':
3375 /* %n has side-effects even when nothing is actually printed to
3376 any buffer. */
3377 info.nowrite = false;
3378 dir.fmtfunc = format_none;
3379 break;
3381 case 'C':
3382 case 'c':
3383 /* POSIX wide character and C/POSIX narrow character. */
3384 dir.fmtfunc = format_character;
3385 break;
3387 case 'S':
3388 case 's':
3389 /* POSIX wide string and C/POSIX narrow character string. */
3390 dir.fmtfunc = format_string;
3391 break;
3393 default:
3394 /* Unknown conversion specification. */
3395 return 0;
3398 dir.specifier = target_to_host (*pf++);
3400 /* Store the length of the format directive. */
3401 dir.len = pf - pcnt;
3403 /* Buffer for the directive in the host character set (used when
3404 the source character set is different). */
3405 char hostdir[32];
3407 if (star_width)
3409 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3410 dir.set_width (star_width, vr_values);
3411 else
3413 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3414 (width is the absolute value of that specified). */
3415 dir.width[0] = 0;
3416 dir.width[1] = target_int_max () + 1;
3419 else
3421 if (width == HOST_WIDE_INT_MAX && werange)
3423 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3424 size_t caret = begin + (werange - pcnt);
3425 size_t end = pf - info.fmtstr - 1;
3427 /* Create a location for the width part of the directive,
3428 pointing the caret at the first out-of-range digit. */
3429 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3430 caret, begin, end);
3432 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3433 "%<%.*s%> directive width out of range", (int) dir.len,
3434 target_to_host (hostdir, sizeof hostdir, dir.beg));
3437 dir.set_width (width);
3440 if (star_precision)
3442 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3443 dir.set_precision (star_precision, vr_values);
3444 else
3446 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3447 (unlike width, negative precision is ignored). */
3448 dir.prec[0] = -1;
3449 dir.prec[1] = target_int_max ();
3452 else
3454 if (precision == HOST_WIDE_INT_MAX && perange)
3456 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3457 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3458 size_t end = pf - info.fmtstr - 2;
3460 /* Create a location for the precision part of the directive,
3461 including the leading period, pointing the caret at the first
3462 out-of-range digit . */
3463 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3464 caret, begin, end);
3466 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3467 "%<%.*s%> directive precision out of range", (int) dir.len,
3468 target_to_host (hostdir, sizeof hostdir, dir.beg));
3471 dir.set_precision (precision);
3474 /* Extract the argument if the directive takes one and if it's
3475 available (e.g., the function doesn't take a va_list). Treat
3476 missing arguments the same as va_list, even though they will
3477 have likely already been diagnosed by -Wformat. */
3478 if (dir.specifier != '%'
3479 && *argno < gimple_call_num_args (info.callstmt))
3480 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3482 if (dump_file)
3484 fprintf (dump_file,
3485 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3486 ": \"%.*s\"",
3487 dir.dirno,
3488 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3489 (int)dir.len, dir.beg);
3490 if (star_width)
3492 if (dir.width[0] == dir.width[1])
3493 fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
3494 dir.width[0]);
3495 else
3496 fprintf (dump_file,
3497 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3498 ", " HOST_WIDE_INT_PRINT_DEC "]",
3499 dir.width[0], dir.width[1]);
3502 if (star_precision)
3504 if (dir.prec[0] == dir.prec[1])
3505 fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
3506 dir.prec[0]);
3507 else
3508 fprintf (dump_file,
3509 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3510 HOST_WIDE_INT_PRINT_DEC "]",
3511 dir.prec[0], dir.prec[1]);
3513 fputc ('\n', dump_file);
3516 return dir.len;
3519 /* Compute the length of the output resulting from the call to a formatted
3520 output function described by INFO and store the result of the call in
3521 *RES. Issue warnings for detected past the end writes. Return true
3522 if the complete format string has been processed and *RES can be relied
3523 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3524 that caused the processing to be terminated early). */
3526 bool
3527 sprintf_dom_walker::compute_format_length (call_info &info,
3528 format_result *res)
3530 if (dump_file)
3532 location_t callloc = gimple_location (info.callstmt);
3533 fprintf (dump_file, "%s:%i: ",
3534 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3535 print_generic_expr (dump_file, info.func, dump_flags);
3537 fprintf (dump_file,
3538 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3539 ", fmtstr = \"%s\"\n",
3540 info.objsize, info.fmtstr);
3543 /* Reset the minimum and maximum byte counters. */
3544 res->range.min = res->range.max = 0;
3546 /* No directive has been seen yet so the length of output is bounded
3547 by the known range [0, 0] (with no conversion resulting in a failure
3548 or producing more than 4K bytes) until determined otherwise. */
3549 res->knownrange = true;
3550 res->floating = false;
3551 res->warned = false;
3553 /* 1-based directive counter. */
3554 unsigned dirno = 1;
3556 /* The variadic argument counter. */
3557 unsigned argno = info.argidx;
3559 for (const char *pf = info.fmtstr; ; ++dirno)
3561 directive dir = directive ();
3562 dir.dirno = dirno;
3564 size_t n = parse_directive (info, dir, res, pf, &argno,
3565 evrp_range_analyzer.get_vr_values ());
3567 /* Return failure if the format function fails. */
3568 if (!format_directive (info, res, dir,
3569 evrp_range_analyzer.get_vr_values ()))
3570 return false;
3572 /* Return success the directive is zero bytes long and it's
3573 the last think in the format string (i.e., it's the terminating
3574 nul, which isn't really a directive but handling it as one makes
3575 things simpler). */
3576 if (!n)
3577 return *pf == '\0';
3579 pf += n;
3582 /* The complete format string was processed (with or without warnings). */
3583 return true;
3586 /* Return the size of the object referenced by the expression DEST if
3587 available, or the maximum possible size otherwise. */
3589 static unsigned HOST_WIDE_INT
3590 get_destination_size (tree dest)
3592 /* When there is no destination return the maximum. */
3593 if (!dest)
3594 return HOST_WIDE_INT_MAX;
3596 /* Initialize object size info before trying to compute it. */
3597 init_object_sizes ();
3599 /* Use __builtin_object_size to determine the size of the destination
3600 object. When optimizing, determine the smallest object (such as
3601 a member array as opposed to the whole enclosing object), otherwise
3602 use type-zero object size to determine the size of the enclosing
3603 object (the function fails without optimization in this type). */
3604 int ost = optimize > 0;
3605 unsigned HOST_WIDE_INT size;
3606 if (compute_builtin_object_size (dest, ost, &size))
3607 return size;
3609 return HOST_WIDE_INT_MAX;
3612 /* Return true if the call described by INFO with result RES safe to
3613 optimize (i.e., no undefined behavior), and set RETVAL to the range
3614 of its return values. */
3616 static bool
3617 is_call_safe (const sprintf_dom_walker::call_info &info,
3618 const format_result &res, bool under4k,
3619 unsigned HOST_WIDE_INT retval[2])
3621 if (under4k && !res.posunder4k)
3622 return false;
3624 /* The minimum return value. */
3625 retval[0] = res.range.min;
3627 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3628 but in cases involving multibyte characters could be as large as
3629 RES.RANGE.UNLIKELY. */
3630 retval[1]
3631 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3633 /* Adjust the number of bytes which includes the terminating nul
3634 to reflect the return value of the function which does not.
3635 Because the valid range of the function is [INT_MIN, INT_MAX],
3636 a valid range before the adjustment below is [0, INT_MAX + 1]
3637 (the functions only return negative values on error or undefined
3638 behavior). */
3639 if (retval[0] <= target_int_max () + 1)
3640 --retval[0];
3641 if (retval[1] <= target_int_max () + 1)
3642 --retval[1];
3644 /* Avoid the return value optimization when the behavior of the call
3645 is undefined either because any directive may have produced 4K or
3646 more of output, or the return value exceeds INT_MAX, or because
3647 the output overflows the destination object (but leave it enabled
3648 when the function is bounded because then the behavior is well-
3649 defined). */
3650 if (retval[0] == retval[1]
3651 && (info.bounded || retval[0] < info.objsize)
3652 && retval[0] <= target_int_max ())
3653 return true;
3655 if ((info.bounded || retval[1] < info.objsize)
3656 && (retval[0] < target_int_max ()
3657 && retval[1] < target_int_max ()))
3658 return true;
3660 if (!under4k && (info.bounded || retval[0] < info.objsize))
3661 return true;
3663 return false;
3666 /* Given a suitable result RES of a call to a formatted output function
3667 described by INFO, substitute the result for the return value of
3668 the call. The result is suitable if the number of bytes it represents
3669 is known and exact. A result that isn't suitable for substitution may
3670 have its range set to the range of return values, if that is known.
3671 Return true if the call is removed and gsi_next should not be performed
3672 in the caller. */
3674 static bool
3675 try_substitute_return_value (gimple_stmt_iterator *gsi,
3676 const sprintf_dom_walker::call_info &info,
3677 const format_result &res)
3679 tree lhs = gimple_get_lhs (info.callstmt);
3681 /* Set to true when the entire call has been removed. */
3682 bool removed = false;
3684 /* The minimum and maximum return value. */
3685 unsigned HOST_WIDE_INT retval[2];
3686 bool safe = is_call_safe (info, res, true, retval);
3688 if (safe
3689 && retval[0] == retval[1]
3690 /* Not prepared to handle possibly throwing calls here; they shouldn't
3691 appear in non-artificial testcases, except when the __*_chk routines
3692 are badly declared. */
3693 && !stmt_ends_bb_p (info.callstmt))
3695 tree cst = build_int_cst (integer_type_node, retval[0]);
3697 if (lhs == NULL_TREE
3698 && info.nowrite)
3700 /* Remove the call to the bounded function with a zero size
3701 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3702 unlink_stmt_vdef (info.callstmt);
3703 gsi_remove (gsi, true);
3704 removed = true;
3706 else if (info.nowrite)
3708 /* Replace the call to the bounded function with a zero size
3709 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3710 of the function. */
3711 if (!update_call_from_tree (gsi, cst))
3712 gimplify_and_update_call_from_tree (gsi, cst);
3713 gimple *callstmt = gsi_stmt (*gsi);
3714 update_stmt (callstmt);
3716 else if (lhs)
3718 /* Replace the left-hand side of the call with the constant
3719 result of the formatted function. */
3720 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3721 gimple *g = gimple_build_assign (lhs, cst);
3722 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3723 update_stmt (info.callstmt);
3726 if (dump_file)
3728 if (removed)
3729 fprintf (dump_file, " Removing call statement.");
3730 else
3732 fprintf (dump_file, " Substituting ");
3733 print_generic_expr (dump_file, cst, dump_flags);
3734 fprintf (dump_file, " for %s.\n",
3735 info.nowrite ? "statement" : "return value");
3739 else if (lhs)
3741 bool setrange = false;
3743 if (safe
3744 && (info.bounded || retval[1] < info.objsize)
3745 && (retval[0] < target_int_max ()
3746 && retval[1] < target_int_max ()))
3748 /* If the result is in a valid range bounded by the size of
3749 the destination set it so that it can be used for subsequent
3750 optimizations. */
3751 int prec = TYPE_PRECISION (integer_type_node);
3753 wide_int min = wi::shwi (retval[0], prec);
3754 wide_int max = wi::shwi (retval[1], prec);
3755 set_range_info (lhs, VR_RANGE, min, max);
3757 setrange = true;
3760 if (dump_file)
3762 const char *inbounds
3763 = (retval[0] < info.objsize
3764 ? (retval[1] < info.objsize
3765 ? "in" : "potentially out-of")
3766 : "out-of");
3768 const char *what = setrange ? "Setting" : "Discarding";
3769 if (retval[0] != retval[1])
3770 fprintf (dump_file,
3771 " %s %s-bounds return value range ["
3772 HOST_WIDE_INT_PRINT_UNSIGNED ", "
3773 HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
3774 what, inbounds, retval[0], retval[1]);
3775 else
3776 fprintf (dump_file, " %s %s-bounds return value "
3777 HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
3778 what, inbounds, retval[0]);
3782 if (dump_file)
3783 fputc ('\n', dump_file);
3785 return removed;
3788 /* Try to simplify a s{,n}printf call described by INFO with result
3789 RES by replacing it with a simpler and presumably more efficient
3790 call (such as strcpy). */
3792 static bool
3793 try_simplify_call (gimple_stmt_iterator *gsi,
3794 const sprintf_dom_walker::call_info &info,
3795 const format_result &res)
3797 unsigned HOST_WIDE_INT dummy[2];
3798 if (!is_call_safe (info, res, info.retval_used (), dummy))
3799 return false;
3801 switch (info.fncode)
3803 case BUILT_IN_SNPRINTF:
3804 return gimple_fold_builtin_snprintf (gsi);
3806 case BUILT_IN_SPRINTF:
3807 return gimple_fold_builtin_sprintf (gsi);
3809 default:
3813 return false;
3816 /* Return the zero-based index of the format string argument of a printf
3817 like function and set *IDX_ARGS to the first format argument. When
3818 no such index exists return UINT_MAX. */
3820 static unsigned
3821 get_user_idx_format (tree fndecl, unsigned *idx_args)
3823 tree attrs = lookup_attribute ("format", DECL_ATTRIBUTES (fndecl));
3824 if (!attrs)
3825 attrs = lookup_attribute ("format", TYPE_ATTRIBUTES (TREE_TYPE (fndecl)));
3827 if (!attrs)
3828 return UINT_MAX;
3830 attrs = TREE_VALUE (attrs);
3832 tree archetype = TREE_VALUE (attrs);
3833 if (strcmp ("printf", IDENTIFIER_POINTER (archetype)))
3834 return UINT_MAX;
3836 attrs = TREE_CHAIN (attrs);
3837 tree fmtarg = TREE_VALUE (attrs);
3839 attrs = TREE_CHAIN (attrs);
3840 tree elliparg = TREE_VALUE (attrs);
3842 /* Attribute argument indices are 1-based but we use zero-based. */
3843 *idx_args = tree_to_uhwi (elliparg) - 1;
3844 return tree_to_uhwi (fmtarg) - 1;
3847 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3848 functions and if so, handle it. Return true if the call is removed
3849 and gsi_next should not be performed in the caller. */
3851 bool
3852 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3854 call_info info = call_info ();
3856 info.callstmt = gsi_stmt (*gsi);
3857 info.func = gimple_call_fndecl (info.callstmt);
3858 if (!info.func)
3859 return false;
3861 /* Format string argument number (valid for all functions). */
3862 unsigned idx_format = UINT_MAX;
3863 if (gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3864 info.fncode = DECL_FUNCTION_CODE (info.func);
3865 else
3867 unsigned idx_args;
3868 idx_format = get_user_idx_format (info.func, &idx_args);
3869 if (idx_format == UINT_MAX
3870 || idx_format >= gimple_call_num_args (info.callstmt)
3871 || idx_args > gimple_call_num_args (info.callstmt)
3872 || !POINTER_TYPE_P (TREE_TYPE (gimple_call_arg (info.callstmt,
3873 idx_format))))
3874 return false;
3875 info.fncode = BUILT_IN_NONE;
3876 info.argidx = idx_args;
3879 /* The size of the destination as in snprintf(dest, size, ...). */
3880 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3882 /* The size of the destination determined by __builtin_object_size. */
3883 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3885 /* Zero-based buffer size argument number (snprintf and vsnprintf). */
3886 unsigned idx_dstsize = UINT_MAX;
3888 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3889 unsigned idx_objsize = UINT_MAX;
3891 /* Destinaton argument number (valid for sprintf functions only). */
3892 unsigned idx_dstptr = 0;
3894 switch (info.fncode)
3896 case BUILT_IN_NONE:
3897 // User-defined function with attribute format (printf).
3898 idx_dstptr = -1;
3899 break;
3901 case BUILT_IN_FPRINTF:
3902 // Signature:
3903 // __builtin_fprintf (FILE*, format, ...)
3904 idx_format = 1;
3905 info.argidx = 2;
3906 idx_dstptr = -1;
3907 break;
3909 case BUILT_IN_FPRINTF_CHK:
3910 // Signature:
3911 // __builtin_fprintf_chk (FILE*, ost, format, ...)
3912 idx_format = 2;
3913 info.argidx = 3;
3914 idx_dstptr = -1;
3915 break;
3917 case BUILT_IN_FPRINTF_UNLOCKED:
3918 // Signature:
3919 // __builtin_fprintf_unnlocked (FILE*, format, ...)
3920 idx_format = 1;
3921 info.argidx = 2;
3922 idx_dstptr = -1;
3923 break;
3925 case BUILT_IN_PRINTF:
3926 // Signature:
3927 // __builtin_printf (format, ...)
3928 idx_format = 0;
3929 info.argidx = 1;
3930 idx_dstptr = -1;
3931 break;
3933 case BUILT_IN_PRINTF_CHK:
3934 // Signature:
3935 // __builtin_printf_chk (ost, format, ...)
3936 idx_format = 1;
3937 info.argidx = 2;
3938 idx_dstptr = -1;
3939 break;
3941 case BUILT_IN_PRINTF_UNLOCKED:
3942 // Signature:
3943 // __builtin_printf (format, ...)
3944 idx_format = 0;
3945 info.argidx = 1;
3946 idx_dstptr = -1;
3947 break;
3949 case BUILT_IN_SPRINTF:
3950 // Signature:
3951 // __builtin_sprintf (dst, format, ...)
3952 idx_format = 1;
3953 info.argidx = 2;
3954 break;
3956 case BUILT_IN_SPRINTF_CHK:
3957 // Signature:
3958 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3959 idx_objsize = 2;
3960 idx_format = 3;
3961 info.argidx = 4;
3962 break;
3964 case BUILT_IN_SNPRINTF:
3965 // Signature:
3966 // __builtin_snprintf (dst, size, format, ...)
3967 idx_dstsize = 1;
3968 idx_format = 2;
3969 info.argidx = 3;
3970 info.bounded = true;
3971 break;
3973 case BUILT_IN_SNPRINTF_CHK:
3974 // Signature:
3975 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3976 idx_dstsize = 1;
3977 idx_objsize = 3;
3978 idx_format = 4;
3979 info.argidx = 5;
3980 info.bounded = true;
3981 break;
3983 case BUILT_IN_VFPRINTF:
3984 // Signature:
3985 // __builtin_vprintf (FILE*, format, va_list)
3986 idx_format = 1;
3987 info.argidx = -1;
3988 idx_dstptr = -1;
3989 break;
3991 case BUILT_IN_VFPRINTF_CHK:
3992 // Signature:
3993 // __builtin___vfprintf_chk (FILE*, ost, format, va_list)
3994 idx_format = 2;
3995 info.argidx = -1;
3996 idx_dstptr = -1;
3997 break;
3999 case BUILT_IN_VPRINTF:
4000 // Signature:
4001 // __builtin_vprintf (format, va_list)
4002 idx_format = 0;
4003 info.argidx = -1;
4004 idx_dstptr = -1;
4005 break;
4007 case BUILT_IN_VPRINTF_CHK:
4008 // Signature:
4009 // __builtin___vprintf_chk (ost, format, va_list)
4010 idx_format = 1;
4011 info.argidx = -1;
4012 idx_dstptr = -1;
4013 break;
4015 case BUILT_IN_VSNPRINTF:
4016 // Signature:
4017 // __builtin_vsprintf (dst, size, format, va)
4018 idx_dstsize = 1;
4019 idx_format = 2;
4020 info.argidx = -1;
4021 info.bounded = true;
4022 break;
4024 case BUILT_IN_VSNPRINTF_CHK:
4025 // Signature:
4026 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
4027 idx_dstsize = 1;
4028 idx_objsize = 3;
4029 idx_format = 4;
4030 info.argidx = -1;
4031 info.bounded = true;
4032 break;
4034 case BUILT_IN_VSPRINTF:
4035 // Signature:
4036 // __builtin_vsprintf (dst, format, va)
4037 idx_format = 1;
4038 info.argidx = -1;
4039 break;
4041 case BUILT_IN_VSPRINTF_CHK:
4042 // Signature:
4043 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
4044 idx_format = 3;
4045 idx_objsize = 2;
4046 info.argidx = -1;
4047 break;
4049 default:
4050 return false;
4053 /* Set the global warning level for this function. */
4054 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
4056 /* For all string functions the first argument is a pointer to
4057 the destination. */
4058 tree dstptr = (idx_dstptr < gimple_call_num_args (info.callstmt)
4059 ? gimple_call_arg (info.callstmt, 0) : NULL_TREE);
4061 info.format = gimple_call_arg (info.callstmt, idx_format);
4063 /* True when the destination size is constant as opposed to the lower
4064 or upper bound of a range. */
4065 bool dstsize_cst_p = true;
4066 bool posunder4k = true;
4068 if (idx_dstsize == UINT_MAX)
4070 /* For non-bounded functions like sprintf, determine the size
4071 of the destination from the object or pointer passed to it
4072 as the first argument. */
4073 dstsize = get_destination_size (dstptr);
4075 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
4077 /* For bounded functions try to get the size argument. */
4079 if (TREE_CODE (size) == INTEGER_CST)
4081 dstsize = tree_to_uhwi (size);
4082 /* No object can be larger than SIZE_MAX bytes (half the address
4083 space) on the target.
4084 The functions are defined only for output of at most INT_MAX
4085 bytes. Specifying a bound in excess of that limit effectively
4086 defeats the bounds checking (and on some implementations such
4087 as Solaris cause the function to fail with EINVAL). */
4088 if (dstsize > target_size_max () / 2)
4090 /* Avoid warning if -Wstringop-overflow is specified since
4091 it also warns for the same thing though only for the
4092 checking built-ins. */
4093 if ((idx_objsize == UINT_MAX
4094 || !warn_stringop_overflow))
4095 warning_at (gimple_location (info.callstmt), info.warnopt (),
4096 "specified bound %wu exceeds maximum object size "
4097 "%wu",
4098 dstsize, target_size_max () / 2);
4099 /* POSIX requires snprintf to fail if DSTSIZE is greater
4100 than INT_MAX. Even though not all POSIX implementations
4101 conform to the requirement, avoid folding in this case. */
4102 posunder4k = false;
4104 else if (dstsize > target_int_max ())
4106 warning_at (gimple_location (info.callstmt), info.warnopt (),
4107 "specified bound %wu exceeds %<INT_MAX%>",
4108 dstsize);
4109 /* POSIX requires snprintf to fail if DSTSIZE is greater
4110 than INT_MAX. Avoid folding in that case. */
4111 posunder4k = false;
4114 else if (TREE_CODE (size) == SSA_NAME)
4116 /* Try to determine the range of values of the argument
4117 and use the greater of the two at level 1 and the smaller
4118 of them at level 2. */
4119 value_range *vr = evrp_range_analyzer.get_value_range (size);
4120 if (range_int_cst_p (vr))
4122 unsigned HOST_WIDE_INT minsize = TREE_INT_CST_LOW (vr->min ());
4123 unsigned HOST_WIDE_INT maxsize = TREE_INT_CST_LOW (vr->max ());
4124 dstsize = warn_level < 2 ? maxsize : minsize;
4126 if (minsize > target_int_max ())
4127 warning_at (gimple_location (info.callstmt), info.warnopt (),
4128 "specified bound range [%wu, %wu] exceeds "
4129 "%<INT_MAX%>",
4130 minsize, maxsize);
4132 /* POSIX requires snprintf to fail if DSTSIZE is greater
4133 than INT_MAX. Avoid folding if that's possible. */
4134 if (maxsize > target_int_max ())
4135 posunder4k = false;
4137 else if (vr->varying_p ())
4139 /* POSIX requires snprintf to fail if DSTSIZE is greater
4140 than INT_MAX. Since SIZE's range is unknown, avoid
4141 folding. */
4142 posunder4k = false;
4145 /* The destination size is not constant. If the function is
4146 bounded (e.g., snprintf) a lower bound of zero doesn't
4147 necessarily imply it can be eliminated. */
4148 dstsize_cst_p = false;
4152 if (idx_objsize != UINT_MAX)
4153 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
4154 if (tree_fits_uhwi_p (size))
4155 objsize = tree_to_uhwi (size);
4157 if (info.bounded && !dstsize)
4159 /* As a special case, when the explicitly specified destination
4160 size argument (to a bounded function like snprintf) is zero
4161 it is a request to determine the number of bytes on output
4162 without actually producing any. Pretend the size is
4163 unlimited in this case. */
4164 info.objsize = HOST_WIDE_INT_MAX;
4165 info.nowrite = dstsize_cst_p;
4167 else
4169 /* For calls to non-bounded functions or to those of bounded
4170 functions with a non-zero size, warn if the destination
4171 pointer is null. */
4172 if (dstptr && integer_zerop (dstptr))
4174 /* This is diagnosed with -Wformat only when the null is a constant
4175 pointer. The warning here diagnoses instances where the pointer
4176 is not constant. */
4177 location_t loc = gimple_location (info.callstmt);
4178 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
4179 info.warnopt (), "%Gnull destination pointer",
4180 info.callstmt);
4181 return false;
4184 /* Set the object size to the smaller of the two arguments
4185 of both have been specified and they're not equal. */
4186 info.objsize = dstsize < objsize ? dstsize : objsize;
4188 if (info.bounded
4189 && dstsize < target_size_max () / 2 && objsize < dstsize
4190 /* Avoid warning if -Wstringop-overflow is specified since
4191 it also warns for the same thing though only for the
4192 checking built-ins. */
4193 && (idx_objsize == UINT_MAX
4194 || !warn_stringop_overflow))
4196 warning_at (gimple_location (info.callstmt), info.warnopt (),
4197 "specified bound %wu exceeds the size %wu "
4198 "of the destination object", dstsize, objsize);
4202 /* Determine if the format argument may be null and warn if not
4203 and if the argument is null. */
4204 if (integer_zerop (info.format)
4205 && gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
4207 location_t loc = gimple_location (info.callstmt);
4208 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
4209 info.warnopt (), "%Gnull format string",
4210 info.callstmt);
4211 return false;
4214 info.fmtstr = get_format_string (info.format, &info.fmtloc);
4215 if (!info.fmtstr)
4216 return false;
4218 /* The result is the number of bytes output by the formatted function,
4219 including the terminating NUL. */
4220 format_result res = format_result ();
4222 /* I/O functions with no destination argument (i.e., all forms of fprintf
4223 and printf) may fail under any conditions. Others (i.e., all forms of
4224 sprintf) may only fail under specific conditions determined for each
4225 directive. Clear POSUNDER4K for the former set of functions and set
4226 it to true for the latter (it can only be cleared later, but it is
4227 never set to true again). */
4228 res.posunder4k = posunder4k && dstptr;
4230 bool success = compute_format_length (info, &res);
4231 if (res.warned)
4232 gimple_set_no_warning (info.callstmt, true);
4234 /* When optimizing and the printf return value optimization is enabled,
4235 attempt to substitute the computed result for the return value of
4236 the call. Avoid this optimization when -frounding-math is in effect
4237 and the format string contains a floating point directive. */
4238 bool call_removed = false;
4239 if (success && optimize > 0)
4241 /* Save a copy of the iterator pointing at the call. The iterator
4242 may change to point past the call in try_substitute_return_value
4243 but the original value is needed in try_simplify_call. */
4244 gimple_stmt_iterator gsi_call = *gsi;
4246 if (flag_printf_return_value
4247 && (!flag_rounding_math || !res.floating))
4248 call_removed = try_substitute_return_value (gsi, info, res);
4250 if (!call_removed)
4251 try_simplify_call (&gsi_call, info, res);
4254 return call_removed;
4257 edge
4258 sprintf_dom_walker::before_dom_children (basic_block bb)
4260 evrp_range_analyzer.enter (bb);
4261 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
4263 /* Iterate over statements, looking for function calls. */
4264 gimple *stmt = gsi_stmt (si);
4266 /* First record ranges generated by this statement. */
4267 evrp_range_analyzer.record_ranges_from_stmt (stmt, false);
4269 if (is_gimple_call (stmt) && handle_gimple_call (&si))
4270 /* If handle_gimple_call returns true, the iterator is
4271 already pointing to the next statement. */
4272 continue;
4274 gsi_next (&si);
4276 return NULL;
4279 void
4280 sprintf_dom_walker::after_dom_children (basic_block bb)
4282 evrp_range_analyzer.leave (bb);
4285 /* Execute the pass for function FUN. */
4287 unsigned int
4288 pass_sprintf_length::execute (function *fun)
4290 init_target_to_host_charmap ();
4292 calculate_dominance_info (CDI_DOMINATORS);
4293 bool use_scev = optimize > 0 && flag_printf_return_value;
4294 if (use_scev)
4296 loop_optimizer_init (LOOPS_NORMAL);
4297 scev_initialize ();
4300 sprintf_dom_walker sprintf_dom_walker;
4301 sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
4303 if (use_scev)
4305 scev_finalize ();
4306 loop_optimizer_finalize ();
4309 /* Clean up object size info. */
4310 fini_object_sizes ();
4311 return 0;
4314 } /* Unnamed namespace. */
4316 /* Return a pointer to a pass object newly constructed from the context
4317 CTXT. */
4319 gimple_opt_pass *
4320 make_pass_sprintf_length (gcc::context *ctxt)
4322 return new pass_sprintf_length (ctxt);