PR tree-optimization/79691 - -Wformat-truncation suppressed by (and only by) -Og
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob7688439aab70d299708ad656af02dbbc9fda2b23
1 /* Copyright (C) 2016-2017 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"
70 #include "builtins.h"
71 #include "stor-layout.h"
73 #include "realmpfr.h"
74 #include "target.h"
76 #include "cpplib.h"
77 #include "input.h"
78 #include "toplev.h"
79 #include "substring-locations.h"
80 #include "diagnostic.h"
82 /* The likely worst case value of MB_LEN_MAX for the target, large enough
83 for UTF-8. Ideally, this would be obtained by a target hook if it were
84 to be used for optimization but it's good enough as is for warnings. */
85 #define target_mb_len_max() 6
87 /* The maximum number of bytes a single non-string directive can result
88 in. This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
89 LDBL_MAX_10_EXP of 4932. */
90 #define IEEE_MAX_10_EXP 4932
91 #define target_dir_max() (target_int_max () + IEEE_MAX_10_EXP + 2)
93 namespace {
95 const pass_data pass_data_sprintf_length = {
96 GIMPLE_PASS, // pass type
97 "printf-return-value", // pass name
98 OPTGROUP_NONE, // optinfo_flags
99 TV_NONE, // tv_id
100 PROP_cfg, // properties_required
101 0, // properties_provided
102 0, // properties_destroyed
103 0, // properties_start
104 0, // properties_finish
107 /* Set to the warning level for the current function which is equal
108 either to warn_format_trunc for bounded functions or to
109 warn_format_overflow otherwise. */
111 static int warn_level;
113 struct format_result;
115 class pass_sprintf_length : public gimple_opt_pass
117 bool fold_return_value;
119 public:
120 pass_sprintf_length (gcc::context *ctxt)
121 : gimple_opt_pass (pass_data_sprintf_length, ctxt),
122 fold_return_value (false)
125 opt_pass * clone () { return new pass_sprintf_length (m_ctxt); }
127 virtual bool gate (function *);
129 virtual unsigned int execute (function *);
131 void set_pass_param (unsigned int n, bool param)
133 gcc_assert (n == 0);
134 fold_return_value = param;
137 bool handle_gimple_call (gimple_stmt_iterator *);
139 struct call_info;
140 bool compute_format_length (call_info &, format_result *);
143 bool
144 pass_sprintf_length::gate (function *)
146 /* Run the pass iff -Warn-format-overflow or -Warn-format-truncation
147 is specified and either not optimizing and the pass is being invoked
148 early, or when optimizing and the pass is being invoked during
149 optimization (i.e., "late"). */
150 return ((warn_format_overflow > 0
151 || warn_format_trunc > 0
152 || flag_printf_return_value)
153 && (optimize > 0) == fold_return_value);
156 /* The minimum, maximum, likely, and unlikely maximum number of bytes
157 of output either a formatting function or an individual directive
158 can result in. */
160 struct result_range
162 /* The absolute minimum number of bytes. The result of a successful
163 conversion is guaranteed to be no less than this. (An erroneous
164 conversion can be indicated by MIN > HOST_WIDE_INT_MAX.) */
165 unsigned HOST_WIDE_INT min;
166 /* The likely maximum result that is used in diagnostics. In most
167 cases MAX is the same as the worst case UNLIKELY result. */
168 unsigned HOST_WIDE_INT max;
169 /* The likely result used to trigger diagnostics. For conversions
170 that result in a range of bytes [MIN, MAX], LIKELY is somewhere
171 in that range. */
172 unsigned HOST_WIDE_INT likely;
173 /* In rare cases (e.g., for nultibyte characters) UNLIKELY gives
174 the worst cases maximum result of a directive. In most cases
175 UNLIKELY == MAX. UNLIKELY is used to control the return value
176 optimization but not in diagnostics. */
177 unsigned HOST_WIDE_INT unlikely;
180 /* The result of a call to a formatted function. */
182 struct format_result
184 /* Range of characters written by the formatted function.
185 Setting the minimum to HOST_WIDE_INT_MAX disables all
186 length tracking for the remainder of the format string. */
187 result_range range;
189 /* True when the range above is obtained from known values of
190 directive arguments, or bounds on the amount of output such
191 as width and precision, and not the result of heuristics that
192 depend on warning levels. It's used to issue stricter diagnostics
193 in cases where strings of unknown lengths are bounded by the arrays
194 they are determined to refer to. KNOWNRANGE must not be used for
195 the return value optimization. */
196 bool knownrange;
198 /* True if no individual directive resulted in more than 4095 bytes
199 of output (the total NUMBER_CHARS_{MIN,MAX} might be greater).
200 Implementations are not required to handle directives that produce
201 more than 4K bytes (leading to undefined behavior) and so when one
202 is found it disables the return value optimization. */
203 bool under4k;
205 /* True when a floating point directive has been seen in the format
206 string. */
207 bool floating;
209 /* True when an intermediate result has caused a warning. Used to
210 avoid issuing duplicate warnings while finishing the processing
211 of a call. WARNED also disables the return value optimization. */
212 bool warned;
214 /* Preincrement the number of output characters by 1. */
215 format_result& operator++ ()
217 return *this += 1;
220 /* Postincrement the number of output characters by 1. */
221 format_result operator++ (int)
223 format_result prev (*this);
224 *this += 1;
225 return prev;
228 /* Increment the number of output characters by N. */
229 format_result& operator+= (unsigned HOST_WIDE_INT);
232 format_result&
233 format_result::operator+= (unsigned HOST_WIDE_INT n)
235 gcc_assert (n < HOST_WIDE_INT_MAX);
237 if (range.min < HOST_WIDE_INT_MAX)
238 range.min += n;
240 if (range.max < HOST_WIDE_INT_MAX)
241 range.max += n;
243 if (range.likely < HOST_WIDE_INT_MAX)
244 range.likely += n;
246 if (range.unlikely < HOST_WIDE_INT_MAX)
247 range.unlikely += n;
249 return *this;
252 /* Return the value of INT_MIN for the target. */
254 static inline HOST_WIDE_INT
255 target_int_min ()
257 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
260 /* Return the value of INT_MAX for the target. */
262 static inline unsigned HOST_WIDE_INT
263 target_int_max ()
265 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
268 /* Return the value of SIZE_MAX for the target. */
270 static inline unsigned HOST_WIDE_INT
271 target_size_max ()
273 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
276 /* Return the constant initial value of DECL if available or DECL
277 otherwise. Same as the synonymous function in c/c-typeck.c. */
279 static tree
280 decl_constant_value (tree decl)
282 if (/* Don't change a variable array bound or initial value to a constant
283 in a place where a variable is invalid. Note that DECL_INITIAL
284 isn't valid for a PARM_DECL. */
285 current_function_decl != 0
286 && TREE_CODE (decl) != PARM_DECL
287 && !TREE_THIS_VOLATILE (decl)
288 && TREE_READONLY (decl)
289 && DECL_INITIAL (decl) != 0
290 && TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK
291 /* This is invalid if initial value is not constant.
292 If it has either a function call, a memory reference,
293 or a variable, then re-evaluating it could give different results. */
294 && TREE_CONSTANT (DECL_INITIAL (decl))
295 /* Check for cases where this is sub-optimal, even though valid. */
296 && TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)
297 return DECL_INITIAL (decl);
298 return decl;
301 /* Given FORMAT, set *PLOC to the source location of the format string
302 and return the format string if it is known or null otherwise. */
304 static const char*
305 get_format_string (tree format, location_t *ploc)
307 if (VAR_P (format))
309 /* Pull out a constant value if the front end didn't. */
310 format = decl_constant_value (format);
311 STRIP_NOPS (format);
314 if (integer_zerop (format))
316 /* FIXME: Diagnose null format string if it hasn't been diagnosed
317 by -Wformat (the latter diagnoses only nul pointer constants,
318 this pass can do better). */
319 return NULL;
322 HOST_WIDE_INT offset = 0;
324 if (TREE_CODE (format) == POINTER_PLUS_EXPR)
326 tree arg0 = TREE_OPERAND (format, 0);
327 tree arg1 = TREE_OPERAND (format, 1);
328 STRIP_NOPS (arg0);
329 STRIP_NOPS (arg1);
331 if (TREE_CODE (arg1) != INTEGER_CST)
332 return NULL;
334 format = arg0;
336 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
337 if (!cst_and_fits_in_hwi (arg1))
338 return NULL;
340 offset = int_cst_value (arg1);
343 if (TREE_CODE (format) != ADDR_EXPR)
344 return NULL;
346 *ploc = EXPR_LOC_OR_LOC (format, input_location);
348 format = TREE_OPERAND (format, 0);
350 if (TREE_CODE (format) == ARRAY_REF
351 && tree_fits_shwi_p (TREE_OPERAND (format, 1))
352 && (offset += tree_to_shwi (TREE_OPERAND (format, 1))) >= 0)
353 format = TREE_OPERAND (format, 0);
355 if (offset < 0)
356 return NULL;
358 tree array_init;
359 tree array_size = NULL_TREE;
361 if (VAR_P (format)
362 && TREE_CODE (TREE_TYPE (format)) == ARRAY_TYPE
363 && (array_init = decl_constant_value (format)) != format
364 && TREE_CODE (array_init) == STRING_CST)
366 /* Extract the string constant initializer. Note that this may
367 include a trailing NUL character that is not in the array (e.g.
368 const char a[3] = "foo";). */
369 array_size = DECL_SIZE_UNIT (format);
370 format = array_init;
373 if (TREE_CODE (format) != STRING_CST)
374 return NULL;
376 if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format))) != char_type_node)
378 /* Wide format string. */
379 return NULL;
382 const char *fmtstr = TREE_STRING_POINTER (format);
383 unsigned fmtlen = TREE_STRING_LENGTH (format);
385 if (array_size)
387 /* Variable length arrays can't be initialized. */
388 gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
390 if (tree_fits_shwi_p (array_size))
392 HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
393 if (array_size_value > 0
394 && array_size_value == (int) array_size_value
395 && fmtlen > array_size_value)
396 fmtlen = array_size_value;
399 if (offset)
401 if (offset >= fmtlen)
402 return NULL;
404 fmtstr += offset;
405 fmtlen -= offset;
408 if (fmtlen < 1 || fmtstr[--fmtlen] != 0)
410 /* FIXME: Diagnose an unterminated format string if it hasn't been
411 diagnosed by -Wformat. Similarly to a null format pointer,
412 -Wformay diagnoses only nul pointer constants, this pass can
413 do better). */
414 return NULL;
417 return fmtstr;
420 /* The format_warning_at_substring function is not used here in a way
421 that makes using attribute format viable. Suppress the warning. */
423 #pragma GCC diagnostic push
424 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
426 /* For convenience and brevity. */
428 static bool
429 (* const fmtwarn) (const substring_loc &, const source_range *,
430 const char *, int, const char *, ...)
431 = format_warning_at_substring;
433 /* Format length modifiers. */
435 enum format_lengths
437 FMT_LEN_none,
438 FMT_LEN_hh, // char argument
439 FMT_LEN_h, // short
440 FMT_LEN_l, // long
441 FMT_LEN_ll, // long long
442 FMT_LEN_L, // long double (and GNU long long)
443 FMT_LEN_z, // size_t
444 FMT_LEN_t, // ptrdiff_t
445 FMT_LEN_j // intmax_t
449 /* Description of the result of conversion either of a single directive
450 or the whole format string. */
452 struct fmtresult
454 /* Construct a FMTRESULT object with all counters initialized
455 to MIN. KNOWNRANGE is set when MIN is valid. */
456 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
457 : argmin (), argmax (),
458 knownrange (min < HOST_WIDE_INT_MAX),
459 nullp ()
461 range.min = min;
462 range.max = min;
463 range.likely = min;
464 range.unlikely = min;
467 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
468 KNOWNRANGE is set when both MIN and MAX are valid. */
469 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
470 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
471 : argmin (), argmax (),
472 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
473 nullp ()
475 range.min = min;
476 range.max = max;
477 range.likely = max < likely ? min : likely;
478 range.unlikely = max;
481 /* Adjust result upward to reflect the RANGE of values the specified
482 width or precision is known to be in. */
483 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
484 tree = NULL_TREE,
485 unsigned = 0, unsigned = 0);
487 /* Return the maximum number of decimal digits a value of TYPE
488 formats as on output. */
489 static unsigned type_max_digits (tree, int);
491 /* The range a directive's argument is in. */
492 tree argmin, argmax;
494 /* The minimum and maximum number of bytes that a directive
495 results in on output for an argument in the range above. */
496 result_range range;
498 /* True when the range above is obtained from a known value of
499 a directive's argument or its bounds and not the result of
500 heuristics that depend on warning levels. */
501 bool knownrange;
503 /* True when the argument is a null pointer. */
504 bool nullp;
507 /* Adjust result upward to reflect the range ADJUST of values the
508 specified width or precision is known to be in. When non-null,
509 TYPE denotes the type of the directive whose result is being
510 adjusted, BASE gives the base of the directive (octal, decimal,
511 or hex), and ADJ denotes the additional adjustment to the LIKELY
512 counter that may need to be added when ADJUST is a range. */
514 fmtresult&
515 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
516 tree type /* = NULL_TREE */,
517 unsigned base /* = 0 */,
518 unsigned adj /* = 0 */)
520 bool minadjusted = false;
522 /* Adjust the minimum and likely counters. */
523 if (adjust[0] >= 0)
525 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
527 range.min = adjust[0];
528 minadjusted = true;
531 /* Adjust the likely counter. */
532 if (range.likely < range.min)
533 range.likely = range.min;
535 else if (adjust[0] == target_int_min ()
536 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
537 knownrange = false;
539 /* Adjust the maximum counter. */
540 if (adjust[1] > 0)
542 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
544 range.max = adjust[1];
546 /* Set KNOWNRANGE if both the minimum and maximum have been
547 adjusted. Otherwise leave it at what it was before. */
548 knownrange = minadjusted;
552 if (warn_level > 1 && type)
554 /* For large non-constant width or precision whose range spans
555 the maximum number of digits produced by the directive for
556 any argument, set the likely number of bytes to be at most
557 the number digits plus other adjustment determined by the
558 caller (one for sign or two for the hexadecimal "0x"
559 prefix). */
560 unsigned dirdigs = type_max_digits (type, base);
561 if (adjust[0] < dirdigs && dirdigs < adjust[1]
562 && range.likely < dirdigs)
563 range.likely = dirdigs + adj;
565 else if (range.likely < (range.min ? range.min : 1))
567 /* Conservatively, set LIKELY to at least MIN but no less than
568 1 unless MAX is zero. */
569 range.likely = (range.min
570 ? range.min
571 : range.max && (range.max < HOST_WIDE_INT_MAX
572 || warn_level > 1) ? 1 : 0);
575 /* Finally adjust the unlikely counter to be at least as large as
576 the maximum. */
577 if (range.unlikely < range.max)
578 range.unlikely = range.max;
580 return *this;
583 /* Return the maximum number of digits a value of TYPE formats in
584 BASE on output, not counting base prefix . */
586 unsigned
587 fmtresult::type_max_digits (tree type, int base)
589 unsigned prec = TYPE_PRECISION (type);
590 if (base == 8)
591 return (prec + 2) / 3;
593 if (base == 16)
594 return prec / 4;
596 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
597 of 8, 16, 32, and 64 bits. */
598 return prec * 301 / 1000 + 1;
601 static bool
602 get_int_range (tree, tree, HOST_WIDE_INT *, HOST_WIDE_INT *,
603 bool, HOST_WIDE_INT);
605 /* Description of a format directive. A directive is either a plain
606 string or a conversion specification that starts with '%'. */
608 struct directive
610 /* The 1-based directive number (for debugging). */
611 unsigned dirno;
613 /* The first character of the directive and its length. */
614 const char *beg;
615 size_t len;
617 /* A bitmap of flags, one for each character. */
618 unsigned flags[256 / sizeof (int)];
620 /* The range of values of the specified width, or -1 if not specified. */
621 HOST_WIDE_INT width[2];
622 /* The range of values of the specified precision, or -1 if not
623 specified. */
624 HOST_WIDE_INT prec[2];
626 /* Length modifier. */
627 format_lengths modifier;
629 /* Format specifier character. */
630 char specifier;
632 /* The argument of the directive or null when the directive doesn't
633 take one or when none is available (such as for vararg functions). */
634 tree arg;
636 /* Format conversion function that given a directive and an argument
637 returns the formatting result. */
638 fmtresult (*fmtfunc) (const directive &, tree);
640 /* Return True when a the format flag CHR has been used. */
641 bool get_flag (char chr) const
643 unsigned char c = chr & 0xff;
644 return (flags[c / (CHAR_BIT * sizeof *flags)]
645 & (1U << (c % (CHAR_BIT * sizeof *flags))));
648 /* Make a record of the format flag CHR having been used. */
649 void set_flag (char chr)
651 unsigned char c = chr & 0xff;
652 flags[c / (CHAR_BIT * sizeof *flags)]
653 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
656 /* Reset the format flag CHR. */
657 void clear_flag (char chr)
659 unsigned char c = chr & 0xff;
660 flags[c / (CHAR_BIT * sizeof *flags)]
661 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
664 /* Set both bounds of the width range to VAL. */
665 void set_width (HOST_WIDE_INT val)
667 width[0] = width[1] = val;
670 /* Set the width range according to ARG, with both bounds being
671 no less than 0. For a constant ARG set both bounds to its value
672 or 0, whichever is greater. For a non-constant ARG in some range
673 set width to its range adjusting each bound to -1 if it's less.
674 For an indeterminate ARG set width to [0, INT_MAX]. */
675 void set_width (tree arg)
677 get_int_range (arg, integer_type_node, width, width + 1, true, 0);
680 /* Set both bounds of the precision range to VAL. */
681 void set_precision (HOST_WIDE_INT val)
683 prec[0] = prec[1] = val;
686 /* Set the precision range according to ARG, with both bounds being
687 no less than -1. For a constant ARG set both bounds to its value
688 or -1 whichever is greater. For a non-constant ARG in some range
689 set precision to its range adjusting each bound to -1 if it's less.
690 For an indeterminate ARG set precision to [-1, INT_MAX]. */
691 void set_precision (tree arg)
693 get_int_range (arg, integer_type_node, prec, prec + 1, false, -1);
697 /* Return the logarithm of X in BASE. */
699 static int
700 ilog (unsigned HOST_WIDE_INT x, int base)
702 int res = 0;
705 ++res;
706 x /= base;
707 } while (x);
708 return res;
711 /* Return the number of bytes resulting from converting into a string
712 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
713 PLUS indicates whether 1 for a plus sign should be added for positive
714 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
715 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
716 be represented. */
718 static HOST_WIDE_INT
719 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
721 unsigned HOST_WIDE_INT absval;
723 HOST_WIDE_INT res;
725 if (TYPE_UNSIGNED (TREE_TYPE (x)))
727 if (tree_fits_uhwi_p (x))
729 absval = tree_to_uhwi (x);
730 res = plus;
732 else
733 return -1;
735 else
737 if (tree_fits_shwi_p (x))
739 HOST_WIDE_INT i = tree_to_shwi (x);
740 if (HOST_WIDE_INT_MIN == i)
742 /* Avoid undefined behavior due to negating a minimum. */
743 absval = HOST_WIDE_INT_MAX;
744 res = 1;
746 else if (i < 0)
748 absval = -i;
749 res = 1;
751 else
753 absval = i;
754 res = plus;
757 else
758 return -1;
761 int ndigs = ilog (absval, base);
763 res += prec < ndigs ? ndigs : prec;
765 /* Adjust a non-zero value for the base prefix, either hexadecimal,
766 or, unless precision has resulted in a leading zero, also octal. */
767 if (prefix && absval && (base == 16 || prec <= ndigs))
769 if (base == 8)
770 res += 1;
771 else if (base == 16)
772 res += 2;
775 return res;
778 /* Given the formatting result described by RES and NAVAIL, the number
779 of available in the destination, return the range of bytes remaining
780 in the destination. */
782 static inline result_range
783 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
785 result_range range;
787 if (HOST_WIDE_INT_MAX <= navail)
789 range.min = range.max = range.likely = range.unlikely = navail;
790 return range;
793 /* The lower bound of the available range is the available size
794 minus the maximum output size, and the upper bound is the size
795 minus the minimum. */
796 range.max = res.range.min < navail ? navail - res.range.min : 0;
798 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
800 if (res.range.max < HOST_WIDE_INT_MAX)
801 range.min = res.range.max < navail ? navail - res.range.max : 0;
802 else
803 range.min = range.likely;
805 range.unlikely = (res.range.unlikely < navail
806 ? navail - res.range.unlikely : 0);
808 return range;
811 /* Description of a call to a formatted function. */
813 struct pass_sprintf_length::call_info
815 /* Function call statement. */
816 gimple *callstmt;
818 /* Function called. */
819 tree func;
821 /* Called built-in function code. */
822 built_in_function fncode;
824 /* Format argument and format string extracted from it. */
825 tree format;
826 const char *fmtstr;
828 /* The location of the format argument. */
829 location_t fmtloc;
831 /* The destination object size for __builtin___xxx_chk functions
832 typically determined by __builtin_object_size, or -1 if unknown. */
833 unsigned HOST_WIDE_INT objsize;
835 /* Number of the first variable argument. */
836 unsigned HOST_WIDE_INT argidx;
838 /* True for functions like snprintf that specify the size of
839 the destination, false for others like sprintf that don't. */
840 bool bounded;
842 /* True for bounded functions like snprintf that specify a zero-size
843 buffer as a request to compute the size of output without actually
844 writing any. NOWRITE is cleared in response to the %n directive
845 which has side-effects similar to writing output. */
846 bool nowrite;
848 /* Return true if the called function's return value is used. */
849 bool retval_used () const
851 return gimple_get_lhs (callstmt);
854 /* Return the warning option corresponding to the called function. */
855 int warnopt () const
857 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
861 /* Return the result of formatting a no-op directive (such as '%n'). */
863 static fmtresult
864 format_none (const directive &, tree)
866 fmtresult res (0);
867 return res;
870 /* Return the result of formatting the '%%' directive. */
872 static fmtresult
873 format_percent (const directive &, tree)
875 fmtresult res (1);
876 return res;
880 /* Compute intmax_type_node and uintmax_type_node similarly to how
881 tree.c builds size_type_node. */
883 static void
884 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
886 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
888 *pintmax = integer_type_node;
889 *puintmax = unsigned_type_node;
891 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
893 *pintmax = long_integer_type_node;
894 *puintmax = long_unsigned_type_node;
896 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
898 *pintmax = long_long_integer_type_node;
899 *puintmax = long_long_unsigned_type_node;
901 else
903 for (int i = 0; i < NUM_INT_N_ENTS; i++)
904 if (int_n_enabled_p[i])
906 char name[50];
907 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
909 if (strcmp (name, UINTMAX_TYPE) == 0)
911 *pintmax = int_n_trees[i].signed_type;
912 *puintmax = int_n_trees[i].unsigned_type;
913 return;
916 gcc_unreachable ();
920 /* Determine the range [*PMIN, *PMAX] that the expression ARG of TYPE
921 is in. Return true when the range is a subrange of that of TYPE.
922 Whn ARG is null it is as if it had the full range of TYPE.
923 When ABSOLUTE is true the range reflects the absolute value of
924 the argument. When ABSOLUTE is false, negative bounds of
925 the determined range are replaced with NEGBOUND. */
927 static bool
928 get_int_range (tree arg, tree type, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
929 bool absolute, HOST_WIDE_INT negbound)
931 bool knownrange = false;
933 if (!arg)
935 *pmin = (TYPE_UNSIGNED (type)
936 ? tree_to_uhwi (TYPE_MIN_VALUE (type))
937 : tree_to_shwi (TYPE_MIN_VALUE (type)));
938 *pmax = tree_to_uhwi (TYPE_MAX_VALUE (type));
940 else if (TREE_CODE (arg) == INTEGER_CST)
942 /* For a constant argument return its value adjusted as specified
943 by NEGATIVE and NEGBOUND and return true to indicate that the
944 result is known. */
945 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
946 *pmax = *pmin;
947 knownrange = true;
949 else
951 /* True if the argument's range cannot be determined. */
952 bool unknown = true;
954 type = TREE_TYPE (arg);
956 if (TREE_CODE (arg) == SSA_NAME
957 && TREE_CODE (type) == INTEGER_TYPE)
959 /* Try to determine the range of values of the integer argument. */
960 wide_int min, max;
961 enum value_range_type range_type = get_range_info (arg, &min, &max);
962 if (range_type == VR_RANGE)
964 HOST_WIDE_INT type_min
965 = (TYPE_UNSIGNED (type)
966 ? tree_to_uhwi (TYPE_MIN_VALUE (type))
967 : tree_to_shwi (TYPE_MIN_VALUE (type)));
969 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (type));
971 *pmin = min.to_shwi ();
972 *pmax = max.to_shwi ();
974 /* Return true if the adjusted range is a subrange of
975 the full range of the argument's type. */
976 knownrange = type_min < *pmin || *pmax < type_max;
978 unknown = false;
982 /* Handle an argument with an unknown range as if none had been
983 provided. */
984 if (unknown)
985 return get_int_range (NULL_TREE, type, pmin, pmax, absolute, negbound);
988 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
989 if (absolute)
991 if (*pmin < 0)
993 if (*pmin == *pmax)
994 *pmin = *pmax = -*pmin;
995 else
997 HOST_WIDE_INT tmp = -*pmin;
998 *pmin = 0;
999 if (*pmax < tmp)
1000 *pmax = tmp;
1004 else if (*pmin < negbound)
1005 *pmin = negbound;
1007 return knownrange;
1010 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1011 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1012 the type of the directive's formal argument it's possible for both
1013 to result in the same number of bytes or a range of bytes that's
1014 less than the number of bytes that would result from formatting
1015 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1016 determined by checking for the actual argument being in the range
1017 of the type of the directive. If it isn't it must be assumed to
1018 take on the full range of the directive's type.
1019 Return true when the range has been adjusted to the full range
1020 of DIRTYPE, and false otherwise. */
1022 static bool
1023 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1025 tree argtype = TREE_TYPE (*argmin);
1026 unsigned argprec = TYPE_PRECISION (argtype);
1027 unsigned dirprec = TYPE_PRECISION (dirtype);
1029 /* If the actual argument and the directive's argument have the same
1030 precision and sign there can be no overflow and so there is nothing
1031 to adjust. */
1032 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1033 return false;
1035 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1036 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1038 if (TREE_CODE (*argmin) == INTEGER_CST
1039 && TREE_CODE (*argmax) == INTEGER_CST
1040 && (dirprec >= argprec
1041 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1042 int_const_binop (MINUS_EXPR,
1043 *argmax,
1044 *argmin),
1045 size_int (dirprec)))))
1047 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1048 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1050 /* If *ARGMIN is still less than *ARGMAX the conversion above
1051 is safe. Otherwise, it has overflowed and would be unsafe. */
1052 if (tree_int_cst_le (*argmin, *argmax))
1053 return false;
1056 *argmin = TYPE_MIN_VALUE (dirtype);
1057 *argmax = TYPE_MAX_VALUE (dirtype);
1058 return true;
1061 /* Return a range representing the minimum and maximum number of bytes
1062 that the format directive DIR will output for any argument given
1063 the WIDTH and PRECISION (extracted from DIR). This function is
1064 used when the directive argument or its value isn't known. */
1066 static fmtresult
1067 format_integer (const directive &dir, tree arg)
1069 tree intmax_type_node;
1070 tree uintmax_type_node;
1072 /* Base to format the number in. */
1073 int base;
1075 /* True when a conversion is preceded by a prefix indicating the base
1076 of the argument (octal or hexadecimal). */
1077 bool maybebase = dir.get_flag ('#');
1079 /* True when a signed conversion is preceded by a sign or space. */
1080 bool maybesign = false;
1082 /* True for signed conversions (i.e., 'd' and 'i'). */
1083 bool sign = false;
1085 switch (dir.specifier)
1087 case 'd':
1088 case 'i':
1089 /* Space and '+' are only meaningful for signed conversions. */
1090 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1091 sign = true;
1092 base = 10;
1093 break;
1094 case 'u':
1095 base = 10;
1096 break;
1097 case 'o':
1098 base = 8;
1099 break;
1100 case 'X':
1101 case 'x':
1102 base = 16;
1103 break;
1104 default:
1105 gcc_unreachable ();
1108 /* The type of the "formal" argument expected by the directive. */
1109 tree dirtype = NULL_TREE;
1111 /* Determine the expected type of the argument from the length
1112 modifier. */
1113 switch (dir.modifier)
1115 case FMT_LEN_none:
1116 if (dir.specifier == 'p')
1117 dirtype = ptr_type_node;
1118 else
1119 dirtype = sign ? integer_type_node : unsigned_type_node;
1120 break;
1122 case FMT_LEN_h:
1123 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1124 break;
1126 case FMT_LEN_hh:
1127 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1128 break;
1130 case FMT_LEN_l:
1131 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1132 break;
1134 case FMT_LEN_L:
1135 case FMT_LEN_ll:
1136 dirtype = (sign
1137 ? long_long_integer_type_node
1138 : long_long_unsigned_type_node);
1139 break;
1141 case FMT_LEN_z:
1142 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1143 break;
1145 case FMT_LEN_t:
1146 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1147 break;
1149 case FMT_LEN_j:
1150 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1151 dirtype = sign ? intmax_type_node : uintmax_type_node;
1152 break;
1154 default:
1155 return fmtresult ();
1158 /* The type of the argument to the directive, either deduced from
1159 the actual non-constant argument if one is known, or from
1160 the directive itself when none has been provided because it's
1161 a va_list. */
1162 tree argtype = NULL_TREE;
1164 if (!arg)
1166 /* When the argument has not been provided, use the type of
1167 the directive's argument as an approximation. This will
1168 result in false positives for directives like %i with
1169 arguments with smaller precision (such as short or char). */
1170 argtype = dirtype;
1172 else if (TREE_CODE (arg) == INTEGER_CST)
1174 /* When a constant argument has been provided use its value
1175 rather than type to determine the length of the output. */
1176 fmtresult res;
1178 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1180 /* As a special case, a precision of zero with a zero argument
1181 results in zero bytes except in base 8 when the '#' flag is
1182 specified, and for signed conversions in base 8 and 10 when
1183 flags when either the space or '+' flag has been specified
1184 when it results in just one byte (with width having the normal
1185 effect). This must extend to the case of a specified precision
1186 with an unknown value because it can be zero. */
1187 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1188 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1190 res.range.max = 1;
1191 res.range.likely = 1;
1193 else
1195 res.range.max = res.range.min;
1196 res.range.likely = res.range.min;
1199 else
1201 /* Convert the argument to the type of the directive. */
1202 arg = fold_convert (dirtype, arg);
1204 res.range.min = tree_digits (arg, base, dir.prec[0],
1205 maybesign, maybebase);
1206 if (dir.prec[0] == dir.prec[1])
1207 res.range.max = res.range.min;
1208 else
1209 res.range.max = tree_digits (arg, base, dir.prec[1],
1210 maybesign, maybebase);
1211 res.range.likely = res.range.min;
1214 res.range.unlikely = res.range.max;
1216 /* Bump up the counters if WIDTH is greater than LEN. */
1217 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1218 (sign | maybebase) + (base == 16));
1219 /* Bump up the counters again if PRECision is greater still. */
1220 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1221 (sign | maybebase) + (base == 16));
1223 return res;
1225 else if (TREE_CODE (TREE_TYPE (arg)) == INTEGER_TYPE
1226 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1227 /* Determine the type of the provided non-constant argument. */
1228 argtype = TREE_TYPE (arg);
1229 else
1230 /* Don't bother with invalid arguments since they likely would
1231 have already been diagnosed, and disable any further checking
1232 of the format string by returning [-1, -1]. */
1233 return fmtresult ();
1235 fmtresult res;
1237 /* Using either the range the non-constant argument is in, or its
1238 type (either "formal" or actual), create a range of values that
1239 constrain the length of output given the warning level. */
1240 tree argmin = NULL_TREE;
1241 tree argmax = NULL_TREE;
1243 if (arg
1244 && TREE_CODE (arg) == SSA_NAME
1245 && TREE_CODE (argtype) == INTEGER_TYPE)
1247 /* Try to determine the range of values of the integer argument
1248 (range information is not available for pointers). */
1249 wide_int min, max;
1250 enum value_range_type range_type = get_range_info (arg, &min, &max);
1251 if (range_type == VR_RANGE)
1253 argmin = wide_int_to_tree (argtype, min);
1254 argmax = wide_int_to_tree (argtype, max);
1256 /* Set KNOWNRANGE if the argument is in a known subrange
1257 of the directive's type (KNOWNRANGE may be reset below). */
1258 res.knownrange
1259 = (!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1260 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax));
1262 res.argmin = argmin;
1263 res.argmax = argmax;
1265 else if (range_type == VR_ANTI_RANGE)
1267 /* Handle anti-ranges if/when bug 71690 is resolved. */
1269 else if (range_type == VR_VARYING)
1271 /* The argument here may be the result of promoting the actual
1272 argument to int. Try to determine the type of the actual
1273 argument before promotion and narrow down its range that
1274 way. */
1275 gimple *def = SSA_NAME_DEF_STMT (arg);
1276 if (is_gimple_assign (def))
1278 tree_code code = gimple_assign_rhs_code (def);
1279 if (code == INTEGER_CST)
1281 arg = gimple_assign_rhs1 (def);
1282 return format_integer (dir, arg);
1285 if (code == NOP_EXPR)
1287 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1288 if (TREE_CODE (type) == INTEGER_TYPE
1289 || TREE_CODE (type) == POINTER_TYPE)
1290 argtype = type;
1296 if (!argmin)
1298 if (TREE_CODE (argtype) == POINTER_TYPE)
1300 argmin = build_int_cst (pointer_sized_int_node, 0);
1301 argmax = build_all_ones_cst (pointer_sized_int_node);
1303 else
1305 argmin = TYPE_MIN_VALUE (argtype);
1306 argmax = TYPE_MAX_VALUE (argtype);
1310 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1311 of the directive. If it has been cleared then since ARGMIN and/or
1312 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1313 ARGMAX in the result to include in diagnostics. */
1314 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1316 res.knownrange = false;
1317 res.argmin = argmin;
1318 res.argmax = argmax;
1321 /* Recursively compute the minimum and maximum from the known range. */
1322 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1324 /* For unsigned conversions/directives or signed when
1325 the minimum is positive, use the minimum and maximum to compute
1326 the shortest and longest output, respectively. */
1327 res.range.min = format_integer (dir, argmin).range.min;
1328 res.range.max = format_integer (dir, argmax).range.max;
1330 else if (tree_int_cst_sgn (argmax) < 0)
1332 /* For signed conversions/directives if maximum is negative,
1333 use the minimum as the longest output and maximum as the
1334 shortest output. */
1335 res.range.min = format_integer (dir, argmax).range.min;
1336 res.range.max = format_integer (dir, argmin).range.max;
1338 else
1340 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1341 as the shortest output and for the longest output compute the
1342 length of the output of both minimum and maximum and pick the
1343 longer. */
1344 unsigned HOST_WIDE_INT max1 = format_integer (dir, argmin).range.max;
1345 unsigned HOST_WIDE_INT max2 = format_integer (dir, argmax).range.max;
1346 res.range.min = format_integer (dir, integer_zero_node).range.min;
1347 res.range.max = MAX (max1, max2);
1350 /* If the range is known, use the maximum as the likely length. */
1351 if (res.knownrange)
1352 res.range.likely = res.range.max;
1353 else
1355 /* Otherwise, use the minimum. Except for the case where for %#x or
1356 %#o the minimum is just for a single value in the range (0) and
1357 for all other values it is something longer, like 0x1 or 01.
1358 Use the length for value 1 in that case instead as the likely
1359 length. */
1360 res.range.likely = res.range.min;
1361 if (maybebase
1362 && base != 10
1363 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1365 if (res.range.min == 1)
1366 res.range.likely += base == 8 ? 1 : 2;
1367 else if (res.range.min == 2
1368 && base == 16
1369 && (dir.width[0] == 2 || dir.prec[0] == 2))
1370 ++res.range.likely;
1374 res.range.unlikely = res.range.max;
1375 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1376 (sign | maybebase) + (base == 16));
1377 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1378 (sign | maybebase) + (base == 16));
1380 return res;
1383 /* Return the number of bytes that a format directive consisting of FLAGS,
1384 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1385 would result for argument X under ideal conditions (i.e., if PREC
1386 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1387 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1388 This function works around those problems. */
1390 static unsigned HOST_WIDE_INT
1391 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1392 char spec, char rndspec)
1394 char fmtstr[40];
1396 HOST_WIDE_INT len = strlen (flags);
1398 fmtstr[0] = '%';
1399 memcpy (fmtstr + 1, flags, len);
1400 memcpy (fmtstr + 1 + len, ".*R", 3);
1401 fmtstr[len + 4] = rndspec;
1402 fmtstr[len + 5] = spec;
1403 fmtstr[len + 6] = '\0';
1405 spec = TOUPPER (spec);
1406 if (spec == 'E' || spec == 'F')
1408 /* For %e, specify the precision explicitly since mpfr_sprintf
1409 does its own thing just to be different (see MPFR bug 21088). */
1410 if (prec < 0)
1411 prec = 6;
1413 else
1415 /* Avoid passing negative precisions with larger magnitude to MPFR
1416 to avoid exposing its bugs. (A negative precision is supposed
1417 to be ignored.) */
1418 if (prec < 0)
1419 prec = -1;
1422 HOST_WIDE_INT p = prec;
1424 if (spec == 'G')
1426 /* For G/g, precision gives the maximum number of significant
1427 digits which is bounded by LDBL_MAX_10_EXP, or, for a 128
1428 bit IEEE extended precision, 4932. Using twice as much
1429 here should be more than sufficient for any real format. */
1430 if ((IEEE_MAX_10_EXP * 2) < prec)
1431 prec = IEEE_MAX_10_EXP * 2;
1432 p = prec;
1434 else
1436 /* Cap precision arbitrarily at 1KB and add the difference
1437 (if any) to the MPFR result. */
1438 if (prec > 1024)
1439 p = 1024;
1442 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1444 /* Handle the unlikely (impossible?) error by returning more than
1445 the maximum dictated by the function's return type. */
1446 if (len < 0)
1447 return target_dir_max () + 1;
1449 /* Adjust the return value by the difference. */
1450 if (p < prec)
1451 len += prec - p;
1453 return len;
1456 /* Return the number of bytes to format using the format specifier
1457 SPEC and the precision PREC the largest value in the real floating
1458 TYPE. */
1460 static unsigned HOST_WIDE_INT
1461 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1463 machine_mode mode = TYPE_MODE (type);
1465 /* IBM Extended mode. */
1466 if (MODE_COMPOSITE_P (mode))
1467 mode = DFmode;
1469 /* Get the real type format desription for the target. */
1470 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1471 REAL_VALUE_TYPE rv;
1473 real_maxval (&rv, 0, mode);
1475 /* Convert the GCC real value representation with the precision
1476 of the real type to the mpfr_t format with the GCC default
1477 round-to-nearest mode. */
1478 mpfr_t x;
1479 mpfr_init2 (x, rfmt->p);
1480 mpfr_from_real (x, &rv, GMP_RNDN);
1482 /* Return a value one greater to account for the leading minus sign. */
1483 unsigned HOST_WIDE_INT r
1484 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1485 mpfr_clear (x);
1486 return r;
1489 /* Return a range representing the minimum and maximum number of bytes
1490 that the directive DIR will output for any argument. This function
1491 is used when the directive argument or its value isn't known. */
1493 static fmtresult
1494 format_floating (const directive &dir)
1496 tree type;
1498 switch (dir.modifier)
1500 case FMT_LEN_l:
1501 case FMT_LEN_none:
1502 type = double_type_node;
1503 break;
1505 case FMT_LEN_L:
1506 type = long_double_type_node;
1507 break;
1509 case FMT_LEN_ll:
1510 type = long_double_type_node;
1511 break;
1513 default:
1514 return fmtresult ();
1517 /* The minimum and maximum number of bytes produced by the directive. */
1518 fmtresult res;
1520 /* The minimum output as determined by flags. It's always at least 1.
1521 When plus or space are set the output is preceded by either a sign
1522 or a space. */
1523 int flagmin = (1 /* for the first digit */
1524 + (dir.get_flag ('+') | dir.get_flag (' ')));
1526 /* When the pound flag is set the decimal point is included in output
1527 regardless of precision. Whether or not a decimal point is included
1528 otherwise depends on the specification and precision. */
1529 bool radix = dir.get_flag ('#');
1531 switch (dir.specifier)
1533 case 'A':
1534 case 'a':
1536 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1537 if (dir.prec[0] <= 0)
1538 minprec = 0;
1539 else if (dir.prec[0] > 0)
1540 minprec = dir.prec[0] + !radix /* decimal point */;
1542 res.range.min = (2 /* 0x */
1543 + flagmin
1544 + radix
1545 + minprec
1546 + 3 /* p+0 */);
1548 res.range.max = format_floating_max (type, 'a', dir.prec[1]);
1549 res.range.likely = res.range.min;
1551 /* The unlikely maximum accounts for the longest multibyte
1552 decimal point character. */
1553 res.range.unlikely = res.range.max;
1554 if (dir.prec[0] != dir.prec[1]
1555 || dir.prec[0] == -1 || dir.prec[0] > 0)
1556 res.range.unlikely += target_mb_len_max () - 1;
1558 break;
1561 case 'E':
1562 case 'e':
1564 /* The minimum output is "[-+]1.234567e+00" regardless
1565 of the value of the actual argument. */
1566 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1567 if ((dir.prec[0] < 0 && dir.prec[1] > -1) || dir.prec[0] == 0)
1568 minprec = 0;
1569 else if (dir.prec[0] > 0)
1570 minprec = dir.prec[0] + !radix /* decimal point */;
1572 res.range.min = (flagmin
1573 + radix
1574 + minprec
1575 + 2 /* e+ */ + 2);
1576 /* MPFR uses a precision of 16 by default for some reason.
1577 Set it to the C default of 6. */
1578 int maxprec = dir.prec[1] < 0 ? 6 : dir.prec[1];
1579 res.range.max = format_floating_max (type, 'e', maxprec);
1581 res.range.likely = res.range.min;
1583 /* The unlikely maximum accounts for the longest multibyte
1584 decimal point character. */
1585 if (dir.prec[0] != dir.prec[1]
1586 || dir.prec[0] == -1 || dir.prec[0] > 0)
1587 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1588 else
1589 res.range.unlikely = res.range.max;
1590 break;
1593 case 'F':
1594 case 'f':
1596 /* The lower bound when precision isn't specified is 8 bytes
1597 ("1.23456" since precision is taken to be 6). When precision
1598 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1599 when precision is greater than zero, then the lower bound
1600 is 2 plus precision (plus flags). */
1601 HOST_WIDE_INT minprec = 0;
1602 if (dir.prec[0] < 0)
1603 minprec = dir.prec[1] < 0 ? 6 + !radix /* decimal point */ : 0;
1604 else if (dir.prec[0])
1605 minprec = dir.prec[0] + !radix /* decimal point */;
1607 res.range.min = flagmin + radix + minprec;
1609 /* Compute the upper bound for -TYPE_MAX. */
1610 res.range.max = format_floating_max (type, 'f', dir.prec[1]);
1612 res.range.likely = res.range.min;
1614 /* The unlikely maximum accounts for the longest multibyte
1615 decimal point character. */
1616 if (dir.prec[0] != dir.prec[1]
1617 || dir.prec[0] == -1 || dir.prec[0] > 0)
1618 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1619 break;
1622 case 'G':
1623 case 'g':
1625 /* The %g output depends on precision and the exponent of
1626 the argument. Since the value of the argument isn't known
1627 the lower bound on the range of bytes (not counting flags
1628 or width) is 1. */
1629 res.range.min = flagmin;
1630 res.range.max = format_floating_max (type, 'g', dir.prec[1]);
1631 res.range.likely = res.range.max;
1633 /* The unlikely maximum accounts for the longest multibyte
1634 decimal point character. */
1635 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1636 break;
1639 default:
1640 return fmtresult ();
1643 /* Bump up the byte counters if WIDTH is greater. */
1644 res.adjust_for_width_or_precision (dir.width);
1645 return res;
1648 /* Return a range representing the minimum and maximum number of bytes
1649 that the directive DIR will write on output for the floating argument
1650 ARG. */
1652 static fmtresult
1653 format_floating (const directive &dir, tree arg)
1655 if (!arg || TREE_CODE (arg) != REAL_CST)
1656 return format_floating (dir);
1658 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1660 if (TOUPPER (dir.specifier) == 'A')
1662 /* For %a, leave the minimum precision unspecified to let
1663 MFPR trim trailing zeros (as it and many other systems
1664 including Glibc happen to do) and set the maximum
1665 precision to reflect what it would be with trailing zeros
1666 present (as Solaris and derived systems do). */
1667 if (prec[0] < 0)
1668 prec[0] = -1;
1669 if (prec[1] < 0)
1671 unsigned fmtprec
1672 = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->p;
1674 /* The precision of the IEEE 754 double format is 53.
1675 The precision of all other GCC binary double formats
1676 is 56 or less. */
1677 prec[1] = fmtprec <= 56 ? 13 : 15;
1681 /* The minimum and maximum number of bytes produced by the directive. */
1682 fmtresult res;
1684 /* Get the real type format desription for the target. */
1685 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1686 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1688 char fmtstr [40];
1689 char *pfmt = fmtstr;
1691 /* Append flags. */
1692 for (const char *pf = "-+ #0"; *pf; ++pf)
1693 if (dir.get_flag (*pf))
1694 *pfmt++ = *pf;
1696 *pfmt = '\0';
1699 /* Set up an array to easily iterate over. */
1700 unsigned HOST_WIDE_INT* const minmax[] = {
1701 &res.range.min, &res.range.max
1704 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1706 /* Convert the GCC real value representation with the precision
1707 of the real type to the mpfr_t format rounding down in the
1708 first iteration that computes the minimm and up in the second
1709 that computes the maximum. This order is arbibtrary because
1710 rounding in either direction can result in longer output. */
1711 mpfr_t mpfrval;
1712 mpfr_init2 (mpfrval, rfmt->p);
1713 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1715 /* Use the MPFR rounding specifier to round down in the first
1716 iteration and then up. In most but not all cases this will
1717 result in the same number of bytes. */
1718 char rndspec = "DU"[i];
1720 /* Format it and store the result in the corresponding member
1721 of the result struct. */
1722 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1723 dir.specifier, rndspec);
1724 mpfr_clear (mpfrval);
1728 /* Make sure the minimum is less than the maximum (MPFR rounding
1729 in the call to mpfr_snprintf can result in the reverse. */
1730 if (res.range.max < res.range.min)
1732 unsigned HOST_WIDE_INT tmp = res.range.min;
1733 res.range.min = res.range.max;
1734 res.range.max = tmp;
1737 res.knownrange = true;
1739 /* For the same floating point constant use the longer output
1740 as the likely maximum since with round to nearest either is
1741 equally likely. */
1742 res.range.likely = res.range.max;
1743 res.range.unlikely = res.range.max;
1745 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
1747 /* Unless the precision is zero output longer than 2 bytes may
1748 include the decimal point which must be a single character
1749 up to MB_LEN_MAX in length. This is overly conservative
1750 since in some conversions some constants result in no decimal
1751 point (e.g., in %g). */
1752 res.range.unlikely += target_mb_len_max () - 1;
1755 res.adjust_for_width_or_precision (dir.width);
1756 return res;
1759 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1760 strings referenced by the expression STR, or (-1, -1) when not known.
1761 Used by the format_string function below. */
1763 static fmtresult
1764 get_string_length (tree str)
1766 if (!str)
1767 return fmtresult ();
1769 if (tree slen = c_strlen (str, 1))
1771 /* Simply return the length of the string. */
1772 fmtresult res (tree_to_shwi (slen));
1773 return res;
1776 /* Determine the length of the shortest and longest string referenced
1777 by STR. Strings of unknown lengths are bounded by the sizes of
1778 arrays that subexpressions of STR may refer to. Pointers that
1779 aren't known to point any such arrays result in LENRANGE[1] set
1780 to SIZE_MAX. */
1781 tree lenrange[2];
1782 bool flexarray = get_range_strlen (str, lenrange);
1784 if (lenrange [0] || lenrange [1])
1786 HOST_WIDE_INT min
1787 = (tree_fits_uhwi_p (lenrange[0])
1788 ? tree_to_uhwi (lenrange[0])
1789 : 0);
1791 HOST_WIDE_INT max
1792 = (tree_fits_uhwi_p (lenrange[1])
1793 ? tree_to_uhwi (lenrange[1])
1794 : HOST_WIDE_INT_M1U);
1796 /* get_range_strlen() returns the target value of SIZE_MAX for
1797 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
1798 which may be bigger. */
1799 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
1800 min = HOST_WIDE_INT_M1U;
1801 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
1802 max = HOST_WIDE_INT_M1U;
1804 fmtresult res (min, max);
1806 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
1807 by STR are known to be bounded (though not necessarily by their
1808 actual length but perhaps by their maximum possible length). */
1809 if (res.range.max < target_int_max ())
1811 res.knownrange = true;
1812 /* When the the length of the longest string is known and not
1813 excessive use it as the likely length of the string(s). */
1814 res.range.likely = res.range.max;
1816 else
1818 /* When the upper bound is unknown (it can be zero or excessive)
1819 set the likely length to the greater of 1 and the length of
1820 the shortest string and reset the lower bound to zero. */
1821 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
1822 res.range.min = 0;
1825 /* If the range of string length has been estimated from the size
1826 of an array at the end of a struct assume that it's longer than
1827 the array bound says it is in case it's used as a poor man's
1828 flexible array member, such as in struct S { char a[4]; }; */
1829 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
1831 return res;
1834 return get_string_length (NULL_TREE);
1837 /* Return the minimum and maximum number of characters formatted
1838 by the '%c' format directives and its wide character form for
1839 the argument ARG. ARG can be null (for functions such as
1840 vsprinf). */
1842 static fmtresult
1843 format_character (const directive &dir, tree arg)
1845 fmtresult res;
1847 res.knownrange = true;
1849 if (dir.modifier == FMT_LEN_l)
1851 /* A wide character can result in as few as zero bytes. */
1852 res.range.min = 0;
1854 HOST_WIDE_INT min, max;
1855 if (get_int_range (arg, integer_type_node, &min, &max, false, 0))
1857 if (min == 0 && max == 0)
1859 /* The NUL wide character results in no bytes. */
1860 res.range.max = 0;
1861 res.range.likely = 0;
1862 res.range.unlikely = 0;
1864 else if (min > 0 && min < 128)
1866 /* A wide character in the ASCII range most likely results
1867 in a single byte, and only unlikely in up to MB_LEN_MAX. */
1868 res.range.max = 1;
1869 res.range.likely = 1;
1870 res.range.unlikely = target_mb_len_max ();
1872 else
1874 /* A wide character outside the ASCII range likely results
1875 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
1876 res.range.max = target_mb_len_max ();
1877 res.range.likely = 2;
1878 res.range.unlikely = res.range.max;
1881 else
1883 /* An unknown wide character is treated the same as a wide
1884 character outside the ASCII range. */
1885 res.range.max = target_mb_len_max ();
1886 res.range.likely = 2;
1887 res.range.unlikely = res.range.max;
1890 else
1892 /* A plain '%c' directive. Its ouput is exactly 1. */
1893 res.range.min = res.range.max = 1;
1894 res.range.likely = res.range.unlikely = 1;
1895 res.knownrange = true;
1898 /* Bump up the byte counters if WIDTH is greater. */
1899 return res.adjust_for_width_or_precision (dir.width);
1902 /* Return the minimum and maximum number of characters formatted
1903 by the '%s' format directive and its wide character form for
1904 the argument ARG. ARG can be null (for functions such as
1905 vsprinf). */
1907 static fmtresult
1908 format_string (const directive &dir, tree arg)
1910 fmtresult res;
1912 /* Compute the range the argument's length can be in. */
1913 fmtresult slen = get_string_length (arg);
1914 if (slen.range.min == slen.range.max
1915 && slen.range.min < HOST_WIDE_INT_MAX)
1917 /* The argument is either a string constant or it refers
1918 to one of a number of strings of the same length. */
1920 /* A '%s' directive with a string argument with constant length. */
1921 res.range = slen.range;
1923 if (dir.modifier == FMT_LEN_l)
1925 /* In the worst case the length of output of a wide string S
1926 is bounded by MB_LEN_MAX * wcslen (S). */
1927 res.range.max *= target_mb_len_max ();
1928 res.range.unlikely = res.range.max;
1929 /* It's likely that the the total length is not more that
1930 2 * wcslen (S).*/
1931 res.range.likely = res.range.min * 2;
1933 if (dir.prec[1] >= 0
1934 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
1936 res.range.max = dir.prec[1];
1937 res.range.likely = dir.prec[1];
1938 res.range.unlikely = dir.prec[1];
1941 if (dir.prec[0] < 0 && dir.prec[1] > -1)
1942 res.range.min = 0;
1943 else if (dir.prec[0] >= 0)
1944 res.range.likely = dir.prec[0];
1946 /* Even a non-empty wide character string need not convert into
1947 any bytes. */
1948 res.range.min = 0;
1950 else
1952 res.knownrange = true;
1954 if (dir.prec[0] < 0 && dir.prec[1] > -1)
1955 res.range.min = 0;
1956 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
1957 res.range.min = dir.prec[0];
1959 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
1961 res.range.max = dir.prec[1];
1962 res.range.likely = dir.prec[1];
1963 res.range.unlikely = dir.prec[1];
1967 else if (arg && integer_zerop (arg))
1969 /* Handle null pointer argument. */
1971 fmtresult res (0);
1972 res.nullp = true;
1973 return res;
1975 else
1977 /* For a '%s' and '%ls' directive with a non-constant string (either
1978 one of a number of strings of known length or an unknown string)
1979 the minimum number of characters is lesser of PRECISION[0] and
1980 the length of the shortest known string or zero, and the maximum
1981 is the lessser of the length of the longest known string or
1982 PTRDIFF_MAX and PRECISION[1]. The likely length is either
1983 the minimum at level 1 and the greater of the minimum and 1
1984 at level 2. This result is adjust upward for width (if it's
1985 specified). */
1987 if (dir.modifier == FMT_LEN_l)
1989 /* A wide character converts to as few as zero bytes. */
1990 slen.range.min = 0;
1991 if (slen.range.max < target_int_max ())
1992 slen.range.max *= target_mb_len_max ();
1994 if (slen.range.likely < target_int_max ())
1995 slen.range.likely *= 2;
1997 if (slen.range.likely < target_int_max ())
1998 slen.range.unlikely *= target_mb_len_max ();
2001 res.range = slen.range;
2003 if (dir.prec[0] >= 0)
2005 /* Adjust the minimum to zero if the string length is unknown,
2006 or at most the lower bound of the precision otherwise. */
2007 if (slen.range.min >= target_int_max ())
2008 res.range.min = 0;
2009 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2010 res.range.min = dir.prec[0];
2012 /* Make both maxima no greater than the upper bound of precision. */
2013 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2014 || slen.range.max >= target_int_max ())
2016 res.range.max = dir.prec[1];
2017 res.range.unlikely = dir.prec[1];
2020 /* If precision is constant, set the likely counter to the lesser
2021 of it and the maximum string length. Otherwise, if the lower
2022 bound of precision is greater than zero, set the likely counter
2023 to the minimum. Otherwise set it to zero or one based on
2024 the warning level. */
2025 if (dir.prec[0] == dir.prec[1])
2026 res.range.likely
2027 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2028 ? dir.prec[0] : slen.range.max);
2029 else if (dir.prec[0] > 0)
2030 res.range.likely = res.range.min;
2031 else
2032 res.range.likely = warn_level > 1;
2034 else if (dir.prec[1] >= 0)
2036 res.range.min = 0;
2037 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2038 res.range.max = dir.prec[1];
2039 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2041 else if (slen.range.min >= target_int_max ())
2043 res.range.min = 0;
2044 res.range.max = HOST_WIDE_INT_MAX;
2045 /* At level 1 strings of unknown length are assumed to be
2046 empty, while at level 1 they are assumed to be one byte
2047 long. */
2048 res.range.likely = warn_level > 1;
2050 else
2052 /* A string of unknown length unconstrained by precision is
2053 assumed to be empty at level 1 and just one character long
2054 at higher levels. */
2055 if (res.range.likely >= target_int_max ())
2056 res.range.likely = warn_level > 1;
2059 res.range.unlikely = res.range.max;
2062 /* Bump up the byte counters if WIDTH is greater. */
2063 return res.adjust_for_width_or_precision (dir.width);
2066 /* Format plain string (part of the format string itself). */
2068 static fmtresult
2069 format_plain (const directive &dir, tree)
2071 fmtresult res (dir.len);
2072 return res;
2075 /* Return true if the RESULT of a directive in a call describe by INFO
2076 should be diagnosed given the AVAILable space in the destination. */
2078 static bool
2079 should_warn_p (const pass_sprintf_length::call_info &info,
2080 const result_range &avail, const result_range &result)
2082 if (result.max <= avail.min)
2084 /* The least amount of space remaining in the destination is big
2085 enough for the longest output. */
2086 return false;
2089 if (info.bounded)
2091 if (warn_format_trunc == 1 && result.min <= avail.max
2092 && info.retval_used ())
2094 /* The likely amount of space remaining in the destination is big
2095 enough for the least output and the return value is used. */
2096 return false;
2099 if (warn_format_trunc == 1 && result.likely <= avail.likely
2100 && !info.retval_used ())
2102 /* The likely amount of space remaining in the destination is big
2103 enough for the likely output and the return value is unused. */
2104 return false;
2107 if (warn_format_trunc == 2
2108 && result.likely <= avail.min
2109 && (result.max <= avail.min
2110 || result.max > HOST_WIDE_INT_MAX))
2112 /* The minimum amount of space remaining in the destination is big
2113 enough for the longest output. */
2114 return false;
2117 else
2119 if (warn_level == 1 && result.likely <= avail.likely)
2121 /* The likely amount of space remaining in the destination is big
2122 enough for the likely output. */
2123 return false;
2126 if (warn_level == 2
2127 && result.likely <= avail.min
2128 && (result.max <= avail.min
2129 || result.max > HOST_WIDE_INT_MAX))
2131 /* The minimum amount of space remaining in the destination is big
2132 enough for the longest output. */
2133 return false;
2137 return true;
2140 /* At format string location describe by DIRLOC in a call described
2141 by INFO, issue a warning for a directive DIR whose output may be
2142 in excess of the available space AVAIL_RANGE in the destination
2143 given the formatting result FMTRES. This function does nothing
2144 except decide whether to issue a warning for a possible write
2145 past the end or truncation and, if so, format the warning.
2146 Return true if a warning has been issued. */
2148 static bool
2149 maybe_warn (substring_loc &dirloc, source_range *pargrange,
2150 const pass_sprintf_length::call_info &info,
2151 const result_range &avail_range, const result_range &res,
2152 const directive &dir)
2154 if (!should_warn_p (info, avail_range, res))
2155 return false;
2157 /* A warning will definitely be issued below. */
2159 /* The maximum byte count to reference in the warning. Larger counts
2160 imply that the upper bound is unknown (and could be anywhere between
2161 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2162 than "between N and X" where X is some huge number. */
2163 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2165 /* True when there is enough room in the destination for the least
2166 amount of a directive's output but not enough for its likely or
2167 maximum output. */
2168 bool maybe = (res.min <= avail_range.max
2169 && (avail_range.min < res.likely
2170 || (res.max < HOST_WIDE_INT_MAX
2171 && avail_range.min < res.max)));
2173 if (avail_range.min == avail_range.max)
2175 /* The size of the destination region is exact. */
2176 unsigned HOST_WIDE_INT navail = avail_range.max;
2178 if (*dir.beg != '%')
2180 /* For plain character directives (i.e., the format string itself)
2181 but not others, point the caret at the first character that's
2182 past the end of the destination. */
2183 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2186 if (*dir.beg == '\0')
2188 /* This is the terminating nul. */
2189 gcc_assert (res.min == 1 && res.min == res.max);
2191 const char *fmtstr
2192 = (info.bounded
2193 ? (maybe
2194 ? G_("%qE output may be truncated before the last format "
2195 "character")
2196 : G_("%qE output truncated before the last format character"))
2197 : (maybe
2198 ? G_("%qE may write a terminating nul past the end "
2199 "of the destination")
2200 : G_("%qE writing a terminating nul past the end "
2201 "of the destination")));
2203 return fmtwarn (dirloc, NULL, NULL, info.warnopt (), fmtstr,
2204 info.func);
2207 if (res.min == res.max)
2209 const char* fmtstr
2210 = (res.min == 1
2211 ? (info.bounded
2212 ? (maybe
2213 ? G_("%<%.*s%> directive output may be truncated writing "
2214 "%wu byte into a region of size %wu")
2215 : G_("%<%.*s%> directive output truncated writing "
2216 "%wu byte into a region of size %wu"))
2217 : G_("%<%.*s%> directive writing %wu byte "
2218 "into a region of size %wu"))
2219 : (info.bounded
2220 ? (maybe
2221 ? G_("%<%.*s%> directive output may be truncated writing "
2222 "%wu bytes into a region of size %wu")
2223 : G_("%<%.*s%> directive output truncated writing "
2224 "%wu bytes into a region of size %wu"))
2225 : G_("%<%.*s%> directive writing %wu bytes "
2226 "into a region of size %wu")));
2227 return fmtwarn (dirloc, pargrange, NULL,
2228 info.warnopt (), fmtstr,
2229 dir.len, dir.beg, res.min,
2230 navail);
2233 if (res.min == 0 && res.max < maxbytes)
2235 const char* fmtstr
2236 = (info.bounded
2237 ? (maybe
2238 ? G_("%<%.*s%> directive output may be truncated writing "
2239 "up to %wu bytes into a region of size %wu")
2240 : G_("%<%.*s%> directive output truncated writing "
2241 "up to %wu bytes into a region of size %wu"))
2242 : G_("%<%.*s%> directive writing up to %wu bytes "
2243 "into a region of size %wu"));
2244 return fmtwarn (dirloc, pargrange, NULL,
2245 info.warnopt (), fmtstr,
2246 dir.len, dir.beg,
2247 res.max, navail);
2250 if (res.min == 0 && maxbytes <= res.max)
2252 /* This is a special case to avoid issuing the potentially
2253 confusing warning:
2254 writing 0 or more bytes into a region of size 0. */
2255 const char* fmtstr
2256 = (info.bounded
2257 ? (maybe
2258 ? G_("%<%.*s%> directive output may be truncated writing "
2259 "likely %wu or more bytes into a region of size %wu")
2260 : G_("%<%.*s%> directive output truncated writing "
2261 "likely %wu or more bytes into a region of size %wu"))
2262 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2263 "into a region of size %wu"));
2264 return fmtwarn (dirloc, pargrange, NULL,
2265 info.warnopt (), fmtstr,
2266 dir.len, dir.beg,
2267 res.likely, navail);
2270 if (res.max < maxbytes)
2272 const char* fmtstr
2273 = (info.bounded
2274 ? (maybe
2275 ? G_("%<%.*s%> directive output may be truncated writing "
2276 "between %wu and %wu bytes into a region of size %wu")
2277 : G_("%<%.*s%> directive output truncated writing "
2278 "between %wu and %wu bytes into a region of size %wu"))
2279 : G_("%<%.*s%> directive writing between %wu and "
2280 "%wu bytes into a region of size %wu"));
2281 return fmtwarn (dirloc, pargrange, NULL,
2282 info.warnopt (), fmtstr,
2283 dir.len, dir.beg,
2284 res.min, res.max,
2285 navail);
2288 const char* fmtstr
2289 = (info.bounded
2290 ? (maybe
2291 ? G_("%<%.*s%> directive output may be truncated writing "
2292 "%wu or more bytes into a region of size %wu")
2293 : G_("%<%.*s%> directive output truncated writing "
2294 "%wu or more bytes into a region of size %wu"))
2295 : G_("%<%.*s%> directive writing %wu or more bytes "
2296 "into a region of size %wu"));
2297 return fmtwarn (dirloc, pargrange, NULL,
2298 info.warnopt (), fmtstr,
2299 dir.len, dir.beg,
2300 res.min, navail);
2303 /* The size of the destination region is a range. */
2305 if (*dir.beg != '%')
2307 unsigned HOST_WIDE_INT navail = avail_range.max;
2309 /* For plain character directives (i.e., the format string itself)
2310 but not others, point the caret at the first character that's
2311 past the end of the destination. */
2312 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2315 if (*dir.beg == '\0')
2317 gcc_assert (res.min == 1 && res.min == res.max);
2319 const char *fmtstr
2320 = (info.bounded
2321 ? (maybe
2322 ? G_("%qE output may be truncated before the last format "
2323 "character")
2324 : G_("%qE output truncated before the last format character"))
2325 : (maybe
2326 ? G_("%qE may write a terminating nul past the end "
2327 "of the destination")
2328 : G_("%qE writing a terminating nul past the end "
2329 "of the destination")));
2331 return fmtwarn (dirloc, NULL, NULL, info.warnopt (), fmtstr,
2332 info.func);
2335 if (res.min == res.max)
2337 const char* fmtstr
2338 = (res.min == 1
2339 ? (info.bounded
2340 ? (maybe
2341 ? G_("%<%.*s%> directive output may be truncated writing "
2342 "%wu byte into a region of size between %wu and %wu")
2343 : G_("%<%.*s%> directive output truncated writing "
2344 "%wu byte into a region of size between %wu and %wu"))
2345 : G_("%<%.*s%> directive writing %wu byte "
2346 "into a region of size between %wu and %wu"))
2347 : (info.bounded
2348 ? (maybe
2349 ? G_("%<%.*s%> directive output may be truncated writing "
2350 "%wu bytes into a region of size between %wu and %wu")
2351 : G_("%<%.*s%> directive output truncated writing "
2352 "%wu bytes into a region of size between %wu and %wu"))
2353 : G_("%<%.*s%> directive writing %wu bytes "
2354 "into a region of size between %wu and %wu")));
2356 return fmtwarn (dirloc, pargrange, NULL,
2357 info.warnopt (), fmtstr,
2358 dir.len, dir.beg, res.min,
2359 avail_range.min, avail_range.max);
2362 if (res.min == 0 && res.max < maxbytes)
2364 const char* fmtstr
2365 = (info.bounded
2366 ? (maybe
2367 ? G_("%<%.*s%> directive output may be truncated writing "
2368 "up to %wu bytes into a region of size between "
2369 "%wu and %wu")
2370 : G_("%<%.*s%> directive output truncated writing "
2371 "up to %wu bytes into a region of size between "
2372 "%wu and %wu"))
2373 : G_("%<%.*s%> directive writing up to %wu bytes "
2374 "into a region of size between %wu and %wu"));
2375 return fmtwarn (dirloc, pargrange, NULL,
2376 info.warnopt (), fmtstr,
2377 dir.len, dir.beg, res.max,
2378 avail_range.min, avail_range.max);
2381 if (res.min == 0 && maxbytes <= res.max)
2383 /* This is a special case to avoid issuing the potentially confusing
2384 warning:
2385 writing 0 or more bytes into a region of size between 0 and N. */
2386 const char* fmtstr
2387 = (info.bounded
2388 ? (maybe
2389 ? G_("%<%.*s%> directive output may be truncated writing "
2390 "likely %wu or more bytes into a region of size between "
2391 "%wu and %wu")
2392 : G_("%<%.*s%> directive output truncated writing likely "
2393 "%wu or more bytes into a region of size between "
2394 "%wu and %wu"))
2395 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2396 "into a region of size between %wu and %wu"));
2397 return fmtwarn (dirloc, pargrange, NULL,
2398 info.warnopt (), fmtstr,
2399 dir.len, dir.beg, res.likely,
2400 avail_range.min, avail_range.max);
2403 if (res.max < maxbytes)
2405 const char* fmtstr
2406 = (info.bounded
2407 ? (maybe
2408 ? G_("%<%.*s%> directive output may be truncated writing "
2409 "between %wu and %wu bytes into a region of size "
2410 "between %wu and %wu")
2411 : G_("%<%.*s%> directive output truncated writing "
2412 "between %wu and %wu bytes into a region of size "
2413 "between %wu and %wu"))
2414 : G_("%<%.*s%> directive writing between %wu and "
2415 "%wu bytes into a region of size between %wu and %wu"));
2416 return fmtwarn (dirloc, pargrange, NULL,
2417 info.warnopt (), fmtstr,
2418 dir.len, dir.beg,
2419 res.min, res.max,
2420 avail_range.min, avail_range.max);
2423 const char* fmtstr
2424 = (info.bounded
2425 ? (maybe
2426 ? G_("%<%.*s%> directive output may be truncated writing "
2427 "%wu or more bytes into a region of size between "
2428 "%wu and %wu")
2429 : G_("%<%.*s%> directive output truncated writing "
2430 "%wu or more bytes into a region of size between "
2431 "%wu and %wu"))
2432 : G_("%<%.*s%> directive writing %wu or more bytes "
2433 "into a region of size between %wu and %wu"));
2434 return fmtwarn (dirloc, pargrange, NULL,
2435 info.warnopt (), fmtstr,
2436 dir.len, dir.beg,
2437 res.min,
2438 avail_range.min, avail_range.max);
2441 /* Compute the length of the output resulting from the directive DIR
2442 in a call described by INFO and update the overall result of the call
2443 in *RES. Return true if the directive has been handled. */
2445 static bool
2446 format_directive (const pass_sprintf_length::call_info &info,
2447 format_result *res, const directive &dir)
2449 /* Offset of the beginning of the directive from the beginning
2450 of the format string. */
2451 size_t offset = dir.beg - info.fmtstr;
2452 size_t start = offset;
2453 size_t length = offset + dir.len - !!dir.len;
2455 /* Create a location for the whole directive from the % to the format
2456 specifier. */
2457 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2458 offset, start, length);
2460 /* Also create a location range for the argument if possible.
2461 This doesn't work for integer literals or function calls. */
2462 source_range argrange;
2463 source_range *pargrange;
2464 if (dir.arg && CAN_HAVE_LOCATION_P (dir.arg))
2466 argrange = EXPR_LOCATION_RANGE (dir.arg);
2467 pargrange = &argrange;
2469 else
2470 pargrange = NULL;
2472 /* Bail when there is no function to compute the output length,
2473 or when minimum length checking has been disabled. */
2474 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2475 return false;
2477 /* Compute the range of lengths of the formatted output. */
2478 fmtresult fmtres = dir.fmtfunc (dir, dir.arg);
2480 /* Record whether the output of all directives is known to be
2481 bounded by some maximum, implying that their arguments are
2482 either known exactly or determined to be in a known range
2483 or, for strings, limited by the upper bounds of the arrays
2484 they refer to. */
2485 res->knownrange &= fmtres.knownrange;
2487 if (!fmtres.knownrange)
2489 /* Only when the range is known, check it against the host value
2490 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2491 INT_MAX precision, which is the longest possible output of any
2492 single directive). That's the largest valid byte count (though
2493 not valid call to a printf-like function because it can never
2494 return such a count). Otherwise, the range doesn't correspond
2495 to known values of the argument. */
2496 if (fmtres.range.max > target_dir_max ())
2498 /* Normalize the MAX counter to avoid having to deal with it
2499 later. The counter can be less than HOST_WIDE_INT_M1U
2500 when compiling for an ILP32 target on an LP64 host. */
2501 fmtres.range.max = HOST_WIDE_INT_M1U;
2502 /* Disable exact and maximum length checking after a failure
2503 to determine the maximum number of characters (for example
2504 for wide characters or wide character strings) but continue
2505 tracking the minimum number of characters. */
2506 res->range.max = HOST_WIDE_INT_M1U;
2509 if (fmtres.range.min > target_dir_max ())
2511 /* Disable exact length checking after a failure to determine
2512 even the minimum number of characters (it shouldn't happen
2513 except in an error) but keep tracking the minimum and maximum
2514 number of characters. */
2515 return true;
2519 int dirlen = dir.len;
2521 if (fmtres.nullp)
2523 fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
2524 "%<%.*s%> directive argument is null",
2525 dirlen, dir.beg);
2527 /* Don't bother processing the rest of the format string. */
2528 res->warned = true;
2529 res->range.min = HOST_WIDE_INT_M1U;
2530 res->range.max = HOST_WIDE_INT_M1U;
2531 return false;
2534 /* Compute the number of available bytes in the destination. There
2535 must always be at least one byte of space for the terminating
2536 NUL that's appended after the format string has been processed. */
2537 result_range avail_range = bytes_remaining (info.objsize, *res);
2539 bool warned = res->warned;
2541 if (!warned)
2542 warned = maybe_warn (dirloc, pargrange, info, avail_range,
2543 fmtres.range, dir);
2545 /* Bump up the total maximum if it isn't too big. */
2546 if (res->range.max < HOST_WIDE_INT_MAX
2547 && fmtres.range.max < HOST_WIDE_INT_MAX)
2548 res->range.max += fmtres.range.max;
2550 /* Raise the total unlikely maximum by the larger of the maximum
2551 and the unlikely maximum. */
2552 unsigned HOST_WIDE_INT save = res->range.unlikely;
2553 if (fmtres.range.max < fmtres.range.unlikely)
2554 res->range.unlikely += fmtres.range.unlikely;
2555 else
2556 res->range.unlikely += fmtres.range.max;
2558 if (res->range.unlikely < save)
2559 res->range.unlikely = HOST_WIDE_INT_M1U;
2561 res->range.min += fmtres.range.min;
2562 res->range.likely += fmtres.range.likely;
2564 /* Has the minimum directive output length exceeded the maximum
2565 of 4095 bytes required to be supported? */
2566 bool minunder4k = fmtres.range.min < 4096;
2567 bool maxunder4k = fmtres.range.max < 4096;
2568 /* Clear UNDER4K in the overall result if the maximum has exceeded
2569 the 4k (this is necessary to avoid the return valuye optimization
2570 that may not be safe in the maximum case). */
2571 if (!maxunder4k)
2572 res->under4k = false;
2574 if (!warned
2575 /* Only warn at level 2. */
2576 && 1 < warn_level
2577 && (!minunder4k
2578 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2580 /* The directive output may be longer than the maximum required
2581 to be handled by an implementation according to 7.21.6.1, p15
2582 of C11. Warn on this only at level 2 but remember this and
2583 prevent folding the return value when done. This allows for
2584 the possibility of the actual libc call failing due to ENOMEM
2585 (like Glibc does under some conditions). */
2587 if (fmtres.range.min == fmtres.range.max)
2588 warned = fmtwarn (dirloc, pargrange, NULL,
2589 info.warnopt (),
2590 "%<%.*s%> directive output of %wu bytes exceeds "
2591 "minimum required size of 4095",
2592 dirlen, dir.beg, fmtres.range.min);
2593 else
2595 const char *fmtstr
2596 = (minunder4k
2597 ? G_("%<%.*s%> directive output between %wu and %wu "
2598 "bytes may exceed minimum required size of 4095")
2599 : G_("%<%.*s%> directive output between %wu and %wu "
2600 "bytes exceeds minimum required size of 4095"));
2602 warned = fmtwarn (dirloc, pargrange, NULL,
2603 info.warnopt (), fmtstr,
2604 dirlen, dir.beg,
2605 fmtres.range.min, fmtres.range.max);
2609 /* Has the likely and maximum directive output exceeded INT_MAX? */
2610 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2611 /* Don't consider the maximum to be in excess when it's the result
2612 of a string of unknown length (i.e., whose maximum has been set
2613 to be greater than or equal to HOST_WIDE_INT_MAX. */
2614 bool maxximax = (*dir.beg
2615 && res->range.max > target_int_max ()
2616 && res->range.max < HOST_WIDE_INT_MAX);
2618 if (!warned
2619 /* Warn for the likely output size at level 1. */
2620 && (likelyximax
2621 /* But only warn for the maximum at level 2. */
2622 || (1 < warn_level
2623 && maxximax
2624 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2626 /* The directive output causes the total length of output
2627 to exceed INT_MAX bytes. */
2629 if (fmtres.range.min == fmtres.range.max)
2630 warned = fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
2631 "%<%.*s%> directive output of %wu bytes causes "
2632 "result to exceed %<INT_MAX%>",
2633 dirlen, dir.beg, fmtres.range.min);
2634 else
2636 const char *fmtstr
2637 = (fmtres.range.min > target_int_max ()
2638 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2639 "bytes causes result to exceed %<INT_MAX%>")
2640 : G_ ("%<%.*s%> directive output between %wu and %wu "
2641 "bytes may cause result to exceed %<INT_MAX%>"));
2642 warned = fmtwarn (dirloc, pargrange, NULL,
2643 info.warnopt (), fmtstr,
2644 dirlen, dir.beg,
2645 fmtres.range.min, fmtres.range.max);
2649 if (warned && fmtres.range.min < fmtres.range.likely
2650 && fmtres.range.likely < fmtres.range.max)
2652 inform (info.fmtloc,
2653 (1 == fmtres.range.likely
2654 ? G_("assuming directive output of %wu byte")
2655 : G_("assuming directive output of %wu bytes")),
2656 fmtres.range.likely);
2659 if (warned && fmtres.argmin)
2661 if (fmtres.argmin == fmtres.argmax)
2662 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2663 else if (fmtres.knownrange)
2664 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2665 fmtres.argmin, fmtres.argmax);
2666 else
2667 inform (info.fmtloc,
2668 "using the range [%E, %E] for directive argument",
2669 fmtres.argmin, fmtres.argmax);
2672 res->warned |= warned;
2674 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2676 /* If a warning has been issued for buffer overflow or truncation
2677 (but not otherwise) help the user figure out how big a buffer
2678 they need. */
2680 location_t callloc = gimple_location (info.callstmt);
2682 unsigned HOST_WIDE_INT min = res->range.min;
2683 unsigned HOST_WIDE_INT max = res->range.max;
2685 if (min == max)
2686 inform (callloc,
2687 (min == 1
2688 ? G_("%qE output %wu byte into a destination of size %wu")
2689 : G_("%qE output %wu bytes into a destination of size %wu")),
2690 info.func, min, info.objsize);
2691 else if (max < HOST_WIDE_INT_MAX)
2692 inform (callloc,
2693 "%qE output between %wu and %wu bytes into "
2694 "a destination of size %wu",
2695 info.func, min, max, info.objsize);
2696 else if (min < res->range.likely && res->range.likely < max)
2697 inform (callloc,
2698 "%qE output %wu or more bytes (assuming %wu) into "
2699 "a destination of size %wu",
2700 info.func, min, res->range.likely, info.objsize);
2701 else
2702 inform (callloc,
2703 "%qE output %wu or more bytes into a destination of size %wu",
2704 info.func, min, info.objsize);
2707 if (dump_file && *dir.beg)
2709 fprintf (dump_file, " Result: %lli, %lli, %lli, %lli "
2710 "(%lli, %lli, %lli, %lli)\n",
2711 (long long)fmtres.range.min,
2712 (long long)fmtres.range.likely,
2713 (long long)fmtres.range.max,
2714 (long long)fmtres.range.unlikely,
2715 (long long)res->range.min,
2716 (long long)res->range.likely,
2717 (long long)res->range.max,
2718 (long long)res->range.unlikely);
2721 return true;
2724 #pragma GCC diagnostic pop
2726 /* Parse a format directive in function call described by INFO starting
2727 at STR and populate DIR structure. Bump up *ARGNO by the number of
2728 arguments extracted for the directive. Return the length of
2729 the directive. */
2731 static size_t
2732 parse_directive (pass_sprintf_length::call_info &info,
2733 directive &dir, format_result *res,
2734 const char *str, unsigned *argno)
2736 const char *pcnt = strchr (str, '%');
2737 dir.beg = str;
2739 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
2741 /* This directive is either a plain string or the terminating nul
2742 (which isn't really a directive but it simplifies things to
2743 handle it as if it were). */
2744 dir.len = len;
2745 dir.fmtfunc = format_plain;
2747 if (dump_file)
2749 fprintf (dump_file, " Directive %u at offset %llu: \"%.*s\", "
2750 "length = %llu\n",
2751 dir.dirno,
2752 (unsigned long long)(size_t)(dir.beg - info.fmtstr),
2753 (int)dir.len, dir.beg, (unsigned long long)dir.len);
2756 return len - !*str;
2759 const char *pf = pcnt + 1;
2761 /* POSIX numbered argument index or zero when none. */
2762 unsigned dollar = 0;
2764 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
2765 when given by a va_list argument, and a non-negative value
2766 when specified in the format string itself. */
2767 HOST_WIDE_INT width = -1;
2768 HOST_WIDE_INT precision = -1;
2770 /* Width specified via the asterisk. Need not be INTEGER_CST.
2771 For vararg functions set to void_node. */
2772 tree star_width = NULL_TREE;
2774 /* Width specified via the asterisk. Need not be INTEGER_CST.
2775 For vararg functions set to void_node. */
2776 tree star_precision = NULL_TREE;
2778 if (ISDIGIT (*pf))
2780 /* This could be either a POSIX positional argument, the '0'
2781 flag, or a width, depending on what follows. Store it as
2782 width and sort it out later after the next character has
2783 been seen. */
2784 char *end;
2785 width = strtol (pf, &end, 10);
2786 pf = end;
2788 else if ('*' == *pf)
2790 /* Similarly to the block above, this could be either a POSIX
2791 positional argument or a width, depending on what follows. */
2792 if (*argno < gimple_call_num_args (info.callstmt))
2793 star_width = gimple_call_arg (info.callstmt, (*argno)++);
2794 else
2795 star_width = void_node;
2796 ++pf;
2799 if (*pf == '$')
2801 /* Handle the POSIX dollar sign which references the 1-based
2802 positional argument number. */
2803 if (width != -1)
2804 dollar = width + info.argidx;
2805 else if (star_width
2806 && TREE_CODE (star_width) == INTEGER_CST)
2807 dollar = width + tree_to_shwi (star_width);
2809 /* Bail when the numbered argument is out of range (it will
2810 have already been diagnosed by -Wformat). */
2811 if (dollar == 0
2812 || dollar == info.argidx
2813 || dollar > gimple_call_num_args (info.callstmt))
2814 return false;
2816 --dollar;
2818 star_width = NULL_TREE;
2819 width = -1;
2820 ++pf;
2823 if (dollar || !star_width)
2825 if (width != -1)
2827 if (width == 0)
2829 /* The '0' that has been interpreted as a width above is
2830 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
2831 and continue processing other flags. */
2832 width = -1;
2833 dir.set_flag ('0');
2835 else if (!dollar)
2837 /* (Non-zero) width has been seen. The next character
2838 is either a period or a digit. */
2839 goto start_precision;
2842 /* When either '$' has been seen, or width has not been seen,
2843 the next field is the optional flags followed by an optional
2844 width. */
2845 for ( ; ; ) {
2846 switch (*pf)
2848 case ' ':
2849 case '0':
2850 case '+':
2851 case '-':
2852 case '#':
2853 dir.set_flag (*pf++);
2854 break;
2856 default:
2857 goto start_width;
2861 start_width:
2862 if (ISDIGIT (*pf))
2864 char *end;
2865 width = strtol (pf, &end, 10);
2866 pf = end;
2868 else if ('*' == *pf)
2870 if (*argno < gimple_call_num_args (info.callstmt))
2871 star_width = gimple_call_arg (info.callstmt, (*argno)++);
2872 else
2874 /* This is (likely) a va_list. It could also be an invalid
2875 call with insufficient arguments. */
2876 star_width = void_node;
2878 ++pf;
2880 else if ('\'' == *pf)
2882 /* The POSIX apostrophe indicating a numeric grouping
2883 in the current locale. Even though it's possible to
2884 estimate the upper bound on the size of the output
2885 based on the number of digits it probably isn't worth
2886 continuing. */
2887 return 0;
2891 start_precision:
2892 if ('.' == *pf)
2894 ++pf;
2896 if (ISDIGIT (*pf))
2898 char *end;
2899 precision = strtol (pf, &end, 10);
2900 pf = end;
2902 else if ('*' == *pf)
2904 if (*argno < gimple_call_num_args (info.callstmt))
2905 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
2906 else
2908 /* This is (likely) a va_list. It could also be an invalid
2909 call with insufficient arguments. */
2910 star_precision = void_node;
2912 ++pf;
2914 else
2916 /* The decimal precision or the asterisk are optional.
2917 When neither is dirified it's taken to be zero. */
2918 precision = 0;
2922 switch (*pf)
2924 case 'h':
2925 if (pf[1] == 'h')
2927 ++pf;
2928 dir.modifier = FMT_LEN_hh;
2930 else
2931 dir.modifier = FMT_LEN_h;
2932 ++pf;
2933 break;
2935 case 'j':
2936 dir.modifier = FMT_LEN_j;
2937 ++pf;
2938 break;
2940 case 'L':
2941 dir.modifier = FMT_LEN_L;
2942 ++pf;
2943 break;
2945 case 'l':
2946 if (pf[1] == 'l')
2948 ++pf;
2949 dir.modifier = FMT_LEN_ll;
2951 else
2952 dir.modifier = FMT_LEN_l;
2953 ++pf;
2954 break;
2956 case 't':
2957 dir.modifier = FMT_LEN_t;
2958 ++pf;
2959 break;
2961 case 'z':
2962 dir.modifier = FMT_LEN_z;
2963 ++pf;
2964 break;
2967 switch (*pf)
2969 /* Handle a sole '%' character the same as "%%" but since it's
2970 undefined prevent the result from being folded. */
2971 case '\0':
2972 --pf;
2973 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
2974 /* FALLTHRU */
2975 case '%':
2976 dir.fmtfunc = format_percent;
2977 break;
2979 case 'a':
2980 case 'A':
2981 case 'e':
2982 case 'E':
2983 case 'f':
2984 case 'F':
2985 case 'g':
2986 case 'G':
2987 res->floating = true;
2988 dir.fmtfunc = format_floating;
2989 break;
2991 case 'd':
2992 case 'i':
2993 case 'o':
2994 case 'u':
2995 case 'x':
2996 case 'X':
2997 dir.fmtfunc = format_integer;
2998 break;
3000 case 'p':
3001 /* The %p output is implementation-defined. It's possible
3002 to determine this format but due to extensions (edirially
3003 those of the Linux kernel -- see bug 78512) the first %p
3004 in the format string disables any further processing. */
3005 return false;
3007 case 'n':
3008 /* %n has side-effects even when nothing is actually printed to
3009 any buffer. */
3010 info.nowrite = false;
3011 dir.fmtfunc = format_none;
3012 break;
3014 case 'c':
3015 dir.fmtfunc = format_character;
3016 break;
3018 case 'S':
3019 case 's':
3020 dir.fmtfunc = format_string;
3021 break;
3023 default:
3024 /* Unknown conversion specification. */
3025 return 0;
3028 dir.specifier = *pf++;
3030 if (star_width)
3032 if (TREE_CODE (TREE_TYPE (star_width)) == INTEGER_TYPE)
3033 dir.set_width (star_width);
3034 else
3036 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3037 (width is the absolute value of that specified). */
3038 dir.width[0] = 0;
3039 dir.width[1] = target_int_max () + 1;
3042 else
3043 dir.set_width (width);
3045 if (star_precision)
3047 if (TREE_CODE (TREE_TYPE (star_precision)) == INTEGER_TYPE)
3048 dir.set_precision (star_precision);
3049 else
3051 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3052 (unlike width, negative precision is ignored). */
3053 dir.prec[0] = -1;
3054 dir.prec[1] = target_int_max ();
3057 else
3058 dir.set_precision (precision);
3060 /* Extract the argument if the directive takes one and if it's
3061 available (e.g., the function doesn't take a va_list). Treat
3062 missing arguments the same as va_list, even though they will
3063 have likely already been diagnosed by -Wformat. */
3064 if (dir.specifier != '%'
3065 && *argno < gimple_call_num_args (info.callstmt))
3066 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3068 /* Return the length of the format directive. */
3069 dir.len = pf - pcnt;
3071 if (dump_file)
3073 fprintf (dump_file, " Directive %u at offset %llu: \"%.*s\"",
3074 dir.dirno, (unsigned long long)(size_t)(dir.beg - info.fmtstr),
3075 (int)dir.len, dir.beg);
3076 if (star_width)
3078 if (dir.width[0] == dir.width[1])
3079 fprintf (dump_file, ", width = %lli", (long long)dir.width[0]);
3080 else
3081 fprintf (dump_file, ", width in range [%lli, %lli]",
3082 (long long)dir.width[0], (long long)dir.width[1]);
3085 if (star_precision)
3087 if (dir.prec[0] == dir.prec[1])
3088 fprintf (dump_file, ", precision = %lli", (long long)dir.prec[0]);
3089 else
3090 fprintf (dump_file, ", precision in range [%lli, %lli]",
3091 (long long)dir.prec[0], (long long)dir.prec[1]);
3093 fputc ('\n', dump_file);
3096 return dir.len;
3099 /* Compute the length of the output resulting from the call to a formatted
3100 output function described by INFO and store the result of the call in
3101 *RES. Issue warnings for detected past the end writes. Return true
3102 if the complete format string has been processed and *RES can be relied
3103 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3104 that caused the processing to be terminated early). */
3106 bool
3107 pass_sprintf_length::compute_format_length (call_info &info,
3108 format_result *res)
3110 if (dump_file)
3112 location_t callloc = gimple_location (info.callstmt);
3113 fprintf (dump_file, "%s:%i: ",
3114 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3115 print_generic_expr (dump_file, info.func, dump_flags);
3117 fprintf (dump_file, ": objsize = %llu, fmtstr = \"%s\"\n",
3118 (unsigned long long)info.objsize, info.fmtstr);
3121 /* Reset the minimum and maximum byte counters. */
3122 res->range.min = res->range.max = 0;
3124 /* No directive has been seen yet so the length of output is bounded
3125 by the known range [0, 0] (with no conversion producing more than
3126 4K bytes) until determined otherwise. */
3127 res->knownrange = true;
3128 res->under4k = true;
3129 res->floating = false;
3130 res->warned = false;
3132 /* 1-based directive counter. */
3133 unsigned dirno = 1;
3135 /* The variadic argument counter. */
3136 unsigned argno = info.argidx;
3138 for (const char *pf = info.fmtstr; ; ++dirno)
3140 directive dir = directive ();
3141 dir.dirno = dirno;
3143 size_t n = parse_directive (info, dir, res, pf, &argno);
3145 /* Return failure if the format function fails. */
3146 if (!format_directive (info, res, dir))
3147 return false;
3149 /* Return success the directive is zero bytes long and it's
3150 the last think in the format string (i.e., it's the terminating
3151 nul, which isn't really a directive but handling it as one makes
3152 things simpler). */
3153 if (!n)
3154 return *pf == '\0';
3156 pf += n;
3159 /* The complete format string was processed (with or without warnings). */
3160 return true;
3163 /* Return the size of the object referenced by the expression DEST if
3164 available, or -1 otherwise. */
3166 static unsigned HOST_WIDE_INT
3167 get_destination_size (tree dest)
3169 /* Initialize object size info before trying to compute it. */
3170 init_object_sizes ();
3172 /* Use __builtin_object_size to determine the size of the destination
3173 object. When optimizing, determine the smallest object (such as
3174 a member array as opposed to the whole enclosing object), otherwise
3175 use type-zero object size to determine the size of the enclosing
3176 object (the function fails without optimization in this type). */
3177 int ost = optimize > 0;
3178 unsigned HOST_WIDE_INT size;
3179 if (compute_builtin_object_size (dest, ost, &size))
3180 return size;
3182 return HOST_WIDE_INT_M1U;
3185 /* Given a suitable result RES of a call to a formatted output function
3186 described by INFO, substitute the result for the return value of
3187 the call. The result is suitable if the number of bytes it represents
3188 is known and exact. A result that isn't suitable for substitution may
3189 have its range set to the range of return values, if that is known.
3190 Return true if the call is removed and gsi_next should not be performed
3191 in the caller. */
3193 static bool
3194 try_substitute_return_value (gimple_stmt_iterator *gsi,
3195 const pass_sprintf_length::call_info &info,
3196 const format_result &res)
3198 tree lhs = gimple_get_lhs (info.callstmt);
3200 /* Set to true when the entire call has been removed. */
3201 bool removed = false;
3203 /* The minimum return value. */
3204 unsigned HOST_WIDE_INT minretval = res.range.min;
3206 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3207 but in cases involving multibyte characters could be as large as
3208 RES.RANGE.UNLIKELY. */
3209 unsigned HOST_WIDE_INT maxretval
3210 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3212 /* Adjust the number of bytes which includes the terminating nul
3213 to reflect the return value of the function which does not.
3214 Because the valid range of the function is [INT_MIN, INT_MAX],
3215 a valid range before the adjustment below is [0, INT_MAX + 1]
3216 (the functions only return negative values on error or undefined
3217 behavior). */
3218 if (minretval <= target_int_max () + 1)
3219 --minretval;
3220 if (maxretval <= target_int_max () + 1)
3221 --maxretval;
3223 /* Avoid the return value optimization when the behavior of the call
3224 is undefined either because any directive may have produced 4K or
3225 more of output, or the return value exceeds INT_MAX, or because
3226 the output overflows the destination object (but leave it enabled
3227 when the function is bounded because then the behavior is well-
3228 defined). */
3229 if (res.under4k
3230 && minretval == maxretval
3231 && (info.bounded || minretval < info.objsize)
3232 && minretval <= target_int_max ()
3233 /* Not prepared to handle possibly throwing calls here; they shouldn't
3234 appear in non-artificial testcases, except when the __*_chk routines
3235 are badly declared. */
3236 && !stmt_ends_bb_p (info.callstmt))
3238 tree cst = build_int_cst (integer_type_node, minretval);
3240 if (lhs == NULL_TREE
3241 && info.nowrite)
3243 /* Remove the call to the bounded function with a zero size
3244 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3245 unlink_stmt_vdef (info.callstmt);
3246 gsi_remove (gsi, true);
3247 removed = true;
3249 else if (info.nowrite)
3251 /* Replace the call to the bounded function with a zero size
3252 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3253 of the function. */
3254 if (!update_call_from_tree (gsi, cst))
3255 gimplify_and_update_call_from_tree (gsi, cst);
3256 gimple *callstmt = gsi_stmt (*gsi);
3257 update_stmt (callstmt);
3259 else if (lhs)
3261 /* Replace the left-hand side of the call with the constant
3262 result of the formatted function. */
3263 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3264 gimple *g = gimple_build_assign (lhs, cst);
3265 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3266 update_stmt (info.callstmt);
3269 if (dump_file)
3271 if (removed)
3272 fprintf (dump_file, " Removing call statement.");
3273 else
3275 fprintf (dump_file, " Substituting ");
3276 print_generic_expr (dump_file, cst, dump_flags);
3277 fprintf (dump_file, " for %s.\n",
3278 info.nowrite ? "statement" : "return value");
3282 else if (lhs)
3284 bool setrange = false;
3286 if ((info.bounded || maxretval < info.objsize)
3287 && res.under4k
3288 && (minretval < target_int_max ()
3289 && maxretval < target_int_max ()))
3291 /* If the result is in a valid range bounded by the size of
3292 the destination set it so that it can be used for subsequent
3293 optimizations. */
3294 int prec = TYPE_PRECISION (integer_type_node);
3296 wide_int min = wi::shwi (minretval, prec);
3297 wide_int max = wi::shwi (maxretval, prec);
3298 set_range_info (lhs, VR_RANGE, min, max);
3300 setrange = true;
3303 if (dump_file)
3305 const char *inbounds
3306 = (minretval < info.objsize
3307 ? (maxretval < info.objsize
3308 ? "in" : "potentially out-of")
3309 : "out-of");
3311 const char *what = setrange ? "Setting" : "Discarding";
3312 if (minretval != maxretval)
3313 fprintf (dump_file,
3314 " %s %s-bounds return value range [%llu, %llu].\n",
3315 what, inbounds,
3316 (unsigned long long)minretval,
3317 (unsigned long long)maxretval);
3318 else
3319 fprintf (dump_file, " %s %s-bounds return value %llu.\n",
3320 what, inbounds, (unsigned long long)minretval);
3324 if (dump_file)
3325 fputc ('\n', dump_file);
3327 return removed;
3330 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3331 functions and if so, handle it. Return true if the call is removed
3332 and gsi_next should not be performed in the caller. */
3334 bool
3335 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator *gsi)
3337 call_info info = call_info ();
3339 info.callstmt = gsi_stmt (*gsi);
3340 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3341 return false;
3343 info.func = gimple_call_fndecl (info.callstmt);
3344 info.fncode = DECL_FUNCTION_CODE (info.func);
3346 /* The size of the destination as in snprintf(dest, size, ...). */
3347 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3349 /* The size of the destination determined by __builtin_object_size. */
3350 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3352 /* Buffer size argument number (snprintf and vsnprintf). */
3353 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3355 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3356 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3358 /* Format string argument number (valid for all functions). */
3359 unsigned idx_format;
3361 switch (info.fncode)
3363 case BUILT_IN_SPRINTF:
3364 // Signature:
3365 // __builtin_sprintf (dst, format, ...)
3366 idx_format = 1;
3367 info.argidx = 2;
3368 break;
3370 case BUILT_IN_SPRINTF_CHK:
3371 // Signature:
3372 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3373 idx_objsize = 2;
3374 idx_format = 3;
3375 info.argidx = 4;
3376 break;
3378 case BUILT_IN_SNPRINTF:
3379 // Signature:
3380 // __builtin_snprintf (dst, size, format, ...)
3381 idx_dstsize = 1;
3382 idx_format = 2;
3383 info.argidx = 3;
3384 info.bounded = true;
3385 break;
3387 case BUILT_IN_SNPRINTF_CHK:
3388 // Signature:
3389 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3390 idx_dstsize = 1;
3391 idx_objsize = 3;
3392 idx_format = 4;
3393 info.argidx = 5;
3394 info.bounded = true;
3395 break;
3397 case BUILT_IN_VSNPRINTF:
3398 // Signature:
3399 // __builtin_vsprintf (dst, size, format, va)
3400 idx_dstsize = 1;
3401 idx_format = 2;
3402 info.argidx = -1;
3403 info.bounded = true;
3404 break;
3406 case BUILT_IN_VSNPRINTF_CHK:
3407 // Signature:
3408 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3409 idx_dstsize = 1;
3410 idx_objsize = 3;
3411 idx_format = 4;
3412 info.argidx = -1;
3413 info.bounded = true;
3414 break;
3416 case BUILT_IN_VSPRINTF:
3417 // Signature:
3418 // __builtin_vsprintf (dst, format, va)
3419 idx_format = 1;
3420 info.argidx = -1;
3421 break;
3423 case BUILT_IN_VSPRINTF_CHK:
3424 // Signature:
3425 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3426 idx_format = 3;
3427 idx_objsize = 2;
3428 info.argidx = -1;
3429 break;
3431 default:
3432 return false;
3435 /* Set the global warning level for this function. */
3436 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3438 /* The first argument is a pointer to the destination. */
3439 tree dstptr = gimple_call_arg (info.callstmt, 0);
3441 info.format = gimple_call_arg (info.callstmt, idx_format);
3443 /* True when the destination size is constant as opposed to the lower
3444 or upper bound of a range. */
3445 bool dstsize_cst_p = true;
3447 if (idx_dstsize == HOST_WIDE_INT_M1U)
3449 /* For non-bounded functions like sprintf, determine the size
3450 of the destination from the object or pointer passed to it
3451 as the first argument. */
3452 dstsize = get_destination_size (dstptr);
3454 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3456 /* For bounded functions try to get the size argument. */
3458 if (TREE_CODE (size) == INTEGER_CST)
3460 dstsize = tree_to_uhwi (size);
3461 /* No object can be larger than SIZE_MAX bytes (half the address
3462 space) on the target.
3463 The functions are defined only for output of at most INT_MAX
3464 bytes. Specifying a bound in excess of that limit effectively
3465 defeats the bounds checking (and on some implementations such
3466 as Solaris cause the function to fail with EINVAL). */
3467 if (dstsize > target_size_max () / 2)
3469 /* Avoid warning if -Wstringop-overflow is specified since
3470 it also warns for the same thing though only for the
3471 checking built-ins. */
3472 if ((idx_objsize == HOST_WIDE_INT_M1U
3473 || !warn_stringop_overflow))
3474 warning_at (gimple_location (info.callstmt), info.warnopt (),
3475 "specified bound %wu exceeds maximum object size "
3476 "%wu",
3477 dstsize, target_size_max () / 2);
3479 else if (dstsize > target_int_max ())
3480 warning_at (gimple_location (info.callstmt), info.warnopt (),
3481 "specified bound %wu exceeds %<INT_MAX %>",
3482 dstsize);
3484 else if (TREE_CODE (size) == SSA_NAME)
3486 /* Try to determine the range of values of the argument
3487 and use the greater of the two at level 1 and the smaller
3488 of them at level 2. */
3489 wide_int min, max;
3490 enum value_range_type range_type
3491 = get_range_info (size, &min, &max);
3492 if (range_type == VR_RANGE)
3494 dstsize
3495 = (warn_level < 2
3496 ? wi::fits_uhwi_p (max) ? max.to_uhwi () : max.to_shwi ()
3497 : wi::fits_uhwi_p (min) ? min.to_uhwi () : min.to_shwi ());
3500 /* The destination size is not constant. If the function is
3501 bounded (e.g., snprintf) a lower bound of zero doesn't
3502 necessarily imply it can be eliminated. */
3503 dstsize_cst_p = false;
3507 if (idx_objsize != HOST_WIDE_INT_M1U)
3508 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3509 if (tree_fits_uhwi_p (size))
3510 objsize = tree_to_uhwi (size);
3512 if (info.bounded && !dstsize)
3514 /* As a special case, when the explicitly specified destination
3515 size argument (to a bounded function like snprintf) is zero
3516 it is a request to determine the number of bytes on output
3517 without actually producing any. Pretend the size is
3518 unlimited in this case. */
3519 info.objsize = HOST_WIDE_INT_MAX;
3520 info.nowrite = dstsize_cst_p;
3522 else
3524 /* For calls to non-bounded functions or to those of bounded
3525 functions with a non-zero size, warn if the destination
3526 pointer is null. */
3527 if (integer_zerop (dstptr))
3529 /* This is diagnosed with -Wformat only when the null is a constant
3530 pointer. The warning here diagnoses instances where the pointer
3531 is not constant. */
3532 location_t loc = gimple_location (info.callstmt);
3533 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3534 info.warnopt (), "null destination pointer");
3535 return false;
3538 /* Set the object size to the smaller of the two arguments
3539 of both have been specified and they're not equal. */
3540 info.objsize = dstsize < objsize ? dstsize : objsize;
3542 if (info.bounded
3543 && dstsize < target_size_max () / 2 && objsize < dstsize
3544 /* Avoid warning if -Wstringop-overflow is specified since
3545 it also warns for the same thing though only for the
3546 checking built-ins. */
3547 && (idx_objsize == HOST_WIDE_INT_M1U
3548 || !warn_stringop_overflow))
3550 warning_at (gimple_location (info.callstmt), info.warnopt (),
3551 "specified bound %wu exceeds the size %wu "
3552 "of the destination object", dstsize, objsize);
3556 if (integer_zerop (info.format))
3558 /* This is diagnosed with -Wformat only when the null is a constant
3559 pointer. The warning here diagnoses instances where the pointer
3560 is not constant. */
3561 location_t loc = gimple_location (info.callstmt);
3562 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3563 info.warnopt (), "null format string");
3564 return false;
3567 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3568 if (!info.fmtstr)
3569 return false;
3571 /* The result is the number of bytes output by the formatted function,
3572 including the terminating NUL. */
3573 format_result res = format_result ();
3575 bool success = compute_format_length (info, &res);
3577 /* When optimizing and the printf return value optimization is enabled,
3578 attempt to substitute the computed result for the return value of
3579 the call. Avoid this optimization when -frounding-math is in effect
3580 and the format string contains a floating point directive. */
3581 if (success
3582 && optimize > 0
3583 && flag_printf_return_value
3584 && (!flag_rounding_math || !res.floating))
3585 return try_substitute_return_value (gsi, info, res);
3587 return false;
3590 /* Execute the pass for function FUN. */
3592 unsigned int
3593 pass_sprintf_length::execute (function *fun)
3595 basic_block bb;
3596 FOR_EACH_BB_FN (bb, fun)
3598 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
3600 /* Iterate over statements, looking for function calls. */
3601 gimple *stmt = gsi_stmt (si);
3603 if (is_gimple_call (stmt) && handle_gimple_call (&si))
3604 /* If handle_gimple_call returns true, the iterator is
3605 already pointing to the next statement. */
3606 continue;
3608 gsi_next (&si);
3612 /* Clean up object size info. */
3613 fini_object_sizes ();
3615 return 0;
3618 } /* Unnamed namespace. */
3620 /* Return a pointer to a pass object newly constructed from the context
3621 CTXT. */
3623 gimple_opt_pass *
3624 make_pass_sprintf_length (gcc::context *ctxt)
3626 return new pass_sprintf_length (ctxt);