re PR fortran/88376 (ICE in is_illegal_recursion, at fortran/resolve.c:1689)
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob8e6016fc42f3dfcec31fc93a1dea8680373d00ba
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 "intl.h"
69 #include "langhooks.h"
71 #include "attribs.h"
72 #include "builtins.h"
73 #include "stor-layout.h"
75 #include "realmpfr.h"
76 #include "target.h"
78 #include "cpplib.h"
79 #include "input.h"
80 #include "toplev.h"
81 #include "substring-locations.h"
82 #include "diagnostic.h"
83 #include "domwalk.h"
84 #include "alloc-pool.h"
85 #include "vr-values.h"
86 #include "gimple-ssa-evrp-analyze.h"
88 /* The likely worst case value of MB_LEN_MAX for the target, large enough
89 for UTF-8. Ideally, this would be obtained by a target hook if it were
90 to be used for optimization but it's good enough as is for warnings. */
91 #define target_mb_len_max() 6
93 /* The maximum number of bytes a single non-string directive can result
94 in. This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
95 LDBL_MAX_10_EXP of 4932. */
96 #define IEEE_MAX_10_EXP 4932
97 #define target_dir_max() (target_int_max () + IEEE_MAX_10_EXP + 2)
99 namespace {
101 const pass_data pass_data_sprintf_length = {
102 GIMPLE_PASS, // pass type
103 "printf-return-value", // pass name
104 OPTGROUP_NONE, // optinfo_flags
105 TV_NONE, // tv_id
106 PROP_cfg, // properties_required
107 0, // properties_provided
108 0, // properties_destroyed
109 0, // properties_start
110 0, // properties_finish
113 /* Set to the warning level for the current function which is equal
114 either to warn_format_trunc for bounded functions or to
115 warn_format_overflow otherwise. */
117 static int warn_level;
119 struct format_result;
121 class sprintf_dom_walker : public dom_walker
123 public:
124 sprintf_dom_walker ()
125 : dom_walker (CDI_DOMINATORS),
126 evrp_range_analyzer (false) {}
127 ~sprintf_dom_walker () {}
129 edge before_dom_children (basic_block) FINAL OVERRIDE;
130 void after_dom_children (basic_block) FINAL OVERRIDE;
131 bool handle_gimple_call (gimple_stmt_iterator *);
133 struct call_info;
134 bool compute_format_length (call_info &, format_result *);
135 class evrp_range_analyzer evrp_range_analyzer;
138 class pass_sprintf_length : public gimple_opt_pass
140 bool fold_return_value;
142 public:
143 pass_sprintf_length (gcc::context *ctxt)
144 : gimple_opt_pass (pass_data_sprintf_length, ctxt),
145 fold_return_value (false)
148 opt_pass * clone () { return new pass_sprintf_length (m_ctxt); }
150 virtual bool gate (function *);
152 virtual unsigned int execute (function *);
154 void set_pass_param (unsigned int n, bool param)
156 gcc_assert (n == 0);
157 fold_return_value = param;
162 bool
163 pass_sprintf_length::gate (function *)
165 /* Run the pass iff -Warn-format-overflow or -Warn-format-truncation
166 is specified and either not optimizing and the pass is being invoked
167 early, or when optimizing and the pass is being invoked during
168 optimization (i.e., "late"). */
169 return ((warn_format_overflow > 0
170 || warn_format_trunc > 0
171 || flag_printf_return_value)
172 && (optimize > 0) == fold_return_value);
175 /* The minimum, maximum, likely, and unlikely maximum number of bytes
176 of output either a formatting function or an individual directive
177 can result in. */
179 struct result_range
181 /* The absolute minimum number of bytes. The result of a successful
182 conversion is guaranteed to be no less than this. (An erroneous
183 conversion can be indicated by MIN > HOST_WIDE_INT_MAX.) */
184 unsigned HOST_WIDE_INT min;
185 /* The likely maximum result that is used in diagnostics. In most
186 cases MAX is the same as the worst case UNLIKELY result. */
187 unsigned HOST_WIDE_INT max;
188 /* The likely result used to trigger diagnostics. For conversions
189 that result in a range of bytes [MIN, MAX], LIKELY is somewhere
190 in that range. */
191 unsigned HOST_WIDE_INT likely;
192 /* In rare cases (e.g., for nultibyte characters) UNLIKELY gives
193 the worst cases maximum result of a directive. In most cases
194 UNLIKELY == MAX. UNLIKELY is used to control the return value
195 optimization but not in diagnostics. */
196 unsigned HOST_WIDE_INT unlikely;
199 /* The result of a call to a formatted function. */
201 struct format_result
203 /* Range of characters written by the formatted function.
204 Setting the minimum to HOST_WIDE_INT_MAX disables all
205 length tracking for the remainder of the format string. */
206 result_range range;
208 /* True when the range above is obtained from known values of
209 directive arguments, or bounds on the amount of output such
210 as width and precision, and not the result of heuristics that
211 depend on warning levels. It's used to issue stricter diagnostics
212 in cases where strings of unknown lengths are bounded by the arrays
213 they are determined to refer to. KNOWNRANGE must not be used for
214 the return value optimization. */
215 bool knownrange;
217 /* True if no individual directive could fail or result in more than
218 4095 bytes of output (the total NUMBER_CHARS_{MIN,MAX} might be
219 greater). Implementations are not required to handle directives
220 that produce more than 4K bytes (leading to undefined behavior)
221 and so when one is found it disables the return value optimization.
222 Similarly, directives that can fail (such as wide character
223 directives) disable the optimization. */
224 bool posunder4k;
226 /* True when a floating point directive has been seen in the format
227 string. */
228 bool floating;
230 /* True when an intermediate result has caused a warning. Used to
231 avoid issuing duplicate warnings while finishing the processing
232 of a call. WARNED also disables the return value optimization. */
233 bool warned;
235 /* Preincrement the number of output characters by 1. */
236 format_result& operator++ ()
238 return *this += 1;
241 /* Postincrement the number of output characters by 1. */
242 format_result operator++ (int)
244 format_result prev (*this);
245 *this += 1;
246 return prev;
249 /* Increment the number of output characters by N. */
250 format_result& operator+= (unsigned HOST_WIDE_INT);
253 format_result&
254 format_result::operator+= (unsigned HOST_WIDE_INT n)
256 gcc_assert (n < HOST_WIDE_INT_MAX);
258 if (range.min < HOST_WIDE_INT_MAX)
259 range.min += n;
261 if (range.max < HOST_WIDE_INT_MAX)
262 range.max += n;
264 if (range.likely < HOST_WIDE_INT_MAX)
265 range.likely += n;
267 if (range.unlikely < HOST_WIDE_INT_MAX)
268 range.unlikely += n;
270 return *this;
273 /* Return the value of INT_MIN for the target. */
275 static inline HOST_WIDE_INT
276 target_int_min ()
278 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
281 /* Return the value of INT_MAX for the target. */
283 static inline unsigned HOST_WIDE_INT
284 target_int_max ()
286 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
289 /* Return the value of SIZE_MAX for the target. */
291 static inline unsigned HOST_WIDE_INT
292 target_size_max ()
294 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
297 /* A straightforward mapping from the execution character set to the host
298 character set indexed by execution character. */
300 static char target_to_host_charmap[256];
302 /* Initialize a mapping from the execution character set to the host
303 character set. */
305 static bool
306 init_target_to_host_charmap ()
308 /* If the percent sign is non-zero the mapping has already been
309 initialized. */
310 if (target_to_host_charmap['%'])
311 return true;
313 /* Initialize the target_percent character (done elsewhere). */
314 if (!init_target_chars ())
315 return false;
317 /* The subset of the source character set used by printf conversion
318 specifications (strictly speaking, not all letters are used but
319 they are included here for the sake of simplicity). The dollar
320 sign must be included even though it's not in the basic source
321 character set. */
322 const char srcset[] = " 0123456789!\"#%&'()*+,-./:;<=>?[\\]^_{|}~$"
323 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
325 /* Set the mapping for all characters to some ordinary value (i,e.,
326 not none used in printf conversion specifications) and overwrite
327 those that are used by conversion specifications with their
328 corresponding values. */
329 memset (target_to_host_charmap + 1, '?', sizeof target_to_host_charmap - 1);
331 /* Are the two sets of characters the same? */
332 bool all_same_p = true;
334 for (const char *pc = srcset; *pc; ++pc)
336 /* Slice off the high end bits in case target characters are
337 signed. All values are expected to be non-nul, otherwise
338 there's a problem. */
339 if (unsigned char tc = lang_hooks.to_target_charset (*pc))
341 target_to_host_charmap[tc] = *pc;
342 if (tc != *pc)
343 all_same_p = false;
345 else
346 return false;
350 /* Set the first element to a non-zero value if the mapping
351 is 1-to-1, otherwise leave it clear (NUL is assumed to be
352 the same in both character sets). */
353 target_to_host_charmap[0] = all_same_p;
355 return true;
358 /* Return the host source character corresponding to the character
359 CH in the execution character set if one exists, or some innocuous
360 (non-special, non-nul) source character otherwise. */
362 static inline unsigned char
363 target_to_host (unsigned char ch)
365 return target_to_host_charmap[ch];
368 /* Convert an initial substring of the string TARGSTR consisting of
369 characters in the execution character set into a string in the
370 source character set on the host and store up to HOSTSZ characters
371 in the buffer pointed to by HOSTR. Return HOSTR. */
373 static const char*
374 target_to_host (char *hostr, size_t hostsz, const char *targstr)
376 /* Make sure the buffer is reasonably big. */
377 gcc_assert (hostsz > 4);
379 /* The interesting subset of source and execution characters are
380 the same so no conversion is necessary. However, truncate
381 overlong strings just like the translated strings are. */
382 if (target_to_host_charmap['\0'] == 1)
384 strncpy (hostr, targstr, hostsz - 4);
385 if (strlen (targstr) >= hostsz)
386 strcpy (hostr + hostsz - 4, "...");
387 return hostr;
390 /* Convert the initial substring of TARGSTR to the corresponding
391 characters in the host set, appending "..." if TARGSTR is too
392 long to fit. Using the static buffer assumes the function is
393 not called in between sequence points (which it isn't). */
394 for (char *ph = hostr; ; ++targstr)
396 *ph++ = target_to_host (*targstr);
397 if (!*targstr)
398 break;
400 if (size_t (ph - hostr) == hostsz - 4)
402 *ph = '\0';
403 strcat (ph, "...");
404 break;
408 return hostr;
411 /* Convert the sequence of decimal digits in the execution character
412 starting at S to a long, just like strtol does. Return the result
413 and set *END to one past the last converted character. On range
414 error set ERANGE to the digit that caused it. */
416 static inline long
417 target_strtol10 (const char **ps, const char **erange)
419 unsigned HOST_WIDE_INT val = 0;
420 for ( ; ; ++*ps)
422 unsigned char c = target_to_host (**ps);
423 if (ISDIGIT (c))
425 c -= '0';
427 /* Check for overflow. */
428 if (val > (LONG_MAX - c) / 10LU)
430 val = LONG_MAX;
431 *erange = *ps;
433 /* Skip the remaining digits. */
435 c = target_to_host (*++*ps);
436 while (ISDIGIT (c));
437 break;
439 else
440 val = val * 10 + c;
442 else
443 break;
446 return val;
449 /* Given FORMAT, set *PLOC to the source location of the format string
450 and return the format string if it is known or null otherwise. */
452 static const char*
453 get_format_string (tree format, location_t *ploc)
455 *ploc = EXPR_LOC_OR_LOC (format, input_location);
457 return c_getstr (format);
460 /* For convenience and brevity, shorter named entrypoints of
461 format_string_diagnostic_t::emit_warning_va and
462 format_string_diagnostic_t::emit_warning_n_va.
463 These have to be functions with the attribute so that exgettext
464 works properly. */
466 static bool
467 ATTRIBUTE_GCC_DIAG (5, 6)
468 fmtwarn (const substring_loc &fmt_loc, location_t param_loc,
469 const char *corrected_substring, int opt, const char *gmsgid, ...)
471 format_string_diagnostic_t diag (fmt_loc, NULL, param_loc, NULL,
472 corrected_substring);
473 va_list ap;
474 va_start (ap, gmsgid);
475 bool warned = diag.emit_warning_va (opt, gmsgid, &ap);
476 va_end (ap);
478 return warned;
481 static bool
482 ATTRIBUTE_GCC_DIAG (6, 8) ATTRIBUTE_GCC_DIAG (7, 8)
483 fmtwarn_n (const substring_loc &fmt_loc, location_t param_loc,
484 const char *corrected_substring, int opt, unsigned HOST_WIDE_INT n,
485 const char *singular_gmsgid, const char *plural_gmsgid, ...)
487 format_string_diagnostic_t diag (fmt_loc, NULL, param_loc, NULL,
488 corrected_substring);
489 va_list ap;
490 va_start (ap, plural_gmsgid);
491 bool warned = diag.emit_warning_n_va (opt, n, singular_gmsgid, plural_gmsgid,
492 &ap);
493 va_end (ap);
495 return warned;
498 /* Format length modifiers. */
500 enum format_lengths
502 FMT_LEN_none,
503 FMT_LEN_hh, // char argument
504 FMT_LEN_h, // short
505 FMT_LEN_l, // long
506 FMT_LEN_ll, // long long
507 FMT_LEN_L, // long double (and GNU long long)
508 FMT_LEN_z, // size_t
509 FMT_LEN_t, // ptrdiff_t
510 FMT_LEN_j // intmax_t
514 /* Description of the result of conversion either of a single directive
515 or the whole format string. */
517 struct fmtresult
519 /* Construct a FMTRESULT object with all counters initialized
520 to MIN. KNOWNRANGE is set when MIN is valid. */
521 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
522 : argmin (), argmax (), nonstr (),
523 knownrange (min < HOST_WIDE_INT_MAX),
524 mayfail (), nullp ()
526 range.min = min;
527 range.max = min;
528 range.likely = min;
529 range.unlikely = min;
532 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
533 KNOWNRANGE is set when both MIN and MAX are valid. */
534 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
535 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
536 : argmin (), argmax (), nonstr (),
537 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
538 mayfail (), nullp ()
540 range.min = min;
541 range.max = max;
542 range.likely = max < likely ? min : likely;
543 range.unlikely = max;
546 /* Adjust result upward to reflect the RANGE of values the specified
547 width or precision is known to be in. */
548 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
549 tree = NULL_TREE,
550 unsigned = 0, unsigned = 0);
552 /* Return the maximum number of decimal digits a value of TYPE
553 formats as on output. */
554 static unsigned type_max_digits (tree, int);
556 /* The range a directive's argument is in. */
557 tree argmin, argmax;
559 /* The minimum and maximum number of bytes that a directive
560 results in on output for an argument in the range above. */
561 result_range range;
563 /* Non-nul when the argument of a string directive is not a nul
564 terminated string. */
565 tree nonstr;
567 /* True when the range above is obtained from a known value of
568 a directive's argument or its bounds and not the result of
569 heuristics that depend on warning levels. */
570 bool knownrange;
572 /* True for a directive that may fail (such as wide character
573 directives). */
574 bool mayfail;
576 /* True when the argument is a null pointer. */
577 bool nullp;
580 /* Adjust result upward to reflect the range ADJUST of values the
581 specified width or precision is known to be in. When non-null,
582 TYPE denotes the type of the directive whose result is being
583 adjusted, BASE gives the base of the directive (octal, decimal,
584 or hex), and ADJ denotes the additional adjustment to the LIKELY
585 counter that may need to be added when ADJUST is a range. */
587 fmtresult&
588 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
589 tree type /* = NULL_TREE */,
590 unsigned base /* = 0 */,
591 unsigned adj /* = 0 */)
593 bool minadjusted = false;
595 /* Adjust the minimum and likely counters. */
596 if (adjust[0] >= 0)
598 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
600 range.min = adjust[0];
601 minadjusted = true;
604 /* Adjust the likely counter. */
605 if (range.likely < range.min)
606 range.likely = range.min;
608 else if (adjust[0] == target_int_min ()
609 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
610 knownrange = false;
612 /* Adjust the maximum counter. */
613 if (adjust[1] > 0)
615 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
617 range.max = adjust[1];
619 /* Set KNOWNRANGE if both the minimum and maximum have been
620 adjusted. Otherwise leave it at what it was before. */
621 knownrange = minadjusted;
625 if (warn_level > 1 && type)
627 /* For large non-constant width or precision whose range spans
628 the maximum number of digits produced by the directive for
629 any argument, set the likely number of bytes to be at most
630 the number digits plus other adjustment determined by the
631 caller (one for sign or two for the hexadecimal "0x"
632 prefix). */
633 unsigned dirdigs = type_max_digits (type, base);
634 if (adjust[0] < dirdigs && dirdigs < adjust[1]
635 && range.likely < dirdigs)
636 range.likely = dirdigs + adj;
638 else if (range.likely < (range.min ? range.min : 1))
640 /* Conservatively, set LIKELY to at least MIN but no less than
641 1 unless MAX is zero. */
642 range.likely = (range.min
643 ? range.min
644 : range.max && (range.max < HOST_WIDE_INT_MAX
645 || warn_level > 1) ? 1 : 0);
648 /* Finally adjust the unlikely counter to be at least as large as
649 the maximum. */
650 if (range.unlikely < range.max)
651 range.unlikely = range.max;
653 return *this;
656 /* Return the maximum number of digits a value of TYPE formats in
657 BASE on output, not counting base prefix . */
659 unsigned
660 fmtresult::type_max_digits (tree type, int base)
662 unsigned prec = TYPE_PRECISION (type);
663 switch (base)
665 case 8:
666 return (prec + 2) / 3;
667 case 10:
668 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
669 of 8, 16, 32, and 64 bits. */
670 return prec * 301 / 1000 + 1;
671 case 16:
672 return prec / 4;
675 gcc_unreachable ();
678 static bool
679 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT,
680 class vr_values *vr_values);
682 /* Description of a format directive. A directive is either a plain
683 string or a conversion specification that starts with '%'. */
685 struct directive
687 /* The 1-based directive number (for debugging). */
688 unsigned dirno;
690 /* The first character of the directive and its length. */
691 const char *beg;
692 size_t len;
694 /* A bitmap of flags, one for each character. */
695 unsigned flags[256 / sizeof (int)];
697 /* The range of values of the specified width, or -1 if not specified. */
698 HOST_WIDE_INT width[2];
699 /* The range of values of the specified precision, or -1 if not
700 specified. */
701 HOST_WIDE_INT prec[2];
703 /* Length modifier. */
704 format_lengths modifier;
706 /* Format specifier character. */
707 char specifier;
709 /* The argument of the directive or null when the directive doesn't
710 take one or when none is available (such as for vararg functions). */
711 tree arg;
713 /* Format conversion function that given a directive and an argument
714 returns the formatting result. */
715 fmtresult (*fmtfunc) (const directive &, tree, vr_values *);
717 /* Return True when a the format flag CHR has been used. */
718 bool get_flag (char chr) const
720 unsigned char c = chr & 0xff;
721 return (flags[c / (CHAR_BIT * sizeof *flags)]
722 & (1U << (c % (CHAR_BIT * sizeof *flags))));
725 /* Make a record of the format flag CHR having been used. */
726 void set_flag (char chr)
728 unsigned char c = chr & 0xff;
729 flags[c / (CHAR_BIT * sizeof *flags)]
730 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
733 /* Reset the format flag CHR. */
734 void clear_flag (char chr)
736 unsigned char c = chr & 0xff;
737 flags[c / (CHAR_BIT * sizeof *flags)]
738 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
741 /* Set both bounds of the width range to VAL. */
742 void set_width (HOST_WIDE_INT val)
744 width[0] = width[1] = val;
747 /* Set the width range according to ARG, with both bounds being
748 no less than 0. For a constant ARG set both bounds to its value
749 or 0, whichever is greater. For a non-constant ARG in some range
750 set width to its range adjusting each bound to -1 if it's less.
751 For an indeterminate ARG set width to [0, INT_MAX]. */
752 void set_width (tree arg, vr_values *vr_values)
754 get_int_range (arg, width, width + 1, true, 0, vr_values);
757 /* Set both bounds of the precision range to VAL. */
758 void set_precision (HOST_WIDE_INT val)
760 prec[0] = prec[1] = val;
763 /* Set the precision range according to ARG, with both bounds being
764 no less than -1. For a constant ARG set both bounds to its value
765 or -1 whichever is greater. For a non-constant ARG in some range
766 set precision to its range adjusting each bound to -1 if it's less.
767 For an indeterminate ARG set precision to [-1, INT_MAX]. */
768 void set_precision (tree arg, vr_values *vr_values)
770 get_int_range (arg, prec, prec + 1, false, -1, vr_values);
773 /* Return true if both width and precision are known to be
774 either constant or in some range, false otherwise. */
775 bool known_width_and_precision () const
777 return ((width[1] < 0
778 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
779 && (prec[1] < 0
780 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
784 /* Return the logarithm of X in BASE. */
786 static int
787 ilog (unsigned HOST_WIDE_INT x, int base)
789 int res = 0;
792 ++res;
793 x /= base;
794 } while (x);
795 return res;
798 /* Return the number of bytes resulting from converting into a string
799 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
800 PLUS indicates whether 1 for a plus sign should be added for positive
801 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
802 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
803 be represented. */
805 static HOST_WIDE_INT
806 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
808 unsigned HOST_WIDE_INT absval;
810 HOST_WIDE_INT res;
812 if (TYPE_UNSIGNED (TREE_TYPE (x)))
814 if (tree_fits_uhwi_p (x))
816 absval = tree_to_uhwi (x);
817 res = plus;
819 else
820 return -1;
822 else
824 if (tree_fits_shwi_p (x))
826 HOST_WIDE_INT i = tree_to_shwi (x);
827 if (HOST_WIDE_INT_MIN == i)
829 /* Avoid undefined behavior due to negating a minimum. */
830 absval = HOST_WIDE_INT_MAX;
831 res = 1;
833 else if (i < 0)
835 absval = -i;
836 res = 1;
838 else
840 absval = i;
841 res = plus;
844 else
845 return -1;
848 int ndigs = ilog (absval, base);
850 res += prec < ndigs ? ndigs : prec;
852 /* Adjust a non-zero value for the base prefix, either hexadecimal,
853 or, unless precision has resulted in a leading zero, also octal. */
854 if (prefix && absval && (base == 16 || prec <= ndigs))
856 if (base == 8)
857 res += 1;
858 else if (base == 16)
859 res += 2;
862 return res;
865 /* Given the formatting result described by RES and NAVAIL, the number
866 of available in the destination, return the range of bytes remaining
867 in the destination. */
869 static inline result_range
870 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
872 result_range range;
874 if (HOST_WIDE_INT_MAX <= navail)
876 range.min = range.max = range.likely = range.unlikely = navail;
877 return range;
880 /* The lower bound of the available range is the available size
881 minus the maximum output size, and the upper bound is the size
882 minus the minimum. */
883 range.max = res.range.min < navail ? navail - res.range.min : 0;
885 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
887 if (res.range.max < HOST_WIDE_INT_MAX)
888 range.min = res.range.max < navail ? navail - res.range.max : 0;
889 else
890 range.min = range.likely;
892 range.unlikely = (res.range.unlikely < navail
893 ? navail - res.range.unlikely : 0);
895 return range;
898 /* Description of a call to a formatted function. */
900 struct sprintf_dom_walker::call_info
902 /* Function call statement. */
903 gimple *callstmt;
905 /* Function called. */
906 tree func;
908 /* Called built-in function code. */
909 built_in_function fncode;
911 /* Format argument and format string extracted from it. */
912 tree format;
913 const char *fmtstr;
915 /* The location of the format argument. */
916 location_t fmtloc;
918 /* The destination object size for __builtin___xxx_chk functions
919 typically determined by __builtin_object_size, or -1 if unknown. */
920 unsigned HOST_WIDE_INT objsize;
922 /* Number of the first variable argument. */
923 unsigned HOST_WIDE_INT argidx;
925 /* True for functions like snprintf that specify the size of
926 the destination, false for others like sprintf that don't. */
927 bool bounded;
929 /* True for bounded functions like snprintf that specify a zero-size
930 buffer as a request to compute the size of output without actually
931 writing any. NOWRITE is cleared in response to the %n directive
932 which has side-effects similar to writing output. */
933 bool nowrite;
935 /* Return true if the called function's return value is used. */
936 bool retval_used () const
938 return gimple_get_lhs (callstmt);
941 /* Return the warning option corresponding to the called function. */
942 int warnopt () const
944 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
948 /* Return the result of formatting a no-op directive (such as '%n'). */
950 static fmtresult
951 format_none (const directive &, tree, vr_values *)
953 fmtresult res (0);
954 return res;
957 /* Return the result of formatting the '%%' directive. */
959 static fmtresult
960 format_percent (const directive &, tree, vr_values *)
962 fmtresult res (1);
963 return res;
967 /* Compute intmax_type_node and uintmax_type_node similarly to how
968 tree.c builds size_type_node. */
970 static void
971 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
973 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
975 *pintmax = integer_type_node;
976 *puintmax = unsigned_type_node;
978 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
980 *pintmax = long_integer_type_node;
981 *puintmax = long_unsigned_type_node;
983 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
985 *pintmax = long_long_integer_type_node;
986 *puintmax = long_long_unsigned_type_node;
988 else
990 for (int i = 0; i < NUM_INT_N_ENTS; i++)
991 if (int_n_enabled_p[i])
993 char name[50];
994 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
996 if (strcmp (name, UINTMAX_TYPE) == 0)
998 *pintmax = int_n_trees[i].signed_type;
999 *puintmax = int_n_trees[i].unsigned_type;
1000 return;
1003 gcc_unreachable ();
1007 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1008 in and that is representable in type int.
1009 Return true when the range is a subrange of that of int.
1010 When ARG is null it is as if it had the full range of int.
1011 When ABSOLUTE is true the range reflects the absolute value of
1012 the argument. When ABSOLUTE is false, negative bounds of
1013 the determined range are replaced with NEGBOUND. */
1015 static bool
1016 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1017 bool absolute, HOST_WIDE_INT negbound,
1018 class vr_values *vr_values)
1020 /* The type of the result. */
1021 const_tree type = integer_type_node;
1023 bool knownrange = false;
1025 if (!arg)
1027 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1028 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1030 else if (TREE_CODE (arg) == INTEGER_CST
1031 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1033 /* For a constant argument return its value adjusted as specified
1034 by NEGATIVE and NEGBOUND and return true to indicate that the
1035 result is known. */
1036 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1037 *pmax = *pmin;
1038 knownrange = true;
1040 else
1042 /* True if the argument's range cannot be determined. */
1043 bool unknown = true;
1045 tree argtype = TREE_TYPE (arg);
1047 /* Ignore invalid arguments with greater precision that that
1048 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1049 They will have been detected and diagnosed by -Wformat and
1050 so it's not important to complicate this code to try to deal
1051 with them again. */
1052 if (TREE_CODE (arg) == SSA_NAME
1053 && INTEGRAL_TYPE_P (argtype)
1054 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1056 /* Try to determine the range of values of the integer argument. */
1057 value_range *vr = vr_values->get_value_range (arg);
1058 if (range_int_cst_p (vr))
1060 HOST_WIDE_INT type_min
1061 = (TYPE_UNSIGNED (argtype)
1062 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1063 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1065 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1067 *pmin = TREE_INT_CST_LOW (vr->min ());
1068 *pmax = TREE_INT_CST_LOW (vr->max ());
1070 if (*pmin < *pmax)
1072 /* Return true if the adjusted range is a subrange of
1073 the full range of the argument's type. *PMAX may
1074 be less than *PMIN when the argument is unsigned
1075 and its upper bound is in excess of TYPE_MAX. In
1076 that (invalid) case disregard the range and use that
1077 of the expected type instead. */
1078 knownrange = type_min < *pmin || *pmax < type_max;
1080 unknown = false;
1085 /* Handle an argument with an unknown range as if none had been
1086 provided. */
1087 if (unknown)
1088 return get_int_range (NULL_TREE, pmin, pmax, absolute,
1089 negbound, vr_values);
1092 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1093 if (absolute)
1095 if (*pmin < 0)
1097 if (*pmin == *pmax)
1098 *pmin = *pmax = -*pmin;
1099 else
1101 /* Make sure signed overlow is avoided. */
1102 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1104 HOST_WIDE_INT tmp = -*pmin;
1105 *pmin = 0;
1106 if (*pmax < tmp)
1107 *pmax = tmp;
1111 else if (*pmin < negbound)
1112 *pmin = negbound;
1114 return knownrange;
1117 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1118 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1119 the type of the directive's formal argument it's possible for both
1120 to result in the same number of bytes or a range of bytes that's
1121 less than the number of bytes that would result from formatting
1122 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1123 determined by checking for the actual argument being in the range
1124 of the type of the directive. If it isn't it must be assumed to
1125 take on the full range of the directive's type.
1126 Return true when the range has been adjusted to the full range
1127 of DIRTYPE, and false otherwise. */
1129 static bool
1130 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1132 tree argtype = TREE_TYPE (*argmin);
1133 unsigned argprec = TYPE_PRECISION (argtype);
1134 unsigned dirprec = TYPE_PRECISION (dirtype);
1136 /* If the actual argument and the directive's argument have the same
1137 precision and sign there can be no overflow and so there is nothing
1138 to adjust. */
1139 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1140 return false;
1142 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1143 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1145 if (TREE_CODE (*argmin) == INTEGER_CST
1146 && TREE_CODE (*argmax) == INTEGER_CST
1147 && (dirprec >= argprec
1148 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1149 int_const_binop (MINUS_EXPR,
1150 *argmax,
1151 *argmin),
1152 size_int (dirprec)))))
1154 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1155 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1157 /* If *ARGMIN is still less than *ARGMAX the conversion above
1158 is safe. Otherwise, it has overflowed and would be unsafe. */
1159 if (tree_int_cst_le (*argmin, *argmax))
1160 return false;
1163 *argmin = TYPE_MIN_VALUE (dirtype);
1164 *argmax = TYPE_MAX_VALUE (dirtype);
1165 return true;
1168 /* Return a range representing the minimum and maximum number of bytes
1169 that the format directive DIR will output for any argument given
1170 the WIDTH and PRECISION (extracted from DIR). This function is
1171 used when the directive argument or its value isn't known. */
1173 static fmtresult
1174 format_integer (const directive &dir, tree arg, vr_values *vr_values)
1176 tree intmax_type_node;
1177 tree uintmax_type_node;
1179 /* Base to format the number in. */
1180 int base;
1182 /* True when a conversion is preceded by a prefix indicating the base
1183 of the argument (octal or hexadecimal). */
1184 bool maybebase = dir.get_flag ('#');
1186 /* True when a signed conversion is preceded by a sign or space. */
1187 bool maybesign = false;
1189 /* True for signed conversions (i.e., 'd' and 'i'). */
1190 bool sign = false;
1192 switch (dir.specifier)
1194 case 'd':
1195 case 'i':
1196 /* Space and '+' are only meaningful for signed conversions. */
1197 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1198 sign = true;
1199 base = 10;
1200 break;
1201 case 'u':
1202 base = 10;
1203 break;
1204 case 'o':
1205 base = 8;
1206 break;
1207 case 'X':
1208 case 'x':
1209 base = 16;
1210 break;
1211 default:
1212 gcc_unreachable ();
1215 /* The type of the "formal" argument expected by the directive. */
1216 tree dirtype = NULL_TREE;
1218 /* Determine the expected type of the argument from the length
1219 modifier. */
1220 switch (dir.modifier)
1222 case FMT_LEN_none:
1223 if (dir.specifier == 'p')
1224 dirtype = ptr_type_node;
1225 else
1226 dirtype = sign ? integer_type_node : unsigned_type_node;
1227 break;
1229 case FMT_LEN_h:
1230 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1231 break;
1233 case FMT_LEN_hh:
1234 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1235 break;
1237 case FMT_LEN_l:
1238 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1239 break;
1241 case FMT_LEN_L:
1242 case FMT_LEN_ll:
1243 dirtype = (sign
1244 ? long_long_integer_type_node
1245 : long_long_unsigned_type_node);
1246 break;
1248 case FMT_LEN_z:
1249 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1250 break;
1252 case FMT_LEN_t:
1253 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1254 break;
1256 case FMT_LEN_j:
1257 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1258 dirtype = sign ? intmax_type_node : uintmax_type_node;
1259 break;
1261 default:
1262 return fmtresult ();
1265 /* The type of the argument to the directive, either deduced from
1266 the actual non-constant argument if one is known, or from
1267 the directive itself when none has been provided because it's
1268 a va_list. */
1269 tree argtype = NULL_TREE;
1271 if (!arg)
1273 /* When the argument has not been provided, use the type of
1274 the directive's argument as an approximation. This will
1275 result in false positives for directives like %i with
1276 arguments with smaller precision (such as short or char). */
1277 argtype = dirtype;
1279 else if (TREE_CODE (arg) == INTEGER_CST)
1281 /* When a constant argument has been provided use its value
1282 rather than type to determine the length of the output. */
1283 fmtresult res;
1285 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1287 /* As a special case, a precision of zero with a zero argument
1288 results in zero bytes except in base 8 when the '#' flag is
1289 specified, and for signed conversions in base 8 and 10 when
1290 either the space or '+' flag has been specified and it results
1291 in just one byte (with width having the normal effect). This
1292 must extend to the case of a specified precision with
1293 an unknown value because it can be zero. */
1294 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1295 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1297 res.range.max = 1;
1298 res.range.likely = 1;
1300 else
1302 res.range.max = res.range.min;
1303 res.range.likely = res.range.min;
1306 else
1308 /* Convert the argument to the type of the directive. */
1309 arg = fold_convert (dirtype, arg);
1311 res.range.min = tree_digits (arg, base, dir.prec[0],
1312 maybesign, maybebase);
1313 if (dir.prec[0] == dir.prec[1])
1314 res.range.max = res.range.min;
1315 else
1316 res.range.max = tree_digits (arg, base, dir.prec[1],
1317 maybesign, maybebase);
1318 res.range.likely = res.range.min;
1319 res.knownrange = true;
1322 res.range.unlikely = res.range.max;
1324 /* Bump up the counters if WIDTH is greater than LEN. */
1325 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1326 (sign | maybebase) + (base == 16));
1327 /* Bump up the counters again if PRECision is greater still. */
1328 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1329 (sign | maybebase) + (base == 16));
1331 return res;
1333 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1334 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1335 /* Determine the type of the provided non-constant argument. */
1336 argtype = TREE_TYPE (arg);
1337 else
1338 /* Don't bother with invalid arguments since they likely would
1339 have already been diagnosed, and disable any further checking
1340 of the format string by returning [-1, -1]. */
1341 return fmtresult ();
1343 fmtresult res;
1345 /* Using either the range the non-constant argument is in, or its
1346 type (either "formal" or actual), create a range of values that
1347 constrain the length of output given the warning level. */
1348 tree argmin = NULL_TREE;
1349 tree argmax = NULL_TREE;
1351 if (arg
1352 && TREE_CODE (arg) == SSA_NAME
1353 && INTEGRAL_TYPE_P (argtype))
1355 /* Try to determine the range of values of the integer argument
1356 (range information is not available for pointers). */
1357 value_range *vr = vr_values->get_value_range (arg);
1358 if (range_int_cst_p (vr))
1360 argmin = vr->min ();
1361 argmax = vr->max ();
1363 /* Set KNOWNRANGE if the argument is in a known subrange
1364 of the directive's type and neither width nor precision
1365 is unknown. (KNOWNRANGE may be reset below). */
1366 res.knownrange
1367 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1368 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1369 && dir.known_width_and_precision ());
1371 res.argmin = argmin;
1372 res.argmax = argmax;
1374 else if (vr->kind () == VR_ANTI_RANGE)
1376 /* Handle anti-ranges if/when bug 71690 is resolved. */
1378 else if (vr->varying_p () || vr->undefined_p ())
1380 /* The argument here may be the result of promoting the actual
1381 argument to int. Try to determine the type of the actual
1382 argument before promotion and narrow down its range that
1383 way. */
1384 gimple *def = SSA_NAME_DEF_STMT (arg);
1385 if (is_gimple_assign (def))
1387 tree_code code = gimple_assign_rhs_code (def);
1388 if (code == INTEGER_CST)
1390 arg = gimple_assign_rhs1 (def);
1391 return format_integer (dir, arg, vr_values);
1394 if (code == NOP_EXPR)
1396 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1397 if (INTEGRAL_TYPE_P (type)
1398 || TREE_CODE (type) == POINTER_TYPE)
1399 argtype = type;
1405 if (!argmin)
1407 if (TREE_CODE (argtype) == POINTER_TYPE)
1409 argmin = build_int_cst (pointer_sized_int_node, 0);
1410 argmax = build_all_ones_cst (pointer_sized_int_node);
1412 else
1414 argmin = TYPE_MIN_VALUE (argtype);
1415 argmax = TYPE_MAX_VALUE (argtype);
1419 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1420 of the directive. If it has been cleared then since ARGMIN and/or
1421 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1422 ARGMAX in the result to include in diagnostics. */
1423 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1425 res.knownrange = false;
1426 res.argmin = argmin;
1427 res.argmax = argmax;
1430 /* Recursively compute the minimum and maximum from the known range. */
1431 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1433 /* For unsigned conversions/directives or signed when
1434 the minimum is positive, use the minimum and maximum to compute
1435 the shortest and longest output, respectively. */
1436 res.range.min = format_integer (dir, argmin, vr_values).range.min;
1437 res.range.max = format_integer (dir, argmax, vr_values).range.max;
1439 else if (tree_int_cst_sgn (argmax) < 0)
1441 /* For signed conversions/directives if maximum is negative,
1442 use the minimum as the longest output and maximum as the
1443 shortest output. */
1444 res.range.min = format_integer (dir, argmax, vr_values).range.min;
1445 res.range.max = format_integer (dir, argmin, vr_values).range.max;
1447 else
1449 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1450 as the shortest output and for the longest output compute the
1451 length of the output of both minimum and maximum and pick the
1452 longer. */
1453 unsigned HOST_WIDE_INT max1
1454 = format_integer (dir, argmin, vr_values).range.max;
1455 unsigned HOST_WIDE_INT max2
1456 = format_integer (dir, argmax, vr_values).range.max;
1457 res.range.min
1458 = format_integer (dir, integer_zero_node, vr_values).range.min;
1459 res.range.max = MAX (max1, max2);
1462 /* If the range is known, use the maximum as the likely length. */
1463 if (res.knownrange)
1464 res.range.likely = res.range.max;
1465 else
1467 /* Otherwise, use the minimum. Except for the case where for %#x or
1468 %#o the minimum is just for a single value in the range (0) and
1469 for all other values it is something longer, like 0x1 or 01.
1470 Use the length for value 1 in that case instead as the likely
1471 length. */
1472 res.range.likely = res.range.min;
1473 if (maybebase
1474 && base != 10
1475 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1477 if (res.range.min == 1)
1478 res.range.likely += base == 8 ? 1 : 2;
1479 else if (res.range.min == 2
1480 && base == 16
1481 && (dir.width[0] == 2 || dir.prec[0] == 2))
1482 ++res.range.likely;
1486 res.range.unlikely = res.range.max;
1487 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1488 (sign | maybebase) + (base == 16));
1489 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1490 (sign | maybebase) + (base == 16));
1492 return res;
1495 /* Return the number of bytes that a format directive consisting of FLAGS,
1496 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1497 would result for argument X under ideal conditions (i.e., if PREC
1498 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1499 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1500 This function works around those problems. */
1502 static unsigned HOST_WIDE_INT
1503 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1504 char spec, char rndspec)
1506 char fmtstr[40];
1508 HOST_WIDE_INT len = strlen (flags);
1510 fmtstr[0] = '%';
1511 memcpy (fmtstr + 1, flags, len);
1512 memcpy (fmtstr + 1 + len, ".*R", 3);
1513 fmtstr[len + 4] = rndspec;
1514 fmtstr[len + 5] = spec;
1515 fmtstr[len + 6] = '\0';
1517 spec = TOUPPER (spec);
1518 if (spec == 'E' || spec == 'F')
1520 /* For %e, specify the precision explicitly since mpfr_sprintf
1521 does its own thing just to be different (see MPFR bug 21088). */
1522 if (prec < 0)
1523 prec = 6;
1525 else
1527 /* Avoid passing negative precisions with larger magnitude to MPFR
1528 to avoid exposing its bugs. (A negative precision is supposed
1529 to be ignored.) */
1530 if (prec < 0)
1531 prec = -1;
1534 HOST_WIDE_INT p = prec;
1536 if (spec == 'G' && !strchr (flags, '#'))
1538 /* For G/g without the pound flag, precision gives the maximum number
1539 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1540 a 128 bit IEEE extended precision, 4932. Using twice as much here
1541 should be more than sufficient for any real format. */
1542 if ((IEEE_MAX_10_EXP * 2) < prec)
1543 prec = IEEE_MAX_10_EXP * 2;
1544 p = prec;
1546 else
1548 /* Cap precision arbitrarily at 1KB and add the difference
1549 (if any) to the MPFR result. */
1550 if (prec > 1024)
1551 p = 1024;
1554 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1556 /* Handle the unlikely (impossible?) error by returning more than
1557 the maximum dictated by the function's return type. */
1558 if (len < 0)
1559 return target_dir_max () + 1;
1561 /* Adjust the return value by the difference. */
1562 if (p < prec)
1563 len += prec - p;
1565 return len;
1568 /* Return the number of bytes to format using the format specifier
1569 SPEC and the precision PREC the largest value in the real floating
1570 TYPE. */
1572 static unsigned HOST_WIDE_INT
1573 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1575 machine_mode mode = TYPE_MODE (type);
1577 /* IBM Extended mode. */
1578 if (MODE_COMPOSITE_P (mode))
1579 mode = DFmode;
1581 /* Get the real type format desription for the target. */
1582 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1583 REAL_VALUE_TYPE rv;
1585 real_maxval (&rv, 0, mode);
1587 /* Convert the GCC real value representation with the precision
1588 of the real type to the mpfr_t format with the GCC default
1589 round-to-nearest mode. */
1590 mpfr_t x;
1591 mpfr_init2 (x, rfmt->p);
1592 mpfr_from_real (x, &rv, GMP_RNDN);
1594 /* Return a value one greater to account for the leading minus sign. */
1595 unsigned HOST_WIDE_INT r
1596 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1597 mpfr_clear (x);
1598 return r;
1601 /* Return a range representing the minimum and maximum number of bytes
1602 that the directive DIR will output for any argument. PREC gives
1603 the adjusted precision range to account for negative precisions
1604 meaning the default 6. This function is used when the directive
1605 argument or its value isn't known. */
1607 static fmtresult
1608 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1610 tree type;
1612 switch (dir.modifier)
1614 case FMT_LEN_l:
1615 case FMT_LEN_none:
1616 type = double_type_node;
1617 break;
1619 case FMT_LEN_L:
1620 type = long_double_type_node;
1621 break;
1623 case FMT_LEN_ll:
1624 type = long_double_type_node;
1625 break;
1627 default:
1628 return fmtresult ();
1631 /* The minimum and maximum number of bytes produced by the directive. */
1632 fmtresult res;
1634 /* The minimum output as determined by flags. It's always at least 1.
1635 When plus or space are set the output is preceded by either a sign
1636 or a space. */
1637 unsigned flagmin = (1 /* for the first digit */
1638 + (dir.get_flag ('+') | dir.get_flag (' ')));
1640 /* The minimum is 3 for "inf" and "nan" for all specifiers, plus 1
1641 for the plus sign/space with the '+' and ' ' flags, respectively,
1642 unless reduced below. */
1643 res.range.min = 2 + flagmin;
1645 /* When the pound flag is set the decimal point is included in output
1646 regardless of precision. Whether or not a decimal point is included
1647 otherwise depends on the specification and precision. */
1648 bool radix = dir.get_flag ('#');
1650 switch (dir.specifier)
1652 case 'A':
1653 case 'a':
1655 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1656 if (dir.prec[0] <= 0)
1657 minprec = 0;
1658 else if (dir.prec[0] > 0)
1659 minprec = dir.prec[0] + !radix /* decimal point */;
1661 res.range.likely = (2 /* 0x */
1662 + flagmin
1663 + radix
1664 + minprec
1665 + 3 /* p+0 */);
1667 res.range.max = format_floating_max (type, 'a', prec[1]);
1669 /* The unlikely maximum accounts for the longest multibyte
1670 decimal point character. */
1671 res.range.unlikely = res.range.max;
1672 if (dir.prec[1] > 0)
1673 res.range.unlikely += target_mb_len_max () - 1;
1675 break;
1678 case 'E':
1679 case 'e':
1681 /* Minimum output attributable to precision and, when it's
1682 non-zero, decimal point. */
1683 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1685 /* The likely minimum output is "[-+]1.234567e+00" regardless
1686 of the value of the actual argument. */
1687 res.range.likely = (flagmin
1688 + radix
1689 + minprec
1690 + 2 /* e+ */ + 2);
1692 res.range.max = format_floating_max (type, 'e', prec[1]);
1694 /* The unlikely maximum accounts for the longest multibyte
1695 decimal point character. */
1696 if (dir.prec[0] != dir.prec[1]
1697 || dir.prec[0] == -1 || dir.prec[0] > 0)
1698 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1699 else
1700 res.range.unlikely = res.range.max;
1701 break;
1704 case 'F':
1705 case 'f':
1707 /* Minimum output attributable to precision and, when it's non-zero,
1708 decimal point. */
1709 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1711 /* For finite numbers (i.e., not infinity or NaN) the lower bound
1712 when precision isn't specified is 8 bytes ("1.23456" since
1713 precision is taken to be 6). When precision is zero, the lower
1714 bound is 1 byte (e.g., "1"). Otherwise, when precision is greater
1715 than zero, then the lower bound is 2 plus precision (plus flags).
1716 But in all cases, the lower bound is no greater than 3. */
1717 unsigned HOST_WIDE_INT min = flagmin + radix + minprec;
1718 if (min < res.range.min)
1719 res.range.min = min;
1721 /* Compute the upper bound for -TYPE_MAX. */
1722 res.range.max = format_floating_max (type, 'f', prec[1]);
1724 /* The minimum output with unknown precision is a single byte
1725 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1726 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1727 res.range.likely = 3;
1728 else
1729 res.range.likely = min;
1731 /* The unlikely maximum accounts for the longest multibyte
1732 decimal point character. */
1733 if (dir.prec[0] != dir.prec[1]
1734 || dir.prec[0] == -1 || dir.prec[0] > 0)
1735 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1736 break;
1739 case 'G':
1740 case 'g':
1742 /* The %g output depends on precision and the exponent of
1743 the argument. Since the value of the argument isn't known
1744 the lower bound on the range of bytes (not counting flags
1745 or width) is 1 plus radix (i.e., either "0" or "0." for
1746 "%g" and "%#g", respectively, with a zero argument). */
1747 unsigned HOST_WIDE_INT min = flagmin + radix;
1748 if (min < res.range.min)
1749 res.range.min = min;
1751 char spec = 'g';
1752 HOST_WIDE_INT maxprec = dir.prec[1];
1753 if (radix && maxprec)
1755 /* When the pound flag (radix) is set, trailing zeros aren't
1756 trimmed and so the longest output is the same as for %e,
1757 except with precision minus 1 (as specified in C11). */
1758 spec = 'e';
1759 if (maxprec > 0)
1760 --maxprec;
1761 else if (maxprec < 0)
1762 maxprec = 5;
1764 else
1765 maxprec = prec[1];
1767 res.range.max = format_floating_max (type, spec, maxprec);
1769 /* The likely output is either the maximum computed above
1770 minus 1 (assuming the maximum is positive) when precision
1771 is known (or unspecified), or the same minimum as for %e
1772 (which is computed for a non-negative argument). Unlike
1773 for the other specifiers above the likely output isn't
1774 the minimum because for %g that's 1 which is unlikely. */
1775 if (dir.prec[1] < 0
1776 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1777 res.range.likely = res.range.max - 1;
1778 else
1780 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1781 res.range.likely = (flagmin
1782 + radix
1783 + minprec
1784 + 2 /* e+ */ + 2);
1787 /* The unlikely maximum accounts for the longest multibyte
1788 decimal point character. */
1789 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1790 break;
1793 default:
1794 return fmtresult ();
1797 /* Bump up the byte counters if WIDTH is greater. */
1798 res.adjust_for_width_or_precision (dir.width);
1799 return res;
1802 /* Return a range representing the minimum and maximum number of bytes
1803 that the directive DIR will write on output for the floating argument
1804 ARG. */
1806 static fmtresult
1807 format_floating (const directive &dir, tree arg, vr_values *)
1809 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1810 tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1811 ? long_double_type_node : double_type_node);
1813 /* For an indeterminate precision the lower bound must be assumed
1814 to be zero. */
1815 if (TOUPPER (dir.specifier) == 'A')
1817 /* Get the number of fractional decimal digits needed to represent
1818 the argument without a loss of accuracy. */
1819 unsigned fmtprec
1820 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1822 /* The precision of the IEEE 754 double format is 53.
1823 The precision of all other GCC binary double formats
1824 is 56 or less. */
1825 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1827 /* For %a, leave the minimum precision unspecified to let
1828 MFPR trim trailing zeros (as it and many other systems
1829 including Glibc happen to do) and set the maximum
1830 precision to reflect what it would be with trailing zeros
1831 present (as Solaris and derived systems do). */
1832 if (dir.prec[1] < 0)
1834 /* Both bounds are negative implies that precision has
1835 not been specified. */
1836 prec[0] = maxprec;
1837 prec[1] = -1;
1839 else if (dir.prec[0] < 0)
1841 /* With a negative lower bound and a non-negative upper
1842 bound set the minimum precision to zero and the maximum
1843 to the greater of the maximum precision (i.e., with
1844 trailing zeros present) and the specified upper bound. */
1845 prec[0] = 0;
1846 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1849 else if (dir.prec[0] < 0)
1851 if (dir.prec[1] < 0)
1853 /* A precision in a strictly negative range is ignored and
1854 the default of 6 is used instead. */
1855 prec[0] = prec[1] = 6;
1857 else
1859 /* For a precision in a partly negative range, the lower bound
1860 must be assumed to be zero and the new upper bound is the
1861 greater of 6 (the default precision used when the specified
1862 precision is negative) and the upper bound of the specified
1863 range. */
1864 prec[0] = 0;
1865 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1869 if (!arg
1870 || TREE_CODE (arg) != REAL_CST
1871 || !useless_type_conversion_p (type, TREE_TYPE (arg)))
1872 return format_floating (dir, prec);
1874 /* The minimum and maximum number of bytes produced by the directive. */
1875 fmtresult res;
1877 /* Get the real type format desription for the target. */
1878 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1879 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1881 if (!real_isfinite (rvp))
1883 /* The format for Infinity and NaN is "[-]inf"/"[-]infinity"
1884 and "[-]nan" with the choice being implementation-defined
1885 but not locale dependent. */
1886 bool sign = dir.get_flag ('+') || real_isneg (rvp);
1887 res.range.min = 3 + sign;
1889 res.range.likely = res.range.min;
1890 res.range.max = res.range.min;
1891 /* The unlikely maximum is "[-/+]infinity" or "[-/+][qs]nan".
1892 For NaN, the C/POSIX standards specify two formats:
1893 "[-/+]nan"
1895 "[-/+]nan(n-char-sequence)"
1896 No known printf implementation outputs the latter format but AIX
1897 outputs QNaN and SNaN for quiet and signalling NaN, respectively,
1898 so the unlikely maximum reflects that. */
1899 res.range.unlikely = sign + (real_isinf (rvp) ? 8 : 4);
1901 /* The range for infinity and NaN is known unless either width
1902 or precision is unknown. Width has the same effect regardless
1903 of whether the argument is finite. Precision is either ignored
1904 (e.g., Glibc) or can have an effect on the short vs long format
1905 such as inf/infinity (e.g., Solaris). */
1906 res.knownrange = dir.known_width_and_precision ();
1908 /* Adjust the range for width but ignore precision. */
1909 res.adjust_for_width_or_precision (dir.width);
1911 return res;
1914 char fmtstr [40];
1915 char *pfmt = fmtstr;
1917 /* Append flags. */
1918 for (const char *pf = "-+ #0"; *pf; ++pf)
1919 if (dir.get_flag (*pf))
1920 *pfmt++ = *pf;
1922 *pfmt = '\0';
1925 /* Set up an array to easily iterate over. */
1926 unsigned HOST_WIDE_INT* const minmax[] = {
1927 &res.range.min, &res.range.max
1930 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1932 /* Convert the GCC real value representation with the precision
1933 of the real type to the mpfr_t format rounding down in the
1934 first iteration that computes the minimm and up in the second
1935 that computes the maximum. This order is arbibtrary because
1936 rounding in either direction can result in longer output. */
1937 mpfr_t mpfrval;
1938 mpfr_init2 (mpfrval, rfmt->p);
1939 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1941 /* Use the MPFR rounding specifier to round down in the first
1942 iteration and then up. In most but not all cases this will
1943 result in the same number of bytes. */
1944 char rndspec = "DU"[i];
1946 /* Format it and store the result in the corresponding member
1947 of the result struct. */
1948 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1949 dir.specifier, rndspec);
1950 mpfr_clear (mpfrval);
1954 /* Make sure the minimum is less than the maximum (MPFR rounding
1955 in the call to mpfr_snprintf can result in the reverse. */
1956 if (res.range.max < res.range.min)
1958 unsigned HOST_WIDE_INT tmp = res.range.min;
1959 res.range.min = res.range.max;
1960 res.range.max = tmp;
1963 /* The range is known unless either width or precision is unknown. */
1964 res.knownrange = dir.known_width_and_precision ();
1966 /* For the same floating point constant, unless width or precision
1967 is unknown, use the longer output as the likely maximum since
1968 with round to nearest either is equally likely. Otheriwse, when
1969 precision is unknown, use the greater of the minimum and 3 as
1970 the likely output (for "0.0" since zero precision is unlikely). */
1971 if (res.knownrange)
1972 res.range.likely = res.range.max;
1973 else if (res.range.min < 3
1974 && dir.prec[0] < 0
1975 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
1976 res.range.likely = 3;
1977 else
1978 res.range.likely = res.range.min;
1980 res.range.unlikely = res.range.max;
1982 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
1984 /* Unless the precision is zero output longer than 2 bytes may
1985 include the decimal point which must be a single character
1986 up to MB_LEN_MAX in length. This is overly conservative
1987 since in some conversions some constants result in no decimal
1988 point (e.g., in %g). */
1989 res.range.unlikely += target_mb_len_max () - 1;
1992 res.adjust_for_width_or_precision (dir.width);
1993 return res;
1996 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1997 strings referenced by the expression STR, or (-1, -1) when not known.
1998 Used by the format_string function below. */
2000 static fmtresult
2001 get_string_length (tree str, unsigned eltsize)
2003 if (!str)
2004 return fmtresult ();
2006 /* Determine the length of the shortest and longest string referenced
2007 by STR. Strings of unknown lengths are bounded by the sizes of
2008 arrays that subexpressions of STR may refer to. Pointers that
2009 aren't known to point any such arrays result in LENDATA.MAXLEN
2010 set to SIZE_MAX. */
2011 c_strlen_data lendata = { };
2012 get_range_strlen (str, &lendata, eltsize);
2014 /* Return the default result when nothing is known about the string. */
2015 if (integer_all_onesp (lendata.maxbound)
2016 && integer_all_onesp (lendata.maxlen))
2017 return fmtresult ();
2019 HOST_WIDE_INT min
2020 = (tree_fits_uhwi_p (lendata.minlen)
2021 ? tree_to_uhwi (lendata.minlen)
2022 : 0);
2024 HOST_WIDE_INT max
2025 = (tree_fits_uhwi_p (lendata.maxbound)
2026 ? tree_to_uhwi (lendata.maxbound)
2027 : HOST_WIDE_INT_M1U);
2029 const bool unbounded = integer_all_onesp (lendata.maxlen);
2031 /* Set the max/likely counters to unbounded when a minimum is known
2032 but the maximum length isn't bounded. This implies that STR is
2033 a conditional expression involving a string of known length and
2034 and an expression of unknown/unbounded length. */
2035 if (min
2036 && (unsigned HOST_WIDE_INT)min < HOST_WIDE_INT_M1U
2037 && unbounded)
2038 max = HOST_WIDE_INT_M1U;
2040 /* get_range_strlen() returns the target value of SIZE_MAX for
2041 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2042 which may be bigger. */
2043 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2044 min = HOST_WIDE_INT_M1U;
2045 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2046 max = HOST_WIDE_INT_M1U;
2048 fmtresult res (min, max);
2049 res.nonstr = lendata.decl;
2051 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2052 by STR are known to be bounded (though not necessarily by their
2053 actual length but perhaps by their maximum possible length). */
2054 if (res.range.max < target_int_max ())
2056 res.knownrange = true;
2057 /* When the the length of the longest string is known and not
2058 excessive use it as the likely length of the string(s). */
2059 res.range.likely = res.range.max;
2061 else
2063 /* When the upper bound is unknown (it can be zero or excessive)
2064 set the likely length to the greater of 1 and the length of
2065 the shortest string and reset the lower bound to zero. */
2066 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2067 res.range.min = 0;
2070 res.range.unlikely = unbounded ? HOST_WIDE_INT_MAX : res.range.max;
2072 return res;
2075 /* Return the minimum and maximum number of characters formatted
2076 by the '%c' format directives and its wide character form for
2077 the argument ARG. ARG can be null (for functions such as
2078 vsprinf). */
2080 static fmtresult
2081 format_character (const directive &dir, tree arg, vr_values *vr_values)
2083 fmtresult res;
2085 res.knownrange = true;
2087 if (dir.specifier == 'C'
2088 || dir.modifier == FMT_LEN_l)
2090 /* A wide character can result in as few as zero bytes. */
2091 res.range.min = 0;
2093 HOST_WIDE_INT min, max;
2094 if (get_int_range (arg, &min, &max, false, 0, vr_values))
2096 if (min == 0 && max == 0)
2098 /* The NUL wide character results in no bytes. */
2099 res.range.max = 0;
2100 res.range.likely = 0;
2101 res.range.unlikely = 0;
2103 else if (min >= 0 && min < 128)
2105 /* Be conservative if the target execution character set
2106 is not a 1-to-1 mapping to the source character set or
2107 if the source set is not ASCII. */
2108 bool one_2_one_ascii
2109 = (target_to_host_charmap[0] == 1 && target_to_host ('a') == 97);
2111 /* A wide character in the ASCII range most likely results
2112 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2113 res.range.max = one_2_one_ascii ? 1 : target_mb_len_max ();;
2114 res.range.likely = 1;
2115 res.range.unlikely = target_mb_len_max ();
2116 res.mayfail = !one_2_one_ascii;
2118 else
2120 /* A wide character outside the ASCII range likely results
2121 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2122 res.range.max = target_mb_len_max ();
2123 res.range.likely = 2;
2124 res.range.unlikely = res.range.max;
2125 /* Converting such a character may fail. */
2126 res.mayfail = true;
2129 else
2131 /* An unknown wide character is treated the same as a wide
2132 character outside the ASCII range. */
2133 res.range.max = target_mb_len_max ();
2134 res.range.likely = 2;
2135 res.range.unlikely = res.range.max;
2136 res.mayfail = true;
2139 else
2141 /* A plain '%c' directive. Its ouput is exactly 1. */
2142 res.range.min = res.range.max = 1;
2143 res.range.likely = res.range.unlikely = 1;
2144 res.knownrange = true;
2147 /* Bump up the byte counters if WIDTH is greater. */
2148 return res.adjust_for_width_or_precision (dir.width);
2151 /* Return the minimum and maximum number of characters formatted
2152 by the '%s' format directive and its wide character form for
2153 the argument ARG. ARG can be null (for functions such as
2154 vsprinf). */
2156 static fmtresult
2157 format_string (const directive &dir, tree arg, vr_values *)
2159 fmtresult res;
2161 /* Compute the range the argument's length can be in. */
2162 int count_by = 1;
2163 if (dir.specifier == 'S' || dir.modifier == FMT_LEN_l)
2165 /* Get a node for a C type that will be the same size
2166 as a wchar_t on the target. */
2167 tree node = get_typenode_from_name (MODIFIED_WCHAR_TYPE);
2169 /* Now that we have a suitable node, get the number of
2170 bytes it occupies. */
2171 count_by = int_size_in_bytes (node);
2172 gcc_checking_assert (count_by == 2 || count_by == 4);
2175 fmtresult slen = get_string_length (arg, count_by);
2176 if (slen.range.min == slen.range.max
2177 && slen.range.min < HOST_WIDE_INT_MAX)
2179 /* The argument is either a string constant or it refers
2180 to one of a number of strings of the same length. */
2182 /* A '%s' directive with a string argument with constant length. */
2183 res.range = slen.range;
2185 if (dir.specifier == 'S'
2186 || dir.modifier == FMT_LEN_l)
2188 /* In the worst case the length of output of a wide string S
2189 is bounded by MB_LEN_MAX * wcslen (S). */
2190 res.range.max *= target_mb_len_max ();
2191 res.range.unlikely = res.range.max;
2192 /* It's likely that the the total length is not more that
2193 2 * wcslen (S).*/
2194 res.range.likely = res.range.min * 2;
2196 if (dir.prec[1] >= 0
2197 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2199 res.range.max = dir.prec[1];
2200 res.range.likely = dir.prec[1];
2201 res.range.unlikely = dir.prec[1];
2204 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2205 res.range.min = 0;
2206 else if (dir.prec[0] >= 0)
2207 res.range.likely = dir.prec[0];
2209 /* Even a non-empty wide character string need not convert into
2210 any bytes. */
2211 res.range.min = 0;
2213 /* A non-empty wide character conversion may fail. */
2214 if (slen.range.max > 0)
2215 res.mayfail = true;
2217 else
2219 res.knownrange = true;
2221 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2222 res.range.min = 0;
2223 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2224 res.range.min = dir.prec[0];
2226 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2228 res.range.max = dir.prec[1];
2229 res.range.likely = dir.prec[1];
2230 res.range.unlikely = dir.prec[1];
2234 else if (arg && integer_zerop (arg))
2236 /* Handle null pointer argument. */
2238 fmtresult res (0);
2239 res.nullp = true;
2240 return res;
2242 else
2244 /* For a '%s' and '%ls' directive with a non-constant string (either
2245 one of a number of strings of known length or an unknown string)
2246 the minimum number of characters is lesser of PRECISION[0] and
2247 the length of the shortest known string or zero, and the maximum
2248 is the lessser of the length of the longest known string or
2249 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2250 the minimum at level 1 and the greater of the minimum and 1
2251 at level 2. This result is adjust upward for width (if it's
2252 specified). */
2254 if (dir.specifier == 'S'
2255 || dir.modifier == FMT_LEN_l)
2257 /* A wide character converts to as few as zero bytes. */
2258 slen.range.min = 0;
2259 if (slen.range.max < target_int_max ())
2260 slen.range.max *= target_mb_len_max ();
2262 if (slen.range.likely < target_int_max ())
2263 slen.range.likely *= 2;
2265 if (slen.range.likely < target_int_max ())
2266 slen.range.unlikely *= target_mb_len_max ();
2268 /* A non-empty wide character conversion may fail. */
2269 if (slen.range.max > 0)
2270 res.mayfail = true;
2273 res.range = slen.range;
2275 if (dir.prec[0] >= 0)
2277 /* Adjust the minimum to zero if the string length is unknown,
2278 or at most the lower bound of the precision otherwise. */
2279 if (slen.range.min >= target_int_max ())
2280 res.range.min = 0;
2281 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2282 res.range.min = dir.prec[0];
2284 /* Make both maxima no greater than the upper bound of precision. */
2285 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2286 || slen.range.max >= target_int_max ())
2288 res.range.max = dir.prec[1];
2289 res.range.unlikely = dir.prec[1];
2292 /* If precision is constant, set the likely counter to the lesser
2293 of it and the maximum string length. Otherwise, if the lower
2294 bound of precision is greater than zero, set the likely counter
2295 to the minimum. Otherwise set it to zero or one based on
2296 the warning level. */
2297 if (dir.prec[0] == dir.prec[1])
2298 res.range.likely
2299 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2300 ? dir.prec[0] : slen.range.max);
2301 else if (dir.prec[0] > 0)
2302 res.range.likely = res.range.min;
2303 else
2304 res.range.likely = warn_level > 1;
2306 else if (dir.prec[1] >= 0)
2308 res.range.min = 0;
2309 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2310 res.range.max = dir.prec[1];
2311 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2312 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.unlikely)
2313 res.range.unlikely = dir.prec[1];
2315 else if (slen.range.min >= target_int_max ())
2317 res.range.min = 0;
2318 res.range.max = HOST_WIDE_INT_MAX;
2319 /* At level 1 strings of unknown length are assumed to be
2320 empty, while at level 1 they are assumed to be one byte
2321 long. */
2322 res.range.likely = warn_level > 1;
2323 res.range.unlikely = HOST_WIDE_INT_MAX;
2325 else
2327 /* A string of unknown length unconstrained by precision is
2328 assumed to be empty at level 1 and just one character long
2329 at higher levels. */
2330 if (res.range.likely >= target_int_max ())
2331 res.range.likely = warn_level > 1;
2335 /* If the argument isn't a nul-terminated string and the number
2336 of bytes on output isn't bounded by precision, set NONSTR. */
2337 if (slen.nonstr && slen.range.min < (unsigned HOST_WIDE_INT)dir.prec[0])
2338 res.nonstr = slen.nonstr;
2340 /* Bump up the byte counters if WIDTH is greater. */
2341 return res.adjust_for_width_or_precision (dir.width);
2344 /* Format plain string (part of the format string itself). */
2346 static fmtresult
2347 format_plain (const directive &dir, tree, vr_values *)
2349 fmtresult res (dir.len);
2350 return res;
2353 /* Return true if the RESULT of a directive in a call describe by INFO
2354 should be diagnosed given the AVAILable space in the destination. */
2356 static bool
2357 should_warn_p (const sprintf_dom_walker::call_info &info,
2358 const result_range &avail, const result_range &result)
2360 if (result.max <= avail.min)
2362 /* The least amount of space remaining in the destination is big
2363 enough for the longest output. */
2364 return false;
2367 if (info.bounded)
2369 if (warn_format_trunc == 1 && result.min <= avail.max
2370 && info.retval_used ())
2372 /* The likely amount of space remaining in the destination is big
2373 enough for the least output and the return value is used. */
2374 return false;
2377 if (warn_format_trunc == 1 && result.likely <= avail.likely
2378 && !info.retval_used ())
2380 /* The likely amount of space remaining in the destination is big
2381 enough for the likely output and the return value is unused. */
2382 return false;
2385 if (warn_format_trunc == 2
2386 && result.likely <= avail.min
2387 && (result.max <= avail.min
2388 || result.max > HOST_WIDE_INT_MAX))
2390 /* The minimum amount of space remaining in the destination is big
2391 enough for the longest output. */
2392 return false;
2395 else
2397 if (warn_level == 1 && result.likely <= avail.likely)
2399 /* The likely amount of space remaining in the destination is big
2400 enough for the likely output. */
2401 return false;
2404 if (warn_level == 2
2405 && result.likely <= avail.min
2406 && (result.max <= avail.min
2407 || result.max > HOST_WIDE_INT_MAX))
2409 /* The minimum amount of space remaining in the destination is big
2410 enough for the longest output. */
2411 return false;
2415 return true;
2418 /* At format string location describe by DIRLOC in a call described
2419 by INFO, issue a warning for a directive DIR whose output may be
2420 in excess of the available space AVAIL_RANGE in the destination
2421 given the formatting result FMTRES. This function does nothing
2422 except decide whether to issue a warning for a possible write
2423 past the end or truncation and, if so, format the warning.
2424 Return true if a warning has been issued. */
2426 static bool
2427 maybe_warn (substring_loc &dirloc, location_t argloc,
2428 const sprintf_dom_walker::call_info &info,
2429 const result_range &avail_range, const result_range &res,
2430 const directive &dir)
2432 if (!should_warn_p (info, avail_range, res))
2433 return false;
2435 /* A warning will definitely be issued below. */
2437 /* The maximum byte count to reference in the warning. Larger counts
2438 imply that the upper bound is unknown (and could be anywhere between
2439 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2440 than "between N and X" where X is some huge number. */
2441 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2443 /* True when there is enough room in the destination for the least
2444 amount of a directive's output but not enough for its likely or
2445 maximum output. */
2446 bool maybe = (res.min <= avail_range.max
2447 && (avail_range.min < res.likely
2448 || (res.max < HOST_WIDE_INT_MAX
2449 && avail_range.min < res.max)));
2451 /* Buffer for the directive in the host character set (used when
2452 the source character set is different). */
2453 char hostdir[32];
2455 if (avail_range.min == avail_range.max)
2457 /* The size of the destination region is exact. */
2458 unsigned HOST_WIDE_INT navail = avail_range.max;
2460 if (target_to_host (*dir.beg) != '%')
2462 /* For plain character directives (i.e., the format string itself)
2463 but not others, point the caret at the first character that's
2464 past the end of the destination. */
2465 if (navail < dir.len)
2466 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2469 if (*dir.beg == '\0')
2471 /* This is the terminating nul. */
2472 gcc_assert (res.min == 1 && res.min == res.max);
2474 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2475 info.bounded
2476 ? (maybe
2477 ? G_("%qE output may be truncated before the "
2478 "last format character")
2479 : G_("%qE output truncated before the last "
2480 "format character"))
2481 : (maybe
2482 ? G_("%qE may write a terminating nul past the "
2483 "end of the destination")
2484 : G_("%qE writing a terminating nul past the "
2485 "end of the destination")),
2486 info.func);
2489 if (res.min == res.max)
2491 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2492 if (!info.bounded)
2493 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2494 "%<%.*s%> directive writing %wu byte into a "
2495 "region of size %wu",
2496 "%<%.*s%> directive writing %wu bytes into a "
2497 "region of size %wu",
2498 (int) dir.len, d, res.min, navail);
2499 else if (maybe)
2500 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2501 "%<%.*s%> directive output may be truncated "
2502 "writing %wu byte into a region of size %wu",
2503 "%<%.*s%> directive output may be truncated "
2504 "writing %wu bytes into a region of size %wu",
2505 (int) dir.len, d, res.min, navail);
2506 else
2507 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2508 "%<%.*s%> directive output truncated writing "
2509 "%wu byte into a region of size %wu",
2510 "%<%.*s%> directive output truncated writing "
2511 "%wu bytes into a region of size %wu",
2512 (int) dir.len, d, res.min, navail);
2514 if (res.min == 0 && res.max < maxbytes)
2515 return fmtwarn (dirloc, argloc, NULL,
2516 info.warnopt (),
2517 info.bounded
2518 ? (maybe
2519 ? G_("%<%.*s%> directive output may be truncated "
2520 "writing up to %wu bytes into a region of "
2521 "size %wu")
2522 : G_("%<%.*s%> directive output truncated writing "
2523 "up to %wu bytes into a region of size %wu"))
2524 : G_("%<%.*s%> directive writing up to %wu bytes "
2525 "into a region of size %wu"), (int) dir.len,
2526 target_to_host (hostdir, sizeof hostdir, dir.beg),
2527 res.max, navail);
2529 if (res.min == 0 && maxbytes <= res.max)
2530 /* This is a special case to avoid issuing the potentially
2531 confusing warning:
2532 writing 0 or more bytes into a region of size 0. */
2533 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2534 info.bounded
2535 ? (maybe
2536 ? G_("%<%.*s%> directive output may be truncated "
2537 "writing likely %wu or more bytes into a "
2538 "region of size %wu")
2539 : G_("%<%.*s%> directive output truncated writing "
2540 "likely %wu or more bytes into a region of "
2541 "size %wu"))
2542 : G_("%<%.*s%> directive writing likely %wu or more "
2543 "bytes into a region of size %wu"), (int) dir.len,
2544 target_to_host (hostdir, sizeof hostdir, dir.beg),
2545 res.likely, navail);
2547 if (res.max < maxbytes)
2548 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2549 info.bounded
2550 ? (maybe
2551 ? G_("%<%.*s%> directive output may be truncated "
2552 "writing between %wu and %wu bytes into a "
2553 "region of size %wu")
2554 : G_("%<%.*s%> directive output truncated "
2555 "writing between %wu and %wu bytes into a "
2556 "region of size %wu"))
2557 : G_("%<%.*s%> directive writing between %wu and "
2558 "%wu bytes into a region of size %wu"),
2559 (int) dir.len,
2560 target_to_host (hostdir, sizeof hostdir, dir.beg),
2561 res.min, res.max, navail);
2563 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2564 info.bounded
2565 ? (maybe
2566 ? G_("%<%.*s%> directive output may be truncated "
2567 "writing %wu or more bytes into a region of "
2568 "size %wu")
2569 : G_("%<%.*s%> directive output truncated writing "
2570 "%wu or more bytes into a region of size %wu"))
2571 : G_("%<%.*s%> directive writing %wu or more bytes "
2572 "into a region of size %wu"), (int) dir.len,
2573 target_to_host (hostdir, sizeof hostdir, dir.beg),
2574 res.min, navail);
2577 /* The size of the destination region is a range. */
2579 if (target_to_host (*dir.beg) != '%')
2581 unsigned HOST_WIDE_INT navail = avail_range.max;
2583 /* For plain character directives (i.e., the format string itself)
2584 but not others, point the caret at the first character that's
2585 past the end of the destination. */
2586 if (navail < dir.len)
2587 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2590 if (*dir.beg == '\0')
2592 gcc_assert (res.min == 1 && res.min == res.max);
2594 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2595 info.bounded
2596 ? (maybe
2597 ? G_("%qE output may be truncated before the last "
2598 "format character")
2599 : G_("%qE output truncated before the last format "
2600 "character"))
2601 : (maybe
2602 ? G_("%qE may write a terminating nul past the end "
2603 "of the destination")
2604 : G_("%qE writing a terminating nul past the end "
2605 "of the destination")), info.func);
2608 if (res.min == res.max)
2610 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2611 if (!info.bounded)
2612 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2613 "%<%.*s%> directive writing %wu byte into a region "
2614 "of size between %wu and %wu",
2615 "%<%.*s%> directive writing %wu bytes into a region "
2616 "of size between %wu and %wu", (int) dir.len, d,
2617 res.min, avail_range.min, avail_range.max);
2618 else if (maybe)
2619 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2620 "%<%.*s%> directive output may be truncated writing "
2621 "%wu byte into a region of size between %wu and %wu",
2622 "%<%.*s%> directive output may be truncated writing "
2623 "%wu bytes into a region of size between %wu and "
2624 "%wu", (int) dir.len, d, res.min, avail_range.min,
2625 avail_range.max);
2626 else
2627 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2628 "%<%.*s%> directive output truncated writing %wu "
2629 "byte into a region of size between %wu and %wu",
2630 "%<%.*s%> directive output truncated writing %wu "
2631 "bytes into a region of size between %wu and %wu",
2632 (int) dir.len, d, res.min, avail_range.min,
2633 avail_range.max);
2636 if (res.min == 0 && res.max < maxbytes)
2637 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2638 info.bounded
2639 ? (maybe
2640 ? G_("%<%.*s%> directive output may be truncated "
2641 "writing up to %wu bytes into a region of size "
2642 "between %wu and %wu")
2643 : G_("%<%.*s%> directive output truncated writing "
2644 "up to %wu bytes into a region of size between "
2645 "%wu and %wu"))
2646 : G_("%<%.*s%> directive writing up to %wu bytes "
2647 "into a region of size between %wu and %wu"),
2648 (int) dir.len,
2649 target_to_host (hostdir, sizeof hostdir, dir.beg),
2650 res.max, avail_range.min, avail_range.max);
2652 if (res.min == 0 && maxbytes <= res.max)
2653 /* This is a special case to avoid issuing the potentially confusing
2654 warning:
2655 writing 0 or more bytes into a region of size between 0 and N. */
2656 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2657 info.bounded
2658 ? (maybe
2659 ? G_("%<%.*s%> directive output may be truncated "
2660 "writing likely %wu or more bytes into a region "
2661 "of size between %wu and %wu")
2662 : G_("%<%.*s%> directive output truncated writing "
2663 "likely %wu or more bytes into a region of size "
2664 "between %wu and %wu"))
2665 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2666 "into a region of size between %wu and %wu"),
2667 (int) dir.len,
2668 target_to_host (hostdir, sizeof hostdir, dir.beg),
2669 res.likely, avail_range.min, avail_range.max);
2671 if (res.max < maxbytes)
2672 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2673 info.bounded
2674 ? (maybe
2675 ? G_("%<%.*s%> directive output may be truncated "
2676 "writing between %wu and %wu bytes into a region "
2677 "of size between %wu and %wu")
2678 : G_("%<%.*s%> directive output truncated writing "
2679 "between %wu and %wu bytes into a region of size "
2680 "between %wu and %wu"))
2681 : G_("%<%.*s%> directive writing between %wu and "
2682 "%wu bytes into a region of size between %wu and "
2683 "%wu"), (int) dir.len,
2684 target_to_host (hostdir, sizeof hostdir, dir.beg),
2685 res.min, res.max, avail_range.min, avail_range.max);
2687 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2688 info.bounded
2689 ? (maybe
2690 ? G_("%<%.*s%> directive output may be truncated writing "
2691 "%wu or more bytes into a region of size between "
2692 "%wu and %wu")
2693 : G_("%<%.*s%> directive output truncated writing "
2694 "%wu or more bytes into a region of size between "
2695 "%wu and %wu"))
2696 : G_("%<%.*s%> directive writing %wu or more bytes "
2697 "into a region of size between %wu and %wu"),
2698 (int) dir.len,
2699 target_to_host (hostdir, sizeof hostdir, dir.beg),
2700 res.min, avail_range.min, avail_range.max);
2703 /* Compute the length of the output resulting from the directive DIR
2704 in a call described by INFO and update the overall result of the call
2705 in *RES. Return true if the directive has been handled. */
2707 static bool
2708 format_directive (const sprintf_dom_walker::call_info &info,
2709 format_result *res, const directive &dir,
2710 class vr_values *vr_values)
2712 /* Offset of the beginning of the directive from the beginning
2713 of the format string. */
2714 size_t offset = dir.beg - info.fmtstr;
2715 size_t start = offset;
2716 size_t length = offset + dir.len - !!dir.len;
2718 /* Create a location for the whole directive from the % to the format
2719 specifier. */
2720 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2721 offset, start, length);
2723 /* Also get the location of the argument if possible.
2724 This doesn't work for integer literals or function calls. */
2725 location_t argloc = UNKNOWN_LOCATION;
2726 if (dir.arg)
2727 argloc = EXPR_LOCATION (dir.arg);
2729 /* Bail when there is no function to compute the output length,
2730 or when minimum length checking has been disabled. */
2731 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2732 return false;
2734 /* Compute the range of lengths of the formatted output. */
2735 fmtresult fmtres = dir.fmtfunc (dir, dir.arg, vr_values);
2737 /* Record whether the output of all directives is known to be
2738 bounded by some maximum, implying that their arguments are
2739 either known exactly or determined to be in a known range
2740 or, for strings, limited by the upper bounds of the arrays
2741 they refer to. */
2742 res->knownrange &= fmtres.knownrange;
2744 if (!fmtres.knownrange)
2746 /* Only when the range is known, check it against the host value
2747 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2748 INT_MAX precision, which is the longest possible output of any
2749 single directive). That's the largest valid byte count (though
2750 not valid call to a printf-like function because it can never
2751 return such a count). Otherwise, the range doesn't correspond
2752 to known values of the argument. */
2753 if (fmtres.range.max > target_dir_max ())
2755 /* Normalize the MAX counter to avoid having to deal with it
2756 later. The counter can be less than HOST_WIDE_INT_M1U
2757 when compiling for an ILP32 target on an LP64 host. */
2758 fmtres.range.max = HOST_WIDE_INT_M1U;
2759 /* Disable exact and maximum length checking after a failure
2760 to determine the maximum number of characters (for example
2761 for wide characters or wide character strings) but continue
2762 tracking the minimum number of characters. */
2763 res->range.max = HOST_WIDE_INT_M1U;
2766 if (fmtres.range.min > target_dir_max ())
2768 /* Disable exact length checking after a failure to determine
2769 even the minimum number of characters (it shouldn't happen
2770 except in an error) but keep tracking the minimum and maximum
2771 number of characters. */
2772 return true;
2776 /* Buffer for the directive in the host character set (used when
2777 the source character set is different). */
2778 char hostdir[32];
2780 int dirlen = dir.len;
2782 if (fmtres.nullp)
2784 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2785 "%G%<%.*s%> directive argument is null",
2786 info.callstmt, dirlen,
2787 target_to_host (hostdir, sizeof hostdir, dir.beg));
2789 /* Don't bother processing the rest of the format string. */
2790 res->warned = true;
2791 res->range.min = HOST_WIDE_INT_M1U;
2792 res->range.max = HOST_WIDE_INT_M1U;
2793 return false;
2796 /* Compute the number of available bytes in the destination. There
2797 must always be at least one byte of space for the terminating
2798 NUL that's appended after the format string has been processed. */
2799 result_range avail_range = bytes_remaining (info.objsize, *res);
2801 bool warned = res->warned;
2803 if (!warned)
2804 warned = maybe_warn (dirloc, argloc, info, avail_range,
2805 fmtres.range, dir);
2807 /* Bump up the total maximum if it isn't too big. */
2808 if (res->range.max < HOST_WIDE_INT_MAX
2809 && fmtres.range.max < HOST_WIDE_INT_MAX)
2810 res->range.max += fmtres.range.max;
2812 /* Raise the total unlikely maximum by the larger of the maximum
2813 and the unlikely maximum. */
2814 unsigned HOST_WIDE_INT save = res->range.unlikely;
2815 if (fmtres.range.max < fmtres.range.unlikely)
2816 res->range.unlikely += fmtres.range.unlikely;
2817 else
2818 res->range.unlikely += fmtres.range.max;
2820 if (res->range.unlikely < save)
2821 res->range.unlikely = HOST_WIDE_INT_M1U;
2823 res->range.min += fmtres.range.min;
2824 res->range.likely += fmtres.range.likely;
2826 /* Has the minimum directive output length exceeded the maximum
2827 of 4095 bytes required to be supported? */
2828 bool minunder4k = fmtres.range.min < 4096;
2829 bool maxunder4k = fmtres.range.max < 4096;
2830 /* Clear POSUNDER4K in the overall result if the maximum has exceeded
2831 the 4k (this is necessary to avoid the return value optimization
2832 that may not be safe in the maximum case). */
2833 if (!maxunder4k)
2834 res->posunder4k = false;
2835 /* Also clear POSUNDER4K if the directive may fail. */
2836 if (fmtres.mayfail)
2837 res->posunder4k = false;
2839 if (!warned
2840 /* Only warn at level 2. */
2841 && warn_level > 1
2842 && (!minunder4k
2843 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2845 /* The directive output may be longer than the maximum required
2846 to be handled by an implementation according to 7.21.6.1, p15
2847 of C11. Warn on this only at level 2 but remember this and
2848 prevent folding the return value when done. This allows for
2849 the possibility of the actual libc call failing due to ENOMEM
2850 (like Glibc does under some conditions). */
2852 if (fmtres.range.min == fmtres.range.max)
2853 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2854 "%<%.*s%> directive output of %wu bytes exceeds "
2855 "minimum required size of 4095", dirlen,
2856 target_to_host (hostdir, sizeof hostdir, dir.beg),
2857 fmtres.range.min);
2858 else
2859 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2860 minunder4k
2861 ? G_("%<%.*s%> directive output between %wu and %wu "
2862 "bytes may exceed minimum required size of "
2863 "4095")
2864 : G_("%<%.*s%> directive output between %wu and %wu "
2865 "bytes exceeds minimum required size of 4095"),
2866 dirlen,
2867 target_to_host (hostdir, sizeof hostdir, dir.beg),
2868 fmtres.range.min, fmtres.range.max);
2871 /* Has the likely and maximum directive output exceeded INT_MAX? */
2872 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2873 /* Don't consider the maximum to be in excess when it's the result
2874 of a string of unknown length (i.e., whose maximum has been set
2875 to be greater than or equal to HOST_WIDE_INT_MAX. */
2876 bool maxximax = (*dir.beg
2877 && res->range.max > target_int_max ()
2878 && res->range.max < HOST_WIDE_INT_MAX);
2880 if (!warned
2881 /* Warn for the likely output size at level 1. */
2882 && (likelyximax
2883 /* But only warn for the maximum at level 2. */
2884 || (warn_level > 1
2885 && maxximax
2886 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2888 /* The directive output causes the total length of output
2889 to exceed INT_MAX bytes. */
2891 if (fmtres.range.min == fmtres.range.max)
2892 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2893 "%<%.*s%> directive output of %wu bytes causes "
2894 "result to exceed %<INT_MAX%>", dirlen,
2895 target_to_host (hostdir, sizeof hostdir, dir.beg),
2896 fmtres.range.min);
2897 else
2898 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2899 fmtres.range.min > target_int_max ()
2900 ? G_("%<%.*s%> directive output between %wu and "
2901 "%wu bytes causes result to exceed "
2902 "%<INT_MAX%>")
2903 : G_("%<%.*s%> directive output between %wu and "
2904 "%wu bytes may cause result to exceed "
2905 "%<INT_MAX%>"), dirlen,
2906 target_to_host (hostdir, sizeof hostdir, dir.beg),
2907 fmtres.range.min, fmtres.range.max);
2910 if (!warned && fmtres.nonstr)
2912 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2913 "%<%.*s%> directive argument is not a nul-terminated "
2914 "string",
2915 dirlen,
2916 target_to_host (hostdir, sizeof hostdir, dir.beg));
2917 if (warned && DECL_P (fmtres.nonstr))
2918 inform (DECL_SOURCE_LOCATION (fmtres.nonstr),
2919 "referenced argument declared here");
2920 return false;
2923 if (warned && fmtres.range.min < fmtres.range.likely
2924 && fmtres.range.likely < fmtres.range.max)
2925 inform_n (info.fmtloc, fmtres.range.likely,
2926 "assuming directive output of %wu byte",
2927 "assuming directive output of %wu bytes",
2928 fmtres.range.likely);
2930 if (warned && fmtres.argmin)
2932 if (fmtres.argmin == fmtres.argmax)
2933 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2934 else if (fmtres.knownrange)
2935 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2936 fmtres.argmin, fmtres.argmax);
2937 else
2938 inform (info.fmtloc,
2939 "using the range [%E, %E] for directive argument",
2940 fmtres.argmin, fmtres.argmax);
2943 res->warned |= warned;
2945 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2947 /* If a warning has been issued for buffer overflow or truncation
2948 (but not otherwise) help the user figure out how big a buffer
2949 they need. */
2951 location_t callloc = gimple_location (info.callstmt);
2953 unsigned HOST_WIDE_INT min = res->range.min;
2954 unsigned HOST_WIDE_INT max = res->range.max;
2956 if (min == max)
2957 inform (callloc,
2958 (min == 1
2959 ? G_("%qE output %wu byte into a destination of size %wu")
2960 : G_("%qE output %wu bytes into a destination of size %wu")),
2961 info.func, min, info.objsize);
2962 else if (max < HOST_WIDE_INT_MAX)
2963 inform (callloc,
2964 "%qE output between %wu and %wu bytes into "
2965 "a destination of size %wu",
2966 info.func, min, max, info.objsize);
2967 else if (min < res->range.likely && res->range.likely < max)
2968 inform (callloc,
2969 "%qE output %wu or more bytes (assuming %wu) into "
2970 "a destination of size %wu",
2971 info.func, min, res->range.likely, info.objsize);
2972 else
2973 inform (callloc,
2974 "%qE output %wu or more bytes into a destination of size %wu",
2975 info.func, min, info.objsize);
2978 if (dump_file && *dir.beg)
2980 fprintf (dump_file,
2981 " Result: "
2982 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
2983 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
2984 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
2985 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
2986 fmtres.range.min, fmtres.range.likely,
2987 fmtres.range.max, fmtres.range.unlikely,
2988 res->range.min, res->range.likely,
2989 res->range.max, res->range.unlikely);
2992 return true;
2995 /* Parse a format directive in function call described by INFO starting
2996 at STR and populate DIR structure. Bump up *ARGNO by the number of
2997 arguments extracted for the directive. Return the length of
2998 the directive. */
3000 static size_t
3001 parse_directive (sprintf_dom_walker::call_info &info,
3002 directive &dir, format_result *res,
3003 const char *str, unsigned *argno,
3004 vr_values *vr_values)
3006 const char *pcnt = strchr (str, target_percent);
3007 dir.beg = str;
3009 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
3011 /* This directive is either a plain string or the terminating nul
3012 (which isn't really a directive but it simplifies things to
3013 handle it as if it were). */
3014 dir.len = len;
3015 dir.fmtfunc = format_plain;
3017 if (dump_file)
3019 fprintf (dump_file, " Directive %u at offset "
3020 HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
3021 "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
3022 dir.dirno,
3023 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3024 (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
3027 return len - !*str;
3030 const char *pf = pcnt + 1;
3032 /* POSIX numbered argument index or zero when none. */
3033 HOST_WIDE_INT dollar = 0;
3035 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3036 when given by a va_list argument, and a non-negative value
3037 when specified in the format string itself. */
3038 HOST_WIDE_INT width = -1;
3039 HOST_WIDE_INT precision = -1;
3041 /* Pointers to the beginning of the width and precision decimal
3042 string (if any) within the directive. */
3043 const char *pwidth = 0;
3044 const char *pprec = 0;
3046 /* When the value of the decimal string that specifies width or
3047 precision is out of range, points to the digit that causes
3048 the value to exceed the limit. */
3049 const char *werange = NULL;
3050 const char *perange = NULL;
3052 /* Width specified via the asterisk. Need not be INTEGER_CST.
3053 For vararg functions set to void_node. */
3054 tree star_width = NULL_TREE;
3056 /* Width specified via the asterisk. Need not be INTEGER_CST.
3057 For vararg functions set to void_node. */
3058 tree star_precision = NULL_TREE;
3060 if (ISDIGIT (target_to_host (*pf)))
3062 /* This could be either a POSIX positional argument, the '0'
3063 flag, or a width, depending on what follows. Store it as
3064 width and sort it out later after the next character has
3065 been seen. */
3066 pwidth = pf;
3067 width = target_strtol10 (&pf, &werange);
3069 else if (target_to_host (*pf) == '*')
3071 /* Similarly to the block above, this could be either a POSIX
3072 positional argument or a width, depending on what follows. */
3073 if (*argno < gimple_call_num_args (info.callstmt))
3074 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3075 else
3076 star_width = void_node;
3077 ++pf;
3080 if (target_to_host (*pf) == '$')
3082 /* Handle the POSIX dollar sign which references the 1-based
3083 positional argument number. */
3084 if (width != -1)
3085 dollar = width + info.argidx;
3086 else if (star_width
3087 && TREE_CODE (star_width) == INTEGER_CST
3088 && (TYPE_PRECISION (TREE_TYPE (star_width))
3089 <= TYPE_PRECISION (integer_type_node)))
3090 dollar = width + tree_to_shwi (star_width);
3092 /* Bail when the numbered argument is out of range (it will
3093 have already been diagnosed by -Wformat). */
3094 if (dollar == 0
3095 || dollar == (int)info.argidx
3096 || dollar > gimple_call_num_args (info.callstmt))
3097 return false;
3099 --dollar;
3101 star_width = NULL_TREE;
3102 width = -1;
3103 ++pf;
3106 if (dollar || !star_width)
3108 if (width != -1)
3110 if (width == 0)
3112 /* The '0' that has been interpreted as a width above is
3113 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3114 and continue processing other flags. */
3115 width = -1;
3116 dir.set_flag ('0');
3118 else if (!dollar)
3120 /* (Non-zero) width has been seen. The next character
3121 is either a period or a digit. */
3122 goto start_precision;
3125 /* When either '$' has been seen, or width has not been seen,
3126 the next field is the optional flags followed by an optional
3127 width. */
3128 for ( ; ; ) {
3129 switch (target_to_host (*pf))
3131 case ' ':
3132 case '0':
3133 case '+':
3134 case '-':
3135 case '#':
3136 dir.set_flag (target_to_host (*pf++));
3137 break;
3139 default:
3140 goto start_width;
3144 start_width:
3145 if (ISDIGIT (target_to_host (*pf)))
3147 werange = 0;
3148 pwidth = pf;
3149 width = target_strtol10 (&pf, &werange);
3151 else if (target_to_host (*pf) == '*')
3153 if (*argno < gimple_call_num_args (info.callstmt))
3154 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3155 else
3157 /* This is (likely) a va_list. It could also be an invalid
3158 call with insufficient arguments. */
3159 star_width = void_node;
3161 ++pf;
3163 else if (target_to_host (*pf) == '\'')
3165 /* The POSIX apostrophe indicating a numeric grouping
3166 in the current locale. Even though it's possible to
3167 estimate the upper bound on the size of the output
3168 based on the number of digits it probably isn't worth
3169 continuing. */
3170 return 0;
3174 start_precision:
3175 if (target_to_host (*pf) == '.')
3177 ++pf;
3179 if (ISDIGIT (target_to_host (*pf)))
3181 pprec = pf;
3182 precision = target_strtol10 (&pf, &perange);
3184 else if (target_to_host (*pf) == '*')
3186 if (*argno < gimple_call_num_args (info.callstmt))
3187 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3188 else
3190 /* This is (likely) a va_list. It could also be an invalid
3191 call with insufficient arguments. */
3192 star_precision = void_node;
3194 ++pf;
3196 else
3198 /* The decimal precision or the asterisk are optional.
3199 When neither is dirified it's taken to be zero. */
3200 precision = 0;
3204 switch (target_to_host (*pf))
3206 case 'h':
3207 if (target_to_host (pf[1]) == 'h')
3209 ++pf;
3210 dir.modifier = FMT_LEN_hh;
3212 else
3213 dir.modifier = FMT_LEN_h;
3214 ++pf;
3215 break;
3217 case 'j':
3218 dir.modifier = FMT_LEN_j;
3219 ++pf;
3220 break;
3222 case 'L':
3223 dir.modifier = FMT_LEN_L;
3224 ++pf;
3225 break;
3227 case 'l':
3228 if (target_to_host (pf[1]) == 'l')
3230 ++pf;
3231 dir.modifier = FMT_LEN_ll;
3233 else
3234 dir.modifier = FMT_LEN_l;
3235 ++pf;
3236 break;
3238 case 't':
3239 dir.modifier = FMT_LEN_t;
3240 ++pf;
3241 break;
3243 case 'z':
3244 dir.modifier = FMT_LEN_z;
3245 ++pf;
3246 break;
3249 switch (target_to_host (*pf))
3251 /* Handle a sole '%' character the same as "%%" but since it's
3252 undefined prevent the result from being folded. */
3253 case '\0':
3254 --pf;
3255 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3256 /* FALLTHRU */
3257 case '%':
3258 dir.fmtfunc = format_percent;
3259 break;
3261 case 'a':
3262 case 'A':
3263 case 'e':
3264 case 'E':
3265 case 'f':
3266 case 'F':
3267 case 'g':
3268 case 'G':
3269 res->floating = true;
3270 dir.fmtfunc = format_floating;
3271 break;
3273 case 'd':
3274 case 'i':
3275 case 'o':
3276 case 'u':
3277 case 'x':
3278 case 'X':
3279 dir.fmtfunc = format_integer;
3280 break;
3282 case 'p':
3283 /* The %p output is implementation-defined. It's possible
3284 to determine this format but due to extensions (edirially
3285 those of the Linux kernel -- see bug 78512) the first %p
3286 in the format string disables any further processing. */
3287 return false;
3289 case 'n':
3290 /* %n has side-effects even when nothing is actually printed to
3291 any buffer. */
3292 info.nowrite = false;
3293 dir.fmtfunc = format_none;
3294 break;
3296 case 'C':
3297 case 'c':
3298 /* POSIX wide character and C/POSIX narrow character. */
3299 dir.fmtfunc = format_character;
3300 break;
3302 case 'S':
3303 case 's':
3304 /* POSIX wide string and C/POSIX narrow character string. */
3305 dir.fmtfunc = format_string;
3306 break;
3308 default:
3309 /* Unknown conversion specification. */
3310 return 0;
3313 dir.specifier = target_to_host (*pf++);
3315 /* Store the length of the format directive. */
3316 dir.len = pf - pcnt;
3318 /* Buffer for the directive in the host character set (used when
3319 the source character set is different). */
3320 char hostdir[32];
3322 if (star_width)
3324 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3325 dir.set_width (star_width, vr_values);
3326 else
3328 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3329 (width is the absolute value of that specified). */
3330 dir.width[0] = 0;
3331 dir.width[1] = target_int_max () + 1;
3334 else
3336 if (width == LONG_MAX && werange)
3338 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3339 size_t caret = begin + (werange - pcnt);
3340 size_t end = pf - info.fmtstr - 1;
3342 /* Create a location for the width part of the directive,
3343 pointing the caret at the first out-of-range digit. */
3344 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3345 caret, begin, end);
3347 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3348 "%<%.*s%> directive width out of range", (int) dir.len,
3349 target_to_host (hostdir, sizeof hostdir, dir.beg));
3352 dir.set_width (width);
3355 if (star_precision)
3357 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3358 dir.set_precision (star_precision, vr_values);
3359 else
3361 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3362 (unlike width, negative precision is ignored). */
3363 dir.prec[0] = -1;
3364 dir.prec[1] = target_int_max ();
3367 else
3369 if (precision == LONG_MAX && perange)
3371 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3372 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3373 size_t end = pf - info.fmtstr - 2;
3375 /* Create a location for the precision part of the directive,
3376 including the leading period, pointing the caret at the first
3377 out-of-range digit . */
3378 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3379 caret, begin, end);
3381 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3382 "%<%.*s%> directive precision out of range", (int) dir.len,
3383 target_to_host (hostdir, sizeof hostdir, dir.beg));
3386 dir.set_precision (precision);
3389 /* Extract the argument if the directive takes one and if it's
3390 available (e.g., the function doesn't take a va_list). Treat
3391 missing arguments the same as va_list, even though they will
3392 have likely already been diagnosed by -Wformat. */
3393 if (dir.specifier != '%'
3394 && *argno < gimple_call_num_args (info.callstmt))
3395 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3397 if (dump_file)
3399 fprintf (dump_file,
3400 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3401 ": \"%.*s\"",
3402 dir.dirno,
3403 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3404 (int)dir.len, dir.beg);
3405 if (star_width)
3407 if (dir.width[0] == dir.width[1])
3408 fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
3409 dir.width[0]);
3410 else
3411 fprintf (dump_file,
3412 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3413 ", " HOST_WIDE_INT_PRINT_DEC "]",
3414 dir.width[0], dir.width[1]);
3417 if (star_precision)
3419 if (dir.prec[0] == dir.prec[1])
3420 fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
3421 dir.prec[0]);
3422 else
3423 fprintf (dump_file,
3424 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3425 HOST_WIDE_INT_PRINT_DEC "]",
3426 dir.prec[0], dir.prec[1]);
3428 fputc ('\n', dump_file);
3431 return dir.len;
3434 /* Compute the length of the output resulting from the call to a formatted
3435 output function described by INFO and store the result of the call in
3436 *RES. Issue warnings for detected past the end writes. Return true
3437 if the complete format string has been processed and *RES can be relied
3438 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3439 that caused the processing to be terminated early). */
3441 bool
3442 sprintf_dom_walker::compute_format_length (call_info &info,
3443 format_result *res)
3445 if (dump_file)
3447 location_t callloc = gimple_location (info.callstmt);
3448 fprintf (dump_file, "%s:%i: ",
3449 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3450 print_generic_expr (dump_file, info.func, dump_flags);
3452 fprintf (dump_file,
3453 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3454 ", fmtstr = \"%s\"\n",
3455 info.objsize, info.fmtstr);
3458 /* Reset the minimum and maximum byte counters. */
3459 res->range.min = res->range.max = 0;
3461 /* No directive has been seen yet so the length of output is bounded
3462 by the known range [0, 0] (with no conversion resulting in a failure
3463 or producing more than 4K bytes) until determined otherwise. */
3464 res->knownrange = true;
3465 res->floating = false;
3466 res->warned = false;
3468 /* 1-based directive counter. */
3469 unsigned dirno = 1;
3471 /* The variadic argument counter. */
3472 unsigned argno = info.argidx;
3474 for (const char *pf = info.fmtstr; ; ++dirno)
3476 directive dir = directive ();
3477 dir.dirno = dirno;
3479 size_t n = parse_directive (info, dir, res, pf, &argno,
3480 evrp_range_analyzer.get_vr_values ());
3482 /* Return failure if the format function fails. */
3483 if (!format_directive (info, res, dir,
3484 evrp_range_analyzer.get_vr_values ()))
3485 return false;
3487 /* Return success the directive is zero bytes long and it's
3488 the last think in the format string (i.e., it's the terminating
3489 nul, which isn't really a directive but handling it as one makes
3490 things simpler). */
3491 if (!n)
3492 return *pf == '\0';
3494 pf += n;
3497 /* The complete format string was processed (with or without warnings). */
3498 return true;
3501 /* Return the size of the object referenced by the expression DEST if
3502 available, or -1 otherwise. */
3504 static unsigned HOST_WIDE_INT
3505 get_destination_size (tree dest)
3507 /* When there is no destination return -1. */
3508 if (!dest)
3509 return HOST_WIDE_INT_M1U;
3511 /* Initialize object size info before trying to compute it. */
3512 init_object_sizes ();
3514 /* Use __builtin_object_size to determine the size of the destination
3515 object. When optimizing, determine the smallest object (such as
3516 a member array as opposed to the whole enclosing object), otherwise
3517 use type-zero object size to determine the size of the enclosing
3518 object (the function fails without optimization in this type). */
3519 int ost = optimize > 0;
3520 unsigned HOST_WIDE_INT size;
3521 if (compute_builtin_object_size (dest, ost, &size))
3522 return size;
3524 return HOST_WIDE_INT_M1U;
3527 /* Return true if the call described by INFO with result RES safe to
3528 optimize (i.e., no undefined behavior), and set RETVAL to the range
3529 of its return values. */
3531 static bool
3532 is_call_safe (const sprintf_dom_walker::call_info &info,
3533 const format_result &res, bool under4k,
3534 unsigned HOST_WIDE_INT retval[2])
3536 if (under4k && !res.posunder4k)
3537 return false;
3539 /* The minimum return value. */
3540 retval[0] = res.range.min;
3542 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3543 but in cases involving multibyte characters could be as large as
3544 RES.RANGE.UNLIKELY. */
3545 retval[1]
3546 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3548 /* Adjust the number of bytes which includes the terminating nul
3549 to reflect the return value of the function which does not.
3550 Because the valid range of the function is [INT_MIN, INT_MAX],
3551 a valid range before the adjustment below is [0, INT_MAX + 1]
3552 (the functions only return negative values on error or undefined
3553 behavior). */
3554 if (retval[0] <= target_int_max () + 1)
3555 --retval[0];
3556 if (retval[1] <= target_int_max () + 1)
3557 --retval[1];
3559 /* Avoid the return value optimization when the behavior of the call
3560 is undefined either because any directive may have produced 4K or
3561 more of output, or the return value exceeds INT_MAX, or because
3562 the output overflows the destination object (but leave it enabled
3563 when the function is bounded because then the behavior is well-
3564 defined). */
3565 if (retval[0] == retval[1]
3566 && (info.bounded || retval[0] < info.objsize)
3567 && retval[0] <= target_int_max ())
3568 return true;
3570 if ((info.bounded || retval[1] < info.objsize)
3571 && (retval[0] < target_int_max ()
3572 && retval[1] < target_int_max ()))
3573 return true;
3575 if (!under4k && (info.bounded || retval[0] < info.objsize))
3576 return true;
3578 return false;
3581 /* Given a suitable result RES of a call to a formatted output function
3582 described by INFO, substitute the result for the return value of
3583 the call. The result is suitable if the number of bytes it represents
3584 is known and exact. A result that isn't suitable for substitution may
3585 have its range set to the range of return values, if that is known.
3586 Return true if the call is removed and gsi_next should not be performed
3587 in the caller. */
3589 static bool
3590 try_substitute_return_value (gimple_stmt_iterator *gsi,
3591 const sprintf_dom_walker::call_info &info,
3592 const format_result &res)
3594 tree lhs = gimple_get_lhs (info.callstmt);
3596 /* Set to true when the entire call has been removed. */
3597 bool removed = false;
3599 /* The minimum and maximum return value. */
3600 unsigned HOST_WIDE_INT retval[2];
3601 bool safe = is_call_safe (info, res, true, retval);
3603 if (safe
3604 && retval[0] == retval[1]
3605 /* Not prepared to handle possibly throwing calls here; they shouldn't
3606 appear in non-artificial testcases, except when the __*_chk routines
3607 are badly declared. */
3608 && !stmt_ends_bb_p (info.callstmt))
3610 tree cst = build_int_cst (integer_type_node, retval[0]);
3612 if (lhs == NULL_TREE
3613 && info.nowrite)
3615 /* Remove the call to the bounded function with a zero size
3616 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3617 unlink_stmt_vdef (info.callstmt);
3618 gsi_remove (gsi, true);
3619 removed = true;
3621 else if (info.nowrite)
3623 /* Replace the call to the bounded function with a zero size
3624 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3625 of the function. */
3626 if (!update_call_from_tree (gsi, cst))
3627 gimplify_and_update_call_from_tree (gsi, cst);
3628 gimple *callstmt = gsi_stmt (*gsi);
3629 update_stmt (callstmt);
3631 else if (lhs)
3633 /* Replace the left-hand side of the call with the constant
3634 result of the formatted function. */
3635 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3636 gimple *g = gimple_build_assign (lhs, cst);
3637 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3638 update_stmt (info.callstmt);
3641 if (dump_file)
3643 if (removed)
3644 fprintf (dump_file, " Removing call statement.");
3645 else
3647 fprintf (dump_file, " Substituting ");
3648 print_generic_expr (dump_file, cst, dump_flags);
3649 fprintf (dump_file, " for %s.\n",
3650 info.nowrite ? "statement" : "return value");
3654 else if (lhs)
3656 bool setrange = false;
3658 if (safe
3659 && (info.bounded || retval[1] < info.objsize)
3660 && (retval[0] < target_int_max ()
3661 && retval[1] < target_int_max ()))
3663 /* If the result is in a valid range bounded by the size of
3664 the destination set it so that it can be used for subsequent
3665 optimizations. */
3666 int prec = TYPE_PRECISION (integer_type_node);
3668 wide_int min = wi::shwi (retval[0], prec);
3669 wide_int max = wi::shwi (retval[1], prec);
3670 set_range_info (lhs, VR_RANGE, min, max);
3672 setrange = true;
3675 if (dump_file)
3677 const char *inbounds
3678 = (retval[0] < info.objsize
3679 ? (retval[1] < info.objsize
3680 ? "in" : "potentially out-of")
3681 : "out-of");
3683 const char *what = setrange ? "Setting" : "Discarding";
3684 if (retval[0] != retval[1])
3685 fprintf (dump_file,
3686 " %s %s-bounds return value range ["
3687 HOST_WIDE_INT_PRINT_UNSIGNED ", "
3688 HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
3689 what, inbounds, retval[0], retval[1]);
3690 else
3691 fprintf (dump_file, " %s %s-bounds return value "
3692 HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
3693 what, inbounds, retval[0]);
3697 if (dump_file)
3698 fputc ('\n', dump_file);
3700 return removed;
3703 /* Try to simplify a s{,n}printf call described by INFO with result
3704 RES by replacing it with a simpler and presumably more efficient
3705 call (such as strcpy). */
3707 static bool
3708 try_simplify_call (gimple_stmt_iterator *gsi,
3709 const sprintf_dom_walker::call_info &info,
3710 const format_result &res)
3712 unsigned HOST_WIDE_INT dummy[2];
3713 if (!is_call_safe (info, res, info.retval_used (), dummy))
3714 return false;
3716 switch (info.fncode)
3718 case BUILT_IN_SNPRINTF:
3719 return gimple_fold_builtin_snprintf (gsi);
3721 case BUILT_IN_SPRINTF:
3722 return gimple_fold_builtin_sprintf (gsi);
3724 default:
3728 return false;
3731 /* Return the zero-based index of the format string argument of a printf
3732 like function and set *IDX_ARGS to the first format argument. When
3733 no such index exists return UINT_MAX. */
3735 static unsigned
3736 get_user_idx_format (tree fndecl, unsigned *idx_args)
3738 tree attrs = lookup_attribute ("format", DECL_ATTRIBUTES (fndecl));
3739 if (!attrs)
3740 attrs = lookup_attribute ("format", TYPE_ATTRIBUTES (TREE_TYPE (fndecl)));
3742 if (!attrs)
3743 return UINT_MAX;
3745 attrs = TREE_VALUE (attrs);
3747 tree archetype = TREE_VALUE (attrs);
3748 if (strcmp ("printf", IDENTIFIER_POINTER (archetype)))
3749 return UINT_MAX;
3751 attrs = TREE_CHAIN (attrs);
3752 tree fmtarg = TREE_VALUE (attrs);
3754 attrs = TREE_CHAIN (attrs);
3755 tree elliparg = TREE_VALUE (attrs);
3757 /* Attribute argument indices are 1-based but we use zero-based. */
3758 *idx_args = tree_to_uhwi (elliparg) - 1;
3759 return tree_to_uhwi (fmtarg) - 1;
3762 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3763 functions and if so, handle it. Return true if the call is removed
3764 and gsi_next should not be performed in the caller. */
3766 bool
3767 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3769 call_info info = call_info ();
3771 info.callstmt = gsi_stmt (*gsi);
3772 info.func = gimple_call_fndecl (info.callstmt);
3773 if (!info.func)
3774 return false;
3776 info.fncode = DECL_FUNCTION_CODE (info.func);
3778 /* Format string argument number (valid for all functions). */
3779 unsigned idx_format = UINT_MAX;
3780 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3782 unsigned idx_args;
3783 idx_format = get_user_idx_format (info.func, &idx_args);
3784 if (idx_format == UINT_MAX)
3785 return false;
3786 info.argidx = idx_args;
3789 /* The size of the destination as in snprintf(dest, size, ...). */
3790 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3792 /* The size of the destination determined by __builtin_object_size. */
3793 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3795 /* Zero-based buffer size argument number (snprintf and vsnprintf). */
3796 unsigned idx_dstsize = UINT_MAX;
3798 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3799 unsigned idx_objsize = UINT_MAX;
3801 /* Destinaton argument number (valid for sprintf functions only). */
3802 unsigned idx_dstptr = 0;
3804 switch (info.fncode)
3806 case BUILT_IN_NONE:
3807 // User-defined function with attribute format (printf).
3808 idx_dstptr = -1;
3809 break;
3811 case BUILT_IN_FPRINTF:
3812 // Signature:
3813 // __builtin_fprintf (FILE*, format, ...)
3814 idx_format = 1;
3815 info.argidx = 2;
3816 idx_dstptr = -1;
3817 break;
3819 case BUILT_IN_FPRINTF_CHK:
3820 // Signature:
3821 // __builtin_fprintf_chk (FILE*, ost, format, ...)
3822 idx_format = 2;
3823 info.argidx = 3;
3824 idx_dstptr = -1;
3825 break;
3827 case BUILT_IN_FPRINTF_UNLOCKED:
3828 // Signature:
3829 // __builtin_fprintf_unnlocked (FILE*, format, ...)
3830 idx_format = 1;
3831 info.argidx = 2;
3832 idx_dstptr = -1;
3833 break;
3835 case BUILT_IN_PRINTF:
3836 // Signature:
3837 // __builtin_printf (format, ...)
3838 idx_format = 0;
3839 info.argidx = 1;
3840 idx_dstptr = -1;
3841 break;
3843 case BUILT_IN_PRINTF_CHK:
3844 // Signature:
3845 // __builtin_printf_chk (it, format, ...)
3846 idx_format = 1;
3847 info.argidx = 2;
3848 idx_dstptr = -1;
3849 break;
3851 case BUILT_IN_PRINTF_UNLOCKED:
3852 // Signature:
3853 // __builtin_printf (format, ...)
3854 idx_format = 0;
3855 info.argidx = 1;
3856 idx_dstptr = -1;
3857 break;
3859 case BUILT_IN_SPRINTF:
3860 // Signature:
3861 // __builtin_sprintf (dst, format, ...)
3862 idx_format = 1;
3863 info.argidx = 2;
3864 break;
3866 case BUILT_IN_SPRINTF_CHK:
3867 // Signature:
3868 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3869 idx_objsize = 2;
3870 idx_format = 3;
3871 info.argidx = 4;
3872 break;
3874 case BUILT_IN_SNPRINTF:
3875 // Signature:
3876 // __builtin_snprintf (dst, size, format, ...)
3877 idx_dstsize = 1;
3878 idx_format = 2;
3879 info.argidx = 3;
3880 info.bounded = true;
3881 break;
3883 case BUILT_IN_SNPRINTF_CHK:
3884 // Signature:
3885 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3886 idx_dstsize = 1;
3887 idx_objsize = 3;
3888 idx_format = 4;
3889 info.argidx = 5;
3890 info.bounded = true;
3891 break;
3893 case BUILT_IN_VFPRINTF:
3894 // Signature:
3895 // __builtin_vprintf (FILE*, format, va_list)
3896 idx_format = 1;
3897 info.argidx = -1;
3898 idx_dstptr = -1;
3899 break;
3901 case BUILT_IN_VFPRINTF_CHK:
3902 // Signature:
3903 // __builtin___vfprintf_chk (FILE*, ost, format, va_list)
3904 idx_format = 2;
3905 info.argidx = -1;
3906 idx_dstptr = -1;
3907 break;
3909 case BUILT_IN_VPRINTF:
3910 // Signature:
3911 // __builtin_vprintf (format, va_list)
3912 idx_format = 0;
3913 info.argidx = -1;
3914 idx_dstptr = -1;
3915 break;
3917 case BUILT_IN_VPRINTF_CHK:
3918 // Signature:
3919 // __builtin___vprintf_chk (ost, format, va_list)
3920 idx_format = 1;
3921 info.argidx = -1;
3922 idx_dstptr = -1;
3923 break;
3925 case BUILT_IN_VSNPRINTF:
3926 // Signature:
3927 // __builtin_vsprintf (dst, size, format, va)
3928 idx_dstsize = 1;
3929 idx_format = 2;
3930 info.argidx = -1;
3931 info.bounded = true;
3932 break;
3934 case BUILT_IN_VSNPRINTF_CHK:
3935 // Signature:
3936 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3937 idx_dstsize = 1;
3938 idx_objsize = 3;
3939 idx_format = 4;
3940 info.argidx = -1;
3941 info.bounded = true;
3942 break;
3944 case BUILT_IN_VSPRINTF:
3945 // Signature:
3946 // __builtin_vsprintf (dst, format, va)
3947 idx_format = 1;
3948 info.argidx = -1;
3949 break;
3951 case BUILT_IN_VSPRINTF_CHK:
3952 // Signature:
3953 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3954 idx_format = 3;
3955 idx_objsize = 2;
3956 info.argidx = -1;
3957 break;
3959 default:
3960 return false;
3963 /* Set the global warning level for this function. */
3964 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3966 /* For all string functions the first argument is a pointer to
3967 the destination. */
3968 tree dstptr = (idx_dstptr < gimple_call_num_args (info.callstmt)
3969 ? gimple_call_arg (info.callstmt, 0) : NULL_TREE);
3971 info.format = gimple_call_arg (info.callstmt, idx_format);
3973 /* True when the destination size is constant as opposed to the lower
3974 or upper bound of a range. */
3975 bool dstsize_cst_p = true;
3976 bool posunder4k = true;
3978 if (idx_dstsize == UINT_MAX)
3980 /* For non-bounded functions like sprintf, determine the size
3981 of the destination from the object or pointer passed to it
3982 as the first argument. */
3983 dstsize = get_destination_size (dstptr);
3985 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3987 /* For bounded functions try to get the size argument. */
3989 if (TREE_CODE (size) == INTEGER_CST)
3991 dstsize = tree_to_uhwi (size);
3992 /* No object can be larger than SIZE_MAX bytes (half the address
3993 space) on the target.
3994 The functions are defined only for output of at most INT_MAX
3995 bytes. Specifying a bound in excess of that limit effectively
3996 defeats the bounds checking (and on some implementations such
3997 as Solaris cause the function to fail with EINVAL). */
3998 if (dstsize > target_size_max () / 2)
4000 /* Avoid warning if -Wstringop-overflow is specified since
4001 it also warns for the same thing though only for the
4002 checking built-ins. */
4003 if ((idx_objsize == UINT_MAX
4004 || !warn_stringop_overflow))
4005 warning_at (gimple_location (info.callstmt), info.warnopt (),
4006 "specified bound %wu exceeds maximum object size "
4007 "%wu",
4008 dstsize, target_size_max () / 2);
4009 /* POSIX requires snprintf to fail if DSTSIZE is greater
4010 than INT_MAX. Even though not all POSIX implementations
4011 conform to the requirement, avoid folding in this case. */
4012 posunder4k = false;
4014 else if (dstsize > target_int_max ())
4016 warning_at (gimple_location (info.callstmt), info.warnopt (),
4017 "specified bound %wu exceeds %<INT_MAX%>",
4018 dstsize);
4019 /* POSIX requires snprintf to fail if DSTSIZE is greater
4020 than INT_MAX. Avoid folding in that case. */
4021 posunder4k = false;
4024 else if (TREE_CODE (size) == SSA_NAME)
4026 /* Try to determine the range of values of the argument
4027 and use the greater of the two at level 1 and the smaller
4028 of them at level 2. */
4029 value_range *vr = evrp_range_analyzer.get_value_range (size);
4030 if (range_int_cst_p (vr))
4032 unsigned HOST_WIDE_INT minsize = TREE_INT_CST_LOW (vr->min ());
4033 unsigned HOST_WIDE_INT maxsize = TREE_INT_CST_LOW (vr->max ());
4034 dstsize = warn_level < 2 ? maxsize : minsize;
4036 if (minsize > target_int_max ())
4037 warning_at (gimple_location (info.callstmt), info.warnopt (),
4038 "specified bound range [%wu, %wu] exceeds "
4039 "%<INT_MAX%>",
4040 minsize, maxsize);
4042 /* POSIX requires snprintf to fail if DSTSIZE is greater
4043 than INT_MAX. Avoid folding if that's possible. */
4044 if (maxsize > target_int_max ())
4045 posunder4k = false;
4047 else if (vr->varying_p ())
4049 /* POSIX requires snprintf to fail if DSTSIZE is greater
4050 than INT_MAX. Since SIZE's range is unknown, avoid
4051 folding. */
4052 posunder4k = false;
4055 /* The destination size is not constant. If the function is
4056 bounded (e.g., snprintf) a lower bound of zero doesn't
4057 necessarily imply it can be eliminated. */
4058 dstsize_cst_p = false;
4062 if (idx_objsize != UINT_MAX)
4063 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
4064 if (tree_fits_uhwi_p (size))
4065 objsize = tree_to_uhwi (size);
4067 if (info.bounded && !dstsize)
4069 /* As a special case, when the explicitly specified destination
4070 size argument (to a bounded function like snprintf) is zero
4071 it is a request to determine the number of bytes on output
4072 without actually producing any. Pretend the size is
4073 unlimited in this case. */
4074 info.objsize = HOST_WIDE_INT_MAX;
4075 info.nowrite = dstsize_cst_p;
4077 else
4079 /* For calls to non-bounded functions or to those of bounded
4080 functions with a non-zero size, warn if the destination
4081 pointer is null. */
4082 if (dstptr && integer_zerop (dstptr))
4084 /* This is diagnosed with -Wformat only when the null is a constant
4085 pointer. The warning here diagnoses instances where the pointer
4086 is not constant. */
4087 location_t loc = gimple_location (info.callstmt);
4088 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
4089 info.warnopt (), "%Gnull destination pointer",
4090 info.callstmt);
4091 return false;
4094 /* Set the object size to the smaller of the two arguments
4095 of both have been specified and they're not equal. */
4096 info.objsize = dstsize < objsize ? dstsize : objsize;
4098 if (info.bounded
4099 && dstsize < target_size_max () / 2 && objsize < dstsize
4100 /* Avoid warning if -Wstringop-overflow is specified since
4101 it also warns for the same thing though only for the
4102 checking built-ins. */
4103 && (idx_objsize == UINT_MAX
4104 || !warn_stringop_overflow))
4106 warning_at (gimple_location (info.callstmt), info.warnopt (),
4107 "specified bound %wu exceeds the size %wu "
4108 "of the destination object", dstsize, objsize);
4112 /* Determine if the format argument may be null and warn if not
4113 and if the argument is null. */
4114 if (integer_zerop (info.format)
4115 && gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
4117 location_t loc = gimple_location (info.callstmt);
4118 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
4119 info.warnopt (), "%Gnull format string",
4120 info.callstmt);
4121 return false;
4124 info.fmtstr = get_format_string (info.format, &info.fmtloc);
4125 if (!info.fmtstr)
4126 return false;
4128 /* The result is the number of bytes output by the formatted function,
4129 including the terminating NUL. */
4130 format_result res = format_result ();
4132 /* I/O functions with no destination argument (i.e., all forms of fprintf
4133 and printf) may fail under any conditions. Others (i.e., all forms of
4134 sprintf) may only fail under specific conditions determined for each
4135 directive. Clear POSUNDER4K for the former set of functions and set
4136 it to true for the latter (it can only be cleared later, but it is
4137 never set to true again). */
4138 res.posunder4k = posunder4k && dstptr;
4140 bool success = compute_format_length (info, &res);
4141 if (res.warned)
4142 gimple_set_no_warning (info.callstmt, true);
4144 /* When optimizing and the printf return value optimization is enabled,
4145 attempt to substitute the computed result for the return value of
4146 the call. Avoid this optimization when -frounding-math is in effect
4147 and the format string contains a floating point directive. */
4148 bool call_removed = false;
4149 if (success && optimize > 0)
4151 /* Save a copy of the iterator pointing at the call. The iterator
4152 may change to point past the call in try_substitute_return_value
4153 but the original value is needed in try_simplify_call. */
4154 gimple_stmt_iterator gsi_call = *gsi;
4156 if (flag_printf_return_value
4157 && (!flag_rounding_math || !res.floating))
4158 call_removed = try_substitute_return_value (gsi, info, res);
4160 if (!call_removed)
4161 try_simplify_call (&gsi_call, info, res);
4164 return call_removed;
4167 edge
4168 sprintf_dom_walker::before_dom_children (basic_block bb)
4170 evrp_range_analyzer.enter (bb);
4171 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
4173 /* Iterate over statements, looking for function calls. */
4174 gimple *stmt = gsi_stmt (si);
4176 /* First record ranges generated by this statement. */
4177 evrp_range_analyzer.record_ranges_from_stmt (stmt, false);
4179 if (is_gimple_call (stmt) && handle_gimple_call (&si))
4180 /* If handle_gimple_call returns true, the iterator is
4181 already pointing to the next statement. */
4182 continue;
4184 gsi_next (&si);
4186 return NULL;
4189 void
4190 sprintf_dom_walker::after_dom_children (basic_block bb)
4192 evrp_range_analyzer.leave (bb);
4195 /* Execute the pass for function FUN. */
4197 unsigned int
4198 pass_sprintf_length::execute (function *fun)
4200 init_target_to_host_charmap ();
4202 calculate_dominance_info (CDI_DOMINATORS);
4204 sprintf_dom_walker sprintf_dom_walker;
4205 sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
4207 /* Clean up object size info. */
4208 fini_object_sizes ();
4209 return 0;
4212 } /* Unnamed namespace. */
4214 /* Return a pointer to a pass object newly constructed from the context
4215 CTXT. */
4217 gimple_opt_pass *
4218 make_pass_sprintf_length (gcc::context *ctxt)
4220 return new pass_sprintf_length (ctxt);