substring-locations: add class format_string_diagnostic_t
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob9b6f6e6019251a01e8190d9f15074f4072d2fc01
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_string_diagnostic_t::emit_warning_va and
459 format_string_diagnostic_t::emit_warning_n_va.
460 These have to be functions with the attribute so that exgettext
461 works properly. */
463 static bool
464 ATTRIBUTE_GCC_DIAG (5, 6)
465 fmtwarn (const substring_loc &fmt_loc, location_t param_loc,
466 const char *corrected_substring, int opt, const char *gmsgid, ...)
468 format_string_diagnostic_t diag (fmt_loc, NULL, param_loc, NULL,
469 corrected_substring);
470 va_list ap;
471 va_start (ap, gmsgid);
472 bool warned = diag.emit_warning_va (opt, gmsgid, &ap);
473 va_end (ap);
475 return warned;
478 static bool
479 ATTRIBUTE_GCC_DIAG (6, 8) ATTRIBUTE_GCC_DIAG (7, 8)
480 fmtwarn_n (const substring_loc &fmt_loc, location_t param_loc,
481 const char *corrected_substring, int opt, unsigned HOST_WIDE_INT n,
482 const char *singular_gmsgid, const char *plural_gmsgid, ...)
484 format_string_diagnostic_t diag (fmt_loc, NULL, param_loc, NULL,
485 corrected_substring);
486 va_list ap;
487 va_start (ap, plural_gmsgid);
488 bool warned = diag.emit_warning_n_va (opt, n, singular_gmsgid, plural_gmsgid,
489 &ap);
490 va_end (ap);
492 return warned;
495 /* Format length modifiers. */
497 enum format_lengths
499 FMT_LEN_none,
500 FMT_LEN_hh, // char argument
501 FMT_LEN_h, // short
502 FMT_LEN_l, // long
503 FMT_LEN_ll, // long long
504 FMT_LEN_L, // long double (and GNU long long)
505 FMT_LEN_z, // size_t
506 FMT_LEN_t, // ptrdiff_t
507 FMT_LEN_j // intmax_t
511 /* Description of the result of conversion either of a single directive
512 or the whole format string. */
514 struct fmtresult
516 /* Construct a FMTRESULT object with all counters initialized
517 to MIN. KNOWNRANGE is set when MIN is valid. */
518 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
519 : argmin (), argmax (),
520 knownrange (min < HOST_WIDE_INT_MAX),
521 mayfail (), nullp ()
523 range.min = min;
524 range.max = min;
525 range.likely = min;
526 range.unlikely = min;
529 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
530 KNOWNRANGE is set when both MIN and MAX are valid. */
531 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
532 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
533 : argmin (), argmax (),
534 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
535 mayfail (), nullp ()
537 range.min = min;
538 range.max = max;
539 range.likely = max < likely ? min : likely;
540 range.unlikely = max;
543 /* Adjust result upward to reflect the RANGE of values the specified
544 width or precision is known to be in. */
545 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
546 tree = NULL_TREE,
547 unsigned = 0, unsigned = 0);
549 /* Return the maximum number of decimal digits a value of TYPE
550 formats as on output. */
551 static unsigned type_max_digits (tree, int);
553 /* The range a directive's argument is in. */
554 tree argmin, argmax;
556 /* The minimum and maximum number of bytes that a directive
557 results in on output for an argument in the range above. */
558 result_range range;
560 /* True when the range above is obtained from a known value of
561 a directive's argument or its bounds and not the result of
562 heuristics that depend on warning levels. */
563 bool knownrange;
565 /* True for a directive that may fail (such as wide character
566 directives). */
567 bool mayfail;
569 /* True when the argument is a null pointer. */
570 bool nullp;
573 /* Adjust result upward to reflect the range ADJUST of values the
574 specified width or precision is known to be in. When non-null,
575 TYPE denotes the type of the directive whose result is being
576 adjusted, BASE gives the base of the directive (octal, decimal,
577 or hex), and ADJ denotes the additional adjustment to the LIKELY
578 counter that may need to be added when ADJUST is a range. */
580 fmtresult&
581 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
582 tree type /* = NULL_TREE */,
583 unsigned base /* = 0 */,
584 unsigned adj /* = 0 */)
586 bool minadjusted = false;
588 /* Adjust the minimum and likely counters. */
589 if (adjust[0] >= 0)
591 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
593 range.min = adjust[0];
594 minadjusted = true;
597 /* Adjust the likely counter. */
598 if (range.likely < range.min)
599 range.likely = range.min;
601 else if (adjust[0] == target_int_min ()
602 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
603 knownrange = false;
605 /* Adjust the maximum counter. */
606 if (adjust[1] > 0)
608 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
610 range.max = adjust[1];
612 /* Set KNOWNRANGE if both the minimum and maximum have been
613 adjusted. Otherwise leave it at what it was before. */
614 knownrange = minadjusted;
618 if (warn_level > 1 && type)
620 /* For large non-constant width or precision whose range spans
621 the maximum number of digits produced by the directive for
622 any argument, set the likely number of bytes to be at most
623 the number digits plus other adjustment determined by the
624 caller (one for sign or two for the hexadecimal "0x"
625 prefix). */
626 unsigned dirdigs = type_max_digits (type, base);
627 if (adjust[0] < dirdigs && dirdigs < adjust[1]
628 && range.likely < dirdigs)
629 range.likely = dirdigs + adj;
631 else if (range.likely < (range.min ? range.min : 1))
633 /* Conservatively, set LIKELY to at least MIN but no less than
634 1 unless MAX is zero. */
635 range.likely = (range.min
636 ? range.min
637 : range.max && (range.max < HOST_WIDE_INT_MAX
638 || warn_level > 1) ? 1 : 0);
641 /* Finally adjust the unlikely counter to be at least as large as
642 the maximum. */
643 if (range.unlikely < range.max)
644 range.unlikely = range.max;
646 return *this;
649 /* Return the maximum number of digits a value of TYPE formats in
650 BASE on output, not counting base prefix . */
652 unsigned
653 fmtresult::type_max_digits (tree type, int base)
655 unsigned prec = TYPE_PRECISION (type);
656 switch (base)
658 case 8:
659 return (prec + 2) / 3;
660 case 10:
661 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
662 of 8, 16, 32, and 64 bits. */
663 return prec * 301 / 1000 + 1;
664 case 16:
665 return prec / 4;
668 gcc_unreachable ();
671 static bool
672 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT,
673 class vr_values *vr_values);
675 /* Description of a format directive. A directive is either a plain
676 string or a conversion specification that starts with '%'. */
678 struct directive
680 /* The 1-based directive number (for debugging). */
681 unsigned dirno;
683 /* The first character of the directive and its length. */
684 const char *beg;
685 size_t len;
687 /* A bitmap of flags, one for each character. */
688 unsigned flags[256 / sizeof (int)];
690 /* The range of values of the specified width, or -1 if not specified. */
691 HOST_WIDE_INT width[2];
692 /* The range of values of the specified precision, or -1 if not
693 specified. */
694 HOST_WIDE_INT prec[2];
696 /* Length modifier. */
697 format_lengths modifier;
699 /* Format specifier character. */
700 char specifier;
702 /* The argument of the directive or null when the directive doesn't
703 take one or when none is available (such as for vararg functions). */
704 tree arg;
706 /* Format conversion function that given a directive and an argument
707 returns the formatting result. */
708 fmtresult (*fmtfunc) (const directive &, tree, vr_values *);
710 /* Return True when a the format flag CHR has been used. */
711 bool get_flag (char chr) const
713 unsigned char c = chr & 0xff;
714 return (flags[c / (CHAR_BIT * sizeof *flags)]
715 & (1U << (c % (CHAR_BIT * sizeof *flags))));
718 /* Make a record of the format flag CHR having been used. */
719 void set_flag (char chr)
721 unsigned char c = chr & 0xff;
722 flags[c / (CHAR_BIT * sizeof *flags)]
723 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
726 /* Reset the format flag CHR. */
727 void clear_flag (char chr)
729 unsigned char c = chr & 0xff;
730 flags[c / (CHAR_BIT * sizeof *flags)]
731 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
734 /* Set both bounds of the width range to VAL. */
735 void set_width (HOST_WIDE_INT val)
737 width[0] = width[1] = val;
740 /* Set the width range according to ARG, with both bounds being
741 no less than 0. For a constant ARG set both bounds to its value
742 or 0, whichever is greater. For a non-constant ARG in some range
743 set width to its range adjusting each bound to -1 if it's less.
744 For an indeterminate ARG set width to [0, INT_MAX]. */
745 void set_width (tree arg, vr_values *vr_values)
747 get_int_range (arg, width, width + 1, true, 0, vr_values);
750 /* Set both bounds of the precision range to VAL. */
751 void set_precision (HOST_WIDE_INT val)
753 prec[0] = prec[1] = val;
756 /* Set the precision range according to ARG, with both bounds being
757 no less than -1. For a constant ARG set both bounds to its value
758 or -1 whichever is greater. For a non-constant ARG in some range
759 set precision to its range adjusting each bound to -1 if it's less.
760 For an indeterminate ARG set precision to [-1, INT_MAX]. */
761 void set_precision (tree arg, vr_values *vr_values)
763 get_int_range (arg, prec, prec + 1, false, -1, vr_values);
766 /* Return true if both width and precision are known to be
767 either constant or in some range, false otherwise. */
768 bool known_width_and_precision () const
770 return ((width[1] < 0
771 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
772 && (prec[1] < 0
773 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
777 /* Return the logarithm of X in BASE. */
779 static int
780 ilog (unsigned HOST_WIDE_INT x, int base)
782 int res = 0;
785 ++res;
786 x /= base;
787 } while (x);
788 return res;
791 /* Return the number of bytes resulting from converting into a string
792 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
793 PLUS indicates whether 1 for a plus sign should be added for positive
794 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
795 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
796 be represented. */
798 static HOST_WIDE_INT
799 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
801 unsigned HOST_WIDE_INT absval;
803 HOST_WIDE_INT res;
805 if (TYPE_UNSIGNED (TREE_TYPE (x)))
807 if (tree_fits_uhwi_p (x))
809 absval = tree_to_uhwi (x);
810 res = plus;
812 else
813 return -1;
815 else
817 if (tree_fits_shwi_p (x))
819 HOST_WIDE_INT i = tree_to_shwi (x);
820 if (HOST_WIDE_INT_MIN == i)
822 /* Avoid undefined behavior due to negating a minimum. */
823 absval = HOST_WIDE_INT_MAX;
824 res = 1;
826 else if (i < 0)
828 absval = -i;
829 res = 1;
831 else
833 absval = i;
834 res = plus;
837 else
838 return -1;
841 int ndigs = ilog (absval, base);
843 res += prec < ndigs ? ndigs : prec;
845 /* Adjust a non-zero value for the base prefix, either hexadecimal,
846 or, unless precision has resulted in a leading zero, also octal. */
847 if (prefix && absval && (base == 16 || prec <= ndigs))
849 if (base == 8)
850 res += 1;
851 else if (base == 16)
852 res += 2;
855 return res;
858 /* Given the formatting result described by RES and NAVAIL, the number
859 of available in the destination, return the range of bytes remaining
860 in the destination. */
862 static inline result_range
863 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
865 result_range range;
867 if (HOST_WIDE_INT_MAX <= navail)
869 range.min = range.max = range.likely = range.unlikely = navail;
870 return range;
873 /* The lower bound of the available range is the available size
874 minus the maximum output size, and the upper bound is the size
875 minus the minimum. */
876 range.max = res.range.min < navail ? navail - res.range.min : 0;
878 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
880 if (res.range.max < HOST_WIDE_INT_MAX)
881 range.min = res.range.max < navail ? navail - res.range.max : 0;
882 else
883 range.min = range.likely;
885 range.unlikely = (res.range.unlikely < navail
886 ? navail - res.range.unlikely : 0);
888 return range;
891 /* Description of a call to a formatted function. */
893 struct sprintf_dom_walker::call_info
895 /* Function call statement. */
896 gimple *callstmt;
898 /* Function called. */
899 tree func;
901 /* Called built-in function code. */
902 built_in_function fncode;
904 /* Format argument and format string extracted from it. */
905 tree format;
906 const char *fmtstr;
908 /* The location of the format argument. */
909 location_t fmtloc;
911 /* The destination object size for __builtin___xxx_chk functions
912 typically determined by __builtin_object_size, or -1 if unknown. */
913 unsigned HOST_WIDE_INT objsize;
915 /* Number of the first variable argument. */
916 unsigned HOST_WIDE_INT argidx;
918 /* True for functions like snprintf that specify the size of
919 the destination, false for others like sprintf that don't. */
920 bool bounded;
922 /* True for bounded functions like snprintf that specify a zero-size
923 buffer as a request to compute the size of output without actually
924 writing any. NOWRITE is cleared in response to the %n directive
925 which has side-effects similar to writing output. */
926 bool nowrite;
928 /* Return true if the called function's return value is used. */
929 bool retval_used () const
931 return gimple_get_lhs (callstmt);
934 /* Return the warning option corresponding to the called function. */
935 int warnopt () const
937 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
941 /* Return the result of formatting a no-op directive (such as '%n'). */
943 static fmtresult
944 format_none (const directive &, tree, vr_values *)
946 fmtresult res (0);
947 return res;
950 /* Return the result of formatting the '%%' directive. */
952 static fmtresult
953 format_percent (const directive &, tree, vr_values *)
955 fmtresult res (1);
956 return res;
960 /* Compute intmax_type_node and uintmax_type_node similarly to how
961 tree.c builds size_type_node. */
963 static void
964 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
966 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
968 *pintmax = integer_type_node;
969 *puintmax = unsigned_type_node;
971 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
973 *pintmax = long_integer_type_node;
974 *puintmax = long_unsigned_type_node;
976 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
978 *pintmax = long_long_integer_type_node;
979 *puintmax = long_long_unsigned_type_node;
981 else
983 for (int i = 0; i < NUM_INT_N_ENTS; i++)
984 if (int_n_enabled_p[i])
986 char name[50];
987 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
989 if (strcmp (name, UINTMAX_TYPE) == 0)
991 *pintmax = int_n_trees[i].signed_type;
992 *puintmax = int_n_trees[i].unsigned_type;
993 return;
996 gcc_unreachable ();
1000 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1001 in and that is representable in type int.
1002 Return true when the range is a subrange of that of int.
1003 When ARG is null it is as if it had the full range of int.
1004 When ABSOLUTE is true the range reflects the absolute value of
1005 the argument. When ABSOLUTE is false, negative bounds of
1006 the determined range are replaced with NEGBOUND. */
1008 static bool
1009 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1010 bool absolute, HOST_WIDE_INT negbound,
1011 class vr_values *vr_values)
1013 /* The type of the result. */
1014 const_tree type = integer_type_node;
1016 bool knownrange = false;
1018 if (!arg)
1020 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1021 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1023 else if (TREE_CODE (arg) == INTEGER_CST
1024 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1026 /* For a constant argument return its value adjusted as specified
1027 by NEGATIVE and NEGBOUND and return true to indicate that the
1028 result is known. */
1029 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1030 *pmax = *pmin;
1031 knownrange = true;
1033 else
1035 /* True if the argument's range cannot be determined. */
1036 bool unknown = true;
1038 tree argtype = TREE_TYPE (arg);
1040 /* Ignore invalid arguments with greater precision that that
1041 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1042 They will have been detected and diagnosed by -Wformat and
1043 so it's not important to complicate this code to try to deal
1044 with them again. */
1045 if (TREE_CODE (arg) == SSA_NAME
1046 && INTEGRAL_TYPE_P (argtype)
1047 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1049 /* Try to determine the range of values of the integer argument. */
1050 value_range *vr = vr_values->get_value_range (arg);
1051 if (vr->type == VR_RANGE
1052 && TREE_CODE (vr->min) == INTEGER_CST
1053 && TREE_CODE (vr->max) == INTEGER_CST)
1055 HOST_WIDE_INT type_min
1056 = (TYPE_UNSIGNED (argtype)
1057 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1058 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1060 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1062 *pmin = TREE_INT_CST_LOW (vr->min);
1063 *pmax = TREE_INT_CST_LOW (vr->max);
1065 if (*pmin < *pmax)
1067 /* Return true if the adjusted range is a subrange of
1068 the full range of the argument's type. *PMAX may
1069 be less than *PMIN when the argument is unsigned
1070 and its upper bound is in excess of TYPE_MAX. In
1071 that (invalid) case disregard the range and use that
1072 of the expected type instead. */
1073 knownrange = type_min < *pmin || *pmax < type_max;
1075 unknown = false;
1080 /* Handle an argument with an unknown range as if none had been
1081 provided. */
1082 if (unknown)
1083 return get_int_range (NULL_TREE, pmin, pmax, absolute,
1084 negbound, vr_values);
1087 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1088 if (absolute)
1090 if (*pmin < 0)
1092 if (*pmin == *pmax)
1093 *pmin = *pmax = -*pmin;
1094 else
1096 /* Make sure signed overlow is avoided. */
1097 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1099 HOST_WIDE_INT tmp = -*pmin;
1100 *pmin = 0;
1101 if (*pmax < tmp)
1102 *pmax = tmp;
1106 else if (*pmin < negbound)
1107 *pmin = negbound;
1109 return knownrange;
1112 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1113 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1114 the type of the directive's formal argument it's possible for both
1115 to result in the same number of bytes or a range of bytes that's
1116 less than the number of bytes that would result from formatting
1117 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1118 determined by checking for the actual argument being in the range
1119 of the type of the directive. If it isn't it must be assumed to
1120 take on the full range of the directive's type.
1121 Return true when the range has been adjusted to the full range
1122 of DIRTYPE, and false otherwise. */
1124 static bool
1125 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1127 tree argtype = TREE_TYPE (*argmin);
1128 unsigned argprec = TYPE_PRECISION (argtype);
1129 unsigned dirprec = TYPE_PRECISION (dirtype);
1131 /* If the actual argument and the directive's argument have the same
1132 precision and sign there can be no overflow and so there is nothing
1133 to adjust. */
1134 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1135 return false;
1137 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1138 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1140 if (TREE_CODE (*argmin) == INTEGER_CST
1141 && TREE_CODE (*argmax) == INTEGER_CST
1142 && (dirprec >= argprec
1143 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1144 int_const_binop (MINUS_EXPR,
1145 *argmax,
1146 *argmin),
1147 size_int (dirprec)))))
1149 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1150 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1152 /* If *ARGMIN is still less than *ARGMAX the conversion above
1153 is safe. Otherwise, it has overflowed and would be unsafe. */
1154 if (tree_int_cst_le (*argmin, *argmax))
1155 return false;
1158 *argmin = TYPE_MIN_VALUE (dirtype);
1159 *argmax = TYPE_MAX_VALUE (dirtype);
1160 return true;
1163 /* Return a range representing the minimum and maximum number of bytes
1164 that the format directive DIR will output for any argument given
1165 the WIDTH and PRECISION (extracted from DIR). This function is
1166 used when the directive argument or its value isn't known. */
1168 static fmtresult
1169 format_integer (const directive &dir, tree arg, vr_values *vr_values)
1171 tree intmax_type_node;
1172 tree uintmax_type_node;
1174 /* Base to format the number in. */
1175 int base;
1177 /* True when a conversion is preceded by a prefix indicating the base
1178 of the argument (octal or hexadecimal). */
1179 bool maybebase = dir.get_flag ('#');
1181 /* True when a signed conversion is preceded by a sign or space. */
1182 bool maybesign = false;
1184 /* True for signed conversions (i.e., 'd' and 'i'). */
1185 bool sign = false;
1187 switch (dir.specifier)
1189 case 'd':
1190 case 'i':
1191 /* Space and '+' are only meaningful for signed conversions. */
1192 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1193 sign = true;
1194 base = 10;
1195 break;
1196 case 'u':
1197 base = 10;
1198 break;
1199 case 'o':
1200 base = 8;
1201 break;
1202 case 'X':
1203 case 'x':
1204 base = 16;
1205 break;
1206 default:
1207 gcc_unreachable ();
1210 /* The type of the "formal" argument expected by the directive. */
1211 tree dirtype = NULL_TREE;
1213 /* Determine the expected type of the argument from the length
1214 modifier. */
1215 switch (dir.modifier)
1217 case FMT_LEN_none:
1218 if (dir.specifier == 'p')
1219 dirtype = ptr_type_node;
1220 else
1221 dirtype = sign ? integer_type_node : unsigned_type_node;
1222 break;
1224 case FMT_LEN_h:
1225 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1226 break;
1228 case FMT_LEN_hh:
1229 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1230 break;
1232 case FMT_LEN_l:
1233 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1234 break;
1236 case FMT_LEN_L:
1237 case FMT_LEN_ll:
1238 dirtype = (sign
1239 ? long_long_integer_type_node
1240 : long_long_unsigned_type_node);
1241 break;
1243 case FMT_LEN_z:
1244 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1245 break;
1247 case FMT_LEN_t:
1248 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1249 break;
1251 case FMT_LEN_j:
1252 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1253 dirtype = sign ? intmax_type_node : uintmax_type_node;
1254 break;
1256 default:
1257 return fmtresult ();
1260 /* The type of the argument to the directive, either deduced from
1261 the actual non-constant argument if one is known, or from
1262 the directive itself when none has been provided because it's
1263 a va_list. */
1264 tree argtype = NULL_TREE;
1266 if (!arg)
1268 /* When the argument has not been provided, use the type of
1269 the directive's argument as an approximation. This will
1270 result in false positives for directives like %i with
1271 arguments with smaller precision (such as short or char). */
1272 argtype = dirtype;
1274 else if (TREE_CODE (arg) == INTEGER_CST)
1276 /* When a constant argument has been provided use its value
1277 rather than type to determine the length of the output. */
1278 fmtresult res;
1280 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1282 /* As a special case, a precision of zero with a zero argument
1283 results in zero bytes except in base 8 when the '#' flag is
1284 specified, and for signed conversions in base 8 and 10 when
1285 either the space or '+' flag has been specified and it results
1286 in just one byte (with width having the normal effect). This
1287 must extend to the case of a specified precision with
1288 an unknown value because it can be zero. */
1289 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1290 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1292 res.range.max = 1;
1293 res.range.likely = 1;
1295 else
1297 res.range.max = res.range.min;
1298 res.range.likely = res.range.min;
1301 else
1303 /* Convert the argument to the type of the directive. */
1304 arg = fold_convert (dirtype, arg);
1306 res.range.min = tree_digits (arg, base, dir.prec[0],
1307 maybesign, maybebase);
1308 if (dir.prec[0] == dir.prec[1])
1309 res.range.max = res.range.min;
1310 else
1311 res.range.max = tree_digits (arg, base, dir.prec[1],
1312 maybesign, maybebase);
1313 res.range.likely = res.range.min;
1314 res.knownrange = true;
1317 res.range.unlikely = res.range.max;
1319 /* Bump up the counters if WIDTH is greater than LEN. */
1320 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1321 (sign | maybebase) + (base == 16));
1322 /* Bump up the counters again if PRECision is greater still. */
1323 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1324 (sign | maybebase) + (base == 16));
1326 return res;
1328 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1329 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1330 /* Determine the type of the provided non-constant argument. */
1331 argtype = TREE_TYPE (arg);
1332 else
1333 /* Don't bother with invalid arguments since they likely would
1334 have already been diagnosed, and disable any further checking
1335 of the format string by returning [-1, -1]. */
1336 return fmtresult ();
1338 fmtresult res;
1340 /* Using either the range the non-constant argument is in, or its
1341 type (either "formal" or actual), create a range of values that
1342 constrain the length of output given the warning level. */
1343 tree argmin = NULL_TREE;
1344 tree argmax = NULL_TREE;
1346 if (arg
1347 && TREE_CODE (arg) == SSA_NAME
1348 && INTEGRAL_TYPE_P (argtype))
1350 /* Try to determine the range of values of the integer argument
1351 (range information is not available for pointers). */
1352 value_range *vr = vr_values->get_value_range (arg);
1353 if (vr->type == VR_RANGE
1354 && TREE_CODE (vr->min) == INTEGER_CST
1355 && TREE_CODE (vr->max) == INTEGER_CST)
1357 argmin = vr->min;
1358 argmax = vr->max;
1360 /* Set KNOWNRANGE if the argument is in a known subrange
1361 of the directive's type and neither width nor precision
1362 is unknown. (KNOWNRANGE may be reset below). */
1363 res.knownrange
1364 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1365 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1366 && dir.known_width_and_precision ());
1368 res.argmin = argmin;
1369 res.argmax = argmax;
1371 else if (vr->type == VR_ANTI_RANGE)
1373 /* Handle anti-ranges if/when bug 71690 is resolved. */
1375 else if (vr->type == VR_VARYING
1376 || vr->type == VR_UNDEFINED)
1378 /* The argument here may be the result of promoting the actual
1379 argument to int. Try to determine the type of the actual
1380 argument before promotion and narrow down its range that
1381 way. */
1382 gimple *def = SSA_NAME_DEF_STMT (arg);
1383 if (is_gimple_assign (def))
1385 tree_code code = gimple_assign_rhs_code (def);
1386 if (code == INTEGER_CST)
1388 arg = gimple_assign_rhs1 (def);
1389 return format_integer (dir, arg, vr_values);
1392 if (code == NOP_EXPR)
1394 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1395 if (INTEGRAL_TYPE_P (type)
1396 || TREE_CODE (type) == POINTER_TYPE)
1397 argtype = type;
1403 if (!argmin)
1405 if (TREE_CODE (argtype) == POINTER_TYPE)
1407 argmin = build_int_cst (pointer_sized_int_node, 0);
1408 argmax = build_all_ones_cst (pointer_sized_int_node);
1410 else
1412 argmin = TYPE_MIN_VALUE (argtype);
1413 argmax = TYPE_MAX_VALUE (argtype);
1417 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1418 of the directive. If it has been cleared then since ARGMIN and/or
1419 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1420 ARGMAX in the result to include in diagnostics. */
1421 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1423 res.knownrange = false;
1424 res.argmin = argmin;
1425 res.argmax = argmax;
1428 /* Recursively compute the minimum and maximum from the known range. */
1429 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1431 /* For unsigned conversions/directives or signed when
1432 the minimum is positive, use the minimum and maximum to compute
1433 the shortest and longest output, respectively. */
1434 res.range.min = format_integer (dir, argmin, vr_values).range.min;
1435 res.range.max = format_integer (dir, argmax, vr_values).range.max;
1437 else if (tree_int_cst_sgn (argmax) < 0)
1439 /* For signed conversions/directives if maximum is negative,
1440 use the minimum as the longest output and maximum as the
1441 shortest output. */
1442 res.range.min = format_integer (dir, argmax, vr_values).range.min;
1443 res.range.max = format_integer (dir, argmin, vr_values).range.max;
1445 else
1447 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1448 as the shortest output and for the longest output compute the
1449 length of the output of both minimum and maximum and pick the
1450 longer. */
1451 unsigned HOST_WIDE_INT max1
1452 = format_integer (dir, argmin, vr_values).range.max;
1453 unsigned HOST_WIDE_INT max2
1454 = format_integer (dir, argmax, vr_values).range.max;
1455 res.range.min
1456 = format_integer (dir, integer_zero_node, vr_values).range.min;
1457 res.range.max = MAX (max1, max2);
1460 /* If the range is known, use the maximum as the likely length. */
1461 if (res.knownrange)
1462 res.range.likely = res.range.max;
1463 else
1465 /* Otherwise, use the minimum. Except for the case where for %#x or
1466 %#o the minimum is just for a single value in the range (0) and
1467 for all other values it is something longer, like 0x1 or 01.
1468 Use the length for value 1 in that case instead as the likely
1469 length. */
1470 res.range.likely = res.range.min;
1471 if (maybebase
1472 && base != 10
1473 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1475 if (res.range.min == 1)
1476 res.range.likely += base == 8 ? 1 : 2;
1477 else if (res.range.min == 2
1478 && base == 16
1479 && (dir.width[0] == 2 || dir.prec[0] == 2))
1480 ++res.range.likely;
1484 res.range.unlikely = res.range.max;
1485 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1486 (sign | maybebase) + (base == 16));
1487 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1488 (sign | maybebase) + (base == 16));
1490 return res;
1493 /* Return the number of bytes that a format directive consisting of FLAGS,
1494 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1495 would result for argument X under ideal conditions (i.e., if PREC
1496 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1497 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1498 This function works around those problems. */
1500 static unsigned HOST_WIDE_INT
1501 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1502 char spec, char rndspec)
1504 char fmtstr[40];
1506 HOST_WIDE_INT len = strlen (flags);
1508 fmtstr[0] = '%';
1509 memcpy (fmtstr + 1, flags, len);
1510 memcpy (fmtstr + 1 + len, ".*R", 3);
1511 fmtstr[len + 4] = rndspec;
1512 fmtstr[len + 5] = spec;
1513 fmtstr[len + 6] = '\0';
1515 spec = TOUPPER (spec);
1516 if (spec == 'E' || spec == 'F')
1518 /* For %e, specify the precision explicitly since mpfr_sprintf
1519 does its own thing just to be different (see MPFR bug 21088). */
1520 if (prec < 0)
1521 prec = 6;
1523 else
1525 /* Avoid passing negative precisions with larger magnitude to MPFR
1526 to avoid exposing its bugs. (A negative precision is supposed
1527 to be ignored.) */
1528 if (prec < 0)
1529 prec = -1;
1532 HOST_WIDE_INT p = prec;
1534 if (spec == 'G' && !strchr (flags, '#'))
1536 /* For G/g without the pound flag, precision gives the maximum number
1537 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1538 a 128 bit IEEE extended precision, 4932. Using twice as much here
1539 should be more than sufficient for any real format. */
1540 if ((IEEE_MAX_10_EXP * 2) < prec)
1541 prec = IEEE_MAX_10_EXP * 2;
1542 p = prec;
1544 else
1546 /* Cap precision arbitrarily at 1KB and add the difference
1547 (if any) to the MPFR result. */
1548 if (prec > 1024)
1549 p = 1024;
1552 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1554 /* Handle the unlikely (impossible?) error by returning more than
1555 the maximum dictated by the function's return type. */
1556 if (len < 0)
1557 return target_dir_max () + 1;
1559 /* Adjust the return value by the difference. */
1560 if (p < prec)
1561 len += prec - p;
1563 return len;
1566 /* Return the number of bytes to format using the format specifier
1567 SPEC and the precision PREC the largest value in the real floating
1568 TYPE. */
1570 static unsigned HOST_WIDE_INT
1571 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1573 machine_mode mode = TYPE_MODE (type);
1575 /* IBM Extended mode. */
1576 if (MODE_COMPOSITE_P (mode))
1577 mode = DFmode;
1579 /* Get the real type format desription for the target. */
1580 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1581 REAL_VALUE_TYPE rv;
1583 real_maxval (&rv, 0, mode);
1585 /* Convert the GCC real value representation with the precision
1586 of the real type to the mpfr_t format with the GCC default
1587 round-to-nearest mode. */
1588 mpfr_t x;
1589 mpfr_init2 (x, rfmt->p);
1590 mpfr_from_real (x, &rv, GMP_RNDN);
1592 /* Return a value one greater to account for the leading minus sign. */
1593 unsigned HOST_WIDE_INT r
1594 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1595 mpfr_clear (x);
1596 return r;
1599 /* Return a range representing the minimum and maximum number of bytes
1600 that the directive DIR will output for any argument. PREC gives
1601 the adjusted precision range to account for negative precisions
1602 meaning the default 6. This function is used when the directive
1603 argument or its value isn't known. */
1605 static fmtresult
1606 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1608 tree type;
1610 switch (dir.modifier)
1612 case FMT_LEN_l:
1613 case FMT_LEN_none:
1614 type = double_type_node;
1615 break;
1617 case FMT_LEN_L:
1618 type = long_double_type_node;
1619 break;
1621 case FMT_LEN_ll:
1622 type = long_double_type_node;
1623 break;
1625 default:
1626 return fmtresult ();
1629 /* The minimum and maximum number of bytes produced by the directive. */
1630 fmtresult res;
1632 /* The minimum output as determined by flags. It's always at least 1.
1633 When plus or space are set the output is preceded by either a sign
1634 or a space. */
1635 unsigned flagmin = (1 /* for the first digit */
1636 + (dir.get_flag ('+') | dir.get_flag (' ')));
1638 /* The minimum is 3 for "inf" and "nan" for all specifiers, plus 1
1639 for the plus sign/space with the '+' and ' ' flags, respectively,
1640 unless reduced below. */
1641 res.range.min = 2 + flagmin;
1643 /* When the pound flag is set the decimal point is included in output
1644 regardless of precision. Whether or not a decimal point is included
1645 otherwise depends on the specification and precision. */
1646 bool radix = dir.get_flag ('#');
1648 switch (dir.specifier)
1650 case 'A':
1651 case 'a':
1653 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1654 if (dir.prec[0] <= 0)
1655 minprec = 0;
1656 else if (dir.prec[0] > 0)
1657 minprec = dir.prec[0] + !radix /* decimal point */;
1659 res.range.likely = (2 /* 0x */
1660 + flagmin
1661 + radix
1662 + minprec
1663 + 3 /* p+0 */);
1665 res.range.max = format_floating_max (type, 'a', prec[1]);
1667 /* The unlikely maximum accounts for the longest multibyte
1668 decimal point character. */
1669 res.range.unlikely = res.range.max;
1670 if (dir.prec[1] > 0)
1671 res.range.unlikely += target_mb_len_max () - 1;
1673 break;
1676 case 'E':
1677 case 'e':
1679 /* Minimum output attributable to precision and, when it's
1680 non-zero, decimal point. */
1681 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1683 /* The likely minimum output is "[-+]1.234567e+00" regardless
1684 of the value of the actual argument. */
1685 res.range.likely = (flagmin
1686 + radix
1687 + minprec
1688 + 2 /* e+ */ + 2);
1690 res.range.max = format_floating_max (type, 'e', prec[1]);
1692 /* The unlikely maximum accounts for the longest multibyte
1693 decimal point character. */
1694 if (dir.prec[0] != dir.prec[1]
1695 || dir.prec[0] == -1 || dir.prec[0] > 0)
1696 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1697 else
1698 res.range.unlikely = res.range.max;
1699 break;
1702 case 'F':
1703 case 'f':
1705 /* Minimum output attributable to precision and, when it's non-zero,
1706 decimal point. */
1707 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1709 /* For finite numbers (i.e., not infinity or NaN) the lower bound
1710 when precision isn't specified is 8 bytes ("1.23456" since
1711 precision is taken to be 6). When precision is zero, the lower
1712 bound is 1 byte (e.g., "1"). Otherwise, when precision is greater
1713 than zero, then the lower bound is 2 plus precision (plus flags).
1714 But in all cases, the lower bound is no greater than 3. */
1715 unsigned HOST_WIDE_INT min = flagmin + radix + minprec;
1716 if (min < res.range.min)
1717 res.range.min = min;
1719 /* Compute the upper bound for -TYPE_MAX. */
1720 res.range.max = format_floating_max (type, 'f', prec[1]);
1722 /* The minimum output with unknown precision is a single byte
1723 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1724 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1725 res.range.likely = 3;
1726 else
1727 res.range.likely = min;
1729 /* The unlikely maximum accounts for the longest multibyte
1730 decimal point character. */
1731 if (dir.prec[0] != dir.prec[1]
1732 || dir.prec[0] == -1 || dir.prec[0] > 0)
1733 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1734 break;
1737 case 'G':
1738 case 'g':
1740 /* The %g output depends on precision and the exponent of
1741 the argument. Since the value of the argument isn't known
1742 the lower bound on the range of bytes (not counting flags
1743 or width) is 1 plus radix (i.e., either "0" or "0." for
1744 "%g" and "%#g", respectively, with a zero argument). */
1745 unsigned HOST_WIDE_INT min = flagmin + radix;
1746 if (min < res.range.min)
1747 res.range.min = min;
1749 char spec = 'g';
1750 HOST_WIDE_INT maxprec = dir.prec[1];
1751 if (radix && maxprec)
1753 /* When the pound flag (radix) is set, trailing zeros aren't
1754 trimmed and so the longest output is the same as for %e,
1755 except with precision minus 1 (as specified in C11). */
1756 spec = 'e';
1757 if (maxprec > 0)
1758 --maxprec;
1759 else if (maxprec < 0)
1760 maxprec = 5;
1762 else
1763 maxprec = prec[1];
1765 res.range.max = format_floating_max (type, spec, maxprec);
1767 /* The likely output is either the maximum computed above
1768 minus 1 (assuming the maximum is positive) when precision
1769 is known (or unspecified), or the same minimum as for %e
1770 (which is computed for a non-negative argument). Unlike
1771 for the other specifiers above the likely output isn't
1772 the minimum because for %g that's 1 which is unlikely. */
1773 if (dir.prec[1] < 0
1774 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1775 res.range.likely = res.range.max - 1;
1776 else
1778 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1779 res.range.likely = (flagmin
1780 + radix
1781 + minprec
1782 + 2 /* e+ */ + 2);
1785 /* The unlikely maximum accounts for the longest multibyte
1786 decimal point character. */
1787 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1788 break;
1791 default:
1792 return fmtresult ();
1795 /* Bump up the byte counters if WIDTH is greater. */
1796 res.adjust_for_width_or_precision (dir.width);
1797 return res;
1800 /* Return a range representing the minimum and maximum number of bytes
1801 that the directive DIR will write on output for the floating argument
1802 ARG. */
1804 static fmtresult
1805 format_floating (const directive &dir, tree arg, vr_values *)
1807 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1808 tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1809 ? long_double_type_node : double_type_node);
1811 /* For an indeterminate precision the lower bound must be assumed
1812 to be zero. */
1813 if (TOUPPER (dir.specifier) == 'A')
1815 /* Get the number of fractional decimal digits needed to represent
1816 the argument without a loss of accuracy. */
1817 unsigned fmtprec
1818 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1820 /* The precision of the IEEE 754 double format is 53.
1821 The precision of all other GCC binary double formats
1822 is 56 or less. */
1823 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1825 /* For %a, leave the minimum precision unspecified to let
1826 MFPR trim trailing zeros (as it and many other systems
1827 including Glibc happen to do) and set the maximum
1828 precision to reflect what it would be with trailing zeros
1829 present (as Solaris and derived systems do). */
1830 if (dir.prec[1] < 0)
1832 /* Both bounds are negative implies that precision has
1833 not been specified. */
1834 prec[0] = maxprec;
1835 prec[1] = -1;
1837 else if (dir.prec[0] < 0)
1839 /* With a negative lower bound and a non-negative upper
1840 bound set the minimum precision to zero and the maximum
1841 to the greater of the maximum precision (i.e., with
1842 trailing zeros present) and the specified upper bound. */
1843 prec[0] = 0;
1844 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1847 else if (dir.prec[0] < 0)
1849 if (dir.prec[1] < 0)
1851 /* A precision in a strictly negative range is ignored and
1852 the default of 6 is used instead. */
1853 prec[0] = prec[1] = 6;
1855 else
1857 /* For a precision in a partly negative range, the lower bound
1858 must be assumed to be zero and the new upper bound is the
1859 greater of 6 (the default precision used when the specified
1860 precision is negative) and the upper bound of the specified
1861 range. */
1862 prec[0] = 0;
1863 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1867 if (!arg
1868 || TREE_CODE (arg) != REAL_CST
1869 || !useless_type_conversion_p (type, TREE_TYPE (arg)))
1870 return format_floating (dir, prec);
1872 /* The minimum and maximum number of bytes produced by the directive. */
1873 fmtresult res;
1875 /* Get the real type format desription for the target. */
1876 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1877 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1879 if (!real_isfinite (rvp))
1881 /* The format for Infinity and NaN is "[-]inf"/"[-]infinity"
1882 and "[-]nan" with the choice being implementation-defined
1883 but not locale dependent. */
1884 bool sign = dir.get_flag ('+') || real_isneg (rvp);
1885 res.range.min = 3 + sign;
1887 res.range.likely = res.range.min;
1888 res.range.max = res.range.min;
1889 /* The unlikely maximum is "[-/+]infinity" or "[-/+][qs]nan".
1890 For NaN, the C/POSIX standards specify two formats:
1891 "[-/+]nan"
1893 "[-/+]nan(n-char-sequence)"
1894 No known printf implementation outputs the latter format but AIX
1895 outputs QNaN and SNaN for quiet and signalling NaN, respectively,
1896 so the unlikely maximum reflects that. */
1897 res.range.unlikely = sign + (real_isinf (rvp) ? 8 : 4);
1899 /* The range for infinity and NaN is known unless either width
1900 or precision is unknown. Width has the same effect regardless
1901 of whether the argument is finite. Precision is either ignored
1902 (e.g., Glibc) or can have an effect on the short vs long format
1903 such as inf/infinity (e.g., Solaris). */
1904 res.knownrange = dir.known_width_and_precision ();
1906 /* Adjust the range for width but ignore precision. */
1907 res.adjust_for_width_or_precision (dir.width);
1909 return res;
1912 char fmtstr [40];
1913 char *pfmt = fmtstr;
1915 /* Append flags. */
1916 for (const char *pf = "-+ #0"; *pf; ++pf)
1917 if (dir.get_flag (*pf))
1918 *pfmt++ = *pf;
1920 *pfmt = '\0';
1923 /* Set up an array to easily iterate over. */
1924 unsigned HOST_WIDE_INT* const minmax[] = {
1925 &res.range.min, &res.range.max
1928 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1930 /* Convert the GCC real value representation with the precision
1931 of the real type to the mpfr_t format rounding down in the
1932 first iteration that computes the minimm and up in the second
1933 that computes the maximum. This order is arbibtrary because
1934 rounding in either direction can result in longer output. */
1935 mpfr_t mpfrval;
1936 mpfr_init2 (mpfrval, rfmt->p);
1937 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1939 /* Use the MPFR rounding specifier to round down in the first
1940 iteration and then up. In most but not all cases this will
1941 result in the same number of bytes. */
1942 char rndspec = "DU"[i];
1944 /* Format it and store the result in the corresponding member
1945 of the result struct. */
1946 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1947 dir.specifier, rndspec);
1948 mpfr_clear (mpfrval);
1952 /* Make sure the minimum is less than the maximum (MPFR rounding
1953 in the call to mpfr_snprintf can result in the reverse. */
1954 if (res.range.max < res.range.min)
1956 unsigned HOST_WIDE_INT tmp = res.range.min;
1957 res.range.min = res.range.max;
1958 res.range.max = tmp;
1961 /* The range is known unless either width or precision is unknown. */
1962 res.knownrange = dir.known_width_and_precision ();
1964 /* For the same floating point constant, unless width or precision
1965 is unknown, use the longer output as the likely maximum since
1966 with round to nearest either is equally likely. Otheriwse, when
1967 precision is unknown, use the greater of the minimum and 3 as
1968 the likely output (for "0.0" since zero precision is unlikely). */
1969 if (res.knownrange)
1970 res.range.likely = res.range.max;
1971 else if (res.range.min < 3
1972 && dir.prec[0] < 0
1973 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
1974 res.range.likely = 3;
1975 else
1976 res.range.likely = res.range.min;
1978 res.range.unlikely = res.range.max;
1980 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
1982 /* Unless the precision is zero output longer than 2 bytes may
1983 include the decimal point which must be a single character
1984 up to MB_LEN_MAX in length. This is overly conservative
1985 since in some conversions some constants result in no decimal
1986 point (e.g., in %g). */
1987 res.range.unlikely += target_mb_len_max () - 1;
1990 res.adjust_for_width_or_precision (dir.width);
1991 return res;
1994 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1995 strings referenced by the expression STR, or (-1, -1) when not known.
1996 Used by the format_string function below. */
1998 static fmtresult
1999 get_string_length (tree str, unsigned eltsize)
2001 if (!str)
2002 return fmtresult ();
2004 /* Determine the length of the shortest and longest string referenced
2005 by STR. Strings of unknown lengths are bounded by the sizes of
2006 arrays that subexpressions of STR may refer to. Pointers that
2007 aren't known to point any such arrays result in LENRANGE[1] set
2008 to SIZE_MAX. */
2009 tree lenrange[2];
2010 bool flexarray = get_range_strlen (str, lenrange, eltsize);
2012 if (lenrange [0] || lenrange [1])
2014 HOST_WIDE_INT min
2015 = (tree_fits_uhwi_p (lenrange[0])
2016 ? tree_to_uhwi (lenrange[0])
2017 : 0);
2019 HOST_WIDE_INT max
2020 = (tree_fits_uhwi_p (lenrange[1])
2021 ? tree_to_uhwi (lenrange[1])
2022 : HOST_WIDE_INT_M1U);
2024 /* get_range_strlen() returns the target value of SIZE_MAX for
2025 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2026 which may be bigger. */
2027 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2028 min = HOST_WIDE_INT_M1U;
2029 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2030 max = HOST_WIDE_INT_M1U;
2032 fmtresult res (min, max);
2034 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2035 by STR are known to be bounded (though not necessarily by their
2036 actual length but perhaps by their maximum possible length). */
2037 if (res.range.max < target_int_max ())
2039 res.knownrange = true;
2040 /* When the the length of the longest string is known and not
2041 excessive use it as the likely length of the string(s). */
2042 res.range.likely = res.range.max;
2044 else
2046 /* When the upper bound is unknown (it can be zero or excessive)
2047 set the likely length to the greater of 1 and the length of
2048 the shortest string and reset the lower bound to zero. */
2049 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2050 res.range.min = 0;
2053 /* If the range of string length has been estimated from the size
2054 of an array at the end of a struct assume that it's longer than
2055 the array bound says it is in case it's used as a poor man's
2056 flexible array member, such as in struct S { char a[4]; }; */
2057 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
2059 return res;
2062 return fmtresult ();
2065 /* Return the minimum and maximum number of characters formatted
2066 by the '%c' format directives and its wide character form for
2067 the argument ARG. ARG can be null (for functions such as
2068 vsprinf). */
2070 static fmtresult
2071 format_character (const directive &dir, tree arg, vr_values *vr_values)
2073 fmtresult res;
2075 res.knownrange = true;
2077 if (dir.specifier == 'C'
2078 || dir.modifier == FMT_LEN_l)
2080 /* A wide character can result in as few as zero bytes. */
2081 res.range.min = 0;
2083 HOST_WIDE_INT min, max;
2084 if (get_int_range (arg, &min, &max, false, 0, vr_values))
2086 if (min == 0 && max == 0)
2088 /* The NUL wide character results in no bytes. */
2089 res.range.max = 0;
2090 res.range.likely = 0;
2091 res.range.unlikely = 0;
2093 else if (min >= 0 && min < 128)
2095 /* Be conservative if the target execution character set
2096 is not a 1-to-1 mapping to the source character set or
2097 if the source set is not ASCII. */
2098 bool one_2_one_ascii
2099 = (target_to_host_charmap[0] == 1 && target_to_host ('a') == 97);
2101 /* A wide character in the ASCII range most likely results
2102 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2103 res.range.max = one_2_one_ascii ? 1 : target_mb_len_max ();;
2104 res.range.likely = 1;
2105 res.range.unlikely = target_mb_len_max ();
2106 res.mayfail = !one_2_one_ascii;
2108 else
2110 /* A wide character outside the ASCII range likely results
2111 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2112 res.range.max = target_mb_len_max ();
2113 res.range.likely = 2;
2114 res.range.unlikely = res.range.max;
2115 /* Converting such a character may fail. */
2116 res.mayfail = true;
2119 else
2121 /* An unknown wide character is treated the same as a wide
2122 character outside the ASCII range. */
2123 res.range.max = target_mb_len_max ();
2124 res.range.likely = 2;
2125 res.range.unlikely = res.range.max;
2126 res.mayfail = true;
2129 else
2131 /* A plain '%c' directive. Its ouput is exactly 1. */
2132 res.range.min = res.range.max = 1;
2133 res.range.likely = res.range.unlikely = 1;
2134 res.knownrange = true;
2137 /* Bump up the byte counters if WIDTH is greater. */
2138 return res.adjust_for_width_or_precision (dir.width);
2141 /* Return the minimum and maximum number of characters formatted
2142 by the '%s' format directive and its wide character form for
2143 the argument ARG. ARG can be null (for functions such as
2144 vsprinf). */
2146 static fmtresult
2147 format_string (const directive &dir, tree arg, vr_values *)
2149 fmtresult res;
2151 /* Compute the range the argument's length can be in. */
2152 int count_by = dir.specifier == 'S' || dir.modifier == FMT_LEN_l ? 4 : 1;
2153 fmtresult slen = get_string_length (arg, count_by);
2154 if (slen.range.min == slen.range.max
2155 && slen.range.min < HOST_WIDE_INT_MAX)
2157 /* The argument is either a string constant or it refers
2158 to one of a number of strings of the same length. */
2160 /* A '%s' directive with a string argument with constant length. */
2161 res.range = slen.range;
2163 if (dir.specifier == 'S'
2164 || dir.modifier == FMT_LEN_l)
2166 /* In the worst case the length of output of a wide string S
2167 is bounded by MB_LEN_MAX * wcslen (S). */
2168 res.range.max *= target_mb_len_max ();
2169 res.range.unlikely = res.range.max;
2170 /* It's likely that the the total length is not more that
2171 2 * wcslen (S).*/
2172 res.range.likely = res.range.min * 2;
2174 if (dir.prec[1] >= 0
2175 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2177 res.range.max = dir.prec[1];
2178 res.range.likely = dir.prec[1];
2179 res.range.unlikely = dir.prec[1];
2182 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2183 res.range.min = 0;
2184 else if (dir.prec[0] >= 0)
2185 res.range.likely = dir.prec[0];
2187 /* Even a non-empty wide character string need not convert into
2188 any bytes. */
2189 res.range.min = 0;
2191 /* A non-empty wide character conversion may fail. */
2192 if (slen.range.max > 0)
2193 res.mayfail = true;
2195 else
2197 res.knownrange = true;
2199 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2200 res.range.min = 0;
2201 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2202 res.range.min = dir.prec[0];
2204 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2206 res.range.max = dir.prec[1];
2207 res.range.likely = dir.prec[1];
2208 res.range.unlikely = dir.prec[1];
2212 else if (arg && integer_zerop (arg))
2214 /* Handle null pointer argument. */
2216 fmtresult res (0);
2217 res.nullp = true;
2218 return res;
2220 else
2222 /* For a '%s' and '%ls' directive with a non-constant string (either
2223 one of a number of strings of known length or an unknown string)
2224 the minimum number of characters is lesser of PRECISION[0] and
2225 the length of the shortest known string or zero, and the maximum
2226 is the lessser of the length of the longest known string or
2227 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2228 the minimum at level 1 and the greater of the minimum and 1
2229 at level 2. This result is adjust upward for width (if it's
2230 specified). */
2232 if (dir.specifier == 'S'
2233 || dir.modifier == FMT_LEN_l)
2235 /* A wide character converts to as few as zero bytes. */
2236 slen.range.min = 0;
2237 if (slen.range.max < target_int_max ())
2238 slen.range.max *= target_mb_len_max ();
2240 if (slen.range.likely < target_int_max ())
2241 slen.range.likely *= 2;
2243 if (slen.range.likely < target_int_max ())
2244 slen.range.unlikely *= target_mb_len_max ();
2246 /* A non-empty wide character conversion may fail. */
2247 if (slen.range.max > 0)
2248 res.mayfail = true;
2251 res.range = slen.range;
2253 if (dir.prec[0] >= 0)
2255 /* Adjust the minimum to zero if the string length is unknown,
2256 or at most the lower bound of the precision otherwise. */
2257 if (slen.range.min >= target_int_max ())
2258 res.range.min = 0;
2259 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2260 res.range.min = dir.prec[0];
2262 /* Make both maxima no greater than the upper bound of precision. */
2263 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2264 || slen.range.max >= target_int_max ())
2266 res.range.max = dir.prec[1];
2267 res.range.unlikely = dir.prec[1];
2270 /* If precision is constant, set the likely counter to the lesser
2271 of it and the maximum string length. Otherwise, if the lower
2272 bound of precision is greater than zero, set the likely counter
2273 to the minimum. Otherwise set it to zero or one based on
2274 the warning level. */
2275 if (dir.prec[0] == dir.prec[1])
2276 res.range.likely
2277 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2278 ? dir.prec[0] : slen.range.max);
2279 else if (dir.prec[0] > 0)
2280 res.range.likely = res.range.min;
2281 else
2282 res.range.likely = warn_level > 1;
2284 else if (dir.prec[1] >= 0)
2286 res.range.min = 0;
2287 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2288 res.range.max = dir.prec[1];
2289 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2291 else if (slen.range.min >= target_int_max ())
2293 res.range.min = 0;
2294 res.range.max = HOST_WIDE_INT_MAX;
2295 /* At level 1 strings of unknown length are assumed to be
2296 empty, while at level 1 they are assumed to be one byte
2297 long. */
2298 res.range.likely = warn_level > 1;
2300 else
2302 /* A string of unknown length unconstrained by precision is
2303 assumed to be empty at level 1 and just one character long
2304 at higher levels. */
2305 if (res.range.likely >= target_int_max ())
2306 res.range.likely = warn_level > 1;
2309 res.range.unlikely = res.range.max;
2312 /* Bump up the byte counters if WIDTH is greater. */
2313 return res.adjust_for_width_or_precision (dir.width);
2316 /* Format plain string (part of the format string itself). */
2318 static fmtresult
2319 format_plain (const directive &dir, tree, vr_values *)
2321 fmtresult res (dir.len);
2322 return res;
2325 /* Return true if the RESULT of a directive in a call describe by INFO
2326 should be diagnosed given the AVAILable space in the destination. */
2328 static bool
2329 should_warn_p (const sprintf_dom_walker::call_info &info,
2330 const result_range &avail, const result_range &result)
2332 if (result.max <= avail.min)
2334 /* The least amount of space remaining in the destination is big
2335 enough for the longest output. */
2336 return false;
2339 if (info.bounded)
2341 if (warn_format_trunc == 1 && result.min <= avail.max
2342 && info.retval_used ())
2344 /* The likely amount of space remaining in the destination is big
2345 enough for the least output and the return value is used. */
2346 return false;
2349 if (warn_format_trunc == 1 && result.likely <= avail.likely
2350 && !info.retval_used ())
2352 /* The likely amount of space remaining in the destination is big
2353 enough for the likely output and the return value is unused. */
2354 return false;
2357 if (warn_format_trunc == 2
2358 && result.likely <= avail.min
2359 && (result.max <= avail.min
2360 || result.max > HOST_WIDE_INT_MAX))
2362 /* The minimum amount of space remaining in the destination is big
2363 enough for the longest output. */
2364 return false;
2367 else
2369 if (warn_level == 1 && result.likely <= avail.likely)
2371 /* The likely amount of space remaining in the destination is big
2372 enough for the likely output. */
2373 return false;
2376 if (warn_level == 2
2377 && result.likely <= avail.min
2378 && (result.max <= avail.min
2379 || result.max > HOST_WIDE_INT_MAX))
2381 /* The minimum amount of space remaining in the destination is big
2382 enough for the longest output. */
2383 return false;
2387 return true;
2390 /* At format string location describe by DIRLOC in a call described
2391 by INFO, issue a warning for a directive DIR whose output may be
2392 in excess of the available space AVAIL_RANGE in the destination
2393 given the formatting result FMTRES. This function does nothing
2394 except decide whether to issue a warning for a possible write
2395 past the end or truncation and, if so, format the warning.
2396 Return true if a warning has been issued. */
2398 static bool
2399 maybe_warn (substring_loc &dirloc, location_t argloc,
2400 const sprintf_dom_walker::call_info &info,
2401 const result_range &avail_range, const result_range &res,
2402 const directive &dir)
2404 if (!should_warn_p (info, avail_range, res))
2405 return false;
2407 /* A warning will definitely be issued below. */
2409 /* The maximum byte count to reference in the warning. Larger counts
2410 imply that the upper bound is unknown (and could be anywhere between
2411 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2412 than "between N and X" where X is some huge number. */
2413 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2415 /* True when there is enough room in the destination for the least
2416 amount of a directive's output but not enough for its likely or
2417 maximum output. */
2418 bool maybe = (res.min <= avail_range.max
2419 && (avail_range.min < res.likely
2420 || (res.max < HOST_WIDE_INT_MAX
2421 && avail_range.min < res.max)));
2423 /* Buffer for the directive in the host character set (used when
2424 the source character set is different). */
2425 char hostdir[32];
2427 if (avail_range.min == avail_range.max)
2429 /* The size of the destination region is exact. */
2430 unsigned HOST_WIDE_INT navail = avail_range.max;
2432 if (target_to_host (*dir.beg) != '%')
2434 /* For plain character directives (i.e., the format string itself)
2435 but not others, point the caret at the first character that's
2436 past the end of the destination. */
2437 if (navail < dir.len)
2438 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2441 if (*dir.beg == '\0')
2443 /* This is the terminating nul. */
2444 gcc_assert (res.min == 1 && res.min == res.max);
2446 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2447 info.bounded
2448 ? (maybe
2449 ? G_("%qE output may be truncated before the "
2450 "last format character")
2451 : G_("%qE output truncated before the last "
2452 "format character"))
2453 : (maybe
2454 ? G_("%qE may write a terminating nul past the "
2455 "end of the destination")
2456 : G_("%qE writing a terminating nul past the "
2457 "end of the destination")),
2458 info.func);
2461 if (res.min == res.max)
2463 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2464 if (!info.bounded)
2465 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2466 "%<%.*s%> directive writing %wu byte into a "
2467 "region of size %wu",
2468 "%<%.*s%> directive writing %wu bytes into a "
2469 "region of size %wu",
2470 (int) dir.len, d, res.min, navail);
2471 else if (maybe)
2472 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2473 "%<%.*s%> directive output may be truncated "
2474 "writing %wu byte into a region of size %wu",
2475 "%<%.*s%> directive output may be truncated "
2476 "writing %wu bytes into a region of size %wu",
2477 (int) dir.len, d, res.min, navail);
2478 else
2479 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2480 "%<%.*s%> directive output truncated writing "
2481 "%wu byte into a region of size %wu",
2482 "%<%.*s%> directive output truncated writing "
2483 "%wu bytes into a region of size %wu",
2484 (int) dir.len, d, res.min, navail);
2486 if (res.min == 0 && res.max < maxbytes)
2487 return fmtwarn (dirloc, argloc, NULL,
2488 info.warnopt (),
2489 info.bounded
2490 ? (maybe
2491 ? G_("%<%.*s%> directive output may be truncated "
2492 "writing up to %wu bytes into a region of "
2493 "size %wu")
2494 : G_("%<%.*s%> directive output truncated writing "
2495 "up to %wu bytes into a region of size %wu"))
2496 : G_("%<%.*s%> directive writing up to %wu bytes "
2497 "into a region of size %wu"), (int) dir.len,
2498 target_to_host (hostdir, sizeof hostdir, dir.beg),
2499 res.max, navail);
2501 if (res.min == 0 && maxbytes <= res.max)
2502 /* This is a special case to avoid issuing the potentially
2503 confusing warning:
2504 writing 0 or more bytes into a region of size 0. */
2505 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2506 info.bounded
2507 ? (maybe
2508 ? G_("%<%.*s%> directive output may be truncated "
2509 "writing likely %wu or more bytes into a "
2510 "region of size %wu")
2511 : G_("%<%.*s%> directive output truncated writing "
2512 "likely %wu or more bytes into a region of "
2513 "size %wu"))
2514 : G_("%<%.*s%> directive writing likely %wu or more "
2515 "bytes into a region of size %wu"), (int) dir.len,
2516 target_to_host (hostdir, sizeof hostdir, dir.beg),
2517 res.likely, navail);
2519 if (res.max < maxbytes)
2520 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2521 info.bounded
2522 ? (maybe
2523 ? G_("%<%.*s%> directive output may be truncated "
2524 "writing between %wu and %wu bytes into a "
2525 "region of size %wu")
2526 : G_("%<%.*s%> directive output truncated "
2527 "writing between %wu and %wu bytes into a "
2528 "region of size %wu"))
2529 : G_("%<%.*s%> directive writing between %wu and "
2530 "%wu bytes into a region of size %wu"),
2531 (int) dir.len,
2532 target_to_host (hostdir, sizeof hostdir, dir.beg),
2533 res.min, res.max, navail);
2535 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2536 info.bounded
2537 ? (maybe
2538 ? G_("%<%.*s%> directive output may be truncated "
2539 "writing %wu or more bytes into a region of "
2540 "size %wu")
2541 : G_("%<%.*s%> directive output truncated writing "
2542 "%wu or more bytes into a region of size %wu"))
2543 : G_("%<%.*s%> directive writing %wu or more bytes "
2544 "into a region of size %wu"), (int) dir.len,
2545 target_to_host (hostdir, sizeof hostdir, dir.beg),
2546 res.min, navail);
2549 /* The size of the destination region is a range. */
2551 if (target_to_host (*dir.beg) != '%')
2553 unsigned HOST_WIDE_INT navail = avail_range.max;
2555 /* For plain character directives (i.e., the format string itself)
2556 but not others, point the caret at the first character that's
2557 past the end of the destination. */
2558 if (navail < dir.len)
2559 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2562 if (*dir.beg == '\0')
2564 gcc_assert (res.min == 1 && res.min == res.max);
2566 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2567 info.bounded
2568 ? (maybe
2569 ? G_("%qE output may be truncated before the last "
2570 "format character")
2571 : G_("%qE output truncated before the last format "
2572 "character"))
2573 : (maybe
2574 ? G_("%qE may write a terminating nul past the end "
2575 "of the destination")
2576 : G_("%qE writing a terminating nul past the end "
2577 "of the destination")), info.func);
2580 if (res.min == res.max)
2582 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2583 if (!info.bounded)
2584 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2585 "%<%.*s%> directive writing %wu byte into a region "
2586 "of size between %wu and %wu",
2587 "%<%.*s%> directive writing %wu bytes into a region "
2588 "of size between %wu and %wu", (int) dir.len, d,
2589 res.min, avail_range.min, avail_range.max);
2590 else if (maybe)
2591 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2592 "%<%.*s%> directive output may be truncated writing "
2593 "%wu byte into a region of size between %wu and %wu",
2594 "%<%.*s%> directive output may be truncated writing "
2595 "%wu bytes into a region of size between %wu and "
2596 "%wu", (int) dir.len, d, res.min, avail_range.min,
2597 avail_range.max);
2598 else
2599 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2600 "%<%.*s%> directive output truncated writing %wu "
2601 "byte into a region of size between %wu and %wu",
2602 "%<%.*s%> directive output truncated writing %wu "
2603 "bytes into a region of size between %wu and %wu",
2604 (int) dir.len, d, res.min, avail_range.min,
2605 avail_range.max);
2608 if (res.min == 0 && res.max < maxbytes)
2609 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2610 info.bounded
2611 ? (maybe
2612 ? G_("%<%.*s%> directive output may be truncated "
2613 "writing up to %wu bytes into a region of size "
2614 "between %wu and %wu")
2615 : G_("%<%.*s%> directive output truncated writing "
2616 "up to %wu bytes into a region of size between "
2617 "%wu and %wu"))
2618 : G_("%<%.*s%> directive writing up to %wu bytes "
2619 "into a region of size between %wu and %wu"),
2620 (int) dir.len,
2621 target_to_host (hostdir, sizeof hostdir, dir.beg),
2622 res.max, avail_range.min, avail_range.max);
2624 if (res.min == 0 && maxbytes <= res.max)
2625 /* This is a special case to avoid issuing the potentially confusing
2626 warning:
2627 writing 0 or more bytes into a region of size between 0 and N. */
2628 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2629 info.bounded
2630 ? (maybe
2631 ? G_("%<%.*s%> directive output may be truncated "
2632 "writing likely %wu or more bytes into a region "
2633 "of size between %wu and %wu")
2634 : G_("%<%.*s%> directive output truncated writing "
2635 "likely %wu or more bytes into a region of size "
2636 "between %wu and %wu"))
2637 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2638 "into a region of size between %wu and %wu"),
2639 (int) dir.len,
2640 target_to_host (hostdir, sizeof hostdir, dir.beg),
2641 res.likely, avail_range.min, avail_range.max);
2643 if (res.max < maxbytes)
2644 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2645 info.bounded
2646 ? (maybe
2647 ? G_("%<%.*s%> directive output may be truncated "
2648 "writing between %wu and %wu bytes into a region "
2649 "of size between %wu and %wu")
2650 : G_("%<%.*s%> directive output truncated writing "
2651 "between %wu and %wu bytes into a region of size "
2652 "between %wu and %wu"))
2653 : G_("%<%.*s%> directive writing between %wu and "
2654 "%wu bytes into a region of size between %wu and "
2655 "%wu"), (int) dir.len,
2656 target_to_host (hostdir, sizeof hostdir, dir.beg),
2657 res.min, res.max, avail_range.min, avail_range.max);
2659 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2660 info.bounded
2661 ? (maybe
2662 ? G_("%<%.*s%> directive output may be truncated writing "
2663 "%wu or more bytes into a region of size between "
2664 "%wu and %wu")
2665 : G_("%<%.*s%> directive output truncated writing "
2666 "%wu or more bytes into a region of size between "
2667 "%wu and %wu"))
2668 : G_("%<%.*s%> directive writing %wu or more bytes "
2669 "into a region of size between %wu and %wu"),
2670 (int) dir.len,
2671 target_to_host (hostdir, sizeof hostdir, dir.beg),
2672 res.min, avail_range.min, avail_range.max);
2675 /* Compute the length of the output resulting from the directive DIR
2676 in a call described by INFO and update the overall result of the call
2677 in *RES. Return true if the directive has been handled. */
2679 static bool
2680 format_directive (const sprintf_dom_walker::call_info &info,
2681 format_result *res, const directive &dir,
2682 class vr_values *vr_values)
2684 /* Offset of the beginning of the directive from the beginning
2685 of the format string. */
2686 size_t offset = dir.beg - info.fmtstr;
2687 size_t start = offset;
2688 size_t length = offset + dir.len - !!dir.len;
2690 /* Create a location for the whole directive from the % to the format
2691 specifier. */
2692 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2693 offset, start, length);
2695 /* Also get the location of the argument if possible.
2696 This doesn't work for integer literals or function calls. */
2697 location_t argloc = UNKNOWN_LOCATION;
2698 if (dir.arg)
2699 argloc = EXPR_LOCATION (dir.arg);
2701 /* Bail when there is no function to compute the output length,
2702 or when minimum length checking has been disabled. */
2703 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2704 return false;
2706 /* Compute the range of lengths of the formatted output. */
2707 fmtresult fmtres = dir.fmtfunc (dir, dir.arg, vr_values);
2709 /* Record whether the output of all directives is known to be
2710 bounded by some maximum, implying that their arguments are
2711 either known exactly or determined to be in a known range
2712 or, for strings, limited by the upper bounds of the arrays
2713 they refer to. */
2714 res->knownrange &= fmtres.knownrange;
2716 if (!fmtres.knownrange)
2718 /* Only when the range is known, check it against the host value
2719 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2720 INT_MAX precision, which is the longest possible output of any
2721 single directive). That's the largest valid byte count (though
2722 not valid call to a printf-like function because it can never
2723 return such a count). Otherwise, the range doesn't correspond
2724 to known values of the argument. */
2725 if (fmtres.range.max > target_dir_max ())
2727 /* Normalize the MAX counter to avoid having to deal with it
2728 later. The counter can be less than HOST_WIDE_INT_M1U
2729 when compiling for an ILP32 target on an LP64 host. */
2730 fmtres.range.max = HOST_WIDE_INT_M1U;
2731 /* Disable exact and maximum length checking after a failure
2732 to determine the maximum number of characters (for example
2733 for wide characters or wide character strings) but continue
2734 tracking the minimum number of characters. */
2735 res->range.max = HOST_WIDE_INT_M1U;
2738 if (fmtres.range.min > target_dir_max ())
2740 /* Disable exact length checking after a failure to determine
2741 even the minimum number of characters (it shouldn't happen
2742 except in an error) but keep tracking the minimum and maximum
2743 number of characters. */
2744 return true;
2748 /* Buffer for the directive in the host character set (used when
2749 the source character set is different). */
2750 char hostdir[32];
2752 int dirlen = dir.len;
2754 if (fmtres.nullp)
2756 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2757 "%<%.*s%> directive argument is null",
2758 dirlen, target_to_host (hostdir, sizeof hostdir, dir.beg));
2760 /* Don't bother processing the rest of the format string. */
2761 res->warned = true;
2762 res->range.min = HOST_WIDE_INT_M1U;
2763 res->range.max = HOST_WIDE_INT_M1U;
2764 return false;
2767 /* Compute the number of available bytes in the destination. There
2768 must always be at least one byte of space for the terminating
2769 NUL that's appended after the format string has been processed. */
2770 result_range avail_range = bytes_remaining (info.objsize, *res);
2772 bool warned = res->warned;
2774 if (!warned)
2775 warned = maybe_warn (dirloc, argloc, info, avail_range,
2776 fmtres.range, dir);
2778 /* Bump up the total maximum if it isn't too big. */
2779 if (res->range.max < HOST_WIDE_INT_MAX
2780 && fmtres.range.max < HOST_WIDE_INT_MAX)
2781 res->range.max += fmtres.range.max;
2783 /* Raise the total unlikely maximum by the larger of the maximum
2784 and the unlikely maximum. */
2785 unsigned HOST_WIDE_INT save = res->range.unlikely;
2786 if (fmtres.range.max < fmtres.range.unlikely)
2787 res->range.unlikely += fmtres.range.unlikely;
2788 else
2789 res->range.unlikely += fmtres.range.max;
2791 if (res->range.unlikely < save)
2792 res->range.unlikely = HOST_WIDE_INT_M1U;
2794 res->range.min += fmtres.range.min;
2795 res->range.likely += fmtres.range.likely;
2797 /* Has the minimum directive output length exceeded the maximum
2798 of 4095 bytes required to be supported? */
2799 bool minunder4k = fmtres.range.min < 4096;
2800 bool maxunder4k = fmtres.range.max < 4096;
2801 /* Clear POSUNDER4K in the overall result if the maximum has exceeded
2802 the 4k (this is necessary to avoid the return value optimization
2803 that may not be safe in the maximum case). */
2804 if (!maxunder4k)
2805 res->posunder4k = false;
2806 /* Also clear POSUNDER4K if the directive may fail. */
2807 if (fmtres.mayfail)
2808 res->posunder4k = false;
2810 if (!warned
2811 /* Only warn at level 2. */
2812 && warn_level > 1
2813 && (!minunder4k
2814 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2816 /* The directive output may be longer than the maximum required
2817 to be handled by an implementation according to 7.21.6.1, p15
2818 of C11. Warn on this only at level 2 but remember this and
2819 prevent folding the return value when done. This allows for
2820 the possibility of the actual libc call failing due to ENOMEM
2821 (like Glibc does under some conditions). */
2823 if (fmtres.range.min == fmtres.range.max)
2824 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2825 "%<%.*s%> directive output of %wu bytes exceeds "
2826 "minimum required size of 4095", dirlen,
2827 target_to_host (hostdir, sizeof hostdir, dir.beg),
2828 fmtres.range.min);
2829 else
2830 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2831 minunder4k
2832 ? G_("%<%.*s%> directive output between %wu and %wu "
2833 "bytes may exceed minimum required size of "
2834 "4095")
2835 : G_("%<%.*s%> directive output between %wu and %wu "
2836 "bytes exceeds minimum required size of 4095"),
2837 dirlen,
2838 target_to_host (hostdir, sizeof hostdir, dir.beg),
2839 fmtres.range.min, fmtres.range.max);
2842 /* Has the likely and maximum directive output exceeded INT_MAX? */
2843 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2844 /* Don't consider the maximum to be in excess when it's the result
2845 of a string of unknown length (i.e., whose maximum has been set
2846 to be greater than or equal to HOST_WIDE_INT_MAX. */
2847 bool maxximax = (*dir.beg
2848 && res->range.max > target_int_max ()
2849 && res->range.max < HOST_WIDE_INT_MAX);
2851 if (!warned
2852 /* Warn for the likely output size at level 1. */
2853 && (likelyximax
2854 /* But only warn for the maximum at level 2. */
2855 || (warn_level > 1
2856 && maxximax
2857 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2859 /* The directive output causes the total length of output
2860 to exceed INT_MAX bytes. */
2862 if (fmtres.range.min == fmtres.range.max)
2863 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2864 "%<%.*s%> directive output of %wu bytes causes "
2865 "result to exceed %<INT_MAX%>", dirlen,
2866 target_to_host (hostdir, sizeof hostdir, dir.beg),
2867 fmtres.range.min);
2868 else
2869 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2870 fmtres.range.min > target_int_max ()
2871 ? G_("%<%.*s%> directive output between %wu and "
2872 "%wu bytes causes result to exceed "
2873 "%<INT_MAX%>")
2874 : G_("%<%.*s%> directive output between %wu and "
2875 "%wu bytes may cause result to exceed "
2876 "%<INT_MAX%>"), dirlen,
2877 target_to_host (hostdir, sizeof hostdir, dir.beg),
2878 fmtres.range.min, fmtres.range.max);
2881 if (warned && fmtres.range.min < fmtres.range.likely
2882 && fmtres.range.likely < fmtres.range.max)
2883 inform_n (info.fmtloc, fmtres.range.likely,
2884 "assuming directive output of %wu byte",
2885 "assuming directive output of %wu bytes",
2886 fmtres.range.likely);
2888 if (warned && fmtres.argmin)
2890 if (fmtres.argmin == fmtres.argmax)
2891 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2892 else if (fmtres.knownrange)
2893 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2894 fmtres.argmin, fmtres.argmax);
2895 else
2896 inform (info.fmtloc,
2897 "using the range [%E, %E] for directive argument",
2898 fmtres.argmin, fmtres.argmax);
2901 res->warned |= warned;
2903 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2905 /* If a warning has been issued for buffer overflow or truncation
2906 (but not otherwise) help the user figure out how big a buffer
2907 they need. */
2909 location_t callloc = gimple_location (info.callstmt);
2911 unsigned HOST_WIDE_INT min = res->range.min;
2912 unsigned HOST_WIDE_INT max = res->range.max;
2914 if (min == max)
2915 inform (callloc,
2916 (min == 1
2917 ? G_("%qE output %wu byte into a destination of size %wu")
2918 : G_("%qE output %wu bytes into a destination of size %wu")),
2919 info.func, min, info.objsize);
2920 else if (max < HOST_WIDE_INT_MAX)
2921 inform (callloc,
2922 "%qE output between %wu and %wu bytes into "
2923 "a destination of size %wu",
2924 info.func, min, max, info.objsize);
2925 else if (min < res->range.likely && res->range.likely < max)
2926 inform (callloc,
2927 "%qE output %wu or more bytes (assuming %wu) into "
2928 "a destination of size %wu",
2929 info.func, min, res->range.likely, info.objsize);
2930 else
2931 inform (callloc,
2932 "%qE output %wu or more bytes into a destination of size %wu",
2933 info.func, min, info.objsize);
2936 if (dump_file && *dir.beg)
2938 fprintf (dump_file,
2939 " Result: "
2940 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
2941 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
2942 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
2943 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
2944 fmtres.range.min, fmtres.range.likely,
2945 fmtres.range.max, fmtres.range.unlikely,
2946 res->range.min, res->range.likely,
2947 res->range.max, res->range.unlikely);
2950 return true;
2953 /* Parse a format directive in function call described by INFO starting
2954 at STR and populate DIR structure. Bump up *ARGNO by the number of
2955 arguments extracted for the directive. Return the length of
2956 the directive. */
2958 static size_t
2959 parse_directive (sprintf_dom_walker::call_info &info,
2960 directive &dir, format_result *res,
2961 const char *str, unsigned *argno,
2962 vr_values *vr_values)
2964 const char *pcnt = strchr (str, target_percent);
2965 dir.beg = str;
2967 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
2969 /* This directive is either a plain string or the terminating nul
2970 (which isn't really a directive but it simplifies things to
2971 handle it as if it were). */
2972 dir.len = len;
2973 dir.fmtfunc = format_plain;
2975 if (dump_file)
2977 fprintf (dump_file, " Directive %u at offset "
2978 HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
2979 "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
2980 dir.dirno,
2981 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
2982 (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
2985 return len - !*str;
2988 const char *pf = pcnt + 1;
2990 /* POSIX numbered argument index or zero when none. */
2991 HOST_WIDE_INT dollar = 0;
2993 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
2994 when given by a va_list argument, and a non-negative value
2995 when specified in the format string itself. */
2996 HOST_WIDE_INT width = -1;
2997 HOST_WIDE_INT precision = -1;
2999 /* Pointers to the beginning of the width and precision decimal
3000 string (if any) within the directive. */
3001 const char *pwidth = 0;
3002 const char *pprec = 0;
3004 /* When the value of the decimal string that specifies width or
3005 precision is out of range, points to the digit that causes
3006 the value to exceed the limit. */
3007 const char *werange = NULL;
3008 const char *perange = NULL;
3010 /* Width specified via the asterisk. Need not be INTEGER_CST.
3011 For vararg functions set to void_node. */
3012 tree star_width = NULL_TREE;
3014 /* Width specified via the asterisk. Need not be INTEGER_CST.
3015 For vararg functions set to void_node. */
3016 tree star_precision = NULL_TREE;
3018 if (ISDIGIT (target_to_host (*pf)))
3020 /* This could be either a POSIX positional argument, the '0'
3021 flag, or a width, depending on what follows. Store it as
3022 width and sort it out later after the next character has
3023 been seen. */
3024 pwidth = pf;
3025 width = target_strtol10 (&pf, &werange);
3027 else if (target_to_host (*pf) == '*')
3029 /* Similarly to the block above, this could be either a POSIX
3030 positional argument or a width, depending on what follows. */
3031 if (*argno < gimple_call_num_args (info.callstmt))
3032 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3033 else
3034 star_width = void_node;
3035 ++pf;
3038 if (target_to_host (*pf) == '$')
3040 /* Handle the POSIX dollar sign which references the 1-based
3041 positional argument number. */
3042 if (width != -1)
3043 dollar = width + info.argidx;
3044 else if (star_width
3045 && TREE_CODE (star_width) == INTEGER_CST
3046 && (TYPE_PRECISION (TREE_TYPE (star_width))
3047 <= TYPE_PRECISION (integer_type_node)))
3048 dollar = width + tree_to_shwi (star_width);
3050 /* Bail when the numbered argument is out of range (it will
3051 have already been diagnosed by -Wformat). */
3052 if (dollar == 0
3053 || dollar == (int)info.argidx
3054 || dollar > gimple_call_num_args (info.callstmt))
3055 return false;
3057 --dollar;
3059 star_width = NULL_TREE;
3060 width = -1;
3061 ++pf;
3064 if (dollar || !star_width)
3066 if (width != -1)
3068 if (width == 0)
3070 /* The '0' that has been interpreted as a width above is
3071 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3072 and continue processing other flags. */
3073 width = -1;
3074 dir.set_flag ('0');
3076 else if (!dollar)
3078 /* (Non-zero) width has been seen. The next character
3079 is either a period or a digit. */
3080 goto start_precision;
3083 /* When either '$' has been seen, or width has not been seen,
3084 the next field is the optional flags followed by an optional
3085 width. */
3086 for ( ; ; ) {
3087 switch (target_to_host (*pf))
3089 case ' ':
3090 case '0':
3091 case '+':
3092 case '-':
3093 case '#':
3094 dir.set_flag (target_to_host (*pf++));
3095 break;
3097 default:
3098 goto start_width;
3102 start_width:
3103 if (ISDIGIT (target_to_host (*pf)))
3105 werange = 0;
3106 pwidth = pf;
3107 width = target_strtol10 (&pf, &werange);
3109 else if (target_to_host (*pf) == '*')
3111 if (*argno < gimple_call_num_args (info.callstmt))
3112 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3113 else
3115 /* This is (likely) a va_list. It could also be an invalid
3116 call with insufficient arguments. */
3117 star_width = void_node;
3119 ++pf;
3121 else if (target_to_host (*pf) == '\'')
3123 /* The POSIX apostrophe indicating a numeric grouping
3124 in the current locale. Even though it's possible to
3125 estimate the upper bound on the size of the output
3126 based on the number of digits it probably isn't worth
3127 continuing. */
3128 return 0;
3132 start_precision:
3133 if (target_to_host (*pf) == '.')
3135 ++pf;
3137 if (ISDIGIT (target_to_host (*pf)))
3139 pprec = pf;
3140 precision = target_strtol10 (&pf, &perange);
3142 else if (target_to_host (*pf) == '*')
3144 if (*argno < gimple_call_num_args (info.callstmt))
3145 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3146 else
3148 /* This is (likely) a va_list. It could also be an invalid
3149 call with insufficient arguments. */
3150 star_precision = void_node;
3152 ++pf;
3154 else
3156 /* The decimal precision or the asterisk are optional.
3157 When neither is dirified it's taken to be zero. */
3158 precision = 0;
3162 switch (target_to_host (*pf))
3164 case 'h':
3165 if (target_to_host (pf[1]) == 'h')
3167 ++pf;
3168 dir.modifier = FMT_LEN_hh;
3170 else
3171 dir.modifier = FMT_LEN_h;
3172 ++pf;
3173 break;
3175 case 'j':
3176 dir.modifier = FMT_LEN_j;
3177 ++pf;
3178 break;
3180 case 'L':
3181 dir.modifier = FMT_LEN_L;
3182 ++pf;
3183 break;
3185 case 'l':
3186 if (target_to_host (pf[1]) == 'l')
3188 ++pf;
3189 dir.modifier = FMT_LEN_ll;
3191 else
3192 dir.modifier = FMT_LEN_l;
3193 ++pf;
3194 break;
3196 case 't':
3197 dir.modifier = FMT_LEN_t;
3198 ++pf;
3199 break;
3201 case 'z':
3202 dir.modifier = FMT_LEN_z;
3203 ++pf;
3204 break;
3207 switch (target_to_host (*pf))
3209 /* Handle a sole '%' character the same as "%%" but since it's
3210 undefined prevent the result from being folded. */
3211 case '\0':
3212 --pf;
3213 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3214 /* FALLTHRU */
3215 case '%':
3216 dir.fmtfunc = format_percent;
3217 break;
3219 case 'a':
3220 case 'A':
3221 case 'e':
3222 case 'E':
3223 case 'f':
3224 case 'F':
3225 case 'g':
3226 case 'G':
3227 res->floating = true;
3228 dir.fmtfunc = format_floating;
3229 break;
3231 case 'd':
3232 case 'i':
3233 case 'o':
3234 case 'u':
3235 case 'x':
3236 case 'X':
3237 dir.fmtfunc = format_integer;
3238 break;
3240 case 'p':
3241 /* The %p output is implementation-defined. It's possible
3242 to determine this format but due to extensions (edirially
3243 those of the Linux kernel -- see bug 78512) the first %p
3244 in the format string disables any further processing. */
3245 return false;
3247 case 'n':
3248 /* %n has side-effects even when nothing is actually printed to
3249 any buffer. */
3250 info.nowrite = false;
3251 dir.fmtfunc = format_none;
3252 break;
3254 case 'C':
3255 case 'c':
3256 /* POSIX wide character and C/POSIX narrow character. */
3257 dir.fmtfunc = format_character;
3258 break;
3260 case 'S':
3261 case 's':
3262 /* POSIX wide string and C/POSIX narrow character string. */
3263 dir.fmtfunc = format_string;
3264 break;
3266 default:
3267 /* Unknown conversion specification. */
3268 return 0;
3271 dir.specifier = target_to_host (*pf++);
3273 /* Store the length of the format directive. */
3274 dir.len = pf - pcnt;
3276 /* Buffer for the directive in the host character set (used when
3277 the source character set is different). */
3278 char hostdir[32];
3280 if (star_width)
3282 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3283 dir.set_width (star_width, vr_values);
3284 else
3286 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3287 (width is the absolute value of that specified). */
3288 dir.width[0] = 0;
3289 dir.width[1] = target_int_max () + 1;
3292 else
3294 if (width == LONG_MAX && werange)
3296 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3297 size_t caret = begin + (werange - pcnt);
3298 size_t end = pf - info.fmtstr - 1;
3300 /* Create a location for the width part of the directive,
3301 pointing the caret at the first out-of-range digit. */
3302 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3303 caret, begin, end);
3305 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3306 "%<%.*s%> directive width out of range", (int) dir.len,
3307 target_to_host (hostdir, sizeof hostdir, dir.beg));
3310 dir.set_width (width);
3313 if (star_precision)
3315 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3316 dir.set_precision (star_precision, vr_values);
3317 else
3319 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3320 (unlike width, negative precision is ignored). */
3321 dir.prec[0] = -1;
3322 dir.prec[1] = target_int_max ();
3325 else
3327 if (precision == LONG_MAX && perange)
3329 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3330 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3331 size_t end = pf - info.fmtstr - 2;
3333 /* Create a location for the precision part of the directive,
3334 including the leading period, pointing the caret at the first
3335 out-of-range digit . */
3336 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3337 caret, begin, end);
3339 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3340 "%<%.*s%> directive precision out of range", (int) dir.len,
3341 target_to_host (hostdir, sizeof hostdir, dir.beg));
3344 dir.set_precision (precision);
3347 /* Extract the argument if the directive takes one and if it's
3348 available (e.g., the function doesn't take a va_list). Treat
3349 missing arguments the same as va_list, even though they will
3350 have likely already been diagnosed by -Wformat. */
3351 if (dir.specifier != '%'
3352 && *argno < gimple_call_num_args (info.callstmt))
3353 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3355 if (dump_file)
3357 fprintf (dump_file,
3358 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3359 ": \"%.*s\"",
3360 dir.dirno,
3361 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3362 (int)dir.len, dir.beg);
3363 if (star_width)
3365 if (dir.width[0] == dir.width[1])
3366 fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
3367 dir.width[0]);
3368 else
3369 fprintf (dump_file,
3370 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3371 ", " HOST_WIDE_INT_PRINT_DEC "]",
3372 dir.width[0], dir.width[1]);
3375 if (star_precision)
3377 if (dir.prec[0] == dir.prec[1])
3378 fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
3379 dir.prec[0]);
3380 else
3381 fprintf (dump_file,
3382 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3383 HOST_WIDE_INT_PRINT_DEC "]",
3384 dir.prec[0], dir.prec[1]);
3386 fputc ('\n', dump_file);
3389 return dir.len;
3392 /* Compute the length of the output resulting from the call to a formatted
3393 output function described by INFO and store the result of the call in
3394 *RES. Issue warnings for detected past the end writes. Return true
3395 if the complete format string has been processed and *RES can be relied
3396 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3397 that caused the processing to be terminated early). */
3399 bool
3400 sprintf_dom_walker::compute_format_length (call_info &info,
3401 format_result *res)
3403 if (dump_file)
3405 location_t callloc = gimple_location (info.callstmt);
3406 fprintf (dump_file, "%s:%i: ",
3407 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3408 print_generic_expr (dump_file, info.func, dump_flags);
3410 fprintf (dump_file,
3411 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3412 ", fmtstr = \"%s\"\n",
3413 info.objsize, info.fmtstr);
3416 /* Reset the minimum and maximum byte counters. */
3417 res->range.min = res->range.max = 0;
3419 /* No directive has been seen yet so the length of output is bounded
3420 by the known range [0, 0] (with no conversion resulting in a failure
3421 or producing more than 4K bytes) until determined otherwise. */
3422 res->knownrange = true;
3423 res->posunder4k = true;
3424 res->floating = false;
3425 res->warned = false;
3427 /* 1-based directive counter. */
3428 unsigned dirno = 1;
3430 /* The variadic argument counter. */
3431 unsigned argno = info.argidx;
3433 for (const char *pf = info.fmtstr; ; ++dirno)
3435 directive dir = directive ();
3436 dir.dirno = dirno;
3438 size_t n = parse_directive (info, dir, res, pf, &argno,
3439 evrp_range_analyzer.get_vr_values ());
3441 /* Return failure if the format function fails. */
3442 if (!format_directive (info, res, dir,
3443 evrp_range_analyzer.get_vr_values ()))
3444 return false;
3446 /* Return success the directive is zero bytes long and it's
3447 the last think in the format string (i.e., it's the terminating
3448 nul, which isn't really a directive but handling it as one makes
3449 things simpler). */
3450 if (!n)
3451 return *pf == '\0';
3453 pf += n;
3456 /* The complete format string was processed (with or without warnings). */
3457 return true;
3460 /* Return the size of the object referenced by the expression DEST if
3461 available, or -1 otherwise. */
3463 static unsigned HOST_WIDE_INT
3464 get_destination_size (tree dest)
3466 /* Initialize object size info before trying to compute it. */
3467 init_object_sizes ();
3469 /* Use __builtin_object_size to determine the size of the destination
3470 object. When optimizing, determine the smallest object (such as
3471 a member array as opposed to the whole enclosing object), otherwise
3472 use type-zero object size to determine the size of the enclosing
3473 object (the function fails without optimization in this type). */
3474 int ost = optimize > 0;
3475 unsigned HOST_WIDE_INT size;
3476 if (compute_builtin_object_size (dest, ost, &size))
3477 return size;
3479 return HOST_WIDE_INT_M1U;
3482 /* Return true if the call described by INFO with result RES safe to
3483 optimize (i.e., no undefined behavior), and set RETVAL to the range
3484 of its return values. */
3486 static bool
3487 is_call_safe (const sprintf_dom_walker::call_info &info,
3488 const format_result &res, bool under4k,
3489 unsigned HOST_WIDE_INT retval[2])
3491 if (under4k && !res.posunder4k)
3492 return false;
3494 /* The minimum return value. */
3495 retval[0] = res.range.min;
3497 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3498 but in cases involving multibyte characters could be as large as
3499 RES.RANGE.UNLIKELY. */
3500 retval[1]
3501 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3503 /* Adjust the number of bytes which includes the terminating nul
3504 to reflect the return value of the function which does not.
3505 Because the valid range of the function is [INT_MIN, INT_MAX],
3506 a valid range before the adjustment below is [0, INT_MAX + 1]
3507 (the functions only return negative values on error or undefined
3508 behavior). */
3509 if (retval[0] <= target_int_max () + 1)
3510 --retval[0];
3511 if (retval[1] <= target_int_max () + 1)
3512 --retval[1];
3514 /* Avoid the return value optimization when the behavior of the call
3515 is undefined either because any directive may have produced 4K or
3516 more of output, or the return value exceeds INT_MAX, or because
3517 the output overflows the destination object (but leave it enabled
3518 when the function is bounded because then the behavior is well-
3519 defined). */
3520 if (retval[0] == retval[1]
3521 && (info.bounded || retval[0] < info.objsize)
3522 && retval[0] <= target_int_max ())
3523 return true;
3525 if ((info.bounded || retval[1] < info.objsize)
3526 && (retval[0] < target_int_max ()
3527 && retval[1] < target_int_max ()))
3528 return true;
3530 if (!under4k && (info.bounded || retval[0] < info.objsize))
3531 return true;
3533 return false;
3536 /* Given a suitable result RES of a call to a formatted output function
3537 described by INFO, substitute the result for the return value of
3538 the call. The result is suitable if the number of bytes it represents
3539 is known and exact. A result that isn't suitable for substitution may
3540 have its range set to the range of return values, if that is known.
3541 Return true if the call is removed and gsi_next should not be performed
3542 in the caller. */
3544 static bool
3545 try_substitute_return_value (gimple_stmt_iterator *gsi,
3546 const sprintf_dom_walker::call_info &info,
3547 const format_result &res)
3549 tree lhs = gimple_get_lhs (info.callstmt);
3551 /* Set to true when the entire call has been removed. */
3552 bool removed = false;
3554 /* The minimum and maximum return value. */
3555 unsigned HOST_WIDE_INT retval[2];
3556 bool safe = is_call_safe (info, res, true, retval);
3558 if (safe
3559 && retval[0] == retval[1]
3560 /* Not prepared to handle possibly throwing calls here; they shouldn't
3561 appear in non-artificial testcases, except when the __*_chk routines
3562 are badly declared. */
3563 && !stmt_ends_bb_p (info.callstmt))
3565 tree cst = build_int_cst (integer_type_node, retval[0]);
3567 if (lhs == NULL_TREE
3568 && info.nowrite)
3570 /* Remove the call to the bounded function with a zero size
3571 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3572 unlink_stmt_vdef (info.callstmt);
3573 gsi_remove (gsi, true);
3574 removed = true;
3576 else if (info.nowrite)
3578 /* Replace the call to the bounded function with a zero size
3579 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3580 of the function. */
3581 if (!update_call_from_tree (gsi, cst))
3582 gimplify_and_update_call_from_tree (gsi, cst);
3583 gimple *callstmt = gsi_stmt (*gsi);
3584 update_stmt (callstmt);
3586 else if (lhs)
3588 /* Replace the left-hand side of the call with the constant
3589 result of the formatted function. */
3590 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3591 gimple *g = gimple_build_assign (lhs, cst);
3592 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3593 update_stmt (info.callstmt);
3596 if (dump_file)
3598 if (removed)
3599 fprintf (dump_file, " Removing call statement.");
3600 else
3602 fprintf (dump_file, " Substituting ");
3603 print_generic_expr (dump_file, cst, dump_flags);
3604 fprintf (dump_file, " for %s.\n",
3605 info.nowrite ? "statement" : "return value");
3609 else if (lhs)
3611 bool setrange = false;
3613 if (safe
3614 && (info.bounded || retval[1] < info.objsize)
3615 && (retval[0] < target_int_max ()
3616 && retval[1] < target_int_max ()))
3618 /* If the result is in a valid range bounded by the size of
3619 the destination set it so that it can be used for subsequent
3620 optimizations. */
3621 int prec = TYPE_PRECISION (integer_type_node);
3623 wide_int min = wi::shwi (retval[0], prec);
3624 wide_int max = wi::shwi (retval[1], prec);
3625 set_range_info (lhs, VR_RANGE, min, max);
3627 setrange = true;
3630 if (dump_file)
3632 const char *inbounds
3633 = (retval[0] < info.objsize
3634 ? (retval[1] < info.objsize
3635 ? "in" : "potentially out-of")
3636 : "out-of");
3638 const char *what = setrange ? "Setting" : "Discarding";
3639 if (retval[0] != retval[1])
3640 fprintf (dump_file,
3641 " %s %s-bounds return value range ["
3642 HOST_WIDE_INT_PRINT_UNSIGNED ", "
3643 HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
3644 what, inbounds, retval[0], retval[1]);
3645 else
3646 fprintf (dump_file, " %s %s-bounds return value "
3647 HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
3648 what, inbounds, retval[0]);
3652 if (dump_file)
3653 fputc ('\n', dump_file);
3655 return removed;
3658 /* Try to simplify a s{,n}printf call described by INFO with result
3659 RES by replacing it with a simpler and presumably more efficient
3660 call (such as strcpy). */
3662 static bool
3663 try_simplify_call (gimple_stmt_iterator *gsi,
3664 const sprintf_dom_walker::call_info &info,
3665 const format_result &res)
3667 unsigned HOST_WIDE_INT dummy[2];
3668 if (!is_call_safe (info, res, info.retval_used (), dummy))
3669 return false;
3671 switch (info.fncode)
3673 case BUILT_IN_SNPRINTF:
3674 return gimple_fold_builtin_snprintf (gsi);
3676 case BUILT_IN_SPRINTF:
3677 return gimple_fold_builtin_sprintf (gsi);
3679 default:
3683 return false;
3686 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3687 functions and if so, handle it. Return true if the call is removed
3688 and gsi_next should not be performed in the caller. */
3690 bool
3691 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3693 call_info info = call_info ();
3695 info.callstmt = gsi_stmt (*gsi);
3696 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3697 return false;
3699 info.func = gimple_call_fndecl (info.callstmt);
3700 info.fncode = DECL_FUNCTION_CODE (info.func);
3702 /* The size of the destination as in snprintf(dest, size, ...). */
3703 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3705 /* The size of the destination determined by __builtin_object_size. */
3706 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3708 /* Buffer size argument number (snprintf and vsnprintf). */
3709 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3711 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3712 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3714 /* Format string argument number (valid for all functions). */
3715 unsigned idx_format;
3717 switch (info.fncode)
3719 case BUILT_IN_SPRINTF:
3720 // Signature:
3721 // __builtin_sprintf (dst, format, ...)
3722 idx_format = 1;
3723 info.argidx = 2;
3724 break;
3726 case BUILT_IN_SPRINTF_CHK:
3727 // Signature:
3728 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3729 idx_objsize = 2;
3730 idx_format = 3;
3731 info.argidx = 4;
3732 break;
3734 case BUILT_IN_SNPRINTF:
3735 // Signature:
3736 // __builtin_snprintf (dst, size, format, ...)
3737 idx_dstsize = 1;
3738 idx_format = 2;
3739 info.argidx = 3;
3740 info.bounded = true;
3741 break;
3743 case BUILT_IN_SNPRINTF_CHK:
3744 // Signature:
3745 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3746 idx_dstsize = 1;
3747 idx_objsize = 3;
3748 idx_format = 4;
3749 info.argidx = 5;
3750 info.bounded = true;
3751 break;
3753 case BUILT_IN_VSNPRINTF:
3754 // Signature:
3755 // __builtin_vsprintf (dst, size, format, va)
3756 idx_dstsize = 1;
3757 idx_format = 2;
3758 info.argidx = -1;
3759 info.bounded = true;
3760 break;
3762 case BUILT_IN_VSNPRINTF_CHK:
3763 // Signature:
3764 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3765 idx_dstsize = 1;
3766 idx_objsize = 3;
3767 idx_format = 4;
3768 info.argidx = -1;
3769 info.bounded = true;
3770 break;
3772 case BUILT_IN_VSPRINTF:
3773 // Signature:
3774 // __builtin_vsprintf (dst, format, va)
3775 idx_format = 1;
3776 info.argidx = -1;
3777 break;
3779 case BUILT_IN_VSPRINTF_CHK:
3780 // Signature:
3781 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3782 idx_format = 3;
3783 idx_objsize = 2;
3784 info.argidx = -1;
3785 break;
3787 default:
3788 return false;
3791 /* Set the global warning level for this function. */
3792 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3794 /* The first argument is a pointer to the destination. */
3795 tree dstptr = gimple_call_arg (info.callstmt, 0);
3797 info.format = gimple_call_arg (info.callstmt, idx_format);
3799 /* True when the destination size is constant as opposed to the lower
3800 or upper bound of a range. */
3801 bool dstsize_cst_p = true;
3803 if (idx_dstsize == HOST_WIDE_INT_M1U)
3805 /* For non-bounded functions like sprintf, determine the size
3806 of the destination from the object or pointer passed to it
3807 as the first argument. */
3808 dstsize = get_destination_size (dstptr);
3810 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3812 /* For bounded functions try to get the size argument. */
3814 if (TREE_CODE (size) == INTEGER_CST)
3816 dstsize = tree_to_uhwi (size);
3817 /* No object can be larger than SIZE_MAX bytes (half the address
3818 space) on the target.
3819 The functions are defined only for output of at most INT_MAX
3820 bytes. Specifying a bound in excess of that limit effectively
3821 defeats the bounds checking (and on some implementations such
3822 as Solaris cause the function to fail with EINVAL). */
3823 if (dstsize > target_size_max () / 2)
3825 /* Avoid warning if -Wstringop-overflow is specified since
3826 it also warns for the same thing though only for the
3827 checking built-ins. */
3828 if ((idx_objsize == HOST_WIDE_INT_M1U
3829 || !warn_stringop_overflow))
3830 warning_at (gimple_location (info.callstmt), info.warnopt (),
3831 "specified bound %wu exceeds maximum object size "
3832 "%wu",
3833 dstsize, target_size_max () / 2);
3835 else if (dstsize > target_int_max ())
3836 warning_at (gimple_location (info.callstmt), info.warnopt (),
3837 "specified bound %wu exceeds %<INT_MAX%>",
3838 dstsize);
3840 else if (TREE_CODE (size) == SSA_NAME)
3842 /* Try to determine the range of values of the argument
3843 and use the greater of the two at level 1 and the smaller
3844 of them at level 2. */
3845 value_range *vr = evrp_range_analyzer.get_value_range (size);
3846 if (vr->type == VR_RANGE
3847 && TREE_CODE (vr->min) == INTEGER_CST
3848 && TREE_CODE (vr->max) == INTEGER_CST)
3849 dstsize = (warn_level < 2
3850 ? TREE_INT_CST_LOW (vr->max)
3851 : TREE_INT_CST_LOW (vr->min));
3853 /* The destination size is not constant. If the function is
3854 bounded (e.g., snprintf) a lower bound of zero doesn't
3855 necessarily imply it can be eliminated. */
3856 dstsize_cst_p = false;
3860 if (idx_objsize != HOST_WIDE_INT_M1U)
3861 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3862 if (tree_fits_uhwi_p (size))
3863 objsize = tree_to_uhwi (size);
3865 if (info.bounded && !dstsize)
3867 /* As a special case, when the explicitly specified destination
3868 size argument (to a bounded function like snprintf) is zero
3869 it is a request to determine the number of bytes on output
3870 without actually producing any. Pretend the size is
3871 unlimited in this case. */
3872 info.objsize = HOST_WIDE_INT_MAX;
3873 info.nowrite = dstsize_cst_p;
3875 else
3877 /* For calls to non-bounded functions or to those of bounded
3878 functions with a non-zero size, warn if the destination
3879 pointer is null. */
3880 if (integer_zerop (dstptr))
3882 /* This is diagnosed with -Wformat only when the null is a constant
3883 pointer. The warning here diagnoses instances where the pointer
3884 is not constant. */
3885 location_t loc = gimple_location (info.callstmt);
3886 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3887 info.warnopt (), "null destination pointer");
3888 return false;
3891 /* Set the object size to the smaller of the two arguments
3892 of both have been specified and they're not equal. */
3893 info.objsize = dstsize < objsize ? dstsize : objsize;
3895 if (info.bounded
3896 && dstsize < target_size_max () / 2 && objsize < dstsize
3897 /* Avoid warning if -Wstringop-overflow is specified since
3898 it also warns for the same thing though only for the
3899 checking built-ins. */
3900 && (idx_objsize == HOST_WIDE_INT_M1U
3901 || !warn_stringop_overflow))
3903 warning_at (gimple_location (info.callstmt), info.warnopt (),
3904 "specified bound %wu exceeds the size %wu "
3905 "of the destination object", dstsize, objsize);
3909 if (integer_zerop (info.format))
3911 /* This is diagnosed with -Wformat only when the null is a constant
3912 pointer. The warning here diagnoses instances where the pointer
3913 is not constant. */
3914 location_t loc = gimple_location (info.callstmt);
3915 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3916 info.warnopt (), "null format string");
3917 return false;
3920 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3921 if (!info.fmtstr)
3922 return false;
3924 /* The result is the number of bytes output by the formatted function,
3925 including the terminating NUL. */
3926 format_result res = format_result ();
3928 bool success = compute_format_length (info, &res);
3930 /* When optimizing and the printf return value optimization is enabled,
3931 attempt to substitute the computed result for the return value of
3932 the call. Avoid this optimization when -frounding-math is in effect
3933 and the format string contains a floating point directive. */
3934 bool call_removed = false;
3935 if (success && optimize > 0)
3937 /* Save a copy of the iterator pointing at the call. The iterator
3938 may change to point past the call in try_substitute_return_value
3939 but the original value is needed in try_simplify_call. */
3940 gimple_stmt_iterator gsi_call = *gsi;
3942 if (flag_printf_return_value
3943 && (!flag_rounding_math || !res.floating))
3944 call_removed = try_substitute_return_value (gsi, info, res);
3946 if (!call_removed)
3947 try_simplify_call (&gsi_call, info, res);
3950 return call_removed;
3953 edge
3954 sprintf_dom_walker::before_dom_children (basic_block bb)
3956 evrp_range_analyzer.enter (bb);
3957 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
3959 /* Iterate over statements, looking for function calls. */
3960 gimple *stmt = gsi_stmt (si);
3962 /* First record ranges generated by this statement. */
3963 evrp_range_analyzer.record_ranges_from_stmt (stmt, false);
3965 if (is_gimple_call (stmt) && handle_gimple_call (&si))
3966 /* If handle_gimple_call returns true, the iterator is
3967 already pointing to the next statement. */
3968 continue;
3970 gsi_next (&si);
3972 return NULL;
3975 void
3976 sprintf_dom_walker::after_dom_children (basic_block bb)
3978 evrp_range_analyzer.leave (bb);
3981 /* Execute the pass for function FUN. */
3983 unsigned int
3984 pass_sprintf_length::execute (function *fun)
3986 init_target_to_host_charmap ();
3988 calculate_dominance_info (CDI_DOMINATORS);
3990 sprintf_dom_walker sprintf_dom_walker;
3991 sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
3993 /* Clean up object size info. */
3994 fini_object_sizes ();
3995 return 0;
3998 } /* Unnamed namespace. */
4000 /* Return a pointer to a pass object newly constructed from the context
4001 CTXT. */
4003 gimple_opt_pass *
4004 make_pass_sprintf_length (gcc::context *ctxt)
4006 return new pass_sprintf_length (ctxt);