PR tree-optimization/81184
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
bloba2dd54502e854781ee435df8dd3073325f39f353
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"
84 /* The likely worst case value of MB_LEN_MAX for the target, large enough
85 for UTF-8. Ideally, this would be obtained by a target hook if it were
86 to be used for optimization but it's good enough as is for warnings. */
87 #define target_mb_len_max() 6
89 /* The maximum number of bytes a single non-string directive can result
90 in. This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
91 LDBL_MAX_10_EXP of 4932. */
92 #define IEEE_MAX_10_EXP 4932
93 #define target_dir_max() (target_int_max () + IEEE_MAX_10_EXP + 2)
95 namespace {
97 const pass_data pass_data_sprintf_length = {
98 GIMPLE_PASS, // pass type
99 "printf-return-value", // pass name
100 OPTGROUP_NONE, // optinfo_flags
101 TV_NONE, // tv_id
102 PROP_cfg, // properties_required
103 0, // properties_provided
104 0, // properties_destroyed
105 0, // properties_start
106 0, // properties_finish
109 /* Set to the warning level for the current function which is equal
110 either to warn_format_trunc for bounded functions or to
111 warn_format_overflow otherwise. */
113 static int warn_level;
115 struct format_result;
117 class sprintf_dom_walker : public dom_walker
119 public:
120 sprintf_dom_walker () : dom_walker (CDI_DOMINATORS) {}
121 ~sprintf_dom_walker () {}
123 edge before_dom_children (basic_block) FINAL OVERRIDE;
124 bool handle_gimple_call (gimple_stmt_iterator *);
126 struct call_info;
127 bool compute_format_length (call_info &, format_result *);
130 class pass_sprintf_length : public gimple_opt_pass
132 bool fold_return_value;
134 public:
135 pass_sprintf_length (gcc::context *ctxt)
136 : gimple_opt_pass (pass_data_sprintf_length, ctxt),
137 fold_return_value (false)
140 opt_pass * clone () { return new pass_sprintf_length (m_ctxt); }
142 virtual bool gate (function *);
144 virtual unsigned int execute (function *);
146 void set_pass_param (unsigned int n, bool param)
148 gcc_assert (n == 0);
149 fold_return_value = param;
154 bool
155 pass_sprintf_length::gate (function *)
157 /* Run the pass iff -Warn-format-overflow or -Warn-format-truncation
158 is specified and either not optimizing and the pass is being invoked
159 early, or when optimizing and the pass is being invoked during
160 optimization (i.e., "late"). */
161 return ((warn_format_overflow > 0
162 || warn_format_trunc > 0
163 || flag_printf_return_value)
164 && (optimize > 0) == fold_return_value);
167 /* The minimum, maximum, likely, and unlikely maximum number of bytes
168 of output either a formatting function or an individual directive
169 can result in. */
171 struct result_range
173 /* The absolute minimum number of bytes. The result of a successful
174 conversion is guaranteed to be no less than this. (An erroneous
175 conversion can be indicated by MIN > HOST_WIDE_INT_MAX.) */
176 unsigned HOST_WIDE_INT min;
177 /* The likely maximum result that is used in diagnostics. In most
178 cases MAX is the same as the worst case UNLIKELY result. */
179 unsigned HOST_WIDE_INT max;
180 /* The likely result used to trigger diagnostics. For conversions
181 that result in a range of bytes [MIN, MAX], LIKELY is somewhere
182 in that range. */
183 unsigned HOST_WIDE_INT likely;
184 /* In rare cases (e.g., for nultibyte characters) UNLIKELY gives
185 the worst cases maximum result of a directive. In most cases
186 UNLIKELY == MAX. UNLIKELY is used to control the return value
187 optimization but not in diagnostics. */
188 unsigned HOST_WIDE_INT unlikely;
191 /* The result of a call to a formatted function. */
193 struct format_result
195 /* Range of characters written by the formatted function.
196 Setting the minimum to HOST_WIDE_INT_MAX disables all
197 length tracking for the remainder of the format string. */
198 result_range range;
200 /* True when the range above is obtained from known values of
201 directive arguments, or bounds on the amount of output such
202 as width and precision, and not the result of heuristics that
203 depend on warning levels. It's used to issue stricter diagnostics
204 in cases where strings of unknown lengths are bounded by the arrays
205 they are determined to refer to. KNOWNRANGE must not be used for
206 the return value optimization. */
207 bool knownrange;
209 /* True if no individual directive resulted in more than 4095 bytes
210 of output (the total NUMBER_CHARS_{MIN,MAX} might be greater).
211 Implementations are not required to handle directives that produce
212 more than 4K bytes (leading to undefined behavior) and so when one
213 is found it disables the return value optimization. */
214 bool under4k;
216 /* True when a floating point directive has been seen in the format
217 string. */
218 bool floating;
220 /* True when an intermediate result has caused a warning. Used to
221 avoid issuing duplicate warnings while finishing the processing
222 of a call. WARNED also disables the return value optimization. */
223 bool warned;
225 /* Preincrement the number of output characters by 1. */
226 format_result& operator++ ()
228 return *this += 1;
231 /* Postincrement the number of output characters by 1. */
232 format_result operator++ (int)
234 format_result prev (*this);
235 *this += 1;
236 return prev;
239 /* Increment the number of output characters by N. */
240 format_result& operator+= (unsigned HOST_WIDE_INT);
243 format_result&
244 format_result::operator+= (unsigned HOST_WIDE_INT n)
246 gcc_assert (n < HOST_WIDE_INT_MAX);
248 if (range.min < HOST_WIDE_INT_MAX)
249 range.min += n;
251 if (range.max < HOST_WIDE_INT_MAX)
252 range.max += n;
254 if (range.likely < HOST_WIDE_INT_MAX)
255 range.likely += n;
257 if (range.unlikely < HOST_WIDE_INT_MAX)
258 range.unlikely += n;
260 return *this;
263 /* Return the value of INT_MIN for the target. */
265 static inline HOST_WIDE_INT
266 target_int_min ()
268 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
271 /* Return the value of INT_MAX for the target. */
273 static inline unsigned HOST_WIDE_INT
274 target_int_max ()
276 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
279 /* Return the value of SIZE_MAX for the target. */
281 static inline unsigned HOST_WIDE_INT
282 target_size_max ()
284 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
287 /* A straightforward mapping from the execution character set to the host
288 character set indexed by execution character. */
290 static char target_to_host_charmap[256];
292 /* Initialize a mapping from the execution character set to the host
293 character set. */
295 static bool
296 init_target_to_host_charmap ()
298 /* If the percent sign is non-zero the mapping has already been
299 initialized. */
300 if (target_to_host_charmap['%'])
301 return true;
303 /* Initialize the target_percent character (done elsewhere). */
304 if (!init_target_chars ())
305 return false;
307 /* The subset of the source character set used by printf conversion
308 specifications (strictly speaking, not all letters are used but
309 they are included here for the sake of simplicity). The dollar
310 sign must be included even though it's not in the basic source
311 character set. */
312 const char srcset[] = " 0123456789!\"#%&'()*+,-./:;<=>?[\\]^_{|}~$"
313 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
315 /* Set the mapping for all characters to some ordinary value (i,e.,
316 not none used in printf conversion specifications) and overwrite
317 those that are used by conversion specifications with their
318 corresponding values. */
319 memset (target_to_host_charmap + 1, '?', sizeof target_to_host_charmap - 1);
321 /* Are the two sets of characters the same? */
322 bool all_same_p = true;
324 for (const char *pc = srcset; *pc; ++pc)
326 /* Slice off the high end bits in case target characters are
327 signed. All values are expected to be non-nul, otherwise
328 there's a problem. */
329 if (unsigned char tc = lang_hooks.to_target_charset (*pc))
331 target_to_host_charmap[tc] = *pc;
332 if (tc != *pc)
333 all_same_p = false;
335 else
336 return false;
340 /* Set the first element to a non-zero value if the mapping
341 is 1-to-1, otherwise leave it clear (NUL is assumed to be
342 the same in both character sets). */
343 target_to_host_charmap[0] = all_same_p;
345 return true;
348 /* Return the host source character corresponding to the character
349 CH in the execution character set if one exists, or some innocuous
350 (non-special, non-nul) source character otherwise. */
352 static inline unsigned char
353 target_to_host (unsigned char ch)
355 return target_to_host_charmap[ch];
358 /* Convert an initial substring of the string TARGSTR consisting of
359 characters in the execution character set into a string in the
360 source character set on the host and store up to HOSTSZ characters
361 in the buffer pointed to by HOSTR. Return HOSTR. */
363 static const char*
364 target_to_host (char *hostr, size_t hostsz, const char *targstr)
366 /* Make sure the buffer is reasonably big. */
367 gcc_assert (hostsz > 4);
369 /* The interesting subset of source and execution characters are
370 the same so no conversion is necessary. However, truncate
371 overlong strings just like the translated strings are. */
372 if (target_to_host_charmap['\0'] == 1)
374 strncpy (hostr, targstr, hostsz - 4);
375 if (strlen (targstr) >= hostsz)
376 strcpy (hostr + hostsz - 4, "...");
377 return hostr;
380 /* Convert the initial substring of TARGSTR to the corresponding
381 characters in the host set, appending "..." if TARGSTR is too
382 long to fit. Using the static buffer assumes the function is
383 not called in between sequence points (which it isn't). */
384 for (char *ph = hostr; ; ++targstr)
386 *ph++ = target_to_host (*targstr);
387 if (!*targstr)
388 break;
390 if (size_t (ph - hostr) == hostsz - 4)
392 *ph = '\0';
393 strcat (ph, "...");
394 break;
398 return hostr;
401 /* Convert the sequence of decimal digits in the execution character
402 starting at S to a long, just like strtol does. Return the result
403 and set *END to one past the last converted character. On range
404 error set ERANGE to the digit that caused it. */
406 static inline long
407 target_strtol10 (const char **ps, const char **erange)
409 unsigned HOST_WIDE_INT val = 0;
410 for ( ; ; ++*ps)
412 unsigned char c = target_to_host (**ps);
413 if (ISDIGIT (c))
415 c -= '0';
417 /* Check for overflow. */
418 if (val > (LONG_MAX - c) / 10LU)
420 val = LONG_MAX;
421 *erange = *ps;
423 /* Skip the remaining digits. */
425 c = target_to_host (*++*ps);
426 while (ISDIGIT (c));
427 break;
429 else
430 val = val * 10 + c;
432 else
433 break;
436 return val;
439 /* Return the constant initial value of DECL if available or DECL
440 otherwise. Same as the synonymous function in c/c-typeck.c. */
442 static tree
443 decl_constant_value (tree decl)
445 if (/* Don't change a variable array bound or initial value to a constant
446 in a place where a variable is invalid. Note that DECL_INITIAL
447 isn't valid for a PARM_DECL. */
448 current_function_decl != 0
449 && TREE_CODE (decl) != PARM_DECL
450 && !TREE_THIS_VOLATILE (decl)
451 && TREE_READONLY (decl)
452 && DECL_INITIAL (decl) != 0
453 && TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK
454 /* This is invalid if initial value is not constant.
455 If it has either a function call, a memory reference,
456 or a variable, then re-evaluating it could give different results. */
457 && TREE_CONSTANT (DECL_INITIAL (decl))
458 /* Check for cases where this is sub-optimal, even though valid. */
459 && TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)
460 return DECL_INITIAL (decl);
461 return decl;
464 /* Given FORMAT, set *PLOC to the source location of the format string
465 and return the format string if it is known or null otherwise. */
467 static const char*
468 get_format_string (tree format, location_t *ploc)
470 if (VAR_P (format))
472 /* Pull out a constant value if the front end didn't. */
473 format = decl_constant_value (format);
474 STRIP_NOPS (format);
477 if (integer_zerop (format))
479 /* FIXME: Diagnose null format string if it hasn't been diagnosed
480 by -Wformat (the latter diagnoses only nul pointer constants,
481 this pass can do better). */
482 return NULL;
485 HOST_WIDE_INT offset = 0;
487 if (TREE_CODE (format) == POINTER_PLUS_EXPR)
489 tree arg0 = TREE_OPERAND (format, 0);
490 tree arg1 = TREE_OPERAND (format, 1);
491 STRIP_NOPS (arg0);
492 STRIP_NOPS (arg1);
494 if (TREE_CODE (arg1) != INTEGER_CST)
495 return NULL;
497 format = arg0;
499 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
500 if (!cst_and_fits_in_hwi (arg1))
501 return NULL;
503 offset = int_cst_value (arg1);
506 if (TREE_CODE (format) != ADDR_EXPR)
507 return NULL;
509 *ploc = EXPR_LOC_OR_LOC (format, input_location);
511 format = TREE_OPERAND (format, 0);
513 if (TREE_CODE (format) == ARRAY_REF
514 && tree_fits_shwi_p (TREE_OPERAND (format, 1))
515 && (offset += tree_to_shwi (TREE_OPERAND (format, 1))) >= 0)
516 format = TREE_OPERAND (format, 0);
518 if (offset < 0)
519 return NULL;
521 tree array_init;
522 tree array_size = NULL_TREE;
524 if (VAR_P (format)
525 && TREE_CODE (TREE_TYPE (format)) == ARRAY_TYPE
526 && (array_init = decl_constant_value (format)) != format
527 && TREE_CODE (array_init) == STRING_CST)
529 /* Extract the string constant initializer. Note that this may
530 include a trailing NUL character that is not in the array (e.g.
531 const char a[3] = "foo";). */
532 array_size = DECL_SIZE_UNIT (format);
533 format = array_init;
536 if (TREE_CODE (format) != STRING_CST)
537 return NULL;
539 tree type = TREE_TYPE (format);
541 scalar_int_mode char_mode;
542 if (!is_int_mode (TYPE_MODE (TREE_TYPE (type)), &char_mode)
543 || GET_MODE_SIZE (char_mode) != 1)
545 /* Wide format string. */
546 return NULL;
549 const char *fmtstr = TREE_STRING_POINTER (format);
550 unsigned fmtlen = TREE_STRING_LENGTH (format);
552 if (array_size)
554 /* Variable length arrays can't be initialized. */
555 gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
557 if (tree_fits_shwi_p (array_size))
559 HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
560 if (array_size_value > 0
561 && array_size_value == (int) array_size_value
562 && fmtlen > array_size_value)
563 fmtlen = array_size_value;
566 if (offset)
568 if (offset >= fmtlen)
569 return NULL;
571 fmtstr += offset;
572 fmtlen -= offset;
575 if (fmtlen < 1 || fmtstr[--fmtlen] != 0)
577 /* FIXME: Diagnose an unterminated format string if it hasn't been
578 diagnosed by -Wformat. Similarly to a null format pointer,
579 -Wformay diagnoses only nul pointer constants, this pass can
580 do better). */
581 return NULL;
584 return fmtstr;
587 /* The format_warning_at_substring function is not used here in a way
588 that makes using attribute format viable. Suppress the warning. */
590 #pragma GCC diagnostic push
591 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
593 /* For convenience and brevity. */
595 static bool
596 (* const fmtwarn) (const substring_loc &, location_t,
597 const char *, int, const char *, ...)
598 = format_warning_at_substring;
600 /* Format length modifiers. */
602 enum format_lengths
604 FMT_LEN_none,
605 FMT_LEN_hh, // char argument
606 FMT_LEN_h, // short
607 FMT_LEN_l, // long
608 FMT_LEN_ll, // long long
609 FMT_LEN_L, // long double (and GNU long long)
610 FMT_LEN_z, // size_t
611 FMT_LEN_t, // ptrdiff_t
612 FMT_LEN_j // intmax_t
616 /* Description of the result of conversion either of a single directive
617 or the whole format string. */
619 struct fmtresult
621 /* Construct a FMTRESULT object with all counters initialized
622 to MIN. KNOWNRANGE is set when MIN is valid. */
623 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
624 : argmin (), argmax (),
625 knownrange (min < HOST_WIDE_INT_MAX),
626 nullp ()
628 range.min = min;
629 range.max = min;
630 range.likely = min;
631 range.unlikely = min;
634 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
635 KNOWNRANGE is set when both MIN and MAX are valid. */
636 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
637 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
638 : argmin (), argmax (),
639 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
640 nullp ()
642 range.min = min;
643 range.max = max;
644 range.likely = max < likely ? min : likely;
645 range.unlikely = max;
648 /* Adjust result upward to reflect the RANGE of values the specified
649 width or precision is known to be in. */
650 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
651 tree = NULL_TREE,
652 unsigned = 0, unsigned = 0);
654 /* Return the maximum number of decimal digits a value of TYPE
655 formats as on output. */
656 static unsigned type_max_digits (tree, int);
658 /* The range a directive's argument is in. */
659 tree argmin, argmax;
661 /* The minimum and maximum number of bytes that a directive
662 results in on output for an argument in the range above. */
663 result_range range;
665 /* True when the range above is obtained from a known value of
666 a directive's argument or its bounds and not the result of
667 heuristics that depend on warning levels. */
668 bool knownrange;
670 /* True when the argument is a null pointer. */
671 bool nullp;
674 /* Adjust result upward to reflect the range ADJUST of values the
675 specified width or precision is known to be in. When non-null,
676 TYPE denotes the type of the directive whose result is being
677 adjusted, BASE gives the base of the directive (octal, decimal,
678 or hex), and ADJ denotes the additional adjustment to the LIKELY
679 counter that may need to be added when ADJUST is a range. */
681 fmtresult&
682 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
683 tree type /* = NULL_TREE */,
684 unsigned base /* = 0 */,
685 unsigned adj /* = 0 */)
687 bool minadjusted = false;
689 /* Adjust the minimum and likely counters. */
690 if (adjust[0] >= 0)
692 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
694 range.min = adjust[0];
695 minadjusted = true;
698 /* Adjust the likely counter. */
699 if (range.likely < range.min)
700 range.likely = range.min;
702 else if (adjust[0] == target_int_min ()
703 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
704 knownrange = false;
706 /* Adjust the maximum counter. */
707 if (adjust[1] > 0)
709 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
711 range.max = adjust[1];
713 /* Set KNOWNRANGE if both the minimum and maximum have been
714 adjusted. Otherwise leave it at what it was before. */
715 knownrange = minadjusted;
719 if (warn_level > 1 && type)
721 /* For large non-constant width or precision whose range spans
722 the maximum number of digits produced by the directive for
723 any argument, set the likely number of bytes to be at most
724 the number digits plus other adjustment determined by the
725 caller (one for sign or two for the hexadecimal "0x"
726 prefix). */
727 unsigned dirdigs = type_max_digits (type, base);
728 if (adjust[0] < dirdigs && dirdigs < adjust[1]
729 && range.likely < dirdigs)
730 range.likely = dirdigs + adj;
732 else if (range.likely < (range.min ? range.min : 1))
734 /* Conservatively, set LIKELY to at least MIN but no less than
735 1 unless MAX is zero. */
736 range.likely = (range.min
737 ? range.min
738 : range.max && (range.max < HOST_WIDE_INT_MAX
739 || warn_level > 1) ? 1 : 0);
742 /* Finally adjust the unlikely counter to be at least as large as
743 the maximum. */
744 if (range.unlikely < range.max)
745 range.unlikely = range.max;
747 return *this;
750 /* Return the maximum number of digits a value of TYPE formats in
751 BASE on output, not counting base prefix . */
753 unsigned
754 fmtresult::type_max_digits (tree type, int base)
756 unsigned prec = TYPE_PRECISION (type);
757 if (base == 8)
758 return (prec + 2) / 3;
760 if (base == 16)
761 return prec / 4;
763 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
764 of 8, 16, 32, and 64 bits. */
765 return prec * 301 / 1000 + 1;
768 static bool
769 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT);
771 /* Description of a format directive. A directive is either a plain
772 string or a conversion specification that starts with '%'. */
774 struct directive
776 /* The 1-based directive number (for debugging). */
777 unsigned dirno;
779 /* The first character of the directive and its length. */
780 const char *beg;
781 size_t len;
783 /* A bitmap of flags, one for each character. */
784 unsigned flags[256 / sizeof (int)];
786 /* The range of values of the specified width, or -1 if not specified. */
787 HOST_WIDE_INT width[2];
788 /* The range of values of the specified precision, or -1 if not
789 specified. */
790 HOST_WIDE_INT prec[2];
792 /* Length modifier. */
793 format_lengths modifier;
795 /* Format specifier character. */
796 char specifier;
798 /* The argument of the directive or null when the directive doesn't
799 take one or when none is available (such as for vararg functions). */
800 tree arg;
802 /* Format conversion function that given a directive and an argument
803 returns the formatting result. */
804 fmtresult (*fmtfunc) (const directive &, tree);
806 /* Return True when a the format flag CHR has been used. */
807 bool get_flag (char chr) const
809 unsigned char c = chr & 0xff;
810 return (flags[c / (CHAR_BIT * sizeof *flags)]
811 & (1U << (c % (CHAR_BIT * sizeof *flags))));
814 /* Make a record of the format flag CHR having been used. */
815 void set_flag (char chr)
817 unsigned char c = chr & 0xff;
818 flags[c / (CHAR_BIT * sizeof *flags)]
819 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
822 /* Reset the format flag CHR. */
823 void clear_flag (char chr)
825 unsigned char c = chr & 0xff;
826 flags[c / (CHAR_BIT * sizeof *flags)]
827 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
830 /* Set both bounds of the width range to VAL. */
831 void set_width (HOST_WIDE_INT val)
833 width[0] = width[1] = val;
836 /* Set the width range according to ARG, with both bounds being
837 no less than 0. For a constant ARG set both bounds to its value
838 or 0, whichever is greater. For a non-constant ARG in some range
839 set width to its range adjusting each bound to -1 if it's less.
840 For an indeterminate ARG set width to [0, INT_MAX]. */
841 void set_width (tree arg)
843 get_int_range (arg, width, width + 1, true, 0);
846 /* Set both bounds of the precision range to VAL. */
847 void set_precision (HOST_WIDE_INT val)
849 prec[0] = prec[1] = val;
852 /* Set the precision range according to ARG, with both bounds being
853 no less than -1. For a constant ARG set both bounds to its value
854 or -1 whichever is greater. For a non-constant ARG in some range
855 set precision to its range adjusting each bound to -1 if it's less.
856 For an indeterminate ARG set precision to [-1, INT_MAX]. */
857 void set_precision (tree arg)
859 get_int_range (arg, prec, prec + 1, false, -1);
862 /* Return true if both width and precision are known to be
863 either constant or in some range, false otherwise. */
864 bool known_width_and_precision () const
866 return ((width[1] < 0
867 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
868 && (prec[1] < 0
869 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
873 /* Return the logarithm of X in BASE. */
875 static int
876 ilog (unsigned HOST_WIDE_INT x, int base)
878 int res = 0;
881 ++res;
882 x /= base;
883 } while (x);
884 return res;
887 /* Return the number of bytes resulting from converting into a string
888 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
889 PLUS indicates whether 1 for a plus sign should be added for positive
890 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
891 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
892 be represented. */
894 static HOST_WIDE_INT
895 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
897 unsigned HOST_WIDE_INT absval;
899 HOST_WIDE_INT res;
901 if (TYPE_UNSIGNED (TREE_TYPE (x)))
903 if (tree_fits_uhwi_p (x))
905 absval = tree_to_uhwi (x);
906 res = plus;
908 else
909 return -1;
911 else
913 if (tree_fits_shwi_p (x))
915 HOST_WIDE_INT i = tree_to_shwi (x);
916 if (HOST_WIDE_INT_MIN == i)
918 /* Avoid undefined behavior due to negating a minimum. */
919 absval = HOST_WIDE_INT_MAX;
920 res = 1;
922 else if (i < 0)
924 absval = -i;
925 res = 1;
927 else
929 absval = i;
930 res = plus;
933 else
934 return -1;
937 int ndigs = ilog (absval, base);
939 res += prec < ndigs ? ndigs : prec;
941 /* Adjust a non-zero value for the base prefix, either hexadecimal,
942 or, unless precision has resulted in a leading zero, also octal. */
943 if (prefix && absval && (base == 16 || prec <= ndigs))
945 if (base == 8)
946 res += 1;
947 else if (base == 16)
948 res += 2;
951 return res;
954 /* Given the formatting result described by RES and NAVAIL, the number
955 of available in the destination, return the range of bytes remaining
956 in the destination. */
958 static inline result_range
959 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
961 result_range range;
963 if (HOST_WIDE_INT_MAX <= navail)
965 range.min = range.max = range.likely = range.unlikely = navail;
966 return range;
969 /* The lower bound of the available range is the available size
970 minus the maximum output size, and the upper bound is the size
971 minus the minimum. */
972 range.max = res.range.min < navail ? navail - res.range.min : 0;
974 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
976 if (res.range.max < HOST_WIDE_INT_MAX)
977 range.min = res.range.max < navail ? navail - res.range.max : 0;
978 else
979 range.min = range.likely;
981 range.unlikely = (res.range.unlikely < navail
982 ? navail - res.range.unlikely : 0);
984 return range;
987 /* Description of a call to a formatted function. */
989 struct sprintf_dom_walker::call_info
991 /* Function call statement. */
992 gimple *callstmt;
994 /* Function called. */
995 tree func;
997 /* Called built-in function code. */
998 built_in_function fncode;
1000 /* Format argument and format string extracted from it. */
1001 tree format;
1002 const char *fmtstr;
1004 /* The location of the format argument. */
1005 location_t fmtloc;
1007 /* The destination object size for __builtin___xxx_chk functions
1008 typically determined by __builtin_object_size, or -1 if unknown. */
1009 unsigned HOST_WIDE_INT objsize;
1011 /* Number of the first variable argument. */
1012 unsigned HOST_WIDE_INT argidx;
1014 /* True for functions like snprintf that specify the size of
1015 the destination, false for others like sprintf that don't. */
1016 bool bounded;
1018 /* True for bounded functions like snprintf that specify a zero-size
1019 buffer as a request to compute the size of output without actually
1020 writing any. NOWRITE is cleared in response to the %n directive
1021 which has side-effects similar to writing output. */
1022 bool nowrite;
1024 /* Return true if the called function's return value is used. */
1025 bool retval_used () const
1027 return gimple_get_lhs (callstmt);
1030 /* Return the warning option corresponding to the called function. */
1031 int warnopt () const
1033 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
1037 /* Return the result of formatting a no-op directive (such as '%n'). */
1039 static fmtresult
1040 format_none (const directive &, tree)
1042 fmtresult res (0);
1043 return res;
1046 /* Return the result of formatting the '%%' directive. */
1048 static fmtresult
1049 format_percent (const directive &, tree)
1051 fmtresult res (1);
1052 return res;
1056 /* Compute intmax_type_node and uintmax_type_node similarly to how
1057 tree.c builds size_type_node. */
1059 static void
1060 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
1062 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
1064 *pintmax = integer_type_node;
1065 *puintmax = unsigned_type_node;
1067 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
1069 *pintmax = long_integer_type_node;
1070 *puintmax = long_unsigned_type_node;
1072 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
1074 *pintmax = long_long_integer_type_node;
1075 *puintmax = long_long_unsigned_type_node;
1077 else
1079 for (int i = 0; i < NUM_INT_N_ENTS; i++)
1080 if (int_n_enabled_p[i])
1082 char name[50];
1083 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
1085 if (strcmp (name, UINTMAX_TYPE) == 0)
1087 *pintmax = int_n_trees[i].signed_type;
1088 *puintmax = int_n_trees[i].unsigned_type;
1089 return;
1092 gcc_unreachable ();
1096 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1097 in and that is representable in type int.
1098 Return true when the range is a subrange of that of int.
1099 When ARG is null it is as if it had the full range of int.
1100 When ABSOLUTE is true the range reflects the absolute value of
1101 the argument. When ABSOLUTE is false, negative bounds of
1102 the determined range are replaced with NEGBOUND. */
1104 static bool
1105 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1106 bool absolute, HOST_WIDE_INT negbound)
1108 /* The type of the result. */
1109 const_tree type = integer_type_node;
1111 bool knownrange = false;
1113 if (!arg)
1115 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1116 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1118 else if (TREE_CODE (arg) == INTEGER_CST
1119 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1121 /* For a constant argument return its value adjusted as specified
1122 by NEGATIVE and NEGBOUND and return true to indicate that the
1123 result is known. */
1124 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1125 *pmax = *pmin;
1126 knownrange = true;
1128 else
1130 /* True if the argument's range cannot be determined. */
1131 bool unknown = true;
1133 tree argtype = TREE_TYPE (arg);
1135 /* Ignore invalid arguments with greater precision that that
1136 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1137 They will have been detected and diagnosed by -Wformat and
1138 so it's not important to complicate this code to try to deal
1139 with them again. */
1140 if (TREE_CODE (arg) == SSA_NAME
1141 && INTEGRAL_TYPE_P (argtype)
1142 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1144 /* Try to determine the range of values of the integer argument. */
1145 wide_int min, max;
1146 enum value_range_type range_type = get_range_info (arg, &min, &max);
1147 if (range_type == VR_RANGE)
1149 HOST_WIDE_INT type_min
1150 = (TYPE_UNSIGNED (argtype)
1151 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1152 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1154 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1156 *pmin = min.to_shwi ();
1157 *pmax = max.to_shwi ();
1159 if (*pmin < *pmax)
1161 /* Return true if the adjusted range is a subrange of
1162 the full range of the argument's type. *PMAX may
1163 be less than *PMIN when the argument is unsigned
1164 and its upper bound is in excess of TYPE_MAX. In
1165 that (invalid) case disregard the range and use that
1166 of the expected type instead. */
1167 knownrange = type_min < *pmin || *pmax < type_max;
1169 unknown = false;
1174 /* Handle an argument with an unknown range as if none had been
1175 provided. */
1176 if (unknown)
1177 return get_int_range (NULL_TREE, pmin, pmax, absolute, negbound);
1180 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1181 if (absolute)
1183 if (*pmin < 0)
1185 if (*pmin == *pmax)
1186 *pmin = *pmax = -*pmin;
1187 else
1189 /* Make sure signed overlow is avoided. */
1190 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1192 HOST_WIDE_INT tmp = -*pmin;
1193 *pmin = 0;
1194 if (*pmax < tmp)
1195 *pmax = tmp;
1199 else if (*pmin < negbound)
1200 *pmin = negbound;
1202 return knownrange;
1205 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1206 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1207 the type of the directive's formal argument it's possible for both
1208 to result in the same number of bytes or a range of bytes that's
1209 less than the number of bytes that would result from formatting
1210 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1211 determined by checking for the actual argument being in the range
1212 of the type of the directive. If it isn't it must be assumed to
1213 take on the full range of the directive's type.
1214 Return true when the range has been adjusted to the full range
1215 of DIRTYPE, and false otherwise. */
1217 static bool
1218 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1220 tree argtype = TREE_TYPE (*argmin);
1221 unsigned argprec = TYPE_PRECISION (argtype);
1222 unsigned dirprec = TYPE_PRECISION (dirtype);
1224 /* If the actual argument and the directive's argument have the same
1225 precision and sign there can be no overflow and so there is nothing
1226 to adjust. */
1227 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1228 return false;
1230 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1231 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1233 if (TREE_CODE (*argmin) == INTEGER_CST
1234 && TREE_CODE (*argmax) == INTEGER_CST
1235 && (dirprec >= argprec
1236 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1237 int_const_binop (MINUS_EXPR,
1238 *argmax,
1239 *argmin),
1240 size_int (dirprec)))))
1242 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1243 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1245 /* If *ARGMIN is still less than *ARGMAX the conversion above
1246 is safe. Otherwise, it has overflowed and would be unsafe. */
1247 if (tree_int_cst_le (*argmin, *argmax))
1248 return false;
1251 *argmin = TYPE_MIN_VALUE (dirtype);
1252 *argmax = TYPE_MAX_VALUE (dirtype);
1253 return true;
1256 /* Return a range representing the minimum and maximum number of bytes
1257 that the format directive DIR will output for any argument given
1258 the WIDTH and PRECISION (extracted from DIR). This function is
1259 used when the directive argument or its value isn't known. */
1261 static fmtresult
1262 format_integer (const directive &dir, tree arg)
1264 tree intmax_type_node;
1265 tree uintmax_type_node;
1267 /* Base to format the number in. */
1268 int base;
1270 /* True when a conversion is preceded by a prefix indicating the base
1271 of the argument (octal or hexadecimal). */
1272 bool maybebase = dir.get_flag ('#');
1274 /* True when a signed conversion is preceded by a sign or space. */
1275 bool maybesign = false;
1277 /* True for signed conversions (i.e., 'd' and 'i'). */
1278 bool sign = false;
1280 switch (dir.specifier)
1282 case 'd':
1283 case 'i':
1284 /* Space and '+' are only meaningful for signed conversions. */
1285 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1286 sign = true;
1287 base = 10;
1288 break;
1289 case 'u':
1290 base = 10;
1291 break;
1292 case 'o':
1293 base = 8;
1294 break;
1295 case 'X':
1296 case 'x':
1297 base = 16;
1298 break;
1299 default:
1300 gcc_unreachable ();
1303 /* The type of the "formal" argument expected by the directive. */
1304 tree dirtype = NULL_TREE;
1306 /* Determine the expected type of the argument from the length
1307 modifier. */
1308 switch (dir.modifier)
1310 case FMT_LEN_none:
1311 if (dir.specifier == 'p')
1312 dirtype = ptr_type_node;
1313 else
1314 dirtype = sign ? integer_type_node : unsigned_type_node;
1315 break;
1317 case FMT_LEN_h:
1318 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1319 break;
1321 case FMT_LEN_hh:
1322 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1323 break;
1325 case FMT_LEN_l:
1326 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1327 break;
1329 case FMT_LEN_L:
1330 case FMT_LEN_ll:
1331 dirtype = (sign
1332 ? long_long_integer_type_node
1333 : long_long_unsigned_type_node);
1334 break;
1336 case FMT_LEN_z:
1337 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1338 break;
1340 case FMT_LEN_t:
1341 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1342 break;
1344 case FMT_LEN_j:
1345 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1346 dirtype = sign ? intmax_type_node : uintmax_type_node;
1347 break;
1349 default:
1350 return fmtresult ();
1353 /* The type of the argument to the directive, either deduced from
1354 the actual non-constant argument if one is known, or from
1355 the directive itself when none has been provided because it's
1356 a va_list. */
1357 tree argtype = NULL_TREE;
1359 if (!arg)
1361 /* When the argument has not been provided, use the type of
1362 the directive's argument as an approximation. This will
1363 result in false positives for directives like %i with
1364 arguments with smaller precision (such as short or char). */
1365 argtype = dirtype;
1367 else if (TREE_CODE (arg) == INTEGER_CST)
1369 /* When a constant argument has been provided use its value
1370 rather than type to determine the length of the output. */
1371 fmtresult res;
1373 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1375 /* As a special case, a precision of zero with a zero argument
1376 results in zero bytes except in base 8 when the '#' flag is
1377 specified, and for signed conversions in base 8 and 10 when
1378 either the space or '+' flag has been specified and it results
1379 in just one byte (with width having the normal effect). This
1380 must extend to the case of a specified precision with
1381 an unknown value because it can be zero. */
1382 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1383 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1385 res.range.max = 1;
1386 res.range.likely = 1;
1388 else
1390 res.range.max = res.range.min;
1391 res.range.likely = res.range.min;
1394 else
1396 /* Convert the argument to the type of the directive. */
1397 arg = fold_convert (dirtype, arg);
1399 res.range.min = tree_digits (arg, base, dir.prec[0],
1400 maybesign, maybebase);
1401 if (dir.prec[0] == dir.prec[1])
1402 res.range.max = res.range.min;
1403 else
1404 res.range.max = tree_digits (arg, base, dir.prec[1],
1405 maybesign, maybebase);
1406 res.range.likely = res.range.min;
1407 res.knownrange = true;
1410 res.range.unlikely = res.range.max;
1412 /* Bump up the counters if WIDTH is greater than LEN. */
1413 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1414 (sign | maybebase) + (base == 16));
1415 /* Bump up the counters again if PRECision is greater still. */
1416 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1417 (sign | maybebase) + (base == 16));
1419 return res;
1421 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1422 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1423 /* Determine the type of the provided non-constant argument. */
1424 argtype = TREE_TYPE (arg);
1425 else
1426 /* Don't bother with invalid arguments since they likely would
1427 have already been diagnosed, and disable any further checking
1428 of the format string by returning [-1, -1]. */
1429 return fmtresult ();
1431 fmtresult res;
1433 /* Using either the range the non-constant argument is in, or its
1434 type (either "formal" or actual), create a range of values that
1435 constrain the length of output given the warning level. */
1436 tree argmin = NULL_TREE;
1437 tree argmax = NULL_TREE;
1439 if (arg
1440 && TREE_CODE (arg) == SSA_NAME
1441 && INTEGRAL_TYPE_P (argtype))
1443 /* Try to determine the range of values of the integer argument
1444 (range information is not available for pointers). */
1445 wide_int min, max;
1446 enum value_range_type range_type = get_range_info (arg, &min, &max);
1447 if (range_type == VR_RANGE)
1449 argmin = wide_int_to_tree (argtype, min);
1450 argmax = wide_int_to_tree (argtype, max);
1452 /* Set KNOWNRANGE if the argument is in a known subrange
1453 of the directive's type and neither width nor precision
1454 is unknown. (KNOWNRANGE may be reset below). */
1455 res.knownrange
1456 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1457 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1458 && dir.known_width_and_precision ());
1460 res.argmin = argmin;
1461 res.argmax = argmax;
1463 else if (range_type == VR_ANTI_RANGE)
1465 /* Handle anti-ranges if/when bug 71690 is resolved. */
1467 else if (range_type == VR_VARYING)
1469 /* The argument here may be the result of promoting the actual
1470 argument to int. Try to determine the type of the actual
1471 argument before promotion and narrow down its range that
1472 way. */
1473 gimple *def = SSA_NAME_DEF_STMT (arg);
1474 if (is_gimple_assign (def))
1476 tree_code code = gimple_assign_rhs_code (def);
1477 if (code == INTEGER_CST)
1479 arg = gimple_assign_rhs1 (def);
1480 return format_integer (dir, arg);
1483 if (code == NOP_EXPR)
1485 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1486 if (INTEGRAL_TYPE_P (type)
1487 || TREE_CODE (type) == POINTER_TYPE)
1488 argtype = type;
1494 if (!argmin)
1496 if (TREE_CODE (argtype) == POINTER_TYPE)
1498 argmin = build_int_cst (pointer_sized_int_node, 0);
1499 argmax = build_all_ones_cst (pointer_sized_int_node);
1501 else
1503 argmin = TYPE_MIN_VALUE (argtype);
1504 argmax = TYPE_MAX_VALUE (argtype);
1508 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1509 of the directive. If it has been cleared then since ARGMIN and/or
1510 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1511 ARGMAX in the result to include in diagnostics. */
1512 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1514 res.knownrange = false;
1515 res.argmin = argmin;
1516 res.argmax = argmax;
1519 /* Recursively compute the minimum and maximum from the known range. */
1520 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1522 /* For unsigned conversions/directives or signed when
1523 the minimum is positive, use the minimum and maximum to compute
1524 the shortest and longest output, respectively. */
1525 res.range.min = format_integer (dir, argmin).range.min;
1526 res.range.max = format_integer (dir, argmax).range.max;
1528 else if (tree_int_cst_sgn (argmax) < 0)
1530 /* For signed conversions/directives if maximum is negative,
1531 use the minimum as the longest output and maximum as the
1532 shortest output. */
1533 res.range.min = format_integer (dir, argmax).range.min;
1534 res.range.max = format_integer (dir, argmin).range.max;
1536 else
1538 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1539 as the shortest output and for the longest output compute the
1540 length of the output of both minimum and maximum and pick the
1541 longer. */
1542 unsigned HOST_WIDE_INT max1 = format_integer (dir, argmin).range.max;
1543 unsigned HOST_WIDE_INT max2 = format_integer (dir, argmax).range.max;
1544 res.range.min = format_integer (dir, integer_zero_node).range.min;
1545 res.range.max = MAX (max1, max2);
1548 /* If the range is known, use the maximum as the likely length. */
1549 if (res.knownrange)
1550 res.range.likely = res.range.max;
1551 else
1553 /* Otherwise, use the minimum. Except for the case where for %#x or
1554 %#o the minimum is just for a single value in the range (0) and
1555 for all other values it is something longer, like 0x1 or 01.
1556 Use the length for value 1 in that case instead as the likely
1557 length. */
1558 res.range.likely = res.range.min;
1559 if (maybebase
1560 && base != 10
1561 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1563 if (res.range.min == 1)
1564 res.range.likely += base == 8 ? 1 : 2;
1565 else if (res.range.min == 2
1566 && base == 16
1567 && (dir.width[0] == 2 || dir.prec[0] == 2))
1568 ++res.range.likely;
1572 res.range.unlikely = res.range.max;
1573 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1574 (sign | maybebase) + (base == 16));
1575 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1576 (sign | maybebase) + (base == 16));
1578 return res;
1581 /* Return the number of bytes that a format directive consisting of FLAGS,
1582 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1583 would result for argument X under ideal conditions (i.e., if PREC
1584 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1585 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1586 This function works around those problems. */
1588 static unsigned HOST_WIDE_INT
1589 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1590 char spec, char rndspec)
1592 char fmtstr[40];
1594 HOST_WIDE_INT len = strlen (flags);
1596 fmtstr[0] = '%';
1597 memcpy (fmtstr + 1, flags, len);
1598 memcpy (fmtstr + 1 + len, ".*R", 3);
1599 fmtstr[len + 4] = rndspec;
1600 fmtstr[len + 5] = spec;
1601 fmtstr[len + 6] = '\0';
1603 spec = TOUPPER (spec);
1604 if (spec == 'E' || spec == 'F')
1606 /* For %e, specify the precision explicitly since mpfr_sprintf
1607 does its own thing just to be different (see MPFR bug 21088). */
1608 if (prec < 0)
1609 prec = 6;
1611 else
1613 /* Avoid passing negative precisions with larger magnitude to MPFR
1614 to avoid exposing its bugs. (A negative precision is supposed
1615 to be ignored.) */
1616 if (prec < 0)
1617 prec = -1;
1620 HOST_WIDE_INT p = prec;
1622 if (spec == 'G' && !strchr (flags, '#'))
1624 /* For G/g without the pound flag, precision gives the maximum number
1625 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1626 a 128 bit IEEE extended precision, 4932. Using twice as much here
1627 should be more than sufficient for any real format. */
1628 if ((IEEE_MAX_10_EXP * 2) < prec)
1629 prec = IEEE_MAX_10_EXP * 2;
1630 p = prec;
1632 else
1634 /* Cap precision arbitrarily at 1KB and add the difference
1635 (if any) to the MPFR result. */
1636 if (prec > 1024)
1637 p = 1024;
1640 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1642 /* Handle the unlikely (impossible?) error by returning more than
1643 the maximum dictated by the function's return type. */
1644 if (len < 0)
1645 return target_dir_max () + 1;
1647 /* Adjust the return value by the difference. */
1648 if (p < prec)
1649 len += prec - p;
1651 return len;
1654 /* Return the number of bytes to format using the format specifier
1655 SPEC and the precision PREC the largest value in the real floating
1656 TYPE. */
1658 static unsigned HOST_WIDE_INT
1659 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1661 machine_mode mode = TYPE_MODE (type);
1663 /* IBM Extended mode. */
1664 if (MODE_COMPOSITE_P (mode))
1665 mode = DFmode;
1667 /* Get the real type format desription for the target. */
1668 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1669 REAL_VALUE_TYPE rv;
1671 real_maxval (&rv, 0, mode);
1673 /* Convert the GCC real value representation with the precision
1674 of the real type to the mpfr_t format with the GCC default
1675 round-to-nearest mode. */
1676 mpfr_t x;
1677 mpfr_init2 (x, rfmt->p);
1678 mpfr_from_real (x, &rv, GMP_RNDN);
1680 /* Return a value one greater to account for the leading minus sign. */
1681 unsigned HOST_WIDE_INT r
1682 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1683 mpfr_clear (x);
1684 return r;
1687 /* Return a range representing the minimum and maximum number of bytes
1688 that the directive DIR will output for any argument. PREC gives
1689 the adjusted precision range to account for negative precisions
1690 meaning the default 6. This function is used when the directive
1691 argument or its value isn't known. */
1693 static fmtresult
1694 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1696 tree type;
1698 switch (dir.modifier)
1700 case FMT_LEN_l:
1701 case FMT_LEN_none:
1702 type = double_type_node;
1703 break;
1705 case FMT_LEN_L:
1706 type = long_double_type_node;
1707 break;
1709 case FMT_LEN_ll:
1710 type = long_double_type_node;
1711 break;
1713 default:
1714 return fmtresult ();
1717 /* The minimum and maximum number of bytes produced by the directive. */
1718 fmtresult res;
1720 /* The minimum output as determined by flags. It's always at least 1.
1721 When plus or space are set the output is preceded by either a sign
1722 or a space. */
1723 unsigned flagmin = (1 /* for the first digit */
1724 + (dir.get_flag ('+') | dir.get_flag (' ')));
1726 /* When the pound flag is set the decimal point is included in output
1727 regardless of precision. Whether or not a decimal point is included
1728 otherwise depends on the specification and precision. */
1729 bool radix = dir.get_flag ('#');
1731 switch (dir.specifier)
1733 case 'A':
1734 case 'a':
1736 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1737 if (dir.prec[0] <= 0)
1738 minprec = 0;
1739 else if (dir.prec[0] > 0)
1740 minprec = dir.prec[0] + !radix /* decimal point */;
1742 res.range.min = (2 /* 0x */
1743 + flagmin
1744 + radix
1745 + minprec
1746 + 3 /* p+0 */);
1748 res.range.max = format_floating_max (type, 'a', prec[1]);
1749 res.range.likely = res.range.min;
1751 /* The unlikely maximum accounts for the longest multibyte
1752 decimal point character. */
1753 res.range.unlikely = res.range.max;
1754 if (dir.prec[1] > 0)
1755 res.range.unlikely += target_mb_len_max () - 1;
1757 break;
1760 case 'E':
1761 case 'e':
1763 /* Minimum output attributable to precision and, when it's
1764 non-zero, decimal point. */
1765 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1767 /* The minimum output is "[-+]1.234567e+00" regardless
1768 of the value of the actual argument. */
1769 res.range.min = (flagmin
1770 + radix
1771 + minprec
1772 + 2 /* e+ */ + 2);
1774 res.range.max = format_floating_max (type, 'e', prec[1]);
1775 res.range.likely = res.range.min;
1777 /* The unlikely maximum accounts for the longest multibyte
1778 decimal point character. */
1779 if (dir.prec[0] != dir.prec[1]
1780 || dir.prec[0] == -1 || dir.prec[0] > 0)
1781 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1782 else
1783 res.range.unlikely = res.range.max;
1784 break;
1787 case 'F':
1788 case 'f':
1790 /* Minimum output attributable to precision and, when it's non-zero,
1791 decimal point. */
1792 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1794 /* The lower bound when precision isn't specified is 8 bytes
1795 ("1.23456" since precision is taken to be 6). When precision
1796 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1797 when precision is greater than zero, then the lower bound
1798 is 2 plus precision (plus flags). */
1799 res.range.min = flagmin + radix + minprec;
1801 /* Compute the upper bound for -TYPE_MAX. */
1802 res.range.max = format_floating_max (type, 'f', prec[1]);
1804 /* The minimum output with unknown precision is a single byte
1805 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1806 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1807 res.range.likely = 3;
1808 else
1809 res.range.likely = res.range.min;
1811 /* The unlikely maximum accounts for the longest multibyte
1812 decimal point character. */
1813 if (dir.prec[0] != dir.prec[1]
1814 || dir.prec[0] == -1 || dir.prec[0] > 0)
1815 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1816 break;
1819 case 'G':
1820 case 'g':
1822 /* The %g output depends on precision and the exponent of
1823 the argument. Since the value of the argument isn't known
1824 the lower bound on the range of bytes (not counting flags
1825 or width) is 1 plus radix (i.e., either "0" or "0." for
1826 "%g" and "%#g", respectively, with a zero argument). */
1827 res.range.min = flagmin + radix;
1829 char spec = 'g';
1830 HOST_WIDE_INT maxprec = dir.prec[1];
1831 if (radix && maxprec)
1833 /* When the pound flag (radix) is set, trailing zeros aren't
1834 trimmed and so the longest output is the same as for %e,
1835 except with precision minus 1 (as specified in C11). */
1836 spec = 'e';
1837 if (maxprec > 0)
1838 --maxprec;
1839 else if (maxprec < 0)
1840 maxprec = 5;
1842 else
1843 maxprec = prec[1];
1845 res.range.max = format_floating_max (type, spec, maxprec);
1847 /* The likely output is either the maximum computed above
1848 minus 1 (assuming the maximum is positive) when precision
1849 is known (or unspecified), or the same minimum as for %e
1850 (which is computed for a non-negative argument). Unlike
1851 for the other specifiers above the likely output isn't
1852 the minimum because for %g that's 1 which is unlikely. */
1853 if (dir.prec[1] < 0
1854 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1855 res.range.likely = res.range.max - 1;
1856 else
1858 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1859 res.range.likely = (flagmin
1860 + radix
1861 + minprec
1862 + 2 /* e+ */ + 2);
1865 /* The unlikely maximum accounts for the longest multibyte
1866 decimal point character. */
1867 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1868 break;
1871 default:
1872 return fmtresult ();
1875 /* Bump up the byte counters if WIDTH is greater. */
1876 res.adjust_for_width_or_precision (dir.width);
1877 return res;
1880 /* Return a range representing the minimum and maximum number of bytes
1881 that the directive DIR will write on output for the floating argument
1882 ARG. */
1884 static fmtresult
1885 format_floating (const directive &dir, tree arg)
1887 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1888 tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1889 ? long_double_type_node : double_type_node);
1891 /* For an indeterminate precision the lower bound must be assumed
1892 to be zero. */
1893 if (TOUPPER (dir.specifier) == 'A')
1895 /* Get the number of fractional decimal digits needed to represent
1896 the argument without a loss of accuracy. */
1897 unsigned fmtprec
1898 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1900 /* The precision of the IEEE 754 double format is 53.
1901 The precision of all other GCC binary double formats
1902 is 56 or less. */
1903 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1905 /* For %a, leave the minimum precision unspecified to let
1906 MFPR trim trailing zeros (as it and many other systems
1907 including Glibc happen to do) and set the maximum
1908 precision to reflect what it would be with trailing zeros
1909 present (as Solaris and derived systems do). */
1910 if (dir.prec[1] < 0)
1912 /* Both bounds are negative implies that precision has
1913 not been specified. */
1914 prec[0] = maxprec;
1915 prec[1] = -1;
1917 else if (dir.prec[0] < 0)
1919 /* With a negative lower bound and a non-negative upper
1920 bound set the minimum precision to zero and the maximum
1921 to the greater of the maximum precision (i.e., with
1922 trailing zeros present) and the specified upper bound. */
1923 prec[0] = 0;
1924 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1927 else if (dir.prec[0] < 0)
1929 if (dir.prec[1] < 0)
1931 /* A precision in a strictly negative range is ignored and
1932 the default of 6 is used instead. */
1933 prec[0] = prec[1] = 6;
1935 else
1937 /* For a precision in a partly negative range, the lower bound
1938 must be assumed to be zero and the new upper bound is the
1939 greater of 6 (the default precision used when the specified
1940 precision is negative) and the upper bound of the specified
1941 range. */
1942 prec[0] = 0;
1943 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1947 if (!arg
1948 || TREE_CODE (arg) != REAL_CST
1949 || !useless_type_conversion_p (type, TREE_TYPE (arg)))
1950 return format_floating (dir, prec);
1952 /* The minimum and maximum number of bytes produced by the directive. */
1953 fmtresult res;
1955 /* Get the real type format desription for the target. */
1956 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1957 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1959 char fmtstr [40];
1960 char *pfmt = fmtstr;
1962 /* Append flags. */
1963 for (const char *pf = "-+ #0"; *pf; ++pf)
1964 if (dir.get_flag (*pf))
1965 *pfmt++ = *pf;
1967 *pfmt = '\0';
1970 /* Set up an array to easily iterate over. */
1971 unsigned HOST_WIDE_INT* const minmax[] = {
1972 &res.range.min, &res.range.max
1975 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1977 /* Convert the GCC real value representation with the precision
1978 of the real type to the mpfr_t format rounding down in the
1979 first iteration that computes the minimm and up in the second
1980 that computes the maximum. This order is arbibtrary because
1981 rounding in either direction can result in longer output. */
1982 mpfr_t mpfrval;
1983 mpfr_init2 (mpfrval, rfmt->p);
1984 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1986 /* Use the MPFR rounding specifier to round down in the first
1987 iteration and then up. In most but not all cases this will
1988 result in the same number of bytes. */
1989 char rndspec = "DU"[i];
1991 /* Format it and store the result in the corresponding member
1992 of the result struct. */
1993 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1994 dir.specifier, rndspec);
1995 mpfr_clear (mpfrval);
1999 /* Make sure the minimum is less than the maximum (MPFR rounding
2000 in the call to mpfr_snprintf can result in the reverse. */
2001 if (res.range.max < res.range.min)
2003 unsigned HOST_WIDE_INT tmp = res.range.min;
2004 res.range.min = res.range.max;
2005 res.range.max = tmp;
2008 /* The range is known unless either width or precision is unknown. */
2009 res.knownrange = dir.known_width_and_precision ();
2011 /* For the same floating point constant, unless width or precision
2012 is unknown, use the longer output as the likely maximum since
2013 with round to nearest either is equally likely. Otheriwse, when
2014 precision is unknown, use the greater of the minimum and 3 as
2015 the likely output (for "0.0" since zero precision is unlikely). */
2016 if (res.knownrange)
2017 res.range.likely = res.range.max;
2018 else if (res.range.min < 3
2019 && dir.prec[0] < 0
2020 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
2021 res.range.likely = 3;
2022 else
2023 res.range.likely = res.range.min;
2025 res.range.unlikely = res.range.max;
2027 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
2029 /* Unless the precision is zero output longer than 2 bytes may
2030 include the decimal point which must be a single character
2031 up to MB_LEN_MAX in length. This is overly conservative
2032 since in some conversions some constants result in no decimal
2033 point (e.g., in %g). */
2034 res.range.unlikely += target_mb_len_max () - 1;
2037 res.adjust_for_width_or_precision (dir.width);
2038 return res;
2041 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
2042 strings referenced by the expression STR, or (-1, -1) when not known.
2043 Used by the format_string function below. */
2045 static fmtresult
2046 get_string_length (tree str)
2048 if (!str)
2049 return fmtresult ();
2051 if (tree slen = c_strlen (str, 1))
2053 /* Simply return the length of the string. */
2054 fmtresult res (tree_to_shwi (slen));
2055 return res;
2058 /* Determine the length of the shortest and longest string referenced
2059 by STR. Strings of unknown lengths are bounded by the sizes of
2060 arrays that subexpressions of STR may refer to. Pointers that
2061 aren't known to point any such arrays result in LENRANGE[1] set
2062 to SIZE_MAX. */
2063 tree lenrange[2];
2064 bool flexarray = get_range_strlen (str, lenrange);
2066 if (lenrange [0] || lenrange [1])
2068 HOST_WIDE_INT min
2069 = (tree_fits_uhwi_p (lenrange[0])
2070 ? tree_to_uhwi (lenrange[0])
2071 : 0);
2073 HOST_WIDE_INT max
2074 = (tree_fits_uhwi_p (lenrange[1])
2075 ? tree_to_uhwi (lenrange[1])
2076 : HOST_WIDE_INT_M1U);
2078 /* get_range_strlen() returns the target value of SIZE_MAX for
2079 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2080 which may be bigger. */
2081 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2082 min = HOST_WIDE_INT_M1U;
2083 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2084 max = HOST_WIDE_INT_M1U;
2086 fmtresult res (min, max);
2088 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2089 by STR are known to be bounded (though not necessarily by their
2090 actual length but perhaps by their maximum possible length). */
2091 if (res.range.max < target_int_max ())
2093 res.knownrange = true;
2094 /* When the the length of the longest string is known and not
2095 excessive use it as the likely length of the string(s). */
2096 res.range.likely = res.range.max;
2098 else
2100 /* When the upper bound is unknown (it can be zero or excessive)
2101 set the likely length to the greater of 1 and the length of
2102 the shortest string and reset the lower bound to zero. */
2103 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2104 res.range.min = 0;
2107 /* If the range of string length has been estimated from the size
2108 of an array at the end of a struct assume that it's longer than
2109 the array bound says it is in case it's used as a poor man's
2110 flexible array member, such as in struct S { char a[4]; }; */
2111 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
2113 return res;
2116 return get_string_length (NULL_TREE);
2119 /* Return the minimum and maximum number of characters formatted
2120 by the '%c' format directives and its wide character form for
2121 the argument ARG. ARG can be null (for functions such as
2122 vsprinf). */
2124 static fmtresult
2125 format_character (const directive &dir, tree arg)
2127 fmtresult res;
2129 res.knownrange = true;
2131 if (dir.modifier == FMT_LEN_l)
2133 /* A wide character can result in as few as zero bytes. */
2134 res.range.min = 0;
2136 HOST_WIDE_INT min, max;
2137 if (get_int_range (arg, &min, &max, false, 0))
2139 if (min == 0 && max == 0)
2141 /* The NUL wide character results in no bytes. */
2142 res.range.max = 0;
2143 res.range.likely = 0;
2144 res.range.unlikely = 0;
2146 else if (min > 0 && min < 128)
2148 /* A wide character in the ASCII range most likely results
2149 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2150 res.range.max = 1;
2151 res.range.likely = 1;
2152 res.range.unlikely = target_mb_len_max ();
2154 else
2156 /* A wide character outside the ASCII range likely results
2157 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2158 res.range.max = target_mb_len_max ();
2159 res.range.likely = 2;
2160 res.range.unlikely = res.range.max;
2163 else
2165 /* An unknown wide character is treated the same as a wide
2166 character outside the ASCII range. */
2167 res.range.max = target_mb_len_max ();
2168 res.range.likely = 2;
2169 res.range.unlikely = res.range.max;
2172 else
2174 /* A plain '%c' directive. Its ouput is exactly 1. */
2175 res.range.min = res.range.max = 1;
2176 res.range.likely = res.range.unlikely = 1;
2177 res.knownrange = true;
2180 /* Bump up the byte counters if WIDTH is greater. */
2181 return res.adjust_for_width_or_precision (dir.width);
2184 /* Return the minimum and maximum number of characters formatted
2185 by the '%s' format directive and its wide character form for
2186 the argument ARG. ARG can be null (for functions such as
2187 vsprinf). */
2189 static fmtresult
2190 format_string (const directive &dir, tree arg)
2192 fmtresult res;
2194 /* Compute the range the argument's length can be in. */
2195 fmtresult slen = get_string_length (arg);
2196 if (slen.range.min == slen.range.max
2197 && slen.range.min < HOST_WIDE_INT_MAX)
2199 /* The argument is either a string constant or it refers
2200 to one of a number of strings of the same length. */
2202 /* A '%s' directive with a string argument with constant length. */
2203 res.range = slen.range;
2205 if (dir.modifier == FMT_LEN_l)
2207 /* In the worst case the length of output of a wide string S
2208 is bounded by MB_LEN_MAX * wcslen (S). */
2209 res.range.max *= target_mb_len_max ();
2210 res.range.unlikely = res.range.max;
2211 /* It's likely that the the total length is not more that
2212 2 * wcslen (S).*/
2213 res.range.likely = res.range.min * 2;
2215 if (dir.prec[1] >= 0
2216 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2218 res.range.max = dir.prec[1];
2219 res.range.likely = dir.prec[1];
2220 res.range.unlikely = dir.prec[1];
2223 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2224 res.range.min = 0;
2225 else if (dir.prec[0] >= 0)
2226 res.range.likely = dir.prec[0];
2228 /* Even a non-empty wide character string need not convert into
2229 any bytes. */
2230 res.range.min = 0;
2232 else
2234 res.knownrange = true;
2236 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2237 res.range.min = 0;
2238 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2239 res.range.min = dir.prec[0];
2241 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2243 res.range.max = dir.prec[1];
2244 res.range.likely = dir.prec[1];
2245 res.range.unlikely = dir.prec[1];
2249 else if (arg && integer_zerop (arg))
2251 /* Handle null pointer argument. */
2253 fmtresult res (0);
2254 res.nullp = true;
2255 return res;
2257 else
2259 /* For a '%s' and '%ls' directive with a non-constant string (either
2260 one of a number of strings of known length or an unknown string)
2261 the minimum number of characters is lesser of PRECISION[0] and
2262 the length of the shortest known string or zero, and the maximum
2263 is the lessser of the length of the longest known string or
2264 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2265 the minimum at level 1 and the greater of the minimum and 1
2266 at level 2. This result is adjust upward for width (if it's
2267 specified). */
2269 if (dir.modifier == FMT_LEN_l)
2271 /* A wide character converts to as few as zero bytes. */
2272 slen.range.min = 0;
2273 if (slen.range.max < target_int_max ())
2274 slen.range.max *= target_mb_len_max ();
2276 if (slen.range.likely < target_int_max ())
2277 slen.range.likely *= 2;
2279 if (slen.range.likely < target_int_max ())
2280 slen.range.unlikely *= target_mb_len_max ();
2283 res.range = slen.range;
2285 if (dir.prec[0] >= 0)
2287 /* Adjust the minimum to zero if the string length is unknown,
2288 or at most the lower bound of the precision otherwise. */
2289 if (slen.range.min >= target_int_max ())
2290 res.range.min = 0;
2291 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2292 res.range.min = dir.prec[0];
2294 /* Make both maxima no greater than the upper bound of precision. */
2295 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2296 || slen.range.max >= target_int_max ())
2298 res.range.max = dir.prec[1];
2299 res.range.unlikely = dir.prec[1];
2302 /* If precision is constant, set the likely counter to the lesser
2303 of it and the maximum string length. Otherwise, if the lower
2304 bound of precision is greater than zero, set the likely counter
2305 to the minimum. Otherwise set it to zero or one based on
2306 the warning level. */
2307 if (dir.prec[0] == dir.prec[1])
2308 res.range.likely
2309 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2310 ? dir.prec[0] : slen.range.max);
2311 else if (dir.prec[0] > 0)
2312 res.range.likely = res.range.min;
2313 else
2314 res.range.likely = warn_level > 1;
2316 else if (dir.prec[1] >= 0)
2318 res.range.min = 0;
2319 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2320 res.range.max = dir.prec[1];
2321 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2323 else if (slen.range.min >= target_int_max ())
2325 res.range.min = 0;
2326 res.range.max = HOST_WIDE_INT_MAX;
2327 /* At level 1 strings of unknown length are assumed to be
2328 empty, while at level 1 they are assumed to be one byte
2329 long. */
2330 res.range.likely = warn_level > 1;
2332 else
2334 /* A string of unknown length unconstrained by precision is
2335 assumed to be empty at level 1 and just one character long
2336 at higher levels. */
2337 if (res.range.likely >= target_int_max ())
2338 res.range.likely = warn_level > 1;
2341 res.range.unlikely = res.range.max;
2344 /* Bump up the byte counters if WIDTH is greater. */
2345 return res.adjust_for_width_or_precision (dir.width);
2348 /* Format plain string (part of the format string itself). */
2350 static fmtresult
2351 format_plain (const directive &dir, tree)
2353 fmtresult res (dir.len);
2354 return res;
2357 /* Return true if the RESULT of a directive in a call describe by INFO
2358 should be diagnosed given the AVAILable space in the destination. */
2360 static bool
2361 should_warn_p (const sprintf_dom_walker::call_info &info,
2362 const result_range &avail, const result_range &result)
2364 if (result.max <= avail.min)
2366 /* The least amount of space remaining in the destination is big
2367 enough for the longest output. */
2368 return false;
2371 if (info.bounded)
2373 if (warn_format_trunc == 1 && result.min <= avail.max
2374 && info.retval_used ())
2376 /* The likely amount of space remaining in the destination is big
2377 enough for the least output and the return value is used. */
2378 return false;
2381 if (warn_format_trunc == 1 && result.likely <= avail.likely
2382 && !info.retval_used ())
2384 /* The likely amount of space remaining in the destination is big
2385 enough for the likely output and the return value is unused. */
2386 return false;
2389 if (warn_format_trunc == 2
2390 && result.likely <= avail.min
2391 && (result.max <= avail.min
2392 || result.max > HOST_WIDE_INT_MAX))
2394 /* The minimum amount of space remaining in the destination is big
2395 enough for the longest output. */
2396 return false;
2399 else
2401 if (warn_level == 1 && result.likely <= avail.likely)
2403 /* The likely amount of space remaining in the destination is big
2404 enough for the likely output. */
2405 return false;
2408 if (warn_level == 2
2409 && result.likely <= avail.min
2410 && (result.max <= avail.min
2411 || result.max > HOST_WIDE_INT_MAX))
2413 /* The minimum amount of space remaining in the destination is big
2414 enough for the longest output. */
2415 return false;
2419 return true;
2422 /* At format string location describe by DIRLOC in a call described
2423 by INFO, issue a warning for a directive DIR whose output may be
2424 in excess of the available space AVAIL_RANGE in the destination
2425 given the formatting result FMTRES. This function does nothing
2426 except decide whether to issue a warning for a possible write
2427 past the end or truncation and, if so, format the warning.
2428 Return true if a warning has been issued. */
2430 static bool
2431 maybe_warn (substring_loc &dirloc, location_t argloc,
2432 const sprintf_dom_walker::call_info &info,
2433 const result_range &avail_range, const result_range &res,
2434 const directive &dir)
2436 if (!should_warn_p (info, avail_range, res))
2437 return false;
2439 /* A warning will definitely be issued below. */
2441 /* The maximum byte count to reference in the warning. Larger counts
2442 imply that the upper bound is unknown (and could be anywhere between
2443 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2444 than "between N and X" where X is some huge number. */
2445 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2447 /* True when there is enough room in the destination for the least
2448 amount of a directive's output but not enough for its likely or
2449 maximum output. */
2450 bool maybe = (res.min <= avail_range.max
2451 && (avail_range.min < res.likely
2452 || (res.max < HOST_WIDE_INT_MAX
2453 && avail_range.min < res.max)));
2455 /* Buffer for the directive in the host character set (used when
2456 the source character set is different). */
2457 char hostdir[32];
2459 if (avail_range.min == avail_range.max)
2461 /* The size of the destination region is exact. */
2462 unsigned HOST_WIDE_INT navail = avail_range.max;
2464 if (target_to_host (*dir.beg) != '%')
2466 /* For plain character directives (i.e., the format string itself)
2467 but not others, point the caret at the first character that's
2468 past the end of the destination. */
2469 if (navail < dir.len)
2470 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2473 if (*dir.beg == '\0')
2475 /* This is the terminating nul. */
2476 gcc_assert (res.min == 1 && res.min == res.max);
2478 const char *fmtstr
2479 = (info.bounded
2480 ? (maybe
2481 ? G_("%qE output may be truncated before the last format "
2482 "character")
2483 : G_("%qE output truncated before the last format character"))
2484 : (maybe
2485 ? G_("%qE may write a terminating nul past the end "
2486 "of the destination")
2487 : G_("%qE writing a terminating nul past the end "
2488 "of the destination")));
2490 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2491 fmtstr, info.func);
2494 if (res.min == res.max)
2496 const char* fmtstr
2497 = (res.min == 1
2498 ? (info.bounded
2499 ? (maybe
2500 ? G_("%<%.*s%> directive output may be truncated writing "
2501 "%wu byte into a region of size %wu")
2502 : G_("%<%.*s%> directive output truncated writing "
2503 "%wu byte into a region of size %wu"))
2504 : G_("%<%.*s%> directive writing %wu byte "
2505 "into a region of size %wu"))
2506 : (info.bounded
2507 ? (maybe
2508 ? G_("%<%.*s%> directive output may be truncated writing "
2509 "%wu bytes into a region of size %wu")
2510 : G_("%<%.*s%> directive output truncated writing "
2511 "%wu bytes into a region of size %wu"))
2512 : G_("%<%.*s%> directive writing %wu bytes "
2513 "into a region of size %wu")));
2514 return fmtwarn (dirloc, argloc, NULL,
2515 info.warnopt (), fmtstr, dir.len,
2516 target_to_host (hostdir, sizeof hostdir, dir.beg),
2517 res.min, navail);
2520 if (res.min == 0 && res.max < maxbytes)
2522 const char* fmtstr
2523 = (info.bounded
2524 ? (maybe
2525 ? G_("%<%.*s%> directive output may be truncated writing "
2526 "up to %wu bytes into a region of size %wu")
2527 : G_("%<%.*s%> directive output truncated writing "
2528 "up to %wu bytes into a region of size %wu"))
2529 : G_("%<%.*s%> directive writing up to %wu bytes "
2530 "into a region of size %wu"));
2531 return fmtwarn (dirloc, argloc, NULL,
2532 info.warnopt (), fmtstr, dir.len,
2533 target_to_host (hostdir, sizeof hostdir, dir.beg),
2534 res.max, navail);
2537 if (res.min == 0 && maxbytes <= res.max)
2539 /* This is a special case to avoid issuing the potentially
2540 confusing warning:
2541 writing 0 or more bytes into a region of size 0. */
2542 const char* fmtstr
2543 = (info.bounded
2544 ? (maybe
2545 ? G_("%<%.*s%> directive output may be truncated writing "
2546 "likely %wu or more bytes into a region of size %wu")
2547 : G_("%<%.*s%> directive output truncated writing "
2548 "likely %wu or more bytes into a region of size %wu"))
2549 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2550 "into a region of size %wu"));
2551 return fmtwarn (dirloc, argloc, NULL,
2552 info.warnopt (), fmtstr, dir.len,
2553 target_to_host (hostdir, sizeof hostdir, dir.beg),
2554 res.likely, navail);
2557 if (res.max < maxbytes)
2559 const char* fmtstr
2560 = (info.bounded
2561 ? (maybe
2562 ? G_("%<%.*s%> directive output may be truncated writing "
2563 "between %wu and %wu bytes into a region of size %wu")
2564 : G_("%<%.*s%> directive output truncated writing "
2565 "between %wu and %wu bytes into a region of size %wu"))
2566 : G_("%<%.*s%> directive writing between %wu and "
2567 "%wu bytes into a region of size %wu"));
2568 return fmtwarn (dirloc, argloc, NULL,
2569 info.warnopt (), fmtstr, dir.len,
2570 target_to_host (hostdir, sizeof hostdir, dir.beg),
2571 res.min, res.max, navail);
2574 const char* fmtstr
2575 = (info.bounded
2576 ? (maybe
2577 ? G_("%<%.*s%> directive output may be truncated writing "
2578 "%wu or more bytes into a region of size %wu")
2579 : G_("%<%.*s%> directive output truncated writing "
2580 "%wu or more bytes into a region of size %wu"))
2581 : G_("%<%.*s%> directive writing %wu or more bytes "
2582 "into a region of size %wu"));
2583 return fmtwarn (dirloc, argloc, NULL,
2584 info.warnopt (), fmtstr, dir.len,
2585 target_to_host (hostdir, sizeof hostdir, dir.beg),
2586 res.min, navail);
2589 /* The size of the destination region is a range. */
2591 if (target_to_host (*dir.beg) != '%')
2593 unsigned HOST_WIDE_INT navail = avail_range.max;
2595 /* For plain character directives (i.e., the format string itself)
2596 but not others, point the caret at the first character that's
2597 past the end of the destination. */
2598 if (navail < dir.len)
2599 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2602 if (*dir.beg == '\0')
2604 gcc_assert (res.min == 1 && res.min == res.max);
2606 const char *fmtstr
2607 = (info.bounded
2608 ? (maybe
2609 ? G_("%qE output may be truncated before the last format "
2610 "character")
2611 : G_("%qE output truncated before the last format character"))
2612 : (maybe
2613 ? G_("%qE may write a terminating nul past the end "
2614 "of the destination")
2615 : G_("%qE writing a terminating nul past the end "
2616 "of the destination")));
2618 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (), fmtstr,
2619 info.func);
2622 if (res.min == res.max)
2624 const char* fmtstr
2625 = (res.min == 1
2626 ? (info.bounded
2627 ? (maybe
2628 ? G_("%<%.*s%> directive output may be truncated writing "
2629 "%wu byte into a region of size between %wu and %wu")
2630 : G_("%<%.*s%> directive output truncated writing "
2631 "%wu byte into a region of size between %wu and %wu"))
2632 : G_("%<%.*s%> directive writing %wu byte "
2633 "into a region of size between %wu and %wu"))
2634 : (info.bounded
2635 ? (maybe
2636 ? G_("%<%.*s%> directive output may be truncated writing "
2637 "%wu bytes into a region of size between %wu and %wu")
2638 : G_("%<%.*s%> directive output truncated writing "
2639 "%wu bytes into a region of size between %wu and %wu"))
2640 : G_("%<%.*s%> directive writing %wu bytes "
2641 "into a region of size between %wu and %wu")));
2643 return fmtwarn (dirloc, argloc, NULL,
2644 info.warnopt (), fmtstr, dir.len,
2645 target_to_host (hostdir, sizeof hostdir, dir.beg),
2646 res.min, avail_range.min, avail_range.max);
2649 if (res.min == 0 && res.max < maxbytes)
2651 const char* fmtstr
2652 = (info.bounded
2653 ? (maybe
2654 ? G_("%<%.*s%> directive output may be truncated writing "
2655 "up to %wu bytes into a region of size between "
2656 "%wu and %wu")
2657 : G_("%<%.*s%> directive output truncated writing "
2658 "up to %wu bytes into a region of size between "
2659 "%wu and %wu"))
2660 : G_("%<%.*s%> directive writing up to %wu bytes "
2661 "into a region of size between %wu and %wu"));
2662 return fmtwarn (dirloc, argloc, NULL,
2663 info.warnopt (), fmtstr, dir.len,
2664 target_to_host (hostdir, sizeof hostdir, dir.beg),
2665 res.max, avail_range.min, avail_range.max);
2668 if (res.min == 0 && maxbytes <= res.max)
2670 /* This is a special case to avoid issuing the potentially confusing
2671 warning:
2672 writing 0 or more bytes into a region of size between 0 and N. */
2673 const char* fmtstr
2674 = (info.bounded
2675 ? (maybe
2676 ? G_("%<%.*s%> directive output may be truncated writing "
2677 "likely %wu or more bytes into a region of size between "
2678 "%wu and %wu")
2679 : G_("%<%.*s%> directive output truncated writing likely "
2680 "%wu or more bytes into a region of size between "
2681 "%wu and %wu"))
2682 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2683 "into a region of size between %wu and %wu"));
2684 return fmtwarn (dirloc, argloc, NULL,
2685 info.warnopt (), fmtstr, dir.len,
2686 target_to_host (hostdir, sizeof hostdir, dir.beg),
2687 res.likely, avail_range.min, avail_range.max);
2690 if (res.max < maxbytes)
2692 const char* fmtstr
2693 = (info.bounded
2694 ? (maybe
2695 ? G_("%<%.*s%> directive output may be truncated writing "
2696 "between %wu and %wu bytes into a region of size "
2697 "between %wu and %wu")
2698 : G_("%<%.*s%> directive output truncated writing "
2699 "between %wu and %wu bytes into a region of size "
2700 "between %wu and %wu"))
2701 : G_("%<%.*s%> directive writing between %wu and "
2702 "%wu bytes into a region of size between %wu and %wu"));
2703 return fmtwarn (dirloc, argloc, NULL,
2704 info.warnopt (), fmtstr, dir.len,
2705 target_to_host (hostdir, sizeof hostdir, dir.beg),
2706 res.min, res.max, avail_range.min, avail_range.max);
2709 const char* fmtstr
2710 = (info.bounded
2711 ? (maybe
2712 ? G_("%<%.*s%> directive output may be truncated writing "
2713 "%wu or more bytes into a region of size between "
2714 "%wu and %wu")
2715 : G_("%<%.*s%> directive output truncated writing "
2716 "%wu or more bytes into a region of size between "
2717 "%wu and %wu"))
2718 : G_("%<%.*s%> directive writing %wu or more bytes "
2719 "into a region of size between %wu and %wu"));
2720 return fmtwarn (dirloc, argloc, NULL,
2721 info.warnopt (), fmtstr, dir.len,
2722 target_to_host (hostdir, sizeof hostdir, dir.beg),
2723 res.min, avail_range.min, avail_range.max);
2726 /* Compute the length of the output resulting from the directive DIR
2727 in a call described by INFO and update the overall result of the call
2728 in *RES. Return true if the directive has been handled. */
2730 static bool
2731 format_directive (const sprintf_dom_walker::call_info &info,
2732 format_result *res, const directive &dir)
2734 /* Offset of the beginning of the directive from the beginning
2735 of the format string. */
2736 size_t offset = dir.beg - info.fmtstr;
2737 size_t start = offset;
2738 size_t length = offset + dir.len - !!dir.len;
2740 /* Create a location for the whole directive from the % to the format
2741 specifier. */
2742 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2743 offset, start, length);
2745 /* Also get the location of the argument if possible.
2746 This doesn't work for integer literals or function calls. */
2747 location_t argloc = UNKNOWN_LOCATION;
2748 if (dir.arg)
2749 argloc = EXPR_LOCATION (dir.arg);
2751 /* Bail when there is no function to compute the output length,
2752 or when minimum length checking has been disabled. */
2753 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2754 return false;
2756 /* Compute the range of lengths of the formatted output. */
2757 fmtresult fmtres = dir.fmtfunc (dir, dir.arg);
2759 /* Record whether the output of all directives is known to be
2760 bounded by some maximum, implying that their arguments are
2761 either known exactly or determined to be in a known range
2762 or, for strings, limited by the upper bounds of the arrays
2763 they refer to. */
2764 res->knownrange &= fmtres.knownrange;
2766 if (!fmtres.knownrange)
2768 /* Only when the range is known, check it against the host value
2769 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2770 INT_MAX precision, which is the longest possible output of any
2771 single directive). That's the largest valid byte count (though
2772 not valid call to a printf-like function because it can never
2773 return such a count). Otherwise, the range doesn't correspond
2774 to known values of the argument. */
2775 if (fmtres.range.max > target_dir_max ())
2777 /* Normalize the MAX counter to avoid having to deal with it
2778 later. The counter can be less than HOST_WIDE_INT_M1U
2779 when compiling for an ILP32 target on an LP64 host. */
2780 fmtres.range.max = HOST_WIDE_INT_M1U;
2781 /* Disable exact and maximum length checking after a failure
2782 to determine the maximum number of characters (for example
2783 for wide characters or wide character strings) but continue
2784 tracking the minimum number of characters. */
2785 res->range.max = HOST_WIDE_INT_M1U;
2788 if (fmtres.range.min > target_dir_max ())
2790 /* Disable exact length checking after a failure to determine
2791 even the minimum number of characters (it shouldn't happen
2792 except in an error) but keep tracking the minimum and maximum
2793 number of characters. */
2794 return true;
2798 /* Buffer for the directive in the host character set (used when
2799 the source character set is different). */
2800 char hostdir[32];
2802 int dirlen = dir.len;
2804 if (fmtres.nullp)
2806 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2807 "%<%.*s%> directive argument is null",
2808 dirlen, target_to_host (hostdir, sizeof hostdir, dir.beg));
2810 /* Don't bother processing the rest of the format string. */
2811 res->warned = true;
2812 res->range.min = HOST_WIDE_INT_M1U;
2813 res->range.max = HOST_WIDE_INT_M1U;
2814 return false;
2817 /* Compute the number of available bytes in the destination. There
2818 must always be at least one byte of space for the terminating
2819 NUL that's appended after the format string has been processed. */
2820 result_range avail_range = bytes_remaining (info.objsize, *res);
2822 bool warned = res->warned;
2824 if (!warned)
2825 warned = maybe_warn (dirloc, argloc, info, avail_range,
2826 fmtres.range, dir);
2828 /* Bump up the total maximum if it isn't too big. */
2829 if (res->range.max < HOST_WIDE_INT_MAX
2830 && fmtres.range.max < HOST_WIDE_INT_MAX)
2831 res->range.max += fmtres.range.max;
2833 /* Raise the total unlikely maximum by the larger of the maximum
2834 and the unlikely maximum. */
2835 unsigned HOST_WIDE_INT save = res->range.unlikely;
2836 if (fmtres.range.max < fmtres.range.unlikely)
2837 res->range.unlikely += fmtres.range.unlikely;
2838 else
2839 res->range.unlikely += fmtres.range.max;
2841 if (res->range.unlikely < save)
2842 res->range.unlikely = HOST_WIDE_INT_M1U;
2844 res->range.min += fmtres.range.min;
2845 res->range.likely += fmtres.range.likely;
2847 /* Has the minimum directive output length exceeded the maximum
2848 of 4095 bytes required to be supported? */
2849 bool minunder4k = fmtres.range.min < 4096;
2850 bool maxunder4k = fmtres.range.max < 4096;
2851 /* Clear UNDER4K in the overall result if the maximum has exceeded
2852 the 4k (this is necessary to avoid the return valuye optimization
2853 that may not be safe in the maximum case). */
2854 if (!maxunder4k)
2855 res->under4k = false;
2857 if (!warned
2858 /* Only warn at level 2. */
2859 && warn_level > 1
2860 && (!minunder4k
2861 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2863 /* The directive output may be longer than the maximum required
2864 to be handled by an implementation according to 7.21.6.1, p15
2865 of C11. Warn on this only at level 2 but remember this and
2866 prevent folding the return value when done. This allows for
2867 the possibility of the actual libc call failing due to ENOMEM
2868 (like Glibc does under some conditions). */
2870 if (fmtres.range.min == fmtres.range.max)
2871 warned = fmtwarn (dirloc, argloc, NULL,
2872 info.warnopt (),
2873 "%<%.*s%> directive output of %wu bytes exceeds "
2874 "minimum required size of 4095",
2875 dirlen,
2876 target_to_host (hostdir, sizeof hostdir, dir.beg),
2877 fmtres.range.min);
2878 else
2880 const char *fmtstr
2881 = (minunder4k
2882 ? G_("%<%.*s%> directive output between %wu and %wu "
2883 "bytes may exceed minimum required size of 4095")
2884 : G_("%<%.*s%> directive output between %wu and %wu "
2885 "bytes exceeds minimum required size of 4095"));
2887 warned = fmtwarn (dirloc, argloc, NULL,
2888 info.warnopt (), fmtstr, dirlen,
2889 target_to_host (hostdir, sizeof hostdir, dir.beg),
2890 fmtres.range.min, fmtres.range.max);
2894 /* Has the likely and maximum directive output exceeded INT_MAX? */
2895 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2896 /* Don't consider the maximum to be in excess when it's the result
2897 of a string of unknown length (i.e., whose maximum has been set
2898 to be greater than or equal to HOST_WIDE_INT_MAX. */
2899 bool maxximax = (*dir.beg
2900 && res->range.max > target_int_max ()
2901 && res->range.max < HOST_WIDE_INT_MAX);
2903 if (!warned
2904 /* Warn for the likely output size at level 1. */
2905 && (likelyximax
2906 /* But only warn for the maximum at level 2. */
2907 || (warn_level > 1
2908 && maxximax
2909 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2911 /* The directive output causes the total length of output
2912 to exceed INT_MAX bytes. */
2914 if (fmtres.range.min == fmtres.range.max)
2915 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2916 "%<%.*s%> directive output of %wu bytes causes "
2917 "result to exceed %<INT_MAX%>",
2918 dirlen,
2919 target_to_host (hostdir, sizeof hostdir, dir.beg),
2920 fmtres.range.min);
2921 else
2923 const char *fmtstr
2924 = (fmtres.range.min > target_int_max ()
2925 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2926 "bytes causes result to exceed %<INT_MAX%>")
2927 : G_ ("%<%.*s%> directive output between %wu and %wu "
2928 "bytes may cause result to exceed %<INT_MAX%>"));
2929 warned = fmtwarn (dirloc, argloc, NULL,
2930 info.warnopt (), fmtstr, dirlen,
2931 target_to_host (hostdir, sizeof hostdir, dir.beg),
2932 fmtres.range.min, fmtres.range.max);
2936 if (warned && fmtres.range.min < fmtres.range.likely
2937 && fmtres.range.likely < fmtres.range.max)
2938 /* Some languages have special plural rules even for large values,
2939 but it is periodic with period of 10, 100, 1000 etc. */
2940 inform_n (info.fmtloc,
2941 fmtres.range.likely > INT_MAX
2942 ? (fmtres.range.likely % 1000000) + 1000000
2943 : fmtres.range.likely,
2944 "assuming directive output of %wu byte",
2945 "assuming directive output of %wu bytes",
2946 fmtres.range.likely);
2948 if (warned && fmtres.argmin)
2950 if (fmtres.argmin == fmtres.argmax)
2951 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2952 else if (fmtres.knownrange)
2953 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2954 fmtres.argmin, fmtres.argmax);
2955 else
2956 inform (info.fmtloc,
2957 "using the range [%E, %E] for directive argument",
2958 fmtres.argmin, fmtres.argmax);
2961 res->warned |= warned;
2963 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2965 /* If a warning has been issued for buffer overflow or truncation
2966 (but not otherwise) help the user figure out how big a buffer
2967 they need. */
2969 location_t callloc = gimple_location (info.callstmt);
2971 unsigned HOST_WIDE_INT min = res->range.min;
2972 unsigned HOST_WIDE_INT max = res->range.max;
2974 if (min == max)
2975 inform (callloc,
2976 (min == 1
2977 ? G_("%qE output %wu byte into a destination of size %wu")
2978 : G_("%qE output %wu bytes into a destination of size %wu")),
2979 info.func, min, info.objsize);
2980 else if (max < HOST_WIDE_INT_MAX)
2981 inform (callloc,
2982 "%qE output between %wu and %wu bytes into "
2983 "a destination of size %wu",
2984 info.func, min, max, info.objsize);
2985 else if (min < res->range.likely && res->range.likely < max)
2986 inform (callloc,
2987 "%qE output %wu or more bytes (assuming %wu) into "
2988 "a destination of size %wu",
2989 info.func, min, res->range.likely, info.objsize);
2990 else
2991 inform (callloc,
2992 "%qE output %wu or more bytes into a destination of size %wu",
2993 info.func, min, info.objsize);
2996 if (dump_file && *dir.beg)
2998 fprintf (dump_file,
2999 " Result: "
3000 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3001 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
3002 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
3003 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
3004 fmtres.range.min, fmtres.range.likely,
3005 fmtres.range.max, fmtres.range.unlikely,
3006 res->range.min, res->range.likely,
3007 res->range.max, res->range.unlikely);
3010 return true;
3013 #pragma GCC diagnostic pop
3015 /* Parse a format directive in function call described by INFO starting
3016 at STR and populate DIR structure. Bump up *ARGNO by the number of
3017 arguments extracted for the directive. Return the length of
3018 the directive. */
3020 static size_t
3021 parse_directive (sprintf_dom_walker::call_info &info,
3022 directive &dir, format_result *res,
3023 const char *str, unsigned *argno)
3025 const char *pcnt = strchr (str, target_percent);
3026 dir.beg = str;
3028 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
3030 /* This directive is either a plain string or the terminating nul
3031 (which isn't really a directive but it simplifies things to
3032 handle it as if it were). */
3033 dir.len = len;
3034 dir.fmtfunc = format_plain;
3036 if (dump_file)
3038 fprintf (dump_file, " Directive %u at offset "
3039 HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
3040 "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
3041 dir.dirno,
3042 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3043 (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
3046 return len - !*str;
3049 const char *pf = pcnt + 1;
3051 /* POSIX numbered argument index or zero when none. */
3052 HOST_WIDE_INT dollar = 0;
3054 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3055 when given by a va_list argument, and a non-negative value
3056 when specified in the format string itself. */
3057 HOST_WIDE_INT width = -1;
3058 HOST_WIDE_INT precision = -1;
3060 /* Pointers to the beginning of the width and precision decimal
3061 string (if any) within the directive. */
3062 const char *pwidth = 0;
3063 const char *pprec = 0;
3065 /* When the value of the decimal string that specifies width or
3066 precision is out of range, points to the digit that causes
3067 the value to exceed the limit. */
3068 const char *werange = NULL;
3069 const char *perange = NULL;
3071 /* Width specified via the asterisk. Need not be INTEGER_CST.
3072 For vararg functions set to void_node. */
3073 tree star_width = NULL_TREE;
3075 /* Width specified via the asterisk. Need not be INTEGER_CST.
3076 For vararg functions set to void_node. */
3077 tree star_precision = NULL_TREE;
3079 if (ISDIGIT (target_to_host (*pf)))
3081 /* This could be either a POSIX positional argument, the '0'
3082 flag, or a width, depending on what follows. Store it as
3083 width and sort it out later after the next character has
3084 been seen. */
3085 pwidth = pf;
3086 width = target_strtol10 (&pf, &werange);
3088 else if (target_to_host (*pf) == '*')
3090 /* Similarly to the block above, this could be either a POSIX
3091 positional argument or a width, depending on what follows. */
3092 if (*argno < gimple_call_num_args (info.callstmt))
3093 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3094 else
3095 star_width = void_node;
3096 ++pf;
3099 if (target_to_host (*pf) == '$')
3101 /* Handle the POSIX dollar sign which references the 1-based
3102 positional argument number. */
3103 if (width != -1)
3104 dollar = width + info.argidx;
3105 else if (star_width
3106 && TREE_CODE (star_width) == INTEGER_CST
3107 && (TYPE_PRECISION (TREE_TYPE (star_width))
3108 <= TYPE_PRECISION (integer_type_node)))
3109 dollar = width + tree_to_shwi (star_width);
3111 /* Bail when the numbered argument is out of range (it will
3112 have already been diagnosed by -Wformat). */
3113 if (dollar == 0
3114 || dollar == (int)info.argidx
3115 || dollar > gimple_call_num_args (info.callstmt))
3116 return false;
3118 --dollar;
3120 star_width = NULL_TREE;
3121 width = -1;
3122 ++pf;
3125 if (dollar || !star_width)
3127 if (width != -1)
3129 if (width == 0)
3131 /* The '0' that has been interpreted as a width above is
3132 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3133 and continue processing other flags. */
3134 width = -1;
3135 dir.set_flag ('0');
3137 else if (!dollar)
3139 /* (Non-zero) width has been seen. The next character
3140 is either a period or a digit. */
3141 goto start_precision;
3144 /* When either '$' has been seen, or width has not been seen,
3145 the next field is the optional flags followed by an optional
3146 width. */
3147 for ( ; ; ) {
3148 switch (target_to_host (*pf))
3150 case ' ':
3151 case '0':
3152 case '+':
3153 case '-':
3154 case '#':
3155 dir.set_flag (target_to_host (*pf++));
3156 break;
3158 default:
3159 goto start_width;
3163 start_width:
3164 if (ISDIGIT (target_to_host (*pf)))
3166 werange = 0;
3167 pwidth = pf;
3168 width = target_strtol10 (&pf, &werange);
3170 else if (target_to_host (*pf) == '*')
3172 if (*argno < gimple_call_num_args (info.callstmt))
3173 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3174 else
3176 /* This is (likely) a va_list. It could also be an invalid
3177 call with insufficient arguments. */
3178 star_width = void_node;
3180 ++pf;
3182 else if (target_to_host (*pf) == '\'')
3184 /* The POSIX apostrophe indicating a numeric grouping
3185 in the current locale. Even though it's possible to
3186 estimate the upper bound on the size of the output
3187 based on the number of digits it probably isn't worth
3188 continuing. */
3189 return 0;
3193 start_precision:
3194 if (target_to_host (*pf) == '.')
3196 ++pf;
3198 if (ISDIGIT (target_to_host (*pf)))
3200 pprec = pf;
3201 precision = target_strtol10 (&pf, &perange);
3203 else if (target_to_host (*pf) == '*')
3205 if (*argno < gimple_call_num_args (info.callstmt))
3206 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3207 else
3209 /* This is (likely) a va_list. It could also be an invalid
3210 call with insufficient arguments. */
3211 star_precision = void_node;
3213 ++pf;
3215 else
3217 /* The decimal precision or the asterisk are optional.
3218 When neither is dirified it's taken to be zero. */
3219 precision = 0;
3223 switch (target_to_host (*pf))
3225 case 'h':
3226 if (target_to_host (pf[1]) == 'h')
3228 ++pf;
3229 dir.modifier = FMT_LEN_hh;
3231 else
3232 dir.modifier = FMT_LEN_h;
3233 ++pf;
3234 break;
3236 case 'j':
3237 dir.modifier = FMT_LEN_j;
3238 ++pf;
3239 break;
3241 case 'L':
3242 dir.modifier = FMT_LEN_L;
3243 ++pf;
3244 break;
3246 case 'l':
3247 if (target_to_host (pf[1]) == 'l')
3249 ++pf;
3250 dir.modifier = FMT_LEN_ll;
3252 else
3253 dir.modifier = FMT_LEN_l;
3254 ++pf;
3255 break;
3257 case 't':
3258 dir.modifier = FMT_LEN_t;
3259 ++pf;
3260 break;
3262 case 'z':
3263 dir.modifier = FMT_LEN_z;
3264 ++pf;
3265 break;
3268 switch (target_to_host (*pf))
3270 /* Handle a sole '%' character the same as "%%" but since it's
3271 undefined prevent the result from being folded. */
3272 case '\0':
3273 --pf;
3274 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3275 /* FALLTHRU */
3276 case '%':
3277 dir.fmtfunc = format_percent;
3278 break;
3280 case 'a':
3281 case 'A':
3282 case 'e':
3283 case 'E':
3284 case 'f':
3285 case 'F':
3286 case 'g':
3287 case 'G':
3288 res->floating = true;
3289 dir.fmtfunc = format_floating;
3290 break;
3292 case 'd':
3293 case 'i':
3294 case 'o':
3295 case 'u':
3296 case 'x':
3297 case 'X':
3298 dir.fmtfunc = format_integer;
3299 break;
3301 case 'p':
3302 /* The %p output is implementation-defined. It's possible
3303 to determine this format but due to extensions (edirially
3304 those of the Linux kernel -- see bug 78512) the first %p
3305 in the format string disables any further processing. */
3306 return false;
3308 case 'n':
3309 /* %n has side-effects even when nothing is actually printed to
3310 any buffer. */
3311 info.nowrite = false;
3312 dir.fmtfunc = format_none;
3313 break;
3315 case 'c':
3316 dir.fmtfunc = format_character;
3317 break;
3319 case 'S':
3320 case 's':
3321 dir.fmtfunc = format_string;
3322 break;
3324 default:
3325 /* Unknown conversion specification. */
3326 return 0;
3329 dir.specifier = target_to_host (*pf++);
3331 /* Store the length of the format directive. */
3332 dir.len = pf - pcnt;
3334 /* Buffer for the directive in the host character set (used when
3335 the source character set is different). */
3336 char hostdir[32];
3338 if (star_width)
3340 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3341 dir.set_width (star_width);
3342 else
3344 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3345 (width is the absolute value of that specified). */
3346 dir.width[0] = 0;
3347 dir.width[1] = target_int_max () + 1;
3350 else
3352 if (width == LONG_MAX && werange)
3354 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3355 size_t caret = begin + (werange - pcnt);
3356 size_t end = pf - info.fmtstr - 1;
3358 /* Create a location for the width part of the directive,
3359 pointing the caret at the first out-of-range digit. */
3360 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3361 caret, begin, end);
3363 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL,
3364 info.warnopt (), "%<%.*s%> directive width out of range",
3365 dir.len, target_to_host (hostdir, sizeof hostdir, dir.beg));
3368 dir.set_width (width);
3371 if (star_precision)
3373 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3374 dir.set_precision (star_precision);
3375 else
3377 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3378 (unlike width, negative precision is ignored). */
3379 dir.prec[0] = -1;
3380 dir.prec[1] = target_int_max ();
3383 else
3385 if (precision == LONG_MAX && perange)
3387 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3388 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3389 size_t end = pf - info.fmtstr - 2;
3391 /* Create a location for the precision part of the directive,
3392 including the leading period, pointing the caret at the first
3393 out-of-range digit . */
3394 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3395 caret, begin, end);
3397 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL,
3398 info.warnopt (), "%<%.*s%> directive precision out of range",
3399 dir.len, target_to_host (hostdir, sizeof hostdir, dir.beg));
3402 dir.set_precision (precision);
3405 /* Extract the argument if the directive takes one and if it's
3406 available (e.g., the function doesn't take a va_list). Treat
3407 missing arguments the same as va_list, even though they will
3408 have likely already been diagnosed by -Wformat. */
3409 if (dir.specifier != '%'
3410 && *argno < gimple_call_num_args (info.callstmt))
3411 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3413 if (dump_file)
3415 fprintf (dump_file,
3416 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3417 ": \"%.*s\"",
3418 dir.dirno,
3419 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3420 (int)dir.len, dir.beg);
3421 if (star_width)
3423 if (dir.width[0] == dir.width[1])
3424 fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
3425 dir.width[0]);
3426 else
3427 fprintf (dump_file,
3428 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3429 ", " HOST_WIDE_INT_PRINT_DEC "]",
3430 dir.width[0], dir.width[1]);
3433 if (star_precision)
3435 if (dir.prec[0] == dir.prec[1])
3436 fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
3437 dir.prec[0]);
3438 else
3439 fprintf (dump_file,
3440 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3441 HOST_WIDE_INT_PRINT_DEC "]",
3442 dir.prec[0], dir.prec[1]);
3444 fputc ('\n', dump_file);
3447 return dir.len;
3450 /* Compute the length of the output resulting from the call to a formatted
3451 output function described by INFO and store the result of the call in
3452 *RES. Issue warnings for detected past the end writes. Return true
3453 if the complete format string has been processed and *RES can be relied
3454 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3455 that caused the processing to be terminated early). */
3457 bool
3458 sprintf_dom_walker::compute_format_length (call_info &info,
3459 format_result *res)
3461 if (dump_file)
3463 location_t callloc = gimple_location (info.callstmt);
3464 fprintf (dump_file, "%s:%i: ",
3465 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3466 print_generic_expr (dump_file, info.func, dump_flags);
3468 fprintf (dump_file,
3469 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3470 ", fmtstr = \"%s\"\n",
3471 info.objsize, info.fmtstr);
3474 /* Reset the minimum and maximum byte counters. */
3475 res->range.min = res->range.max = 0;
3477 /* No directive has been seen yet so the length of output is bounded
3478 by the known range [0, 0] (with no conversion producing more than
3479 4K bytes) until determined otherwise. */
3480 res->knownrange = true;
3481 res->under4k = true;
3482 res->floating = false;
3483 res->warned = false;
3485 /* 1-based directive counter. */
3486 unsigned dirno = 1;
3488 /* The variadic argument counter. */
3489 unsigned argno = info.argidx;
3491 for (const char *pf = info.fmtstr; ; ++dirno)
3493 directive dir = directive ();
3494 dir.dirno = dirno;
3496 size_t n = parse_directive (info, dir, res, pf, &argno);
3498 /* Return failure if the format function fails. */
3499 if (!format_directive (info, res, dir))
3500 return false;
3502 /* Return success the directive is zero bytes long and it's
3503 the last think in the format string (i.e., it's the terminating
3504 nul, which isn't really a directive but handling it as one makes
3505 things simpler). */
3506 if (!n)
3507 return *pf == '\0';
3509 pf += n;
3512 /* The complete format string was processed (with or without warnings). */
3513 return true;
3516 /* Return the size of the object referenced by the expression DEST if
3517 available, or -1 otherwise. */
3519 static unsigned HOST_WIDE_INT
3520 get_destination_size (tree dest)
3522 /* Initialize object size info before trying to compute it. */
3523 init_object_sizes ();
3525 /* Use __builtin_object_size to determine the size of the destination
3526 object. When optimizing, determine the smallest object (such as
3527 a member array as opposed to the whole enclosing object), otherwise
3528 use type-zero object size to determine the size of the enclosing
3529 object (the function fails without optimization in this type). */
3530 int ost = optimize > 0;
3531 unsigned HOST_WIDE_INT size;
3532 if (compute_builtin_object_size (dest, ost, &size))
3533 return size;
3535 return HOST_WIDE_INT_M1U;
3538 /* Return true if the call described by INFO with result RES safe to
3539 optimize (i.e., no undefined behavior), and set RETVAL to the range
3540 of its return values. */
3542 static bool
3543 is_call_safe (const sprintf_dom_walker::call_info &info,
3544 const format_result &res, bool under4k,
3545 unsigned HOST_WIDE_INT retval[2])
3547 if (under4k && !res.under4k)
3548 return false;
3550 /* The minimum return value. */
3551 retval[0] = res.range.min;
3553 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3554 but in cases involving multibyte characters could be as large as
3555 RES.RANGE.UNLIKELY. */
3556 retval[1]
3557 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3559 /* Adjust the number of bytes which includes the terminating nul
3560 to reflect the return value of the function which does not.
3561 Because the valid range of the function is [INT_MIN, INT_MAX],
3562 a valid range before the adjustment below is [0, INT_MAX + 1]
3563 (the functions only return negative values on error or undefined
3564 behavior). */
3565 if (retval[0] <= target_int_max () + 1)
3566 --retval[0];
3567 if (retval[1] <= target_int_max () + 1)
3568 --retval[1];
3570 /* Avoid the return value optimization when the behavior of the call
3571 is undefined either because any directive may have produced 4K or
3572 more of output, or the return value exceeds INT_MAX, or because
3573 the output overflows the destination object (but leave it enabled
3574 when the function is bounded because then the behavior is well-
3575 defined). */
3576 if (retval[0] == retval[1]
3577 && (info.bounded || retval[0] < info.objsize)
3578 && retval[0] <= target_int_max ())
3579 return true;
3581 if ((info.bounded || retval[1] < info.objsize)
3582 && (retval[0] < target_int_max ()
3583 && retval[1] < target_int_max ()))
3584 return true;
3586 if (!under4k && (info.bounded || retval[0] < info.objsize))
3587 return true;
3589 return false;
3592 /* Given a suitable result RES of a call to a formatted output function
3593 described by INFO, substitute the result for the return value of
3594 the call. The result is suitable if the number of bytes it represents
3595 is known and exact. A result that isn't suitable for substitution may
3596 have its range set to the range of return values, if that is known.
3597 Return true if the call is removed and gsi_next should not be performed
3598 in the caller. */
3600 static bool
3601 try_substitute_return_value (gimple_stmt_iterator *gsi,
3602 const sprintf_dom_walker::call_info &info,
3603 const format_result &res)
3605 tree lhs = gimple_get_lhs (info.callstmt);
3607 /* Set to true when the entire call has been removed. */
3608 bool removed = false;
3610 /* The minimum and maximum return value. */
3611 unsigned HOST_WIDE_INT retval[2];
3612 bool safe = is_call_safe (info, res, true, retval);
3614 if (safe
3615 && retval[0] == retval[1]
3616 /* Not prepared to handle possibly throwing calls here; they shouldn't
3617 appear in non-artificial testcases, except when the __*_chk routines
3618 are badly declared. */
3619 && !stmt_ends_bb_p (info.callstmt))
3621 tree cst = build_int_cst (integer_type_node, retval[0]);
3623 if (lhs == NULL_TREE
3624 && info.nowrite)
3626 /* Remove the call to the bounded function with a zero size
3627 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3628 unlink_stmt_vdef (info.callstmt);
3629 gsi_remove (gsi, true);
3630 removed = true;
3632 else if (info.nowrite)
3634 /* Replace the call to the bounded function with a zero size
3635 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3636 of the function. */
3637 if (!update_call_from_tree (gsi, cst))
3638 gimplify_and_update_call_from_tree (gsi, cst);
3639 gimple *callstmt = gsi_stmt (*gsi);
3640 update_stmt (callstmt);
3642 else if (lhs)
3644 /* Replace the left-hand side of the call with the constant
3645 result of the formatted function. */
3646 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3647 gimple *g = gimple_build_assign (lhs, cst);
3648 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3649 update_stmt (info.callstmt);
3652 if (dump_file)
3654 if (removed)
3655 fprintf (dump_file, " Removing call statement.");
3656 else
3658 fprintf (dump_file, " Substituting ");
3659 print_generic_expr (dump_file, cst, dump_flags);
3660 fprintf (dump_file, " for %s.\n",
3661 info.nowrite ? "statement" : "return value");
3665 else if (lhs)
3667 bool setrange = false;
3669 if (safe
3670 && (info.bounded || retval[1] < info.objsize)
3671 && (retval[0] < target_int_max ()
3672 && retval[1] < target_int_max ()))
3674 /* If the result is in a valid range bounded by the size of
3675 the destination set it so that it can be used for subsequent
3676 optimizations. */
3677 int prec = TYPE_PRECISION (integer_type_node);
3679 wide_int min = wi::shwi (retval[0], prec);
3680 wide_int max = wi::shwi (retval[1], prec);
3681 set_range_info (lhs, VR_RANGE, min, max);
3683 setrange = true;
3686 if (dump_file)
3688 const char *inbounds
3689 = (retval[0] < info.objsize
3690 ? (retval[1] < info.objsize
3691 ? "in" : "potentially out-of")
3692 : "out-of");
3694 const char *what = setrange ? "Setting" : "Discarding";
3695 if (retval[0] != retval[1])
3696 fprintf (dump_file,
3697 " %s %s-bounds return value range ["
3698 HOST_WIDE_INT_PRINT_UNSIGNED ", "
3699 HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
3700 what, inbounds, retval[0], retval[1]);
3701 else
3702 fprintf (dump_file, " %s %s-bounds return value "
3703 HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
3704 what, inbounds, retval[0]);
3708 if (dump_file)
3709 fputc ('\n', dump_file);
3711 return removed;
3714 /* Try to simplify a s{,n}printf call described by INFO with result
3715 RES by replacing it with a simpler and presumably more efficient
3716 call (such as strcpy). */
3718 static bool
3719 try_simplify_call (gimple_stmt_iterator *gsi,
3720 const sprintf_dom_walker::call_info &info,
3721 const format_result &res)
3723 unsigned HOST_WIDE_INT dummy[2];
3724 if (!is_call_safe (info, res, info.retval_used (), dummy))
3725 return false;
3727 switch (info.fncode)
3729 case BUILT_IN_SNPRINTF:
3730 return gimple_fold_builtin_snprintf (gsi);
3732 case BUILT_IN_SPRINTF:
3733 return gimple_fold_builtin_sprintf (gsi);
3735 default:
3739 return false;
3742 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3743 functions and if so, handle it. Return true if the call is removed
3744 and gsi_next should not be performed in the caller. */
3746 bool
3747 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3749 call_info info = call_info ();
3751 info.callstmt = gsi_stmt (*gsi);
3752 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3753 return false;
3755 info.func = gimple_call_fndecl (info.callstmt);
3756 info.fncode = DECL_FUNCTION_CODE (info.func);
3758 /* The size of the destination as in snprintf(dest, size, ...). */
3759 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3761 /* The size of the destination determined by __builtin_object_size. */
3762 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3764 /* Buffer size argument number (snprintf and vsnprintf). */
3765 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3767 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3768 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3770 /* Format string argument number (valid for all functions). */
3771 unsigned idx_format;
3773 switch (info.fncode)
3775 case BUILT_IN_SPRINTF:
3776 // Signature:
3777 // __builtin_sprintf (dst, format, ...)
3778 idx_format = 1;
3779 info.argidx = 2;
3780 break;
3782 case BUILT_IN_SPRINTF_CHK:
3783 // Signature:
3784 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3785 idx_objsize = 2;
3786 idx_format = 3;
3787 info.argidx = 4;
3788 break;
3790 case BUILT_IN_SNPRINTF:
3791 // Signature:
3792 // __builtin_snprintf (dst, size, format, ...)
3793 idx_dstsize = 1;
3794 idx_format = 2;
3795 info.argidx = 3;
3796 info.bounded = true;
3797 break;
3799 case BUILT_IN_SNPRINTF_CHK:
3800 // Signature:
3801 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3802 idx_dstsize = 1;
3803 idx_objsize = 3;
3804 idx_format = 4;
3805 info.argidx = 5;
3806 info.bounded = true;
3807 break;
3809 case BUILT_IN_VSNPRINTF:
3810 // Signature:
3811 // __builtin_vsprintf (dst, size, format, va)
3812 idx_dstsize = 1;
3813 idx_format = 2;
3814 info.argidx = -1;
3815 info.bounded = true;
3816 break;
3818 case BUILT_IN_VSNPRINTF_CHK:
3819 // Signature:
3820 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3821 idx_dstsize = 1;
3822 idx_objsize = 3;
3823 idx_format = 4;
3824 info.argidx = -1;
3825 info.bounded = true;
3826 break;
3828 case BUILT_IN_VSPRINTF:
3829 // Signature:
3830 // __builtin_vsprintf (dst, format, va)
3831 idx_format = 1;
3832 info.argidx = -1;
3833 break;
3835 case BUILT_IN_VSPRINTF_CHK:
3836 // Signature:
3837 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3838 idx_format = 3;
3839 idx_objsize = 2;
3840 info.argidx = -1;
3841 break;
3843 default:
3844 return false;
3847 /* Set the global warning level for this function. */
3848 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3850 /* The first argument is a pointer to the destination. */
3851 tree dstptr = gimple_call_arg (info.callstmt, 0);
3853 info.format = gimple_call_arg (info.callstmt, idx_format);
3855 /* True when the destination size is constant as opposed to the lower
3856 or upper bound of a range. */
3857 bool dstsize_cst_p = true;
3859 if (idx_dstsize == HOST_WIDE_INT_M1U)
3861 /* For non-bounded functions like sprintf, determine the size
3862 of the destination from the object or pointer passed to it
3863 as the first argument. */
3864 dstsize = get_destination_size (dstptr);
3866 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3868 /* For bounded functions try to get the size argument. */
3870 if (TREE_CODE (size) == INTEGER_CST)
3872 dstsize = tree_to_uhwi (size);
3873 /* No object can be larger than SIZE_MAX bytes (half the address
3874 space) on the target.
3875 The functions are defined only for output of at most INT_MAX
3876 bytes. Specifying a bound in excess of that limit effectively
3877 defeats the bounds checking (and on some implementations such
3878 as Solaris cause the function to fail with EINVAL). */
3879 if (dstsize > target_size_max () / 2)
3881 /* Avoid warning if -Wstringop-overflow is specified since
3882 it also warns for the same thing though only for the
3883 checking built-ins. */
3884 if ((idx_objsize == HOST_WIDE_INT_M1U
3885 || !warn_stringop_overflow))
3886 warning_at (gimple_location (info.callstmt), info.warnopt (),
3887 "specified bound %wu exceeds maximum object size "
3888 "%wu",
3889 dstsize, target_size_max () / 2);
3891 else if (dstsize > target_int_max ())
3892 warning_at (gimple_location (info.callstmt), info.warnopt (),
3893 "specified bound %wu exceeds %<INT_MAX%>",
3894 dstsize);
3896 else if (TREE_CODE (size) == SSA_NAME)
3898 /* Try to determine the range of values of the argument
3899 and use the greater of the two at level 1 and the smaller
3900 of them at level 2. */
3901 wide_int min, max;
3902 enum value_range_type range_type
3903 = get_range_info (size, &min, &max);
3904 if (range_type == VR_RANGE)
3906 dstsize
3907 = (warn_level < 2
3908 ? wi::fits_uhwi_p (max) ? max.to_uhwi () : max.to_shwi ()
3909 : wi::fits_uhwi_p (min) ? min.to_uhwi () : min.to_shwi ());
3912 /* The destination size is not constant. If the function is
3913 bounded (e.g., snprintf) a lower bound of zero doesn't
3914 necessarily imply it can be eliminated. */
3915 dstsize_cst_p = false;
3919 if (idx_objsize != HOST_WIDE_INT_M1U)
3920 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3921 if (tree_fits_uhwi_p (size))
3922 objsize = tree_to_uhwi (size);
3924 if (info.bounded && !dstsize)
3926 /* As a special case, when the explicitly specified destination
3927 size argument (to a bounded function like snprintf) is zero
3928 it is a request to determine the number of bytes on output
3929 without actually producing any. Pretend the size is
3930 unlimited in this case. */
3931 info.objsize = HOST_WIDE_INT_MAX;
3932 info.nowrite = dstsize_cst_p;
3934 else
3936 /* For calls to non-bounded functions or to those of bounded
3937 functions with a non-zero size, warn if the destination
3938 pointer is null. */
3939 if (integer_zerop (dstptr))
3941 /* This is diagnosed with -Wformat only when the null is a constant
3942 pointer. The warning here diagnoses instances where the pointer
3943 is not constant. */
3944 location_t loc = gimple_location (info.callstmt);
3945 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3946 info.warnopt (), "null destination pointer");
3947 return false;
3950 /* Set the object size to the smaller of the two arguments
3951 of both have been specified and they're not equal. */
3952 info.objsize = dstsize < objsize ? dstsize : objsize;
3954 if (info.bounded
3955 && dstsize < target_size_max () / 2 && objsize < dstsize
3956 /* Avoid warning if -Wstringop-overflow is specified since
3957 it also warns for the same thing though only for the
3958 checking built-ins. */
3959 && (idx_objsize == HOST_WIDE_INT_M1U
3960 || !warn_stringop_overflow))
3962 warning_at (gimple_location (info.callstmt), info.warnopt (),
3963 "specified bound %wu exceeds the size %wu "
3964 "of the destination object", dstsize, objsize);
3968 if (integer_zerop (info.format))
3970 /* This is diagnosed with -Wformat only when the null is a constant
3971 pointer. The warning here diagnoses instances where the pointer
3972 is not constant. */
3973 location_t loc = gimple_location (info.callstmt);
3974 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3975 info.warnopt (), "null format string");
3976 return false;
3979 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3980 if (!info.fmtstr)
3981 return false;
3983 /* The result is the number of bytes output by the formatted function,
3984 including the terminating NUL. */
3985 format_result res = format_result ();
3987 bool success = compute_format_length (info, &res);
3989 /* When optimizing and the printf return value optimization is enabled,
3990 attempt to substitute the computed result for the return value of
3991 the call. Avoid this optimization when -frounding-math is in effect
3992 and the format string contains a floating point directive. */
3993 bool call_removed = false;
3994 if (success && optimize > 0)
3996 /* Save a copy of the iterator pointing at the call. The iterator
3997 may change to point past the call in try_substitute_return_value
3998 but the original value is needed in try_simplify_call. */
3999 gimple_stmt_iterator gsi_call = *gsi;
4001 if (flag_printf_return_value
4002 && (!flag_rounding_math || !res.floating))
4003 call_removed = try_substitute_return_value (gsi, info, res);
4005 if (!call_removed)
4006 try_simplify_call (&gsi_call, info, res);
4009 return call_removed;
4012 edge
4013 sprintf_dom_walker::before_dom_children (basic_block bb)
4015 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
4017 /* Iterate over statements, looking for function calls. */
4018 gimple *stmt = gsi_stmt (si);
4020 if (is_gimple_call (stmt) && handle_gimple_call (&si))
4021 /* If handle_gimple_call returns true, the iterator is
4022 already pointing to the next statement. */
4023 continue;
4025 gsi_next (&si);
4027 return NULL;
4030 /* Execute the pass for function FUN. */
4032 unsigned int
4033 pass_sprintf_length::execute (function *fun)
4035 init_target_to_host_charmap ();
4037 calculate_dominance_info (CDI_DOMINATORS);
4039 sprintf_dom_walker sprintf_dom_walker;
4040 sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
4042 /* Clean up object size info. */
4043 fini_object_sizes ();
4044 return 0;
4047 } /* Unnamed namespace. */
4049 /* Return a pointer to a pass object newly constructed from the context
4050 CTXT. */
4052 gimple_opt_pass *
4053 make_pass_sprintf_length (gcc::context *ctxt)
4055 return new pass_sprintf_length (ctxt);