PR middle-end/82123
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob54c91320e56a230e0cb33742b452fbb3089ff6af
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 /* The format_warning_at_substring function is not used here in a way
593 that makes using attribute format viable. Suppress the warning. */
595 #pragma GCC diagnostic push
596 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
598 /* For convenience and brevity. */
600 static bool
601 (* const fmtwarn) (const substring_loc &, location_t,
602 const char *, int, const char *, ...)
603 = format_warning_at_substring;
605 /* Format length modifiers. */
607 enum format_lengths
609 FMT_LEN_none,
610 FMT_LEN_hh, // char argument
611 FMT_LEN_h, // short
612 FMT_LEN_l, // long
613 FMT_LEN_ll, // long long
614 FMT_LEN_L, // long double (and GNU long long)
615 FMT_LEN_z, // size_t
616 FMT_LEN_t, // ptrdiff_t
617 FMT_LEN_j // intmax_t
621 /* Description of the result of conversion either of a single directive
622 or the whole format string. */
624 struct fmtresult
626 /* Construct a FMTRESULT object with all counters initialized
627 to MIN. KNOWNRANGE is set when MIN is valid. */
628 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
629 : argmin (), argmax (),
630 knownrange (min < HOST_WIDE_INT_MAX),
631 nullp ()
633 range.min = min;
634 range.max = min;
635 range.likely = min;
636 range.unlikely = min;
639 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
640 KNOWNRANGE is set when both MIN and MAX are valid. */
641 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
642 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
643 : argmin (), argmax (),
644 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
645 nullp ()
647 range.min = min;
648 range.max = max;
649 range.likely = max < likely ? min : likely;
650 range.unlikely = max;
653 /* Adjust result upward to reflect the RANGE of values the specified
654 width or precision is known to be in. */
655 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
656 tree = NULL_TREE,
657 unsigned = 0, unsigned = 0);
659 /* Return the maximum number of decimal digits a value of TYPE
660 formats as on output. */
661 static unsigned type_max_digits (tree, int);
663 /* The range a directive's argument is in. */
664 tree argmin, argmax;
666 /* The minimum and maximum number of bytes that a directive
667 results in on output for an argument in the range above. */
668 result_range range;
670 /* True when the range above is obtained from a known value of
671 a directive's argument or its bounds and not the result of
672 heuristics that depend on warning levels. */
673 bool knownrange;
675 /* True when the argument is a null pointer. */
676 bool nullp;
679 /* Adjust result upward to reflect the range ADJUST of values the
680 specified width or precision is known to be in. When non-null,
681 TYPE denotes the type of the directive whose result is being
682 adjusted, BASE gives the base of the directive (octal, decimal,
683 or hex), and ADJ denotes the additional adjustment to the LIKELY
684 counter that may need to be added when ADJUST is a range. */
686 fmtresult&
687 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
688 tree type /* = NULL_TREE */,
689 unsigned base /* = 0 */,
690 unsigned adj /* = 0 */)
692 bool minadjusted = false;
694 /* Adjust the minimum and likely counters. */
695 if (adjust[0] >= 0)
697 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
699 range.min = adjust[0];
700 minadjusted = true;
703 /* Adjust the likely counter. */
704 if (range.likely < range.min)
705 range.likely = range.min;
707 else if (adjust[0] == target_int_min ()
708 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
709 knownrange = false;
711 /* Adjust the maximum counter. */
712 if (adjust[1] > 0)
714 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
716 range.max = adjust[1];
718 /* Set KNOWNRANGE if both the minimum and maximum have been
719 adjusted. Otherwise leave it at what it was before. */
720 knownrange = minadjusted;
724 if (warn_level > 1 && type)
726 /* For large non-constant width or precision whose range spans
727 the maximum number of digits produced by the directive for
728 any argument, set the likely number of bytes to be at most
729 the number digits plus other adjustment determined by the
730 caller (one for sign or two for the hexadecimal "0x"
731 prefix). */
732 unsigned dirdigs = type_max_digits (type, base);
733 if (adjust[0] < dirdigs && dirdigs < adjust[1]
734 && range.likely < dirdigs)
735 range.likely = dirdigs + adj;
737 else if (range.likely < (range.min ? range.min : 1))
739 /* Conservatively, set LIKELY to at least MIN but no less than
740 1 unless MAX is zero. */
741 range.likely = (range.min
742 ? range.min
743 : range.max && (range.max < HOST_WIDE_INT_MAX
744 || warn_level > 1) ? 1 : 0);
747 /* Finally adjust the unlikely counter to be at least as large as
748 the maximum. */
749 if (range.unlikely < range.max)
750 range.unlikely = range.max;
752 return *this;
755 /* Return the maximum number of digits a value of TYPE formats in
756 BASE on output, not counting base prefix . */
758 unsigned
759 fmtresult::type_max_digits (tree type, int base)
761 unsigned prec = TYPE_PRECISION (type);
762 if (base == 8)
763 return (prec + 2) / 3;
765 if (base == 16)
766 return prec / 4;
768 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
769 of 8, 16, 32, and 64 bits. */
770 return prec * 301 / 1000 + 1;
773 static bool
774 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT,
775 class vr_values *vr_values);
777 /* Description of a format directive. A directive is either a plain
778 string or a conversion specification that starts with '%'. */
780 struct directive
782 /* The 1-based directive number (for debugging). */
783 unsigned dirno;
785 /* The first character of the directive and its length. */
786 const char *beg;
787 size_t len;
789 /* A bitmap of flags, one for each character. */
790 unsigned flags[256 / sizeof (int)];
792 /* The range of values of the specified width, or -1 if not specified. */
793 HOST_WIDE_INT width[2];
794 /* The range of values of the specified precision, or -1 if not
795 specified. */
796 HOST_WIDE_INT prec[2];
798 /* Length modifier. */
799 format_lengths modifier;
801 /* Format specifier character. */
802 char specifier;
804 /* The argument of the directive or null when the directive doesn't
805 take one or when none is available (such as for vararg functions). */
806 tree arg;
808 /* Format conversion function that given a directive and an argument
809 returns the formatting result. */
810 fmtresult (*fmtfunc) (const directive &, tree, vr_values *);
812 /* Return True when a the format flag CHR has been used. */
813 bool get_flag (char chr) const
815 unsigned char c = chr & 0xff;
816 return (flags[c / (CHAR_BIT * sizeof *flags)]
817 & (1U << (c % (CHAR_BIT * sizeof *flags))));
820 /* Make a record of the format flag CHR having been used. */
821 void set_flag (char chr)
823 unsigned char c = chr & 0xff;
824 flags[c / (CHAR_BIT * sizeof *flags)]
825 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
828 /* Reset the format flag CHR. */
829 void clear_flag (char chr)
831 unsigned char c = chr & 0xff;
832 flags[c / (CHAR_BIT * sizeof *flags)]
833 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
836 /* Set both bounds of the width range to VAL. */
837 void set_width (HOST_WIDE_INT val)
839 width[0] = width[1] = val;
842 /* Set the width range according to ARG, with both bounds being
843 no less than 0. For a constant ARG set both bounds to its value
844 or 0, whichever is greater. For a non-constant ARG in some range
845 set width to its range adjusting each bound to -1 if it's less.
846 For an indeterminate ARG set width to [0, INT_MAX]. */
847 void set_width (tree arg, vr_values *vr_values)
849 get_int_range (arg, width, width + 1, true, 0, vr_values);
852 /* Set both bounds of the precision range to VAL. */
853 void set_precision (HOST_WIDE_INT val)
855 prec[0] = prec[1] = val;
858 /* Set the precision range according to ARG, with both bounds being
859 no less than -1. For a constant ARG set both bounds to its value
860 or -1 whichever is greater. For a non-constant ARG in some range
861 set precision to its range adjusting each bound to -1 if it's less.
862 For an indeterminate ARG set precision to [-1, INT_MAX]. */
863 void set_precision (tree arg, vr_values *vr_values)
865 get_int_range (arg, prec, prec + 1, false, -1, vr_values);
868 /* Return true if both width and precision are known to be
869 either constant or in some range, false otherwise. */
870 bool known_width_and_precision () const
872 return ((width[1] < 0
873 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
874 && (prec[1] < 0
875 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
879 /* Return the logarithm of X in BASE. */
881 static int
882 ilog (unsigned HOST_WIDE_INT x, int base)
884 int res = 0;
887 ++res;
888 x /= base;
889 } while (x);
890 return res;
893 /* Return the number of bytes resulting from converting into a string
894 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
895 PLUS indicates whether 1 for a plus sign should be added for positive
896 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
897 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
898 be represented. */
900 static HOST_WIDE_INT
901 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
903 unsigned HOST_WIDE_INT absval;
905 HOST_WIDE_INT res;
907 if (TYPE_UNSIGNED (TREE_TYPE (x)))
909 if (tree_fits_uhwi_p (x))
911 absval = tree_to_uhwi (x);
912 res = plus;
914 else
915 return -1;
917 else
919 if (tree_fits_shwi_p (x))
921 HOST_WIDE_INT i = tree_to_shwi (x);
922 if (HOST_WIDE_INT_MIN == i)
924 /* Avoid undefined behavior due to negating a minimum. */
925 absval = HOST_WIDE_INT_MAX;
926 res = 1;
928 else if (i < 0)
930 absval = -i;
931 res = 1;
933 else
935 absval = i;
936 res = plus;
939 else
940 return -1;
943 int ndigs = ilog (absval, base);
945 res += prec < ndigs ? ndigs : prec;
947 /* Adjust a non-zero value for the base prefix, either hexadecimal,
948 or, unless precision has resulted in a leading zero, also octal. */
949 if (prefix && absval && (base == 16 || prec <= ndigs))
951 if (base == 8)
952 res += 1;
953 else if (base == 16)
954 res += 2;
957 return res;
960 /* Given the formatting result described by RES and NAVAIL, the number
961 of available in the destination, return the range of bytes remaining
962 in the destination. */
964 static inline result_range
965 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
967 result_range range;
969 if (HOST_WIDE_INT_MAX <= navail)
971 range.min = range.max = range.likely = range.unlikely = navail;
972 return range;
975 /* The lower bound of the available range is the available size
976 minus the maximum output size, and the upper bound is the size
977 minus the minimum. */
978 range.max = res.range.min < navail ? navail - res.range.min : 0;
980 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
982 if (res.range.max < HOST_WIDE_INT_MAX)
983 range.min = res.range.max < navail ? navail - res.range.max : 0;
984 else
985 range.min = range.likely;
987 range.unlikely = (res.range.unlikely < navail
988 ? navail - res.range.unlikely : 0);
990 return range;
993 /* Description of a call to a formatted function. */
995 struct sprintf_dom_walker::call_info
997 /* Function call statement. */
998 gimple *callstmt;
1000 /* Function called. */
1001 tree func;
1003 /* Called built-in function code. */
1004 built_in_function fncode;
1006 /* Format argument and format string extracted from it. */
1007 tree format;
1008 const char *fmtstr;
1010 /* The location of the format argument. */
1011 location_t fmtloc;
1013 /* The destination object size for __builtin___xxx_chk functions
1014 typically determined by __builtin_object_size, or -1 if unknown. */
1015 unsigned HOST_WIDE_INT objsize;
1017 /* Number of the first variable argument. */
1018 unsigned HOST_WIDE_INT argidx;
1020 /* True for functions like snprintf that specify the size of
1021 the destination, false for others like sprintf that don't. */
1022 bool bounded;
1024 /* True for bounded functions like snprintf that specify a zero-size
1025 buffer as a request to compute the size of output without actually
1026 writing any. NOWRITE is cleared in response to the %n directive
1027 which has side-effects similar to writing output. */
1028 bool nowrite;
1030 /* Return true if the called function's return value is used. */
1031 bool retval_used () const
1033 return gimple_get_lhs (callstmt);
1036 /* Return the warning option corresponding to the called function. */
1037 int warnopt () const
1039 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
1043 /* Return the result of formatting a no-op directive (such as '%n'). */
1045 static fmtresult
1046 format_none (const directive &, tree, vr_values *)
1048 fmtresult res (0);
1049 return res;
1052 /* Return the result of formatting the '%%' directive. */
1054 static fmtresult
1055 format_percent (const directive &, tree, vr_values *)
1057 fmtresult res (1);
1058 return res;
1062 /* Compute intmax_type_node and uintmax_type_node similarly to how
1063 tree.c builds size_type_node. */
1065 static void
1066 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
1068 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
1070 *pintmax = integer_type_node;
1071 *puintmax = unsigned_type_node;
1073 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
1075 *pintmax = long_integer_type_node;
1076 *puintmax = long_unsigned_type_node;
1078 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
1080 *pintmax = long_long_integer_type_node;
1081 *puintmax = long_long_unsigned_type_node;
1083 else
1085 for (int i = 0; i < NUM_INT_N_ENTS; i++)
1086 if (int_n_enabled_p[i])
1088 char name[50];
1089 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
1091 if (strcmp (name, UINTMAX_TYPE) == 0)
1093 *pintmax = int_n_trees[i].signed_type;
1094 *puintmax = int_n_trees[i].unsigned_type;
1095 return;
1098 gcc_unreachable ();
1102 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1103 in and that is representable in type int.
1104 Return true when the range is a subrange of that of int.
1105 When ARG is null it is as if it had the full range of int.
1106 When ABSOLUTE is true the range reflects the absolute value of
1107 the argument. When ABSOLUTE is false, negative bounds of
1108 the determined range are replaced with NEGBOUND. */
1110 static bool
1111 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1112 bool absolute, HOST_WIDE_INT negbound,
1113 class vr_values *vr_values)
1115 /* The type of the result. */
1116 const_tree type = integer_type_node;
1118 bool knownrange = false;
1120 if (!arg)
1122 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1123 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1125 else if (TREE_CODE (arg) == INTEGER_CST
1126 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1128 /* For a constant argument return its value adjusted as specified
1129 by NEGATIVE and NEGBOUND and return true to indicate that the
1130 result is known. */
1131 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1132 *pmax = *pmin;
1133 knownrange = true;
1135 else
1137 /* True if the argument's range cannot be determined. */
1138 bool unknown = true;
1140 tree argtype = TREE_TYPE (arg);
1142 /* Ignore invalid arguments with greater precision that that
1143 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1144 They will have been detected and diagnosed by -Wformat and
1145 so it's not important to complicate this code to try to deal
1146 with them again. */
1147 if (TREE_CODE (arg) == SSA_NAME
1148 && INTEGRAL_TYPE_P (argtype)
1149 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1151 /* Try to determine the range of values of the integer argument. */
1152 wide_int min, max;
1153 enum value_range_type range_type = get_range_info (arg, &min, &max);
1154 if (range_type == VR_RANGE)
1156 HOST_WIDE_INT type_min
1157 = (TYPE_UNSIGNED (argtype)
1158 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1159 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1161 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1163 *pmin = min.to_shwi ();
1164 *pmax = max.to_shwi ();
1166 if (*pmin < *pmax)
1168 /* Return true if the adjusted range is a subrange of
1169 the full range of the argument's type. *PMAX may
1170 be less than *PMIN when the argument is unsigned
1171 and its upper bound is in excess of TYPE_MAX. In
1172 that (invalid) case disregard the range and use that
1173 of the expected type instead. */
1174 knownrange = type_min < *pmin || *pmax < type_max;
1176 unknown = false;
1181 /* Handle an argument with an unknown range as if none had been
1182 provided. */
1183 if (unknown)
1184 return get_int_range (NULL_TREE, pmin, pmax, absolute,
1185 negbound, vr_values);
1188 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1189 if (absolute)
1191 if (*pmin < 0)
1193 if (*pmin == *pmax)
1194 *pmin = *pmax = -*pmin;
1195 else
1197 /* Make sure signed overlow is avoided. */
1198 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1200 HOST_WIDE_INT tmp = -*pmin;
1201 *pmin = 0;
1202 if (*pmax < tmp)
1203 *pmax = tmp;
1207 else if (*pmin < negbound)
1208 *pmin = negbound;
1210 return knownrange;
1213 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1214 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1215 the type of the directive's formal argument it's possible for both
1216 to result in the same number of bytes or a range of bytes that's
1217 less than the number of bytes that would result from formatting
1218 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1219 determined by checking for the actual argument being in the range
1220 of the type of the directive. If it isn't it must be assumed to
1221 take on the full range of the directive's type.
1222 Return true when the range has been adjusted to the full range
1223 of DIRTYPE, and false otherwise. */
1225 static bool
1226 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1228 tree argtype = TREE_TYPE (*argmin);
1229 unsigned argprec = TYPE_PRECISION (argtype);
1230 unsigned dirprec = TYPE_PRECISION (dirtype);
1232 /* If the actual argument and the directive's argument have the same
1233 precision and sign there can be no overflow and so there is nothing
1234 to adjust. */
1235 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1236 return false;
1238 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1239 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1241 if (TREE_CODE (*argmin) == INTEGER_CST
1242 && TREE_CODE (*argmax) == INTEGER_CST
1243 && (dirprec >= argprec
1244 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1245 int_const_binop (MINUS_EXPR,
1246 *argmax,
1247 *argmin),
1248 size_int (dirprec)))))
1250 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1251 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1253 /* If *ARGMIN is still less than *ARGMAX the conversion above
1254 is safe. Otherwise, it has overflowed and would be unsafe. */
1255 if (tree_int_cst_le (*argmin, *argmax))
1256 return false;
1259 *argmin = TYPE_MIN_VALUE (dirtype);
1260 *argmax = TYPE_MAX_VALUE (dirtype);
1261 return true;
1264 /* Return a range representing the minimum and maximum number of bytes
1265 that the format directive DIR will output for any argument given
1266 the WIDTH and PRECISION (extracted from DIR). This function is
1267 used when the directive argument or its value isn't known. */
1269 static fmtresult
1270 format_integer (const directive &dir, tree arg, vr_values *vr_values)
1272 tree intmax_type_node;
1273 tree uintmax_type_node;
1275 /* Base to format the number in. */
1276 int base;
1278 /* True when a conversion is preceded by a prefix indicating the base
1279 of the argument (octal or hexadecimal). */
1280 bool maybebase = dir.get_flag ('#');
1282 /* True when a signed conversion is preceded by a sign or space. */
1283 bool maybesign = false;
1285 /* True for signed conversions (i.e., 'd' and 'i'). */
1286 bool sign = false;
1288 switch (dir.specifier)
1290 case 'd':
1291 case 'i':
1292 /* Space and '+' are only meaningful for signed conversions. */
1293 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1294 sign = true;
1295 base = 10;
1296 break;
1297 case 'u':
1298 base = 10;
1299 break;
1300 case 'o':
1301 base = 8;
1302 break;
1303 case 'X':
1304 case 'x':
1305 base = 16;
1306 break;
1307 default:
1308 gcc_unreachable ();
1311 /* The type of the "formal" argument expected by the directive. */
1312 tree dirtype = NULL_TREE;
1314 /* Determine the expected type of the argument from the length
1315 modifier. */
1316 switch (dir.modifier)
1318 case FMT_LEN_none:
1319 if (dir.specifier == 'p')
1320 dirtype = ptr_type_node;
1321 else
1322 dirtype = sign ? integer_type_node : unsigned_type_node;
1323 break;
1325 case FMT_LEN_h:
1326 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1327 break;
1329 case FMT_LEN_hh:
1330 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1331 break;
1333 case FMT_LEN_l:
1334 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1335 break;
1337 case FMT_LEN_L:
1338 case FMT_LEN_ll:
1339 dirtype = (sign
1340 ? long_long_integer_type_node
1341 : long_long_unsigned_type_node);
1342 break;
1344 case FMT_LEN_z:
1345 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1346 break;
1348 case FMT_LEN_t:
1349 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1350 break;
1352 case FMT_LEN_j:
1353 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1354 dirtype = sign ? intmax_type_node : uintmax_type_node;
1355 break;
1357 default:
1358 return fmtresult ();
1361 /* The type of the argument to the directive, either deduced from
1362 the actual non-constant argument if one is known, or from
1363 the directive itself when none has been provided because it's
1364 a va_list. */
1365 tree argtype = NULL_TREE;
1367 if (!arg)
1369 /* When the argument has not been provided, use the type of
1370 the directive's argument as an approximation. This will
1371 result in false positives for directives like %i with
1372 arguments with smaller precision (such as short or char). */
1373 argtype = dirtype;
1375 else if (TREE_CODE (arg) == INTEGER_CST)
1377 /* When a constant argument has been provided use its value
1378 rather than type to determine the length of the output. */
1379 fmtresult res;
1381 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1383 /* As a special case, a precision of zero with a zero argument
1384 results in zero bytes except in base 8 when the '#' flag is
1385 specified, and for signed conversions in base 8 and 10 when
1386 either the space or '+' flag has been specified and it results
1387 in just one byte (with width having the normal effect). This
1388 must extend to the case of a specified precision with
1389 an unknown value because it can be zero. */
1390 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1391 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1393 res.range.max = 1;
1394 res.range.likely = 1;
1396 else
1398 res.range.max = res.range.min;
1399 res.range.likely = res.range.min;
1402 else
1404 /* Convert the argument to the type of the directive. */
1405 arg = fold_convert (dirtype, arg);
1407 res.range.min = tree_digits (arg, base, dir.prec[0],
1408 maybesign, maybebase);
1409 if (dir.prec[0] == dir.prec[1])
1410 res.range.max = res.range.min;
1411 else
1412 res.range.max = tree_digits (arg, base, dir.prec[1],
1413 maybesign, maybebase);
1414 res.range.likely = res.range.min;
1415 res.knownrange = true;
1418 res.range.unlikely = res.range.max;
1420 /* Bump up the counters if WIDTH is greater than LEN. */
1421 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1422 (sign | maybebase) + (base == 16));
1423 /* Bump up the counters again if PRECision is greater still. */
1424 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1425 (sign | maybebase) + (base == 16));
1427 return res;
1429 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1430 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1431 /* Determine the type of the provided non-constant argument. */
1432 argtype = TREE_TYPE (arg);
1433 else
1434 /* Don't bother with invalid arguments since they likely would
1435 have already been diagnosed, and disable any further checking
1436 of the format string by returning [-1, -1]. */
1437 return fmtresult ();
1439 fmtresult res;
1441 /* Using either the range the non-constant argument is in, or its
1442 type (either "formal" or actual), create a range of values that
1443 constrain the length of output given the warning level. */
1444 tree argmin = NULL_TREE;
1445 tree argmax = NULL_TREE;
1447 if (arg
1448 && TREE_CODE (arg) == SSA_NAME
1449 && INTEGRAL_TYPE_P (argtype))
1451 /* Try to determine the range of values of the integer argument
1452 (range information is not available for pointers). */
1453 wide_int min, max;
1454 enum value_range_type range_type = get_range_info (arg, &min, &max);
1455 if (range_type == VR_RANGE)
1457 argmin = wide_int_to_tree (argtype, min);
1458 argmax = wide_int_to_tree (argtype, max);
1460 /* Set KNOWNRANGE if the argument is in a known subrange
1461 of the directive's type and neither width nor precision
1462 is unknown. (KNOWNRANGE may be reset below). */
1463 res.knownrange
1464 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1465 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1466 && dir.known_width_and_precision ());
1468 res.argmin = argmin;
1469 res.argmax = argmax;
1471 else if (range_type == VR_ANTI_RANGE)
1473 /* Handle anti-ranges if/when bug 71690 is resolved. */
1475 else if (range_type == VR_VARYING)
1477 /* The argument here may be the result of promoting the actual
1478 argument to int. Try to determine the type of the actual
1479 argument before promotion and narrow down its range that
1480 way. */
1481 gimple *def = SSA_NAME_DEF_STMT (arg);
1482 if (is_gimple_assign (def))
1484 tree_code code = gimple_assign_rhs_code (def);
1485 if (code == INTEGER_CST)
1487 arg = gimple_assign_rhs1 (def);
1488 return format_integer (dir, arg, vr_values);
1491 if (code == NOP_EXPR)
1493 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1494 if (INTEGRAL_TYPE_P (type)
1495 || TREE_CODE (type) == POINTER_TYPE)
1496 argtype = type;
1502 if (!argmin)
1504 if (TREE_CODE (argtype) == POINTER_TYPE)
1506 argmin = build_int_cst (pointer_sized_int_node, 0);
1507 argmax = build_all_ones_cst (pointer_sized_int_node);
1509 else
1511 argmin = TYPE_MIN_VALUE (argtype);
1512 argmax = TYPE_MAX_VALUE (argtype);
1516 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1517 of the directive. If it has been cleared then since ARGMIN and/or
1518 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1519 ARGMAX in the result to include in diagnostics. */
1520 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1522 res.knownrange = false;
1523 res.argmin = argmin;
1524 res.argmax = argmax;
1527 /* Recursively compute the minimum and maximum from the known range. */
1528 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1530 /* For unsigned conversions/directives or signed when
1531 the minimum is positive, use the minimum and maximum to compute
1532 the shortest and longest output, respectively. */
1533 res.range.min = format_integer (dir, argmin, vr_values).range.min;
1534 res.range.max = format_integer (dir, argmax, vr_values).range.max;
1536 else if (tree_int_cst_sgn (argmax) < 0)
1538 /* For signed conversions/directives if maximum is negative,
1539 use the minimum as the longest output and maximum as the
1540 shortest output. */
1541 res.range.min = format_integer (dir, argmax, vr_values).range.min;
1542 res.range.max = format_integer (dir, argmin, vr_values).range.max;
1544 else
1546 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1547 as the shortest output and for the longest output compute the
1548 length of the output of both minimum and maximum and pick the
1549 longer. */
1550 unsigned HOST_WIDE_INT max1
1551 = format_integer (dir, argmin, vr_values).range.max;
1552 unsigned HOST_WIDE_INT max2
1553 = format_integer (dir, argmax, vr_values).range.max;
1554 res.range.min
1555 = format_integer (dir, integer_zero_node, vr_values).range.min;
1556 res.range.max = MAX (max1, max2);
1559 /* If the range is known, use the maximum as the likely length. */
1560 if (res.knownrange)
1561 res.range.likely = res.range.max;
1562 else
1564 /* Otherwise, use the minimum. Except for the case where for %#x or
1565 %#o the minimum is just for a single value in the range (0) and
1566 for all other values it is something longer, like 0x1 or 01.
1567 Use the length for value 1 in that case instead as the likely
1568 length. */
1569 res.range.likely = res.range.min;
1570 if (maybebase
1571 && base != 10
1572 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1574 if (res.range.min == 1)
1575 res.range.likely += base == 8 ? 1 : 2;
1576 else if (res.range.min == 2
1577 && base == 16
1578 && (dir.width[0] == 2 || dir.prec[0] == 2))
1579 ++res.range.likely;
1583 res.range.unlikely = res.range.max;
1584 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1585 (sign | maybebase) + (base == 16));
1586 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1587 (sign | maybebase) + (base == 16));
1589 return res;
1592 /* Return the number of bytes that a format directive consisting of FLAGS,
1593 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1594 would result for argument X under ideal conditions (i.e., if PREC
1595 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1596 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1597 This function works around those problems. */
1599 static unsigned HOST_WIDE_INT
1600 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1601 char spec, char rndspec)
1603 char fmtstr[40];
1605 HOST_WIDE_INT len = strlen (flags);
1607 fmtstr[0] = '%';
1608 memcpy (fmtstr + 1, flags, len);
1609 memcpy (fmtstr + 1 + len, ".*R", 3);
1610 fmtstr[len + 4] = rndspec;
1611 fmtstr[len + 5] = spec;
1612 fmtstr[len + 6] = '\0';
1614 spec = TOUPPER (spec);
1615 if (spec == 'E' || spec == 'F')
1617 /* For %e, specify the precision explicitly since mpfr_sprintf
1618 does its own thing just to be different (see MPFR bug 21088). */
1619 if (prec < 0)
1620 prec = 6;
1622 else
1624 /* Avoid passing negative precisions with larger magnitude to MPFR
1625 to avoid exposing its bugs. (A negative precision is supposed
1626 to be ignored.) */
1627 if (prec < 0)
1628 prec = -1;
1631 HOST_WIDE_INT p = prec;
1633 if (spec == 'G' && !strchr (flags, '#'))
1635 /* For G/g without the pound flag, precision gives the maximum number
1636 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1637 a 128 bit IEEE extended precision, 4932. Using twice as much here
1638 should be more than sufficient for any real format. */
1639 if ((IEEE_MAX_10_EXP * 2) < prec)
1640 prec = IEEE_MAX_10_EXP * 2;
1641 p = prec;
1643 else
1645 /* Cap precision arbitrarily at 1KB and add the difference
1646 (if any) to the MPFR result. */
1647 if (prec > 1024)
1648 p = 1024;
1651 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1653 /* Handle the unlikely (impossible?) error by returning more than
1654 the maximum dictated by the function's return type. */
1655 if (len < 0)
1656 return target_dir_max () + 1;
1658 /* Adjust the return value by the difference. */
1659 if (p < prec)
1660 len += prec - p;
1662 return len;
1665 /* Return the number of bytes to format using the format specifier
1666 SPEC and the precision PREC the largest value in the real floating
1667 TYPE. */
1669 static unsigned HOST_WIDE_INT
1670 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1672 machine_mode mode = TYPE_MODE (type);
1674 /* IBM Extended mode. */
1675 if (MODE_COMPOSITE_P (mode))
1676 mode = DFmode;
1678 /* Get the real type format desription for the target. */
1679 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1680 REAL_VALUE_TYPE rv;
1682 real_maxval (&rv, 0, mode);
1684 /* Convert the GCC real value representation with the precision
1685 of the real type to the mpfr_t format with the GCC default
1686 round-to-nearest mode. */
1687 mpfr_t x;
1688 mpfr_init2 (x, rfmt->p);
1689 mpfr_from_real (x, &rv, GMP_RNDN);
1691 /* Return a value one greater to account for the leading minus sign. */
1692 unsigned HOST_WIDE_INT r
1693 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1694 mpfr_clear (x);
1695 return r;
1698 /* Return a range representing the minimum and maximum number of bytes
1699 that the directive DIR will output for any argument. PREC gives
1700 the adjusted precision range to account for negative precisions
1701 meaning the default 6. This function is used when the directive
1702 argument or its value isn't known. */
1704 static fmtresult
1705 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1707 tree type;
1709 switch (dir.modifier)
1711 case FMT_LEN_l:
1712 case FMT_LEN_none:
1713 type = double_type_node;
1714 break;
1716 case FMT_LEN_L:
1717 type = long_double_type_node;
1718 break;
1720 case FMT_LEN_ll:
1721 type = long_double_type_node;
1722 break;
1724 default:
1725 return fmtresult ();
1728 /* The minimum and maximum number of bytes produced by the directive. */
1729 fmtresult res;
1731 /* The minimum output as determined by flags. It's always at least 1.
1732 When plus or space are set the output is preceded by either a sign
1733 or a space. */
1734 unsigned flagmin = (1 /* for the first digit */
1735 + (dir.get_flag ('+') | dir.get_flag (' ')));
1737 /* When the pound flag is set the decimal point is included in output
1738 regardless of precision. Whether or not a decimal point is included
1739 otherwise depends on the specification and precision. */
1740 bool radix = dir.get_flag ('#');
1742 switch (dir.specifier)
1744 case 'A':
1745 case 'a':
1747 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1748 if (dir.prec[0] <= 0)
1749 minprec = 0;
1750 else if (dir.prec[0] > 0)
1751 minprec = dir.prec[0] + !radix /* decimal point */;
1753 res.range.min = (2 /* 0x */
1754 + flagmin
1755 + radix
1756 + minprec
1757 + 3 /* p+0 */);
1759 res.range.max = format_floating_max (type, 'a', prec[1]);
1760 res.range.likely = res.range.min;
1762 /* The unlikely maximum accounts for the longest multibyte
1763 decimal point character. */
1764 res.range.unlikely = res.range.max;
1765 if (dir.prec[1] > 0)
1766 res.range.unlikely += target_mb_len_max () - 1;
1768 break;
1771 case 'E':
1772 case 'e':
1774 /* Minimum output attributable to precision and, when it's
1775 non-zero, decimal point. */
1776 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1778 /* The minimum output is "[-+]1.234567e+00" regardless
1779 of the value of the actual argument. */
1780 res.range.min = (flagmin
1781 + radix
1782 + minprec
1783 + 2 /* e+ */ + 2);
1785 res.range.max = format_floating_max (type, 'e', prec[1]);
1786 res.range.likely = res.range.min;
1788 /* The unlikely maximum accounts for the longest multibyte
1789 decimal point character. */
1790 if (dir.prec[0] != dir.prec[1]
1791 || dir.prec[0] == -1 || dir.prec[0] > 0)
1792 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1793 else
1794 res.range.unlikely = res.range.max;
1795 break;
1798 case 'F':
1799 case 'f':
1801 /* Minimum output attributable to precision and, when it's non-zero,
1802 decimal point. */
1803 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1805 /* The lower bound when precision isn't specified is 8 bytes
1806 ("1.23456" since precision is taken to be 6). When precision
1807 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1808 when precision is greater than zero, then the lower bound
1809 is 2 plus precision (plus flags). */
1810 res.range.min = flagmin + radix + minprec;
1812 /* Compute the upper bound for -TYPE_MAX. */
1813 res.range.max = format_floating_max (type, 'f', prec[1]);
1815 /* The minimum output with unknown precision is a single byte
1816 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1817 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1818 res.range.likely = 3;
1819 else
1820 res.range.likely = res.range.min;
1822 /* The unlikely maximum accounts for the longest multibyte
1823 decimal point character. */
1824 if (dir.prec[0] != dir.prec[1]
1825 || dir.prec[0] == -1 || dir.prec[0] > 0)
1826 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1827 break;
1830 case 'G':
1831 case 'g':
1833 /* The %g output depends on precision and the exponent of
1834 the argument. Since the value of the argument isn't known
1835 the lower bound on the range of bytes (not counting flags
1836 or width) is 1 plus radix (i.e., either "0" or "0." for
1837 "%g" and "%#g", respectively, with a zero argument). */
1838 res.range.min = flagmin + radix;
1840 char spec = 'g';
1841 HOST_WIDE_INT maxprec = dir.prec[1];
1842 if (radix && maxprec)
1844 /* When the pound flag (radix) is set, trailing zeros aren't
1845 trimmed and so the longest output is the same as for %e,
1846 except with precision minus 1 (as specified in C11). */
1847 spec = 'e';
1848 if (maxprec > 0)
1849 --maxprec;
1850 else if (maxprec < 0)
1851 maxprec = 5;
1853 else
1854 maxprec = prec[1];
1856 res.range.max = format_floating_max (type, spec, maxprec);
1858 /* The likely output is either the maximum computed above
1859 minus 1 (assuming the maximum is positive) when precision
1860 is known (or unspecified), or the same minimum as for %e
1861 (which is computed for a non-negative argument). Unlike
1862 for the other specifiers above the likely output isn't
1863 the minimum because for %g that's 1 which is unlikely. */
1864 if (dir.prec[1] < 0
1865 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1866 res.range.likely = res.range.max - 1;
1867 else
1869 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1870 res.range.likely = (flagmin
1871 + radix
1872 + minprec
1873 + 2 /* e+ */ + 2);
1876 /* The unlikely maximum accounts for the longest multibyte
1877 decimal point character. */
1878 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1879 break;
1882 default:
1883 return fmtresult ();
1886 /* Bump up the byte counters if WIDTH is greater. */
1887 res.adjust_for_width_or_precision (dir.width);
1888 return res;
1891 /* Return a range representing the minimum and maximum number of bytes
1892 that the directive DIR will write on output for the floating argument
1893 ARG. */
1895 static fmtresult
1896 format_floating (const directive &dir, tree arg, vr_values *)
1898 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1899 tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1900 ? long_double_type_node : double_type_node);
1902 /* For an indeterminate precision the lower bound must be assumed
1903 to be zero. */
1904 if (TOUPPER (dir.specifier) == 'A')
1906 /* Get the number of fractional decimal digits needed to represent
1907 the argument without a loss of accuracy. */
1908 unsigned fmtprec
1909 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1911 /* The precision of the IEEE 754 double format is 53.
1912 The precision of all other GCC binary double formats
1913 is 56 or less. */
1914 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1916 /* For %a, leave the minimum precision unspecified to let
1917 MFPR trim trailing zeros (as it and many other systems
1918 including Glibc happen to do) and set the maximum
1919 precision to reflect what it would be with trailing zeros
1920 present (as Solaris and derived systems do). */
1921 if (dir.prec[1] < 0)
1923 /* Both bounds are negative implies that precision has
1924 not been specified. */
1925 prec[0] = maxprec;
1926 prec[1] = -1;
1928 else if (dir.prec[0] < 0)
1930 /* With a negative lower bound and a non-negative upper
1931 bound set the minimum precision to zero and the maximum
1932 to the greater of the maximum precision (i.e., with
1933 trailing zeros present) and the specified upper bound. */
1934 prec[0] = 0;
1935 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1938 else if (dir.prec[0] < 0)
1940 if (dir.prec[1] < 0)
1942 /* A precision in a strictly negative range is ignored and
1943 the default of 6 is used instead. */
1944 prec[0] = prec[1] = 6;
1946 else
1948 /* For a precision in a partly negative range, the lower bound
1949 must be assumed to be zero and the new upper bound is the
1950 greater of 6 (the default precision used when the specified
1951 precision is negative) and the upper bound of the specified
1952 range. */
1953 prec[0] = 0;
1954 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1958 if (!arg
1959 || TREE_CODE (arg) != REAL_CST
1960 || !useless_type_conversion_p (type, TREE_TYPE (arg)))
1961 return format_floating (dir, prec);
1963 /* The minimum and maximum number of bytes produced by the directive. */
1964 fmtresult res;
1966 /* Get the real type format desription for the target. */
1967 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1968 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1970 char fmtstr [40];
1971 char *pfmt = fmtstr;
1973 /* Append flags. */
1974 for (const char *pf = "-+ #0"; *pf; ++pf)
1975 if (dir.get_flag (*pf))
1976 *pfmt++ = *pf;
1978 *pfmt = '\0';
1981 /* Set up an array to easily iterate over. */
1982 unsigned HOST_WIDE_INT* const minmax[] = {
1983 &res.range.min, &res.range.max
1986 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1988 /* Convert the GCC real value representation with the precision
1989 of the real type to the mpfr_t format rounding down in the
1990 first iteration that computes the minimm and up in the second
1991 that computes the maximum. This order is arbibtrary because
1992 rounding in either direction can result in longer output. */
1993 mpfr_t mpfrval;
1994 mpfr_init2 (mpfrval, rfmt->p);
1995 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1997 /* Use the MPFR rounding specifier to round down in the first
1998 iteration and then up. In most but not all cases this will
1999 result in the same number of bytes. */
2000 char rndspec = "DU"[i];
2002 /* Format it and store the result in the corresponding member
2003 of the result struct. */
2004 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
2005 dir.specifier, rndspec);
2006 mpfr_clear (mpfrval);
2010 /* Make sure the minimum is less than the maximum (MPFR rounding
2011 in the call to mpfr_snprintf can result in the reverse. */
2012 if (res.range.max < res.range.min)
2014 unsigned HOST_WIDE_INT tmp = res.range.min;
2015 res.range.min = res.range.max;
2016 res.range.max = tmp;
2019 /* The range is known unless either width or precision is unknown. */
2020 res.knownrange = dir.known_width_and_precision ();
2022 /* For the same floating point constant, unless width or precision
2023 is unknown, use the longer output as the likely maximum since
2024 with round to nearest either is equally likely. Otheriwse, when
2025 precision is unknown, use the greater of the minimum and 3 as
2026 the likely output (for "0.0" since zero precision is unlikely). */
2027 if (res.knownrange)
2028 res.range.likely = res.range.max;
2029 else if (res.range.min < 3
2030 && dir.prec[0] < 0
2031 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
2032 res.range.likely = 3;
2033 else
2034 res.range.likely = res.range.min;
2036 res.range.unlikely = res.range.max;
2038 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
2040 /* Unless the precision is zero output longer than 2 bytes may
2041 include the decimal point which must be a single character
2042 up to MB_LEN_MAX in length. This is overly conservative
2043 since in some conversions some constants result in no decimal
2044 point (e.g., in %g). */
2045 res.range.unlikely += target_mb_len_max () - 1;
2048 res.adjust_for_width_or_precision (dir.width);
2049 return res;
2052 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
2053 strings referenced by the expression STR, or (-1, -1) when not known.
2054 Used by the format_string function below. */
2056 static fmtresult
2057 get_string_length (tree str)
2059 if (!str)
2060 return fmtresult ();
2062 if (tree slen = c_strlen (str, 1))
2064 /* Simply return the length of the string. */
2065 fmtresult res (tree_to_shwi (slen));
2066 return res;
2069 /* Determine the length of the shortest and longest string referenced
2070 by STR. Strings of unknown lengths are bounded by the sizes of
2071 arrays that subexpressions of STR may refer to. Pointers that
2072 aren't known to point any such arrays result in LENRANGE[1] set
2073 to SIZE_MAX. */
2074 tree lenrange[2];
2075 bool flexarray = get_range_strlen (str, lenrange);
2077 if (lenrange [0] || lenrange [1])
2079 HOST_WIDE_INT min
2080 = (tree_fits_uhwi_p (lenrange[0])
2081 ? tree_to_uhwi (lenrange[0])
2082 : 0);
2084 HOST_WIDE_INT max
2085 = (tree_fits_uhwi_p (lenrange[1])
2086 ? tree_to_uhwi (lenrange[1])
2087 : HOST_WIDE_INT_M1U);
2089 /* get_range_strlen() returns the target value of SIZE_MAX for
2090 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2091 which may be bigger. */
2092 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2093 min = HOST_WIDE_INT_M1U;
2094 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2095 max = HOST_WIDE_INT_M1U;
2097 fmtresult res (min, max);
2099 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2100 by STR are known to be bounded (though not necessarily by their
2101 actual length but perhaps by their maximum possible length). */
2102 if (res.range.max < target_int_max ())
2104 res.knownrange = true;
2105 /* When the the length of the longest string is known and not
2106 excessive use it as the likely length of the string(s). */
2107 res.range.likely = res.range.max;
2109 else
2111 /* When the upper bound is unknown (it can be zero or excessive)
2112 set the likely length to the greater of 1 and the length of
2113 the shortest string and reset the lower bound to zero. */
2114 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2115 res.range.min = 0;
2118 /* If the range of string length has been estimated from the size
2119 of an array at the end of a struct assume that it's longer than
2120 the array bound says it is in case it's used as a poor man's
2121 flexible array member, such as in struct S { char a[4]; }; */
2122 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
2124 return res;
2127 return get_string_length (NULL_TREE);
2130 /* Return the minimum and maximum number of characters formatted
2131 by the '%c' format directives and its wide character form for
2132 the argument ARG. ARG can be null (for functions such as
2133 vsprinf). */
2135 static fmtresult
2136 format_character (const directive &dir, tree arg, vr_values *vr_values)
2138 fmtresult res;
2140 res.knownrange = true;
2142 if (dir.modifier == FMT_LEN_l)
2144 /* A wide character can result in as few as zero bytes. */
2145 res.range.min = 0;
2147 HOST_WIDE_INT min, max;
2148 if (get_int_range (arg, &min, &max, false, 0, vr_values))
2150 if (min == 0 && max == 0)
2152 /* The NUL wide character results in no bytes. */
2153 res.range.max = 0;
2154 res.range.likely = 0;
2155 res.range.unlikely = 0;
2157 else if (min > 0 && min < 128)
2159 /* A wide character in the ASCII range most likely results
2160 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2161 res.range.max = 1;
2162 res.range.likely = 1;
2163 res.range.unlikely = target_mb_len_max ();
2165 else
2167 /* A wide character outside the ASCII range likely results
2168 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2169 res.range.max = target_mb_len_max ();
2170 res.range.likely = 2;
2171 res.range.unlikely = res.range.max;
2174 else
2176 /* An unknown wide character is treated the same as a wide
2177 character outside the ASCII range. */
2178 res.range.max = target_mb_len_max ();
2179 res.range.likely = 2;
2180 res.range.unlikely = res.range.max;
2183 else
2185 /* A plain '%c' directive. Its ouput is exactly 1. */
2186 res.range.min = res.range.max = 1;
2187 res.range.likely = res.range.unlikely = 1;
2188 res.knownrange = true;
2191 /* Bump up the byte counters if WIDTH is greater. */
2192 return res.adjust_for_width_or_precision (dir.width);
2195 /* Return the minimum and maximum number of characters formatted
2196 by the '%s' format directive and its wide character form for
2197 the argument ARG. ARG can be null (for functions such as
2198 vsprinf). */
2200 static fmtresult
2201 format_string (const directive &dir, tree arg, vr_values *)
2203 fmtresult res;
2205 /* Compute the range the argument's length can be in. */
2206 fmtresult slen = get_string_length (arg);
2207 if (slen.range.min == slen.range.max
2208 && slen.range.min < HOST_WIDE_INT_MAX)
2210 /* The argument is either a string constant or it refers
2211 to one of a number of strings of the same length. */
2213 /* A '%s' directive with a string argument with constant length. */
2214 res.range = slen.range;
2216 if (dir.modifier == FMT_LEN_l)
2218 /* In the worst case the length of output of a wide string S
2219 is bounded by MB_LEN_MAX * wcslen (S). */
2220 res.range.max *= target_mb_len_max ();
2221 res.range.unlikely = res.range.max;
2222 /* It's likely that the the total length is not more that
2223 2 * wcslen (S).*/
2224 res.range.likely = res.range.min * 2;
2226 if (dir.prec[1] >= 0
2227 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2229 res.range.max = dir.prec[1];
2230 res.range.likely = dir.prec[1];
2231 res.range.unlikely = dir.prec[1];
2234 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2235 res.range.min = 0;
2236 else if (dir.prec[0] >= 0)
2237 res.range.likely = dir.prec[0];
2239 /* Even a non-empty wide character string need not convert into
2240 any bytes. */
2241 res.range.min = 0;
2243 else
2245 res.knownrange = true;
2247 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2248 res.range.min = 0;
2249 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2250 res.range.min = dir.prec[0];
2252 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2254 res.range.max = dir.prec[1];
2255 res.range.likely = dir.prec[1];
2256 res.range.unlikely = dir.prec[1];
2260 else if (arg && integer_zerop (arg))
2262 /* Handle null pointer argument. */
2264 fmtresult res (0);
2265 res.nullp = true;
2266 return res;
2268 else
2270 /* For a '%s' and '%ls' directive with a non-constant string (either
2271 one of a number of strings of known length or an unknown string)
2272 the minimum number of characters is lesser of PRECISION[0] and
2273 the length of the shortest known string or zero, and the maximum
2274 is the lessser of the length of the longest known string or
2275 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2276 the minimum at level 1 and the greater of the minimum and 1
2277 at level 2. This result is adjust upward for width (if it's
2278 specified). */
2280 if (dir.modifier == FMT_LEN_l)
2282 /* A wide character converts to as few as zero bytes. */
2283 slen.range.min = 0;
2284 if (slen.range.max < target_int_max ())
2285 slen.range.max *= target_mb_len_max ();
2287 if (slen.range.likely < target_int_max ())
2288 slen.range.likely *= 2;
2290 if (slen.range.likely < target_int_max ())
2291 slen.range.unlikely *= target_mb_len_max ();
2294 res.range = slen.range;
2296 if (dir.prec[0] >= 0)
2298 /* Adjust the minimum to zero if the string length is unknown,
2299 or at most the lower bound of the precision otherwise. */
2300 if (slen.range.min >= target_int_max ())
2301 res.range.min = 0;
2302 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2303 res.range.min = dir.prec[0];
2305 /* Make both maxima no greater than the upper bound of precision. */
2306 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2307 || slen.range.max >= target_int_max ())
2309 res.range.max = dir.prec[1];
2310 res.range.unlikely = dir.prec[1];
2313 /* If precision is constant, set the likely counter to the lesser
2314 of it and the maximum string length. Otherwise, if the lower
2315 bound of precision is greater than zero, set the likely counter
2316 to the minimum. Otherwise set it to zero or one based on
2317 the warning level. */
2318 if (dir.prec[0] == dir.prec[1])
2319 res.range.likely
2320 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2321 ? dir.prec[0] : slen.range.max);
2322 else if (dir.prec[0] > 0)
2323 res.range.likely = res.range.min;
2324 else
2325 res.range.likely = warn_level > 1;
2327 else if (dir.prec[1] >= 0)
2329 res.range.min = 0;
2330 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2331 res.range.max = dir.prec[1];
2332 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2334 else if (slen.range.min >= target_int_max ())
2336 res.range.min = 0;
2337 res.range.max = HOST_WIDE_INT_MAX;
2338 /* At level 1 strings of unknown length are assumed to be
2339 empty, while at level 1 they are assumed to be one byte
2340 long. */
2341 res.range.likely = warn_level > 1;
2343 else
2345 /* A string of unknown length unconstrained by precision is
2346 assumed to be empty at level 1 and just one character long
2347 at higher levels. */
2348 if (res.range.likely >= target_int_max ())
2349 res.range.likely = warn_level > 1;
2352 res.range.unlikely = res.range.max;
2355 /* Bump up the byte counters if WIDTH is greater. */
2356 return res.adjust_for_width_or_precision (dir.width);
2359 /* Format plain string (part of the format string itself). */
2361 static fmtresult
2362 format_plain (const directive &dir, tree, vr_values *)
2364 fmtresult res (dir.len);
2365 return res;
2368 /* Return true if the RESULT of a directive in a call describe by INFO
2369 should be diagnosed given the AVAILable space in the destination. */
2371 static bool
2372 should_warn_p (const sprintf_dom_walker::call_info &info,
2373 const result_range &avail, const result_range &result)
2375 if (result.max <= avail.min)
2377 /* The least amount of space remaining in the destination is big
2378 enough for the longest output. */
2379 return false;
2382 if (info.bounded)
2384 if (warn_format_trunc == 1 && result.min <= avail.max
2385 && info.retval_used ())
2387 /* The likely amount of space remaining in the destination is big
2388 enough for the least output and the return value is used. */
2389 return false;
2392 if (warn_format_trunc == 1 && result.likely <= avail.likely
2393 && !info.retval_used ())
2395 /* The likely amount of space remaining in the destination is big
2396 enough for the likely output and the return value is unused. */
2397 return false;
2400 if (warn_format_trunc == 2
2401 && result.likely <= avail.min
2402 && (result.max <= avail.min
2403 || result.max > HOST_WIDE_INT_MAX))
2405 /* The minimum amount of space remaining in the destination is big
2406 enough for the longest output. */
2407 return false;
2410 else
2412 if (warn_level == 1 && result.likely <= avail.likely)
2414 /* The likely amount of space remaining in the destination is big
2415 enough for the likely output. */
2416 return false;
2419 if (warn_level == 2
2420 && result.likely <= avail.min
2421 && (result.max <= avail.min
2422 || result.max > HOST_WIDE_INT_MAX))
2424 /* The minimum amount of space remaining in the destination is big
2425 enough for the longest output. */
2426 return false;
2430 return true;
2433 /* At format string location describe by DIRLOC in a call described
2434 by INFO, issue a warning for a directive DIR whose output may be
2435 in excess of the available space AVAIL_RANGE in the destination
2436 given the formatting result FMTRES. This function does nothing
2437 except decide whether to issue a warning for a possible write
2438 past the end or truncation and, if so, format the warning.
2439 Return true if a warning has been issued. */
2441 static bool
2442 maybe_warn (substring_loc &dirloc, location_t argloc,
2443 const sprintf_dom_walker::call_info &info,
2444 const result_range &avail_range, const result_range &res,
2445 const directive &dir)
2447 if (!should_warn_p (info, avail_range, res))
2448 return false;
2450 /* A warning will definitely be issued below. */
2452 /* The maximum byte count to reference in the warning. Larger counts
2453 imply that the upper bound is unknown (and could be anywhere between
2454 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2455 than "between N and X" where X is some huge number. */
2456 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2458 /* True when there is enough room in the destination for the least
2459 amount of a directive's output but not enough for its likely or
2460 maximum output. */
2461 bool maybe = (res.min <= avail_range.max
2462 && (avail_range.min < res.likely
2463 || (res.max < HOST_WIDE_INT_MAX
2464 && avail_range.min < res.max)));
2466 /* Buffer for the directive in the host character set (used when
2467 the source character set is different). */
2468 char hostdir[32];
2470 if (avail_range.min == avail_range.max)
2472 /* The size of the destination region is exact. */
2473 unsigned HOST_WIDE_INT navail = avail_range.max;
2475 if (target_to_host (*dir.beg) != '%')
2477 /* For plain character directives (i.e., the format string itself)
2478 but not others, point the caret at the first character that's
2479 past the end of the destination. */
2480 if (navail < dir.len)
2481 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2484 if (*dir.beg == '\0')
2486 /* This is the terminating nul. */
2487 gcc_assert (res.min == 1 && res.min == res.max);
2489 const char *fmtstr
2490 = (info.bounded
2491 ? (maybe
2492 ? G_("%qE output may be truncated before the last format "
2493 "character")
2494 : G_("%qE output truncated before the last format character"))
2495 : (maybe
2496 ? G_("%qE may write a terminating nul past the end "
2497 "of the destination")
2498 : G_("%qE writing a terminating nul past the end "
2499 "of the destination")));
2501 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2502 fmtstr, info.func);
2505 if (res.min == res.max)
2507 const char* fmtstr
2508 = (res.min == 1
2509 ? (info.bounded
2510 ? (maybe
2511 ? G_("%<%.*s%> directive output may be truncated writing "
2512 "%wu byte into a region of size %wu")
2513 : G_("%<%.*s%> directive output truncated writing "
2514 "%wu byte into a region of size %wu"))
2515 : G_("%<%.*s%> directive writing %wu byte "
2516 "into a region of size %wu"))
2517 : (info.bounded
2518 ? (maybe
2519 ? G_("%<%.*s%> directive output may be truncated writing "
2520 "%wu bytes into a region of size %wu")
2521 : G_("%<%.*s%> directive output truncated writing "
2522 "%wu bytes into a region of size %wu"))
2523 : G_("%<%.*s%> directive writing %wu bytes "
2524 "into a region of size %wu")));
2525 return fmtwarn (dirloc, argloc, NULL,
2526 info.warnopt (), fmtstr, dir.len,
2527 target_to_host (hostdir, sizeof hostdir, dir.beg),
2528 res.min, navail);
2531 if (res.min == 0 && res.max < maxbytes)
2533 const char* fmtstr
2534 = (info.bounded
2535 ? (maybe
2536 ? G_("%<%.*s%> directive output may be truncated writing "
2537 "up to %wu bytes into a region of size %wu")
2538 : G_("%<%.*s%> directive output truncated writing "
2539 "up to %wu bytes into a region of size %wu"))
2540 : G_("%<%.*s%> directive writing up to %wu bytes "
2541 "into a region of size %wu"));
2542 return fmtwarn (dirloc, argloc, NULL,
2543 info.warnopt (), fmtstr, dir.len,
2544 target_to_host (hostdir, sizeof hostdir, dir.beg),
2545 res.max, navail);
2548 if (res.min == 0 && maxbytes <= res.max)
2550 /* This is a special case to avoid issuing the potentially
2551 confusing warning:
2552 writing 0 or more bytes into a region of size 0. */
2553 const char* fmtstr
2554 = (info.bounded
2555 ? (maybe
2556 ? G_("%<%.*s%> directive output may be truncated writing "
2557 "likely %wu or more bytes into a region of size %wu")
2558 : G_("%<%.*s%> directive output truncated writing "
2559 "likely %wu or more bytes into a region of size %wu"))
2560 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2561 "into a region of size %wu"));
2562 return fmtwarn (dirloc, argloc, NULL,
2563 info.warnopt (), fmtstr, dir.len,
2564 target_to_host (hostdir, sizeof hostdir, dir.beg),
2565 res.likely, navail);
2568 if (res.max < maxbytes)
2570 const char* fmtstr
2571 = (info.bounded
2572 ? (maybe
2573 ? G_("%<%.*s%> directive output may be truncated writing "
2574 "between %wu and %wu bytes into a region of size %wu")
2575 : G_("%<%.*s%> directive output truncated writing "
2576 "between %wu and %wu bytes into a region of size %wu"))
2577 : G_("%<%.*s%> directive writing between %wu and "
2578 "%wu bytes into a region of size %wu"));
2579 return fmtwarn (dirloc, argloc, NULL,
2580 info.warnopt (), fmtstr, dir.len,
2581 target_to_host (hostdir, sizeof hostdir, dir.beg),
2582 res.min, res.max, navail);
2585 const char* fmtstr
2586 = (info.bounded
2587 ? (maybe
2588 ? G_("%<%.*s%> directive output may be truncated writing "
2589 "%wu or more bytes into a region of size %wu")
2590 : G_("%<%.*s%> directive output truncated writing "
2591 "%wu or more bytes into a region of size %wu"))
2592 : G_("%<%.*s%> directive writing %wu or more bytes "
2593 "into a region of size %wu"));
2594 return fmtwarn (dirloc, argloc, NULL,
2595 info.warnopt (), fmtstr, dir.len,
2596 target_to_host (hostdir, sizeof hostdir, dir.beg),
2597 res.min, navail);
2600 /* The size of the destination region is a range. */
2602 if (target_to_host (*dir.beg) != '%')
2604 unsigned HOST_WIDE_INT navail = avail_range.max;
2606 /* For plain character directives (i.e., the format string itself)
2607 but not others, point the caret at the first character that's
2608 past the end of the destination. */
2609 if (navail < dir.len)
2610 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2613 if (*dir.beg == '\0')
2615 gcc_assert (res.min == 1 && res.min == res.max);
2617 const char *fmtstr
2618 = (info.bounded
2619 ? (maybe
2620 ? G_("%qE output may be truncated before the last format "
2621 "character")
2622 : G_("%qE output truncated before the last format character"))
2623 : (maybe
2624 ? G_("%qE may write a terminating nul past the end "
2625 "of the destination")
2626 : G_("%qE writing a terminating nul past the end "
2627 "of the destination")));
2629 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (), fmtstr,
2630 info.func);
2633 if (res.min == res.max)
2635 const char* fmtstr
2636 = (res.min == 1
2637 ? (info.bounded
2638 ? (maybe
2639 ? G_("%<%.*s%> directive output may be truncated writing "
2640 "%wu byte into a region of size between %wu and %wu")
2641 : G_("%<%.*s%> directive output truncated writing "
2642 "%wu byte into a region of size between %wu and %wu"))
2643 : G_("%<%.*s%> directive writing %wu byte "
2644 "into a region of size between %wu and %wu"))
2645 : (info.bounded
2646 ? (maybe
2647 ? G_("%<%.*s%> directive output may be truncated writing "
2648 "%wu bytes into a region of size between %wu and %wu")
2649 : G_("%<%.*s%> directive output truncated writing "
2650 "%wu bytes into a region of size between %wu and %wu"))
2651 : G_("%<%.*s%> directive writing %wu bytes "
2652 "into a region of size between %wu and %wu")));
2654 return fmtwarn (dirloc, argloc, NULL,
2655 info.warnopt (), fmtstr, dir.len,
2656 target_to_host (hostdir, sizeof hostdir, dir.beg),
2657 res.min, avail_range.min, avail_range.max);
2660 if (res.min == 0 && res.max < maxbytes)
2662 const char* fmtstr
2663 = (info.bounded
2664 ? (maybe
2665 ? G_("%<%.*s%> directive output may be truncated writing "
2666 "up to %wu bytes into a region of size between "
2667 "%wu and %wu")
2668 : G_("%<%.*s%> directive output truncated writing "
2669 "up to %wu bytes into a region of size between "
2670 "%wu and %wu"))
2671 : G_("%<%.*s%> directive writing up to %wu bytes "
2672 "into a region of size between %wu and %wu"));
2673 return fmtwarn (dirloc, argloc, NULL,
2674 info.warnopt (), fmtstr, dir.len,
2675 target_to_host (hostdir, sizeof hostdir, dir.beg),
2676 res.max, avail_range.min, avail_range.max);
2679 if (res.min == 0 && maxbytes <= res.max)
2681 /* This is a special case to avoid issuing the potentially confusing
2682 warning:
2683 writing 0 or more bytes into a region of size between 0 and N. */
2684 const char* fmtstr
2685 = (info.bounded
2686 ? (maybe
2687 ? G_("%<%.*s%> directive output may be truncated writing "
2688 "likely %wu or more bytes into a region of size between "
2689 "%wu and %wu")
2690 : G_("%<%.*s%> directive output truncated writing likely "
2691 "%wu or more bytes into a region of size between "
2692 "%wu and %wu"))
2693 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2694 "into a region of size between %wu and %wu"));
2695 return fmtwarn (dirloc, argloc, NULL,
2696 info.warnopt (), fmtstr, dir.len,
2697 target_to_host (hostdir, sizeof hostdir, dir.beg),
2698 res.likely, avail_range.min, avail_range.max);
2701 if (res.max < maxbytes)
2703 const char* fmtstr
2704 = (info.bounded
2705 ? (maybe
2706 ? G_("%<%.*s%> directive output may be truncated writing "
2707 "between %wu and %wu bytes into a region of size "
2708 "between %wu and %wu")
2709 : G_("%<%.*s%> directive output truncated writing "
2710 "between %wu and %wu bytes into a region of size "
2711 "between %wu and %wu"))
2712 : G_("%<%.*s%> directive writing between %wu and "
2713 "%wu bytes into a region of size between %wu and %wu"));
2714 return fmtwarn (dirloc, argloc, NULL,
2715 info.warnopt (), fmtstr, dir.len,
2716 target_to_host (hostdir, sizeof hostdir, dir.beg),
2717 res.min, res.max, avail_range.min, avail_range.max);
2720 const char* fmtstr
2721 = (info.bounded
2722 ? (maybe
2723 ? G_("%<%.*s%> directive output may be truncated writing "
2724 "%wu or more bytes into a region of size between "
2725 "%wu and %wu")
2726 : G_("%<%.*s%> directive output truncated writing "
2727 "%wu or more bytes into a region of size between "
2728 "%wu and %wu"))
2729 : G_("%<%.*s%> directive writing %wu or more bytes "
2730 "into a region of size between %wu and %wu"));
2731 return fmtwarn (dirloc, argloc, NULL,
2732 info.warnopt (), fmtstr, dir.len,
2733 target_to_host (hostdir, sizeof hostdir, dir.beg),
2734 res.min, avail_range.min, avail_range.max);
2737 /* Compute the length of the output resulting from the directive DIR
2738 in a call described by INFO and update the overall result of the call
2739 in *RES. Return true if the directive has been handled. */
2741 static bool
2742 format_directive (const sprintf_dom_walker::call_info &info,
2743 format_result *res, const directive &dir,
2744 class vr_values *vr_values)
2746 /* Offset of the beginning of the directive from the beginning
2747 of the format string. */
2748 size_t offset = dir.beg - info.fmtstr;
2749 size_t start = offset;
2750 size_t length = offset + dir.len - !!dir.len;
2752 /* Create a location for the whole directive from the % to the format
2753 specifier. */
2754 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2755 offset, start, length);
2757 /* Also get the location of the argument if possible.
2758 This doesn't work for integer literals or function calls. */
2759 location_t argloc = UNKNOWN_LOCATION;
2760 if (dir.arg)
2761 argloc = EXPR_LOCATION (dir.arg);
2763 /* Bail when there is no function to compute the output length,
2764 or when minimum length checking has been disabled. */
2765 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2766 return false;
2768 /* Compute the range of lengths of the formatted output. */
2769 fmtresult fmtres = dir.fmtfunc (dir, dir.arg, vr_values);
2771 /* Record whether the output of all directives is known to be
2772 bounded by some maximum, implying that their arguments are
2773 either known exactly or determined to be in a known range
2774 or, for strings, limited by the upper bounds of the arrays
2775 they refer to. */
2776 res->knownrange &= fmtres.knownrange;
2778 if (!fmtres.knownrange)
2780 /* Only when the range is known, check it against the host value
2781 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2782 INT_MAX precision, which is the longest possible output of any
2783 single directive). That's the largest valid byte count (though
2784 not valid call to a printf-like function because it can never
2785 return such a count). Otherwise, the range doesn't correspond
2786 to known values of the argument. */
2787 if (fmtres.range.max > target_dir_max ())
2789 /* Normalize the MAX counter to avoid having to deal with it
2790 later. The counter can be less than HOST_WIDE_INT_M1U
2791 when compiling for an ILP32 target on an LP64 host. */
2792 fmtres.range.max = HOST_WIDE_INT_M1U;
2793 /* Disable exact and maximum length checking after a failure
2794 to determine the maximum number of characters (for example
2795 for wide characters or wide character strings) but continue
2796 tracking the minimum number of characters. */
2797 res->range.max = HOST_WIDE_INT_M1U;
2800 if (fmtres.range.min > target_dir_max ())
2802 /* Disable exact length checking after a failure to determine
2803 even the minimum number of characters (it shouldn't happen
2804 except in an error) but keep tracking the minimum and maximum
2805 number of characters. */
2806 return true;
2810 /* Buffer for the directive in the host character set (used when
2811 the source character set is different). */
2812 char hostdir[32];
2814 int dirlen = dir.len;
2816 if (fmtres.nullp)
2818 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2819 "%<%.*s%> directive argument is null",
2820 dirlen, target_to_host (hostdir, sizeof hostdir, dir.beg));
2822 /* Don't bother processing the rest of the format string. */
2823 res->warned = true;
2824 res->range.min = HOST_WIDE_INT_M1U;
2825 res->range.max = HOST_WIDE_INT_M1U;
2826 return false;
2829 /* Compute the number of available bytes in the destination. There
2830 must always be at least one byte of space for the terminating
2831 NUL that's appended after the format string has been processed. */
2832 result_range avail_range = bytes_remaining (info.objsize, *res);
2834 bool warned = res->warned;
2836 if (!warned)
2837 warned = maybe_warn (dirloc, argloc, info, avail_range,
2838 fmtres.range, dir);
2840 /* Bump up the total maximum if it isn't too big. */
2841 if (res->range.max < HOST_WIDE_INT_MAX
2842 && fmtres.range.max < HOST_WIDE_INT_MAX)
2843 res->range.max += fmtres.range.max;
2845 /* Raise the total unlikely maximum by the larger of the maximum
2846 and the unlikely maximum. */
2847 unsigned HOST_WIDE_INT save = res->range.unlikely;
2848 if (fmtres.range.max < fmtres.range.unlikely)
2849 res->range.unlikely += fmtres.range.unlikely;
2850 else
2851 res->range.unlikely += fmtres.range.max;
2853 if (res->range.unlikely < save)
2854 res->range.unlikely = HOST_WIDE_INT_M1U;
2856 res->range.min += fmtres.range.min;
2857 res->range.likely += fmtres.range.likely;
2859 /* Has the minimum directive output length exceeded the maximum
2860 of 4095 bytes required to be supported? */
2861 bool minunder4k = fmtres.range.min < 4096;
2862 bool maxunder4k = fmtres.range.max < 4096;
2863 /* Clear UNDER4K in the overall result if the maximum has exceeded
2864 the 4k (this is necessary to avoid the return valuye optimization
2865 that may not be safe in the maximum case). */
2866 if (!maxunder4k)
2867 res->under4k = false;
2869 if (!warned
2870 /* Only warn at level 2. */
2871 && warn_level > 1
2872 && (!minunder4k
2873 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2875 /* The directive output may be longer than the maximum required
2876 to be handled by an implementation according to 7.21.6.1, p15
2877 of C11. Warn on this only at level 2 but remember this and
2878 prevent folding the return value when done. This allows for
2879 the possibility of the actual libc call failing due to ENOMEM
2880 (like Glibc does under some conditions). */
2882 if (fmtres.range.min == fmtres.range.max)
2883 warned = fmtwarn (dirloc, argloc, NULL,
2884 info.warnopt (),
2885 "%<%.*s%> directive output of %wu bytes exceeds "
2886 "minimum required size of 4095",
2887 dirlen,
2888 target_to_host (hostdir, sizeof hostdir, dir.beg),
2889 fmtres.range.min);
2890 else
2892 const char *fmtstr
2893 = (minunder4k
2894 ? G_("%<%.*s%> directive output between %wu and %wu "
2895 "bytes may exceed minimum required size of 4095")
2896 : G_("%<%.*s%> directive output between %wu and %wu "
2897 "bytes exceeds minimum required size of 4095"));
2899 warned = fmtwarn (dirloc, argloc, NULL,
2900 info.warnopt (), fmtstr, dirlen,
2901 target_to_host (hostdir, sizeof hostdir, dir.beg),
2902 fmtres.range.min, fmtres.range.max);
2906 /* Has the likely and maximum directive output exceeded INT_MAX? */
2907 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2908 /* Don't consider the maximum to be in excess when it's the result
2909 of a string of unknown length (i.e., whose maximum has been set
2910 to be greater than or equal to HOST_WIDE_INT_MAX. */
2911 bool maxximax = (*dir.beg
2912 && res->range.max > target_int_max ()
2913 && res->range.max < HOST_WIDE_INT_MAX);
2915 if (!warned
2916 /* Warn for the likely output size at level 1. */
2917 && (likelyximax
2918 /* But only warn for the maximum at level 2. */
2919 || (warn_level > 1
2920 && maxximax
2921 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2923 /* The directive output causes the total length of output
2924 to exceed INT_MAX bytes. */
2926 if (fmtres.range.min == fmtres.range.max)
2927 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2928 "%<%.*s%> directive output of %wu bytes causes "
2929 "result to exceed %<INT_MAX%>",
2930 dirlen,
2931 target_to_host (hostdir, sizeof hostdir, dir.beg),
2932 fmtres.range.min);
2933 else
2935 const char *fmtstr
2936 = (fmtres.range.min > target_int_max ()
2937 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2938 "bytes causes result to exceed %<INT_MAX%>")
2939 : G_ ("%<%.*s%> directive output between %wu and %wu "
2940 "bytes may cause result to exceed %<INT_MAX%>"));
2941 warned = fmtwarn (dirloc, argloc, NULL,
2942 info.warnopt (), fmtstr, dirlen,
2943 target_to_host (hostdir, sizeof hostdir, dir.beg),
2944 fmtres.range.min, fmtres.range.max);
2948 if (warned && fmtres.range.min < fmtres.range.likely
2949 && fmtres.range.likely < fmtres.range.max)
2950 /* Some languages have special plural rules even for large values,
2951 but it is periodic with period of 10, 100, 1000 etc. */
2952 inform_n (info.fmtloc,
2953 fmtres.range.likely > INT_MAX
2954 ? (fmtres.range.likely % 1000000) + 1000000
2955 : fmtres.range.likely,
2956 "assuming directive output of %wu byte",
2957 "assuming directive output of %wu bytes",
2958 fmtres.range.likely);
2960 if (warned && fmtres.argmin)
2962 if (fmtres.argmin == fmtres.argmax)
2963 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2964 else if (fmtres.knownrange)
2965 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2966 fmtres.argmin, fmtres.argmax);
2967 else
2968 inform (info.fmtloc,
2969 "using the range [%E, %E] for directive argument",
2970 fmtres.argmin, fmtres.argmax);
2973 res->warned |= warned;
2975 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2977 /* If a warning has been issued for buffer overflow or truncation
2978 (but not otherwise) help the user figure out how big a buffer
2979 they need. */
2981 location_t callloc = gimple_location (info.callstmt);
2983 unsigned HOST_WIDE_INT min = res->range.min;
2984 unsigned HOST_WIDE_INT max = res->range.max;
2986 if (min == max)
2987 inform (callloc,
2988 (min == 1
2989 ? G_("%qE output %wu byte into a destination of size %wu")
2990 : G_("%qE output %wu bytes into a destination of size %wu")),
2991 info.func, min, info.objsize);
2992 else if (max < HOST_WIDE_INT_MAX)
2993 inform (callloc,
2994 "%qE output between %wu and %wu bytes into "
2995 "a destination of size %wu",
2996 info.func, min, max, info.objsize);
2997 else if (min < res->range.likely && res->range.likely < max)
2998 inform (callloc,
2999 "%qE output %wu or more bytes (assuming %wu) into "
3000 "a destination of size %wu",
3001 info.func, min, res->range.likely, info.objsize);
3002 else
3003 inform (callloc,
3004 "%qE output %wu or more bytes into a destination of size %wu",
3005 info.func, min, info.objsize);
3008 if (dump_file && *dir.beg)
3010 fprintf (dump_file,
3011 " Result: "
3012 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3013 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
3014 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3015 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
3016 fmtres.range.min, fmtres.range.likely,
3017 fmtres.range.max, fmtres.range.unlikely,
3018 res->range.min, res->range.likely,
3019 res->range.max, res->range.unlikely);
3022 return true;
3025 #pragma GCC diagnostic pop
3027 /* Parse a format directive in function call described by INFO starting
3028 at STR and populate DIR structure. Bump up *ARGNO by the number of
3029 arguments extracted for the directive. Return the length of
3030 the directive. */
3032 static size_t
3033 parse_directive (sprintf_dom_walker::call_info &info,
3034 directive &dir, format_result *res,
3035 const char *str, unsigned *argno,
3036 vr_values *vr_values)
3038 const char *pcnt = strchr (str, target_percent);
3039 dir.beg = str;
3041 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
3043 /* This directive is either a plain string or the terminating nul
3044 (which isn't really a directive but it simplifies things to
3045 handle it as if it were). */
3046 dir.len = len;
3047 dir.fmtfunc = format_plain;
3049 if (dump_file)
3051 fprintf (dump_file, " Directive %u at offset "
3052 HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
3053 "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
3054 dir.dirno,
3055 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3056 (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
3059 return len - !*str;
3062 const char *pf = pcnt + 1;
3064 /* POSIX numbered argument index or zero when none. */
3065 HOST_WIDE_INT dollar = 0;
3067 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3068 when given by a va_list argument, and a non-negative value
3069 when specified in the format string itself. */
3070 HOST_WIDE_INT width = -1;
3071 HOST_WIDE_INT precision = -1;
3073 /* Pointers to the beginning of the width and precision decimal
3074 string (if any) within the directive. */
3075 const char *pwidth = 0;
3076 const char *pprec = 0;
3078 /* When the value of the decimal string that specifies width or
3079 precision is out of range, points to the digit that causes
3080 the value to exceed the limit. */
3081 const char *werange = NULL;
3082 const char *perange = NULL;
3084 /* Width specified via the asterisk. Need not be INTEGER_CST.
3085 For vararg functions set to void_node. */
3086 tree star_width = NULL_TREE;
3088 /* Width specified via the asterisk. Need not be INTEGER_CST.
3089 For vararg functions set to void_node. */
3090 tree star_precision = NULL_TREE;
3092 if (ISDIGIT (target_to_host (*pf)))
3094 /* This could be either a POSIX positional argument, the '0'
3095 flag, or a width, depending on what follows. Store it as
3096 width and sort it out later after the next character has
3097 been seen. */
3098 pwidth = pf;
3099 width = target_strtol10 (&pf, &werange);
3101 else if (target_to_host (*pf) == '*')
3103 /* Similarly to the block above, this could be either a POSIX
3104 positional argument or a width, depending on what follows. */
3105 if (*argno < gimple_call_num_args (info.callstmt))
3106 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3107 else
3108 star_width = void_node;
3109 ++pf;
3112 if (target_to_host (*pf) == '$')
3114 /* Handle the POSIX dollar sign which references the 1-based
3115 positional argument number. */
3116 if (width != -1)
3117 dollar = width + info.argidx;
3118 else if (star_width
3119 && TREE_CODE (star_width) == INTEGER_CST
3120 && (TYPE_PRECISION (TREE_TYPE (star_width))
3121 <= TYPE_PRECISION (integer_type_node)))
3122 dollar = width + tree_to_shwi (star_width);
3124 /* Bail when the numbered argument is out of range (it will
3125 have already been diagnosed by -Wformat). */
3126 if (dollar == 0
3127 || dollar == (int)info.argidx
3128 || dollar > gimple_call_num_args (info.callstmt))
3129 return false;
3131 --dollar;
3133 star_width = NULL_TREE;
3134 width = -1;
3135 ++pf;
3138 if (dollar || !star_width)
3140 if (width != -1)
3142 if (width == 0)
3144 /* The '0' that has been interpreted as a width above is
3145 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3146 and continue processing other flags. */
3147 width = -1;
3148 dir.set_flag ('0');
3150 else if (!dollar)
3152 /* (Non-zero) width has been seen. The next character
3153 is either a period or a digit. */
3154 goto start_precision;
3157 /* When either '$' has been seen, or width has not been seen,
3158 the next field is the optional flags followed by an optional
3159 width. */
3160 for ( ; ; ) {
3161 switch (target_to_host (*pf))
3163 case ' ':
3164 case '0':
3165 case '+':
3166 case '-':
3167 case '#':
3168 dir.set_flag (target_to_host (*pf++));
3169 break;
3171 default:
3172 goto start_width;
3176 start_width:
3177 if (ISDIGIT (target_to_host (*pf)))
3179 werange = 0;
3180 pwidth = pf;
3181 width = target_strtol10 (&pf, &werange);
3183 else if (target_to_host (*pf) == '*')
3185 if (*argno < gimple_call_num_args (info.callstmt))
3186 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3187 else
3189 /* This is (likely) a va_list. It could also be an invalid
3190 call with insufficient arguments. */
3191 star_width = void_node;
3193 ++pf;
3195 else if (target_to_host (*pf) == '\'')
3197 /* The POSIX apostrophe indicating a numeric grouping
3198 in the current locale. Even though it's possible to
3199 estimate the upper bound on the size of the output
3200 based on the number of digits it probably isn't worth
3201 continuing. */
3202 return 0;
3206 start_precision:
3207 if (target_to_host (*pf) == '.')
3209 ++pf;
3211 if (ISDIGIT (target_to_host (*pf)))
3213 pprec = pf;
3214 precision = target_strtol10 (&pf, &perange);
3216 else if (target_to_host (*pf) == '*')
3218 if (*argno < gimple_call_num_args (info.callstmt))
3219 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3220 else
3222 /* This is (likely) a va_list. It could also be an invalid
3223 call with insufficient arguments. */
3224 star_precision = void_node;
3226 ++pf;
3228 else
3230 /* The decimal precision or the asterisk are optional.
3231 When neither is dirified it's taken to be zero. */
3232 precision = 0;
3236 switch (target_to_host (*pf))
3238 case 'h':
3239 if (target_to_host (pf[1]) == 'h')
3241 ++pf;
3242 dir.modifier = FMT_LEN_hh;
3244 else
3245 dir.modifier = FMT_LEN_h;
3246 ++pf;
3247 break;
3249 case 'j':
3250 dir.modifier = FMT_LEN_j;
3251 ++pf;
3252 break;
3254 case 'L':
3255 dir.modifier = FMT_LEN_L;
3256 ++pf;
3257 break;
3259 case 'l':
3260 if (target_to_host (pf[1]) == 'l')
3262 ++pf;
3263 dir.modifier = FMT_LEN_ll;
3265 else
3266 dir.modifier = FMT_LEN_l;
3267 ++pf;
3268 break;
3270 case 't':
3271 dir.modifier = FMT_LEN_t;
3272 ++pf;
3273 break;
3275 case 'z':
3276 dir.modifier = FMT_LEN_z;
3277 ++pf;
3278 break;
3281 switch (target_to_host (*pf))
3283 /* Handle a sole '%' character the same as "%%" but since it's
3284 undefined prevent the result from being folded. */
3285 case '\0':
3286 --pf;
3287 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3288 /* FALLTHRU */
3289 case '%':
3290 dir.fmtfunc = format_percent;
3291 break;
3293 case 'a':
3294 case 'A':
3295 case 'e':
3296 case 'E':
3297 case 'f':
3298 case 'F':
3299 case 'g':
3300 case 'G':
3301 res->floating = true;
3302 dir.fmtfunc = format_floating;
3303 break;
3305 case 'd':
3306 case 'i':
3307 case 'o':
3308 case 'u':
3309 case 'x':
3310 case 'X':
3311 dir.fmtfunc = format_integer;
3312 break;
3314 case 'p':
3315 /* The %p output is implementation-defined. It's possible
3316 to determine this format but due to extensions (edirially
3317 those of the Linux kernel -- see bug 78512) the first %p
3318 in the format string disables any further processing. */
3319 return false;
3321 case 'n':
3322 /* %n has side-effects even when nothing is actually printed to
3323 any buffer. */
3324 info.nowrite = false;
3325 dir.fmtfunc = format_none;
3326 break;
3328 case 'c':
3329 dir.fmtfunc = format_character;
3330 break;
3332 case 'S':
3333 case 's':
3334 dir.fmtfunc = format_string;
3335 break;
3337 default:
3338 /* Unknown conversion specification. */
3339 return 0;
3342 dir.specifier = target_to_host (*pf++);
3344 /* Store the length of the format directive. */
3345 dir.len = pf - pcnt;
3347 /* Buffer for the directive in the host character set (used when
3348 the source character set is different). */
3349 char hostdir[32];
3351 if (star_width)
3353 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3354 dir.set_width (star_width, vr_values);
3355 else
3357 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3358 (width is the absolute value of that specified). */
3359 dir.width[0] = 0;
3360 dir.width[1] = target_int_max () + 1;
3363 else
3365 if (width == LONG_MAX && werange)
3367 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3368 size_t caret = begin + (werange - pcnt);
3369 size_t end = pf - info.fmtstr - 1;
3371 /* Create a location for the width part of the directive,
3372 pointing the caret at the first out-of-range digit. */
3373 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3374 caret, begin, end);
3376 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL,
3377 info.warnopt (), "%<%.*s%> directive width out of range",
3378 dir.len, target_to_host (hostdir, sizeof hostdir, dir.beg));
3381 dir.set_width (width);
3384 if (star_precision)
3386 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3387 dir.set_precision (star_precision, vr_values);
3388 else
3390 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3391 (unlike width, negative precision is ignored). */
3392 dir.prec[0] = -1;
3393 dir.prec[1] = target_int_max ();
3396 else
3398 if (precision == LONG_MAX && perange)
3400 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3401 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3402 size_t end = pf - info.fmtstr - 2;
3404 /* Create a location for the precision part of the directive,
3405 including the leading period, pointing the caret at the first
3406 out-of-range digit . */
3407 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3408 caret, begin, end);
3410 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL,
3411 info.warnopt (), "%<%.*s%> directive precision out of range",
3412 dir.len, target_to_host (hostdir, sizeof hostdir, dir.beg));
3415 dir.set_precision (precision);
3418 /* Extract the argument if the directive takes one and if it's
3419 available (e.g., the function doesn't take a va_list). Treat
3420 missing arguments the same as va_list, even though they will
3421 have likely already been diagnosed by -Wformat. */
3422 if (dir.specifier != '%'
3423 && *argno < gimple_call_num_args (info.callstmt))
3424 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3426 if (dump_file)
3428 fprintf (dump_file,
3429 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3430 ": \"%.*s\"",
3431 dir.dirno,
3432 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3433 (int)dir.len, dir.beg);
3434 if (star_width)
3436 if (dir.width[0] == dir.width[1])
3437 fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
3438 dir.width[0]);
3439 else
3440 fprintf (dump_file,
3441 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3442 ", " HOST_WIDE_INT_PRINT_DEC "]",
3443 dir.width[0], dir.width[1]);
3446 if (star_precision)
3448 if (dir.prec[0] == dir.prec[1])
3449 fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
3450 dir.prec[0]);
3451 else
3452 fprintf (dump_file,
3453 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3454 HOST_WIDE_INT_PRINT_DEC "]",
3455 dir.prec[0], dir.prec[1]);
3457 fputc ('\n', dump_file);
3460 return dir.len;
3463 /* Compute the length of the output resulting from the call to a formatted
3464 output function described by INFO and store the result of the call in
3465 *RES. Issue warnings for detected past the end writes. Return true
3466 if the complete format string has been processed and *RES can be relied
3467 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3468 that caused the processing to be terminated early). */
3470 bool
3471 sprintf_dom_walker::compute_format_length (call_info &info,
3472 format_result *res)
3474 if (dump_file)
3476 location_t callloc = gimple_location (info.callstmt);
3477 fprintf (dump_file, "%s:%i: ",
3478 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3479 print_generic_expr (dump_file, info.func, dump_flags);
3481 fprintf (dump_file,
3482 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3483 ", fmtstr = \"%s\"\n",
3484 info.objsize, info.fmtstr);
3487 /* Reset the minimum and maximum byte counters. */
3488 res->range.min = res->range.max = 0;
3490 /* No directive has been seen yet so the length of output is bounded
3491 by the known range [0, 0] (with no conversion producing more than
3492 4K bytes) until determined otherwise. */
3493 res->knownrange = true;
3494 res->under4k = true;
3495 res->floating = false;
3496 res->warned = false;
3498 /* 1-based directive counter. */
3499 unsigned dirno = 1;
3501 /* The variadic argument counter. */
3502 unsigned argno = info.argidx;
3504 for (const char *pf = info.fmtstr; ; ++dirno)
3506 directive dir = directive ();
3507 dir.dirno = dirno;
3509 size_t n = parse_directive (info, dir, res, pf, &argno,
3510 evrp_range_analyzer.get_vr_values ());
3512 /* Return failure if the format function fails. */
3513 if (!format_directive (info, res, dir,
3514 evrp_range_analyzer.get_vr_values ()))
3515 return false;
3517 /* Return success the directive is zero bytes long and it's
3518 the last think in the format string (i.e., it's the terminating
3519 nul, which isn't really a directive but handling it as one makes
3520 things simpler). */
3521 if (!n)
3522 return *pf == '\0';
3524 pf += n;
3527 /* The complete format string was processed (with or without warnings). */
3528 return true;
3531 /* Return the size of the object referenced by the expression DEST if
3532 available, or -1 otherwise. */
3534 static unsigned HOST_WIDE_INT
3535 get_destination_size (tree dest)
3537 /* Initialize object size info before trying to compute it. */
3538 init_object_sizes ();
3540 /* Use __builtin_object_size to determine the size of the destination
3541 object. When optimizing, determine the smallest object (such as
3542 a member array as opposed to the whole enclosing object), otherwise
3543 use type-zero object size to determine the size of the enclosing
3544 object (the function fails without optimization in this type). */
3545 int ost = optimize > 0;
3546 unsigned HOST_WIDE_INT size;
3547 if (compute_builtin_object_size (dest, ost, &size))
3548 return size;
3550 return HOST_WIDE_INT_M1U;
3553 /* Return true if the call described by INFO with result RES safe to
3554 optimize (i.e., no undefined behavior), and set RETVAL to the range
3555 of its return values. */
3557 static bool
3558 is_call_safe (const sprintf_dom_walker::call_info &info,
3559 const format_result &res, bool under4k,
3560 unsigned HOST_WIDE_INT retval[2])
3562 if (under4k && !res.under4k)
3563 return false;
3565 /* The minimum return value. */
3566 retval[0] = res.range.min;
3568 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3569 but in cases involving multibyte characters could be as large as
3570 RES.RANGE.UNLIKELY. */
3571 retval[1]
3572 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3574 /* Adjust the number of bytes which includes the terminating nul
3575 to reflect the return value of the function which does not.
3576 Because the valid range of the function is [INT_MIN, INT_MAX],
3577 a valid range before the adjustment below is [0, INT_MAX + 1]
3578 (the functions only return negative values on error or undefined
3579 behavior). */
3580 if (retval[0] <= target_int_max () + 1)
3581 --retval[0];
3582 if (retval[1] <= target_int_max () + 1)
3583 --retval[1];
3585 /* Avoid the return value optimization when the behavior of the call
3586 is undefined either because any directive may have produced 4K or
3587 more of output, or the return value exceeds INT_MAX, or because
3588 the output overflows the destination object (but leave it enabled
3589 when the function is bounded because then the behavior is well-
3590 defined). */
3591 if (retval[0] == retval[1]
3592 && (info.bounded || retval[0] < info.objsize)
3593 && retval[0] <= target_int_max ())
3594 return true;
3596 if ((info.bounded || retval[1] < info.objsize)
3597 && (retval[0] < target_int_max ()
3598 && retval[1] < target_int_max ()))
3599 return true;
3601 if (!under4k && (info.bounded || retval[0] < info.objsize))
3602 return true;
3604 return false;
3607 /* Given a suitable result RES of a call to a formatted output function
3608 described by INFO, substitute the result for the return value of
3609 the call. The result is suitable if the number of bytes it represents
3610 is known and exact. A result that isn't suitable for substitution may
3611 have its range set to the range of return values, if that is known.
3612 Return true if the call is removed and gsi_next should not be performed
3613 in the caller. */
3615 static bool
3616 try_substitute_return_value (gimple_stmt_iterator *gsi,
3617 const sprintf_dom_walker::call_info &info,
3618 const format_result &res)
3620 tree lhs = gimple_get_lhs (info.callstmt);
3622 /* Set to true when the entire call has been removed. */
3623 bool removed = false;
3625 /* The minimum and maximum return value. */
3626 unsigned HOST_WIDE_INT retval[2];
3627 bool safe = is_call_safe (info, res, true, retval);
3629 if (safe
3630 && retval[0] == retval[1]
3631 /* Not prepared to handle possibly throwing calls here; they shouldn't
3632 appear in non-artificial testcases, except when the __*_chk routines
3633 are badly declared. */
3634 && !stmt_ends_bb_p (info.callstmt))
3636 tree cst = build_int_cst (integer_type_node, retval[0]);
3638 if (lhs == NULL_TREE
3639 && info.nowrite)
3641 /* Remove the call to the bounded function with a zero size
3642 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3643 unlink_stmt_vdef (info.callstmt);
3644 gsi_remove (gsi, true);
3645 removed = true;
3647 else if (info.nowrite)
3649 /* Replace the call to the bounded function with a zero size
3650 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3651 of the function. */
3652 if (!update_call_from_tree (gsi, cst))
3653 gimplify_and_update_call_from_tree (gsi, cst);
3654 gimple *callstmt = gsi_stmt (*gsi);
3655 update_stmt (callstmt);
3657 else if (lhs)
3659 /* Replace the left-hand side of the call with the constant
3660 result of the formatted function. */
3661 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3662 gimple *g = gimple_build_assign (lhs, cst);
3663 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3664 update_stmt (info.callstmt);
3667 if (dump_file)
3669 if (removed)
3670 fprintf (dump_file, " Removing call statement.");
3671 else
3673 fprintf (dump_file, " Substituting ");
3674 print_generic_expr (dump_file, cst, dump_flags);
3675 fprintf (dump_file, " for %s.\n",
3676 info.nowrite ? "statement" : "return value");
3680 else if (lhs)
3682 bool setrange = false;
3684 if (safe
3685 && (info.bounded || retval[1] < info.objsize)
3686 && (retval[0] < target_int_max ()
3687 && retval[1] < target_int_max ()))
3689 /* If the result is in a valid range bounded by the size of
3690 the destination set it so that it can be used for subsequent
3691 optimizations. */
3692 int prec = TYPE_PRECISION (integer_type_node);
3694 wide_int min = wi::shwi (retval[0], prec);
3695 wide_int max = wi::shwi (retval[1], prec);
3696 set_range_info (lhs, VR_RANGE, min, max);
3698 setrange = true;
3701 if (dump_file)
3703 const char *inbounds
3704 = (retval[0] < info.objsize
3705 ? (retval[1] < info.objsize
3706 ? "in" : "potentially out-of")
3707 : "out-of");
3709 const char *what = setrange ? "Setting" : "Discarding";
3710 if (retval[0] != retval[1])
3711 fprintf (dump_file,
3712 " %s %s-bounds return value range ["
3713 HOST_WIDE_INT_PRINT_UNSIGNED ", "
3714 HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
3715 what, inbounds, retval[0], retval[1]);
3716 else
3717 fprintf (dump_file, " %s %s-bounds return value "
3718 HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
3719 what, inbounds, retval[0]);
3723 if (dump_file)
3724 fputc ('\n', dump_file);
3726 return removed;
3729 /* Try to simplify a s{,n}printf call described by INFO with result
3730 RES by replacing it with a simpler and presumably more efficient
3731 call (such as strcpy). */
3733 static bool
3734 try_simplify_call (gimple_stmt_iterator *gsi,
3735 const sprintf_dom_walker::call_info &info,
3736 const format_result &res)
3738 unsigned HOST_WIDE_INT dummy[2];
3739 if (!is_call_safe (info, res, info.retval_used (), dummy))
3740 return false;
3742 switch (info.fncode)
3744 case BUILT_IN_SNPRINTF:
3745 return gimple_fold_builtin_snprintf (gsi);
3747 case BUILT_IN_SPRINTF:
3748 return gimple_fold_builtin_sprintf (gsi);
3750 default:
3754 return false;
3757 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3758 functions and if so, handle it. Return true if the call is removed
3759 and gsi_next should not be performed in the caller. */
3761 bool
3762 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3764 call_info info = call_info ();
3766 info.callstmt = gsi_stmt (*gsi);
3767 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3768 return false;
3770 info.func = gimple_call_fndecl (info.callstmt);
3771 info.fncode = DECL_FUNCTION_CODE (info.func);
3773 /* The size of the destination as in snprintf(dest, size, ...). */
3774 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3776 /* The size of the destination determined by __builtin_object_size. */
3777 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3779 /* Buffer size argument number (snprintf and vsnprintf). */
3780 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3782 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3783 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3785 /* Format string argument number (valid for all functions). */
3786 unsigned idx_format;
3788 switch (info.fncode)
3790 case BUILT_IN_SPRINTF:
3791 // Signature:
3792 // __builtin_sprintf (dst, format, ...)
3793 idx_format = 1;
3794 info.argidx = 2;
3795 break;
3797 case BUILT_IN_SPRINTF_CHK:
3798 // Signature:
3799 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3800 idx_objsize = 2;
3801 idx_format = 3;
3802 info.argidx = 4;
3803 break;
3805 case BUILT_IN_SNPRINTF:
3806 // Signature:
3807 // __builtin_snprintf (dst, size, format, ...)
3808 idx_dstsize = 1;
3809 idx_format = 2;
3810 info.argidx = 3;
3811 info.bounded = true;
3812 break;
3814 case BUILT_IN_SNPRINTF_CHK:
3815 // Signature:
3816 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3817 idx_dstsize = 1;
3818 idx_objsize = 3;
3819 idx_format = 4;
3820 info.argidx = 5;
3821 info.bounded = true;
3822 break;
3824 case BUILT_IN_VSNPRINTF:
3825 // Signature:
3826 // __builtin_vsprintf (dst, size, format, va)
3827 idx_dstsize = 1;
3828 idx_format = 2;
3829 info.argidx = -1;
3830 info.bounded = true;
3831 break;
3833 case BUILT_IN_VSNPRINTF_CHK:
3834 // Signature:
3835 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3836 idx_dstsize = 1;
3837 idx_objsize = 3;
3838 idx_format = 4;
3839 info.argidx = -1;
3840 info.bounded = true;
3841 break;
3843 case BUILT_IN_VSPRINTF:
3844 // Signature:
3845 // __builtin_vsprintf (dst, format, va)
3846 idx_format = 1;
3847 info.argidx = -1;
3848 break;
3850 case BUILT_IN_VSPRINTF_CHK:
3851 // Signature:
3852 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3853 idx_format = 3;
3854 idx_objsize = 2;
3855 info.argidx = -1;
3856 break;
3858 default:
3859 return false;
3862 /* Set the global warning level for this function. */
3863 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3865 /* The first argument is a pointer to the destination. */
3866 tree dstptr = gimple_call_arg (info.callstmt, 0);
3868 info.format = gimple_call_arg (info.callstmt, idx_format);
3870 /* True when the destination size is constant as opposed to the lower
3871 or upper bound of a range. */
3872 bool dstsize_cst_p = true;
3874 if (idx_dstsize == HOST_WIDE_INT_M1U)
3876 /* For non-bounded functions like sprintf, determine the size
3877 of the destination from the object or pointer passed to it
3878 as the first argument. */
3879 dstsize = get_destination_size (dstptr);
3881 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3883 /* For bounded functions try to get the size argument. */
3885 if (TREE_CODE (size) == INTEGER_CST)
3887 dstsize = tree_to_uhwi (size);
3888 /* No object can be larger than SIZE_MAX bytes (half the address
3889 space) on the target.
3890 The functions are defined only for output of at most INT_MAX
3891 bytes. Specifying a bound in excess of that limit effectively
3892 defeats the bounds checking (and on some implementations such
3893 as Solaris cause the function to fail with EINVAL). */
3894 if (dstsize > target_size_max () / 2)
3896 /* Avoid warning if -Wstringop-overflow is specified since
3897 it also warns for the same thing though only for the
3898 checking built-ins. */
3899 if ((idx_objsize == HOST_WIDE_INT_M1U
3900 || !warn_stringop_overflow))
3901 warning_at (gimple_location (info.callstmt), info.warnopt (),
3902 "specified bound %wu exceeds maximum object size "
3903 "%wu",
3904 dstsize, target_size_max () / 2);
3906 else if (dstsize > target_int_max ())
3907 warning_at (gimple_location (info.callstmt), info.warnopt (),
3908 "specified bound %wu exceeds %<INT_MAX%>",
3909 dstsize);
3911 else if (TREE_CODE (size) == SSA_NAME)
3913 /* Try to determine the range of values of the argument
3914 and use the greater of the two at level 1 and the smaller
3915 of them at level 2. */
3916 value_range *vr = evrp_range_analyzer.get_value_range (size);
3917 if (vr->type == VR_RANGE
3918 && TREE_CODE (vr->min) == INTEGER_CST
3919 && TREE_CODE (vr->max) == INTEGER_CST)
3920 dstsize = (warn_level < 2
3921 ? TREE_INT_CST_LOW (vr->max)
3922 : TREE_INT_CST_LOW (vr->min));
3924 /* The destination size is not constant. If the function is
3925 bounded (e.g., snprintf) a lower bound of zero doesn't
3926 necessarily imply it can be eliminated. */
3927 dstsize_cst_p = false;
3931 if (idx_objsize != HOST_WIDE_INT_M1U)
3932 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3933 if (tree_fits_uhwi_p (size))
3934 objsize = tree_to_uhwi (size);
3936 if (info.bounded && !dstsize)
3938 /* As a special case, when the explicitly specified destination
3939 size argument (to a bounded function like snprintf) is zero
3940 it is a request to determine the number of bytes on output
3941 without actually producing any. Pretend the size is
3942 unlimited in this case. */
3943 info.objsize = HOST_WIDE_INT_MAX;
3944 info.nowrite = dstsize_cst_p;
3946 else
3948 /* For calls to non-bounded functions or to those of bounded
3949 functions with a non-zero size, warn if the destination
3950 pointer is null. */
3951 if (integer_zerop (dstptr))
3953 /* This is diagnosed with -Wformat only when the null is a constant
3954 pointer. The warning here diagnoses instances where the pointer
3955 is not constant. */
3956 location_t loc = gimple_location (info.callstmt);
3957 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3958 info.warnopt (), "null destination pointer");
3959 return false;
3962 /* Set the object size to the smaller of the two arguments
3963 of both have been specified and they're not equal. */
3964 info.objsize = dstsize < objsize ? dstsize : objsize;
3966 if (info.bounded
3967 && dstsize < target_size_max () / 2 && objsize < dstsize
3968 /* Avoid warning if -Wstringop-overflow is specified since
3969 it also warns for the same thing though only for the
3970 checking built-ins. */
3971 && (idx_objsize == HOST_WIDE_INT_M1U
3972 || !warn_stringop_overflow))
3974 warning_at (gimple_location (info.callstmt), info.warnopt (),
3975 "specified bound %wu exceeds the size %wu "
3976 "of the destination object", dstsize, objsize);
3980 if (integer_zerop (info.format))
3982 /* This is diagnosed with -Wformat only when the null is a constant
3983 pointer. The warning here diagnoses instances where the pointer
3984 is not constant. */
3985 location_t loc = gimple_location (info.callstmt);
3986 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3987 info.warnopt (), "null format string");
3988 return false;
3991 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3992 if (!info.fmtstr)
3993 return false;
3995 /* The result is the number of bytes output by the formatted function,
3996 including the terminating NUL. */
3997 format_result res = format_result ();
3999 bool success = compute_format_length (info, &res);
4001 /* When optimizing and the printf return value optimization is enabled,
4002 attempt to substitute the computed result for the return value of
4003 the call. Avoid this optimization when -frounding-math is in effect
4004 and the format string contains a floating point directive. */
4005 bool call_removed = false;
4006 if (success && optimize > 0)
4008 /* Save a copy of the iterator pointing at the call. The iterator
4009 may change to point past the call in try_substitute_return_value
4010 but the original value is needed in try_simplify_call. */
4011 gimple_stmt_iterator gsi_call = *gsi;
4013 if (flag_printf_return_value
4014 && (!flag_rounding_math || !res.floating))
4015 call_removed = try_substitute_return_value (gsi, info, res);
4017 if (!call_removed)
4018 try_simplify_call (&gsi_call, info, res);
4021 return call_removed;
4024 edge
4025 sprintf_dom_walker::before_dom_children (basic_block bb)
4027 evrp_range_analyzer.enter (bb);
4028 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
4030 /* Iterate over statements, looking for function calls. */
4031 gimple *stmt = gsi_stmt (si);
4033 /* First record ranges generated by this statement. */
4034 evrp_range_analyzer.record_ranges_from_stmt (stmt, false);
4036 if (is_gimple_call (stmt) && handle_gimple_call (&si))
4037 /* If handle_gimple_call returns true, the iterator is
4038 already pointing to the next statement. */
4039 continue;
4041 gsi_next (&si);
4043 return NULL;
4046 void
4047 sprintf_dom_walker::after_dom_children (basic_block bb)
4049 evrp_range_analyzer.leave (bb);
4052 /* Execute the pass for function FUN. */
4054 unsigned int
4055 pass_sprintf_length::execute (function *fun)
4057 init_target_to_host_charmap ();
4059 calculate_dominance_info (CDI_DOMINATORS);
4061 sprintf_dom_walker sprintf_dom_walker;
4062 sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
4064 /* Clean up object size info. */
4065 fini_object_sizes ();
4066 return 0;
4069 } /* Unnamed namespace. */
4071 /* Return a pointer to a pass object newly constructed from the context
4072 CTXT. */
4074 gimple_opt_pass *
4075 make_pass_sprintf_length (gcc::context *ctxt)
4077 return new pass_sprintf_length (ctxt);