1 /* Copyright (C) 2016 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
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
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. */
50 #include "coretypes.h"
54 #include "tree-pass.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"
62 #include "tree-object-size.h"
65 #include "tree-ssa-propagate.h"
71 #include "stor-layout.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
89 const pass_data pass_data_sprintf_length
= {
90 GIMPLE_PASS
, // pass type
91 "printf-return-value", // pass name
92 OPTGROUP_NONE
, // optinfo_flags
94 PROP_cfg
, // properties_required
95 0, // properties_provided
96 0, // properties_destroyed
97 0, // properties_start
98 0, // properties_finish
101 struct format_result
;
103 class pass_sprintf_length
: public gimple_opt_pass
105 bool fold_return_value
;
108 pass_sprintf_length (gcc::context
*ctxt
)
109 : gimple_opt_pass (pass_data_sprintf_length
, ctxt
),
110 fold_return_value (false)
113 opt_pass
* clone () { return new pass_sprintf_length (m_ctxt
); }
115 virtual bool gate (function
*);
117 virtual unsigned int execute (function
*);
119 void set_pass_param (unsigned int n
, bool param
)
122 fold_return_value
= param
;
125 void handle_gimple_call (gimple_stmt_iterator
*);
128 bool compute_format_length (const call_info
&, format_result
*);
132 pass_sprintf_length::gate (function
*)
134 /* Run the pass iff -Warn-format-length is specified and either
135 not optimizing and the pass is being invoked early, or when
136 optimizing and the pass is being invoked during optimization
138 return ((warn_format_length
> 0 || flag_printf_return_value
)
139 && (optimize
> 0) == fold_return_value
);
142 /* The result of a call to a formatted function. */
146 /* Number of characters written by the formatted function, exact,
147 minimum and maximum when an exact number cannot be determined.
148 Setting the minimum to HOST_WIDE_INT_MAX disables all length
149 tracking for the remainder of the format string.
150 Setting either of the other two members to HOST_WIDE_INT_MAX
151 disables the exact or maximum length tracking, respectively,
152 but continues to track the maximum. */
153 unsigned HOST_WIDE_INT number_chars
;
154 unsigned HOST_WIDE_INT number_chars_min
;
155 unsigned HOST_WIDE_INT number_chars_max
;
157 /* True when the range given by NUMBER_CHARS_MIN and NUMBER_CHARS_MAX
158 can be relied on for value range propagation, false otherwise.
159 This means that BOUNDED must not be set if the number of bytes
160 produced by any directive is unspecified or implementation-
161 defined (unless the implementation's behavior is known and
162 determined via a target hook).
163 Note that BOUNDED only implies that the length of a function's
164 output is known to be within some range, not that it's constant
165 and a candidate for string folding. BOUNDED is a stronger
166 guarantee than KNOWNRANGE. */
169 /* True when the range above is obtained from known values of
170 directive arguments or their bounds and not the result of
171 heuristics that depend on warning levels. It is used to
172 issue stricter diagnostics in cases where strings of unknown
173 lengths are bounded by the arrays they are determined to
174 refer to. KNOWNRANGE must not be used to set the range of
175 the return value of a call. */
178 /* True when the output of the formatted call is constant (and
179 thus a candidate for string constant folding). This is rare
180 and typically requires that the arguments of all directives
181 are also constant. CONSTANT implies BOUNDED. */
184 /* True if no individual directive resulted in more than 4095 bytes
185 of output (the total NUMBER_CHARS might be greater). */
188 /* True when a floating point directive has been seen in the format
192 /* True when an intermediate result has caused a warning. Used to
193 avoid issuing duplicate warnings while finishing the processing
197 /* Preincrement the number of output characters by 1. */
198 format_result
& operator++ ()
203 /* Postincrement the number of output characters by 1. */
204 format_result
operator++ (int)
206 format_result
prev (*this);
211 /* Increment the number of output characters by N. */
212 format_result
& operator+= (unsigned HOST_WIDE_INT n
)
214 gcc_assert (n
< HOST_WIDE_INT_MAX
);
216 if (number_chars
< HOST_WIDE_INT_MAX
)
218 if (number_chars_min
< HOST_WIDE_INT_MAX
)
219 number_chars_min
+= n
;
220 if (number_chars_max
< HOST_WIDE_INT_MAX
)
221 number_chars_max
+= n
;
226 /* Return the value of INT_MIN for the target. */
228 static inline HOST_WIDE_INT
231 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node
));
234 /* Return the value of INT_MAX for the target. */
236 static inline unsigned HOST_WIDE_INT
239 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node
));
242 /* Return the value of SIZE_MAX for the target. */
244 static inline unsigned HOST_WIDE_INT
247 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node
));
250 /* Return the constant initial value of DECL if available or DECL
251 otherwise. Same as the synonymous function in c/c-typeck.c. */
254 decl_constant_value (tree decl
)
256 if (/* Don't change a variable array bound or initial value to a constant
257 in a place where a variable is invalid. Note that DECL_INITIAL
258 isn't valid for a PARM_DECL. */
259 current_function_decl
!= 0
260 && TREE_CODE (decl
) != PARM_DECL
261 && !TREE_THIS_VOLATILE (decl
)
262 && TREE_READONLY (decl
)
263 && DECL_INITIAL (decl
) != 0
264 && TREE_CODE (DECL_INITIAL (decl
)) != ERROR_MARK
265 /* This is invalid if initial value is not constant.
266 If it has either a function call, a memory reference,
267 or a variable, then re-evaluating it could give different results. */
268 && TREE_CONSTANT (DECL_INITIAL (decl
))
269 /* Check for cases where this is sub-optimal, even though valid. */
270 && TREE_CODE (DECL_INITIAL (decl
)) != CONSTRUCTOR
)
271 return DECL_INITIAL (decl
);
275 /* Given FORMAT, set *PLOC to the source location of the format string
276 and return the format string if it is known or null otherwise. */
279 get_format_string (tree format
, location_t
*ploc
)
283 /* Pull out a constant value if the front end didn't. */
284 format
= decl_constant_value (format
);
288 if (integer_zerop (format
))
290 /* FIXME: Diagnose null format string if it hasn't been diagnosed
291 by -Wformat (the latter diagnoses only nul pointer constants,
292 this pass can do better). */
296 HOST_WIDE_INT offset
= 0;
298 if (TREE_CODE (format
) == POINTER_PLUS_EXPR
)
300 tree arg0
= TREE_OPERAND (format
, 0);
301 tree arg1
= TREE_OPERAND (format
, 1);
305 if (TREE_CODE (arg1
) != INTEGER_CST
)
310 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
311 if (!cst_and_fits_in_hwi (arg1
))
314 offset
= int_cst_value (arg1
);
317 if (TREE_CODE (format
) != ADDR_EXPR
)
320 *ploc
= EXPR_LOC_OR_LOC (format
, input_location
);
322 format
= TREE_OPERAND (format
, 0);
324 if (TREE_CODE (format
) == ARRAY_REF
325 && tree_fits_shwi_p (TREE_OPERAND (format
, 1))
326 && (offset
+= tree_to_shwi (TREE_OPERAND (format
, 1))) >= 0)
327 format
= TREE_OPERAND (format
, 0);
333 tree array_size
= NULL_TREE
;
336 && TREE_CODE (TREE_TYPE (format
)) == ARRAY_TYPE
337 && (array_init
= decl_constant_value (format
)) != format
338 && TREE_CODE (array_init
) == STRING_CST
)
340 /* Extract the string constant initializer. Note that this may
341 include a trailing NUL character that is not in the array (e.g.
342 const char a[3] = "foo";). */
343 array_size
= DECL_SIZE_UNIT (format
);
347 if (TREE_CODE (format
) != STRING_CST
)
350 if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format
))) != char_type_node
)
352 /* Wide format string. */
356 const char *fmtstr
= TREE_STRING_POINTER (format
);
357 unsigned fmtlen
= TREE_STRING_LENGTH (format
);
361 /* Variable length arrays can't be initialized. */
362 gcc_assert (TREE_CODE (array_size
) == INTEGER_CST
);
364 if (tree_fits_shwi_p (array_size
))
366 HOST_WIDE_INT array_size_value
= tree_to_shwi (array_size
);
367 if (array_size_value
> 0
368 && array_size_value
== (int) array_size_value
369 && fmtlen
> array_size_value
)
370 fmtlen
= array_size_value
;
375 if (offset
>= fmtlen
)
382 if (fmtlen
< 1 || fmtstr
[--fmtlen
] != 0)
384 /* FIXME: Diagnose an unterminated format string if it hasn't been
385 diagnosed by -Wformat. Similarly to a null format pointer,
386 -Wformay diagnoses only nul pointer constants, this pass can
394 /* The format_warning_at_substring function is not used here in a way
395 that makes using attribute format viable. Suppress the warning. */
397 #pragma GCC diagnostic push
398 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
400 /* For convenience and brevity. */
403 (* const fmtwarn
) (const substring_loc
&, const source_range
*,
404 const char *, int, const char *, ...)
405 = format_warning_at_substring
;
407 /* Format length modifiers. */
412 FMT_LEN_hh
, // char argument
415 FMT_LEN_ll
, // long long
416 FMT_LEN_L
, // long double (and GNU long long)
418 FMT_LEN_t
, // ptrdiff_t
419 FMT_LEN_j
// intmax_t
423 /* A minimum and maximum number of bytes. */
427 unsigned HOST_WIDE_INT min
, max
;
430 /* Description of the result of conversion either of a single directive
431 or the whole format string. */
436 : argmin (), argmax (), knownrange (), bounded (), constant ()
438 range
.min
= range
.max
= HOST_WIDE_INT_MAX
;
441 /* The range a directive's argument is in. */
444 /* The minimum and maximum number of bytes that a directive
445 results in on output for an argument in the range above. */
448 /* True when the range above is obtained from a known value of
449 a directive's argument or its bounds and not the result of
450 heuristics that depend on warning levels. */
453 /* True when the range is the result of an argument determined
454 to be bounded to a subrange of its type or value (such as by
455 value range propagation or the width of the formt directive),
459 /* True when the output of a directive is constant. This is rare
460 and typically requires that the argument(s) of the directive
461 are also constant (such as determined by constant propagation,
462 though not value range propagation). */
466 /* Description of a conversion specification. */
468 struct conversion_spec
470 /* A bitmap of flags, one for each character. */
471 unsigned flags
[256 / sizeof (int)];
472 /* Numeric width as in "%8x". */
474 /* Numeric precision as in "%.32s". */
477 /* Width specified via the '*' character. */
479 /* Precision specified via the asterisk. */
482 /* Length modifier. */
483 format_lengths modifier
;
485 /* Format specifier character. */
488 /* Numeric width was given. */
489 unsigned have_width
: 1;
490 /* Numeric precision was given. */
491 unsigned have_precision
: 1;
492 /* Non-zero when certain flags should be interpreted even for a directive
493 that normally doesn't accept them (used when "%p" with flags such as
494 space or plus is interepreted as a "%x". */
495 unsigned force_flags
: 1;
497 /* Format conversion function that given a conversion specification
498 and an argument returns the formatting result. */
499 fmtresult (*fmtfunc
) (const conversion_spec
&, tree
);
501 /* Return True when a the format flag CHR has been used. */
502 bool get_flag (char chr
) const
504 unsigned char c
= chr
& 0xff;
505 return (flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
506 & (1U << (c
% (CHAR_BIT
* sizeof *flags
))));
509 /* Make a record of the format flag CHR having been used. */
510 void set_flag (char chr
)
512 unsigned char c
= chr
& 0xff;
513 flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
514 |= (1U << (c
% (CHAR_BIT
* sizeof *flags
)));
517 /* Reset the format flag CHR. */
518 void clear_flag (char chr
)
520 unsigned char c
= chr
& 0xff;
521 flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
522 &= ~(1U << (c
% (CHAR_BIT
* sizeof *flags
)));
526 /* Return the logarithm of X in BASE. */
529 ilog (unsigned HOST_WIDE_INT x
, int base
)
540 /* Return the number of bytes resulting from converting into a string
541 the INTEGER_CST tree node X in BASE. PLUS indicates whether 1 for
542 a plus sign should be added for positive numbers, and PREFIX whether
543 the length of an octal ('O') or hexadecimal ('0x') prefix should be
544 added for nonzero numbers. Return -1 if X cannot be represented. */
547 tree_digits (tree x
, int base
, bool plus
, bool prefix
)
549 unsigned HOST_WIDE_INT absval
;
553 if (TYPE_UNSIGNED (TREE_TYPE (x
)))
555 if (tree_fits_uhwi_p (x
))
557 absval
= tree_to_uhwi (x
);
565 if (tree_fits_shwi_p (x
))
567 HOST_WIDE_INT i
= tree_to_shwi (x
);
583 res
+= ilog (absval
, base
);
585 if (prefix
&& absval
)
596 /* Given the formatting result described by RES and NAVAIL, the number
597 of available in the destination, return the number of bytes remaining
598 in the destination. */
600 static inline result_range
601 bytes_remaining (unsigned HOST_WIDE_INT navail
, const format_result
&res
)
605 if (HOST_WIDE_INT_MAX
<= navail
)
607 range
.min
= range
.max
= navail
;
611 if (res
.number_chars
< navail
)
613 range
.min
= range
.max
= navail
- res
.number_chars
;
615 else if (res
.number_chars_min
< navail
)
617 range
.max
= navail
- res
.number_chars_min
;
622 if (res
.number_chars_max
< navail
)
623 range
.min
= navail
- res
.number_chars_max
;
630 /* Given the formatting result described by RES and NAVAIL, the number
631 of available in the destination, return the minimum number of bytes
632 remaining in the destination. */
634 static inline unsigned HOST_WIDE_INT
635 min_bytes_remaining (unsigned HOST_WIDE_INT navail
, const format_result
&res
)
637 if (HOST_WIDE_INT_MAX
<= navail
)
640 if (1 < warn_format_length
|| res
.bounded
)
642 /* At level 2, or when all directives output an exact number
643 of bytes or when their arguments were bounded by known
644 ranges, use the greater of the two byte counters if it's
645 valid to compute the result. */
646 if (res
.number_chars_max
< HOST_WIDE_INT_MAX
)
647 navail
-= res
.number_chars_max
;
648 else if (res
.number_chars
< HOST_WIDE_INT_MAX
)
649 navail
-= res
.number_chars
;
650 else if (res
.number_chars_min
< HOST_WIDE_INT_MAX
)
651 navail
-= res
.number_chars_min
;
655 /* At level 1 use the smaller of the byte counters to compute
657 if (res
.number_chars
< HOST_WIDE_INT_MAX
)
658 navail
-= res
.number_chars
;
659 else if (res
.number_chars_min
< HOST_WIDE_INT_MAX
)
660 navail
-= res
.number_chars_min
;
661 else if (res
.number_chars_max
< HOST_WIDE_INT_MAX
)
662 navail
-= res
.number_chars_max
;
665 if (navail
> HOST_WIDE_INT_MAX
)
671 /* Description of a call to a formatted function. */
673 struct pass_sprintf_length::call_info
675 /* Function call statement. */
678 /* Function called. */
681 /* Called built-in function code. */
682 built_in_function fncode
;
684 /* Format argument and format string extracted from it. */
688 /* The location of the format argument. */
691 /* The destination object size for __builtin___xxx_chk functions
692 typically determined by __builtin_object_size, or -1 if unknown. */
693 unsigned HOST_WIDE_INT objsize
;
695 /* Number of the first variable argument. */
696 unsigned HOST_WIDE_INT argidx
;
698 /* True for functions like snprintf that specify the size of
699 the destination, false for others like sprintf that don't. */
702 /* True for bounded functions like snprintf that specify a zero-size
703 buffer as a request to compute the size of output without actually
708 /* Return the result of formatting the '%%' directive. */
711 format_percent (const conversion_spec
&, tree
)
714 res
.argmin
= res
.argmax
= NULL_TREE
;
715 res
.range
.min
= res
.range
.max
= 1;
716 res
.bounded
= res
.constant
= true;
721 /* Compute intmax_type_node and uintmax_type_node similarly to how
722 tree.c builds size_type_node. */
725 build_intmax_type_nodes (tree
*pintmax
, tree
*puintmax
)
727 if (strcmp (UINTMAX_TYPE
, "unsigned int") == 0)
729 *pintmax
= integer_type_node
;
730 *puintmax
= unsigned_type_node
;
732 else if (strcmp (UINTMAX_TYPE
, "long unsigned int") == 0)
734 *pintmax
= long_integer_type_node
;
735 *puintmax
= long_unsigned_type_node
;
737 else if (strcmp (UINTMAX_TYPE
, "long long unsigned int") == 0)
739 *pintmax
= long_long_integer_type_node
;
740 *puintmax
= long_long_unsigned_type_node
;
744 for (int i
= 0; i
< NUM_INT_N_ENTS
; i
++)
745 if (int_n_enabled_p
[i
])
748 sprintf (name
, "__int%d unsigned", int_n_data
[i
].bitsize
);
750 if (strcmp (name
, UINTMAX_TYPE
) == 0)
752 *pintmax
= int_n_trees
[i
].signed_type
;
753 *puintmax
= int_n_trees
[i
].unsigned_type
;
761 /* Set *PWIDTH and *PPREC according to the width and precision specified
762 in SPEC. Each is set to HOST_WIDE_INT_MIN when the corresponding
763 field is specified but unknown, to zero for width and -1 for precision,
764 respectively when it's not specified, or to a non-negative value
765 corresponding to the known value. */
768 get_width_and_precision (const conversion_spec
&spec
,
769 HOST_WIDE_INT
*pwidth
, HOST_WIDE_INT
*pprec
)
771 HOST_WIDE_INT width
= spec
.have_width
? spec
.width
: 0;
772 HOST_WIDE_INT prec
= spec
.have_precision
? spec
.precision
: -1;
776 if (TREE_CODE (spec
.star_width
) == INTEGER_CST
)
777 width
= abs (tree_to_shwi (spec
.star_width
));
779 width
= HOST_WIDE_INT_MIN
;
782 if (spec
.star_precision
)
784 if (TREE_CODE (spec
.star_precision
) == INTEGER_CST
)
786 prec
= tree_to_shwi (spec
.star_precision
);
791 prec
= HOST_WIDE_INT_MIN
;
798 /* Return a range representing the minimum and maximum number of bytes
799 that the conversion specification SPEC will write on output for the
800 integer argument ARG when non-null. ARG may be null (for vararg
804 format_integer (const conversion_spec
&spec
, tree arg
)
806 tree intmax_type_node
;
807 tree uintmax_type_node
;
809 /* Set WIDTH and PRECISION based on the specification. */
812 get_width_and_precision (spec
, &width
, &prec
);
814 bool sign
= spec
.specifier
== 'd' || spec
.specifier
== 'i';
816 /* The type of the "formal" argument expected by the directive. */
817 tree dirtype
= NULL_TREE
;
819 /* Determine the expected type of the argument from the length
821 switch (spec
.modifier
)
824 if (spec
.specifier
== 'p')
825 dirtype
= ptr_type_node
;
827 dirtype
= sign
? integer_type_node
: unsigned_type_node
;
831 dirtype
= sign
? short_integer_type_node
: short_unsigned_type_node
;
835 dirtype
= sign
? signed_char_type_node
: unsigned_char_type_node
;
839 dirtype
= sign
? long_integer_type_node
: long_unsigned_type_node
;
845 ? long_long_integer_type_node
846 : long_long_unsigned_type_node
);
850 dirtype
= signed_or_unsigned_type_for (!sign
, size_type_node
);
854 dirtype
= signed_or_unsigned_type_for (!sign
, ptrdiff_type_node
);
858 build_intmax_type_nodes (&intmax_type_node
, &uintmax_type_node
);
859 dirtype
= sign
? intmax_type_node
: uintmax_type_node
;
866 /* The type of the argument to the directive, either deduced from
867 the actual non-constant argument if one is known, or from
868 the directive itself when none has been provided because it's
870 tree argtype
= NULL_TREE
;
874 /* When the argument has not been provided, use the type of
875 the directive's argument as an approximation. This will
876 result in false positives for directives like %i with
877 arguments with smaller precision (such as short or char). */
880 else if (TREE_CODE (arg
) == INTEGER_CST
)
882 /* When a constant argument has been provided use its value
883 rather than type to determine the length of the output. */
885 /* Base to format the number in. */
888 /* True when a signed conversion is preceded by a sign or space. */
891 switch (spec
.specifier
)
895 /* Space is only effective for signed conversions. */
896 maybesign
= spec
.get_flag (' ');
900 maybesign
= spec
.force_flags
? spec
.get_flag (' ') : false;
904 maybesign
= spec
.force_flags
? spec
.get_flag (' ') : false;
909 maybesign
= spec
.force_flags
? spec
.get_flag (' ') : false;
918 if ((prec
== HOST_WIDE_INT_MIN
|| prec
== 0) && integer_zerop (arg
))
920 /* As a special case, a precision of zero with an argument
921 of zero results in zero bytes regardless of flags (with
922 width having the normal effect). This must extend to
923 the case of a specified precision with an unknown value
924 because it can be zero. */
929 /* Convert the argument to the type of the directive. */
930 arg
= fold_convert (dirtype
, arg
);
932 maybesign
|= spec
.get_flag ('+');
934 /* True when a conversion is preceded by a prefix indicating the base
935 of the argument (octal or hexadecimal). */
936 bool maybebase
= spec
.get_flag ('#');
937 len
= tree_digits (arg
, base
, maybesign
, maybebase
);
946 /* The minimum and maximum number of bytes produced by the directive. */
951 /* The upper bound of the number of bytes is unlimited when either
952 width or precision is specified but its value is unknown, and
953 the same as the lower bound otherwise. */
954 if (width
== HOST_WIDE_INT_MIN
|| prec
== HOST_WIDE_INT_MIN
)
956 res
.range
.max
= HOST_WIDE_INT_MAX
;
963 res
.knownrange
= true;
969 else if (TREE_CODE (TREE_TYPE (arg
)) == INTEGER_TYPE
970 || TREE_CODE (TREE_TYPE (arg
)) == POINTER_TYPE
)
971 /* Determine the type of the provided non-constant argument. */
972 argtype
= TREE_TYPE (arg
);
974 /* Don't bother with invalid arguments since they likely would
975 have already been diagnosed, and disable any further checking
976 of the format string by returning [-1, -1]. */
981 /* Using either the range the non-constant argument is in, or its
982 type (either "formal" or actual), create a range of values that
983 constrain the length of output given the warning level. */
984 tree argmin
= NULL_TREE
;
985 tree argmax
= NULL_TREE
;
988 && TREE_CODE (arg
) == SSA_NAME
989 && TREE_CODE (argtype
) == INTEGER_TYPE
)
991 /* Try to determine the range of values of the integer argument
992 (range information is not available for pointers). */
994 enum value_range_type range_type
= get_range_info (arg
, &min
, &max
);
995 if (range_type
== VR_RANGE
)
997 res
.argmin
= build_int_cst (argtype
, wi::fits_uhwi_p (min
)
998 ? min
.to_uhwi () : min
.to_shwi ());
999 res
.argmax
= build_int_cst (argtype
, wi::fits_uhwi_p (max
)
1000 ? max
.to_uhwi () : max
.to_shwi ());
1002 /* For a range with a negative lower bound and a non-negative
1003 upper bound, use one to determine the minimum number of bytes
1004 on output and whichever of the two bounds that results in
1005 the greater number of bytes on output for the upper bound.
1006 For example, for ARG in the range of [-3, 123], use 123 as
1007 the upper bound for %i but -3 for %u. */
1008 if (wi::neg_p (min
) && !wi::neg_p (max
))
1010 argmin
= res
.argmin
;
1011 argmax
= res
.argmax
;
1012 int minbytes
= format_integer (spec
, res
.argmin
).range
.min
;
1013 int maxbytes
= format_integer (spec
, res
.argmax
).range
.max
;
1014 if (maxbytes
< minbytes
)
1015 argmax
= res
.argmin
;
1017 argmin
= integer_zero_node
;
1021 argmin
= res
.argmin
;
1022 argmax
= res
.argmax
;
1025 /* The argument is bounded by the known range of values
1026 determined by Value Range Propagation. */
1028 res
.knownrange
= true;
1030 else if (range_type
== VR_ANTI_RANGE
)
1032 /* Handle anti-ranges if/when bug 71690 is resolved. */
1034 else if (range_type
== VR_VARYING
)
1036 /* The argument here may be the result of promoting the actual
1037 argument to int. Try to determine the type of the actual
1038 argument before promotion and narrow down its range that
1040 gimple
*def
= SSA_NAME_DEF_STMT (arg
);
1041 if (is_gimple_assign (def
))
1043 tree_code code
= gimple_assign_rhs_code (def
);
1044 if (code
== INTEGER_CST
)
1046 arg
= gimple_assign_rhs1 (def
);
1047 return format_integer (spec
, arg
);
1050 if (code
== NOP_EXPR
)
1052 tree type
= TREE_TYPE (gimple_assign_rhs1 (def
));
1053 if (TREE_CODE (type
) == INTEGER_TYPE
1054 || TREE_CODE (type
) == POINTER_TYPE
)
1063 /* For an unknown argument (e.g., one passed to a vararg function)
1064 or one whose value range cannot be determined, create a T_MIN
1065 constant if the argument's type is signed and T_MAX otherwise,
1066 and use those to compute the range of bytes that the directive
1067 can output. When precision is specified but unknown, use zero
1068 as the minimum since it results in no bytes on output (unless
1069 width is specified to be greater than 0). */
1070 argmin
= build_int_cst (argtype
, prec
!= HOST_WIDE_INT_MIN
);
1072 int typeprec
= TYPE_PRECISION (dirtype
);
1073 int argprec
= TYPE_PRECISION (argtype
);
1075 if (argprec
< typeprec
)
1077 if (POINTER_TYPE_P (argtype
))
1078 argmax
= build_all_ones_cst (argtype
);
1079 else if (TYPE_UNSIGNED (argtype
))
1080 argmax
= TYPE_MAX_VALUE (argtype
);
1082 argmax
= TYPE_MIN_VALUE (argtype
);
1086 if (POINTER_TYPE_P (dirtype
))
1087 argmax
= build_all_ones_cst (dirtype
);
1088 else if (TYPE_UNSIGNED (dirtype
))
1089 argmax
= TYPE_MAX_VALUE (dirtype
);
1091 argmax
= TYPE_MIN_VALUE (dirtype
);
1094 res
.argmin
= argmin
;
1095 res
.argmax
= argmax
;
1098 /* Recursively compute the minimum and maximum from the known range,
1099 taking care to swap them if the lower bound results in longer
1100 output than the upper bound (e.g., in the range [-1, 0]. */
1101 res
.range
.min
= format_integer (spec
, argmin
).range
.min
;
1102 res
.range
.max
= format_integer (spec
, argmax
).range
.max
;
1104 /* The result is bounded either when the argument is determined to be
1105 (e.g., when it's within some range) or when the minimum and maximum
1106 are the same. That can happen here for example when the specified
1107 width is as wide as the greater of MIN and MAX, as would be the case
1108 with sprintf (d, "%08x", x) with a 32-bit integer x. */
1109 res
.bounded
|= res
.range
.min
== res
.range
.max
;
1111 if (res
.range
.max
< res
.range
.min
)
1113 unsigned HOST_WIDE_INT tmp
= res
.range
.max
;
1114 res
.range
.max
= res
.range
.min
;
1115 res
.range
.min
= tmp
;
1121 /* Return the number of bytes to format using the format specifier
1122 SPEC the largest value in the real floating TYPE. */
1125 format_floating_max (tree type
, char spec
, int prec
= -1)
1127 machine_mode mode
= TYPE_MODE (type
);
1129 /* IBM Extended mode. */
1130 if (MODE_COMPOSITE_P (mode
))
1133 /* Get the real type format desription for the target. */
1134 const real_format
*rfmt
= REAL_MODE_FORMAT (mode
);
1139 get_max_float (rfmt
, buf
, sizeof buf
);
1140 real_from_string (&rv
, buf
);
1143 /* Convert the GCC real value representation with the precision
1144 of the real type to the mpfr_t format with the GCC default
1145 round-to-nearest mode. */
1147 mpfr_init2 (x
, rfmt
->p
);
1148 mpfr_from_real (x
, &rv
, GMP_RNDN
);
1154 const char fmt
[] = { '%', '.', '*', 'R', spec
, '\0' };
1155 n
= mpfr_snprintf (NULL
, 0, fmt
, prec
, x
);
1159 const char fmt
[] = { '%', 'R', spec
, '\0' };
1160 n
= mpfr_snprintf (NULL
, 0, fmt
, x
);
1163 /* Return a value one greater to account for the leading minus sign. */
1167 /* Return a range representing the minimum and maximum number of bytes
1168 that the conversion specification SPEC will output for any argument
1169 given the WIDTH and PRECISION (extracted from SPEC). This function
1170 is used when the directive argument or its value isn't known. */
1173 format_floating (const conversion_spec
&spec
, int width
, int prec
)
1178 switch (spec
.modifier
)
1182 type
= double_type_node
;
1186 type
= long_double_type_node
;
1191 type
= long_double_type_node
;
1196 return fmtresult ();
1199 /* The minimum and maximum number of bytes produced by the directive. */
1202 /* Log10 of of the maximum number of exponent digits for the type. */
1205 if (REAL_MODE_FORMAT (TYPE_MODE (type
))->b
== 2)
1207 /* The base in which the exponent is represented should always
1210 const double log10_2
= .30102999566398119521;
1212 /* Compute T_MAX_EXP for base 2. */
1213 int expdigs
= REAL_MODE_FORMAT (TYPE_MODE (type
))->emax
* log10_2
;
1214 logexpdigs
= ilog (expdigs
, 10);
1217 switch (spec
.specifier
)
1222 /* The minimum output is "0x.p+0". */
1223 res
.range
.min
= 6 + (prec
> 0 ? prec
: 0);
1224 res
.range
.max
= (width
== INT_MIN
1226 : format_floating_max (type
, 'a', prec
));
1228 /* The output of "%a" is fully specified only when precision
1229 is explicitly specified and width isn't unknown. */
1230 res
.bounded
= INT_MIN
!= width
&& -1 < prec
;
1237 bool sign
= spec
.get_flag ('+') || spec
.get_flag (' ');
1238 /* The minimum output is "[-+]1.234567e+00" regardless
1239 of the value of the actual argument. */
1240 res
.range
.min
= (sign
1241 + 1 /* unit */ + (prec
< 0 ? 7 : prec
? prec
+ 1 : 0)
1243 /* Unless width is uknown the maximum output is the minimum plus
1244 sign (unless already included), plus the difference between
1245 the minimum exponent of 2 and the maximum exponent for the type. */
1246 res
.range
.max
= (width
== INT_MIN
1248 : res
.range
.min
+ !sign
+ logexpdigs
- 2);
1250 /* "%e" is fully specified and the range of bytes is bounded
1251 unless width is unknown. */
1252 res
.bounded
= INT_MIN
!= width
;
1259 /* The minimum output is "1.234567" regardless of the value
1260 of the actual argument. */
1261 res
.range
.min
= 2 + (prec
< 0 ? 6 : prec
);
1263 /* Compute the maximum just once. */
1264 static const int f_max
[] = {
1265 format_floating_max (double_type_node
, 'f'),
1266 format_floating_max (long_double_type_node
, 'f')
1268 res
.range
.max
= width
== INT_MIN
? HOST_WIDE_INT_MAX
: f_max
[ldbl
];
1270 /* "%f" is fully specified and the range of bytes is bounded
1271 unless width is unknown. */
1272 res
.bounded
= INT_MIN
!= width
;
1278 /* The minimum is the same as for '%F'. */
1279 res
.range
.min
= 2 + (prec
< 0 ? 6 : prec
);
1281 /* Compute the maximum just once. */
1282 static const int g_max
[] = {
1283 format_floating_max (double_type_node
, 'g'),
1284 format_floating_max (long_double_type_node
, 'g')
1286 res
.range
.max
= width
== INT_MIN
? HOST_WIDE_INT_MAX
: g_max
[ldbl
];
1288 /* "%g" is fully specified and the range of bytes is bounded
1289 unless width is unknown. */
1290 res
.bounded
= INT_MIN
!= width
;
1295 return fmtresult ();
1300 if (res
.range
.min
< (unsigned)width
)
1301 res
.range
.min
= width
;
1302 if (res
.range
.max
< (unsigned)width
)
1303 res
.range
.max
= width
;
1309 /* Return a range representing the minimum and maximum number of bytes
1310 that the conversion specification SPEC will write on output for the
1311 floating argument ARG. */
1314 format_floating (const conversion_spec
&spec
, tree arg
)
1316 /* Set WIDTH to -1 when it's not specified, to INT_MIN when it is
1317 specified by the asterisk to an unknown value, and otherwise to
1318 a non-negative value corresponding to the specified width. */
1322 /* The minimum and maximum number of bytes produced by the directive. */
1324 res
.constant
= arg
&& TREE_CODE (arg
) == REAL_CST
;
1326 if (spec
.have_width
)
1328 else if (spec
.star_width
)
1330 if (TREE_CODE (spec
.star_width
) == INTEGER_CST
)
1332 width
= tree_to_shwi (spec
.star_width
);
1340 if (spec
.have_precision
)
1341 prec
= spec
.precision
;
1342 else if (spec
.star_precision
)
1344 if (TREE_CODE (spec
.star_precision
) == INTEGER_CST
)
1345 prec
= tree_to_shwi (spec
.star_precision
);
1348 /* FIXME: Handle non-constant precision. */
1349 res
.range
.min
= res
.range
.max
= HOST_WIDE_INT_M1U
;
1353 else if (res
.constant
&& TOUPPER (spec
.specifier
) != 'A')
1355 /* Specify the precision explicitly since mpfr_sprintf defaults
1362 /* Set up an array to easily iterate over. */
1363 unsigned HOST_WIDE_INT
* const minmax
[] = {
1364 &res
.range
.min
, &res
.range
.max
1367 /* Get the real type format desription for the target. */
1368 const REAL_VALUE_TYPE
*rvp
= TREE_REAL_CST_PTR (arg
);
1369 const real_format
*rfmt
= REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg
)));
1371 /* Convert the GCC real value representation with the precision
1372 of the real type to the mpfr_t format with the GCC default
1373 round-to-nearest mode. */
1375 mpfr_init2 (mpfrval
, rfmt
->p
);
1376 mpfr_from_real (mpfrval
, rvp
, GMP_RNDN
);
1379 char *pfmt
= fmtstr
;
1383 for (const char *pf
= "-+ #0"; *pf
; ++pf
)
1384 if (spec
.get_flag (*pf
))
1387 /* Append width when specified and precision. */
1389 pfmt
+= sprintf (pfmt
, "%i", width
);
1391 pfmt
+= sprintf (pfmt
, ".%i", prec
);
1393 /* Append the MPFR 'R' floating type specifier (no length modifier
1394 is necessary or allowed by MPFR for mpfr_t values). */
1397 /* Save the position of the MPFR rounding specifier and skip over
1398 it. It will be set in each iteration in the loop below. */
1399 char* const rndspec
= pfmt
++;
1401 /* Append the C type specifier and nul-terminate. */
1402 *pfmt
++ = spec
.specifier
;
1405 for (int i
= 0; i
!= sizeof minmax
/ sizeof *minmax
; ++i
)
1407 /* Use the MPFR rounding specifier to round down in the first
1408 iteration and then up. In most but not all cases this will
1409 result in the same number of bytes. */
1412 /* Format it and store the result in the corresponding
1413 member of the result struct. */
1414 *minmax
[i
] = mpfr_snprintf (NULL
, 0, fmtstr
, mpfrval
);
1417 /* The range of output is known even if the result isn't bounded. */
1418 if (width
== INT_MIN
)
1420 res
.knownrange
= false;
1421 res
.range
.max
= HOST_WIDE_INT_MAX
;
1424 res
.knownrange
= true;
1426 /* The output of all directives except "%a" is fully specified
1427 and so the result is bounded unless it exceeds INT_MAX.
1428 For "%a" the output is fully specified only when precision
1429 is explicitly specified. */
1430 res
.bounded
= (res
.knownrange
1431 && (TOUPPER (spec
.specifier
) != 'A'
1432 || (0 <= prec
&& (unsigned) prec
< target_int_max ()))
1433 && res
.range
.min
< target_int_max ());
1438 return format_floating (spec
, width
, prec
);
1441 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1442 strings referenced by the expression STR, or (-1, -1) when not known.
1443 Used by the format_string function below. */
1446 get_string_length (tree str
)
1449 return fmtresult ();
1451 if (tree slen
= c_strlen (str
, 1))
1453 /* Simply return the length of the string. */
1455 res
.range
.min
= res
.range
.max
= tree_to_shwi (slen
);
1457 res
.constant
= true;
1458 res
.knownrange
= true;
1462 /* Determine the length of the shortest and longest string referenced
1463 by STR. Strings of unknown lengths are bounded by the sizes of
1464 arrays that subexpressions of STR may refer to. Pointers that
1465 aren't known to point any such arrays result in LENRANGE[1] set
1468 get_range_strlen (str
, lenrange
);
1470 if (lenrange
[0] || lenrange
[1])
1474 res
.range
.min
= (tree_fits_uhwi_p (lenrange
[0])
1475 ? tree_to_uhwi (lenrange
[0]) : 1 < warn_format_length
);
1476 res
.range
.max
= (tree_fits_uhwi_p (lenrange
[1])
1477 ? tree_to_uhwi (lenrange
[1]) : HOST_WIDE_INT_M1U
);
1479 /* Set RES.BOUNDED to true if and only if all strings referenced
1480 by STR are known to be bounded (though not necessarily by their
1481 actual length but perhaps by their maximum possible length). */
1482 res
.bounded
= res
.range
.max
< target_int_max ();
1483 res
.knownrange
= res
.bounded
;
1485 /* Set RES.CONSTANT to false even though that may be overly
1486 conservative in rare cases like: 'x ? a : b' where a and
1487 b have the same lengths and consist of the same characters. */
1488 res
.constant
= false;
1493 return get_string_length (NULL_TREE
);
1496 /* Return the minimum and maximum number of characters formatted
1497 by the '%c' and '%s' format directives and ther wide character
1498 forms for the argument ARG. ARG can be null (for functions
1499 such as vsprinf). */
1502 format_string (const conversion_spec
&spec
, tree arg
)
1504 /* Set WIDTH and PRECISION based on the specification. */
1505 HOST_WIDE_INT width
;
1507 get_width_and_precision (spec
, &width
, &prec
);
1511 /* The maximum number of bytes for an unknown wide character argument
1512 to a "%lc" directive adjusted for precision but not field width.
1513 6 is the longest UTF-8 sequence for a single wide character. */
1514 const unsigned HOST_WIDE_INT max_bytes_for_unknown_wc
1515 = (0 <= prec
? prec
: 1 < warn_format_length
? 6 : 1);
1517 /* The maximum number of bytes for an unknown string argument to either
1518 a "%s" or "%ls" directive adjusted for precision but not field width. */
1519 const unsigned HOST_WIDE_INT max_bytes_for_unknown_str
1520 = (0 <= prec
? prec
: 1 < warn_format_length
);
1522 /* The result is bounded unless overriddden for a non-constant string
1523 of an unknown length. */
1524 bool bounded
= true;
1526 if (spec
.specifier
== 'c')
1528 if (spec
.modifier
== FMT_LEN_l
)
1530 /* Positive if the argument is a wide NUL character? */
1531 int nul
= (arg
&& TREE_CODE (arg
) == INTEGER_CST
1532 ? integer_zerop (arg
) : -1);
1534 /* A '%lc' directive is the same as '%ls' for a two element
1535 wide string character with the second element of NUL, so
1536 when the character is unknown the minimum number of bytes
1537 is the smaller of either 0 (at level 1) or 1 (at level 2)
1538 and WIDTH, and the maximum is MB_CUR_MAX in the selected
1539 locale, which is unfortunately, unknown. */
1540 res
.range
.min
= 1 == warn_format_length
? !nul
: nul
< 1;
1541 res
.range
.max
= max_bytes_for_unknown_wc
;
1542 /* The range above is good enough to issue warnings but not
1543 for value range propagation, so clear BOUNDED. */
1544 res
.bounded
= false;
1548 /* A plain '%c' directive. Its ouput is exactly 1. */
1549 res
.range
.min
= res
.range
.max
= 1;
1551 res
.knownrange
= true;
1552 res
.constant
= arg
&& TREE_CODE (arg
) == INTEGER_CST
;
1555 else /* spec.specifier == 's' */
1557 /* Compute the range the argument's length can be in. */
1558 fmtresult slen
= get_string_length (arg
);
1561 gcc_checking_assert (slen
.range
.min
== slen
.range
.max
);
1563 /* A '%s' directive with a string argument with constant length. */
1564 res
.range
= slen
.range
;
1566 /* The output of "%s" and "%ls" directives with a constant
1567 string is in a known range unless width of an unknown value
1568 is specified. For "%s" it is the length of the string. For
1569 "%ls" it is in the range [length, length * MB_LEN_MAX].
1570 (The final range can be further constrained by width and
1571 precision but it's always known.) */
1572 res
.knownrange
= -1 < width
;
1574 if (spec
.modifier
== FMT_LEN_l
)
1578 if (warn_format_length
> 1)
1580 /* Leave the minimum number of bytes the wide string
1581 converts to equal to its length and set the maximum
1582 to the worst case length which is the string length
1583 multiplied by MB_LEN_MAX. */
1585 /* It's possible to be smarter about computing the maximum
1586 by scanning the wide string for any 8-bit characters and
1587 if it contains none, using its length for the maximum.
1588 Even though this would be simple to do it's unlikely to
1589 be worth it when dealing with wide characters. */
1590 res
.range
.max
*= target_mb_len_max
;
1593 /* For a wide character string, use precision as the maximum
1594 even if precision is greater than the string length since
1595 the number of bytes the string converts to may be greater
1596 (due to MB_CUR_MAX). */
1598 res
.range
.max
= prec
;
1600 else if (0 <= width
)
1602 /* The output of a "%s" directive with a constant argument
1603 and constant or no width is bounded. It is constant if
1604 precision is either not specified or it is specified and
1605 its value is known. */
1607 res
.constant
= prec
!= HOST_WIDE_INT_MIN
;
1609 else if (width
== HOST_WIDE_INT_MIN
)
1611 /* Specified but unknown width makes the output unbounded. */
1612 res
.range
.max
= HOST_WIDE_INT_MAX
;
1615 if (0 <= prec
&& (unsigned HOST_WIDE_INT
)prec
< res
.range
.min
)
1617 res
.range
.min
= prec
;
1618 res
.range
.max
= prec
;
1620 else if (prec
== HOST_WIDE_INT_MIN
)
1622 /* When precision is specified but not known the lower
1623 bound is assumed to be as low as zero. */
1629 /* For a '%s' and '%ls' directive with a non-constant string,
1630 the minimum number of characters is the greater of WIDTH
1631 and either 0 in mode 1 or the smaller of PRECISION and 1
1632 in mode 2, and the maximum is PRECISION or -1 to disable
1637 if (slen
.range
.min
>= target_int_max ())
1639 else if ((unsigned HOST_WIDE_INT
)prec
< slen
.range
.min
)
1640 slen
.range
.min
= prec
;
1642 if ((unsigned HOST_WIDE_INT
)prec
< slen
.range
.max
1643 || slen
.range
.max
>= target_int_max ())
1644 slen
.range
.max
= prec
;
1646 else if (slen
.range
.min
>= target_int_max ())
1648 slen
.range
.min
= max_bytes_for_unknown_str
;
1649 slen
.range
.max
= max_bytes_for_unknown_str
;
1653 res
.range
= slen
.range
;
1655 /* The output is considered bounded when a precision has been
1656 specified to limit the number of bytes or when the number
1657 of bytes is known or contrained to some range. */
1658 res
.bounded
= 0 <= prec
|| slen
.bounded
;
1659 res
.knownrange
= slen
.knownrange
;
1660 res
.constant
= false;
1664 /* Adjust the lengths for field width. */
1667 if (res
.range
.min
< (unsigned HOST_WIDE_INT
)width
)
1668 res
.range
.min
= width
;
1670 if (res
.range
.max
< (unsigned HOST_WIDE_INT
)width
)
1671 res
.range
.max
= width
;
1673 /* Adjust BOUNDED if width happens to make them equal. */
1674 if (res
.range
.min
== res
.range
.max
&& res
.range
.min
< target_int_max ()
1679 /* When precision is specified the range of characters on output
1680 is known to be bounded by it. */
1681 if (-1 < width
&& -1 < prec
)
1682 res
.knownrange
= true;
1687 /* Compute the length of the output resulting from the conversion
1688 specification SPEC with the argument ARG in a call described by INFO
1689 and update the overall result of the call in *RES. The format directive
1690 corresponding to SPEC starts at CVTBEG and is CVTLEN characters long. */
1693 format_directive (const pass_sprintf_length::call_info
&info
,
1694 format_result
*res
, const char *cvtbeg
, size_t cvtlen
,
1695 const conversion_spec
&spec
, tree arg
)
1697 /* Offset of the beginning of the directive from the beginning
1698 of the format string. */
1699 size_t offset
= cvtbeg
- info
.fmtstr
;
1701 /* Create a location for the whole directive from the % to the format
1703 substring_loc
dirloc (info
.fmtloc
, TREE_TYPE (info
.format
),
1704 offset
, offset
, offset
+ cvtlen
- 1);
1706 /* Also create a location range for the argument if possible.
1707 This doesn't work for integer literals or function calls. */
1708 source_range argrange
;
1709 source_range
*pargrange
;
1710 if (arg
&& CAN_HAVE_LOCATION_P (arg
))
1712 argrange
= EXPR_LOCATION_RANGE (arg
);
1713 pargrange
= &argrange
;
1718 /* Bail when there is no function to compute the output length,
1719 or when minimum length checking has been disabled. */
1720 if (!spec
.fmtfunc
|| res
->number_chars_min
>= HOST_WIDE_INT_MAX
)
1723 /* Compute the (approximate) length of the formatted output. */
1724 fmtresult fmtres
= spec
.fmtfunc (spec
, arg
);
1726 /* The overall result is bounded and constant only if the output
1727 of every directive is bounded and constant, respectively. */
1728 res
->bounded
&= fmtres
.bounded
;
1729 res
->constant
&= fmtres
.constant
;
1731 /* Record whether the output of all directives is known to be
1732 bounded by some maximum, implying that their arguments are
1733 either known exactly or determined to be in a known range
1734 or, for strings, limited by the upper bounds of the arrays
1736 res
->knownrange
&= fmtres
.knownrange
;
1738 if (!fmtres
.knownrange
)
1740 /* Only when the range is known, check it against the host value
1741 of INT_MAX. Otherwise the range doesn't correspond to known
1742 values of the argument. */
1743 if (fmtres
.range
.max
>= target_int_max ())
1745 /* Normalize the MAX counter to avoid having to deal with it
1746 later. The counter can be less than HOST_WIDE_INT_M1U
1747 when compiling for an ILP32 target on an LP64 host. */
1748 fmtres
.range
.max
= HOST_WIDE_INT_M1U
;
1749 /* Disable exact and maximum length checking after a failure
1750 to determine the maximum number of characters (for example
1751 for wide characters or wide character strings) but continue
1752 tracking the minimum number of characters. */
1753 res
->number_chars_max
= HOST_WIDE_INT_M1U
;
1754 res
->number_chars
= HOST_WIDE_INT_M1U
;
1757 if (fmtres
.range
.min
>= target_int_max ())
1759 /* Disable exact length checking after a failure to determine
1760 even the minimum number of characters (it shouldn't happen
1761 except in an error) but keep tracking the minimum and maximum
1762 number of characters. */
1763 res
->number_chars
= HOST_WIDE_INT_M1U
;
1768 /* Compute the number of available bytes in the destination. There
1769 must always be at least one byte of space for the terminating
1770 NUL that's appended after the format string has been processed. */
1771 unsigned HOST_WIDE_INT navail
= min_bytes_remaining (info
.objsize
, *res
);
1773 if (fmtres
.range
.min
< fmtres
.range
.max
)
1775 /* The result is a range (i.e., it's inexact). */
1778 bool warned
= false;
1780 if (navail
< fmtres
.range
.min
)
1782 /* The minimum directive output is longer than there is
1783 room in the destination. */
1784 if (fmtres
.range
.min
== fmtres
.range
.max
)
1788 ? G_("%<%.*s%> directive output truncated writing "
1789 "%wu bytes into a region of size %wu")
1790 : G_("%<%.*s%> directive writing %wu bytes "
1791 "into a region of size %wu"));
1792 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1793 OPT_Wformat_length_
, fmtstr
,
1794 (int)cvtlen
, cvtbeg
, fmtres
.range
.min
,
1797 else if (fmtres
.range
.max
< HOST_WIDE_INT_MAX
)
1801 ? G_("%<%.*s%> directive output truncated writing "
1802 "between %wu and %wu bytes into a region of "
1804 : G_("%<%.*s%> directive writing between %wu and "
1805 "%wu bytes into a region of size %wu"));
1806 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1807 OPT_Wformat_length_
, fmtstr
,
1808 (int)cvtlen
, cvtbeg
,
1809 fmtres
.range
.min
, fmtres
.range
.max
, navail
);
1815 ? G_("%<%.*s%> directive output truncated writing "
1816 "%wu or more bytes into a region of size %wu")
1817 : G_("%<%.*s%> directive writing %wu or more bytes "
1818 "into a region of size %wu"));
1819 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1820 OPT_Wformat_length_
, fmtstr
,
1821 (int)cvtlen
, cvtbeg
,
1822 fmtres
.range
.min
, navail
);
1825 else if (navail
< fmtres
.range
.max
1826 && (((spec
.specifier
== 's'
1827 && fmtres
.range
.max
< HOST_WIDE_INT_MAX
)
1828 /* && (spec.precision || spec.star_precision) */)
1829 || 1 < warn_format_length
))
1831 /* The maximum directive output is longer than there is
1832 room in the destination and the output length is either
1833 explicitly constrained by the precision (for strings)
1834 or the warning level is greater than 1. */
1835 if (fmtres
.range
.max
>= HOST_WIDE_INT_MAX
)
1839 ? G_("%<%.*s%> directive output may be truncated "
1840 "writing %wu or more bytes a region of size %wu")
1841 : G_("%<%.*s%> directive writing %wu or more bytes "
1842 "into a region of size %wu"));
1843 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1844 OPT_Wformat_length_
, fmtstr
,
1845 (int)cvtlen
, cvtbeg
,
1846 fmtres
.range
.min
, navail
);
1852 ? G_("%<%.*s%> directive output may be truncated "
1853 "writing between %wu and %wu bytes into a region "
1855 : G_("%<%.*s%> directive writing between %wu and %wu "
1856 "bytes into a region of size %wu"));
1857 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1858 OPT_Wformat_length_
, fmtstr
,
1859 (int)cvtlen
, cvtbeg
,
1860 fmtres
.range
.min
, fmtres
.range
.max
,
1865 res
->warned
|= warned
;
1867 if (warned
&& fmtres
.argmin
)
1869 if (fmtres
.argmin
== fmtres
.argmax
)
1870 inform (info
.fmtloc
, "directive argument %qE", fmtres
.argmin
);
1871 else if (fmtres
.bounded
)
1872 inform (info
.fmtloc
, "directive argument in the range [%E, %E]",
1873 fmtres
.argmin
, fmtres
.argmax
);
1875 inform (info
.fmtloc
,
1876 "using the range [%qE, %qE] for directive argument",
1877 fmtres
.argmin
, fmtres
.argmax
);
1881 /* Disable exact length checking but adjust the minimum and maximum. */
1882 res
->number_chars
= HOST_WIDE_INT_M1U
;
1883 if (res
->number_chars_max
< HOST_WIDE_INT_MAX
1884 && fmtres
.range
.max
< HOST_WIDE_INT_MAX
)
1885 res
->number_chars_max
+= fmtres
.range
.max
;
1887 res
->number_chars_min
+= fmtres
.range
.min
;
1891 if (!res
->warned
&& fmtres
.range
.min
> 0 && navail
< fmtres
.range
.min
)
1895 ? (1 < fmtres
.range
.min
1896 ? G_("%<%.*s%> directive output truncated while writing "
1897 "%wu bytes into a region of size %wu")
1898 : G_("%<%.*s%> directive output truncated while writing "
1899 "%wu byte into a region of size %wu"))
1900 : (1 < fmtres
.range
.min
1901 ? G_("%<%.*s%> directive writing %wu bytes "
1902 "into a region of size %wu")
1903 : G_("%<%.*s%> directive writing %wu byte "
1904 "into a region of size %wu")));
1906 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1907 OPT_Wformat_length_
, fmtstr
,
1908 (int)cvtlen
, cvtbeg
, fmtres
.range
.min
,
1911 *res
+= fmtres
.range
.min
;
1914 /* Has the minimum directive output length exceeded the maximum
1915 of 4095 bytes required to be supported? */
1916 bool minunder4k
= fmtres
.range
.min
< 4096;
1917 if (!minunder4k
|| fmtres
.range
.max
> 4095)
1918 res
->under4k
= false;
1920 if (!res
->warned
&& 1 < warn_format_length
1921 && (!minunder4k
|| fmtres
.range
.max
> 4095))
1923 /* The directive output may be longer than the maximum required
1924 to be handled by an implementation according to 7.21.6.1, p15
1925 of C11. Warn on this only at level 2 but remember this and
1926 prevent folding the return value when done. This allows for
1927 the possibility of the actual libc call failing due to ENOMEM
1928 (like Glibc does under some conditions). */
1930 if (fmtres
.range
.min
== fmtres
.range
.max
)
1931 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1932 OPT_Wformat_length_
,
1933 "%<%.*s%> directive output of %wu bytes exceeds "
1934 "minimum required size of 4095",
1935 (int)cvtlen
, cvtbeg
, fmtres
.range
.min
);
1940 ? G_("%<%.*s%> directive output between %qu and %wu "
1941 "bytes may exceed minimum required size of 4095")
1942 : G_("%<%.*s%> directive output between %qu and %wu "
1943 "bytes exceeds minimum required size of 4095"));
1945 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1946 OPT_Wformat_length_
, fmtstr
,
1947 (int)cvtlen
, cvtbeg
,
1948 fmtres
.range
.min
, fmtres
.range
.max
);
1952 /* Has the minimum directive output length exceeded INT_MAX? */
1953 bool exceedmin
= res
->number_chars_min
> target_int_max ();
1957 || (1 < warn_format_length
1958 && res
->number_chars_max
> target_int_max ())))
1960 /* The directive output causes the total length of output
1961 to exceed INT_MAX bytes. */
1963 if (fmtres
.range
.min
== fmtres
.range
.max
)
1964 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1965 OPT_Wformat_length_
,
1966 "%<%.*s%> directive output of %wu bytes causes "
1967 "result to exceed %<INT_MAX%>",
1968 (int)cvtlen
, cvtbeg
, fmtres
.range
.min
);
1973 ? G_ ("%<%.*s%> directive output between %wu and %wu "
1974 "bytes causes result to exceed %<INT_MAX%>")
1975 : G_ ("%<%.*s%> directive output between %wu and %wu "
1976 "bytes may cause result to exceed %<INT_MAX%>"));
1977 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1978 OPT_Wformat_length_
, fmtstr
,
1979 (int)cvtlen
, cvtbeg
,
1980 fmtres
.range
.min
, fmtres
.range
.max
);
1985 /* Account for the number of bytes between BEG and END (or between
1986 BEG + strlen (BEG) when END is null) in the format string in a call
1987 to a formatted output function described by INFO. Reflect the count
1988 in RES and issue warnings as appropriate. */
1991 add_bytes (const pass_sprintf_length::call_info
&info
,
1992 const char *beg
, const char *end
, format_result
*res
)
1994 if (res
->number_chars_min
>= HOST_WIDE_INT_MAX
)
1997 /* The number of bytes to output is the number of bytes between
1998 the end of the last directive and the beginning of the next
1999 one if it exists, otherwise the number of characters remaining
2000 in the format string plus 1 for the terminating NUL. */
2001 size_t nbytes
= end
? end
- beg
: strlen (beg
) + 1;
2003 /* Return if there are no bytes to add at this time but there are
2004 directives remaining in the format string. */
2008 /* Compute the range of available bytes in the destination. There
2009 must always be at least one byte left for the terminating NUL
2010 that's appended after the format string has been processed. */
2011 result_range avail_range
= bytes_remaining (info
.objsize
, *res
);
2013 /* If issuing a diagnostic (only when one hasn't already been issued),
2014 distinguish between a possible overflow ("may write") and a certain
2015 overflow somewhere "past the end." (Ditto for truncation.)
2016 KNOWNRANGE is used to warn even at level 1 about possibly writing
2017 past the end or truncation due to strings of unknown lengths that
2018 are bounded by the arrays they are known to refer to. */
2020 && (avail_range
.max
< nbytes
2021 || ((res
->knownrange
|| 1 < warn_format_length
)
2022 && avail_range
.min
< nbytes
)))
2024 /* Set NAVAIL to the number of available bytes used to decide
2025 whether or not to issue a warning below. The exact kind of
2026 warning will depend on AVAIL_RANGE. */
2027 unsigned HOST_WIDE_INT navail
= avail_range
.max
;
2028 if (nbytes
<= navail
&& avail_range
.min
< HOST_WIDE_INT_MAX
2029 && (res
->knownrange
|| 1 < warn_format_length
))
2030 navail
= avail_range
.min
;
2032 /* Compute the offset of the first format character that is beyond
2033 the end of the destination region and the length of the rest of
2034 the format string from that point on. */
2035 unsigned HOST_WIDE_INT off
2036 = (unsigned HOST_WIDE_INT
)(beg
- info
.fmtstr
) + navail
;
2038 size_t len
= strlen (info
.fmtstr
+ off
);
2040 /* Create a location that underscores the substring of the format
2041 string that is or may be written past the end (or is or may be
2042 truncated), pointing the caret at the first character of the
2045 (info
.fmtloc
, TREE_TYPE (info
.format
), off
, len
? off
: 0,
2048 /* Is the output of the last directive the result of the argument
2049 being within a range whose lower bound would fit in the buffer
2050 but the upper bound would not? If so, use the word "may" to
2051 indicate that the overflow/truncation may (but need not) happen. */
2053 = (res
->number_chars_min
< res
->number_chars_max
2054 && res
->number_chars_min
< info
.objsize
);
2056 if (!end
&& ((nbytes
- navail
) == 1 || boundrange
))
2058 /* There is room for the rest of the format string but none
2059 for the terminating nul. */
2061 = (info
.bounded
// Snprintf and the like.
2063 ? G_("output may be truncated before the last format character"
2064 : "output truncated before the last format character"))
2066 ? G_("may write a terminating nul past the end "
2067 "of the destination")
2068 : G_("writing a terminating nul past the end "
2069 "of the destination")));
2071 res
->warned
= fmtwarn (loc
, NULL
, NULL
, OPT_Wformat_length_
, text
);
2075 /* There isn't enough room for 1 or more characters that remain
2076 to copy from the format string. */
2078 = (info
.bounded
// Snprintf and the like.
2080 ? G_("output may be truncated at or before format character "
2081 "%qc at offset %wu")
2082 : G_("output truncated at format character %qc at offset %wu"))
2083 : (res
->number_chars
>= HOST_WIDE_INT_MAX
2084 ? G_("may write format character %#qc at offset %wu past "
2085 "the end of the destination")
2086 : G_("writing format character %#qc at offset %wu past "
2087 "the end of the destination")));
2089 res
->warned
= fmtwarn (loc
, NULL
, NULL
, OPT_Wformat_length_
,
2090 text
, info
.fmtstr
[off
], off
);
2094 if (res
->warned
&& !end
&& info
.objsize
< HOST_WIDE_INT_MAX
)
2096 /* If a warning has been issued for buffer overflow or truncation
2097 (but not otherwise) help the user figure out how big a buffer
2100 location_t callloc
= gimple_location (info
.callstmt
);
2102 unsigned HOST_WIDE_INT min
= res
->number_chars_min
;
2103 unsigned HOST_WIDE_INT max
= res
->number_chars_max
;
2104 unsigned HOST_WIDE_INT exact
2105 = (res
->number_chars
< HOST_WIDE_INT_MAX
2106 ? res
->number_chars
: res
->number_chars_min
);
2108 if (min
< max
&& max
< HOST_WIDE_INT_MAX
)
2110 "format output between %wu and %wu bytes into "
2111 "a destination of size %wu",
2112 min
+ nbytes
, max
+ nbytes
, info
.objsize
);
2115 (nbytes
+ exact
== 1
2116 ? G_("format output %wu byte into a destination of size %wu")
2117 : G_("format output %wu bytes into a destination of size %wu")),
2118 nbytes
+ exact
, info
.objsize
);
2121 /* Add the number of bytes and then check for INT_MAX overflow. */
2124 /* Has the minimum output length minus the terminating nul exceeded
2126 bool exceedmin
= (res
->number_chars_min
- !end
) > target_int_max ();
2130 || (1 < warn_format_length
2131 && (res
->number_chars_max
- !end
) > target_int_max ())))
2133 /* The function's output exceeds INT_MAX bytes. */
2135 /* Set NAVAIL to the number of available bytes used to decide
2136 whether or not to issue a warning below. The exact kind of
2137 warning will depend on AVAIL_RANGE. */
2138 unsigned HOST_WIDE_INT navail
= avail_range
.max
;
2139 if (nbytes
<= navail
&& avail_range
.min
< HOST_WIDE_INT_MAX
2140 && (res
->bounded
|| 1 < warn_format_length
))
2141 navail
= avail_range
.min
;
2143 /* Compute the offset of the first format character that is beyond
2144 the end of the destination region and the length of the rest of
2145 the format string from that point on. */
2146 unsigned HOST_WIDE_INT off
= (unsigned HOST_WIDE_INT
)(beg
- info
.fmtstr
);
2147 if (navail
< HOST_WIDE_INT_MAX
)
2150 size_t len
= strlen (info
.fmtstr
+ off
);
2153 (info
.fmtloc
, TREE_TYPE (info
.format
), off
- !len
, len
? off
: 0,
2156 if (res
->number_chars_min
== res
->number_chars_max
)
2157 res
->warned
= fmtwarn (loc
, NULL
, NULL
,
2158 OPT_Wformat_length_
,
2159 "output of %wu bytes causes "
2160 "result to exceed %<INT_MAX%>",
2161 res
->number_chars_min
- !end
);
2166 ? G_ ("output between %wu and %wu bytes causes "
2167 "result to exceed %<INT_MAX%>")
2168 : G_ ("output between %wu and %wu bytes may cause "
2169 "result to exceed %<INT_MAX%>"));
2170 res
->warned
= fmtwarn (loc
, NULL
, NULL
, OPT_Wformat_length_
,
2172 res
->number_chars_min
- !end
,
2173 res
->number_chars_max
- !end
);
2178 #pragma GCC diagnostic pop
2180 /* Compute the length of the output resulting from the call to a formatted
2181 output function described by INFO and store the result of the call in
2182 *RES. Issue warnings for detected past the end writes. Return true
2183 if the complete format string has been processed and *RES can be relied
2184 on, false otherwise (e.g., when a unknown or unhandled directive was seen
2185 that caused the processing to be terminated early). */
2188 pass_sprintf_length::compute_format_length (const call_info
&info
,
2191 /* The variadic argument counter. */
2192 unsigned argno
= info
.argidx
;
2194 /* Reset exact, minimum, and maximum character counters. */
2195 res
->number_chars
= res
->number_chars_min
= res
->number_chars_max
= 0;
2197 /* No directive has been seen yet so the length of output is bounded
2198 by the known range [0, 0] and constant (with no conversion producing
2199 more than 4K bytes) until determined otherwise. */
2200 res
->bounded
= true;
2201 res
->knownrange
= true;
2202 res
->constant
= true;
2203 res
->under4k
= true;
2204 res
->floating
= false;
2205 res
->warned
= false;
2207 const char *pf
= info
.fmtstr
;
2211 /* The beginning of the next format directive. */
2212 const char *dir
= strchr (pf
, '%');
2214 /* Add the number of bytes between the end of the last directive
2215 and either the next if one exists, or the end of the format
2217 add_bytes (info
, pf
, dir
, res
);
2226 /* Incomplete directive. */
2230 conversion_spec spec
= conversion_spec ();
2232 /* POSIX numbered argument index or zero when none. */
2233 unsigned dollar
= 0;
2237 /* This could be either a POSIX positional argument, the '0'
2238 flag, or a width, depending on what follows. Store it as
2239 width and sort it out later after the next character has
2242 spec
.width
= strtol (pf
, &end
, 10);
2243 spec
.have_width
= true;
2246 else if ('*' == *pf
)
2248 /* Similarly to the block above, this could be either a POSIX
2249 positional argument or a width, depending on what follows. */
2250 if (gimple_call_num_args (info
.callstmt
) <= argno
)
2253 spec
.star_width
= gimple_call_arg (info
.callstmt
, argno
++);
2259 /* Handle the POSIX dollar sign which references the 1-based
2260 positional argument number. */
2261 if (spec
.have_width
)
2262 dollar
= spec
.width
+ info
.argidx
;
2263 else if (spec
.star_width
2264 && TREE_CODE (spec
.star_width
) == INTEGER_CST
)
2265 dollar
= spec
.width
+ tree_to_shwi (spec
.star_width
);
2267 /* Bail when the numbered argument is out of range (it will
2268 have already been diagnosed by -Wformat). */
2270 || dollar
== info
.argidx
2271 || dollar
> gimple_call_num_args (info
.callstmt
))
2276 spec
.star_width
= NULL_TREE
;
2277 spec
.have_width
= false;
2281 if (dollar
|| !spec
.star_width
)
2283 if (spec
.have_width
)
2285 if (spec
.width
== 0)
2287 /* The '0' that has been interpreted as a width above is
2288 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
2289 and continue processing other flags. */
2290 spec
.have_width
= false;
2291 spec
.set_flag ('0');
2295 /* (Non-zero) width has been seen. The next character
2296 is either a period or a digit. */
2297 goto start_precision
;
2300 /* When either '$' has been seen, or width has not been seen,
2301 the next field is the optional flags followed by an optional
2311 spec
.set_flag (*pf
++);
2323 spec
.width
= strtol (pf
, &end
, 10);
2324 spec
.have_width
= true;
2327 else if ('*' == *pf
)
2329 spec
.star_width
= gimple_call_arg (info
.callstmt
, argno
++);
2332 else if ('\'' == *pf
)
2334 /* The POSIX apostrophe indicating a numeric grouping
2335 in the current locale. Even though it's possible to
2336 estimate the upper bound on the size of the output
2337 based on the number of digits it probably isn't worth
2351 spec
.precision
= strtol (pf
, &end
, 10);
2352 spec
.have_precision
= true;
2355 else if ('*' == *pf
)
2357 spec
.star_precision
= gimple_call_arg (info
.callstmt
, argno
++);
2362 /* The decimal precision or the asterisk are optional.
2363 When neither is specified it's taken to be zero. */
2365 spec
.have_precision
= true;
2375 spec
.modifier
= FMT_LEN_hh
;
2378 spec
.modifier
= FMT_LEN_h
;
2383 spec
.modifier
= FMT_LEN_j
;
2388 spec
.modifier
= FMT_LEN_L
;
2396 spec
.modifier
= FMT_LEN_ll
;
2399 spec
.modifier
= FMT_LEN_l
;
2404 spec
.modifier
= FMT_LEN_t
;
2409 spec
.modifier
= FMT_LEN_z
;
2416 /* Handle a sole '%' character the same as "%%" but since it's
2417 undefined prevent the result from being folded. */
2420 res
->bounded
= false;
2423 spec
.fmtfunc
= format_percent
;
2434 res
->floating
= true;
2435 spec
.fmtfunc
= format_floating
;
2444 spec
.fmtfunc
= format_integer
;
2448 /* The %p output is implementation-defined. It's possible
2449 to determine this format but due to extensions (especially
2450 those of the Linux kernel -- see bug 78512) the first %p
2451 in the format string disables any further processing. */
2460 spec
.fmtfunc
= format_string
;
2464 /* Unknown conversion specification. */
2468 spec
.specifier
= *pf
++;
2470 /* Compute the length of the format directive. */
2471 size_t dirlen
= pf
- dir
;
2473 /* Extract the argument if the directive takes one and if it's
2474 available (e.g., the function doesn't take a va_list). Treat
2475 missing arguments the same as va_list, even though they will
2476 have likely already been diagnosed by -Wformat. */
2477 tree arg
= NULL_TREE
;
2478 if (spec
.specifier
!= '%'
2479 && argno
< gimple_call_num_args (info
.callstmt
))
2480 arg
= gimple_call_arg (info
.callstmt
, dollar
? dollar
: argno
++);
2482 ::format_directive (info
, res
, dir
, dirlen
, spec
, arg
);
2485 /* Complete format string was processed (with or without warnings). */
2489 /* Return the size of the object referenced by the expression DEST if
2490 available, or -1 otherwise. */
2492 static unsigned HOST_WIDE_INT
2493 get_destination_size (tree dest
)
2495 /* Use __builtin_object_size to determine the size of the destination
2496 object. When optimizing, determine the smallest object (such as
2497 a member array as opposed to the whole enclosing object), otherwise
2498 use type-zero object size to determine the size of the enclosing
2499 object (the function fails without optimization in this type). */
2500 int ost
= optimize
> 0;
2501 unsigned HOST_WIDE_INT size
;
2502 if (compute_builtin_object_size (dest
, ost
, &size
))
2505 return HOST_WIDE_INT_M1U
;
2508 /* Given a suitable result RES of a call to a formatted output function
2509 described by INFO, substitute the result for the return value of
2510 the call. The result is suitable if the number of bytes it represents
2511 is known and exact. A result that isn't suitable for substitution may
2512 have its range set to the range of return values, if that is known. */
2515 try_substitute_return_value (gimple_stmt_iterator
*gsi
,
2516 const pass_sprintf_length::call_info
&info
,
2517 const format_result
&res
)
2519 tree lhs
= gimple_get_lhs (info
.callstmt
);
2521 /* Avoid the return value optimization when the behavior of the call
2522 is undefined either because any directive may have produced 4K or
2523 more of output, or the return value exceeds INT_MAX, or because
2524 the output overflows the destination object (but leave it enabled
2525 when the function is bounded because then the behavior is well-
2527 if (lhs
&& res
.bounded
&& res
.under4k
2528 && (info
.bounded
|| res
.number_chars
<= info
.objsize
)
2529 && res
.number_chars
- 1 <= target_int_max ())
2531 tree cst
= build_int_cst (integer_type_node
, res
.number_chars
- 1);
2535 /* Replace the call to the bounded function with a zero size
2536 (e.g., snprintf(0, 0, "%i", 123) with the constant result
2537 of the function minus 1 for the terminating NUL which
2538 the function's return value does not include. */
2539 if (!update_call_from_tree (gsi
, cst
))
2540 gimplify_and_update_call_from_tree (gsi
, cst
);
2541 gimple
*callstmt
= gsi_stmt (*gsi
);
2542 update_stmt (callstmt
);
2546 /* Replace the left-hand side of the call with the constant
2547 result of the formatted function minus 1 for the terminating
2548 NUL which the function's return value does not include. */
2549 gimple_call_set_lhs (info
.callstmt
, NULL_TREE
);
2550 gimple
*g
= gimple_build_assign (lhs
, cst
);
2551 gsi_insert_after (gsi
, g
, GSI_NEW_STMT
);
2552 update_stmt (info
.callstmt
);
2557 location_t callloc
= gimple_location (info
.callstmt
);
2558 fprintf (dump_file
, "On line %i substituting ",
2559 LOCATION_LINE (callloc
));
2560 print_generic_expr (dump_file
, cst
, dump_flags
);
2561 fprintf (dump_file
, " for ");
2562 print_generic_expr (dump_file
, info
.func
, dump_flags
);
2563 fprintf (dump_file
, " %s (output %s).\n",
2564 info
.nowrite
? "call" : "return value",
2565 res
.constant
? "constant" : "variable");
2570 unsigned HOST_WIDE_INT maxbytes
;
2574 && ((maxbytes
= res
.number_chars
- 1) <= target_int_max ()
2575 || (res
.number_chars_min
- 1 <= target_int_max ()
2576 && (maxbytes
= res
.number_chars_max
- 1) <= target_int_max ()))
2577 && (info
.bounded
|| maxbytes
< info
.objsize
))
2579 /* If the result is in a valid range bounded by the size of
2580 the destination set it so that it can be used for subsequent
2582 int prec
= TYPE_PRECISION (integer_type_node
);
2584 if (res
.number_chars
< target_int_max () && res
.under4k
)
2586 wide_int num
= wi::shwi (res
.number_chars
- 1, prec
);
2587 set_range_info (lhs
, VR_RANGE
, num
, num
);
2589 else if (res
.number_chars_min
< target_int_max ()
2590 && res
.number_chars_max
< target_int_max ())
2592 wide_int min
= wi::shwi (res
.under4k
? res
.number_chars_min
- 1
2593 : target_int_min (), prec
);
2594 wide_int max
= wi::shwi (res
.number_chars_max
- 1, prec
);
2595 set_range_info (lhs
, VR_RANGE
, min
, max
);
2601 const char *inbounds
2602 = (res
.number_chars_min
<= info
.objsize
2603 ? (res
.number_chars_max
<= info
.objsize
2604 ? "in" : "potentially out-of")
2607 location_t callloc
= gimple_location (info
.callstmt
);
2608 fprintf (dump_file
, "On line %i ", LOCATION_LINE (callloc
));
2609 print_generic_expr (dump_file
, info
.func
, dump_flags
);
2611 const char *ign
= lhs
? "" : " ignored";
2612 if (res
.number_chars
>= HOST_WIDE_INT_MAX
)
2614 " %s-bounds return value in range [%lu, %lu]%s.\n",
2616 (unsigned long)res
.number_chars_min
,
2617 (unsigned long)res
.number_chars_max
, ign
);
2619 fprintf (dump_file
, " %s-bounds return value %lu%s.\n",
2620 inbounds
, (unsigned long)res
.number_chars
, ign
);
2625 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
2626 functions and if so, handle it. */
2629 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator
*gsi
)
2631 call_info info
= call_info ();
2633 info
.callstmt
= gsi_stmt (*gsi
);
2634 if (!gimple_call_builtin_p (info
.callstmt
, BUILT_IN_NORMAL
))
2637 info
.func
= gimple_call_fndecl (info
.callstmt
);
2638 info
.fncode
= DECL_FUNCTION_CODE (info
.func
);
2640 /* The size of the destination as in snprintf(dest, size, ...). */
2641 unsigned HOST_WIDE_INT dstsize
= HOST_WIDE_INT_M1U
;
2643 /* The size of the destination determined by __builtin_object_size. */
2644 unsigned HOST_WIDE_INT objsize
= HOST_WIDE_INT_M1U
;
2646 /* Buffer size argument number (snprintf and vsnprintf). */
2647 unsigned HOST_WIDE_INT idx_dstsize
= HOST_WIDE_INT_M1U
;
2649 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
2650 unsigned HOST_WIDE_INT idx_objsize
= HOST_WIDE_INT_M1U
;
2652 /* Format string argument number (valid for all functions). */
2653 unsigned idx_format
;
2655 switch (info
.fncode
)
2657 case BUILT_IN_SPRINTF
:
2659 // __builtin_sprintf (dst, format, ...)
2664 case BUILT_IN_SPRINTF_CHK
:
2666 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
2672 case BUILT_IN_SNPRINTF
:
2674 // __builtin_snprintf (dst, size, format, ...)
2678 info
.bounded
= true;
2681 case BUILT_IN_SNPRINTF_CHK
:
2683 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
2688 info
.bounded
= true;
2691 case BUILT_IN_VSNPRINTF
:
2693 // __builtin_vsprintf (dst, size, format, va)
2697 info
.bounded
= true;
2700 case BUILT_IN_VSNPRINTF_CHK
:
2702 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
2707 info
.bounded
= true;
2710 case BUILT_IN_VSPRINTF
:
2712 // __builtin_vsprintf (dst, format, va)
2717 case BUILT_IN_VSPRINTF_CHK
:
2719 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
2729 info
.format
= gimple_call_arg (info
.callstmt
, idx_format
);
2731 if (idx_dstsize
== HOST_WIDE_INT_M1U
)
2733 /* For non-bounded functions like sprintf, determine the size
2734 of the destination from the object or pointer passed to it
2735 as the first argument. */
2736 dstsize
= get_destination_size (gimple_call_arg (info
.callstmt
, 0));
2738 else if (tree size
= gimple_call_arg (info
.callstmt
, idx_dstsize
))
2740 /* For bounded functions try to get the size argument. */
2742 if (TREE_CODE (size
) == INTEGER_CST
)
2744 dstsize
= tree_to_uhwi (size
);
2745 /* No object can be larger than SIZE_MAX bytes (half the address
2746 space) on the target. This imposes a limit that's one byte
2748 The functions are defined only for output of at most INT_MAX
2749 bytes. Specifying a bound in excess of that limit effectively
2750 defeats the bounds checking (and on some implementations such
2751 as Solaris cause the function to fail with EINVAL). */
2752 if (dstsize
>= target_size_max () / 2)
2753 warning_at (gimple_location (info
.callstmt
), OPT_Wformat_length_
,
2754 "specified destination size %wu is too large",
2756 else if (dstsize
> target_int_max ())
2757 warning_at (gimple_location (info
.callstmt
), OPT_Wformat_length_
,
2758 "specified destination size %wu exceeds %<INT_MAX %>",
2761 else if (TREE_CODE (size
) == SSA_NAME
)
2763 /* Try to determine the range of values of the argument
2764 and use the greater of the two at -Wformat-level 1 and
2765 the smaller of them at level 2. */
2767 enum value_range_type range_type
2768 = get_range_info (size
, &min
, &max
);
2769 if (range_type
== VR_RANGE
)
2772 = (warn_format_length
< 2
2773 ? wi::fits_uhwi_p (max
) ? max
.to_uhwi () : max
.to_shwi ()
2774 : wi::fits_uhwi_p (min
) ? min
.to_uhwi () : min
.to_shwi ());
2779 if (idx_objsize
!= HOST_WIDE_INT_M1U
)
2781 if (tree size
= gimple_call_arg (info
.callstmt
, idx_objsize
))
2782 if (tree_fits_uhwi_p (size
))
2783 objsize
= tree_to_uhwi (size
);
2786 if (info
.bounded
&& !dstsize
)
2788 /* As a special case, when the explicitly specified destination
2789 size argument (to a bounded function like snprintf) is zero
2790 it is a request to determine the number of bytes on output
2791 without actually producing any. Pretend the size is
2792 unlimited in this case. */
2793 info
.objsize
= HOST_WIDE_INT_MAX
;
2794 info
.nowrite
= true;
2798 /* Set the object size to the smaller of the two arguments
2799 of both have been specified and they're not equal. */
2800 info
.objsize
= dstsize
< objsize
? dstsize
: objsize
;
2803 && dstsize
< target_size_max () / 2 && objsize
< dstsize
)
2805 warning_at (gimple_location (info
.callstmt
), OPT_Wformat_length_
,
2806 "specified size %wu exceeds the size %wu "
2807 "of the destination object", dstsize
, objsize
);
2811 if (integer_zerop (info
.format
))
2813 /* This is diagnosed with -Wformat only when the null is a constant
2814 pointer. The warning here diagnoses instances where the pointer
2816 warning_at (EXPR_LOC_OR_LOC (info
.format
, input_location
),
2817 OPT_Wformat_length_
, "null format string");
2821 info
.fmtstr
= get_format_string (info
.format
, &info
.fmtloc
);
2825 /* The result is the number of bytes output by the formatted function,
2826 including the terminating NUL. */
2827 format_result res
= format_result ();
2829 bool success
= compute_format_length (info
, &res
);
2831 /* When optimizing and the printf return value optimization is enabled,
2832 attempt to substitute the computed result for the return value of
2833 the call. Avoid this optimization when -frounding-math is in effect
2834 and the format string contains a floating point directive. */
2837 && flag_printf_return_value
2838 && (!flag_rounding_math
|| !res
.floating
))
2839 try_substitute_return_value (gsi
, info
, res
);
2842 /* Execute the pass for function FUN. */
2845 pass_sprintf_length::execute (function
*fun
)
2848 FOR_EACH_BB_FN (bb
, fun
)
2850 for (gimple_stmt_iterator si
= gsi_start_bb (bb
); !gsi_end_p (si
);
2853 /* Iterate over statements, looking for function calls. */
2854 gimple
*stmt
= gsi_stmt (si
);
2856 if (is_gimple_call (stmt
))
2857 handle_gimple_call (&si
);
2864 } /* Unnamed namespace. */
2866 /* Return a pointer to a pass object newly constructed from the context
2870 make_pass_sprintf_length (gcc::context
*ctxt
)
2872 return new pass_sprintf_length (ctxt
);