Avoid is_constant calls in vectorizable_bswap
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob91e21af209370e36009016c8e5970eac48c3fa80
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 "builtins.h"
72 #include "stor-layout.h"
74 #include "realmpfr.h"
75 #include "target.h"
77 #include "cpplib.h"
78 #include "input.h"
79 #include "toplev.h"
80 #include "substring-locations.h"
81 #include "diagnostic.h"
82 #include "domwalk.h"
83 #include "alloc-pool.h"
84 #include "vr-values.h"
85 #include "gimple-ssa-evrp-analyze.h"
87 /* The likely worst case value of MB_LEN_MAX for the target, large enough
88 for UTF-8. Ideally, this would be obtained by a target hook if it were
89 to be used for optimization but it's good enough as is for warnings. */
90 #define target_mb_len_max() 6
92 /* The maximum number of bytes a single non-string directive can result
93 in. This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
94 LDBL_MAX_10_EXP of 4932. */
95 #define IEEE_MAX_10_EXP 4932
96 #define target_dir_max() (target_int_max () + IEEE_MAX_10_EXP + 2)
98 namespace {
100 const pass_data pass_data_sprintf_length = {
101 GIMPLE_PASS, // pass type
102 "printf-return-value", // pass name
103 OPTGROUP_NONE, // optinfo_flags
104 TV_NONE, // tv_id
105 PROP_cfg, // properties_required
106 0, // properties_provided
107 0, // properties_destroyed
108 0, // properties_start
109 0, // properties_finish
112 /* Set to the warning level for the current function which is equal
113 either to warn_format_trunc for bounded functions or to
114 warn_format_overflow otherwise. */
116 static int warn_level;
118 struct format_result;
120 class sprintf_dom_walker : public dom_walker
122 public:
123 sprintf_dom_walker () : dom_walker (CDI_DOMINATORS) {}
124 ~sprintf_dom_walker () {}
126 edge before_dom_children (basic_block) FINAL OVERRIDE;
127 void after_dom_children (basic_block) FINAL OVERRIDE;
128 bool handle_gimple_call (gimple_stmt_iterator *);
130 struct call_info;
131 bool compute_format_length (call_info &, format_result *);
132 class evrp_range_analyzer evrp_range_analyzer;
135 class pass_sprintf_length : public gimple_opt_pass
137 bool fold_return_value;
139 public:
140 pass_sprintf_length (gcc::context *ctxt)
141 : gimple_opt_pass (pass_data_sprintf_length, ctxt),
142 fold_return_value (false)
145 opt_pass * clone () { return new pass_sprintf_length (m_ctxt); }
147 virtual bool gate (function *);
149 virtual unsigned int execute (function *);
151 void set_pass_param (unsigned int n, bool param)
153 gcc_assert (n == 0);
154 fold_return_value = param;
159 bool
160 pass_sprintf_length::gate (function *)
162 /* Run the pass iff -Warn-format-overflow or -Warn-format-truncation
163 is specified and either not optimizing and the pass is being invoked
164 early, or when optimizing and the pass is being invoked during
165 optimization (i.e., "late"). */
166 return ((warn_format_overflow > 0
167 || warn_format_trunc > 0
168 || flag_printf_return_value)
169 && (optimize > 0) == fold_return_value);
172 /* The minimum, maximum, likely, and unlikely maximum number of bytes
173 of output either a formatting function or an individual directive
174 can result in. */
176 struct result_range
178 /* The absolute minimum number of bytes. The result of a successful
179 conversion is guaranteed to be no less than this. (An erroneous
180 conversion can be indicated by MIN > HOST_WIDE_INT_MAX.) */
181 unsigned HOST_WIDE_INT min;
182 /* The likely maximum result that is used in diagnostics. In most
183 cases MAX is the same as the worst case UNLIKELY result. */
184 unsigned HOST_WIDE_INT max;
185 /* The likely result used to trigger diagnostics. For conversions
186 that result in a range of bytes [MIN, MAX], LIKELY is somewhere
187 in that range. */
188 unsigned HOST_WIDE_INT likely;
189 /* In rare cases (e.g., for nultibyte characters) UNLIKELY gives
190 the worst cases maximum result of a directive. In most cases
191 UNLIKELY == MAX. UNLIKELY is used to control the return value
192 optimization but not in diagnostics. */
193 unsigned HOST_WIDE_INT unlikely;
196 /* The result of a call to a formatted function. */
198 struct format_result
200 /* Range of characters written by the formatted function.
201 Setting the minimum to HOST_WIDE_INT_MAX disables all
202 length tracking for the remainder of the format string. */
203 result_range range;
205 /* True when the range above is obtained from known values of
206 directive arguments, or bounds on the amount of output such
207 as width and precision, and not the result of heuristics that
208 depend on warning levels. It's used to issue stricter diagnostics
209 in cases where strings of unknown lengths are bounded by the arrays
210 they are determined to refer to. KNOWNRANGE must not be used for
211 the return value optimization. */
212 bool knownrange;
214 /* True if no individual directive could fail or result in more than
215 4095 bytes of output (the total NUMBER_CHARS_{MIN,MAX} might be
216 greater). Implementations are not required to handle directives
217 that produce more than 4K bytes (leading to undefined behavior)
218 and so when one is found it disables the return value optimization.
219 Similarly, directives that can fail (such as wide character
220 directives) disable the optimization. */
221 bool posunder4k;
223 /* True when a floating point directive has been seen in the format
224 string. */
225 bool floating;
227 /* True when an intermediate result has caused a warning. Used to
228 avoid issuing duplicate warnings while finishing the processing
229 of a call. WARNED also disables the return value optimization. */
230 bool warned;
232 /* Preincrement the number of output characters by 1. */
233 format_result& operator++ ()
235 return *this += 1;
238 /* Postincrement the number of output characters by 1. */
239 format_result operator++ (int)
241 format_result prev (*this);
242 *this += 1;
243 return prev;
246 /* Increment the number of output characters by N. */
247 format_result& operator+= (unsigned HOST_WIDE_INT);
250 format_result&
251 format_result::operator+= (unsigned HOST_WIDE_INT n)
253 gcc_assert (n < HOST_WIDE_INT_MAX);
255 if (range.min < HOST_WIDE_INT_MAX)
256 range.min += n;
258 if (range.max < HOST_WIDE_INT_MAX)
259 range.max += n;
261 if (range.likely < HOST_WIDE_INT_MAX)
262 range.likely += n;
264 if (range.unlikely < HOST_WIDE_INT_MAX)
265 range.unlikely += n;
267 return *this;
270 /* Return the value of INT_MIN for the target. */
272 static inline HOST_WIDE_INT
273 target_int_min ()
275 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
278 /* Return the value of INT_MAX for the target. */
280 static inline unsigned HOST_WIDE_INT
281 target_int_max ()
283 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
286 /* Return the value of SIZE_MAX for the target. */
288 static inline unsigned HOST_WIDE_INT
289 target_size_max ()
291 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
294 /* A straightforward mapping from the execution character set to the host
295 character set indexed by execution character. */
297 static char target_to_host_charmap[256];
299 /* Initialize a mapping from the execution character set to the host
300 character set. */
302 static bool
303 init_target_to_host_charmap ()
305 /* If the percent sign is non-zero the mapping has already been
306 initialized. */
307 if (target_to_host_charmap['%'])
308 return true;
310 /* Initialize the target_percent character (done elsewhere). */
311 if (!init_target_chars ())
312 return false;
314 /* The subset of the source character set used by printf conversion
315 specifications (strictly speaking, not all letters are used but
316 they are included here for the sake of simplicity). The dollar
317 sign must be included even though it's not in the basic source
318 character set. */
319 const char srcset[] = " 0123456789!\"#%&'()*+,-./:;<=>?[\\]^_{|}~$"
320 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
322 /* Set the mapping for all characters to some ordinary value (i,e.,
323 not none used in printf conversion specifications) and overwrite
324 those that are used by conversion specifications with their
325 corresponding values. */
326 memset (target_to_host_charmap + 1, '?', sizeof target_to_host_charmap - 1);
328 /* Are the two sets of characters the same? */
329 bool all_same_p = true;
331 for (const char *pc = srcset; *pc; ++pc)
333 /* Slice off the high end bits in case target characters are
334 signed. All values are expected to be non-nul, otherwise
335 there's a problem. */
336 if (unsigned char tc = lang_hooks.to_target_charset (*pc))
338 target_to_host_charmap[tc] = *pc;
339 if (tc != *pc)
340 all_same_p = false;
342 else
343 return false;
347 /* Set the first element to a non-zero value if the mapping
348 is 1-to-1, otherwise leave it clear (NUL is assumed to be
349 the same in both character sets). */
350 target_to_host_charmap[0] = all_same_p;
352 return true;
355 /* Return the host source character corresponding to the character
356 CH in the execution character set if one exists, or some innocuous
357 (non-special, non-nul) source character otherwise. */
359 static inline unsigned char
360 target_to_host (unsigned char ch)
362 return target_to_host_charmap[ch];
365 /* Convert an initial substring of the string TARGSTR consisting of
366 characters in the execution character set into a string in the
367 source character set on the host and store up to HOSTSZ characters
368 in the buffer pointed to by HOSTR. Return HOSTR. */
370 static const char*
371 target_to_host (char *hostr, size_t hostsz, const char *targstr)
373 /* Make sure the buffer is reasonably big. */
374 gcc_assert (hostsz > 4);
376 /* The interesting subset of source and execution characters are
377 the same so no conversion is necessary. However, truncate
378 overlong strings just like the translated strings are. */
379 if (target_to_host_charmap['\0'] == 1)
381 strncpy (hostr, targstr, hostsz - 4);
382 if (strlen (targstr) >= hostsz)
383 strcpy (hostr + hostsz - 4, "...");
384 return hostr;
387 /* Convert the initial substring of TARGSTR to the corresponding
388 characters in the host set, appending "..." if TARGSTR is too
389 long to fit. Using the static buffer assumes the function is
390 not called in between sequence points (which it isn't). */
391 for (char *ph = hostr; ; ++targstr)
393 *ph++ = target_to_host (*targstr);
394 if (!*targstr)
395 break;
397 if (size_t (ph - hostr) == hostsz - 4)
399 *ph = '\0';
400 strcat (ph, "...");
401 break;
405 return hostr;
408 /* Convert the sequence of decimal digits in the execution character
409 starting at S to a long, just like strtol does. Return the result
410 and set *END to one past the last converted character. On range
411 error set ERANGE to the digit that caused it. */
413 static inline long
414 target_strtol10 (const char **ps, const char **erange)
416 unsigned HOST_WIDE_INT val = 0;
417 for ( ; ; ++*ps)
419 unsigned char c = target_to_host (**ps);
420 if (ISDIGIT (c))
422 c -= '0';
424 /* Check for overflow. */
425 if (val > (LONG_MAX - c) / 10LU)
427 val = LONG_MAX;
428 *erange = *ps;
430 /* Skip the remaining digits. */
432 c = target_to_host (*++*ps);
433 while (ISDIGIT (c));
434 break;
436 else
437 val = val * 10 + c;
439 else
440 break;
443 return val;
446 /* Given FORMAT, set *PLOC to the source location of the format string
447 and return the format string if it is known or null otherwise. */
449 static const char*
450 get_format_string (tree format, location_t *ploc)
452 *ploc = EXPR_LOC_OR_LOC (format, input_location);
454 return c_getstr (format);
457 /* For convenience and brevity, shorter named entrypoints of
458 format_warning_at_substring and format_warning_at_substring_n.
459 These have to be functions with the attribute so that exgettext
460 works properly. */
462 static bool
463 ATTRIBUTE_GCC_DIAG (5, 6)
464 fmtwarn (const substring_loc &fmt_loc, location_t param_loc,
465 const char *corrected_substring, int opt, const char *gmsgid, ...)
467 va_list ap;
468 va_start (ap, gmsgid);
469 bool warned = format_warning_va (fmt_loc, NULL, param_loc, NULL,
470 corrected_substring, opt, gmsgid, &ap);
471 va_end (ap);
473 return warned;
476 static bool
477 ATTRIBUTE_GCC_DIAG (6, 8) ATTRIBUTE_GCC_DIAG (7, 8)
478 fmtwarn_n (const substring_loc &fmt_loc, location_t param_loc,
479 const char *corrected_substring, int opt, unsigned HOST_WIDE_INT n,
480 const char *singular_gmsgid, const char *plural_gmsgid, ...)
482 va_list ap;
483 va_start (ap, plural_gmsgid);
484 bool warned = format_warning_n_va (fmt_loc, NULL, param_loc, NULL,
485 corrected_substring,
486 opt, n, singular_gmsgid, plural_gmsgid,
487 &ap);
488 va_end (ap);
490 return warned;
493 /* Format length modifiers. */
495 enum format_lengths
497 FMT_LEN_none,
498 FMT_LEN_hh, // char argument
499 FMT_LEN_h, // short
500 FMT_LEN_l, // long
501 FMT_LEN_ll, // long long
502 FMT_LEN_L, // long double (and GNU long long)
503 FMT_LEN_z, // size_t
504 FMT_LEN_t, // ptrdiff_t
505 FMT_LEN_j // intmax_t
509 /* Description of the result of conversion either of a single directive
510 or the whole format string. */
512 struct fmtresult
514 /* Construct a FMTRESULT object with all counters initialized
515 to MIN. KNOWNRANGE is set when MIN is valid. */
516 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
517 : argmin (), argmax (),
518 knownrange (min < HOST_WIDE_INT_MAX),
519 mayfail (), nullp ()
521 range.min = min;
522 range.max = min;
523 range.likely = min;
524 range.unlikely = min;
527 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
528 KNOWNRANGE is set when both MIN and MAX are valid. */
529 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
530 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
531 : argmin (), argmax (),
532 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
533 mayfail (), nullp ()
535 range.min = min;
536 range.max = max;
537 range.likely = max < likely ? min : likely;
538 range.unlikely = max;
541 /* Adjust result upward to reflect the RANGE of values the specified
542 width or precision is known to be in. */
543 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
544 tree = NULL_TREE,
545 unsigned = 0, unsigned = 0);
547 /* Return the maximum number of decimal digits a value of TYPE
548 formats as on output. */
549 static unsigned type_max_digits (tree, int);
551 /* The range a directive's argument is in. */
552 tree argmin, argmax;
554 /* The minimum and maximum number of bytes that a directive
555 results in on output for an argument in the range above. */
556 result_range range;
558 /* True when the range above is obtained from a known value of
559 a directive's argument or its bounds and not the result of
560 heuristics that depend on warning levels. */
561 bool knownrange;
563 /* True for a directive that may fail (such as wide character
564 directives). */
565 bool mayfail;
567 /* True when the argument is a null pointer. */
568 bool nullp;
571 /* Adjust result upward to reflect the range ADJUST of values the
572 specified width or precision is known to be in. When non-null,
573 TYPE denotes the type of the directive whose result is being
574 adjusted, BASE gives the base of the directive (octal, decimal,
575 or hex), and ADJ denotes the additional adjustment to the LIKELY
576 counter that may need to be added when ADJUST is a range. */
578 fmtresult&
579 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
580 tree type /* = NULL_TREE */,
581 unsigned base /* = 0 */,
582 unsigned adj /* = 0 */)
584 bool minadjusted = false;
586 /* Adjust the minimum and likely counters. */
587 if (adjust[0] >= 0)
589 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
591 range.min = adjust[0];
592 minadjusted = true;
595 /* Adjust the likely counter. */
596 if (range.likely < range.min)
597 range.likely = range.min;
599 else if (adjust[0] == target_int_min ()
600 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
601 knownrange = false;
603 /* Adjust the maximum counter. */
604 if (adjust[1] > 0)
606 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
608 range.max = adjust[1];
610 /* Set KNOWNRANGE if both the minimum and maximum have been
611 adjusted. Otherwise leave it at what it was before. */
612 knownrange = minadjusted;
616 if (warn_level > 1 && type)
618 /* For large non-constant width or precision whose range spans
619 the maximum number of digits produced by the directive for
620 any argument, set the likely number of bytes to be at most
621 the number digits plus other adjustment determined by the
622 caller (one for sign or two for the hexadecimal "0x"
623 prefix). */
624 unsigned dirdigs = type_max_digits (type, base);
625 if (adjust[0] < dirdigs && dirdigs < adjust[1]
626 && range.likely < dirdigs)
627 range.likely = dirdigs + adj;
629 else if (range.likely < (range.min ? range.min : 1))
631 /* Conservatively, set LIKELY to at least MIN but no less than
632 1 unless MAX is zero. */
633 range.likely = (range.min
634 ? range.min
635 : range.max && (range.max < HOST_WIDE_INT_MAX
636 || warn_level > 1) ? 1 : 0);
639 /* Finally adjust the unlikely counter to be at least as large as
640 the maximum. */
641 if (range.unlikely < range.max)
642 range.unlikely = range.max;
644 return *this;
647 /* Return the maximum number of digits a value of TYPE formats in
648 BASE on output, not counting base prefix . */
650 unsigned
651 fmtresult::type_max_digits (tree type, int base)
653 unsigned prec = TYPE_PRECISION (type);
654 switch (base)
656 case 8:
657 return (prec + 2) / 3;
658 case 10:
659 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
660 of 8, 16, 32, and 64 bits. */
661 return prec * 301 / 1000 + 1;
662 case 16:
663 return prec / 4;
666 gcc_unreachable ();
669 static bool
670 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT,
671 class vr_values *vr_values);
673 /* Description of a format directive. A directive is either a plain
674 string or a conversion specification that starts with '%'. */
676 struct directive
678 /* The 1-based directive number (for debugging). */
679 unsigned dirno;
681 /* The first character of the directive and its length. */
682 const char *beg;
683 size_t len;
685 /* A bitmap of flags, one for each character. */
686 unsigned flags[256 / sizeof (int)];
688 /* The range of values of the specified width, or -1 if not specified. */
689 HOST_WIDE_INT width[2];
690 /* The range of values of the specified precision, or -1 if not
691 specified. */
692 HOST_WIDE_INT prec[2];
694 /* Length modifier. */
695 format_lengths modifier;
697 /* Format specifier character. */
698 char specifier;
700 /* The argument of the directive or null when the directive doesn't
701 take one or when none is available (such as for vararg functions). */
702 tree arg;
704 /* Format conversion function that given a directive and an argument
705 returns the formatting result. */
706 fmtresult (*fmtfunc) (const directive &, tree, vr_values *);
708 /* Return True when a the format flag CHR has been used. */
709 bool get_flag (char chr) const
711 unsigned char c = chr & 0xff;
712 return (flags[c / (CHAR_BIT * sizeof *flags)]
713 & (1U << (c % (CHAR_BIT * sizeof *flags))));
716 /* Make a record of the format flag CHR having been used. */
717 void set_flag (char chr)
719 unsigned char c = chr & 0xff;
720 flags[c / (CHAR_BIT * sizeof *flags)]
721 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
724 /* Reset the format flag CHR. */
725 void clear_flag (char chr)
727 unsigned char c = chr & 0xff;
728 flags[c / (CHAR_BIT * sizeof *flags)]
729 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
732 /* Set both bounds of the width range to VAL. */
733 void set_width (HOST_WIDE_INT val)
735 width[0] = width[1] = val;
738 /* Set the width range according to ARG, with both bounds being
739 no less than 0. For a constant ARG set both bounds to its value
740 or 0, whichever is greater. For a non-constant ARG in some range
741 set width to its range adjusting each bound to -1 if it's less.
742 For an indeterminate ARG set width to [0, INT_MAX]. */
743 void set_width (tree arg, vr_values *vr_values)
745 get_int_range (arg, width, width + 1, true, 0, vr_values);
748 /* Set both bounds of the precision range to VAL. */
749 void set_precision (HOST_WIDE_INT val)
751 prec[0] = prec[1] = val;
754 /* Set the precision range according to ARG, with both bounds being
755 no less than -1. For a constant ARG set both bounds to its value
756 or -1 whichever is greater. For a non-constant ARG in some range
757 set precision to its range adjusting each bound to -1 if it's less.
758 For an indeterminate ARG set precision to [-1, INT_MAX]. */
759 void set_precision (tree arg, vr_values *vr_values)
761 get_int_range (arg, prec, prec + 1, false, -1, vr_values);
764 /* Return true if both width and precision are known to be
765 either constant or in some range, false otherwise. */
766 bool known_width_and_precision () const
768 return ((width[1] < 0
769 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
770 && (prec[1] < 0
771 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
775 /* Return the logarithm of X in BASE. */
777 static int
778 ilog (unsigned HOST_WIDE_INT x, int base)
780 int res = 0;
783 ++res;
784 x /= base;
785 } while (x);
786 return res;
789 /* Return the number of bytes resulting from converting into a string
790 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
791 PLUS indicates whether 1 for a plus sign should be added for positive
792 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
793 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
794 be represented. */
796 static HOST_WIDE_INT
797 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
799 unsigned HOST_WIDE_INT absval;
801 HOST_WIDE_INT res;
803 if (TYPE_UNSIGNED (TREE_TYPE (x)))
805 if (tree_fits_uhwi_p (x))
807 absval = tree_to_uhwi (x);
808 res = plus;
810 else
811 return -1;
813 else
815 if (tree_fits_shwi_p (x))
817 HOST_WIDE_INT i = tree_to_shwi (x);
818 if (HOST_WIDE_INT_MIN == i)
820 /* Avoid undefined behavior due to negating a minimum. */
821 absval = HOST_WIDE_INT_MAX;
822 res = 1;
824 else if (i < 0)
826 absval = -i;
827 res = 1;
829 else
831 absval = i;
832 res = plus;
835 else
836 return -1;
839 int ndigs = ilog (absval, base);
841 res += prec < ndigs ? ndigs : prec;
843 /* Adjust a non-zero value for the base prefix, either hexadecimal,
844 or, unless precision has resulted in a leading zero, also octal. */
845 if (prefix && absval && (base == 16 || prec <= ndigs))
847 if (base == 8)
848 res += 1;
849 else if (base == 16)
850 res += 2;
853 return res;
856 /* Given the formatting result described by RES and NAVAIL, the number
857 of available in the destination, return the range of bytes remaining
858 in the destination. */
860 static inline result_range
861 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
863 result_range range;
865 if (HOST_WIDE_INT_MAX <= navail)
867 range.min = range.max = range.likely = range.unlikely = navail;
868 return range;
871 /* The lower bound of the available range is the available size
872 minus the maximum output size, and the upper bound is the size
873 minus the minimum. */
874 range.max = res.range.min < navail ? navail - res.range.min : 0;
876 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
878 if (res.range.max < HOST_WIDE_INT_MAX)
879 range.min = res.range.max < navail ? navail - res.range.max : 0;
880 else
881 range.min = range.likely;
883 range.unlikely = (res.range.unlikely < navail
884 ? navail - res.range.unlikely : 0);
886 return range;
889 /* Description of a call to a formatted function. */
891 struct sprintf_dom_walker::call_info
893 /* Function call statement. */
894 gimple *callstmt;
896 /* Function called. */
897 tree func;
899 /* Called built-in function code. */
900 built_in_function fncode;
902 /* Format argument and format string extracted from it. */
903 tree format;
904 const char *fmtstr;
906 /* The location of the format argument. */
907 location_t fmtloc;
909 /* The destination object size for __builtin___xxx_chk functions
910 typically determined by __builtin_object_size, or -1 if unknown. */
911 unsigned HOST_WIDE_INT objsize;
913 /* Number of the first variable argument. */
914 unsigned HOST_WIDE_INT argidx;
916 /* True for functions like snprintf that specify the size of
917 the destination, false for others like sprintf that don't. */
918 bool bounded;
920 /* True for bounded functions like snprintf that specify a zero-size
921 buffer as a request to compute the size of output without actually
922 writing any. NOWRITE is cleared in response to the %n directive
923 which has side-effects similar to writing output. */
924 bool nowrite;
926 /* Return true if the called function's return value is used. */
927 bool retval_used () const
929 return gimple_get_lhs (callstmt);
932 /* Return the warning option corresponding to the called function. */
933 int warnopt () const
935 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
939 /* Return the result of formatting a no-op directive (such as '%n'). */
941 static fmtresult
942 format_none (const directive &, tree, vr_values *)
944 fmtresult res (0);
945 return res;
948 /* Return the result of formatting the '%%' directive. */
950 static fmtresult
951 format_percent (const directive &, tree, vr_values *)
953 fmtresult res (1);
954 return res;
958 /* Compute intmax_type_node and uintmax_type_node similarly to how
959 tree.c builds size_type_node. */
961 static void
962 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
964 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
966 *pintmax = integer_type_node;
967 *puintmax = unsigned_type_node;
969 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
971 *pintmax = long_integer_type_node;
972 *puintmax = long_unsigned_type_node;
974 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
976 *pintmax = long_long_integer_type_node;
977 *puintmax = long_long_unsigned_type_node;
979 else
981 for (int i = 0; i < NUM_INT_N_ENTS; i++)
982 if (int_n_enabled_p[i])
984 char name[50];
985 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
987 if (strcmp (name, UINTMAX_TYPE) == 0)
989 *pintmax = int_n_trees[i].signed_type;
990 *puintmax = int_n_trees[i].unsigned_type;
991 return;
994 gcc_unreachable ();
998 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
999 in and that is representable in type int.
1000 Return true when the range is a subrange of that of int.
1001 When ARG is null it is as if it had the full range of int.
1002 When ABSOLUTE is true the range reflects the absolute value of
1003 the argument. When ABSOLUTE is false, negative bounds of
1004 the determined range are replaced with NEGBOUND. */
1006 static bool
1007 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1008 bool absolute, HOST_WIDE_INT negbound,
1009 class vr_values *vr_values)
1011 /* The type of the result. */
1012 const_tree type = integer_type_node;
1014 bool knownrange = false;
1016 if (!arg)
1018 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1019 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1021 else if (TREE_CODE (arg) == INTEGER_CST
1022 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1024 /* For a constant argument return its value adjusted as specified
1025 by NEGATIVE and NEGBOUND and return true to indicate that the
1026 result is known. */
1027 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1028 *pmax = *pmin;
1029 knownrange = true;
1031 else
1033 /* True if the argument's range cannot be determined. */
1034 bool unknown = true;
1036 tree argtype = TREE_TYPE (arg);
1038 /* Ignore invalid arguments with greater precision that that
1039 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1040 They will have been detected and diagnosed by -Wformat and
1041 so it's not important to complicate this code to try to deal
1042 with them again. */
1043 if (TREE_CODE (arg) == SSA_NAME
1044 && INTEGRAL_TYPE_P (argtype)
1045 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1047 /* Try to determine the range of values of the integer argument. */
1048 value_range *vr = vr_values->get_value_range (arg);
1049 if (vr->type == VR_RANGE
1050 && TREE_CODE (vr->min) == INTEGER_CST
1051 && TREE_CODE (vr->max) == INTEGER_CST)
1053 HOST_WIDE_INT type_min
1054 = (TYPE_UNSIGNED (argtype)
1055 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1056 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1058 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1060 *pmin = TREE_INT_CST_LOW (vr->min);
1061 *pmax = TREE_INT_CST_LOW (vr->max);
1063 if (*pmin < *pmax)
1065 /* Return true if the adjusted range is a subrange of
1066 the full range of the argument's type. *PMAX may
1067 be less than *PMIN when the argument is unsigned
1068 and its upper bound is in excess of TYPE_MAX. In
1069 that (invalid) case disregard the range and use that
1070 of the expected type instead. */
1071 knownrange = type_min < *pmin || *pmax < type_max;
1073 unknown = false;
1078 /* Handle an argument with an unknown range as if none had been
1079 provided. */
1080 if (unknown)
1081 return get_int_range (NULL_TREE, pmin, pmax, absolute,
1082 negbound, vr_values);
1085 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1086 if (absolute)
1088 if (*pmin < 0)
1090 if (*pmin == *pmax)
1091 *pmin = *pmax = -*pmin;
1092 else
1094 /* Make sure signed overlow is avoided. */
1095 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1097 HOST_WIDE_INT tmp = -*pmin;
1098 *pmin = 0;
1099 if (*pmax < tmp)
1100 *pmax = tmp;
1104 else if (*pmin < negbound)
1105 *pmin = negbound;
1107 return knownrange;
1110 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1111 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1112 the type of the directive's formal argument it's possible for both
1113 to result in the same number of bytes or a range of bytes that's
1114 less than the number of bytes that would result from formatting
1115 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1116 determined by checking for the actual argument being in the range
1117 of the type of the directive. If it isn't it must be assumed to
1118 take on the full range of the directive's type.
1119 Return true when the range has been adjusted to the full range
1120 of DIRTYPE, and false otherwise. */
1122 static bool
1123 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1125 tree argtype = TREE_TYPE (*argmin);
1126 unsigned argprec = TYPE_PRECISION (argtype);
1127 unsigned dirprec = TYPE_PRECISION (dirtype);
1129 /* If the actual argument and the directive's argument have the same
1130 precision and sign there can be no overflow and so there is nothing
1131 to adjust. */
1132 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1133 return false;
1135 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1136 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1138 if (TREE_CODE (*argmin) == INTEGER_CST
1139 && TREE_CODE (*argmax) == INTEGER_CST
1140 && (dirprec >= argprec
1141 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1142 int_const_binop (MINUS_EXPR,
1143 *argmax,
1144 *argmin),
1145 size_int (dirprec)))))
1147 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1148 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1150 /* If *ARGMIN is still less than *ARGMAX the conversion above
1151 is safe. Otherwise, it has overflowed and would be unsafe. */
1152 if (tree_int_cst_le (*argmin, *argmax))
1153 return false;
1156 *argmin = TYPE_MIN_VALUE (dirtype);
1157 *argmax = TYPE_MAX_VALUE (dirtype);
1158 return true;
1161 /* Return a range representing the minimum and maximum number of bytes
1162 that the format directive DIR will output for any argument given
1163 the WIDTH and PRECISION (extracted from DIR). This function is
1164 used when the directive argument or its value isn't known. */
1166 static fmtresult
1167 format_integer (const directive &dir, tree arg, vr_values *vr_values)
1169 tree intmax_type_node;
1170 tree uintmax_type_node;
1172 /* Base to format the number in. */
1173 int base;
1175 /* True when a conversion is preceded by a prefix indicating the base
1176 of the argument (octal or hexadecimal). */
1177 bool maybebase = dir.get_flag ('#');
1179 /* True when a signed conversion is preceded by a sign or space. */
1180 bool maybesign = false;
1182 /* True for signed conversions (i.e., 'd' and 'i'). */
1183 bool sign = false;
1185 switch (dir.specifier)
1187 case 'd':
1188 case 'i':
1189 /* Space and '+' are only meaningful for signed conversions. */
1190 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1191 sign = true;
1192 base = 10;
1193 break;
1194 case 'u':
1195 base = 10;
1196 break;
1197 case 'o':
1198 base = 8;
1199 break;
1200 case 'X':
1201 case 'x':
1202 base = 16;
1203 break;
1204 default:
1205 gcc_unreachable ();
1208 /* The type of the "formal" argument expected by the directive. */
1209 tree dirtype = NULL_TREE;
1211 /* Determine the expected type of the argument from the length
1212 modifier. */
1213 switch (dir.modifier)
1215 case FMT_LEN_none:
1216 if (dir.specifier == 'p')
1217 dirtype = ptr_type_node;
1218 else
1219 dirtype = sign ? integer_type_node : unsigned_type_node;
1220 break;
1222 case FMT_LEN_h:
1223 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1224 break;
1226 case FMT_LEN_hh:
1227 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1228 break;
1230 case FMT_LEN_l:
1231 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1232 break;
1234 case FMT_LEN_L:
1235 case FMT_LEN_ll:
1236 dirtype = (sign
1237 ? long_long_integer_type_node
1238 : long_long_unsigned_type_node);
1239 break;
1241 case FMT_LEN_z:
1242 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1243 break;
1245 case FMT_LEN_t:
1246 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1247 break;
1249 case FMT_LEN_j:
1250 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1251 dirtype = sign ? intmax_type_node : uintmax_type_node;
1252 break;
1254 default:
1255 return fmtresult ();
1258 /* The type of the argument to the directive, either deduced from
1259 the actual non-constant argument if one is known, or from
1260 the directive itself when none has been provided because it's
1261 a va_list. */
1262 tree argtype = NULL_TREE;
1264 if (!arg)
1266 /* When the argument has not been provided, use the type of
1267 the directive's argument as an approximation. This will
1268 result in false positives for directives like %i with
1269 arguments with smaller precision (such as short or char). */
1270 argtype = dirtype;
1272 else if (TREE_CODE (arg) == INTEGER_CST)
1274 /* When a constant argument has been provided use its value
1275 rather than type to determine the length of the output. */
1276 fmtresult res;
1278 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1280 /* As a special case, a precision of zero with a zero argument
1281 results in zero bytes except in base 8 when the '#' flag is
1282 specified, and for signed conversions in base 8 and 10 when
1283 either the space or '+' flag has been specified and it results
1284 in just one byte (with width having the normal effect). This
1285 must extend to the case of a specified precision with
1286 an unknown value because it can be zero. */
1287 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1288 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1290 res.range.max = 1;
1291 res.range.likely = 1;
1293 else
1295 res.range.max = res.range.min;
1296 res.range.likely = res.range.min;
1299 else
1301 /* Convert the argument to the type of the directive. */
1302 arg = fold_convert (dirtype, arg);
1304 res.range.min = tree_digits (arg, base, dir.prec[0],
1305 maybesign, maybebase);
1306 if (dir.prec[0] == dir.prec[1])
1307 res.range.max = res.range.min;
1308 else
1309 res.range.max = tree_digits (arg, base, dir.prec[1],
1310 maybesign, maybebase);
1311 res.range.likely = res.range.min;
1312 res.knownrange = true;
1315 res.range.unlikely = res.range.max;
1317 /* Bump up the counters if WIDTH is greater than LEN. */
1318 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1319 (sign | maybebase) + (base == 16));
1320 /* Bump up the counters again if PRECision is greater still. */
1321 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1322 (sign | maybebase) + (base == 16));
1324 return res;
1326 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1327 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1328 /* Determine the type of the provided non-constant argument. */
1329 argtype = TREE_TYPE (arg);
1330 else
1331 /* Don't bother with invalid arguments since they likely would
1332 have already been diagnosed, and disable any further checking
1333 of the format string by returning [-1, -1]. */
1334 return fmtresult ();
1336 fmtresult res;
1338 /* Using either the range the non-constant argument is in, or its
1339 type (either "formal" or actual), create a range of values that
1340 constrain the length of output given the warning level. */
1341 tree argmin = NULL_TREE;
1342 tree argmax = NULL_TREE;
1344 if (arg
1345 && TREE_CODE (arg) == SSA_NAME
1346 && INTEGRAL_TYPE_P (argtype))
1348 /* Try to determine the range of values of the integer argument
1349 (range information is not available for pointers). */
1350 value_range *vr = vr_values->get_value_range (arg);
1351 if (vr->type == VR_RANGE
1352 && TREE_CODE (vr->min) == INTEGER_CST
1353 && TREE_CODE (vr->max) == INTEGER_CST)
1355 argmin = vr->min;
1356 argmax = vr->max;
1358 /* Set KNOWNRANGE if the argument is in a known subrange
1359 of the directive's type and neither width nor precision
1360 is unknown. (KNOWNRANGE may be reset below). */
1361 res.knownrange
1362 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1363 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1364 && dir.known_width_and_precision ());
1366 res.argmin = argmin;
1367 res.argmax = argmax;
1369 else if (vr->type == VR_ANTI_RANGE)
1371 /* Handle anti-ranges if/when bug 71690 is resolved. */
1373 else if (vr->type == VR_VARYING
1374 || vr->type == VR_UNDEFINED)
1376 /* The argument here may be the result of promoting the actual
1377 argument to int. Try to determine the type of the actual
1378 argument before promotion and narrow down its range that
1379 way. */
1380 gimple *def = SSA_NAME_DEF_STMT (arg);
1381 if (is_gimple_assign (def))
1383 tree_code code = gimple_assign_rhs_code (def);
1384 if (code == INTEGER_CST)
1386 arg = gimple_assign_rhs1 (def);
1387 return format_integer (dir, arg, vr_values);
1390 if (code == NOP_EXPR)
1392 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1393 if (INTEGRAL_TYPE_P (type)
1394 || TREE_CODE (type) == POINTER_TYPE)
1395 argtype = type;
1401 if (!argmin)
1403 if (TREE_CODE (argtype) == POINTER_TYPE)
1405 argmin = build_int_cst (pointer_sized_int_node, 0);
1406 argmax = build_all_ones_cst (pointer_sized_int_node);
1408 else
1410 argmin = TYPE_MIN_VALUE (argtype);
1411 argmax = TYPE_MAX_VALUE (argtype);
1415 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1416 of the directive. If it has been cleared then since ARGMIN and/or
1417 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1418 ARGMAX in the result to include in diagnostics. */
1419 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1421 res.knownrange = false;
1422 res.argmin = argmin;
1423 res.argmax = argmax;
1426 /* Recursively compute the minimum and maximum from the known range. */
1427 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1429 /* For unsigned conversions/directives or signed when
1430 the minimum is positive, use the minimum and maximum to compute
1431 the shortest and longest output, respectively. */
1432 res.range.min = format_integer (dir, argmin, vr_values).range.min;
1433 res.range.max = format_integer (dir, argmax, vr_values).range.max;
1435 else if (tree_int_cst_sgn (argmax) < 0)
1437 /* For signed conversions/directives if maximum is negative,
1438 use the minimum as the longest output and maximum as the
1439 shortest output. */
1440 res.range.min = format_integer (dir, argmax, vr_values).range.min;
1441 res.range.max = format_integer (dir, argmin, vr_values).range.max;
1443 else
1445 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1446 as the shortest output and for the longest output compute the
1447 length of the output of both minimum and maximum and pick the
1448 longer. */
1449 unsigned HOST_WIDE_INT max1
1450 = format_integer (dir, argmin, vr_values).range.max;
1451 unsigned HOST_WIDE_INT max2
1452 = format_integer (dir, argmax, vr_values).range.max;
1453 res.range.min
1454 = format_integer (dir, integer_zero_node, vr_values).range.min;
1455 res.range.max = MAX (max1, max2);
1458 /* If the range is known, use the maximum as the likely length. */
1459 if (res.knownrange)
1460 res.range.likely = res.range.max;
1461 else
1463 /* Otherwise, use the minimum. Except for the case where for %#x or
1464 %#o the minimum is just for a single value in the range (0) and
1465 for all other values it is something longer, like 0x1 or 01.
1466 Use the length for value 1 in that case instead as the likely
1467 length. */
1468 res.range.likely = res.range.min;
1469 if (maybebase
1470 && base != 10
1471 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1473 if (res.range.min == 1)
1474 res.range.likely += base == 8 ? 1 : 2;
1475 else if (res.range.min == 2
1476 && base == 16
1477 && (dir.width[0] == 2 || dir.prec[0] == 2))
1478 ++res.range.likely;
1482 res.range.unlikely = res.range.max;
1483 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1484 (sign | maybebase) + (base == 16));
1485 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1486 (sign | maybebase) + (base == 16));
1488 return res;
1491 /* Return the number of bytes that a format directive consisting of FLAGS,
1492 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1493 would result for argument X under ideal conditions (i.e., if PREC
1494 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1495 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1496 This function works around those problems. */
1498 static unsigned HOST_WIDE_INT
1499 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1500 char spec, char rndspec)
1502 char fmtstr[40];
1504 HOST_WIDE_INT len = strlen (flags);
1506 fmtstr[0] = '%';
1507 memcpy (fmtstr + 1, flags, len);
1508 memcpy (fmtstr + 1 + len, ".*R", 3);
1509 fmtstr[len + 4] = rndspec;
1510 fmtstr[len + 5] = spec;
1511 fmtstr[len + 6] = '\0';
1513 spec = TOUPPER (spec);
1514 if (spec == 'E' || spec == 'F')
1516 /* For %e, specify the precision explicitly since mpfr_sprintf
1517 does its own thing just to be different (see MPFR bug 21088). */
1518 if (prec < 0)
1519 prec = 6;
1521 else
1523 /* Avoid passing negative precisions with larger magnitude to MPFR
1524 to avoid exposing its bugs. (A negative precision is supposed
1525 to be ignored.) */
1526 if (prec < 0)
1527 prec = -1;
1530 HOST_WIDE_INT p = prec;
1532 if (spec == 'G' && !strchr (flags, '#'))
1534 /* For G/g without the pound flag, precision gives the maximum number
1535 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1536 a 128 bit IEEE extended precision, 4932. Using twice as much here
1537 should be more than sufficient for any real format. */
1538 if ((IEEE_MAX_10_EXP * 2) < prec)
1539 prec = IEEE_MAX_10_EXP * 2;
1540 p = prec;
1542 else
1544 /* Cap precision arbitrarily at 1KB and add the difference
1545 (if any) to the MPFR result. */
1546 if (prec > 1024)
1547 p = 1024;
1550 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1552 /* Handle the unlikely (impossible?) error by returning more than
1553 the maximum dictated by the function's return type. */
1554 if (len < 0)
1555 return target_dir_max () + 1;
1557 /* Adjust the return value by the difference. */
1558 if (p < prec)
1559 len += prec - p;
1561 return len;
1564 /* Return the number of bytes to format using the format specifier
1565 SPEC and the precision PREC the largest value in the real floating
1566 TYPE. */
1568 static unsigned HOST_WIDE_INT
1569 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1571 machine_mode mode = TYPE_MODE (type);
1573 /* IBM Extended mode. */
1574 if (MODE_COMPOSITE_P (mode))
1575 mode = DFmode;
1577 /* Get the real type format desription for the target. */
1578 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1579 REAL_VALUE_TYPE rv;
1581 real_maxval (&rv, 0, mode);
1583 /* Convert the GCC real value representation with the precision
1584 of the real type to the mpfr_t format with the GCC default
1585 round-to-nearest mode. */
1586 mpfr_t x;
1587 mpfr_init2 (x, rfmt->p);
1588 mpfr_from_real (x, &rv, GMP_RNDN);
1590 /* Return a value one greater to account for the leading minus sign. */
1591 unsigned HOST_WIDE_INT r
1592 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1593 mpfr_clear (x);
1594 return r;
1597 /* Return a range representing the minimum and maximum number of bytes
1598 that the directive DIR will output for any argument. PREC gives
1599 the adjusted precision range to account for negative precisions
1600 meaning the default 6. This function is used when the directive
1601 argument or its value isn't known. */
1603 static fmtresult
1604 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1606 tree type;
1608 switch (dir.modifier)
1610 case FMT_LEN_l:
1611 case FMT_LEN_none:
1612 type = double_type_node;
1613 break;
1615 case FMT_LEN_L:
1616 type = long_double_type_node;
1617 break;
1619 case FMT_LEN_ll:
1620 type = long_double_type_node;
1621 break;
1623 default:
1624 return fmtresult ();
1627 /* The minimum and maximum number of bytes produced by the directive. */
1628 fmtresult res;
1630 /* The minimum output as determined by flags. It's always at least 1.
1631 When plus or space are set the output is preceded by either a sign
1632 or a space. */
1633 unsigned flagmin = (1 /* for the first digit */
1634 + (dir.get_flag ('+') | dir.get_flag (' ')));
1636 /* The minimum is 3 for "inf" and "nan" for all specifiers, plus 1
1637 for the plus sign/space with the '+' and ' ' flags, respectively,
1638 unless reduced below. */
1639 res.range.min = 2 + flagmin;
1641 /* When the pound flag is set the decimal point is included in output
1642 regardless of precision. Whether or not a decimal point is included
1643 otherwise depends on the specification and precision. */
1644 bool radix = dir.get_flag ('#');
1646 switch (dir.specifier)
1648 case 'A':
1649 case 'a':
1651 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1652 if (dir.prec[0] <= 0)
1653 minprec = 0;
1654 else if (dir.prec[0] > 0)
1655 minprec = dir.prec[0] + !radix /* decimal point */;
1657 res.range.likely = (2 /* 0x */
1658 + flagmin
1659 + radix
1660 + minprec
1661 + 3 /* p+0 */);
1663 res.range.max = format_floating_max (type, 'a', prec[1]);
1665 /* The unlikely maximum accounts for the longest multibyte
1666 decimal point character. */
1667 res.range.unlikely = res.range.max;
1668 if (dir.prec[1] > 0)
1669 res.range.unlikely += target_mb_len_max () - 1;
1671 break;
1674 case 'E':
1675 case 'e':
1677 /* Minimum output attributable to precision and, when it's
1678 non-zero, decimal point. */
1679 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1681 /* The likely minimum output is "[-+]1.234567e+00" regardless
1682 of the value of the actual argument. */
1683 res.range.likely = (flagmin
1684 + radix
1685 + minprec
1686 + 2 /* e+ */ + 2);
1688 res.range.max = format_floating_max (type, 'e', prec[1]);
1690 /* The unlikely maximum accounts for the longest multibyte
1691 decimal point character. */
1692 if (dir.prec[0] != dir.prec[1]
1693 || dir.prec[0] == -1 || dir.prec[0] > 0)
1694 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1695 else
1696 res.range.unlikely = res.range.max;
1697 break;
1700 case 'F':
1701 case 'f':
1703 /* Minimum output attributable to precision and, when it's non-zero,
1704 decimal point. */
1705 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1707 /* For finite numbers (i.e., not infinity or NaN) the lower bound
1708 when precision isn't specified is 8 bytes ("1.23456" since
1709 precision is taken to be 6). When precision is zero, the lower
1710 bound is 1 byte (e.g., "1"). Otherwise, when precision is greater
1711 than zero, then the lower bound is 2 plus precision (plus flags).
1712 But in all cases, the lower bound is no greater than 3. */
1713 unsigned HOST_WIDE_INT min = flagmin + radix + minprec;
1714 if (min < res.range.min)
1715 res.range.min = min;
1717 /* Compute the upper bound for -TYPE_MAX. */
1718 res.range.max = format_floating_max (type, 'f', prec[1]);
1720 /* The minimum output with unknown precision is a single byte
1721 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1722 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1723 res.range.likely = 3;
1724 else
1725 res.range.likely = min;
1727 /* The unlikely maximum accounts for the longest multibyte
1728 decimal point character. */
1729 if (dir.prec[0] != dir.prec[1]
1730 || dir.prec[0] == -1 || dir.prec[0] > 0)
1731 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1732 break;
1735 case 'G':
1736 case 'g':
1738 /* The %g output depends on precision and the exponent of
1739 the argument. Since the value of the argument isn't known
1740 the lower bound on the range of bytes (not counting flags
1741 or width) is 1 plus radix (i.e., either "0" or "0." for
1742 "%g" and "%#g", respectively, with a zero argument). */
1743 unsigned HOST_WIDE_INT min = flagmin + radix;
1744 if (min < res.range.min)
1745 res.range.min = min;
1747 char spec = 'g';
1748 HOST_WIDE_INT maxprec = dir.prec[1];
1749 if (radix && maxprec)
1751 /* When the pound flag (radix) is set, trailing zeros aren't
1752 trimmed and so the longest output is the same as for %e,
1753 except with precision minus 1 (as specified in C11). */
1754 spec = 'e';
1755 if (maxprec > 0)
1756 --maxprec;
1757 else if (maxprec < 0)
1758 maxprec = 5;
1760 else
1761 maxprec = prec[1];
1763 res.range.max = format_floating_max (type, spec, maxprec);
1765 /* The likely output is either the maximum computed above
1766 minus 1 (assuming the maximum is positive) when precision
1767 is known (or unspecified), or the same minimum as for %e
1768 (which is computed for a non-negative argument). Unlike
1769 for the other specifiers above the likely output isn't
1770 the minimum because for %g that's 1 which is unlikely. */
1771 if (dir.prec[1] < 0
1772 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1773 res.range.likely = res.range.max - 1;
1774 else
1776 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1777 res.range.likely = (flagmin
1778 + radix
1779 + minprec
1780 + 2 /* e+ */ + 2);
1783 /* The unlikely maximum accounts for the longest multibyte
1784 decimal point character. */
1785 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1786 break;
1789 default:
1790 return fmtresult ();
1793 /* Bump up the byte counters if WIDTH is greater. */
1794 res.adjust_for_width_or_precision (dir.width);
1795 return res;
1798 /* Return a range representing the minimum and maximum number of bytes
1799 that the directive DIR will write on output for the floating argument
1800 ARG. */
1802 static fmtresult
1803 format_floating (const directive &dir, tree arg, vr_values *)
1805 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1806 tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1807 ? long_double_type_node : double_type_node);
1809 /* For an indeterminate precision the lower bound must be assumed
1810 to be zero. */
1811 if (TOUPPER (dir.specifier) == 'A')
1813 /* Get the number of fractional decimal digits needed to represent
1814 the argument without a loss of accuracy. */
1815 unsigned fmtprec
1816 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1818 /* The precision of the IEEE 754 double format is 53.
1819 The precision of all other GCC binary double formats
1820 is 56 or less. */
1821 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1823 /* For %a, leave the minimum precision unspecified to let
1824 MFPR trim trailing zeros (as it and many other systems
1825 including Glibc happen to do) and set the maximum
1826 precision to reflect what it would be with trailing zeros
1827 present (as Solaris and derived systems do). */
1828 if (dir.prec[1] < 0)
1830 /* Both bounds are negative implies that precision has
1831 not been specified. */
1832 prec[0] = maxprec;
1833 prec[1] = -1;
1835 else if (dir.prec[0] < 0)
1837 /* With a negative lower bound and a non-negative upper
1838 bound set the minimum precision to zero and the maximum
1839 to the greater of the maximum precision (i.e., with
1840 trailing zeros present) and the specified upper bound. */
1841 prec[0] = 0;
1842 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1845 else if (dir.prec[0] < 0)
1847 if (dir.prec[1] < 0)
1849 /* A precision in a strictly negative range is ignored and
1850 the default of 6 is used instead. */
1851 prec[0] = prec[1] = 6;
1853 else
1855 /* For a precision in a partly negative range, the lower bound
1856 must be assumed to be zero and the new upper bound is the
1857 greater of 6 (the default precision used when the specified
1858 precision is negative) and the upper bound of the specified
1859 range. */
1860 prec[0] = 0;
1861 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1865 if (!arg
1866 || TREE_CODE (arg) != REAL_CST
1867 || !useless_type_conversion_p (type, TREE_TYPE (arg)))
1868 return format_floating (dir, prec);
1870 /* The minimum and maximum number of bytes produced by the directive. */
1871 fmtresult res;
1873 /* Get the real type format desription for the target. */
1874 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1875 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1877 if (!real_isfinite (rvp))
1879 /* The format for Infinity and NaN is "[-]inf"/"[-]infinity"
1880 and "[-]nan" with the choice being implementation-defined
1881 but not locale dependent. */
1882 bool sign = dir.get_flag ('+') || real_isneg (rvp);
1883 res.range.min = 3 + sign;
1885 res.range.likely = res.range.min;
1886 res.range.max = res.range.min;
1887 /* The unlikely maximum is "[-/+]infinity" or "[-/+][qs]nan".
1888 For NaN, the C/POSIX standards specify two formats:
1889 "[-/+]nan"
1891 "[-/+]nan(n-char-sequence)"
1892 No known printf implementation outputs the latter format but AIX
1893 outputs QNaN and SNaN for quiet and signalling NaN, respectively,
1894 so the unlikely maximum reflects that. */
1895 res.range.unlikely = sign + (real_isinf (rvp) ? 8 : 4);
1897 /* The range for infinity and NaN is known unless either width
1898 or precision is unknown. Width has the same effect regardless
1899 of whether the argument is finite. Precision is either ignored
1900 (e.g., Glibc) or can have an effect on the short vs long format
1901 such as inf/infinity (e.g., Solaris). */
1902 res.knownrange = dir.known_width_and_precision ();
1904 /* Adjust the range for width but ignore precision. */
1905 res.adjust_for_width_or_precision (dir.width);
1907 return res;
1910 char fmtstr [40];
1911 char *pfmt = fmtstr;
1913 /* Append flags. */
1914 for (const char *pf = "-+ #0"; *pf; ++pf)
1915 if (dir.get_flag (*pf))
1916 *pfmt++ = *pf;
1918 *pfmt = '\0';
1921 /* Set up an array to easily iterate over. */
1922 unsigned HOST_WIDE_INT* const minmax[] = {
1923 &res.range.min, &res.range.max
1926 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1928 /* Convert the GCC real value representation with the precision
1929 of the real type to the mpfr_t format rounding down in the
1930 first iteration that computes the minimm and up in the second
1931 that computes the maximum. This order is arbibtrary because
1932 rounding in either direction can result in longer output. */
1933 mpfr_t mpfrval;
1934 mpfr_init2 (mpfrval, rfmt->p);
1935 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1937 /* Use the MPFR rounding specifier to round down in the first
1938 iteration and then up. In most but not all cases this will
1939 result in the same number of bytes. */
1940 char rndspec = "DU"[i];
1942 /* Format it and store the result in the corresponding member
1943 of the result struct. */
1944 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1945 dir.specifier, rndspec);
1946 mpfr_clear (mpfrval);
1950 /* Make sure the minimum is less than the maximum (MPFR rounding
1951 in the call to mpfr_snprintf can result in the reverse. */
1952 if (res.range.max < res.range.min)
1954 unsigned HOST_WIDE_INT tmp = res.range.min;
1955 res.range.min = res.range.max;
1956 res.range.max = tmp;
1959 /* The range is known unless either width or precision is unknown. */
1960 res.knownrange = dir.known_width_and_precision ();
1962 /* For the same floating point constant, unless width or precision
1963 is unknown, use the longer output as the likely maximum since
1964 with round to nearest either is equally likely. Otheriwse, when
1965 precision is unknown, use the greater of the minimum and 3 as
1966 the likely output (for "0.0" since zero precision is unlikely). */
1967 if (res.knownrange)
1968 res.range.likely = res.range.max;
1969 else if (res.range.min < 3
1970 && dir.prec[0] < 0
1971 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
1972 res.range.likely = 3;
1973 else
1974 res.range.likely = res.range.min;
1976 res.range.unlikely = res.range.max;
1978 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
1980 /* Unless the precision is zero output longer than 2 bytes may
1981 include the decimal point which must be a single character
1982 up to MB_LEN_MAX in length. This is overly conservative
1983 since in some conversions some constants result in no decimal
1984 point (e.g., in %g). */
1985 res.range.unlikely += target_mb_len_max () - 1;
1988 res.adjust_for_width_or_precision (dir.width);
1989 return res;
1992 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1993 strings referenced by the expression STR, or (-1, -1) when not known.
1994 Used by the format_string function below. */
1996 static fmtresult
1997 get_string_length (tree str, unsigned eltsize)
1999 if (!str)
2000 return fmtresult ();
2002 if (tree slen = c_strlen (str, 1, eltsize))
2004 /* Simply return the length of the string. */
2005 fmtresult res (tree_to_shwi (slen));
2006 return res;
2009 /* Determine the length of the shortest and longest string referenced
2010 by STR. Strings of unknown lengths are bounded by the sizes of
2011 arrays that subexpressions of STR may refer to. Pointers that
2012 aren't known to point any such arrays result in LENRANGE[1] set
2013 to SIZE_MAX. */
2014 tree lenrange[2];
2015 bool flexarray = get_range_strlen (str, lenrange, eltsize);
2017 if (lenrange [0] || lenrange [1])
2019 HOST_WIDE_INT min
2020 = (tree_fits_uhwi_p (lenrange[0])
2021 ? tree_to_uhwi (lenrange[0])
2022 : 0);
2024 HOST_WIDE_INT max
2025 = (tree_fits_uhwi_p (lenrange[1])
2026 ? tree_to_uhwi (lenrange[1])
2027 : HOST_WIDE_INT_M1U);
2029 /* get_range_strlen() returns the target value of SIZE_MAX for
2030 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2031 which may be bigger. */
2032 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2033 min = HOST_WIDE_INT_M1U;
2034 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2035 max = HOST_WIDE_INT_M1U;
2037 fmtresult res (min, max);
2039 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2040 by STR are known to be bounded (though not necessarily by their
2041 actual length but perhaps by their maximum possible length). */
2042 if (res.range.max < target_int_max ())
2044 res.knownrange = true;
2045 /* When the the length of the longest string is known and not
2046 excessive use it as the likely length of the string(s). */
2047 res.range.likely = res.range.max;
2049 else
2051 /* When the upper bound is unknown (it can be zero or excessive)
2052 set the likely length to the greater of 1 and the length of
2053 the shortest string and reset the lower bound to zero. */
2054 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2055 res.range.min = 0;
2058 /* If the range of string length has been estimated from the size
2059 of an array at the end of a struct assume that it's longer than
2060 the array bound says it is in case it's used as a poor man's
2061 flexible array member, such as in struct S { char a[4]; }; */
2062 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
2064 return res;
2067 return fmtresult ();
2070 /* Return the minimum and maximum number of characters formatted
2071 by the '%c' format directives and its wide character form for
2072 the argument ARG. ARG can be null (for functions such as
2073 vsprinf). */
2075 static fmtresult
2076 format_character (const directive &dir, tree arg, vr_values *vr_values)
2078 fmtresult res;
2080 res.knownrange = true;
2082 if (dir.specifier == 'C'
2083 || dir.modifier == FMT_LEN_l)
2085 /* A wide character can result in as few as zero bytes. */
2086 res.range.min = 0;
2088 HOST_WIDE_INT min, max;
2089 if (get_int_range (arg, &min, &max, false, 0, vr_values))
2091 if (min == 0 && max == 0)
2093 /* The NUL wide character results in no bytes. */
2094 res.range.max = 0;
2095 res.range.likely = 0;
2096 res.range.unlikely = 0;
2098 else if (min >= 0 && min < 128)
2100 /* Be conservative if the target execution character set
2101 is not a 1-to-1 mapping to the source character set or
2102 if the source set is not ASCII. */
2103 bool one_2_one_ascii
2104 = (target_to_host_charmap[0] == 1 && target_to_host ('a') == 97);
2106 /* A wide character in the ASCII range most likely results
2107 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2108 res.range.max = one_2_one_ascii ? 1 : target_mb_len_max ();;
2109 res.range.likely = 1;
2110 res.range.unlikely = target_mb_len_max ();
2111 res.mayfail = !one_2_one_ascii;
2113 else
2115 /* A wide character outside the ASCII range likely results
2116 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2117 res.range.max = target_mb_len_max ();
2118 res.range.likely = 2;
2119 res.range.unlikely = res.range.max;
2120 /* Converting such a character may fail. */
2121 res.mayfail = true;
2124 else
2126 /* An unknown wide character is treated the same as a wide
2127 character outside the ASCII range. */
2128 res.range.max = target_mb_len_max ();
2129 res.range.likely = 2;
2130 res.range.unlikely = res.range.max;
2131 res.mayfail = true;
2134 else
2136 /* A plain '%c' directive. Its ouput is exactly 1. */
2137 res.range.min = res.range.max = 1;
2138 res.range.likely = res.range.unlikely = 1;
2139 res.knownrange = true;
2142 /* Bump up the byte counters if WIDTH is greater. */
2143 return res.adjust_for_width_or_precision (dir.width);
2146 /* Return the minimum and maximum number of characters formatted
2147 by the '%s' format directive and its wide character form for
2148 the argument ARG. ARG can be null (for functions such as
2149 vsprinf). */
2151 static fmtresult
2152 format_string (const directive &dir, tree arg, vr_values *)
2154 fmtresult res;
2156 /* Compute the range the argument's length can be in. */
2157 int count_by = dir.specifier == 'S' || dir.modifier == FMT_LEN_l ? 4 : 1;
2158 fmtresult slen = get_string_length (arg, count_by);
2159 if (slen.range.min == slen.range.max
2160 && slen.range.min < HOST_WIDE_INT_MAX)
2162 /* The argument is either a string constant or it refers
2163 to one of a number of strings of the same length. */
2165 /* A '%s' directive with a string argument with constant length. */
2166 res.range = slen.range;
2168 if (dir.specifier == 'S'
2169 || dir.modifier == FMT_LEN_l)
2171 /* In the worst case the length of output of a wide string S
2172 is bounded by MB_LEN_MAX * wcslen (S). */
2173 res.range.max *= target_mb_len_max ();
2174 res.range.unlikely = res.range.max;
2175 /* It's likely that the the total length is not more that
2176 2 * wcslen (S).*/
2177 res.range.likely = res.range.min * 2;
2179 if (dir.prec[1] >= 0
2180 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2182 res.range.max = dir.prec[1];
2183 res.range.likely = dir.prec[1];
2184 res.range.unlikely = dir.prec[1];
2187 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2188 res.range.min = 0;
2189 else if (dir.prec[0] >= 0)
2190 res.range.likely = dir.prec[0];
2192 /* Even a non-empty wide character string need not convert into
2193 any bytes. */
2194 res.range.min = 0;
2196 /* A non-empty wide character conversion may fail. */
2197 if (slen.range.max > 0)
2198 res.mayfail = true;
2200 else
2202 res.knownrange = true;
2204 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2205 res.range.min = 0;
2206 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2207 res.range.min = dir.prec[0];
2209 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2211 res.range.max = dir.prec[1];
2212 res.range.likely = dir.prec[1];
2213 res.range.unlikely = dir.prec[1];
2217 else if (arg && integer_zerop (arg))
2219 /* Handle null pointer argument. */
2221 fmtresult res (0);
2222 res.nullp = true;
2223 return res;
2225 else
2227 /* For a '%s' and '%ls' directive with a non-constant string (either
2228 one of a number of strings of known length or an unknown string)
2229 the minimum number of characters is lesser of PRECISION[0] and
2230 the length of the shortest known string or zero, and the maximum
2231 is the lessser of the length of the longest known string or
2232 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2233 the minimum at level 1 and the greater of the minimum and 1
2234 at level 2. This result is adjust upward for width (if it's
2235 specified). */
2237 if (dir.specifier == 'S'
2238 || dir.modifier == FMT_LEN_l)
2240 /* A wide character converts to as few as zero bytes. */
2241 slen.range.min = 0;
2242 if (slen.range.max < target_int_max ())
2243 slen.range.max *= target_mb_len_max ();
2245 if (slen.range.likely < target_int_max ())
2246 slen.range.likely *= 2;
2248 if (slen.range.likely < target_int_max ())
2249 slen.range.unlikely *= target_mb_len_max ();
2251 /* A non-empty wide character conversion may fail. */
2252 if (slen.range.max > 0)
2253 res.mayfail = true;
2256 res.range = slen.range;
2258 if (dir.prec[0] >= 0)
2260 /* Adjust the minimum to zero if the string length is unknown,
2261 or at most the lower bound of the precision otherwise. */
2262 if (slen.range.min >= target_int_max ())
2263 res.range.min = 0;
2264 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2265 res.range.min = dir.prec[0];
2267 /* Make both maxima no greater than the upper bound of precision. */
2268 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2269 || slen.range.max >= target_int_max ())
2271 res.range.max = dir.prec[1];
2272 res.range.unlikely = dir.prec[1];
2275 /* If precision is constant, set the likely counter to the lesser
2276 of it and the maximum string length. Otherwise, if the lower
2277 bound of precision is greater than zero, set the likely counter
2278 to the minimum. Otherwise set it to zero or one based on
2279 the warning level. */
2280 if (dir.prec[0] == dir.prec[1])
2281 res.range.likely
2282 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2283 ? dir.prec[0] : slen.range.max);
2284 else if (dir.prec[0] > 0)
2285 res.range.likely = res.range.min;
2286 else
2287 res.range.likely = warn_level > 1;
2289 else if (dir.prec[1] >= 0)
2291 res.range.min = 0;
2292 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2293 res.range.max = dir.prec[1];
2294 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2296 else if (slen.range.min >= target_int_max ())
2298 res.range.min = 0;
2299 res.range.max = HOST_WIDE_INT_MAX;
2300 /* At level 1 strings of unknown length are assumed to be
2301 empty, while at level 1 they are assumed to be one byte
2302 long. */
2303 res.range.likely = warn_level > 1;
2305 else
2307 /* A string of unknown length unconstrained by precision is
2308 assumed to be empty at level 1 and just one character long
2309 at higher levels. */
2310 if (res.range.likely >= target_int_max ())
2311 res.range.likely = warn_level > 1;
2314 res.range.unlikely = res.range.max;
2317 /* Bump up the byte counters if WIDTH is greater. */
2318 return res.adjust_for_width_or_precision (dir.width);
2321 /* Format plain string (part of the format string itself). */
2323 static fmtresult
2324 format_plain (const directive &dir, tree, vr_values *)
2326 fmtresult res (dir.len);
2327 return res;
2330 /* Return true if the RESULT of a directive in a call describe by INFO
2331 should be diagnosed given the AVAILable space in the destination. */
2333 static bool
2334 should_warn_p (const sprintf_dom_walker::call_info &info,
2335 const result_range &avail, const result_range &result)
2337 if (result.max <= avail.min)
2339 /* The least amount of space remaining in the destination is big
2340 enough for the longest output. */
2341 return false;
2344 if (info.bounded)
2346 if (warn_format_trunc == 1 && result.min <= avail.max
2347 && info.retval_used ())
2349 /* The likely amount of space remaining in the destination is big
2350 enough for the least output and the return value is used. */
2351 return false;
2354 if (warn_format_trunc == 1 && result.likely <= avail.likely
2355 && !info.retval_used ())
2357 /* The likely amount of space remaining in the destination is big
2358 enough for the likely output and the return value is unused. */
2359 return false;
2362 if (warn_format_trunc == 2
2363 && result.likely <= avail.min
2364 && (result.max <= avail.min
2365 || result.max > HOST_WIDE_INT_MAX))
2367 /* The minimum amount of space remaining in the destination is big
2368 enough for the longest output. */
2369 return false;
2372 else
2374 if (warn_level == 1 && result.likely <= avail.likely)
2376 /* The likely amount of space remaining in the destination is big
2377 enough for the likely output. */
2378 return false;
2381 if (warn_level == 2
2382 && result.likely <= avail.min
2383 && (result.max <= avail.min
2384 || result.max > HOST_WIDE_INT_MAX))
2386 /* The minimum amount of space remaining in the destination is big
2387 enough for the longest output. */
2388 return false;
2392 return true;
2395 /* At format string location describe by DIRLOC in a call described
2396 by INFO, issue a warning for a directive DIR whose output may be
2397 in excess of the available space AVAIL_RANGE in the destination
2398 given the formatting result FMTRES. This function does nothing
2399 except decide whether to issue a warning for a possible write
2400 past the end or truncation and, if so, format the warning.
2401 Return true if a warning has been issued. */
2403 static bool
2404 maybe_warn (substring_loc &dirloc, location_t argloc,
2405 const sprintf_dom_walker::call_info &info,
2406 const result_range &avail_range, const result_range &res,
2407 const directive &dir)
2409 if (!should_warn_p (info, avail_range, res))
2410 return false;
2412 /* A warning will definitely be issued below. */
2414 /* The maximum byte count to reference in the warning. Larger counts
2415 imply that the upper bound is unknown (and could be anywhere between
2416 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2417 than "between N and X" where X is some huge number. */
2418 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2420 /* True when there is enough room in the destination for the least
2421 amount of a directive's output but not enough for its likely or
2422 maximum output. */
2423 bool maybe = (res.min <= avail_range.max
2424 && (avail_range.min < res.likely
2425 || (res.max < HOST_WIDE_INT_MAX
2426 && avail_range.min < res.max)));
2428 /* Buffer for the directive in the host character set (used when
2429 the source character set is different). */
2430 char hostdir[32];
2432 if (avail_range.min == avail_range.max)
2434 /* The size of the destination region is exact. */
2435 unsigned HOST_WIDE_INT navail = avail_range.max;
2437 if (target_to_host (*dir.beg) != '%')
2439 /* For plain character directives (i.e., the format string itself)
2440 but not others, point the caret at the first character that's
2441 past the end of the destination. */
2442 if (navail < dir.len)
2443 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2446 if (*dir.beg == '\0')
2448 /* This is the terminating nul. */
2449 gcc_assert (res.min == 1 && res.min == res.max);
2451 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2452 info.bounded
2453 ? (maybe
2454 ? G_("%qE output may be truncated before the "
2455 "last format character")
2456 : G_("%qE output truncated before the last "
2457 "format character"))
2458 : (maybe
2459 ? G_("%qE may write a terminating nul past the "
2460 "end of the destination")
2461 : G_("%qE writing a terminating nul past the "
2462 "end of the destination")),
2463 info.func);
2466 if (res.min == res.max)
2468 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2469 if (!info.bounded)
2470 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2471 "%<%.*s%> directive writing %wu byte into a "
2472 "region of size %wu",
2473 "%<%.*s%> directive writing %wu bytes into a "
2474 "region of size %wu",
2475 (int) dir.len, d, res.min, navail);
2476 else if (maybe)
2477 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2478 "%<%.*s%> directive output may be truncated "
2479 "writing %wu byte into a region of size %wu",
2480 "%<%.*s%> directive output may be truncated "
2481 "writing %wu bytes into a region of size %wu",
2482 (int) dir.len, d, res.min, navail);
2483 else
2484 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2485 "%<%.*s%> directive output truncated writing "
2486 "%wu byte into a region of size %wu",
2487 "%<%.*s%> directive output truncated writing "
2488 "%wu bytes into a region of size %wu",
2489 (int) dir.len, d, res.min, navail);
2491 if (res.min == 0 && res.max < maxbytes)
2492 return fmtwarn (dirloc, argloc, NULL,
2493 info.warnopt (),
2494 info.bounded
2495 ? (maybe
2496 ? G_("%<%.*s%> directive output may be truncated "
2497 "writing up to %wu bytes into a region of "
2498 "size %wu")
2499 : G_("%<%.*s%> directive output truncated writing "
2500 "up to %wu bytes into a region of size %wu"))
2501 : G_("%<%.*s%> directive writing up to %wu bytes "
2502 "into a region of size %wu"), (int) dir.len,
2503 target_to_host (hostdir, sizeof hostdir, dir.beg),
2504 res.max, navail);
2506 if (res.min == 0 && maxbytes <= res.max)
2507 /* This is a special case to avoid issuing the potentially
2508 confusing warning:
2509 writing 0 or more bytes into a region of size 0. */
2510 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2511 info.bounded
2512 ? (maybe
2513 ? G_("%<%.*s%> directive output may be truncated "
2514 "writing likely %wu or more bytes into a "
2515 "region of size %wu")
2516 : G_("%<%.*s%> directive output truncated writing "
2517 "likely %wu or more bytes into a region of "
2518 "size %wu"))
2519 : G_("%<%.*s%> directive writing likely %wu or more "
2520 "bytes into a region of size %wu"), (int) dir.len,
2521 target_to_host (hostdir, sizeof hostdir, dir.beg),
2522 res.likely, navail);
2524 if (res.max < maxbytes)
2525 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2526 info.bounded
2527 ? (maybe
2528 ? G_("%<%.*s%> directive output may be truncated "
2529 "writing between %wu and %wu bytes into a "
2530 "region of size %wu")
2531 : G_("%<%.*s%> directive output truncated "
2532 "writing between %wu and %wu bytes into a "
2533 "region of size %wu"))
2534 : G_("%<%.*s%> directive writing between %wu and "
2535 "%wu bytes into a region of size %wu"),
2536 (int) dir.len,
2537 target_to_host (hostdir, sizeof hostdir, dir.beg),
2538 res.min, res.max, navail);
2540 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2541 info.bounded
2542 ? (maybe
2543 ? G_("%<%.*s%> directive output may be truncated "
2544 "writing %wu or more bytes into a region of "
2545 "size %wu")
2546 : G_("%<%.*s%> directive output truncated writing "
2547 "%wu or more bytes into a region of size %wu"))
2548 : G_("%<%.*s%> directive writing %wu or more bytes "
2549 "into a region of size %wu"), (int) dir.len,
2550 target_to_host (hostdir, sizeof hostdir, dir.beg),
2551 res.min, navail);
2554 /* The size of the destination region is a range. */
2556 if (target_to_host (*dir.beg) != '%')
2558 unsigned HOST_WIDE_INT navail = avail_range.max;
2560 /* For plain character directives (i.e., the format string itself)
2561 but not others, point the caret at the first character that's
2562 past the end of the destination. */
2563 if (navail < dir.len)
2564 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2567 if (*dir.beg == '\0')
2569 gcc_assert (res.min == 1 && res.min == res.max);
2571 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2572 info.bounded
2573 ? (maybe
2574 ? G_("%qE output may be truncated before the last "
2575 "format character")
2576 : G_("%qE output truncated before the last format "
2577 "character"))
2578 : (maybe
2579 ? G_("%qE may write a terminating nul past the end "
2580 "of the destination")
2581 : G_("%qE writing a terminating nul past the end "
2582 "of the destination")), info.func);
2585 if (res.min == res.max)
2587 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2588 if (!info.bounded)
2589 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2590 "%<%.*s%> directive writing %wu byte into a region "
2591 "of size between %wu and %wu",
2592 "%<%.*s%> directive writing %wu bytes into a region "
2593 "of size between %wu and %wu", (int) dir.len, d,
2594 res.min, avail_range.min, avail_range.max);
2595 else if (maybe)
2596 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2597 "%<%.*s%> directive output may be truncated writing "
2598 "%wu byte into a region of size between %wu and %wu",
2599 "%<%.*s%> directive output may be truncated writing "
2600 "%wu bytes into a region of size between %wu and "
2601 "%wu", (int) dir.len, d, res.min, avail_range.min,
2602 avail_range.max);
2603 else
2604 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2605 "%<%.*s%> directive output truncated writing %wu "
2606 "byte into a region of size between %wu and %wu",
2607 "%<%.*s%> directive output truncated writing %wu "
2608 "bytes into a region of size between %wu and %wu",
2609 (int) dir.len, d, res.min, avail_range.min,
2610 avail_range.max);
2613 if (res.min == 0 && res.max < maxbytes)
2614 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2615 info.bounded
2616 ? (maybe
2617 ? G_("%<%.*s%> directive output may be truncated "
2618 "writing up to %wu bytes into a region of size "
2619 "between %wu and %wu")
2620 : G_("%<%.*s%> directive output truncated writing "
2621 "up to %wu bytes into a region of size between "
2622 "%wu and %wu"))
2623 : G_("%<%.*s%> directive writing up to %wu bytes "
2624 "into a region of size between %wu and %wu"),
2625 (int) dir.len,
2626 target_to_host (hostdir, sizeof hostdir, dir.beg),
2627 res.max, avail_range.min, avail_range.max);
2629 if (res.min == 0 && maxbytes <= res.max)
2630 /* This is a special case to avoid issuing the potentially confusing
2631 warning:
2632 writing 0 or more bytes into a region of size between 0 and N. */
2633 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2634 info.bounded
2635 ? (maybe
2636 ? G_("%<%.*s%> directive output may be truncated "
2637 "writing likely %wu or more bytes into a region "
2638 "of size between %wu and %wu")
2639 : G_("%<%.*s%> directive output truncated writing "
2640 "likely %wu or more bytes into a region of size "
2641 "between %wu and %wu"))
2642 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2643 "into a region of size between %wu and %wu"),
2644 (int) dir.len,
2645 target_to_host (hostdir, sizeof hostdir, dir.beg),
2646 res.likely, avail_range.min, avail_range.max);
2648 if (res.max < maxbytes)
2649 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2650 info.bounded
2651 ? (maybe
2652 ? G_("%<%.*s%> directive output may be truncated "
2653 "writing between %wu and %wu bytes into a region "
2654 "of size between %wu and %wu")
2655 : G_("%<%.*s%> directive output truncated writing "
2656 "between %wu and %wu bytes into a region of size "
2657 "between %wu and %wu"))
2658 : G_("%<%.*s%> directive writing between %wu and "
2659 "%wu bytes into a region of size between %wu and "
2660 "%wu"), (int) dir.len,
2661 target_to_host (hostdir, sizeof hostdir, dir.beg),
2662 res.min, res.max, avail_range.min, avail_range.max);
2664 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2665 info.bounded
2666 ? (maybe
2667 ? G_("%<%.*s%> directive output may be truncated writing "
2668 "%wu or more bytes into a region of size between "
2669 "%wu and %wu")
2670 : G_("%<%.*s%> directive output truncated writing "
2671 "%wu or more bytes into a region of size between "
2672 "%wu and %wu"))
2673 : G_("%<%.*s%> directive writing %wu or more bytes "
2674 "into a region of size between %wu and %wu"),
2675 (int) dir.len,
2676 target_to_host (hostdir, sizeof hostdir, dir.beg),
2677 res.min, avail_range.min, avail_range.max);
2680 /* Compute the length of the output resulting from the directive DIR
2681 in a call described by INFO and update the overall result of the call
2682 in *RES. Return true if the directive has been handled. */
2684 static bool
2685 format_directive (const sprintf_dom_walker::call_info &info,
2686 format_result *res, const directive &dir,
2687 class vr_values *vr_values)
2689 /* Offset of the beginning of the directive from the beginning
2690 of the format string. */
2691 size_t offset = dir.beg - info.fmtstr;
2692 size_t start = offset;
2693 size_t length = offset + dir.len - !!dir.len;
2695 /* Create a location for the whole directive from the % to the format
2696 specifier. */
2697 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2698 offset, start, length);
2700 /* Also get the location of the argument if possible.
2701 This doesn't work for integer literals or function calls. */
2702 location_t argloc = UNKNOWN_LOCATION;
2703 if (dir.arg)
2704 argloc = EXPR_LOCATION (dir.arg);
2706 /* Bail when there is no function to compute the output length,
2707 or when minimum length checking has been disabled. */
2708 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2709 return false;
2711 /* Compute the range of lengths of the formatted output. */
2712 fmtresult fmtres = dir.fmtfunc (dir, dir.arg, vr_values);
2714 /* Record whether the output of all directives is known to be
2715 bounded by some maximum, implying that their arguments are
2716 either known exactly or determined to be in a known range
2717 or, for strings, limited by the upper bounds of the arrays
2718 they refer to. */
2719 res->knownrange &= fmtres.knownrange;
2721 if (!fmtres.knownrange)
2723 /* Only when the range is known, check it against the host value
2724 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2725 INT_MAX precision, which is the longest possible output of any
2726 single directive). That's the largest valid byte count (though
2727 not valid call to a printf-like function because it can never
2728 return such a count). Otherwise, the range doesn't correspond
2729 to known values of the argument. */
2730 if (fmtres.range.max > target_dir_max ())
2732 /* Normalize the MAX counter to avoid having to deal with it
2733 later. The counter can be less than HOST_WIDE_INT_M1U
2734 when compiling for an ILP32 target on an LP64 host. */
2735 fmtres.range.max = HOST_WIDE_INT_M1U;
2736 /* Disable exact and maximum length checking after a failure
2737 to determine the maximum number of characters (for example
2738 for wide characters or wide character strings) but continue
2739 tracking the minimum number of characters. */
2740 res->range.max = HOST_WIDE_INT_M1U;
2743 if (fmtres.range.min > target_dir_max ())
2745 /* Disable exact length checking after a failure to determine
2746 even the minimum number of characters (it shouldn't happen
2747 except in an error) but keep tracking the minimum and maximum
2748 number of characters. */
2749 return true;
2753 /* Buffer for the directive in the host character set (used when
2754 the source character set is different). */
2755 char hostdir[32];
2757 int dirlen = dir.len;
2759 if (fmtres.nullp)
2761 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2762 "%<%.*s%> directive argument is null",
2763 dirlen, target_to_host (hostdir, sizeof hostdir, dir.beg));
2765 /* Don't bother processing the rest of the format string. */
2766 res->warned = true;
2767 res->range.min = HOST_WIDE_INT_M1U;
2768 res->range.max = HOST_WIDE_INT_M1U;
2769 return false;
2772 /* Compute the number of available bytes in the destination. There
2773 must always be at least one byte of space for the terminating
2774 NUL that's appended after the format string has been processed. */
2775 result_range avail_range = bytes_remaining (info.objsize, *res);
2777 bool warned = res->warned;
2779 if (!warned)
2780 warned = maybe_warn (dirloc, argloc, info, avail_range,
2781 fmtres.range, dir);
2783 /* Bump up the total maximum if it isn't too big. */
2784 if (res->range.max < HOST_WIDE_INT_MAX
2785 && fmtres.range.max < HOST_WIDE_INT_MAX)
2786 res->range.max += fmtres.range.max;
2788 /* Raise the total unlikely maximum by the larger of the maximum
2789 and the unlikely maximum. */
2790 unsigned HOST_WIDE_INT save = res->range.unlikely;
2791 if (fmtres.range.max < fmtres.range.unlikely)
2792 res->range.unlikely += fmtres.range.unlikely;
2793 else
2794 res->range.unlikely += fmtres.range.max;
2796 if (res->range.unlikely < save)
2797 res->range.unlikely = HOST_WIDE_INT_M1U;
2799 res->range.min += fmtres.range.min;
2800 res->range.likely += fmtres.range.likely;
2802 /* Has the minimum directive output length exceeded the maximum
2803 of 4095 bytes required to be supported? */
2804 bool minunder4k = fmtres.range.min < 4096;
2805 bool maxunder4k = fmtres.range.max < 4096;
2806 /* Clear POSUNDER4K in the overall result if the maximum has exceeded
2807 the 4k (this is necessary to avoid the return value optimization
2808 that may not be safe in the maximum case). */
2809 if (!maxunder4k)
2810 res->posunder4k = false;
2811 /* Also clear POSUNDER4K if the directive may fail. */
2812 if (fmtres.mayfail)
2813 res->posunder4k = false;
2815 if (!warned
2816 /* Only warn at level 2. */
2817 && warn_level > 1
2818 && (!minunder4k
2819 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2821 /* The directive output may be longer than the maximum required
2822 to be handled by an implementation according to 7.21.6.1, p15
2823 of C11. Warn on this only at level 2 but remember this and
2824 prevent folding the return value when done. This allows for
2825 the possibility of the actual libc call failing due to ENOMEM
2826 (like Glibc does under some conditions). */
2828 if (fmtres.range.min == fmtres.range.max)
2829 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2830 "%<%.*s%> directive output of %wu bytes exceeds "
2831 "minimum required size of 4095", dirlen,
2832 target_to_host (hostdir, sizeof hostdir, dir.beg),
2833 fmtres.range.min);
2834 else
2835 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2836 minunder4k
2837 ? G_("%<%.*s%> directive output between %wu and %wu "
2838 "bytes may exceed minimum required size of "
2839 "4095")
2840 : G_("%<%.*s%> directive output between %wu and %wu "
2841 "bytes exceeds minimum required size of 4095"),
2842 dirlen,
2843 target_to_host (hostdir, sizeof hostdir, dir.beg),
2844 fmtres.range.min, fmtres.range.max);
2847 /* Has the likely and maximum directive output exceeded INT_MAX? */
2848 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2849 /* Don't consider the maximum to be in excess when it's the result
2850 of a string of unknown length (i.e., whose maximum has been set
2851 to be greater than or equal to HOST_WIDE_INT_MAX. */
2852 bool maxximax = (*dir.beg
2853 && res->range.max > target_int_max ()
2854 && res->range.max < HOST_WIDE_INT_MAX);
2856 if (!warned
2857 /* Warn for the likely output size at level 1. */
2858 && (likelyximax
2859 /* But only warn for the maximum at level 2. */
2860 || (warn_level > 1
2861 && maxximax
2862 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2864 /* The directive output causes the total length of output
2865 to exceed INT_MAX bytes. */
2867 if (fmtres.range.min == fmtres.range.max)
2868 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2869 "%<%.*s%> directive output of %wu bytes causes "
2870 "result to exceed %<INT_MAX%>", dirlen,
2871 target_to_host (hostdir, sizeof hostdir, dir.beg),
2872 fmtres.range.min);
2873 else
2874 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2875 fmtres.range.min > target_int_max ()
2876 ? G_("%<%.*s%> directive output between %wu and "
2877 "%wu bytes causes result to exceed "
2878 "%<INT_MAX%>")
2879 : G_("%<%.*s%> directive output between %wu and "
2880 "%wu bytes may cause result to exceed "
2881 "%<INT_MAX%>"), dirlen,
2882 target_to_host (hostdir, sizeof hostdir, dir.beg),
2883 fmtres.range.min, fmtres.range.max);
2886 if (warned && fmtres.range.min < fmtres.range.likely
2887 && fmtres.range.likely < fmtres.range.max)
2888 inform_n (info.fmtloc, fmtres.range.likely,
2889 "assuming directive output of %wu byte",
2890 "assuming directive output of %wu bytes",
2891 fmtres.range.likely);
2893 if (warned && fmtres.argmin)
2895 if (fmtres.argmin == fmtres.argmax)
2896 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2897 else if (fmtres.knownrange)
2898 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2899 fmtres.argmin, fmtres.argmax);
2900 else
2901 inform (info.fmtloc,
2902 "using the range [%E, %E] for directive argument",
2903 fmtres.argmin, fmtres.argmax);
2906 res->warned |= warned;
2908 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2910 /* If a warning has been issued for buffer overflow or truncation
2911 (but not otherwise) help the user figure out how big a buffer
2912 they need. */
2914 location_t callloc = gimple_location (info.callstmt);
2916 unsigned HOST_WIDE_INT min = res->range.min;
2917 unsigned HOST_WIDE_INT max = res->range.max;
2919 if (min == max)
2920 inform (callloc,
2921 (min == 1
2922 ? G_("%qE output %wu byte into a destination of size %wu")
2923 : G_("%qE output %wu bytes into a destination of size %wu")),
2924 info.func, min, info.objsize);
2925 else if (max < HOST_WIDE_INT_MAX)
2926 inform (callloc,
2927 "%qE output between %wu and %wu bytes into "
2928 "a destination of size %wu",
2929 info.func, min, max, info.objsize);
2930 else if (min < res->range.likely && res->range.likely < max)
2931 inform (callloc,
2932 "%qE output %wu or more bytes (assuming %wu) into "
2933 "a destination of size %wu",
2934 info.func, min, res->range.likely, info.objsize);
2935 else
2936 inform (callloc,
2937 "%qE output %wu or more bytes into a destination of size %wu",
2938 info.func, min, info.objsize);
2941 if (dump_file && *dir.beg)
2943 fprintf (dump_file,
2944 " Result: "
2945 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
2946 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
2947 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
2948 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
2949 fmtres.range.min, fmtres.range.likely,
2950 fmtres.range.max, fmtres.range.unlikely,
2951 res->range.min, res->range.likely,
2952 res->range.max, res->range.unlikely);
2955 return true;
2958 /* Parse a format directive in function call described by INFO starting
2959 at STR and populate DIR structure. Bump up *ARGNO by the number of
2960 arguments extracted for the directive. Return the length of
2961 the directive. */
2963 static size_t
2964 parse_directive (sprintf_dom_walker::call_info &info,
2965 directive &dir, format_result *res,
2966 const char *str, unsigned *argno,
2967 vr_values *vr_values)
2969 const char *pcnt = strchr (str, target_percent);
2970 dir.beg = str;
2972 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
2974 /* This directive is either a plain string or the terminating nul
2975 (which isn't really a directive but it simplifies things to
2976 handle it as if it were). */
2977 dir.len = len;
2978 dir.fmtfunc = format_plain;
2980 if (dump_file)
2982 fprintf (dump_file, " Directive %u at offset "
2983 HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
2984 "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
2985 dir.dirno,
2986 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
2987 (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
2990 return len - !*str;
2993 const char *pf = pcnt + 1;
2995 /* POSIX numbered argument index or zero when none. */
2996 HOST_WIDE_INT dollar = 0;
2998 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
2999 when given by a va_list argument, and a non-negative value
3000 when specified in the format string itself. */
3001 HOST_WIDE_INT width = -1;
3002 HOST_WIDE_INT precision = -1;
3004 /* Pointers to the beginning of the width and precision decimal
3005 string (if any) within the directive. */
3006 const char *pwidth = 0;
3007 const char *pprec = 0;
3009 /* When the value of the decimal string that specifies width or
3010 precision is out of range, points to the digit that causes
3011 the value to exceed the limit. */
3012 const char *werange = NULL;
3013 const char *perange = NULL;
3015 /* Width specified via the asterisk. Need not be INTEGER_CST.
3016 For vararg functions set to void_node. */
3017 tree star_width = NULL_TREE;
3019 /* Width specified via the asterisk. Need not be INTEGER_CST.
3020 For vararg functions set to void_node. */
3021 tree star_precision = NULL_TREE;
3023 if (ISDIGIT (target_to_host (*pf)))
3025 /* This could be either a POSIX positional argument, the '0'
3026 flag, or a width, depending on what follows. Store it as
3027 width and sort it out later after the next character has
3028 been seen. */
3029 pwidth = pf;
3030 width = target_strtol10 (&pf, &werange);
3032 else if (target_to_host (*pf) == '*')
3034 /* Similarly to the block above, this could be either a POSIX
3035 positional argument or a width, depending on what follows. */
3036 if (*argno < gimple_call_num_args (info.callstmt))
3037 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3038 else
3039 star_width = void_node;
3040 ++pf;
3043 if (target_to_host (*pf) == '$')
3045 /* Handle the POSIX dollar sign which references the 1-based
3046 positional argument number. */
3047 if (width != -1)
3048 dollar = width + info.argidx;
3049 else if (star_width
3050 && TREE_CODE (star_width) == INTEGER_CST
3051 && (TYPE_PRECISION (TREE_TYPE (star_width))
3052 <= TYPE_PRECISION (integer_type_node)))
3053 dollar = width + tree_to_shwi (star_width);
3055 /* Bail when the numbered argument is out of range (it will
3056 have already been diagnosed by -Wformat). */
3057 if (dollar == 0
3058 || dollar == (int)info.argidx
3059 || dollar > gimple_call_num_args (info.callstmt))
3060 return false;
3062 --dollar;
3064 star_width = NULL_TREE;
3065 width = -1;
3066 ++pf;
3069 if (dollar || !star_width)
3071 if (width != -1)
3073 if (width == 0)
3075 /* The '0' that has been interpreted as a width above is
3076 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3077 and continue processing other flags. */
3078 width = -1;
3079 dir.set_flag ('0');
3081 else if (!dollar)
3083 /* (Non-zero) width has been seen. The next character
3084 is either a period or a digit. */
3085 goto start_precision;
3088 /* When either '$' has been seen, or width has not been seen,
3089 the next field is the optional flags followed by an optional
3090 width. */
3091 for ( ; ; ) {
3092 switch (target_to_host (*pf))
3094 case ' ':
3095 case '0':
3096 case '+':
3097 case '-':
3098 case '#':
3099 dir.set_flag (target_to_host (*pf++));
3100 break;
3102 default:
3103 goto start_width;
3107 start_width:
3108 if (ISDIGIT (target_to_host (*pf)))
3110 werange = 0;
3111 pwidth = pf;
3112 width = target_strtol10 (&pf, &werange);
3114 else if (target_to_host (*pf) == '*')
3116 if (*argno < gimple_call_num_args (info.callstmt))
3117 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3118 else
3120 /* This is (likely) a va_list. It could also be an invalid
3121 call with insufficient arguments. */
3122 star_width = void_node;
3124 ++pf;
3126 else if (target_to_host (*pf) == '\'')
3128 /* The POSIX apostrophe indicating a numeric grouping
3129 in the current locale. Even though it's possible to
3130 estimate the upper bound on the size of the output
3131 based on the number of digits it probably isn't worth
3132 continuing. */
3133 return 0;
3137 start_precision:
3138 if (target_to_host (*pf) == '.')
3140 ++pf;
3142 if (ISDIGIT (target_to_host (*pf)))
3144 pprec = pf;
3145 precision = target_strtol10 (&pf, &perange);
3147 else if (target_to_host (*pf) == '*')
3149 if (*argno < gimple_call_num_args (info.callstmt))
3150 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3151 else
3153 /* This is (likely) a va_list. It could also be an invalid
3154 call with insufficient arguments. */
3155 star_precision = void_node;
3157 ++pf;
3159 else
3161 /* The decimal precision or the asterisk are optional.
3162 When neither is dirified it's taken to be zero. */
3163 precision = 0;
3167 switch (target_to_host (*pf))
3169 case 'h':
3170 if (target_to_host (pf[1]) == 'h')
3172 ++pf;
3173 dir.modifier = FMT_LEN_hh;
3175 else
3176 dir.modifier = FMT_LEN_h;
3177 ++pf;
3178 break;
3180 case 'j':
3181 dir.modifier = FMT_LEN_j;
3182 ++pf;
3183 break;
3185 case 'L':
3186 dir.modifier = FMT_LEN_L;
3187 ++pf;
3188 break;
3190 case 'l':
3191 if (target_to_host (pf[1]) == 'l')
3193 ++pf;
3194 dir.modifier = FMT_LEN_ll;
3196 else
3197 dir.modifier = FMT_LEN_l;
3198 ++pf;
3199 break;
3201 case 't':
3202 dir.modifier = FMT_LEN_t;
3203 ++pf;
3204 break;
3206 case 'z':
3207 dir.modifier = FMT_LEN_z;
3208 ++pf;
3209 break;
3212 switch (target_to_host (*pf))
3214 /* Handle a sole '%' character the same as "%%" but since it's
3215 undefined prevent the result from being folded. */
3216 case '\0':
3217 --pf;
3218 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3219 /* FALLTHRU */
3220 case '%':
3221 dir.fmtfunc = format_percent;
3222 break;
3224 case 'a':
3225 case 'A':
3226 case 'e':
3227 case 'E':
3228 case 'f':
3229 case 'F':
3230 case 'g':
3231 case 'G':
3232 res->floating = true;
3233 dir.fmtfunc = format_floating;
3234 break;
3236 case 'd':
3237 case 'i':
3238 case 'o':
3239 case 'u':
3240 case 'x':
3241 case 'X':
3242 dir.fmtfunc = format_integer;
3243 break;
3245 case 'p':
3246 /* The %p output is implementation-defined. It's possible
3247 to determine this format but due to extensions (edirially
3248 those of the Linux kernel -- see bug 78512) the first %p
3249 in the format string disables any further processing. */
3250 return false;
3252 case 'n':
3253 /* %n has side-effects even when nothing is actually printed to
3254 any buffer. */
3255 info.nowrite = false;
3256 dir.fmtfunc = format_none;
3257 break;
3259 case 'C':
3260 case 'c':
3261 /* POSIX wide character and C/POSIX narrow character. */
3262 dir.fmtfunc = format_character;
3263 break;
3265 case 'S':
3266 case 's':
3267 /* POSIX wide string and C/POSIX narrow character string. */
3268 dir.fmtfunc = format_string;
3269 break;
3271 default:
3272 /* Unknown conversion specification. */
3273 return 0;
3276 dir.specifier = target_to_host (*pf++);
3278 /* Store the length of the format directive. */
3279 dir.len = pf - pcnt;
3281 /* Buffer for the directive in the host character set (used when
3282 the source character set is different). */
3283 char hostdir[32];
3285 if (star_width)
3287 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3288 dir.set_width (star_width, vr_values);
3289 else
3291 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3292 (width is the absolute value of that specified). */
3293 dir.width[0] = 0;
3294 dir.width[1] = target_int_max () + 1;
3297 else
3299 if (width == LONG_MAX && werange)
3301 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3302 size_t caret = begin + (werange - pcnt);
3303 size_t end = pf - info.fmtstr - 1;
3305 /* Create a location for the width part of the directive,
3306 pointing the caret at the first out-of-range digit. */
3307 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3308 caret, begin, end);
3310 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3311 "%<%.*s%> directive width out of range", (int) dir.len,
3312 target_to_host (hostdir, sizeof hostdir, dir.beg));
3315 dir.set_width (width);
3318 if (star_precision)
3320 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3321 dir.set_precision (star_precision, vr_values);
3322 else
3324 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3325 (unlike width, negative precision is ignored). */
3326 dir.prec[0] = -1;
3327 dir.prec[1] = target_int_max ();
3330 else
3332 if (precision == LONG_MAX && perange)
3334 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3335 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3336 size_t end = pf - info.fmtstr - 2;
3338 /* Create a location for the precision part of the directive,
3339 including the leading period, pointing the caret at the first
3340 out-of-range digit . */
3341 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3342 caret, begin, end);
3344 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3345 "%<%.*s%> directive precision out of range", (int) dir.len,
3346 target_to_host (hostdir, sizeof hostdir, dir.beg));
3349 dir.set_precision (precision);
3352 /* Extract the argument if the directive takes one and if it's
3353 available (e.g., the function doesn't take a va_list). Treat
3354 missing arguments the same as va_list, even though they will
3355 have likely already been diagnosed by -Wformat. */
3356 if (dir.specifier != '%'
3357 && *argno < gimple_call_num_args (info.callstmt))
3358 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3360 if (dump_file)
3362 fprintf (dump_file,
3363 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3364 ": \"%.*s\"",
3365 dir.dirno,
3366 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3367 (int)dir.len, dir.beg);
3368 if (star_width)
3370 if (dir.width[0] == dir.width[1])
3371 fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
3372 dir.width[0]);
3373 else
3374 fprintf (dump_file,
3375 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3376 ", " HOST_WIDE_INT_PRINT_DEC "]",
3377 dir.width[0], dir.width[1]);
3380 if (star_precision)
3382 if (dir.prec[0] == dir.prec[1])
3383 fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
3384 dir.prec[0]);
3385 else
3386 fprintf (dump_file,
3387 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3388 HOST_WIDE_INT_PRINT_DEC "]",
3389 dir.prec[0], dir.prec[1]);
3391 fputc ('\n', dump_file);
3394 return dir.len;
3397 /* Compute the length of the output resulting from the call to a formatted
3398 output function described by INFO and store the result of the call in
3399 *RES. Issue warnings for detected past the end writes. Return true
3400 if the complete format string has been processed and *RES can be relied
3401 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3402 that caused the processing to be terminated early). */
3404 bool
3405 sprintf_dom_walker::compute_format_length (call_info &info,
3406 format_result *res)
3408 if (dump_file)
3410 location_t callloc = gimple_location (info.callstmt);
3411 fprintf (dump_file, "%s:%i: ",
3412 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3413 print_generic_expr (dump_file, info.func, dump_flags);
3415 fprintf (dump_file,
3416 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3417 ", fmtstr = \"%s\"\n",
3418 info.objsize, info.fmtstr);
3421 /* Reset the minimum and maximum byte counters. */
3422 res->range.min = res->range.max = 0;
3424 /* No directive has been seen yet so the length of output is bounded
3425 by the known range [0, 0] (with no conversion resulting in a failure
3426 or producing more than 4K bytes) until determined otherwise. */
3427 res->knownrange = true;
3428 res->posunder4k = true;
3429 res->floating = false;
3430 res->warned = false;
3432 /* 1-based directive counter. */
3433 unsigned dirno = 1;
3435 /* The variadic argument counter. */
3436 unsigned argno = info.argidx;
3438 for (const char *pf = info.fmtstr; ; ++dirno)
3440 directive dir = directive ();
3441 dir.dirno = dirno;
3443 size_t n = parse_directive (info, dir, res, pf, &argno,
3444 evrp_range_analyzer.get_vr_values ());
3446 /* Return failure if the format function fails. */
3447 if (!format_directive (info, res, dir,
3448 evrp_range_analyzer.get_vr_values ()))
3449 return false;
3451 /* Return success the directive is zero bytes long and it's
3452 the last think in the format string (i.e., it's the terminating
3453 nul, which isn't really a directive but handling it as one makes
3454 things simpler). */
3455 if (!n)
3456 return *pf == '\0';
3458 pf += n;
3461 /* The complete format string was processed (with or without warnings). */
3462 return true;
3465 /* Return the size of the object referenced by the expression DEST if
3466 available, or -1 otherwise. */
3468 static unsigned HOST_WIDE_INT
3469 get_destination_size (tree dest)
3471 /* Initialize object size info before trying to compute it. */
3472 init_object_sizes ();
3474 /* Use __builtin_object_size to determine the size of the destination
3475 object. When optimizing, determine the smallest object (such as
3476 a member array as opposed to the whole enclosing object), otherwise
3477 use type-zero object size to determine the size of the enclosing
3478 object (the function fails without optimization in this type). */
3479 int ost = optimize > 0;
3480 unsigned HOST_WIDE_INT size;
3481 if (compute_builtin_object_size (dest, ost, &size))
3482 return size;
3484 return HOST_WIDE_INT_M1U;
3487 /* Return true if the call described by INFO with result RES safe to
3488 optimize (i.e., no undefined behavior), and set RETVAL to the range
3489 of its return values. */
3491 static bool
3492 is_call_safe (const sprintf_dom_walker::call_info &info,
3493 const format_result &res, bool under4k,
3494 unsigned HOST_WIDE_INT retval[2])
3496 if (under4k && !res.posunder4k)
3497 return false;
3499 /* The minimum return value. */
3500 retval[0] = res.range.min;
3502 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3503 but in cases involving multibyte characters could be as large as
3504 RES.RANGE.UNLIKELY. */
3505 retval[1]
3506 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3508 /* Adjust the number of bytes which includes the terminating nul
3509 to reflect the return value of the function which does not.
3510 Because the valid range of the function is [INT_MIN, INT_MAX],
3511 a valid range before the adjustment below is [0, INT_MAX + 1]
3512 (the functions only return negative values on error or undefined
3513 behavior). */
3514 if (retval[0] <= target_int_max () + 1)
3515 --retval[0];
3516 if (retval[1] <= target_int_max () + 1)
3517 --retval[1];
3519 /* Avoid the return value optimization when the behavior of the call
3520 is undefined either because any directive may have produced 4K or
3521 more of output, or the return value exceeds INT_MAX, or because
3522 the output overflows the destination object (but leave it enabled
3523 when the function is bounded because then the behavior is well-
3524 defined). */
3525 if (retval[0] == retval[1]
3526 && (info.bounded || retval[0] < info.objsize)
3527 && retval[0] <= target_int_max ())
3528 return true;
3530 if ((info.bounded || retval[1] < info.objsize)
3531 && (retval[0] < target_int_max ()
3532 && retval[1] < target_int_max ()))
3533 return true;
3535 if (!under4k && (info.bounded || retval[0] < info.objsize))
3536 return true;
3538 return false;
3541 /* Given a suitable result RES of a call to a formatted output function
3542 described by INFO, substitute the result for the return value of
3543 the call. The result is suitable if the number of bytes it represents
3544 is known and exact. A result that isn't suitable for substitution may
3545 have its range set to the range of return values, if that is known.
3546 Return true if the call is removed and gsi_next should not be performed
3547 in the caller. */
3549 static bool
3550 try_substitute_return_value (gimple_stmt_iterator *gsi,
3551 const sprintf_dom_walker::call_info &info,
3552 const format_result &res)
3554 tree lhs = gimple_get_lhs (info.callstmt);
3556 /* Set to true when the entire call has been removed. */
3557 bool removed = false;
3559 /* The minimum and maximum return value. */
3560 unsigned HOST_WIDE_INT retval[2];
3561 bool safe = is_call_safe (info, res, true, retval);
3563 if (safe
3564 && retval[0] == retval[1]
3565 /* Not prepared to handle possibly throwing calls here; they shouldn't
3566 appear in non-artificial testcases, except when the __*_chk routines
3567 are badly declared. */
3568 && !stmt_ends_bb_p (info.callstmt))
3570 tree cst = build_int_cst (integer_type_node, retval[0]);
3572 if (lhs == NULL_TREE
3573 && info.nowrite)
3575 /* Remove the call to the bounded function with a zero size
3576 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3577 unlink_stmt_vdef (info.callstmt);
3578 gsi_remove (gsi, true);
3579 removed = true;
3581 else if (info.nowrite)
3583 /* Replace the call to the bounded function with a zero size
3584 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3585 of the function. */
3586 if (!update_call_from_tree (gsi, cst))
3587 gimplify_and_update_call_from_tree (gsi, cst);
3588 gimple *callstmt = gsi_stmt (*gsi);
3589 update_stmt (callstmt);
3591 else if (lhs)
3593 /* Replace the left-hand side of the call with the constant
3594 result of the formatted function. */
3595 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3596 gimple *g = gimple_build_assign (lhs, cst);
3597 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3598 update_stmt (info.callstmt);
3601 if (dump_file)
3603 if (removed)
3604 fprintf (dump_file, " Removing call statement.");
3605 else
3607 fprintf (dump_file, " Substituting ");
3608 print_generic_expr (dump_file, cst, dump_flags);
3609 fprintf (dump_file, " for %s.\n",
3610 info.nowrite ? "statement" : "return value");
3614 else if (lhs)
3616 bool setrange = false;
3618 if (safe
3619 && (info.bounded || retval[1] < info.objsize)
3620 && (retval[0] < target_int_max ()
3621 && retval[1] < target_int_max ()))
3623 /* If the result is in a valid range bounded by the size of
3624 the destination set it so that it can be used for subsequent
3625 optimizations. */
3626 int prec = TYPE_PRECISION (integer_type_node);
3628 wide_int min = wi::shwi (retval[0], prec);
3629 wide_int max = wi::shwi (retval[1], prec);
3630 set_range_info (lhs, VR_RANGE, min, max);
3632 setrange = true;
3635 if (dump_file)
3637 const char *inbounds
3638 = (retval[0] < info.objsize
3639 ? (retval[1] < info.objsize
3640 ? "in" : "potentially out-of")
3641 : "out-of");
3643 const char *what = setrange ? "Setting" : "Discarding";
3644 if (retval[0] != retval[1])
3645 fprintf (dump_file,
3646 " %s %s-bounds return value range ["
3647 HOST_WIDE_INT_PRINT_UNSIGNED ", "
3648 HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
3649 what, inbounds, retval[0], retval[1]);
3650 else
3651 fprintf (dump_file, " %s %s-bounds return value "
3652 HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
3653 what, inbounds, retval[0]);
3657 if (dump_file)
3658 fputc ('\n', dump_file);
3660 return removed;
3663 /* Try to simplify a s{,n}printf call described by INFO with result
3664 RES by replacing it with a simpler and presumably more efficient
3665 call (such as strcpy). */
3667 static bool
3668 try_simplify_call (gimple_stmt_iterator *gsi,
3669 const sprintf_dom_walker::call_info &info,
3670 const format_result &res)
3672 unsigned HOST_WIDE_INT dummy[2];
3673 if (!is_call_safe (info, res, info.retval_used (), dummy))
3674 return false;
3676 switch (info.fncode)
3678 case BUILT_IN_SNPRINTF:
3679 return gimple_fold_builtin_snprintf (gsi);
3681 case BUILT_IN_SPRINTF:
3682 return gimple_fold_builtin_sprintf (gsi);
3684 default:
3688 return false;
3691 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3692 functions and if so, handle it. Return true if the call is removed
3693 and gsi_next should not be performed in the caller. */
3695 bool
3696 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3698 call_info info = call_info ();
3700 info.callstmt = gsi_stmt (*gsi);
3701 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3702 return false;
3704 info.func = gimple_call_fndecl (info.callstmt);
3705 info.fncode = DECL_FUNCTION_CODE (info.func);
3707 /* The size of the destination as in snprintf(dest, size, ...). */
3708 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3710 /* The size of the destination determined by __builtin_object_size. */
3711 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3713 /* Buffer size argument number (snprintf and vsnprintf). */
3714 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3716 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3717 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3719 /* Format string argument number (valid for all functions). */
3720 unsigned idx_format;
3722 switch (info.fncode)
3724 case BUILT_IN_SPRINTF:
3725 // Signature:
3726 // __builtin_sprintf (dst, format, ...)
3727 idx_format = 1;
3728 info.argidx = 2;
3729 break;
3731 case BUILT_IN_SPRINTF_CHK:
3732 // Signature:
3733 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3734 idx_objsize = 2;
3735 idx_format = 3;
3736 info.argidx = 4;
3737 break;
3739 case BUILT_IN_SNPRINTF:
3740 // Signature:
3741 // __builtin_snprintf (dst, size, format, ...)
3742 idx_dstsize = 1;
3743 idx_format = 2;
3744 info.argidx = 3;
3745 info.bounded = true;
3746 break;
3748 case BUILT_IN_SNPRINTF_CHK:
3749 // Signature:
3750 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3751 idx_dstsize = 1;
3752 idx_objsize = 3;
3753 idx_format = 4;
3754 info.argidx = 5;
3755 info.bounded = true;
3756 break;
3758 case BUILT_IN_VSNPRINTF:
3759 // Signature:
3760 // __builtin_vsprintf (dst, size, format, va)
3761 idx_dstsize = 1;
3762 idx_format = 2;
3763 info.argidx = -1;
3764 info.bounded = true;
3765 break;
3767 case BUILT_IN_VSNPRINTF_CHK:
3768 // Signature:
3769 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3770 idx_dstsize = 1;
3771 idx_objsize = 3;
3772 idx_format = 4;
3773 info.argidx = -1;
3774 info.bounded = true;
3775 break;
3777 case BUILT_IN_VSPRINTF:
3778 // Signature:
3779 // __builtin_vsprintf (dst, format, va)
3780 idx_format = 1;
3781 info.argidx = -1;
3782 break;
3784 case BUILT_IN_VSPRINTF_CHK:
3785 // Signature:
3786 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3787 idx_format = 3;
3788 idx_objsize = 2;
3789 info.argidx = -1;
3790 break;
3792 default:
3793 return false;
3796 /* Set the global warning level for this function. */
3797 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3799 /* The first argument is a pointer to the destination. */
3800 tree dstptr = gimple_call_arg (info.callstmt, 0);
3802 info.format = gimple_call_arg (info.callstmt, idx_format);
3804 /* True when the destination size is constant as opposed to the lower
3805 or upper bound of a range. */
3806 bool dstsize_cst_p = true;
3808 if (idx_dstsize == HOST_WIDE_INT_M1U)
3810 /* For non-bounded functions like sprintf, determine the size
3811 of the destination from the object or pointer passed to it
3812 as the first argument. */
3813 dstsize = get_destination_size (dstptr);
3815 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3817 /* For bounded functions try to get the size argument. */
3819 if (TREE_CODE (size) == INTEGER_CST)
3821 dstsize = tree_to_uhwi (size);
3822 /* No object can be larger than SIZE_MAX bytes (half the address
3823 space) on the target.
3824 The functions are defined only for output of at most INT_MAX
3825 bytes. Specifying a bound in excess of that limit effectively
3826 defeats the bounds checking (and on some implementations such
3827 as Solaris cause the function to fail with EINVAL). */
3828 if (dstsize > target_size_max () / 2)
3830 /* Avoid warning if -Wstringop-overflow is specified since
3831 it also warns for the same thing though only for the
3832 checking built-ins. */
3833 if ((idx_objsize == HOST_WIDE_INT_M1U
3834 || !warn_stringop_overflow))
3835 warning_at (gimple_location (info.callstmt), info.warnopt (),
3836 "specified bound %wu exceeds maximum object size "
3837 "%wu",
3838 dstsize, target_size_max () / 2);
3840 else if (dstsize > target_int_max ())
3841 warning_at (gimple_location (info.callstmt), info.warnopt (),
3842 "specified bound %wu exceeds %<INT_MAX%>",
3843 dstsize);
3845 else if (TREE_CODE (size) == SSA_NAME)
3847 /* Try to determine the range of values of the argument
3848 and use the greater of the two at level 1 and the smaller
3849 of them at level 2. */
3850 value_range *vr = evrp_range_analyzer.get_value_range (size);
3851 if (vr->type == VR_RANGE
3852 && TREE_CODE (vr->min) == INTEGER_CST
3853 && TREE_CODE (vr->max) == INTEGER_CST)
3854 dstsize = (warn_level < 2
3855 ? TREE_INT_CST_LOW (vr->max)
3856 : TREE_INT_CST_LOW (vr->min));
3858 /* The destination size is not constant. If the function is
3859 bounded (e.g., snprintf) a lower bound of zero doesn't
3860 necessarily imply it can be eliminated. */
3861 dstsize_cst_p = false;
3865 if (idx_objsize != HOST_WIDE_INT_M1U)
3866 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3867 if (tree_fits_uhwi_p (size))
3868 objsize = tree_to_uhwi (size);
3870 if (info.bounded && !dstsize)
3872 /* As a special case, when the explicitly specified destination
3873 size argument (to a bounded function like snprintf) is zero
3874 it is a request to determine the number of bytes on output
3875 without actually producing any. Pretend the size is
3876 unlimited in this case. */
3877 info.objsize = HOST_WIDE_INT_MAX;
3878 info.nowrite = dstsize_cst_p;
3880 else
3882 /* For calls to non-bounded functions or to those of bounded
3883 functions with a non-zero size, warn if the destination
3884 pointer is null. */
3885 if (integer_zerop (dstptr))
3887 /* This is diagnosed with -Wformat only when the null is a constant
3888 pointer. The warning here diagnoses instances where the pointer
3889 is not constant. */
3890 location_t loc = gimple_location (info.callstmt);
3891 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3892 info.warnopt (), "null destination pointer");
3893 return false;
3896 /* Set the object size to the smaller of the two arguments
3897 of both have been specified and they're not equal. */
3898 info.objsize = dstsize < objsize ? dstsize : objsize;
3900 if (info.bounded
3901 && dstsize < target_size_max () / 2 && objsize < dstsize
3902 /* Avoid warning if -Wstringop-overflow is specified since
3903 it also warns for the same thing though only for the
3904 checking built-ins. */
3905 && (idx_objsize == HOST_WIDE_INT_M1U
3906 || !warn_stringop_overflow))
3908 warning_at (gimple_location (info.callstmt), info.warnopt (),
3909 "specified bound %wu exceeds the size %wu "
3910 "of the destination object", dstsize, objsize);
3914 if (integer_zerop (info.format))
3916 /* This is diagnosed with -Wformat only when the null is a constant
3917 pointer. The warning here diagnoses instances where the pointer
3918 is not constant. */
3919 location_t loc = gimple_location (info.callstmt);
3920 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3921 info.warnopt (), "null format string");
3922 return false;
3925 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3926 if (!info.fmtstr)
3927 return false;
3929 /* The result is the number of bytes output by the formatted function,
3930 including the terminating NUL. */
3931 format_result res = format_result ();
3933 bool success = compute_format_length (info, &res);
3935 /* When optimizing and the printf return value optimization is enabled,
3936 attempt to substitute the computed result for the return value of
3937 the call. Avoid this optimization when -frounding-math is in effect
3938 and the format string contains a floating point directive. */
3939 bool call_removed = false;
3940 if (success && optimize > 0)
3942 /* Save a copy of the iterator pointing at the call. The iterator
3943 may change to point past the call in try_substitute_return_value
3944 but the original value is needed in try_simplify_call. */
3945 gimple_stmt_iterator gsi_call = *gsi;
3947 if (flag_printf_return_value
3948 && (!flag_rounding_math || !res.floating))
3949 call_removed = try_substitute_return_value (gsi, info, res);
3951 if (!call_removed)
3952 try_simplify_call (&gsi_call, info, res);
3955 return call_removed;
3958 edge
3959 sprintf_dom_walker::before_dom_children (basic_block bb)
3961 evrp_range_analyzer.enter (bb);
3962 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
3964 /* Iterate over statements, looking for function calls. */
3965 gimple *stmt = gsi_stmt (si);
3967 /* First record ranges generated by this statement. */
3968 evrp_range_analyzer.record_ranges_from_stmt (stmt, false);
3970 if (is_gimple_call (stmt) && handle_gimple_call (&si))
3971 /* If handle_gimple_call returns true, the iterator is
3972 already pointing to the next statement. */
3973 continue;
3975 gsi_next (&si);
3977 return NULL;
3980 void
3981 sprintf_dom_walker::after_dom_children (basic_block bb)
3983 evrp_range_analyzer.leave (bb);
3986 /* Execute the pass for function FUN. */
3988 unsigned int
3989 pass_sprintf_length::execute (function *fun)
3991 init_target_to_host_charmap ();
3993 calculate_dominance_info (CDI_DOMINATORS);
3995 sprintf_dom_walker sprintf_dom_walker;
3996 sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
3998 /* Clean up object size info. */
3999 fini_object_sizes ();
4000 return 0;
4003 } /* Unnamed namespace. */
4005 /* Return a pointer to a pass object newly constructed from the context
4006 CTXT. */
4008 gimple_opt_pass *
4009 make_pass_sprintf_length (gcc::context *ctxt)
4011 return new pass_sprintf_length (ctxt);