Prevent ICEs due to bogus substring locations (PR preprocessor/79210)
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob11f41741f95f38d389226590f08111f548974649
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 if (prefix && absval)
767 if (base == 8)
768 res += 1;
769 else if (base == 16)
770 res += 2;
773 return res;
776 /* Given the formatting result described by RES and NAVAIL, the number
777 of available in the destination, return the range of bytes remaining
778 in the destination. */
780 static inline result_range
781 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
783 result_range range;
785 if (HOST_WIDE_INT_MAX <= navail)
787 range.min = range.max = range.likely = range.unlikely = navail;
788 return range;
791 /* The lower bound of the available range is the available size
792 minus the maximum output size, and the upper bound is the size
793 minus the minimum. */
794 range.max = res.range.min < navail ? navail - res.range.min : 0;
796 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
798 if (res.range.max < HOST_WIDE_INT_MAX)
799 range.min = res.range.max < navail ? navail - res.range.max : 0;
800 else
801 range.min = range.likely;
803 range.unlikely = (res.range.unlikely < navail
804 ? navail - res.range.unlikely : 0);
806 return range;
809 /* Description of a call to a formatted function. */
811 struct pass_sprintf_length::call_info
813 /* Function call statement. */
814 gimple *callstmt;
816 /* Function called. */
817 tree func;
819 /* Called built-in function code. */
820 built_in_function fncode;
822 /* Format argument and format string extracted from it. */
823 tree format;
824 const char *fmtstr;
826 /* The location of the format argument. */
827 location_t fmtloc;
829 /* The destination object size for __builtin___xxx_chk functions
830 typically determined by __builtin_object_size, or -1 if unknown. */
831 unsigned HOST_WIDE_INT objsize;
833 /* Number of the first variable argument. */
834 unsigned HOST_WIDE_INT argidx;
836 /* True for functions like snprintf that specify the size of
837 the destination, false for others like sprintf that don't. */
838 bool bounded;
840 /* True for bounded functions like snprintf that specify a zero-size
841 buffer as a request to compute the size of output without actually
842 writing any. NOWRITE is cleared in response to the %n directive
843 which has side-effects similar to writing output. */
844 bool nowrite;
846 /* Return true if the called function's return value is used. */
847 bool retval_used () const
849 return gimple_get_lhs (callstmt);
852 /* Return the warning option corresponding to the called function. */
853 int warnopt () const
855 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
859 /* Return the result of formatting a no-op directive (such as '%n'). */
861 static fmtresult
862 format_none (const directive &, tree)
864 fmtresult res (0);
865 return res;
868 /* Return the result of formatting the '%%' directive. */
870 static fmtresult
871 format_percent (const directive &, tree)
873 fmtresult res (1);
874 return res;
878 /* Compute intmax_type_node and uintmax_type_node similarly to how
879 tree.c builds size_type_node. */
881 static void
882 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
884 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
886 *pintmax = integer_type_node;
887 *puintmax = unsigned_type_node;
889 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
891 *pintmax = long_integer_type_node;
892 *puintmax = long_unsigned_type_node;
894 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
896 *pintmax = long_long_integer_type_node;
897 *puintmax = long_long_unsigned_type_node;
899 else
901 for (int i = 0; i < NUM_INT_N_ENTS; i++)
902 if (int_n_enabled_p[i])
904 char name[50];
905 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
907 if (strcmp (name, UINTMAX_TYPE) == 0)
909 *pintmax = int_n_trees[i].signed_type;
910 *puintmax = int_n_trees[i].unsigned_type;
911 return;
914 gcc_unreachable ();
918 /* Determine the range [*PMIN, *PMAX] that the expression ARG of TYPE
919 is in. Return true when the range is a subrange of that of TYPE.
920 Whn ARG is null it is as if it had the full range of TYPE.
921 When ABSOLUTE is true the range reflects the absolute value of
922 the argument. When ABSOLUTE is false, negative bounds of
923 the determined range are replaced with NEGBOUND. */
925 static bool
926 get_int_range (tree arg, tree type, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
927 bool absolute, HOST_WIDE_INT negbound)
929 bool knownrange = false;
931 if (!arg)
933 *pmin = (TYPE_UNSIGNED (type)
934 ? tree_to_uhwi (TYPE_MIN_VALUE (type))
935 : tree_to_shwi (TYPE_MIN_VALUE (type)));
936 *pmax = tree_to_uhwi (TYPE_MAX_VALUE (type));
938 else if (TREE_CODE (arg) == INTEGER_CST)
940 /* For a constant argument return its value adjusted as specified
941 by NEGATIVE and NEGBOUND and return true to indicate that the
942 result is known. */
943 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
944 *pmax = *pmin;
945 knownrange = true;
947 else
949 /* True if the argument's range cannot be determined. */
950 bool unknown = true;
952 type = TREE_TYPE (arg);
954 if (TREE_CODE (arg) == SSA_NAME
955 && TREE_CODE (type) == INTEGER_TYPE)
957 /* Try to determine the range of values of the integer argument. */
958 wide_int min, max;
959 enum value_range_type range_type = get_range_info (arg, &min, &max);
960 if (range_type == VR_RANGE)
962 HOST_WIDE_INT type_min
963 = (TYPE_UNSIGNED (type)
964 ? tree_to_uhwi (TYPE_MIN_VALUE (type))
965 : tree_to_shwi (TYPE_MIN_VALUE (type)));
967 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (type));
969 *pmin = min.to_shwi ();
970 *pmax = max.to_shwi ();
972 /* Return true if the adjusted range is a subrange of
973 the full range of the argument's type. */
974 knownrange = type_min < *pmin || *pmax < type_max;
976 unknown = false;
980 /* Handle an argument with an unknown range as if none had been
981 provided. */
982 if (unknown)
983 return get_int_range (NULL_TREE, type, pmin, pmax, absolute, negbound);
986 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
987 if (absolute)
989 if (*pmin < 0)
991 if (*pmin == *pmax)
992 *pmin = *pmax = -*pmin;
993 else
995 HOST_WIDE_INT tmp = -*pmin;
996 *pmin = 0;
997 if (*pmax < tmp)
998 *pmax = tmp;
1002 else if (*pmin < negbound)
1003 *pmin = negbound;
1005 return knownrange;
1008 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1009 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1010 the type of the directive's formal argument it's possible for both
1011 to result in the same number of bytes or a range of bytes that's
1012 less than the number of bytes that would result from formatting
1013 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1014 determined by checking for the actual argument being in the range
1015 of the type of the directive. If it isn't it must be assumed to
1016 take on the full range of the directive's type.
1017 Return true when the range has been adjusted to the full unsigned
1018 range of DIRTYPE, or [0, DIRTYPE_MAX], and false otherwise. */
1020 static bool
1021 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1023 tree argtype = TREE_TYPE (*argmin);
1024 unsigned argprec = TYPE_PRECISION (argtype);
1025 unsigned dirprec = TYPE_PRECISION (dirtype);
1027 /* If the actual argument and the directive's argument have the same
1028 precision and sign there can be no overflow and so there is nothing
1029 to adjust. */
1030 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1031 return false;
1033 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1034 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1036 if (TREE_CODE (*argmin) == INTEGER_CST
1037 && TREE_CODE (*argmax) == INTEGER_CST
1038 && (dirprec >= argprec
1039 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1040 int_const_binop (MINUS_EXPR,
1041 *argmax,
1042 *argmin),
1043 size_int (dirprec)))))
1045 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1046 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1048 /* If *ARGMIN is still less than *ARGMAX the conversion above
1049 is safe. Otherwise, it has overflowed and would be unsafe. */
1050 if (tree_int_cst_le (*argmin, *argmax))
1051 return false;
1054 tree dirmin = TYPE_MIN_VALUE (dirtype);
1055 tree dirmax = TYPE_MAX_VALUE (dirtype);
1057 if (TYPE_UNSIGNED (dirtype))
1059 *argmin = dirmin;
1060 *argmax = dirmax;
1062 else
1064 *argmin = integer_zero_node;
1065 *argmax = dirmin;
1068 return true;
1071 /* Return a range representing the minimum and maximum number of bytes
1072 that the format directive DIR will output for any argument given
1073 the WIDTH and PRECISION (extracted from DIR). This function is
1074 used when the directive argument or its value isn't known. */
1076 static fmtresult
1077 format_integer (const directive &dir, tree arg)
1079 tree intmax_type_node;
1080 tree uintmax_type_node;
1082 /* Base to format the number in. */
1083 int base;
1085 /* True when a conversion is preceded by a prefix indicating the base
1086 of the argument (octal or hexadecimal). */
1087 bool maybebase = dir.get_flag ('#');
1089 /* True when a signed conversion is preceded by a sign or space. */
1090 bool maybesign = false;
1092 /* True for signed conversions (i.e., 'd' and 'i'). */
1093 bool sign = false;
1095 switch (dir.specifier)
1097 case 'd':
1098 case 'i':
1099 /* Space and '+' are only meaningful for signed conversions. */
1100 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1101 sign = true;
1102 base = 10;
1103 break;
1104 case 'u':
1105 base = 10;
1106 break;
1107 case 'o':
1108 base = 8;
1109 break;
1110 case 'X':
1111 case 'x':
1112 base = 16;
1113 break;
1114 default:
1115 gcc_unreachable ();
1118 /* The type of the "formal" argument expected by the directive. */
1119 tree dirtype = NULL_TREE;
1121 /* Determine the expected type of the argument from the length
1122 modifier. */
1123 switch (dir.modifier)
1125 case FMT_LEN_none:
1126 if (dir.specifier == 'p')
1127 dirtype = ptr_type_node;
1128 else
1129 dirtype = sign ? integer_type_node : unsigned_type_node;
1130 break;
1132 case FMT_LEN_h:
1133 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1134 break;
1136 case FMT_LEN_hh:
1137 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1138 break;
1140 case FMT_LEN_l:
1141 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1142 break;
1144 case FMT_LEN_L:
1145 case FMT_LEN_ll:
1146 dirtype = (sign
1147 ? long_long_integer_type_node
1148 : long_long_unsigned_type_node);
1149 break;
1151 case FMT_LEN_z:
1152 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1153 break;
1155 case FMT_LEN_t:
1156 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1157 break;
1159 case FMT_LEN_j:
1160 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1161 dirtype = sign ? intmax_type_node : uintmax_type_node;
1162 break;
1164 default:
1165 return fmtresult ();
1168 /* The type of the argument to the directive, either deduced from
1169 the actual non-constant argument if one is known, or from
1170 the directive itself when none has been provided because it's
1171 a va_list. */
1172 tree argtype = NULL_TREE;
1174 if (!arg)
1176 /* When the argument has not been provided, use the type of
1177 the directive's argument as an approximation. This will
1178 result in false positives for directives like %i with
1179 arguments with smaller precision (such as short or char). */
1180 argtype = dirtype;
1182 else if (TREE_CODE (arg) == INTEGER_CST)
1184 /* When a constant argument has been provided use its value
1185 rather than type to determine the length of the output. */
1186 fmtresult res;
1188 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1190 /* As a special case, a precision of zero with a zero argument
1191 results in zero bytes except in base 8 when the '#' flag is
1192 specified, and for signed conversions in base 8 and 10 when
1193 flags when either the space or '+' flag has been specified
1194 when it results in just one byte (with width having the normal
1195 effect). This must extend to the case of a specified precision
1196 with an unknown value because it can be zero. */
1197 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1198 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1200 res.range.max = 1;
1201 res.range.likely = 1;
1203 else
1205 res.range.max = res.range.min;
1206 res.range.likely = res.range.min;
1209 else
1211 /* Convert the argument to the type of the directive. */
1212 arg = fold_convert (dirtype, arg);
1214 res.range.min = tree_digits (arg, base, dir.prec[0],
1215 maybesign, maybebase);
1216 if (dir.prec[0] == dir.prec[1])
1217 res.range.max = res.range.min;
1218 else
1219 res.range.max = tree_digits (arg, base, dir.prec[1],
1220 maybesign, maybebase);
1221 res.range.likely = res.range.min;
1224 res.range.unlikely = res.range.max;
1226 /* Bump up the counters if WIDTH is greater than LEN. */
1227 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1228 (sign | maybebase) + (base == 16));
1229 /* Bump up the counters again if PRECision is greater still. */
1230 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1231 (sign | maybebase) + (base == 16));
1233 return res;
1235 else if (TREE_CODE (TREE_TYPE (arg)) == INTEGER_TYPE
1236 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1237 /* Determine the type of the provided non-constant argument. */
1238 argtype = TREE_TYPE (arg);
1239 else
1240 /* Don't bother with invalid arguments since they likely would
1241 have already been diagnosed, and disable any further checking
1242 of the format string by returning [-1, -1]. */
1243 return fmtresult ();
1245 fmtresult res;
1247 /* Using either the range the non-constant argument is in, or its
1248 type (either "formal" or actual), create a range of values that
1249 constrain the length of output given the warning level. */
1250 tree argmin = NULL_TREE;
1251 tree argmax = NULL_TREE;
1253 if (arg
1254 && TREE_CODE (arg) == SSA_NAME
1255 && TREE_CODE (argtype) == INTEGER_TYPE)
1257 /* Try to determine the range of values of the integer argument
1258 (range information is not available for pointers). */
1259 wide_int min, max;
1260 enum value_range_type range_type = get_range_info (arg, &min, &max);
1261 if (range_type == VR_RANGE)
1263 argmin = build_int_cst (argtype, wi::fits_uhwi_p (min)
1264 ? min.to_uhwi () : min.to_shwi ());
1265 argmax = build_int_cst (argtype, wi::fits_uhwi_p (max)
1266 ? max.to_uhwi () : max.to_shwi ());
1268 /* Set KNOWNRANGE if the argument is in a known subrange
1269 of the directive's type (KNOWNRANGE may be reset below). */
1270 res.knownrange
1271 = (!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1272 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax));
1274 res.argmin = argmin;
1275 res.argmax = argmax;
1277 else if (range_type == VR_ANTI_RANGE)
1279 /* Handle anti-ranges if/when bug 71690 is resolved. */
1281 else if (range_type == VR_VARYING)
1283 /* The argument here may be the result of promoting the actual
1284 argument to int. Try to determine the type of the actual
1285 argument before promotion and narrow down its range that
1286 way. */
1287 gimple *def = SSA_NAME_DEF_STMT (arg);
1288 if (is_gimple_assign (def))
1290 tree_code code = gimple_assign_rhs_code (def);
1291 if (code == INTEGER_CST)
1293 arg = gimple_assign_rhs1 (def);
1294 return format_integer (dir, arg);
1297 if (code == NOP_EXPR)
1299 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1300 if (TREE_CODE (type) == INTEGER_TYPE
1301 || TREE_CODE (type) == POINTER_TYPE)
1302 argtype = type;
1308 if (!argmin)
1310 /* For an unknown argument (e.g., one passed to a vararg function)
1311 or one whose value range cannot be determined, create a T_MIN
1312 constant if the argument's type is signed and T_MAX otherwise,
1313 and use those to compute the range of bytes that the directive
1314 can output. When precision may be zero, use zero as the minimum
1315 since it results in no bytes on output (unless width is specified
1316 to be greater than 0). */
1317 bool zero = dir.prec[0] <= 0 && dir.prec[1] >= 0;
1318 argmin = build_int_cst (argtype, !zero);
1320 int typeprec = TYPE_PRECISION (dirtype);
1321 int argprec = TYPE_PRECISION (argtype);
1323 if (argprec < typeprec)
1325 if (POINTER_TYPE_P (argtype))
1326 argmax = build_all_ones_cst (argtype);
1327 else if (TYPE_UNSIGNED (argtype))
1328 argmax = TYPE_MAX_VALUE (argtype);
1329 else
1330 argmax = TYPE_MIN_VALUE (argtype);
1332 else
1334 if (POINTER_TYPE_P (dirtype))
1335 argmax = build_all_ones_cst (dirtype);
1336 else if (TYPE_UNSIGNED (dirtype))
1337 argmax = TYPE_MAX_VALUE (dirtype);
1338 else
1339 argmax = TYPE_MIN_VALUE (dirtype);
1342 res.argmin = argmin;
1343 res.argmax = argmax;
1346 if (tree_int_cst_lt (argmax, argmin))
1348 tree tmp = argmax;
1349 argmax = argmin;
1350 argmin = tmp;
1353 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1354 of the directive. If it has been cleared then since ARGMIN and/or
1355 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1356 ARGMAX in the result to include in diagnostics. */
1357 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1359 res.knownrange = false;
1360 res.argmin = argmin;
1361 res.argmax = argmax;
1364 /* Recursively compute the minimum and maximum from the known range,
1365 taking care to swap them if the lower bound results in longer
1366 output than the upper bound (e.g., in the range [-1, 0]. */
1368 if (TYPE_UNSIGNED (dirtype))
1370 /* For unsigned conversions/directives, use the minimum (i.e., 0
1371 or 1) and maximum to compute the shortest and longest output,
1372 respectively. */
1373 res.range.min = format_integer (dir, argmin).range.min;
1374 res.range.max = format_integer (dir, argmax).range.max;
1376 else
1378 /* For signed conversions/directives, use the maximum (i.e., 0)
1379 to compute the shortest output and the minimum (i.e., TYPE_MIN)
1380 to compute the longest output. This is important when precision
1381 is specified but unknown because otherwise both output lengths
1382 would reflect the largest possible precision (i.e., INT_MAX). */
1383 res.range.min = format_integer (dir, argmax).range.min;
1384 res.range.max = format_integer (dir, argmin).range.max;
1387 if (res.range.max < res.range.min)
1389 unsigned HOST_WIDE_INT tmp = res.range.max;
1390 res.range.max = res.range.min;
1391 res.range.min = tmp;
1394 res.range.likely = res.knownrange ? res.range.max : res.range.min;
1395 res.range.unlikely = res.range.max;
1396 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1397 (sign | maybebase) + (base == 16));
1398 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1399 (sign | maybebase) + (base == 16));
1401 return res;
1404 /* Return the number of bytes that a format directive consisting of FLAGS,
1405 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1406 would result for argument X under ideal conditions (i.e., if PREC
1407 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1408 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1409 This function works around those problems. */
1411 static unsigned HOST_WIDE_INT
1412 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1413 char spec, char rndspec)
1415 char fmtstr[40];
1417 HOST_WIDE_INT len = strlen (flags);
1419 fmtstr[0] = '%';
1420 memcpy (fmtstr + 1, flags, len);
1421 memcpy (fmtstr + 1 + len, ".*R", 3);
1422 fmtstr[len + 4] = rndspec;
1423 fmtstr[len + 5] = spec;
1424 fmtstr[len + 6] = '\0';
1426 spec = TOUPPER (spec);
1427 if (spec == 'E' || spec == 'F')
1429 /* For %e, specify the precision explicitly since mpfr_sprintf
1430 does its own thing just to be different (see MPFR bug 21088). */
1431 if (prec < 0)
1432 prec = 6;
1434 else
1436 /* Avoid passing negative precisions with larger magnitude to MPFR
1437 to avoid exposing its bugs. (A negative precision is supposed
1438 to be ignored.) */
1439 if (prec < 0)
1440 prec = -1;
1443 HOST_WIDE_INT p = prec;
1445 if (spec == 'G')
1447 /* For G/g, precision gives the maximum number of significant
1448 digits which is bounded by LDBL_MAX_10_EXP, or, for a 128
1449 bit IEEE extended precision, 4932. Using twice as much
1450 here should be more than sufficient for any real format. */
1451 if ((IEEE_MAX_10_EXP * 2) < prec)
1452 prec = IEEE_MAX_10_EXP * 2;
1453 p = prec;
1455 else
1457 /* Cap precision arbitrarily at 1KB and add the difference
1458 (if any) to the MPFR result. */
1459 if (prec > 1024)
1460 p = 1024;
1463 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1465 /* Handle the unlikely (impossible?) error by returning more than
1466 the maximum dictated by the function's return type. */
1467 if (len < 0)
1468 return target_dir_max () + 1;
1470 /* Adjust the return value by the difference. */
1471 if (p < prec)
1472 len += prec - p;
1474 return len;
1477 /* Return the number of bytes to format using the format specifier
1478 SPEC and the precision PREC the largest value in the real floating
1479 TYPE. */
1481 static unsigned HOST_WIDE_INT
1482 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1484 machine_mode mode = TYPE_MODE (type);
1486 /* IBM Extended mode. */
1487 if (MODE_COMPOSITE_P (mode))
1488 mode = DFmode;
1490 /* Get the real type format desription for the target. */
1491 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1492 REAL_VALUE_TYPE rv;
1494 real_maxval (&rv, 0, mode);
1496 /* Convert the GCC real value representation with the precision
1497 of the real type to the mpfr_t format with the GCC default
1498 round-to-nearest mode. */
1499 mpfr_t x;
1500 mpfr_init2 (x, rfmt->p);
1501 mpfr_from_real (x, &rv, GMP_RNDN);
1503 /* Return a value one greater to account for the leading minus sign. */
1504 return 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1507 /* Return a range representing the minimum and maximum number of bytes
1508 that the directive DIR will output for any argument. This function
1509 is used when the directive argument or its value isn't known. */
1511 static fmtresult
1512 format_floating (const directive &dir)
1514 tree type;
1516 switch (dir.modifier)
1518 case FMT_LEN_l:
1519 case FMT_LEN_none:
1520 type = double_type_node;
1521 break;
1523 case FMT_LEN_L:
1524 type = long_double_type_node;
1525 break;
1527 case FMT_LEN_ll:
1528 type = long_double_type_node;
1529 break;
1531 default:
1532 return fmtresult ();
1535 /* The minimum and maximum number of bytes produced by the directive. */
1536 fmtresult res;
1538 /* The minimum output as determined by flags. It's always at least 1.
1539 When plus or space are set the output is preceded by either a sign
1540 or a space. */
1541 int flagmin = (1 /* for the first digit */
1542 + (dir.get_flag ('+') | dir.get_flag (' ')));
1544 /* When the pound flag is set the decimal point is included in output
1545 regardless of precision. Whether or not a decimal point is included
1546 otherwise depends on the specification and precision. */
1547 bool radix = dir.get_flag ('#');
1549 switch (dir.specifier)
1551 case 'A':
1552 case 'a':
1554 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1555 if (dir.prec[0] <= 0)
1556 minprec = 0;
1557 else if (dir.prec[0] > 0)
1558 minprec = dir.prec[0] + !radix /* decimal point */;
1560 res.range.min = (2 /* 0x */
1561 + flagmin
1562 + radix
1563 + minprec
1564 + 3 /* p+0 */);
1566 res.range.max = format_floating_max (type, 'a', dir.prec[1]);
1567 res.range.likely = res.range.min;
1569 /* The unlikely maximum accounts for the longest multibyte
1570 decimal point character. */
1571 res.range.unlikely = res.range.max;
1572 if (dir.prec[0] != dir.prec[1]
1573 || dir.prec[0] == -1 || dir.prec[0] > 0)
1574 res.range.unlikely += target_mb_len_max () - 1;
1576 break;
1579 case 'E':
1580 case 'e':
1582 /* The minimum output is "[-+]1.234567e+00" regardless
1583 of the value of the actual argument. */
1584 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1585 if ((dir.prec[0] < 0 && dir.prec[1] > -1) || dir.prec[0] == 0)
1586 minprec = 0;
1587 else if (dir.prec[0] > 0)
1588 minprec = dir.prec[0] + !radix /* decimal point */;
1590 res.range.min = (flagmin
1591 + radix
1592 + minprec
1593 + 2 /* e+ */ + 2);
1594 /* MPFR uses a precision of 16 by default for some reason.
1595 Set it to the C default of 6. */
1596 int maxprec = dir.prec[1] < 0 ? 6 : dir.prec[1];
1597 res.range.max = format_floating_max (type, 'e', maxprec);
1599 res.range.likely = res.range.min;
1601 /* The unlikely maximum accounts for the longest multibyte
1602 decimal point character. */
1603 if (dir.prec[0] != dir.prec[1]
1604 || dir.prec[0] == -1 || dir.prec[0] > 0)
1605 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1606 else
1607 res.range.unlikely = res.range.max;
1608 break;
1611 case 'F':
1612 case 'f':
1614 /* The lower bound when precision isn't specified is 8 bytes
1615 ("1.23456" since precision is taken to be 6). When precision
1616 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1617 when precision is greater than zero, then the lower bound
1618 is 2 plus precision (plus flags). */
1619 HOST_WIDE_INT minprec = 0;
1620 if (dir.prec[0] < 0)
1621 minprec = dir.prec[1] < 0 ? 6 + !radix /* decimal point */ : 0;
1622 else if (dir.prec[0])
1623 minprec = dir.prec[0] + !radix /* decimal point */;
1625 res.range.min = flagmin + radix + minprec;
1627 /* Compute the upper bound for -TYPE_MAX. */
1628 res.range.max = format_floating_max (type, 'f', dir.prec[1]);
1630 res.range.likely = res.range.min;
1632 /* The unlikely maximum accounts for the longest multibyte
1633 decimal point character. */
1634 if (dir.prec[0] != dir.prec[1]
1635 || dir.prec[0] == -1 || dir.prec[0] > 0)
1636 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1637 break;
1640 case 'G':
1641 case 'g':
1643 /* The %g output depends on precision and the exponent of
1644 the argument. Since the value of the argument isn't known
1645 the lower bound on the range of bytes (not counting flags
1646 or width) is 1. */
1647 res.range.min = flagmin;
1648 res.range.max = format_floating_max (type, 'g', dir.prec[1]);
1649 res.range.likely = res.range.max;
1651 /* The unlikely maximum accounts for the longest multibyte
1652 decimal point character. */
1653 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1654 break;
1657 default:
1658 return fmtresult ();
1661 /* Bump up the byte counters if WIDTH is greater. */
1662 res.adjust_for_width_or_precision (dir.width);
1663 return res;
1666 /* Return a range representing the minimum and maximum number of bytes
1667 that the directive DIR will write on output for the floating argument
1668 ARG. */
1670 static fmtresult
1671 format_floating (const directive &dir, tree arg)
1673 if (!arg || TREE_CODE (arg) != REAL_CST)
1674 return format_floating (dir);
1676 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1678 if (TOUPPER (dir.specifier) == 'A')
1680 /* For %a, leave the minimum precision unspecified to let
1681 MFPR trim trailing zeros (as it and many other systems
1682 including Glibc happen to do) and set the maximum
1683 precision to reflect what it would be with trailing zeros
1684 present (as Solaris and derived systems do). */
1685 if (prec[0] < 0)
1686 prec[0] = -1;
1687 if (prec[1] < 0)
1689 unsigned fmtprec
1690 = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)))->p;
1692 /* The precision of the IEEE 754 double format is 53.
1693 The precision of all other GCC binary double formats
1694 is 56 or less. */
1695 prec[1] = fmtprec <= 56 ? 13 : 15;
1699 /* The minimum and maximum number of bytes produced by the directive. */
1700 fmtresult res;
1702 /* Get the real type format desription for the target. */
1703 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1704 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1706 char fmtstr [40];
1707 char *pfmt = fmtstr;
1709 /* Append flags. */
1710 for (const char *pf = "-+ #0"; *pf; ++pf)
1711 if (dir.get_flag (*pf))
1712 *pfmt++ = *pf;
1714 *pfmt = '\0';
1717 /* Set up an array to easily iterate over. */
1718 unsigned HOST_WIDE_INT* const minmax[] = {
1719 &res.range.min, &res.range.max
1722 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1724 /* Convert the GCC real value representation with the precision
1725 of the real type to the mpfr_t format rounding down in the
1726 first iteration that computes the minimm and up in the second
1727 that computes the maximum. This order is arbibtrary because
1728 rounding in either direction can result in longer output. */
1729 mpfr_t mpfrval;
1730 mpfr_init2 (mpfrval, rfmt->p);
1731 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1733 /* Use the MPFR rounding specifier to round down in the first
1734 iteration and then up. In most but not all cases this will
1735 result in the same number of bytes. */
1736 char rndspec = "DU"[i];
1738 /* Format it and store the result in the corresponding member
1739 of the result struct. */
1740 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1741 dir.specifier, rndspec);
1745 /* Make sure the minimum is less than the maximum (MPFR rounding
1746 in the call to mpfr_snprintf can result in the reverse. */
1747 if (res.range.max < res.range.min)
1749 unsigned HOST_WIDE_INT tmp = res.range.min;
1750 res.range.min = res.range.max;
1751 res.range.max = tmp;
1754 res.knownrange = true;
1756 /* For the same floating point constant use the longer output
1757 as the likely maximum since with round to nearest either is
1758 equally likely. */
1759 res.range.likely = res.range.max;
1760 res.range.unlikely = res.range.max;
1762 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
1764 /* Unless the precision is zero output longer than 2 bytes may
1765 include the decimal point which must be a single character
1766 up to MB_LEN_MAX in length. This is overly conservative
1767 since in some conversions some constants result in no decimal
1768 point (e.g., in %g). */
1769 res.range.unlikely += target_mb_len_max () - 1;
1772 res.adjust_for_width_or_precision (dir.width);
1773 return res;
1776 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1777 strings referenced by the expression STR, or (-1, -1) when not known.
1778 Used by the format_string function below. */
1780 static fmtresult
1781 get_string_length (tree str)
1783 if (!str)
1784 return fmtresult ();
1786 if (tree slen = c_strlen (str, 1))
1788 /* Simply return the length of the string. */
1789 fmtresult res (tree_to_shwi (slen));
1790 return res;
1793 /* Determine the length of the shortest and longest string referenced
1794 by STR. Strings of unknown lengths are bounded by the sizes of
1795 arrays that subexpressions of STR may refer to. Pointers that
1796 aren't known to point any such arrays result in LENRANGE[1] set
1797 to SIZE_MAX. */
1798 tree lenrange[2];
1799 get_range_strlen (str, lenrange);
1801 if (lenrange [0] || lenrange [1])
1803 HOST_WIDE_INT min
1804 = (tree_fits_uhwi_p (lenrange[0])
1805 ? tree_to_uhwi (lenrange[0])
1806 : 0);
1808 HOST_WIDE_INT max
1809 = (tree_fits_uhwi_p (lenrange[1])
1810 ? tree_to_uhwi (lenrange[1])
1811 : HOST_WIDE_INT_M1U);
1813 /* get_range_strlen() returns the target value of SIZE_MAX for
1814 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
1815 which may be bigger. */
1816 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
1817 min = HOST_WIDE_INT_M1U;
1818 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
1819 max = HOST_WIDE_INT_M1U;
1821 fmtresult res (min, max);
1823 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
1824 by STR are known to be bounded (though not necessarily by their
1825 actual length but perhaps by their maximum possible length). */
1826 if (res.range.max < target_int_max ())
1828 res.knownrange = true;
1829 /* When the the length of the longest string is known and not
1830 excessive use it as the likely length of the string(s). */
1831 res.range.likely = res.range.max;
1833 else
1835 /* When the upper bound is unknown (as assumed to be excessive)
1836 set the likely length to the greater of 1 and the length of
1837 the shortest string. */
1838 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
1841 res.range.unlikely = res.range.max;
1843 return res;
1846 return get_string_length (NULL_TREE);
1849 /* Return the minimum and maximum number of characters formatted
1850 by the '%c' format directives and its wide character form for
1851 the argument ARG. ARG can be null (for functions such as
1852 vsprinf). */
1854 static fmtresult
1855 format_character (const directive &dir, tree arg)
1857 fmtresult res;
1859 res.knownrange = true;
1861 if (dir.modifier == FMT_LEN_l)
1863 /* A wide character can result in as few as zero bytes. */
1864 res.range.min = 0;
1866 HOST_WIDE_INT min, max;
1867 if (get_int_range (arg, integer_type_node, &min, &max, false, 0))
1869 if (min == 0 && max == 0)
1871 /* The NUL wide character results in no bytes. */
1872 res.range.max = 0;
1873 res.range.likely = 0;
1874 res.range.unlikely = 0;
1876 else if (min > 0 && min < 128)
1878 /* A wide character in the ASCII range most likely results
1879 in a single byte, and only unlikely in up to MB_LEN_MAX. */
1880 res.range.max = 1;
1881 res.range.likely = 1;
1882 res.range.unlikely = target_mb_len_max ();
1884 else
1886 /* A wide character outside the ASCII range likely results
1887 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
1888 res.range.max = target_mb_len_max ();
1889 res.range.likely = 2;
1890 res.range.unlikely = res.range.max;
1893 else
1895 /* An unknown wide character is treated the same as a wide
1896 character outside the ASCII range. */
1897 res.range.max = target_mb_len_max ();
1898 res.range.likely = 2;
1899 res.range.unlikely = res.range.max;
1902 else
1904 /* A plain '%c' directive. Its ouput is exactly 1. */
1905 res.range.min = res.range.max = 1;
1906 res.range.likely = res.range.unlikely = 1;
1907 res.knownrange = true;
1910 /* Bump up the byte counters if WIDTH is greater. */
1911 return res.adjust_for_width_or_precision (dir.width);
1914 /* Return the minimum and maximum number of characters formatted
1915 by the '%s' format directive and its wide character form for
1916 the argument ARG. ARG can be null (for functions such as
1917 vsprinf). */
1919 static fmtresult
1920 format_string (const directive &dir, tree arg)
1922 fmtresult res;
1924 /* Compute the range the argument's length can be in. */
1925 fmtresult slen = get_string_length (arg);
1926 if (slen.range.min == slen.range.max
1927 && slen.range.min < HOST_WIDE_INT_MAX)
1929 /* The argument is either a string constant or it refers
1930 to one of a number of strings of the same length. */
1932 /* A '%s' directive with a string argument with constant length. */
1933 res.range = slen.range;
1935 if (dir.modifier == FMT_LEN_l)
1937 /* In the worst case the length of output of a wide string S
1938 is bounded by MB_LEN_MAX * wcslen (S). */
1939 res.range.max *= target_mb_len_max ();
1940 res.range.unlikely = res.range.max;
1941 /* It's likely that the the total length is not more that
1942 2 * wcslen (S).*/
1943 res.range.likely = res.range.min * 2;
1945 if (dir.prec[1] >= 0
1946 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
1948 res.range.max = dir.prec[1];
1949 res.range.likely = dir.prec[1];
1950 res.range.unlikely = dir.prec[1];
1953 if (dir.prec[0] < 0 && dir.prec[1] > -1)
1954 res.range.min = 0;
1955 else if (dir.prec[0] >= 0)
1956 res.range.likely = dir.prec[0];
1958 /* Even a non-empty wide character string need not convert into
1959 any bytes. */
1960 res.range.min = 0;
1962 else
1964 res.knownrange = true;
1966 if (dir.prec[0] < 0 && dir.prec[1] > -1)
1967 res.range.min = 0;
1968 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
1969 res.range.min = dir.prec[0];
1971 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
1973 res.range.max = dir.prec[1];
1974 res.range.likely = dir.prec[1];
1975 res.range.unlikely = dir.prec[1];
1979 else if (arg && integer_zerop (arg))
1981 /* Handle null pointer argument. */
1983 fmtresult res (0);
1984 res.nullp = true;
1985 return res;
1987 else
1989 /* For a '%s' and '%ls' directive with a non-constant string,
1990 the minimum number of characters is the greater of WIDTH
1991 and either 0 in mode 1 or the smaller of PRECISION and 1
1992 in mode 2, and the maximum is PRECISION or -1 to disable
1993 tracking. */
1995 if (dir.prec[0] >= 0)
1997 if (slen.range.min >= target_int_max ())
1998 slen.range.min = 0;
1999 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2001 slen.range.min = dir.prec[0];
2002 slen.range.likely = slen.range.min;
2005 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2006 || slen.range.max >= target_int_max ())
2008 slen.range.max = dir.prec[1];
2009 slen.range.likely = slen.range.max;
2012 else if (slen.range.min >= target_int_max ())
2014 slen.range.min = 0;
2015 slen.range.max = HOST_WIDE_INT_MAX;
2016 /* At level one strings of unknown length are assumed to be
2017 empty, while at level 1 they are assumed to be one byte
2018 long. */
2019 slen.range.likely = warn_level > 1;
2022 slen.range.unlikely = slen.range.max;
2024 res.range = slen.range;
2025 res.knownrange = slen.knownrange;
2028 /* Bump up the byte counters if WIDTH is greater. */
2029 return res.adjust_for_width_or_precision (dir.width);
2032 /* Format plain string (part of the format string itself). */
2034 static fmtresult
2035 format_plain (const directive &dir, tree)
2037 fmtresult res (dir.len);
2038 return res;
2041 /* Return true if the RESULT of a directive in a call describe by INFO
2042 should be diagnosed given the AVAILable space in the destination. */
2044 static bool
2045 should_warn_p (const pass_sprintf_length::call_info &info,
2046 const result_range &avail, const result_range &result)
2048 if (result.max <= avail.min)
2050 /* The least amount of space remaining in the destination is big
2051 enough for the longest output. */
2052 return false;
2055 if (info.bounded)
2057 if (warn_format_trunc == 1 && result.min <= avail.max
2058 && info.retval_used ())
2060 /* The likely amount of space remaining in the destination is big
2061 enough for the least output and the return value is used. */
2062 return false;
2065 if (warn_format_trunc == 1 && result.likely <= avail.likely
2066 && !info.retval_used ())
2068 /* The likely amount of space remaining in the destination is big
2069 enough for the likely output and the return value is unused. */
2070 return false;
2073 if (warn_format_trunc == 2
2074 && result.likely <= avail.min
2075 && (result.max <= avail.min
2076 || result.max > HOST_WIDE_INT_MAX))
2078 /* The minimum amount of space remaining in the destination is big
2079 enough for the longest output. */
2080 return false;
2083 else
2085 if (warn_level == 1 && result.likely <= avail.likely)
2087 /* The likely amount of space remaining in the destination is big
2088 enough for the likely output. */
2089 return false;
2092 if (warn_level == 2
2093 && result.likely <= avail.min
2094 && (result.max <= avail.min
2095 || result.max > HOST_WIDE_INT_MAX))
2097 /* The minimum amount of space remaining in the destination is big
2098 enough for the longest output. */
2099 return false;
2103 return true;
2106 /* At format string location describe by DIRLOC in a call described
2107 by INFO, issue a warning for a directive DIR whose output may be
2108 in excess of the available space AVAIL_RANGE in the destination
2109 given the formatting result FMTRES. This function does nothing
2110 except decide whether to issue a warning for a possible write
2111 past the end or truncation and, if so, format the warning.
2112 Return true if a warning has been issued. */
2114 static bool
2115 maybe_warn (substring_loc &dirloc, source_range *pargrange,
2116 const pass_sprintf_length::call_info &info,
2117 const result_range &avail_range, const result_range &res,
2118 const directive &dir)
2120 if (!should_warn_p (info, avail_range, res))
2121 return false;
2123 /* A warning will definitely be issued below. */
2125 /* The maximum byte count to reference in the warning. Larger counts
2126 imply that the upper bound is unknown (and could be anywhere between
2127 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2128 than "between N and X" where X is some huge number. */
2129 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2131 /* True when there is enough room in the destination for the least
2132 amount of a directive's output but not enough for its likely or
2133 maximum output. */
2134 bool maybe = (res.min <= avail_range.max
2135 && (avail_range.min < res.likely
2136 || (res.max < HOST_WIDE_INT_MAX
2137 && avail_range.min < res.max)));
2139 if (avail_range.min == avail_range.max)
2141 /* The size of the destination region is exact. */
2142 unsigned HOST_WIDE_INT navail = avail_range.max;
2144 if (*dir.beg != '%')
2146 /* For plain character directives (i.e., the format string itself)
2147 but not others, point the caret at the first character that's
2148 past the end of the destination. */
2149 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2152 if (*dir.beg == '\0')
2154 /* This is the terminating nul. */
2155 gcc_assert (res.min == 1 && res.min == res.max);
2157 const char *fmtstr
2158 = (info.bounded
2159 ? (maybe
2160 ? G_("%qE output may be truncated before the last format "
2161 "character")
2162 : G_("%qE output truncated before the last format character"))
2163 : (maybe
2164 ? G_("%qE may write a terminating nul past the end "
2165 "of the destination")
2166 : G_("%qE writing a terminating nul past the end "
2167 "of the destination")));
2169 return fmtwarn (dirloc, NULL, NULL, info.warnopt (), fmtstr,
2170 info.func);
2173 if (res.min == res.max)
2175 const char* fmtstr
2176 = (res.min == 1
2177 ? (info.bounded
2178 ? (maybe
2179 ? G_("%<%.*s%> directive output may be truncated writing "
2180 "%wu byte into a region of size %wu")
2181 : G_("%<%.*s%> directive output truncated writing "
2182 "%wu byte into a region of size %wu"))
2183 : G_("%<%.*s%> directive writing %wu byte "
2184 "into a region of size %wu"))
2185 : (info.bounded
2186 ? (maybe
2187 ? G_("%<%.*s%> directive output may be truncated writing "
2188 "%wu bytes into a region of size %wu")
2189 : G_("%<%.*s%> directive output truncated writing "
2190 "%wu bytes into a region of size %wu"))
2191 : G_("%<%.*s%> directive writing %wu bytes "
2192 "into a region of size %wu")));
2193 return fmtwarn (dirloc, pargrange, NULL,
2194 info.warnopt (), fmtstr,
2195 dir.len, dir.beg, res.min,
2196 navail);
2199 if (res.min == 0 && res.max < maxbytes)
2201 const char* fmtstr
2202 = (info.bounded
2203 ? (maybe
2204 ? G_("%<%.*s%> directive output may be truncated writing "
2205 "up to %wu bytes into a region of size %wu")
2206 : G_("%<%.*s%> directive output truncated writing "
2207 "up to %wu bytes into a region of size %wu"))
2208 : G_("%<%.*s%> directive writing up to %wu bytes "
2209 "into a region of size %wu"));
2210 return fmtwarn (dirloc, pargrange, NULL,
2211 info.warnopt (), fmtstr,
2212 dir.len, dir.beg,
2213 res.max, navail);
2216 if (res.min == 0 && maxbytes <= res.max)
2218 /* This is a special case to avoid issuing the potentially
2219 confusing warning:
2220 writing 0 or more bytes into a region of size 0. */
2221 const char* fmtstr
2222 = (info.bounded
2223 ? (maybe
2224 ? G_("%<%.*s%> directive output may be truncated writing "
2225 "likely %wu or more bytes into a region of size %wu")
2226 : G_("%<%.*s%> directive output truncated writing "
2227 "likely %wu or more bytes into a region of size %wu"))
2228 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2229 "into a region of size %wu"));
2230 return fmtwarn (dirloc, pargrange, NULL,
2231 info.warnopt (), fmtstr,
2232 dir.len, dir.beg,
2233 res.likely, navail);
2236 if (res.max < maxbytes)
2238 const char* fmtstr
2239 = (info.bounded
2240 ? (maybe
2241 ? G_("%<%.*s%> directive output may be truncated writing "
2242 "between %wu and %wu bytes into a region of size %wu")
2243 : G_("%<%.*s%> directive output truncated writing "
2244 "between %wu and %wu bytes into a region of size %wu"))
2245 : G_("%<%.*s%> directive writing between %wu and "
2246 "%wu bytes into a region of size %wu"));
2247 return fmtwarn (dirloc, pargrange, NULL,
2248 info.warnopt (), fmtstr,
2249 dir.len, dir.beg,
2250 res.min, res.max,
2251 navail);
2254 const char* fmtstr
2255 = (info.bounded
2256 ? (maybe
2257 ? G_("%<%.*s%> directive output may be truncated writing "
2258 "%wu or more bytes into a region of size %wu")
2259 : G_("%<%.*s%> directive output truncated writing "
2260 "%wu or more bytes into a region of size %wu"))
2261 : G_("%<%.*s%> directive writing %wu or more bytes "
2262 "into a region of size %wu"));
2263 return fmtwarn (dirloc, pargrange, NULL,
2264 info.warnopt (), fmtstr,
2265 dir.len, dir.beg,
2266 res.min, navail);
2269 /* The size of the destination region is a range. */
2271 if (*dir.beg != '%')
2273 unsigned HOST_WIDE_INT navail = avail_range.max;
2275 /* For plain character directives (i.e., the format string itself)
2276 but not others, point the caret at the first character that's
2277 past the end of the destination. */
2278 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2281 if (*dir.beg == '\0')
2283 gcc_assert (res.min == 1 && res.min == res.max);
2285 const char *fmtstr
2286 = (info.bounded
2287 ? (maybe
2288 ? G_("%qE output may be truncated before the last format "
2289 "character")
2290 : G_("%qE output truncated before the last format character"))
2291 : (maybe
2292 ? G_("%qE may write a terminating nul past the end "
2293 "of the destination")
2294 : G_("%qE writing a terminating nul past the end "
2295 "of the destination")));
2297 return fmtwarn (dirloc, NULL, NULL, info.warnopt (), fmtstr,
2298 info.func);
2301 if (res.min == res.max)
2303 const char* fmtstr
2304 = (res.min == 1
2305 ? (info.bounded
2306 ? (maybe
2307 ? G_("%<%.*s%> directive output may be truncated writing "
2308 "%wu byte into a region of size between %wu and %wu")
2309 : G_("%<%.*s%> directive output truncated writing "
2310 "%wu byte into a region of size between %wu and %wu"))
2311 : G_("%<%.*s%> directive writing %wu byte "
2312 "into a region of size between %wu and %wu"))
2313 : (info.bounded
2314 ? (maybe
2315 ? G_("%<%.*s%> directive output may be truncated writing "
2316 "%wu bytes into a region of size between %wu and %wu")
2317 : G_("%<%.*s%> directive output truncated writing "
2318 "%wu bytes into a region of size between %wu and %wu"))
2319 : G_("%<%.*s%> directive writing %wu bytes "
2320 "into a region of size between %wu and %wu")));
2322 return fmtwarn (dirloc, pargrange, NULL,
2323 info.warnopt (), fmtstr,
2324 dir.len, dir.beg, res.min,
2325 avail_range.min, avail_range.max);
2328 if (res.min == 0 && res.max < maxbytes)
2330 const char* fmtstr
2331 = (info.bounded
2332 ? (maybe
2333 ? G_("%<%.*s%> directive output may be truncated writing "
2334 "up to %wu bytes into a region of size between "
2335 "%wu and %wu")
2336 : G_("%<%.*s%> directive output truncated writing "
2337 "up to %wu bytes into a region of size between "
2338 "%wu and %wu"))
2339 : G_("%<%.*s%> directive writing up to %wu bytes "
2340 "into a region of size between %wu and %wu"));
2341 return fmtwarn (dirloc, pargrange, NULL,
2342 info.warnopt (), fmtstr,
2343 dir.len, dir.beg, res.max,
2344 avail_range.min, avail_range.max);
2347 if (res.min == 0 && maxbytes <= res.max)
2349 /* This is a special case to avoid issuing the potentially confusing
2350 warning:
2351 writing 0 or more bytes into a region of size between 0 and N. */
2352 const char* fmtstr
2353 = (info.bounded
2354 ? (maybe
2355 ? G_("%<%.*s%> directive output may be truncated writing "
2356 "likely %wu or more bytes into a region of size between "
2357 "%wu and %wu")
2358 : G_("%<%.*s%> directive output truncated writing likely "
2359 "%wu or more bytes into a region of size between "
2360 "%wu and %wu"))
2361 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2362 "into a region of size between %wu and %wu"));
2363 return fmtwarn (dirloc, pargrange, NULL,
2364 info.warnopt (), fmtstr,
2365 dir.len, dir.beg, res.likely,
2366 avail_range.min, avail_range.max);
2369 if (res.max < maxbytes)
2371 const char* fmtstr
2372 = (info.bounded
2373 ? (maybe
2374 ? G_("%<%.*s%> directive output may be truncated writing "
2375 "between %wu and %wu bytes into a region of size "
2376 "between %wu and %wu")
2377 : G_("%<%.*s%> directive output truncated writing "
2378 "between %wu and %wu bytes into a region of size "
2379 "between %wu and %wu"))
2380 : G_("%<%.*s%> directive writing between %wu and "
2381 "%wu bytes into a region of size between %wu and %wu"));
2382 return fmtwarn (dirloc, pargrange, NULL,
2383 info.warnopt (), fmtstr,
2384 dir.len, dir.beg,
2385 res.min, res.max,
2386 avail_range.min, avail_range.max);
2389 const char* fmtstr
2390 = (info.bounded
2391 ? (maybe
2392 ? G_("%<%.*s%> directive output may be truncated writing "
2393 "%wu or more bytes into a region of size between "
2394 "%wu and %wu")
2395 : G_("%<%.*s%> directive output truncated writing "
2396 "%wu or more bytes into a region of size between "
2397 "%wu and %wu"))
2398 : G_("%<%.*s%> directive writing %wu or more bytes "
2399 "into a region of size between %wu and %wu"));
2400 return fmtwarn (dirloc, pargrange, NULL,
2401 info.warnopt (), fmtstr,
2402 dir.len, dir.beg,
2403 res.min,
2404 avail_range.min, avail_range.max);
2407 /* Compute the length of the output resulting from the directive DIR
2408 in a call described by INFO and update the overall result of the call
2409 in *RES. Return true if the directive has been handled. */
2411 static bool
2412 format_directive (const pass_sprintf_length::call_info &info,
2413 format_result *res, const directive &dir)
2415 /* Offset of the beginning of the directive from the beginning
2416 of the format string. */
2417 size_t offset = dir.beg - info.fmtstr;
2418 size_t start = offset;
2419 size_t length = offset + dir.len - !!dir.len;
2421 /* Create a location for the whole directive from the % to the format
2422 specifier. */
2423 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2424 offset, start, length);
2426 /* Also create a location range for the argument if possible.
2427 This doesn't work for integer literals or function calls. */
2428 source_range argrange;
2429 source_range *pargrange;
2430 if (dir.arg && CAN_HAVE_LOCATION_P (dir.arg))
2432 argrange = EXPR_LOCATION_RANGE (dir.arg);
2433 pargrange = &argrange;
2435 else
2436 pargrange = NULL;
2438 /* Bail when there is no function to compute the output length,
2439 or when minimum length checking has been disabled. */
2440 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2441 return false;
2443 /* Compute the range of lengths of the formatted output. */
2444 fmtresult fmtres = dir.fmtfunc (dir, dir.arg);
2446 /* Record whether the output of all directives is known to be
2447 bounded by some maximum, implying that their arguments are
2448 either known exactly or determined to be in a known range
2449 or, for strings, limited by the upper bounds of the arrays
2450 they refer to. */
2451 res->knownrange &= fmtres.knownrange;
2453 if (!fmtres.knownrange)
2455 /* Only when the range is known, check it against the host value
2456 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2457 INT_MAX precision, which is the longest possible output of any
2458 single directive). That's the largest valid byte count (though
2459 not valid call to a printf-like function because it can never
2460 return such a count). Otherwise, the range doesn't correspond
2461 to known values of the argument. */
2462 if (fmtres.range.max > target_dir_max ())
2464 /* Normalize the MAX counter to avoid having to deal with it
2465 later. The counter can be less than HOST_WIDE_INT_M1U
2466 when compiling for an ILP32 target on an LP64 host. */
2467 fmtres.range.max = HOST_WIDE_INT_M1U;
2468 /* Disable exact and maximum length checking after a failure
2469 to determine the maximum number of characters (for example
2470 for wide characters or wide character strings) but continue
2471 tracking the minimum number of characters. */
2472 res->range.max = HOST_WIDE_INT_M1U;
2475 if (fmtres.range.min > target_dir_max ())
2477 /* Disable exact length checking after a failure to determine
2478 even the minimum number of characters (it shouldn't happen
2479 except in an error) but keep tracking the minimum and maximum
2480 number of characters. */
2481 return true;
2485 int dirlen = dir.len;
2487 if (fmtres.nullp)
2489 fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
2490 "%<%.*s%> directive argument is null",
2491 dirlen, dir.beg);
2493 /* Don't bother processing the rest of the format string. */
2494 res->warned = true;
2495 res->range.min = HOST_WIDE_INT_M1U;
2496 res->range.max = HOST_WIDE_INT_M1U;
2497 return false;
2500 /* Compute the number of available bytes in the destination. There
2501 must always be at least one byte of space for the terminating
2502 NUL that's appended after the format string has been processed. */
2503 result_range avail_range = bytes_remaining (info.objsize, *res);
2505 bool warned = res->warned;
2507 if (!warned)
2508 warned = maybe_warn (dirloc, pargrange, info, avail_range,
2509 fmtres.range, dir);
2511 /* Bump up the total maximum if it isn't too big. */
2512 if (res->range.max < HOST_WIDE_INT_MAX
2513 && fmtres.range.max < HOST_WIDE_INT_MAX)
2514 res->range.max += fmtres.range.max;
2516 /* Raise the total unlikely maximum by the larger of the maximum
2517 and the unlikely maximum. It doesn't matter if the unlikely
2518 maximum overflows. */
2519 if (fmtres.range.max < fmtres.range.unlikely)
2520 res->range.unlikely += fmtres.range.unlikely;
2521 else
2522 res->range.unlikely += fmtres.range.max;
2524 res->range.min += fmtres.range.min;
2525 res->range.likely += fmtres.range.likely;
2527 /* Has the minimum directive output length exceeded the maximum
2528 of 4095 bytes required to be supported? */
2529 bool minunder4k = fmtres.range.min < 4096;
2530 bool maxunder4k = fmtres.range.max < 4096;
2531 /* Clear UNDER4K in the overall result if the maximum has exceeded
2532 the 4k (this is necessary to avoid the return valuye optimization
2533 that may not be safe in the maximum case). */
2534 if (!maxunder4k)
2535 res->under4k = false;
2537 if (!warned
2538 /* Only warn at level 2. */
2539 && 1 < warn_level
2540 && (!minunder4k
2541 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2543 /* The directive output may be longer than the maximum required
2544 to be handled by an implementation according to 7.21.6.1, p15
2545 of C11. Warn on this only at level 2 but remember this and
2546 prevent folding the return value when done. This allows for
2547 the possibility of the actual libc call failing due to ENOMEM
2548 (like Glibc does under some conditions). */
2550 if (fmtres.range.min == fmtres.range.max)
2551 warned = fmtwarn (dirloc, pargrange, NULL,
2552 info.warnopt (),
2553 "%<%.*s%> directive output of %wu bytes exceeds "
2554 "minimum required size of 4095",
2555 dirlen, dir.beg, fmtres.range.min);
2556 else
2558 const char *fmtstr
2559 = (minunder4k
2560 ? G_("%<%.*s%> directive output between %wu and %wu "
2561 "bytes may exceed minimum required size of 4095")
2562 : G_("%<%.*s%> directive output between %wu and %wu "
2563 "bytes exceeds minimum required size of 4095"));
2565 warned = fmtwarn (dirloc, pargrange, NULL,
2566 info.warnopt (), fmtstr,
2567 dirlen, dir.beg,
2568 fmtres.range.min, fmtres.range.max);
2572 /* Has the likely and maximum directive output exceeded INT_MAX? */
2573 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2574 bool maxximax = *dir.beg && res->range.max > target_int_max ();
2576 if (!warned
2577 /* Warn for the likely output size at level 1. */
2578 && (likelyximax
2579 /* But only warn for the maximum at level 2. */
2580 || (1 < warn_level
2581 && maxximax
2582 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2584 /* The directive output causes the total length of output
2585 to exceed INT_MAX bytes. */
2587 if (fmtres.range.min == fmtres.range.max)
2588 warned = fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
2589 "%<%.*s%> directive output of %wu bytes causes "
2590 "result to exceed %<INT_MAX%>",
2591 dirlen, dir.beg, fmtres.range.min);
2592 else
2594 const char *fmtstr
2595 = (fmtres.range.min > target_int_max ()
2596 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2597 "bytes causes result to exceed %<INT_MAX%>")
2598 : G_ ("%<%.*s%> directive output between %wu and %wu "
2599 "bytes may cause result to exceed %<INT_MAX%>"));
2600 warned = fmtwarn (dirloc, pargrange, NULL,
2601 info.warnopt (), fmtstr,
2602 dirlen, dir.beg,
2603 fmtres.range.min, fmtres.range.max);
2607 if (warned && fmtres.range.min < fmtres.range.likely
2608 && fmtres.range.likely < fmtres.range.max)
2610 inform (info.fmtloc,
2611 (1 == fmtres.range.likely
2612 ? G_("assuming directive output of %wu byte")
2613 : G_("assuming directive output of %wu bytes")),
2614 fmtres.range.likely);
2617 if (warned && fmtres.argmin)
2619 if (fmtres.argmin == fmtres.argmax)
2620 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2621 else if (fmtres.knownrange)
2622 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2623 fmtres.argmin, fmtres.argmax);
2624 else
2625 inform (info.fmtloc,
2626 "using the range [%E, %E] for directive argument",
2627 fmtres.argmin, fmtres.argmax);
2630 res->warned |= warned;
2632 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2634 /* If a warning has been issued for buffer overflow or truncation
2635 (but not otherwise) help the user figure out how big a buffer
2636 they need. */
2638 location_t callloc = gimple_location (info.callstmt);
2640 unsigned HOST_WIDE_INT min = res->range.min;
2641 unsigned HOST_WIDE_INT max = res->range.max;
2643 if (min == max)
2644 inform (callloc,
2645 (min == 1
2646 ? G_("%qE output %wu byte into a destination of size %wu")
2647 : G_("%qE output %wu bytes into a destination of size %wu")),
2648 info.func, min, info.objsize);
2649 else if (max < HOST_WIDE_INT_MAX)
2650 inform (callloc,
2651 "%qE output between %wu and %wu bytes into "
2652 "a destination of size %wu",
2653 info.func, min, max, info.objsize);
2654 else if (min < res->range.likely && res->range.likely < max)
2655 inform (callloc,
2656 "%qE output %wu or more bytes (assuming %wu) into "
2657 "a destination of size %wu",
2658 info.func, min, res->range.likely, info.objsize);
2659 else
2660 inform (callloc,
2661 "%qE output %wu or more bytes into a destination of size %wu",
2662 info.func, min, info.objsize);
2665 if (dump_file && *dir.beg)
2667 fprintf (dump_file, " Result: %lli, %lli, %lli, %lli "
2668 "(%lli, %lli, %lli, %lli)\n",
2669 (long long)fmtres.range.min,
2670 (long long)fmtres.range.likely,
2671 (long long)fmtres.range.max,
2672 (long long)fmtres.range.unlikely,
2673 (long long)res->range.min,
2674 (long long)res->range.likely,
2675 (long long)res->range.max,
2676 (long long)res->range.unlikely);
2679 return true;
2682 #pragma GCC diagnostic pop
2684 /* Parse a format directive in function call described by INFO starting
2685 at STR and populate DIR structure. Bump up *ARGNO by the number of
2686 arguments extracted for the directive. Return the length of
2687 the directive. */
2689 static size_t
2690 parse_directive (pass_sprintf_length::call_info &info,
2691 directive &dir, format_result *res,
2692 const char *str, unsigned *argno)
2694 const char *pcnt = strchr (str, '%');
2695 dir.beg = str;
2697 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
2699 /* This directive is either a plain string or the terminating nul
2700 (which isn't really a directive but it simplifies things to
2701 handle it as if it were). */
2702 dir.len = len;
2703 dir.fmtfunc = format_plain;
2705 if (dump_file)
2707 fprintf (dump_file, " Directive %u at offset %llu: \"%.*s\", "
2708 "length = %llu\n",
2709 dir.dirno,
2710 (unsigned long long)(size_t)(dir.beg - info.fmtstr),
2711 (int)dir.len, dir.beg, (unsigned long long)dir.len);
2714 return len - !*str;
2717 const char *pf = pcnt + 1;
2719 /* POSIX numbered argument index or zero when none. */
2720 unsigned dollar = 0;
2722 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
2723 when given by a va_list argument, and a non-negative value
2724 when specified in the format string itself. */
2725 HOST_WIDE_INT width = -1;
2726 HOST_WIDE_INT precision = -1;
2728 /* Width specified via the asterisk. Need not be INTEGER_CST.
2729 For vararg functions set to void_node. */
2730 tree star_width = NULL_TREE;
2732 /* Width specified via the asterisk. Need not be INTEGER_CST.
2733 For vararg functions set to void_node. */
2734 tree star_precision = NULL_TREE;
2736 if (ISDIGIT (*pf))
2738 /* This could be either a POSIX positional argument, the '0'
2739 flag, or a width, depending on what follows. Store it as
2740 width and sort it out later after the next character has
2741 been seen. */
2742 char *end;
2743 width = strtol (pf, &end, 10);
2744 pf = end;
2746 else if ('*' == *pf)
2748 /* Similarly to the block above, this could be either a POSIX
2749 positional argument or a width, depending on what follows. */
2750 if (*argno < gimple_call_num_args (info.callstmt))
2751 star_width = gimple_call_arg (info.callstmt, (*argno)++);
2752 else
2753 star_width = void_node;
2754 ++pf;
2757 if (*pf == '$')
2759 /* Handle the POSIX dollar sign which references the 1-based
2760 positional argument number. */
2761 if (width != -1)
2762 dollar = width + info.argidx;
2763 else if (star_width
2764 && TREE_CODE (star_width) == INTEGER_CST)
2765 dollar = width + tree_to_shwi (star_width);
2767 /* Bail when the numbered argument is out of range (it will
2768 have already been diagnosed by -Wformat). */
2769 if (dollar == 0
2770 || dollar == info.argidx
2771 || dollar > gimple_call_num_args (info.callstmt))
2772 return false;
2774 --dollar;
2776 star_width = NULL_TREE;
2777 width = -1;
2778 ++pf;
2781 if (dollar || !star_width)
2783 if (width != -1)
2785 if (width == 0)
2787 /* The '0' that has been interpreted as a width above is
2788 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
2789 and continue processing other flags. */
2790 width = -1;
2791 dir.set_flag ('0');
2793 else if (!dollar)
2795 /* (Non-zero) width has been seen. The next character
2796 is either a period or a digit. */
2797 goto start_precision;
2800 /* When either '$' has been seen, or width has not been seen,
2801 the next field is the optional flags followed by an optional
2802 width. */
2803 for ( ; ; ) {
2804 switch (*pf)
2806 case ' ':
2807 case '0':
2808 case '+':
2809 case '-':
2810 case '#':
2811 dir.set_flag (*pf++);
2812 break;
2814 default:
2815 goto start_width;
2819 start_width:
2820 if (ISDIGIT (*pf))
2822 char *end;
2823 width = strtol (pf, &end, 10);
2824 pf = end;
2826 else if ('*' == *pf)
2828 if (*argno < gimple_call_num_args (info.callstmt))
2829 star_width = gimple_call_arg (info.callstmt, (*argno)++);
2830 else
2832 /* This is (likely) a va_list. It could also be an invalid
2833 call with insufficient arguments. */
2834 star_width = void_node;
2836 ++pf;
2838 else if ('\'' == *pf)
2840 /* The POSIX apostrophe indicating a numeric grouping
2841 in the current locale. Even though it's possible to
2842 estimate the upper bound on the size of the output
2843 based on the number of digits it probably isn't worth
2844 continuing. */
2845 return 0;
2849 start_precision:
2850 if ('.' == *pf)
2852 ++pf;
2854 if (ISDIGIT (*pf))
2856 char *end;
2857 precision = strtol (pf, &end, 10);
2858 pf = end;
2860 else if ('*' == *pf)
2862 if (*argno < gimple_call_num_args (info.callstmt))
2863 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
2864 else
2866 /* This is (likely) a va_list. It could also be an invalid
2867 call with insufficient arguments. */
2868 star_precision = void_node;
2870 ++pf;
2872 else
2874 /* The decimal precision or the asterisk are optional.
2875 When neither is dirified it's taken to be zero. */
2876 precision = 0;
2880 switch (*pf)
2882 case 'h':
2883 if (pf[1] == 'h')
2885 ++pf;
2886 dir.modifier = FMT_LEN_hh;
2888 else
2889 dir.modifier = FMT_LEN_h;
2890 ++pf;
2891 break;
2893 case 'j':
2894 dir.modifier = FMT_LEN_j;
2895 ++pf;
2896 break;
2898 case 'L':
2899 dir.modifier = FMT_LEN_L;
2900 ++pf;
2901 break;
2903 case 'l':
2904 if (pf[1] == 'l')
2906 ++pf;
2907 dir.modifier = FMT_LEN_ll;
2909 else
2910 dir.modifier = FMT_LEN_l;
2911 ++pf;
2912 break;
2914 case 't':
2915 dir.modifier = FMT_LEN_t;
2916 ++pf;
2917 break;
2919 case 'z':
2920 dir.modifier = FMT_LEN_z;
2921 ++pf;
2922 break;
2925 switch (*pf)
2927 /* Handle a sole '%' character the same as "%%" but since it's
2928 undefined prevent the result from being folded. */
2929 case '\0':
2930 --pf;
2931 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
2932 /* FALLTHRU */
2933 case '%':
2934 dir.fmtfunc = format_percent;
2935 break;
2937 case 'a':
2938 case 'A':
2939 case 'e':
2940 case 'E':
2941 case 'f':
2942 case 'F':
2943 case 'g':
2944 case 'G':
2945 res->floating = true;
2946 dir.fmtfunc = format_floating;
2947 break;
2949 case 'd':
2950 case 'i':
2951 case 'o':
2952 case 'u':
2953 case 'x':
2954 case 'X':
2955 dir.fmtfunc = format_integer;
2956 break;
2958 case 'p':
2959 /* The %p output is implementation-defined. It's possible
2960 to determine this format but due to extensions (edirially
2961 those of the Linux kernel -- see bug 78512) the first %p
2962 in the format string disables any further processing. */
2963 return false;
2965 case 'n':
2966 /* %n has side-effects even when nothing is actually printed to
2967 any buffer. */
2968 info.nowrite = false;
2969 dir.fmtfunc = format_none;
2970 break;
2972 case 'c':
2973 dir.fmtfunc = format_character;
2974 break;
2976 case 'S':
2977 case 's':
2978 dir.fmtfunc = format_string;
2979 break;
2981 default:
2982 /* Unknown conversion specification. */
2983 return 0;
2986 dir.specifier = *pf++;
2988 if (star_width)
2990 if (TREE_CODE (TREE_TYPE (star_width)) == INTEGER_TYPE)
2991 dir.set_width (star_width);
2992 else
2994 /* Width specified by a va_list takes on the range [0, -INT_MIN]
2995 (width is the absolute value of that specified). */
2996 dir.width[0] = 0;
2997 dir.width[1] = target_int_max () + 1;
3000 else
3001 dir.set_width (width);
3003 if (star_precision)
3005 if (TREE_CODE (TREE_TYPE (star_precision)) == INTEGER_TYPE)
3006 dir.set_precision (star_precision);
3007 else
3009 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3010 (unlike width, negative precision is ignored). */
3011 dir.prec[0] = -1;
3012 dir.prec[1] = target_int_max ();
3015 else
3016 dir.set_precision (precision);
3018 /* Extract the argument if the directive takes one and if it's
3019 available (e.g., the function doesn't take a va_list). Treat
3020 missing arguments the same as va_list, even though they will
3021 have likely already been diagnosed by -Wformat. */
3022 if (dir.specifier != '%'
3023 && *argno < gimple_call_num_args (info.callstmt))
3024 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3026 /* Return the length of the format directive. */
3027 dir.len = pf - pcnt;
3029 if (dump_file)
3031 fprintf (dump_file, " Directive %u at offset %llu: \"%.*s\"",
3032 dir.dirno, (unsigned long long)(size_t)(dir.beg - info.fmtstr),
3033 (int)dir.len, dir.beg);
3034 if (star_width)
3036 if (dir.width[0] == dir.width[1])
3037 fprintf (dump_file, ", width = %lli", (long long)dir.width[0]);
3038 else
3039 fprintf (dump_file, ", width in range [%lli, %lli]",
3040 (long long)dir.width[0], (long long)dir.width[1]);
3043 if (star_precision)
3045 if (dir.prec[0] == dir.prec[1])
3046 fprintf (dump_file, ", precision = %lli", (long long)dir.prec[0]);
3047 else
3048 fprintf (dump_file, ", precision in range [%lli, %lli]",
3049 (long long)dir.prec[0], (long long)dir.prec[1]);
3051 fputc ('\n', dump_file);
3054 return dir.len;
3057 /* Compute the length of the output resulting from the call to a formatted
3058 output function described by INFO and store the result of the call in
3059 *RES. Issue warnings for detected past the end writes. Return true
3060 if the complete format string has been processed and *RES can be relied
3061 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3062 that caused the processing to be terminated early). */
3064 bool
3065 pass_sprintf_length::compute_format_length (call_info &info,
3066 format_result *res)
3068 if (dump_file)
3070 location_t callloc = gimple_location (info.callstmt);
3071 fprintf (dump_file, "%s:%i: ",
3072 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3073 print_generic_expr (dump_file, info.func, dump_flags);
3075 fprintf (dump_file, ": objsize = %llu, fmtstr = \"%s\"\n",
3076 (unsigned long long)info.objsize, info.fmtstr);
3079 /* Reset the minimum and maximum byte counters. */
3080 res->range.min = res->range.max = 0;
3082 /* No directive has been seen yet so the length of output is bounded
3083 by the known range [0, 0] (with no conversion producing more than
3084 4K bytes) until determined otherwise. */
3085 res->knownrange = true;
3086 res->under4k = true;
3087 res->floating = false;
3088 res->warned = false;
3090 /* 1-based directive counter. */
3091 unsigned dirno = 1;
3093 /* The variadic argument counter. */
3094 unsigned argno = info.argidx;
3096 for (const char *pf = info.fmtstr; ; ++dirno)
3098 directive dir = directive ();
3099 dir.dirno = dirno;
3101 size_t n = parse_directive (info, dir, res, pf, &argno);
3103 /* Return failure if the format function fails. */
3104 if (!format_directive (info, res, dir))
3105 return false;
3107 /* Return success the directive is zero bytes long and it's
3108 the last think in the format string (i.e., it's the terminating
3109 nul, which isn't really a directive but handling it as one makes
3110 things simpler). */
3111 if (!n)
3112 return *pf == '\0';
3114 pf += n;
3117 /* The complete format string was processed (with or without warnings). */
3118 return true;
3121 /* Return the size of the object referenced by the expression DEST if
3122 available, or -1 otherwise. */
3124 static unsigned HOST_WIDE_INT
3125 get_destination_size (tree dest)
3127 /* Initialize object size info before trying to compute it. */
3128 init_object_sizes ();
3130 /* Use __builtin_object_size to determine the size of the destination
3131 object. When optimizing, determine the smallest object (such as
3132 a member array as opposed to the whole enclosing object), otherwise
3133 use type-zero object size to determine the size of the enclosing
3134 object (the function fails without optimization in this type). */
3135 int ost = optimize > 0;
3136 unsigned HOST_WIDE_INT size;
3137 if (compute_builtin_object_size (dest, ost, &size))
3138 return size;
3140 return HOST_WIDE_INT_M1U;
3143 /* Given a suitable result RES of a call to a formatted output function
3144 described by INFO, substitute the result for the return value of
3145 the call. The result is suitable if the number of bytes it represents
3146 is known and exact. A result that isn't suitable for substitution may
3147 have its range set to the range of return values, if that is known.
3148 Return true if the call is removed and gsi_next should not be performed
3149 in the caller. */
3151 static bool
3152 try_substitute_return_value (gimple_stmt_iterator *gsi,
3153 const pass_sprintf_length::call_info &info,
3154 const format_result &res)
3156 tree lhs = gimple_get_lhs (info.callstmt);
3158 /* Set to true when the entire call has been removed. */
3159 bool removed = false;
3161 /* The minimum return value. */
3162 unsigned HOST_WIDE_INT minretval = res.range.min;
3164 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3165 but in cases involving multibyte characters could be as large as
3166 RES.RANGE.UNLIKELY. */
3167 unsigned HOST_WIDE_INT maxretval
3168 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3170 /* Adjust the number of bytes which includes the terminating nul
3171 to reflect the return value of the function which does not.
3172 Because the valid range of the function is [INT_MIN, INT_MAX],
3173 a valid range before the adjustment below is [0, INT_MAX + 1]
3174 (the functions only return negative values on error or undefined
3175 behavior). */
3176 if (minretval <= target_int_max () + 1)
3177 --minretval;
3178 if (maxretval <= target_int_max () + 1)
3179 --maxretval;
3181 /* Avoid the return value optimization when the behavior of the call
3182 is undefined either because any directive may have produced 4K or
3183 more of output, or the return value exceeds INT_MAX, or because
3184 the output overflows the destination object (but leave it enabled
3185 when the function is bounded because then the behavior is well-
3186 defined). */
3187 if (res.under4k
3188 && minretval == maxretval
3189 && (info.bounded || minretval < info.objsize)
3190 && minretval <= target_int_max ()
3191 /* Not prepared to handle possibly throwing calls here; they shouldn't
3192 appear in non-artificial testcases, except when the __*_chk routines
3193 are badly declared. */
3194 && !stmt_ends_bb_p (info.callstmt))
3196 tree cst = build_int_cst (integer_type_node, minretval);
3198 if (lhs == NULL_TREE
3199 && info.nowrite)
3201 /* Remove the call to the bounded function with a zero size
3202 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3203 unlink_stmt_vdef (info.callstmt);
3204 gsi_remove (gsi, true);
3205 removed = true;
3207 else if (info.nowrite)
3209 /* Replace the call to the bounded function with a zero size
3210 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3211 of the function. */
3212 if (!update_call_from_tree (gsi, cst))
3213 gimplify_and_update_call_from_tree (gsi, cst);
3214 gimple *callstmt = gsi_stmt (*gsi);
3215 update_stmt (callstmt);
3217 else if (lhs)
3219 /* Replace the left-hand side of the call with the constant
3220 result of the formatted function. */
3221 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3222 gimple *g = gimple_build_assign (lhs, cst);
3223 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3224 update_stmt (info.callstmt);
3227 if (dump_file)
3229 if (removed)
3230 fprintf (dump_file, " Removing call statement.");
3231 else
3233 fprintf (dump_file, " Substituting ");
3234 print_generic_expr (dump_file, cst, dump_flags);
3235 fprintf (dump_file, " for %s.\n",
3236 info.nowrite ? "statement" : "return value");
3240 else if (lhs)
3242 bool setrange = false;
3244 if ((info.bounded || maxretval < info.objsize)
3245 && res.under4k
3246 && (minretval < target_int_max ()
3247 && maxretval < target_int_max ()))
3249 /* If the result is in a valid range bounded by the size of
3250 the destination set it so that it can be used for subsequent
3251 optimizations. */
3252 int prec = TYPE_PRECISION (integer_type_node);
3254 wide_int min = wi::shwi (minretval, prec);
3255 wide_int max = wi::shwi (maxretval, prec);
3256 set_range_info (lhs, VR_RANGE, min, max);
3258 setrange = true;
3261 if (dump_file)
3263 const char *inbounds
3264 = (minretval < info.objsize
3265 ? (maxretval < info.objsize
3266 ? "in" : "potentially out-of")
3267 : "out-of");
3269 const char *what = setrange ? "Setting" : "Discarding";
3270 if (minretval != maxretval)
3271 fprintf (dump_file,
3272 " %s %s-bounds return value range [%llu, %llu].\n",
3273 what, inbounds,
3274 (unsigned long long)minretval,
3275 (unsigned long long)maxretval);
3276 else
3277 fprintf (dump_file, " %s %s-bounds return value %llu.\n",
3278 what, inbounds, (unsigned long long)minretval);
3282 if (dump_file)
3283 fputc ('\n', dump_file);
3285 return removed;
3288 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3289 functions and if so, handle it. Return true if the call is removed
3290 and gsi_next should not be performed in the caller. */
3292 bool
3293 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator *gsi)
3295 call_info info = call_info ();
3297 info.callstmt = gsi_stmt (*gsi);
3298 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3299 return false;
3301 info.func = gimple_call_fndecl (info.callstmt);
3302 info.fncode = DECL_FUNCTION_CODE (info.func);
3304 /* The size of the destination as in snprintf(dest, size, ...). */
3305 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3307 /* The size of the destination determined by __builtin_object_size. */
3308 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3310 /* Buffer size argument number (snprintf and vsnprintf). */
3311 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3313 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3314 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3316 /* Format string argument number (valid for all functions). */
3317 unsigned idx_format;
3319 switch (info.fncode)
3321 case BUILT_IN_SPRINTF:
3322 // Signature:
3323 // __builtin_sprintf (dst, format, ...)
3324 idx_format = 1;
3325 info.argidx = 2;
3326 break;
3328 case BUILT_IN_SPRINTF_CHK:
3329 // Signature:
3330 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3331 idx_objsize = 2;
3332 idx_format = 3;
3333 info.argidx = 4;
3334 break;
3336 case BUILT_IN_SNPRINTF:
3337 // Signature:
3338 // __builtin_snprintf (dst, size, format, ...)
3339 idx_dstsize = 1;
3340 idx_format = 2;
3341 info.argidx = 3;
3342 info.bounded = true;
3343 break;
3345 case BUILT_IN_SNPRINTF_CHK:
3346 // Signature:
3347 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3348 idx_dstsize = 1;
3349 idx_objsize = 3;
3350 idx_format = 4;
3351 info.argidx = 5;
3352 info.bounded = true;
3353 break;
3355 case BUILT_IN_VSNPRINTF:
3356 // Signature:
3357 // __builtin_vsprintf (dst, size, format, va)
3358 idx_dstsize = 1;
3359 idx_format = 2;
3360 info.argidx = -1;
3361 info.bounded = true;
3362 break;
3364 case BUILT_IN_VSNPRINTF_CHK:
3365 // Signature:
3366 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3367 idx_dstsize = 1;
3368 idx_objsize = 3;
3369 idx_format = 4;
3370 info.argidx = -1;
3371 info.bounded = true;
3372 break;
3374 case BUILT_IN_VSPRINTF:
3375 // Signature:
3376 // __builtin_vsprintf (dst, format, va)
3377 idx_format = 1;
3378 info.argidx = -1;
3379 break;
3381 case BUILT_IN_VSPRINTF_CHK:
3382 // Signature:
3383 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3384 idx_format = 3;
3385 idx_objsize = 2;
3386 info.argidx = -1;
3387 break;
3389 default:
3390 return false;
3393 /* Set the global warning level for this function. */
3394 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3396 /* The first argument is a pointer to the destination. */
3397 tree dstptr = gimple_call_arg (info.callstmt, 0);
3399 info.format = gimple_call_arg (info.callstmt, idx_format);
3401 if (idx_dstsize == HOST_WIDE_INT_M1U)
3403 /* For non-bounded functions like sprintf, determine the size
3404 of the destination from the object or pointer passed to it
3405 as the first argument. */
3406 dstsize = get_destination_size (dstptr);
3408 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3410 /* For bounded functions try to get the size argument. */
3412 if (TREE_CODE (size) == INTEGER_CST)
3414 dstsize = tree_to_uhwi (size);
3415 /* No object can be larger than SIZE_MAX bytes (half the address
3416 space) on the target.
3417 The functions are defined only for output of at most INT_MAX
3418 bytes. Specifying a bound in excess of that limit effectively
3419 defeats the bounds checking (and on some implementations such
3420 as Solaris cause the function to fail with EINVAL). */
3421 if (dstsize > target_size_max () / 2)
3423 /* Avoid warning if -Wstringop-overflow is specified since
3424 it also warns for the same thing though only for the
3425 checking built-ins. */
3426 if ((idx_objsize == HOST_WIDE_INT_M1U
3427 || !warn_stringop_overflow))
3428 warning_at (gimple_location (info.callstmt), info.warnopt (),
3429 "specified bound %wu exceeds maximum object size "
3430 "%wu",
3431 dstsize, target_size_max () / 2);
3433 else if (dstsize > target_int_max ())
3434 warning_at (gimple_location (info.callstmt), info.warnopt (),
3435 "specified bound %wu exceeds %<INT_MAX %>",
3436 dstsize);
3438 else if (TREE_CODE (size) == SSA_NAME)
3440 /* Try to determine the range of values of the argument
3441 and use the greater of the two at -Wformat-level 1 and
3442 the smaller of them at level 2. */
3443 wide_int min, max;
3444 enum value_range_type range_type
3445 = get_range_info (size, &min, &max);
3446 if (range_type == VR_RANGE)
3448 dstsize
3449 = (warn_level < 2
3450 ? wi::fits_uhwi_p (max) ? max.to_uhwi () : max.to_shwi ()
3451 : wi::fits_uhwi_p (min) ? min.to_uhwi () : min.to_shwi ());
3456 if (idx_objsize != HOST_WIDE_INT_M1U)
3457 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3458 if (tree_fits_uhwi_p (size))
3459 objsize = tree_to_uhwi (size);
3461 if (info.bounded && !dstsize)
3463 /* As a special case, when the explicitly specified destination
3464 size argument (to a bounded function like snprintf) is zero
3465 it is a request to determine the number of bytes on output
3466 without actually producing any. Pretend the size is
3467 unlimited in this case. */
3468 info.objsize = HOST_WIDE_INT_MAX;
3469 info.nowrite = true;
3471 else
3473 /* For calls to non-bounded functions or to those of bounded
3474 functions with a non-zero size, warn if the destination
3475 pointer is null. */
3476 if (integer_zerop (dstptr))
3478 /* This is diagnosed with -Wformat only when the null is a constant
3479 pointer. The warning here diagnoses instances where the pointer
3480 is not constant. */
3481 location_t loc = gimple_location (info.callstmt);
3482 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3483 info.warnopt (), "null destination pointer");
3484 return false;
3487 /* Set the object size to the smaller of the two arguments
3488 of both have been specified and they're not equal. */
3489 info.objsize = dstsize < objsize ? dstsize : objsize;
3491 if (info.bounded
3492 && dstsize < target_size_max () / 2 && objsize < dstsize
3493 /* Avoid warning if -Wstringop-overflow is specified since
3494 it also warns for the same thing though only for the
3495 checking built-ins. */
3496 && (idx_objsize == HOST_WIDE_INT_M1U
3497 || !warn_stringop_overflow))
3499 warning_at (gimple_location (info.callstmt), info.warnopt (),
3500 "specified bound %wu exceeds the size %wu "
3501 "of the destination object", dstsize, objsize);
3505 if (integer_zerop (info.format))
3507 /* This is diagnosed with -Wformat only when the null is a constant
3508 pointer. The warning here diagnoses instances where the pointer
3509 is not constant. */
3510 location_t loc = gimple_location (info.callstmt);
3511 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3512 info.warnopt (), "null format string");
3513 return false;
3516 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3517 if (!info.fmtstr)
3518 return false;
3520 /* The result is the number of bytes output by the formatted function,
3521 including the terminating NUL. */
3522 format_result res = format_result ();
3524 bool success = compute_format_length (info, &res);
3526 /* When optimizing and the printf return value optimization is enabled,
3527 attempt to substitute the computed result for the return value of
3528 the call. Avoid this optimization when -frounding-math is in effect
3529 and the format string contains a floating point directive. */
3530 if (success
3531 && optimize > 0
3532 && flag_printf_return_value
3533 && (!flag_rounding_math || !res.floating))
3534 return try_substitute_return_value (gsi, info, res);
3536 return false;
3539 /* Execute the pass for function FUN. */
3541 unsigned int
3542 pass_sprintf_length::execute (function *fun)
3544 basic_block bb;
3545 FOR_EACH_BB_FN (bb, fun)
3547 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
3549 /* Iterate over statements, looking for function calls. */
3550 gimple *stmt = gsi_stmt (si);
3552 if (is_gimple_call (stmt) && handle_gimple_call (&si))
3553 /* If handle_gimple_call returns true, the iterator is
3554 already pointing to the next statement. */
3555 continue;
3557 gsi_next (&si);
3561 /* Clean up object size info. */
3562 fini_object_sizes ();
3564 return 0;
3567 } /* Unnamed namespace. */
3569 /* Return a pointer to a pass object newly constructed from the context
3570 CTXT. */
3572 gimple_opt_pass *
3573 make_pass_sprintf_length (gcc::context *ctxt)
3575 return new pass_sprintf_length (ctxt);