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"
75 #include "targhooks.h"
80 #include "substring-locations.h"
81 #include "diagnostic.h"
83 /* The likely worst case value of MB_LEN_MAX for the target, large enough
84 for UTF-8. Ideally, this would be obtained by a target hook if it were
85 to be used for optimization but it's good enough as is for warnings. */
86 #define target_mb_len_max 6
90 const pass_data pass_data_sprintf_length
= {
91 GIMPLE_PASS
, // pass type
92 "printf-return-value", // pass name
93 OPTGROUP_NONE
, // optinfo_flags
95 PROP_cfg
, // properties_required
96 0, // properties_provided
97 0, // properties_destroyed
98 0, // properties_start
99 0, // properties_finish
102 struct format_result
;
104 class pass_sprintf_length
: public gimple_opt_pass
106 bool fold_return_value
;
109 pass_sprintf_length (gcc::context
*ctxt
)
110 : gimple_opt_pass (pass_data_sprintf_length
, ctxt
),
111 fold_return_value (false)
114 opt_pass
* clone () { return new pass_sprintf_length (m_ctxt
); }
116 virtual bool gate (function
*);
118 virtual unsigned int execute (function
*);
120 void set_pass_param (unsigned int n
, bool param
)
123 fold_return_value
= param
;
126 void handle_gimple_call (gimple_stmt_iterator
*);
129 void compute_format_length (const call_info
&, format_result
*);
133 pass_sprintf_length::gate (function
*)
135 /* Run the pass iff -Warn-format-length is specified and either
136 not optimizing and the pass is being invoked early, or when
137 optimizing and the pass is being invoked during optimization
139 return ((warn_format_length
> 0 || flag_printf_return_value
)
140 && (optimize
> 0) == fold_return_value
);
143 /* The result of a call to a formatted function. */
147 /* Number of characters written by the formatted function, exact,
148 minimum and maximum when an exact number cannot be determined.
149 Setting the minimum to HOST_WIDE_INT_MAX disables all length
150 tracking for the remainder of the format string.
151 Setting either of the other two members to HOST_WIDE_INT_MAX
152 disables the exact or maximum length tracking, respectively,
153 but continues to track the maximum. */
154 unsigned HOST_WIDE_INT number_chars
;
155 unsigned HOST_WIDE_INT number_chars_min
;
156 unsigned HOST_WIDE_INT number_chars_max
;
158 /* True when the range given by NUMBER_CHARS_MIN and NUMBER_CHARS_MAX
159 can be relied on for value range propagation, false otherwise.
160 This means that BOUNDED must not be set if the number of bytes
161 produced by any directive is unspecified or implementation-
162 defined (unless the implementation's behavior is known and
163 determined via a target hook).
164 Note that BOUNDED only implies that the length of a function's
165 output is known to be within some range, not that it's constant
166 and a candidate for string folding. BOUNDED is a stronger
167 guarantee than KNOWNRANGE. */
170 /* True when the range above is obtained from known values of
171 directive arguments or their bounds and not the result of
172 heuristics that depend on warning levels. It is used to
173 issue stricter diagnostics in cases where strings of unknown
174 lengths are bounded by the arrays they are determined to
175 refer to. KNOWNRANGE must not be used to set the range of
176 the return value of a call. */
179 /* True when the output of the formatted call is constant (and
180 thus a candidate for string constant folding). This is rare
181 and typically requires that the arguments of all directives
182 are also constant. CONSTANT implies BOUNDED. */
185 /* True if no individual directive resulted in more than 4095 bytes
186 of output (the total NUMBER_CHARS might be greater). */
189 /* True when a floating point directive has been seen in the format
193 /* True when an intermediate result has caused a warning. Used to
194 avoid issuing duplicate warnings while finishing the processing
198 /* Preincrement the number of output characters by 1. */
199 format_result
& operator++ ()
204 /* Postincrement the number of output characters by 1. */
205 format_result
operator++ (int)
207 format_result
prev (*this);
212 /* Increment the number of output characters by N. */
213 format_result
& operator+= (unsigned HOST_WIDE_INT n
)
215 gcc_assert (n
< HOST_WIDE_INT_MAX
);
217 if (number_chars
< HOST_WIDE_INT_MAX
)
219 if (number_chars_min
< HOST_WIDE_INT_MAX
)
220 number_chars_min
+= n
;
221 if (number_chars_max
< HOST_WIDE_INT_MAX
)
222 number_chars_max
+= n
;
227 /* Return the value of INT_MIN for the target. */
229 static inline HOST_WIDE_INT
232 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node
));
235 /* Return the value of INT_MAX for the target. */
237 static inline unsigned HOST_WIDE_INT
240 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node
));
243 /* Return the value of SIZE_MAX for the target. */
245 static inline unsigned HOST_WIDE_INT
248 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node
));
251 /* Return the constant initial value of DECL if available or DECL
252 otherwise. Same as the synonymous function in c/c-typeck.c. */
255 decl_constant_value (tree decl
)
257 if (/* Don't change a variable array bound or initial value to a constant
258 in a place where a variable is invalid. Note that DECL_INITIAL
259 isn't valid for a PARM_DECL. */
260 current_function_decl
!= 0
261 && TREE_CODE (decl
) != PARM_DECL
262 && !TREE_THIS_VOLATILE (decl
)
263 && TREE_READONLY (decl
)
264 && DECL_INITIAL (decl
) != 0
265 && TREE_CODE (DECL_INITIAL (decl
)) != ERROR_MARK
266 /* This is invalid if initial value is not constant.
267 If it has either a function call, a memory reference,
268 or a variable, then re-evaluating it could give different results. */
269 && TREE_CONSTANT (DECL_INITIAL (decl
))
270 /* Check for cases where this is sub-optimal, even though valid. */
271 && TREE_CODE (DECL_INITIAL (decl
)) != CONSTRUCTOR
)
272 return DECL_INITIAL (decl
);
276 /* Given FORMAT, set *PLOC to the source location of the format string
277 and return the format string if it is known or null otherwise. */
280 get_format_string (tree format
, location_t
*ploc
)
284 /* Pull out a constant value if the front end didn't. */
285 format
= decl_constant_value (format
);
289 if (integer_zerop (format
))
291 /* FIXME: Diagnose null format string if it hasn't been diagnosed
292 by -Wformat (the latter diagnoses only nul pointer constants,
293 this pass can do better). */
297 HOST_WIDE_INT offset
= 0;
299 if (TREE_CODE (format
) == POINTER_PLUS_EXPR
)
301 tree arg0
= TREE_OPERAND (format
, 0);
302 tree arg1
= TREE_OPERAND (format
, 1);
306 if (TREE_CODE (arg1
) != INTEGER_CST
)
311 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
312 if (!cst_and_fits_in_hwi (arg1
))
315 offset
= int_cst_value (arg1
);
318 if (TREE_CODE (format
) != ADDR_EXPR
)
321 *ploc
= EXPR_LOC_OR_LOC (format
, input_location
);
323 format
= TREE_OPERAND (format
, 0);
325 if (TREE_CODE (format
) == ARRAY_REF
326 && tree_fits_shwi_p (TREE_OPERAND (format
, 1))
327 && (offset
+= tree_to_shwi (TREE_OPERAND (format
, 1))) >= 0)
328 format
= TREE_OPERAND (format
, 0);
334 tree array_size
= NULL_TREE
;
337 && TREE_CODE (TREE_TYPE (format
)) == ARRAY_TYPE
338 && (array_init
= decl_constant_value (format
)) != format
339 && TREE_CODE (array_init
) == STRING_CST
)
341 /* Extract the string constant initializer. Note that this may
342 include a trailing NUL character that is not in the array (e.g.
343 const char a[3] = "foo";). */
344 array_size
= DECL_SIZE_UNIT (format
);
348 if (TREE_CODE (format
) != STRING_CST
)
351 if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format
))) != char_type_node
)
353 /* Wide format string. */
357 const char *fmtstr
= TREE_STRING_POINTER (format
);
358 unsigned fmtlen
= TREE_STRING_LENGTH (format
);
362 /* Variable length arrays can't be initialized. */
363 gcc_assert (TREE_CODE (array_size
) == INTEGER_CST
);
365 if (tree_fits_shwi_p (array_size
))
367 HOST_WIDE_INT array_size_value
= tree_to_shwi (array_size
);
368 if (array_size_value
> 0
369 && array_size_value
== (int) array_size_value
370 && fmtlen
> array_size_value
)
371 fmtlen
= array_size_value
;
376 if (offset
>= fmtlen
)
383 if (fmtlen
< 1 || fmtstr
[--fmtlen
] != 0)
385 /* FIXME: Diagnose an unterminated format string if it hasn't been
386 diagnosed by -Wformat. Similarly to a null format pointer,
387 -Wformay diagnoses only nul pointer constants, this pass can
395 /* The format_warning_at_substring function is not used here in a way
396 that makes using attribute format viable. Suppress the warning. */
398 #pragma GCC diagnostic push
399 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
401 /* For convenience and brevity. */
404 (* const fmtwarn
) (const substring_loc
&, const source_range
*,
405 const char *, int, const char *, ...)
406 = format_warning_at_substring
;
408 /* Format length modifiers. */
413 FMT_LEN_hh
, // char argument
416 FMT_LEN_ll
, // long long
417 FMT_LEN_L
, // long double (and GNU long long)
419 FMT_LEN_t
, // ptrdiff_t
420 FMT_LEN_j
// intmax_t
424 /* A minimum and maximum number of bytes. */
428 unsigned HOST_WIDE_INT min
, max
;
431 /* Description of the result of conversion either of a single directive
432 or the whole format string. */
437 : argmin (), argmax (), knownrange (), bounded (), constant ()
439 range
.min
= range
.max
= HOST_WIDE_INT_MAX
;
442 /* The range a directive's argument is in. */
445 /* The minimum and maximum number of bytes that a directive
446 results in on output for an argument in the range above. */
449 /* True when the range above is obtained from a known value of
450 a directive's argument or its bounds and not the result of
451 heuristics that depend on warning levels. */
454 /* True when the range is the result of an argument determined
455 to be bounded to a subrange of its type or value (such as by
456 value range propagation or the width of the formt directive),
460 /* True when the output of a directive is constant. This is rare
461 and typically requires that the argument(s) of the directive
462 are also constant (such as determined by constant propagation,
463 though not value range propagation). */
467 /* Description of a conversion specification. */
469 struct conversion_spec
471 /* A bitmap of flags, one for each character. */
472 unsigned flags
[256 / sizeof (int)];
473 /* Numeric width as in "%8x". */
475 /* Numeric precision as in "%.32s". */
478 /* Width specified via the '*' character. */
480 /* Precision specified via the asterisk. */
483 /* Length modifier. */
484 format_lengths modifier
;
486 /* Format specifier character. */
489 /* Numeric width was given. */
490 unsigned have_width
: 1;
491 /* Numeric precision was given. */
492 unsigned have_precision
: 1;
493 /* Non-zero when certain flags should be interpreted even for a directive
494 that normally doesn't accept them (used when "%p" with flags such as
495 space or plus is interepreted as a "%x". */
496 unsigned force_flags
: 1;
498 /* Format conversion function that given a conversion specification
499 and an argument returns the formatting result. */
500 fmtresult (*fmtfunc
) (const conversion_spec
&, tree
);
502 /* Return True when a the format flag CHR has been used. */
503 bool get_flag (char chr
) const
505 unsigned char c
= chr
& 0xff;
506 return (flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
507 & (1U << (c
% (CHAR_BIT
* sizeof *flags
))));
510 /* Make a record of the format flag CHR having been used. */
511 void set_flag (char chr
)
513 unsigned char c
= chr
& 0xff;
514 flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
515 |= (1U << (c
% (CHAR_BIT
* sizeof *flags
)));
518 /* Reset the format flag CHR. */
519 void clear_flag (char chr
)
521 unsigned char c
= chr
& 0xff;
522 flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
523 &= ~(1U << (c
% (CHAR_BIT
* sizeof *flags
)));
527 /* Return the logarithm of X in BASE. */
530 ilog (unsigned HOST_WIDE_INT x
, int base
)
541 /* Return the number of bytes resulting from converting into a string
542 the INTEGER_CST tree node X in BASE. PLUS indicates whether 1 for
543 a plus sign should be added for positive numbers, and PREFIX whether
544 the length of an octal ('O') or hexadecimal ('0x') prefix should be
545 added for nonzero numbers. Return -1 if X cannot be represented. */
548 tree_digits (tree x
, int base
, bool plus
, bool prefix
)
550 unsigned HOST_WIDE_INT absval
;
554 if (TYPE_UNSIGNED (TREE_TYPE (x
)))
556 if (tree_fits_uhwi_p (x
))
558 absval
= tree_to_uhwi (x
);
566 if (tree_fits_shwi_p (x
))
568 HOST_WIDE_INT i
= tree_to_shwi (x
);
584 res
+= ilog (absval
, base
);
586 if (prefix
&& absval
)
597 /* Given the formatting result described by RES and NAVAIL, the number
598 of available in the destination, return the number of bytes remaining
599 in the destination. */
601 static inline result_range
602 bytes_remaining (unsigned HOST_WIDE_INT navail
, const format_result
&res
)
606 if (HOST_WIDE_INT_MAX
<= navail
)
608 range
.min
= range
.max
= navail
;
612 if (res
.number_chars
< navail
)
614 range
.min
= range
.max
= navail
- res
.number_chars
;
616 else if (res
.number_chars_min
< navail
)
618 range
.max
= navail
- res
.number_chars_min
;
623 if (res
.number_chars_max
< navail
)
624 range
.min
= navail
- res
.number_chars_max
;
631 /* Given the formatting result described by RES and NAVAIL, the number
632 of available in the destination, return the minimum number of bytes
633 remaining in the destination. */
635 static inline unsigned HOST_WIDE_INT
636 min_bytes_remaining (unsigned HOST_WIDE_INT navail
, const format_result
&res
)
638 if (HOST_WIDE_INT_MAX
<= navail
)
641 if (1 < warn_format_length
|| res
.bounded
)
643 /* At level 2, or when all directives output an exact number
644 of bytes or when their arguments were bounded by known
645 ranges, use the greater of the two byte counters if it's
646 valid to compute the result. */
647 if (res
.number_chars_max
< HOST_WIDE_INT_MAX
)
648 navail
-= res
.number_chars_max
;
649 else if (res
.number_chars
< HOST_WIDE_INT_MAX
)
650 navail
-= res
.number_chars
;
651 else if (res
.number_chars_min
< HOST_WIDE_INT_MAX
)
652 navail
-= res
.number_chars_min
;
656 /* At level 1 use the smaller of the byte counters to compute
658 if (res
.number_chars
< HOST_WIDE_INT_MAX
)
659 navail
-= res
.number_chars
;
660 else if (res
.number_chars_min
< HOST_WIDE_INT_MAX
)
661 navail
-= res
.number_chars_min
;
662 else if (res
.number_chars_max
< HOST_WIDE_INT_MAX
)
663 navail
-= res
.number_chars_max
;
666 if (navail
> HOST_WIDE_INT_MAX
)
672 /* Description of a call to a formatted function. */
674 struct pass_sprintf_length::call_info
676 /* Function call statement. */
679 /* Function called. */
682 /* Called built-in function code. */
683 built_in_function fncode
;
685 /* Format argument and format string extracted from it. */
689 /* The location of the format argument. */
692 /* The destination object size for __builtin___xxx_chk functions
693 typically determined by __builtin_object_size, or -1 if unknown. */
694 unsigned HOST_WIDE_INT objsize
;
696 /* Number of the first variable argument. */
697 unsigned HOST_WIDE_INT argidx
;
699 /* True for functions like snprintf that specify the size of
700 the destination, false for others like sprintf that don't. */
703 /* True for bounded functions like snprintf that specify a zero-size
704 buffer as a request to compute the size of output without actually
709 /* Return the result of formatting the '%%' directive. */
712 format_percent (const conversion_spec
&, tree
)
715 res
.argmin
= res
.argmax
= NULL_TREE
;
716 res
.range
.min
= res
.range
.max
= 1;
717 res
.bounded
= res
.constant
= true;
722 /* Compute intmax_type_node and uintmax_type_node similarly to how
723 tree.c builds size_type_node. */
726 build_intmax_type_nodes (tree
*pintmax
, tree
*puintmax
)
728 if (strcmp (UINTMAX_TYPE
, "unsigned int") == 0)
730 *pintmax
= integer_type_node
;
731 *puintmax
= unsigned_type_node
;
733 else if (strcmp (UINTMAX_TYPE
, "long unsigned int") == 0)
735 *pintmax
= long_integer_type_node
;
736 *puintmax
= long_unsigned_type_node
;
738 else if (strcmp (UINTMAX_TYPE
, "long long unsigned int") == 0)
740 *pintmax
= long_long_integer_type_node
;
741 *puintmax
= long_long_unsigned_type_node
;
745 for (int i
= 0; i
< NUM_INT_N_ENTS
; i
++)
746 if (int_n_enabled_p
[i
])
749 sprintf (name
, "__int%d unsigned", int_n_data
[i
].bitsize
);
751 if (strcmp (name
, UINTMAX_TYPE
) == 0)
753 *pintmax
= int_n_trees
[i
].signed_type
;
754 *puintmax
= int_n_trees
[i
].unsigned_type
;
763 format_integer (const conversion_spec
&, tree
);
765 /* Return a range representing the minimum and maximum number of bytes
766 that the conversion specification SPEC will write on output for the
767 pointer argument ARG when non-null. ARG may be null (for vararg
771 format_pointer (const conversion_spec
&spec
, tree arg
)
775 /* Determine the target's integer format corresponding to "%p". */
777 const char *pfmt
= targetm
.printf_pointer_format (arg
, &flags
);
780 /* The format couldn't be determined. */
781 res
.range
.min
= res
.range
.max
= HOST_WIDE_INT_M1U
;
787 /* Format the pointer using the integer format string. */
788 conversion_spec pspec
= spec
;
790 /* Clear flags that are not listed as recognized. */
791 for (const char *pf
= "+ #0"; *pf
; ++pf
)
793 if (!strchr (flags
, *pf
))
794 pspec
.clear_flag (*pf
);
797 /* Set flags that are specified in the format string. */
803 case '+': case ' ': case '#': case '0':
804 pspec
.set_flag (*pfmt
);
812 /* Set the appropriate length modifier taking care to clear
813 the one that may be set (Glibc's %p accepts but ignores all
814 the integer length modifiers). */
817 case 'l': pspec
.modifier
= FMT_LEN_l
; ++pfmt
; break;
818 case 't': pspec
.modifier
= FMT_LEN_t
; ++pfmt
; break;
819 case 'z': pspec
.modifier
= FMT_LEN_z
; ++pfmt
; break;
820 default: pspec
.modifier
= FMT_LEN_none
;
823 pspec
.force_flags
= 1;
824 pspec
.specifier
= *pfmt
++;
825 gcc_assert (*pfmt
== '\0');
826 return format_integer (pspec
, arg
);
829 /* The format is a plain string such as Glibc's "(nil)". */
830 res
.range
.min
= res
.range
.max
= strlen (pfmt
);
834 /* Set *PWIDTH and *PPREC according to the width and precision specified
835 in SPEC. Each is set to HOST_WIDE_INT_MIN when the corresponding
836 field is specified but unknown, to zero for width and -1 for precision,
837 respectively when it's not specified, or to a non-negative value
838 corresponding to the known value. */
840 get_width_and_precision (const conversion_spec
&spec
,
841 HOST_WIDE_INT
*pwidth
, HOST_WIDE_INT
*pprec
)
843 HOST_WIDE_INT width
= spec
.have_width
? spec
.width
: 0;
844 HOST_WIDE_INT prec
= spec
.have_precision
? spec
.precision
: -1;
848 if (TREE_CODE (spec
.star_width
) == INTEGER_CST
)
849 width
= abs (tree_to_shwi (spec
.star_width
));
851 width
= HOST_WIDE_INT_MIN
;
854 if (spec
.star_precision
)
856 if (TREE_CODE (spec
.star_precision
) == INTEGER_CST
)
858 prec
= tree_to_shwi (spec
.star_precision
);
863 prec
= HOST_WIDE_INT_MIN
;
871 /* Return a range representing the minimum and maximum number of bytes
872 that the conversion specification SPEC will write on output for the
873 integer argument ARG when non-null. ARG may be null (for vararg
877 format_integer (const conversion_spec
&spec
, tree arg
)
879 tree intmax_type_node
;
880 tree uintmax_type_node
;
882 /* Set WIDTH and PRECISION based on the specification. */
885 get_width_and_precision (spec
, &width
, &prec
);
887 bool sign
= spec
.specifier
== 'd' || spec
.specifier
== 'i';
889 /* The type of the "formal" argument expected by the directive. */
890 tree dirtype
= NULL_TREE
;
892 /* Determine the expected type of the argument from the length
894 switch (spec
.modifier
)
897 if (spec
.specifier
== 'p')
898 dirtype
= ptr_type_node
;
900 dirtype
= sign
? integer_type_node
: unsigned_type_node
;
904 dirtype
= sign
? short_integer_type_node
: short_unsigned_type_node
;
908 dirtype
= sign
? signed_char_type_node
: unsigned_char_type_node
;
912 dirtype
= sign
? long_integer_type_node
: long_unsigned_type_node
;
918 ? long_long_integer_type_node
919 : long_long_unsigned_type_node
);
923 dirtype
= signed_or_unsigned_type_for (!sign
, size_type_node
);
927 dirtype
= signed_or_unsigned_type_for (!sign
, ptrdiff_type_node
);
931 build_intmax_type_nodes (&intmax_type_node
, &uintmax_type_node
);
932 dirtype
= sign
? intmax_type_node
: uintmax_type_node
;
939 /* The type of the argument to the directive, either deduced from
940 the actual non-constant argument if one is known, or from
941 the directive itself when none has been provided because it's
943 tree argtype
= NULL_TREE
;
947 /* When the argument has not been provided, use the type of
948 the directive's argument as an approximation. This will
949 result in false positives for directives like %i with
950 arguments with smaller precision (such as short or char). */
953 else if (TREE_CODE (arg
) == INTEGER_CST
)
955 /* When a constant argument has been provided use its value
956 rather than type to determine the length of the output. */
958 /* Base to format the number in. */
961 /* True when a signed conversion is preceded by a sign or space. */
964 switch (spec
.specifier
)
968 /* Space is only effective for signed conversions. */
969 maybesign
= spec
.get_flag (' ');
973 maybesign
= spec
.force_flags
? spec
.get_flag (' ') : false;
977 maybesign
= spec
.force_flags
? spec
.get_flag (' ') : false;
982 maybesign
= spec
.force_flags
? spec
.get_flag (' ') : false;
991 if ((prec
== HOST_WIDE_INT_MIN
|| prec
== 0) && integer_zerop (arg
))
993 /* As a special case, a precision of zero with an argument
994 of zero results in zero bytes regardless of flags (with
995 width having the normal effect). This must extend to
996 the case of a specified precision with an unknown value
997 because it can be zero. */
1002 /* Convert the argument to the type of the directive. */
1003 arg
= fold_convert (dirtype
, arg
);
1005 maybesign
|= spec
.get_flag ('+');
1007 /* True when a conversion is preceded by a prefix indicating the base
1008 of the argument (octal or hexadecimal). */
1009 bool maybebase
= spec
.get_flag ('#');
1010 len
= tree_digits (arg
, base
, maybesign
, maybebase
);
1019 /* The minimum and maximum number of bytes produced by the directive. */
1022 res
.range
.min
= len
;
1024 /* The upper bound of the number of bytes is unlimited when either
1025 width or precision is specified but its value is unknown, and
1026 the same as the lower bound otherwise. */
1027 if (width
== HOST_WIDE_INT_MIN
|| prec
== HOST_WIDE_INT_MIN
)
1029 res
.range
.max
= HOST_WIDE_INT_MAX
;
1033 res
.range
.max
= len
;
1035 res
.constant
= true;
1036 res
.knownrange
= true;
1042 else if (TREE_CODE (TREE_TYPE (arg
)) == INTEGER_TYPE
1043 || TREE_CODE (TREE_TYPE (arg
)) == POINTER_TYPE
)
1045 /* Determine the type of the provided non-constant argument. */
1046 if (TREE_CODE (arg
) == NOP_EXPR
)
1047 arg
= TREE_OPERAND (arg
, 0);
1048 else if (TREE_CODE (arg
) == CONVERT_EXPR
)
1049 arg
= TREE_OPERAND (arg
, 0);
1050 if (TREE_CODE (arg
) == COMPONENT_REF
)
1051 arg
= TREE_OPERAND (arg
, 1);
1053 argtype
= TREE_TYPE (arg
);
1057 /* Don't bother with invalid arguments since they likely would
1058 have already been diagnosed, and disable any further checking
1059 of the format string by returning [-1, -1]. */
1060 return fmtresult ();
1065 /* Using either the range the non-constant argument is in, or its
1066 type (either "formal" or actual), create a range of values that
1067 constrain the length of output given the warning level. */
1068 tree argmin
= NULL_TREE
;
1069 tree argmax
= NULL_TREE
;
1071 if (arg
&& TREE_CODE (arg
) == SSA_NAME
1072 && TREE_CODE (argtype
) == INTEGER_TYPE
)
1074 /* Try to determine the range of values of the integer argument
1075 (range information is not available for pointers). */
1077 enum value_range_type range_type
= get_range_info (arg
, &min
, &max
);
1078 if (range_type
== VR_RANGE
)
1080 res
.argmin
= build_int_cst (argtype
, wi::fits_uhwi_p (min
)
1081 ? min
.to_uhwi () : min
.to_shwi ());
1082 res
.argmax
= build_int_cst (argtype
, wi::fits_uhwi_p (max
)
1083 ? max
.to_uhwi () : max
.to_shwi ());
1085 /* For a range with a negative lower bound and a non-negative
1086 upper bound, use one to determine the minimum number of bytes
1087 on output and whichever of the two bounds that results in
1088 the greater number of bytes on output for the upper bound.
1089 For example, for ARG in the range of [-3, 123], use 123 as
1090 the upper bound for %i but -3 for %u. */
1091 if (wi::neg_p (min
) && !wi::neg_p (max
))
1093 argmin
= build_int_cst (argtype
, wi::fits_uhwi_p (min
)
1094 ? min
.to_uhwi () : min
.to_shwi ());
1096 argmax
= build_int_cst (argtype
, wi::fits_uhwi_p (max
)
1097 ? max
.to_uhwi () : max
.to_shwi ());
1099 int minbytes
= format_integer (spec
, res
.argmin
).range
.min
;
1100 int maxbytes
= format_integer (spec
, res
.argmax
).range
.max
;
1101 if (maxbytes
< minbytes
)
1102 argmax
= res
.argmin
;
1104 argmin
= integer_zero_node
;
1108 argmin
= res
.argmin
;
1109 argmax
= res
.argmax
;
1112 /* The argument is bounded by the known range of values
1113 determined by Value Range Propagation. */
1115 res
.knownrange
= true;
1117 else if (range_type
== VR_ANTI_RANGE
)
1119 /* Handle anti-ranges if/when bug 71690 is resolved. */
1121 else if (range_type
== VR_VARYING
)
1123 /* The argument here may be the result of promoting the actual
1124 argument to int. Try to determine the type of the actual
1125 argument before promotion and narrow down its range that
1127 gimple
*def
= SSA_NAME_DEF_STMT (arg
);
1128 if (is_gimple_assign (def
))
1130 tree_code code
= gimple_assign_rhs_code (def
);
1131 if (code
== INTEGER_CST
)
1133 arg
= gimple_assign_rhs1 (def
);
1134 return format_integer (spec
, arg
);
1137 if (code
== NOP_EXPR
)
1138 argtype
= TREE_TYPE (gimple_assign_rhs1 (def
));
1145 /* For an unknown argument (e.g., one passed to a vararg function)
1146 or one whose value range cannot be determined, create a T_MIN
1147 constant if the argument's type is signed and T_MAX otherwise,
1148 and use those to compute the range of bytes that the directive
1149 can output. When precision is specified but unknown, use zero
1150 as the minimum since it results in no bytes on output (unless
1151 width is specified to be greater than 0). */
1152 argmin
= build_int_cst (argtype
, prec
!= HOST_WIDE_INT_MIN
);
1154 int typeprec
= TYPE_PRECISION (dirtype
);
1155 int argprec
= TYPE_PRECISION (argtype
);
1157 if (argprec
< typeprec
|| POINTER_TYPE_P (argtype
))
1159 if (TYPE_UNSIGNED (argtype
))
1160 argmax
= build_all_ones_cst (argtype
);
1162 argmax
= fold_build2 (LSHIFT_EXPR
, argtype
, integer_one_node
,
1163 build_int_cst (integer_type_node
,
1168 argmax
= fold_build2 (LSHIFT_EXPR
, dirtype
, integer_one_node
,
1169 build_int_cst (integer_type_node
,
1172 res
.argmin
= argmin
;
1173 res
.argmax
= argmax
;
1176 /* Recursively compute the minimum and maximum from the known range,
1177 taking care to swap them if the lower bound results in longer
1178 output than the upper bound (e.g., in the range [-1, 0]. */
1179 res
.range
.min
= format_integer (spec
, argmin
).range
.min
;
1180 res
.range
.max
= format_integer (spec
, argmax
).range
.max
;
1182 /* The result is bounded either when the argument is determined to be
1183 (e.g., when it's within some range) or when the minimum and maximum
1184 are the same. That can happen here for example when the specified
1185 width is as wide as the greater of MIN and MAX, as would be the case
1186 with sprintf (d, "%08x", x) with a 32-bit integer x. */
1187 res
.bounded
|= res
.range
.min
== res
.range
.max
;
1189 if (res
.range
.max
< res
.range
.min
)
1191 unsigned HOST_WIDE_INT tmp
= res
.range
.max
;
1192 res
.range
.max
= res
.range
.min
;
1193 res
.range
.min
= tmp
;
1199 /* Return the number of bytes to format using the format specifier
1200 SPEC the largest value in the real floating TYPE. */
1203 format_floating_max (tree type
, char spec
, int prec
= -1)
1205 machine_mode mode
= TYPE_MODE (type
);
1207 /* IBM Extended mode. */
1208 if (MODE_COMPOSITE_P (mode
))
1211 /* Get the real type format desription for the target. */
1212 const real_format
*rfmt
= REAL_MODE_FORMAT (mode
);
1217 get_max_float (rfmt
, buf
, sizeof buf
);
1218 real_from_string (&rv
, buf
);
1221 /* Convert the GCC real value representation with the precision
1222 of the real type to the mpfr_t format with the GCC default
1223 round-to-nearest mode. */
1225 mpfr_init2 (x
, rfmt
->p
);
1226 mpfr_from_real (x
, &rv
, GMP_RNDN
);
1232 const char fmt
[] = { '%', '.', '*', 'R', spec
, '\0' };
1233 n
= mpfr_snprintf (NULL
, 0, fmt
, prec
, x
);
1237 const char fmt
[] = { '%', 'R', spec
, '\0' };
1238 n
= mpfr_snprintf (NULL
, 0, fmt
, x
);
1241 /* Return a value one greater to account for the leading minus sign. */
1245 /* Return a range representing the minimum and maximum number of bytes
1246 that the conversion specification SPEC will output for any argument
1247 given the WIDTH and PRECISION (extracted from SPEC). This function
1248 is used when the directive argument or its value isn't known. */
1251 format_floating (const conversion_spec
&spec
, int width
, int prec
)
1256 switch (spec
.modifier
)
1260 type
= double_type_node
;
1264 type
= long_double_type_node
;
1269 type
= long_double_type_node
;
1274 return fmtresult ();
1277 /* The minimum and maximum number of bytes produced by the directive. */
1280 /* Log10 of of the maximum number of exponent digits for the type. */
1283 if (REAL_MODE_FORMAT (TYPE_MODE (type
))->b
== 2)
1285 /* The base in which the exponent is represented should always
1288 const double log10_2
= .30102999566398119521;
1290 /* Compute T_MAX_EXP for base 2. */
1291 int expdigs
= REAL_MODE_FORMAT (TYPE_MODE (type
))->emax
* log10_2
;
1292 logexpdigs
= ilog (expdigs
, 10);
1295 switch (spec
.specifier
)
1300 /* The minimum output is "0x.p+0". */
1301 res
.range
.min
= 6 + (prec
> 0 ? prec
: 0);
1302 res
.range
.max
= (width
== INT_MIN
1304 : format_floating_max (type
, 'a', prec
));
1306 /* The output of "%a" is fully specified only when precision
1307 is explicitly specified and width isn't unknown. */
1308 res
.bounded
= INT_MIN
!= width
&& -1 < prec
;
1315 bool sign
= spec
.get_flag ('+') || spec
.get_flag (' ');
1316 /* The minimum output is "[-+]1.234567e+00" regardless
1317 of the value of the actual argument. */
1318 res
.range
.min
= (sign
1319 + 1 /* unit */ + (prec
< 0 ? 7 : prec
? prec
+ 1 : 0)
1321 /* Unless width is uknown the maximum output is the minimum plus
1322 sign (unless already included), plus the difference between
1323 the minimum exponent of 2 and the maximum exponent for the type. */
1324 res
.range
.max
= (width
== INT_MIN
1326 : res
.range
.min
+ !sign
+ logexpdigs
- 2);
1328 /* "%e" is fully specified and the range of bytes is bounded
1329 unless width is unknown. */
1330 res
.bounded
= INT_MIN
!= width
;
1337 /* The minimum output is "1.234567" regardless of the value
1338 of the actual argument. */
1339 res
.range
.min
= 2 + (prec
< 0 ? 6 : prec
);
1341 /* Compute the maximum just once. */
1342 static const int f_max
[] = {
1343 format_floating_max (double_type_node
, 'f'),
1344 format_floating_max (long_double_type_node
, 'f')
1346 res
.range
.max
= width
== INT_MIN
? HOST_WIDE_INT_MAX
: f_max
[ldbl
];
1348 /* "%f" is fully specified and the range of bytes is bounded
1349 unless width is unknown. */
1350 res
.bounded
= INT_MIN
!= width
;
1356 /* The minimum is the same as for '%F'. */
1357 res
.range
.min
= 2 + (prec
< 0 ? 6 : prec
);
1359 /* Compute the maximum just once. */
1360 static const int g_max
[] = {
1361 format_floating_max (double_type_node
, 'g'),
1362 format_floating_max (long_double_type_node
, 'g')
1364 res
.range
.max
= width
== INT_MIN
? HOST_WIDE_INT_MAX
: g_max
[ldbl
];
1366 /* "%g" is fully specified and the range of bytes is bounded
1367 unless width is unknown. */
1368 res
.bounded
= INT_MIN
!= width
;
1373 return fmtresult ();
1378 if (res
.range
.min
< (unsigned)width
)
1379 res
.range
.min
= width
;
1380 if (res
.range
.max
< (unsigned)width
)
1381 res
.range
.max
= width
;
1387 /* Return a range representing the minimum and maximum number of bytes
1388 that the conversion specification SPEC will write on output for the
1389 floating argument ARG. */
1392 format_floating (const conversion_spec
&spec
, tree arg
)
1394 /* Set WIDTH to -1 when it's not specified, to INT_MIN when it is
1395 specified by the asterisk to an unknown value, and otherwise to
1396 a non-negative value corresponding to the specified width. */
1400 /* The minimum and maximum number of bytes produced by the directive. */
1402 res
.constant
= arg
&& TREE_CODE (arg
) == REAL_CST
;
1404 if (spec
.have_width
)
1406 else if (spec
.star_width
)
1408 if (TREE_CODE (spec
.star_width
) == INTEGER_CST
)
1410 width
= tree_to_shwi (spec
.star_width
);
1418 if (spec
.have_precision
)
1419 prec
= spec
.precision
;
1420 else if (spec
.star_precision
)
1422 if (TREE_CODE (spec
.star_precision
) == INTEGER_CST
)
1423 prec
= tree_to_shwi (spec
.star_precision
);
1426 /* FIXME: Handle non-constant precision. */
1427 res
.range
.min
= res
.range
.max
= HOST_WIDE_INT_M1U
;
1431 else if (res
.constant
&& TOUPPER (spec
.specifier
) != 'A')
1433 /* Specify the precision explicitly since mpfr_sprintf defaults
1440 /* Set up an array to easily iterate over. */
1441 unsigned HOST_WIDE_INT
* const minmax
[] = {
1442 &res
.range
.min
, &res
.range
.max
1445 /* Get the real type format desription for the target. */
1446 const REAL_VALUE_TYPE
*rvp
= TREE_REAL_CST_PTR (arg
);
1447 const real_format
*rfmt
= REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg
)));
1449 /* Convert the GCC real value representation with the precision
1450 of the real type to the mpfr_t format with the GCC default
1451 round-to-nearest mode. */
1453 mpfr_init2 (mpfrval
, rfmt
->p
);
1454 mpfr_from_real (mpfrval
, rvp
, GMP_RNDN
);
1457 char *pfmt
= fmtstr
;
1461 for (const char *pf
= "-+ #0"; *pf
; ++pf
)
1462 if (spec
.get_flag (*pf
))
1465 /* Append width when specified and precision. */
1467 pfmt
+= sprintf (pfmt
, "%i", width
);
1469 pfmt
+= sprintf (pfmt
, ".%i", prec
);
1471 /* Append the MPFR 'R' floating type specifier (no length modifier
1472 is necessary or allowed by MPFR for mpfr_t values). */
1475 /* Save the position of the MPFR rounding specifier and skip over
1476 it. It will be set in each iteration in the loop below. */
1477 char* const rndspec
= pfmt
++;
1479 /* Append the C type specifier and nul-terminate. */
1480 *pfmt
++ = spec
.specifier
;
1483 for (int i
= 0; i
!= sizeof minmax
/ sizeof *minmax
; ++i
)
1485 /* Use the MPFR rounding specifier to round down in the first
1486 iteration and then up. In most but not all cases this will
1487 result in the same number of bytes. */
1490 /* Format it and store the result in the corresponding
1491 member of the result struct. */
1492 *minmax
[i
] = mpfr_snprintf (NULL
, 0, fmtstr
, mpfrval
);
1495 /* The range of output is known even if the result isn't bounded. */
1496 if (width
== INT_MIN
)
1498 res
.knownrange
= false;
1499 res
.range
.max
= HOST_WIDE_INT_MAX
;
1502 res
.knownrange
= true;
1504 /* The output of all directives except "%a" is fully specified
1505 and so the result is bounded unless it exceeds INT_MAX.
1506 For "%a" the output is fully specified only when precision
1507 is explicitly specified. */
1508 res
.bounded
= (res
.knownrange
1509 && (TOUPPER (spec
.specifier
) != 'A'
1510 || (0 <= prec
&& (unsigned) prec
< target_int_max ()))
1511 && res
.range
.min
< target_int_max ());
1516 return format_floating (spec
, width
, prec
);
1519 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1520 strings referenced by the expression STR, or (-1, -1) when not known.
1521 Used by the format_string function below. */
1524 get_string_length (tree str
)
1527 return fmtresult ();
1529 if (tree slen
= c_strlen (str
, 1))
1531 /* Simply return the length of the string. */
1533 res
.range
.min
= res
.range
.max
= tree_to_shwi (slen
);
1535 res
.constant
= true;
1536 res
.knownrange
= true;
1540 /* Determine the length of the shortest and longest string referenced
1541 by STR. Strings of unknown lengths are bounded by the sizes of
1542 arrays that subexpressions of STR may refer to. Pointers that
1543 aren't known to point any such arrays result in LENRANGE[1] set
1546 get_range_strlen (str
, lenrange
);
1548 if (lenrange
[0] || lenrange
[1])
1552 res
.range
.min
= (tree_fits_uhwi_p (lenrange
[0])
1553 ? tree_to_uhwi (lenrange
[0]) : 1 < warn_format_length
);
1554 res
.range
.max
= (tree_fits_uhwi_p (lenrange
[1])
1555 ? tree_to_uhwi (lenrange
[1]) : HOST_WIDE_INT_M1U
);
1557 /* Set RES.BOUNDED to true if and only if all strings referenced
1558 by STR are known to be bounded (though not necessarily by their
1559 actual length but perhaps by their maximum possible length). */
1560 res
.bounded
= res
.range
.max
< target_int_max ();
1561 res
.knownrange
= res
.bounded
;
1563 /* Set RES.CONSTANT to false even though that may be overly
1564 conservative in rare cases like: 'x ? a : b' where a and
1565 b have the same lengths and consist of the same characters. */
1566 res
.constant
= false;
1571 return get_string_length (NULL_TREE
);
1574 /* Return the minimum and maximum number of characters formatted
1575 by the '%c' and '%s' format directives and ther wide character
1576 forms for the argument ARG. ARG can be null (for functions
1577 such as vsprinf). */
1580 format_string (const conversion_spec
&spec
, tree arg
)
1582 /* Set WIDTH and PRECISION based on the specification. */
1583 HOST_WIDE_INT width
;
1585 get_width_and_precision (spec
, &width
, &prec
);
1589 /* The maximum number of bytes for an unknown wide character argument
1590 to a "%lc" directive adjusted for precision but not field width.
1591 6 is the longest UTF-8 sequence for a single wide character. */
1592 const unsigned HOST_WIDE_INT max_bytes_for_unknown_wc
1593 = (0 <= prec
? prec
: 1 < warn_format_length
? 6 : 1);
1595 /* The maximum number of bytes for an unknown string argument to either
1596 a "%s" or "%ls" directive adjusted for precision but not field width. */
1597 const unsigned HOST_WIDE_INT max_bytes_for_unknown_str
1598 = (0 <= prec
? prec
: 1 < warn_format_length
);
1600 /* The result is bounded unless overriddden for a non-constant string
1601 of an unknown length. */
1602 bool bounded
= true;
1604 if (spec
.specifier
== 'c')
1606 if (spec
.modifier
== FMT_LEN_l
)
1608 /* Positive if the argument is a wide NUL character? */
1609 int nul
= (arg
&& TREE_CODE (arg
) == INTEGER_CST
1610 ? integer_zerop (arg
) : -1);
1612 /* A '%lc' directive is the same as '%ls' for a two element
1613 wide string character with the second element of NUL, so
1614 when the character is unknown the minimum number of bytes
1615 is the smaller of either 0 (at level 1) or 1 (at level 2)
1616 and WIDTH, and the maximum is MB_CUR_MAX in the selected
1617 locale, which is unfortunately, unknown. */
1618 res
.range
.min
= 1 == warn_format_length
? !nul
: nul
< 1;
1619 res
.range
.max
= max_bytes_for_unknown_wc
;
1620 /* The range above is good enough to issue warnings but not
1621 for value range propagation, so clear BOUNDED. */
1622 res
.bounded
= false;
1626 /* A plain '%c' directive. Its ouput is exactly 1. */
1627 res
.range
.min
= res
.range
.max
= 1;
1629 res
.knownrange
= true;
1630 res
.constant
= arg
&& TREE_CODE (arg
) == INTEGER_CST
;
1633 else /* spec.specifier == 's' */
1635 /* Compute the range the argument's length can be in. */
1636 fmtresult slen
= get_string_length (arg
);
1639 gcc_checking_assert (slen
.range
.min
== slen
.range
.max
);
1641 /* A '%s' directive with a string argument with constant length. */
1642 res
.range
= slen
.range
;
1644 /* The output of "%s" and "%ls" directives with a constant
1645 string is in a known range unless width of an unknown value
1646 is specified. For "%s" it is the length of the string. For
1647 "%ls" it is in the range [length, length * MB_LEN_MAX].
1648 (The final range can be further constrained by width and
1649 precision but it's always known.) */
1650 res
.knownrange
= -1 < width
;
1652 if (spec
.modifier
== FMT_LEN_l
)
1656 if (warn_format_length
> 1)
1658 /* Leave the minimum number of bytes the wide string
1659 converts to equal to its length and set the maximum
1660 to the worst case length which is the string length
1661 multiplied by MB_LEN_MAX. */
1663 /* It's possible to be smarter about computing the maximum
1664 by scanning the wide string for any 8-bit characters and
1665 if it contains none, using its length for the maximum.
1666 Even though this would be simple to do it's unlikely to
1667 be worth it when dealing with wide characters. */
1668 res
.range
.max
*= target_mb_len_max
;
1671 /* For a wide character string, use precision as the maximum
1672 even if precision is greater than the string length since
1673 the number of bytes the string converts to may be greater
1674 (due to MB_CUR_MAX). */
1676 res
.range
.max
= prec
;
1678 else if (0 <= width
)
1680 /* The output of a "%s" directive with a constant argument
1681 and constant or no width is bounded. It is constant if
1682 precision is either not specified or it is specified and
1683 its value is known. */
1685 res
.constant
= prec
!= HOST_WIDE_INT_MIN
;
1687 else if (width
== HOST_WIDE_INT_MIN
)
1689 /* Specified but unknown width makes the output unbounded. */
1690 res
.range
.max
= HOST_WIDE_INT_MAX
;
1693 if (0 <= prec
&& (unsigned HOST_WIDE_INT
)prec
< res
.range
.min
)
1695 res
.range
.min
= prec
;
1696 res
.range
.max
= prec
;
1698 else if (prec
== HOST_WIDE_INT_MIN
)
1700 /* When precision is specified but not known the lower
1701 bound is assumed to be as low as zero. */
1707 /* For a '%s' and '%ls' directive with a non-constant string,
1708 the minimum number of characters is the greater of WIDTH
1709 and either 0 in mode 1 or the smaller of PRECISION and 1
1710 in mode 2, and the maximum is PRECISION or -1 to disable
1715 if (slen
.range
.min
>= target_int_max ())
1717 else if ((unsigned HOST_WIDE_INT
)prec
< slen
.range
.min
)
1718 slen
.range
.min
= prec
;
1720 if ((unsigned HOST_WIDE_INT
)prec
< slen
.range
.max
1721 || slen
.range
.max
>= target_int_max ())
1722 slen
.range
.max
= prec
;
1724 else if (slen
.range
.min
>= target_int_max ())
1726 slen
.range
.min
= max_bytes_for_unknown_str
;
1727 slen
.range
.max
= max_bytes_for_unknown_str
;
1731 res
.range
= slen
.range
;
1733 /* The output is considered bounded when a precision has been
1734 specified to limit the number of bytes or when the number
1735 of bytes is known or contrained to some range. */
1736 res
.bounded
= 0 <= prec
|| slen
.bounded
;
1737 res
.knownrange
= slen
.knownrange
;
1738 res
.constant
= false;
1742 /* Adjust the lengths for field width. */
1745 if (res
.range
.min
< (unsigned HOST_WIDE_INT
)width
)
1746 res
.range
.min
= width
;
1748 if (res
.range
.max
< (unsigned HOST_WIDE_INT
)width
)
1749 res
.range
.max
= width
;
1751 /* Adjust BOUNDED if width happens to make them equal. */
1752 if (res
.range
.min
== res
.range
.max
&& res
.range
.min
< target_int_max ()
1757 /* When precision is specified the range of characters on output
1758 is known to be bounded by it. */
1759 if (-1 < width
&& -1 < prec
)
1760 res
.knownrange
= true;
1765 /* Compute the length of the output resulting from the conversion
1766 specification SPEC with the argument ARG in a call described by INFO
1767 and update the overall result of the call in *RES. The format directive
1768 corresponding to SPEC starts at CVTBEG and is CVTLEN characters long. */
1771 format_directive (const pass_sprintf_length::call_info
&info
,
1772 format_result
*res
, const char *cvtbeg
, size_t cvtlen
,
1773 const conversion_spec
&spec
, tree arg
)
1775 /* Offset of the beginning of the directive from the beginning
1776 of the format string. */
1777 size_t offset
= cvtbeg
- info
.fmtstr
;
1779 /* Create a location for the whole directive from the % to the format
1781 substring_loc
dirloc (info
.fmtloc
, TREE_TYPE (info
.format
),
1782 offset
, offset
, offset
+ cvtlen
- 1);
1784 /* Also create a location range for the argument if possible.
1785 This doesn't work for integer literals or function calls. */
1786 source_range argrange
;
1787 source_range
*pargrange
;
1788 if (arg
&& CAN_HAVE_LOCATION_P (arg
))
1790 argrange
= EXPR_LOCATION_RANGE (arg
);
1791 pargrange
= &argrange
;
1796 /* Bail when there is no function to compute the output length,
1797 or when minimum length checking has been disabled. */
1798 if (!spec
.fmtfunc
|| res
->number_chars_min
>= HOST_WIDE_INT_MAX
)
1801 /* Compute the (approximate) length of the formatted output. */
1802 fmtresult fmtres
= spec
.fmtfunc (spec
, arg
);
1804 /* The overall result is bounded and constant only if the output
1805 of every directive is bounded and constant, respectively. */
1806 res
->bounded
&= fmtres
.bounded
;
1807 res
->constant
&= fmtres
.constant
;
1809 /* Record whether the output of all directives is known to be
1810 bounded by some maximum, implying that their arguments are
1811 either known exactly or determined to be in a known range
1812 or, for strings, limited by the upper bounds of the arrays
1814 res
->knownrange
&= fmtres
.knownrange
;
1816 if (!fmtres
.knownrange
)
1818 /* Only when the range is known, check it against the host value
1819 of INT_MAX. Otherwise the range doesn't correspond to known
1820 values of the argument. */
1821 if (fmtres
.range
.max
>= target_int_max ())
1823 /* Normalize the MAX counter to avoid having to deal with it
1824 later. The counter can be less than HOST_WIDE_INT_M1U
1825 when compiling for an ILP32 target on an LP64 host. */
1826 fmtres
.range
.max
= HOST_WIDE_INT_M1U
;
1827 /* Disable exact and maximum length checking after a failure
1828 to determine the maximum number of characters (for example
1829 for wide characters or wide character strings) but continue
1830 tracking the minimum number of characters. */
1831 res
->number_chars_max
= HOST_WIDE_INT_M1U
;
1832 res
->number_chars
= HOST_WIDE_INT_M1U
;
1835 if (fmtres
.range
.min
>= target_int_max ())
1837 /* Disable exact length checking after a failure to determine
1838 even the minimum number of characters (it shouldn't happen
1839 except in an error) but keep tracking the minimum and maximum
1840 number of characters. */
1841 res
->number_chars
= HOST_WIDE_INT_M1U
;
1846 /* Compute the number of available bytes in the destination. There
1847 must always be at least one byte of space for the terminating
1848 NUL that's appended after the format string has been processed. */
1849 unsigned HOST_WIDE_INT navail
= min_bytes_remaining (info
.objsize
, *res
);
1851 if (fmtres
.range
.min
< fmtres
.range
.max
)
1853 /* The result is a range (i.e., it's inexact). */
1856 bool warned
= false;
1858 if (navail
< fmtres
.range
.min
)
1860 /* The minimum directive output is longer than there is
1861 room in the destination. */
1862 if (fmtres
.range
.min
== fmtres
.range
.max
)
1866 ? G_("%<%.*s%> directive output truncated writing "
1867 "%wu bytes into a region of size %wu")
1868 : G_("%<%.*s%> directive writing %wu bytes "
1869 "into a region of size %wu"));
1870 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1871 OPT_Wformat_length_
, fmtstr
,
1872 (int)cvtlen
, cvtbeg
, fmtres
.range
.min
,
1875 else if (fmtres
.range
.max
< HOST_WIDE_INT_MAX
)
1879 ? G_("%<%.*s%> directive output truncated writing "
1880 "between %wu and %wu bytes into a region of "
1882 : G_("%<%.*s%> directive writing between %wu and "
1883 "%wu bytes into a region of size %wu"));
1884 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1885 OPT_Wformat_length_
, fmtstr
,
1886 (int)cvtlen
, cvtbeg
,
1887 fmtres
.range
.min
, fmtres
.range
.max
, navail
);
1893 ? G_("%<%.*s%> directive output truncated writing "
1894 "%wu or more bytes into a region of size %wu")
1895 : G_("%<%.*s%> directive writing %wu or more bytes "
1896 "into a region of size %wu"));
1897 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1898 OPT_Wformat_length_
, fmtstr
,
1899 (int)cvtlen
, cvtbeg
,
1900 fmtres
.range
.min
, navail
);
1903 else if (navail
< fmtres
.range
.max
1904 && (((spec
.specifier
== 's'
1905 && fmtres
.range
.max
< HOST_WIDE_INT_MAX
)
1906 /* && (spec.precision || spec.star_precision) */)
1907 || 1 < warn_format_length
))
1909 /* The maximum directive output is longer than there is
1910 room in the destination and the output length is either
1911 explicitly constrained by the precision (for strings)
1912 or the warning level is greater than 1. */
1913 if (fmtres
.range
.max
>= HOST_WIDE_INT_MAX
)
1917 ? G_("%<%.*s%> directive output may be truncated "
1918 "writing %wu or more bytes a region of size %wu")
1919 : G_("%<%.*s%> directive writing %wu or more bytes "
1920 "into a region of size %wu"));
1921 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1922 OPT_Wformat_length_
, fmtstr
,
1923 (int)cvtlen
, cvtbeg
,
1924 fmtres
.range
.min
, navail
);
1930 ? G_("%<%.*s%> directive output may be truncated "
1931 "writing between %wu and %wu bytes into a region "
1933 : G_("%<%.*s%> directive writing between %wu and %wu "
1934 "bytes into a region of size %wu"));
1935 warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1936 OPT_Wformat_length_
, fmtstr
,
1937 (int)cvtlen
, cvtbeg
,
1938 fmtres
.range
.min
, fmtres
.range
.max
,
1943 res
->warned
|= warned
;
1945 if (warned
&& fmtres
.argmin
)
1947 if (fmtres
.argmin
== fmtres
.argmax
)
1948 inform (info
.fmtloc
, "directive argument %qE", fmtres
.argmin
);
1949 else if (fmtres
.bounded
)
1950 inform (info
.fmtloc
, "directive argument in the range [%E, %E]",
1951 fmtres
.argmin
, fmtres
.argmax
);
1953 inform (info
.fmtloc
,
1954 "using the range [%qE, %qE] for directive argument",
1955 fmtres
.argmin
, fmtres
.argmax
);
1959 /* Disable exact length checking but adjust the minimum and maximum. */
1960 res
->number_chars
= HOST_WIDE_INT_M1U
;
1961 if (res
->number_chars_max
< HOST_WIDE_INT_MAX
1962 && fmtres
.range
.max
< HOST_WIDE_INT_MAX
)
1963 res
->number_chars_max
+= fmtres
.range
.max
;
1965 res
->number_chars_min
+= fmtres
.range
.min
;
1969 if (!res
->warned
&& fmtres
.range
.min
> 0 && navail
< fmtres
.range
.min
)
1973 ? (1 < fmtres
.range
.min
1974 ? G_("%<%.*s%> directive output truncated while writing "
1975 "%wu bytes into a region of size %wu")
1976 : G_("%<%.*s%> directive output truncated while writing "
1977 "%wu byte into a region of size %wu"))
1978 : (1 < fmtres
.range
.min
1979 ? G_("%<%.*s%> directive writing %wu bytes "
1980 "into a region of size %wu")
1981 : G_("%<%.*s%> directive writing %wu byte "
1982 "into a region of size %wu")));
1984 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
1985 OPT_Wformat_length_
, fmtstr
,
1986 (int)cvtlen
, cvtbeg
, fmtres
.range
.min
,
1989 *res
+= fmtres
.range
.min
;
1992 /* Has the minimum directive output length exceeded the maximum
1993 of 4095 bytes required to be supported? */
1994 bool minunder4k
= fmtres
.range
.min
< 4096;
1995 if (!minunder4k
|| fmtres
.range
.max
> 4095)
1996 res
->under4k
= false;
1998 if (!res
->warned
&& 1 < warn_format_length
1999 && (!minunder4k
|| fmtres
.range
.max
> 4095))
2001 /* The directive output may be longer than the maximum required
2002 to be handled by an implementation according to 7.21.6.1, p15
2003 of C11. Warn on this only at level 2 but remember this and
2004 prevent folding the return value when done. This allows for
2005 the possibility of the actual libc call failing due to ENOMEM
2006 (like Glibc does under some conditions). */
2008 if (fmtres
.range
.min
== fmtres
.range
.max
)
2009 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
2010 OPT_Wformat_length_
,
2011 "%<%.*s%> directive output of %wu bytes exceeds "
2012 "minimum required size of 4095",
2013 (int)cvtlen
, cvtbeg
, fmtres
.range
.min
);
2018 ? G_("%<%.*s%> directive output between %qu and %wu "
2019 "bytes may exceed minimum required size of 4095")
2020 : G_("%<%.*s%> directive output between %qu and %wu "
2021 "bytes exceeds minimum required size of 4095"));
2023 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
2024 OPT_Wformat_length_
, fmtstr
,
2025 (int)cvtlen
, cvtbeg
,
2026 fmtres
.range
.min
, fmtres
.range
.max
);
2030 /* Has the minimum directive output length exceeded INT_MAX? */
2031 bool exceedmin
= res
->number_chars_min
> target_int_max ();
2035 || (1 < warn_format_length
2036 && res
->number_chars_max
> target_int_max ())))
2038 /* The directive output causes the total length of output
2039 to exceed INT_MAX bytes. */
2041 if (fmtres
.range
.min
== fmtres
.range
.max
)
2042 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
2043 OPT_Wformat_length_
,
2044 "%<%.*s%> directive output of %wu bytes causes "
2045 "result to exceed %<INT_MAX%>",
2046 (int)cvtlen
, cvtbeg
, fmtres
.range
.min
);
2051 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2052 "bytes causes result to exceed %<INT_MAX%>")
2053 : G_ ("%<%.*s%> directive output between %wu and %wu "
2054 "bytes may cause result to exceed %<INT_MAX%>"));
2055 res
->warned
= fmtwarn (dirloc
, pargrange
, NULL
,
2056 OPT_Wformat_length_
, fmtstr
,
2057 (int)cvtlen
, cvtbeg
,
2058 fmtres
.range
.min
, fmtres
.range
.max
);
2063 /* Account for the number of bytes between BEG and END (or between
2064 BEG + strlen (BEG) when END is null) in the format string in a call
2065 to a formatted output function described by INFO. Reflect the count
2066 in RES and issue warnings as appropriate. */
2069 add_bytes (const pass_sprintf_length::call_info
&info
,
2070 const char *beg
, const char *end
, format_result
*res
)
2072 if (res
->number_chars_min
>= HOST_WIDE_INT_MAX
)
2075 /* The number of bytes to output is the number of bytes between
2076 the end of the last directive and the beginning of the next
2077 one if it exists, otherwise the number of characters remaining
2078 in the format string plus 1 for the terminating NUL. */
2079 size_t nbytes
= end
? end
- beg
: strlen (beg
) + 1;
2081 /* Return if there are no bytes to add at this time but there are
2082 directives remaining in the format string. */
2086 /* Compute the range of available bytes in the destination. There
2087 must always be at least one byte left for the terminating NUL
2088 that's appended after the format string has been processed. */
2089 result_range avail_range
= bytes_remaining (info
.objsize
, *res
);
2091 /* If issuing a diagnostic (only when one hasn't already been issued),
2092 distinguish between a possible overflow ("may write") and a certain
2093 overflow somewhere "past the end." (Ditto for truncation.)
2094 KNOWNRANGE is used to warn even at level 1 about possibly writing
2095 past the end or truncation due to strings of unknown lengths that
2096 are bounded by the arrays they are known to refer to. */
2098 && (avail_range
.max
< nbytes
2099 || ((res
->knownrange
|| 1 < warn_format_length
)
2100 && avail_range
.min
< nbytes
)))
2102 /* Set NAVAIL to the number of available bytes used to decide
2103 whether or not to issue a warning below. The exact kind of
2104 warning will depend on AVAIL_RANGE. */
2105 unsigned HOST_WIDE_INT navail
= avail_range
.max
;
2106 if (nbytes
<= navail
&& avail_range
.min
< HOST_WIDE_INT_MAX
2107 && (res
->knownrange
|| 1 < warn_format_length
))
2108 navail
= avail_range
.min
;
2110 /* Compute the offset of the first format character that is beyond
2111 the end of the destination region and the length of the rest of
2112 the format string from that point on. */
2113 unsigned HOST_WIDE_INT off
2114 = (unsigned HOST_WIDE_INT
)(beg
- info
.fmtstr
) + navail
;
2116 size_t len
= strlen (info
.fmtstr
+ off
);
2118 /* Create a location that underscores the substring of the format
2119 string that is or may be written past the end (or is or may be
2120 truncated), pointing the caret at the first character of the
2123 (info
.fmtloc
, TREE_TYPE (info
.format
), off
, len
? off
: 0,
2126 /* Is the output of the last directive the result of the argument
2127 being within a range whose lower bound would fit in the buffer
2128 but the upper bound would not? If so, use the word "may" to
2129 indicate that the overflow/truncation may (but need not) happen. */
2131 = (res
->number_chars_min
< res
->number_chars_max
2132 && res
->number_chars_min
< info
.objsize
);
2134 if (!end
&& ((nbytes
- navail
) == 1 || boundrange
))
2136 /* There is room for the rest of the format string but none
2137 for the terminating nul. */
2139 = (info
.bounded
// Snprintf and the like.
2141 ? G_("output may be truncated before the last format character"
2142 : "output truncated before the last format character"))
2144 ? G_("may write a terminating nul past the end "
2145 "of the destination")
2146 : G_("writing a terminating nul past the end "
2147 "of the destination")));
2149 res
->warned
= fmtwarn (loc
, NULL
, NULL
, OPT_Wformat_length_
, text
);
2153 /* There isn't enough room for 1 or more characters that remain
2154 to copy from the format string. */
2156 = (info
.bounded
// Snprintf and the like.
2158 ? G_("output may be truncated at or before format character "
2159 "%qc at offset %wu")
2160 : G_("output truncated at format character %qc at offset %wu"))
2161 : (res
->number_chars
>= HOST_WIDE_INT_MAX
2162 ? G_("may write format character %#qc at offset %wu past "
2163 "the end of the destination")
2164 : G_("writing format character %#qc at offset %wu past "
2165 "the end of the destination")));
2167 res
->warned
= fmtwarn (loc
, NULL
, NULL
, OPT_Wformat_length_
,
2168 text
, info
.fmtstr
[off
], off
);
2172 if (res
->warned
&& !end
&& info
.objsize
< HOST_WIDE_INT_MAX
)
2174 /* If a warning has been issued for buffer overflow or truncation
2175 (but not otherwise) help the user figure out how big a buffer
2178 location_t callloc
= gimple_location (info
.callstmt
);
2180 unsigned HOST_WIDE_INT min
= res
->number_chars_min
;
2181 unsigned HOST_WIDE_INT max
= res
->number_chars_max
;
2182 unsigned HOST_WIDE_INT exact
2183 = (res
->number_chars
< HOST_WIDE_INT_MAX
2184 ? res
->number_chars
: res
->number_chars_min
);
2186 if (min
< max
&& max
< HOST_WIDE_INT_MAX
)
2188 "format output between %wu and %wu bytes into "
2189 "a destination of size %wu",
2190 min
+ nbytes
, max
+ nbytes
, info
.objsize
);
2193 (nbytes
+ exact
== 1
2194 ? G_("format output %wu byte into a destination of size %wu")
2195 : G_("format output %wu bytes into a destination of size %wu")),
2196 nbytes
+ exact
, info
.objsize
);
2199 /* Add the number of bytes and then check for INT_MAX overflow. */
2202 /* Has the minimum output length minus the terminating nul exceeded
2204 bool exceedmin
= (res
->number_chars_min
- !end
) > target_int_max ();
2208 || (1 < warn_format_length
2209 && (res
->number_chars_max
- !end
) > target_int_max ())))
2211 /* The function's output exceeds INT_MAX bytes. */
2213 /* Set NAVAIL to the number of available bytes used to decide
2214 whether or not to issue a warning below. The exact kind of
2215 warning will depend on AVAIL_RANGE. */
2216 unsigned HOST_WIDE_INT navail
= avail_range
.max
;
2217 if (nbytes
<= navail
&& avail_range
.min
< HOST_WIDE_INT_MAX
2218 && (res
->bounded
|| 1 < warn_format_length
))
2219 navail
= avail_range
.min
;
2221 /* Compute the offset of the first format character that is beyond
2222 the end of the destination region and the length of the rest of
2223 the format string from that point on. */
2224 unsigned HOST_WIDE_INT off
= (unsigned HOST_WIDE_INT
)(beg
- info
.fmtstr
);
2225 if (navail
< HOST_WIDE_INT_MAX
)
2228 size_t len
= strlen (info
.fmtstr
+ off
);
2231 (info
.fmtloc
, TREE_TYPE (info
.format
), off
- !len
, len
? off
: 0,
2234 if (res
->number_chars_min
== res
->number_chars_max
)
2235 res
->warned
= fmtwarn (loc
, NULL
, NULL
,
2236 OPT_Wformat_length_
,
2237 "output of %wu bytes causes "
2238 "result to exceed %<INT_MAX%>",
2239 res
->number_chars_min
- !end
);
2244 ? G_ ("output between %wu and %wu bytes causes "
2245 "result to exceed %<INT_MAX%>")
2246 : G_ ("output between %wu and %wu bytes may cause "
2247 "result to exceed %<INT_MAX%>"));
2248 res
->warned
= fmtwarn (loc
, NULL
, NULL
, OPT_Wformat_length_
,
2250 res
->number_chars_min
- !end
,
2251 res
->number_chars_max
- !end
);
2256 #pragma GCC diagnostic pop
2258 /* Compute the length of the output resulting from the call to a formatted
2259 output function described by INFO and store the result of the call in
2260 *RES. Issue warnings for detected past the end writes. */
2263 pass_sprintf_length::compute_format_length (const call_info
&info
,
2266 /* The variadic argument counter. */
2267 unsigned argno
= info
.argidx
;
2269 /* Reset exact, minimum, and maximum character counters. */
2270 res
->number_chars
= res
->number_chars_min
= res
->number_chars_max
= 0;
2272 /* No directive has been seen yet so the length of output is bounded
2273 by the known range [0, 0] and constant (with no conversion producing
2274 more than 4K bytes) until determined otherwise. */
2275 res
->bounded
= true;
2276 res
->knownrange
= true;
2277 res
->constant
= true;
2278 res
->under4k
= true;
2279 res
->floating
= false;
2280 res
->warned
= false;
2282 const char *pf
= info
.fmtstr
;
2286 /* The beginning of the next format directive. */
2287 const char *dir
= strchr (pf
, '%');
2289 /* Add the number of bytes between the end of the last directive
2290 and either the next if one exists, or the end of the format
2292 add_bytes (info
, pf
, dir
, res
);
2301 /* Incomplete directive. */
2305 conversion_spec spec
= conversion_spec ();
2307 /* POSIX numbered argument index or zero when none. */
2308 unsigned dollar
= 0;
2312 /* This could be either a POSIX positional argument, the '0'
2313 flag, or a width, depending on what follows. Store it as
2314 width and sort it out later after the next character has
2317 spec
.width
= strtol (pf
, &end
, 10);
2318 spec
.have_width
= true;
2321 else if ('*' == *pf
)
2323 /* Similarly to the block above, this could be either a POSIX
2324 positional argument or a width, depending on what follows. */
2325 if (argno
< gimple_call_num_args (info
.callstmt
))
2326 spec
.star_width
= gimple_call_arg (info
.callstmt
, argno
++);
2334 /* Handle the POSIX dollar sign which references the 1-based
2335 positional argument number. */
2336 if (spec
.have_width
)
2337 dollar
= spec
.width
+ info
.argidx
;
2338 else if (spec
.star_width
2339 && TREE_CODE (spec
.star_width
) == INTEGER_CST
)
2340 dollar
= spec
.width
+ tree_to_shwi (spec
.star_width
);
2342 /* Bail when the numbered argument is out of range (it will
2343 have already been diagnosed by -Wformat). */
2345 || dollar
== info
.argidx
2346 || dollar
> gimple_call_num_args (info
.callstmt
))
2351 spec
.star_width
= NULL_TREE
;
2352 spec
.have_width
= false;
2356 if (dollar
|| !spec
.star_width
)
2358 if (spec
.have_width
)
2360 if (spec
.width
== 0)
2362 /* The '0' that has been interpreted as a width above is
2363 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
2364 and continue processing other flags. */
2365 spec
.have_width
= false;
2366 spec
.set_flag ('0');
2370 /* (Non-zero) width has been seen. The next character
2371 is either a period or a digit. */
2372 goto start_precision
;
2375 /* When either '$' has been seen, or width has not been seen,
2376 the next field is the optional flags followed by an optional
2386 spec
.set_flag (*pf
++);
2398 spec
.width
= strtol (pf
, &end
, 10);
2399 spec
.have_width
= true;
2402 else if ('*' == *pf
)
2404 spec
.star_width
= gimple_call_arg (info
.callstmt
, argno
++);
2407 else if ('\'' == *pf
)
2409 /* The POSIX apostrophe indicating a numeric grouping
2410 in the current locale. Even though it's possible to
2411 estimate the upper bound on the size of the output
2412 based on the number of digits it probably isn't worth
2426 spec
.precision
= strtol (pf
, &end
, 10);
2427 spec
.have_precision
= true;
2430 else if ('*' == *pf
)
2432 spec
.star_precision
= gimple_call_arg (info
.callstmt
, argno
++);
2437 /* The decimal precision or the asterisk are optional.
2438 When neither is specified it's taken to be zero. */
2440 spec
.have_precision
= true;
2450 spec
.modifier
= FMT_LEN_hh
;
2453 spec
.modifier
= FMT_LEN_h
;
2458 spec
.modifier
= FMT_LEN_j
;
2463 spec
.modifier
= FMT_LEN_L
;
2471 spec
.modifier
= FMT_LEN_ll
;
2474 spec
.modifier
= FMT_LEN_l
;
2479 spec
.modifier
= FMT_LEN_t
;
2484 spec
.modifier
= FMT_LEN_z
;
2491 /* Handle a sole '%' character the same as "%%" but since it's
2492 undefined prevent the result from being folded. */
2495 res
->bounded
= false;
2498 spec
.fmtfunc
= format_percent
;
2509 res
->floating
= true;
2510 spec
.fmtfunc
= format_floating
;
2519 spec
.fmtfunc
= format_integer
;
2523 spec
.fmtfunc
= format_pointer
;
2532 spec
.fmtfunc
= format_string
;
2539 spec
.specifier
= *pf
++;
2541 /* Compute the length of the format directive. */
2542 size_t dirlen
= pf
- dir
;
2544 /* Extract the argument if the directive takes one and if it's
2545 available (e.g., the function doesn't take a va_list). Treat
2546 missing arguments the same as va_list, even though they will
2547 have likely already been diagnosed by -Wformat. */
2548 tree arg
= NULL_TREE
;
2549 if (spec
.specifier
!= '%'
2550 && argno
< gimple_call_num_args (info
.callstmt
))
2551 arg
= gimple_call_arg (info
.callstmt
, dollar
? dollar
: argno
++);
2553 ::format_directive (info
, res
, dir
, dirlen
, spec
, arg
);
2557 /* Return the size of the object referenced by the expression DEST if
2558 available, or -1 otherwise. */
2560 static unsigned HOST_WIDE_INT
2561 get_destination_size (tree dest
)
2563 /* Use __builtin_object_size to determine the size of the destination
2564 object. When optimizing, determine the smallest object (such as
2565 a member array as opposed to the whole enclosing object), otherwise
2566 use type-zero object size to determine the size of the enclosing
2567 object (the function fails without optimization in this type). */
2568 int ost
= optimize
> 0;
2569 unsigned HOST_WIDE_INT size
;
2570 if (compute_builtin_object_size (dest
, ost
, &size
))
2573 return HOST_WIDE_INT_M1U
;
2576 /* Given a suitable result RES of a call to a formatted output function
2577 described by INFO, substitute the result for the return value of
2578 the call. The result is suitable if the number of bytes it represents
2579 is known and exact. A result that isn't suitable for substitution may
2580 have its range set to the range of return values, if that is known. */
2583 try_substitute_return_value (gimple_stmt_iterator
*gsi
,
2584 const pass_sprintf_length::call_info
&info
,
2585 const format_result
&res
)
2587 tree lhs
= gimple_get_lhs (info
.callstmt
);
2589 /* Avoid the return value optimization when the behavior of the call
2590 is undefined either because any directive may have produced 4K or
2591 more of output, or the return value exceeds INT_MAX, or because
2592 the output overflows the destination object (but leave it enabled
2593 when the function is bounded because then the behavior is well-
2595 if (lhs
&& res
.bounded
&& res
.under4k
2596 && (info
.bounded
|| res
.number_chars
<= info
.objsize
)
2597 && res
.number_chars
- 1 <= target_int_max ())
2599 tree cst
= build_int_cst (integer_type_node
, res
.number_chars
- 1);
2603 /* Replace the call to the bounded function with a zero size
2604 (e.g., snprintf(0, 0, "%i", 123) with the constant result
2605 of the function minus 1 for the terminating NUL which
2606 the function's return value does not include. */
2607 if (!update_call_from_tree (gsi
, cst
))
2608 gimplify_and_update_call_from_tree (gsi
, cst
);
2609 gimple
*callstmt
= gsi_stmt (*gsi
);
2610 update_stmt (callstmt
);
2614 /* Replace the left-hand side of the call with the constant
2615 result of the formatted function minus 1 for the terminating
2616 NUL which the function's return value does not include. */
2617 gimple_call_set_lhs (info
.callstmt
, NULL_TREE
);
2618 gimple
*g
= gimple_build_assign (lhs
, cst
);
2619 gsi_insert_after (gsi
, g
, GSI_NEW_STMT
);
2620 update_stmt (info
.callstmt
);
2625 location_t callloc
= gimple_location (info
.callstmt
);
2626 fprintf (dump_file
, "On line %i substituting ",
2627 LOCATION_LINE (callloc
));
2628 print_generic_expr (dump_file
, cst
, dump_flags
);
2629 fprintf (dump_file
, " for ");
2630 print_generic_expr (dump_file
, info
.func
, dump_flags
);
2631 fprintf (dump_file
, " %s (output %s).\n",
2632 info
.nowrite
? "call" : "return value",
2633 res
.constant
? "constant" : "variable");
2638 unsigned HOST_WIDE_INT maxbytes
;
2642 && ((maxbytes
= res
.number_chars
- 1) <= target_int_max ()
2643 || (res
.number_chars_min
- 1 <= target_int_max ()
2644 && (maxbytes
= res
.number_chars_max
- 1) <= target_int_max ()))
2645 && (info
.bounded
|| maxbytes
< info
.objsize
))
2647 /* If the result is in a valid range bounded by the size of
2648 the destination set it so that it can be used for subsequent
2650 int prec
= TYPE_PRECISION (integer_type_node
);
2652 if (res
.number_chars
< target_int_max () && res
.under4k
)
2654 wide_int num
= wi::shwi (res
.number_chars
- 1, prec
);
2655 set_range_info (lhs
, VR_RANGE
, num
, num
);
2657 else if (res
.number_chars_min
< target_int_max ()
2658 && res
.number_chars_max
< target_int_max ())
2660 wide_int min
= wi::shwi (res
.under4k
? res
.number_chars_min
- 1
2661 : target_int_min (), prec
);
2662 wide_int max
= wi::shwi (res
.number_chars_max
- 1, prec
);
2663 set_range_info (lhs
, VR_RANGE
, min
, max
);
2669 const char *inbounds
2670 = (res
.number_chars_min
<= info
.objsize
2671 ? (res
.number_chars_max
<= info
.objsize
2672 ? "in" : "potentially out-of")
2675 location_t callloc
= gimple_location (info
.callstmt
);
2676 fprintf (dump_file
, "On line %i ", LOCATION_LINE (callloc
));
2677 print_generic_expr (dump_file
, info
.func
, dump_flags
);
2679 const char *ign
= lhs
? "" : " ignored";
2680 if (res
.number_chars
>= HOST_WIDE_INT_MAX
)
2682 " %s-bounds return value in range [%lu, %lu]%s.\n",
2684 (unsigned long)res
.number_chars_min
,
2685 (unsigned long)res
.number_chars_max
, ign
);
2687 fprintf (dump_file
, " %s-bounds return value %lu%s.\n",
2688 inbounds
, (unsigned long)res
.number_chars
, ign
);
2693 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
2694 functions and if so, handle it. */
2697 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator
*gsi
)
2699 call_info info
= call_info ();
2701 info
.callstmt
= gsi_stmt (*gsi
);
2702 if (!gimple_call_builtin_p (info
.callstmt
, BUILT_IN_NORMAL
))
2705 info
.func
= gimple_call_fndecl (info
.callstmt
);
2706 info
.fncode
= DECL_FUNCTION_CODE (info
.func
);
2708 /* The size of the destination as in snprintf(dest, size, ...). */
2709 unsigned HOST_WIDE_INT dstsize
= HOST_WIDE_INT_M1U
;
2711 /* The size of the destination determined by __builtin_object_size. */
2712 unsigned HOST_WIDE_INT objsize
= HOST_WIDE_INT_M1U
;
2714 /* Buffer size argument number (snprintf and vsnprintf). */
2715 unsigned HOST_WIDE_INT idx_dstsize
= HOST_WIDE_INT_M1U
;
2717 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
2718 unsigned HOST_WIDE_INT idx_objsize
= HOST_WIDE_INT_M1U
;
2720 /* Format string argument number (valid for all functions). */
2721 unsigned idx_format
;
2723 switch (info
.fncode
)
2725 case BUILT_IN_SPRINTF
:
2727 // __builtin_sprintf (dst, format, ...)
2732 case BUILT_IN_SPRINTF_CHK
:
2734 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
2740 case BUILT_IN_SNPRINTF
:
2742 // __builtin_snprintf (dst, size, format, ...)
2746 info
.bounded
= true;
2749 case BUILT_IN_SNPRINTF_CHK
:
2751 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
2756 info
.bounded
= true;
2759 case BUILT_IN_VSNPRINTF
:
2761 // __builtin_vsprintf (dst, size, format, va)
2765 info
.bounded
= true;
2768 case BUILT_IN_VSNPRINTF_CHK
:
2770 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
2775 info
.bounded
= true;
2778 case BUILT_IN_VSPRINTF
:
2780 // __builtin_vsprintf (dst, format, va)
2785 case BUILT_IN_VSPRINTF_CHK
:
2787 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
2797 info
.format
= gimple_call_arg (info
.callstmt
, idx_format
);
2799 if (idx_dstsize
== HOST_WIDE_INT_M1U
)
2801 /* For non-bounded functions like sprintf, determine the size
2802 of the destination from the object or pointer passed to it
2803 as the first argument. */
2804 dstsize
= get_destination_size (gimple_call_arg (info
.callstmt
, 0));
2806 else if (tree size
= gimple_call_arg (info
.callstmt
, idx_dstsize
))
2808 /* For bounded functions try to get the size argument. */
2810 if (TREE_CODE (size
) == INTEGER_CST
)
2812 dstsize
= tree_to_uhwi (size
);
2813 /* No object can be larger than SIZE_MAX bytes (half the address
2814 space) on the target. This imposes a limit that's one byte
2816 The functions are defined only for output of at most INT_MAX
2817 bytes. Specifying a bound in excess of that limit effectively
2818 defeats the bounds checking (and on some implementations such
2819 as Solaris cause the function to fail with EINVAL). */
2820 if (dstsize
>= target_size_max () / 2)
2821 warning_at (gimple_location (info
.callstmt
), OPT_Wformat_length_
,
2822 "specified destination size %wu is too large",
2824 else if (dstsize
> target_int_max ())
2825 warning_at (gimple_location (info
.callstmt
), OPT_Wformat_length_
,
2826 "specified destination size %wu exceeds %<INT_MAX %>",
2829 else if (TREE_CODE (size
) == SSA_NAME
)
2831 /* Try to determine the range of values of the argument
2832 and use the greater of the two at -Wformat-level 1 and
2833 the smaller of them at level 2. */
2835 enum value_range_type range_type
2836 = get_range_info (size
, &min
, &max
);
2837 if (range_type
== VR_RANGE
)
2840 = (warn_format_length
< 2
2841 ? wi::fits_uhwi_p (max
) ? max
.to_uhwi () : max
.to_shwi ()
2842 : wi::fits_uhwi_p (min
) ? min
.to_uhwi () : min
.to_shwi ());
2847 if (idx_objsize
!= HOST_WIDE_INT_M1U
)
2849 if (tree size
= gimple_call_arg (info
.callstmt
, idx_objsize
))
2850 if (tree_fits_uhwi_p (size
))
2851 objsize
= tree_to_uhwi (size
);
2854 if (info
.bounded
&& !dstsize
)
2856 /* As a special case, when the explicitly specified destination
2857 size argument (to a bounded function like snprintf) is zero
2858 it is a request to determine the number of bytes on output
2859 without actually producing any. Pretend the size is
2860 unlimited in this case. */
2861 info
.objsize
= HOST_WIDE_INT_MAX
;
2862 info
.nowrite
= true;
2866 /* Set the object size to the smaller of the two arguments
2867 of both have been specified and they're not equal. */
2868 info
.objsize
= dstsize
< objsize
? dstsize
: objsize
;
2871 && dstsize
< target_size_max () / 2 && objsize
< dstsize
)
2873 warning_at (gimple_location (info
.callstmt
), OPT_Wformat_length_
,
2874 "specified size %wu exceeds the size %wu "
2875 "of the destination object", dstsize
, objsize
);
2879 if (integer_zerop (info
.format
))
2881 /* This is diagnosed with -Wformat only when the null is a constant
2882 pointer. The warning here diagnoses instances where the pointer
2884 warning_at (EXPR_LOC_OR_LOC (info
.format
, input_location
),
2885 OPT_Wformat_length_
, "null format string");
2889 info
.fmtstr
= get_format_string (info
.format
, &info
.fmtloc
);
2893 /* The result is the number of bytes output by the formatted function,
2894 including the terminating NUL. */
2895 format_result res
= format_result ();
2896 compute_format_length (info
, &res
);
2898 /* When optimizing and the printf return value optimization is enabled,
2899 attempt to substitute the computed result for the return value of
2900 the call. Avoid this optimization when -frounding-math is in effect
2901 and the format string contains a floating point directive. */
2903 && flag_printf_return_value
2904 && (!flag_rounding_math
|| !res
.floating
))
2905 try_substitute_return_value (gsi
, info
, res
);
2908 /* Execute the pass for function FUN. */
2911 pass_sprintf_length::execute (function
*fun
)
2914 FOR_EACH_BB_FN (bb
, fun
)
2916 for (gimple_stmt_iterator si
= gsi_start_bb (bb
); !gsi_end_p (si
);
2919 /* Iterate over statements, looking for function calls. */
2920 gimple
*stmt
= gsi_stmt (si
);
2922 if (is_gimple_call (stmt
))
2923 handle_gimple_call (&si
);
2930 } /* Unnamed namespace. */
2932 /* Return a pointer to a pass object newly constructed from the context
2936 make_pass_sprintf_length (gcc::context
*ctxt
)
2938 return new pass_sprintf_length (ctxt
);