builtins.c (unterminated_array): Use empty brace initialization for c_strlen_data.
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blobd6278305fc4f4e3aff781de688c88305f8d5d0cb
1 /* Copyright (C) 2016-2018 Free Software Foundation, Inc.
2 Contributed by Martin Sebor <msebor@redhat.com>.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
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 c_strlen_data data = { };
2007 tree slen = c_strlen (str, 1, &data, eltsize);
2008 if (slen && TREE_CODE (slen) == INTEGER_CST)
2010 /* The string is properly terminated and
2011 we know its length. */
2012 fmtresult res (tree_to_shwi (slen));
2013 res.nonstr = NULL_TREE;
2014 return res;
2016 else if (!slen
2017 && data.decl
2018 && data.len
2019 && TREE_CODE (data.len) == INTEGER_CST)
2021 /* STR was not properly NUL terminated, but we have
2022 length information about the unterminated string. */
2023 fmtresult res (tree_to_shwi (data.len));
2024 res.nonstr = data.decl;
2025 return res;
2028 /* Determine the length of the shortest and longest string referenced
2029 by STR. Strings of unknown lengths are bounded by the sizes of
2030 arrays that subexpressions of STR may refer to. Pointers that
2031 aren't known to point any such arrays result in LENRANGE[1] set
2032 to SIZE_MAX. NONSTR is set to the declaration of the constant
2033 array that is known not to be nul-terminated. */
2034 tree lenrange[2];
2035 tree nonstr;
2036 bool flexarray = get_range_strlen (str, lenrange, eltsize, false, &nonstr);
2038 if (lenrange [0] || lenrange [1])
2040 HOST_WIDE_INT min
2041 = (tree_fits_uhwi_p (lenrange[0])
2042 ? tree_to_uhwi (lenrange[0])
2043 : 0);
2045 HOST_WIDE_INT max
2046 = (tree_fits_uhwi_p (lenrange[1])
2047 ? tree_to_uhwi (lenrange[1])
2048 : HOST_WIDE_INT_M1U);
2050 /* get_range_strlen() returns the target value of SIZE_MAX for
2051 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2052 which may be bigger. */
2053 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2054 min = HOST_WIDE_INT_M1U;
2055 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2056 max = HOST_WIDE_INT_M1U;
2058 fmtresult res (min, max);
2059 res.nonstr = nonstr;
2061 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2062 by STR are known to be bounded (though not necessarily by their
2063 actual length but perhaps by their maximum possible length). */
2064 if (res.range.max < target_int_max ())
2066 res.knownrange = true;
2067 /* When the the length of the longest string is known and not
2068 excessive use it as the likely length of the string(s). */
2069 res.range.likely = res.range.max;
2071 else
2073 /* When the upper bound is unknown (it can be zero or excessive)
2074 set the likely length to the greater of 1 and the length of
2075 the shortest string and reset the lower bound to zero. */
2076 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2077 res.range.min = 0;
2080 /* If the range of string length has been estimated from the size
2081 of an array at the end of a struct assume that it's longer than
2082 the array bound says it is in case it's used as a poor man's
2083 flexible array member, such as in struct S { char a[4]; }; */
2084 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
2086 return res;
2089 return fmtresult ();
2092 /* Return the minimum and maximum number of characters formatted
2093 by the '%c' format directives and its wide character form for
2094 the argument ARG. ARG can be null (for functions such as
2095 vsprinf). */
2097 static fmtresult
2098 format_character (const directive &dir, tree arg, vr_values *vr_values)
2100 fmtresult res;
2102 res.knownrange = true;
2104 if (dir.specifier == 'C'
2105 || dir.modifier == FMT_LEN_l)
2107 /* A wide character can result in as few as zero bytes. */
2108 res.range.min = 0;
2110 HOST_WIDE_INT min, max;
2111 if (get_int_range (arg, &min, &max, false, 0, vr_values))
2113 if (min == 0 && max == 0)
2115 /* The NUL wide character results in no bytes. */
2116 res.range.max = 0;
2117 res.range.likely = 0;
2118 res.range.unlikely = 0;
2120 else if (min >= 0 && min < 128)
2122 /* Be conservative if the target execution character set
2123 is not a 1-to-1 mapping to the source character set or
2124 if the source set is not ASCII. */
2125 bool one_2_one_ascii
2126 = (target_to_host_charmap[0] == 1 && target_to_host ('a') == 97);
2128 /* A wide character in the ASCII range most likely results
2129 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2130 res.range.max = one_2_one_ascii ? 1 : target_mb_len_max ();;
2131 res.range.likely = 1;
2132 res.range.unlikely = target_mb_len_max ();
2133 res.mayfail = !one_2_one_ascii;
2135 else
2137 /* A wide character outside the ASCII range likely results
2138 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2139 res.range.max = target_mb_len_max ();
2140 res.range.likely = 2;
2141 res.range.unlikely = res.range.max;
2142 /* Converting such a character may fail. */
2143 res.mayfail = true;
2146 else
2148 /* An unknown wide character is treated the same as a wide
2149 character outside the ASCII range. */
2150 res.range.max = target_mb_len_max ();
2151 res.range.likely = 2;
2152 res.range.unlikely = res.range.max;
2153 res.mayfail = true;
2156 else
2158 /* A plain '%c' directive. Its ouput is exactly 1. */
2159 res.range.min = res.range.max = 1;
2160 res.range.likely = res.range.unlikely = 1;
2161 res.knownrange = true;
2164 /* Bump up the byte counters if WIDTH is greater. */
2165 return res.adjust_for_width_or_precision (dir.width);
2168 /* Return the minimum and maximum number of characters formatted
2169 by the '%s' format directive and its wide character form for
2170 the argument ARG. ARG can be null (for functions such as
2171 vsprinf). */
2173 static fmtresult
2174 format_string (const directive &dir, tree arg, vr_values *)
2176 fmtresult res;
2178 /* Compute the range the argument's length can be in. */
2179 int count_by = 1;
2180 if (dir.specifier == 'S' || dir.modifier == FMT_LEN_l)
2182 /* Get a node for a C type that will be the same size
2183 as a wchar_t on the target. */
2184 tree node = get_typenode_from_name (MODIFIED_WCHAR_TYPE);
2186 /* Now that we have a suitable node, get the number of
2187 bytes it occupies. */
2188 count_by = int_size_in_bytes (node);
2189 gcc_checking_assert (count_by == 2 || count_by == 4);
2192 fmtresult slen = get_string_length (arg, count_by);
2193 if (slen.range.min == slen.range.max
2194 && slen.range.min < HOST_WIDE_INT_MAX)
2196 /* The argument is either a string constant or it refers
2197 to one of a number of strings of the same length. */
2199 /* A '%s' directive with a string argument with constant length. */
2200 res.range = slen.range;
2202 if (dir.specifier == 'S'
2203 || dir.modifier == FMT_LEN_l)
2205 /* In the worst case the length of output of a wide string S
2206 is bounded by MB_LEN_MAX * wcslen (S). */
2207 res.range.max *= target_mb_len_max ();
2208 res.range.unlikely = res.range.max;
2209 /* It's likely that the the total length is not more that
2210 2 * wcslen (S).*/
2211 res.range.likely = res.range.min * 2;
2213 if (dir.prec[1] >= 0
2214 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2216 res.range.max = dir.prec[1];
2217 res.range.likely = dir.prec[1];
2218 res.range.unlikely = dir.prec[1];
2221 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2222 res.range.min = 0;
2223 else if (dir.prec[0] >= 0)
2224 res.range.likely = dir.prec[0];
2226 /* Even a non-empty wide character string need not convert into
2227 any bytes. */
2228 res.range.min = 0;
2230 /* A non-empty wide character conversion may fail. */
2231 if (slen.range.max > 0)
2232 res.mayfail = true;
2234 else
2236 res.knownrange = true;
2238 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2239 res.range.min = 0;
2240 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2241 res.range.min = dir.prec[0];
2243 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2245 res.range.max = dir.prec[1];
2246 res.range.likely = dir.prec[1];
2247 res.range.unlikely = dir.prec[1];
2251 else if (arg && integer_zerop (arg))
2253 /* Handle null pointer argument. */
2255 fmtresult res (0);
2256 res.nullp = true;
2257 return res;
2259 else
2261 /* For a '%s' and '%ls' directive with a non-constant string (either
2262 one of a number of strings of known length or an unknown string)
2263 the minimum number of characters is lesser of PRECISION[0] and
2264 the length of the shortest known string or zero, and the maximum
2265 is the lessser of the length of the longest known string or
2266 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2267 the minimum at level 1 and the greater of the minimum and 1
2268 at level 2. This result is adjust upward for width (if it's
2269 specified). */
2271 if (dir.specifier == 'S'
2272 || dir.modifier == FMT_LEN_l)
2274 /* A wide character converts to as few as zero bytes. */
2275 slen.range.min = 0;
2276 if (slen.range.max < target_int_max ())
2277 slen.range.max *= target_mb_len_max ();
2279 if (slen.range.likely < target_int_max ())
2280 slen.range.likely *= 2;
2282 if (slen.range.likely < target_int_max ())
2283 slen.range.unlikely *= target_mb_len_max ();
2285 /* A non-empty wide character conversion may fail. */
2286 if (slen.range.max > 0)
2287 res.mayfail = true;
2290 res.range = slen.range;
2292 if (dir.prec[0] >= 0)
2294 /* Adjust the minimum to zero if the string length is unknown,
2295 or at most the lower bound of the precision otherwise. */
2296 if (slen.range.min >= target_int_max ())
2297 res.range.min = 0;
2298 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2299 res.range.min = dir.prec[0];
2301 /* Make both maxima no greater than the upper bound of precision. */
2302 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2303 || slen.range.max >= target_int_max ())
2305 res.range.max = dir.prec[1];
2306 res.range.unlikely = dir.prec[1];
2309 /* If precision is constant, set the likely counter to the lesser
2310 of it and the maximum string length. Otherwise, if the lower
2311 bound of precision is greater than zero, set the likely counter
2312 to the minimum. Otherwise set it to zero or one based on
2313 the warning level. */
2314 if (dir.prec[0] == dir.prec[1])
2315 res.range.likely
2316 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2317 ? dir.prec[0] : slen.range.max);
2318 else if (dir.prec[0] > 0)
2319 res.range.likely = res.range.min;
2320 else
2321 res.range.likely = warn_level > 1;
2323 else if (dir.prec[1] >= 0)
2325 res.range.min = 0;
2326 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2327 res.range.max = dir.prec[1];
2328 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2330 else if (slen.range.min >= target_int_max ())
2332 res.range.min = 0;
2333 res.range.max = HOST_WIDE_INT_MAX;
2334 /* At level 1 strings of unknown length are assumed to be
2335 empty, while at level 1 they are assumed to be one byte
2336 long. */
2337 res.range.likely = warn_level > 1;
2339 else
2341 /* A string of unknown length unconstrained by precision is
2342 assumed to be empty at level 1 and just one character long
2343 at higher levels. */
2344 if (res.range.likely >= target_int_max ())
2345 res.range.likely = warn_level > 1;
2348 res.range.unlikely = res.range.max;
2351 /* If the argument isn't a nul-terminated string and the number
2352 of bytes on output isn't bounded by precision, set NONSTR. */
2353 if (slen.nonstr && slen.range.min < (unsigned HOST_WIDE_INT)dir.prec[0])
2354 res.nonstr = slen.nonstr;
2356 /* Bump up the byte counters if WIDTH is greater. */
2357 return res.adjust_for_width_or_precision (dir.width);
2360 /* Format plain string (part of the format string itself). */
2362 static fmtresult
2363 format_plain (const directive &dir, tree, vr_values *)
2365 fmtresult res (dir.len);
2366 return res;
2369 /* Return true if the RESULT of a directive in a call describe by INFO
2370 should be diagnosed given the AVAILable space in the destination. */
2372 static bool
2373 should_warn_p (const sprintf_dom_walker::call_info &info,
2374 const result_range &avail, const result_range &result)
2376 if (result.max <= avail.min)
2378 /* The least amount of space remaining in the destination is big
2379 enough for the longest output. */
2380 return false;
2383 if (info.bounded)
2385 if (warn_format_trunc == 1 && result.min <= avail.max
2386 && info.retval_used ())
2388 /* The likely amount of space remaining in the destination is big
2389 enough for the least output and the return value is used. */
2390 return false;
2393 if (warn_format_trunc == 1 && result.likely <= avail.likely
2394 && !info.retval_used ())
2396 /* The likely amount of space remaining in the destination is big
2397 enough for the likely output and the return value is unused. */
2398 return false;
2401 if (warn_format_trunc == 2
2402 && result.likely <= avail.min
2403 && (result.max <= avail.min
2404 || result.max > HOST_WIDE_INT_MAX))
2406 /* The minimum amount of space remaining in the destination is big
2407 enough for the longest output. */
2408 return false;
2411 else
2413 if (warn_level == 1 && result.likely <= avail.likely)
2415 /* The likely amount of space remaining in the destination is big
2416 enough for the likely output. */
2417 return false;
2420 if (warn_level == 2
2421 && result.likely <= avail.min
2422 && (result.max <= avail.min
2423 || result.max > HOST_WIDE_INT_MAX))
2425 /* The minimum amount of space remaining in the destination is big
2426 enough for the longest output. */
2427 return false;
2431 return true;
2434 /* At format string location describe by DIRLOC in a call described
2435 by INFO, issue a warning for a directive DIR whose output may be
2436 in excess of the available space AVAIL_RANGE in the destination
2437 given the formatting result FMTRES. This function does nothing
2438 except decide whether to issue a warning for a possible write
2439 past the end or truncation and, if so, format the warning.
2440 Return true if a warning has been issued. */
2442 static bool
2443 maybe_warn (substring_loc &dirloc, location_t argloc,
2444 const sprintf_dom_walker::call_info &info,
2445 const result_range &avail_range, const result_range &res,
2446 const directive &dir)
2448 if (!should_warn_p (info, avail_range, res))
2449 return false;
2451 /* A warning will definitely be issued below. */
2453 /* The maximum byte count to reference in the warning. Larger counts
2454 imply that the upper bound is unknown (and could be anywhere between
2455 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2456 than "between N and X" where X is some huge number. */
2457 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2459 /* True when there is enough room in the destination for the least
2460 amount of a directive's output but not enough for its likely or
2461 maximum output. */
2462 bool maybe = (res.min <= avail_range.max
2463 && (avail_range.min < res.likely
2464 || (res.max < HOST_WIDE_INT_MAX
2465 && avail_range.min < res.max)));
2467 /* Buffer for the directive in the host character set (used when
2468 the source character set is different). */
2469 char hostdir[32];
2471 if (avail_range.min == avail_range.max)
2473 /* The size of the destination region is exact. */
2474 unsigned HOST_WIDE_INT navail = avail_range.max;
2476 if (target_to_host (*dir.beg) != '%')
2478 /* For plain character directives (i.e., the format string itself)
2479 but not others, point the caret at the first character that's
2480 past the end of the destination. */
2481 if (navail < dir.len)
2482 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2485 if (*dir.beg == '\0')
2487 /* This is the terminating nul. */
2488 gcc_assert (res.min == 1 && res.min == res.max);
2490 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2491 info.bounded
2492 ? (maybe
2493 ? G_("%qE output may be truncated before the "
2494 "last format character")
2495 : G_("%qE output truncated before the last "
2496 "format character"))
2497 : (maybe
2498 ? G_("%qE may write a terminating nul past the "
2499 "end of the destination")
2500 : G_("%qE writing a terminating nul past the "
2501 "end of the destination")),
2502 info.func);
2505 if (res.min == res.max)
2507 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2508 if (!info.bounded)
2509 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2510 "%<%.*s%> directive writing %wu byte into a "
2511 "region of size %wu",
2512 "%<%.*s%> directive writing %wu bytes into a "
2513 "region of size %wu",
2514 (int) dir.len, d, res.min, navail);
2515 else if (maybe)
2516 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2517 "%<%.*s%> directive output may be truncated "
2518 "writing %wu byte into a region of size %wu",
2519 "%<%.*s%> directive output may be truncated "
2520 "writing %wu bytes into a region of size %wu",
2521 (int) dir.len, d, res.min, navail);
2522 else
2523 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2524 "%<%.*s%> directive output truncated writing "
2525 "%wu byte into a region of size %wu",
2526 "%<%.*s%> directive output truncated writing "
2527 "%wu bytes into a region of size %wu",
2528 (int) dir.len, d, res.min, navail);
2530 if (res.min == 0 && res.max < maxbytes)
2531 return fmtwarn (dirloc, argloc, NULL,
2532 info.warnopt (),
2533 info.bounded
2534 ? (maybe
2535 ? G_("%<%.*s%> directive output may be truncated "
2536 "writing up to %wu bytes into a region of "
2537 "size %wu")
2538 : G_("%<%.*s%> directive output truncated writing "
2539 "up to %wu bytes into a region of size %wu"))
2540 : G_("%<%.*s%> directive writing up to %wu bytes "
2541 "into a region of size %wu"), (int) dir.len,
2542 target_to_host (hostdir, sizeof hostdir, dir.beg),
2543 res.max, navail);
2545 if (res.min == 0 && maxbytes <= res.max)
2546 /* This is a special case to avoid issuing the potentially
2547 confusing warning:
2548 writing 0 or more bytes into a region of size 0. */
2549 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2550 info.bounded
2551 ? (maybe
2552 ? G_("%<%.*s%> directive output may be truncated "
2553 "writing likely %wu or more bytes into a "
2554 "region of size %wu")
2555 : G_("%<%.*s%> directive output truncated writing "
2556 "likely %wu or more bytes into a region of "
2557 "size %wu"))
2558 : G_("%<%.*s%> directive writing likely %wu or more "
2559 "bytes into a region of size %wu"), (int) dir.len,
2560 target_to_host (hostdir, sizeof hostdir, dir.beg),
2561 res.likely, navail);
2563 if (res.max < maxbytes)
2564 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2565 info.bounded
2566 ? (maybe
2567 ? G_("%<%.*s%> directive output may be truncated "
2568 "writing between %wu and %wu bytes into a "
2569 "region of size %wu")
2570 : G_("%<%.*s%> directive output truncated "
2571 "writing between %wu and %wu bytes into a "
2572 "region of size %wu"))
2573 : G_("%<%.*s%> directive writing between %wu and "
2574 "%wu bytes into a region of size %wu"),
2575 (int) dir.len,
2576 target_to_host (hostdir, sizeof hostdir, dir.beg),
2577 res.min, res.max, navail);
2579 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2580 info.bounded
2581 ? (maybe
2582 ? G_("%<%.*s%> directive output may be truncated "
2583 "writing %wu or more bytes into a region of "
2584 "size %wu")
2585 : G_("%<%.*s%> directive output truncated writing "
2586 "%wu or more bytes into a region of size %wu"))
2587 : G_("%<%.*s%> directive writing %wu or more bytes "
2588 "into a region of size %wu"), (int) dir.len,
2589 target_to_host (hostdir, sizeof hostdir, dir.beg),
2590 res.min, navail);
2593 /* The size of the destination region is a range. */
2595 if (target_to_host (*dir.beg) != '%')
2597 unsigned HOST_WIDE_INT navail = avail_range.max;
2599 /* For plain character directives (i.e., the format string itself)
2600 but not others, point the caret at the first character that's
2601 past the end of the destination. */
2602 if (navail < dir.len)
2603 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2606 if (*dir.beg == '\0')
2608 gcc_assert (res.min == 1 && res.min == res.max);
2610 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2611 info.bounded
2612 ? (maybe
2613 ? G_("%qE output may be truncated before the last "
2614 "format character")
2615 : G_("%qE output truncated before the last format "
2616 "character"))
2617 : (maybe
2618 ? G_("%qE may write a terminating nul past the end "
2619 "of the destination")
2620 : G_("%qE writing a terminating nul past the end "
2621 "of the destination")), info.func);
2624 if (res.min == res.max)
2626 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2627 if (!info.bounded)
2628 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2629 "%<%.*s%> directive writing %wu byte into a region "
2630 "of size between %wu and %wu",
2631 "%<%.*s%> directive writing %wu bytes into a region "
2632 "of size between %wu and %wu", (int) dir.len, d,
2633 res.min, avail_range.min, avail_range.max);
2634 else if (maybe)
2635 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2636 "%<%.*s%> directive output may be truncated writing "
2637 "%wu byte into a region of size between %wu and %wu",
2638 "%<%.*s%> directive output may be truncated writing "
2639 "%wu bytes into a region of size between %wu and "
2640 "%wu", (int) dir.len, d, res.min, avail_range.min,
2641 avail_range.max);
2642 else
2643 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2644 "%<%.*s%> directive output truncated writing %wu "
2645 "byte into a region of size between %wu and %wu",
2646 "%<%.*s%> directive output truncated writing %wu "
2647 "bytes into a region of size between %wu and %wu",
2648 (int) dir.len, d, res.min, avail_range.min,
2649 avail_range.max);
2652 if (res.min == 0 && res.max < maxbytes)
2653 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2654 info.bounded
2655 ? (maybe
2656 ? G_("%<%.*s%> directive output may be truncated "
2657 "writing up to %wu bytes into a region of size "
2658 "between %wu and %wu")
2659 : G_("%<%.*s%> directive output truncated writing "
2660 "up to %wu bytes into a region of size between "
2661 "%wu and %wu"))
2662 : G_("%<%.*s%> directive writing up to %wu bytes "
2663 "into a region of size between %wu and %wu"),
2664 (int) dir.len,
2665 target_to_host (hostdir, sizeof hostdir, dir.beg),
2666 res.max, avail_range.min, avail_range.max);
2668 if (res.min == 0 && maxbytes <= res.max)
2669 /* This is a special case to avoid issuing the potentially confusing
2670 warning:
2671 writing 0 or more bytes into a region of size between 0 and N. */
2672 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2673 info.bounded
2674 ? (maybe
2675 ? G_("%<%.*s%> directive output may be truncated "
2676 "writing likely %wu or more bytes into a region "
2677 "of size between %wu and %wu")
2678 : G_("%<%.*s%> directive output truncated writing "
2679 "likely %wu or more bytes into a region of size "
2680 "between %wu and %wu"))
2681 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2682 "into a region of size between %wu and %wu"),
2683 (int) dir.len,
2684 target_to_host (hostdir, sizeof hostdir, dir.beg),
2685 res.likely, avail_range.min, avail_range.max);
2687 if (res.max < maxbytes)
2688 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2689 info.bounded
2690 ? (maybe
2691 ? G_("%<%.*s%> directive output may be truncated "
2692 "writing between %wu and %wu bytes into a region "
2693 "of size between %wu and %wu")
2694 : G_("%<%.*s%> directive output truncated writing "
2695 "between %wu and %wu bytes into a region of size "
2696 "between %wu and %wu"))
2697 : G_("%<%.*s%> directive writing between %wu and "
2698 "%wu bytes into a region of size between %wu and "
2699 "%wu"), (int) dir.len,
2700 target_to_host (hostdir, sizeof hostdir, dir.beg),
2701 res.min, res.max, avail_range.min, avail_range.max);
2703 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2704 info.bounded
2705 ? (maybe
2706 ? G_("%<%.*s%> directive output may be truncated writing "
2707 "%wu or more bytes into a region of size between "
2708 "%wu and %wu")
2709 : G_("%<%.*s%> directive output truncated writing "
2710 "%wu or more bytes into a region of size between "
2711 "%wu and %wu"))
2712 : G_("%<%.*s%> directive writing %wu or more bytes "
2713 "into a region of size between %wu and %wu"),
2714 (int) dir.len,
2715 target_to_host (hostdir, sizeof hostdir, dir.beg),
2716 res.min, avail_range.min, avail_range.max);
2719 /* Compute the length of the output resulting from the directive DIR
2720 in a call described by INFO and update the overall result of the call
2721 in *RES. Return true if the directive has been handled. */
2723 static bool
2724 format_directive (const sprintf_dom_walker::call_info &info,
2725 format_result *res, const directive &dir,
2726 class vr_values *vr_values)
2728 /* Offset of the beginning of the directive from the beginning
2729 of the format string. */
2730 size_t offset = dir.beg - info.fmtstr;
2731 size_t start = offset;
2732 size_t length = offset + dir.len - !!dir.len;
2734 /* Create a location for the whole directive from the % to the format
2735 specifier. */
2736 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2737 offset, start, length);
2739 /* Also get the location of the argument if possible.
2740 This doesn't work for integer literals or function calls. */
2741 location_t argloc = UNKNOWN_LOCATION;
2742 if (dir.arg)
2743 argloc = EXPR_LOCATION (dir.arg);
2745 /* Bail when there is no function to compute the output length,
2746 or when minimum length checking has been disabled. */
2747 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2748 return false;
2750 /* Compute the range of lengths of the formatted output. */
2751 fmtresult fmtres = dir.fmtfunc (dir, dir.arg, vr_values);
2753 /* Record whether the output of all directives is known to be
2754 bounded by some maximum, implying that their arguments are
2755 either known exactly or determined to be in a known range
2756 or, for strings, limited by the upper bounds of the arrays
2757 they refer to. */
2758 res->knownrange &= fmtres.knownrange;
2760 if (!fmtres.knownrange)
2762 /* Only when the range is known, check it against the host value
2763 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2764 INT_MAX precision, which is the longest possible output of any
2765 single directive). That's the largest valid byte count (though
2766 not valid call to a printf-like function because it can never
2767 return such a count). Otherwise, the range doesn't correspond
2768 to known values of the argument. */
2769 if (fmtres.range.max > target_dir_max ())
2771 /* Normalize the MAX counter to avoid having to deal with it
2772 later. The counter can be less than HOST_WIDE_INT_M1U
2773 when compiling for an ILP32 target on an LP64 host. */
2774 fmtres.range.max = HOST_WIDE_INT_M1U;
2775 /* Disable exact and maximum length checking after a failure
2776 to determine the maximum number of characters (for example
2777 for wide characters or wide character strings) but continue
2778 tracking the minimum number of characters. */
2779 res->range.max = HOST_WIDE_INT_M1U;
2782 if (fmtres.range.min > target_dir_max ())
2784 /* Disable exact length checking after a failure to determine
2785 even the minimum number of characters (it shouldn't happen
2786 except in an error) but keep tracking the minimum and maximum
2787 number of characters. */
2788 return true;
2792 /* Buffer for the directive in the host character set (used when
2793 the source character set is different). */
2794 char hostdir[32];
2796 int dirlen = dir.len;
2798 if (fmtres.nullp)
2800 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2801 "%G%<%.*s%> directive argument is null",
2802 info.callstmt, dirlen,
2803 target_to_host (hostdir, sizeof hostdir, dir.beg));
2805 /* Don't bother processing the rest of the format string. */
2806 res->warned = true;
2807 res->range.min = HOST_WIDE_INT_M1U;
2808 res->range.max = HOST_WIDE_INT_M1U;
2809 return false;
2812 /* Compute the number of available bytes in the destination. There
2813 must always be at least one byte of space for the terminating
2814 NUL that's appended after the format string has been processed. */
2815 result_range avail_range = bytes_remaining (info.objsize, *res);
2817 bool warned = res->warned;
2819 if (!warned)
2820 warned = maybe_warn (dirloc, argloc, info, avail_range,
2821 fmtres.range, dir);
2823 /* Bump up the total maximum if it isn't too big. */
2824 if (res->range.max < HOST_WIDE_INT_MAX
2825 && fmtres.range.max < HOST_WIDE_INT_MAX)
2826 res->range.max += fmtres.range.max;
2828 /* Raise the total unlikely maximum by the larger of the maximum
2829 and the unlikely maximum. */
2830 unsigned HOST_WIDE_INT save = res->range.unlikely;
2831 if (fmtres.range.max < fmtres.range.unlikely)
2832 res->range.unlikely += fmtres.range.unlikely;
2833 else
2834 res->range.unlikely += fmtres.range.max;
2836 if (res->range.unlikely < save)
2837 res->range.unlikely = HOST_WIDE_INT_M1U;
2839 res->range.min += fmtres.range.min;
2840 res->range.likely += fmtres.range.likely;
2842 /* Has the minimum directive output length exceeded the maximum
2843 of 4095 bytes required to be supported? */
2844 bool minunder4k = fmtres.range.min < 4096;
2845 bool maxunder4k = fmtres.range.max < 4096;
2846 /* Clear POSUNDER4K in the overall result if the maximum has exceeded
2847 the 4k (this is necessary to avoid the return value optimization
2848 that may not be safe in the maximum case). */
2849 if (!maxunder4k)
2850 res->posunder4k = false;
2851 /* Also clear POSUNDER4K if the directive may fail. */
2852 if (fmtres.mayfail)
2853 res->posunder4k = false;
2855 if (!warned
2856 /* Only warn at level 2. */
2857 && warn_level > 1
2858 && (!minunder4k
2859 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2861 /* The directive output may be longer than the maximum required
2862 to be handled by an implementation according to 7.21.6.1, p15
2863 of C11. Warn on this only at level 2 but remember this and
2864 prevent folding the return value when done. This allows for
2865 the possibility of the actual libc call failing due to ENOMEM
2866 (like Glibc does under some conditions). */
2868 if (fmtres.range.min == fmtres.range.max)
2869 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2870 "%<%.*s%> directive output of %wu bytes exceeds "
2871 "minimum required size of 4095", dirlen,
2872 target_to_host (hostdir, sizeof hostdir, dir.beg),
2873 fmtres.range.min);
2874 else
2875 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2876 minunder4k
2877 ? G_("%<%.*s%> directive output between %wu and %wu "
2878 "bytes may exceed minimum required size of "
2879 "4095")
2880 : G_("%<%.*s%> directive output between %wu and %wu "
2881 "bytes exceeds minimum required size of 4095"),
2882 dirlen,
2883 target_to_host (hostdir, sizeof hostdir, dir.beg),
2884 fmtres.range.min, fmtres.range.max);
2887 /* Has the likely and maximum directive output exceeded INT_MAX? */
2888 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2889 /* Don't consider the maximum to be in excess when it's the result
2890 of a string of unknown length (i.e., whose maximum has been set
2891 to be greater than or equal to HOST_WIDE_INT_MAX. */
2892 bool maxximax = (*dir.beg
2893 && res->range.max > target_int_max ()
2894 && res->range.max < HOST_WIDE_INT_MAX);
2896 if (!warned
2897 /* Warn for the likely output size at level 1. */
2898 && (likelyximax
2899 /* But only warn for the maximum at level 2. */
2900 || (warn_level > 1
2901 && maxximax
2902 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2904 /* The directive output causes the total length of output
2905 to exceed INT_MAX bytes. */
2907 if (fmtres.range.min == fmtres.range.max)
2908 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2909 "%<%.*s%> directive output of %wu bytes causes "
2910 "result to exceed %<INT_MAX%>", dirlen,
2911 target_to_host (hostdir, sizeof hostdir, dir.beg),
2912 fmtres.range.min);
2913 else
2914 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2915 fmtres.range.min > target_int_max ()
2916 ? G_("%<%.*s%> directive output between %wu and "
2917 "%wu bytes causes result to exceed "
2918 "%<INT_MAX%>")
2919 : G_("%<%.*s%> directive output between %wu and "
2920 "%wu bytes may cause result to exceed "
2921 "%<INT_MAX%>"), dirlen,
2922 target_to_host (hostdir, sizeof hostdir, dir.beg),
2923 fmtres.range.min, fmtres.range.max);
2926 if (!warned && fmtres.nonstr)
2928 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2929 "%<%.*s%> directive argument is not a nul-terminated "
2930 "string",
2931 dirlen,
2932 target_to_host (hostdir, sizeof hostdir, dir.beg));
2933 if (warned && DECL_P (fmtres.nonstr))
2934 inform (DECL_SOURCE_LOCATION (fmtres.nonstr),
2935 "referenced argument declared here");
2936 return false;
2939 if (warned && fmtres.range.min < fmtres.range.likely
2940 && fmtres.range.likely < fmtres.range.max)
2941 inform_n (info.fmtloc, fmtres.range.likely,
2942 "assuming directive output of %wu byte",
2943 "assuming directive output of %wu bytes",
2944 fmtres.range.likely);
2946 if (warned && fmtres.argmin)
2948 if (fmtres.argmin == fmtres.argmax)
2949 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2950 else if (fmtres.knownrange)
2951 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2952 fmtres.argmin, fmtres.argmax);
2953 else
2954 inform (info.fmtloc,
2955 "using the range [%E, %E] for directive argument",
2956 fmtres.argmin, fmtres.argmax);
2959 res->warned |= warned;
2961 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2963 /* If a warning has been issued for buffer overflow or truncation
2964 (but not otherwise) help the user figure out how big a buffer
2965 they need. */
2967 location_t callloc = gimple_location (info.callstmt);
2969 unsigned HOST_WIDE_INT min = res->range.min;
2970 unsigned HOST_WIDE_INT max = res->range.max;
2972 if (min == max)
2973 inform (callloc,
2974 (min == 1
2975 ? G_("%qE output %wu byte into a destination of size %wu")
2976 : G_("%qE output %wu bytes into a destination of size %wu")),
2977 info.func, min, info.objsize);
2978 else if (max < HOST_WIDE_INT_MAX)
2979 inform (callloc,
2980 "%qE output between %wu and %wu bytes into "
2981 "a destination of size %wu",
2982 info.func, min, max, info.objsize);
2983 else if (min < res->range.likely && res->range.likely < max)
2984 inform (callloc,
2985 "%qE output %wu or more bytes (assuming %wu) into "
2986 "a destination of size %wu",
2987 info.func, min, res->range.likely, info.objsize);
2988 else
2989 inform (callloc,
2990 "%qE output %wu or more bytes into a destination of size %wu",
2991 info.func, min, info.objsize);
2994 if (dump_file && *dir.beg)
2996 fprintf (dump_file,
2997 " Result: "
2998 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
2999 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
3000 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3001 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
3002 fmtres.range.min, fmtres.range.likely,
3003 fmtres.range.max, fmtres.range.unlikely,
3004 res->range.min, res->range.likely,
3005 res->range.max, res->range.unlikely);
3008 return true;
3011 /* Parse a format directive in function call described by INFO starting
3012 at STR and populate DIR structure. Bump up *ARGNO by the number of
3013 arguments extracted for the directive. Return the length of
3014 the directive. */
3016 static size_t
3017 parse_directive (sprintf_dom_walker::call_info &info,
3018 directive &dir, format_result *res,
3019 const char *str, unsigned *argno,
3020 vr_values *vr_values)
3022 const char *pcnt = strchr (str, target_percent);
3023 dir.beg = str;
3025 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
3027 /* This directive is either a plain string or the terminating nul
3028 (which isn't really a directive but it simplifies things to
3029 handle it as if it were). */
3030 dir.len = len;
3031 dir.fmtfunc = format_plain;
3033 if (dump_file)
3035 fprintf (dump_file, " Directive %u at offset "
3036 HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
3037 "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
3038 dir.dirno,
3039 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3040 (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
3043 return len - !*str;
3046 const char *pf = pcnt + 1;
3048 /* POSIX numbered argument index or zero when none. */
3049 HOST_WIDE_INT dollar = 0;
3051 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3052 when given by a va_list argument, and a non-negative value
3053 when specified in the format string itself. */
3054 HOST_WIDE_INT width = -1;
3055 HOST_WIDE_INT precision = -1;
3057 /* Pointers to the beginning of the width and precision decimal
3058 string (if any) within the directive. */
3059 const char *pwidth = 0;
3060 const char *pprec = 0;
3062 /* When the value of the decimal string that specifies width or
3063 precision is out of range, points to the digit that causes
3064 the value to exceed the limit. */
3065 const char *werange = NULL;
3066 const char *perange = NULL;
3068 /* Width specified via the asterisk. Need not be INTEGER_CST.
3069 For vararg functions set to void_node. */
3070 tree star_width = NULL_TREE;
3072 /* Width specified via the asterisk. Need not be INTEGER_CST.
3073 For vararg functions set to void_node. */
3074 tree star_precision = NULL_TREE;
3076 if (ISDIGIT (target_to_host (*pf)))
3078 /* This could be either a POSIX positional argument, the '0'
3079 flag, or a width, depending on what follows. Store it as
3080 width and sort it out later after the next character has
3081 been seen. */
3082 pwidth = pf;
3083 width = target_strtol10 (&pf, &werange);
3085 else if (target_to_host (*pf) == '*')
3087 /* Similarly to the block above, this could be either a POSIX
3088 positional argument or a width, depending on what follows. */
3089 if (*argno < gimple_call_num_args (info.callstmt))
3090 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3091 else
3092 star_width = void_node;
3093 ++pf;
3096 if (target_to_host (*pf) == '$')
3098 /* Handle the POSIX dollar sign which references the 1-based
3099 positional argument number. */
3100 if (width != -1)
3101 dollar = width + info.argidx;
3102 else if (star_width
3103 && TREE_CODE (star_width) == INTEGER_CST
3104 && (TYPE_PRECISION (TREE_TYPE (star_width))
3105 <= TYPE_PRECISION (integer_type_node)))
3106 dollar = width + tree_to_shwi (star_width);
3108 /* Bail when the numbered argument is out of range (it will
3109 have already been diagnosed by -Wformat). */
3110 if (dollar == 0
3111 || dollar == (int)info.argidx
3112 || dollar > gimple_call_num_args (info.callstmt))
3113 return false;
3115 --dollar;
3117 star_width = NULL_TREE;
3118 width = -1;
3119 ++pf;
3122 if (dollar || !star_width)
3124 if (width != -1)
3126 if (width == 0)
3128 /* The '0' that has been interpreted as a width above is
3129 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3130 and continue processing other flags. */
3131 width = -1;
3132 dir.set_flag ('0');
3134 else if (!dollar)
3136 /* (Non-zero) width has been seen. The next character
3137 is either a period or a digit. */
3138 goto start_precision;
3141 /* When either '$' has been seen, or width has not been seen,
3142 the next field is the optional flags followed by an optional
3143 width. */
3144 for ( ; ; ) {
3145 switch (target_to_host (*pf))
3147 case ' ':
3148 case '0':
3149 case '+':
3150 case '-':
3151 case '#':
3152 dir.set_flag (target_to_host (*pf++));
3153 break;
3155 default:
3156 goto start_width;
3160 start_width:
3161 if (ISDIGIT (target_to_host (*pf)))
3163 werange = 0;
3164 pwidth = pf;
3165 width = target_strtol10 (&pf, &werange);
3167 else if (target_to_host (*pf) == '*')
3169 if (*argno < gimple_call_num_args (info.callstmt))
3170 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3171 else
3173 /* This is (likely) a va_list. It could also be an invalid
3174 call with insufficient arguments. */
3175 star_width = void_node;
3177 ++pf;
3179 else if (target_to_host (*pf) == '\'')
3181 /* The POSIX apostrophe indicating a numeric grouping
3182 in the current locale. Even though it's possible to
3183 estimate the upper bound on the size of the output
3184 based on the number of digits it probably isn't worth
3185 continuing. */
3186 return 0;
3190 start_precision:
3191 if (target_to_host (*pf) == '.')
3193 ++pf;
3195 if (ISDIGIT (target_to_host (*pf)))
3197 pprec = pf;
3198 precision = target_strtol10 (&pf, &perange);
3200 else if (target_to_host (*pf) == '*')
3202 if (*argno < gimple_call_num_args (info.callstmt))
3203 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3204 else
3206 /* This is (likely) a va_list. It could also be an invalid
3207 call with insufficient arguments. */
3208 star_precision = void_node;
3210 ++pf;
3212 else
3214 /* The decimal precision or the asterisk are optional.
3215 When neither is dirified it's taken to be zero. */
3216 precision = 0;
3220 switch (target_to_host (*pf))
3222 case 'h':
3223 if (target_to_host (pf[1]) == 'h')
3225 ++pf;
3226 dir.modifier = FMT_LEN_hh;
3228 else
3229 dir.modifier = FMT_LEN_h;
3230 ++pf;
3231 break;
3233 case 'j':
3234 dir.modifier = FMT_LEN_j;
3235 ++pf;
3236 break;
3238 case 'L':
3239 dir.modifier = FMT_LEN_L;
3240 ++pf;
3241 break;
3243 case 'l':
3244 if (target_to_host (pf[1]) == 'l')
3246 ++pf;
3247 dir.modifier = FMT_LEN_ll;
3249 else
3250 dir.modifier = FMT_LEN_l;
3251 ++pf;
3252 break;
3254 case 't':
3255 dir.modifier = FMT_LEN_t;
3256 ++pf;
3257 break;
3259 case 'z':
3260 dir.modifier = FMT_LEN_z;
3261 ++pf;
3262 break;
3265 switch (target_to_host (*pf))
3267 /* Handle a sole '%' character the same as "%%" but since it's
3268 undefined prevent the result from being folded. */
3269 case '\0':
3270 --pf;
3271 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3272 /* FALLTHRU */
3273 case '%':
3274 dir.fmtfunc = format_percent;
3275 break;
3277 case 'a':
3278 case 'A':
3279 case 'e':
3280 case 'E':
3281 case 'f':
3282 case 'F':
3283 case 'g':
3284 case 'G':
3285 res->floating = true;
3286 dir.fmtfunc = format_floating;
3287 break;
3289 case 'd':
3290 case 'i':
3291 case 'o':
3292 case 'u':
3293 case 'x':
3294 case 'X':
3295 dir.fmtfunc = format_integer;
3296 break;
3298 case 'p':
3299 /* The %p output is implementation-defined. It's possible
3300 to determine this format but due to extensions (edirially
3301 those of the Linux kernel -- see bug 78512) the first %p
3302 in the format string disables any further processing. */
3303 return false;
3305 case 'n':
3306 /* %n has side-effects even when nothing is actually printed to
3307 any buffer. */
3308 info.nowrite = false;
3309 dir.fmtfunc = format_none;
3310 break;
3312 case 'C':
3313 case 'c':
3314 /* POSIX wide character and C/POSIX narrow character. */
3315 dir.fmtfunc = format_character;
3316 break;
3318 case 'S':
3319 case 's':
3320 /* POSIX wide string and C/POSIX narrow character string. */
3321 dir.fmtfunc = format_string;
3322 break;
3324 default:
3325 /* Unknown conversion specification. */
3326 return 0;
3329 dir.specifier = target_to_host (*pf++);
3331 /* Store the length of the format directive. */
3332 dir.len = pf - pcnt;
3334 /* Buffer for the directive in the host character set (used when
3335 the source character set is different). */
3336 char hostdir[32];
3338 if (star_width)
3340 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3341 dir.set_width (star_width, vr_values);
3342 else
3344 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3345 (width is the absolute value of that specified). */
3346 dir.width[0] = 0;
3347 dir.width[1] = target_int_max () + 1;
3350 else
3352 if (width == LONG_MAX && werange)
3354 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3355 size_t caret = begin + (werange - pcnt);
3356 size_t end = pf - info.fmtstr - 1;
3358 /* Create a location for the width part of the directive,
3359 pointing the caret at the first out-of-range digit. */
3360 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3361 caret, begin, end);
3363 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3364 "%<%.*s%> directive width out of range", (int) dir.len,
3365 target_to_host (hostdir, sizeof hostdir, dir.beg));
3368 dir.set_width (width);
3371 if (star_precision)
3373 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3374 dir.set_precision (star_precision, vr_values);
3375 else
3377 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3378 (unlike width, negative precision is ignored). */
3379 dir.prec[0] = -1;
3380 dir.prec[1] = target_int_max ();
3383 else
3385 if (precision == LONG_MAX && perange)
3387 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3388 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3389 size_t end = pf - info.fmtstr - 2;
3391 /* Create a location for the precision part of the directive,
3392 including the leading period, pointing the caret at the first
3393 out-of-range digit . */
3394 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3395 caret, begin, end);
3397 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3398 "%<%.*s%> directive precision out of range", (int) dir.len,
3399 target_to_host (hostdir, sizeof hostdir, dir.beg));
3402 dir.set_precision (precision);
3405 /* Extract the argument if the directive takes one and if it's
3406 available (e.g., the function doesn't take a va_list). Treat
3407 missing arguments the same as va_list, even though they will
3408 have likely already been diagnosed by -Wformat. */
3409 if (dir.specifier != '%'
3410 && *argno < gimple_call_num_args (info.callstmt))
3411 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3413 if (dump_file)
3415 fprintf (dump_file,
3416 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3417 ": \"%.*s\"",
3418 dir.dirno,
3419 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3420 (int)dir.len, dir.beg);
3421 if (star_width)
3423 if (dir.width[0] == dir.width[1])
3424 fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
3425 dir.width[0]);
3426 else
3427 fprintf (dump_file,
3428 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3429 ", " HOST_WIDE_INT_PRINT_DEC "]",
3430 dir.width[0], dir.width[1]);
3433 if (star_precision)
3435 if (dir.prec[0] == dir.prec[1])
3436 fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
3437 dir.prec[0]);
3438 else
3439 fprintf (dump_file,
3440 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3441 HOST_WIDE_INT_PRINT_DEC "]",
3442 dir.prec[0], dir.prec[1]);
3444 fputc ('\n', dump_file);
3447 return dir.len;
3450 /* Compute the length of the output resulting from the call to a formatted
3451 output function described by INFO and store the result of the call in
3452 *RES. Issue warnings for detected past the end writes. Return true
3453 if the complete format string has been processed and *RES can be relied
3454 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3455 that caused the processing to be terminated early). */
3457 bool
3458 sprintf_dom_walker::compute_format_length (call_info &info,
3459 format_result *res)
3461 if (dump_file)
3463 location_t callloc = gimple_location (info.callstmt);
3464 fprintf (dump_file, "%s:%i: ",
3465 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3466 print_generic_expr (dump_file, info.func, dump_flags);
3468 fprintf (dump_file,
3469 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3470 ", fmtstr = \"%s\"\n",
3471 info.objsize, info.fmtstr);
3474 /* Reset the minimum and maximum byte counters. */
3475 res->range.min = res->range.max = 0;
3477 /* No directive has been seen yet so the length of output is bounded
3478 by the known range [0, 0] (with no conversion resulting in a failure
3479 or producing more than 4K bytes) until determined otherwise. */
3480 res->knownrange = true;
3481 res->floating = false;
3482 res->warned = false;
3484 /* 1-based directive counter. */
3485 unsigned dirno = 1;
3487 /* The variadic argument counter. */
3488 unsigned argno = info.argidx;
3490 for (const char *pf = info.fmtstr; ; ++dirno)
3492 directive dir = directive ();
3493 dir.dirno = dirno;
3495 size_t n = parse_directive (info, dir, res, pf, &argno,
3496 evrp_range_analyzer.get_vr_values ());
3498 /* Return failure if the format function fails. */
3499 if (!format_directive (info, res, dir,
3500 evrp_range_analyzer.get_vr_values ()))
3501 return false;
3503 /* Return success the directive is zero bytes long and it's
3504 the last think in the format string (i.e., it's the terminating
3505 nul, which isn't really a directive but handling it as one makes
3506 things simpler). */
3507 if (!n)
3508 return *pf == '\0';
3510 pf += n;
3513 /* The complete format string was processed (with or without warnings). */
3514 return true;
3517 /* Return the size of the object referenced by the expression DEST if
3518 available, or -1 otherwise. */
3520 static unsigned HOST_WIDE_INT
3521 get_destination_size (tree dest)
3523 /* When there is no destination return -1. */
3524 if (!dest)
3525 return HOST_WIDE_INT_M1U;
3527 /* Initialize object size info before trying to compute it. */
3528 init_object_sizes ();
3530 /* Use __builtin_object_size to determine the size of the destination
3531 object. When optimizing, determine the smallest object (such as
3532 a member array as opposed to the whole enclosing object), otherwise
3533 use type-zero object size to determine the size of the enclosing
3534 object (the function fails without optimization in this type). */
3535 int ost = optimize > 0;
3536 unsigned HOST_WIDE_INT size;
3537 if (compute_builtin_object_size (dest, ost, &size))
3538 return size;
3540 return HOST_WIDE_INT_M1U;
3543 /* Return true if the call described by INFO with result RES safe to
3544 optimize (i.e., no undefined behavior), and set RETVAL to the range
3545 of its return values. */
3547 static bool
3548 is_call_safe (const sprintf_dom_walker::call_info &info,
3549 const format_result &res, bool under4k,
3550 unsigned HOST_WIDE_INT retval[2])
3552 if (under4k && !res.posunder4k)
3553 return false;
3555 /* The minimum return value. */
3556 retval[0] = res.range.min;
3558 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3559 but in cases involving multibyte characters could be as large as
3560 RES.RANGE.UNLIKELY. */
3561 retval[1]
3562 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3564 /* Adjust the number of bytes which includes the terminating nul
3565 to reflect the return value of the function which does not.
3566 Because the valid range of the function is [INT_MIN, INT_MAX],
3567 a valid range before the adjustment below is [0, INT_MAX + 1]
3568 (the functions only return negative values on error or undefined
3569 behavior). */
3570 if (retval[0] <= target_int_max () + 1)
3571 --retval[0];
3572 if (retval[1] <= target_int_max () + 1)
3573 --retval[1];
3575 /* Avoid the return value optimization when the behavior of the call
3576 is undefined either because any directive may have produced 4K or
3577 more of output, or the return value exceeds INT_MAX, or because
3578 the output overflows the destination object (but leave it enabled
3579 when the function is bounded because then the behavior is well-
3580 defined). */
3581 if (retval[0] == retval[1]
3582 && (info.bounded || retval[0] < info.objsize)
3583 && retval[0] <= target_int_max ())
3584 return true;
3586 if ((info.bounded || retval[1] < info.objsize)
3587 && (retval[0] < target_int_max ()
3588 && retval[1] < target_int_max ()))
3589 return true;
3591 if (!under4k && (info.bounded || retval[0] < info.objsize))
3592 return true;
3594 return false;
3597 /* Given a suitable result RES of a call to a formatted output function
3598 described by INFO, substitute the result for the return value of
3599 the call. The result is suitable if the number of bytes it represents
3600 is known and exact. A result that isn't suitable for substitution may
3601 have its range set to the range of return values, if that is known.
3602 Return true if the call is removed and gsi_next should not be performed
3603 in the caller. */
3605 static bool
3606 try_substitute_return_value (gimple_stmt_iterator *gsi,
3607 const sprintf_dom_walker::call_info &info,
3608 const format_result &res)
3610 tree lhs = gimple_get_lhs (info.callstmt);
3612 /* Set to true when the entire call has been removed. */
3613 bool removed = false;
3615 /* The minimum and maximum return value. */
3616 unsigned HOST_WIDE_INT retval[2];
3617 bool safe = is_call_safe (info, res, true, retval);
3619 if (safe
3620 && retval[0] == retval[1]
3621 /* Not prepared to handle possibly throwing calls here; they shouldn't
3622 appear in non-artificial testcases, except when the __*_chk routines
3623 are badly declared. */
3624 && !stmt_ends_bb_p (info.callstmt))
3626 tree cst = build_int_cst (integer_type_node, retval[0]);
3628 if (lhs == NULL_TREE
3629 && info.nowrite)
3631 /* Remove the call to the bounded function with a zero size
3632 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3633 unlink_stmt_vdef (info.callstmt);
3634 gsi_remove (gsi, true);
3635 removed = true;
3637 else if (info.nowrite)
3639 /* Replace the call to the bounded function with a zero size
3640 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3641 of the function. */
3642 if (!update_call_from_tree (gsi, cst))
3643 gimplify_and_update_call_from_tree (gsi, cst);
3644 gimple *callstmt = gsi_stmt (*gsi);
3645 update_stmt (callstmt);
3647 else if (lhs)
3649 /* Replace the left-hand side of the call with the constant
3650 result of the formatted function. */
3651 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3652 gimple *g = gimple_build_assign (lhs, cst);
3653 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3654 update_stmt (info.callstmt);
3657 if (dump_file)
3659 if (removed)
3660 fprintf (dump_file, " Removing call statement.");
3661 else
3663 fprintf (dump_file, " Substituting ");
3664 print_generic_expr (dump_file, cst, dump_flags);
3665 fprintf (dump_file, " for %s.\n",
3666 info.nowrite ? "statement" : "return value");
3670 else if (lhs)
3672 bool setrange = false;
3674 if (safe
3675 && (info.bounded || retval[1] < info.objsize)
3676 && (retval[0] < target_int_max ()
3677 && retval[1] < target_int_max ()))
3679 /* If the result is in a valid range bounded by the size of
3680 the destination set it so that it can be used for subsequent
3681 optimizations. */
3682 int prec = TYPE_PRECISION (integer_type_node);
3684 wide_int min = wi::shwi (retval[0], prec);
3685 wide_int max = wi::shwi (retval[1], prec);
3686 set_range_info (lhs, VR_RANGE, min, max);
3688 setrange = true;
3691 if (dump_file)
3693 const char *inbounds
3694 = (retval[0] < info.objsize
3695 ? (retval[1] < info.objsize
3696 ? "in" : "potentially out-of")
3697 : "out-of");
3699 const char *what = setrange ? "Setting" : "Discarding";
3700 if (retval[0] != retval[1])
3701 fprintf (dump_file,
3702 " %s %s-bounds return value range ["
3703 HOST_WIDE_INT_PRINT_UNSIGNED ", "
3704 HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
3705 what, inbounds, retval[0], retval[1]);
3706 else
3707 fprintf (dump_file, " %s %s-bounds return value "
3708 HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
3709 what, inbounds, retval[0]);
3713 if (dump_file)
3714 fputc ('\n', dump_file);
3716 return removed;
3719 /* Try to simplify a s{,n}printf call described by INFO with result
3720 RES by replacing it with a simpler and presumably more efficient
3721 call (such as strcpy). */
3723 static bool
3724 try_simplify_call (gimple_stmt_iterator *gsi,
3725 const sprintf_dom_walker::call_info &info,
3726 const format_result &res)
3728 unsigned HOST_WIDE_INT dummy[2];
3729 if (!is_call_safe (info, res, info.retval_used (), dummy))
3730 return false;
3732 switch (info.fncode)
3734 case BUILT_IN_SNPRINTF:
3735 return gimple_fold_builtin_snprintf (gsi);
3737 case BUILT_IN_SPRINTF:
3738 return gimple_fold_builtin_sprintf (gsi);
3740 default:
3744 return false;
3747 /* Return the zero-based index of the format string argument of a printf
3748 like function and set *IDX_ARGS to the first format argument. When
3749 no such index exists return UINT_MAX. */
3751 static unsigned
3752 get_user_idx_format (tree fndecl, unsigned *idx_args)
3754 tree attrs = lookup_attribute ("format", DECL_ATTRIBUTES (fndecl));
3755 if (!attrs)
3756 attrs = lookup_attribute ("format", TYPE_ATTRIBUTES (TREE_TYPE (fndecl)));
3758 if (!attrs)
3759 return UINT_MAX;
3761 attrs = TREE_VALUE (attrs);
3763 tree archetype = TREE_VALUE (attrs);
3764 if (strcmp ("printf", IDENTIFIER_POINTER (archetype)))
3765 return UINT_MAX;
3767 attrs = TREE_CHAIN (attrs);
3768 tree fmtarg = TREE_VALUE (attrs);
3770 attrs = TREE_CHAIN (attrs);
3771 tree elliparg = TREE_VALUE (attrs);
3773 /* Attribute argument indices are 1-based but we use zero-based. */
3774 *idx_args = tree_to_uhwi (elliparg) - 1;
3775 return tree_to_uhwi (fmtarg) - 1;
3778 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3779 functions and if so, handle it. Return true if the call is removed
3780 and gsi_next should not be performed in the caller. */
3782 bool
3783 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3785 call_info info = call_info ();
3787 info.callstmt = gsi_stmt (*gsi);
3788 info.func = gimple_call_fndecl (info.callstmt);
3789 if (!info.func)
3790 return false;
3792 info.fncode = DECL_FUNCTION_CODE (info.func);
3794 /* Format string argument number (valid for all functions). */
3795 unsigned idx_format = UINT_MAX;
3796 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3798 unsigned idx_args;
3799 idx_format = get_user_idx_format (info.func, &idx_args);
3800 if (idx_format == UINT_MAX)
3801 return false;
3802 info.argidx = idx_args;
3805 /* The size of the destination as in snprintf(dest, size, ...). */
3806 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3808 /* The size of the destination determined by __builtin_object_size. */
3809 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3811 /* Zero-based buffer size argument number (snprintf and vsnprintf). */
3812 unsigned idx_dstsize = UINT_MAX;
3814 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3815 unsigned idx_objsize = UINT_MAX;
3817 /* Destinaton argument number (valid for sprintf functions only). */
3818 unsigned idx_dstptr = 0;
3820 switch (info.fncode)
3822 case BUILT_IN_NONE:
3823 // User-defined function with attribute format (printf).
3824 idx_dstptr = -1;
3825 break;
3827 case BUILT_IN_FPRINTF:
3828 // Signature:
3829 // __builtin_fprintf (FILE*, format, ...)
3830 idx_format = 1;
3831 info.argidx = 2;
3832 idx_dstptr = -1;
3833 break;
3835 case BUILT_IN_FPRINTF_CHK:
3836 // Signature:
3837 // __builtin_fprintf_chk (FILE*, ost, format, ...)
3838 idx_format = 2;
3839 info.argidx = 3;
3840 idx_dstptr = -1;
3841 break;
3843 case BUILT_IN_FPRINTF_UNLOCKED:
3844 // Signature:
3845 // __builtin_fprintf_unnlocked (FILE*, format, ...)
3846 idx_format = 1;
3847 info.argidx = 2;
3848 idx_dstptr = -1;
3849 break;
3851 case BUILT_IN_PRINTF:
3852 // Signature:
3853 // __builtin_printf (format, ...)
3854 idx_format = 0;
3855 info.argidx = 1;
3856 idx_dstptr = -1;
3857 break;
3859 case BUILT_IN_PRINTF_CHK:
3860 // Signature:
3861 // __builtin_printf_chk (it, format, ...)
3862 idx_format = 1;
3863 info.argidx = 2;
3864 idx_dstptr = -1;
3865 break;
3867 case BUILT_IN_PRINTF_UNLOCKED:
3868 // Signature:
3869 // __builtin_printf (format, ...)
3870 idx_format = 0;
3871 info.argidx = 1;
3872 idx_dstptr = -1;
3873 break;
3875 case BUILT_IN_SPRINTF:
3876 // Signature:
3877 // __builtin_sprintf (dst, format, ...)
3878 idx_format = 1;
3879 info.argidx = 2;
3880 break;
3882 case BUILT_IN_SPRINTF_CHK:
3883 // Signature:
3884 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3885 idx_objsize = 2;
3886 idx_format = 3;
3887 info.argidx = 4;
3888 break;
3890 case BUILT_IN_SNPRINTF:
3891 // Signature:
3892 // __builtin_snprintf (dst, size, format, ...)
3893 idx_dstsize = 1;
3894 idx_format = 2;
3895 info.argidx = 3;
3896 info.bounded = true;
3897 break;
3899 case BUILT_IN_SNPRINTF_CHK:
3900 // Signature:
3901 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3902 idx_dstsize = 1;
3903 idx_objsize = 3;
3904 idx_format = 4;
3905 info.argidx = 5;
3906 info.bounded = true;
3907 break;
3909 case BUILT_IN_VFPRINTF:
3910 // Signature:
3911 // __builtin_vprintf (FILE*, format, va_list)
3912 idx_format = 1;
3913 info.argidx = -1;
3914 idx_dstptr = -1;
3915 break;
3917 case BUILT_IN_VFPRINTF_CHK:
3918 // Signature:
3919 // __builtin___vfprintf_chk (FILE*, ost, format, va_list)
3920 idx_format = 2;
3921 info.argidx = -1;
3922 idx_dstptr = -1;
3923 break;
3925 case BUILT_IN_VPRINTF:
3926 // Signature:
3927 // __builtin_vprintf (format, va_list)
3928 idx_format = 0;
3929 info.argidx = -1;
3930 idx_dstptr = -1;
3931 break;
3933 case BUILT_IN_VPRINTF_CHK:
3934 // Signature:
3935 // __builtin___vprintf_chk (ost, format, va_list)
3936 idx_format = 1;
3937 info.argidx = -1;
3938 idx_dstptr = -1;
3939 break;
3941 case BUILT_IN_VSNPRINTF:
3942 // Signature:
3943 // __builtin_vsprintf (dst, size, format, va)
3944 idx_dstsize = 1;
3945 idx_format = 2;
3946 info.argidx = -1;
3947 info.bounded = true;
3948 break;
3950 case BUILT_IN_VSNPRINTF_CHK:
3951 // Signature:
3952 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3953 idx_dstsize = 1;
3954 idx_objsize = 3;
3955 idx_format = 4;
3956 info.argidx = -1;
3957 info.bounded = true;
3958 break;
3960 case BUILT_IN_VSPRINTF:
3961 // Signature:
3962 // __builtin_vsprintf (dst, format, va)
3963 idx_format = 1;
3964 info.argidx = -1;
3965 break;
3967 case BUILT_IN_VSPRINTF_CHK:
3968 // Signature:
3969 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3970 idx_format = 3;
3971 idx_objsize = 2;
3972 info.argidx = -1;
3973 break;
3975 default:
3976 return false;
3979 /* Set the global warning level for this function. */
3980 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3982 /* For all string functions the first argument is a pointer to
3983 the destination. */
3984 tree dstptr = (idx_dstptr < gimple_call_num_args (info.callstmt)
3985 ? gimple_call_arg (info.callstmt, 0) : NULL_TREE);
3987 info.format = gimple_call_arg (info.callstmt, idx_format);
3989 /* True when the destination size is constant as opposed to the lower
3990 or upper bound of a range. */
3991 bool dstsize_cst_p = true;
3992 bool posunder4k = true;
3994 if (idx_dstsize == UINT_MAX)
3996 /* For non-bounded functions like sprintf, determine the size
3997 of the destination from the object or pointer passed to it
3998 as the first argument. */
3999 dstsize = get_destination_size (dstptr);
4001 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
4003 /* For bounded functions try to get the size argument. */
4005 if (TREE_CODE (size) == INTEGER_CST)
4007 dstsize = tree_to_uhwi (size);
4008 /* No object can be larger than SIZE_MAX bytes (half the address
4009 space) on the target.
4010 The functions are defined only for output of at most INT_MAX
4011 bytes. Specifying a bound in excess of that limit effectively
4012 defeats the bounds checking (and on some implementations such
4013 as Solaris cause the function to fail with EINVAL). */
4014 if (dstsize > target_size_max () / 2)
4016 /* Avoid warning if -Wstringop-overflow is specified since
4017 it also warns for the same thing though only for the
4018 checking built-ins. */
4019 if ((idx_objsize == UINT_MAX
4020 || !warn_stringop_overflow))
4021 warning_at (gimple_location (info.callstmt), info.warnopt (),
4022 "specified bound %wu exceeds maximum object size "
4023 "%wu",
4024 dstsize, target_size_max () / 2);
4025 /* POSIX requires snprintf to fail if DSTSIZE is greater
4026 than INT_MAX. Even though not all POSIX implementations
4027 conform to the requirement, avoid folding in this case. */
4028 posunder4k = false;
4030 else if (dstsize > target_int_max ())
4032 warning_at (gimple_location (info.callstmt), info.warnopt (),
4033 "specified bound %wu exceeds %<INT_MAX%>",
4034 dstsize);
4035 /* POSIX requires snprintf to fail if DSTSIZE is greater
4036 than INT_MAX. Avoid folding in that case. */
4037 posunder4k = false;
4040 else if (TREE_CODE (size) == SSA_NAME)
4042 /* Try to determine the range of values of the argument
4043 and use the greater of the two at level 1 and the smaller
4044 of them at level 2. */
4045 value_range *vr = evrp_range_analyzer.get_value_range (size);
4046 if (range_int_cst_p (vr))
4048 unsigned HOST_WIDE_INT minsize = TREE_INT_CST_LOW (vr->min ());
4049 unsigned HOST_WIDE_INT maxsize = TREE_INT_CST_LOW (vr->max ());
4050 dstsize = warn_level < 2 ? maxsize : minsize;
4052 if (minsize > target_int_max ())
4053 warning_at (gimple_location (info.callstmt), info.warnopt (),
4054 "specified bound range [%wu, %wu] exceeds "
4055 "%<INT_MAX%>",
4056 minsize, maxsize);
4058 /* POSIX requires snprintf to fail if DSTSIZE is greater
4059 than INT_MAX. Avoid folding if that's possible. */
4060 if (maxsize > target_int_max ())
4061 posunder4k = false;
4063 else if (vr->varying_p ())
4065 /* POSIX requires snprintf to fail if DSTSIZE is greater
4066 than INT_MAX. Since SIZE's range is unknown, avoid
4067 folding. */
4068 posunder4k = false;
4071 /* The destination size is not constant. If the function is
4072 bounded (e.g., snprintf) a lower bound of zero doesn't
4073 necessarily imply it can be eliminated. */
4074 dstsize_cst_p = false;
4078 if (idx_objsize != UINT_MAX)
4079 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
4080 if (tree_fits_uhwi_p (size))
4081 objsize = tree_to_uhwi (size);
4083 if (info.bounded && !dstsize)
4085 /* As a special case, when the explicitly specified destination
4086 size argument (to a bounded function like snprintf) is zero
4087 it is a request to determine the number of bytes on output
4088 without actually producing any. Pretend the size is
4089 unlimited in this case. */
4090 info.objsize = HOST_WIDE_INT_MAX;
4091 info.nowrite = dstsize_cst_p;
4093 else
4095 /* For calls to non-bounded functions or to those of bounded
4096 functions with a non-zero size, warn if the destination
4097 pointer is null. */
4098 if (dstptr && integer_zerop (dstptr))
4100 /* This is diagnosed with -Wformat only when the null is a constant
4101 pointer. The warning here diagnoses instances where the pointer
4102 is not constant. */
4103 location_t loc = gimple_location (info.callstmt);
4104 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
4105 info.warnopt (), "%Gnull destination pointer",
4106 info.callstmt);
4107 return false;
4110 /* Set the object size to the smaller of the two arguments
4111 of both have been specified and they're not equal. */
4112 info.objsize = dstsize < objsize ? dstsize : objsize;
4114 if (info.bounded
4115 && dstsize < target_size_max () / 2 && objsize < dstsize
4116 /* Avoid warning if -Wstringop-overflow is specified since
4117 it also warns for the same thing though only for the
4118 checking built-ins. */
4119 && (idx_objsize == UINT_MAX
4120 || !warn_stringop_overflow))
4122 warning_at (gimple_location (info.callstmt), info.warnopt (),
4123 "specified bound %wu exceeds the size %wu "
4124 "of the destination object", dstsize, objsize);
4128 /* Determine if the format argument may be null and warn if not
4129 and if the argument is null. */
4130 if (integer_zerop (info.format)
4131 && gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
4133 location_t loc = gimple_location (info.callstmt);
4134 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
4135 info.warnopt (), "%Gnull format string",
4136 info.callstmt);
4137 return false;
4140 info.fmtstr = get_format_string (info.format, &info.fmtloc);
4141 if (!info.fmtstr)
4142 return false;
4144 /* The result is the number of bytes output by the formatted function,
4145 including the terminating NUL. */
4146 format_result res = format_result ();
4148 /* I/O functions with no destination argument (i.e., all forms of fprintf
4149 and printf) may fail under any conditions. Others (i.e., all forms of
4150 sprintf) may only fail under specific conditions determined for each
4151 directive. Clear POSUNDER4K for the former set of functions and set
4152 it to true for the latter (it can only be cleared later, but it is
4153 never set to true again). */
4154 res.posunder4k = posunder4k && dstptr;
4156 bool success = compute_format_length (info, &res);
4157 if (res.warned)
4158 gimple_set_no_warning (info.callstmt, true);
4160 /* When optimizing and the printf return value optimization is enabled,
4161 attempt to substitute the computed result for the return value of
4162 the call. Avoid this optimization when -frounding-math is in effect
4163 and the format string contains a floating point directive. */
4164 bool call_removed = false;
4165 if (success && optimize > 0)
4167 /* Save a copy of the iterator pointing at the call. The iterator
4168 may change to point past the call in try_substitute_return_value
4169 but the original value is needed in try_simplify_call. */
4170 gimple_stmt_iterator gsi_call = *gsi;
4172 if (flag_printf_return_value
4173 && (!flag_rounding_math || !res.floating))
4174 call_removed = try_substitute_return_value (gsi, info, res);
4176 if (!call_removed)
4177 try_simplify_call (&gsi_call, info, res);
4180 return call_removed;
4183 edge
4184 sprintf_dom_walker::before_dom_children (basic_block bb)
4186 evrp_range_analyzer.enter (bb);
4187 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
4189 /* Iterate over statements, looking for function calls. */
4190 gimple *stmt = gsi_stmt (si);
4192 /* First record ranges generated by this statement. */
4193 evrp_range_analyzer.record_ranges_from_stmt (stmt, false);
4195 if (is_gimple_call (stmt) && handle_gimple_call (&si))
4196 /* If handle_gimple_call returns true, the iterator is
4197 already pointing to the next statement. */
4198 continue;
4200 gsi_next (&si);
4202 return NULL;
4205 void
4206 sprintf_dom_walker::after_dom_children (basic_block bb)
4208 evrp_range_analyzer.leave (bb);
4211 /* Execute the pass for function FUN. */
4213 unsigned int
4214 pass_sprintf_length::execute (function *fun)
4216 init_target_to_host_charmap ();
4218 calculate_dominance_info (CDI_DOMINATORS);
4220 sprintf_dom_walker sprintf_dom_walker;
4221 sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
4223 /* Clean up object size info. */
4224 fini_object_sizes ();
4225 return 0;
4228 } /* Unnamed namespace. */
4230 /* Return a pointer to a pass object newly constructed from the context
4231 CTXT. */
4233 gimple_opt_pass *
4234 make_pass_sprintf_length (gcc::context *ctxt)
4236 return new pass_sprintf_length (ctxt);