[Ada] New aspect/pragma No_Caching for analysis of volatile data
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob88ba1f2cac1690aa77de8cee3c41432bd68200dc
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 size_t len = strlen (targstr);
387 if (len >= hostsz)
389 memcpy (hostr, targstr, hostsz - 4);
390 strcpy (hostr + hostsz - 4, "...");
392 else
393 memcpy (hostr, targstr, len + 1);
394 return hostr;
397 /* Convert the initial substring of TARGSTR to the corresponding
398 characters in the host set, appending "..." if TARGSTR is too
399 long to fit. Using the static buffer assumes the function is
400 not called in between sequence points (which it isn't). */
401 for (char *ph = hostr; ; ++targstr)
403 *ph++ = target_to_host (*targstr);
404 if (!*targstr)
405 break;
407 if (size_t (ph - hostr) == hostsz)
409 strcpy (ph - 4, "...");
410 break;
414 return hostr;
417 /* Convert the sequence of decimal digits in the execution character
418 starting at *PS to a HOST_WIDE_INT, analogously to strtol. Return
419 the result and set *PS to one past the last converted character.
420 On range error set ERANGE to the digit that caused it. */
422 static inline HOST_WIDE_INT
423 target_strtowi (const char **ps, const char **erange)
425 unsigned HOST_WIDE_INT val = 0;
426 for ( ; ; ++*ps)
428 unsigned char c = target_to_host (**ps);
429 if (ISDIGIT (c))
431 c -= '0';
433 /* Check for overflow. */
434 if (val > ((unsigned HOST_WIDE_INT) HOST_WIDE_INT_MAX - c) / 10LU)
436 val = HOST_WIDE_INT_MAX;
437 *erange = *ps;
439 /* Skip the remaining digits. */
441 c = target_to_host (*++*ps);
442 while (ISDIGIT (c));
443 break;
445 else
446 val = val * 10 + c;
448 else
449 break;
452 return val;
455 /* Given FORMAT, set *PLOC to the source location of the format string
456 and return the format string if it is known or null otherwise. */
458 static const char*
459 get_format_string (tree format, location_t *ploc)
461 *ploc = EXPR_LOC_OR_LOC (format, input_location);
463 return c_getstr (format);
466 /* For convenience and brevity, shorter named entrypoints of
467 format_string_diagnostic_t::emit_warning_va and
468 format_string_diagnostic_t::emit_warning_n_va.
469 These have to be functions with the attribute so that exgettext
470 works properly. */
472 static bool
473 ATTRIBUTE_GCC_DIAG (5, 6)
474 fmtwarn (const substring_loc &fmt_loc, location_t param_loc,
475 const char *corrected_substring, int opt, const char *gmsgid, ...)
477 format_string_diagnostic_t diag (fmt_loc, NULL, param_loc, NULL,
478 corrected_substring);
479 va_list ap;
480 va_start (ap, gmsgid);
481 bool warned = diag.emit_warning_va (opt, gmsgid, &ap);
482 va_end (ap);
484 return warned;
487 static bool
488 ATTRIBUTE_GCC_DIAG (6, 8) ATTRIBUTE_GCC_DIAG (7, 8)
489 fmtwarn_n (const substring_loc &fmt_loc, location_t param_loc,
490 const char *corrected_substring, int opt, unsigned HOST_WIDE_INT n,
491 const char *singular_gmsgid, const char *plural_gmsgid, ...)
493 format_string_diagnostic_t diag (fmt_loc, NULL, param_loc, NULL,
494 corrected_substring);
495 va_list ap;
496 va_start (ap, plural_gmsgid);
497 bool warned = diag.emit_warning_n_va (opt, n, singular_gmsgid, plural_gmsgid,
498 &ap);
499 va_end (ap);
501 return warned;
504 /* Format length modifiers. */
506 enum format_lengths
508 FMT_LEN_none,
509 FMT_LEN_hh, // char argument
510 FMT_LEN_h, // short
511 FMT_LEN_l, // long
512 FMT_LEN_ll, // long long
513 FMT_LEN_L, // long double (and GNU long long)
514 FMT_LEN_z, // size_t
515 FMT_LEN_t, // ptrdiff_t
516 FMT_LEN_j // intmax_t
520 /* Description of the result of conversion either of a single directive
521 or the whole format string. */
523 class fmtresult
525 public:
526 /* Construct a FMTRESULT object with all counters initialized
527 to MIN. KNOWNRANGE is set when MIN is valid. */
528 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
529 : argmin (), argmax (), nonstr (),
530 knownrange (min < HOST_WIDE_INT_MAX),
531 mayfail (), nullp ()
533 range.min = min;
534 range.max = min;
535 range.likely = min;
536 range.unlikely = min;
539 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
540 KNOWNRANGE is set when both MIN and MAX are valid. */
541 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
542 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
543 : argmin (), argmax (), nonstr (),
544 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
545 mayfail (), nullp ()
547 range.min = min;
548 range.max = max;
549 range.likely = max < likely ? min : likely;
550 range.unlikely = max;
553 /* Adjust result upward to reflect the RANGE of values the specified
554 width or precision is known to be in. */
555 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
556 tree = NULL_TREE,
557 unsigned = 0, unsigned = 0);
559 /* Return the maximum number of decimal digits a value of TYPE
560 formats as on output. */
561 static unsigned type_max_digits (tree, int);
563 /* The range a directive's argument is in. */
564 tree argmin, argmax;
566 /* The minimum and maximum number of bytes that a directive
567 results in on output for an argument in the range above. */
568 result_range range;
570 /* Non-nul when the argument of a string directive is not a nul
571 terminated string. */
572 tree nonstr;
574 /* True when the range above is obtained from a known value of
575 a directive's argument or its bounds and not the result of
576 heuristics that depend on warning levels. */
577 bool knownrange;
579 /* True for a directive that may fail (such as wide character
580 directives). */
581 bool mayfail;
583 /* True when the argument is a null pointer. */
584 bool nullp;
587 /* Adjust result upward to reflect the range ADJUST of values the
588 specified width or precision is known to be in. When non-null,
589 TYPE denotes the type of the directive whose result is being
590 adjusted, BASE gives the base of the directive (octal, decimal,
591 or hex), and ADJ denotes the additional adjustment to the LIKELY
592 counter that may need to be added when ADJUST is a range. */
594 fmtresult&
595 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
596 tree type /* = NULL_TREE */,
597 unsigned base /* = 0 */,
598 unsigned adj /* = 0 */)
600 bool minadjusted = false;
602 /* Adjust the minimum and likely counters. */
603 if (adjust[0] >= 0)
605 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
607 range.min = adjust[0];
608 minadjusted = true;
611 /* Adjust the likely counter. */
612 if (range.likely < range.min)
613 range.likely = range.min;
615 else if (adjust[0] == target_int_min ()
616 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
617 knownrange = false;
619 /* Adjust the maximum counter. */
620 if (adjust[1] > 0)
622 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
624 range.max = adjust[1];
626 /* Set KNOWNRANGE if both the minimum and maximum have been
627 adjusted. Otherwise leave it at what it was before. */
628 knownrange = minadjusted;
632 if (warn_level > 1 && type)
634 /* For large non-constant width or precision whose range spans
635 the maximum number of digits produced by the directive for
636 any argument, set the likely number of bytes to be at most
637 the number digits plus other adjustment determined by the
638 caller (one for sign or two for the hexadecimal "0x"
639 prefix). */
640 unsigned dirdigs = type_max_digits (type, base);
641 if (adjust[0] < dirdigs && dirdigs < adjust[1]
642 && range.likely < dirdigs)
643 range.likely = dirdigs + adj;
645 else if (range.likely < (range.min ? range.min : 1))
647 /* Conservatively, set LIKELY to at least MIN but no less than
648 1 unless MAX is zero. */
649 range.likely = (range.min
650 ? range.min
651 : range.max && (range.max < HOST_WIDE_INT_MAX
652 || warn_level > 1) ? 1 : 0);
655 /* Finally adjust the unlikely counter to be at least as large as
656 the maximum. */
657 if (range.unlikely < range.max)
658 range.unlikely = range.max;
660 return *this;
663 /* Return the maximum number of digits a value of TYPE formats in
664 BASE on output, not counting base prefix . */
666 unsigned
667 fmtresult::type_max_digits (tree type, int base)
669 unsigned prec = TYPE_PRECISION (type);
670 switch (base)
672 case 8:
673 return (prec + 2) / 3;
674 case 10:
675 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
676 of 8, 16, 32, and 64 bits. */
677 return prec * 301 / 1000 + 1;
678 case 16:
679 return prec / 4;
682 gcc_unreachable ();
685 static bool
686 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT,
687 class vr_values *vr_values);
689 /* Description of a format directive. A directive is either a plain
690 string or a conversion specification that starts with '%'. */
692 struct directive
694 /* The 1-based directive number (for debugging). */
695 unsigned dirno;
697 /* The first character of the directive and its length. */
698 const char *beg;
699 size_t len;
701 /* A bitmap of flags, one for each character. */
702 unsigned flags[256 / sizeof (int)];
704 /* The range of values of the specified width, or -1 if not specified. */
705 HOST_WIDE_INT width[2];
706 /* The range of values of the specified precision, or -1 if not
707 specified. */
708 HOST_WIDE_INT prec[2];
710 /* Length modifier. */
711 format_lengths modifier;
713 /* Format specifier character. */
714 char specifier;
716 /* The argument of the directive or null when the directive doesn't
717 take one or when none is available (such as for vararg functions). */
718 tree arg;
720 /* Format conversion function that given a directive and an argument
721 returns the formatting result. */
722 fmtresult (*fmtfunc) (const directive &, tree, vr_values *);
724 /* Return True when a the format flag CHR has been used. */
725 bool get_flag (char chr) const
727 unsigned char c = chr & 0xff;
728 return (flags[c / (CHAR_BIT * sizeof *flags)]
729 & (1U << (c % (CHAR_BIT * sizeof *flags))));
732 /* Make a record of the format flag CHR having been used. */
733 void set_flag (char chr)
735 unsigned char c = chr & 0xff;
736 flags[c / (CHAR_BIT * sizeof *flags)]
737 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
740 /* Reset the format flag CHR. */
741 void clear_flag (char chr)
743 unsigned char c = chr & 0xff;
744 flags[c / (CHAR_BIT * sizeof *flags)]
745 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
748 /* Set both bounds of the width range to VAL. */
749 void set_width (HOST_WIDE_INT val)
751 width[0] = width[1] = val;
754 /* Set the width range according to ARG, with both bounds being
755 no less than 0. For a constant ARG set both bounds to its value
756 or 0, whichever is greater. For a non-constant ARG in some range
757 set width to its range adjusting each bound to -1 if it's less.
758 For an indeterminate ARG set width to [0, INT_MAX]. */
759 void set_width (tree arg, vr_values *vr_values)
761 get_int_range (arg, width, width + 1, true, 0, vr_values);
764 /* Set both bounds of the precision range to VAL. */
765 void set_precision (HOST_WIDE_INT val)
767 prec[0] = prec[1] = val;
770 /* Set the precision range according to ARG, with both bounds being
771 no less than -1. For a constant ARG set both bounds to its value
772 or -1 whichever is greater. For a non-constant ARG in some range
773 set precision to its range adjusting each bound to -1 if it's less.
774 For an indeterminate ARG set precision to [-1, INT_MAX]. */
775 void set_precision (tree arg, vr_values *vr_values)
777 get_int_range (arg, prec, prec + 1, false, -1, vr_values);
780 /* Return true if both width and precision are known to be
781 either constant or in some range, false otherwise. */
782 bool known_width_and_precision () const
784 return ((width[1] < 0
785 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
786 && (prec[1] < 0
787 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
791 /* Return the logarithm of X in BASE. */
793 static int
794 ilog (unsigned HOST_WIDE_INT x, int base)
796 int res = 0;
799 ++res;
800 x /= base;
801 } while (x);
802 return res;
805 /* Return the number of bytes resulting from converting into a string
806 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
807 PLUS indicates whether 1 for a plus sign should be added for positive
808 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
809 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
810 be represented. */
812 static HOST_WIDE_INT
813 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
815 unsigned HOST_WIDE_INT absval;
817 HOST_WIDE_INT res;
819 if (TYPE_UNSIGNED (TREE_TYPE (x)))
821 if (tree_fits_uhwi_p (x))
823 absval = tree_to_uhwi (x);
824 res = plus;
826 else
827 return -1;
829 else
831 if (tree_fits_shwi_p (x))
833 HOST_WIDE_INT i = tree_to_shwi (x);
834 if (HOST_WIDE_INT_MIN == i)
836 /* Avoid undefined behavior due to negating a minimum. */
837 absval = HOST_WIDE_INT_MAX;
838 res = 1;
840 else if (i < 0)
842 absval = -i;
843 res = 1;
845 else
847 absval = i;
848 res = plus;
851 else
852 return -1;
855 int ndigs = ilog (absval, base);
857 res += prec < ndigs ? ndigs : prec;
859 /* Adjust a non-zero value for the base prefix, either hexadecimal,
860 or, unless precision has resulted in a leading zero, also octal. */
861 if (prefix && absval && (base == 16 || prec <= ndigs))
863 if (base == 8)
864 res += 1;
865 else if (base == 16)
866 res += 2;
869 return res;
872 /* Given the formatting result described by RES and NAVAIL, the number
873 of available in the destination, return the range of bytes remaining
874 in the destination. */
876 static inline result_range
877 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
879 result_range range;
881 if (HOST_WIDE_INT_MAX <= navail)
883 range.min = range.max = range.likely = range.unlikely = navail;
884 return range;
887 /* The lower bound of the available range is the available size
888 minus the maximum output size, and the upper bound is the size
889 minus the minimum. */
890 range.max = res.range.min < navail ? navail - res.range.min : 0;
892 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
894 if (res.range.max < HOST_WIDE_INT_MAX)
895 range.min = res.range.max < navail ? navail - res.range.max : 0;
896 else
897 range.min = range.likely;
899 range.unlikely = (res.range.unlikely < navail
900 ? navail - res.range.unlikely : 0);
902 return range;
905 /* Description of a call to a formatted function. */
907 struct sprintf_dom_walker::call_info
909 /* Function call statement. */
910 gimple *callstmt;
912 /* Function called. */
913 tree func;
915 /* Called built-in function code. */
916 built_in_function fncode;
918 /* Format argument and format string extracted from it. */
919 tree format;
920 const char *fmtstr;
922 /* The location of the format argument. */
923 location_t fmtloc;
925 /* The destination object size for __builtin___xxx_chk functions
926 typically determined by __builtin_object_size, or -1 if unknown. */
927 unsigned HOST_WIDE_INT objsize;
929 /* Number of the first variable argument. */
930 unsigned HOST_WIDE_INT argidx;
932 /* True for functions like snprintf that specify the size of
933 the destination, false for others like sprintf that don't. */
934 bool bounded;
936 /* True for bounded functions like snprintf that specify a zero-size
937 buffer as a request to compute the size of output without actually
938 writing any. NOWRITE is cleared in response to the %n directive
939 which has side-effects similar to writing output. */
940 bool nowrite;
942 /* Return true if the called function's return value is used. */
943 bool retval_used () const
945 return gimple_get_lhs (callstmt);
948 /* Return the warning option corresponding to the called function. */
949 int warnopt () const
951 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
954 /* Return true for calls to file formatted functions. */
955 bool is_file_func () const
957 return (fncode == BUILT_IN_FPRINTF
958 || fncode == BUILT_IN_FPRINTF_CHK
959 || fncode == BUILT_IN_FPRINTF_UNLOCKED
960 || fncode == BUILT_IN_VFPRINTF
961 || fncode == BUILT_IN_VFPRINTF_CHK);
964 /* Return true for calls to string formatted functions. */
965 bool is_string_func () const
967 return (fncode == BUILT_IN_SPRINTF
968 || fncode == BUILT_IN_SPRINTF_CHK
969 || fncode == BUILT_IN_SNPRINTF
970 || fncode == BUILT_IN_SNPRINTF_CHK
971 || fncode == BUILT_IN_VSPRINTF
972 || fncode == BUILT_IN_VSPRINTF_CHK
973 || fncode == BUILT_IN_VSNPRINTF
974 || fncode == BUILT_IN_VSNPRINTF_CHK);
978 /* Return the result of formatting a no-op directive (such as '%n'). */
980 static fmtresult
981 format_none (const directive &, tree, vr_values *)
983 fmtresult res (0);
984 return res;
987 /* Return the result of formatting the '%%' directive. */
989 static fmtresult
990 format_percent (const directive &, tree, vr_values *)
992 fmtresult res (1);
993 return res;
997 /* Compute intmax_type_node and uintmax_type_node similarly to how
998 tree.c builds size_type_node. */
1000 static void
1001 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
1003 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
1005 *pintmax = integer_type_node;
1006 *puintmax = unsigned_type_node;
1008 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
1010 *pintmax = long_integer_type_node;
1011 *puintmax = long_unsigned_type_node;
1013 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
1015 *pintmax = long_long_integer_type_node;
1016 *puintmax = long_long_unsigned_type_node;
1018 else
1020 for (int i = 0; i < NUM_INT_N_ENTS; i++)
1021 if (int_n_enabled_p[i])
1023 char name[50], altname[50];
1024 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
1025 sprintf (altname, "__int%d__ unsigned", int_n_data[i].bitsize);
1027 if (strcmp (name, UINTMAX_TYPE) == 0
1028 || strcmp (altname, UINTMAX_TYPE) == 0)
1030 *pintmax = int_n_trees[i].signed_type;
1031 *puintmax = int_n_trees[i].unsigned_type;
1032 return;
1035 gcc_unreachable ();
1039 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1040 in and that is representable in type int.
1041 Return true when the range is a subrange of that of int.
1042 When ARG is null it is as if it had the full range of int.
1043 When ABSOLUTE is true the range reflects the absolute value of
1044 the argument. When ABSOLUTE is false, negative bounds of
1045 the determined range are replaced with NEGBOUND. */
1047 static bool
1048 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1049 bool absolute, HOST_WIDE_INT negbound,
1050 class vr_values *vr_values)
1052 /* The type of the result. */
1053 const_tree type = integer_type_node;
1055 bool knownrange = false;
1057 if (!arg)
1059 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1060 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1062 else if (TREE_CODE (arg) == INTEGER_CST
1063 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1065 /* For a constant argument return its value adjusted as specified
1066 by NEGATIVE and NEGBOUND and return true to indicate that the
1067 result is known. */
1068 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1069 *pmax = *pmin;
1070 knownrange = true;
1072 else
1074 /* True if the argument's range cannot be determined. */
1075 bool unknown = true;
1077 tree argtype = TREE_TYPE (arg);
1079 /* Ignore invalid arguments with greater precision that that
1080 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1081 They will have been detected and diagnosed by -Wformat and
1082 so it's not important to complicate this code to try to deal
1083 with them again. */
1084 if (TREE_CODE (arg) == SSA_NAME
1085 && INTEGRAL_TYPE_P (argtype)
1086 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1088 /* Try to determine the range of values of the integer argument. */
1089 const value_range *vr = vr_values->get_value_range (arg);
1090 if (range_int_cst_p (vr))
1092 HOST_WIDE_INT type_min
1093 = (TYPE_UNSIGNED (argtype)
1094 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1095 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1097 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1099 *pmin = TREE_INT_CST_LOW (vr->min ());
1100 *pmax = TREE_INT_CST_LOW (vr->max ());
1102 if (*pmin < *pmax)
1104 /* Return true if the adjusted range is a subrange of
1105 the full range of the argument's type. *PMAX may
1106 be less than *PMIN when the argument is unsigned
1107 and its upper bound is in excess of TYPE_MAX. In
1108 that (invalid) case disregard the range and use that
1109 of the expected type instead. */
1110 knownrange = type_min < *pmin || *pmax < type_max;
1112 unknown = false;
1117 /* Handle an argument with an unknown range as if none had been
1118 provided. */
1119 if (unknown)
1120 return get_int_range (NULL_TREE, pmin, pmax, absolute,
1121 negbound, vr_values);
1124 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1125 if (absolute)
1127 if (*pmin < 0)
1129 if (*pmin == *pmax)
1130 *pmin = *pmax = -*pmin;
1131 else
1133 /* Make sure signed overlow is avoided. */
1134 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1136 HOST_WIDE_INT tmp = -*pmin;
1137 *pmin = 0;
1138 if (*pmax < tmp)
1139 *pmax = tmp;
1143 else if (*pmin < negbound)
1144 *pmin = negbound;
1146 return knownrange;
1149 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1150 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1151 the type of the directive's formal argument it's possible for both
1152 to result in the same number of bytes or a range of bytes that's
1153 less than the number of bytes that would result from formatting
1154 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1155 determined by checking for the actual argument being in the range
1156 of the type of the directive. If it isn't it must be assumed to
1157 take on the full range of the directive's type.
1158 Return true when the range has been adjusted to the full range
1159 of DIRTYPE, and false otherwise. */
1161 static bool
1162 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1164 tree argtype = TREE_TYPE (*argmin);
1165 unsigned argprec = TYPE_PRECISION (argtype);
1166 unsigned dirprec = TYPE_PRECISION (dirtype);
1168 /* If the actual argument and the directive's argument have the same
1169 precision and sign there can be no overflow and so there is nothing
1170 to adjust. */
1171 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1172 return false;
1174 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1175 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1177 if (TREE_CODE (*argmin) == INTEGER_CST
1178 && TREE_CODE (*argmax) == INTEGER_CST
1179 && (dirprec >= argprec
1180 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1181 int_const_binop (MINUS_EXPR,
1182 *argmax,
1183 *argmin),
1184 size_int (dirprec)))))
1186 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1187 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1189 /* If *ARGMIN is still less than *ARGMAX the conversion above
1190 is safe. Otherwise, it has overflowed and would be unsafe. */
1191 if (tree_int_cst_le (*argmin, *argmax))
1192 return false;
1195 *argmin = TYPE_MIN_VALUE (dirtype);
1196 *argmax = TYPE_MAX_VALUE (dirtype);
1197 return true;
1200 /* Return a range representing the minimum and maximum number of bytes
1201 that the format directive DIR will output for any argument given
1202 the WIDTH and PRECISION (extracted from DIR). This function is
1203 used when the directive argument or its value isn't known. */
1205 static fmtresult
1206 format_integer (const directive &dir, tree arg, vr_values *vr_values)
1208 tree intmax_type_node;
1209 tree uintmax_type_node;
1211 /* Base to format the number in. */
1212 int base;
1214 /* True when a conversion is preceded by a prefix indicating the base
1215 of the argument (octal or hexadecimal). */
1216 bool maybebase = dir.get_flag ('#');
1218 /* True when a signed conversion is preceded by a sign or space. */
1219 bool maybesign = false;
1221 /* True for signed conversions (i.e., 'd' and 'i'). */
1222 bool sign = false;
1224 switch (dir.specifier)
1226 case 'd':
1227 case 'i':
1228 /* Space and '+' are only meaningful for signed conversions. */
1229 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1230 sign = true;
1231 base = 10;
1232 break;
1233 case 'u':
1234 base = 10;
1235 break;
1236 case 'o':
1237 base = 8;
1238 break;
1239 case 'X':
1240 case 'x':
1241 base = 16;
1242 break;
1243 default:
1244 gcc_unreachable ();
1247 /* The type of the "formal" argument expected by the directive. */
1248 tree dirtype = NULL_TREE;
1250 /* Determine the expected type of the argument from the length
1251 modifier. */
1252 switch (dir.modifier)
1254 case FMT_LEN_none:
1255 if (dir.specifier == 'p')
1256 dirtype = ptr_type_node;
1257 else
1258 dirtype = sign ? integer_type_node : unsigned_type_node;
1259 break;
1261 case FMT_LEN_h:
1262 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1263 break;
1265 case FMT_LEN_hh:
1266 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1267 break;
1269 case FMT_LEN_l:
1270 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1271 break;
1273 case FMT_LEN_L:
1274 case FMT_LEN_ll:
1275 dirtype = (sign
1276 ? long_long_integer_type_node
1277 : long_long_unsigned_type_node);
1278 break;
1280 case FMT_LEN_z:
1281 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1282 break;
1284 case FMT_LEN_t:
1285 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1286 break;
1288 case FMT_LEN_j:
1289 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1290 dirtype = sign ? intmax_type_node : uintmax_type_node;
1291 break;
1293 default:
1294 return fmtresult ();
1297 /* The type of the argument to the directive, either deduced from
1298 the actual non-constant argument if one is known, or from
1299 the directive itself when none has been provided because it's
1300 a va_list. */
1301 tree argtype = NULL_TREE;
1303 if (!arg)
1305 /* When the argument has not been provided, use the type of
1306 the directive's argument as an approximation. This will
1307 result in false positives for directives like %i with
1308 arguments with smaller precision (such as short or char). */
1309 argtype = dirtype;
1311 else if (TREE_CODE (arg) == INTEGER_CST)
1313 /* When a constant argument has been provided use its value
1314 rather than type to determine the length of the output. */
1315 fmtresult res;
1317 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1319 /* As a special case, a precision of zero with a zero argument
1320 results in zero bytes except in base 8 when the '#' flag is
1321 specified, and for signed conversions in base 8 and 10 when
1322 either the space or '+' flag has been specified and it results
1323 in just one byte (with width having the normal effect). This
1324 must extend to the case of a specified precision with
1325 an unknown value because it can be zero. */
1326 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1327 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1329 res.range.max = 1;
1330 res.range.likely = 1;
1332 else
1334 res.range.max = res.range.min;
1335 res.range.likely = res.range.min;
1338 else
1340 /* Convert the argument to the type of the directive. */
1341 arg = fold_convert (dirtype, arg);
1343 res.range.min = tree_digits (arg, base, dir.prec[0],
1344 maybesign, maybebase);
1345 if (dir.prec[0] == dir.prec[1])
1346 res.range.max = res.range.min;
1347 else
1348 res.range.max = tree_digits (arg, base, dir.prec[1],
1349 maybesign, maybebase);
1350 res.range.likely = res.range.min;
1351 res.knownrange = true;
1354 res.range.unlikely = res.range.max;
1356 /* Bump up the counters if WIDTH is greater than LEN. */
1357 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1358 (sign | maybebase) + (base == 16));
1359 /* Bump up the counters again if PRECision is greater still. */
1360 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1361 (sign | maybebase) + (base == 16));
1363 return res;
1365 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1366 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1367 /* Determine the type of the provided non-constant argument. */
1368 argtype = TREE_TYPE (arg);
1369 else
1370 /* Don't bother with invalid arguments since they likely would
1371 have already been diagnosed, and disable any further checking
1372 of the format string by returning [-1, -1]. */
1373 return fmtresult ();
1375 fmtresult res;
1377 /* Using either the range the non-constant argument is in, or its
1378 type (either "formal" or actual), create a range of values that
1379 constrain the length of output given the warning level. */
1380 tree argmin = NULL_TREE;
1381 tree argmax = NULL_TREE;
1383 if (arg
1384 && TREE_CODE (arg) == SSA_NAME
1385 && INTEGRAL_TYPE_P (argtype))
1387 /* Try to determine the range of values of the integer argument
1388 (range information is not available for pointers). */
1389 const value_range *vr = vr_values->get_value_range (arg);
1390 if (range_int_cst_p (vr))
1392 argmin = vr->min ();
1393 argmax = vr->max ();
1395 /* Set KNOWNRANGE if the argument is in a known subrange
1396 of the directive's type and neither width nor precision
1397 is unknown. (KNOWNRANGE may be reset below). */
1398 res.knownrange
1399 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1400 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1401 && dir.known_width_and_precision ());
1403 res.argmin = argmin;
1404 res.argmax = argmax;
1406 else if (vr->kind () == VR_ANTI_RANGE)
1408 /* Handle anti-ranges if/when bug 71690 is resolved. */
1410 else if (vr->varying_p () || vr->undefined_p ())
1412 /* The argument here may be the result of promoting the actual
1413 argument to int. Try to determine the type of the actual
1414 argument before promotion and narrow down its range that
1415 way. */
1416 gimple *def = SSA_NAME_DEF_STMT (arg);
1417 if (is_gimple_assign (def))
1419 tree_code code = gimple_assign_rhs_code (def);
1420 if (code == INTEGER_CST)
1422 arg = gimple_assign_rhs1 (def);
1423 return format_integer (dir, arg, vr_values);
1426 if (code == NOP_EXPR)
1428 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1429 if (INTEGRAL_TYPE_P (type)
1430 || TREE_CODE (type) == POINTER_TYPE)
1431 argtype = type;
1437 if (!argmin)
1439 if (TREE_CODE (argtype) == POINTER_TYPE)
1441 argmin = build_int_cst (pointer_sized_int_node, 0);
1442 argmax = build_all_ones_cst (pointer_sized_int_node);
1444 else
1446 argmin = TYPE_MIN_VALUE (argtype);
1447 argmax = TYPE_MAX_VALUE (argtype);
1451 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1452 of the directive. If it has been cleared then since ARGMIN and/or
1453 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1454 ARGMAX in the result to include in diagnostics. */
1455 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1457 res.knownrange = false;
1458 res.argmin = argmin;
1459 res.argmax = argmax;
1462 /* Recursively compute the minimum and maximum from the known range. */
1463 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1465 /* For unsigned conversions/directives or signed when
1466 the minimum is positive, use the minimum and maximum to compute
1467 the shortest and longest output, respectively. */
1468 res.range.min = format_integer (dir, argmin, vr_values).range.min;
1469 res.range.max = format_integer (dir, argmax, vr_values).range.max;
1471 else if (tree_int_cst_sgn (argmax) < 0)
1473 /* For signed conversions/directives if maximum is negative,
1474 use the minimum as the longest output and maximum as the
1475 shortest output. */
1476 res.range.min = format_integer (dir, argmax, vr_values).range.min;
1477 res.range.max = format_integer (dir, argmin, vr_values).range.max;
1479 else
1481 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1482 as the shortest output and for the longest output compute the
1483 length of the output of both minimum and maximum and pick the
1484 longer. */
1485 unsigned HOST_WIDE_INT max1
1486 = format_integer (dir, argmin, vr_values).range.max;
1487 unsigned HOST_WIDE_INT max2
1488 = format_integer (dir, argmax, vr_values).range.max;
1489 res.range.min
1490 = format_integer (dir, integer_zero_node, vr_values).range.min;
1491 res.range.max = MAX (max1, max2);
1494 /* If the range is known, use the maximum as the likely length. */
1495 if (res.knownrange)
1496 res.range.likely = res.range.max;
1497 else
1499 /* Otherwise, use the minimum. Except for the case where for %#x or
1500 %#o the minimum is just for a single value in the range (0) and
1501 for all other values it is something longer, like 0x1 or 01.
1502 Use the length for value 1 in that case instead as the likely
1503 length. */
1504 res.range.likely = res.range.min;
1505 if (maybebase
1506 && base != 10
1507 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1509 if (res.range.min == 1)
1510 res.range.likely += base == 8 ? 1 : 2;
1511 else if (res.range.min == 2
1512 && base == 16
1513 && (dir.width[0] == 2 || dir.prec[0] == 2))
1514 ++res.range.likely;
1518 res.range.unlikely = res.range.max;
1519 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1520 (sign | maybebase) + (base == 16));
1521 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1522 (sign | maybebase) + (base == 16));
1524 return res;
1527 /* Return the number of bytes that a format directive consisting of FLAGS,
1528 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1529 would result for argument X under ideal conditions (i.e., if PREC
1530 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1531 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1532 This function works around those problems. */
1534 static unsigned HOST_WIDE_INT
1535 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1536 char spec, char rndspec)
1538 char fmtstr[40];
1540 HOST_WIDE_INT len = strlen (flags);
1542 fmtstr[0] = '%';
1543 memcpy (fmtstr + 1, flags, len);
1544 memcpy (fmtstr + 1 + len, ".*R", 3);
1545 fmtstr[len + 4] = rndspec;
1546 fmtstr[len + 5] = spec;
1547 fmtstr[len + 6] = '\0';
1549 spec = TOUPPER (spec);
1550 if (spec == 'E' || spec == 'F')
1552 /* For %e, specify the precision explicitly since mpfr_sprintf
1553 does its own thing just to be different (see MPFR bug 21088). */
1554 if (prec < 0)
1555 prec = 6;
1557 else
1559 /* Avoid passing negative precisions with larger magnitude to MPFR
1560 to avoid exposing its bugs. (A negative precision is supposed
1561 to be ignored.) */
1562 if (prec < 0)
1563 prec = -1;
1566 HOST_WIDE_INT p = prec;
1568 if (spec == 'G' && !strchr (flags, '#'))
1570 /* For G/g without the pound flag, precision gives the maximum number
1571 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1572 a 128 bit IEEE extended precision, 4932. Using twice as much here
1573 should be more than sufficient for any real format. */
1574 if ((IEEE_MAX_10_EXP * 2) < prec)
1575 prec = IEEE_MAX_10_EXP * 2;
1576 p = prec;
1578 else
1580 /* Cap precision arbitrarily at 1KB and add the difference
1581 (if any) to the MPFR result. */
1582 if (prec > 1024)
1583 p = 1024;
1586 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1588 /* Handle the unlikely (impossible?) error by returning more than
1589 the maximum dictated by the function's return type. */
1590 if (len < 0)
1591 return target_dir_max () + 1;
1593 /* Adjust the return value by the difference. */
1594 if (p < prec)
1595 len += prec - p;
1597 return len;
1600 /* Return the number of bytes to format using the format specifier
1601 SPEC and the precision PREC the largest value in the real floating
1602 TYPE. */
1604 static unsigned HOST_WIDE_INT
1605 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1607 machine_mode mode = TYPE_MODE (type);
1609 /* IBM Extended mode. */
1610 if (MODE_COMPOSITE_P (mode))
1611 mode = DFmode;
1613 /* Get the real type format desription for the target. */
1614 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1615 REAL_VALUE_TYPE rv;
1617 real_maxval (&rv, 0, mode);
1619 /* Convert the GCC real value representation with the precision
1620 of the real type to the mpfr_t format with the GCC default
1621 round-to-nearest mode. */
1622 mpfr_t x;
1623 mpfr_init2 (x, rfmt->p);
1624 mpfr_from_real (x, &rv, GMP_RNDN);
1626 /* Return a value one greater to account for the leading minus sign. */
1627 unsigned HOST_WIDE_INT r
1628 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1629 mpfr_clear (x);
1630 return r;
1633 /* Return a range representing the minimum and maximum number of bytes
1634 that the directive DIR will output for any argument. PREC gives
1635 the adjusted precision range to account for negative precisions
1636 meaning the default 6. This function is used when the directive
1637 argument or its value isn't known. */
1639 static fmtresult
1640 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1642 tree type;
1644 switch (dir.modifier)
1646 case FMT_LEN_l:
1647 case FMT_LEN_none:
1648 type = double_type_node;
1649 break;
1651 case FMT_LEN_L:
1652 type = long_double_type_node;
1653 break;
1655 case FMT_LEN_ll:
1656 type = long_double_type_node;
1657 break;
1659 default:
1660 return fmtresult ();
1663 /* The minimum and maximum number of bytes produced by the directive. */
1664 fmtresult res;
1666 /* The minimum output as determined by flags. It's always at least 1.
1667 When plus or space are set the output is preceded by either a sign
1668 or a space. */
1669 unsigned flagmin = (1 /* for the first digit */
1670 + (dir.get_flag ('+') | dir.get_flag (' ')));
1672 /* The minimum is 3 for "inf" and "nan" for all specifiers, plus 1
1673 for the plus sign/space with the '+' and ' ' flags, respectively,
1674 unless reduced below. */
1675 res.range.min = 2 + flagmin;
1677 /* When the pound flag is set the decimal point is included in output
1678 regardless of precision. Whether or not a decimal point is included
1679 otherwise depends on the specification and precision. */
1680 bool radix = dir.get_flag ('#');
1682 switch (dir.specifier)
1684 case 'A':
1685 case 'a':
1687 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1688 if (dir.prec[0] <= 0)
1689 minprec = 0;
1690 else if (dir.prec[0] > 0)
1691 minprec = dir.prec[0] + !radix /* decimal point */;
1693 res.range.likely = (2 /* 0x */
1694 + flagmin
1695 + radix
1696 + minprec
1697 + 3 /* p+0 */);
1699 res.range.max = format_floating_max (type, 'a', prec[1]);
1701 /* The unlikely maximum accounts for the longest multibyte
1702 decimal point character. */
1703 res.range.unlikely = res.range.max;
1704 if (dir.prec[1] > 0)
1705 res.range.unlikely += target_mb_len_max () - 1;
1707 break;
1710 case 'E':
1711 case 'e':
1713 /* Minimum output attributable to precision and, when it's
1714 non-zero, decimal point. */
1715 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1717 /* The likely minimum output is "[-+]1.234567e+00" regardless
1718 of the value of the actual argument. */
1719 res.range.likely = (flagmin
1720 + radix
1721 + minprec
1722 + 2 /* e+ */ + 2);
1724 res.range.max = format_floating_max (type, 'e', prec[1]);
1726 /* The unlikely maximum accounts for the longest multibyte
1727 decimal point character. */
1728 if (dir.prec[0] != dir.prec[1]
1729 || dir.prec[0] == -1 || dir.prec[0] > 0)
1730 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1731 else
1732 res.range.unlikely = res.range.max;
1733 break;
1736 case 'F':
1737 case 'f':
1739 /* Minimum output attributable to precision and, when it's non-zero,
1740 decimal point. */
1741 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1743 /* For finite numbers (i.e., not infinity or NaN) the lower bound
1744 when precision isn't specified is 8 bytes ("1.23456" since
1745 precision is taken to be 6). When precision is zero, the lower
1746 bound is 1 byte (e.g., "1"). Otherwise, when precision is greater
1747 than zero, then the lower bound is 2 plus precision (plus flags).
1748 But in all cases, the lower bound is no greater than 3. */
1749 unsigned HOST_WIDE_INT min = flagmin + radix + minprec;
1750 if (min < res.range.min)
1751 res.range.min = min;
1753 /* Compute the upper bound for -TYPE_MAX. */
1754 res.range.max = format_floating_max (type, 'f', prec[1]);
1756 /* The minimum output with unknown precision is a single byte
1757 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1758 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1759 res.range.likely = 3;
1760 else
1761 res.range.likely = min;
1763 /* The unlikely maximum accounts for the longest multibyte
1764 decimal point character. */
1765 if (dir.prec[0] != dir.prec[1]
1766 || dir.prec[0] == -1 || dir.prec[0] > 0)
1767 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1768 break;
1771 case 'G':
1772 case 'g':
1774 /* The %g output depends on precision and the exponent of
1775 the argument. Since the value of the argument isn't known
1776 the lower bound on the range of bytes (not counting flags
1777 or width) is 1 plus radix (i.e., either "0" or "0." for
1778 "%g" and "%#g", respectively, with a zero argument). */
1779 unsigned HOST_WIDE_INT min = flagmin + radix;
1780 if (min < res.range.min)
1781 res.range.min = min;
1783 char spec = 'g';
1784 HOST_WIDE_INT maxprec = dir.prec[1];
1785 if (radix && maxprec)
1787 /* When the pound flag (radix) is set, trailing zeros aren't
1788 trimmed and so the longest output is the same as for %e,
1789 except with precision minus 1 (as specified in C11). */
1790 spec = 'e';
1791 if (maxprec > 0)
1792 --maxprec;
1793 else if (maxprec < 0)
1794 maxprec = 5;
1796 else
1797 maxprec = prec[1];
1799 res.range.max = format_floating_max (type, spec, maxprec);
1801 /* The likely output is either the maximum computed above
1802 minus 1 (assuming the maximum is positive) when precision
1803 is known (or unspecified), or the same minimum as for %e
1804 (which is computed for a non-negative argument). Unlike
1805 for the other specifiers above the likely output isn't
1806 the minimum because for %g that's 1 which is unlikely. */
1807 if (dir.prec[1] < 0
1808 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1809 res.range.likely = res.range.max - 1;
1810 else
1812 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1813 res.range.likely = (flagmin
1814 + radix
1815 + minprec
1816 + 2 /* e+ */ + 2);
1819 /* The unlikely maximum accounts for the longest multibyte
1820 decimal point character. */
1821 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1822 break;
1825 default:
1826 return fmtresult ();
1829 /* Bump up the byte counters if WIDTH is greater. */
1830 res.adjust_for_width_or_precision (dir.width);
1831 return res;
1834 /* Return a range representing the minimum and maximum number of bytes
1835 that the directive DIR will write on output for the floating argument
1836 ARG. */
1838 static fmtresult
1839 format_floating (const directive &dir, tree arg, vr_values *)
1841 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1842 tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1843 ? long_double_type_node : double_type_node);
1845 /* For an indeterminate precision the lower bound must be assumed
1846 to be zero. */
1847 if (TOUPPER (dir.specifier) == 'A')
1849 /* Get the number of fractional decimal digits needed to represent
1850 the argument without a loss of accuracy. */
1851 unsigned fmtprec
1852 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1854 /* The precision of the IEEE 754 double format is 53.
1855 The precision of all other GCC binary double formats
1856 is 56 or less. */
1857 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1859 /* For %a, leave the minimum precision unspecified to let
1860 MFPR trim trailing zeros (as it and many other systems
1861 including Glibc happen to do) and set the maximum
1862 precision to reflect what it would be with trailing zeros
1863 present (as Solaris and derived systems do). */
1864 if (dir.prec[1] < 0)
1866 /* Both bounds are negative implies that precision has
1867 not been specified. */
1868 prec[0] = maxprec;
1869 prec[1] = -1;
1871 else if (dir.prec[0] < 0)
1873 /* With a negative lower bound and a non-negative upper
1874 bound set the minimum precision to zero and the maximum
1875 to the greater of the maximum precision (i.e., with
1876 trailing zeros present) and the specified upper bound. */
1877 prec[0] = 0;
1878 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1881 else if (dir.prec[0] < 0)
1883 if (dir.prec[1] < 0)
1885 /* A precision in a strictly negative range is ignored and
1886 the default of 6 is used instead. */
1887 prec[0] = prec[1] = 6;
1889 else
1891 /* For a precision in a partly negative range, the lower bound
1892 must be assumed to be zero and the new upper bound is the
1893 greater of 6 (the default precision used when the specified
1894 precision is negative) and the upper bound of the specified
1895 range. */
1896 prec[0] = 0;
1897 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1901 if (!arg
1902 || TREE_CODE (arg) != REAL_CST
1903 || !useless_type_conversion_p (type, TREE_TYPE (arg)))
1904 return format_floating (dir, prec);
1906 /* The minimum and maximum number of bytes produced by the directive. */
1907 fmtresult res;
1909 /* Get the real type format desription for the target. */
1910 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1911 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1913 if (!real_isfinite (rvp))
1915 /* The format for Infinity and NaN is "[-]inf"/"[-]infinity"
1916 and "[-]nan" with the choice being implementation-defined
1917 but not locale dependent. */
1918 bool sign = dir.get_flag ('+') || real_isneg (rvp);
1919 res.range.min = 3 + sign;
1921 res.range.likely = res.range.min;
1922 res.range.max = res.range.min;
1923 /* The unlikely maximum is "[-/+]infinity" or "[-/+][qs]nan".
1924 For NaN, the C/POSIX standards specify two formats:
1925 "[-/+]nan"
1927 "[-/+]nan(n-char-sequence)"
1928 No known printf implementation outputs the latter format but AIX
1929 outputs QNaN and SNaN for quiet and signalling NaN, respectively,
1930 so the unlikely maximum reflects that. */
1931 res.range.unlikely = sign + (real_isinf (rvp) ? 8 : 4);
1933 /* The range for infinity and NaN is known unless either width
1934 or precision is unknown. Width has the same effect regardless
1935 of whether the argument is finite. Precision is either ignored
1936 (e.g., Glibc) or can have an effect on the short vs long format
1937 such as inf/infinity (e.g., Solaris). */
1938 res.knownrange = dir.known_width_and_precision ();
1940 /* Adjust the range for width but ignore precision. */
1941 res.adjust_for_width_or_precision (dir.width);
1943 return res;
1946 char fmtstr [40];
1947 char *pfmt = fmtstr;
1949 /* Append flags. */
1950 for (const char *pf = "-+ #0"; *pf; ++pf)
1951 if (dir.get_flag (*pf))
1952 *pfmt++ = *pf;
1954 *pfmt = '\0';
1957 /* Set up an array to easily iterate over. */
1958 unsigned HOST_WIDE_INT* const minmax[] = {
1959 &res.range.min, &res.range.max
1962 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1964 /* Convert the GCC real value representation with the precision
1965 of the real type to the mpfr_t format rounding down in the
1966 first iteration that computes the minimm and up in the second
1967 that computes the maximum. This order is arbibtrary because
1968 rounding in either direction can result in longer output. */
1969 mpfr_t mpfrval;
1970 mpfr_init2 (mpfrval, rfmt->p);
1971 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1973 /* Use the MPFR rounding specifier to round down in the first
1974 iteration and then up. In most but not all cases this will
1975 result in the same number of bytes. */
1976 char rndspec = "DU"[i];
1978 /* Format it and store the result in the corresponding member
1979 of the result struct. */
1980 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1981 dir.specifier, rndspec);
1982 mpfr_clear (mpfrval);
1986 /* Make sure the minimum is less than the maximum (MPFR rounding
1987 in the call to mpfr_snprintf can result in the reverse. */
1988 if (res.range.max < res.range.min)
1990 unsigned HOST_WIDE_INT tmp = res.range.min;
1991 res.range.min = res.range.max;
1992 res.range.max = tmp;
1995 /* The range is known unless either width or precision is unknown. */
1996 res.knownrange = dir.known_width_and_precision ();
1998 /* For the same floating point constant, unless width or precision
1999 is unknown, use the longer output as the likely maximum since
2000 with round to nearest either is equally likely. Otheriwse, when
2001 precision is unknown, use the greater of the minimum and 3 as
2002 the likely output (for "0.0" since zero precision is unlikely). */
2003 if (res.knownrange)
2004 res.range.likely = res.range.max;
2005 else if (res.range.min < 3
2006 && dir.prec[0] < 0
2007 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
2008 res.range.likely = 3;
2009 else
2010 res.range.likely = res.range.min;
2012 res.range.unlikely = res.range.max;
2014 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
2016 /* Unless the precision is zero output longer than 2 bytes may
2017 include the decimal point which must be a single character
2018 up to MB_LEN_MAX in length. This is overly conservative
2019 since in some conversions some constants result in no decimal
2020 point (e.g., in %g). */
2021 res.range.unlikely += target_mb_len_max () - 1;
2024 res.adjust_for_width_or_precision (dir.width);
2025 return res;
2028 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
2029 strings referenced by the expression STR, or (-1, -1) when not known.
2030 Used by the format_string function below. */
2032 static fmtresult
2033 get_string_length (tree str, unsigned eltsize)
2035 if (!str)
2036 return fmtresult ();
2038 /* Determine the length of the shortest and longest string referenced
2039 by STR. Strings of unknown lengths are bounded by the sizes of
2040 arrays that subexpressions of STR may refer to. Pointers that
2041 aren't known to point any such arrays result in LENDATA.MAXLEN
2042 set to SIZE_MAX. */
2043 c_strlen_data lendata = { };
2044 get_range_strlen (str, &lendata, eltsize);
2046 /* Return the default result when nothing is known about the string. */
2047 if (integer_all_onesp (lendata.maxbound)
2048 && integer_all_onesp (lendata.maxlen))
2049 return fmtresult ();
2051 HOST_WIDE_INT min
2052 = (tree_fits_uhwi_p (lendata.minlen)
2053 ? tree_to_uhwi (lendata.minlen)
2054 : 0);
2056 HOST_WIDE_INT max
2057 = (tree_fits_uhwi_p (lendata.maxbound)
2058 ? tree_to_uhwi (lendata.maxbound)
2059 : HOST_WIDE_INT_M1U);
2061 const bool unbounded = integer_all_onesp (lendata.maxlen);
2063 /* Set the max/likely counters to unbounded when a minimum is known
2064 but the maximum length isn't bounded. This implies that STR is
2065 a conditional expression involving a string of known length and
2066 and an expression of unknown/unbounded length. */
2067 if (min
2068 && (unsigned HOST_WIDE_INT)min < HOST_WIDE_INT_M1U
2069 && unbounded)
2070 max = HOST_WIDE_INT_M1U;
2072 /* get_range_strlen() returns the target value of SIZE_MAX for
2073 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2074 which may be bigger. */
2075 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2076 min = HOST_WIDE_INT_M1U;
2077 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2078 max = HOST_WIDE_INT_M1U;
2080 fmtresult res (min, max);
2081 res.nonstr = lendata.decl;
2083 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2084 by STR are known to be bounded (though not necessarily by their
2085 actual length but perhaps by their maximum possible length). */
2086 if (res.range.max < target_int_max ())
2088 res.knownrange = true;
2089 /* When the the length of the longest string is known and not
2090 excessive use it as the likely length of the string(s). */
2091 res.range.likely = res.range.max;
2093 else
2095 /* When the upper bound is unknown (it can be zero or excessive)
2096 set the likely length to the greater of 1 and the length of
2097 the shortest string and reset the lower bound to zero. */
2098 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2099 res.range.min = 0;
2102 res.range.unlikely = unbounded ? HOST_WIDE_INT_MAX : res.range.max;
2104 return res;
2107 /* Return the minimum and maximum number of characters formatted
2108 by the '%c' format directives and its wide character form for
2109 the argument ARG. ARG can be null (for functions such as
2110 vsprinf). */
2112 static fmtresult
2113 format_character (const directive &dir, tree arg, vr_values *vr_values)
2115 fmtresult res;
2117 res.knownrange = true;
2119 if (dir.specifier == 'C'
2120 || dir.modifier == FMT_LEN_l)
2122 /* A wide character can result in as few as zero bytes. */
2123 res.range.min = 0;
2125 HOST_WIDE_INT min, max;
2126 if (get_int_range (arg, &min, &max, false, 0, vr_values))
2128 if (min == 0 && max == 0)
2130 /* The NUL wide character results in no bytes. */
2131 res.range.max = 0;
2132 res.range.likely = 0;
2133 res.range.unlikely = 0;
2135 else if (min >= 0 && min < 128)
2137 /* Be conservative if the target execution character set
2138 is not a 1-to-1 mapping to the source character set or
2139 if the source set is not ASCII. */
2140 bool one_2_one_ascii
2141 = (target_to_host_charmap[0] == 1 && target_to_host ('a') == 97);
2143 /* A wide character in the ASCII range most likely results
2144 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2145 res.range.max = one_2_one_ascii ? 1 : target_mb_len_max ();;
2146 res.range.likely = 1;
2147 res.range.unlikely = target_mb_len_max ();
2148 res.mayfail = !one_2_one_ascii;
2150 else
2152 /* A wide character outside the ASCII range likely results
2153 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2154 res.range.max = target_mb_len_max ();
2155 res.range.likely = 2;
2156 res.range.unlikely = res.range.max;
2157 /* Converting such a character may fail. */
2158 res.mayfail = true;
2161 else
2163 /* An unknown wide character is treated the same as a wide
2164 character outside the ASCII range. */
2165 res.range.max = target_mb_len_max ();
2166 res.range.likely = 2;
2167 res.range.unlikely = res.range.max;
2168 res.mayfail = true;
2171 else
2173 /* A plain '%c' directive. Its ouput is exactly 1. */
2174 res.range.min = res.range.max = 1;
2175 res.range.likely = res.range.unlikely = 1;
2176 res.knownrange = true;
2179 /* Bump up the byte counters if WIDTH is greater. */
2180 return res.adjust_for_width_or_precision (dir.width);
2183 /* Return the minimum and maximum number of characters formatted
2184 by the '%s' format directive and its wide character form for
2185 the argument ARG. ARG can be null (for functions such as
2186 vsprinf). */
2188 static fmtresult
2189 format_string (const directive &dir, tree arg, vr_values *)
2191 fmtresult res;
2193 /* Compute the range the argument's length can be in. */
2194 int count_by = 1;
2195 if (dir.specifier == 'S' || dir.modifier == FMT_LEN_l)
2197 /* Get a node for a C type that will be the same size
2198 as a wchar_t on the target. */
2199 tree node = get_typenode_from_name (MODIFIED_WCHAR_TYPE);
2201 /* Now that we have a suitable node, get the number of
2202 bytes it occupies. */
2203 count_by = int_size_in_bytes (node);
2204 gcc_checking_assert (count_by == 2 || count_by == 4);
2207 fmtresult slen = get_string_length (arg, count_by);
2208 if (slen.range.min == slen.range.max
2209 && slen.range.min < HOST_WIDE_INT_MAX)
2211 /* The argument is either a string constant or it refers
2212 to one of a number of strings of the same length. */
2214 /* A '%s' directive with a string argument with constant length. */
2215 res.range = slen.range;
2217 if (dir.specifier == 'S'
2218 || dir.modifier == FMT_LEN_l)
2220 /* In the worst case the length of output of a wide string S
2221 is bounded by MB_LEN_MAX * wcslen (S). */
2222 res.range.max *= target_mb_len_max ();
2223 res.range.unlikely = res.range.max;
2224 /* It's likely that the the total length is not more that
2225 2 * wcslen (S).*/
2226 res.range.likely = res.range.min * 2;
2228 if (dir.prec[1] >= 0
2229 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2231 res.range.max = dir.prec[1];
2232 res.range.likely = dir.prec[1];
2233 res.range.unlikely = dir.prec[1];
2236 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2237 res.range.min = 0;
2238 else if (dir.prec[0] >= 0)
2239 res.range.likely = dir.prec[0];
2241 /* Even a non-empty wide character string need not convert into
2242 any bytes. */
2243 res.range.min = 0;
2245 /* A non-empty wide character conversion may fail. */
2246 if (slen.range.max > 0)
2247 res.mayfail = true;
2249 else
2251 res.knownrange = true;
2253 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2254 res.range.min = 0;
2255 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2256 res.range.min = dir.prec[0];
2258 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2260 res.range.max = dir.prec[1];
2261 res.range.likely = dir.prec[1];
2262 res.range.unlikely = dir.prec[1];
2266 else if (arg && integer_zerop (arg))
2268 /* Handle null pointer argument. */
2270 fmtresult res (0);
2271 res.nullp = true;
2272 return res;
2274 else
2276 /* For a '%s' and '%ls' directive with a non-constant string (either
2277 one of a number of strings of known length or an unknown string)
2278 the minimum number of characters is lesser of PRECISION[0] and
2279 the length of the shortest known string or zero, and the maximum
2280 is the lessser of the length of the longest known string or
2281 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2282 the minimum at level 1 and the greater of the minimum and 1
2283 at level 2. This result is adjust upward for width (if it's
2284 specified). */
2286 if (dir.specifier == 'S'
2287 || dir.modifier == FMT_LEN_l)
2289 /* A wide character converts to as few as zero bytes. */
2290 slen.range.min = 0;
2291 if (slen.range.max < target_int_max ())
2292 slen.range.max *= target_mb_len_max ();
2294 if (slen.range.likely < target_int_max ())
2295 slen.range.likely *= 2;
2297 if (slen.range.likely < target_int_max ())
2298 slen.range.unlikely *= target_mb_len_max ();
2300 /* A non-empty wide character conversion may fail. */
2301 if (slen.range.max > 0)
2302 res.mayfail = true;
2305 res.range = slen.range;
2307 if (dir.prec[0] >= 0)
2309 /* Adjust the minimum to zero if the string length is unknown,
2310 or at most the lower bound of the precision otherwise. */
2311 if (slen.range.min >= target_int_max ())
2312 res.range.min = 0;
2313 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2314 res.range.min = dir.prec[0];
2316 /* Make both maxima no greater than the upper bound of precision. */
2317 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2318 || slen.range.max >= target_int_max ())
2320 res.range.max = dir.prec[1];
2321 res.range.unlikely = dir.prec[1];
2324 /* If precision is constant, set the likely counter to the lesser
2325 of it and the maximum string length. Otherwise, if the lower
2326 bound of precision is greater than zero, set the likely counter
2327 to the minimum. Otherwise set it to zero or one based on
2328 the warning level. */
2329 if (dir.prec[0] == dir.prec[1])
2330 res.range.likely
2331 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2332 ? dir.prec[0] : slen.range.max);
2333 else if (dir.prec[0] > 0)
2334 res.range.likely = res.range.min;
2335 else
2336 res.range.likely = warn_level > 1;
2338 else if (dir.prec[1] >= 0)
2340 res.range.min = 0;
2341 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2342 res.range.max = dir.prec[1];
2343 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2344 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.unlikely)
2345 res.range.unlikely = dir.prec[1];
2347 else if (slen.range.min >= target_int_max ())
2349 res.range.min = 0;
2350 res.range.max = HOST_WIDE_INT_MAX;
2351 /* At level 1 strings of unknown length are assumed to be
2352 empty, while at level 1 they are assumed to be one byte
2353 long. */
2354 res.range.likely = warn_level > 1;
2355 res.range.unlikely = HOST_WIDE_INT_MAX;
2357 else
2359 /* A string of unknown length unconstrained by precision is
2360 assumed to be empty at level 1 and just one character long
2361 at higher levels. */
2362 if (res.range.likely >= target_int_max ())
2363 res.range.likely = warn_level > 1;
2367 /* If the argument isn't a nul-terminated string and the number
2368 of bytes on output isn't bounded by precision, set NONSTR. */
2369 if (slen.nonstr && slen.range.min < (unsigned HOST_WIDE_INT)dir.prec[0])
2370 res.nonstr = slen.nonstr;
2372 /* Bump up the byte counters if WIDTH is greater. */
2373 return res.adjust_for_width_or_precision (dir.width);
2376 /* Format plain string (part of the format string itself). */
2378 static fmtresult
2379 format_plain (const directive &dir, tree, vr_values *)
2381 fmtresult res (dir.len);
2382 return res;
2385 /* Return true if the RESULT of a directive in a call describe by INFO
2386 should be diagnosed given the AVAILable space in the destination. */
2388 static bool
2389 should_warn_p (const sprintf_dom_walker::call_info &info,
2390 const result_range &avail, const result_range &result)
2392 if (result.max <= avail.min)
2394 /* The least amount of space remaining in the destination is big
2395 enough for the longest output. */
2396 return false;
2399 if (info.bounded)
2401 if (warn_format_trunc == 1 && result.min <= avail.max
2402 && info.retval_used ())
2404 /* The likely amount of space remaining in the destination is big
2405 enough for the least output and the return value is used. */
2406 return false;
2409 if (warn_format_trunc == 1 && result.likely <= avail.likely
2410 && !info.retval_used ())
2412 /* The likely amount of space remaining in the destination is big
2413 enough for the likely output and the return value is unused. */
2414 return false;
2417 if (warn_format_trunc == 2
2418 && result.likely <= avail.min
2419 && (result.max <= avail.min
2420 || result.max > HOST_WIDE_INT_MAX))
2422 /* The minimum amount of space remaining in the destination is big
2423 enough for the longest output. */
2424 return false;
2427 else
2429 if (warn_level == 1 && result.likely <= avail.likely)
2431 /* The likely amount of space remaining in the destination is big
2432 enough for the likely output. */
2433 return false;
2436 if (warn_level == 2
2437 && result.likely <= avail.min
2438 && (result.max <= avail.min
2439 || result.max > HOST_WIDE_INT_MAX))
2441 /* The minimum amount of space remaining in the destination is big
2442 enough for the longest output. */
2443 return false;
2447 return true;
2450 /* At format string location describe by DIRLOC in a call described
2451 by INFO, issue a warning for a directive DIR whose output may be
2452 in excess of the available space AVAIL_RANGE in the destination
2453 given the formatting result FMTRES. This function does nothing
2454 except decide whether to issue a warning for a possible write
2455 past the end or truncation and, if so, format the warning.
2456 Return true if a warning has been issued. */
2458 static bool
2459 maybe_warn (substring_loc &dirloc, location_t argloc,
2460 const sprintf_dom_walker::call_info &info,
2461 const result_range &avail_range, const result_range &res,
2462 const directive &dir)
2464 if (!should_warn_p (info, avail_range, res))
2465 return false;
2467 /* A warning will definitely be issued below. */
2469 /* The maximum byte count to reference in the warning. Larger counts
2470 imply that the upper bound is unknown (and could be anywhere between
2471 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2472 than "between N and X" where X is some huge number. */
2473 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2475 /* True when there is enough room in the destination for the least
2476 amount of a directive's output but not enough for its likely or
2477 maximum output. */
2478 bool maybe = (res.min <= avail_range.max
2479 && (avail_range.min < res.likely
2480 || (res.max < HOST_WIDE_INT_MAX
2481 && avail_range.min < res.max)));
2483 /* Buffer for the directive in the host character set (used when
2484 the source character set is different). */
2485 char hostdir[32];
2487 if (avail_range.min == avail_range.max)
2489 /* The size of the destination region is exact. */
2490 unsigned HOST_WIDE_INT navail = avail_range.max;
2492 if (target_to_host (*dir.beg) != '%')
2494 /* For plain character directives (i.e., the format string itself)
2495 but not others, point the caret at the first character that's
2496 past the end of the destination. */
2497 if (navail < dir.len)
2498 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2501 if (*dir.beg == '\0')
2503 /* This is the terminating nul. */
2504 gcc_assert (res.min == 1 && res.min == res.max);
2506 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2507 info.bounded
2508 ? (maybe
2509 ? G_("%qE output may be truncated before the "
2510 "last format character")
2511 : G_("%qE output truncated before the last "
2512 "format character"))
2513 : (maybe
2514 ? G_("%qE may write a terminating nul past the "
2515 "end of the destination")
2516 : G_("%qE writing a terminating nul past the "
2517 "end of the destination")),
2518 info.func);
2521 if (res.min == res.max)
2523 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2524 if (!info.bounded)
2525 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2526 "%<%.*s%> directive writing %wu byte into a "
2527 "region of size %wu",
2528 "%<%.*s%> directive writing %wu bytes into a "
2529 "region of size %wu",
2530 (int) dir.len, d, res.min, navail);
2531 else if (maybe)
2532 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2533 "%<%.*s%> directive output may be truncated "
2534 "writing %wu byte into a region of size %wu",
2535 "%<%.*s%> directive output may be truncated "
2536 "writing %wu bytes into a region of size %wu",
2537 (int) dir.len, d, res.min, navail);
2538 else
2539 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2540 "%<%.*s%> directive output truncated writing "
2541 "%wu byte into a region of size %wu",
2542 "%<%.*s%> directive output truncated writing "
2543 "%wu bytes into a region of size %wu",
2544 (int) dir.len, d, res.min, navail);
2546 if (res.min == 0 && res.max < maxbytes)
2547 return fmtwarn (dirloc, argloc, NULL,
2548 info.warnopt (),
2549 info.bounded
2550 ? (maybe
2551 ? G_("%<%.*s%> directive output may be truncated "
2552 "writing up to %wu bytes into a region of "
2553 "size %wu")
2554 : G_("%<%.*s%> directive output truncated writing "
2555 "up to %wu bytes into a region of size %wu"))
2556 : G_("%<%.*s%> directive writing up to %wu bytes "
2557 "into a region of size %wu"), (int) dir.len,
2558 target_to_host (hostdir, sizeof hostdir, dir.beg),
2559 res.max, navail);
2561 if (res.min == 0 && maxbytes <= res.max)
2562 /* This is a special case to avoid issuing the potentially
2563 confusing warning:
2564 writing 0 or more bytes into a region of size 0. */
2565 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2566 info.bounded
2567 ? (maybe
2568 ? G_("%<%.*s%> directive output may be truncated "
2569 "writing likely %wu or more bytes into a "
2570 "region of size %wu")
2571 : G_("%<%.*s%> directive output truncated writing "
2572 "likely %wu or more bytes into a region of "
2573 "size %wu"))
2574 : G_("%<%.*s%> directive writing likely %wu or more "
2575 "bytes into a region of size %wu"), (int) dir.len,
2576 target_to_host (hostdir, sizeof hostdir, dir.beg),
2577 res.likely, navail);
2579 if (res.max < maxbytes)
2580 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2581 info.bounded
2582 ? (maybe
2583 ? G_("%<%.*s%> directive output may be truncated "
2584 "writing between %wu and %wu bytes into a "
2585 "region of size %wu")
2586 : G_("%<%.*s%> directive output truncated "
2587 "writing between %wu and %wu bytes into a "
2588 "region of size %wu"))
2589 : G_("%<%.*s%> directive writing between %wu and "
2590 "%wu bytes into a region of size %wu"),
2591 (int) dir.len,
2592 target_to_host (hostdir, sizeof hostdir, dir.beg),
2593 res.min, res.max, navail);
2595 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2596 info.bounded
2597 ? (maybe
2598 ? G_("%<%.*s%> directive output may be truncated "
2599 "writing %wu or more bytes into a region of "
2600 "size %wu")
2601 : G_("%<%.*s%> directive output truncated writing "
2602 "%wu or more bytes into a region of size %wu"))
2603 : G_("%<%.*s%> directive writing %wu or more bytes "
2604 "into a region of size %wu"), (int) dir.len,
2605 target_to_host (hostdir, sizeof hostdir, dir.beg),
2606 res.min, navail);
2609 /* The size of the destination region is a range. */
2611 if (target_to_host (*dir.beg) != '%')
2613 unsigned HOST_WIDE_INT navail = avail_range.max;
2615 /* For plain character directives (i.e., the format string itself)
2616 but not others, point the caret at the first character that's
2617 past the end of the destination. */
2618 if (navail < dir.len)
2619 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2622 if (*dir.beg == '\0')
2624 gcc_assert (res.min == 1 && res.min == res.max);
2626 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2627 info.bounded
2628 ? (maybe
2629 ? G_("%qE output may be truncated before the last "
2630 "format character")
2631 : G_("%qE output truncated before the last format "
2632 "character"))
2633 : (maybe
2634 ? G_("%qE may write a terminating nul past the end "
2635 "of the destination")
2636 : G_("%qE writing a terminating nul past the end "
2637 "of the destination")), info.func);
2640 if (res.min == res.max)
2642 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2643 if (!info.bounded)
2644 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2645 "%<%.*s%> directive writing %wu byte into a region "
2646 "of size between %wu and %wu",
2647 "%<%.*s%> directive writing %wu bytes into a region "
2648 "of size between %wu and %wu", (int) dir.len, d,
2649 res.min, avail_range.min, avail_range.max);
2650 else if (maybe)
2651 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2652 "%<%.*s%> directive output may be truncated writing "
2653 "%wu byte into a region of size between %wu and %wu",
2654 "%<%.*s%> directive output may be truncated writing "
2655 "%wu bytes into a region of size between %wu and "
2656 "%wu", (int) dir.len, d, res.min, avail_range.min,
2657 avail_range.max);
2658 else
2659 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2660 "%<%.*s%> directive output truncated writing %wu "
2661 "byte into a region of size between %wu and %wu",
2662 "%<%.*s%> directive output truncated writing %wu "
2663 "bytes into a region of size between %wu and %wu",
2664 (int) dir.len, d, res.min, avail_range.min,
2665 avail_range.max);
2668 if (res.min == 0 && res.max < maxbytes)
2669 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2670 info.bounded
2671 ? (maybe
2672 ? G_("%<%.*s%> directive output may be truncated "
2673 "writing up to %wu bytes into a region of size "
2674 "between %wu and %wu")
2675 : G_("%<%.*s%> directive output truncated writing "
2676 "up to %wu bytes into a region of size between "
2677 "%wu and %wu"))
2678 : G_("%<%.*s%> directive writing up to %wu bytes "
2679 "into a region of size between %wu and %wu"),
2680 (int) dir.len,
2681 target_to_host (hostdir, sizeof hostdir, dir.beg),
2682 res.max, avail_range.min, avail_range.max);
2684 if (res.min == 0 && maxbytes <= res.max)
2685 /* This is a special case to avoid issuing the potentially confusing
2686 warning:
2687 writing 0 or more bytes into a region of size between 0 and N. */
2688 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2689 info.bounded
2690 ? (maybe
2691 ? G_("%<%.*s%> directive output may be truncated "
2692 "writing likely %wu or more bytes into a region "
2693 "of size between %wu and %wu")
2694 : G_("%<%.*s%> directive output truncated writing "
2695 "likely %wu or more bytes into a region of size "
2696 "between %wu and %wu"))
2697 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2698 "into a region of size between %wu and %wu"),
2699 (int) dir.len,
2700 target_to_host (hostdir, sizeof hostdir, dir.beg),
2701 res.likely, avail_range.min, avail_range.max);
2703 if (res.max < maxbytes)
2704 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2705 info.bounded
2706 ? (maybe
2707 ? G_("%<%.*s%> directive output may be truncated "
2708 "writing between %wu and %wu bytes into a region "
2709 "of size between %wu and %wu")
2710 : G_("%<%.*s%> directive output truncated writing "
2711 "between %wu and %wu bytes into a region of size "
2712 "between %wu and %wu"))
2713 : G_("%<%.*s%> directive writing between %wu and "
2714 "%wu bytes into a region of size between %wu and "
2715 "%wu"), (int) dir.len,
2716 target_to_host (hostdir, sizeof hostdir, dir.beg),
2717 res.min, res.max, avail_range.min, avail_range.max);
2719 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2720 info.bounded
2721 ? (maybe
2722 ? G_("%<%.*s%> directive output may be truncated writing "
2723 "%wu or more bytes into a region of size between "
2724 "%wu and %wu")
2725 : G_("%<%.*s%> directive output truncated writing "
2726 "%wu or more bytes into a region of size between "
2727 "%wu and %wu"))
2728 : G_("%<%.*s%> directive writing %wu or more bytes "
2729 "into a region of size between %wu and %wu"),
2730 (int) dir.len,
2731 target_to_host (hostdir, sizeof hostdir, dir.beg),
2732 res.min, avail_range.min, avail_range.max);
2735 /* Compute the length of the output resulting from the directive DIR
2736 in a call described by INFO and update the overall result of the call
2737 in *RES. Return true if the directive has been handled. */
2739 static bool
2740 format_directive (const sprintf_dom_walker::call_info &info,
2741 format_result *res, const directive &dir,
2742 class vr_values *vr_values)
2744 /* Offset of the beginning of the directive from the beginning
2745 of the format string. */
2746 size_t offset = dir.beg - info.fmtstr;
2747 size_t start = offset;
2748 size_t length = offset + dir.len - !!dir.len;
2750 /* Create a location for the whole directive from the % to the format
2751 specifier. */
2752 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2753 offset, start, length);
2755 /* Also get the location of the argument if possible.
2756 This doesn't work for integer literals or function calls. */
2757 location_t argloc = UNKNOWN_LOCATION;
2758 if (dir.arg)
2759 argloc = EXPR_LOCATION (dir.arg);
2761 /* Bail when there is no function to compute the output length,
2762 or when minimum length checking has been disabled. */
2763 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2764 return false;
2766 /* Compute the range of lengths of the formatted output. */
2767 fmtresult fmtres = dir.fmtfunc (dir, dir.arg, vr_values);
2769 /* Record whether the output of all directives is known to be
2770 bounded by some maximum, implying that their arguments are
2771 either known exactly or determined to be in a known range
2772 or, for strings, limited by the upper bounds of the arrays
2773 they refer to. */
2774 res->knownrange &= fmtres.knownrange;
2776 if (!fmtres.knownrange)
2778 /* Only when the range is known, check it against the host value
2779 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2780 INT_MAX precision, which is the longest possible output of any
2781 single directive). That's the largest valid byte count (though
2782 not valid call to a printf-like function because it can never
2783 return such a count). Otherwise, the range doesn't correspond
2784 to known values of the argument. */
2785 if (fmtres.range.max > target_dir_max ())
2787 /* Normalize the MAX counter to avoid having to deal with it
2788 later. The counter can be less than HOST_WIDE_INT_M1U
2789 when compiling for an ILP32 target on an LP64 host. */
2790 fmtres.range.max = HOST_WIDE_INT_M1U;
2791 /* Disable exact and maximum length checking after a failure
2792 to determine the maximum number of characters (for example
2793 for wide characters or wide character strings) but continue
2794 tracking the minimum number of characters. */
2795 res->range.max = HOST_WIDE_INT_M1U;
2798 if (fmtres.range.min > target_dir_max ())
2800 /* Disable exact length checking after a failure to determine
2801 even the minimum number of characters (it shouldn't happen
2802 except in an error) but keep tracking the minimum and maximum
2803 number of characters. */
2804 return true;
2808 /* Buffer for the directive in the host character set (used when
2809 the source character set is different). */
2810 char hostdir[32];
2812 int dirlen = dir.len;
2814 if (fmtres.nullp)
2816 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2817 "%G%<%.*s%> directive argument is null",
2818 info.callstmt, dirlen,
2819 target_to_host (hostdir, sizeof hostdir, dir.beg));
2821 /* Don't bother processing the rest of the format string. */
2822 res->warned = true;
2823 res->range.min = HOST_WIDE_INT_M1U;
2824 res->range.max = HOST_WIDE_INT_M1U;
2825 return false;
2828 /* Compute the number of available bytes in the destination. There
2829 must always be at least one byte of space for the terminating
2830 NUL that's appended after the format string has been processed. */
2831 result_range avail_range = bytes_remaining (info.objsize, *res);
2833 bool warned = res->warned;
2835 if (!warned)
2836 warned = maybe_warn (dirloc, argloc, info, avail_range,
2837 fmtres.range, dir);
2839 /* Bump up the total maximum if it isn't too big. */
2840 if (res->range.max < HOST_WIDE_INT_MAX
2841 && fmtres.range.max < HOST_WIDE_INT_MAX)
2842 res->range.max += fmtres.range.max;
2844 /* Raise the total unlikely maximum by the larger of the maximum
2845 and the unlikely maximum. */
2846 unsigned HOST_WIDE_INT save = res->range.unlikely;
2847 if (fmtres.range.max < fmtres.range.unlikely)
2848 res->range.unlikely += fmtres.range.unlikely;
2849 else
2850 res->range.unlikely += fmtres.range.max;
2852 if (res->range.unlikely < save)
2853 res->range.unlikely = HOST_WIDE_INT_M1U;
2855 res->range.min += fmtres.range.min;
2856 res->range.likely += fmtres.range.likely;
2858 /* Has the minimum directive output length exceeded the maximum
2859 of 4095 bytes required to be supported? */
2860 bool minunder4k = fmtres.range.min < 4096;
2861 bool maxunder4k = fmtres.range.max < 4096;
2862 /* Clear POSUNDER4K in the overall result if the maximum has exceeded
2863 the 4k (this is necessary to avoid the return value optimization
2864 that may not be safe in the maximum case). */
2865 if (!maxunder4k)
2866 res->posunder4k = false;
2867 /* Also clear POSUNDER4K if the directive may fail. */
2868 if (fmtres.mayfail)
2869 res->posunder4k = false;
2871 if (!warned
2872 /* Only warn at level 2. */
2873 && warn_level > 1
2874 /* Only warn for string functions. */
2875 && info.is_string_func ()
2876 && (!minunder4k
2877 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2879 /* The directive output may be longer than the maximum required
2880 to be handled by an implementation according to 7.21.6.1, p15
2881 of C11. Warn on this only at level 2 but remember this and
2882 prevent folding the return value when done. This allows for
2883 the possibility of the actual libc call failing due to ENOMEM
2884 (like Glibc does with very large precision or width).
2885 Issue the "may exceed" warning only for string functions and
2886 not for fprintf or printf. */
2888 if (fmtres.range.min == fmtres.range.max)
2889 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2890 "%<%.*s%> directive output of %wu bytes exceeds "
2891 "minimum required size of 4095", dirlen,
2892 target_to_host (hostdir, sizeof hostdir, dir.beg),
2893 fmtres.range.min);
2894 else if (!minunder4k)
2895 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2896 "%<%.*s%> directive output between %wu and %wu "
2897 "bytes exceeds minimum required size of 4095",
2898 dirlen,
2899 target_to_host (hostdir, sizeof hostdir, dir.beg),
2900 fmtres.range.min, fmtres.range.max);
2901 else if (!info.retval_used () && info.is_string_func ())
2902 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2903 "%<%.*s%> directive output between %wu and %wu "
2904 "bytes may exceed minimum required size of "
2905 "4095",
2906 dirlen,
2907 target_to_host (hostdir, sizeof hostdir, dir.beg),
2908 fmtres.range.min, fmtres.range.max);
2911 /* Has the likely and maximum directive output exceeded INT_MAX? */
2912 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2913 /* Don't consider the maximum to be in excess when it's the result
2914 of a string of unknown length (i.e., whose maximum has been set
2915 to be greater than or equal to HOST_WIDE_INT_MAX. */
2916 bool maxximax = (*dir.beg
2917 && res->range.max > target_int_max ()
2918 && res->range.max < HOST_WIDE_INT_MAX);
2920 if (!warned
2921 /* Warn for the likely output size at level 1. */
2922 && (likelyximax
2923 /* But only warn for the maximum at level 2. */
2924 || (warn_level > 1
2925 && maxximax
2926 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2928 if (fmtres.range.min > target_int_max ())
2930 /* The directive output exceeds INT_MAX bytes. */
2931 if (fmtres.range.min == fmtres.range.max)
2932 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2933 "%<%.*s%> directive output of %wu bytes exceeds "
2934 "%<INT_MAX%>", dirlen,
2935 target_to_host (hostdir, sizeof hostdir, dir.beg),
2936 fmtres.range.min);
2937 else
2938 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2939 "%<%.*s%> directive output between %wu and "
2940 "%wu bytes exceeds %<INT_MAX%>", dirlen,
2941 target_to_host (hostdir, sizeof hostdir, dir.beg),
2942 fmtres.range.min, fmtres.range.max);
2944 else if (res->range.min > target_int_max ())
2946 /* The directive output is under INT_MAX but causes the result
2947 to exceed INT_MAX bytes. */
2948 if (fmtres.range.min == fmtres.range.max)
2949 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2950 "%<%.*s%> directive output of %wu bytes causes "
2951 "result to exceed %<INT_MAX%>", dirlen,
2952 target_to_host (hostdir, sizeof hostdir, dir.beg),
2953 fmtres.range.min);
2954 else
2955 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2956 "%<%.*s%> directive output between %wu and "
2957 "%wu bytes causes result to exceed %<INT_MAX%>",
2958 dirlen,
2959 target_to_host (hostdir, sizeof hostdir, dir.beg),
2960 fmtres.range.min, fmtres.range.max);
2962 else if ((!info.retval_used () || !info.bounded)
2963 && (info.is_string_func ()))
2964 /* Warn for calls to string functions that either aren't bounded
2965 (sprintf) or whose return value isn't used. */
2966 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2967 "%<%.*s%> directive output between %wu and "
2968 "%wu bytes may cause result to exceed "
2969 "%<INT_MAX%>", dirlen,
2970 target_to_host (hostdir, sizeof hostdir, dir.beg),
2971 fmtres.range.min, fmtres.range.max);
2974 if (!warned && fmtres.nonstr)
2976 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2977 "%<%.*s%> directive argument is not a nul-terminated "
2978 "string",
2979 dirlen,
2980 target_to_host (hostdir, sizeof hostdir, dir.beg));
2981 if (warned && DECL_P (fmtres.nonstr))
2982 inform (DECL_SOURCE_LOCATION (fmtres.nonstr),
2983 "referenced argument declared here");
2984 return false;
2987 if (warned && fmtres.range.min < fmtres.range.likely
2988 && fmtres.range.likely < fmtres.range.max)
2989 inform_n (info.fmtloc, fmtres.range.likely,
2990 "assuming directive output of %wu byte",
2991 "assuming directive output of %wu bytes",
2992 fmtres.range.likely);
2994 if (warned && fmtres.argmin)
2996 if (fmtres.argmin == fmtres.argmax)
2997 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2998 else if (fmtres.knownrange)
2999 inform (info.fmtloc, "directive argument in the range [%E, %E]",
3000 fmtres.argmin, fmtres.argmax);
3001 else
3002 inform (info.fmtloc,
3003 "using the range [%E, %E] for directive argument",
3004 fmtres.argmin, fmtres.argmax);
3007 res->warned |= warned;
3009 if (!dir.beg[0] && res->warned)
3011 location_t callloc = gimple_location (info.callstmt);
3013 unsigned HOST_WIDE_INT min = res->range.min;
3014 unsigned HOST_WIDE_INT max = res->range.max;
3016 if (info.objsize < HOST_WIDE_INT_MAX)
3018 /* If a warning has been issued for buffer overflow or truncation
3019 help the user figure out how big a buffer they need. */
3021 if (min == max)
3022 inform_n (callloc, min,
3023 "%qE output %wu byte into a destination of size %wu",
3024 "%qE output %wu bytes into a destination of size %wu",
3025 info.func, min, info.objsize);
3026 else if (max < HOST_WIDE_INT_MAX)
3027 inform (callloc,
3028 "%qE output between %wu and %wu bytes into "
3029 "a destination of size %wu",
3030 info.func, min, max, info.objsize);
3031 else if (min < res->range.likely && res->range.likely < max)
3032 inform (callloc,
3033 "%qE output %wu or more bytes (assuming %wu) into "
3034 "a destination of size %wu",
3035 info.func, min, res->range.likely, info.objsize);
3036 else
3037 inform (callloc,
3038 "%qE output %wu or more bytes into a destination of size "
3039 "%wu",
3040 info.func, min, info.objsize);
3042 else if (!info.is_string_func ())
3044 /* If the warning is for a file function function like fprintf
3045 of printf with no destination size just print the computed
3046 result. */
3047 if (min == max)
3048 inform_n (callloc, min,
3049 "%qE output %wu byte", "%qE output %wu bytes",
3050 info.func, min);
3051 else if (max < HOST_WIDE_INT_MAX)
3052 inform (callloc,
3053 "%qE output between %wu and %wu bytes",
3054 info.func, min, max);
3055 else if (min < res->range.likely && res->range.likely < max)
3056 inform (callloc,
3057 "%qE output %wu or more bytes (assuming %wu)",
3058 info.func, min, res->range.likely);
3059 else
3060 inform (callloc,
3061 "%qE output %wu or more bytes",
3062 info.func, min);
3066 if (dump_file && *dir.beg)
3068 fprintf (dump_file,
3069 " Result: "
3070 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3071 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
3072 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3073 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
3074 fmtres.range.min, fmtres.range.likely,
3075 fmtres.range.max, fmtres.range.unlikely,
3076 res->range.min, res->range.likely,
3077 res->range.max, res->range.unlikely);
3080 return true;
3083 /* Parse a format directive in function call described by INFO starting
3084 at STR and populate DIR structure. Bump up *ARGNO by the number of
3085 arguments extracted for the directive. Return the length of
3086 the directive. */
3088 static size_t
3089 parse_directive (sprintf_dom_walker::call_info &info,
3090 directive &dir, format_result *res,
3091 const char *str, unsigned *argno,
3092 vr_values *vr_values)
3094 const char *pcnt = strchr (str, target_percent);
3095 dir.beg = str;
3097 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
3099 /* This directive is either a plain string or the terminating nul
3100 (which isn't really a directive but it simplifies things to
3101 handle it as if it were). */
3102 dir.len = len;
3103 dir.fmtfunc = format_plain;
3105 if (dump_file)
3107 fprintf (dump_file, " Directive %u at offset "
3108 HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
3109 "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
3110 dir.dirno,
3111 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3112 (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
3115 return len - !*str;
3118 const char *pf = pcnt + 1;
3120 /* POSIX numbered argument index or zero when none. */
3121 HOST_WIDE_INT dollar = 0;
3123 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3124 when given by a va_list argument, and a non-negative value
3125 when specified in the format string itself. */
3126 HOST_WIDE_INT width = -1;
3127 HOST_WIDE_INT precision = -1;
3129 /* Pointers to the beginning of the width and precision decimal
3130 string (if any) within the directive. */
3131 const char *pwidth = 0;
3132 const char *pprec = 0;
3134 /* When the value of the decimal string that specifies width or
3135 precision is out of range, points to the digit that causes
3136 the value to exceed the limit. */
3137 const char *werange = NULL;
3138 const char *perange = NULL;
3140 /* Width specified via the asterisk. Need not be INTEGER_CST.
3141 For vararg functions set to void_node. */
3142 tree star_width = NULL_TREE;
3144 /* Width specified via the asterisk. Need not be INTEGER_CST.
3145 For vararg functions set to void_node. */
3146 tree star_precision = NULL_TREE;
3148 if (ISDIGIT (target_to_host (*pf)))
3150 /* This could be either a POSIX positional argument, the '0'
3151 flag, or a width, depending on what follows. Store it as
3152 width and sort it out later after the next character has
3153 been seen. */
3154 pwidth = pf;
3155 width = target_strtowi (&pf, &werange);
3157 else if (target_to_host (*pf) == '*')
3159 /* Similarly to the block above, this could be either a POSIX
3160 positional argument or a width, depending on what follows. */
3161 if (*argno < gimple_call_num_args (info.callstmt))
3162 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3163 else
3164 star_width = void_node;
3165 ++pf;
3168 if (target_to_host (*pf) == '$')
3170 /* Handle the POSIX dollar sign which references the 1-based
3171 positional argument number. */
3172 if (width != -1)
3173 dollar = width + info.argidx;
3174 else if (star_width
3175 && TREE_CODE (star_width) == INTEGER_CST
3176 && (TYPE_PRECISION (TREE_TYPE (star_width))
3177 <= TYPE_PRECISION (integer_type_node)))
3178 dollar = width + tree_to_shwi (star_width);
3180 /* Bail when the numbered argument is out of range (it will
3181 have already been diagnosed by -Wformat). */
3182 if (dollar == 0
3183 || dollar == (int)info.argidx
3184 || dollar > gimple_call_num_args (info.callstmt))
3185 return false;
3187 --dollar;
3189 star_width = NULL_TREE;
3190 width = -1;
3191 ++pf;
3194 if (dollar || !star_width)
3196 if (width != -1)
3198 if (width == 0)
3200 /* The '0' that has been interpreted as a width above is
3201 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3202 and continue processing other flags. */
3203 width = -1;
3204 dir.set_flag ('0');
3206 else if (!dollar)
3208 /* (Non-zero) width has been seen. The next character
3209 is either a period or a digit. */
3210 goto start_precision;
3213 /* When either '$' has been seen, or width has not been seen,
3214 the next field is the optional flags followed by an optional
3215 width. */
3216 for ( ; ; ) {
3217 switch (target_to_host (*pf))
3219 case ' ':
3220 case '0':
3221 case '+':
3222 case '-':
3223 case '#':
3224 dir.set_flag (target_to_host (*pf++));
3225 break;
3227 default:
3228 goto start_width;
3232 start_width:
3233 if (ISDIGIT (target_to_host (*pf)))
3235 werange = 0;
3236 pwidth = pf;
3237 width = target_strtowi (&pf, &werange);
3239 else if (target_to_host (*pf) == '*')
3241 if (*argno < gimple_call_num_args (info.callstmt))
3242 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3243 else
3245 /* This is (likely) a va_list. It could also be an invalid
3246 call with insufficient arguments. */
3247 star_width = void_node;
3249 ++pf;
3251 else if (target_to_host (*pf) == '\'')
3253 /* The POSIX apostrophe indicating a numeric grouping
3254 in the current locale. Even though it's possible to
3255 estimate the upper bound on the size of the output
3256 based on the number of digits it probably isn't worth
3257 continuing. */
3258 return 0;
3262 start_precision:
3263 if (target_to_host (*pf) == '.')
3265 ++pf;
3267 if (ISDIGIT (target_to_host (*pf)))
3269 pprec = pf;
3270 precision = target_strtowi (&pf, &perange);
3272 else if (target_to_host (*pf) == '*')
3274 if (*argno < gimple_call_num_args (info.callstmt))
3275 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3276 else
3278 /* This is (likely) a va_list. It could also be an invalid
3279 call with insufficient arguments. */
3280 star_precision = void_node;
3282 ++pf;
3284 else
3286 /* The decimal precision or the asterisk are optional.
3287 When neither is dirified it's taken to be zero. */
3288 precision = 0;
3292 switch (target_to_host (*pf))
3294 case 'h':
3295 if (target_to_host (pf[1]) == 'h')
3297 ++pf;
3298 dir.modifier = FMT_LEN_hh;
3300 else
3301 dir.modifier = FMT_LEN_h;
3302 ++pf;
3303 break;
3305 case 'j':
3306 dir.modifier = FMT_LEN_j;
3307 ++pf;
3308 break;
3310 case 'L':
3311 dir.modifier = FMT_LEN_L;
3312 ++pf;
3313 break;
3315 case 'l':
3316 if (target_to_host (pf[1]) == 'l')
3318 ++pf;
3319 dir.modifier = FMT_LEN_ll;
3321 else
3322 dir.modifier = FMT_LEN_l;
3323 ++pf;
3324 break;
3326 case 't':
3327 dir.modifier = FMT_LEN_t;
3328 ++pf;
3329 break;
3331 case 'z':
3332 dir.modifier = FMT_LEN_z;
3333 ++pf;
3334 break;
3337 switch (target_to_host (*pf))
3339 /* Handle a sole '%' character the same as "%%" but since it's
3340 undefined prevent the result from being folded. */
3341 case '\0':
3342 --pf;
3343 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3344 /* FALLTHRU */
3345 case '%':
3346 dir.fmtfunc = format_percent;
3347 break;
3349 case 'a':
3350 case 'A':
3351 case 'e':
3352 case 'E':
3353 case 'f':
3354 case 'F':
3355 case 'g':
3356 case 'G':
3357 res->floating = true;
3358 dir.fmtfunc = format_floating;
3359 break;
3361 case 'd':
3362 case 'i':
3363 case 'o':
3364 case 'u':
3365 case 'x':
3366 case 'X':
3367 dir.fmtfunc = format_integer;
3368 break;
3370 case 'p':
3371 /* The %p output is implementation-defined. It's possible
3372 to determine this format but due to extensions (edirially
3373 those of the Linux kernel -- see bug 78512) the first %p
3374 in the format string disables any further processing. */
3375 return false;
3377 case 'n':
3378 /* %n has side-effects even when nothing is actually printed to
3379 any buffer. */
3380 info.nowrite = false;
3381 dir.fmtfunc = format_none;
3382 break;
3384 case 'C':
3385 case 'c':
3386 /* POSIX wide character and C/POSIX narrow character. */
3387 dir.fmtfunc = format_character;
3388 break;
3390 case 'S':
3391 case 's':
3392 /* POSIX wide string and C/POSIX narrow character string. */
3393 dir.fmtfunc = format_string;
3394 break;
3396 default:
3397 /* Unknown conversion specification. */
3398 return 0;
3401 dir.specifier = target_to_host (*pf++);
3403 /* Store the length of the format directive. */
3404 dir.len = pf - pcnt;
3406 /* Buffer for the directive in the host character set (used when
3407 the source character set is different). */
3408 char hostdir[32];
3410 if (star_width)
3412 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3413 dir.set_width (star_width, vr_values);
3414 else
3416 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3417 (width is the absolute value of that specified). */
3418 dir.width[0] = 0;
3419 dir.width[1] = target_int_max () + 1;
3422 else
3424 if (width == HOST_WIDE_INT_MAX && werange)
3426 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3427 size_t caret = begin + (werange - pcnt);
3428 size_t end = pf - info.fmtstr - 1;
3430 /* Create a location for the width part of the directive,
3431 pointing the caret at the first out-of-range digit. */
3432 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3433 caret, begin, end);
3435 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3436 "%<%.*s%> directive width out of range", (int) dir.len,
3437 target_to_host (hostdir, sizeof hostdir, dir.beg));
3440 dir.set_width (width);
3443 if (star_precision)
3445 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3446 dir.set_precision (star_precision, vr_values);
3447 else
3449 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3450 (unlike width, negative precision is ignored). */
3451 dir.prec[0] = -1;
3452 dir.prec[1] = target_int_max ();
3455 else
3457 if (precision == HOST_WIDE_INT_MAX && perange)
3459 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3460 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3461 size_t end = pf - info.fmtstr - 2;
3463 /* Create a location for the precision part of the directive,
3464 including the leading period, pointing the caret at the first
3465 out-of-range digit . */
3466 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3467 caret, begin, end);
3469 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3470 "%<%.*s%> directive precision out of range", (int) dir.len,
3471 target_to_host (hostdir, sizeof hostdir, dir.beg));
3474 dir.set_precision (precision);
3477 /* Extract the argument if the directive takes one and if it's
3478 available (e.g., the function doesn't take a va_list). Treat
3479 missing arguments the same as va_list, even though they will
3480 have likely already been diagnosed by -Wformat. */
3481 if (dir.specifier != '%'
3482 && *argno < gimple_call_num_args (info.callstmt))
3483 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3485 if (dump_file)
3487 fprintf (dump_file,
3488 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3489 ": \"%.*s\"",
3490 dir.dirno,
3491 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3492 (int)dir.len, dir.beg);
3493 if (star_width)
3495 if (dir.width[0] == dir.width[1])
3496 fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
3497 dir.width[0]);
3498 else
3499 fprintf (dump_file,
3500 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3501 ", " HOST_WIDE_INT_PRINT_DEC "]",
3502 dir.width[0], dir.width[1]);
3505 if (star_precision)
3507 if (dir.prec[0] == dir.prec[1])
3508 fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
3509 dir.prec[0]);
3510 else
3511 fprintf (dump_file,
3512 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3513 HOST_WIDE_INT_PRINT_DEC "]",
3514 dir.prec[0], dir.prec[1]);
3516 fputc ('\n', dump_file);
3519 return dir.len;
3522 /* Compute the length of the output resulting from the call to a formatted
3523 output function described by INFO and store the result of the call in
3524 *RES. Issue warnings for detected past the end writes. Return true
3525 if the complete format string has been processed and *RES can be relied
3526 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3527 that caused the processing to be terminated early). */
3529 bool
3530 sprintf_dom_walker::compute_format_length (call_info &info,
3531 format_result *res)
3533 if (dump_file)
3535 location_t callloc = gimple_location (info.callstmt);
3536 fprintf (dump_file, "%s:%i: ",
3537 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3538 print_generic_expr (dump_file, info.func, dump_flags);
3540 fprintf (dump_file,
3541 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3542 ", fmtstr = \"%s\"\n",
3543 info.objsize, info.fmtstr);
3546 /* Reset the minimum and maximum byte counters. */
3547 res->range.min = res->range.max = 0;
3549 /* No directive has been seen yet so the length of output is bounded
3550 by the known range [0, 0] (with no conversion resulting in a failure
3551 or producing more than 4K bytes) until determined otherwise. */
3552 res->knownrange = true;
3553 res->floating = false;
3554 res->warned = false;
3556 /* 1-based directive counter. */
3557 unsigned dirno = 1;
3559 /* The variadic argument counter. */
3560 unsigned argno = info.argidx;
3562 for (const char *pf = info.fmtstr; ; ++dirno)
3564 directive dir = directive ();
3565 dir.dirno = dirno;
3567 size_t n = parse_directive (info, dir, res, pf, &argno,
3568 evrp_range_analyzer.get_vr_values ());
3570 /* Return failure if the format function fails. */
3571 if (!format_directive (info, res, dir,
3572 evrp_range_analyzer.get_vr_values ()))
3573 return false;
3575 /* Return success the directive is zero bytes long and it's
3576 the last think in the format string (i.e., it's the terminating
3577 nul, which isn't really a directive but handling it as one makes
3578 things simpler). */
3579 if (!n)
3580 return *pf == '\0';
3582 pf += n;
3585 /* The complete format string was processed (with or without warnings). */
3586 return true;
3589 /* Return the size of the object referenced by the expression DEST if
3590 available, or the maximum possible size otherwise. */
3592 static unsigned HOST_WIDE_INT
3593 get_destination_size (tree dest)
3595 /* When there is no destination return the maximum. */
3596 if (!dest)
3597 return HOST_WIDE_INT_MAX;
3599 /* Initialize object size info before trying to compute it. */
3600 init_object_sizes ();
3602 /* Use __builtin_object_size to determine the size of the destination
3603 object. When optimizing, determine the smallest object (such as
3604 a member array as opposed to the whole enclosing object), otherwise
3605 use type-zero object size to determine the size of the enclosing
3606 object (the function fails without optimization in this type). */
3607 int ost = optimize > 0;
3608 unsigned HOST_WIDE_INT size;
3609 if (compute_builtin_object_size (dest, ost, &size))
3610 return size;
3612 return HOST_WIDE_INT_MAX;
3615 /* Return true if the call described by INFO with result RES safe to
3616 optimize (i.e., no undefined behavior), and set RETVAL to the range
3617 of its return values. */
3619 static bool
3620 is_call_safe (const sprintf_dom_walker::call_info &info,
3621 const format_result &res, bool under4k,
3622 unsigned HOST_WIDE_INT retval[2])
3624 if (under4k && !res.posunder4k)
3625 return false;
3627 /* The minimum return value. */
3628 retval[0] = res.range.min;
3630 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3631 but in cases involving multibyte characters could be as large as
3632 RES.RANGE.UNLIKELY. */
3633 retval[1]
3634 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3636 /* Adjust the number of bytes which includes the terminating nul
3637 to reflect the return value of the function which does not.
3638 Because the valid range of the function is [INT_MIN, INT_MAX],
3639 a valid range before the adjustment below is [0, INT_MAX + 1]
3640 (the functions only return negative values on error or undefined
3641 behavior). */
3642 if (retval[0] <= target_int_max () + 1)
3643 --retval[0];
3644 if (retval[1] <= target_int_max () + 1)
3645 --retval[1];
3647 /* Avoid the return value optimization when the behavior of the call
3648 is undefined either because any directive may have produced 4K or
3649 more of output, or the return value exceeds INT_MAX, or because
3650 the output overflows the destination object (but leave it enabled
3651 when the function is bounded because then the behavior is well-
3652 defined). */
3653 if (retval[0] == retval[1]
3654 && (info.bounded || retval[0] < info.objsize)
3655 && retval[0] <= target_int_max ())
3656 return true;
3658 if ((info.bounded || retval[1] < info.objsize)
3659 && (retval[0] < target_int_max ()
3660 && retval[1] < target_int_max ()))
3661 return true;
3663 if (!under4k && (info.bounded || retval[0] < info.objsize))
3664 return true;
3666 return false;
3669 /* Given a suitable result RES of a call to a formatted output function
3670 described by INFO, substitute the result for the return value of
3671 the call. The result is suitable if the number of bytes it represents
3672 is known and exact. A result that isn't suitable for substitution may
3673 have its range set to the range of return values, if that is known.
3674 Return true if the call is removed and gsi_next should not be performed
3675 in the caller. */
3677 static bool
3678 try_substitute_return_value (gimple_stmt_iterator *gsi,
3679 const sprintf_dom_walker::call_info &info,
3680 const format_result &res)
3682 tree lhs = gimple_get_lhs (info.callstmt);
3684 /* Set to true when the entire call has been removed. */
3685 bool removed = false;
3687 /* The minimum and maximum return value. */
3688 unsigned HOST_WIDE_INT retval[2];
3689 bool safe = is_call_safe (info, res, true, retval);
3691 if (safe
3692 && retval[0] == retval[1]
3693 /* Not prepared to handle possibly throwing calls here; they shouldn't
3694 appear in non-artificial testcases, except when the __*_chk routines
3695 are badly declared. */
3696 && !stmt_ends_bb_p (info.callstmt))
3698 tree cst = build_int_cst (lhs ? TREE_TYPE (lhs) : integer_type_node,
3699 retval[0]);
3701 if (lhs == NULL_TREE && info.nowrite)
3703 /* Remove the call to the bounded function with a zero size
3704 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3705 unlink_stmt_vdef (info.callstmt);
3706 gsi_remove (gsi, true);
3707 removed = true;
3709 else if (info.nowrite)
3711 /* Replace the call to the bounded function with a zero size
3712 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3713 of the function. */
3714 if (!update_call_from_tree (gsi, cst))
3715 gimplify_and_update_call_from_tree (gsi, cst);
3716 gimple *callstmt = gsi_stmt (*gsi);
3717 update_stmt (callstmt);
3719 else if (lhs)
3721 /* Replace the left-hand side of the call with the constant
3722 result of the formatted function. */
3723 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3724 gimple *g = gimple_build_assign (lhs, cst);
3725 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3726 update_stmt (info.callstmt);
3729 if (dump_file)
3731 if (removed)
3732 fprintf (dump_file, " Removing call statement.");
3733 else
3735 fprintf (dump_file, " Substituting ");
3736 print_generic_expr (dump_file, cst, dump_flags);
3737 fprintf (dump_file, " for %s.\n",
3738 info.nowrite ? "statement" : "return value");
3742 else if (lhs && types_compatible_p (TREE_TYPE (lhs), integer_type_node))
3744 bool setrange = false;
3746 if (safe
3747 && (info.bounded || retval[1] < info.objsize)
3748 && (retval[0] < target_int_max ()
3749 && retval[1] < target_int_max ()))
3751 /* If the result is in a valid range bounded by the size of
3752 the destination set it so that it can be used for subsequent
3753 optimizations. */
3754 int prec = TYPE_PRECISION (integer_type_node);
3756 wide_int min = wi::shwi (retval[0], prec);
3757 wide_int max = wi::shwi (retval[1], prec);
3758 set_range_info (lhs, VR_RANGE, min, max);
3760 setrange = true;
3763 if (dump_file)
3765 const char *inbounds
3766 = (retval[0] < info.objsize
3767 ? (retval[1] < info.objsize
3768 ? "in" : "potentially out-of")
3769 : "out-of");
3771 const char *what = setrange ? "Setting" : "Discarding";
3772 if (retval[0] != retval[1])
3773 fprintf (dump_file,
3774 " %s %s-bounds return value range ["
3775 HOST_WIDE_INT_PRINT_UNSIGNED ", "
3776 HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
3777 what, inbounds, retval[0], retval[1]);
3778 else
3779 fprintf (dump_file, " %s %s-bounds return value "
3780 HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
3781 what, inbounds, retval[0]);
3785 if (dump_file)
3786 fputc ('\n', dump_file);
3788 return removed;
3791 /* Try to simplify a s{,n}printf call described by INFO with result
3792 RES by replacing it with a simpler and presumably more efficient
3793 call (such as strcpy). */
3795 static bool
3796 try_simplify_call (gimple_stmt_iterator *gsi,
3797 const sprintf_dom_walker::call_info &info,
3798 const format_result &res)
3800 unsigned HOST_WIDE_INT dummy[2];
3801 if (!is_call_safe (info, res, info.retval_used (), dummy))
3802 return false;
3804 switch (info.fncode)
3806 case BUILT_IN_SNPRINTF:
3807 return gimple_fold_builtin_snprintf (gsi);
3809 case BUILT_IN_SPRINTF:
3810 return gimple_fold_builtin_sprintf (gsi);
3812 default:
3816 return false;
3819 /* Return the zero-based index of the format string argument of a printf
3820 like function and set *IDX_ARGS to the first format argument. When
3821 no such index exists return UINT_MAX. */
3823 static unsigned
3824 get_user_idx_format (tree fndecl, unsigned *idx_args)
3826 tree attrs = lookup_attribute ("format", DECL_ATTRIBUTES (fndecl));
3827 if (!attrs)
3828 attrs = lookup_attribute ("format", TYPE_ATTRIBUTES (TREE_TYPE (fndecl)));
3830 if (!attrs)
3831 return UINT_MAX;
3833 attrs = TREE_VALUE (attrs);
3835 tree archetype = TREE_VALUE (attrs);
3836 if (strcmp ("printf", IDENTIFIER_POINTER (archetype)))
3837 return UINT_MAX;
3839 attrs = TREE_CHAIN (attrs);
3840 tree fmtarg = TREE_VALUE (attrs);
3842 attrs = TREE_CHAIN (attrs);
3843 tree elliparg = TREE_VALUE (attrs);
3845 /* Attribute argument indices are 1-based but we use zero-based. */
3846 *idx_args = tree_to_uhwi (elliparg) - 1;
3847 return tree_to_uhwi (fmtarg) - 1;
3850 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3851 functions and if so, handle it. Return true if the call is removed
3852 and gsi_next should not be performed in the caller. */
3854 bool
3855 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3857 call_info info = call_info ();
3859 info.callstmt = gsi_stmt (*gsi);
3860 info.func = gimple_call_fndecl (info.callstmt);
3861 if (!info.func)
3862 return false;
3864 /* Format string argument number (valid for all functions). */
3865 unsigned idx_format = UINT_MAX;
3866 if (gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3867 info.fncode = DECL_FUNCTION_CODE (info.func);
3868 else
3870 unsigned idx_args;
3871 idx_format = get_user_idx_format (info.func, &idx_args);
3872 if (idx_format == UINT_MAX
3873 || idx_format >= gimple_call_num_args (info.callstmt)
3874 || idx_args > gimple_call_num_args (info.callstmt)
3875 || !POINTER_TYPE_P (TREE_TYPE (gimple_call_arg (info.callstmt,
3876 idx_format))))
3877 return false;
3878 info.fncode = BUILT_IN_NONE;
3879 info.argidx = idx_args;
3882 /* The size of the destination as in snprintf(dest, size, ...). */
3883 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3885 /* The size of the destination determined by __builtin_object_size. */
3886 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3888 /* Zero-based buffer size argument number (snprintf and vsnprintf). */
3889 unsigned idx_dstsize = UINT_MAX;
3891 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3892 unsigned idx_objsize = UINT_MAX;
3894 /* Destinaton argument number (valid for sprintf functions only). */
3895 unsigned idx_dstptr = 0;
3897 switch (info.fncode)
3899 case BUILT_IN_NONE:
3900 // User-defined function with attribute format (printf).
3901 idx_dstptr = -1;
3902 break;
3904 case BUILT_IN_FPRINTF:
3905 // Signature:
3906 // __builtin_fprintf (FILE*, format, ...)
3907 idx_format = 1;
3908 info.argidx = 2;
3909 idx_dstptr = -1;
3910 break;
3912 case BUILT_IN_FPRINTF_CHK:
3913 // Signature:
3914 // __builtin_fprintf_chk (FILE*, ost, format, ...)
3915 idx_format = 2;
3916 info.argidx = 3;
3917 idx_dstptr = -1;
3918 break;
3920 case BUILT_IN_FPRINTF_UNLOCKED:
3921 // Signature:
3922 // __builtin_fprintf_unnlocked (FILE*, format, ...)
3923 idx_format = 1;
3924 info.argidx = 2;
3925 idx_dstptr = -1;
3926 break;
3928 case BUILT_IN_PRINTF:
3929 // Signature:
3930 // __builtin_printf (format, ...)
3931 idx_format = 0;
3932 info.argidx = 1;
3933 idx_dstptr = -1;
3934 break;
3936 case BUILT_IN_PRINTF_CHK:
3937 // Signature:
3938 // __builtin_printf_chk (ost, format, ...)
3939 idx_format = 1;
3940 info.argidx = 2;
3941 idx_dstptr = -1;
3942 break;
3944 case BUILT_IN_PRINTF_UNLOCKED:
3945 // Signature:
3946 // __builtin_printf (format, ...)
3947 idx_format = 0;
3948 info.argidx = 1;
3949 idx_dstptr = -1;
3950 break;
3952 case BUILT_IN_SPRINTF:
3953 // Signature:
3954 // __builtin_sprintf (dst, format, ...)
3955 idx_format = 1;
3956 info.argidx = 2;
3957 break;
3959 case BUILT_IN_SPRINTF_CHK:
3960 // Signature:
3961 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3962 idx_objsize = 2;
3963 idx_format = 3;
3964 info.argidx = 4;
3965 break;
3967 case BUILT_IN_SNPRINTF:
3968 // Signature:
3969 // __builtin_snprintf (dst, size, format, ...)
3970 idx_dstsize = 1;
3971 idx_format = 2;
3972 info.argidx = 3;
3973 info.bounded = true;
3974 break;
3976 case BUILT_IN_SNPRINTF_CHK:
3977 // Signature:
3978 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3979 idx_dstsize = 1;
3980 idx_objsize = 3;
3981 idx_format = 4;
3982 info.argidx = 5;
3983 info.bounded = true;
3984 break;
3986 case BUILT_IN_VFPRINTF:
3987 // Signature:
3988 // __builtin_vprintf (FILE*, format, va_list)
3989 idx_format = 1;
3990 info.argidx = -1;
3991 idx_dstptr = -1;
3992 break;
3994 case BUILT_IN_VFPRINTF_CHK:
3995 // Signature:
3996 // __builtin___vfprintf_chk (FILE*, ost, format, va_list)
3997 idx_format = 2;
3998 info.argidx = -1;
3999 idx_dstptr = -1;
4000 break;
4002 case BUILT_IN_VPRINTF:
4003 // Signature:
4004 // __builtin_vprintf (format, va_list)
4005 idx_format = 0;
4006 info.argidx = -1;
4007 idx_dstptr = -1;
4008 break;
4010 case BUILT_IN_VPRINTF_CHK:
4011 // Signature:
4012 // __builtin___vprintf_chk (ost, format, va_list)
4013 idx_format = 1;
4014 info.argidx = -1;
4015 idx_dstptr = -1;
4016 break;
4018 case BUILT_IN_VSNPRINTF:
4019 // Signature:
4020 // __builtin_vsprintf (dst, size, format, va)
4021 idx_dstsize = 1;
4022 idx_format = 2;
4023 info.argidx = -1;
4024 info.bounded = true;
4025 break;
4027 case BUILT_IN_VSNPRINTF_CHK:
4028 // Signature:
4029 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
4030 idx_dstsize = 1;
4031 idx_objsize = 3;
4032 idx_format = 4;
4033 info.argidx = -1;
4034 info.bounded = true;
4035 break;
4037 case BUILT_IN_VSPRINTF:
4038 // Signature:
4039 // __builtin_vsprintf (dst, format, va)
4040 idx_format = 1;
4041 info.argidx = -1;
4042 break;
4044 case BUILT_IN_VSPRINTF_CHK:
4045 // Signature:
4046 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
4047 idx_format = 3;
4048 idx_objsize = 2;
4049 info.argidx = -1;
4050 break;
4052 default:
4053 return false;
4056 /* Set the global warning level for this function. */
4057 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
4059 /* For all string functions the first argument is a pointer to
4060 the destination. */
4061 tree dstptr = (idx_dstptr < gimple_call_num_args (info.callstmt)
4062 ? gimple_call_arg (info.callstmt, 0) : NULL_TREE);
4064 info.format = gimple_call_arg (info.callstmt, idx_format);
4066 /* True when the destination size is constant as opposed to the lower
4067 or upper bound of a range. */
4068 bool dstsize_cst_p = true;
4069 bool posunder4k = true;
4071 if (idx_dstsize == UINT_MAX)
4073 /* For non-bounded functions like sprintf, determine the size
4074 of the destination from the object or pointer passed to it
4075 as the first argument. */
4076 dstsize = get_destination_size (dstptr);
4078 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
4080 /* For bounded functions try to get the size argument. */
4082 if (TREE_CODE (size) == INTEGER_CST)
4084 dstsize = tree_to_uhwi (size);
4085 /* No object can be larger than SIZE_MAX bytes (half the address
4086 space) on the target.
4087 The functions are defined only for output of at most INT_MAX
4088 bytes. Specifying a bound in excess of that limit effectively
4089 defeats the bounds checking (and on some implementations such
4090 as Solaris cause the function to fail with EINVAL). */
4091 if (dstsize > target_size_max () / 2)
4093 /* Avoid warning if -Wstringop-overflow is specified since
4094 it also warns for the same thing though only for the
4095 checking built-ins. */
4096 if ((idx_objsize == UINT_MAX
4097 || !warn_stringop_overflow))
4098 warning_at (gimple_location (info.callstmt), info.warnopt (),
4099 "specified bound %wu exceeds maximum object size "
4100 "%wu",
4101 dstsize, target_size_max () / 2);
4102 /* POSIX requires snprintf to fail if DSTSIZE is greater
4103 than INT_MAX. Even though not all POSIX implementations
4104 conform to the requirement, avoid folding in this case. */
4105 posunder4k = false;
4107 else if (dstsize > target_int_max ())
4109 warning_at (gimple_location (info.callstmt), info.warnopt (),
4110 "specified bound %wu exceeds %<INT_MAX%>",
4111 dstsize);
4112 /* POSIX requires snprintf to fail if DSTSIZE is greater
4113 than INT_MAX. Avoid folding in that case. */
4114 posunder4k = false;
4117 else if (TREE_CODE (size) == SSA_NAME)
4119 /* Try to determine the range of values of the argument
4120 and use the greater of the two at level 1 and the smaller
4121 of them at level 2. */
4122 const value_range *vr = evrp_range_analyzer.get_value_range (size);
4123 if (range_int_cst_p (vr))
4125 unsigned HOST_WIDE_INT minsize = TREE_INT_CST_LOW (vr->min ());
4126 unsigned HOST_WIDE_INT maxsize = TREE_INT_CST_LOW (vr->max ());
4127 dstsize = warn_level < 2 ? maxsize : minsize;
4129 if (minsize > target_int_max ())
4130 warning_at (gimple_location (info.callstmt), info.warnopt (),
4131 "specified bound range [%wu, %wu] exceeds "
4132 "%<INT_MAX%>",
4133 minsize, maxsize);
4135 /* POSIX requires snprintf to fail if DSTSIZE is greater
4136 than INT_MAX. Avoid folding if that's possible. */
4137 if (maxsize > target_int_max ())
4138 posunder4k = false;
4140 else if (vr->varying_p ())
4142 /* POSIX requires snprintf to fail if DSTSIZE is greater
4143 than INT_MAX. Since SIZE's range is unknown, avoid
4144 folding. */
4145 posunder4k = false;
4148 /* The destination size is not constant. If the function is
4149 bounded (e.g., snprintf) a lower bound of zero doesn't
4150 necessarily imply it can be eliminated. */
4151 dstsize_cst_p = false;
4155 if (idx_objsize != UINT_MAX)
4156 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
4157 if (tree_fits_uhwi_p (size))
4158 objsize = tree_to_uhwi (size);
4160 if (info.bounded && !dstsize)
4162 /* As a special case, when the explicitly specified destination
4163 size argument (to a bounded function like snprintf) is zero
4164 it is a request to determine the number of bytes on output
4165 without actually producing any. Pretend the size is
4166 unlimited in this case. */
4167 info.objsize = HOST_WIDE_INT_MAX;
4168 info.nowrite = dstsize_cst_p;
4170 else
4172 /* For calls to non-bounded functions or to those of bounded
4173 functions with a non-zero size, warn if the destination
4174 pointer is null. */
4175 if (dstptr && integer_zerop (dstptr))
4177 /* This is diagnosed with -Wformat only when the null is a constant
4178 pointer. The warning here diagnoses instances where the pointer
4179 is not constant. */
4180 location_t loc = gimple_location (info.callstmt);
4181 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
4182 info.warnopt (), "%Gnull destination pointer",
4183 info.callstmt);
4184 return false;
4187 /* Set the object size to the smaller of the two arguments
4188 of both have been specified and they're not equal. */
4189 info.objsize = dstsize < objsize ? dstsize : objsize;
4191 if (info.bounded
4192 && dstsize < target_size_max () / 2 && objsize < dstsize
4193 /* Avoid warning if -Wstringop-overflow is specified since
4194 it also warns for the same thing though only for the
4195 checking built-ins. */
4196 && (idx_objsize == UINT_MAX
4197 || !warn_stringop_overflow))
4199 warning_at (gimple_location (info.callstmt), info.warnopt (),
4200 "specified bound %wu exceeds the size %wu "
4201 "of the destination object", dstsize, objsize);
4205 /* Determine if the format argument may be null and warn if not
4206 and if the argument is null. */
4207 if (integer_zerop (info.format)
4208 && gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
4210 location_t loc = gimple_location (info.callstmt);
4211 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
4212 info.warnopt (), "%Gnull format string",
4213 info.callstmt);
4214 return false;
4217 info.fmtstr = get_format_string (info.format, &info.fmtloc);
4218 if (!info.fmtstr)
4219 return false;
4221 /* The result is the number of bytes output by the formatted function,
4222 including the terminating NUL. */
4223 format_result res = format_result ();
4225 /* I/O functions with no destination argument (i.e., all forms of fprintf
4226 and printf) may fail under any conditions. Others (i.e., all forms of
4227 sprintf) may only fail under specific conditions determined for each
4228 directive. Clear POSUNDER4K for the former set of functions and set
4229 it to true for the latter (it can only be cleared later, but it is
4230 never set to true again). */
4231 res.posunder4k = posunder4k && dstptr;
4233 bool success = compute_format_length (info, &res);
4234 if (res.warned)
4235 gimple_set_no_warning (info.callstmt, true);
4237 /* When optimizing and the printf return value optimization is enabled,
4238 attempt to substitute the computed result for the return value of
4239 the call. Avoid this optimization when -frounding-math is in effect
4240 and the format string contains a floating point directive. */
4241 bool call_removed = false;
4242 if (success && optimize > 0)
4244 /* Save a copy of the iterator pointing at the call. The iterator
4245 may change to point past the call in try_substitute_return_value
4246 but the original value is needed in try_simplify_call. */
4247 gimple_stmt_iterator gsi_call = *gsi;
4249 if (flag_printf_return_value
4250 && (!flag_rounding_math || !res.floating))
4251 call_removed = try_substitute_return_value (gsi, info, res);
4253 if (!call_removed)
4254 try_simplify_call (&gsi_call, info, res);
4257 return call_removed;
4260 edge
4261 sprintf_dom_walker::before_dom_children (basic_block bb)
4263 evrp_range_analyzer.enter (bb);
4264 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
4266 /* Iterate over statements, looking for function calls. */
4267 gimple *stmt = gsi_stmt (si);
4269 /* First record ranges generated by this statement. */
4270 evrp_range_analyzer.record_ranges_from_stmt (stmt, false);
4272 if (is_gimple_call (stmt) && handle_gimple_call (&si))
4273 /* If handle_gimple_call returns true, the iterator is
4274 already pointing to the next statement. */
4275 continue;
4277 gsi_next (&si);
4279 return NULL;
4282 void
4283 sprintf_dom_walker::after_dom_children (basic_block bb)
4285 evrp_range_analyzer.leave (bb);
4288 /* Execute the pass for function FUN. */
4290 unsigned int
4291 pass_sprintf_length::execute (function *fun)
4293 init_target_to_host_charmap ();
4295 calculate_dominance_info (CDI_DOMINATORS);
4296 bool use_scev = optimize > 0 && flag_printf_return_value;
4297 if (use_scev)
4299 loop_optimizer_init (LOOPS_NORMAL);
4300 scev_initialize ();
4303 sprintf_dom_walker sprintf_dom_walker;
4304 sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
4306 if (use_scev)
4308 scev_finalize ();
4309 loop_optimizer_finalize ();
4312 /* Clean up object size info. */
4313 fini_object_sizes ();
4314 return 0;
4317 } /* Unnamed namespace. */
4319 /* Return a pointer to a pass object newly constructed from the context
4320 CTXT. */
4322 gimple_opt_pass *
4323 make_pass_sprintf_length (gcc::context *ctxt)
4325 return new pass_sprintf_length (ctxt);