PR translation/84207 - Hard coded plural in gimple-fold.c
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob83d71f0d64468087609b3ac2dee24777aaa31cf3
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 value_range *vr = vr_values->get_value_range (arg);
1153 if (vr->type == VR_RANGE
1154 && TREE_CODE (vr->min) == INTEGER_CST
1155 && TREE_CODE (vr->max) == INTEGER_CST)
1157 HOST_WIDE_INT type_min
1158 = (TYPE_UNSIGNED (argtype)
1159 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1160 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1162 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1164 *pmin = TREE_INT_CST_LOW (vr->min);
1165 *pmax = TREE_INT_CST_LOW (vr->max);
1167 if (*pmin < *pmax)
1169 /* Return true if the adjusted range is a subrange of
1170 the full range of the argument's type. *PMAX may
1171 be less than *PMIN when the argument is unsigned
1172 and its upper bound is in excess of TYPE_MAX. In
1173 that (invalid) case disregard the range and use that
1174 of the expected type instead. */
1175 knownrange = type_min < *pmin || *pmax < type_max;
1177 unknown = false;
1182 /* Handle an argument with an unknown range as if none had been
1183 provided. */
1184 if (unknown)
1185 return get_int_range (NULL_TREE, pmin, pmax, absolute,
1186 negbound, vr_values);
1189 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1190 if (absolute)
1192 if (*pmin < 0)
1194 if (*pmin == *pmax)
1195 *pmin = *pmax = -*pmin;
1196 else
1198 /* Make sure signed overlow is avoided. */
1199 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1201 HOST_WIDE_INT tmp = -*pmin;
1202 *pmin = 0;
1203 if (*pmax < tmp)
1204 *pmax = tmp;
1208 else if (*pmin < negbound)
1209 *pmin = negbound;
1211 return knownrange;
1214 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1215 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1216 the type of the directive's formal argument it's possible for both
1217 to result in the same number of bytes or a range of bytes that's
1218 less than the number of bytes that would result from formatting
1219 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1220 determined by checking for the actual argument being in the range
1221 of the type of the directive. If it isn't it must be assumed to
1222 take on the full range of the directive's type.
1223 Return true when the range has been adjusted to the full range
1224 of DIRTYPE, and false otherwise. */
1226 static bool
1227 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1229 tree argtype = TREE_TYPE (*argmin);
1230 unsigned argprec = TYPE_PRECISION (argtype);
1231 unsigned dirprec = TYPE_PRECISION (dirtype);
1233 /* If the actual argument and the directive's argument have the same
1234 precision and sign there can be no overflow and so there is nothing
1235 to adjust. */
1236 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1237 return false;
1239 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1240 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1242 if (TREE_CODE (*argmin) == INTEGER_CST
1243 && TREE_CODE (*argmax) == INTEGER_CST
1244 && (dirprec >= argprec
1245 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1246 int_const_binop (MINUS_EXPR,
1247 *argmax,
1248 *argmin),
1249 size_int (dirprec)))))
1251 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1252 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1254 /* If *ARGMIN is still less than *ARGMAX the conversion above
1255 is safe. Otherwise, it has overflowed and would be unsafe. */
1256 if (tree_int_cst_le (*argmin, *argmax))
1257 return false;
1260 *argmin = TYPE_MIN_VALUE (dirtype);
1261 *argmax = TYPE_MAX_VALUE (dirtype);
1262 return true;
1265 /* Return a range representing the minimum and maximum number of bytes
1266 that the format directive DIR will output for any argument given
1267 the WIDTH and PRECISION (extracted from DIR). This function is
1268 used when the directive argument or its value isn't known. */
1270 static fmtresult
1271 format_integer (const directive &dir, tree arg, vr_values *vr_values)
1273 tree intmax_type_node;
1274 tree uintmax_type_node;
1276 /* Base to format the number in. */
1277 int base;
1279 /* True when a conversion is preceded by a prefix indicating the base
1280 of the argument (octal or hexadecimal). */
1281 bool maybebase = dir.get_flag ('#');
1283 /* True when a signed conversion is preceded by a sign or space. */
1284 bool maybesign = false;
1286 /* True for signed conversions (i.e., 'd' and 'i'). */
1287 bool sign = false;
1289 switch (dir.specifier)
1291 case 'd':
1292 case 'i':
1293 /* Space and '+' are only meaningful for signed conversions. */
1294 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1295 sign = true;
1296 base = 10;
1297 break;
1298 case 'u':
1299 base = 10;
1300 break;
1301 case 'o':
1302 base = 8;
1303 break;
1304 case 'X':
1305 case 'x':
1306 base = 16;
1307 break;
1308 default:
1309 gcc_unreachable ();
1312 /* The type of the "formal" argument expected by the directive. */
1313 tree dirtype = NULL_TREE;
1315 /* Determine the expected type of the argument from the length
1316 modifier. */
1317 switch (dir.modifier)
1319 case FMT_LEN_none:
1320 if (dir.specifier == 'p')
1321 dirtype = ptr_type_node;
1322 else
1323 dirtype = sign ? integer_type_node : unsigned_type_node;
1324 break;
1326 case FMT_LEN_h:
1327 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1328 break;
1330 case FMT_LEN_hh:
1331 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1332 break;
1334 case FMT_LEN_l:
1335 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1336 break;
1338 case FMT_LEN_L:
1339 case FMT_LEN_ll:
1340 dirtype = (sign
1341 ? long_long_integer_type_node
1342 : long_long_unsigned_type_node);
1343 break;
1345 case FMT_LEN_z:
1346 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1347 break;
1349 case FMT_LEN_t:
1350 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1351 break;
1353 case FMT_LEN_j:
1354 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1355 dirtype = sign ? intmax_type_node : uintmax_type_node;
1356 break;
1358 default:
1359 return fmtresult ();
1362 /* The type of the argument to the directive, either deduced from
1363 the actual non-constant argument if one is known, or from
1364 the directive itself when none has been provided because it's
1365 a va_list. */
1366 tree argtype = NULL_TREE;
1368 if (!arg)
1370 /* When the argument has not been provided, use the type of
1371 the directive's argument as an approximation. This will
1372 result in false positives for directives like %i with
1373 arguments with smaller precision (such as short or char). */
1374 argtype = dirtype;
1376 else if (TREE_CODE (arg) == INTEGER_CST)
1378 /* When a constant argument has been provided use its value
1379 rather than type to determine the length of the output. */
1380 fmtresult res;
1382 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1384 /* As a special case, a precision of zero with a zero argument
1385 results in zero bytes except in base 8 when the '#' flag is
1386 specified, and for signed conversions in base 8 and 10 when
1387 either the space or '+' flag has been specified and it results
1388 in just one byte (with width having the normal effect). This
1389 must extend to the case of a specified precision with
1390 an unknown value because it can be zero. */
1391 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1392 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1394 res.range.max = 1;
1395 res.range.likely = 1;
1397 else
1399 res.range.max = res.range.min;
1400 res.range.likely = res.range.min;
1403 else
1405 /* Convert the argument to the type of the directive. */
1406 arg = fold_convert (dirtype, arg);
1408 res.range.min = tree_digits (arg, base, dir.prec[0],
1409 maybesign, maybebase);
1410 if (dir.prec[0] == dir.prec[1])
1411 res.range.max = res.range.min;
1412 else
1413 res.range.max = tree_digits (arg, base, dir.prec[1],
1414 maybesign, maybebase);
1415 res.range.likely = res.range.min;
1416 res.knownrange = true;
1419 res.range.unlikely = res.range.max;
1421 /* Bump up the counters if WIDTH is greater than LEN. */
1422 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1423 (sign | maybebase) + (base == 16));
1424 /* Bump up the counters again if PRECision is greater still. */
1425 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1426 (sign | maybebase) + (base == 16));
1428 return res;
1430 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1431 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1432 /* Determine the type of the provided non-constant argument. */
1433 argtype = TREE_TYPE (arg);
1434 else
1435 /* Don't bother with invalid arguments since they likely would
1436 have already been diagnosed, and disable any further checking
1437 of the format string by returning [-1, -1]. */
1438 return fmtresult ();
1440 fmtresult res;
1442 /* Using either the range the non-constant argument is in, or its
1443 type (either "formal" or actual), create a range of values that
1444 constrain the length of output given the warning level. */
1445 tree argmin = NULL_TREE;
1446 tree argmax = NULL_TREE;
1448 if (arg
1449 && TREE_CODE (arg) == SSA_NAME
1450 && INTEGRAL_TYPE_P (argtype))
1452 /* Try to determine the range of values of the integer argument
1453 (range information is not available for pointers). */
1454 value_range *vr = vr_values->get_value_range (arg);
1455 if (vr->type == VR_RANGE
1456 && TREE_CODE (vr->min) == INTEGER_CST
1457 && TREE_CODE (vr->max) == INTEGER_CST)
1459 argmin = vr->min;
1460 argmax = vr->max;
1462 /* Set KNOWNRANGE if the argument is in a known subrange
1463 of the directive's type and neither width nor precision
1464 is unknown. (KNOWNRANGE may be reset below). */
1465 res.knownrange
1466 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1467 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1468 && dir.known_width_and_precision ());
1470 res.argmin = argmin;
1471 res.argmax = argmax;
1473 else if (vr->type == VR_ANTI_RANGE)
1475 /* Handle anti-ranges if/when bug 71690 is resolved. */
1477 else if (vr->type == VR_VARYING
1478 || vr->type == VR_UNDEFINED)
1480 /* The argument here may be the result of promoting the actual
1481 argument to int. Try to determine the type of the actual
1482 argument before promotion and narrow down its range that
1483 way. */
1484 gimple *def = SSA_NAME_DEF_STMT (arg);
1485 if (is_gimple_assign (def))
1487 tree_code code = gimple_assign_rhs_code (def);
1488 if (code == INTEGER_CST)
1490 arg = gimple_assign_rhs1 (def);
1491 return format_integer (dir, arg, vr_values);
1494 if (code == NOP_EXPR)
1496 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1497 if (INTEGRAL_TYPE_P (type)
1498 || TREE_CODE (type) == POINTER_TYPE)
1499 argtype = type;
1505 if (!argmin)
1507 if (TREE_CODE (argtype) == POINTER_TYPE)
1509 argmin = build_int_cst (pointer_sized_int_node, 0);
1510 argmax = build_all_ones_cst (pointer_sized_int_node);
1512 else
1514 argmin = TYPE_MIN_VALUE (argtype);
1515 argmax = TYPE_MAX_VALUE (argtype);
1519 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1520 of the directive. If it has been cleared then since ARGMIN and/or
1521 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1522 ARGMAX in the result to include in diagnostics. */
1523 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1525 res.knownrange = false;
1526 res.argmin = argmin;
1527 res.argmax = argmax;
1530 /* Recursively compute the minimum and maximum from the known range. */
1531 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1533 /* For unsigned conversions/directives or signed when
1534 the minimum is positive, use the minimum and maximum to compute
1535 the shortest and longest output, respectively. */
1536 res.range.min = format_integer (dir, argmin, vr_values).range.min;
1537 res.range.max = format_integer (dir, argmax, vr_values).range.max;
1539 else if (tree_int_cst_sgn (argmax) < 0)
1541 /* For signed conversions/directives if maximum is negative,
1542 use the minimum as the longest output and maximum as the
1543 shortest output. */
1544 res.range.min = format_integer (dir, argmax, vr_values).range.min;
1545 res.range.max = format_integer (dir, argmin, vr_values).range.max;
1547 else
1549 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1550 as the shortest output and for the longest output compute the
1551 length of the output of both minimum and maximum and pick the
1552 longer. */
1553 unsigned HOST_WIDE_INT max1
1554 = format_integer (dir, argmin, vr_values).range.max;
1555 unsigned HOST_WIDE_INT max2
1556 = format_integer (dir, argmax, vr_values).range.max;
1557 res.range.min
1558 = format_integer (dir, integer_zero_node, vr_values).range.min;
1559 res.range.max = MAX (max1, max2);
1562 /* If the range is known, use the maximum as the likely length. */
1563 if (res.knownrange)
1564 res.range.likely = res.range.max;
1565 else
1567 /* Otherwise, use the minimum. Except for the case where for %#x or
1568 %#o the minimum is just for a single value in the range (0) and
1569 for all other values it is something longer, like 0x1 or 01.
1570 Use the length for value 1 in that case instead as the likely
1571 length. */
1572 res.range.likely = res.range.min;
1573 if (maybebase
1574 && base != 10
1575 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1577 if (res.range.min == 1)
1578 res.range.likely += base == 8 ? 1 : 2;
1579 else if (res.range.min == 2
1580 && base == 16
1581 && (dir.width[0] == 2 || dir.prec[0] == 2))
1582 ++res.range.likely;
1586 res.range.unlikely = res.range.max;
1587 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1588 (sign | maybebase) + (base == 16));
1589 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1590 (sign | maybebase) + (base == 16));
1592 return res;
1595 /* Return the number of bytes that a format directive consisting of FLAGS,
1596 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1597 would result for argument X under ideal conditions (i.e., if PREC
1598 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1599 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1600 This function works around those problems. */
1602 static unsigned HOST_WIDE_INT
1603 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1604 char spec, char rndspec)
1606 char fmtstr[40];
1608 HOST_WIDE_INT len = strlen (flags);
1610 fmtstr[0] = '%';
1611 memcpy (fmtstr + 1, flags, len);
1612 memcpy (fmtstr + 1 + len, ".*R", 3);
1613 fmtstr[len + 4] = rndspec;
1614 fmtstr[len + 5] = spec;
1615 fmtstr[len + 6] = '\0';
1617 spec = TOUPPER (spec);
1618 if (spec == 'E' || spec == 'F')
1620 /* For %e, specify the precision explicitly since mpfr_sprintf
1621 does its own thing just to be different (see MPFR bug 21088). */
1622 if (prec < 0)
1623 prec = 6;
1625 else
1627 /* Avoid passing negative precisions with larger magnitude to MPFR
1628 to avoid exposing its bugs. (A negative precision is supposed
1629 to be ignored.) */
1630 if (prec < 0)
1631 prec = -1;
1634 HOST_WIDE_INT p = prec;
1636 if (spec == 'G' && !strchr (flags, '#'))
1638 /* For G/g without the pound flag, precision gives the maximum number
1639 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1640 a 128 bit IEEE extended precision, 4932. Using twice as much here
1641 should be more than sufficient for any real format. */
1642 if ((IEEE_MAX_10_EXP * 2) < prec)
1643 prec = IEEE_MAX_10_EXP * 2;
1644 p = prec;
1646 else
1648 /* Cap precision arbitrarily at 1KB and add the difference
1649 (if any) to the MPFR result. */
1650 if (prec > 1024)
1651 p = 1024;
1654 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1656 /* Handle the unlikely (impossible?) error by returning more than
1657 the maximum dictated by the function's return type. */
1658 if (len < 0)
1659 return target_dir_max () + 1;
1661 /* Adjust the return value by the difference. */
1662 if (p < prec)
1663 len += prec - p;
1665 return len;
1668 /* Return the number of bytes to format using the format specifier
1669 SPEC and the precision PREC the largest value in the real floating
1670 TYPE. */
1672 static unsigned HOST_WIDE_INT
1673 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1675 machine_mode mode = TYPE_MODE (type);
1677 /* IBM Extended mode. */
1678 if (MODE_COMPOSITE_P (mode))
1679 mode = DFmode;
1681 /* Get the real type format desription for the target. */
1682 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1683 REAL_VALUE_TYPE rv;
1685 real_maxval (&rv, 0, mode);
1687 /* Convert the GCC real value representation with the precision
1688 of the real type to the mpfr_t format with the GCC default
1689 round-to-nearest mode. */
1690 mpfr_t x;
1691 mpfr_init2 (x, rfmt->p);
1692 mpfr_from_real (x, &rv, GMP_RNDN);
1694 /* Return a value one greater to account for the leading minus sign. */
1695 unsigned HOST_WIDE_INT r
1696 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1697 mpfr_clear (x);
1698 return r;
1701 /* Return a range representing the minimum and maximum number of bytes
1702 that the directive DIR will output for any argument. PREC gives
1703 the adjusted precision range to account for negative precisions
1704 meaning the default 6. This function is used when the directive
1705 argument or its value isn't known. */
1707 static fmtresult
1708 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1710 tree type;
1712 switch (dir.modifier)
1714 case FMT_LEN_l:
1715 case FMT_LEN_none:
1716 type = double_type_node;
1717 break;
1719 case FMT_LEN_L:
1720 type = long_double_type_node;
1721 break;
1723 case FMT_LEN_ll:
1724 type = long_double_type_node;
1725 break;
1727 default:
1728 return fmtresult ();
1731 /* The minimum and maximum number of bytes produced by the directive. */
1732 fmtresult res;
1734 /* The minimum output as determined by flags. It's always at least 1.
1735 When plus or space are set the output is preceded by either a sign
1736 or a space. */
1737 unsigned flagmin = (1 /* for the first digit */
1738 + (dir.get_flag ('+') | dir.get_flag (' ')));
1740 /* When the pound flag is set the decimal point is included in output
1741 regardless of precision. Whether or not a decimal point is included
1742 otherwise depends on the specification and precision. */
1743 bool radix = dir.get_flag ('#');
1745 switch (dir.specifier)
1747 case 'A':
1748 case 'a':
1750 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1751 if (dir.prec[0] <= 0)
1752 minprec = 0;
1753 else if (dir.prec[0] > 0)
1754 minprec = dir.prec[0] + !radix /* decimal point */;
1756 res.range.min = (2 /* 0x */
1757 + flagmin
1758 + radix
1759 + minprec
1760 + 3 /* p+0 */);
1762 res.range.max = format_floating_max (type, 'a', prec[1]);
1763 res.range.likely = res.range.min;
1765 /* The unlikely maximum accounts for the longest multibyte
1766 decimal point character. */
1767 res.range.unlikely = res.range.max;
1768 if (dir.prec[1] > 0)
1769 res.range.unlikely += target_mb_len_max () - 1;
1771 break;
1774 case 'E':
1775 case 'e':
1777 /* Minimum output attributable to precision and, when it's
1778 non-zero, decimal point. */
1779 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1781 /* The minimum output is "[-+]1.234567e+00" regardless
1782 of the value of the actual argument. */
1783 res.range.min = (flagmin
1784 + radix
1785 + minprec
1786 + 2 /* e+ */ + 2);
1788 res.range.max = format_floating_max (type, 'e', prec[1]);
1789 res.range.likely = res.range.min;
1791 /* The unlikely maximum accounts for the longest multibyte
1792 decimal point character. */
1793 if (dir.prec[0] != dir.prec[1]
1794 || dir.prec[0] == -1 || dir.prec[0] > 0)
1795 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1796 else
1797 res.range.unlikely = res.range.max;
1798 break;
1801 case 'F':
1802 case 'f':
1804 /* Minimum output attributable to precision and, when it's non-zero,
1805 decimal point. */
1806 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1808 /* The lower bound when precision isn't specified is 8 bytes
1809 ("1.23456" since precision is taken to be 6). When precision
1810 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1811 when precision is greater than zero, then the lower bound
1812 is 2 plus precision (plus flags). */
1813 res.range.min = flagmin + radix + minprec;
1815 /* Compute the upper bound for -TYPE_MAX. */
1816 res.range.max = format_floating_max (type, 'f', prec[1]);
1818 /* The minimum output with unknown precision is a single byte
1819 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1820 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1821 res.range.likely = 3;
1822 else
1823 res.range.likely = res.range.min;
1825 /* The unlikely maximum accounts for the longest multibyte
1826 decimal point character. */
1827 if (dir.prec[0] != dir.prec[1]
1828 || dir.prec[0] == -1 || dir.prec[0] > 0)
1829 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1830 break;
1833 case 'G':
1834 case 'g':
1836 /* The %g output depends on precision and the exponent of
1837 the argument. Since the value of the argument isn't known
1838 the lower bound on the range of bytes (not counting flags
1839 or width) is 1 plus radix (i.e., either "0" or "0." for
1840 "%g" and "%#g", respectively, with a zero argument). */
1841 res.range.min = flagmin + radix;
1843 char spec = 'g';
1844 HOST_WIDE_INT maxprec = dir.prec[1];
1845 if (radix && maxprec)
1847 /* When the pound flag (radix) is set, trailing zeros aren't
1848 trimmed and so the longest output is the same as for %e,
1849 except with precision minus 1 (as specified in C11). */
1850 spec = 'e';
1851 if (maxprec > 0)
1852 --maxprec;
1853 else if (maxprec < 0)
1854 maxprec = 5;
1856 else
1857 maxprec = prec[1];
1859 res.range.max = format_floating_max (type, spec, maxprec);
1861 /* The likely output is either the maximum computed above
1862 minus 1 (assuming the maximum is positive) when precision
1863 is known (or unspecified), or the same minimum as for %e
1864 (which is computed for a non-negative argument). Unlike
1865 for the other specifiers above the likely output isn't
1866 the minimum because for %g that's 1 which is unlikely. */
1867 if (dir.prec[1] < 0
1868 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1869 res.range.likely = res.range.max - 1;
1870 else
1872 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1873 res.range.likely = (flagmin
1874 + radix
1875 + minprec
1876 + 2 /* e+ */ + 2);
1879 /* The unlikely maximum accounts for the longest multibyte
1880 decimal point character. */
1881 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1882 break;
1885 default:
1886 return fmtresult ();
1889 /* Bump up the byte counters if WIDTH is greater. */
1890 res.adjust_for_width_or_precision (dir.width);
1891 return res;
1894 /* Return a range representing the minimum and maximum number of bytes
1895 that the directive DIR will write on output for the floating argument
1896 ARG. */
1898 static fmtresult
1899 format_floating (const directive &dir, tree arg, vr_values *)
1901 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1902 tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1903 ? long_double_type_node : double_type_node);
1905 /* For an indeterminate precision the lower bound must be assumed
1906 to be zero. */
1907 if (TOUPPER (dir.specifier) == 'A')
1909 /* Get the number of fractional decimal digits needed to represent
1910 the argument without a loss of accuracy. */
1911 unsigned fmtprec
1912 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1914 /* The precision of the IEEE 754 double format is 53.
1915 The precision of all other GCC binary double formats
1916 is 56 or less. */
1917 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1919 /* For %a, leave the minimum precision unspecified to let
1920 MFPR trim trailing zeros (as it and many other systems
1921 including Glibc happen to do) and set the maximum
1922 precision to reflect what it would be with trailing zeros
1923 present (as Solaris and derived systems do). */
1924 if (dir.prec[1] < 0)
1926 /* Both bounds are negative implies that precision has
1927 not been specified. */
1928 prec[0] = maxprec;
1929 prec[1] = -1;
1931 else if (dir.prec[0] < 0)
1933 /* With a negative lower bound and a non-negative upper
1934 bound set the minimum precision to zero and the maximum
1935 to the greater of the maximum precision (i.e., with
1936 trailing zeros present) and the specified upper bound. */
1937 prec[0] = 0;
1938 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1941 else if (dir.prec[0] < 0)
1943 if (dir.prec[1] < 0)
1945 /* A precision in a strictly negative range is ignored and
1946 the default of 6 is used instead. */
1947 prec[0] = prec[1] = 6;
1949 else
1951 /* For a precision in a partly negative range, the lower bound
1952 must be assumed to be zero and the new upper bound is the
1953 greater of 6 (the default precision used when the specified
1954 precision is negative) and the upper bound of the specified
1955 range. */
1956 prec[0] = 0;
1957 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1961 if (!arg
1962 || TREE_CODE (arg) != REAL_CST
1963 || !useless_type_conversion_p (type, TREE_TYPE (arg)))
1964 return format_floating (dir, prec);
1966 /* The minimum and maximum number of bytes produced by the directive. */
1967 fmtresult res;
1969 /* Get the real type format desription for the target. */
1970 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1971 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1973 char fmtstr [40];
1974 char *pfmt = fmtstr;
1976 /* Append flags. */
1977 for (const char *pf = "-+ #0"; *pf; ++pf)
1978 if (dir.get_flag (*pf))
1979 *pfmt++ = *pf;
1981 *pfmt = '\0';
1984 /* Set up an array to easily iterate over. */
1985 unsigned HOST_WIDE_INT* const minmax[] = {
1986 &res.range.min, &res.range.max
1989 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1991 /* Convert the GCC real value representation with the precision
1992 of the real type to the mpfr_t format rounding down in the
1993 first iteration that computes the minimm and up in the second
1994 that computes the maximum. This order is arbibtrary because
1995 rounding in either direction can result in longer output. */
1996 mpfr_t mpfrval;
1997 mpfr_init2 (mpfrval, rfmt->p);
1998 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
2000 /* Use the MPFR rounding specifier to round down in the first
2001 iteration and then up. In most but not all cases this will
2002 result in the same number of bytes. */
2003 char rndspec = "DU"[i];
2005 /* Format it and store the result in the corresponding member
2006 of the result struct. */
2007 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
2008 dir.specifier, rndspec);
2009 mpfr_clear (mpfrval);
2013 /* Make sure the minimum is less than the maximum (MPFR rounding
2014 in the call to mpfr_snprintf can result in the reverse. */
2015 if (res.range.max < res.range.min)
2017 unsigned HOST_WIDE_INT tmp = res.range.min;
2018 res.range.min = res.range.max;
2019 res.range.max = tmp;
2022 /* The range is known unless either width or precision is unknown. */
2023 res.knownrange = dir.known_width_and_precision ();
2025 /* For the same floating point constant, unless width or precision
2026 is unknown, use the longer output as the likely maximum since
2027 with round to nearest either is equally likely. Otheriwse, when
2028 precision is unknown, use the greater of the minimum and 3 as
2029 the likely output (for "0.0" since zero precision is unlikely). */
2030 if (res.knownrange)
2031 res.range.likely = res.range.max;
2032 else if (res.range.min < 3
2033 && dir.prec[0] < 0
2034 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
2035 res.range.likely = 3;
2036 else
2037 res.range.likely = res.range.min;
2039 res.range.unlikely = res.range.max;
2041 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
2043 /* Unless the precision is zero output longer than 2 bytes may
2044 include the decimal point which must be a single character
2045 up to MB_LEN_MAX in length. This is overly conservative
2046 since in some conversions some constants result in no decimal
2047 point (e.g., in %g). */
2048 res.range.unlikely += target_mb_len_max () - 1;
2051 res.adjust_for_width_or_precision (dir.width);
2052 return res;
2055 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
2056 strings referenced by the expression STR, or (-1, -1) when not known.
2057 Used by the format_string function below. */
2059 static fmtresult
2060 get_string_length (tree str)
2062 if (!str)
2063 return fmtresult ();
2065 if (tree slen = c_strlen (str, 1))
2067 /* Simply return the length of the string. */
2068 fmtresult res (tree_to_shwi (slen));
2069 return res;
2072 /* Determine the length of the shortest and longest string referenced
2073 by STR. Strings of unknown lengths are bounded by the sizes of
2074 arrays that subexpressions of STR may refer to. Pointers that
2075 aren't known to point any such arrays result in LENRANGE[1] set
2076 to SIZE_MAX. */
2077 tree lenrange[2];
2078 bool flexarray = get_range_strlen (str, lenrange);
2080 if (lenrange [0] || lenrange [1])
2082 HOST_WIDE_INT min
2083 = (tree_fits_uhwi_p (lenrange[0])
2084 ? tree_to_uhwi (lenrange[0])
2085 : 0);
2087 HOST_WIDE_INT max
2088 = (tree_fits_uhwi_p (lenrange[1])
2089 ? tree_to_uhwi (lenrange[1])
2090 : HOST_WIDE_INT_M1U);
2092 /* get_range_strlen() returns the target value of SIZE_MAX for
2093 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2094 which may be bigger. */
2095 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2096 min = HOST_WIDE_INT_M1U;
2097 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2098 max = HOST_WIDE_INT_M1U;
2100 fmtresult res (min, max);
2102 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2103 by STR are known to be bounded (though not necessarily by their
2104 actual length but perhaps by their maximum possible length). */
2105 if (res.range.max < target_int_max ())
2107 res.knownrange = true;
2108 /* When the the length of the longest string is known and not
2109 excessive use it as the likely length of the string(s). */
2110 res.range.likely = res.range.max;
2112 else
2114 /* When the upper bound is unknown (it can be zero or excessive)
2115 set the likely length to the greater of 1 and the length of
2116 the shortest string and reset the lower bound to zero. */
2117 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2118 res.range.min = 0;
2121 /* If the range of string length has been estimated from the size
2122 of an array at the end of a struct assume that it's longer than
2123 the array bound says it is in case it's used as a poor man's
2124 flexible array member, such as in struct S { char a[4]; }; */
2125 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
2127 return res;
2130 return get_string_length (NULL_TREE);
2133 /* Return the minimum and maximum number of characters formatted
2134 by the '%c' format directives and its wide character form for
2135 the argument ARG. ARG can be null (for functions such as
2136 vsprinf). */
2138 static fmtresult
2139 format_character (const directive &dir, tree arg, vr_values *vr_values)
2141 fmtresult res;
2143 res.knownrange = true;
2145 if (dir.modifier == FMT_LEN_l)
2147 /* A wide character can result in as few as zero bytes. */
2148 res.range.min = 0;
2150 HOST_WIDE_INT min, max;
2151 if (get_int_range (arg, &min, &max, false, 0, vr_values))
2153 if (min == 0 && max == 0)
2155 /* The NUL wide character results in no bytes. */
2156 res.range.max = 0;
2157 res.range.likely = 0;
2158 res.range.unlikely = 0;
2160 else if (min > 0 && min < 128)
2162 /* A wide character in the ASCII range most likely results
2163 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2164 res.range.max = 1;
2165 res.range.likely = 1;
2166 res.range.unlikely = target_mb_len_max ();
2168 else
2170 /* A wide character outside the ASCII range likely results
2171 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2172 res.range.max = target_mb_len_max ();
2173 res.range.likely = 2;
2174 res.range.unlikely = res.range.max;
2177 else
2179 /* An unknown wide character is treated the same as a wide
2180 character outside the ASCII range. */
2181 res.range.max = target_mb_len_max ();
2182 res.range.likely = 2;
2183 res.range.unlikely = res.range.max;
2186 else
2188 /* A plain '%c' directive. Its ouput is exactly 1. */
2189 res.range.min = res.range.max = 1;
2190 res.range.likely = res.range.unlikely = 1;
2191 res.knownrange = true;
2194 /* Bump up the byte counters if WIDTH is greater. */
2195 return res.adjust_for_width_or_precision (dir.width);
2198 /* Return the minimum and maximum number of characters formatted
2199 by the '%s' format directive and its wide character form for
2200 the argument ARG. ARG can be null (for functions such as
2201 vsprinf). */
2203 static fmtresult
2204 format_string (const directive &dir, tree arg, vr_values *)
2206 fmtresult res;
2208 /* Compute the range the argument's length can be in. */
2209 fmtresult slen = get_string_length (arg);
2210 if (slen.range.min == slen.range.max
2211 && slen.range.min < HOST_WIDE_INT_MAX)
2213 /* The argument is either a string constant or it refers
2214 to one of a number of strings of the same length. */
2216 /* A '%s' directive with a string argument with constant length. */
2217 res.range = slen.range;
2219 if (dir.modifier == FMT_LEN_l)
2221 /* In the worst case the length of output of a wide string S
2222 is bounded by MB_LEN_MAX * wcslen (S). */
2223 res.range.max *= target_mb_len_max ();
2224 res.range.unlikely = res.range.max;
2225 /* It's likely that the the total length is not more that
2226 2 * wcslen (S).*/
2227 res.range.likely = res.range.min * 2;
2229 if (dir.prec[1] >= 0
2230 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2232 res.range.max = dir.prec[1];
2233 res.range.likely = dir.prec[1];
2234 res.range.unlikely = dir.prec[1];
2237 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2238 res.range.min = 0;
2239 else if (dir.prec[0] >= 0)
2240 res.range.likely = dir.prec[0];
2242 /* Even a non-empty wide character string need not convert into
2243 any bytes. */
2244 res.range.min = 0;
2246 else
2248 res.knownrange = true;
2250 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2251 res.range.min = 0;
2252 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2253 res.range.min = dir.prec[0];
2255 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2257 res.range.max = dir.prec[1];
2258 res.range.likely = dir.prec[1];
2259 res.range.unlikely = dir.prec[1];
2263 else if (arg && integer_zerop (arg))
2265 /* Handle null pointer argument. */
2267 fmtresult res (0);
2268 res.nullp = true;
2269 return res;
2271 else
2273 /* For a '%s' and '%ls' directive with a non-constant string (either
2274 one of a number of strings of known length or an unknown string)
2275 the minimum number of characters is lesser of PRECISION[0] and
2276 the length of the shortest known string or zero, and the maximum
2277 is the lessser of the length of the longest known string or
2278 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2279 the minimum at level 1 and the greater of the minimum and 1
2280 at level 2. This result is adjust upward for width (if it's
2281 specified). */
2283 if (dir.modifier == FMT_LEN_l)
2285 /* A wide character converts to as few as zero bytes. */
2286 slen.range.min = 0;
2287 if (slen.range.max < target_int_max ())
2288 slen.range.max *= target_mb_len_max ();
2290 if (slen.range.likely < target_int_max ())
2291 slen.range.likely *= 2;
2293 if (slen.range.likely < target_int_max ())
2294 slen.range.unlikely *= target_mb_len_max ();
2297 res.range = slen.range;
2299 if (dir.prec[0] >= 0)
2301 /* Adjust the minimum to zero if the string length is unknown,
2302 or at most the lower bound of the precision otherwise. */
2303 if (slen.range.min >= target_int_max ())
2304 res.range.min = 0;
2305 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2306 res.range.min = dir.prec[0];
2308 /* Make both maxima no greater than the upper bound of precision. */
2309 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2310 || slen.range.max >= target_int_max ())
2312 res.range.max = dir.prec[1];
2313 res.range.unlikely = dir.prec[1];
2316 /* If precision is constant, set the likely counter to the lesser
2317 of it and the maximum string length. Otherwise, if the lower
2318 bound of precision is greater than zero, set the likely counter
2319 to the minimum. Otherwise set it to zero or one based on
2320 the warning level. */
2321 if (dir.prec[0] == dir.prec[1])
2322 res.range.likely
2323 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2324 ? dir.prec[0] : slen.range.max);
2325 else if (dir.prec[0] > 0)
2326 res.range.likely = res.range.min;
2327 else
2328 res.range.likely = warn_level > 1;
2330 else if (dir.prec[1] >= 0)
2332 res.range.min = 0;
2333 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2334 res.range.max = dir.prec[1];
2335 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2337 else if (slen.range.min >= target_int_max ())
2339 res.range.min = 0;
2340 res.range.max = HOST_WIDE_INT_MAX;
2341 /* At level 1 strings of unknown length are assumed to be
2342 empty, while at level 1 they are assumed to be one byte
2343 long. */
2344 res.range.likely = warn_level > 1;
2346 else
2348 /* A string of unknown length unconstrained by precision is
2349 assumed to be empty at level 1 and just one character long
2350 at higher levels. */
2351 if (res.range.likely >= target_int_max ())
2352 res.range.likely = warn_level > 1;
2355 res.range.unlikely = res.range.max;
2358 /* Bump up the byte counters if WIDTH is greater. */
2359 return res.adjust_for_width_or_precision (dir.width);
2362 /* Format plain string (part of the format string itself). */
2364 static fmtresult
2365 format_plain (const directive &dir, tree, vr_values *)
2367 fmtresult res (dir.len);
2368 return res;
2371 /* Return true if the RESULT of a directive in a call describe by INFO
2372 should be diagnosed given the AVAILable space in the destination. */
2374 static bool
2375 should_warn_p (const sprintf_dom_walker::call_info &info,
2376 const result_range &avail, const result_range &result)
2378 if (result.max <= avail.min)
2380 /* The least amount of space remaining in the destination is big
2381 enough for the longest output. */
2382 return false;
2385 if (info.bounded)
2387 if (warn_format_trunc == 1 && result.min <= avail.max
2388 && info.retval_used ())
2390 /* The likely amount of space remaining in the destination is big
2391 enough for the least output and the return value is used. */
2392 return false;
2395 if (warn_format_trunc == 1 && result.likely <= avail.likely
2396 && !info.retval_used ())
2398 /* The likely amount of space remaining in the destination is big
2399 enough for the likely output and the return value is unused. */
2400 return false;
2403 if (warn_format_trunc == 2
2404 && result.likely <= avail.min
2405 && (result.max <= avail.min
2406 || result.max > HOST_WIDE_INT_MAX))
2408 /* The minimum amount of space remaining in the destination is big
2409 enough for the longest output. */
2410 return false;
2413 else
2415 if (warn_level == 1 && result.likely <= avail.likely)
2417 /* The likely amount of space remaining in the destination is big
2418 enough for the likely output. */
2419 return false;
2422 if (warn_level == 2
2423 && result.likely <= avail.min
2424 && (result.max <= avail.min
2425 || result.max > HOST_WIDE_INT_MAX))
2427 /* The minimum amount of space remaining in the destination is big
2428 enough for the longest output. */
2429 return false;
2433 return true;
2436 /* At format string location describe by DIRLOC in a call described
2437 by INFO, issue a warning for a directive DIR whose output may be
2438 in excess of the available space AVAIL_RANGE in the destination
2439 given the formatting result FMTRES. This function does nothing
2440 except decide whether to issue a warning for a possible write
2441 past the end or truncation and, if so, format the warning.
2442 Return true if a warning has been issued. */
2444 static bool
2445 maybe_warn (substring_loc &dirloc, location_t argloc,
2446 const sprintf_dom_walker::call_info &info,
2447 const result_range &avail_range, const result_range &res,
2448 const directive &dir)
2450 if (!should_warn_p (info, avail_range, res))
2451 return false;
2453 /* A warning will definitely be issued below. */
2455 /* The maximum byte count to reference in the warning. Larger counts
2456 imply that the upper bound is unknown (and could be anywhere between
2457 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2458 than "between N and X" where X is some huge number. */
2459 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2461 /* True when there is enough room in the destination for the least
2462 amount of a directive's output but not enough for its likely or
2463 maximum output. */
2464 bool maybe = (res.min <= avail_range.max
2465 && (avail_range.min < res.likely
2466 || (res.max < HOST_WIDE_INT_MAX
2467 && avail_range.min < res.max)));
2469 /* Buffer for the directive in the host character set (used when
2470 the source character set is different). */
2471 char hostdir[32];
2473 if (avail_range.min == avail_range.max)
2475 /* The size of the destination region is exact. */
2476 unsigned HOST_WIDE_INT navail = avail_range.max;
2478 if (target_to_host (*dir.beg) != '%')
2480 /* For plain character directives (i.e., the format string itself)
2481 but not others, point the caret at the first character that's
2482 past the end of the destination. */
2483 if (navail < dir.len)
2484 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2487 if (*dir.beg == '\0')
2489 /* This is the terminating nul. */
2490 gcc_assert (res.min == 1 && res.min == res.max);
2492 const char *fmtstr
2493 = (info.bounded
2494 ? (maybe
2495 ? G_("%qE output may be truncated before the last format "
2496 "character")
2497 : G_("%qE output truncated before the last format character"))
2498 : (maybe
2499 ? G_("%qE may write a terminating nul past the end "
2500 "of the destination")
2501 : G_("%qE writing a terminating nul past the end "
2502 "of the destination")));
2504 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2505 fmtstr, info.func);
2508 if (res.min == res.max)
2510 const char* fmtstr
2511 = (res.min == 1
2512 ? (info.bounded
2513 ? (maybe
2514 ? G_("%<%.*s%> directive output may be truncated writing "
2515 "%wu byte into a region of size %wu")
2516 : G_("%<%.*s%> directive output truncated writing "
2517 "%wu byte into a region of size %wu"))
2518 : G_("%<%.*s%> directive writing %wu byte "
2519 "into a region of size %wu"))
2520 : (info.bounded
2521 ? (maybe
2522 ? G_("%<%.*s%> directive output may be truncated writing "
2523 "%wu bytes into a region of size %wu")
2524 : G_("%<%.*s%> directive output truncated writing "
2525 "%wu bytes into a region of size %wu"))
2526 : G_("%<%.*s%> directive writing %wu bytes "
2527 "into a region of size %wu")));
2528 return fmtwarn (dirloc, argloc, NULL,
2529 info.warnopt (), fmtstr, dir.len,
2530 target_to_host (hostdir, sizeof hostdir, dir.beg),
2531 res.min, navail);
2534 if (res.min == 0 && res.max < maxbytes)
2536 const char* fmtstr
2537 = (info.bounded
2538 ? (maybe
2539 ? G_("%<%.*s%> directive output may be truncated writing "
2540 "up to %wu bytes into a region of size %wu")
2541 : G_("%<%.*s%> directive output truncated writing "
2542 "up to %wu bytes into a region of size %wu"))
2543 : G_("%<%.*s%> directive writing up to %wu bytes "
2544 "into a region of size %wu"));
2545 return fmtwarn (dirloc, argloc, NULL,
2546 info.warnopt (), fmtstr, dir.len,
2547 target_to_host (hostdir, sizeof hostdir, dir.beg),
2548 res.max, navail);
2551 if (res.min == 0 && maxbytes <= res.max)
2553 /* This is a special case to avoid issuing the potentially
2554 confusing warning:
2555 writing 0 or more bytes into a region of size 0. */
2556 const char* fmtstr
2557 = (info.bounded
2558 ? (maybe
2559 ? G_("%<%.*s%> directive output may be truncated writing "
2560 "likely %wu or more bytes into a region of size %wu")
2561 : G_("%<%.*s%> directive output truncated writing "
2562 "likely %wu or more bytes into a region of size %wu"))
2563 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2564 "into a region of size %wu"));
2565 return fmtwarn (dirloc, argloc, NULL,
2566 info.warnopt (), fmtstr, dir.len,
2567 target_to_host (hostdir, sizeof hostdir, dir.beg),
2568 res.likely, navail);
2571 if (res.max < maxbytes)
2573 const char* fmtstr
2574 = (info.bounded
2575 ? (maybe
2576 ? G_("%<%.*s%> directive output may be truncated writing "
2577 "between %wu and %wu bytes into a region of size %wu")
2578 : G_("%<%.*s%> directive output truncated writing "
2579 "between %wu and %wu bytes into a region of size %wu"))
2580 : G_("%<%.*s%> directive writing between %wu and "
2581 "%wu bytes into a region of size %wu"));
2582 return fmtwarn (dirloc, argloc, NULL,
2583 info.warnopt (), fmtstr, dir.len,
2584 target_to_host (hostdir, sizeof hostdir, dir.beg),
2585 res.min, res.max, navail);
2588 const char* fmtstr
2589 = (info.bounded
2590 ? (maybe
2591 ? G_("%<%.*s%> directive output may be truncated writing "
2592 "%wu or more bytes into a region of size %wu")
2593 : G_("%<%.*s%> directive output truncated writing "
2594 "%wu or more bytes into a region of size %wu"))
2595 : G_("%<%.*s%> directive writing %wu or more bytes "
2596 "into a region of size %wu"));
2597 return fmtwarn (dirloc, argloc, NULL,
2598 info.warnopt (), fmtstr, dir.len,
2599 target_to_host (hostdir, sizeof hostdir, dir.beg),
2600 res.min, navail);
2603 /* The size of the destination region is a range. */
2605 if (target_to_host (*dir.beg) != '%')
2607 unsigned HOST_WIDE_INT navail = avail_range.max;
2609 /* For plain character directives (i.e., the format string itself)
2610 but not others, point the caret at the first character that's
2611 past the end of the destination. */
2612 if (navail < dir.len)
2613 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2616 if (*dir.beg == '\0')
2618 gcc_assert (res.min == 1 && res.min == res.max);
2620 const char *fmtstr
2621 = (info.bounded
2622 ? (maybe
2623 ? G_("%qE output may be truncated before the last format "
2624 "character")
2625 : G_("%qE output truncated before the last format character"))
2626 : (maybe
2627 ? G_("%qE may write a terminating nul past the end "
2628 "of the destination")
2629 : G_("%qE writing a terminating nul past the end "
2630 "of the destination")));
2632 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (), fmtstr,
2633 info.func);
2636 if (res.min == res.max)
2638 const char* fmtstr
2639 = (res.min == 1
2640 ? (info.bounded
2641 ? (maybe
2642 ? G_("%<%.*s%> directive output may be truncated writing "
2643 "%wu byte into a region of size between %wu and %wu")
2644 : G_("%<%.*s%> directive output truncated writing "
2645 "%wu byte into a region of size between %wu and %wu"))
2646 : G_("%<%.*s%> directive writing %wu byte "
2647 "into a region of size between %wu and %wu"))
2648 : (info.bounded
2649 ? (maybe
2650 ? G_("%<%.*s%> directive output may be truncated writing "
2651 "%wu bytes into a region of size between %wu and %wu")
2652 : G_("%<%.*s%> directive output truncated writing "
2653 "%wu bytes into a region of size between %wu and %wu"))
2654 : G_("%<%.*s%> directive writing %wu bytes "
2655 "into a region of size between %wu and %wu")));
2657 return fmtwarn (dirloc, argloc, NULL,
2658 info.warnopt (), fmtstr, dir.len,
2659 target_to_host (hostdir, sizeof hostdir, dir.beg),
2660 res.min, avail_range.min, avail_range.max);
2663 if (res.min == 0 && res.max < maxbytes)
2665 const char* fmtstr
2666 = (info.bounded
2667 ? (maybe
2668 ? G_("%<%.*s%> directive output may be truncated writing "
2669 "up to %wu bytes into a region of size between "
2670 "%wu and %wu")
2671 : G_("%<%.*s%> directive output truncated writing "
2672 "up to %wu bytes into a region of size between "
2673 "%wu and %wu"))
2674 : G_("%<%.*s%> directive writing up to %wu bytes "
2675 "into a region of size between %wu and %wu"));
2676 return fmtwarn (dirloc, argloc, NULL,
2677 info.warnopt (), fmtstr, dir.len,
2678 target_to_host (hostdir, sizeof hostdir, dir.beg),
2679 res.max, avail_range.min, avail_range.max);
2682 if (res.min == 0 && maxbytes <= res.max)
2684 /* This is a special case to avoid issuing the potentially confusing
2685 warning:
2686 writing 0 or more bytes into a region of size between 0 and N. */
2687 const char* fmtstr
2688 = (info.bounded
2689 ? (maybe
2690 ? G_("%<%.*s%> directive output may be truncated writing "
2691 "likely %wu or more bytes into a region of size between "
2692 "%wu and %wu")
2693 : G_("%<%.*s%> directive output truncated writing likely "
2694 "%wu or more bytes into a region of size between "
2695 "%wu and %wu"))
2696 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2697 "into a region of size between %wu and %wu"));
2698 return fmtwarn (dirloc, argloc, NULL,
2699 info.warnopt (), fmtstr, dir.len,
2700 target_to_host (hostdir, sizeof hostdir, dir.beg),
2701 res.likely, avail_range.min, avail_range.max);
2704 if (res.max < maxbytes)
2706 const char* fmtstr
2707 = (info.bounded
2708 ? (maybe
2709 ? G_("%<%.*s%> directive output may be truncated writing "
2710 "between %wu and %wu bytes into a region of size "
2711 "between %wu and %wu")
2712 : G_("%<%.*s%> directive output truncated writing "
2713 "between %wu and %wu bytes into a region of size "
2714 "between %wu and %wu"))
2715 : G_("%<%.*s%> directive writing between %wu and "
2716 "%wu bytes into a region of size between %wu and %wu"));
2717 return fmtwarn (dirloc, argloc, NULL,
2718 info.warnopt (), fmtstr, dir.len,
2719 target_to_host (hostdir, sizeof hostdir, dir.beg),
2720 res.min, res.max, avail_range.min, avail_range.max);
2723 const char* fmtstr
2724 = (info.bounded
2725 ? (maybe
2726 ? G_("%<%.*s%> directive output may be truncated writing "
2727 "%wu or more bytes into a region of size between "
2728 "%wu and %wu")
2729 : G_("%<%.*s%> directive output truncated writing "
2730 "%wu or more bytes into a region of size between "
2731 "%wu and %wu"))
2732 : G_("%<%.*s%> directive writing %wu or more bytes "
2733 "into a region of size between %wu and %wu"));
2734 return fmtwarn (dirloc, argloc, NULL,
2735 info.warnopt (), fmtstr, dir.len,
2736 target_to_host (hostdir, sizeof hostdir, dir.beg),
2737 res.min, avail_range.min, avail_range.max);
2740 /* Compute the length of the output resulting from the directive DIR
2741 in a call described by INFO and update the overall result of the call
2742 in *RES. Return true if the directive has been handled. */
2744 static bool
2745 format_directive (const sprintf_dom_walker::call_info &info,
2746 format_result *res, const directive &dir,
2747 class vr_values *vr_values)
2749 /* Offset of the beginning of the directive from the beginning
2750 of the format string. */
2751 size_t offset = dir.beg - info.fmtstr;
2752 size_t start = offset;
2753 size_t length = offset + dir.len - !!dir.len;
2755 /* Create a location for the whole directive from the % to the format
2756 specifier. */
2757 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2758 offset, start, length);
2760 /* Also get the location of the argument if possible.
2761 This doesn't work for integer literals or function calls. */
2762 location_t argloc = UNKNOWN_LOCATION;
2763 if (dir.arg)
2764 argloc = EXPR_LOCATION (dir.arg);
2766 /* Bail when there is no function to compute the output length,
2767 or when minimum length checking has been disabled. */
2768 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2769 return false;
2771 /* Compute the range of lengths of the formatted output. */
2772 fmtresult fmtres = dir.fmtfunc (dir, dir.arg, vr_values);
2774 /* Record whether the output of all directives is known to be
2775 bounded by some maximum, implying that their arguments are
2776 either known exactly or determined to be in a known range
2777 or, for strings, limited by the upper bounds of the arrays
2778 they refer to. */
2779 res->knownrange &= fmtres.knownrange;
2781 if (!fmtres.knownrange)
2783 /* Only when the range is known, check it against the host value
2784 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2785 INT_MAX precision, which is the longest possible output of any
2786 single directive). That's the largest valid byte count (though
2787 not valid call to a printf-like function because it can never
2788 return such a count). Otherwise, the range doesn't correspond
2789 to known values of the argument. */
2790 if (fmtres.range.max > target_dir_max ())
2792 /* Normalize the MAX counter to avoid having to deal with it
2793 later. The counter can be less than HOST_WIDE_INT_M1U
2794 when compiling for an ILP32 target on an LP64 host. */
2795 fmtres.range.max = HOST_WIDE_INT_M1U;
2796 /* Disable exact and maximum length checking after a failure
2797 to determine the maximum number of characters (for example
2798 for wide characters or wide character strings) but continue
2799 tracking the minimum number of characters. */
2800 res->range.max = HOST_WIDE_INT_M1U;
2803 if (fmtres.range.min > target_dir_max ())
2805 /* Disable exact length checking after a failure to determine
2806 even the minimum number of characters (it shouldn't happen
2807 except in an error) but keep tracking the minimum and maximum
2808 number of characters. */
2809 return true;
2813 /* Buffer for the directive in the host character set (used when
2814 the source character set is different). */
2815 char hostdir[32];
2817 int dirlen = dir.len;
2819 if (fmtres.nullp)
2821 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2822 "%<%.*s%> directive argument is null",
2823 dirlen, target_to_host (hostdir, sizeof hostdir, dir.beg));
2825 /* Don't bother processing the rest of the format string. */
2826 res->warned = true;
2827 res->range.min = HOST_WIDE_INT_M1U;
2828 res->range.max = HOST_WIDE_INT_M1U;
2829 return false;
2832 /* Compute the number of available bytes in the destination. There
2833 must always be at least one byte of space for the terminating
2834 NUL that's appended after the format string has been processed. */
2835 result_range avail_range = bytes_remaining (info.objsize, *res);
2837 bool warned = res->warned;
2839 if (!warned)
2840 warned = maybe_warn (dirloc, argloc, info, avail_range,
2841 fmtres.range, dir);
2843 /* Bump up the total maximum if it isn't too big. */
2844 if (res->range.max < HOST_WIDE_INT_MAX
2845 && fmtres.range.max < HOST_WIDE_INT_MAX)
2846 res->range.max += fmtres.range.max;
2848 /* Raise the total unlikely maximum by the larger of the maximum
2849 and the unlikely maximum. */
2850 unsigned HOST_WIDE_INT save = res->range.unlikely;
2851 if (fmtres.range.max < fmtres.range.unlikely)
2852 res->range.unlikely += fmtres.range.unlikely;
2853 else
2854 res->range.unlikely += fmtres.range.max;
2856 if (res->range.unlikely < save)
2857 res->range.unlikely = HOST_WIDE_INT_M1U;
2859 res->range.min += fmtres.range.min;
2860 res->range.likely += fmtres.range.likely;
2862 /* Has the minimum directive output length exceeded the maximum
2863 of 4095 bytes required to be supported? */
2864 bool minunder4k = fmtres.range.min < 4096;
2865 bool maxunder4k = fmtres.range.max < 4096;
2866 /* Clear UNDER4K in the overall result if the maximum has exceeded
2867 the 4k (this is necessary to avoid the return valuye optimization
2868 that may not be safe in the maximum case). */
2869 if (!maxunder4k)
2870 res->under4k = false;
2872 if (!warned
2873 /* Only warn at level 2. */
2874 && warn_level > 1
2875 && (!minunder4k
2876 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2878 /* The directive output may be longer than the maximum required
2879 to be handled by an implementation according to 7.21.6.1, p15
2880 of C11. Warn on this only at level 2 but remember this and
2881 prevent folding the return value when done. This allows for
2882 the possibility of the actual libc call failing due to ENOMEM
2883 (like Glibc does under some conditions). */
2885 if (fmtres.range.min == fmtres.range.max)
2886 warned = fmtwarn (dirloc, argloc, NULL,
2887 info.warnopt (),
2888 "%<%.*s%> directive output of %wu bytes exceeds "
2889 "minimum required size of 4095",
2890 dirlen,
2891 target_to_host (hostdir, sizeof hostdir, dir.beg),
2892 fmtres.range.min);
2893 else
2895 const char *fmtstr
2896 = (minunder4k
2897 ? G_("%<%.*s%> directive output between %wu and %wu "
2898 "bytes may exceed minimum required size of 4095")
2899 : G_("%<%.*s%> directive output between %wu and %wu "
2900 "bytes exceeds minimum required size of 4095"));
2902 warned = fmtwarn (dirloc, argloc, NULL,
2903 info.warnopt (), fmtstr, dirlen,
2904 target_to_host (hostdir, sizeof hostdir, dir.beg),
2905 fmtres.range.min, fmtres.range.max);
2909 /* Has the likely and maximum directive output exceeded INT_MAX? */
2910 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2911 /* Don't consider the maximum to be in excess when it's the result
2912 of a string of unknown length (i.e., whose maximum has been set
2913 to be greater than or equal to HOST_WIDE_INT_MAX. */
2914 bool maxximax = (*dir.beg
2915 && res->range.max > target_int_max ()
2916 && res->range.max < HOST_WIDE_INT_MAX);
2918 if (!warned
2919 /* Warn for the likely output size at level 1. */
2920 && (likelyximax
2921 /* But only warn for the maximum at level 2. */
2922 || (warn_level > 1
2923 && maxximax
2924 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2926 /* The directive output causes the total length of output
2927 to exceed INT_MAX bytes. */
2929 if (fmtres.range.min == fmtres.range.max)
2930 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2931 "%<%.*s%> directive output of %wu bytes causes "
2932 "result to exceed %<INT_MAX%>",
2933 dirlen,
2934 target_to_host (hostdir, sizeof hostdir, dir.beg),
2935 fmtres.range.min);
2936 else
2938 const char *fmtstr
2939 = (fmtres.range.min > target_int_max ()
2940 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2941 "bytes causes result to exceed %<INT_MAX%>")
2942 : G_ ("%<%.*s%> directive output between %wu and %wu "
2943 "bytes may cause result to exceed %<INT_MAX%>"));
2944 warned = fmtwarn (dirloc, argloc, NULL,
2945 info.warnopt (), fmtstr, dirlen,
2946 target_to_host (hostdir, sizeof hostdir, dir.beg),
2947 fmtres.range.min, fmtres.range.max);
2951 if (warned && fmtres.range.min < fmtres.range.likely
2952 && fmtres.range.likely < fmtres.range.max)
2953 /* Some languages have special plural rules even for large values,
2954 but it is periodic with period of 10, 100, 1000 etc. */
2955 inform_n (info.fmtloc, 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);