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"
70 #include "stor-layout.h"
74 #include "targhooks.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 void 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. */
231 const unsigned HOST_WIDE_INT int_min
232 = HOST_WIDE_INT_M1U
<< (TYPE_PRECISION (integer_type_node
) - 1);
237 /* Return the largest value for TYPE on the target. */
239 static unsigned HOST_WIDE_INT
240 target_max_value (tree type
)
242 const unsigned HOST_WIDE_INT max_value
243 = HOST_WIDE_INT_M1U
>> (HOST_BITS_PER_WIDE_INT
244 - TYPE_PRECISION (type
) + 1);
248 /* Return the value of INT_MAX for the target. */
250 static inline unsigned HOST_WIDE_INT
253 return target_max_value (integer_type_node
);
256 /* Return the value of SIZE_MAX for the target. */
258 static inline unsigned HOST_WIDE_INT
261 return target_max_value (size_type_node
);
264 /* Return the constant initial value of DECL if available or DECL
265 otherwise. Same as the synonymous function in c/c-typeck.c. */
268 decl_constant_value (tree decl
)
270 if (/* Don't change a variable array bound or initial value to a constant
271 in a place where a variable is invalid. Note that DECL_INITIAL
272 isn't valid for a PARM_DECL. */
273 current_function_decl
!= 0
274 && TREE_CODE (decl
) != PARM_DECL
275 && !TREE_THIS_VOLATILE (decl
)
276 && TREE_READONLY (decl
)
277 && DECL_INITIAL (decl
) != 0
278 && TREE_CODE (DECL_INITIAL (decl
)) != ERROR_MARK
279 /* This is invalid if initial value is not constant.
280 If it has either a function call, a memory reference,
281 or a variable, then re-evaluating it could give different results. */
282 && TREE_CONSTANT (DECL_INITIAL (decl
))
283 /* Check for cases where this is sub-optimal, even though valid. */
284 && TREE_CODE (DECL_INITIAL (decl
)) != CONSTRUCTOR
)
285 return DECL_INITIAL (decl
);
289 /* Given FORMAT, set *PLOC to the source location of the format string
290 and return the format string if it is known or null otherwise. */
293 get_format_string (tree format
, location_t
*ploc
)
297 /* Pull out a constant value if the front end didn't. */
298 format
= decl_constant_value (format
);
302 if (integer_zerop (format
))
304 /* FIXME: Diagnose null format string if it hasn't been diagnosed
305 by -Wformat (the latter diagnoses only nul pointer constants,
306 this pass can do better). */
310 HOST_WIDE_INT offset
= 0;
312 if (TREE_CODE (format
) == POINTER_PLUS_EXPR
)
314 tree arg0
= TREE_OPERAND (format
, 0);
315 tree arg1
= TREE_OPERAND (format
, 1);
319 if (TREE_CODE (arg1
) != INTEGER_CST
)
324 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
325 if (!cst_and_fits_in_hwi (arg1
))
328 offset
= int_cst_value (arg1
);
331 if (TREE_CODE (format
) != ADDR_EXPR
)
334 *ploc
= EXPR_LOC_OR_LOC (format
, input_location
);
336 format
= TREE_OPERAND (format
, 0);
338 if (TREE_CODE (format
) == ARRAY_REF
339 && tree_fits_shwi_p (TREE_OPERAND (format
, 1))
340 && (offset
+= tree_to_shwi (TREE_OPERAND (format
, 1))) >= 0)
341 format
= TREE_OPERAND (format
, 0);
347 tree array_size
= NULL_TREE
;
350 && TREE_CODE (TREE_TYPE (format
)) == ARRAY_TYPE
351 && (array_init
= decl_constant_value (format
)) != format
352 && TREE_CODE (array_init
) == STRING_CST
)
354 /* Extract the string constant initializer. Note that this may
355 include a trailing NUL character that is not in the array (e.g.
356 const char a[3] = "foo";). */
357 array_size
= DECL_SIZE_UNIT (format
);
361 if (TREE_CODE (format
) != STRING_CST
)
364 if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format
))) != char_type_node
)
366 /* Wide format string. */
370 const char *fmtstr
= TREE_STRING_POINTER (format
);
371 unsigned fmtlen
= TREE_STRING_LENGTH (format
);
375 /* Variable length arrays can't be initialized. */
376 gcc_assert (TREE_CODE (array_size
) == INTEGER_CST
);
378 if (tree_fits_shwi_p (array_size
))
380 HOST_WIDE_INT array_size_value
= tree_to_shwi (array_size
);
381 if (array_size_value
> 0
382 && array_size_value
== (int) array_size_value
383 && fmtlen
> array_size_value
)
384 fmtlen
= array_size_value
;
389 if (offset
>= fmtlen
)
396 if (fmtlen
< 1 || fmtstr
[--fmtlen
] != 0)
398 /* FIXME: Diagnose an unterminated format string if it hasn't been
399 diagnosed by -Wformat. Similarly to a null format pointer,
400 -Wformay diagnoses only nul pointer constants, this pass can
408 /* The format_warning_at_substring function is not used here in a way
409 that makes using attribute format viable. Suppress the warning. */
411 #pragma GCC diagnostic push
412 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
414 /* For convenience and brevity. */
417 (* const fmtwarn
) (const substring_loc
&, const source_range
*,
418 const char *, int, const char *, ...)
419 = format_warning_at_substring
;
421 /* Format length modifiers. */
426 FMT_LEN_hh
, // char argument
429 FMT_LEN_ll
, // long long
430 FMT_LEN_L
, // long double (and GNU long long)
432 FMT_LEN_t
, // ptrdiff_t
433 FMT_LEN_j
// intmax_t
437 /* A minimum and maximum number of bytes. */
441 unsigned HOST_WIDE_INT min
, max
;
444 /* Description of the result of conversion either of a single directive
445 or the whole format string. */
450 : argmin (), argmax (), knownrange (), bounded (), constant ()
452 range
.min
= range
.max
= HOST_WIDE_INT_MAX
;
455 /* The range a directive's argument is in. */
458 /* The minimum and maximum number of bytes that a directive
459 results in on output for an argument in the range above. */
462 /* True when the range above is obtained from a known value of
463 a directive's argument or its bounds and not the result of
464 heuristics that depend on warning levels. */
467 /* True when the range is the result of an argument determined
468 to be bounded to a subrange of its type or value (such as by
469 value range propagation or the width of the formt directive),
473 /* True when the output of a directive is constant. This is rare
474 and typically requires that the argument(s) of the directive
475 are also constant (such as determined by constant propagation,
476 though not value range propagation). */
480 /* Description of a conversion specification. */
482 struct conversion_spec
484 /* A bitmap of flags, one for each character. */
485 unsigned flags
[256 / sizeof (int)];
486 /* Numeric width as in "%8x". */
488 /* Numeric precision as in "%.32s". */
491 /* Width specified via the '*' character. */
493 /* Precision specified via the asterisk. */
496 /* Length modifier. */
497 format_lengths modifier
;
499 /* Format specifier character. */
502 /* Numeric width was given. */
503 unsigned have_width
: 1;
504 /* Numeric precision was given. */
505 unsigned have_precision
: 1;
506 /* Non-zero when certain flags should be interpreted even for a directive
507 that normally doesn't accept them (used when "%p" with flags such as
508 space or plus is interepreted as a "%x". */
509 unsigned force_flags
: 1;
511 /* Format conversion function that given a conversion specification
512 and an argument returns the formatting result. */
513 fmtresult (*fmtfunc
) (const conversion_spec
&, tree
);
515 /* Return True when a the format flag CHR has been used. */
516 bool get_flag (char chr
) const
518 unsigned char c
= chr
& 0xff;
519 return (flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
520 & (1U << (c
% (CHAR_BIT
* sizeof *flags
))));
523 /* Make a record of the format flag CHR having been used. */
524 void set_flag (char chr
)
526 unsigned char c
= chr
& 0xff;
527 flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
528 |= (1U << (c
% (CHAR_BIT
* sizeof *flags
)));
531 /* Reset the format flag CHR. */
532 void clear_flag (char chr
)
534 unsigned char c
= chr
& 0xff;
535 flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
536 &= ~(1U << (c
% (CHAR_BIT
* sizeof *flags
)));
540 /* Return the logarithm of X in BASE. */
543 ilog (unsigned HOST_WIDE_INT x
, int base
)
554 /* Return the number of bytes resulting from converting into a string
555 the INTEGER_CST tree node X in BASE. PLUS indicates whether 1 for
556 a plus sign should be added for positive numbers, and PREFIX whether
557 the length of an octal ('O') or hexadecimal ('0x') prefix should be
558 added for nonzero numbers. Return -1 if X cannot be represented. */
561 tree_digits (tree x
, int base
, bool plus
, bool prefix
)
563 unsigned HOST_WIDE_INT absval
;
567 if (TYPE_UNSIGNED (TREE_TYPE (x
)))
569 if (tree_fits_uhwi_p (x
))
571 absval
= tree_to_uhwi (x
);
579 if (tree_fits_shwi_p (x
))
581 HOST_WIDE_INT i
= tree_to_shwi (x
);
597 res
+= ilog (absval
, base
);
599 if (prefix
&& absval
)
610 /* Given the formatting result described by RES and NAVAIL, the number
611 of available in the destination, return the number of bytes remaining
612 in the destination. */
614 static inline result_range
615 bytes_remaining (unsigned HOST_WIDE_INT navail
, const format_result
&res
)
619 if (HOST_WIDE_INT_MAX
<= navail
)
621 range
.min
= range
.max
= navail
;
625 if (res
.number_chars
< navail
)
627 range
.min
= range
.max
= navail
- res
.number_chars
;
629 else if (res
.number_chars_min
< navail
)
631 range
.max
= navail
- res
.number_chars_min
;
636 if (res
.number_chars_max
< navail
)
637 range
.min
= navail
- res
.number_chars_max
;
644 /* Given the formatting result described by RES and NAVAIL, the number
645 of available in the destination, return the minimum number of bytes
646 remaining in the destination. */
648 static inline unsigned HOST_WIDE_INT
649 min_bytes_remaining (unsigned HOST_WIDE_INT navail
, const format_result
&res
)
651 if (HOST_WIDE_INT_MAX
<= navail
)
654 if (1 < warn_format_length
|| res
.bounded
)
656 /* At level 2, or when all directives output an exact number
657 of bytes or when their arguments were bounded by known
658 ranges, use the greater of the two byte counters if it's
659 valid to compute the result. */
660 if (res
.number_chars_max
< HOST_WIDE_INT_MAX
)
661 navail
-= res
.number_chars_max
;
662 else if (res
.number_chars
< HOST_WIDE_INT_MAX
)
663 navail
-= res
.number_chars
;
664 else if (res
.number_chars_min
< HOST_WIDE_INT_MAX
)
665 navail
-= res
.number_chars_min
;
669 /* At level 1 use the smaller of the byte counters to compute
671 if (res
.number_chars
< HOST_WIDE_INT_MAX
)
672 navail
-= res
.number_chars
;
673 else if (res
.number_chars_min
< HOST_WIDE_INT_MAX
)
674 navail
-= res
.number_chars_min
;
675 else if (res
.number_chars_max
< HOST_WIDE_INT_MAX
)
676 navail
-= res
.number_chars_max
;
679 if (navail
> HOST_WIDE_INT_MAX
)
685 /* Description of a call to a formatted function. */
687 struct pass_sprintf_length::call_info
689 /* Function call statement. */
692 /* Function called. */
695 /* Called built-in function code. */
696 built_in_function fncode
;
698 /* Format argument and format string extracted from it. */
702 /* The location of the format argument. */
705 /* The destination object size for __builtin___xxx_chk functions
706 typically determined by __builtin_object_size, or -1 if unknown. */
707 unsigned HOST_WIDE_INT objsize
;
709 /* Number of the first variable argument. */
710 unsigned HOST_WIDE_INT argidx
;
712 /* True for functions like snprintf that specify the size of
713 the destination, false for others like sprintf that don't. */
717 /* Return the result of formatting the '%%' directive. */
720 format_percent (const conversion_spec
&, tree
)
723 res
.argmin
= res
.argmax
= NULL_TREE
;
724 res
.range
.min
= res
.range
.max
= 1;
725 res
.bounded
= res
.constant
= true;
730 /* Ugh. Compute intmax_type_node and uintmax_type_node the same way
731 lto/lto-lang.c does it. This should be available in tree.h. */
734 build_intmax_type_nodes (tree
*pintmax
, tree
*puintmax
)
736 if (strcmp (SIZE_TYPE
, "unsigned int") == 0)
738 *pintmax
= integer_type_node
;
739 *puintmax
= unsigned_type_node
;
741 else if (strcmp (SIZE_TYPE
, "long unsigned int") == 0)
743 *pintmax
= long_integer_type_node
;
744 *puintmax
= long_unsigned_type_node
;
746 else if (strcmp (SIZE_TYPE
, "long long unsigned int") == 0)
748 *pintmax
= long_long_integer_type_node
;
749 *puintmax
= long_long_unsigned_type_node
;
753 for (int i
= 0; i
< NUM_INT_N_ENTS
; i
++)
754 if (int_n_enabled_p
[i
])
757 sprintf (name
, "__int%d unsigned", int_n_data
[i
].bitsize
);
759 if (strcmp (name
, SIZE_TYPE
) == 0)
761 *pintmax
= int_n_trees
[i
].signed_type
;
762 *puintmax
= int_n_trees
[i
].unsigned_type
;
769 format_integer (const conversion_spec
&, tree
);
771 /* Return a range representing the minimum and maximum number of bytes
772 that the conversion specification SPEC will write on output for the
773 pointer argument ARG when non-null. ARG may be null (for vararg
777 format_pointer (const conversion_spec
&spec
, tree arg
)
781 /* Determine the target's integer format corresponding to "%p". */
783 const char *pfmt
= targetm
.printf_pointer_format (arg
, &flags
);
786 /* The format couldn't be determined. */
787 res
.range
.min
= res
.range
.max
= HOST_WIDE_INT_M1U
;
793 /* Format the pointer using the integer format string. */
794 conversion_spec pspec
= spec
;
796 /* Clear flags that are not listed as recognized. */
797 for (const char *pf
= "+ #0"; *pf
; ++pf
)
799 if (!strchr (flags
, *pf
))
800 pspec
.clear_flag (*pf
);
803 /* Set flags that are specified in the format string. */
809 case '+': case ' ': case '#': case '0':
810 pspec
.set_flag (*pfmt
);
818 /* Set the appropriate length modifier taking care to clear
819 the one that may be set (Glibc's %p accepts but ignores all
820 the integer length modifiers). */
823 case 'l': pspec
.modifier
= FMT_LEN_l
; ++pfmt
; break;
824 case 't': pspec
.modifier
= FMT_LEN_t
; ++pfmt
; break;
825 case 'z': pspec
.modifier
= FMT_LEN_z
; ++pfmt
; break;
826 default: pspec
.modifier
= FMT_LEN_none
;
829 pspec
.force_flags
= 1;
830 pspec
.specifier
= *pfmt
++;
831 gcc_assert (*pfmt
== '\0');
832 return format_integer (pspec
, arg
);
835 /* The format is a plain string such as Glibc's "(nil)". */
836 res
.range
.min
= res
.range
.max
= strlen (pfmt
);
840 /* Return a range representing the minimum and maximum number of bytes
841 that the conversion specification SPEC will write on output for the
842 integer argument ARG when non-null. ARG may be null (for vararg
846 format_integer (const conversion_spec
&spec
, tree arg
)
848 /* These are available as macros in the C and C++ front ends but,
850 static tree intmax_type_node
;
851 static tree uintmax_type_node
;
853 /* Initialize the intmax nodes above the first time through here. */
854 if (!intmax_type_node
)
855 build_intmax_type_nodes (&intmax_type_node
, &uintmax_type_node
);
857 /* Set WIDTH and PRECISION to either the values in the format
858 specification or to zero. */
859 int width
= spec
.have_width
? spec
.width
: 0;
860 int prec
= spec
.have_precision
? spec
.precision
: 0;
863 width
= (TREE_CODE (spec
.star_width
) == INTEGER_CST
864 ? tree_to_shwi (spec
.star_width
) : 0);
866 if (spec
.star_precision
)
867 prec
= (TREE_CODE (spec
.star_precision
) == INTEGER_CST
868 ? tree_to_shwi (spec
.star_precision
) : 0);
870 bool sign
= spec
.specifier
== 'd' || spec
.specifier
== 'i';
872 /* The type of the "formal" argument expected by the directive. */
873 tree dirtype
= NULL_TREE
;
875 /* Determine the expected type of the argument from the length
877 switch (spec
.modifier
)
880 if (spec
.specifier
== 'p')
881 dirtype
= ptr_type_node
;
883 dirtype
= sign
? integer_type_node
: unsigned_type_node
;
887 dirtype
= sign
? short_integer_type_node
: short_unsigned_type_node
;
891 dirtype
= sign
? signed_char_type_node
: unsigned_char_type_node
;
895 dirtype
= sign
? long_integer_type_node
: long_unsigned_type_node
;
901 ? long_long_integer_type_node
902 : long_long_unsigned_type_node
);
906 dirtype
= sign
? ptrdiff_type_node
: size_type_node
;
910 dirtype
= sign
? ptrdiff_type_node
: size_type_node
;
914 dirtype
= sign
? intmax_type_node
: uintmax_type_node
;
921 /* The type of the argument to the directive, either deduced from
922 the actual non-constant argument if one is known, or from
923 the directive itself when none has been provided because it's
925 tree argtype
= NULL_TREE
;
929 /* When the argument has not been provided, use the type of
930 the directive's argument as an approximation. This will
931 result in false positives for directives like %i with
932 arguments with smaller precision (such as short or char). */
935 else if (TREE_CODE (arg
) == INTEGER_CST
)
937 /* The minimum and maximum number of bytes produced by
941 /* When a constant argument has been provided use its value
942 rather than type to determine the length of the output. */
945 res
.knownrange
= true;
947 /* Base to format the number in. */
950 /* True when a signed conversion is preceded by a sign or space. */
953 switch (spec
.specifier
)
957 /* Space is only effective for signed conversions. */
958 maybesign
= spec
.get_flag (' ');
962 maybesign
= spec
.force_flags
? spec
.get_flag (' ') : false;
966 maybesign
= spec
.force_flags
? spec
.get_flag (' ') : false;
971 maybesign
= spec
.force_flags
? spec
.get_flag (' ') : false;
978 /* Convert the argument to the type of the directive. */
979 arg
= fold_convert (dirtype
, arg
);
981 maybesign
|= spec
.get_flag ('+');
983 /* True when a conversion is preceded by a prefix indicating the base
984 of the argument (octal or hexadecimal). */
985 bool maybebase
= spec
.get_flag ('#');
986 int len
= tree_digits (arg
, base
, maybesign
, maybebase
);
995 res
.range
.min
= res
.range
.max
;
1000 else if (TREE_CODE (TREE_TYPE (arg
)) == INTEGER_TYPE
1001 || TREE_CODE (TREE_TYPE (arg
)) == POINTER_TYPE
)
1003 /* Determine the type of the provided non-constant argument. */
1004 if (TREE_CODE (arg
) == NOP_EXPR
)
1005 arg
= TREE_OPERAND (arg
, 0);
1006 else if (TREE_CODE (arg
) == CONVERT_EXPR
)
1007 arg
= TREE_OPERAND (arg
, 0);
1008 if (TREE_CODE (arg
) == COMPONENT_REF
)
1009 arg
= TREE_OPERAND (arg
, 1);
1011 argtype
= TREE_TYPE (arg
);
1015 /* Don't bother with invalid arguments since they likely would
1016 have already been diagnosed, and disable any further checking
1017 of the format string by returning [-1, -1]. */
1018 return fmtresult ();
1023 /* Using either the range the non-constant argument is in, or its
1024 type (either "formal" or actual), create a range of values that
1025 constrain the length of output given the warning level. */
1026 tree argmin
= NULL_TREE
;
1027 tree argmax
= NULL_TREE
;
1029 if (arg
&& TREE_CODE (arg
) == SSA_NAME
1030 && TREE_CODE (argtype
) == INTEGER_TYPE
)
1032 /* Try to determine the range of values of the integer argument
1033 (range information is not available for pointers). */
1035 enum value_range_type range_type
= get_range_info (arg
, &min
, &max
);
1036 if (range_type
== VR_RANGE
)
1038 res
.argmin
= build_int_cst (argtype
, wi::fits_uhwi_p (min
)
1039 ? min
.to_uhwi () : min
.to_shwi ());
1040 res
.argmax
= build_int_cst (argtype
, wi::fits_uhwi_p (max
)
1041 ? max
.to_uhwi () : max
.to_shwi ());
1043 /* For a range with a negative lower bound and a non-negative
1044 upper bound, use one to determine the minimum number of bytes
1045 on output and whichever of the two bounds that results in
1046 the greater number of bytes on output for the upper bound.
1047 For example, for ARG in the range of [-3, 123], use 123 as
1048 the upper bound for %i but -3 for %u. */
1049 if (wi::neg_p (min
) && !wi::neg_p (max
))
1051 argmin
= build_int_cst (argtype
, wi::fits_uhwi_p (min
)
1052 ? min
.to_uhwi () : min
.to_shwi ());
1054 argmax
= build_int_cst (argtype
, wi::fits_uhwi_p (max
)
1055 ? max
.to_uhwi () : max
.to_shwi ());
1057 int minbytes
= format_integer (spec
, res
.argmin
).range
.min
;
1058 int maxbytes
= format_integer (spec
, res
.argmax
).range
.max
;
1059 if (maxbytes
< minbytes
)
1060 argmax
= res
.argmin
;
1062 argmin
= integer_zero_node
;
1066 argmin
= res
.argmin
;
1067 argmax
= res
.argmax
;
1070 /* The argument is bounded by the known range of values
1071 determined by Value Range Propagation. */
1073 res
.knownrange
= true;
1075 else if (range_type
== VR_ANTI_RANGE
)
1077 /* Handle anti-ranges if/when bug 71690 is resolved. */
1079 else if (range_type
== VR_VARYING
)
1081 /* The argument here may be the result of promoting the actual
1082 argument to int. Try to determine the type of the actual
1083 argument before promotion and narrow down its range that
1085 gimple
*def
= SSA_NAME_DEF_STMT (arg
);
1086 if (is_gimple_assign (def
))
1088 tree_code code
= gimple_assign_rhs_code (def
);
1089 if (code
== INTEGER_CST
)
1091 arg
= gimple_assign_rhs1 (def
);
1092 return format_integer (spec
, arg
);
1095 if (code
== NOP_EXPR
)
1096 argtype
= TREE_TYPE (gimple_assign_rhs1 (def
));
1103 /* For an unknown argument (e.g., one passed to a vararg function)
1104 or one whose value range cannot be determined, create a T_MIN
1105 constant if the argument's type is signed and T_MAX otherwise,
1106 and use those to compute the range of bytes that the directive
1108 argmin
= build_int_cst (argtype
, 1);
1110 int typeprec
= TYPE_PRECISION (dirtype
);
1111 int argprec
= TYPE_PRECISION (argtype
);
1113 if (argprec
< typeprec
|| POINTER_TYPE_P (argtype
))
1115 if (TYPE_UNSIGNED (argtype
))
1116 argmax
= build_all_ones_cst (argtype
);
1118 argmax
= fold_build2 (LSHIFT_EXPR
, argtype
, integer_one_node
,
1119 build_int_cst (integer_type_node
,
1124 argmax
= fold_build2 (LSHIFT_EXPR
, dirtype
, integer_one_node
,
1125 build_int_cst (integer_type_node
,
1128 res
.argmin
= argmin
;
1129 res
.argmax
= argmax
;
1132 /* Recursively compute the minimum and maximum from the known range,
1133 taking care to swap them if the lower bound results in longer
1134 output than the upper bound (e.g., in the range [-1, 0]. */
1135 res
.range
.min
= format_integer (spec
, argmin
).range
.min
;
1136 res
.range
.max
= format_integer (spec
, argmax
).range
.max
;
1138 /* The result is bounded either when the argument is determined to be
1139 (e.g., when it's within some range) or when the minimum and maximum
1140 are the same. That can happen here for example when the specified
1141 width is as wide as the greater of MIN and MAX, as would be the case
1142 with sprintf (d, "%08x", x) with a 32-bit integer x. */
1143 res
.bounded
|= res
.range
.min
== res
.range
.max
;
1145 if (res
.range
.max
< res
.range
.min
)
1147 unsigned HOST_WIDE_INT tmp
= res
.range
.max
;
1148 res
.range
.max
= res
.range
.min
;
1149 res
.range
.min
= tmp
;
1155 /* Return the number of bytes to format using the format specifier
1156 SPEC the largest value in the real floating TYPE. */
1159 format_floating_max (tree type
, char spec
, int prec
= -1)
1161 machine_mode mode
= TYPE_MODE (type
);
1163 /* IBM Extended mode. */
1164 if (MODE_COMPOSITE_P (mode
))
1167 /* Get the real type format desription for the target. */
1168 const real_format
*rfmt
= REAL_MODE_FORMAT (mode
);
1173 get_max_float (rfmt
, buf
, sizeof buf
);
1174 real_from_string (&rv
, buf
);
1177 /* Convert the GCC real value representation with the precision
1178 of the real type to the mpfr_t format with the GCC default
1179 round-to-nearest mode. */
1181 mpfr_init2 (x
, rfmt
->p
);
1182 mpfr_from_real (x
, &rv
, GMP_RNDN
);
1188 const char fmt
[] = { '%', '.', '*', 'R', spec
, '\0' };
1189 n
= mpfr_snprintf (NULL
, 0, fmt
, prec
, x
);
1193 const char fmt
[] = { '%', 'R', spec
, '\0' };
1194 n
= mpfr_snprintf (NULL
, 0, fmt
, x
);
1197 /* Return a value one greater to account for the leading minus sign. */
1201 /* Return a range representing the minimum and maximum number of bytes
1202 that the conversion specification SPEC will output for any argument
1203 given the WIDTH and PRECISION (extracted from SPEC). This function
1204 is used when the directive argument or its value isn't known. */
1207 format_floating (const conversion_spec
&spec
, int width
, int prec
)
1212 switch (spec
.modifier
)
1216 type
= double_type_node
;
1220 type
= long_double_type_node
;
1225 type
= long_double_type_node
;
1230 return fmtresult ();
1233 /* The minimum and maximum number of bytes produced by the directive. */
1236 /* Log10 of of the maximum number of exponent digits for the type. */
1239 if (REAL_MODE_FORMAT (TYPE_MODE (type
))->b
== 2)
1241 /* The base in which the exponent is represented should always
1244 const double log10_2
= .30102999566398119521;
1246 /* Compute T_MAX_EXP for base 2. */
1247 int expdigs
= REAL_MODE_FORMAT (TYPE_MODE (type
))->emax
* log10_2
;
1248 logexpdigs
= ilog (expdigs
, 10);
1251 switch (spec
.specifier
)
1256 /* The minimum output is "0x.p+0". */
1257 res
.range
.min
= 6 + (prec
> 0 ? prec
: 0);
1258 res
.range
.max
= format_floating_max (type
, 'a', prec
);
1260 /* The output of "%a" is fully specified only when precision
1261 is explicitly specified. */
1262 res
.bounded
= -1 < prec
;
1269 bool sign
= spec
.get_flag ('+') || spec
.get_flag (' ');
1270 /* The minimum output is "[-+]1.234567e+00" regardless
1271 of the value of the actual argument. */
1272 res
.range
.min
= (sign
1273 + 1 /* unit */ + (prec
< 0 ? 7 : prec
? prec
+ 1 : 0)
1275 /* The maximum output is the minimum plus sign (unless already
1276 included), plus the difference between the minimum exponent
1277 of 2 and the maximum exponent for the type. */
1278 res
.range
.max
= res
.range
.min
+ !sign
+ logexpdigs
- 2;
1280 /* "%e" is fully specified and the range of bytes is bounded. */
1288 /* The minimum output is "1.234567" regardless of the value
1289 of the actual argument. */
1290 res
.range
.min
= 2 + (prec
< 0 ? 6 : prec
);
1292 /* Compute the maximum just once. */
1293 static const int f_max
[] = {
1294 format_floating_max (double_type_node
, 'f'),
1295 format_floating_max (long_double_type_node
, 'f')
1297 res
.range
.max
= f_max
[ldbl
];
1299 /* "%f" is fully specified and the range of bytes is bounded. */
1306 /* The minimum is the same as for '%F'. */
1307 res
.range
.min
= 2 + (prec
< 0 ? 6 : prec
);
1309 /* Compute the maximum just once. */
1310 static const int g_max
[] = {
1311 format_floating_max (double_type_node
, 'g'),
1312 format_floating_max (long_double_type_node
, 'g')
1314 res
.range
.max
= g_max
[ldbl
];
1316 /* "%g" is fully specified and the range of bytes is bounded. */
1322 return fmtresult ();
1327 if (res
.range
.min
< (unsigned)width
)
1328 res
.range
.min
= width
;
1329 if (res
.range
.max
< (unsigned)width
)
1330 res
.range
.max
= width
;
1336 /* Return a range representing the minimum and maximum number of bytes
1337 that the conversion specification SPEC will write on output for the
1338 floating argument ARG. */
1341 format_floating (const conversion_spec
&spec
, tree arg
)
1346 /* The minimum and maximum number of bytes produced by the directive. */
1348 res
.constant
= arg
&& TREE_CODE (arg
) == REAL_CST
;
1350 if (spec
.have_width
)
1352 else if (spec
.star_width
)
1354 if (TREE_CODE (spec
.star_width
) == INTEGER_CST
)
1355 width
= tree_to_shwi (spec
.star_width
);
1358 res
.range
.min
= res
.range
.max
= HOST_WIDE_INT_M1U
;
1363 if (spec
.have_precision
)
1364 prec
= spec
.precision
;
1365 else if (spec
.star_precision
)
1367 if (TREE_CODE (spec
.star_precision
) == INTEGER_CST
)
1368 prec
= tree_to_shwi (spec
.star_precision
);
1371 res
.range
.min
= res
.range
.max
= HOST_WIDE_INT_M1U
;
1375 else if (res
.constant
&& TOUPPER (spec
.specifier
) != 'A')
1377 /* Specify the precision explicitly since mpfr_sprintf defaults
1384 /* Set up an array to easily iterate over. */
1385 unsigned HOST_WIDE_INT
* const minmax
[] = {
1386 &res
.range
.min
, &res
.range
.max
1389 /* Get the real type format desription for the target. */
1390 const REAL_VALUE_TYPE
*rvp
= TREE_REAL_CST_PTR (arg
);
1391 const real_format
*rfmt
= REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg
)));
1393 /* Convert the GCC real value representation with the precision
1394 of the real type to the mpfr_t format with the GCC default
1395 round-to-nearest mode. */
1397 mpfr_init2 (mpfrval
, rfmt
->p
);
1398 mpfr_from_real (mpfrval
, rvp
, GMP_RNDN
);
1401 char *pfmt
= fmtstr
;
1405 for (const char *pf
= "-+ #0"; *pf
; ++pf
)
1406 if (spec
.get_flag (*pf
))
1409 /* Append width when specified and precision. */
1411 pfmt
+= sprintf (pfmt
, "%i", width
);
1413 pfmt
+= sprintf (pfmt
, ".%i", prec
);
1415 /* Append the MPFR 'R' floating type specifier (no length modifier
1416 is necessary or allowed by MPFR for mpfr_t values). */
1419 /* Save the position of the MPFR rounding specifier and skip over
1420 it. It will be set in each iteration in the loop below. */
1421 char* const rndspec
= pfmt
++;
1423 /* Append the C type specifier and nul-terminate. */
1424 *pfmt
++ = spec
.specifier
;
1427 for (int i
= 0; i
!= sizeof minmax
/ sizeof *minmax
; ++i
)
1429 /* Use the MPFR rounding specifier to round down in the first
1430 iteration and then up. In most but not all cases this will
1431 result in the same number of bytes. */
1434 /* Format it and store the result in the corresponding
1435 member of the result struct. */
1436 *minmax
[i
] = mpfr_snprintf (NULL
, 0, fmtstr
, mpfrval
);
1439 /* The output of all directives except "%a" is fully specified
1440 and so the result is bounded unless it exceeds INT_MAX.
1441 For "%a" the output is fully specified only when precision
1442 is explicitly specified. */
1443 res
.bounded
= ((TOUPPER (spec
.specifier
) != 'A'
1444 || (0 <= prec
&& (unsigned) prec
< target_int_max ()))
1445 && res
.range
.min
< target_int_max ());
1447 /* The range of output is known even if the result isn't bounded. */
1448 res
.knownrange
= true;
1452 return format_floating (spec
, width
, prec
);
1455 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1456 strings referenced by the expression STR, or (-1, -1) when not known.
1457 Used by the format_string function below. */
1460 get_string_length (tree str
)
1463 return fmtresult ();
1465 if (tree slen
= c_strlen (str
, 1))
1467 /* Simply return the length of the string. */
1469 res
.range
.min
= res
.range
.max
= tree_to_shwi (slen
);
1471 res
.constant
= true;
1472 res
.knownrange
= true;
1476 /* Determine the length of the shortest and longest string referenced
1477 by STR. Strings of unknown lengths are bounded by the sizes of
1478 arrays that subexpressions of STR may refer to. Pointers that
1479 aren't known to point any such arrays result in LENRANGE[1] set
1482 get_range_strlen (str
, lenrange
);
1484 if (lenrange
[0] || lenrange
[1])
1488 res
.range
.min
= (tree_fits_uhwi_p (lenrange
[0])
1489 ? tree_to_uhwi (lenrange
[0]) : 1 < warn_format_length
);
1490 res
.range
.max
= (tree_fits_uhwi_p (lenrange
[1])
1491 ? tree_to_uhwi (lenrange
[1]) : HOST_WIDE_INT_M1U
);
1493 /* Set RES.BOUNDED to true if and only if all strings referenced
1494 by STR are known to be bounded (though not necessarily by their
1495 actual length but perhaps by their maximum possible length). */
1496 res
.bounded
= res
.range
.max
< target_int_max ();
1497 res
.knownrange
= res
.bounded
;
1499 /* Set RES.CONSTANT to false even though that may be overly
1500 conservative in rare cases like: 'x ? a : b' where a and
1501 b have the same lengths and consist of the same characters. */
1502 res
.constant
= false;
1507 return get_string_length (NULL_TREE
);
1510 /* Return the minimum and maximum number of characters formatted
1511 by the '%c' and '%s' format directives and ther wide character
1512 forms for the argument ARG. ARG can be null (for functions
1513 such as vsprinf). */
1516 format_string (const conversion_spec
&spec
, tree arg
)
1518 unsigned width
= spec
.have_width
&& spec
.width
> 0 ? spec
.width
: 0;
1519 int prec
= spec
.have_precision
? spec
.precision
: -1;
1521 if (spec
.star_width
)
1523 width
= (TREE_CODE (spec
.star_width
) == INTEGER_CST
1524 ? tree_to_shwi (spec
.star_width
) : 0);
1525 if (width
> INT_MAX
)
1529 if (spec
.star_precision
)
1530 prec
= (TREE_CODE (spec
.star_precision
) == INTEGER_CST
1531 ? tree_to_shwi (spec
.star_precision
) : -1);
1535 /* The maximum number of bytes for an unknown wide character argument
1536 to a "%lc" directive adjusted for precision but not field width. */
1537 const unsigned HOST_WIDE_INT max_bytes_for_unknown_wc
1538 = (1 == warn_format_length
? 0 <= prec
? prec
: 0
1539 : 2 == warn_format_length
? 0 <= prec
? prec
: 1
1540 : 0 <= prec
? prec
: 6 /* Longest UTF-8 sequence. */);
1542 /* The maximum number of bytes for an unknown string argument to either
1543 a "%s" or "%ls" directive adjusted for precision but not field width. */
1544 const unsigned HOST_WIDE_INT max_bytes_for_unknown_str
1545 = (1 == warn_format_length
? 0 <= prec
? prec
: 0
1546 : 2 == warn_format_length
? 0 <= prec
? prec
: 1
1547 : HOST_WIDE_INT_MAX
);
1549 /* The result is bounded unless overriddden for a non-constant string
1550 of an unknown length. */
1551 bool bounded
= true;
1553 if (spec
.specifier
== 'c')
1555 if (spec
.modifier
== FMT_LEN_l
)
1557 /* Positive if the argument is a wide NUL character? */
1558 int nul
= (arg
&& TREE_CODE (arg
) == INTEGER_CST
1559 ? integer_zerop (arg
) : -1);
1561 /* A '%lc' directive is the same as '%ls' for a two element
1562 wide string character with the second element of NUL, so
1563 when the character is unknown the minimum number of bytes
1564 is the smaller of either 0 (at level 1) or 1 (at level 2)
1565 and WIDTH, and the maximum is MB_CUR_MAX in the selected
1566 locale, which is unfortunately, unknown. */
1567 res
.range
.min
= 1 == warn_format_length
? !nul
: nul
< 1;
1568 res
.range
.max
= max_bytes_for_unknown_wc
;
1569 /* The range above is good enough to issue warnings but not
1570 for value range propagation, so clear BOUNDED. */
1571 res
.bounded
= false;
1575 /* A plain '%c' directive. Its ouput is exactly 1. */
1576 res
.range
.min
= res
.range
.max
= 1;
1578 res
.knownrange
= true;
1579 res
.constant
= arg
&& TREE_CODE (arg
) == INTEGER_CST
;
1582 else /* spec.specifier == 's' */
1584 /* Compute the range the argument's length can be in. */
1585 fmtresult slen
= get_string_length (arg
);
1588 gcc_checking_assert (slen
.range
.min
== slen
.range
.max
);
1590 /* A '%s' directive with a string argument with constant length. */
1591 res
.range
= slen
.range
;
1593 /* The output of "%s" and "%ls" directives with a constant
1594 string is in a known range. For "%s" it is the length
1595 of the string. For "%ls" it is in the range [length,
1596 length * MB_LEN_MAX]. (The final range can be further
1597 constrained by width and precision but it's always known.) */
1598 res
.knownrange
= true;
1600 if (spec
.modifier
== FMT_LEN_l
)
1604 if (warn_format_length
> 1)
1606 /* Leave the minimum number of bytes the wide string
1607 converts to equal to its length and set the maximum
1608 to the worst case length which is the string length
1609 multiplied by MB_LEN_MAX. */
1611 /* It's possible to be smarter about computing the maximum
1612 by scanning the wide string for any 8-bit characters and
1613 if it contains none, using its length for the maximum.
1614 Even though this would be simple to do it's unlikely to
1615 be worth it when dealing with wide characters. */
1616 res
.range
.max
*= target_mb_len_max
;
1619 /* For a wide character string, use precision as the maximum
1620 even if precision is greater than the string length since
1621 the number of bytes the string converts to may be greater
1622 (due to MB_CUR_MAX). */
1624 res
.range
.max
= prec
;
1628 /* The output od a "%s" directive with a constant argument
1629 is bounded, constant, and obviously in a known range. */
1631 res
.constant
= true;
1634 if (0 <= prec
&& (unsigned)prec
< res
.range
.min
)
1636 res
.range
.min
= prec
;
1637 res
.range
.max
= prec
;
1642 /* For a '%s' and '%ls' directive with a non-constant string,
1643 the minimum number of characters is the greater of WIDTH
1644 and either 0 in mode 1 or the smaller of PRECISION and 1
1645 in mode 2, and the maximum is PRECISION or -1 to disable
1650 if (slen
.range
.min
>= target_int_max ())
1651 slen
.range
.min
= max_bytes_for_unknown_str
;
1652 else if ((unsigned)prec
< slen
.range
.min
)
1653 slen
.range
.min
= prec
;
1655 if ((unsigned)prec
< slen
.range
.max
1656 || slen
.range
.max
>= target_int_max ())
1657 slen
.range
.max
= prec
;
1659 else if (slen
.range
.min
>= target_int_max ())
1661 slen
.range
.min
= max_bytes_for_unknown_str
;
1662 slen
.range
.max
= max_bytes_for_unknown_str
;
1666 res
.range
= slen
.range
;
1668 /* The output is considered bounded when a precision has been
1669 specified to limit the number of bytes or when the number
1670 of bytes is known or contrained to some range. */
1671 res
.bounded
= 0 <= prec
|| slen
.bounded
;
1672 res
.knownrange
= slen
.knownrange
;
1673 res
.constant
= false;
1677 /* Adjust the lengths for field width. */
1678 if (res
.range
.min
< width
)
1679 res
.range
.min
= width
;
1681 if (res
.range
.max
< width
)
1682 res
.range
.max
= width
;
1684 /* Adjust BOUNDED if width happens to make them equal. */
1685 if (res
.range
.min
== res
.range
.max
&& res
.range
.min
< target_int_max ()
1689 /* When precision is specified the range of characters on output
1690 is known to be bounded by it. */
1692 res
.knownrange
= true;
1697 /* Compute the length of the output resulting from the conversion
1698 specification SPEC with the argument ARG in a call described by INFO
1699 and update the overall result of the call in *RES. The format directive
1700 corresponding to SPEC starts at CVTBEG and is CVTLEN characters long. */
1703 format_directive (const pass_sprintf_length::call_info
&info
,
1704 format_result
*res
, const char *cvtbeg
, size_t cvtlen
,
1705 const conversion_spec
&spec
, tree arg
)
1707 /* Offset of the beginning of the directive from the beginning
1708 of the format string. */
1709 size_t offset
= cvtbeg
- info
.fmtstr
;
1711 /* Create a location for the whole directive from the % to the format
1713 substring_loc
dirloc (info
.fmtloc
, TREE_TYPE (info
.format
),
1714 offset
, offset
, offset
+ cvtlen
- 1);
1716 /* Also create a location range for the argument if possible.
1717 This doesn't work for integer literals or function calls. */
1718 source_range argrange
;
1719 source_range
*pargrange
;
1720 if (arg
&& CAN_HAVE_LOCATION_P (arg
))
1722 argrange
= EXPR_LOCATION_RANGE (arg
);
1723 pargrange
= &argrange
;
1728 /* Bail when there is no function to compute the output length,
1729 or when minimum length checking has been disabled. */
1730 if (!spec
.fmtfunc
|| res
->number_chars_min
>= HOST_WIDE_INT_MAX
)
1733 /* Compute the (approximate) length of the formatted output. */
1734 fmtresult fmtres
= spec
.fmtfunc (spec
, arg
);
1736 /* The overall result is bounded and constant only if the output
1737 of every directive is bounded and constant, respectively. */
1738 res
->bounded
&= fmtres
.bounded
;
1739 res
->constant
&= fmtres
.constant
;
1741 /* Record whether the output of all directives is known to be
1742 bounded by some maximum, implying that their arguments are
1743 either known exactly or determined to be in a known range
1744 or, for strings, limited by the upper bounds of the arrays
1746 res
->knownrange
&= fmtres
.knownrange
;
1748 if (!fmtres
.knownrange
)
1750 /* Only when the range is known, check it against the host value
1751 of INT_MAX. Otherwise the range doesn't correspond to known
1752 values of the argument. */
1753 if (fmtres
.range
.max
>= target_int_max ())
1755 /* Normalize the MAX counter to avoid having to deal with it
1756 later. The counter can be less than HOST_WIDE_INT_M1U
1757 when compiling for an ILP32 target on an LP64 host. */
1758 fmtres
.range
.max
= HOST_WIDE_INT_M1U
;
1759 /* Disable exact and maximum length checking after a failure
1760 to determine the maximum number of characters (for example
1761 for wide characters or wide character strings) but continue
1762 tracking the minimum number of characters. */
1763 res
->number_chars_max
= HOST_WIDE_INT_M1U
;
1764 res
->number_chars
= HOST_WIDE_INT_M1U
;
1767 if (fmtres
.range
.min
>= target_int_max ())
1769 /* Disable exact length checking after a failure to determine
1770 even the minimum number of characters (it shouldn't happen
1771 except in an error) but keep tracking the minimum and maximum
1772 number of characters. */
1773 res
->number_chars
= HOST_WIDE_INT_M1U
;
1778 /* Compute the number of available bytes in the destination. There
1779 must always be at least one byte of space for the terminating
1780 NUL that's appended after the format string has been processed. */
1781 unsigned HOST_WIDE_INT navail
= min_bytes_remaining (info
.objsize
, *res
);
1783 if (fmtres
.range
.min
< fmtres
.range
.max
)
1785 /* The result is a range (i.e., it's inexact). */
1788 bool warned
= false;
1790 if (navail
< fmtres
.range
.min
)
1792 /* The minimum directive output is longer than there is
1793 room in the destination. */
1794 if (fmtres
.range
.min
== fmtres
.range
.max
)
1798 ? G_("%<%.*s%> directive output truncated writing "
1799 "%wu bytes into a region of size %wu")
1800 : G_("%<%.*s%> directive writing %wu bytes "
1801 "into a region of size %wu"));
1802 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1803 OPT_Wformat_length_
, fmtstr
,
1804 (int)cvtlen
, cvtbeg
, fmtres
.range
.min
,
1811 ? G_("%<%.*s%> directive output truncated writing "
1812 "between %wu and %wu bytes into a region of "
1814 : G_("%<%.*s%> directive writing between %wu and "
1815 "%wu bytes into a region of size %wu"));
1816 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1817 OPT_Wformat_length_
, fmtstr
,
1818 (int)cvtlen
, cvtbeg
,
1819 fmtres
.range
.min
, fmtres
.range
.max
, navail
);
1822 else if (navail
< fmtres
.range
.max
1823 && (((spec
.specifier
== 's'
1824 && fmtres
.range
.max
< HOST_WIDE_INT_MAX
)
1825 /* && (spec.precision || spec.star_precision) */)
1826 || 1 < warn_format_length
))
1828 /* The maximum directive output is longer than there is
1829 room in the destination and the output length is either
1830 explicitly constrained by the precision (for strings)
1831 or the warning level is greater than 1. */
1832 if (fmtres
.range
.max
>= HOST_WIDE_INT_MAX
)
1836 ? G_("%<%.*s%> directive output may be truncated "
1837 "writing %wu or more bytes a region of size %wu")
1838 : G_("%<%.*s%> directive writing %wu or more bytes "
1839 "into a region of size %wu"));
1840 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1841 OPT_Wformat_length_
, fmtstr
,
1842 (int)cvtlen
, cvtbeg
,
1843 fmtres
.range
.min
, navail
);
1849 ? G_("%<%.*s%> directive output may be truncated "
1850 "writing between %wu and %wu bytes into a region "
1852 : G_("%<%.*s%> directive writing between %wu and %wu "
1853 "bytes into a region of size %wu"));
1854 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1855 OPT_Wformat_length_
, fmtstr
,
1856 (int)cvtlen
, cvtbeg
,
1857 fmtres
.range
.min
, fmtres
.range
.max
,
1862 res
->warned
|= warned
;
1864 if (warned
&& fmtres
.argmin
)
1866 if (fmtres
.argmin
== fmtres
.argmax
)
1867 inform (info
.fmtloc
, "directive argument %qE", fmtres
.argmin
);
1868 else if (fmtres
.bounded
)
1869 inform (info
.fmtloc
, "directive argument in the range [%E, %E]",
1870 fmtres
.argmin
, fmtres
.argmax
);
1872 inform (info
.fmtloc
,
1873 "using the range [%qE, %qE] for directive argument",
1874 fmtres
.argmin
, fmtres
.argmax
);
1878 /* Disable exact length checking but adjust the minimum and maximum. */
1879 res
->number_chars
= HOST_WIDE_INT_M1U
;
1880 if (res
->number_chars_max
< HOST_WIDE_INT_MAX
1881 && fmtres
.range
.max
< HOST_WIDE_INT_MAX
)
1882 res
->number_chars_max
+= fmtres
.range
.max
;
1884 res
->number_chars_min
+= fmtres
.range
.min
;
1888 if (!res
->warned
&& fmtres
.range
.min
> 0 && navail
< fmtres
.range
.min
)
1892 ? (1 < fmtres
.range
.min
1893 ? G_("%<%.*s%> directive output truncated while writing "
1894 "%wu bytes into a region of size %wu")
1895 : G_("%<%.*s%> directive output truncated while writing "
1896 "%wu byte into a region of size %wu"))
1897 : (1 < fmtres
.range
.min
1898 ? G_("%<%.*s%> directive writing %wu bytes "
1899 "into a region of size %wu")
1900 : G_("%<%.*s%> directive writing %wu byte "
1901 "into a region of size %wu")));
1903 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1904 OPT_Wformat_length_
, fmtstr
,
1905 (int)cvtlen
, cvtbeg
, fmtres
.range
.min
,
1908 *res
+= fmtres
.range
.min
;
1911 /* Has the minimum directive output length exceeded the maximum
1912 of 4095 bytes required to be supported? */
1913 bool minunder4k
= fmtres
.range
.min
< 4096;
1914 if (!minunder4k
|| fmtres
.range
.max
> 4095)
1915 res
->under4k
= false;
1917 if (!res
->warned
&& 1 < warn_format_length
1918 && (!minunder4k
|| fmtres
.range
.max
> 4095))
1920 /* The directive output may be longer than the maximum required
1921 to be handled by an implementation according to 7.21.6.1, p15
1922 of C11. Warn on this only at level 2 but remember this and
1923 prevent folding the return value when done. This allows for
1924 the possibility of the actual libc call failing due to ENOMEM
1925 (like Glibc does under some conditions). */
1927 if (fmtres
.range
.min
== fmtres
.range
.max
)
1928 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1929 OPT_Wformat_length_
,
1930 "%<%.*s%> directive output of %wu bytes exceeds "
1931 "minimum required size of 4095",
1932 (int)cvtlen
, cvtbeg
, fmtres
.range
.min
);
1937 ? G_("%<%.*s%> directive output between %qu and %wu "
1938 "bytes may exceed minimum required size of 4095")
1939 : G_("%<%.*s%> directive output between %qu and %wu "
1940 "bytes exceeds minimum required size of 4095"));
1942 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1943 OPT_Wformat_length_
, fmtstr
,
1944 (int)cvtlen
, cvtbeg
,
1945 fmtres
.range
.min
, fmtres
.range
.max
);
1949 /* Has the minimum directive output length exceeded INT_MAX? */
1950 bool exceedmin
= res
->number_chars_min
> target_int_max ();
1954 || (1 < warn_format_length
1955 && res
->number_chars_max
> target_int_max ())))
1957 /* The directive output causes the total length of output
1958 to exceed INT_MAX bytes. */
1960 if (fmtres
.range
.min
== fmtres
.range
.max
)
1961 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1962 OPT_Wformat_length_
,
1963 "%<%.*s%> directive output of %wu bytes causes "
1964 "result to exceed %<INT_MAX%>",
1965 (int)cvtlen
, cvtbeg
, fmtres
.range
.min
);
1970 ? G_ ("%<%.*s%> directive output between %wu and %wu "
1971 "bytes causes result to exceed %<INT_MAX%>")
1972 : G_ ("%<%.*s%> directive output between %wu and %wu "
1973 "bytes may cause result to exceed %<INT_MAX%>"));
1974 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1975 OPT_Wformat_length_
, fmtstr
,
1976 (int)cvtlen
, cvtbeg
,
1977 fmtres
.range
.min
, fmtres
.range
.max
);
1982 /* Account for the number of bytes between BEG and END (or between
1983 BEG + strlen (BEG) when END is null) in the format string in a call
1984 to a formatted output function described by INFO. Reflect the count
1985 in RES and issue warnings as appropriate. */
1988 add_bytes (const pass_sprintf_length::call_info
&info
,
1989 const char *beg
, const char *end
, format_result
*res
)
1991 if (res
->number_chars_min
>= HOST_WIDE_INT_MAX
)
1994 /* The number of bytes to output is the number of bytes between
1995 the end of the last directive and the beginning of the next
1996 one if it exists, otherwise the number of characters remaining
1997 in the format string plus 1 for the terminating NUL. */
1998 size_t nbytes
= end
? end
- beg
: strlen (beg
) + 1;
2000 /* Return if there are no bytes to add at this time but there are
2001 directives remaining in the format string. */
2005 /* Compute the range of available bytes in the destination. There
2006 must always be at least one byte left for the terminating NUL
2007 that's appended after the format string has been processed. */
2008 result_range avail_range
= bytes_remaining (info
.objsize
, *res
);
2010 /* If issuing a diagnostic (only when one hasn't already been issued),
2011 distinguish between a possible overflow ("may write") and a certain
2012 overflow somewhere "past the end." (Ditto for truncation.)
2013 KNOWNRANGE is used to warn even at level 1 about possibly writing
2014 past the end or truncation due to strings of unknown lengths that
2015 are bounded by the arrays they are known to refer to. */
2017 && (avail_range
.max
< nbytes
2018 || ((res
->knownrange
|| 1 < warn_format_length
)
2019 && avail_range
.min
< nbytes
)))
2021 /* Set NAVAIL to the number of available bytes used to decide
2022 whether or not to issue a warning below. The exact kind of
2023 warning will depend on AVAIL_RANGE. */
2024 unsigned HOST_WIDE_INT navail
= avail_range
.max
;
2025 if (nbytes
<= navail
&& avail_range
.min
< HOST_WIDE_INT_MAX
2026 && (res
->knownrange
|| 1 < warn_format_length
))
2027 navail
= avail_range
.min
;
2029 /* Compute the offset of the first format character that is beyond
2030 the end of the destination region and the length of the rest of
2031 the format string from that point on. */
2032 unsigned HOST_WIDE_INT off
2033 = (unsigned HOST_WIDE_INT
)(beg
- info
.fmtstr
) + navail
;
2035 size_t len
= strlen (info
.fmtstr
+ off
);
2037 /* Create a location that underscores the substring of the format
2038 string that is or may be written past the end (or is or may be
2039 truncated), pointing the caret at the first character of the
2042 (info
.fmtloc
, TREE_TYPE (info
.format
), off
, len
? off
: 0,
2045 /* Is the output of the last directive the result of the argument
2046 being within a range whose lower bound would fit in the buffer
2047 but the upper bound would not? If so, use the word "may" to
2048 indicate that the overflow/truncation may (but need not) happen. */
2050 = (res
->number_chars_min
< res
->number_chars_max
2051 && res
->number_chars_min
< info
.objsize
);
2053 if (!end
&& ((nbytes
- navail
) == 1 || boundrange
))
2055 /* There is room for the rest of the format string but none
2056 for the terminating nul. */
2058 = (info
.bounded
// Snprintf and the like.
2060 ? G_("output may be truncated before the last format character"
2061 : "output truncated before the last format character"))
2063 ? G_("may write a terminating nul past the end "
2064 "of the destination")
2065 : G_("writing a terminating nul past the end "
2066 "of the destination")));
2068 res
->warned
= fmtwarn (loc
, NULL
, NULL
, OPT_Wformat_length_
, text
);
2072 /* There isn't enough room for 1 or more characters that remain
2073 to copy from the format string. */
2075 = (info
.bounded
// Snprintf and the like.
2077 ? G_("output may be truncated at or before format character "
2078 "%qc at offset %wu")
2079 : G_("output truncated at format character %qc at offset %wu"))
2080 : (res
->number_chars
>= HOST_WIDE_INT_MAX
2081 ? G_("may write format character %#qc at offset %wu past "
2082 "the end of the destination")
2083 : G_("writing format character %#qc at offset %wu past "
2084 "the end of the destination")));
2086 res
->warned
= fmtwarn (loc
, NULL
, NULL
, OPT_Wformat_length_
,
2087 text
, info
.fmtstr
[off
], off
);
2091 if (res
->warned
&& !end
&& info
.objsize
< HOST_WIDE_INT_MAX
)
2093 /* If a warning has been issued for buffer overflow or truncation
2094 (but not otherwise) help the user figure out how big a buffer
2097 location_t callloc
= gimple_location (info
.callstmt
);
2099 unsigned HOST_WIDE_INT min
= res
->number_chars_min
;
2100 unsigned HOST_WIDE_INT max
= res
->number_chars_max
;
2101 unsigned HOST_WIDE_INT exact
2102 = (res
->number_chars
< HOST_WIDE_INT_MAX
2103 ? res
->number_chars
: res
->number_chars_min
);
2105 if (min
< max
&& max
< HOST_WIDE_INT_MAX
)
2107 "format output between %wu and %wu bytes into "
2108 "a destination of size %wu",
2109 min
+ nbytes
, max
+ nbytes
, info
.objsize
);
2112 (nbytes
+ exact
== 1
2113 ? G_("format output %wu byte into a destination of size %wu")
2114 : G_("format output %wu bytes into a destination of size %wu")),
2115 nbytes
+ exact
, info
.objsize
);
2118 /* Add the number of bytes and then check for INT_MAX overflow. */
2121 /* Has the minimum output length minus the terminating nul exceeded
2123 bool exceedmin
= (res
->number_chars_min
- !end
) > target_int_max ();
2127 || (1 < warn_format_length
2128 && (res
->number_chars_max
- !end
) > target_int_max ())))
2130 /* The function's output exceeds INT_MAX bytes. */
2132 /* Set NAVAIL to the number of available bytes used to decide
2133 whether or not to issue a warning below. The exact kind of
2134 warning will depend on AVAIL_RANGE. */
2135 unsigned HOST_WIDE_INT navail
= avail_range
.max
;
2136 if (nbytes
<= navail
&& avail_range
.min
< HOST_WIDE_INT_MAX
2137 && (res
->bounded
|| 1 < warn_format_length
))
2138 navail
= avail_range
.min
;
2140 /* Compute the offset of the first format character that is beyond
2141 the end of the destination region and the length of the rest of
2142 the format string from that point on. */
2143 unsigned HOST_WIDE_INT off
= (unsigned HOST_WIDE_INT
)(beg
- info
.fmtstr
);
2144 if (navail
< HOST_WIDE_INT_MAX
)
2147 size_t len
= strlen (info
.fmtstr
+ off
);
2150 (info
.fmtloc
, TREE_TYPE (info
.format
), off
- !len
, len
? off
: 0,
2153 if (res
->number_chars_min
== res
->number_chars_max
)
2154 res
->warned
= fmtwarn (loc
, NULL
, NULL
,
2155 OPT_Wformat_length_
,
2156 "output of %wu bytes causes "
2157 "result to exceed %<INT_MAX%>",
2158 res
->number_chars_min
- !end
);
2163 ? G_ ("output between %wu and %wu bytes causes "
2164 "result to exceed %<INT_MAX%>")
2165 : G_ ("output between %wu and %wu bytes may cause "
2166 "result to exceed %<INT_MAX%>"));
2167 res
->warned
= fmtwarn (loc
, NULL
, NULL
, OPT_Wformat_length_
,
2169 res
->number_chars_min
- !end
,
2170 res
->number_chars_max
- !end
);
2175 #pragma GCC diagnostic pop
2177 /* Compute the length of the output resulting from the call to a formatted
2178 output function described by INFO and store the result of the call in
2179 *RES. Issue warnings for detected past the end writes. */
2182 pass_sprintf_length::compute_format_length (const call_info
&info
,
2185 /* The variadic argument counter. */
2186 unsigned argno
= info
.argidx
;
2188 /* Reset exact, minimum, and maximum character counters. */
2189 res
->number_chars
= res
->number_chars_min
= res
->number_chars_max
= 0;
2191 /* No directive has been seen yet so the length of output is bounded
2192 by the known range [0, 0] and constant (with no conversion producing
2193 more than 4K bytes) until determined otherwise. */
2194 res
->bounded
= true;
2195 res
->knownrange
= true;
2196 res
->constant
= true;
2197 res
->under4k
= true;
2198 res
->floating
= false;
2199 res
->warned
= false;
2201 const char *pf
= info
.fmtstr
;
2205 /* The beginning of the next format directive. */
2206 const char *dir
= strchr (pf
, '%');
2208 /* Add the number of bytes between the end of the last directive
2209 and either the next if one exists, or the end of the format
2211 add_bytes (info
, pf
, dir
, res
);
2220 /* Incomplete directive. */
2224 conversion_spec spec
= conversion_spec ();
2226 /* POSIX numbered argument index or zero when none. */
2227 unsigned dollar
= 0;
2231 /* This could be either a POSIX positional argument, the '0'
2232 flag, or a width, depending on what follows. Store it as
2233 width and sort it out later after the next character has
2236 spec
.width
= strtol (pf
, &end
, 10);
2237 spec
.have_width
= true;
2240 else if ('*' == *pf
)
2242 /* Similarly to the block above, this could be either a POSIX
2243 positional argument or a width, depending on what follows. */
2244 if (argno
< gimple_call_num_args (info
.callstmt
))
2245 spec
.star_width
= gimple_call_arg (info
.callstmt
, argno
++);
2253 /* Handle the POSIX dollar sign which references the 1-based
2254 positional argument number. */
2255 if (spec
.have_width
)
2256 dollar
= spec
.width
+ info
.argidx
;
2257 else if (spec
.star_width
2258 && TREE_CODE (spec
.star_width
) == INTEGER_CST
)
2259 dollar
= spec
.width
+ tree_to_shwi (spec
.star_width
);
2261 /* Bail when the numbered argument is out of range (it will
2262 have already been diagnosed by -Wformat). */
2264 || dollar
== info
.argidx
2265 || dollar
> gimple_call_num_args (info
.callstmt
))
2270 spec
.star_width
= NULL_TREE
;
2271 spec
.have_width
= false;
2275 if (dollar
|| !spec
.star_width
)
2277 if (spec
.have_width
&& spec
.width
== 0)
2279 /* The '0' that has been interpreted as a width above is
2280 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
2281 and continue processing other flags. */
2282 spec
.have_width
= false;
2283 spec
.set_flag ('0');
2285 /* When either '$' has been seen, or width has not been seen,
2286 the next field is the optional flags followed by an optional
2296 spec
.set_flag (*pf
++);
2308 spec
.width
= strtol (pf
, &end
, 10);
2309 spec
.have_width
= true;
2312 else if ('*' == *pf
)
2314 spec
.star_width
= gimple_call_arg (info
.callstmt
, argno
++);
2317 else if ('\'' == *pf
)
2319 /* The POSIX apostrophe indicating a numeric grouping
2320 in the current locale. Even though it's possible to
2321 estimate the upper bound on the size of the output
2322 based on the number of digits it probably isn't worth
2335 spec
.precision
= strtol (pf
, &end
, 10);
2336 spec
.have_precision
= true;
2339 else if ('*' == *pf
)
2341 spec
.star_precision
= gimple_call_arg (info
.callstmt
, argno
++);
2354 spec
.modifier
= FMT_LEN_hh
;
2357 spec
.modifier
= FMT_LEN_h
;
2362 spec
.modifier
= FMT_LEN_j
;
2367 spec
.modifier
= FMT_LEN_L
;
2375 spec
.modifier
= FMT_LEN_ll
;
2378 spec
.modifier
= FMT_LEN_l
;
2383 spec
.modifier
= FMT_LEN_t
;
2388 spec
.modifier
= FMT_LEN_z
;
2395 /* Handle a sole '%' character the same as "%%" but since it's
2396 undefined prevent the result from being folded. */
2399 res
->bounded
= false;
2402 spec
.fmtfunc
= format_percent
;
2413 res
->floating
= true;
2414 spec
.fmtfunc
= format_floating
;
2423 spec
.fmtfunc
= format_integer
;
2427 spec
.fmtfunc
= format_pointer
;
2436 spec
.fmtfunc
= format_string
;
2443 spec
.specifier
= *pf
++;
2445 /* Compute the length of the format directive. */
2446 size_t dirlen
= pf
- dir
;
2448 /* Extract the argument if the directive takes one and if it's
2449 available (e.g., the function doesn't take a va_list). Treat
2450 missing arguments the same as va_list, even though they will
2451 have likely already been diagnosed by -Wformat. */
2452 tree arg
= NULL_TREE
;
2453 if (spec
.specifier
!= '%'
2454 && argno
< gimple_call_num_args (info
.callstmt
))
2455 arg
= gimple_call_arg (info
.callstmt
, dollar
? dollar
: argno
++);
2457 ::format_directive (info
, res
, dir
, dirlen
, spec
, arg
);
2461 /* Return the size of the object referenced by the expression DEST if
2462 available, or -1 otherwise. */
2464 static unsigned HOST_WIDE_INT
2465 get_destination_size (tree dest
)
2467 /* Use __builtin_object_size to determine the size of the destination
2468 object. When optimizing, determine the smallest object (such as
2469 a member array as opposed to the whole enclosing object), otherwise
2470 use type-zero object size to determine the size of the enclosing
2471 object (the function fails without optimization in this type). */
2472 int ost
= optimize
> 0;
2473 unsigned HOST_WIDE_INT size
;
2474 if (compute_builtin_object_size (dest
, ost
, &size
))
2477 return HOST_WIDE_INT_M1U
;
2480 /* Given a suitable result RES of a call to a formatted output function
2481 described by INFO, substitute the result for the return value of
2482 the call. The result is suitable if the number of bytes it represents
2483 is known and exact. A result that isn't suitable for substitution may
2484 have its range set to the range of return values, if that is known. */
2487 try_substitute_return_value (gimple_stmt_iterator gsi
,
2488 const pass_sprintf_length::call_info
&info
,
2489 const format_result
&res
)
2491 tree lhs
= gimple_get_lhs (info
.callstmt
);
2493 /* Avoid the return value optimization when the behavior of the call
2494 is undefined either because any directive may have produced 4K or
2495 more of output, or the return value exceeds INT_MAX, or because
2496 the output overflows the destination object (but leave it enabled
2497 when the function is bounded because then the behavior is well-
2499 if (lhs
&& res
.bounded
&& res
.under4k
2500 && (info
.bounded
|| res
.number_chars
<= info
.objsize
)
2501 && res
.number_chars
- 1 <= target_int_max ())
2503 /* Replace the left-hand side of the call with the constant
2504 result of the formatted function minus 1 for the terminating
2505 NUL which the functions' return value does not include. */
2506 gimple_call_set_lhs (info
.callstmt
, NULL_TREE
);
2507 tree cst
= build_int_cst (integer_type_node
, res
.number_chars
- 1);
2508 gimple
*g
= gimple_build_assign (lhs
, cst
);
2509 gsi_insert_after (&gsi
, g
, GSI_NEW_STMT
);
2510 update_stmt (info
.callstmt
);
2514 location_t callloc
= gimple_location (info
.callstmt
);
2515 fprintf (dump_file
, "On line %i substituting ",
2516 LOCATION_LINE (callloc
));
2517 print_generic_expr (dump_file
, cst
, dump_flags
);
2518 fprintf (dump_file
, " for ");
2519 print_generic_expr (dump_file
, info
.func
, dump_flags
);
2520 fprintf (dump_file
, " return value (output %s).\n",
2521 res
.constant
? "constant" : "variable");
2526 unsigned HOST_WIDE_INT maxbytes
;
2530 && ((maxbytes
= res
.number_chars
- 1) <= target_int_max ()
2531 || (res
.number_chars_min
- 1 <= target_int_max ()
2532 && (maxbytes
= res
.number_chars_max
- 1) <= target_int_max ()))
2533 && (info
.bounded
|| maxbytes
< info
.objsize
))
2535 /* If the result is in a valid range bounded by the size of
2536 the destination set it so that it can be used for subsequent
2538 int prec
= TYPE_PRECISION (integer_type_node
);
2540 if (res
.number_chars
< target_int_max () && res
.under4k
)
2542 wide_int num
= wi::shwi (res
.number_chars
- 1, prec
);
2543 set_range_info (lhs
, VR_RANGE
, num
, num
);
2545 else if (res
.number_chars_min
< target_int_max ()
2546 && res
.number_chars_max
< target_int_max ())
2548 wide_int min
= wi::shwi (res
.under4k
? res
.number_chars_min
- 1
2549 : target_int_min (), prec
);
2550 wide_int max
= wi::shwi (res
.number_chars_max
- 1, prec
);
2551 set_range_info (lhs
, VR_RANGE
, min
, max
);
2557 const char *inbounds
2558 = (res
.number_chars_min
<= info
.objsize
2559 ? (res
.number_chars_max
<= info
.objsize
2560 ? "in" : "potentially out-of")
2563 location_t callloc
= gimple_location (info
.callstmt
);
2564 fprintf (dump_file
, "On line %i ", LOCATION_LINE (callloc
));
2565 print_generic_expr (dump_file
, info
.func
, dump_flags
);
2567 const char *ign
= lhs
? "" : " ignored";
2568 if (res
.number_chars
>= HOST_WIDE_INT_MAX
)
2570 " %s-bounds return value in range [%lu, %lu]%s.\n",
2572 (unsigned long)res
.number_chars_min
,
2573 (unsigned long)res
.number_chars_max
, ign
);
2575 fprintf (dump_file
, " %s-bounds return value %lu%s.\n",
2576 inbounds
, (unsigned long)res
.number_chars
, ign
);
2581 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
2582 functions and if so, handle it. */
2585 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator gsi
)
2587 call_info info
= call_info ();
2589 info
.callstmt
= gsi_stmt (gsi
);
2590 if (!gimple_call_builtin_p (info
.callstmt
, BUILT_IN_NORMAL
))
2593 info
.func
= gimple_call_fndecl (info
.callstmt
);
2594 info
.fncode
= DECL_FUNCTION_CODE (info
.func
);
2596 /* The size of the destination as in snprintf(dest, size, ...). */
2597 unsigned HOST_WIDE_INT dstsize
= HOST_WIDE_INT_M1U
;
2599 /* The size of the destination determined by __builtin_object_size. */
2600 unsigned HOST_WIDE_INT objsize
= HOST_WIDE_INT_M1U
;
2602 /* Buffer size argument number (snprintf and vsnprintf). */
2603 unsigned HOST_WIDE_INT idx_dstsize
= HOST_WIDE_INT_M1U
;
2605 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
2606 unsigned HOST_WIDE_INT idx_objsize
= HOST_WIDE_INT_M1U
;
2608 /* Format string argument number (valid for all functions). */
2609 unsigned idx_format
;
2611 switch (info
.fncode
)
2613 case BUILT_IN_SPRINTF
:
2615 // __builtin_sprintf (dst, format, ...)
2620 case BUILT_IN_SPRINTF_CHK
:
2622 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
2628 case BUILT_IN_SNPRINTF
:
2630 // __builtin_snprintf (dst, size, format, ...)
2634 info
.bounded
= true;
2637 case BUILT_IN_SNPRINTF_CHK
:
2639 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
2644 info
.bounded
= true;
2647 case BUILT_IN_VSNPRINTF
:
2649 // __builtin_vsprintf (dst, size, format, va)
2653 info
.bounded
= true;
2656 case BUILT_IN_VSNPRINTF_CHK
:
2658 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
2663 info
.bounded
= true;
2666 case BUILT_IN_VSPRINTF
:
2668 // __builtin_vsprintf (dst, format, va)
2673 case BUILT_IN_VSPRINTF_CHK
:
2675 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
2685 info
.format
= gimple_call_arg (info
.callstmt
, idx_format
);
2687 if (idx_dstsize
== HOST_WIDE_INT_M1U
)
2689 // For non-bounded functions like sprintf, to determine
2690 // the size of the destination from the object or pointer
2691 // passed to it as the first argument.
2692 dstsize
= get_destination_size (gimple_call_arg (info
.callstmt
, 0));
2694 else if (tree size
= gimple_call_arg (info
.callstmt
, idx_dstsize
))
2696 /* For bounded functions try to get the size argument. */
2698 if (TREE_CODE (size
) == INTEGER_CST
)
2700 dstsize
= tree_to_uhwi (size
);
2701 /* No object can be larger than SIZE_MAX bytes (half the address
2702 space) on the target. This imposes a limit that's one byte
2704 if (dstsize
>= target_size_max () / 2)
2705 warning_at (gimple_location (info
.callstmt
), OPT_Wformat_length_
,
2706 "specified destination size %wu too large",
2709 else if (TREE_CODE (size
) == SSA_NAME
)
2711 /* Try to determine the range of values of the argument
2712 and use the greater of the two at -Wformat-level 1 and
2713 the smaller of them at level 2. */
2715 enum value_range_type range_type
2716 = get_range_info (size
, &min
, &max
);
2717 if (range_type
== VR_RANGE
)
2720 = (warn_format_length
< 2
2721 ? wi::fits_uhwi_p (max
) ? max
.to_uhwi () : max
.to_shwi ()
2722 : wi::fits_uhwi_p (min
) ? min
.to_uhwi () : min
.to_shwi ());
2727 if (idx_objsize
!= HOST_WIDE_INT_M1U
)
2729 if (tree size
= gimple_call_arg (info
.callstmt
, idx_objsize
))
2730 if (tree_fits_uhwi_p (size
))
2731 objsize
= tree_to_uhwi (size
);
2734 if (info
.bounded
&& !dstsize
)
2736 /* As a special case, when the explicitly specified destination
2737 size argument (to a bounded function like snprintf) is zero
2738 it is a request to determine the number of bytes on output
2739 without actually producing any. Pretend the size is
2740 unlimited in this case. */
2741 info
.objsize
= HOST_WIDE_INT_MAX
;
2745 /* Set the object size to the smaller of the two arguments
2746 of both have been specified and they're not equal. */
2747 info
.objsize
= dstsize
< objsize
? dstsize
: objsize
;
2750 && dstsize
< target_size_max () / 2 && objsize
< dstsize
)
2752 warning_at (gimple_location (info
.callstmt
), OPT_Wformat_length_
,
2753 "specified size %wu exceeds the size %wu "
2754 "of the destination object", dstsize
, objsize
);
2758 if (integer_zerop (info
.format
))
2760 /* This is diagnosed with -Wformat only when the null is a constant
2761 pointer. The warning here diagnoses instances where the pointer
2763 warning_at (EXPR_LOC_OR_LOC (info
.format
, input_location
),
2764 OPT_Wformat_length_
, "null format string");
2768 info
.fmtstr
= get_format_string (info
.format
, &info
.fmtloc
);
2772 /* The result is the number of bytes output by the formatted function,
2773 including the terminating NUL. */
2774 format_result res
= format_result ();
2775 compute_format_length (info
, &res
);
2777 /* When optimizing and the printf return value optimization is enabled,
2778 attempt to substitute the computed result for the return value of
2779 the call. Avoid this optimization when -frounding-math is in effect
2780 and the format string contains a floating point directive. */
2782 && flag_printf_return_value
2783 && (!flag_rounding_math
|| !res
.floating
))
2784 try_substitute_return_value (gsi
, info
, res
);
2787 /* Execute the pass for function FUN. */
2790 pass_sprintf_length::execute (function
*fun
)
2793 FOR_EACH_BB_FN (bb
, fun
)
2795 for (gimple_stmt_iterator si
= gsi_start_bb (bb
); !gsi_end_p (si
);
2798 /* Iterate over statements, looking for function calls. */
2799 gimple
*stmt
= gsi_stmt (si
);
2801 if (is_gimple_call (stmt
))
2802 handle_gimple_call (si
);
2809 } /* Unnamed namespace. */
2811 /* Return a pointer to a pass object newly constructed from the context
2815 make_pass_sprintf_length (gcc::context
*ctxt
)
2817 return new pass_sprintf_length (ctxt
);