2018-10-09 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob471bfc45eb87514824299ff975d2d464f80e60c4
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 (), nonstr (),
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 (), nonstr (),
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 /* Non-nul when the argument of a string directive is not a nul
561 terminated string. */
562 tree nonstr;
564 /* True when the range above is obtained from a known value of
565 a directive's argument or its bounds and not the result of
566 heuristics that depend on warning levels. */
567 bool knownrange;
569 /* True for a directive that may fail (such as wide character
570 directives). */
571 bool mayfail;
573 /* True when the argument is a null pointer. */
574 bool nullp;
577 /* Adjust result upward to reflect the range ADJUST of values the
578 specified width or precision is known to be in. When non-null,
579 TYPE denotes the type of the directive whose result is being
580 adjusted, BASE gives the base of the directive (octal, decimal,
581 or hex), and ADJ denotes the additional adjustment to the LIKELY
582 counter that may need to be added when ADJUST is a range. */
584 fmtresult&
585 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
586 tree type /* = NULL_TREE */,
587 unsigned base /* = 0 */,
588 unsigned adj /* = 0 */)
590 bool minadjusted = false;
592 /* Adjust the minimum and likely counters. */
593 if (adjust[0] >= 0)
595 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
597 range.min = adjust[0];
598 minadjusted = true;
601 /* Adjust the likely counter. */
602 if (range.likely < range.min)
603 range.likely = range.min;
605 else if (adjust[0] == target_int_min ()
606 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
607 knownrange = false;
609 /* Adjust the maximum counter. */
610 if (adjust[1] > 0)
612 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
614 range.max = adjust[1];
616 /* Set KNOWNRANGE if both the minimum and maximum have been
617 adjusted. Otherwise leave it at what it was before. */
618 knownrange = minadjusted;
622 if (warn_level > 1 && type)
624 /* For large non-constant width or precision whose range spans
625 the maximum number of digits produced by the directive for
626 any argument, set the likely number of bytes to be at most
627 the number digits plus other adjustment determined by the
628 caller (one for sign or two for the hexadecimal "0x"
629 prefix). */
630 unsigned dirdigs = type_max_digits (type, base);
631 if (adjust[0] < dirdigs && dirdigs < adjust[1]
632 && range.likely < dirdigs)
633 range.likely = dirdigs + adj;
635 else if (range.likely < (range.min ? range.min : 1))
637 /* Conservatively, set LIKELY to at least MIN but no less than
638 1 unless MAX is zero. */
639 range.likely = (range.min
640 ? range.min
641 : range.max && (range.max < HOST_WIDE_INT_MAX
642 || warn_level > 1) ? 1 : 0);
645 /* Finally adjust the unlikely counter to be at least as large as
646 the maximum. */
647 if (range.unlikely < range.max)
648 range.unlikely = range.max;
650 return *this;
653 /* Return the maximum number of digits a value of TYPE formats in
654 BASE on output, not counting base prefix . */
656 unsigned
657 fmtresult::type_max_digits (tree type, int base)
659 unsigned prec = TYPE_PRECISION (type);
660 switch (base)
662 case 8:
663 return (prec + 2) / 3;
664 case 10:
665 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
666 of 8, 16, 32, and 64 bits. */
667 return prec * 301 / 1000 + 1;
668 case 16:
669 return prec / 4;
672 gcc_unreachable ();
675 static bool
676 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT,
677 class vr_values *vr_values);
679 /* Description of a format directive. A directive is either a plain
680 string or a conversion specification that starts with '%'. */
682 struct directive
684 /* The 1-based directive number (for debugging). */
685 unsigned dirno;
687 /* The first character of the directive and its length. */
688 const char *beg;
689 size_t len;
691 /* A bitmap of flags, one for each character. */
692 unsigned flags[256 / sizeof (int)];
694 /* The range of values of the specified width, or -1 if not specified. */
695 HOST_WIDE_INT width[2];
696 /* The range of values of the specified precision, or -1 if not
697 specified. */
698 HOST_WIDE_INT prec[2];
700 /* Length modifier. */
701 format_lengths modifier;
703 /* Format specifier character. */
704 char specifier;
706 /* The argument of the directive or null when the directive doesn't
707 take one or when none is available (such as for vararg functions). */
708 tree arg;
710 /* Format conversion function that given a directive and an argument
711 returns the formatting result. */
712 fmtresult (*fmtfunc) (const directive &, tree, vr_values *);
714 /* Return True when a the format flag CHR has been used. */
715 bool get_flag (char chr) const
717 unsigned char c = chr & 0xff;
718 return (flags[c / (CHAR_BIT * sizeof *flags)]
719 & (1U << (c % (CHAR_BIT * sizeof *flags))));
722 /* Make a record of the format flag CHR having been used. */
723 void set_flag (char chr)
725 unsigned char c = chr & 0xff;
726 flags[c / (CHAR_BIT * sizeof *flags)]
727 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
730 /* Reset the format flag CHR. */
731 void clear_flag (char chr)
733 unsigned char c = chr & 0xff;
734 flags[c / (CHAR_BIT * sizeof *flags)]
735 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
738 /* Set both bounds of the width range to VAL. */
739 void set_width (HOST_WIDE_INT val)
741 width[0] = width[1] = val;
744 /* Set the width range according to ARG, with both bounds being
745 no less than 0. For a constant ARG set both bounds to its value
746 or 0, whichever is greater. For a non-constant ARG in some range
747 set width to its range adjusting each bound to -1 if it's less.
748 For an indeterminate ARG set width to [0, INT_MAX]. */
749 void set_width (tree arg, vr_values *vr_values)
751 get_int_range (arg, width, width + 1, true, 0, vr_values);
754 /* Set both bounds of the precision range to VAL. */
755 void set_precision (HOST_WIDE_INT val)
757 prec[0] = prec[1] = val;
760 /* Set the precision range according to ARG, with both bounds being
761 no less than -1. For a constant ARG set both bounds to its value
762 or -1 whichever is greater. For a non-constant ARG in some range
763 set precision to its range adjusting each bound to -1 if it's less.
764 For an indeterminate ARG set precision to [-1, INT_MAX]. */
765 void set_precision (tree arg, vr_values *vr_values)
767 get_int_range (arg, prec, prec + 1, false, -1, vr_values);
770 /* Return true if both width and precision are known to be
771 either constant or in some range, false otherwise. */
772 bool known_width_and_precision () const
774 return ((width[1] < 0
775 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
776 && (prec[1] < 0
777 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
781 /* Return the logarithm of X in BASE. */
783 static int
784 ilog (unsigned HOST_WIDE_INT x, int base)
786 int res = 0;
789 ++res;
790 x /= base;
791 } while (x);
792 return res;
795 /* Return the number of bytes resulting from converting into a string
796 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
797 PLUS indicates whether 1 for a plus sign should be added for positive
798 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
799 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
800 be represented. */
802 static HOST_WIDE_INT
803 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
805 unsigned HOST_WIDE_INT absval;
807 HOST_WIDE_INT res;
809 if (TYPE_UNSIGNED (TREE_TYPE (x)))
811 if (tree_fits_uhwi_p (x))
813 absval = tree_to_uhwi (x);
814 res = plus;
816 else
817 return -1;
819 else
821 if (tree_fits_shwi_p (x))
823 HOST_WIDE_INT i = tree_to_shwi (x);
824 if (HOST_WIDE_INT_MIN == i)
826 /* Avoid undefined behavior due to negating a minimum. */
827 absval = HOST_WIDE_INT_MAX;
828 res = 1;
830 else if (i < 0)
832 absval = -i;
833 res = 1;
835 else
837 absval = i;
838 res = plus;
841 else
842 return -1;
845 int ndigs = ilog (absval, base);
847 res += prec < ndigs ? ndigs : prec;
849 /* Adjust a non-zero value for the base prefix, either hexadecimal,
850 or, unless precision has resulted in a leading zero, also octal. */
851 if (prefix && absval && (base == 16 || prec <= ndigs))
853 if (base == 8)
854 res += 1;
855 else if (base == 16)
856 res += 2;
859 return res;
862 /* Given the formatting result described by RES and NAVAIL, the number
863 of available in the destination, return the range of bytes remaining
864 in the destination. */
866 static inline result_range
867 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
869 result_range range;
871 if (HOST_WIDE_INT_MAX <= navail)
873 range.min = range.max = range.likely = range.unlikely = navail;
874 return range;
877 /* The lower bound of the available range is the available size
878 minus the maximum output size, and the upper bound is the size
879 minus the minimum. */
880 range.max = res.range.min < navail ? navail - res.range.min : 0;
882 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
884 if (res.range.max < HOST_WIDE_INT_MAX)
885 range.min = res.range.max < navail ? navail - res.range.max : 0;
886 else
887 range.min = range.likely;
889 range.unlikely = (res.range.unlikely < navail
890 ? navail - res.range.unlikely : 0);
892 return range;
895 /* Description of a call to a formatted function. */
897 struct sprintf_dom_walker::call_info
899 /* Function call statement. */
900 gimple *callstmt;
902 /* Function called. */
903 tree func;
905 /* Called built-in function code. */
906 built_in_function fncode;
908 /* Format argument and format string extracted from it. */
909 tree format;
910 const char *fmtstr;
912 /* The location of the format argument. */
913 location_t fmtloc;
915 /* The destination object size for __builtin___xxx_chk functions
916 typically determined by __builtin_object_size, or -1 if unknown. */
917 unsigned HOST_WIDE_INT objsize;
919 /* Number of the first variable argument. */
920 unsigned HOST_WIDE_INT argidx;
922 /* True for functions like snprintf that specify the size of
923 the destination, false for others like sprintf that don't. */
924 bool bounded;
926 /* True for bounded functions like snprintf that specify a zero-size
927 buffer as a request to compute the size of output without actually
928 writing any. NOWRITE is cleared in response to the %n directive
929 which has side-effects similar to writing output. */
930 bool nowrite;
932 /* Return true if the called function's return value is used. */
933 bool retval_used () const
935 return gimple_get_lhs (callstmt);
938 /* Return the warning option corresponding to the called function. */
939 int warnopt () const
941 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
945 /* Return the result of formatting a no-op directive (such as '%n'). */
947 static fmtresult
948 format_none (const directive &, tree, vr_values *)
950 fmtresult res (0);
951 return res;
954 /* Return the result of formatting the '%%' directive. */
956 static fmtresult
957 format_percent (const directive &, tree, vr_values *)
959 fmtresult res (1);
960 return res;
964 /* Compute intmax_type_node and uintmax_type_node similarly to how
965 tree.c builds size_type_node. */
967 static void
968 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
970 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
972 *pintmax = integer_type_node;
973 *puintmax = unsigned_type_node;
975 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
977 *pintmax = long_integer_type_node;
978 *puintmax = long_unsigned_type_node;
980 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
982 *pintmax = long_long_integer_type_node;
983 *puintmax = long_long_unsigned_type_node;
985 else
987 for (int i = 0; i < NUM_INT_N_ENTS; i++)
988 if (int_n_enabled_p[i])
990 char name[50];
991 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
993 if (strcmp (name, UINTMAX_TYPE) == 0)
995 *pintmax = int_n_trees[i].signed_type;
996 *puintmax = int_n_trees[i].unsigned_type;
997 return;
1000 gcc_unreachable ();
1004 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1005 in and that is representable in type int.
1006 Return true when the range is a subrange of that of int.
1007 When ARG is null it is as if it had the full range of int.
1008 When ABSOLUTE is true the range reflects the absolute value of
1009 the argument. When ABSOLUTE is false, negative bounds of
1010 the determined range are replaced with NEGBOUND. */
1012 static bool
1013 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1014 bool absolute, HOST_WIDE_INT negbound,
1015 class vr_values *vr_values)
1017 /* The type of the result. */
1018 const_tree type = integer_type_node;
1020 bool knownrange = false;
1022 if (!arg)
1024 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1025 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1027 else if (TREE_CODE (arg) == INTEGER_CST
1028 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1030 /* For a constant argument return its value adjusted as specified
1031 by NEGATIVE and NEGBOUND and return true to indicate that the
1032 result is known. */
1033 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1034 *pmax = *pmin;
1035 knownrange = true;
1037 else
1039 /* True if the argument's range cannot be determined. */
1040 bool unknown = true;
1042 tree argtype = TREE_TYPE (arg);
1044 /* Ignore invalid arguments with greater precision that that
1045 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1046 They will have been detected and diagnosed by -Wformat and
1047 so it's not important to complicate this code to try to deal
1048 with them again. */
1049 if (TREE_CODE (arg) == SSA_NAME
1050 && INTEGRAL_TYPE_P (argtype)
1051 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1053 /* Try to determine the range of values of the integer argument. */
1054 value_range *vr = vr_values->get_value_range (arg);
1055 if (vr->type == VR_RANGE
1056 && TREE_CODE (vr->min) == INTEGER_CST
1057 && TREE_CODE (vr->max) == INTEGER_CST)
1059 HOST_WIDE_INT type_min
1060 = (TYPE_UNSIGNED (argtype)
1061 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1062 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1064 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1066 *pmin = TREE_INT_CST_LOW (vr->min);
1067 *pmax = TREE_INT_CST_LOW (vr->max);
1069 if (*pmin < *pmax)
1071 /* Return true if the adjusted range is a subrange of
1072 the full range of the argument's type. *PMAX may
1073 be less than *PMIN when the argument is unsigned
1074 and its upper bound is in excess of TYPE_MAX. In
1075 that (invalid) case disregard the range and use that
1076 of the expected type instead. */
1077 knownrange = type_min < *pmin || *pmax < type_max;
1079 unknown = false;
1084 /* Handle an argument with an unknown range as if none had been
1085 provided. */
1086 if (unknown)
1087 return get_int_range (NULL_TREE, pmin, pmax, absolute,
1088 negbound, vr_values);
1091 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1092 if (absolute)
1094 if (*pmin < 0)
1096 if (*pmin == *pmax)
1097 *pmin = *pmax = -*pmin;
1098 else
1100 /* Make sure signed overlow is avoided. */
1101 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1103 HOST_WIDE_INT tmp = -*pmin;
1104 *pmin = 0;
1105 if (*pmax < tmp)
1106 *pmax = tmp;
1110 else if (*pmin < negbound)
1111 *pmin = negbound;
1113 return knownrange;
1116 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1117 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1118 the type of the directive's formal argument it's possible for both
1119 to result in the same number of bytes or a range of bytes that's
1120 less than the number of bytes that would result from formatting
1121 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1122 determined by checking for the actual argument being in the range
1123 of the type of the directive. If it isn't it must be assumed to
1124 take on the full range of the directive's type.
1125 Return true when the range has been adjusted to the full range
1126 of DIRTYPE, and false otherwise. */
1128 static bool
1129 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1131 tree argtype = TREE_TYPE (*argmin);
1132 unsigned argprec = TYPE_PRECISION (argtype);
1133 unsigned dirprec = TYPE_PRECISION (dirtype);
1135 /* If the actual argument and the directive's argument have the same
1136 precision and sign there can be no overflow and so there is nothing
1137 to adjust. */
1138 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1139 return false;
1141 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1142 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1144 if (TREE_CODE (*argmin) == INTEGER_CST
1145 && TREE_CODE (*argmax) == INTEGER_CST
1146 && (dirprec >= argprec
1147 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1148 int_const_binop (MINUS_EXPR,
1149 *argmax,
1150 *argmin),
1151 size_int (dirprec)))))
1153 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1154 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1156 /* If *ARGMIN is still less than *ARGMAX the conversion above
1157 is safe. Otherwise, it has overflowed and would be unsafe. */
1158 if (tree_int_cst_le (*argmin, *argmax))
1159 return false;
1162 *argmin = TYPE_MIN_VALUE (dirtype);
1163 *argmax = TYPE_MAX_VALUE (dirtype);
1164 return true;
1167 /* Return a range representing the minimum and maximum number of bytes
1168 that the format directive DIR will output for any argument given
1169 the WIDTH and PRECISION (extracted from DIR). This function is
1170 used when the directive argument or its value isn't known. */
1172 static fmtresult
1173 format_integer (const directive &dir, tree arg, vr_values *vr_values)
1175 tree intmax_type_node;
1176 tree uintmax_type_node;
1178 /* Base to format the number in. */
1179 int base;
1181 /* True when a conversion is preceded by a prefix indicating the base
1182 of the argument (octal or hexadecimal). */
1183 bool maybebase = dir.get_flag ('#');
1185 /* True when a signed conversion is preceded by a sign or space. */
1186 bool maybesign = false;
1188 /* True for signed conversions (i.e., 'd' and 'i'). */
1189 bool sign = false;
1191 switch (dir.specifier)
1193 case 'd':
1194 case 'i':
1195 /* Space and '+' are only meaningful for signed conversions. */
1196 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1197 sign = true;
1198 base = 10;
1199 break;
1200 case 'u':
1201 base = 10;
1202 break;
1203 case 'o':
1204 base = 8;
1205 break;
1206 case 'X':
1207 case 'x':
1208 base = 16;
1209 break;
1210 default:
1211 gcc_unreachable ();
1214 /* The type of the "formal" argument expected by the directive. */
1215 tree dirtype = NULL_TREE;
1217 /* Determine the expected type of the argument from the length
1218 modifier. */
1219 switch (dir.modifier)
1221 case FMT_LEN_none:
1222 if (dir.specifier == 'p')
1223 dirtype = ptr_type_node;
1224 else
1225 dirtype = sign ? integer_type_node : unsigned_type_node;
1226 break;
1228 case FMT_LEN_h:
1229 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1230 break;
1232 case FMT_LEN_hh:
1233 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1234 break;
1236 case FMT_LEN_l:
1237 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1238 break;
1240 case FMT_LEN_L:
1241 case FMT_LEN_ll:
1242 dirtype = (sign
1243 ? long_long_integer_type_node
1244 : long_long_unsigned_type_node);
1245 break;
1247 case FMT_LEN_z:
1248 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1249 break;
1251 case FMT_LEN_t:
1252 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1253 break;
1255 case FMT_LEN_j:
1256 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1257 dirtype = sign ? intmax_type_node : uintmax_type_node;
1258 break;
1260 default:
1261 return fmtresult ();
1264 /* The type of the argument to the directive, either deduced from
1265 the actual non-constant argument if one is known, or from
1266 the directive itself when none has been provided because it's
1267 a va_list. */
1268 tree argtype = NULL_TREE;
1270 if (!arg)
1272 /* When the argument has not been provided, use the type of
1273 the directive's argument as an approximation. This will
1274 result in false positives for directives like %i with
1275 arguments with smaller precision (such as short or char). */
1276 argtype = dirtype;
1278 else if (TREE_CODE (arg) == INTEGER_CST)
1280 /* When a constant argument has been provided use its value
1281 rather than type to determine the length of the output. */
1282 fmtresult res;
1284 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1286 /* As a special case, a precision of zero with a zero argument
1287 results in zero bytes except in base 8 when the '#' flag is
1288 specified, and for signed conversions in base 8 and 10 when
1289 either the space or '+' flag has been specified and it results
1290 in just one byte (with width having the normal effect). This
1291 must extend to the case of a specified precision with
1292 an unknown value because it can be zero. */
1293 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1294 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1296 res.range.max = 1;
1297 res.range.likely = 1;
1299 else
1301 res.range.max = res.range.min;
1302 res.range.likely = res.range.min;
1305 else
1307 /* Convert the argument to the type of the directive. */
1308 arg = fold_convert (dirtype, arg);
1310 res.range.min = tree_digits (arg, base, dir.prec[0],
1311 maybesign, maybebase);
1312 if (dir.prec[0] == dir.prec[1])
1313 res.range.max = res.range.min;
1314 else
1315 res.range.max = tree_digits (arg, base, dir.prec[1],
1316 maybesign, maybebase);
1317 res.range.likely = res.range.min;
1318 res.knownrange = true;
1321 res.range.unlikely = res.range.max;
1323 /* Bump up the counters if WIDTH is greater than LEN. */
1324 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1325 (sign | maybebase) + (base == 16));
1326 /* Bump up the counters again if PRECision is greater still. */
1327 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1328 (sign | maybebase) + (base == 16));
1330 return res;
1332 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1333 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1334 /* Determine the type of the provided non-constant argument. */
1335 argtype = TREE_TYPE (arg);
1336 else
1337 /* Don't bother with invalid arguments since they likely would
1338 have already been diagnosed, and disable any further checking
1339 of the format string by returning [-1, -1]. */
1340 return fmtresult ();
1342 fmtresult res;
1344 /* Using either the range the non-constant argument is in, or its
1345 type (either "formal" or actual), create a range of values that
1346 constrain the length of output given the warning level. */
1347 tree argmin = NULL_TREE;
1348 tree argmax = NULL_TREE;
1350 if (arg
1351 && TREE_CODE (arg) == SSA_NAME
1352 && INTEGRAL_TYPE_P (argtype))
1354 /* Try to determine the range of values of the integer argument
1355 (range information is not available for pointers). */
1356 value_range *vr = vr_values->get_value_range (arg);
1357 if (vr->type == VR_RANGE
1358 && TREE_CODE (vr->min) == INTEGER_CST
1359 && TREE_CODE (vr->max) == INTEGER_CST)
1361 argmin = vr->min;
1362 argmax = vr->max;
1364 /* Set KNOWNRANGE if the argument is in a known subrange
1365 of the directive's type and neither width nor precision
1366 is unknown. (KNOWNRANGE may be reset below). */
1367 res.knownrange
1368 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1369 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1370 && dir.known_width_and_precision ());
1372 res.argmin = argmin;
1373 res.argmax = argmax;
1375 else if (vr->type == VR_ANTI_RANGE)
1377 /* Handle anti-ranges if/when bug 71690 is resolved. */
1379 else if (vr->type == VR_VARYING
1380 || vr->type == VR_UNDEFINED)
1382 /* The argument here may be the result of promoting the actual
1383 argument to int. Try to determine the type of the actual
1384 argument before promotion and narrow down its range that
1385 way. */
1386 gimple *def = SSA_NAME_DEF_STMT (arg);
1387 if (is_gimple_assign (def))
1389 tree_code code = gimple_assign_rhs_code (def);
1390 if (code == INTEGER_CST)
1392 arg = gimple_assign_rhs1 (def);
1393 return format_integer (dir, arg, vr_values);
1396 if (code == NOP_EXPR)
1398 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1399 if (INTEGRAL_TYPE_P (type)
1400 || TREE_CODE (type) == POINTER_TYPE)
1401 argtype = type;
1407 if (!argmin)
1409 if (TREE_CODE (argtype) == POINTER_TYPE)
1411 argmin = build_int_cst (pointer_sized_int_node, 0);
1412 argmax = build_all_ones_cst (pointer_sized_int_node);
1414 else
1416 argmin = TYPE_MIN_VALUE (argtype);
1417 argmax = TYPE_MAX_VALUE (argtype);
1421 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1422 of the directive. If it has been cleared then since ARGMIN and/or
1423 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1424 ARGMAX in the result to include in diagnostics. */
1425 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1427 res.knownrange = false;
1428 res.argmin = argmin;
1429 res.argmax = argmax;
1432 /* Recursively compute the minimum and maximum from the known range. */
1433 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1435 /* For unsigned conversions/directives or signed when
1436 the minimum is positive, use the minimum and maximum to compute
1437 the shortest and longest output, respectively. */
1438 res.range.min = format_integer (dir, argmin, vr_values).range.min;
1439 res.range.max = format_integer (dir, argmax, vr_values).range.max;
1441 else if (tree_int_cst_sgn (argmax) < 0)
1443 /* For signed conversions/directives if maximum is negative,
1444 use the minimum as the longest output and maximum as the
1445 shortest output. */
1446 res.range.min = format_integer (dir, argmax, vr_values).range.min;
1447 res.range.max = format_integer (dir, argmin, vr_values).range.max;
1449 else
1451 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1452 as the shortest output and for the longest output compute the
1453 length of the output of both minimum and maximum and pick the
1454 longer. */
1455 unsigned HOST_WIDE_INT max1
1456 = format_integer (dir, argmin, vr_values).range.max;
1457 unsigned HOST_WIDE_INT max2
1458 = format_integer (dir, argmax, vr_values).range.max;
1459 res.range.min
1460 = format_integer (dir, integer_zero_node, vr_values).range.min;
1461 res.range.max = MAX (max1, max2);
1464 /* If the range is known, use the maximum as the likely length. */
1465 if (res.knownrange)
1466 res.range.likely = res.range.max;
1467 else
1469 /* Otherwise, use the minimum. Except for the case where for %#x or
1470 %#o the minimum is just for a single value in the range (0) and
1471 for all other values it is something longer, like 0x1 or 01.
1472 Use the length for value 1 in that case instead as the likely
1473 length. */
1474 res.range.likely = res.range.min;
1475 if (maybebase
1476 && base != 10
1477 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1479 if (res.range.min == 1)
1480 res.range.likely += base == 8 ? 1 : 2;
1481 else if (res.range.min == 2
1482 && base == 16
1483 && (dir.width[0] == 2 || dir.prec[0] == 2))
1484 ++res.range.likely;
1488 res.range.unlikely = res.range.max;
1489 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1490 (sign | maybebase) + (base == 16));
1491 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1492 (sign | maybebase) + (base == 16));
1494 return res;
1497 /* Return the number of bytes that a format directive consisting of FLAGS,
1498 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1499 would result for argument X under ideal conditions (i.e., if PREC
1500 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1501 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1502 This function works around those problems. */
1504 static unsigned HOST_WIDE_INT
1505 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1506 char spec, char rndspec)
1508 char fmtstr[40];
1510 HOST_WIDE_INT len = strlen (flags);
1512 fmtstr[0] = '%';
1513 memcpy (fmtstr + 1, flags, len);
1514 memcpy (fmtstr + 1 + len, ".*R", 3);
1515 fmtstr[len + 4] = rndspec;
1516 fmtstr[len + 5] = spec;
1517 fmtstr[len + 6] = '\0';
1519 spec = TOUPPER (spec);
1520 if (spec == 'E' || spec == 'F')
1522 /* For %e, specify the precision explicitly since mpfr_sprintf
1523 does its own thing just to be different (see MPFR bug 21088). */
1524 if (prec < 0)
1525 prec = 6;
1527 else
1529 /* Avoid passing negative precisions with larger magnitude to MPFR
1530 to avoid exposing its bugs. (A negative precision is supposed
1531 to be ignored.) */
1532 if (prec < 0)
1533 prec = -1;
1536 HOST_WIDE_INT p = prec;
1538 if (spec == 'G' && !strchr (flags, '#'))
1540 /* For G/g without the pound flag, precision gives the maximum number
1541 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1542 a 128 bit IEEE extended precision, 4932. Using twice as much here
1543 should be more than sufficient for any real format. */
1544 if ((IEEE_MAX_10_EXP * 2) < prec)
1545 prec = IEEE_MAX_10_EXP * 2;
1546 p = prec;
1548 else
1550 /* Cap precision arbitrarily at 1KB and add the difference
1551 (if any) to the MPFR result. */
1552 if (prec > 1024)
1553 p = 1024;
1556 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1558 /* Handle the unlikely (impossible?) error by returning more than
1559 the maximum dictated by the function's return type. */
1560 if (len < 0)
1561 return target_dir_max () + 1;
1563 /* Adjust the return value by the difference. */
1564 if (p < prec)
1565 len += prec - p;
1567 return len;
1570 /* Return the number of bytes to format using the format specifier
1571 SPEC and the precision PREC the largest value in the real floating
1572 TYPE. */
1574 static unsigned HOST_WIDE_INT
1575 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1577 machine_mode mode = TYPE_MODE (type);
1579 /* IBM Extended mode. */
1580 if (MODE_COMPOSITE_P (mode))
1581 mode = DFmode;
1583 /* Get the real type format desription for the target. */
1584 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1585 REAL_VALUE_TYPE rv;
1587 real_maxval (&rv, 0, mode);
1589 /* Convert the GCC real value representation with the precision
1590 of the real type to the mpfr_t format with the GCC default
1591 round-to-nearest mode. */
1592 mpfr_t x;
1593 mpfr_init2 (x, rfmt->p);
1594 mpfr_from_real (x, &rv, GMP_RNDN);
1596 /* Return a value one greater to account for the leading minus sign. */
1597 unsigned HOST_WIDE_INT r
1598 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1599 mpfr_clear (x);
1600 return r;
1603 /* Return a range representing the minimum and maximum number of bytes
1604 that the directive DIR will output for any argument. PREC gives
1605 the adjusted precision range to account for negative precisions
1606 meaning the default 6. This function is used when the directive
1607 argument or its value isn't known. */
1609 static fmtresult
1610 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1612 tree type;
1614 switch (dir.modifier)
1616 case FMT_LEN_l:
1617 case FMT_LEN_none:
1618 type = double_type_node;
1619 break;
1621 case FMT_LEN_L:
1622 type = long_double_type_node;
1623 break;
1625 case FMT_LEN_ll:
1626 type = long_double_type_node;
1627 break;
1629 default:
1630 return fmtresult ();
1633 /* The minimum and maximum number of bytes produced by the directive. */
1634 fmtresult res;
1636 /* The minimum output as determined by flags. It's always at least 1.
1637 When plus or space are set the output is preceded by either a sign
1638 or a space. */
1639 unsigned flagmin = (1 /* for the first digit */
1640 + (dir.get_flag ('+') | dir.get_flag (' ')));
1642 /* The minimum is 3 for "inf" and "nan" for all specifiers, plus 1
1643 for the plus sign/space with the '+' and ' ' flags, respectively,
1644 unless reduced below. */
1645 res.range.min = 2 + flagmin;
1647 /* When the pound flag is set the decimal point is included in output
1648 regardless of precision. Whether or not a decimal point is included
1649 otherwise depends on the specification and precision. */
1650 bool radix = dir.get_flag ('#');
1652 switch (dir.specifier)
1654 case 'A':
1655 case 'a':
1657 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1658 if (dir.prec[0] <= 0)
1659 minprec = 0;
1660 else if (dir.prec[0] > 0)
1661 minprec = dir.prec[0] + !radix /* decimal point */;
1663 res.range.likely = (2 /* 0x */
1664 + flagmin
1665 + radix
1666 + minprec
1667 + 3 /* p+0 */);
1669 res.range.max = format_floating_max (type, 'a', prec[1]);
1671 /* The unlikely maximum accounts for the longest multibyte
1672 decimal point character. */
1673 res.range.unlikely = res.range.max;
1674 if (dir.prec[1] > 0)
1675 res.range.unlikely += target_mb_len_max () - 1;
1677 break;
1680 case 'E':
1681 case 'e':
1683 /* Minimum output attributable to precision and, when it's
1684 non-zero, decimal point. */
1685 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1687 /* The likely minimum output is "[-+]1.234567e+00" regardless
1688 of the value of the actual argument. */
1689 res.range.likely = (flagmin
1690 + radix
1691 + minprec
1692 + 2 /* e+ */ + 2);
1694 res.range.max = format_floating_max (type, 'e', prec[1]);
1696 /* The unlikely maximum accounts for the longest multibyte
1697 decimal point character. */
1698 if (dir.prec[0] != dir.prec[1]
1699 || dir.prec[0] == -1 || dir.prec[0] > 0)
1700 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1701 else
1702 res.range.unlikely = res.range.max;
1703 break;
1706 case 'F':
1707 case 'f':
1709 /* Minimum output attributable to precision and, when it's non-zero,
1710 decimal point. */
1711 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1713 /* For finite numbers (i.e., not infinity or NaN) the lower bound
1714 when precision isn't specified is 8 bytes ("1.23456" since
1715 precision is taken to be 6). When precision is zero, the lower
1716 bound is 1 byte (e.g., "1"). Otherwise, when precision is greater
1717 than zero, then the lower bound is 2 plus precision (plus flags).
1718 But in all cases, the lower bound is no greater than 3. */
1719 unsigned HOST_WIDE_INT min = flagmin + radix + minprec;
1720 if (min < res.range.min)
1721 res.range.min = min;
1723 /* Compute the upper bound for -TYPE_MAX. */
1724 res.range.max = format_floating_max (type, 'f', prec[1]);
1726 /* The minimum output with unknown precision is a single byte
1727 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1728 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1729 res.range.likely = 3;
1730 else
1731 res.range.likely = min;
1733 /* The unlikely maximum accounts for the longest multibyte
1734 decimal point character. */
1735 if (dir.prec[0] != dir.prec[1]
1736 || dir.prec[0] == -1 || dir.prec[0] > 0)
1737 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1738 break;
1741 case 'G':
1742 case 'g':
1744 /* The %g output depends on precision and the exponent of
1745 the argument. Since the value of the argument isn't known
1746 the lower bound on the range of bytes (not counting flags
1747 or width) is 1 plus radix (i.e., either "0" or "0." for
1748 "%g" and "%#g", respectively, with a zero argument). */
1749 unsigned HOST_WIDE_INT min = flagmin + radix;
1750 if (min < res.range.min)
1751 res.range.min = min;
1753 char spec = 'g';
1754 HOST_WIDE_INT maxprec = dir.prec[1];
1755 if (radix && maxprec)
1757 /* When the pound flag (radix) is set, trailing zeros aren't
1758 trimmed and so the longest output is the same as for %e,
1759 except with precision minus 1 (as specified in C11). */
1760 spec = 'e';
1761 if (maxprec > 0)
1762 --maxprec;
1763 else if (maxprec < 0)
1764 maxprec = 5;
1766 else
1767 maxprec = prec[1];
1769 res.range.max = format_floating_max (type, spec, maxprec);
1771 /* The likely output is either the maximum computed above
1772 minus 1 (assuming the maximum is positive) when precision
1773 is known (or unspecified), or the same minimum as for %e
1774 (which is computed for a non-negative argument). Unlike
1775 for the other specifiers above the likely output isn't
1776 the minimum because for %g that's 1 which is unlikely. */
1777 if (dir.prec[1] < 0
1778 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1779 res.range.likely = res.range.max - 1;
1780 else
1782 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1783 res.range.likely = (flagmin
1784 + radix
1785 + minprec
1786 + 2 /* e+ */ + 2);
1789 /* The unlikely maximum accounts for the longest multibyte
1790 decimal point character. */
1791 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1792 break;
1795 default:
1796 return fmtresult ();
1799 /* Bump up the byte counters if WIDTH is greater. */
1800 res.adjust_for_width_or_precision (dir.width);
1801 return res;
1804 /* Return a range representing the minimum and maximum number of bytes
1805 that the directive DIR will write on output for the floating argument
1806 ARG. */
1808 static fmtresult
1809 format_floating (const directive &dir, tree arg, vr_values *)
1811 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1812 tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1813 ? long_double_type_node : double_type_node);
1815 /* For an indeterminate precision the lower bound must be assumed
1816 to be zero. */
1817 if (TOUPPER (dir.specifier) == 'A')
1819 /* Get the number of fractional decimal digits needed to represent
1820 the argument without a loss of accuracy. */
1821 unsigned fmtprec
1822 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1824 /* The precision of the IEEE 754 double format is 53.
1825 The precision of all other GCC binary double formats
1826 is 56 or less. */
1827 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1829 /* For %a, leave the minimum precision unspecified to let
1830 MFPR trim trailing zeros (as it and many other systems
1831 including Glibc happen to do) and set the maximum
1832 precision to reflect what it would be with trailing zeros
1833 present (as Solaris and derived systems do). */
1834 if (dir.prec[1] < 0)
1836 /* Both bounds are negative implies that precision has
1837 not been specified. */
1838 prec[0] = maxprec;
1839 prec[1] = -1;
1841 else if (dir.prec[0] < 0)
1843 /* With a negative lower bound and a non-negative upper
1844 bound set the minimum precision to zero and the maximum
1845 to the greater of the maximum precision (i.e., with
1846 trailing zeros present) and the specified upper bound. */
1847 prec[0] = 0;
1848 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1851 else if (dir.prec[0] < 0)
1853 if (dir.prec[1] < 0)
1855 /* A precision in a strictly negative range is ignored and
1856 the default of 6 is used instead. */
1857 prec[0] = prec[1] = 6;
1859 else
1861 /* For a precision in a partly negative range, the lower bound
1862 must be assumed to be zero and the new upper bound is the
1863 greater of 6 (the default precision used when the specified
1864 precision is negative) and the upper bound of the specified
1865 range. */
1866 prec[0] = 0;
1867 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1871 if (!arg
1872 || TREE_CODE (arg) != REAL_CST
1873 || !useless_type_conversion_p (type, TREE_TYPE (arg)))
1874 return format_floating (dir, prec);
1876 /* The minimum and maximum number of bytes produced by the directive. */
1877 fmtresult res;
1879 /* Get the real type format desription for the target. */
1880 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1881 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1883 if (!real_isfinite (rvp))
1885 /* The format for Infinity and NaN is "[-]inf"/"[-]infinity"
1886 and "[-]nan" with the choice being implementation-defined
1887 but not locale dependent. */
1888 bool sign = dir.get_flag ('+') || real_isneg (rvp);
1889 res.range.min = 3 + sign;
1891 res.range.likely = res.range.min;
1892 res.range.max = res.range.min;
1893 /* The unlikely maximum is "[-/+]infinity" or "[-/+][qs]nan".
1894 For NaN, the C/POSIX standards specify two formats:
1895 "[-/+]nan"
1897 "[-/+]nan(n-char-sequence)"
1898 No known printf implementation outputs the latter format but AIX
1899 outputs QNaN and SNaN for quiet and signalling NaN, respectively,
1900 so the unlikely maximum reflects that. */
1901 res.range.unlikely = sign + (real_isinf (rvp) ? 8 : 4);
1903 /* The range for infinity and NaN is known unless either width
1904 or precision is unknown. Width has the same effect regardless
1905 of whether the argument is finite. Precision is either ignored
1906 (e.g., Glibc) or can have an effect on the short vs long format
1907 such as inf/infinity (e.g., Solaris). */
1908 res.knownrange = dir.known_width_and_precision ();
1910 /* Adjust the range for width but ignore precision. */
1911 res.adjust_for_width_or_precision (dir.width);
1913 return res;
1916 char fmtstr [40];
1917 char *pfmt = fmtstr;
1919 /* Append flags. */
1920 for (const char *pf = "-+ #0"; *pf; ++pf)
1921 if (dir.get_flag (*pf))
1922 *pfmt++ = *pf;
1924 *pfmt = '\0';
1927 /* Set up an array to easily iterate over. */
1928 unsigned HOST_WIDE_INT* const minmax[] = {
1929 &res.range.min, &res.range.max
1932 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1934 /* Convert the GCC real value representation with the precision
1935 of the real type to the mpfr_t format rounding down in the
1936 first iteration that computes the minimm and up in the second
1937 that computes the maximum. This order is arbibtrary because
1938 rounding in either direction can result in longer output. */
1939 mpfr_t mpfrval;
1940 mpfr_init2 (mpfrval, rfmt->p);
1941 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1943 /* Use the MPFR rounding specifier to round down in the first
1944 iteration and then up. In most but not all cases this will
1945 result in the same number of bytes. */
1946 char rndspec = "DU"[i];
1948 /* Format it and store the result in the corresponding member
1949 of the result struct. */
1950 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1951 dir.specifier, rndspec);
1952 mpfr_clear (mpfrval);
1956 /* Make sure the minimum is less than the maximum (MPFR rounding
1957 in the call to mpfr_snprintf can result in the reverse. */
1958 if (res.range.max < res.range.min)
1960 unsigned HOST_WIDE_INT tmp = res.range.min;
1961 res.range.min = res.range.max;
1962 res.range.max = tmp;
1965 /* The range is known unless either width or precision is unknown. */
1966 res.knownrange = dir.known_width_and_precision ();
1968 /* For the same floating point constant, unless width or precision
1969 is unknown, use the longer output as the likely maximum since
1970 with round to nearest either is equally likely. Otheriwse, when
1971 precision is unknown, use the greater of the minimum and 3 as
1972 the likely output (for "0.0" since zero precision is unlikely). */
1973 if (res.knownrange)
1974 res.range.likely = res.range.max;
1975 else if (res.range.min < 3
1976 && dir.prec[0] < 0
1977 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
1978 res.range.likely = 3;
1979 else
1980 res.range.likely = res.range.min;
1982 res.range.unlikely = res.range.max;
1984 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
1986 /* Unless the precision is zero output longer than 2 bytes may
1987 include the decimal point which must be a single character
1988 up to MB_LEN_MAX in length. This is overly conservative
1989 since in some conversions some constants result in no decimal
1990 point (e.g., in %g). */
1991 res.range.unlikely += target_mb_len_max () - 1;
1994 res.adjust_for_width_or_precision (dir.width);
1995 return res;
1998 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1999 strings referenced by the expression STR, or (-1, -1) when not known.
2000 Used by the format_string function below. */
2002 static fmtresult
2003 get_string_length (tree str, unsigned eltsize)
2005 if (!str)
2006 return fmtresult ();
2008 c_strlen_data data;
2009 memset (&data, 0, sizeof (c_strlen_data));
2010 tree slen = c_strlen (str, 1, &data, eltsize);
2011 if (slen && TREE_CODE (slen) == INTEGER_CST)
2013 /* The string is properly terminated and
2014 we know its length. */
2015 fmtresult res (tree_to_shwi (slen));
2016 res.nonstr = NULL_TREE;
2017 return res;
2019 else if (!slen
2020 && data.decl
2021 && data.len
2022 && TREE_CODE (data.len) == INTEGER_CST)
2024 /* STR was not properly NUL terminated, but we have
2025 length information about the unterminated string. */
2026 fmtresult res (tree_to_shwi (data.len));
2027 res.nonstr = data.decl;
2028 return res;
2031 /* Determine the length of the shortest and longest string referenced
2032 by STR. Strings of unknown lengths are bounded by the sizes of
2033 arrays that subexpressions of STR may refer to. Pointers that
2034 aren't known to point any such arrays result in LENRANGE[1] set
2035 to SIZE_MAX. NONSTR is set to the declaration of the constant
2036 array that is known not to be nul-terminated. */
2037 tree lenrange[2];
2038 tree nonstr;
2039 bool flexarray = get_range_strlen (str, lenrange, eltsize, false, &nonstr);
2041 if (lenrange [0] || lenrange [1])
2043 HOST_WIDE_INT min
2044 = (tree_fits_uhwi_p (lenrange[0])
2045 ? tree_to_uhwi (lenrange[0])
2046 : 0);
2048 HOST_WIDE_INT max
2049 = (tree_fits_uhwi_p (lenrange[1])
2050 ? tree_to_uhwi (lenrange[1])
2051 : HOST_WIDE_INT_M1U);
2053 /* get_range_strlen() returns the target value of SIZE_MAX for
2054 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2055 which may be bigger. */
2056 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2057 min = HOST_WIDE_INT_M1U;
2058 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2059 max = HOST_WIDE_INT_M1U;
2061 fmtresult res (min, max);
2062 res.nonstr = nonstr;
2064 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2065 by STR are known to be bounded (though not necessarily by their
2066 actual length but perhaps by their maximum possible length). */
2067 if (res.range.max < target_int_max ())
2069 res.knownrange = true;
2070 /* When the the length of the longest string is known and not
2071 excessive use it as the likely length of the string(s). */
2072 res.range.likely = res.range.max;
2074 else
2076 /* When the upper bound is unknown (it can be zero or excessive)
2077 set the likely length to the greater of 1 and the length of
2078 the shortest string and reset the lower bound to zero. */
2079 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2080 res.range.min = 0;
2083 /* If the range of string length has been estimated from the size
2084 of an array at the end of a struct assume that it's longer than
2085 the array bound says it is in case it's used as a poor man's
2086 flexible array member, such as in struct S { char a[4]; }; */
2087 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
2089 return res;
2092 return fmtresult ();
2095 /* Return the minimum and maximum number of characters formatted
2096 by the '%c' format directives and its wide character form for
2097 the argument ARG. ARG can be null (for functions such as
2098 vsprinf). */
2100 static fmtresult
2101 format_character (const directive &dir, tree arg, vr_values *vr_values)
2103 fmtresult res;
2105 res.knownrange = true;
2107 if (dir.specifier == 'C'
2108 || dir.modifier == FMT_LEN_l)
2110 /* A wide character can result in as few as zero bytes. */
2111 res.range.min = 0;
2113 HOST_WIDE_INT min, max;
2114 if (get_int_range (arg, &min, &max, false, 0, vr_values))
2116 if (min == 0 && max == 0)
2118 /* The NUL wide character results in no bytes. */
2119 res.range.max = 0;
2120 res.range.likely = 0;
2121 res.range.unlikely = 0;
2123 else if (min >= 0 && min < 128)
2125 /* Be conservative if the target execution character set
2126 is not a 1-to-1 mapping to the source character set or
2127 if the source set is not ASCII. */
2128 bool one_2_one_ascii
2129 = (target_to_host_charmap[0] == 1 && target_to_host ('a') == 97);
2131 /* A wide character in the ASCII range most likely results
2132 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2133 res.range.max = one_2_one_ascii ? 1 : target_mb_len_max ();;
2134 res.range.likely = 1;
2135 res.range.unlikely = target_mb_len_max ();
2136 res.mayfail = !one_2_one_ascii;
2138 else
2140 /* A wide character outside the ASCII range likely results
2141 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2142 res.range.max = target_mb_len_max ();
2143 res.range.likely = 2;
2144 res.range.unlikely = res.range.max;
2145 /* Converting such a character may fail. */
2146 res.mayfail = true;
2149 else
2151 /* An unknown wide character is treated the same as a wide
2152 character outside the ASCII range. */
2153 res.range.max = target_mb_len_max ();
2154 res.range.likely = 2;
2155 res.range.unlikely = res.range.max;
2156 res.mayfail = true;
2159 else
2161 /* A plain '%c' directive. Its ouput is exactly 1. */
2162 res.range.min = res.range.max = 1;
2163 res.range.likely = res.range.unlikely = 1;
2164 res.knownrange = true;
2167 /* Bump up the byte counters if WIDTH is greater. */
2168 return res.adjust_for_width_or_precision (dir.width);
2171 /* Return the minimum and maximum number of characters formatted
2172 by the '%s' format directive and its wide character form for
2173 the argument ARG. ARG can be null (for functions such as
2174 vsprinf). */
2176 static fmtresult
2177 format_string (const directive &dir, tree arg, vr_values *)
2179 fmtresult res;
2181 /* Compute the range the argument's length can be in. */
2182 int count_by = 1;
2183 if (dir.specifier == 'S' || dir.modifier == FMT_LEN_l)
2185 /* Get a node for a C type that will be the same size
2186 as a wchar_t on the target. */
2187 tree node = get_typenode_from_name (MODIFIED_WCHAR_TYPE);
2189 /* Now that we have a suitable node, get the number of
2190 bytes it occupies. */
2191 count_by = int_size_in_bytes (node);
2192 gcc_checking_assert (count_by == 2 || count_by == 4);
2195 fmtresult slen = get_string_length (arg, count_by);
2196 if (slen.range.min == slen.range.max
2197 && slen.range.min < HOST_WIDE_INT_MAX)
2199 /* The argument is either a string constant or it refers
2200 to one of a number of strings of the same length. */
2202 /* A '%s' directive with a string argument with constant length. */
2203 res.range = slen.range;
2205 if (dir.specifier == 'S'
2206 || dir.modifier == FMT_LEN_l)
2208 /* In the worst case the length of output of a wide string S
2209 is bounded by MB_LEN_MAX * wcslen (S). */
2210 res.range.max *= target_mb_len_max ();
2211 res.range.unlikely = res.range.max;
2212 /* It's likely that the the total length is not more that
2213 2 * wcslen (S).*/
2214 res.range.likely = res.range.min * 2;
2216 if (dir.prec[1] >= 0
2217 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2219 res.range.max = dir.prec[1];
2220 res.range.likely = dir.prec[1];
2221 res.range.unlikely = dir.prec[1];
2224 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2225 res.range.min = 0;
2226 else if (dir.prec[0] >= 0)
2227 res.range.likely = dir.prec[0];
2229 /* Even a non-empty wide character string need not convert into
2230 any bytes. */
2231 res.range.min = 0;
2233 /* A non-empty wide character conversion may fail. */
2234 if (slen.range.max > 0)
2235 res.mayfail = true;
2237 else
2239 res.knownrange = true;
2241 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2242 res.range.min = 0;
2243 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2244 res.range.min = dir.prec[0];
2246 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2248 res.range.max = dir.prec[1];
2249 res.range.likely = dir.prec[1];
2250 res.range.unlikely = dir.prec[1];
2254 else if (arg && integer_zerop (arg))
2256 /* Handle null pointer argument. */
2258 fmtresult res (0);
2259 res.nullp = true;
2260 return res;
2262 else
2264 /* For a '%s' and '%ls' directive with a non-constant string (either
2265 one of a number of strings of known length or an unknown string)
2266 the minimum number of characters is lesser of PRECISION[0] and
2267 the length of the shortest known string or zero, and the maximum
2268 is the lessser of the length of the longest known string or
2269 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2270 the minimum at level 1 and the greater of the minimum and 1
2271 at level 2. This result is adjust upward for width (if it's
2272 specified). */
2274 if (dir.specifier == 'S'
2275 || dir.modifier == FMT_LEN_l)
2277 /* A wide character converts to as few as zero bytes. */
2278 slen.range.min = 0;
2279 if (slen.range.max < target_int_max ())
2280 slen.range.max *= target_mb_len_max ();
2282 if (slen.range.likely < target_int_max ())
2283 slen.range.likely *= 2;
2285 if (slen.range.likely < target_int_max ())
2286 slen.range.unlikely *= target_mb_len_max ();
2288 /* A non-empty wide character conversion may fail. */
2289 if (slen.range.max > 0)
2290 res.mayfail = true;
2293 res.range = slen.range;
2295 if (dir.prec[0] >= 0)
2297 /* Adjust the minimum to zero if the string length is unknown,
2298 or at most the lower bound of the precision otherwise. */
2299 if (slen.range.min >= target_int_max ())
2300 res.range.min = 0;
2301 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2302 res.range.min = dir.prec[0];
2304 /* Make both maxima no greater than the upper bound of precision. */
2305 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2306 || slen.range.max >= target_int_max ())
2308 res.range.max = dir.prec[1];
2309 res.range.unlikely = dir.prec[1];
2312 /* If precision is constant, set the likely counter to the lesser
2313 of it and the maximum string length. Otherwise, if the lower
2314 bound of precision is greater than zero, set the likely counter
2315 to the minimum. Otherwise set it to zero or one based on
2316 the warning level. */
2317 if (dir.prec[0] == dir.prec[1])
2318 res.range.likely
2319 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2320 ? dir.prec[0] : slen.range.max);
2321 else if (dir.prec[0] > 0)
2322 res.range.likely = res.range.min;
2323 else
2324 res.range.likely = warn_level > 1;
2326 else if (dir.prec[1] >= 0)
2328 res.range.min = 0;
2329 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2330 res.range.max = dir.prec[1];
2331 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2333 else if (slen.range.min >= target_int_max ())
2335 res.range.min = 0;
2336 res.range.max = HOST_WIDE_INT_MAX;
2337 /* At level 1 strings of unknown length are assumed to be
2338 empty, while at level 1 they are assumed to be one byte
2339 long. */
2340 res.range.likely = warn_level > 1;
2342 else
2344 /* A string of unknown length unconstrained by precision is
2345 assumed to be empty at level 1 and just one character long
2346 at higher levels. */
2347 if (res.range.likely >= target_int_max ())
2348 res.range.likely = warn_level > 1;
2351 res.range.unlikely = res.range.max;
2354 /* If the argument isn't a nul-terminated string and the number
2355 of bytes on output isn't bounded by precision, set NONSTR. */
2356 if (slen.nonstr && slen.range.min < (unsigned HOST_WIDE_INT)dir.prec[0])
2357 res.nonstr = slen.nonstr;
2359 /* Bump up the byte counters if WIDTH is greater. */
2360 return res.adjust_for_width_or_precision (dir.width);
2363 /* Format plain string (part of the format string itself). */
2365 static fmtresult
2366 format_plain (const directive &dir, tree, vr_values *)
2368 fmtresult res (dir.len);
2369 return res;
2372 /* Return true if the RESULT of a directive in a call describe by INFO
2373 should be diagnosed given the AVAILable space in the destination. */
2375 static bool
2376 should_warn_p (const sprintf_dom_walker::call_info &info,
2377 const result_range &avail, const result_range &result)
2379 if (result.max <= avail.min)
2381 /* The least amount of space remaining in the destination is big
2382 enough for the longest output. */
2383 return false;
2386 if (info.bounded)
2388 if (warn_format_trunc == 1 && result.min <= avail.max
2389 && info.retval_used ())
2391 /* The likely amount of space remaining in the destination is big
2392 enough for the least output and the return value is used. */
2393 return false;
2396 if (warn_format_trunc == 1 && result.likely <= avail.likely
2397 && !info.retval_used ())
2399 /* The likely amount of space remaining in the destination is big
2400 enough for the likely output and the return value is unused. */
2401 return false;
2404 if (warn_format_trunc == 2
2405 && result.likely <= avail.min
2406 && (result.max <= avail.min
2407 || result.max > HOST_WIDE_INT_MAX))
2409 /* The minimum amount of space remaining in the destination is big
2410 enough for the longest output. */
2411 return false;
2414 else
2416 if (warn_level == 1 && result.likely <= avail.likely)
2418 /* The likely amount of space remaining in the destination is big
2419 enough for the likely output. */
2420 return false;
2423 if (warn_level == 2
2424 && result.likely <= avail.min
2425 && (result.max <= avail.min
2426 || result.max > HOST_WIDE_INT_MAX))
2428 /* The minimum amount of space remaining in the destination is big
2429 enough for the longest output. */
2430 return false;
2434 return true;
2437 /* At format string location describe by DIRLOC in a call described
2438 by INFO, issue a warning for a directive DIR whose output may be
2439 in excess of the available space AVAIL_RANGE in the destination
2440 given the formatting result FMTRES. This function does nothing
2441 except decide whether to issue a warning for a possible write
2442 past the end or truncation and, if so, format the warning.
2443 Return true if a warning has been issued. */
2445 static bool
2446 maybe_warn (substring_loc &dirloc, location_t argloc,
2447 const sprintf_dom_walker::call_info &info,
2448 const result_range &avail_range, const result_range &res,
2449 const directive &dir)
2451 if (!should_warn_p (info, avail_range, res))
2452 return false;
2454 /* A warning will definitely be issued below. */
2456 /* The maximum byte count to reference in the warning. Larger counts
2457 imply that the upper bound is unknown (and could be anywhere between
2458 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2459 than "between N and X" where X is some huge number. */
2460 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2462 /* True when there is enough room in the destination for the least
2463 amount of a directive's output but not enough for its likely or
2464 maximum output. */
2465 bool maybe = (res.min <= avail_range.max
2466 && (avail_range.min < res.likely
2467 || (res.max < HOST_WIDE_INT_MAX
2468 && avail_range.min < res.max)));
2470 /* Buffer for the directive in the host character set (used when
2471 the source character set is different). */
2472 char hostdir[32];
2474 if (avail_range.min == avail_range.max)
2476 /* The size of the destination region is exact. */
2477 unsigned HOST_WIDE_INT navail = avail_range.max;
2479 if (target_to_host (*dir.beg) != '%')
2481 /* For plain character directives (i.e., the format string itself)
2482 but not others, point the caret at the first character that's
2483 past the end of the destination. */
2484 if (navail < dir.len)
2485 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2488 if (*dir.beg == '\0')
2490 /* This is the terminating nul. */
2491 gcc_assert (res.min == 1 && res.min == res.max);
2493 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2494 info.bounded
2495 ? (maybe
2496 ? G_("%qE output may be truncated before the "
2497 "last format character")
2498 : G_("%qE output truncated before the last "
2499 "format character"))
2500 : (maybe
2501 ? G_("%qE may write a terminating nul past the "
2502 "end of the destination")
2503 : G_("%qE writing a terminating nul past the "
2504 "end of the destination")),
2505 info.func);
2508 if (res.min == res.max)
2510 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2511 if (!info.bounded)
2512 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2513 "%<%.*s%> directive writing %wu byte into a "
2514 "region of size %wu",
2515 "%<%.*s%> directive writing %wu bytes into a "
2516 "region of size %wu",
2517 (int) dir.len, d, res.min, navail);
2518 else if (maybe)
2519 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2520 "%<%.*s%> directive output may be truncated "
2521 "writing %wu byte into a region of size %wu",
2522 "%<%.*s%> directive output may be truncated "
2523 "writing %wu bytes into a region of size %wu",
2524 (int) dir.len, d, res.min, navail);
2525 else
2526 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2527 "%<%.*s%> directive output truncated writing "
2528 "%wu byte into a region of size %wu",
2529 "%<%.*s%> directive output truncated writing "
2530 "%wu bytes into a region of size %wu",
2531 (int) dir.len, d, res.min, navail);
2533 if (res.min == 0 && res.max < maxbytes)
2534 return fmtwarn (dirloc, argloc, NULL,
2535 info.warnopt (),
2536 info.bounded
2537 ? (maybe
2538 ? G_("%<%.*s%> directive output may be truncated "
2539 "writing up to %wu bytes into a region of "
2540 "size %wu")
2541 : G_("%<%.*s%> directive output truncated writing "
2542 "up to %wu bytes into a region of size %wu"))
2543 : G_("%<%.*s%> directive writing up to %wu bytes "
2544 "into a region of size %wu"), (int) dir.len,
2545 target_to_host (hostdir, sizeof hostdir, dir.beg),
2546 res.max, navail);
2548 if (res.min == 0 && maxbytes <= res.max)
2549 /* This is a special case to avoid issuing the potentially
2550 confusing warning:
2551 writing 0 or more bytes into a region of size 0. */
2552 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2553 info.bounded
2554 ? (maybe
2555 ? G_("%<%.*s%> directive output may be truncated "
2556 "writing likely %wu or more bytes into a "
2557 "region of size %wu")
2558 : G_("%<%.*s%> directive output truncated writing "
2559 "likely %wu or more bytes into a region of "
2560 "size %wu"))
2561 : G_("%<%.*s%> directive writing likely %wu or more "
2562 "bytes into a region of size %wu"), (int) dir.len,
2563 target_to_host (hostdir, sizeof hostdir, dir.beg),
2564 res.likely, navail);
2566 if (res.max < maxbytes)
2567 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2568 info.bounded
2569 ? (maybe
2570 ? G_("%<%.*s%> directive output may be truncated "
2571 "writing between %wu and %wu bytes into a "
2572 "region of size %wu")
2573 : G_("%<%.*s%> directive output truncated "
2574 "writing between %wu and %wu bytes into a "
2575 "region of size %wu"))
2576 : G_("%<%.*s%> directive writing between %wu and "
2577 "%wu bytes into a region of size %wu"),
2578 (int) dir.len,
2579 target_to_host (hostdir, sizeof hostdir, dir.beg),
2580 res.min, res.max, navail);
2582 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2583 info.bounded
2584 ? (maybe
2585 ? G_("%<%.*s%> directive output may be truncated "
2586 "writing %wu or more bytes into a region of "
2587 "size %wu")
2588 : G_("%<%.*s%> directive output truncated writing "
2589 "%wu or more bytes into a region of size %wu"))
2590 : G_("%<%.*s%> directive writing %wu or more bytes "
2591 "into a region of size %wu"), (int) dir.len,
2592 target_to_host (hostdir, sizeof hostdir, dir.beg),
2593 res.min, navail);
2596 /* The size of the destination region is a range. */
2598 if (target_to_host (*dir.beg) != '%')
2600 unsigned HOST_WIDE_INT navail = avail_range.max;
2602 /* For plain character directives (i.e., the format string itself)
2603 but not others, point the caret at the first character that's
2604 past the end of the destination. */
2605 if (navail < dir.len)
2606 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2609 if (*dir.beg == '\0')
2611 gcc_assert (res.min == 1 && res.min == res.max);
2613 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2614 info.bounded
2615 ? (maybe
2616 ? G_("%qE output may be truncated before the last "
2617 "format character")
2618 : G_("%qE output truncated before the last format "
2619 "character"))
2620 : (maybe
2621 ? G_("%qE may write a terminating nul past the end "
2622 "of the destination")
2623 : G_("%qE writing a terminating nul past the end "
2624 "of the destination")), info.func);
2627 if (res.min == res.max)
2629 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2630 if (!info.bounded)
2631 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2632 "%<%.*s%> directive writing %wu byte into a region "
2633 "of size between %wu and %wu",
2634 "%<%.*s%> directive writing %wu bytes into a region "
2635 "of size between %wu and %wu", (int) dir.len, d,
2636 res.min, avail_range.min, avail_range.max);
2637 else if (maybe)
2638 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2639 "%<%.*s%> directive output may be truncated writing "
2640 "%wu byte into a region of size between %wu and %wu",
2641 "%<%.*s%> directive output may be truncated writing "
2642 "%wu bytes into a region of size between %wu and "
2643 "%wu", (int) dir.len, d, res.min, avail_range.min,
2644 avail_range.max);
2645 else
2646 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2647 "%<%.*s%> directive output truncated writing %wu "
2648 "byte into a region of size between %wu and %wu",
2649 "%<%.*s%> directive output truncated writing %wu "
2650 "bytes into a region of size between %wu and %wu",
2651 (int) dir.len, d, res.min, avail_range.min,
2652 avail_range.max);
2655 if (res.min == 0 && res.max < maxbytes)
2656 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2657 info.bounded
2658 ? (maybe
2659 ? G_("%<%.*s%> directive output may be truncated "
2660 "writing up to %wu bytes into a region of size "
2661 "between %wu and %wu")
2662 : G_("%<%.*s%> directive output truncated writing "
2663 "up to %wu bytes into a region of size between "
2664 "%wu and %wu"))
2665 : G_("%<%.*s%> directive writing up to %wu bytes "
2666 "into a region of size between %wu and %wu"),
2667 (int) dir.len,
2668 target_to_host (hostdir, sizeof hostdir, dir.beg),
2669 res.max, avail_range.min, avail_range.max);
2671 if (res.min == 0 && maxbytes <= res.max)
2672 /* This is a special case to avoid issuing the potentially confusing
2673 warning:
2674 writing 0 or more bytes into a region of size between 0 and N. */
2675 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2676 info.bounded
2677 ? (maybe
2678 ? G_("%<%.*s%> directive output may be truncated "
2679 "writing likely %wu or more bytes into a region "
2680 "of size between %wu and %wu")
2681 : G_("%<%.*s%> directive output truncated writing "
2682 "likely %wu or more bytes into a region of size "
2683 "between %wu and %wu"))
2684 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2685 "into a region of size between %wu and %wu"),
2686 (int) dir.len,
2687 target_to_host (hostdir, sizeof hostdir, dir.beg),
2688 res.likely, avail_range.min, avail_range.max);
2690 if (res.max < maxbytes)
2691 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2692 info.bounded
2693 ? (maybe
2694 ? G_("%<%.*s%> directive output may be truncated "
2695 "writing between %wu and %wu bytes into a region "
2696 "of size between %wu and %wu")
2697 : G_("%<%.*s%> directive output truncated writing "
2698 "between %wu and %wu bytes into a region of size "
2699 "between %wu and %wu"))
2700 : G_("%<%.*s%> directive writing between %wu and "
2701 "%wu bytes into a region of size between %wu and "
2702 "%wu"), (int) dir.len,
2703 target_to_host (hostdir, sizeof hostdir, dir.beg),
2704 res.min, res.max, avail_range.min, avail_range.max);
2706 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2707 info.bounded
2708 ? (maybe
2709 ? G_("%<%.*s%> directive output may be truncated writing "
2710 "%wu or more bytes into a region of size between "
2711 "%wu and %wu")
2712 : G_("%<%.*s%> directive output truncated writing "
2713 "%wu or more bytes into a region of size between "
2714 "%wu and %wu"))
2715 : G_("%<%.*s%> directive writing %wu or more bytes "
2716 "into a region of size between %wu and %wu"),
2717 (int) dir.len,
2718 target_to_host (hostdir, sizeof hostdir, dir.beg),
2719 res.min, avail_range.min, avail_range.max);
2722 /* Compute the length of the output resulting from the directive DIR
2723 in a call described by INFO and update the overall result of the call
2724 in *RES. Return true if the directive has been handled. */
2726 static bool
2727 format_directive (const sprintf_dom_walker::call_info &info,
2728 format_result *res, const directive &dir,
2729 class vr_values *vr_values)
2731 /* Offset of the beginning of the directive from the beginning
2732 of the format string. */
2733 size_t offset = dir.beg - info.fmtstr;
2734 size_t start = offset;
2735 size_t length = offset + dir.len - !!dir.len;
2737 /* Create a location for the whole directive from the % to the format
2738 specifier. */
2739 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2740 offset, start, length);
2742 /* Also get the location of the argument if possible.
2743 This doesn't work for integer literals or function calls. */
2744 location_t argloc = UNKNOWN_LOCATION;
2745 if (dir.arg)
2746 argloc = EXPR_LOCATION (dir.arg);
2748 /* Bail when there is no function to compute the output length,
2749 or when minimum length checking has been disabled. */
2750 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2751 return false;
2753 /* Compute the range of lengths of the formatted output. */
2754 fmtresult fmtres = dir.fmtfunc (dir, dir.arg, vr_values);
2756 /* Record whether the output of all directives is known to be
2757 bounded by some maximum, implying that their arguments are
2758 either known exactly or determined to be in a known range
2759 or, for strings, limited by the upper bounds of the arrays
2760 they refer to. */
2761 res->knownrange &= fmtres.knownrange;
2763 if (!fmtres.knownrange)
2765 /* Only when the range is known, check it against the host value
2766 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2767 INT_MAX precision, which is the longest possible output of any
2768 single directive). That's the largest valid byte count (though
2769 not valid call to a printf-like function because it can never
2770 return such a count). Otherwise, the range doesn't correspond
2771 to known values of the argument. */
2772 if (fmtres.range.max > target_dir_max ())
2774 /* Normalize the MAX counter to avoid having to deal with it
2775 later. The counter can be less than HOST_WIDE_INT_M1U
2776 when compiling for an ILP32 target on an LP64 host. */
2777 fmtres.range.max = HOST_WIDE_INT_M1U;
2778 /* Disable exact and maximum length checking after a failure
2779 to determine the maximum number of characters (for example
2780 for wide characters or wide character strings) but continue
2781 tracking the minimum number of characters. */
2782 res->range.max = HOST_WIDE_INT_M1U;
2785 if (fmtres.range.min > target_dir_max ())
2787 /* Disable exact length checking after a failure to determine
2788 even the minimum number of characters (it shouldn't happen
2789 except in an error) but keep tracking the minimum and maximum
2790 number of characters. */
2791 return true;
2795 /* Buffer for the directive in the host character set (used when
2796 the source character set is different). */
2797 char hostdir[32];
2799 int dirlen = dir.len;
2801 if (fmtres.nullp)
2803 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2804 "%<%.*s%> directive argument is null",
2805 dirlen, target_to_host (hostdir, sizeof hostdir, dir.beg));
2807 /* Don't bother processing the rest of the format string. */
2808 res->warned = true;
2809 res->range.min = HOST_WIDE_INT_M1U;
2810 res->range.max = HOST_WIDE_INT_M1U;
2811 return false;
2814 /* Compute the number of available bytes in the destination. There
2815 must always be at least one byte of space for the terminating
2816 NUL that's appended after the format string has been processed. */
2817 result_range avail_range = bytes_remaining (info.objsize, *res);
2819 bool warned = res->warned;
2821 if (!warned)
2822 warned = maybe_warn (dirloc, argloc, info, avail_range,
2823 fmtres.range, dir);
2825 /* Bump up the total maximum if it isn't too big. */
2826 if (res->range.max < HOST_WIDE_INT_MAX
2827 && fmtres.range.max < HOST_WIDE_INT_MAX)
2828 res->range.max += fmtres.range.max;
2830 /* Raise the total unlikely maximum by the larger of the maximum
2831 and the unlikely maximum. */
2832 unsigned HOST_WIDE_INT save = res->range.unlikely;
2833 if (fmtres.range.max < fmtres.range.unlikely)
2834 res->range.unlikely += fmtres.range.unlikely;
2835 else
2836 res->range.unlikely += fmtres.range.max;
2838 if (res->range.unlikely < save)
2839 res->range.unlikely = HOST_WIDE_INT_M1U;
2841 res->range.min += fmtres.range.min;
2842 res->range.likely += fmtres.range.likely;
2844 /* Has the minimum directive output length exceeded the maximum
2845 of 4095 bytes required to be supported? */
2846 bool minunder4k = fmtres.range.min < 4096;
2847 bool maxunder4k = fmtres.range.max < 4096;
2848 /* Clear POSUNDER4K in the overall result if the maximum has exceeded
2849 the 4k (this is necessary to avoid the return value optimization
2850 that may not be safe in the maximum case). */
2851 if (!maxunder4k)
2852 res->posunder4k = false;
2853 /* Also clear POSUNDER4K if the directive may fail. */
2854 if (fmtres.mayfail)
2855 res->posunder4k = false;
2857 if (!warned
2858 /* Only warn at level 2. */
2859 && warn_level > 1
2860 && (!minunder4k
2861 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2863 /* The directive output may be longer than the maximum required
2864 to be handled by an implementation according to 7.21.6.1, p15
2865 of C11. Warn on this only at level 2 but remember this and
2866 prevent folding the return value when done. This allows for
2867 the possibility of the actual libc call failing due to ENOMEM
2868 (like Glibc does under some conditions). */
2870 if (fmtres.range.min == fmtres.range.max)
2871 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2872 "%<%.*s%> directive output of %wu bytes exceeds "
2873 "minimum required size of 4095", dirlen,
2874 target_to_host (hostdir, sizeof hostdir, dir.beg),
2875 fmtres.range.min);
2876 else
2877 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2878 minunder4k
2879 ? G_("%<%.*s%> directive output between %wu and %wu "
2880 "bytes may exceed minimum required size of "
2881 "4095")
2882 : G_("%<%.*s%> directive output between %wu and %wu "
2883 "bytes exceeds minimum required size of 4095"),
2884 dirlen,
2885 target_to_host (hostdir, sizeof hostdir, dir.beg),
2886 fmtres.range.min, fmtres.range.max);
2889 /* Has the likely and maximum directive output exceeded INT_MAX? */
2890 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2891 /* Don't consider the maximum to be in excess when it's the result
2892 of a string of unknown length (i.e., whose maximum has been set
2893 to be greater than or equal to HOST_WIDE_INT_MAX. */
2894 bool maxximax = (*dir.beg
2895 && res->range.max > target_int_max ()
2896 && res->range.max < HOST_WIDE_INT_MAX);
2898 if (!warned
2899 /* Warn for the likely output size at level 1. */
2900 && (likelyximax
2901 /* But only warn for the maximum at level 2. */
2902 || (warn_level > 1
2903 && maxximax
2904 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2906 /* The directive output causes the total length of output
2907 to exceed INT_MAX bytes. */
2909 if (fmtres.range.min == fmtres.range.max)
2910 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2911 "%<%.*s%> directive output of %wu bytes causes "
2912 "result to exceed %<INT_MAX%>", dirlen,
2913 target_to_host (hostdir, sizeof hostdir, dir.beg),
2914 fmtres.range.min);
2915 else
2916 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2917 fmtres.range.min > target_int_max ()
2918 ? G_("%<%.*s%> directive output between %wu and "
2919 "%wu bytes causes result to exceed "
2920 "%<INT_MAX%>")
2921 : G_("%<%.*s%> directive output between %wu and "
2922 "%wu bytes may cause result to exceed "
2923 "%<INT_MAX%>"), dirlen,
2924 target_to_host (hostdir, sizeof hostdir, dir.beg),
2925 fmtres.range.min, fmtres.range.max);
2928 if (!warned && fmtres.nonstr)
2930 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2931 "%<%.*s%> directive argument is not a nul-terminated "
2932 "string",
2933 dirlen,
2934 target_to_host (hostdir, sizeof hostdir, dir.beg));
2935 if (warned && DECL_P (fmtres.nonstr))
2936 inform (DECL_SOURCE_LOCATION (fmtres.nonstr),
2937 "referenced argument declared here");
2938 return false;
2941 if (warned && fmtres.range.min < fmtres.range.likely
2942 && fmtres.range.likely < fmtres.range.max)
2943 inform_n (info.fmtloc, fmtres.range.likely,
2944 "assuming directive output of %wu byte",
2945 "assuming directive output of %wu bytes",
2946 fmtres.range.likely);
2948 if (warned && fmtres.argmin)
2950 if (fmtres.argmin == fmtres.argmax)
2951 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2952 else if (fmtres.knownrange)
2953 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2954 fmtres.argmin, fmtres.argmax);
2955 else
2956 inform (info.fmtloc,
2957 "using the range [%E, %E] for directive argument",
2958 fmtres.argmin, fmtres.argmax);
2961 res->warned |= warned;
2963 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2965 /* If a warning has been issued for buffer overflow or truncation
2966 (but not otherwise) help the user figure out how big a buffer
2967 they need. */
2969 location_t callloc = gimple_location (info.callstmt);
2971 unsigned HOST_WIDE_INT min = res->range.min;
2972 unsigned HOST_WIDE_INT max = res->range.max;
2974 if (min == max)
2975 inform (callloc,
2976 (min == 1
2977 ? G_("%qE output %wu byte into a destination of size %wu")
2978 : G_("%qE output %wu bytes into a destination of size %wu")),
2979 info.func, min, info.objsize);
2980 else if (max < HOST_WIDE_INT_MAX)
2981 inform (callloc,
2982 "%qE output between %wu and %wu bytes into "
2983 "a destination of size %wu",
2984 info.func, min, max, info.objsize);
2985 else if (min < res->range.likely && res->range.likely < max)
2986 inform (callloc,
2987 "%qE output %wu or more bytes (assuming %wu) into "
2988 "a destination of size %wu",
2989 info.func, min, res->range.likely, info.objsize);
2990 else
2991 inform (callloc,
2992 "%qE output %wu or more bytes into a destination of size %wu",
2993 info.func, min, info.objsize);
2996 if (dump_file && *dir.beg)
2998 fprintf (dump_file,
2999 " Result: "
3000 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3001 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
3002 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3003 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
3004 fmtres.range.min, fmtres.range.likely,
3005 fmtres.range.max, fmtres.range.unlikely,
3006 res->range.min, res->range.likely,
3007 res->range.max, res->range.unlikely);
3010 return true;
3013 /* Parse a format directive in function call described by INFO starting
3014 at STR and populate DIR structure. Bump up *ARGNO by the number of
3015 arguments extracted for the directive. Return the length of
3016 the directive. */
3018 static size_t
3019 parse_directive (sprintf_dom_walker::call_info &info,
3020 directive &dir, format_result *res,
3021 const char *str, unsigned *argno,
3022 vr_values *vr_values)
3024 const char *pcnt = strchr (str, target_percent);
3025 dir.beg = str;
3027 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
3029 /* This directive is either a plain string or the terminating nul
3030 (which isn't really a directive but it simplifies things to
3031 handle it as if it were). */
3032 dir.len = len;
3033 dir.fmtfunc = format_plain;
3035 if (dump_file)
3037 fprintf (dump_file, " Directive %u at offset "
3038 HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
3039 "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
3040 dir.dirno,
3041 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3042 (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
3045 return len - !*str;
3048 const char *pf = pcnt + 1;
3050 /* POSIX numbered argument index or zero when none. */
3051 HOST_WIDE_INT dollar = 0;
3053 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3054 when given by a va_list argument, and a non-negative value
3055 when specified in the format string itself. */
3056 HOST_WIDE_INT width = -1;
3057 HOST_WIDE_INT precision = -1;
3059 /* Pointers to the beginning of the width and precision decimal
3060 string (if any) within the directive. */
3061 const char *pwidth = 0;
3062 const char *pprec = 0;
3064 /* When the value of the decimal string that specifies width or
3065 precision is out of range, points to the digit that causes
3066 the value to exceed the limit. */
3067 const char *werange = NULL;
3068 const char *perange = NULL;
3070 /* Width specified via the asterisk. Need not be INTEGER_CST.
3071 For vararg functions set to void_node. */
3072 tree star_width = NULL_TREE;
3074 /* Width specified via the asterisk. Need not be INTEGER_CST.
3075 For vararg functions set to void_node. */
3076 tree star_precision = NULL_TREE;
3078 if (ISDIGIT (target_to_host (*pf)))
3080 /* This could be either a POSIX positional argument, the '0'
3081 flag, or a width, depending on what follows. Store it as
3082 width and sort it out later after the next character has
3083 been seen. */
3084 pwidth = pf;
3085 width = target_strtol10 (&pf, &werange);
3087 else if (target_to_host (*pf) == '*')
3089 /* Similarly to the block above, this could be either a POSIX
3090 positional argument or a width, depending on what follows. */
3091 if (*argno < gimple_call_num_args (info.callstmt))
3092 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3093 else
3094 star_width = void_node;
3095 ++pf;
3098 if (target_to_host (*pf) == '$')
3100 /* Handle the POSIX dollar sign which references the 1-based
3101 positional argument number. */
3102 if (width != -1)
3103 dollar = width + info.argidx;
3104 else if (star_width
3105 && TREE_CODE (star_width) == INTEGER_CST
3106 && (TYPE_PRECISION (TREE_TYPE (star_width))
3107 <= TYPE_PRECISION (integer_type_node)))
3108 dollar = width + tree_to_shwi (star_width);
3110 /* Bail when the numbered argument is out of range (it will
3111 have already been diagnosed by -Wformat). */
3112 if (dollar == 0
3113 || dollar == (int)info.argidx
3114 || dollar > gimple_call_num_args (info.callstmt))
3115 return false;
3117 --dollar;
3119 star_width = NULL_TREE;
3120 width = -1;
3121 ++pf;
3124 if (dollar || !star_width)
3126 if (width != -1)
3128 if (width == 0)
3130 /* The '0' that has been interpreted as a width above is
3131 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3132 and continue processing other flags. */
3133 width = -1;
3134 dir.set_flag ('0');
3136 else if (!dollar)
3138 /* (Non-zero) width has been seen. The next character
3139 is either a period or a digit. */
3140 goto start_precision;
3143 /* When either '$' has been seen, or width has not been seen,
3144 the next field is the optional flags followed by an optional
3145 width. */
3146 for ( ; ; ) {
3147 switch (target_to_host (*pf))
3149 case ' ':
3150 case '0':
3151 case '+':
3152 case '-':
3153 case '#':
3154 dir.set_flag (target_to_host (*pf++));
3155 break;
3157 default:
3158 goto start_width;
3162 start_width:
3163 if (ISDIGIT (target_to_host (*pf)))
3165 werange = 0;
3166 pwidth = pf;
3167 width = target_strtol10 (&pf, &werange);
3169 else if (target_to_host (*pf) == '*')
3171 if (*argno < gimple_call_num_args (info.callstmt))
3172 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3173 else
3175 /* This is (likely) a va_list. It could also be an invalid
3176 call with insufficient arguments. */
3177 star_width = void_node;
3179 ++pf;
3181 else if (target_to_host (*pf) == '\'')
3183 /* The POSIX apostrophe indicating a numeric grouping
3184 in the current locale. Even though it's possible to
3185 estimate the upper bound on the size of the output
3186 based on the number of digits it probably isn't worth
3187 continuing. */
3188 return 0;
3192 start_precision:
3193 if (target_to_host (*pf) == '.')
3195 ++pf;
3197 if (ISDIGIT (target_to_host (*pf)))
3199 pprec = pf;
3200 precision = target_strtol10 (&pf, &perange);
3202 else if (target_to_host (*pf) == '*')
3204 if (*argno < gimple_call_num_args (info.callstmt))
3205 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3206 else
3208 /* This is (likely) a va_list. It could also be an invalid
3209 call with insufficient arguments. */
3210 star_precision = void_node;
3212 ++pf;
3214 else
3216 /* The decimal precision or the asterisk are optional.
3217 When neither is dirified it's taken to be zero. */
3218 precision = 0;
3222 switch (target_to_host (*pf))
3224 case 'h':
3225 if (target_to_host (pf[1]) == 'h')
3227 ++pf;
3228 dir.modifier = FMT_LEN_hh;
3230 else
3231 dir.modifier = FMT_LEN_h;
3232 ++pf;
3233 break;
3235 case 'j':
3236 dir.modifier = FMT_LEN_j;
3237 ++pf;
3238 break;
3240 case 'L':
3241 dir.modifier = FMT_LEN_L;
3242 ++pf;
3243 break;
3245 case 'l':
3246 if (target_to_host (pf[1]) == 'l')
3248 ++pf;
3249 dir.modifier = FMT_LEN_ll;
3251 else
3252 dir.modifier = FMT_LEN_l;
3253 ++pf;
3254 break;
3256 case 't':
3257 dir.modifier = FMT_LEN_t;
3258 ++pf;
3259 break;
3261 case 'z':
3262 dir.modifier = FMT_LEN_z;
3263 ++pf;
3264 break;
3267 switch (target_to_host (*pf))
3269 /* Handle a sole '%' character the same as "%%" but since it's
3270 undefined prevent the result from being folded. */
3271 case '\0':
3272 --pf;
3273 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3274 /* FALLTHRU */
3275 case '%':
3276 dir.fmtfunc = format_percent;
3277 break;
3279 case 'a':
3280 case 'A':
3281 case 'e':
3282 case 'E':
3283 case 'f':
3284 case 'F':
3285 case 'g':
3286 case 'G':
3287 res->floating = true;
3288 dir.fmtfunc = format_floating;
3289 break;
3291 case 'd':
3292 case 'i':
3293 case 'o':
3294 case 'u':
3295 case 'x':
3296 case 'X':
3297 dir.fmtfunc = format_integer;
3298 break;
3300 case 'p':
3301 /* The %p output is implementation-defined. It's possible
3302 to determine this format but due to extensions (edirially
3303 those of the Linux kernel -- see bug 78512) the first %p
3304 in the format string disables any further processing. */
3305 return false;
3307 case 'n':
3308 /* %n has side-effects even when nothing is actually printed to
3309 any buffer. */
3310 info.nowrite = false;
3311 dir.fmtfunc = format_none;
3312 break;
3314 case 'C':
3315 case 'c':
3316 /* POSIX wide character and C/POSIX narrow character. */
3317 dir.fmtfunc = format_character;
3318 break;
3320 case 'S':
3321 case 's':
3322 /* POSIX wide string and C/POSIX narrow character string. */
3323 dir.fmtfunc = format_string;
3324 break;
3326 default:
3327 /* Unknown conversion specification. */
3328 return 0;
3331 dir.specifier = target_to_host (*pf++);
3333 /* Store the length of the format directive. */
3334 dir.len = pf - pcnt;
3336 /* Buffer for the directive in the host character set (used when
3337 the source character set is different). */
3338 char hostdir[32];
3340 if (star_width)
3342 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3343 dir.set_width (star_width, vr_values);
3344 else
3346 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3347 (width is the absolute value of that specified). */
3348 dir.width[0] = 0;
3349 dir.width[1] = target_int_max () + 1;
3352 else
3354 if (width == LONG_MAX && werange)
3356 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3357 size_t caret = begin + (werange - pcnt);
3358 size_t end = pf - info.fmtstr - 1;
3360 /* Create a location for the width part of the directive,
3361 pointing the caret at the first out-of-range digit. */
3362 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3363 caret, begin, end);
3365 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3366 "%<%.*s%> directive width out of range", (int) dir.len,
3367 target_to_host (hostdir, sizeof hostdir, dir.beg));
3370 dir.set_width (width);
3373 if (star_precision)
3375 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3376 dir.set_precision (star_precision, vr_values);
3377 else
3379 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3380 (unlike width, negative precision is ignored). */
3381 dir.prec[0] = -1;
3382 dir.prec[1] = target_int_max ();
3385 else
3387 if (precision == LONG_MAX && perange)
3389 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3390 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3391 size_t end = pf - info.fmtstr - 2;
3393 /* Create a location for the precision part of the directive,
3394 including the leading period, pointing the caret at the first
3395 out-of-range digit . */
3396 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3397 caret, begin, end);
3399 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3400 "%<%.*s%> directive precision out of range", (int) dir.len,
3401 target_to_host (hostdir, sizeof hostdir, dir.beg));
3404 dir.set_precision (precision);
3407 /* Extract the argument if the directive takes one and if it's
3408 available (e.g., the function doesn't take a va_list). Treat
3409 missing arguments the same as va_list, even though they will
3410 have likely already been diagnosed by -Wformat. */
3411 if (dir.specifier != '%'
3412 && *argno < gimple_call_num_args (info.callstmt))
3413 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3415 if (dump_file)
3417 fprintf (dump_file,
3418 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3419 ": \"%.*s\"",
3420 dir.dirno,
3421 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3422 (int)dir.len, dir.beg);
3423 if (star_width)
3425 if (dir.width[0] == dir.width[1])
3426 fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
3427 dir.width[0]);
3428 else
3429 fprintf (dump_file,
3430 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3431 ", " HOST_WIDE_INT_PRINT_DEC "]",
3432 dir.width[0], dir.width[1]);
3435 if (star_precision)
3437 if (dir.prec[0] == dir.prec[1])
3438 fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
3439 dir.prec[0]);
3440 else
3441 fprintf (dump_file,
3442 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3443 HOST_WIDE_INT_PRINT_DEC "]",
3444 dir.prec[0], dir.prec[1]);
3446 fputc ('\n', dump_file);
3449 return dir.len;
3452 /* Compute the length of the output resulting from the call to a formatted
3453 output function described by INFO and store the result of the call in
3454 *RES. Issue warnings for detected past the end writes. Return true
3455 if the complete format string has been processed and *RES can be relied
3456 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3457 that caused the processing to be terminated early). */
3459 bool
3460 sprintf_dom_walker::compute_format_length (call_info &info,
3461 format_result *res)
3463 if (dump_file)
3465 location_t callloc = gimple_location (info.callstmt);
3466 fprintf (dump_file, "%s:%i: ",
3467 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3468 print_generic_expr (dump_file, info.func, dump_flags);
3470 fprintf (dump_file,
3471 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3472 ", fmtstr = \"%s\"\n",
3473 info.objsize, info.fmtstr);
3476 /* Reset the minimum and maximum byte counters. */
3477 res->range.min = res->range.max = 0;
3479 /* No directive has been seen yet so the length of output is bounded
3480 by the known range [0, 0] (with no conversion resulting in a failure
3481 or producing more than 4K bytes) until determined otherwise. */
3482 res->knownrange = true;
3483 res->posunder4k = true;
3484 res->floating = false;
3485 res->warned = false;
3487 /* 1-based directive counter. */
3488 unsigned dirno = 1;
3490 /* The variadic argument counter. */
3491 unsigned argno = info.argidx;
3493 for (const char *pf = info.fmtstr; ; ++dirno)
3495 directive dir = directive ();
3496 dir.dirno = dirno;
3498 size_t n = parse_directive (info, dir, res, pf, &argno,
3499 evrp_range_analyzer.get_vr_values ());
3501 /* Return failure if the format function fails. */
3502 if (!format_directive (info, res, dir,
3503 evrp_range_analyzer.get_vr_values ()))
3504 return false;
3506 /* Return success the directive is zero bytes long and it's
3507 the last think in the format string (i.e., it's the terminating
3508 nul, which isn't really a directive but handling it as one makes
3509 things simpler). */
3510 if (!n)
3511 return *pf == '\0';
3513 pf += n;
3516 /* The complete format string was processed (with or without warnings). */
3517 return true;
3520 /* Return the size of the object referenced by the expression DEST if
3521 available, or -1 otherwise. */
3523 static unsigned HOST_WIDE_INT
3524 get_destination_size (tree dest)
3526 /* Initialize object size info before trying to compute it. */
3527 init_object_sizes ();
3529 /* Use __builtin_object_size to determine the size of the destination
3530 object. When optimizing, determine the smallest object (such as
3531 a member array as opposed to the whole enclosing object), otherwise
3532 use type-zero object size to determine the size of the enclosing
3533 object (the function fails without optimization in this type). */
3534 int ost = optimize > 0;
3535 unsigned HOST_WIDE_INT size;
3536 if (compute_builtin_object_size (dest, ost, &size))
3537 return size;
3539 return HOST_WIDE_INT_M1U;
3542 /* Return true if the call described by INFO with result RES safe to
3543 optimize (i.e., no undefined behavior), and set RETVAL to the range
3544 of its return values. */
3546 static bool
3547 is_call_safe (const sprintf_dom_walker::call_info &info,
3548 const format_result &res, bool under4k,
3549 unsigned HOST_WIDE_INT retval[2])
3551 if (under4k && !res.posunder4k)
3552 return false;
3554 /* The minimum return value. */
3555 retval[0] = res.range.min;
3557 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3558 but in cases involving multibyte characters could be as large as
3559 RES.RANGE.UNLIKELY. */
3560 retval[1]
3561 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3563 /* Adjust the number of bytes which includes the terminating nul
3564 to reflect the return value of the function which does not.
3565 Because the valid range of the function is [INT_MIN, INT_MAX],
3566 a valid range before the adjustment below is [0, INT_MAX + 1]
3567 (the functions only return negative values on error or undefined
3568 behavior). */
3569 if (retval[0] <= target_int_max () + 1)
3570 --retval[0];
3571 if (retval[1] <= target_int_max () + 1)
3572 --retval[1];
3574 /* Avoid the return value optimization when the behavior of the call
3575 is undefined either because any directive may have produced 4K or
3576 more of output, or the return value exceeds INT_MAX, or because
3577 the output overflows the destination object (but leave it enabled
3578 when the function is bounded because then the behavior is well-
3579 defined). */
3580 if (retval[0] == retval[1]
3581 && (info.bounded || retval[0] < info.objsize)
3582 && retval[0] <= target_int_max ())
3583 return true;
3585 if ((info.bounded || retval[1] < info.objsize)
3586 && (retval[0] < target_int_max ()
3587 && retval[1] < target_int_max ()))
3588 return true;
3590 if (!under4k && (info.bounded || retval[0] < info.objsize))
3591 return true;
3593 return false;
3596 /* Given a suitable result RES of a call to a formatted output function
3597 described by INFO, substitute the result for the return value of
3598 the call. The result is suitable if the number of bytes it represents
3599 is known and exact. A result that isn't suitable for substitution may
3600 have its range set to the range of return values, if that is known.
3601 Return true if the call is removed and gsi_next should not be performed
3602 in the caller. */
3604 static bool
3605 try_substitute_return_value (gimple_stmt_iterator *gsi,
3606 const sprintf_dom_walker::call_info &info,
3607 const format_result &res)
3609 tree lhs = gimple_get_lhs (info.callstmt);
3611 /* Set to true when the entire call has been removed. */
3612 bool removed = false;
3614 /* The minimum and maximum return value. */
3615 unsigned HOST_WIDE_INT retval[2];
3616 bool safe = is_call_safe (info, res, true, retval);
3618 if (safe
3619 && retval[0] == retval[1]
3620 /* Not prepared to handle possibly throwing calls here; they shouldn't
3621 appear in non-artificial testcases, except when the __*_chk routines
3622 are badly declared. */
3623 && !stmt_ends_bb_p (info.callstmt))
3625 tree cst = build_int_cst (integer_type_node, retval[0]);
3627 if (lhs == NULL_TREE
3628 && info.nowrite)
3630 /* Remove the call to the bounded function with a zero size
3631 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3632 unlink_stmt_vdef (info.callstmt);
3633 gsi_remove (gsi, true);
3634 removed = true;
3636 else if (info.nowrite)
3638 /* Replace the call to the bounded function with a zero size
3639 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3640 of the function. */
3641 if (!update_call_from_tree (gsi, cst))
3642 gimplify_and_update_call_from_tree (gsi, cst);
3643 gimple *callstmt = gsi_stmt (*gsi);
3644 update_stmt (callstmt);
3646 else if (lhs)
3648 /* Replace the left-hand side of the call with the constant
3649 result of the formatted function. */
3650 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3651 gimple *g = gimple_build_assign (lhs, cst);
3652 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3653 update_stmt (info.callstmt);
3656 if (dump_file)
3658 if (removed)
3659 fprintf (dump_file, " Removing call statement.");
3660 else
3662 fprintf (dump_file, " Substituting ");
3663 print_generic_expr (dump_file, cst, dump_flags);
3664 fprintf (dump_file, " for %s.\n",
3665 info.nowrite ? "statement" : "return value");
3669 else if (lhs)
3671 bool setrange = false;
3673 if (safe
3674 && (info.bounded || retval[1] < info.objsize)
3675 && (retval[0] < target_int_max ()
3676 && retval[1] < target_int_max ()))
3678 /* If the result is in a valid range bounded by the size of
3679 the destination set it so that it can be used for subsequent
3680 optimizations. */
3681 int prec = TYPE_PRECISION (integer_type_node);
3683 wide_int min = wi::shwi (retval[0], prec);
3684 wide_int max = wi::shwi (retval[1], prec);
3685 set_range_info (lhs, VR_RANGE, min, max);
3687 setrange = true;
3690 if (dump_file)
3692 const char *inbounds
3693 = (retval[0] < info.objsize
3694 ? (retval[1] < info.objsize
3695 ? "in" : "potentially out-of")
3696 : "out-of");
3698 const char *what = setrange ? "Setting" : "Discarding";
3699 if (retval[0] != retval[1])
3700 fprintf (dump_file,
3701 " %s %s-bounds return value range ["
3702 HOST_WIDE_INT_PRINT_UNSIGNED ", "
3703 HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
3704 what, inbounds, retval[0], retval[1]);
3705 else
3706 fprintf (dump_file, " %s %s-bounds return value "
3707 HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
3708 what, inbounds, retval[0]);
3712 if (dump_file)
3713 fputc ('\n', dump_file);
3715 return removed;
3718 /* Try to simplify a s{,n}printf call described by INFO with result
3719 RES by replacing it with a simpler and presumably more efficient
3720 call (such as strcpy). */
3722 static bool
3723 try_simplify_call (gimple_stmt_iterator *gsi,
3724 const sprintf_dom_walker::call_info &info,
3725 const format_result &res)
3727 unsigned HOST_WIDE_INT dummy[2];
3728 if (!is_call_safe (info, res, info.retval_used (), dummy))
3729 return false;
3731 switch (info.fncode)
3733 case BUILT_IN_SNPRINTF:
3734 return gimple_fold_builtin_snprintf (gsi);
3736 case BUILT_IN_SPRINTF:
3737 return gimple_fold_builtin_sprintf (gsi);
3739 default:
3743 return false;
3746 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3747 functions and if so, handle it. Return true if the call is removed
3748 and gsi_next should not be performed in the caller. */
3750 bool
3751 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3753 call_info info = call_info ();
3755 info.callstmt = gsi_stmt (*gsi);
3756 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3757 return false;
3759 info.func = gimple_call_fndecl (info.callstmt);
3760 info.fncode = DECL_FUNCTION_CODE (info.func);
3762 /* The size of the destination as in snprintf(dest, size, ...). */
3763 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3765 /* The size of the destination determined by __builtin_object_size. */
3766 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3768 /* Buffer size argument number (snprintf and vsnprintf). */
3769 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3771 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3772 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3774 /* Format string argument number (valid for all functions). */
3775 unsigned idx_format;
3777 switch (info.fncode)
3779 case BUILT_IN_SPRINTF:
3780 // Signature:
3781 // __builtin_sprintf (dst, format, ...)
3782 idx_format = 1;
3783 info.argidx = 2;
3784 break;
3786 case BUILT_IN_SPRINTF_CHK:
3787 // Signature:
3788 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3789 idx_objsize = 2;
3790 idx_format = 3;
3791 info.argidx = 4;
3792 break;
3794 case BUILT_IN_SNPRINTF:
3795 // Signature:
3796 // __builtin_snprintf (dst, size, format, ...)
3797 idx_dstsize = 1;
3798 idx_format = 2;
3799 info.argidx = 3;
3800 info.bounded = true;
3801 break;
3803 case BUILT_IN_SNPRINTF_CHK:
3804 // Signature:
3805 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3806 idx_dstsize = 1;
3807 idx_objsize = 3;
3808 idx_format = 4;
3809 info.argidx = 5;
3810 info.bounded = true;
3811 break;
3813 case BUILT_IN_VSNPRINTF:
3814 // Signature:
3815 // __builtin_vsprintf (dst, size, format, va)
3816 idx_dstsize = 1;
3817 idx_format = 2;
3818 info.argidx = -1;
3819 info.bounded = true;
3820 break;
3822 case BUILT_IN_VSNPRINTF_CHK:
3823 // Signature:
3824 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3825 idx_dstsize = 1;
3826 idx_objsize = 3;
3827 idx_format = 4;
3828 info.argidx = -1;
3829 info.bounded = true;
3830 break;
3832 case BUILT_IN_VSPRINTF:
3833 // Signature:
3834 // __builtin_vsprintf (dst, format, va)
3835 idx_format = 1;
3836 info.argidx = -1;
3837 break;
3839 case BUILT_IN_VSPRINTF_CHK:
3840 // Signature:
3841 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3842 idx_format = 3;
3843 idx_objsize = 2;
3844 info.argidx = -1;
3845 break;
3847 default:
3848 return false;
3851 /* Set the global warning level for this function. */
3852 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3854 /* The first argument is a pointer to the destination. */
3855 tree dstptr = gimple_call_arg (info.callstmt, 0);
3857 info.format = gimple_call_arg (info.callstmt, idx_format);
3859 /* True when the destination size is constant as opposed to the lower
3860 or upper bound of a range. */
3861 bool dstsize_cst_p = true;
3863 if (idx_dstsize == HOST_WIDE_INT_M1U)
3865 /* For non-bounded functions like sprintf, determine the size
3866 of the destination from the object or pointer passed to it
3867 as the first argument. */
3868 dstsize = get_destination_size (dstptr);
3870 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3872 /* For bounded functions try to get the size argument. */
3874 if (TREE_CODE (size) == INTEGER_CST)
3876 dstsize = tree_to_uhwi (size);
3877 /* No object can be larger than SIZE_MAX bytes (half the address
3878 space) on the target.
3879 The functions are defined only for output of at most INT_MAX
3880 bytes. Specifying a bound in excess of that limit effectively
3881 defeats the bounds checking (and on some implementations such
3882 as Solaris cause the function to fail with EINVAL). */
3883 if (dstsize > target_size_max () / 2)
3885 /* Avoid warning if -Wstringop-overflow is specified since
3886 it also warns for the same thing though only for the
3887 checking built-ins. */
3888 if ((idx_objsize == HOST_WIDE_INT_M1U
3889 || !warn_stringop_overflow))
3890 warning_at (gimple_location (info.callstmt), info.warnopt (),
3891 "specified bound %wu exceeds maximum object size "
3892 "%wu",
3893 dstsize, target_size_max () / 2);
3895 else if (dstsize > target_int_max ())
3896 warning_at (gimple_location (info.callstmt), info.warnopt (),
3897 "specified bound %wu exceeds %<INT_MAX%>",
3898 dstsize);
3900 else if (TREE_CODE (size) == SSA_NAME)
3902 /* Try to determine the range of values of the argument
3903 and use the greater of the two at level 1 and the smaller
3904 of them at level 2. */
3905 value_range *vr = evrp_range_analyzer.get_value_range (size);
3906 if (vr->type == VR_RANGE
3907 && TREE_CODE (vr->min) == INTEGER_CST
3908 && TREE_CODE (vr->max) == INTEGER_CST)
3909 dstsize = (warn_level < 2
3910 ? TREE_INT_CST_LOW (vr->max)
3911 : TREE_INT_CST_LOW (vr->min));
3913 /* The destination size is not constant. If the function is
3914 bounded (e.g., snprintf) a lower bound of zero doesn't
3915 necessarily imply it can be eliminated. */
3916 dstsize_cst_p = false;
3920 if (idx_objsize != HOST_WIDE_INT_M1U)
3921 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3922 if (tree_fits_uhwi_p (size))
3923 objsize = tree_to_uhwi (size);
3925 if (info.bounded && !dstsize)
3927 /* As a special case, when the explicitly specified destination
3928 size argument (to a bounded function like snprintf) is zero
3929 it is a request to determine the number of bytes on output
3930 without actually producing any. Pretend the size is
3931 unlimited in this case. */
3932 info.objsize = HOST_WIDE_INT_MAX;
3933 info.nowrite = dstsize_cst_p;
3935 else
3937 /* For calls to non-bounded functions or to those of bounded
3938 functions with a non-zero size, warn if the destination
3939 pointer is null. */
3940 if (integer_zerop (dstptr))
3942 /* This is diagnosed with -Wformat only when the null is a constant
3943 pointer. The warning here diagnoses instances where the pointer
3944 is not constant. */
3945 location_t loc = gimple_location (info.callstmt);
3946 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3947 info.warnopt (), "null destination pointer");
3948 return false;
3951 /* Set the object size to the smaller of the two arguments
3952 of both have been specified and they're not equal. */
3953 info.objsize = dstsize < objsize ? dstsize : objsize;
3955 if (info.bounded
3956 && dstsize < target_size_max () / 2 && objsize < dstsize
3957 /* Avoid warning if -Wstringop-overflow is specified since
3958 it also warns for the same thing though only for the
3959 checking built-ins. */
3960 && (idx_objsize == HOST_WIDE_INT_M1U
3961 || !warn_stringop_overflow))
3963 warning_at (gimple_location (info.callstmt), info.warnopt (),
3964 "specified bound %wu exceeds the size %wu "
3965 "of the destination object", dstsize, objsize);
3969 if (integer_zerop (info.format))
3971 /* This is diagnosed with -Wformat only when the null is a constant
3972 pointer. The warning here diagnoses instances where the pointer
3973 is not constant. */
3974 location_t loc = gimple_location (info.callstmt);
3975 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3976 info.warnopt (), "null format string");
3977 return false;
3980 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3981 if (!info.fmtstr)
3982 return false;
3984 /* The result is the number of bytes output by the formatted function,
3985 including the terminating NUL. */
3986 format_result res = format_result ();
3988 bool success = compute_format_length (info, &res);
3989 if (res.warned)
3990 gimple_set_no_warning (info.callstmt, true);
3992 /* When optimizing and the printf return value optimization is enabled,
3993 attempt to substitute the computed result for the return value of
3994 the call. Avoid this optimization when -frounding-math is in effect
3995 and the format string contains a floating point directive. */
3996 bool call_removed = false;
3997 if (success && optimize > 0)
3999 /* Save a copy of the iterator pointing at the call. The iterator
4000 may change to point past the call in try_substitute_return_value
4001 but the original value is needed in try_simplify_call. */
4002 gimple_stmt_iterator gsi_call = *gsi;
4004 if (flag_printf_return_value
4005 && (!flag_rounding_math || !res.floating))
4006 call_removed = try_substitute_return_value (gsi, info, res);
4008 if (!call_removed)
4009 try_simplify_call (&gsi_call, info, res);
4012 return call_removed;
4015 edge
4016 sprintf_dom_walker::before_dom_children (basic_block bb)
4018 evrp_range_analyzer.enter (bb);
4019 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
4021 /* Iterate over statements, looking for function calls. */
4022 gimple *stmt = gsi_stmt (si);
4024 /* First record ranges generated by this statement. */
4025 evrp_range_analyzer.record_ranges_from_stmt (stmt, false);
4027 if (is_gimple_call (stmt) && handle_gimple_call (&si))
4028 /* If handle_gimple_call returns true, the iterator is
4029 already pointing to the next statement. */
4030 continue;
4032 gsi_next (&si);
4034 return NULL;
4037 void
4038 sprintf_dom_walker::after_dom_children (basic_block bb)
4040 evrp_range_analyzer.leave (bb);
4043 /* Execute the pass for function FUN. */
4045 unsigned int
4046 pass_sprintf_length::execute (function *fun)
4048 init_target_to_host_charmap ();
4050 calculate_dominance_info (CDI_DOMINATORS);
4052 sprintf_dom_walker sprintf_dom_walker;
4053 sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
4055 /* Clean up object size info. */
4056 fini_object_sizes ();
4057 return 0;
4060 } /* Unnamed namespace. */
4062 /* Return a pointer to a pass object newly constructed from the context
4063 CTXT. */
4065 gimple_opt_pass *
4066 make_pass_sprintf_length (gcc::context *ctxt)
4068 return new pass_sprintf_length (ctxt);