Remove not needed __builtin_expect due to malloc predictor.
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blobc652c556f9762e4efed3f395d9277abbc445f66b
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 resulted in more than 4095 bytes
215 of output (the total NUMBER_CHARS_{MIN,MAX} might be greater).
216 Implementations are not required to handle directives that produce
217 more than 4K bytes (leading to undefined behavior) and so when one
218 is found it disables the return value optimization. */
219 bool under4k;
221 /* True when a floating point directive has been seen in the format
222 string. */
223 bool floating;
225 /* True when an intermediate result has caused a warning. Used to
226 avoid issuing duplicate warnings while finishing the processing
227 of a call. WARNED also disables the return value optimization. */
228 bool warned;
230 /* Preincrement the number of output characters by 1. */
231 format_result& operator++ ()
233 return *this += 1;
236 /* Postincrement the number of output characters by 1. */
237 format_result operator++ (int)
239 format_result prev (*this);
240 *this += 1;
241 return prev;
244 /* Increment the number of output characters by N. */
245 format_result& operator+= (unsigned HOST_WIDE_INT);
248 format_result&
249 format_result::operator+= (unsigned HOST_WIDE_INT n)
251 gcc_assert (n < HOST_WIDE_INT_MAX);
253 if (range.min < HOST_WIDE_INT_MAX)
254 range.min += n;
256 if (range.max < HOST_WIDE_INT_MAX)
257 range.max += n;
259 if (range.likely < HOST_WIDE_INT_MAX)
260 range.likely += n;
262 if (range.unlikely < HOST_WIDE_INT_MAX)
263 range.unlikely += n;
265 return *this;
268 /* Return the value of INT_MIN for the target. */
270 static inline HOST_WIDE_INT
271 target_int_min ()
273 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
276 /* Return the value of INT_MAX for the target. */
278 static inline unsigned HOST_WIDE_INT
279 target_int_max ()
281 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
284 /* Return the value of SIZE_MAX for the target. */
286 static inline unsigned HOST_WIDE_INT
287 target_size_max ()
289 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
292 /* A straightforward mapping from the execution character set to the host
293 character set indexed by execution character. */
295 static char target_to_host_charmap[256];
297 /* Initialize a mapping from the execution character set to the host
298 character set. */
300 static bool
301 init_target_to_host_charmap ()
303 /* If the percent sign is non-zero the mapping has already been
304 initialized. */
305 if (target_to_host_charmap['%'])
306 return true;
308 /* Initialize the target_percent character (done elsewhere). */
309 if (!init_target_chars ())
310 return false;
312 /* The subset of the source character set used by printf conversion
313 specifications (strictly speaking, not all letters are used but
314 they are included here for the sake of simplicity). The dollar
315 sign must be included even though it's not in the basic source
316 character set. */
317 const char srcset[] = " 0123456789!\"#%&'()*+,-./:;<=>?[\\]^_{|}~$"
318 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
320 /* Set the mapping for all characters to some ordinary value (i,e.,
321 not none used in printf conversion specifications) and overwrite
322 those that are used by conversion specifications with their
323 corresponding values. */
324 memset (target_to_host_charmap + 1, '?', sizeof target_to_host_charmap - 1);
326 /* Are the two sets of characters the same? */
327 bool all_same_p = true;
329 for (const char *pc = srcset; *pc; ++pc)
331 /* Slice off the high end bits in case target characters are
332 signed. All values are expected to be non-nul, otherwise
333 there's a problem. */
334 if (unsigned char tc = lang_hooks.to_target_charset (*pc))
336 target_to_host_charmap[tc] = *pc;
337 if (tc != *pc)
338 all_same_p = false;
340 else
341 return false;
345 /* Set the first element to a non-zero value if the mapping
346 is 1-to-1, otherwise leave it clear (NUL is assumed to be
347 the same in both character sets). */
348 target_to_host_charmap[0] = all_same_p;
350 return true;
353 /* Return the host source character corresponding to the character
354 CH in the execution character set if one exists, or some innocuous
355 (non-special, non-nul) source character otherwise. */
357 static inline unsigned char
358 target_to_host (unsigned char ch)
360 return target_to_host_charmap[ch];
363 /* Convert an initial substring of the string TARGSTR consisting of
364 characters in the execution character set into a string in the
365 source character set on the host and store up to HOSTSZ characters
366 in the buffer pointed to by HOSTR. Return HOSTR. */
368 static const char*
369 target_to_host (char *hostr, size_t hostsz, const char *targstr)
371 /* Make sure the buffer is reasonably big. */
372 gcc_assert (hostsz > 4);
374 /* The interesting subset of source and execution characters are
375 the same so no conversion is necessary. However, truncate
376 overlong strings just like the translated strings are. */
377 if (target_to_host_charmap['\0'] == 1)
379 strncpy (hostr, targstr, hostsz - 4);
380 if (strlen (targstr) >= hostsz)
381 strcpy (hostr + hostsz - 4, "...");
382 return hostr;
385 /* Convert the initial substring of TARGSTR to the corresponding
386 characters in the host set, appending "..." if TARGSTR is too
387 long to fit. Using the static buffer assumes the function is
388 not called in between sequence points (which it isn't). */
389 for (char *ph = hostr; ; ++targstr)
391 *ph++ = target_to_host (*targstr);
392 if (!*targstr)
393 break;
395 if (size_t (ph - hostr) == hostsz - 4)
397 *ph = '\0';
398 strcat (ph, "...");
399 break;
403 return hostr;
406 /* Convert the sequence of decimal digits in the execution character
407 starting at S to a long, just like strtol does. Return the result
408 and set *END to one past the last converted character. On range
409 error set ERANGE to the digit that caused it. */
411 static inline long
412 target_strtol10 (const char **ps, const char **erange)
414 unsigned HOST_WIDE_INT val = 0;
415 for ( ; ; ++*ps)
417 unsigned char c = target_to_host (**ps);
418 if (ISDIGIT (c))
420 c -= '0';
422 /* Check for overflow. */
423 if (val > (LONG_MAX - c) / 10LU)
425 val = LONG_MAX;
426 *erange = *ps;
428 /* Skip the remaining digits. */
430 c = target_to_host (*++*ps);
431 while (ISDIGIT (c));
432 break;
434 else
435 val = val * 10 + c;
437 else
438 break;
441 return val;
444 /* Return the constant initial value of DECL if available or DECL
445 otherwise. Same as the synonymous function in c/c-typeck.c. */
447 static tree
448 decl_constant_value (tree decl)
450 if (/* Don't change a variable array bound or initial value to a constant
451 in a place where a variable is invalid. Note that DECL_INITIAL
452 isn't valid for a PARM_DECL. */
453 current_function_decl != 0
454 && TREE_CODE (decl) != PARM_DECL
455 && !TREE_THIS_VOLATILE (decl)
456 && TREE_READONLY (decl)
457 && DECL_INITIAL (decl) != 0
458 && TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK
459 /* This is invalid if initial value is not constant.
460 If it has either a function call, a memory reference,
461 or a variable, then re-evaluating it could give different results. */
462 && TREE_CONSTANT (DECL_INITIAL (decl))
463 /* Check for cases where this is sub-optimal, even though valid. */
464 && TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)
465 return DECL_INITIAL (decl);
466 return decl;
469 /* Given FORMAT, set *PLOC to the source location of the format string
470 and return the format string if it is known or null otherwise. */
472 static const char*
473 get_format_string (tree format, location_t *ploc)
475 if (VAR_P (format))
477 /* Pull out a constant value if the front end didn't. */
478 format = decl_constant_value (format);
479 STRIP_NOPS (format);
482 if (integer_zerop (format))
484 /* FIXME: Diagnose null format string if it hasn't been diagnosed
485 by -Wformat (the latter diagnoses only nul pointer constants,
486 this pass can do better). */
487 return NULL;
490 HOST_WIDE_INT offset = 0;
492 if (TREE_CODE (format) == POINTER_PLUS_EXPR)
494 tree arg0 = TREE_OPERAND (format, 0);
495 tree arg1 = TREE_OPERAND (format, 1);
496 STRIP_NOPS (arg0);
497 STRIP_NOPS (arg1);
499 if (TREE_CODE (arg1) != INTEGER_CST)
500 return NULL;
502 format = arg0;
504 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
505 if (!cst_and_fits_in_hwi (arg1))
506 return NULL;
508 offset = int_cst_value (arg1);
511 if (TREE_CODE (format) != ADDR_EXPR)
512 return NULL;
514 *ploc = EXPR_LOC_OR_LOC (format, input_location);
516 format = TREE_OPERAND (format, 0);
518 if (TREE_CODE (format) == ARRAY_REF
519 && tree_fits_shwi_p (TREE_OPERAND (format, 1))
520 && (offset += tree_to_shwi (TREE_OPERAND (format, 1))) >= 0)
521 format = TREE_OPERAND (format, 0);
523 if (offset < 0)
524 return NULL;
526 tree array_init;
527 tree array_size = NULL_TREE;
529 if (VAR_P (format)
530 && TREE_CODE (TREE_TYPE (format)) == ARRAY_TYPE
531 && (array_init = decl_constant_value (format)) != format
532 && TREE_CODE (array_init) == STRING_CST)
534 /* Extract the string constant initializer. Note that this may
535 include a trailing NUL character that is not in the array (e.g.
536 const char a[3] = "foo";). */
537 array_size = DECL_SIZE_UNIT (format);
538 format = array_init;
541 if (TREE_CODE (format) != STRING_CST)
542 return NULL;
544 tree type = TREE_TYPE (format);
546 scalar_int_mode char_mode;
547 if (!is_int_mode (TYPE_MODE (TREE_TYPE (type)), &char_mode)
548 || GET_MODE_SIZE (char_mode) != 1)
550 /* Wide format string. */
551 return NULL;
554 const char *fmtstr = TREE_STRING_POINTER (format);
555 unsigned fmtlen = TREE_STRING_LENGTH (format);
557 if (array_size)
559 /* Variable length arrays can't be initialized. */
560 gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
562 if (tree_fits_shwi_p (array_size))
564 HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
565 if (array_size_value > 0
566 && array_size_value == (int) array_size_value
567 && fmtlen > array_size_value)
568 fmtlen = array_size_value;
571 if (offset)
573 if (offset >= fmtlen)
574 return NULL;
576 fmtstr += offset;
577 fmtlen -= offset;
580 if (fmtlen < 1 || fmtstr[--fmtlen] != 0)
582 /* FIXME: Diagnose an unterminated format string if it hasn't been
583 diagnosed by -Wformat. Similarly to a null format pointer,
584 -Wformay diagnoses only nul pointer constants, this pass can
585 do better). */
586 return NULL;
589 return fmtstr;
592 /* For convenience and brevity, shorter named entrypoints of
593 format_warning_at_substring and format_warning_at_substring_n.
594 These have to be functions with the attribute so that exgettext
595 works properly. */
597 static bool
598 ATTRIBUTE_GCC_DIAG (5, 6)
599 fmtwarn (const substring_loc &fmt_loc, location_t param_loc,
600 const char *corrected_substring, int opt, const char *gmsgid, ...)
602 va_list ap;
603 va_start (ap, gmsgid);
604 bool warned = format_warning_va (fmt_loc, param_loc, corrected_substring,
605 opt, gmsgid, &ap);
606 va_end (ap);
608 return warned;
611 static bool
612 ATTRIBUTE_GCC_DIAG (6, 8) ATTRIBUTE_GCC_DIAG (7, 8)
613 fmtwarn_n (const substring_loc &fmt_loc, location_t param_loc,
614 const char *corrected_substring, int opt, unsigned HOST_WIDE_INT n,
615 const char *singular_gmsgid, const char *plural_gmsgid, ...)
617 va_list ap;
618 va_start (ap, plural_gmsgid);
619 bool warned = format_warning_n_va (fmt_loc, param_loc, corrected_substring,
620 opt, n, singular_gmsgid, plural_gmsgid,
621 &ap);
622 va_end (ap);
624 return warned;
627 /* Format length modifiers. */
629 enum format_lengths
631 FMT_LEN_none,
632 FMT_LEN_hh, // char argument
633 FMT_LEN_h, // short
634 FMT_LEN_l, // long
635 FMT_LEN_ll, // long long
636 FMT_LEN_L, // long double (and GNU long long)
637 FMT_LEN_z, // size_t
638 FMT_LEN_t, // ptrdiff_t
639 FMT_LEN_j // intmax_t
643 /* Description of the result of conversion either of a single directive
644 or the whole format string. */
646 struct fmtresult
648 /* Construct a FMTRESULT object with all counters initialized
649 to MIN. KNOWNRANGE is set when MIN is valid. */
650 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
651 : argmin (), argmax (),
652 knownrange (min < HOST_WIDE_INT_MAX),
653 nullp ()
655 range.min = min;
656 range.max = min;
657 range.likely = min;
658 range.unlikely = min;
661 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
662 KNOWNRANGE is set when both MIN and MAX are valid. */
663 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
664 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
665 : argmin (), argmax (),
666 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
667 nullp ()
669 range.min = min;
670 range.max = max;
671 range.likely = max < likely ? min : likely;
672 range.unlikely = max;
675 /* Adjust result upward to reflect the RANGE of values the specified
676 width or precision is known to be in. */
677 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
678 tree = NULL_TREE,
679 unsigned = 0, unsigned = 0);
681 /* Return the maximum number of decimal digits a value of TYPE
682 formats as on output. */
683 static unsigned type_max_digits (tree, int);
685 /* The range a directive's argument is in. */
686 tree argmin, argmax;
688 /* The minimum and maximum number of bytes that a directive
689 results in on output for an argument in the range above. */
690 result_range range;
692 /* True when the range above is obtained from a known value of
693 a directive's argument or its bounds and not the result of
694 heuristics that depend on warning levels. */
695 bool knownrange;
697 /* True when the argument is a null pointer. */
698 bool nullp;
701 /* Adjust result upward to reflect the range ADJUST of values the
702 specified width or precision is known to be in. When non-null,
703 TYPE denotes the type of the directive whose result is being
704 adjusted, BASE gives the base of the directive (octal, decimal,
705 or hex), and ADJ denotes the additional adjustment to the LIKELY
706 counter that may need to be added when ADJUST is a range. */
708 fmtresult&
709 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
710 tree type /* = NULL_TREE */,
711 unsigned base /* = 0 */,
712 unsigned adj /* = 0 */)
714 bool minadjusted = false;
716 /* Adjust the minimum and likely counters. */
717 if (adjust[0] >= 0)
719 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
721 range.min = adjust[0];
722 minadjusted = true;
725 /* Adjust the likely counter. */
726 if (range.likely < range.min)
727 range.likely = range.min;
729 else if (adjust[0] == target_int_min ()
730 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
731 knownrange = false;
733 /* Adjust the maximum counter. */
734 if (adjust[1] > 0)
736 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
738 range.max = adjust[1];
740 /* Set KNOWNRANGE if both the minimum and maximum have been
741 adjusted. Otherwise leave it at what it was before. */
742 knownrange = minadjusted;
746 if (warn_level > 1 && type)
748 /* For large non-constant width or precision whose range spans
749 the maximum number of digits produced by the directive for
750 any argument, set the likely number of bytes to be at most
751 the number digits plus other adjustment determined by the
752 caller (one for sign or two for the hexadecimal "0x"
753 prefix). */
754 unsigned dirdigs = type_max_digits (type, base);
755 if (adjust[0] < dirdigs && dirdigs < adjust[1]
756 && range.likely < dirdigs)
757 range.likely = dirdigs + adj;
759 else if (range.likely < (range.min ? range.min : 1))
761 /* Conservatively, set LIKELY to at least MIN but no less than
762 1 unless MAX is zero. */
763 range.likely = (range.min
764 ? range.min
765 : range.max && (range.max < HOST_WIDE_INT_MAX
766 || warn_level > 1) ? 1 : 0);
769 /* Finally adjust the unlikely counter to be at least as large as
770 the maximum. */
771 if (range.unlikely < range.max)
772 range.unlikely = range.max;
774 return *this;
777 /* Return the maximum number of digits a value of TYPE formats in
778 BASE on output, not counting base prefix . */
780 unsigned
781 fmtresult::type_max_digits (tree type, int base)
783 unsigned prec = TYPE_PRECISION (type);
784 switch (base)
786 case 8:
787 return (prec + 2) / 3;
788 case 10:
789 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
790 of 8, 16, 32, and 64 bits. */
791 return prec * 301 / 1000 + 1;
792 case 16:
793 return prec / 4;
796 gcc_unreachable ();
799 static bool
800 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT,
801 class vr_values *vr_values);
803 /* Description of a format directive. A directive is either a plain
804 string or a conversion specification that starts with '%'. */
806 struct directive
808 /* The 1-based directive number (for debugging). */
809 unsigned dirno;
811 /* The first character of the directive and its length. */
812 const char *beg;
813 size_t len;
815 /* A bitmap of flags, one for each character. */
816 unsigned flags[256 / sizeof (int)];
818 /* The range of values of the specified width, or -1 if not specified. */
819 HOST_WIDE_INT width[2];
820 /* The range of values of the specified precision, or -1 if not
821 specified. */
822 HOST_WIDE_INT prec[2];
824 /* Length modifier. */
825 format_lengths modifier;
827 /* Format specifier character. */
828 char specifier;
830 /* The argument of the directive or null when the directive doesn't
831 take one or when none is available (such as for vararg functions). */
832 tree arg;
834 /* Format conversion function that given a directive and an argument
835 returns the formatting result. */
836 fmtresult (*fmtfunc) (const directive &, tree, vr_values *);
838 /* Return True when a the format flag CHR has been used. */
839 bool get_flag (char chr) const
841 unsigned char c = chr & 0xff;
842 return (flags[c / (CHAR_BIT * sizeof *flags)]
843 & (1U << (c % (CHAR_BIT * sizeof *flags))));
846 /* Make a record of the format flag CHR having been used. */
847 void set_flag (char chr)
849 unsigned char c = chr & 0xff;
850 flags[c / (CHAR_BIT * sizeof *flags)]
851 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
854 /* Reset the format flag CHR. */
855 void clear_flag (char chr)
857 unsigned char c = chr & 0xff;
858 flags[c / (CHAR_BIT * sizeof *flags)]
859 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
862 /* Set both bounds of the width range to VAL. */
863 void set_width (HOST_WIDE_INT val)
865 width[0] = width[1] = val;
868 /* Set the width range according to ARG, with both bounds being
869 no less than 0. For a constant ARG set both bounds to its value
870 or 0, whichever is greater. For a non-constant ARG in some range
871 set width to its range adjusting each bound to -1 if it's less.
872 For an indeterminate ARG set width to [0, INT_MAX]. */
873 void set_width (tree arg, vr_values *vr_values)
875 get_int_range (arg, width, width + 1, true, 0, vr_values);
878 /* Set both bounds of the precision range to VAL. */
879 void set_precision (HOST_WIDE_INT val)
881 prec[0] = prec[1] = val;
884 /* Set the precision range according to ARG, with both bounds being
885 no less than -1. For a constant ARG set both bounds to its value
886 or -1 whichever is greater. For a non-constant ARG in some range
887 set precision to its range adjusting each bound to -1 if it's less.
888 For an indeterminate ARG set precision to [-1, INT_MAX]. */
889 void set_precision (tree arg, vr_values *vr_values)
891 get_int_range (arg, prec, prec + 1, false, -1, vr_values);
894 /* Return true if both width and precision are known to be
895 either constant or in some range, false otherwise. */
896 bool known_width_and_precision () const
898 return ((width[1] < 0
899 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
900 && (prec[1] < 0
901 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
905 /* Return the logarithm of X in BASE. */
907 static int
908 ilog (unsigned HOST_WIDE_INT x, int base)
910 int res = 0;
913 ++res;
914 x /= base;
915 } while (x);
916 return res;
919 /* Return the number of bytes resulting from converting into a string
920 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
921 PLUS indicates whether 1 for a plus sign should be added for positive
922 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
923 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
924 be represented. */
926 static HOST_WIDE_INT
927 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
929 unsigned HOST_WIDE_INT absval;
931 HOST_WIDE_INT res;
933 if (TYPE_UNSIGNED (TREE_TYPE (x)))
935 if (tree_fits_uhwi_p (x))
937 absval = tree_to_uhwi (x);
938 res = plus;
940 else
941 return -1;
943 else
945 if (tree_fits_shwi_p (x))
947 HOST_WIDE_INT i = tree_to_shwi (x);
948 if (HOST_WIDE_INT_MIN == i)
950 /* Avoid undefined behavior due to negating a minimum. */
951 absval = HOST_WIDE_INT_MAX;
952 res = 1;
954 else if (i < 0)
956 absval = -i;
957 res = 1;
959 else
961 absval = i;
962 res = plus;
965 else
966 return -1;
969 int ndigs = ilog (absval, base);
971 res += prec < ndigs ? ndigs : prec;
973 /* Adjust a non-zero value for the base prefix, either hexadecimal,
974 or, unless precision has resulted in a leading zero, also octal. */
975 if (prefix && absval && (base == 16 || prec <= ndigs))
977 if (base == 8)
978 res += 1;
979 else if (base == 16)
980 res += 2;
983 return res;
986 /* Given the formatting result described by RES and NAVAIL, the number
987 of available in the destination, return the range of bytes remaining
988 in the destination. */
990 static inline result_range
991 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
993 result_range range;
995 if (HOST_WIDE_INT_MAX <= navail)
997 range.min = range.max = range.likely = range.unlikely = navail;
998 return range;
1001 /* The lower bound of the available range is the available size
1002 minus the maximum output size, and the upper bound is the size
1003 minus the minimum. */
1004 range.max = res.range.min < navail ? navail - res.range.min : 0;
1006 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
1008 if (res.range.max < HOST_WIDE_INT_MAX)
1009 range.min = res.range.max < navail ? navail - res.range.max : 0;
1010 else
1011 range.min = range.likely;
1013 range.unlikely = (res.range.unlikely < navail
1014 ? navail - res.range.unlikely : 0);
1016 return range;
1019 /* Description of a call to a formatted function. */
1021 struct sprintf_dom_walker::call_info
1023 /* Function call statement. */
1024 gimple *callstmt;
1026 /* Function called. */
1027 tree func;
1029 /* Called built-in function code. */
1030 built_in_function fncode;
1032 /* Format argument and format string extracted from it. */
1033 tree format;
1034 const char *fmtstr;
1036 /* The location of the format argument. */
1037 location_t fmtloc;
1039 /* The destination object size for __builtin___xxx_chk functions
1040 typically determined by __builtin_object_size, or -1 if unknown. */
1041 unsigned HOST_WIDE_INT objsize;
1043 /* Number of the first variable argument. */
1044 unsigned HOST_WIDE_INT argidx;
1046 /* True for functions like snprintf that specify the size of
1047 the destination, false for others like sprintf that don't. */
1048 bool bounded;
1050 /* True for bounded functions like snprintf that specify a zero-size
1051 buffer as a request to compute the size of output without actually
1052 writing any. NOWRITE is cleared in response to the %n directive
1053 which has side-effects similar to writing output. */
1054 bool nowrite;
1056 /* Return true if the called function's return value is used. */
1057 bool retval_used () const
1059 return gimple_get_lhs (callstmt);
1062 /* Return the warning option corresponding to the called function. */
1063 int warnopt () const
1065 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
1069 /* Return the result of formatting a no-op directive (such as '%n'). */
1071 static fmtresult
1072 format_none (const directive &, tree, vr_values *)
1074 fmtresult res (0);
1075 return res;
1078 /* Return the result of formatting the '%%' directive. */
1080 static fmtresult
1081 format_percent (const directive &, tree, vr_values *)
1083 fmtresult res (1);
1084 return res;
1088 /* Compute intmax_type_node and uintmax_type_node similarly to how
1089 tree.c builds size_type_node. */
1091 static void
1092 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
1094 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
1096 *pintmax = integer_type_node;
1097 *puintmax = unsigned_type_node;
1099 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
1101 *pintmax = long_integer_type_node;
1102 *puintmax = long_unsigned_type_node;
1104 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
1106 *pintmax = long_long_integer_type_node;
1107 *puintmax = long_long_unsigned_type_node;
1109 else
1111 for (int i = 0; i < NUM_INT_N_ENTS; i++)
1112 if (int_n_enabled_p[i])
1114 char name[50];
1115 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
1117 if (strcmp (name, UINTMAX_TYPE) == 0)
1119 *pintmax = int_n_trees[i].signed_type;
1120 *puintmax = int_n_trees[i].unsigned_type;
1121 return;
1124 gcc_unreachable ();
1128 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1129 in and that is representable in type int.
1130 Return true when the range is a subrange of that of int.
1131 When ARG is null it is as if it had the full range of int.
1132 When ABSOLUTE is true the range reflects the absolute value of
1133 the argument. When ABSOLUTE is false, negative bounds of
1134 the determined range are replaced with NEGBOUND. */
1136 static bool
1137 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1138 bool absolute, HOST_WIDE_INT negbound,
1139 class vr_values *vr_values)
1141 /* The type of the result. */
1142 const_tree type = integer_type_node;
1144 bool knownrange = false;
1146 if (!arg)
1148 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1149 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1151 else if (TREE_CODE (arg) == INTEGER_CST
1152 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1154 /* For a constant argument return its value adjusted as specified
1155 by NEGATIVE and NEGBOUND and return true to indicate that the
1156 result is known. */
1157 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1158 *pmax = *pmin;
1159 knownrange = true;
1161 else
1163 /* True if the argument's range cannot be determined. */
1164 bool unknown = true;
1166 tree argtype = TREE_TYPE (arg);
1168 /* Ignore invalid arguments with greater precision that that
1169 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1170 They will have been detected and diagnosed by -Wformat and
1171 so it's not important to complicate this code to try to deal
1172 with them again. */
1173 if (TREE_CODE (arg) == SSA_NAME
1174 && INTEGRAL_TYPE_P (argtype)
1175 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1177 /* Try to determine the range of values of the integer argument. */
1178 value_range *vr = vr_values->get_value_range (arg);
1179 if (vr->type == VR_RANGE
1180 && TREE_CODE (vr->min) == INTEGER_CST
1181 && TREE_CODE (vr->max) == INTEGER_CST)
1183 HOST_WIDE_INT type_min
1184 = (TYPE_UNSIGNED (argtype)
1185 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1186 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1188 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1190 *pmin = TREE_INT_CST_LOW (vr->min);
1191 *pmax = TREE_INT_CST_LOW (vr->max);
1193 if (*pmin < *pmax)
1195 /* Return true if the adjusted range is a subrange of
1196 the full range of the argument's type. *PMAX may
1197 be less than *PMIN when the argument is unsigned
1198 and its upper bound is in excess of TYPE_MAX. In
1199 that (invalid) case disregard the range and use that
1200 of the expected type instead. */
1201 knownrange = type_min < *pmin || *pmax < type_max;
1203 unknown = false;
1208 /* Handle an argument with an unknown range as if none had been
1209 provided. */
1210 if (unknown)
1211 return get_int_range (NULL_TREE, pmin, pmax, absolute,
1212 negbound, vr_values);
1215 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1216 if (absolute)
1218 if (*pmin < 0)
1220 if (*pmin == *pmax)
1221 *pmin = *pmax = -*pmin;
1222 else
1224 /* Make sure signed overlow is avoided. */
1225 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1227 HOST_WIDE_INT tmp = -*pmin;
1228 *pmin = 0;
1229 if (*pmax < tmp)
1230 *pmax = tmp;
1234 else if (*pmin < negbound)
1235 *pmin = negbound;
1237 return knownrange;
1240 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1241 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1242 the type of the directive's formal argument it's possible for both
1243 to result in the same number of bytes or a range of bytes that's
1244 less than the number of bytes that would result from formatting
1245 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1246 determined by checking for the actual argument being in the range
1247 of the type of the directive. If it isn't it must be assumed to
1248 take on the full range of the directive's type.
1249 Return true when the range has been adjusted to the full range
1250 of DIRTYPE, and false otherwise. */
1252 static bool
1253 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1255 tree argtype = TREE_TYPE (*argmin);
1256 unsigned argprec = TYPE_PRECISION (argtype);
1257 unsigned dirprec = TYPE_PRECISION (dirtype);
1259 /* If the actual argument and the directive's argument have the same
1260 precision and sign there can be no overflow and so there is nothing
1261 to adjust. */
1262 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1263 return false;
1265 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1266 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1268 if (TREE_CODE (*argmin) == INTEGER_CST
1269 && TREE_CODE (*argmax) == INTEGER_CST
1270 && (dirprec >= argprec
1271 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1272 int_const_binop (MINUS_EXPR,
1273 *argmax,
1274 *argmin),
1275 size_int (dirprec)))))
1277 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1278 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1280 /* If *ARGMIN is still less than *ARGMAX the conversion above
1281 is safe. Otherwise, it has overflowed and would be unsafe. */
1282 if (tree_int_cst_le (*argmin, *argmax))
1283 return false;
1286 *argmin = TYPE_MIN_VALUE (dirtype);
1287 *argmax = TYPE_MAX_VALUE (dirtype);
1288 return true;
1291 /* Return a range representing the minimum and maximum number of bytes
1292 that the format directive DIR will output for any argument given
1293 the WIDTH and PRECISION (extracted from DIR). This function is
1294 used when the directive argument or its value isn't known. */
1296 static fmtresult
1297 format_integer (const directive &dir, tree arg, vr_values *vr_values)
1299 tree intmax_type_node;
1300 tree uintmax_type_node;
1302 /* Base to format the number in. */
1303 int base;
1305 /* True when a conversion is preceded by a prefix indicating the base
1306 of the argument (octal or hexadecimal). */
1307 bool maybebase = dir.get_flag ('#');
1309 /* True when a signed conversion is preceded by a sign or space. */
1310 bool maybesign = false;
1312 /* True for signed conversions (i.e., 'd' and 'i'). */
1313 bool sign = false;
1315 switch (dir.specifier)
1317 case 'd':
1318 case 'i':
1319 /* Space and '+' are only meaningful for signed conversions. */
1320 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1321 sign = true;
1322 base = 10;
1323 break;
1324 case 'u':
1325 base = 10;
1326 break;
1327 case 'o':
1328 base = 8;
1329 break;
1330 case 'X':
1331 case 'x':
1332 base = 16;
1333 break;
1334 default:
1335 gcc_unreachable ();
1338 /* The type of the "formal" argument expected by the directive. */
1339 tree dirtype = NULL_TREE;
1341 /* Determine the expected type of the argument from the length
1342 modifier. */
1343 switch (dir.modifier)
1345 case FMT_LEN_none:
1346 if (dir.specifier == 'p')
1347 dirtype = ptr_type_node;
1348 else
1349 dirtype = sign ? integer_type_node : unsigned_type_node;
1350 break;
1352 case FMT_LEN_h:
1353 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1354 break;
1356 case FMT_LEN_hh:
1357 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1358 break;
1360 case FMT_LEN_l:
1361 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1362 break;
1364 case FMT_LEN_L:
1365 case FMT_LEN_ll:
1366 dirtype = (sign
1367 ? long_long_integer_type_node
1368 : long_long_unsigned_type_node);
1369 break;
1371 case FMT_LEN_z:
1372 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1373 break;
1375 case FMT_LEN_t:
1376 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1377 break;
1379 case FMT_LEN_j:
1380 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1381 dirtype = sign ? intmax_type_node : uintmax_type_node;
1382 break;
1384 default:
1385 return fmtresult ();
1388 /* The type of the argument to the directive, either deduced from
1389 the actual non-constant argument if one is known, or from
1390 the directive itself when none has been provided because it's
1391 a va_list. */
1392 tree argtype = NULL_TREE;
1394 if (!arg)
1396 /* When the argument has not been provided, use the type of
1397 the directive's argument as an approximation. This will
1398 result in false positives for directives like %i with
1399 arguments with smaller precision (such as short or char). */
1400 argtype = dirtype;
1402 else if (TREE_CODE (arg) == INTEGER_CST)
1404 /* When a constant argument has been provided use its value
1405 rather than type to determine the length of the output. */
1406 fmtresult res;
1408 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1410 /* As a special case, a precision of zero with a zero argument
1411 results in zero bytes except in base 8 when the '#' flag is
1412 specified, and for signed conversions in base 8 and 10 when
1413 either the space or '+' flag has been specified and it results
1414 in just one byte (with width having the normal effect). This
1415 must extend to the case of a specified precision with
1416 an unknown value because it can be zero. */
1417 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1418 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1420 res.range.max = 1;
1421 res.range.likely = 1;
1423 else
1425 res.range.max = res.range.min;
1426 res.range.likely = res.range.min;
1429 else
1431 /* Convert the argument to the type of the directive. */
1432 arg = fold_convert (dirtype, arg);
1434 res.range.min = tree_digits (arg, base, dir.prec[0],
1435 maybesign, maybebase);
1436 if (dir.prec[0] == dir.prec[1])
1437 res.range.max = res.range.min;
1438 else
1439 res.range.max = tree_digits (arg, base, dir.prec[1],
1440 maybesign, maybebase);
1441 res.range.likely = res.range.min;
1442 res.knownrange = true;
1445 res.range.unlikely = res.range.max;
1447 /* Bump up the counters if WIDTH is greater than LEN. */
1448 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1449 (sign | maybebase) + (base == 16));
1450 /* Bump up the counters again if PRECision is greater still. */
1451 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1452 (sign | maybebase) + (base == 16));
1454 return res;
1456 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1457 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1458 /* Determine the type of the provided non-constant argument. */
1459 argtype = TREE_TYPE (arg);
1460 else
1461 /* Don't bother with invalid arguments since they likely would
1462 have already been diagnosed, and disable any further checking
1463 of the format string by returning [-1, -1]. */
1464 return fmtresult ();
1466 fmtresult res;
1468 /* Using either the range the non-constant argument is in, or its
1469 type (either "formal" or actual), create a range of values that
1470 constrain the length of output given the warning level. */
1471 tree argmin = NULL_TREE;
1472 tree argmax = NULL_TREE;
1474 if (arg
1475 && TREE_CODE (arg) == SSA_NAME
1476 && INTEGRAL_TYPE_P (argtype))
1478 /* Try to determine the range of values of the integer argument
1479 (range information is not available for pointers). */
1480 value_range *vr = vr_values->get_value_range (arg);
1481 if (vr->type == VR_RANGE
1482 && TREE_CODE (vr->min) == INTEGER_CST
1483 && TREE_CODE (vr->max) == INTEGER_CST)
1485 argmin = vr->min;
1486 argmax = vr->max;
1488 /* Set KNOWNRANGE if the argument is in a known subrange
1489 of the directive's type and neither width nor precision
1490 is unknown. (KNOWNRANGE may be reset below). */
1491 res.knownrange
1492 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1493 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1494 && dir.known_width_and_precision ());
1496 res.argmin = argmin;
1497 res.argmax = argmax;
1499 else if (vr->type == VR_ANTI_RANGE)
1501 /* Handle anti-ranges if/when bug 71690 is resolved. */
1503 else if (vr->type == VR_VARYING
1504 || vr->type == VR_UNDEFINED)
1506 /* The argument here may be the result of promoting the actual
1507 argument to int. Try to determine the type of the actual
1508 argument before promotion and narrow down its range that
1509 way. */
1510 gimple *def = SSA_NAME_DEF_STMT (arg);
1511 if (is_gimple_assign (def))
1513 tree_code code = gimple_assign_rhs_code (def);
1514 if (code == INTEGER_CST)
1516 arg = gimple_assign_rhs1 (def);
1517 return format_integer (dir, arg, vr_values);
1520 if (code == NOP_EXPR)
1522 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1523 if (INTEGRAL_TYPE_P (type)
1524 || TREE_CODE (type) == POINTER_TYPE)
1525 argtype = type;
1531 if (!argmin)
1533 if (TREE_CODE (argtype) == POINTER_TYPE)
1535 argmin = build_int_cst (pointer_sized_int_node, 0);
1536 argmax = build_all_ones_cst (pointer_sized_int_node);
1538 else
1540 argmin = TYPE_MIN_VALUE (argtype);
1541 argmax = TYPE_MAX_VALUE (argtype);
1545 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1546 of the directive. If it has been cleared then since ARGMIN and/or
1547 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1548 ARGMAX in the result to include in diagnostics. */
1549 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1551 res.knownrange = false;
1552 res.argmin = argmin;
1553 res.argmax = argmax;
1556 /* Recursively compute the minimum and maximum from the known range. */
1557 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1559 /* For unsigned conversions/directives or signed when
1560 the minimum is positive, use the minimum and maximum to compute
1561 the shortest and longest output, respectively. */
1562 res.range.min = format_integer (dir, argmin, vr_values).range.min;
1563 res.range.max = format_integer (dir, argmax, vr_values).range.max;
1565 else if (tree_int_cst_sgn (argmax) < 0)
1567 /* For signed conversions/directives if maximum is negative,
1568 use the minimum as the longest output and maximum as the
1569 shortest output. */
1570 res.range.min = format_integer (dir, argmax, vr_values).range.min;
1571 res.range.max = format_integer (dir, argmin, vr_values).range.max;
1573 else
1575 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1576 as the shortest output and for the longest output compute the
1577 length of the output of both minimum and maximum and pick the
1578 longer. */
1579 unsigned HOST_WIDE_INT max1
1580 = format_integer (dir, argmin, vr_values).range.max;
1581 unsigned HOST_WIDE_INT max2
1582 = format_integer (dir, argmax, vr_values).range.max;
1583 res.range.min
1584 = format_integer (dir, integer_zero_node, vr_values).range.min;
1585 res.range.max = MAX (max1, max2);
1588 /* If the range is known, use the maximum as the likely length. */
1589 if (res.knownrange)
1590 res.range.likely = res.range.max;
1591 else
1593 /* Otherwise, use the minimum. Except for the case where for %#x or
1594 %#o the minimum is just for a single value in the range (0) and
1595 for all other values it is something longer, like 0x1 or 01.
1596 Use the length for value 1 in that case instead as the likely
1597 length. */
1598 res.range.likely = res.range.min;
1599 if (maybebase
1600 && base != 10
1601 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1603 if (res.range.min == 1)
1604 res.range.likely += base == 8 ? 1 : 2;
1605 else if (res.range.min == 2
1606 && base == 16
1607 && (dir.width[0] == 2 || dir.prec[0] == 2))
1608 ++res.range.likely;
1612 res.range.unlikely = res.range.max;
1613 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1614 (sign | maybebase) + (base == 16));
1615 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1616 (sign | maybebase) + (base == 16));
1618 return res;
1621 /* Return the number of bytes that a format directive consisting of FLAGS,
1622 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1623 would result for argument X under ideal conditions (i.e., if PREC
1624 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1625 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1626 This function works around those problems. */
1628 static unsigned HOST_WIDE_INT
1629 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1630 char spec, char rndspec)
1632 char fmtstr[40];
1634 HOST_WIDE_INT len = strlen (flags);
1636 fmtstr[0] = '%';
1637 memcpy (fmtstr + 1, flags, len);
1638 memcpy (fmtstr + 1 + len, ".*R", 3);
1639 fmtstr[len + 4] = rndspec;
1640 fmtstr[len + 5] = spec;
1641 fmtstr[len + 6] = '\0';
1643 spec = TOUPPER (spec);
1644 if (spec == 'E' || spec == 'F')
1646 /* For %e, specify the precision explicitly since mpfr_sprintf
1647 does its own thing just to be different (see MPFR bug 21088). */
1648 if (prec < 0)
1649 prec = 6;
1651 else
1653 /* Avoid passing negative precisions with larger magnitude to MPFR
1654 to avoid exposing its bugs. (A negative precision is supposed
1655 to be ignored.) */
1656 if (prec < 0)
1657 prec = -1;
1660 HOST_WIDE_INT p = prec;
1662 if (spec == 'G' && !strchr (flags, '#'))
1664 /* For G/g without the pound flag, precision gives the maximum number
1665 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1666 a 128 bit IEEE extended precision, 4932. Using twice as much here
1667 should be more than sufficient for any real format. */
1668 if ((IEEE_MAX_10_EXP * 2) < prec)
1669 prec = IEEE_MAX_10_EXP * 2;
1670 p = prec;
1672 else
1674 /* Cap precision arbitrarily at 1KB and add the difference
1675 (if any) to the MPFR result. */
1676 if (prec > 1024)
1677 p = 1024;
1680 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1682 /* Handle the unlikely (impossible?) error by returning more than
1683 the maximum dictated by the function's return type. */
1684 if (len < 0)
1685 return target_dir_max () + 1;
1687 /* Adjust the return value by the difference. */
1688 if (p < prec)
1689 len += prec - p;
1691 return len;
1694 /* Return the number of bytes to format using the format specifier
1695 SPEC and the precision PREC the largest value in the real floating
1696 TYPE. */
1698 static unsigned HOST_WIDE_INT
1699 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1701 machine_mode mode = TYPE_MODE (type);
1703 /* IBM Extended mode. */
1704 if (MODE_COMPOSITE_P (mode))
1705 mode = DFmode;
1707 /* Get the real type format desription for the target. */
1708 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1709 REAL_VALUE_TYPE rv;
1711 real_maxval (&rv, 0, mode);
1713 /* Convert the GCC real value representation with the precision
1714 of the real type to the mpfr_t format with the GCC default
1715 round-to-nearest mode. */
1716 mpfr_t x;
1717 mpfr_init2 (x, rfmt->p);
1718 mpfr_from_real (x, &rv, GMP_RNDN);
1720 /* Return a value one greater to account for the leading minus sign. */
1721 unsigned HOST_WIDE_INT r
1722 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1723 mpfr_clear (x);
1724 return r;
1727 /* Return a range representing the minimum and maximum number of bytes
1728 that the directive DIR will output for any argument. PREC gives
1729 the adjusted precision range to account for negative precisions
1730 meaning the default 6. This function is used when the directive
1731 argument or its value isn't known. */
1733 static fmtresult
1734 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1736 tree type;
1738 switch (dir.modifier)
1740 case FMT_LEN_l:
1741 case FMT_LEN_none:
1742 type = double_type_node;
1743 break;
1745 case FMT_LEN_L:
1746 type = long_double_type_node;
1747 break;
1749 case FMT_LEN_ll:
1750 type = long_double_type_node;
1751 break;
1753 default:
1754 return fmtresult ();
1757 /* The minimum and maximum number of bytes produced by the directive. */
1758 fmtresult res;
1760 /* The minimum output as determined by flags. It's always at least 1.
1761 When plus or space are set the output is preceded by either a sign
1762 or a space. */
1763 unsigned flagmin = (1 /* for the first digit */
1764 + (dir.get_flag ('+') | dir.get_flag (' ')));
1766 /* The minimum is 3 for "inf" and "nan" for all specifiers, plus 1
1767 for the plus sign/space with the '+' and ' ' flags, respectively,
1768 unless reduced below. */
1769 res.range.min = 2 + flagmin;
1771 /* When the pound flag is set the decimal point is included in output
1772 regardless of precision. Whether or not a decimal point is included
1773 otherwise depends on the specification and precision. */
1774 bool radix = dir.get_flag ('#');
1776 switch (dir.specifier)
1778 case 'A':
1779 case 'a':
1781 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1782 if (dir.prec[0] <= 0)
1783 minprec = 0;
1784 else if (dir.prec[0] > 0)
1785 minprec = dir.prec[0] + !radix /* decimal point */;
1787 res.range.likely = (2 /* 0x */
1788 + flagmin
1789 + radix
1790 + minprec
1791 + 3 /* p+0 */);
1793 res.range.max = format_floating_max (type, 'a', prec[1]);
1795 /* The unlikely maximum accounts for the longest multibyte
1796 decimal point character. */
1797 res.range.unlikely = res.range.max;
1798 if (dir.prec[1] > 0)
1799 res.range.unlikely += target_mb_len_max () - 1;
1801 break;
1804 case 'E':
1805 case 'e':
1807 /* Minimum output attributable to precision and, when it's
1808 non-zero, decimal point. */
1809 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1811 /* The likely minimum output is "[-+]1.234567e+00" regardless
1812 of the value of the actual argument. */
1813 res.range.likely = (flagmin
1814 + radix
1815 + minprec
1816 + 2 /* e+ */ + 2);
1818 res.range.max = format_floating_max (type, 'e', prec[1]);
1820 /* The unlikely maximum accounts for the longest multibyte
1821 decimal point character. */
1822 if (dir.prec[0] != dir.prec[1]
1823 || dir.prec[0] == -1 || dir.prec[0] > 0)
1824 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1825 else
1826 res.range.unlikely = res.range.max;
1827 break;
1830 case 'F':
1831 case 'f':
1833 /* Minimum output attributable to precision and, when it's non-zero,
1834 decimal point. */
1835 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1837 /* For finite numbers (i.e., not infinity or NaN) the lower bound
1838 when precision isn't specified is 8 bytes ("1.23456" since
1839 precision is taken to be 6). When precision is zero, the lower
1840 bound is 1 byte (e.g., "1"). Otherwise, when precision is greater
1841 than zero, then the lower bound is 2 plus precision (plus flags).
1842 But in all cases, the lower bound is no greater than 3. */
1843 unsigned HOST_WIDE_INT min = flagmin + radix + minprec;
1844 if (min < res.range.min)
1845 res.range.min = min;
1847 /* Compute the upper bound for -TYPE_MAX. */
1848 res.range.max = format_floating_max (type, 'f', prec[1]);
1850 /* The minimum output with unknown precision is a single byte
1851 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1852 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1853 res.range.likely = 3;
1854 else
1855 res.range.likely = min;
1857 /* The unlikely maximum accounts for the longest multibyte
1858 decimal point character. */
1859 if (dir.prec[0] != dir.prec[1]
1860 || dir.prec[0] == -1 || dir.prec[0] > 0)
1861 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1862 break;
1865 case 'G':
1866 case 'g':
1868 /* The %g output depends on precision and the exponent of
1869 the argument. Since the value of the argument isn't known
1870 the lower bound on the range of bytes (not counting flags
1871 or width) is 1 plus radix (i.e., either "0" or "0." for
1872 "%g" and "%#g", respectively, with a zero argument). */
1873 unsigned HOST_WIDE_INT min = flagmin + radix;
1874 if (min < res.range.min)
1875 res.range.min = min;
1877 char spec = 'g';
1878 HOST_WIDE_INT maxprec = dir.prec[1];
1879 if (radix && maxprec)
1881 /* When the pound flag (radix) is set, trailing zeros aren't
1882 trimmed and so the longest output is the same as for %e,
1883 except with precision minus 1 (as specified in C11). */
1884 spec = 'e';
1885 if (maxprec > 0)
1886 --maxprec;
1887 else if (maxprec < 0)
1888 maxprec = 5;
1890 else
1891 maxprec = prec[1];
1893 res.range.max = format_floating_max (type, spec, maxprec);
1895 /* The likely output is either the maximum computed above
1896 minus 1 (assuming the maximum is positive) when precision
1897 is known (or unspecified), or the same minimum as for %e
1898 (which is computed for a non-negative argument). Unlike
1899 for the other specifiers above the likely output isn't
1900 the minimum because for %g that's 1 which is unlikely. */
1901 if (dir.prec[1] < 0
1902 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1903 res.range.likely = res.range.max - 1;
1904 else
1906 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1907 res.range.likely = (flagmin
1908 + radix
1909 + minprec
1910 + 2 /* e+ */ + 2);
1913 /* The unlikely maximum accounts for the longest multibyte
1914 decimal point character. */
1915 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1916 break;
1919 default:
1920 return fmtresult ();
1923 /* Bump up the byte counters if WIDTH is greater. */
1924 res.adjust_for_width_or_precision (dir.width);
1925 return res;
1928 /* Return a range representing the minimum and maximum number of bytes
1929 that the directive DIR will write on output for the floating argument
1930 ARG. */
1932 static fmtresult
1933 format_floating (const directive &dir, tree arg, vr_values *)
1935 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1936 tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1937 ? long_double_type_node : double_type_node);
1939 /* For an indeterminate precision the lower bound must be assumed
1940 to be zero. */
1941 if (TOUPPER (dir.specifier) == 'A')
1943 /* Get the number of fractional decimal digits needed to represent
1944 the argument without a loss of accuracy. */
1945 unsigned fmtprec
1946 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1948 /* The precision of the IEEE 754 double format is 53.
1949 The precision of all other GCC binary double formats
1950 is 56 or less. */
1951 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1953 /* For %a, leave the minimum precision unspecified to let
1954 MFPR trim trailing zeros (as it and many other systems
1955 including Glibc happen to do) and set the maximum
1956 precision to reflect what it would be with trailing zeros
1957 present (as Solaris and derived systems do). */
1958 if (dir.prec[1] < 0)
1960 /* Both bounds are negative implies that precision has
1961 not been specified. */
1962 prec[0] = maxprec;
1963 prec[1] = -1;
1965 else if (dir.prec[0] < 0)
1967 /* With a negative lower bound and a non-negative upper
1968 bound set the minimum precision to zero and the maximum
1969 to the greater of the maximum precision (i.e., with
1970 trailing zeros present) and the specified upper bound. */
1971 prec[0] = 0;
1972 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1975 else if (dir.prec[0] < 0)
1977 if (dir.prec[1] < 0)
1979 /* A precision in a strictly negative range is ignored and
1980 the default of 6 is used instead. */
1981 prec[0] = prec[1] = 6;
1983 else
1985 /* For a precision in a partly negative range, the lower bound
1986 must be assumed to be zero and the new upper bound is the
1987 greater of 6 (the default precision used when the specified
1988 precision is negative) and the upper bound of the specified
1989 range. */
1990 prec[0] = 0;
1991 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1995 if (!arg
1996 || TREE_CODE (arg) != REAL_CST
1997 || !useless_type_conversion_p (type, TREE_TYPE (arg)))
1998 return format_floating (dir, prec);
2000 /* The minimum and maximum number of bytes produced by the directive. */
2001 fmtresult res;
2003 /* Get the real type format desription for the target. */
2004 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
2005 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
2007 if (!real_isfinite (rvp))
2009 /* The format for Infinity and NaN is "[-]inf"/"[-]infinity"
2010 and "[-]nan" with the choice being implementation-defined
2011 but not locale dependent. */
2012 bool sign = dir.get_flag ('+') || real_isneg (rvp);
2013 res.range.min = 3 + sign;
2015 res.range.likely = res.range.min;
2016 res.range.max = res.range.min;
2017 /* The unlikely maximum is "[-/+]infinity" or "[-/+][qs]nan".
2018 For NaN, the C/POSIX standards specify two formats:
2019 "[-/+]nan"
2021 "[-/+]nan(n-char-sequence)"
2022 No known printf implementation outputs the latter format but AIX
2023 outputs QNaN and SNaN for quiet and signalling NaN, respectively,
2024 so the unlikely maximum reflects that. */
2025 res.range.unlikely = sign + (real_isinf (rvp) ? 8 : 4);
2027 /* The range for infinity and NaN is known unless either width
2028 or precision is unknown. Width has the same effect regardless
2029 of whether the argument is finite. Precision is either ignored
2030 (e.g., Glibc) or can have an effect on the short vs long format
2031 such as inf/infinity (e.g., Solaris). */
2032 res.knownrange = dir.known_width_and_precision ();
2034 /* Adjust the range for width but ignore precision. */
2035 res.adjust_for_width_or_precision (dir.width);
2037 return res;
2040 char fmtstr [40];
2041 char *pfmt = fmtstr;
2043 /* Append flags. */
2044 for (const char *pf = "-+ #0"; *pf; ++pf)
2045 if (dir.get_flag (*pf))
2046 *pfmt++ = *pf;
2048 *pfmt = '\0';
2051 /* Set up an array to easily iterate over. */
2052 unsigned HOST_WIDE_INT* const minmax[] = {
2053 &res.range.min, &res.range.max
2056 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
2058 /* Convert the GCC real value representation with the precision
2059 of the real type to the mpfr_t format rounding down in the
2060 first iteration that computes the minimm and up in the second
2061 that computes the maximum. This order is arbibtrary because
2062 rounding in either direction can result in longer output. */
2063 mpfr_t mpfrval;
2064 mpfr_init2 (mpfrval, rfmt->p);
2065 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
2067 /* Use the MPFR rounding specifier to round down in the first
2068 iteration and then up. In most but not all cases this will
2069 result in the same number of bytes. */
2070 char rndspec = "DU"[i];
2072 /* Format it and store the result in the corresponding member
2073 of the result struct. */
2074 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
2075 dir.specifier, rndspec);
2076 mpfr_clear (mpfrval);
2080 /* Make sure the minimum is less than the maximum (MPFR rounding
2081 in the call to mpfr_snprintf can result in the reverse. */
2082 if (res.range.max < res.range.min)
2084 unsigned HOST_WIDE_INT tmp = res.range.min;
2085 res.range.min = res.range.max;
2086 res.range.max = tmp;
2089 /* The range is known unless either width or precision is unknown. */
2090 res.knownrange = dir.known_width_and_precision ();
2092 /* For the same floating point constant, unless width or precision
2093 is unknown, use the longer output as the likely maximum since
2094 with round to nearest either is equally likely. Otheriwse, when
2095 precision is unknown, use the greater of the minimum and 3 as
2096 the likely output (for "0.0" since zero precision is unlikely). */
2097 if (res.knownrange)
2098 res.range.likely = res.range.max;
2099 else if (res.range.min < 3
2100 && dir.prec[0] < 0
2101 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
2102 res.range.likely = 3;
2103 else
2104 res.range.likely = res.range.min;
2106 res.range.unlikely = res.range.max;
2108 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
2110 /* Unless the precision is zero output longer than 2 bytes may
2111 include the decimal point which must be a single character
2112 up to MB_LEN_MAX in length. This is overly conservative
2113 since in some conversions some constants result in no decimal
2114 point (e.g., in %g). */
2115 res.range.unlikely += target_mb_len_max () - 1;
2118 res.adjust_for_width_or_precision (dir.width);
2119 return res;
2122 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
2123 strings referenced by the expression STR, or (-1, -1) when not known.
2124 Used by the format_string function below. */
2126 static fmtresult
2127 get_string_length (tree str)
2129 if (!str)
2130 return fmtresult ();
2132 if (tree slen = c_strlen (str, 1))
2134 /* Simply return the length of the string. */
2135 fmtresult res (tree_to_shwi (slen));
2136 return res;
2139 /* Determine the length of the shortest and longest string referenced
2140 by STR. Strings of unknown lengths are bounded by the sizes of
2141 arrays that subexpressions of STR may refer to. Pointers that
2142 aren't known to point any such arrays result in LENRANGE[1] set
2143 to SIZE_MAX. */
2144 tree lenrange[2];
2145 bool flexarray = get_range_strlen (str, lenrange);
2147 if (lenrange [0] || lenrange [1])
2149 HOST_WIDE_INT min
2150 = (tree_fits_uhwi_p (lenrange[0])
2151 ? tree_to_uhwi (lenrange[0])
2152 : 0);
2154 HOST_WIDE_INT max
2155 = (tree_fits_uhwi_p (lenrange[1])
2156 ? tree_to_uhwi (lenrange[1])
2157 : HOST_WIDE_INT_M1U);
2159 /* get_range_strlen() returns the target value of SIZE_MAX for
2160 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2161 which may be bigger. */
2162 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2163 min = HOST_WIDE_INT_M1U;
2164 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2165 max = HOST_WIDE_INT_M1U;
2167 fmtresult res (min, max);
2169 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2170 by STR are known to be bounded (though not necessarily by their
2171 actual length but perhaps by their maximum possible length). */
2172 if (res.range.max < target_int_max ())
2174 res.knownrange = true;
2175 /* When the the length of the longest string is known and not
2176 excessive use it as the likely length of the string(s). */
2177 res.range.likely = res.range.max;
2179 else
2181 /* When the upper bound is unknown (it can be zero or excessive)
2182 set the likely length to the greater of 1 and the length of
2183 the shortest string and reset the lower bound to zero. */
2184 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2185 res.range.min = 0;
2188 /* If the range of string length has been estimated from the size
2189 of an array at the end of a struct assume that it's longer than
2190 the array bound says it is in case it's used as a poor man's
2191 flexible array member, such as in struct S { char a[4]; }; */
2192 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
2194 return res;
2197 return get_string_length (NULL_TREE);
2200 /* Return the minimum and maximum number of characters formatted
2201 by the '%c' format directives and its wide character form for
2202 the argument ARG. ARG can be null (for functions such as
2203 vsprinf). */
2205 static fmtresult
2206 format_character (const directive &dir, tree arg, vr_values *vr_values)
2208 fmtresult res;
2210 res.knownrange = true;
2212 if (dir.modifier == FMT_LEN_l)
2214 /* A wide character can result in as few as zero bytes. */
2215 res.range.min = 0;
2217 HOST_WIDE_INT min, max;
2218 if (get_int_range (arg, &min, &max, false, 0, vr_values))
2220 if (min == 0 && max == 0)
2222 /* The NUL wide character results in no bytes. */
2223 res.range.max = 0;
2224 res.range.likely = 0;
2225 res.range.unlikely = 0;
2227 else if (min > 0 && min < 128)
2229 /* A wide character in the ASCII range most likely results
2230 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2231 res.range.max = 1;
2232 res.range.likely = 1;
2233 res.range.unlikely = target_mb_len_max ();
2235 else
2237 /* A wide character outside the ASCII range likely results
2238 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2239 res.range.max = target_mb_len_max ();
2240 res.range.likely = 2;
2241 res.range.unlikely = res.range.max;
2244 else
2246 /* An unknown wide character is treated the same as a wide
2247 character outside the ASCII range. */
2248 res.range.max = target_mb_len_max ();
2249 res.range.likely = 2;
2250 res.range.unlikely = res.range.max;
2253 else
2255 /* A plain '%c' directive. Its ouput is exactly 1. */
2256 res.range.min = res.range.max = 1;
2257 res.range.likely = res.range.unlikely = 1;
2258 res.knownrange = true;
2261 /* Bump up the byte counters if WIDTH is greater. */
2262 return res.adjust_for_width_or_precision (dir.width);
2265 /* Return the minimum and maximum number of characters formatted
2266 by the '%s' format directive and its wide character form for
2267 the argument ARG. ARG can be null (for functions such as
2268 vsprinf). */
2270 static fmtresult
2271 format_string (const directive &dir, tree arg, vr_values *)
2273 fmtresult res;
2275 /* Compute the range the argument's length can be in. */
2276 fmtresult slen = get_string_length (arg);
2277 if (slen.range.min == slen.range.max
2278 && slen.range.min < HOST_WIDE_INT_MAX)
2280 /* The argument is either a string constant or it refers
2281 to one of a number of strings of the same length. */
2283 /* A '%s' directive with a string argument with constant length. */
2284 res.range = slen.range;
2286 if (dir.modifier == FMT_LEN_l)
2288 /* In the worst case the length of output of a wide string S
2289 is bounded by MB_LEN_MAX * wcslen (S). */
2290 res.range.max *= target_mb_len_max ();
2291 res.range.unlikely = res.range.max;
2292 /* It's likely that the the total length is not more that
2293 2 * wcslen (S).*/
2294 res.range.likely = res.range.min * 2;
2296 if (dir.prec[1] >= 0
2297 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2299 res.range.max = dir.prec[1];
2300 res.range.likely = dir.prec[1];
2301 res.range.unlikely = dir.prec[1];
2304 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2305 res.range.min = 0;
2306 else if (dir.prec[0] >= 0)
2307 res.range.likely = dir.prec[0];
2309 /* Even a non-empty wide character string need not convert into
2310 any bytes. */
2311 res.range.min = 0;
2313 else
2315 res.knownrange = true;
2317 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2318 res.range.min = 0;
2319 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2320 res.range.min = dir.prec[0];
2322 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2324 res.range.max = dir.prec[1];
2325 res.range.likely = dir.prec[1];
2326 res.range.unlikely = dir.prec[1];
2330 else if (arg && integer_zerop (arg))
2332 /* Handle null pointer argument. */
2334 fmtresult res (0);
2335 res.nullp = true;
2336 return res;
2338 else
2340 /* For a '%s' and '%ls' directive with a non-constant string (either
2341 one of a number of strings of known length or an unknown string)
2342 the minimum number of characters is lesser of PRECISION[0] and
2343 the length of the shortest known string or zero, and the maximum
2344 is the lessser of the length of the longest known string or
2345 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2346 the minimum at level 1 and the greater of the minimum and 1
2347 at level 2. This result is adjust upward for width (if it's
2348 specified). */
2350 if (dir.modifier == FMT_LEN_l)
2352 /* A wide character converts to as few as zero bytes. */
2353 slen.range.min = 0;
2354 if (slen.range.max < target_int_max ())
2355 slen.range.max *= target_mb_len_max ();
2357 if (slen.range.likely < target_int_max ())
2358 slen.range.likely *= 2;
2360 if (slen.range.likely < target_int_max ())
2361 slen.range.unlikely *= target_mb_len_max ();
2364 res.range = slen.range;
2366 if (dir.prec[0] >= 0)
2368 /* Adjust the minimum to zero if the string length is unknown,
2369 or at most the lower bound of the precision otherwise. */
2370 if (slen.range.min >= target_int_max ())
2371 res.range.min = 0;
2372 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2373 res.range.min = dir.prec[0];
2375 /* Make both maxima no greater than the upper bound of precision. */
2376 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2377 || slen.range.max >= target_int_max ())
2379 res.range.max = dir.prec[1];
2380 res.range.unlikely = dir.prec[1];
2383 /* If precision is constant, set the likely counter to the lesser
2384 of it and the maximum string length. Otherwise, if the lower
2385 bound of precision is greater than zero, set the likely counter
2386 to the minimum. Otherwise set it to zero or one based on
2387 the warning level. */
2388 if (dir.prec[0] == dir.prec[1])
2389 res.range.likely
2390 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2391 ? dir.prec[0] : slen.range.max);
2392 else if (dir.prec[0] > 0)
2393 res.range.likely = res.range.min;
2394 else
2395 res.range.likely = warn_level > 1;
2397 else if (dir.prec[1] >= 0)
2399 res.range.min = 0;
2400 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2401 res.range.max = dir.prec[1];
2402 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2404 else if (slen.range.min >= target_int_max ())
2406 res.range.min = 0;
2407 res.range.max = HOST_WIDE_INT_MAX;
2408 /* At level 1 strings of unknown length are assumed to be
2409 empty, while at level 1 they are assumed to be one byte
2410 long. */
2411 res.range.likely = warn_level > 1;
2413 else
2415 /* A string of unknown length unconstrained by precision is
2416 assumed to be empty at level 1 and just one character long
2417 at higher levels. */
2418 if (res.range.likely >= target_int_max ())
2419 res.range.likely = warn_level > 1;
2422 res.range.unlikely = res.range.max;
2425 /* Bump up the byte counters if WIDTH is greater. */
2426 return res.adjust_for_width_or_precision (dir.width);
2429 /* Format plain string (part of the format string itself). */
2431 static fmtresult
2432 format_plain (const directive &dir, tree, vr_values *)
2434 fmtresult res (dir.len);
2435 return res;
2438 /* Return true if the RESULT of a directive in a call describe by INFO
2439 should be diagnosed given the AVAILable space in the destination. */
2441 static bool
2442 should_warn_p (const sprintf_dom_walker::call_info &info,
2443 const result_range &avail, const result_range &result)
2445 if (result.max <= avail.min)
2447 /* The least amount of space remaining in the destination is big
2448 enough for the longest output. */
2449 return false;
2452 if (info.bounded)
2454 if (warn_format_trunc == 1 && result.min <= avail.max
2455 && info.retval_used ())
2457 /* The likely amount of space remaining in the destination is big
2458 enough for the least output and the return value is used. */
2459 return false;
2462 if (warn_format_trunc == 1 && result.likely <= avail.likely
2463 && !info.retval_used ())
2465 /* The likely amount of space remaining in the destination is big
2466 enough for the likely output and the return value is unused. */
2467 return false;
2470 if (warn_format_trunc == 2
2471 && result.likely <= avail.min
2472 && (result.max <= avail.min
2473 || result.max > HOST_WIDE_INT_MAX))
2475 /* The minimum amount of space remaining in the destination is big
2476 enough for the longest output. */
2477 return false;
2480 else
2482 if (warn_level == 1 && result.likely <= avail.likely)
2484 /* The likely amount of space remaining in the destination is big
2485 enough for the likely output. */
2486 return false;
2489 if (warn_level == 2
2490 && result.likely <= avail.min
2491 && (result.max <= avail.min
2492 || result.max > HOST_WIDE_INT_MAX))
2494 /* The minimum amount of space remaining in the destination is big
2495 enough for the longest output. */
2496 return false;
2500 return true;
2503 /* At format string location describe by DIRLOC in a call described
2504 by INFO, issue a warning for a directive DIR whose output may be
2505 in excess of the available space AVAIL_RANGE in the destination
2506 given the formatting result FMTRES. This function does nothing
2507 except decide whether to issue a warning for a possible write
2508 past the end or truncation and, if so, format the warning.
2509 Return true if a warning has been issued. */
2511 static bool
2512 maybe_warn (substring_loc &dirloc, location_t argloc,
2513 const sprintf_dom_walker::call_info &info,
2514 const result_range &avail_range, const result_range &res,
2515 const directive &dir)
2517 if (!should_warn_p (info, avail_range, res))
2518 return false;
2520 /* A warning will definitely be issued below. */
2522 /* The maximum byte count to reference in the warning. Larger counts
2523 imply that the upper bound is unknown (and could be anywhere between
2524 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2525 than "between N and X" where X is some huge number. */
2526 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2528 /* True when there is enough room in the destination for the least
2529 amount of a directive's output but not enough for its likely or
2530 maximum output. */
2531 bool maybe = (res.min <= avail_range.max
2532 && (avail_range.min < res.likely
2533 || (res.max < HOST_WIDE_INT_MAX
2534 && avail_range.min < res.max)));
2536 /* Buffer for the directive in the host character set (used when
2537 the source character set is different). */
2538 char hostdir[32];
2540 if (avail_range.min == avail_range.max)
2542 /* The size of the destination region is exact. */
2543 unsigned HOST_WIDE_INT navail = avail_range.max;
2545 if (target_to_host (*dir.beg) != '%')
2547 /* For plain character directives (i.e., the format string itself)
2548 but not others, point the caret at the first character that's
2549 past the end of the destination. */
2550 if (navail < dir.len)
2551 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2554 if (*dir.beg == '\0')
2556 /* This is the terminating nul. */
2557 gcc_assert (res.min == 1 && res.min == res.max);
2559 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2560 info.bounded
2561 ? (maybe
2562 ? G_("%qE output may be truncated before the "
2563 "last format character")
2564 : G_("%qE output truncated before the last "
2565 "format character"))
2566 : (maybe
2567 ? G_("%qE may write a terminating nul past the "
2568 "end of the destination")
2569 : G_("%qE writing a terminating nul past the "
2570 "end of the destination")),
2571 info.func);
2574 if (res.min == res.max)
2576 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2577 if (!info.bounded)
2578 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2579 "%<%.*s%> directive writing %wu byte into a "
2580 "region of size %wu",
2581 "%<%.*s%> directive writing %wu bytes into a "
2582 "region of size %wu",
2583 (int) dir.len, d, res.min, navail);
2584 else if (maybe)
2585 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2586 "%<%.*s%> directive output may be truncated "
2587 "writing %wu byte into a region of size %wu",
2588 "%<%.*s%> directive output may be truncated "
2589 "writing %wu bytes into a region of size %wu",
2590 (int) dir.len, d, res.min, navail);
2591 else
2592 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2593 "%<%.*s%> directive output truncated writing "
2594 "%wu byte into a region of size %wu",
2595 "%<%.*s%> directive output truncated writing "
2596 "%wu bytes into a region of size %wu",
2597 (int) dir.len, d, res.min, navail);
2599 if (res.min == 0 && res.max < maxbytes)
2600 return fmtwarn (dirloc, argloc, NULL,
2601 info.warnopt (),
2602 info.bounded
2603 ? (maybe
2604 ? G_("%<%.*s%> directive output may be truncated "
2605 "writing up to %wu bytes into a region of "
2606 "size %wu")
2607 : G_("%<%.*s%> directive output truncated writing "
2608 "up to %wu bytes into a region of size %wu"))
2609 : G_("%<%.*s%> directive writing up to %wu bytes "
2610 "into a region of size %wu"), (int) dir.len,
2611 target_to_host (hostdir, sizeof hostdir, dir.beg),
2612 res.max, navail);
2614 if (res.min == 0 && maxbytes <= res.max)
2615 /* This is a special case to avoid issuing the potentially
2616 confusing warning:
2617 writing 0 or more bytes into a region of size 0. */
2618 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2619 info.bounded
2620 ? (maybe
2621 ? G_("%<%.*s%> directive output may be truncated "
2622 "writing likely %wu or more bytes into a "
2623 "region of size %wu")
2624 : G_("%<%.*s%> directive output truncated writing "
2625 "likely %wu or more bytes into a region of "
2626 "size %wu"))
2627 : G_("%<%.*s%> directive writing likely %wu or more "
2628 "bytes into a region of size %wu"), (int) dir.len,
2629 target_to_host (hostdir, sizeof hostdir, dir.beg),
2630 res.likely, navail);
2632 if (res.max < maxbytes)
2633 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2634 info.bounded
2635 ? (maybe
2636 ? G_("%<%.*s%> directive output may be truncated "
2637 "writing between %wu and %wu bytes into a "
2638 "region of size %wu")
2639 : G_("%<%.*s%> directive output truncated "
2640 "writing between %wu and %wu bytes into a "
2641 "region of size %wu"))
2642 : G_("%<%.*s%> directive writing between %wu and "
2643 "%wu bytes into a region of size %wu"),
2644 (int) dir.len,
2645 target_to_host (hostdir, sizeof hostdir, dir.beg),
2646 res.min, res.max, navail);
2648 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2649 info.bounded
2650 ? (maybe
2651 ? G_("%<%.*s%> directive output may be truncated "
2652 "writing %wu or more bytes into a region of "
2653 "size %wu")
2654 : G_("%<%.*s%> directive output truncated writing "
2655 "%wu or more bytes into a region of size %wu"))
2656 : G_("%<%.*s%> directive writing %wu or more bytes "
2657 "into a region of size %wu"), (int) dir.len,
2658 target_to_host (hostdir, sizeof hostdir, dir.beg),
2659 res.min, navail);
2662 /* The size of the destination region is a range. */
2664 if (target_to_host (*dir.beg) != '%')
2666 unsigned HOST_WIDE_INT navail = avail_range.max;
2668 /* For plain character directives (i.e., the format string itself)
2669 but not others, point the caret at the first character that's
2670 past the end of the destination. */
2671 if (navail < dir.len)
2672 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2675 if (*dir.beg == '\0')
2677 gcc_assert (res.min == 1 && res.min == res.max);
2679 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2680 info.bounded
2681 ? (maybe
2682 ? G_("%qE output may be truncated before the last "
2683 "format character")
2684 : G_("%qE output truncated before the last format "
2685 "character"))
2686 : (maybe
2687 ? G_("%qE may write a terminating nul past the end "
2688 "of the destination")
2689 : G_("%qE writing a terminating nul past the end "
2690 "of the destination")), info.func);
2693 if (res.min == res.max)
2695 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2696 if (!info.bounded)
2697 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2698 "%<%.*s%> directive writing %wu byte into a region "
2699 "of size between %wu and %wu",
2700 "%<%.*s%> directive writing %wu bytes into a region "
2701 "of size between %wu and %wu", (int) dir.len, d,
2702 res.min, avail_range.min, avail_range.max);
2703 else if (maybe)
2704 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2705 "%<%.*s%> directive output may be truncated writing "
2706 "%wu byte into a region of size between %wu and %wu",
2707 "%<%.*s%> directive output may be truncated writing "
2708 "%wu bytes into a region of size between %wu and "
2709 "%wu", (int) dir.len, d, res.min, avail_range.min,
2710 avail_range.max);
2711 else
2712 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2713 "%<%.*s%> directive output truncated writing %wu "
2714 "byte into a region of size between %wu and %wu",
2715 "%<%.*s%> directive output truncated writing %wu "
2716 "bytes into a region of size between %wu and %wu",
2717 (int) dir.len, d, res.min, avail_range.min,
2718 avail_range.max);
2721 if (res.min == 0 && res.max < maxbytes)
2722 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2723 info.bounded
2724 ? (maybe
2725 ? G_("%<%.*s%> directive output may be truncated "
2726 "writing up to %wu bytes into a region of size "
2727 "between %wu and %wu")
2728 : G_("%<%.*s%> directive output truncated writing "
2729 "up to %wu bytes into a region of size between "
2730 "%wu and %wu"))
2731 : G_("%<%.*s%> directive writing up to %wu bytes "
2732 "into a region of size between %wu and %wu"),
2733 (int) dir.len,
2734 target_to_host (hostdir, sizeof hostdir, dir.beg),
2735 res.max, avail_range.min, avail_range.max);
2737 if (res.min == 0 && maxbytes <= res.max)
2738 /* This is a special case to avoid issuing the potentially confusing
2739 warning:
2740 writing 0 or more bytes into a region of size between 0 and N. */
2741 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2742 info.bounded
2743 ? (maybe
2744 ? G_("%<%.*s%> directive output may be truncated "
2745 "writing likely %wu or more bytes into a region "
2746 "of size between %wu and %wu")
2747 : G_("%<%.*s%> directive output truncated writing "
2748 "likely %wu or more bytes into a region of size "
2749 "between %wu and %wu"))
2750 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2751 "into a region of size between %wu and %wu"),
2752 (int) dir.len,
2753 target_to_host (hostdir, sizeof hostdir, dir.beg),
2754 res.likely, avail_range.min, avail_range.max);
2756 if (res.max < maxbytes)
2757 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2758 info.bounded
2759 ? (maybe
2760 ? G_("%<%.*s%> directive output may be truncated "
2761 "writing between %wu and %wu bytes into a region "
2762 "of size between %wu and %wu")
2763 : G_("%<%.*s%> directive output truncated writing "
2764 "between %wu and %wu bytes into a region of size "
2765 "between %wu and %wu"))
2766 : G_("%<%.*s%> directive writing between %wu and "
2767 "%wu bytes into a region of size between %wu and "
2768 "%wu"), (int) dir.len,
2769 target_to_host (hostdir, sizeof hostdir, dir.beg),
2770 res.min, res.max, avail_range.min, avail_range.max);
2772 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2773 info.bounded
2774 ? (maybe
2775 ? G_("%<%.*s%> directive output may be truncated writing "
2776 "%wu or more bytes into a region of size between "
2777 "%wu and %wu")
2778 : G_("%<%.*s%> directive output truncated writing "
2779 "%wu or more bytes into a region of size between "
2780 "%wu and %wu"))
2781 : G_("%<%.*s%> directive writing %wu or more bytes "
2782 "into a region of size between %wu and %wu"),
2783 (int) dir.len,
2784 target_to_host (hostdir, sizeof hostdir, dir.beg),
2785 res.min, avail_range.min, avail_range.max);
2788 /* Compute the length of the output resulting from the directive DIR
2789 in a call described by INFO and update the overall result of the call
2790 in *RES. Return true if the directive has been handled. */
2792 static bool
2793 format_directive (const sprintf_dom_walker::call_info &info,
2794 format_result *res, const directive &dir,
2795 class vr_values *vr_values)
2797 /* Offset of the beginning of the directive from the beginning
2798 of the format string. */
2799 size_t offset = dir.beg - info.fmtstr;
2800 size_t start = offset;
2801 size_t length = offset + dir.len - !!dir.len;
2803 /* Create a location for the whole directive from the % to the format
2804 specifier. */
2805 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2806 offset, start, length);
2808 /* Also get the location of the argument if possible.
2809 This doesn't work for integer literals or function calls. */
2810 location_t argloc = UNKNOWN_LOCATION;
2811 if (dir.arg)
2812 argloc = EXPR_LOCATION (dir.arg);
2814 /* Bail when there is no function to compute the output length,
2815 or when minimum length checking has been disabled. */
2816 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2817 return false;
2819 /* Compute the range of lengths of the formatted output. */
2820 fmtresult fmtres = dir.fmtfunc (dir, dir.arg, vr_values);
2822 /* Record whether the output of all directives is known to be
2823 bounded by some maximum, implying that their arguments are
2824 either known exactly or determined to be in a known range
2825 or, for strings, limited by the upper bounds of the arrays
2826 they refer to. */
2827 res->knownrange &= fmtres.knownrange;
2829 if (!fmtres.knownrange)
2831 /* Only when the range is known, check it against the host value
2832 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2833 INT_MAX precision, which is the longest possible output of any
2834 single directive). That's the largest valid byte count (though
2835 not valid call to a printf-like function because it can never
2836 return such a count). Otherwise, the range doesn't correspond
2837 to known values of the argument. */
2838 if (fmtres.range.max > target_dir_max ())
2840 /* Normalize the MAX counter to avoid having to deal with it
2841 later. The counter can be less than HOST_WIDE_INT_M1U
2842 when compiling for an ILP32 target on an LP64 host. */
2843 fmtres.range.max = HOST_WIDE_INT_M1U;
2844 /* Disable exact and maximum length checking after a failure
2845 to determine the maximum number of characters (for example
2846 for wide characters or wide character strings) but continue
2847 tracking the minimum number of characters. */
2848 res->range.max = HOST_WIDE_INT_M1U;
2851 if (fmtres.range.min > target_dir_max ())
2853 /* Disable exact length checking after a failure to determine
2854 even the minimum number of characters (it shouldn't happen
2855 except in an error) but keep tracking the minimum and maximum
2856 number of characters. */
2857 return true;
2861 /* Buffer for the directive in the host character set (used when
2862 the source character set is different). */
2863 char hostdir[32];
2865 int dirlen = dir.len;
2867 if (fmtres.nullp)
2869 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2870 "%<%.*s%> directive argument is null",
2871 dirlen, target_to_host (hostdir, sizeof hostdir, dir.beg));
2873 /* Don't bother processing the rest of the format string. */
2874 res->warned = true;
2875 res->range.min = HOST_WIDE_INT_M1U;
2876 res->range.max = HOST_WIDE_INT_M1U;
2877 return false;
2880 /* Compute the number of available bytes in the destination. There
2881 must always be at least one byte of space for the terminating
2882 NUL that's appended after the format string has been processed. */
2883 result_range avail_range = bytes_remaining (info.objsize, *res);
2885 bool warned = res->warned;
2887 if (!warned)
2888 warned = maybe_warn (dirloc, argloc, info, avail_range,
2889 fmtres.range, dir);
2891 /* Bump up the total maximum if it isn't too big. */
2892 if (res->range.max < HOST_WIDE_INT_MAX
2893 && fmtres.range.max < HOST_WIDE_INT_MAX)
2894 res->range.max += fmtres.range.max;
2896 /* Raise the total unlikely maximum by the larger of the maximum
2897 and the unlikely maximum. */
2898 unsigned HOST_WIDE_INT save = res->range.unlikely;
2899 if (fmtres.range.max < fmtres.range.unlikely)
2900 res->range.unlikely += fmtres.range.unlikely;
2901 else
2902 res->range.unlikely += fmtres.range.max;
2904 if (res->range.unlikely < save)
2905 res->range.unlikely = HOST_WIDE_INT_M1U;
2907 res->range.min += fmtres.range.min;
2908 res->range.likely += fmtres.range.likely;
2910 /* Has the minimum directive output length exceeded the maximum
2911 of 4095 bytes required to be supported? */
2912 bool minunder4k = fmtres.range.min < 4096;
2913 bool maxunder4k = fmtres.range.max < 4096;
2914 /* Clear UNDER4K in the overall result if the maximum has exceeded
2915 the 4k (this is necessary to avoid the return valuye optimization
2916 that may not be safe in the maximum case). */
2917 if (!maxunder4k)
2918 res->under4k = false;
2920 if (!warned
2921 /* Only warn at level 2. */
2922 && warn_level > 1
2923 && (!minunder4k
2924 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2926 /* The directive output may be longer than the maximum required
2927 to be handled by an implementation according to 7.21.6.1, p15
2928 of C11. Warn on this only at level 2 but remember this and
2929 prevent folding the return value when done. This allows for
2930 the possibility of the actual libc call failing due to ENOMEM
2931 (like Glibc does under some conditions). */
2933 if (fmtres.range.min == fmtres.range.max)
2934 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2935 "%<%.*s%> directive output of %wu bytes exceeds "
2936 "minimum required size of 4095", dirlen,
2937 target_to_host (hostdir, sizeof hostdir, dir.beg),
2938 fmtres.range.min);
2939 else
2940 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2941 minunder4k
2942 ? G_("%<%.*s%> directive output between %wu and %wu "
2943 "bytes may exceed minimum required size of "
2944 "4095")
2945 : G_("%<%.*s%> directive output between %wu and %wu "
2946 "bytes exceeds minimum required size of 4095"),
2947 dirlen,
2948 target_to_host (hostdir, sizeof hostdir, dir.beg),
2949 fmtres.range.min, fmtres.range.max);
2952 /* Has the likely and maximum directive output exceeded INT_MAX? */
2953 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2954 /* Don't consider the maximum to be in excess when it's the result
2955 of a string of unknown length (i.e., whose maximum has been set
2956 to be greater than or equal to HOST_WIDE_INT_MAX. */
2957 bool maxximax = (*dir.beg
2958 && res->range.max > target_int_max ()
2959 && res->range.max < HOST_WIDE_INT_MAX);
2961 if (!warned
2962 /* Warn for the likely output size at level 1. */
2963 && (likelyximax
2964 /* But only warn for the maximum at level 2. */
2965 || (warn_level > 1
2966 && maxximax
2967 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2969 /* The directive output causes the total length of output
2970 to exceed INT_MAX bytes. */
2972 if (fmtres.range.min == fmtres.range.max)
2973 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2974 "%<%.*s%> directive output of %wu bytes causes "
2975 "result to exceed %<INT_MAX%>", dirlen,
2976 target_to_host (hostdir, sizeof hostdir, dir.beg),
2977 fmtres.range.min);
2978 else
2979 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2980 fmtres.range.min > target_int_max ()
2981 ? G_("%<%.*s%> directive output between %wu and "
2982 "%wu bytes causes result to exceed "
2983 "%<INT_MAX%>")
2984 : G_("%<%.*s%> directive output between %wu and "
2985 "%wu bytes may cause result to exceed "
2986 "%<INT_MAX%>"), dirlen,
2987 target_to_host (hostdir, sizeof hostdir, dir.beg),
2988 fmtres.range.min, fmtres.range.max);
2991 if (warned && fmtres.range.min < fmtres.range.likely
2992 && fmtres.range.likely < fmtres.range.max)
2993 inform_n (info.fmtloc, fmtres.range.likely,
2994 "assuming directive output of %wu byte",
2995 "assuming directive output of %wu bytes",
2996 fmtres.range.likely);
2998 if (warned && fmtres.argmin)
3000 if (fmtres.argmin == fmtres.argmax)
3001 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
3002 else if (fmtres.knownrange)
3003 inform (info.fmtloc, "directive argument in the range [%E, %E]",
3004 fmtres.argmin, fmtres.argmax);
3005 else
3006 inform (info.fmtloc,
3007 "using the range [%E, %E] for directive argument",
3008 fmtres.argmin, fmtres.argmax);
3011 res->warned |= warned;
3013 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
3015 /* If a warning has been issued for buffer overflow or truncation
3016 (but not otherwise) help the user figure out how big a buffer
3017 they need. */
3019 location_t callloc = gimple_location (info.callstmt);
3021 unsigned HOST_WIDE_INT min = res->range.min;
3022 unsigned HOST_WIDE_INT max = res->range.max;
3024 if (min == max)
3025 inform (callloc,
3026 (min == 1
3027 ? G_("%qE output %wu byte into a destination of size %wu")
3028 : G_("%qE output %wu bytes into a destination of size %wu")),
3029 info.func, min, info.objsize);
3030 else if (max < HOST_WIDE_INT_MAX)
3031 inform (callloc,
3032 "%qE output between %wu and %wu bytes into "
3033 "a destination of size %wu",
3034 info.func, min, max, info.objsize);
3035 else if (min < res->range.likely && res->range.likely < max)
3036 inform (callloc,
3037 "%qE output %wu or more bytes (assuming %wu) into "
3038 "a destination of size %wu",
3039 info.func, min, res->range.likely, info.objsize);
3040 else
3041 inform (callloc,
3042 "%qE output %wu or more bytes into a destination of size %wu",
3043 info.func, min, info.objsize);
3046 if (dump_file && *dir.beg)
3048 fprintf (dump_file,
3049 " Result: "
3050 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3051 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
3052 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3053 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
3054 fmtres.range.min, fmtres.range.likely,
3055 fmtres.range.max, fmtres.range.unlikely,
3056 res->range.min, res->range.likely,
3057 res->range.max, res->range.unlikely);
3060 return true;
3063 /* Parse a format directive in function call described by INFO starting
3064 at STR and populate DIR structure. Bump up *ARGNO by the number of
3065 arguments extracted for the directive. Return the length of
3066 the directive. */
3068 static size_t
3069 parse_directive (sprintf_dom_walker::call_info &info,
3070 directive &dir, format_result *res,
3071 const char *str, unsigned *argno,
3072 vr_values *vr_values)
3074 const char *pcnt = strchr (str, target_percent);
3075 dir.beg = str;
3077 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
3079 /* This directive is either a plain string or the terminating nul
3080 (which isn't really a directive but it simplifies things to
3081 handle it as if it were). */
3082 dir.len = len;
3083 dir.fmtfunc = format_plain;
3085 if (dump_file)
3087 fprintf (dump_file, " Directive %u at offset "
3088 HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
3089 "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
3090 dir.dirno,
3091 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3092 (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
3095 return len - !*str;
3098 const char *pf = pcnt + 1;
3100 /* POSIX numbered argument index or zero when none. */
3101 HOST_WIDE_INT dollar = 0;
3103 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3104 when given by a va_list argument, and a non-negative value
3105 when specified in the format string itself. */
3106 HOST_WIDE_INT width = -1;
3107 HOST_WIDE_INT precision = -1;
3109 /* Pointers to the beginning of the width and precision decimal
3110 string (if any) within the directive. */
3111 const char *pwidth = 0;
3112 const char *pprec = 0;
3114 /* When the value of the decimal string that specifies width or
3115 precision is out of range, points to the digit that causes
3116 the value to exceed the limit. */
3117 const char *werange = NULL;
3118 const char *perange = NULL;
3120 /* Width specified via the asterisk. Need not be INTEGER_CST.
3121 For vararg functions set to void_node. */
3122 tree star_width = NULL_TREE;
3124 /* Width specified via the asterisk. Need not be INTEGER_CST.
3125 For vararg functions set to void_node. */
3126 tree star_precision = NULL_TREE;
3128 if (ISDIGIT (target_to_host (*pf)))
3130 /* This could be either a POSIX positional argument, the '0'
3131 flag, or a width, depending on what follows. Store it as
3132 width and sort it out later after the next character has
3133 been seen. */
3134 pwidth = pf;
3135 width = target_strtol10 (&pf, &werange);
3137 else if (target_to_host (*pf) == '*')
3139 /* Similarly to the block above, this could be either a POSIX
3140 positional argument or a width, depending on what follows. */
3141 if (*argno < gimple_call_num_args (info.callstmt))
3142 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3143 else
3144 star_width = void_node;
3145 ++pf;
3148 if (target_to_host (*pf) == '$')
3150 /* Handle the POSIX dollar sign which references the 1-based
3151 positional argument number. */
3152 if (width != -1)
3153 dollar = width + info.argidx;
3154 else if (star_width
3155 && TREE_CODE (star_width) == INTEGER_CST
3156 && (TYPE_PRECISION (TREE_TYPE (star_width))
3157 <= TYPE_PRECISION (integer_type_node)))
3158 dollar = width + tree_to_shwi (star_width);
3160 /* Bail when the numbered argument is out of range (it will
3161 have already been diagnosed by -Wformat). */
3162 if (dollar == 0
3163 || dollar == (int)info.argidx
3164 || dollar > gimple_call_num_args (info.callstmt))
3165 return false;
3167 --dollar;
3169 star_width = NULL_TREE;
3170 width = -1;
3171 ++pf;
3174 if (dollar || !star_width)
3176 if (width != -1)
3178 if (width == 0)
3180 /* The '0' that has been interpreted as a width above is
3181 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3182 and continue processing other flags. */
3183 width = -1;
3184 dir.set_flag ('0');
3186 else if (!dollar)
3188 /* (Non-zero) width has been seen. The next character
3189 is either a period or a digit. */
3190 goto start_precision;
3193 /* When either '$' has been seen, or width has not been seen,
3194 the next field is the optional flags followed by an optional
3195 width. */
3196 for ( ; ; ) {
3197 switch (target_to_host (*pf))
3199 case ' ':
3200 case '0':
3201 case '+':
3202 case '-':
3203 case '#':
3204 dir.set_flag (target_to_host (*pf++));
3205 break;
3207 default:
3208 goto start_width;
3212 start_width:
3213 if (ISDIGIT (target_to_host (*pf)))
3215 werange = 0;
3216 pwidth = pf;
3217 width = target_strtol10 (&pf, &werange);
3219 else if (target_to_host (*pf) == '*')
3221 if (*argno < gimple_call_num_args (info.callstmt))
3222 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3223 else
3225 /* This is (likely) a va_list. It could also be an invalid
3226 call with insufficient arguments. */
3227 star_width = void_node;
3229 ++pf;
3231 else if (target_to_host (*pf) == '\'')
3233 /* The POSIX apostrophe indicating a numeric grouping
3234 in the current locale. Even though it's possible to
3235 estimate the upper bound on the size of the output
3236 based on the number of digits it probably isn't worth
3237 continuing. */
3238 return 0;
3242 start_precision:
3243 if (target_to_host (*pf) == '.')
3245 ++pf;
3247 if (ISDIGIT (target_to_host (*pf)))
3249 pprec = pf;
3250 precision = target_strtol10 (&pf, &perange);
3252 else if (target_to_host (*pf) == '*')
3254 if (*argno < gimple_call_num_args (info.callstmt))
3255 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3256 else
3258 /* This is (likely) a va_list. It could also be an invalid
3259 call with insufficient arguments. */
3260 star_precision = void_node;
3262 ++pf;
3264 else
3266 /* The decimal precision or the asterisk are optional.
3267 When neither is dirified it's taken to be zero. */
3268 precision = 0;
3272 switch (target_to_host (*pf))
3274 case 'h':
3275 if (target_to_host (pf[1]) == 'h')
3277 ++pf;
3278 dir.modifier = FMT_LEN_hh;
3280 else
3281 dir.modifier = FMT_LEN_h;
3282 ++pf;
3283 break;
3285 case 'j':
3286 dir.modifier = FMT_LEN_j;
3287 ++pf;
3288 break;
3290 case 'L':
3291 dir.modifier = FMT_LEN_L;
3292 ++pf;
3293 break;
3295 case 'l':
3296 if (target_to_host (pf[1]) == 'l')
3298 ++pf;
3299 dir.modifier = FMT_LEN_ll;
3301 else
3302 dir.modifier = FMT_LEN_l;
3303 ++pf;
3304 break;
3306 case 't':
3307 dir.modifier = FMT_LEN_t;
3308 ++pf;
3309 break;
3311 case 'z':
3312 dir.modifier = FMT_LEN_z;
3313 ++pf;
3314 break;
3317 switch (target_to_host (*pf))
3319 /* Handle a sole '%' character the same as "%%" but since it's
3320 undefined prevent the result from being folded. */
3321 case '\0':
3322 --pf;
3323 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3324 /* FALLTHRU */
3325 case '%':
3326 dir.fmtfunc = format_percent;
3327 break;
3329 case 'a':
3330 case 'A':
3331 case 'e':
3332 case 'E':
3333 case 'f':
3334 case 'F':
3335 case 'g':
3336 case 'G':
3337 res->floating = true;
3338 dir.fmtfunc = format_floating;
3339 break;
3341 case 'd':
3342 case 'i':
3343 case 'o':
3344 case 'u':
3345 case 'x':
3346 case 'X':
3347 dir.fmtfunc = format_integer;
3348 break;
3350 case 'p':
3351 /* The %p output is implementation-defined. It's possible
3352 to determine this format but due to extensions (edirially
3353 those of the Linux kernel -- see bug 78512) the first %p
3354 in the format string disables any further processing. */
3355 return false;
3357 case 'n':
3358 /* %n has side-effects even when nothing is actually printed to
3359 any buffer. */
3360 info.nowrite = false;
3361 dir.fmtfunc = format_none;
3362 break;
3364 case 'c':
3365 dir.fmtfunc = format_character;
3366 break;
3368 case 'S':
3369 case 's':
3370 dir.fmtfunc = format_string;
3371 break;
3373 default:
3374 /* Unknown conversion specification. */
3375 return 0;
3378 dir.specifier = target_to_host (*pf++);
3380 /* Store the length of the format directive. */
3381 dir.len = pf - pcnt;
3383 /* Buffer for the directive in the host character set (used when
3384 the source character set is different). */
3385 char hostdir[32];
3387 if (star_width)
3389 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3390 dir.set_width (star_width, vr_values);
3391 else
3393 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3394 (width is the absolute value of that specified). */
3395 dir.width[0] = 0;
3396 dir.width[1] = target_int_max () + 1;
3399 else
3401 if (width == LONG_MAX && werange)
3403 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3404 size_t caret = begin + (werange - pcnt);
3405 size_t end = pf - info.fmtstr - 1;
3407 /* Create a location for the width part of the directive,
3408 pointing the caret at the first out-of-range digit. */
3409 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3410 caret, begin, end);
3412 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3413 "%<%.*s%> directive width out of range", (int) dir.len,
3414 target_to_host (hostdir, sizeof hostdir, dir.beg));
3417 dir.set_width (width);
3420 if (star_precision)
3422 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3423 dir.set_precision (star_precision, vr_values);
3424 else
3426 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3427 (unlike width, negative precision is ignored). */
3428 dir.prec[0] = -1;
3429 dir.prec[1] = target_int_max ();
3432 else
3434 if (precision == LONG_MAX && perange)
3436 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3437 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3438 size_t end = pf - info.fmtstr - 2;
3440 /* Create a location for the precision part of the directive,
3441 including the leading period, pointing the caret at the first
3442 out-of-range digit . */
3443 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3444 caret, begin, end);
3446 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3447 "%<%.*s%> directive precision out of range", (int) dir.len,
3448 target_to_host (hostdir, sizeof hostdir, dir.beg));
3451 dir.set_precision (precision);
3454 /* Extract the argument if the directive takes one and if it's
3455 available (e.g., the function doesn't take a va_list). Treat
3456 missing arguments the same as va_list, even though they will
3457 have likely already been diagnosed by -Wformat. */
3458 if (dir.specifier != '%'
3459 && *argno < gimple_call_num_args (info.callstmt))
3460 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3462 if (dump_file)
3464 fprintf (dump_file,
3465 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3466 ": \"%.*s\"",
3467 dir.dirno,
3468 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3469 (int)dir.len, dir.beg);
3470 if (star_width)
3472 if (dir.width[0] == dir.width[1])
3473 fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
3474 dir.width[0]);
3475 else
3476 fprintf (dump_file,
3477 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3478 ", " HOST_WIDE_INT_PRINT_DEC "]",
3479 dir.width[0], dir.width[1]);
3482 if (star_precision)
3484 if (dir.prec[0] == dir.prec[1])
3485 fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
3486 dir.prec[0]);
3487 else
3488 fprintf (dump_file,
3489 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3490 HOST_WIDE_INT_PRINT_DEC "]",
3491 dir.prec[0], dir.prec[1]);
3493 fputc ('\n', dump_file);
3496 return dir.len;
3499 /* Compute the length of the output resulting from the call to a formatted
3500 output function described by INFO and store the result of the call in
3501 *RES. Issue warnings for detected past the end writes. Return true
3502 if the complete format string has been processed and *RES can be relied
3503 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3504 that caused the processing to be terminated early). */
3506 bool
3507 sprintf_dom_walker::compute_format_length (call_info &info,
3508 format_result *res)
3510 if (dump_file)
3512 location_t callloc = gimple_location (info.callstmt);
3513 fprintf (dump_file, "%s:%i: ",
3514 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3515 print_generic_expr (dump_file, info.func, dump_flags);
3517 fprintf (dump_file,
3518 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3519 ", fmtstr = \"%s\"\n",
3520 info.objsize, info.fmtstr);
3523 /* Reset the minimum and maximum byte counters. */
3524 res->range.min = res->range.max = 0;
3526 /* No directive has been seen yet so the length of output is bounded
3527 by the known range [0, 0] (with no conversion producing more than
3528 4K bytes) until determined otherwise. */
3529 res->knownrange = true;
3530 res->under4k = true;
3531 res->floating = false;
3532 res->warned = false;
3534 /* 1-based directive counter. */
3535 unsigned dirno = 1;
3537 /* The variadic argument counter. */
3538 unsigned argno = info.argidx;
3540 for (const char *pf = info.fmtstr; ; ++dirno)
3542 directive dir = directive ();
3543 dir.dirno = dirno;
3545 size_t n = parse_directive (info, dir, res, pf, &argno,
3546 evrp_range_analyzer.get_vr_values ());
3548 /* Return failure if the format function fails. */
3549 if (!format_directive (info, res, dir,
3550 evrp_range_analyzer.get_vr_values ()))
3551 return false;
3553 /* Return success the directive is zero bytes long and it's
3554 the last think in the format string (i.e., it's the terminating
3555 nul, which isn't really a directive but handling it as one makes
3556 things simpler). */
3557 if (!n)
3558 return *pf == '\0';
3560 pf += n;
3563 /* The complete format string was processed (with or without warnings). */
3564 return true;
3567 /* Return the size of the object referenced by the expression DEST if
3568 available, or -1 otherwise. */
3570 static unsigned HOST_WIDE_INT
3571 get_destination_size (tree dest)
3573 /* Initialize object size info before trying to compute it. */
3574 init_object_sizes ();
3576 /* Use __builtin_object_size to determine the size of the destination
3577 object. When optimizing, determine the smallest object (such as
3578 a member array as opposed to the whole enclosing object), otherwise
3579 use type-zero object size to determine the size of the enclosing
3580 object (the function fails without optimization in this type). */
3581 int ost = optimize > 0;
3582 unsigned HOST_WIDE_INT size;
3583 if (compute_builtin_object_size (dest, ost, &size))
3584 return size;
3586 return HOST_WIDE_INT_M1U;
3589 /* Return true if the call described by INFO with result RES safe to
3590 optimize (i.e., no undefined behavior), and set RETVAL to the range
3591 of its return values. */
3593 static bool
3594 is_call_safe (const sprintf_dom_walker::call_info &info,
3595 const format_result &res, bool under4k,
3596 unsigned HOST_WIDE_INT retval[2])
3598 if (under4k && !res.under4k)
3599 return false;
3601 /* The minimum return value. */
3602 retval[0] = res.range.min;
3604 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3605 but in cases involving multibyte characters could be as large as
3606 RES.RANGE.UNLIKELY. */
3607 retval[1]
3608 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3610 /* Adjust the number of bytes which includes the terminating nul
3611 to reflect the return value of the function which does not.
3612 Because the valid range of the function is [INT_MIN, INT_MAX],
3613 a valid range before the adjustment below is [0, INT_MAX + 1]
3614 (the functions only return negative values on error or undefined
3615 behavior). */
3616 if (retval[0] <= target_int_max () + 1)
3617 --retval[0];
3618 if (retval[1] <= target_int_max () + 1)
3619 --retval[1];
3621 /* Avoid the return value optimization when the behavior of the call
3622 is undefined either because any directive may have produced 4K or
3623 more of output, or the return value exceeds INT_MAX, or because
3624 the output overflows the destination object (but leave it enabled
3625 when the function is bounded because then the behavior is well-
3626 defined). */
3627 if (retval[0] == retval[1]
3628 && (info.bounded || retval[0] < info.objsize)
3629 && retval[0] <= target_int_max ())
3630 return true;
3632 if ((info.bounded || retval[1] < info.objsize)
3633 && (retval[0] < target_int_max ()
3634 && retval[1] < target_int_max ()))
3635 return true;
3637 if (!under4k && (info.bounded || retval[0] < info.objsize))
3638 return true;
3640 return false;
3643 /* Given a suitable result RES of a call to a formatted output function
3644 described by INFO, substitute the result for the return value of
3645 the call. The result is suitable if the number of bytes it represents
3646 is known and exact. A result that isn't suitable for substitution may
3647 have its range set to the range of return values, if that is known.
3648 Return true if the call is removed and gsi_next should not be performed
3649 in the caller. */
3651 static bool
3652 try_substitute_return_value (gimple_stmt_iterator *gsi,
3653 const sprintf_dom_walker::call_info &info,
3654 const format_result &res)
3656 tree lhs = gimple_get_lhs (info.callstmt);
3658 /* Set to true when the entire call has been removed. */
3659 bool removed = false;
3661 /* The minimum and maximum return value. */
3662 unsigned HOST_WIDE_INT retval[2];
3663 bool safe = is_call_safe (info, res, true, retval);
3665 if (safe
3666 && retval[0] == retval[1]
3667 /* Not prepared to handle possibly throwing calls here; they shouldn't
3668 appear in non-artificial testcases, except when the __*_chk routines
3669 are badly declared. */
3670 && !stmt_ends_bb_p (info.callstmt))
3672 tree cst = build_int_cst (integer_type_node, retval[0]);
3674 if (lhs == NULL_TREE
3675 && info.nowrite)
3677 /* Remove the call to the bounded function with a zero size
3678 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3679 unlink_stmt_vdef (info.callstmt);
3680 gsi_remove (gsi, true);
3681 removed = true;
3683 else if (info.nowrite)
3685 /* Replace the call to the bounded function with a zero size
3686 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3687 of the function. */
3688 if (!update_call_from_tree (gsi, cst))
3689 gimplify_and_update_call_from_tree (gsi, cst);
3690 gimple *callstmt = gsi_stmt (*gsi);
3691 update_stmt (callstmt);
3693 else if (lhs)
3695 /* Replace the left-hand side of the call with the constant
3696 result of the formatted function. */
3697 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3698 gimple *g = gimple_build_assign (lhs, cst);
3699 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3700 update_stmt (info.callstmt);
3703 if (dump_file)
3705 if (removed)
3706 fprintf (dump_file, " Removing call statement.");
3707 else
3709 fprintf (dump_file, " Substituting ");
3710 print_generic_expr (dump_file, cst, dump_flags);
3711 fprintf (dump_file, " for %s.\n",
3712 info.nowrite ? "statement" : "return value");
3716 else if (lhs)
3718 bool setrange = false;
3720 if (safe
3721 && (info.bounded || retval[1] < info.objsize)
3722 && (retval[0] < target_int_max ()
3723 && retval[1] < target_int_max ()))
3725 /* If the result is in a valid range bounded by the size of
3726 the destination set it so that it can be used for subsequent
3727 optimizations. */
3728 int prec = TYPE_PRECISION (integer_type_node);
3730 wide_int min = wi::shwi (retval[0], prec);
3731 wide_int max = wi::shwi (retval[1], prec);
3732 set_range_info (lhs, VR_RANGE, min, max);
3734 setrange = true;
3737 if (dump_file)
3739 const char *inbounds
3740 = (retval[0] < info.objsize
3741 ? (retval[1] < info.objsize
3742 ? "in" : "potentially out-of")
3743 : "out-of");
3745 const char *what = setrange ? "Setting" : "Discarding";
3746 if (retval[0] != retval[1])
3747 fprintf (dump_file,
3748 " %s %s-bounds return value range ["
3749 HOST_WIDE_INT_PRINT_UNSIGNED ", "
3750 HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
3751 what, inbounds, retval[0], retval[1]);
3752 else
3753 fprintf (dump_file, " %s %s-bounds return value "
3754 HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
3755 what, inbounds, retval[0]);
3759 if (dump_file)
3760 fputc ('\n', dump_file);
3762 return removed;
3765 /* Try to simplify a s{,n}printf call described by INFO with result
3766 RES by replacing it with a simpler and presumably more efficient
3767 call (such as strcpy). */
3769 static bool
3770 try_simplify_call (gimple_stmt_iterator *gsi,
3771 const sprintf_dom_walker::call_info &info,
3772 const format_result &res)
3774 unsigned HOST_WIDE_INT dummy[2];
3775 if (!is_call_safe (info, res, info.retval_used (), dummy))
3776 return false;
3778 switch (info.fncode)
3780 case BUILT_IN_SNPRINTF:
3781 return gimple_fold_builtin_snprintf (gsi);
3783 case BUILT_IN_SPRINTF:
3784 return gimple_fold_builtin_sprintf (gsi);
3786 default:
3790 return false;
3793 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3794 functions and if so, handle it. Return true if the call is removed
3795 and gsi_next should not be performed in the caller. */
3797 bool
3798 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3800 call_info info = call_info ();
3802 info.callstmt = gsi_stmt (*gsi);
3803 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3804 return false;
3806 info.func = gimple_call_fndecl (info.callstmt);
3807 info.fncode = DECL_FUNCTION_CODE (info.func);
3809 /* The size of the destination as in snprintf(dest, size, ...). */
3810 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3812 /* The size of the destination determined by __builtin_object_size. */
3813 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3815 /* Buffer size argument number (snprintf and vsnprintf). */
3816 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3818 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3819 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3821 /* Format string argument number (valid for all functions). */
3822 unsigned idx_format;
3824 switch (info.fncode)
3826 case BUILT_IN_SPRINTF:
3827 // Signature:
3828 // __builtin_sprintf (dst, format, ...)
3829 idx_format = 1;
3830 info.argidx = 2;
3831 break;
3833 case BUILT_IN_SPRINTF_CHK:
3834 // Signature:
3835 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3836 idx_objsize = 2;
3837 idx_format = 3;
3838 info.argidx = 4;
3839 break;
3841 case BUILT_IN_SNPRINTF:
3842 // Signature:
3843 // __builtin_snprintf (dst, size, format, ...)
3844 idx_dstsize = 1;
3845 idx_format = 2;
3846 info.argidx = 3;
3847 info.bounded = true;
3848 break;
3850 case BUILT_IN_SNPRINTF_CHK:
3851 // Signature:
3852 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3853 idx_dstsize = 1;
3854 idx_objsize = 3;
3855 idx_format = 4;
3856 info.argidx = 5;
3857 info.bounded = true;
3858 break;
3860 case BUILT_IN_VSNPRINTF:
3861 // Signature:
3862 // __builtin_vsprintf (dst, size, format, va)
3863 idx_dstsize = 1;
3864 idx_format = 2;
3865 info.argidx = -1;
3866 info.bounded = true;
3867 break;
3869 case BUILT_IN_VSNPRINTF_CHK:
3870 // Signature:
3871 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3872 idx_dstsize = 1;
3873 idx_objsize = 3;
3874 idx_format = 4;
3875 info.argidx = -1;
3876 info.bounded = true;
3877 break;
3879 case BUILT_IN_VSPRINTF:
3880 // Signature:
3881 // __builtin_vsprintf (dst, format, va)
3882 idx_format = 1;
3883 info.argidx = -1;
3884 break;
3886 case BUILT_IN_VSPRINTF_CHK:
3887 // Signature:
3888 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3889 idx_format = 3;
3890 idx_objsize = 2;
3891 info.argidx = -1;
3892 break;
3894 default:
3895 return false;
3898 /* Set the global warning level for this function. */
3899 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3901 /* The first argument is a pointer to the destination. */
3902 tree dstptr = gimple_call_arg (info.callstmt, 0);
3904 info.format = gimple_call_arg (info.callstmt, idx_format);
3906 /* True when the destination size is constant as opposed to the lower
3907 or upper bound of a range. */
3908 bool dstsize_cst_p = true;
3910 if (idx_dstsize == HOST_WIDE_INT_M1U)
3912 /* For non-bounded functions like sprintf, determine the size
3913 of the destination from the object or pointer passed to it
3914 as the first argument. */
3915 dstsize = get_destination_size (dstptr);
3917 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3919 /* For bounded functions try to get the size argument. */
3921 if (TREE_CODE (size) == INTEGER_CST)
3923 dstsize = tree_to_uhwi (size);
3924 /* No object can be larger than SIZE_MAX bytes (half the address
3925 space) on the target.
3926 The functions are defined only for output of at most INT_MAX
3927 bytes. Specifying a bound in excess of that limit effectively
3928 defeats the bounds checking (and on some implementations such
3929 as Solaris cause the function to fail with EINVAL). */
3930 if (dstsize > target_size_max () / 2)
3932 /* Avoid warning if -Wstringop-overflow is specified since
3933 it also warns for the same thing though only for the
3934 checking built-ins. */
3935 if ((idx_objsize == HOST_WIDE_INT_M1U
3936 || !warn_stringop_overflow))
3937 warning_at (gimple_location (info.callstmt), info.warnopt (),
3938 "specified bound %wu exceeds maximum object size "
3939 "%wu",
3940 dstsize, target_size_max () / 2);
3942 else if (dstsize > target_int_max ())
3943 warning_at (gimple_location (info.callstmt), info.warnopt (),
3944 "specified bound %wu exceeds %<INT_MAX%>",
3945 dstsize);
3947 else if (TREE_CODE (size) == SSA_NAME)
3949 /* Try to determine the range of values of the argument
3950 and use the greater of the two at level 1 and the smaller
3951 of them at level 2. */
3952 value_range *vr = evrp_range_analyzer.get_value_range (size);
3953 if (vr->type == VR_RANGE
3954 && TREE_CODE (vr->min) == INTEGER_CST
3955 && TREE_CODE (vr->max) == INTEGER_CST)
3956 dstsize = (warn_level < 2
3957 ? TREE_INT_CST_LOW (vr->max)
3958 : TREE_INT_CST_LOW (vr->min));
3960 /* The destination size is not constant. If the function is
3961 bounded (e.g., snprintf) a lower bound of zero doesn't
3962 necessarily imply it can be eliminated. */
3963 dstsize_cst_p = false;
3967 if (idx_objsize != HOST_WIDE_INT_M1U)
3968 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3969 if (tree_fits_uhwi_p (size))
3970 objsize = tree_to_uhwi (size);
3972 if (info.bounded && !dstsize)
3974 /* As a special case, when the explicitly specified destination
3975 size argument (to a bounded function like snprintf) is zero
3976 it is a request to determine the number of bytes on output
3977 without actually producing any. Pretend the size is
3978 unlimited in this case. */
3979 info.objsize = HOST_WIDE_INT_MAX;
3980 info.nowrite = dstsize_cst_p;
3982 else
3984 /* For calls to non-bounded functions or to those of bounded
3985 functions with a non-zero size, warn if the destination
3986 pointer is null. */
3987 if (integer_zerop (dstptr))
3989 /* This is diagnosed with -Wformat only when the null is a constant
3990 pointer. The warning here diagnoses instances where the pointer
3991 is not constant. */
3992 location_t loc = gimple_location (info.callstmt);
3993 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3994 info.warnopt (), "null destination pointer");
3995 return false;
3998 /* Set the object size to the smaller of the two arguments
3999 of both have been specified and they're not equal. */
4000 info.objsize = dstsize < objsize ? dstsize : objsize;
4002 if (info.bounded
4003 && dstsize < target_size_max () / 2 && objsize < dstsize
4004 /* Avoid warning if -Wstringop-overflow is specified since
4005 it also warns for the same thing though only for the
4006 checking built-ins. */
4007 && (idx_objsize == HOST_WIDE_INT_M1U
4008 || !warn_stringop_overflow))
4010 warning_at (gimple_location (info.callstmt), info.warnopt (),
4011 "specified bound %wu exceeds the size %wu "
4012 "of the destination object", dstsize, objsize);
4016 if (integer_zerop (info.format))
4018 /* This is diagnosed with -Wformat only when the null is a constant
4019 pointer. The warning here diagnoses instances where the pointer
4020 is not constant. */
4021 location_t loc = gimple_location (info.callstmt);
4022 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
4023 info.warnopt (), "null format string");
4024 return false;
4027 info.fmtstr = get_format_string (info.format, &info.fmtloc);
4028 if (!info.fmtstr)
4029 return false;
4031 /* The result is the number of bytes output by the formatted function,
4032 including the terminating NUL. */
4033 format_result res = format_result ();
4035 bool success = compute_format_length (info, &res);
4037 /* When optimizing and the printf return value optimization is enabled,
4038 attempt to substitute the computed result for the return value of
4039 the call. Avoid this optimization when -frounding-math is in effect
4040 and the format string contains a floating point directive. */
4041 bool call_removed = false;
4042 if (success && optimize > 0)
4044 /* Save a copy of the iterator pointing at the call. The iterator
4045 may change to point past the call in try_substitute_return_value
4046 but the original value is needed in try_simplify_call. */
4047 gimple_stmt_iterator gsi_call = *gsi;
4049 if (flag_printf_return_value
4050 && (!flag_rounding_math || !res.floating))
4051 call_removed = try_substitute_return_value (gsi, info, res);
4053 if (!call_removed)
4054 try_simplify_call (&gsi_call, info, res);
4057 return call_removed;
4060 edge
4061 sprintf_dom_walker::before_dom_children (basic_block bb)
4063 evrp_range_analyzer.enter (bb);
4064 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
4066 /* Iterate over statements, looking for function calls. */
4067 gimple *stmt = gsi_stmt (si);
4069 /* First record ranges generated by this statement. */
4070 evrp_range_analyzer.record_ranges_from_stmt (stmt, false);
4072 if (is_gimple_call (stmt) && handle_gimple_call (&si))
4073 /* If handle_gimple_call returns true, the iterator is
4074 already pointing to the next statement. */
4075 continue;
4077 gsi_next (&si);
4079 return NULL;
4082 void
4083 sprintf_dom_walker::after_dom_children (basic_block bb)
4085 evrp_range_analyzer.leave (bb);
4088 /* Execute the pass for function FUN. */
4090 unsigned int
4091 pass_sprintf_length::execute (function *fun)
4093 init_target_to_host_charmap ();
4095 calculate_dominance_info (CDI_DOMINATORS);
4097 sprintf_dom_walker sprintf_dom_walker;
4098 sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
4100 /* Clean up object size info. */
4101 fini_object_sizes ();
4102 return 0;
4105 } /* Unnamed namespace. */
4107 /* Return a pointer to a pass object newly constructed from the context
4108 CTXT. */
4110 gimple_opt_pass *
4111 make_pass_sprintf_length (gcc::context *ctxt)
4113 return new pass_sprintf_length (ctxt);