1 /* Copyright (C) 2016-2024 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 rather 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 format 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-iterator.h"
57 #include "gimple-fold.h"
58 #include "gimple-pretty-print.h"
59 #include "diagnostic-core.h"
60 #include "fold-const.h"
62 #include "tree-object-size.h"
64 #include "tree-ssa-propagate.h"
67 #include "tree-scalar-evolution.h"
68 #include "tree-ssa-loop.h"
70 #include "langhooks.h"
74 #include "pointer-query.h"
75 #include "stor-layout.h"
83 #include "substring-locations.h"
84 #include "diagnostic.h"
86 #include "alloc-pool.h"
87 #include "vr-values.h"
88 #include "tree-ssa-strlen.h"
91 /* The likely worst case value of MB_LEN_MAX for the target, large enough
92 for UTF-8. Ideally, this would be obtained by a target hook if it were
93 to be used for optimization but it's good enough as is for warnings. */
94 #define target_mb_len_max() 6
96 /* The maximum number of bytes a single non-string directive can result
97 in. This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
98 LDBL_MAX_10_EXP of 4932. */
99 #define IEEE_MAX_10_EXP 4932
100 #define target_dir_max() (target_int_max () + IEEE_MAX_10_EXP + 2)
104 /* Set to the warning level for the current function which is equal
105 either to warn_format_trunc for bounded functions or to
106 warn_format_overflow otherwise. */
108 static int warn_level
;
110 /* The minimum, maximum, likely, and unlikely maximum number of bytes
111 of output either a formatting function or an individual directive
116 /* The absolute minimum number of bytes. The result of a successful
117 conversion is guaranteed to be no less than this. (An erroneous
118 conversion can be indicated by MIN > HOST_WIDE_INT_MAX.) */
119 unsigned HOST_WIDE_INT min
;
120 /* The likely maximum result that is used in diagnostics. In most
121 cases MAX is the same as the worst case UNLIKELY result. */
122 unsigned HOST_WIDE_INT max
;
123 /* The likely result used to trigger diagnostics. For conversions
124 that result in a range of bytes [MIN, MAX], LIKELY is somewhere
126 unsigned HOST_WIDE_INT likely
;
127 /* In rare cases (e.g., for multibyte characters) UNLIKELY gives
128 the worst cases maximum result of a directive. In most cases
129 UNLIKELY == MAX. UNLIKELY is used to control the return value
130 optimization but not in diagnostics. */
131 unsigned HOST_WIDE_INT unlikely
;
134 /* Return the value of INT_MIN for the target. */
136 static inline HOST_WIDE_INT
139 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node
));
142 /* Return the value of INT_MAX for the target. */
144 static inline unsigned HOST_WIDE_INT
147 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node
));
150 /* Return the value of SIZE_MAX for the target. */
152 static inline unsigned HOST_WIDE_INT
155 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node
));
158 /* A straightforward mapping from the execution character set to the host
159 character set indexed by execution character. */
161 static char target_to_host_charmap
[256];
163 /* Initialize a mapping from the execution character set to the host
167 init_target_to_host_charmap ()
169 /* If the percent sign is non-zero the mapping has already been
171 if (target_to_host_charmap
['%'])
174 /* Initialize the target_percent character (done elsewhere). */
175 if (!init_target_chars ())
178 /* The subset of the source character set used by printf conversion
179 specifications (strictly speaking, not all letters are used but
180 they are included here for the sake of simplicity). The dollar
181 sign must be included even though it's not in the basic source
183 const char srcset
[] = " 0123456789!\"#%&'()*+,-./:;<=>?[\\]^_{|}~$"
184 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
186 /* Set the mapping for all characters to some ordinary value (i,e.,
187 not none used in printf conversion specifications) and overwrite
188 those that are used by conversion specifications with their
189 corresponding values. */
190 memset (target_to_host_charmap
+ 1, '?', sizeof target_to_host_charmap
- 1);
192 /* Are the two sets of characters the same? */
193 bool all_same_p
= true;
195 for (const char *pc
= srcset
; *pc
; ++pc
)
197 /* Slice off the high end bits in case target characters are
198 signed. All values are expected to be non-nul, otherwise
199 there's a problem. */
200 if (unsigned char tc
= lang_hooks
.to_target_charset (*pc
))
202 target_to_host_charmap
[tc
] = *pc
;
211 /* Set the first element to a non-zero value if the mapping
212 is 1-to-1, otherwise leave it clear (NUL is assumed to be
213 the same in both character sets). */
214 target_to_host_charmap
[0] = all_same_p
;
219 /* Return the host source character corresponding to the character
220 CH in the execution character set if one exists, or some innocuous
221 (non-special, non-nul) source character otherwise. */
223 static inline unsigned char
224 target_to_host (unsigned char ch
)
226 return target_to_host_charmap
[ch
];
229 /* Convert an initial substring of the string TARGSTR consisting of
230 characters in the execution character set into a string in the
231 source character set on the host and store up to HOSTSZ characters
232 in the buffer pointed to by HOSTR. Return HOSTR. */
235 target_to_host (char *hostr
, size_t hostsz
, const char *targstr
)
237 /* Make sure the buffer is reasonably big. */
238 gcc_assert (hostsz
> 4);
240 /* The interesting subset of source and execution characters are
241 the same so no conversion is necessary. However, truncate
242 overlong strings just like the translated strings are. */
243 if (target_to_host_charmap
['\0'] == 1)
245 size_t len
= strlen (targstr
);
248 memcpy (hostr
, targstr
, hostsz
- 4);
249 strcpy (hostr
+ hostsz
- 4, "...");
252 memcpy (hostr
, targstr
, len
+ 1);
256 /* Convert the initial substring of TARGSTR to the corresponding
257 characters in the host set, appending "..." if TARGSTR is too
258 long to fit. Using the static buffer assumes the function is
259 not called in between sequence points (which it isn't). */
260 for (char *ph
= hostr
; ; ++targstr
)
262 *ph
++ = target_to_host (*targstr
);
266 if (size_t (ph
- hostr
) == hostsz
)
268 strcpy (ph
- 4, "...");
276 /* Convert the sequence of decimal digits in the execution character
277 starting at *PS to a HOST_WIDE_INT, analogously to strtol. Return
278 the result and set *PS to one past the last converted character.
279 On range error set ERANGE to the digit that caused it. */
281 static inline HOST_WIDE_INT
282 target_strtowi (const char **ps
, const char **erange
)
284 unsigned HOST_WIDE_INT val
= 0;
287 unsigned char c
= target_to_host (**ps
);
292 /* Check for overflow. */
293 if (val
> ((unsigned HOST_WIDE_INT
) HOST_WIDE_INT_MAX
- c
) / 10LU)
295 val
= HOST_WIDE_INT_MAX
;
298 /* Skip the remaining digits. */
300 c
= target_to_host (*++*ps
);
314 /* Given FORMAT, set *PLOC to the source location of the format string
315 and return the format string if it is known or null otherwise. */
318 get_format_string (tree format
, location_t
*ploc
)
320 *ploc
= EXPR_LOC_OR_LOC (format
, input_location
);
322 return c_getstr (format
);
325 /* For convenience and brevity, shorter named entrypoints of
326 format_string_diagnostic_t::emit_warning_va and
327 format_string_diagnostic_t::emit_warning_n_va.
328 These have to be functions with the attribute so that exgettext
332 ATTRIBUTE_GCC_DIAG (5, 6)
333 fmtwarn (const substring_loc
&fmt_loc
, location_t param_loc
,
334 const char *corrected_substring
, opt_code opt
,
335 const char *gmsgid
, ...)
337 format_string_diagnostic_t
diag (fmt_loc
, NULL
, param_loc
, NULL
,
338 corrected_substring
);
340 va_start (ap
, gmsgid
);
341 bool warned
= diag
.emit_warning_va (opt
, gmsgid
, &ap
);
348 ATTRIBUTE_GCC_DIAG (6, 8) ATTRIBUTE_GCC_DIAG (7, 8)
349 fmtwarn_n (const substring_loc
&fmt_loc
, location_t param_loc
,
350 const char *corrected_substring
, opt_code opt
,
351 unsigned HOST_WIDE_INT n
,
352 const char *singular_gmsgid
, const char *plural_gmsgid
, ...)
354 format_string_diagnostic_t
diag (fmt_loc
, NULL
, param_loc
, NULL
,
355 corrected_substring
);
357 va_start (ap
, plural_gmsgid
);
358 bool warned
= diag
.emit_warning_n_va (opt
, n
, singular_gmsgid
, plural_gmsgid
,
365 /* Format length modifiers. */
370 FMT_LEN_hh
, // char argument
373 FMT_LEN_ll
, // long long
374 FMT_LEN_L
, // long double (and GNU long long)
376 FMT_LEN_t
, // ptrdiff_t
377 FMT_LEN_j
// intmax_t
381 /* Description of the result of conversion either of a single directive
382 or the whole format string. */
387 /* Construct a FMTRESULT object with all counters initialized
388 to MIN. KNOWNRANGE is set when MIN is valid. */
389 fmtresult (unsigned HOST_WIDE_INT min
= HOST_WIDE_INT_MAX
)
390 : argmin (), argmax (), dst_offset (HOST_WIDE_INT_MIN
), nonstr (),
391 knownrange (min
< HOST_WIDE_INT_MAX
),
397 range
.unlikely
= min
;
400 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
401 KNOWNRANGE is set when both MIN and MAX are valid. */
402 fmtresult (unsigned HOST_WIDE_INT min
, unsigned HOST_WIDE_INT max
,
403 unsigned HOST_WIDE_INT likely
= HOST_WIDE_INT_MAX
)
404 : argmin (), argmax (), dst_offset (HOST_WIDE_INT_MIN
), nonstr (),
405 knownrange (min
< HOST_WIDE_INT_MAX
&& max
< HOST_WIDE_INT_MAX
),
410 range
.likely
= max
< likely
? min
: likely
;
411 range
.unlikely
= max
;
414 /* Adjust result upward to reflect the RANGE of values the specified
415 width or precision is known to be in. */
416 fmtresult
& adjust_for_width_or_precision (const HOST_WIDE_INT
[2],
418 unsigned = 0, unsigned = 0);
420 /* Return the maximum number of decimal digits a value of TYPE
421 formats as on output. */
422 static unsigned type_max_digits (tree
, int);
424 /* The range a directive's argument is in. */
427 /* The starting offset into the destination of the formatted function
428 call of the %s argument that points into (aliases with) the same
429 destination array. */
430 HOST_WIDE_INT dst_offset
;
432 /* The minimum and maximum number of bytes that a directive
433 results in on output for an argument in the range above. */
436 /* Non-nul when the argument of a string directive is not a nul
437 terminated string. */
440 /* True when the range above is obtained from a known value of
441 a directive's argument or its bounds and not the result of
442 heuristics that depend on warning levels. */
445 /* True for a directive that may fail (such as wide character
449 /* True when the argument is a null pointer. */
453 /* Adjust result upward to reflect the range ADJUST of values the
454 specified width or precision is known to be in. When non-null,
455 TYPE denotes the type of the directive whose result is being
456 adjusted, BASE gives the base of the directive (octal, decimal,
457 or hex), and ADJ denotes the additional adjustment to the LIKELY
458 counter that may need to be added when ADJUST is a range. */
461 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust
[2],
462 tree type
/* = NULL_TREE */,
463 unsigned base
/* = 0 */,
464 unsigned adj
/* = 0 */)
466 bool minadjusted
= false;
468 /* Adjust the minimum and likely counters. */
471 if (range
.min
< (unsigned HOST_WIDE_INT
)adjust
[0])
473 range
.min
= adjust
[0];
477 /* Adjust the likely counter. */
478 if (range
.likely
< range
.min
)
479 range
.likely
= range
.min
;
481 else if (adjust
[0] == target_int_min ()
482 && (unsigned HOST_WIDE_INT
)adjust
[1] == target_int_max ())
485 /* Adjust the maximum counter. */
488 if (range
.max
< (unsigned HOST_WIDE_INT
)adjust
[1])
490 range
.max
= adjust
[1];
492 /* Set KNOWNRANGE if both the minimum and maximum have been
493 adjusted. Otherwise leave it at what it was before. */
494 knownrange
= minadjusted
;
498 if (warn_level
> 1 && type
)
500 /* For large non-constant width or precision whose range spans
501 the maximum number of digits produced by the directive for
502 any argument, set the likely number of bytes to be at most
503 the number digits plus other adjustment determined by the
504 caller (one for sign or two for the hexadecimal "0x"
506 unsigned dirdigs
= type_max_digits (type
, base
);
507 if (adjust
[0] < dirdigs
&& dirdigs
< adjust
[1]
508 && range
.likely
< dirdigs
)
509 range
.likely
= dirdigs
+ adj
;
511 else if (range
.likely
< (range
.min
? range
.min
: 1))
513 /* Conservatively, set LIKELY to at least MIN but no less than
514 1 unless MAX is zero. */
515 range
.likely
= (range
.min
517 : range
.max
&& (range
.max
< HOST_WIDE_INT_MAX
518 || warn_level
> 1) ? 1 : 0);
521 /* Finally adjust the unlikely counter to be at least as large as
523 if (range
.unlikely
< range
.max
)
524 range
.unlikely
= range
.max
;
529 /* Return the maximum number of digits a value of TYPE formats in
530 BASE on output, not counting base prefix . */
533 fmtresult::type_max_digits (tree type
, int base
)
535 unsigned prec
= TYPE_PRECISION (type
);
541 return (prec
+ 2) / 3;
543 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
544 of 8, 16, 32, and 64 bits. */
545 return prec
* 301 / 1000 + 1;
554 get_int_range (tree
, gimple
*, HOST_WIDE_INT
*, HOST_WIDE_INT
*,
555 bool, HOST_WIDE_INT
, range_query
*);
559 /* Description of a format directive. A directive is either a plain
560 string or a conversion specification that starts with '%'. */
564 directive (const call_info
*inf
, unsigned dno
)
565 : info (inf
), dirno (dno
), argno (), beg (), len (), flags (),
566 width (), prec (), modifier (), specifier (), arg (), fmtfunc ()
569 /* Reference to the info structure describing the call that this
570 directive is a part of. */
571 const call_info
*info
;
573 /* The 1-based directive number (for debugging). */
576 /* The zero-based argument number of the directive's argument ARG in
577 the function's argument list. */
580 /* The first character of the directive and its length. */
584 /* A bitmap of flags, one for each character. */
585 unsigned flags
[256 / sizeof (int)];
587 /* The range of values of the specified width, or -1 if not specified. */
588 HOST_WIDE_INT width
[2];
589 /* The range of values of the specified precision, or -1 if not
591 HOST_WIDE_INT prec
[2];
593 /* Length modifier. */
594 format_lengths modifier
;
596 /* Format specifier character. */
599 /* The argument of the directive or null when the directive doesn't
600 take one or when none is available (such as for vararg functions). */
603 /* Format conversion function that given a directive and an argument
604 returns the formatting result. */
605 fmtresult (*fmtfunc
) (const directive
&, tree
, pointer_query
&);
607 /* Return True when the format flag CHR has been used. */
608 bool get_flag (char chr
) const
610 unsigned char c
= chr
& 0xff;
611 return (flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
612 & (1U << (c
% (CHAR_BIT
* sizeof *flags
))));
615 /* Make a record of the format flag CHR having been used. */
616 void set_flag (char chr
)
618 unsigned char c
= chr
& 0xff;
619 flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
620 |= (1U << (c
% (CHAR_BIT
* sizeof *flags
)));
623 /* Reset the format flag CHR. */
624 void clear_flag (char chr
)
626 unsigned char c
= chr
& 0xff;
627 flags
[c
/ (CHAR_BIT
* sizeof *flags
)]
628 &= ~(1U << (c
% (CHAR_BIT
* sizeof *flags
)));
631 /* Set both bounds of the width range to VAL. */
632 void set_width (HOST_WIDE_INT val
)
634 width
[0] = width
[1] = val
;
637 /* Set the width range according to ARG, with both bounds being
638 no less than 0. For a constant ARG set both bounds to its value
639 or 0, whichever is greater. For a non-constant ARG in some range
640 set width to its range adjusting each bound to -1 if it's less.
641 For an indeterminate ARG set width to [0, INT_MAX]. */
642 void set_width (tree arg
, range_query
*);
644 /* Set both bounds of the precision range to VAL. */
645 void set_precision (HOST_WIDE_INT val
)
647 prec
[0] = prec
[1] = val
;
650 /* Set the precision range according to ARG, with both bounds being
651 no less than -1. For a constant ARG set both bounds to its value
652 or -1 whichever is greater. For a non-constant ARG in some range
653 set precision to its range adjusting each bound to -1 if it's less.
654 For an indeterminate ARG set precision to [-1, INT_MAX]. */
655 void set_precision (tree arg
, range_query
*query
);
657 /* Return true if both width and precision are known to be
658 either constant or in some range, false otherwise. */
659 bool known_width_and_precision () const
661 return ((width
[1] < 0
662 || (unsigned HOST_WIDE_INT
)width
[1] <= target_int_max ())
664 || (unsigned HOST_WIDE_INT
)prec
[1] < target_int_max ()));
668 /* The result of a call to a formatted function. */
673 : range (), aliases (), alias_count (), knownrange (), posunder4k (),
674 floating (), warned () { /* No-op. */ }
678 XDELETEVEC (aliases
);
681 /* Range of characters written by the formatted function.
682 Setting the minimum to HOST_WIDE_INT_MAX disables all
683 length tracking for the remainder of the format string. */
688 directive dir
; /* The directive that aliases the destination. */
689 HOST_WIDE_INT offset
; /* The offset at which it aliases it. */
690 result_range range
; /* The raw result of the directive. */
693 /* An array of directives whose pointer argument aliases a part
694 of the destination object of the formatted function. */
696 unsigned alias_count
;
698 /* True when the range above is obtained from known values of
699 directive arguments, or bounds on the amount of output such
700 as width and precision, and not the result of heuristics that
701 depend on warning levels. It's used to issue stricter diagnostics
702 in cases where strings of unknown lengths are bounded by the arrays
703 they are determined to refer to. KNOWNRANGE must not be used for
704 the return value optimization. */
707 /* True if no individual directive could fail or result in more than
708 4095 bytes of output (the total NUMBER_CHARS_{MIN,MAX} might be
709 greater). Implementations are not required to handle directives
710 that produce more than 4K bytes (leading to undefined behavior)
711 and so when one is found it disables the return value optimization.
712 Similarly, directives that can fail (such as wide character
713 directives) disable the optimization. */
716 /* True when a floating point directive has been seen in the format
720 /* True when an intermediate result has caused a warning. Used to
721 avoid issuing duplicate warnings while finishing the processing
722 of a call. WARNED also disables the return value optimization. */
725 /* Preincrement the number of output characters by 1. */
726 format_result
& operator++ ()
731 /* Postincrement the number of output characters by 1. */
732 format_result
operator++ (int)
734 format_result
prev (*this);
739 /* Increment the number of output characters by N. */
740 format_result
& operator+= (unsigned HOST_WIDE_INT
);
742 /* Add a directive to the sequence of those with potentially aliasing
744 void append_alias (const directive
&, HOST_WIDE_INT
, const result_range
&);
747 /* Not copyable or assignable. */
748 format_result (format_result
&);
749 void operator= (format_result
&);
753 format_result::operator+= (unsigned HOST_WIDE_INT n
)
755 gcc_assert (n
< HOST_WIDE_INT_MAX
);
757 if (range
.min
< HOST_WIDE_INT_MAX
)
760 if (range
.max
< HOST_WIDE_INT_MAX
)
763 if (range
.likely
< HOST_WIDE_INT_MAX
)
766 if (range
.unlikely
< HOST_WIDE_INT_MAX
)
773 format_result::append_alias (const directive
&d
, HOST_WIDE_INT off
,
774 const result_range
&resrng
)
776 unsigned cnt
= alias_count
+ 1;
777 alias_info
*ar
= XNEWVEC (alias_info
, cnt
);
779 for (unsigned i
= 0; i
!= alias_count
; ++i
)
782 ar
[alias_count
].dir
= d
;
783 ar
[alias_count
].offset
= off
;
784 ar
[alias_count
].range
= resrng
;
786 XDELETEVEC (aliases
);
792 /* Return the logarithm of X in BASE. */
795 ilog (unsigned HOST_WIDE_INT x
, int base
)
806 /* Return the number of bytes resulting from converting into a string
807 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
808 PLUS indicates whether 1 for a plus sign should be added for positive
809 numbers, and PREFIX whether the length of an octal ('0') or hexadecimal
810 ('0x') or binary ('0b') prefix should be added for nonzero numbers.
811 Return -1 if X cannot be represented. */
814 tree_digits (tree x
, int base
, HOST_WIDE_INT prec
, bool plus
, bool prefix
)
816 unsigned HOST_WIDE_INT absval
;
820 if (TYPE_UNSIGNED (TREE_TYPE (x
)))
822 if (tree_fits_uhwi_p (x
))
824 absval
= tree_to_uhwi (x
);
832 if (tree_fits_shwi_p (x
))
834 HOST_WIDE_INT i
= tree_to_shwi (x
);
835 if (HOST_WIDE_INT_MIN
== i
)
837 /* Avoid undefined behavior due to negating a minimum. */
838 absval
= HOST_WIDE_INT_MAX
;
856 int ndigs
= ilog (absval
, base
);
858 res
+= prec
< ndigs
? ndigs
: prec
;
860 /* Adjust a non-zero value for the base prefix, either hexadecimal,
861 or, unless precision has resulted in a leading zero, also octal. */
862 if (prefix
&& absval
)
864 if (base
== 8 && prec
<= ndigs
)
866 else if (base
== 16 || base
== 2) /* 0x...(0X...) or 0b...(0B...). */
873 /* Description of a call to a formatted function. */
877 /* Function call statement. */
880 /* Function called. */
883 /* Called built-in function code. */
884 built_in_function fncode
;
886 /* The "origin" of the destination pointer argument, which is either
887 the DECL of the destination buffer being written into or a pointer
888 that points to it, plus some offset. */
891 /* For a destination pointing to a struct array member, the offset of
893 HOST_WIDE_INT dst_field
;
895 /* The offset into the destination buffer. */
896 HOST_WIDE_INT dst_offset
;
898 /* Format argument and format string extracted from it. */
902 /* The location of the format argument. */
905 /* The destination object size for __builtin___xxx_chk functions
906 typically determined by __builtin_object_size, or -1 if unknown. */
907 unsigned HOST_WIDE_INT objsize
;
909 /* Number of the first variable argument. */
910 unsigned HOST_WIDE_INT argidx
;
912 /* True for functions like snprintf that specify the size of
913 the destination, false for others like sprintf that don't. */
916 /* True for bounded functions like snprintf that specify a zero-size
917 buffer as a request to compute the size of output without actually
918 writing any. NOWRITE is cleared in response to the %n directive
919 which has side-effects similar to writing output. */
922 /* Return true if the called function's return value is used. */
923 bool retval_used () const
925 return gimple_get_lhs (callstmt
);
928 /* Return the warning option corresponding to the called function. */
929 opt_code
warnopt () const
931 return bounded
? OPT_Wformat_truncation_
: OPT_Wformat_overflow_
;
934 /* Return true for calls to file formatted functions. */
935 bool is_file_func () const
937 return (fncode
== BUILT_IN_FPRINTF
938 || fncode
== BUILT_IN_FPRINTF_CHK
939 || fncode
== BUILT_IN_FPRINTF_UNLOCKED
940 || fncode
== BUILT_IN_VFPRINTF
941 || fncode
== BUILT_IN_VFPRINTF_CHK
);
944 /* Return true for calls to string formatted functions. */
945 bool is_string_func () const
947 return (fncode
== BUILT_IN_SPRINTF
948 || fncode
== BUILT_IN_SPRINTF_CHK
949 || fncode
== BUILT_IN_SNPRINTF
950 || fncode
== BUILT_IN_SNPRINTF_CHK
951 || fncode
== BUILT_IN_VSPRINTF
952 || fncode
== BUILT_IN_VSPRINTF_CHK
953 || fncode
== BUILT_IN_VSNPRINTF
954 || fncode
== BUILT_IN_VSNPRINTF_CHK
);
959 directive::set_width (tree arg
, range_query
*query
)
961 get_int_range (arg
, info
->callstmt
, width
, width
+ 1, true, 0, query
);
965 directive::set_precision (tree arg
, range_query
*query
)
967 get_int_range (arg
, info
->callstmt
, prec
, prec
+ 1, false, -1, query
);
970 /* Return the result of formatting a no-op directive (such as '%n'). */
973 format_none (const directive
&, tree
, pointer_query
&)
979 /* Return the result of formatting the '%%' directive. */
982 format_percent (const directive
&, tree
, pointer_query
&)
989 /* Compute intmax_type_node and uintmax_type_node similarly to how
990 tree.cc builds size_type_node. */
993 build_intmax_type_nodes (tree
*pintmax
, tree
*puintmax
)
995 if (strcmp (UINTMAX_TYPE
, "unsigned int") == 0)
997 *pintmax
= integer_type_node
;
998 *puintmax
= unsigned_type_node
;
1000 else if (strcmp (UINTMAX_TYPE
, "long unsigned int") == 0)
1002 *pintmax
= long_integer_type_node
;
1003 *puintmax
= long_unsigned_type_node
;
1005 else if (strcmp (UINTMAX_TYPE
, "long long unsigned int") == 0)
1007 *pintmax
= long_long_integer_type_node
;
1008 *puintmax
= long_long_unsigned_type_node
;
1012 for (int i
= 0; i
< NUM_INT_N_ENTS
; i
++)
1013 if (int_n_enabled_p
[i
])
1015 char name
[50], altname
[50];
1016 sprintf (name
, "__int%d unsigned", int_n_data
[i
].bitsize
);
1017 sprintf (altname
, "__int%d__ unsigned", int_n_data
[i
].bitsize
);
1019 if (strcmp (name
, UINTMAX_TYPE
) == 0
1020 || strcmp (altname
, UINTMAX_TYPE
) == 0)
1022 *pintmax
= int_n_trees
[i
].signed_type
;
1023 *puintmax
= int_n_trees
[i
].unsigned_type
;
1031 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1032 in and that is representable in type int.
1033 Return true when the range is a subrange of that of int.
1034 When ARG is null it is as if it had the full range of int.
1035 When ABSOLUTE is true the range reflects the absolute value of
1036 the argument. When ABSOLUTE is false, negative bounds of
1037 the determined range are replaced with NEGBOUND. */
1040 get_int_range (tree arg
, gimple
*stmt
,
1041 HOST_WIDE_INT
*pmin
, HOST_WIDE_INT
*pmax
,
1042 bool absolute
, HOST_WIDE_INT negbound
,
1045 /* The type of the result. */
1046 const_tree type
= integer_type_node
;
1048 bool knownrange
= false;
1052 *pmin
= tree_to_shwi (TYPE_MIN_VALUE (type
));
1053 *pmax
= tree_to_shwi (TYPE_MAX_VALUE (type
));
1055 else if (TREE_CODE (arg
) == INTEGER_CST
1056 && TYPE_PRECISION (TREE_TYPE (arg
)) <= TYPE_PRECISION (type
))
1058 /* For a constant argument return its value adjusted as specified
1059 by NEGATIVE and NEGBOUND and return true to indicate that the
1061 *pmin
= tree_fits_shwi_p (arg
) ? tree_to_shwi (arg
) : tree_to_uhwi (arg
);
1067 /* True if the argument's range cannot be determined. */
1068 bool unknown
= true;
1070 tree argtype
= TREE_TYPE (arg
);
1072 /* Ignore invalid arguments with greater precision that that
1073 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1074 They will have been detected and diagnosed by -Wformat and
1075 so it's not important to complicate this code to try to deal
1077 if (TREE_CODE (arg
) == SSA_NAME
1078 && INTEGRAL_TYPE_P (argtype
)
1079 && TYPE_PRECISION (argtype
) <= TYPE_PRECISION (type
))
1081 /* Try to determine the range of values of the integer argument. */
1083 query
->range_of_expr (vr
, arg
, stmt
);
1085 if (!vr
.undefined_p () && !vr
.varying_p ())
1087 HOST_WIDE_INT type_min
1088 = (TYPE_UNSIGNED (argtype
)
1089 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype
))
1090 : tree_to_shwi (TYPE_MIN_VALUE (argtype
)));
1092 HOST_WIDE_INT type_max
= tree_to_uhwi (TYPE_MAX_VALUE (argtype
));
1094 tree type
= TREE_TYPE (arg
);
1095 tree tmin
= wide_int_to_tree (type
, vr
.lower_bound ());
1096 tree tmax
= wide_int_to_tree (type
, vr
.upper_bound ());
1097 *pmin
= TREE_INT_CST_LOW (tmin
);
1098 *pmax
= TREE_INT_CST_LOW (tmax
);
1102 /* Return true if the adjusted range is a subrange of
1103 the full range of the argument's type. *PMAX may
1104 be less than *PMIN when the argument is unsigned
1105 and its upper bound is in excess of TYPE_MAX. In
1106 that (invalid) case disregard the range and use that
1107 of the expected type instead. */
1108 knownrange
= type_min
< *pmin
|| *pmax
< type_max
;
1115 /* Handle an argument with an unknown range as if none had been
1118 return get_int_range (NULL_TREE
, NULL
, pmin
, pmax
, absolute
,
1122 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1128 *pmin
= *pmax
= -*pmin
;
1131 /* Make sure signed overlow is avoided. */
1132 gcc_assert (*pmin
!= HOST_WIDE_INT_MIN
);
1134 HOST_WIDE_INT tmp
= -*pmin
;
1141 else if (*pmin
< negbound
)
1147 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1148 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1149 the type of the directive's formal argument it's possible for both
1150 to result in the same number of bytes or a range of bytes that's
1151 less than the number of bytes that would result from formatting
1152 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1153 determined by checking for the actual argument being in the range
1154 of the type of the directive. If it isn't it must be assumed to
1155 take on the full range of the directive's type.
1156 Return true when the range has been adjusted to the full range
1157 of DIRTYPE, and false otherwise. */
1160 adjust_range_for_overflow (tree dirtype
, tree
*argmin
, tree
*argmax
)
1162 tree argtype
= TREE_TYPE (*argmin
);
1163 unsigned argprec
= TYPE_PRECISION (argtype
);
1164 unsigned dirprec
= TYPE_PRECISION (dirtype
);
1166 /* If the actual argument and the directive's argument have the same
1167 precision and sign there can be no overflow and so there is nothing
1169 if (argprec
== dirprec
&& TYPE_SIGN (argtype
) == TYPE_SIGN (dirtype
))
1172 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1173 branch in the extract_range_from_unary_expr function in tree-vrp.cc. */
1175 if (TREE_CODE (*argmin
) == INTEGER_CST
1176 && TREE_CODE (*argmax
) == INTEGER_CST
1177 && (dirprec
>= argprec
1178 || integer_zerop (int_const_binop (RSHIFT_EXPR
,
1179 int_const_binop (MINUS_EXPR
,
1182 size_int (dirprec
)))))
1184 unsigned int maxprec
= MAX (argprec
, dirprec
);
1185 *argmin
= force_fit_type (dirtype
,
1186 wide_int::from (wi::to_wide (*argmin
), maxprec
,
1187 TYPE_SIGN (argtype
)),
1189 *argmax
= force_fit_type (dirtype
,
1190 wide_int::from (wi::to_wide (*argmax
), maxprec
,
1191 TYPE_SIGN (argtype
)),
1194 /* If *ARGMIN is still less than *ARGMAX the conversion above
1195 is safe. Otherwise, it has overflowed and would be unsafe. */
1196 if (tree_int_cst_le (*argmin
, *argmax
))
1200 *argmin
= TYPE_MIN_VALUE (dirtype
);
1201 *argmax
= TYPE_MAX_VALUE (dirtype
);
1205 /* Return a range representing the minimum and maximum number of bytes
1206 that the format directive DIR will output for any argument given
1207 the WIDTH and PRECISION (extracted from DIR). This function is
1208 used when the directive argument or its value isn't known. */
1211 format_integer (const directive
&dir
, tree arg
, pointer_query
&ptr_qry
)
1213 tree intmax_type_node
;
1214 tree uintmax_type_node
;
1216 /* Base to format the number in. */
1219 /* True when a conversion is preceded by a prefix indicating the base
1220 of the argument (octal or hexadecimal). */
1221 const bool maybebase
= dir
.get_flag ('#');
1223 /* True when a signed conversion is preceded by a sign or space. */
1224 bool maybesign
= false;
1226 /* True for signed conversions (i.e., 'd' and 'i'). */
1229 switch (dir
.specifier
)
1233 /* Space and '+' are only meaningful for signed conversions. */
1234 maybesign
= dir
.get_flag (' ') | dir
.get_flag ('+');
1256 const unsigned adj
= (sign
| maybebase
) + (base
== 2 || base
== 16);
1258 /* The type of the "formal" argument expected by the directive. */
1259 tree dirtype
= NULL_TREE
;
1261 /* Determine the expected type of the argument from the length
1263 switch (dir
.modifier
)
1266 if (dir
.specifier
== 'p')
1267 dirtype
= ptr_type_node
;
1269 dirtype
= sign
? integer_type_node
: unsigned_type_node
;
1273 dirtype
= sign
? short_integer_type_node
: short_unsigned_type_node
;
1277 dirtype
= sign
? signed_char_type_node
: unsigned_char_type_node
;
1281 dirtype
= sign
? long_integer_type_node
: long_unsigned_type_node
;
1287 ? long_long_integer_type_node
1288 : long_long_unsigned_type_node
);
1292 dirtype
= signed_or_unsigned_type_for (!sign
, size_type_node
);
1296 dirtype
= signed_or_unsigned_type_for (!sign
, ptrdiff_type_node
);
1300 build_intmax_type_nodes (&intmax_type_node
, &uintmax_type_node
);
1301 dirtype
= sign
? intmax_type_node
: uintmax_type_node
;
1305 return fmtresult ();
1308 /* The type of the argument to the directive, either deduced from
1309 the actual non-constant argument if one is known, or from
1310 the directive itself when none has been provided because it's
1312 tree argtype
= NULL_TREE
;
1316 /* When the argument has not been provided, use the type of
1317 the directive's argument as an approximation. This will
1318 result in false positives for directives like %i with
1319 arguments with smaller precision (such as short or char). */
1322 else if (TREE_CODE (arg
) == INTEGER_CST
)
1324 /* When a constant argument has been provided use its value
1325 rather than type to determine the length of the output. */
1328 if ((dir
.prec
[0] <= 0 && dir
.prec
[1] >= 0) && integer_zerop (arg
))
1330 /* As a special case, a precision of zero with a zero argument
1331 results in zero bytes except in base 8 when the '#' flag is
1332 specified, and for signed conversions in base 8 and 10 when
1333 either the space or '+' flag has been specified and it results
1334 in just one byte (with width having the normal effect). This
1335 must extend to the case of a specified precision with
1336 an unknown value because it can be zero. */
1337 res
.range
.min
= ((base
== 8 && dir
.get_flag ('#')) || maybesign
);
1338 if (res
.range
.min
== 0 && dir
.prec
[0] != dir
.prec
[1])
1341 res
.range
.likely
= 1;
1345 res
.range
.max
= res
.range
.min
;
1346 res
.range
.likely
= res
.range
.min
;
1351 /* Convert the argument to the type of the directive. */
1352 arg
= fold_convert (dirtype
, arg
);
1354 res
.range
.min
= tree_digits (arg
, base
, dir
.prec
[0],
1355 maybesign
, maybebase
);
1356 if (dir
.prec
[0] == dir
.prec
[1])
1357 res
.range
.max
= res
.range
.min
;
1359 res
.range
.max
= tree_digits (arg
, base
, dir
.prec
[1],
1360 maybesign
, maybebase
);
1361 res
.range
.likely
= res
.range
.min
;
1362 res
.knownrange
= true;
1365 res
.range
.unlikely
= res
.range
.max
;
1367 /* Bump up the counters if WIDTH is greater than LEN. */
1368 res
.adjust_for_width_or_precision (dir
.width
, dirtype
, base
, adj
);
1369 /* Bump up the counters again if PRECision is greater still. */
1370 res
.adjust_for_width_or_precision (dir
.prec
, dirtype
, base
, adj
);
1374 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg
))
1375 || TREE_CODE (TREE_TYPE (arg
)) == POINTER_TYPE
)
1376 /* Determine the type of the provided non-constant argument. */
1377 argtype
= TREE_TYPE (arg
);
1379 /* Don't bother with invalid arguments since they likely would
1380 have already been diagnosed, and disable any further checking
1381 of the format string by returning [-1, -1]. */
1382 return fmtresult ();
1386 /* Using either the range the non-constant argument is in, or its
1387 type (either "formal" or actual), create a range of values that
1388 constrain the length of output given the warning level. */
1389 tree argmin
= NULL_TREE
;
1390 tree argmax
= NULL_TREE
;
1393 && TREE_CODE (arg
) == SSA_NAME
1394 && INTEGRAL_TYPE_P (argtype
))
1396 /* Try to determine the range of values of the integer argument
1397 (range information is not available for pointers). */
1399 ptr_qry
.rvals
->range_of_expr (vr
, arg
, dir
.info
->callstmt
);
1401 if (!vr
.varying_p () && !vr
.undefined_p ())
1403 argmin
= wide_int_to_tree (TREE_TYPE (arg
), vr
.lower_bound ());
1404 argmax
= wide_int_to_tree (TREE_TYPE (arg
), vr
.upper_bound ());
1406 /* Set KNOWNRANGE if the argument is in a known subrange
1407 of the directive's type and neither width nor precision
1408 is unknown. (KNOWNRANGE may be reset below). */
1410 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype
), argmin
)
1411 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype
), argmax
))
1412 && dir
.known_width_and_precision ());
1414 res
.argmin
= argmin
;
1415 res
.argmax
= argmax
;
1419 /* The argument here may be the result of promoting the actual
1420 argument to int. Try to determine the type of the actual
1421 argument before promotion and narrow down its range that
1423 gimple
*def
= SSA_NAME_DEF_STMT (arg
);
1424 if (is_gimple_assign (def
))
1426 tree_code code
= gimple_assign_rhs_code (def
);
1427 if (code
== INTEGER_CST
)
1429 arg
= gimple_assign_rhs1 (def
);
1430 return format_integer (dir
, arg
, ptr_qry
);
1433 if (code
== NOP_EXPR
)
1435 tree type
= TREE_TYPE (gimple_assign_rhs1 (def
));
1436 if (INTEGRAL_TYPE_P (type
)
1437 || TREE_CODE (type
) == POINTER_TYPE
)
1446 if (TREE_CODE (argtype
) == POINTER_TYPE
)
1448 argmin
= build_int_cst (pointer_sized_int_node
, 0);
1449 argmax
= build_all_ones_cst (pointer_sized_int_node
);
1453 argmin
= TYPE_MIN_VALUE (argtype
);
1454 argmax
= TYPE_MAX_VALUE (argtype
);
1458 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1459 of the directive. If it has been cleared then since ARGMIN and/or
1460 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1461 ARGMAX in the result to include in diagnostics. */
1462 if (adjust_range_for_overflow (dirtype
, &argmin
, &argmax
))
1464 res
.knownrange
= false;
1465 res
.argmin
= argmin
;
1466 res
.argmax
= argmax
;
1469 /* Recursively compute the minimum and maximum from the known range. */
1470 if (TYPE_UNSIGNED (dirtype
) || tree_int_cst_sgn (argmin
) >= 0)
1472 /* For unsigned conversions/directives or signed when
1473 the minimum is positive, use the minimum and maximum to compute
1474 the shortest and longest output, respectively. */
1475 res
.range
.min
= format_integer (dir
, argmin
, ptr_qry
).range
.min
;
1476 res
.range
.max
= format_integer (dir
, argmax
, ptr_qry
).range
.max
;
1478 else if (tree_int_cst_sgn (argmax
) < 0)
1480 /* For signed conversions/directives if maximum is negative,
1481 use the minimum as the longest output and maximum as the
1483 res
.range
.min
= format_integer (dir
, argmax
, ptr_qry
).range
.min
;
1484 res
.range
.max
= format_integer (dir
, argmin
, ptr_qry
).range
.max
;
1488 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1489 as the shortest output and for the longest output compute the
1490 length of the output of both minimum and maximum and pick the
1492 unsigned HOST_WIDE_INT max1
1493 = format_integer (dir
, argmin
, ptr_qry
).range
.max
;
1494 unsigned HOST_WIDE_INT max2
1495 = format_integer (dir
, argmax
, ptr_qry
).range
.max
;
1497 = format_integer (dir
, integer_zero_node
, ptr_qry
).range
.min
;
1498 res
.range
.max
= MAX (max1
, max2
);
1501 /* If the range is known, use the maximum as the likely length. */
1503 res
.range
.likely
= res
.range
.max
;
1506 /* Otherwise, use the minimum. Except for the case where for %#x or
1507 %#o the minimum is just for a single value in the range (0) and
1508 for all other values it is something longer, like 0x1 or 01.
1509 Use the length for value 1 in that case instead as the likely
1511 res
.range
.likely
= res
.range
.min
;
1514 && (tree_int_cst_sgn (argmin
) < 0 || tree_int_cst_sgn (argmax
) > 0))
1516 if (res
.range
.min
== 1)
1517 res
.range
.likely
+= base
== 8 ? 1 : 2;
1518 else if (res
.range
.min
== 2
1519 && (base
== 16 || base
== 2)
1520 && (dir
.width
[0] == 2 || dir
.prec
[0] == 2))
1525 res
.range
.unlikely
= res
.range
.max
;
1526 res
.adjust_for_width_or_precision (dir
.width
, dirtype
, base
, adj
);
1527 res
.adjust_for_width_or_precision (dir
.prec
, dirtype
, base
, adj
);
1532 /* Return the number of bytes that a format directive consisting of FLAGS,
1533 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1534 would result for argument X under ideal conditions (i.e., if PREC
1535 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1536 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1537 This function works around those problems. */
1539 static unsigned HOST_WIDE_INT
1540 get_mpfr_format_length (mpfr_ptr x
, const char *flags
, HOST_WIDE_INT prec
,
1541 char spec
, char rndspec
)
1545 HOST_WIDE_INT len
= strlen (flags
);
1548 memcpy (fmtstr
+ 1, flags
, len
);
1549 memcpy (fmtstr
+ 1 + len
, ".*R", 3);
1550 fmtstr
[len
+ 4] = rndspec
;
1551 fmtstr
[len
+ 5] = spec
;
1552 fmtstr
[len
+ 6] = '\0';
1554 spec
= TOUPPER (spec
);
1555 if (spec
== 'E' || spec
== 'F')
1557 /* For %e, specify the precision explicitly since mpfr_sprintf
1558 does its own thing just to be different (see MPFR bug 21088). */
1564 /* Avoid passing negative precisions with larger magnitude to MPFR
1565 to avoid exposing its bugs. (A negative precision is supposed
1571 HOST_WIDE_INT p
= prec
;
1573 if (spec
== 'G' && !strchr (flags
, '#'))
1575 /* For G/g without the pound flag, precision gives the maximum number
1576 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1577 a 128 bit IEEE extended precision, 4932. Using twice as much here
1578 should be more than sufficient for any real format. */
1579 if ((IEEE_MAX_10_EXP
* 2) < prec
)
1580 prec
= IEEE_MAX_10_EXP
* 2;
1585 /* Cap precision arbitrarily at 1KB and add the difference
1586 (if any) to the MPFR result. */
1591 len
= mpfr_snprintf (NULL
, 0, fmtstr
, (int)p
, x
);
1593 /* Handle the unlikely (impossible?) error by returning more than
1594 the maximum dictated by the function's return type. */
1596 return target_dir_max () + 1;
1598 /* Adjust the return value by the difference. */
1605 /* Return the number of bytes to format using the format specifier
1606 SPEC and the precision PREC the largest value in the real floating
1609 static unsigned HOST_WIDE_INT
1610 format_floating_max (tree type
, char spec
, HOST_WIDE_INT prec
)
1612 machine_mode mode
= TYPE_MODE (type
);
1614 /* IBM Extended mode. */
1615 if (MODE_COMPOSITE_P (mode
))
1618 /* Get the real type format description for the target. */
1619 const real_format
*rfmt
= REAL_MODE_FORMAT (mode
);
1622 real_maxval (&rv
, 0, mode
);
1624 /* Convert the GCC real value representation with the precision
1625 of the real type to the mpfr_t format with the GCC default
1626 round-to-nearest mode. */
1628 mpfr_init2 (x
, rfmt
->p
);
1629 mpfr_from_real (x
, &rv
, MPFR_RNDN
);
1631 /* Return a value one greater to account for the leading minus sign. */
1632 unsigned HOST_WIDE_INT r
1633 = 1 + get_mpfr_format_length (x
, "", prec
, spec
, 'D');
1638 /* Return a range representing the minimum and maximum number of bytes
1639 that the directive DIR will output for any argument. PREC gives
1640 the adjusted precision range to account for negative precisions
1641 meaning the default 6. This function is used when the directive
1642 argument or its value isn't known. */
1645 format_floating (const directive
&dir
, const HOST_WIDE_INT prec
[2])
1649 switch (dir
.modifier
)
1653 type
= double_type_node
;
1657 type
= long_double_type_node
;
1661 type
= long_double_type_node
;
1665 return fmtresult ();
1668 /* The minimum and maximum number of bytes produced by the directive. */
1671 /* The minimum output as determined by flags. It's always at least 1.
1672 When plus or space are set the output is preceded by either a sign
1674 unsigned flagmin
= (1 /* for the first digit */
1675 + (dir
.get_flag ('+') | dir
.get_flag (' ')));
1677 /* The minimum is 3 for "inf" and "nan" for all specifiers, plus 1
1678 for the plus sign/space with the '+' and ' ' flags, respectively,
1679 unless reduced below. */
1680 res
.range
.min
= 2 + flagmin
;
1682 /* When the pound flag is set the decimal point is included in output
1683 regardless of precision. Whether or not a decimal point is included
1684 otherwise depends on the specification and precision. */
1685 bool radix
= dir
.get_flag ('#');
1687 switch (dir
.specifier
)
1692 HOST_WIDE_INT minprec
= 6 + !radix
/* decimal point */;
1693 if (dir
.prec
[0] <= 0)
1695 else if (dir
.prec
[0] > 0)
1696 minprec
= dir
.prec
[0] + !radix
/* decimal point */;
1698 res
.range
.likely
= (2 /* 0x */
1704 res
.range
.max
= format_floating_max (type
, 'a', prec
[1]);
1706 /* The unlikely maximum accounts for the longest multibyte
1707 decimal point character. */
1708 res
.range
.unlikely
= res
.range
.max
;
1709 if (dir
.prec
[1] > 0)
1710 res
.range
.unlikely
+= target_mb_len_max () - 1;
1718 /* Minimum output attributable to precision and, when it's
1719 non-zero, decimal point. */
1720 HOST_WIDE_INT minprec
= prec
[0] ? prec
[0] + !radix
: 0;
1722 /* The likely minimum output is "[-+]1.234567e+00" regardless
1723 of the value of the actual argument. */
1724 res
.range
.likely
= (flagmin
1729 res
.range
.max
= format_floating_max (type
, 'e', prec
[1]);
1731 /* The unlikely maximum accounts for the longest multibyte
1732 decimal point character. */
1733 if (dir
.prec
[0] != dir
.prec
[1]
1734 || dir
.prec
[0] == -1 || dir
.prec
[0] > 0)
1735 res
.range
.unlikely
= res
.range
.max
+ target_mb_len_max () -1;
1737 res
.range
.unlikely
= res
.range
.max
;
1744 /* Minimum output attributable to precision and, when it's non-zero,
1746 HOST_WIDE_INT minprec
= prec
[0] ? prec
[0] + !radix
: 0;
1748 /* For finite numbers (i.e., not infinity or NaN) the lower bound
1749 when precision isn't specified is 8 bytes ("1.23456" since
1750 precision is taken to be 6). When precision is zero, the lower
1751 bound is 1 byte (e.g., "1"). Otherwise, when precision is greater
1752 than zero, then the lower bound is 2 plus precision (plus flags).
1753 But in all cases, the lower bound is no greater than 3. */
1754 unsigned HOST_WIDE_INT min
= flagmin
+ radix
+ minprec
;
1755 if (min
< res
.range
.min
)
1756 res
.range
.min
= min
;
1758 /* Compute the upper bound for -TYPE_MAX. */
1759 res
.range
.max
= format_floating_max (type
, 'f', prec
[1]);
1761 /* The minimum output with unknown precision is a single byte
1762 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1763 if (dir
.prec
[0] < 0 && dir
.prec
[1] > 0)
1764 res
.range
.likely
= 3;
1766 res
.range
.likely
= min
;
1768 /* The unlikely maximum accounts for the longest multibyte
1769 decimal point character. */
1770 if (dir
.prec
[0] != dir
.prec
[1]
1771 || dir
.prec
[0] == -1 || dir
.prec
[0] > 0)
1772 res
.range
.unlikely
= res
.range
.max
+ target_mb_len_max () - 1;
1779 /* The %g output depends on precision and the exponent of
1780 the argument. Since the value of the argument isn't known
1781 the lower bound on the range of bytes (not counting flags
1782 or width) is 1 plus radix (i.e., either "0" or "0." for
1783 "%g" and "%#g", respectively, with a zero argument). */
1784 unsigned HOST_WIDE_INT min
= flagmin
+ radix
;
1785 if (min
< res
.range
.min
)
1786 res
.range
.min
= min
;
1789 HOST_WIDE_INT maxprec
= dir
.prec
[1];
1790 if (radix
&& maxprec
)
1792 /* When the pound flag (radix) is set, trailing zeros aren't
1793 trimmed and so the longest output is the same as for %e,
1794 except with precision minus 1 (as specified in C11). */
1798 else if (maxprec
< 0)
1804 res
.range
.max
= format_floating_max (type
, spec
, maxprec
);
1806 /* The likely output is either the maximum computed above
1807 minus 1 (assuming the maximum is positive) when precision
1808 is known (or unspecified), or the same minimum as for %e
1809 (which is computed for a non-negative argument). Unlike
1810 for the other specifiers above the likely output isn't
1811 the minimum because for %g that's 1 which is unlikely. */
1813 || (unsigned HOST_WIDE_INT
)dir
.prec
[1] < target_int_max ())
1814 res
.range
.likely
= res
.range
.max
- 1;
1817 HOST_WIDE_INT minprec
= 6 + !radix
/* decimal point */;
1818 res
.range
.likely
= (flagmin
1824 /* The unlikely maximum accounts for the longest multibyte
1825 decimal point character. */
1826 res
.range
.unlikely
= res
.range
.max
+ target_mb_len_max () - 1;
1831 return fmtresult ();
1834 /* Bump up the byte counters if WIDTH is greater. */
1835 res
.adjust_for_width_or_precision (dir
.width
);
1839 /* Return a range representing the minimum and maximum number of bytes
1840 that the directive DIR will write on output for the floating argument
1844 format_floating (const directive
&dir
, tree arg
, pointer_query
&)
1846 HOST_WIDE_INT prec
[] = { dir
.prec
[0], dir
.prec
[1] };
1847 tree type
= (dir
.modifier
== FMT_LEN_L
|| dir
.modifier
== FMT_LEN_ll
1848 ? long_double_type_node
: double_type_node
);
1850 /* For an indeterminate precision the lower bound must be assumed
1852 if (TOUPPER (dir
.specifier
) == 'A')
1854 /* Get the number of fractional decimal digits needed to represent
1855 the argument without a loss of accuracy. */
1857 = REAL_MODE_FORMAT (TYPE_MODE (type
))->p
;
1859 /* The precision of the IEEE 754 double format is 53.
1860 The precision of all other GCC binary double formats
1862 unsigned maxprec
= fmtprec
<= 56 ? 13 : 15;
1864 /* For %a, leave the minimum precision unspecified to let
1865 MFPR trim trailing zeros (as it and many other systems
1866 including Glibc happen to do) and set the maximum
1867 precision to reflect what it would be with trailing zeros
1868 present (as Solaris and derived systems do). */
1869 if (dir
.prec
[1] < 0)
1871 /* Both bounds are negative implies that precision has
1872 not been specified. */
1876 else if (dir
.prec
[0] < 0)
1878 /* With a negative lower bound and a non-negative upper
1879 bound set the minimum precision to zero and the maximum
1880 to the greater of the maximum precision (i.e., with
1881 trailing zeros present) and the specified upper bound. */
1883 prec
[1] = dir
.prec
[1] < maxprec
? maxprec
: dir
.prec
[1];
1886 else if (dir
.prec
[0] < 0)
1888 if (dir
.prec
[1] < 0)
1890 /* A precision in a strictly negative range is ignored and
1891 the default of 6 is used instead. */
1892 prec
[0] = prec
[1] = 6;
1896 /* For a precision in a partly negative range, the lower bound
1897 must be assumed to be zero and the new upper bound is the
1898 greater of 6 (the default precision used when the specified
1899 precision is negative) and the upper bound of the specified
1902 prec
[1] = dir
.prec
[1] < 6 ? 6 : dir
.prec
[1];
1907 || TREE_CODE (arg
) != REAL_CST
1908 || !useless_type_conversion_p (type
, TREE_TYPE (arg
)))
1909 return format_floating (dir
, prec
);
1911 /* The minimum and maximum number of bytes produced by the directive. */
1914 /* Get the real type format description for the target. */
1915 const REAL_VALUE_TYPE
*rvp
= TREE_REAL_CST_PTR (arg
);
1916 const real_format
*rfmt
= REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg
)));
1918 if (!real_isfinite (rvp
))
1920 /* The format for Infinity and NaN is "[-]inf"/"[-]infinity"
1921 and "[-]nan" with the choice being implementation-defined
1922 but not locale dependent. */
1923 bool sign
= dir
.get_flag ('+') || real_isneg (rvp
);
1924 res
.range
.min
= 3 + sign
;
1926 res
.range
.likely
= res
.range
.min
;
1927 res
.range
.max
= res
.range
.min
;
1928 /* The unlikely maximum is "[-/+]infinity" or "[-/+][qs]nan".
1929 For NaN, the C/POSIX standards specify two formats:
1932 "[-/+]nan(n-char-sequence)"
1933 No known printf implementation outputs the latter format but AIX
1934 outputs QNaN and SNaN for quiet and signalling NaN, respectively,
1935 so the unlikely maximum reflects that. */
1936 res
.range
.unlikely
= sign
+ (real_isinf (rvp
) ? 8 : 4);
1938 /* The range for infinity and NaN is known unless either width
1939 or precision is unknown. Width has the same effect regardless
1940 of whether the argument is finite. Precision is either ignored
1941 (e.g., Glibc) or can have an effect on the short vs long format
1942 such as inf/infinity (e.g., Solaris). */
1943 res
.knownrange
= dir
.known_width_and_precision ();
1945 /* Adjust the range for width but ignore precision. */
1946 res
.adjust_for_width_or_precision (dir
.width
);
1952 char *pfmt
= fmtstr
;
1955 for (const char *pf
= "-+ #0"; *pf
; ++pf
)
1956 if (dir
.get_flag (*pf
))
1962 /* Set up an array to easily iterate over. */
1963 unsigned HOST_WIDE_INT
* const minmax
[] = {
1964 &res
.range
.min
, &res
.range
.max
1967 for (int i
= 0; i
!= ARRAY_SIZE (minmax
); ++i
)
1969 /* Convert the GCC real value representation with the precision
1970 of the real type to the mpfr_t format rounding down in the
1971 first iteration that computes the minimum and up in the second
1972 that computes the maximum. This order is arbitrary because
1973 rounding in either direction can result in longer output. */
1975 mpfr_init2 (mpfrval
, rfmt
->p
);
1976 mpfr_from_real (mpfrval
, rvp
, i
? MPFR_RNDU
: MPFR_RNDD
);
1978 /* Use the MPFR rounding specifier to round down in the first
1979 iteration and then up. In most but not all cases this will
1980 result in the same number of bytes. */
1981 char rndspec
= "DU"[i
];
1983 /* Format it and store the result in the corresponding member
1984 of the result struct. */
1985 *minmax
[i
] = get_mpfr_format_length (mpfrval
, fmtstr
, prec
[i
],
1986 dir
.specifier
, rndspec
);
1987 mpfr_clear (mpfrval
);
1991 /* Make sure the minimum is less than the maximum (MPFR rounding
1992 in the call to mpfr_snprintf can result in the reverse. */
1993 if (res
.range
.max
< res
.range
.min
)
1995 unsigned HOST_WIDE_INT tmp
= res
.range
.min
;
1996 res
.range
.min
= res
.range
.max
;
1997 res
.range
.max
= tmp
;
2000 /* The range is known unless either width or precision is unknown. */
2001 res
.knownrange
= dir
.known_width_and_precision ();
2003 /* For the same floating point constant, unless width or precision
2004 is unknown, use the longer output as the likely maximum since
2005 with round to nearest either is equally likely. Otherwise, when
2006 precision is unknown, use the greater of the minimum and 3 as
2007 the likely output (for "0.0" since zero precision is unlikely). */
2009 res
.range
.likely
= res
.range
.max
;
2010 else if (res
.range
.min
< 3
2012 && (unsigned HOST_WIDE_INT
)dir
.prec
[1] == target_int_max ())
2013 res
.range
.likely
= 3;
2015 res
.range
.likely
= res
.range
.min
;
2017 res
.range
.unlikely
= res
.range
.max
;
2019 if (res
.range
.max
> 2 && (prec
[0] != 0 || prec
[1] != 0))
2021 /* Unless the precision is zero output longer than 2 bytes may
2022 include the decimal point which must be a single character
2023 up to MB_LEN_MAX in length. This is overly conservative
2024 since in some conversions some constants result in no decimal
2025 point (e.g., in %g). */
2026 res
.range
.unlikely
+= target_mb_len_max () - 1;
2029 res
.adjust_for_width_or_precision (dir
.width
);
2033 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
2034 strings referenced by the expression STR, or (-1, -1) when not known.
2035 Used by the format_string function below. */
2038 get_string_length (tree str
, gimple
*stmt
, unsigned HOST_WIDE_INT max_size
,
2039 unsigned eltsize
, pointer_query
&ptr_qry
)
2042 return fmtresult ();
2044 /* Try to determine the dynamic string length first.
2045 Set MAXBOUND to an arbitrary non-null non-integer node as a request
2046 to have it set to the length of the longest string in a PHI. */
2047 c_strlen_data lendata
= { };
2048 lendata
.maxbound
= str
;
2050 get_range_strlen_dynamic (str
, stmt
, &lendata
, ptr_qry
);
2053 /* Determine the length of the shortest and longest string referenced
2054 by STR. Strings of unknown lengths are bounded by the sizes of
2055 arrays that subexpressions of STR may refer to. Pointers that
2056 aren't known to point any such arrays result in LENDATA.MAXLEN
2058 get_range_strlen (str
, &lendata
, eltsize
);
2061 /* If LENDATA.MAXBOUND is not equal to .MINLEN it corresponds to the bound
2062 of the largest array STR refers to, if known, or it's set to SIZE_MAX
2065 /* Return the default result when nothing is known about the string. */
2066 if ((lendata
.maxbound
&& !tree_fits_uhwi_p (lendata
.maxbound
))
2067 || !tree_fits_uhwi_p (lendata
.maxlen
))
2070 res
.nonstr
= lendata
.decl
;
2074 unsigned HOST_WIDE_INT lenmax
= tree_to_uhwi (max_object_size ()) - 2;
2075 if (integer_zerop (lendata
.minlen
)
2076 && (!lendata
.maxbound
|| lenmax
<= tree_to_uhwi (lendata
.maxbound
))
2077 && lenmax
<= tree_to_uhwi (lendata
.maxlen
))
2079 if (max_size
> 0 && max_size
< HOST_WIDE_INT_MAX
)
2081 /* Adjust the conservative unknown/unbounded result if MAX_SIZE
2082 is valid. Set UNLIKELY to maximum in case MAX_SIZE refers
2084 TODO: This is overly conservative. Set UNLIKELY to the size
2085 of the outermost enclosing declared object. */
2086 fmtresult
res (0, max_size
- 1);
2087 res
.nonstr
= lendata
.decl
;
2088 res
.range
.likely
= res
.range
.max
;
2089 res
.range
.unlikely
= HOST_WIDE_INT_MAX
;
2094 res
.nonstr
= lendata
.decl
;
2098 /* The minimum length of the string. */
2100 = (tree_fits_uhwi_p (lendata
.minlen
)
2101 ? tree_to_uhwi (lendata
.minlen
)
2104 /* The maximum length of the string; initially set to MAXBOUND which
2105 may be less than MAXLEN, but may be adjusted up below. */
2107 = (lendata
.maxbound
&& tree_fits_uhwi_p (lendata
.maxbound
)
2108 ? tree_to_uhwi (lendata
.maxbound
)
2109 : HOST_WIDE_INT_M1U
);
2111 /* True if either the maximum length is unknown or (conservatively)
2112 the array bound is less than the maximum length. That can happen
2113 when the length of the string is unknown but the array in which
2114 the string is stored is a member of a struct. The warning uses
2115 the size of the member as the upper bound but the optimization
2116 doesn't. The optimization could still use the size of
2117 enclosing object as the upper bound but that's not done here. */
2118 const bool unbounded
2119 = (integer_all_onesp (lendata
.maxlen
)
2120 || (lendata
.maxbound
2121 && tree_int_cst_lt (lendata
.maxbound
, lendata
.maxlen
)));
2123 /* Set the max/likely counters to unbounded when a minimum is known
2124 but the maximum length isn't bounded. This implies that STR is
2125 a conditional expression involving a string of known length and
2126 an expression of unknown/unbounded length. */
2128 && (unsigned HOST_WIDE_INT
)min
< HOST_WIDE_INT_M1U
2130 max
= HOST_WIDE_INT_M1U
;
2132 /* get_range_strlen() returns the target value of SIZE_MAX for
2133 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2134 which may be bigger. */
2135 if ((unsigned HOST_WIDE_INT
)min
== target_size_max ())
2136 min
= HOST_WIDE_INT_M1U
;
2137 if ((unsigned HOST_WIDE_INT
)max
== target_size_max ())
2138 max
= HOST_WIDE_INT_M1U
;
2140 fmtresult
res (min
, max
);
2141 res
.nonstr
= lendata
.decl
;
2143 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2144 by STR are known to be bounded (though not necessarily by their
2145 actual length but perhaps by their maximum possible length). */
2146 if (res
.range
.max
< target_int_max ())
2148 res
.knownrange
= true;
2149 /* When the length of the longest string is known and not
2150 excessive use it as the likely length of the string(s). */
2151 res
.range
.likely
= res
.range
.max
;
2155 /* When the upper bound is unknown (it can be zero or excessive)
2156 set the likely length to the greater of 1. If MAXBOUND is
2157 known, also reset the length of the lower bound to zero. */
2158 res
.range
.likely
= res
.range
.min
? res
.range
.min
: warn_level
> 1;
2159 if (lendata
.maxbound
&& !integer_all_onesp (lendata
.maxbound
))
2163 res
.range
.unlikely
= unbounded
? HOST_WIDE_INT_MAX
: res
.range
.max
;
2168 /* Return the minimum and maximum number of characters formatted
2169 by the '%c' format directives and its wide character form for
2170 the argument ARG. ARG can be null (for functions such as
2174 format_character (const directive
&dir
, tree arg
, pointer_query
&ptr_qry
)
2178 res
.knownrange
= true;
2180 if (dir
.specifier
== 'C'
2181 || dir
.modifier
== FMT_LEN_l
)
2183 /* A wide character can result in as few as zero bytes. */
2186 HOST_WIDE_INT min
, max
;
2187 if (get_int_range (arg
, dir
.info
->callstmt
, &min
, &max
, false, 0,
2190 if (min
== 0 && max
== 0)
2192 /* The NUL wide character results in no bytes. */
2194 res
.range
.likely
= 0;
2195 res
.range
.unlikely
= 0;
2197 else if (min
>= 0 && min
< 128)
2199 /* Be conservative if the target execution character set
2200 is not a 1-to-1 mapping to the source character set or
2201 if the source set is not ASCII. */
2202 bool one_2_one_ascii
2203 = (target_to_host_charmap
[0] == 1 && target_to_host ('a') == 97);
2205 /* A wide character in the ASCII range most likely results
2206 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2207 res
.range
.max
= one_2_one_ascii
? 1 : target_mb_len_max ();;
2208 res
.range
.likely
= 1;
2209 res
.range
.unlikely
= target_mb_len_max ();
2210 res
.mayfail
= !one_2_one_ascii
;
2214 /* A wide character outside the ASCII range likely results
2215 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2216 res
.range
.max
= target_mb_len_max ();
2217 res
.range
.likely
= 2;
2218 res
.range
.unlikely
= res
.range
.max
;
2219 /* Converting such a character may fail. */
2225 /* An unknown wide character is treated the same as a wide
2226 character outside the ASCII range. */
2227 res
.range
.max
= target_mb_len_max ();
2228 res
.range
.likely
= 2;
2229 res
.range
.unlikely
= res
.range
.max
;
2235 /* A plain '%c' directive. Its output is exactly 1. */
2236 res
.range
.min
= res
.range
.max
= 1;
2237 res
.range
.likely
= res
.range
.unlikely
= 1;
2238 res
.knownrange
= true;
2241 /* Bump up the byte counters if WIDTH is greater. */
2242 return res
.adjust_for_width_or_precision (dir
.width
);
2245 /* If TYPE is an array or struct or union, increment *FLDOFF by the starting
2246 offset of the member that *OFF points into if one can be determined and
2247 set *FLDSIZE to its size in bytes and decrement *OFF by the same.
2248 Otherwise do nothing. */
2251 set_aggregate_size_and_offset (tree type
, HOST_WIDE_INT
*fldoff
,
2252 HOST_WIDE_INT
*fldsize
, HOST_WIDE_INT
*off
)
2254 /* The byte offset of the most basic struct member the byte
2255 offset *OFF corresponds to, or for a (multidimensional)
2256 array member, the byte offset of the array element. */
2257 if (TREE_CODE (type
) == ARRAY_TYPE
2258 && TREE_CODE (TREE_TYPE (type
)) == ARRAY_TYPE
)
2260 HOST_WIDE_INT index
= 0, arrsize
= 0;
2261 if (array_elt_at_offset (type
, *off
, &index
, &arrsize
))
2266 /* Otherwise leave *FLDOFF et al. unchanged. */
2268 else if (RECORD_OR_UNION_TYPE_P (type
))
2270 HOST_WIDE_INT index
= 0;
2271 tree sub
= field_at_offset (type
, NULL_TREE
, *off
, &index
);
2274 tree subsize
= DECL_SIZE_UNIT (sub
);
2275 if (*fldsize
< HOST_WIDE_INT_MAX
2277 && tree_fits_uhwi_p (subsize
))
2278 *fldsize
= tree_to_uhwi (subsize
);
2280 *fldsize
= HOST_WIDE_INT_MAX
;
2284 /* Otherwise leave *FLDOFF et al. unchanged. */
2288 /* For an expression X of pointer type, recursively try to find its origin
2289 (either object DECL or pointer such as PARM_DECL) Y and return such a Y.
2290 When X refers to an array element or struct member, set *FLDOFF to
2291 the offset of the element or member from the beginning of the "most
2292 derived" object and *FLDSIZE to its size. When nonnull, set *OFF to
2293 the overall offset from the beginning of the object so that
2297 get_origin_and_offset_r (tree x
, HOST_WIDE_INT
*fldoff
, HOST_WIDE_INT
*fldsize
,
2300 HOST_WIDE_INT sizebuf
= -1;
2306 /* Set the size if it hasn't been set yet. */
2307 if (tree size
= DECL_SIZE_UNIT (x
))
2308 if (*fldsize
< 0 && tree_fits_shwi_p (size
))
2309 *fldsize
= tree_to_shwi (size
);
2313 switch (TREE_CODE (x
))
2316 x
= TREE_OPERAND (x
, 0);
2317 return get_origin_and_offset_r (x
, fldoff
, fldsize
, off
);
2321 tree sub
= TREE_OPERAND (x
, 1);
2322 unsigned HOST_WIDE_INT idx
=
2323 tree_fits_uhwi_p (sub
) ? tree_to_uhwi (sub
) : HOST_WIDE_INT_MAX
;
2325 tree elsz
= array_ref_element_size (x
);
2326 unsigned HOST_WIDE_INT elbytes
=
2327 tree_fits_shwi_p (elsz
) ? tree_to_shwi (elsz
) : HOST_WIDE_INT_MAX
;
2329 unsigned HOST_WIDE_INT byteoff
= idx
* elbytes
;
2331 if (byteoff
< HOST_WIDE_INT_MAX
2332 && elbytes
< HOST_WIDE_INT_MAX
2333 && (elbytes
== 0 || byteoff
/ elbytes
== idx
))
2335 /* For in-bounds constant offsets into constant-sized arrays
2336 bump up *OFF, and for what's likely arrays or structs of
2337 arrays, also *FLDOFF, as necessary. */
2344 *fldoff
= HOST_WIDE_INT_MAX
;
2346 x
= TREE_OPERAND (x
, 0);
2347 return get_origin_and_offset_r (x
, fldoff
, fldsize
, off
);
2353 tree offset
= TREE_OPERAND (x
, 1);
2354 *off
= (tree_fits_uhwi_p (offset
)
2355 ? tree_to_uhwi (offset
) : HOST_WIDE_INT_MAX
);
2358 x
= TREE_OPERAND (x
, 0);
2363 = (TREE_CODE (x
) == ADDR_EXPR
2364 ? TREE_TYPE (TREE_OPERAND (x
, 0)) : TREE_TYPE (TREE_TYPE (x
)));
2366 set_aggregate_size_and_offset (xtype
, fldoff
, fldsize
, off
);
2369 return get_origin_and_offset_r (x
, fldoff
, fldsize
, nullptr);
2373 tree foff
= component_ref_field_offset (x
);
2374 tree fld
= TREE_OPERAND (x
, 1);
2375 if (!tree_fits_shwi_p (foff
)
2376 || !tree_fits_shwi_p (DECL_FIELD_BIT_OFFSET (fld
)))
2378 *fldoff
+= (tree_to_shwi (foff
)
2379 + (tree_to_shwi (DECL_FIELD_BIT_OFFSET (fld
))
2382 get_origin_and_offset_r (fld
, fldoff
, fldsize
, off
);
2383 x
= TREE_OPERAND (x
, 0);
2384 return get_origin_and_offset_r (x
, fldoff
, nullptr, off
);
2389 gimple
*def
= SSA_NAME_DEF_STMT (x
);
2390 if (is_gimple_assign (def
))
2392 tree_code code
= gimple_assign_rhs_code (def
);
2393 if (code
== ADDR_EXPR
)
2395 x
= gimple_assign_rhs1 (def
);
2396 return get_origin_and_offset_r (x
, fldoff
, fldsize
, off
);
2399 if (code
== POINTER_PLUS_EXPR
)
2401 tree offset
= gimple_assign_rhs2 (def
);
2402 if (off
&& tree_fits_uhwi_p (offset
))
2403 *off
= tree_to_uhwi (offset
);
2405 x
= gimple_assign_rhs1 (def
);
2406 x
= get_origin_and_offset_r (x
, fldoff
, fldsize
, off
);
2407 if (off
&& !tree_fits_uhwi_p (offset
))
2408 *off
= HOST_WIDE_INT_MAX
;
2411 tree xtype
= TREE_TYPE (x
);
2412 set_aggregate_size_and_offset (xtype
, fldoff
, fldsize
, off
);
2416 else if (code
== VAR_DECL
)
2418 x
= gimple_assign_rhs1 (def
);
2419 return get_origin_and_offset_r (x
, fldoff
, fldsize
, off
);
2422 else if (gimple_nop_p (def
) && SSA_NAME_VAR (x
))
2423 x
= SSA_NAME_VAR (x
);
2425 tree xtype
= TREE_TYPE (x
);
2426 if (POINTER_TYPE_P (xtype
))
2427 xtype
= TREE_TYPE (xtype
);
2430 set_aggregate_size_and_offset (xtype
, fldoff
, fldsize
, off
);
2440 /* Nonrecursive version of the above.
2441 The function never returns null unless X is null to begin with. */
2444 get_origin_and_offset (tree x
, HOST_WIDE_INT
*fldoff
, HOST_WIDE_INT
*off
,
2445 HOST_WIDE_INT
*fldsize
= nullptr)
2450 HOST_WIDE_INT sizebuf
;
2454 /* Invalidate *FLDSIZE. */
2458 return get_origin_and_offset_r (x
, fldoff
, fldsize
, off
);
2461 /* If ARG refers to the same (sub)object or array element as described
2462 by DST and DST_FLD, return the byte offset into the struct member or
2463 array element referenced by ARG and set *ARG_SIZE to the size of
2464 the (sub)object. Otherwise return HOST_WIDE_INT_MIN to indicate
2465 that ARG and DST do not refer to the same object. */
2467 static HOST_WIDE_INT
2468 alias_offset (tree arg
, HOST_WIDE_INT
*arg_size
,
2469 tree dst
, HOST_WIDE_INT dst_fld
)
2471 /* See if the argument refers to the same base object as the destination
2472 of the formatted function call, and if so, try to determine if they
2474 if (!arg
|| !dst
|| !ptr_derefs_may_alias_p (arg
, dst
))
2475 return HOST_WIDE_INT_MIN
;
2477 /* The two arguments may refer to the same object. If they both refer
2478 to a struct member, see if the members are one and the same. If so,
2479 return the offset into the member. */
2480 HOST_WIDE_INT arg_off
= 0, arg_fld
= 0;
2482 tree arg_orig
= get_origin_and_offset (arg
, &arg_fld
, &arg_off
, arg_size
);
2484 if (arg_orig
== dst
&& arg_fld
== dst_fld
)
2487 return HOST_WIDE_INT_MIN
;
2490 /* Return the minimum and maximum number of characters formatted
2491 by the '%s' format directive and its wide character form for
2492 the argument ARG. ARG can be null (for functions such as
2496 format_string (const directive
&dir
, tree arg
, pointer_query
&ptr_qry
)
2500 /* The size of the (sub)object ARG refers to. Used to adjust
2501 the conservative get_string_length() result. */
2502 HOST_WIDE_INT arg_size
= 0;
2506 /* See if ARG might alias the destination of the call with
2507 DST_ORIGIN and DST_FIELD. If so, store the starting offset
2508 so that the overlap can be determined for certain later,
2509 when the amount of output of the call (including subsequent
2510 directives) has been computed. Otherwise, store HWI_MIN. */
2511 res
.dst_offset
= alias_offset (arg
, &arg_size
, dir
.info
->dst_origin
,
2512 dir
.info
->dst_field
);
2513 if (res
.dst_offset
>= 0 && res
.dst_offset
<= arg_size
)
2514 arg_size
-= res
.dst_offset
;
2519 /* Compute the range the argument's length can be in. */
2521 if (dir
.specifier
== 'S' || dir
.modifier
== FMT_LEN_l
)
2523 /* Get a node for a C type that will be the same size
2524 as a wchar_t on the target. */
2525 tree node
= get_typenode_from_name (MODIFIED_WCHAR_TYPE
);
2527 /* Now that we have a suitable node, get the number of
2528 bytes it occupies. */
2529 count_by
= int_size_in_bytes (node
);
2530 gcc_checking_assert (count_by
== 2 || count_by
== 4);
2534 get_string_length (arg
, dir
.info
->callstmt
, arg_size
, count_by
, ptr_qry
);
2535 if (slen
.range
.min
== slen
.range
.max
2536 && slen
.range
.min
< HOST_WIDE_INT_MAX
)
2538 /* The argument is either a string constant or it refers
2539 to one of a number of strings of the same length. */
2541 /* A '%s' directive with a string argument with constant length. */
2542 res
.range
= slen
.range
;
2544 if (dir
.specifier
== 'S'
2545 || dir
.modifier
== FMT_LEN_l
)
2547 /* In the worst case the length of output of a wide string S
2548 is bounded by MB_LEN_MAX * wcslen (S). */
2549 res
.range
.max
*= target_mb_len_max ();
2550 res
.range
.unlikely
= res
.range
.max
;
2551 /* It's likely that the total length is not more that
2553 res
.range
.likely
= res
.range
.min
* 2;
2555 if (dir
.prec
[1] >= 0
2556 && (unsigned HOST_WIDE_INT
)dir
.prec
[1] < res
.range
.max
)
2558 res
.range
.max
= dir
.prec
[1];
2559 res
.range
.likely
= dir
.prec
[1];
2560 res
.range
.unlikely
= dir
.prec
[1];
2563 if (dir
.prec
[0] < 0 && dir
.prec
[1] > -1)
2565 else if (dir
.prec
[0] >= 0)
2566 res
.range
.likely
= dir
.prec
[0];
2568 /* Even a non-empty wide character string need not convert into
2572 /* A non-empty wide character conversion may fail. */
2573 if (slen
.range
.max
> 0)
2578 res
.knownrange
= true;
2580 if (dir
.prec
[0] < 0 && dir
.prec
[1] > -1)
2582 else if ((unsigned HOST_WIDE_INT
)dir
.prec
[0] < res
.range
.min
)
2583 res
.range
.min
= dir
.prec
[0];
2585 if ((unsigned HOST_WIDE_INT
)dir
.prec
[1] < res
.range
.max
)
2587 res
.range
.max
= dir
.prec
[1];
2588 res
.range
.likely
= dir
.prec
[1];
2589 res
.range
.unlikely
= dir
.prec
[1];
2593 else if (arg
&& integer_zerop (arg
))
2595 /* Handle null pointer argument. */
2603 /* For a '%s' and '%ls' directive with a non-constant string (either
2604 one of a number of strings of known length or an unknown string)
2605 the minimum number of characters is lesser of PRECISION[0] and
2606 the length of the shortest known string or zero, and the maximum
2607 is the lesser of the length of the longest known string or
2608 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2609 the minimum at level 1 and the greater of the minimum and 1
2610 at level 2. This result is adjust upward for width (if it's
2613 if (dir
.specifier
== 'S'
2614 || dir
.modifier
== FMT_LEN_l
)
2616 /* A wide character converts to as few as zero bytes. */
2618 if (slen
.range
.max
< target_int_max ())
2619 slen
.range
.max
*= target_mb_len_max ();
2621 if (slen
.range
.likely
< target_int_max ())
2622 slen
.range
.likely
*= 2;
2624 if (slen
.range
.likely
< target_int_max ())
2625 slen
.range
.unlikely
*= target_mb_len_max ();
2627 /* A non-empty wide character conversion may fail. */
2628 if (slen
.range
.max
> 0)
2632 res
.range
= slen
.range
;
2634 if (dir
.prec
[0] >= 0)
2636 /* Adjust the minimum to zero if the string length is unknown,
2637 or at most the lower bound of the precision otherwise. */
2638 if (slen
.range
.min
>= target_int_max ())
2640 else if ((unsigned HOST_WIDE_INT
)dir
.prec
[0] < slen
.range
.min
)
2641 res
.range
.min
= dir
.prec
[0];
2643 /* Make both maxima no greater than the upper bound of precision. */
2644 if ((unsigned HOST_WIDE_INT
)dir
.prec
[1] < slen
.range
.max
2645 || slen
.range
.max
>= target_int_max ())
2647 res
.range
.max
= dir
.prec
[1];
2648 res
.range
.unlikely
= dir
.prec
[1];
2651 /* If precision is constant, set the likely counter to the lesser
2652 of it and the maximum string length. Otherwise, if the lower
2653 bound of precision is greater than zero, set the likely counter
2654 to the minimum. Otherwise set it to zero or one based on
2655 the warning level. */
2656 if (dir
.prec
[0] == dir
.prec
[1])
2658 = ((unsigned HOST_WIDE_INT
)dir
.prec
[0] < slen
.range
.max
2659 ? dir
.prec
[0] : slen
.range
.max
);
2660 else if (dir
.prec
[0] > 0)
2661 res
.range
.likely
= res
.range
.min
;
2663 res
.range
.likely
= warn_level
> 1;
2665 else if (dir
.prec
[1] >= 0)
2668 if ((unsigned HOST_WIDE_INT
)dir
.prec
[1] < slen
.range
.max
)
2669 res
.range
.max
= dir
.prec
[1];
2670 res
.range
.likely
= dir
.prec
[1] ? warn_level
> 1 : 0;
2671 if ((unsigned HOST_WIDE_INT
)dir
.prec
[1] < slen
.range
.unlikely
)
2672 res
.range
.unlikely
= dir
.prec
[1];
2674 else if (slen
.range
.min
>= target_int_max ())
2677 res
.range
.max
= HOST_WIDE_INT_MAX
;
2678 /* At level 1 strings of unknown length are assumed to be
2679 empty, while at level 1 they are assumed to be one byte
2681 res
.range
.likely
= warn_level
> 1;
2682 res
.range
.unlikely
= HOST_WIDE_INT_MAX
;
2686 /* A string of unknown length unconstrained by precision is
2687 assumed to be empty at level 1 and just one character long
2688 at higher levels. */
2689 if (res
.range
.likely
>= target_int_max ())
2690 res
.range
.likely
= warn_level
> 1;
2694 /* If the argument isn't a nul-terminated string and the number
2695 of bytes on output isn't bounded by precision, set NONSTR. */
2696 if (slen
.nonstr
&& slen
.range
.min
< (unsigned HOST_WIDE_INT
)dir
.prec
[0])
2697 res
.nonstr
= slen
.nonstr
;
2699 /* Bump up the byte counters if WIDTH is greater. */
2700 return res
.adjust_for_width_or_precision (dir
.width
);
2703 /* Format plain string (part of the format string itself). */
2706 format_plain (const directive
&dir
, tree
, pointer_query
&)
2708 fmtresult
res (dir
.len
);
2712 /* Return true if the RESULT of a directive in a call describe by INFO
2713 should be diagnosed given the AVAILable space in the destination. */
2716 should_warn_p (const call_info
&info
,
2717 const result_range
&avail
, const result_range
&result
)
2719 if (result
.max
<= avail
.min
)
2721 /* The least amount of space remaining in the destination is big
2722 enough for the longest output. */
2728 if (warn_format_trunc
== 1 && result
.min
<= avail
.max
2729 && info
.retval_used ())
2731 /* The likely amount of space remaining in the destination is big
2732 enough for the least output and the return value is used. */
2736 if (warn_format_trunc
== 1 && result
.likely
<= avail
.likely
2737 && !info
.retval_used ())
2739 /* The likely amount of space remaining in the destination is big
2740 enough for the likely output and the return value is unused. */
2744 if (warn_format_trunc
== 2
2745 && result
.likely
<= avail
.min
2746 && (result
.max
<= avail
.min
2747 || result
.max
> HOST_WIDE_INT_MAX
))
2749 /* The minimum amount of space remaining in the destination is big
2750 enough for the longest output. */
2756 if (warn_level
== 1 && result
.likely
<= avail
.likely
)
2758 /* The likely amount of space remaining in the destination is big
2759 enough for the likely output. */
2764 && result
.likely
<= avail
.min
2765 && (result
.max
<= avail
.min
2766 || result
.max
> HOST_WIDE_INT_MAX
))
2768 /* The minimum amount of space remaining in the destination is big
2769 enough for the longest output. */
2777 /* At format string location describe by DIRLOC in a call described
2778 by INFO, issue a warning for a directive DIR whose output may be
2779 in excess of the available space AVAIL_RANGE in the destination
2780 given the formatting result FMTRES. This function does nothing
2781 except decide whether to issue a warning for a possible write
2782 past the end or truncation and, if so, format the warning.
2783 Return true if a warning has been issued. */
2786 maybe_warn (substring_loc
&dirloc
, location_t argloc
,
2787 const call_info
&info
,
2788 const result_range
&avail_range
, const result_range
&res
,
2789 const directive
&dir
)
2791 if (!should_warn_p (info
, avail_range
, res
))
2794 /* A warning will definitely be issued below. */
2796 /* The maximum byte count to reference in the warning. Larger counts
2797 imply that the upper bound is unknown (and could be anywhere between
2798 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2799 than "between N and X" where X is some huge number. */
2800 unsigned HOST_WIDE_INT maxbytes
= target_dir_max ();
2802 /* True when there is enough room in the destination for the least
2803 amount of a directive's output but not enough for its likely or
2805 bool maybe
= (res
.min
<= avail_range
.max
2806 && (avail_range
.min
< res
.likely
2807 || (res
.max
< HOST_WIDE_INT_MAX
2808 && avail_range
.min
< res
.max
)));
2810 /* Buffer for the directive in the host character set (used when
2811 the source character set is different). */
2814 if (avail_range
.min
== avail_range
.max
)
2816 /* The size of the destination region is exact. */
2817 unsigned HOST_WIDE_INT navail
= avail_range
.max
;
2819 if (target_to_host (*dir
.beg
) != '%')
2821 /* For plain character directives (i.e., the format string itself)
2822 but not others, point the caret at the first character that's
2823 past the end of the destination. */
2824 if (navail
< dir
.len
)
2825 dirloc
.set_caret_index (dirloc
.get_caret_idx () + navail
);
2828 if (*dir
.beg
== '\0')
2830 /* This is the terminating nul. */
2831 gcc_assert (res
.min
== 1 && res
.min
== res
.max
);
2833 return fmtwarn (dirloc
, UNKNOWN_LOCATION
, NULL
, info
.warnopt (),
2836 ? G_("%qE output may be truncated before the "
2837 "last format character")
2838 : G_("%qE output truncated before the last "
2839 "format character"))
2841 ? G_("%qE may write a terminating nul past the "
2842 "end of the destination")
2843 : G_("%qE writing a terminating nul past the "
2844 "end of the destination")),
2848 if (res
.min
== res
.max
)
2850 const char *d
= target_to_host (hostdir
, sizeof hostdir
, dir
.beg
);
2852 return fmtwarn_n (dirloc
, argloc
, NULL
, info
.warnopt (), res
.min
,
2853 "%<%.*s%> directive writing %wu byte into a "
2854 "region of size %wu",
2855 "%<%.*s%> directive writing %wu bytes into a "
2856 "region of size %wu",
2857 (int) dir
.len
, d
, res
.min
, navail
);
2859 return fmtwarn_n (dirloc
, argloc
, NULL
, info
.warnopt (), res
.min
,
2860 "%<%.*s%> directive output may be truncated "
2861 "writing %wu byte into a region of size %wu",
2862 "%<%.*s%> directive output may be truncated "
2863 "writing %wu bytes into a region of size %wu",
2864 (int) dir
.len
, d
, res
.min
, navail
);
2866 return fmtwarn_n (dirloc
, argloc
, NULL
, info
.warnopt (), res
.min
,
2867 "%<%.*s%> directive output truncated writing "
2868 "%wu byte into a region of size %wu",
2869 "%<%.*s%> directive output truncated writing "
2870 "%wu bytes into a region of size %wu",
2871 (int) dir
.len
, d
, res
.min
, navail
);
2873 if (res
.min
== 0 && res
.max
< maxbytes
)
2874 return fmtwarn (dirloc
, argloc
, NULL
,
2878 ? G_("%<%.*s%> directive output may be truncated "
2879 "writing up to %wu bytes into a region of "
2881 : G_("%<%.*s%> directive output truncated writing "
2882 "up to %wu bytes into a region of size %wu"))
2883 : G_("%<%.*s%> directive writing up to %wu bytes "
2884 "into a region of size %wu"), (int) dir
.len
,
2885 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2888 if (res
.min
== 0 && maxbytes
<= res
.max
)
2889 /* This is a special case to avoid issuing the potentially
2891 writing 0 or more bytes into a region of size 0. */
2892 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2895 ? G_("%<%.*s%> directive output may be truncated "
2896 "writing likely %wu or more bytes into a "
2897 "region of size %wu")
2898 : G_("%<%.*s%> directive output truncated writing "
2899 "likely %wu or more bytes into a region of "
2901 : G_("%<%.*s%> directive writing likely %wu or more "
2902 "bytes into a region of size %wu"), (int) dir
.len
,
2903 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2904 res
.likely
, navail
);
2906 if (res
.max
< maxbytes
)
2907 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2910 ? G_("%<%.*s%> directive output may be truncated "
2911 "writing between %wu and %wu bytes into a "
2912 "region of size %wu")
2913 : G_("%<%.*s%> directive output truncated "
2914 "writing between %wu and %wu bytes into a "
2915 "region of size %wu"))
2916 : G_("%<%.*s%> directive writing between %wu and "
2917 "%wu bytes into a region of size %wu"),
2919 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2920 res
.min
, res
.max
, navail
);
2922 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2925 ? G_("%<%.*s%> directive output may be truncated "
2926 "writing %wu or more bytes into a region of "
2928 : G_("%<%.*s%> directive output truncated writing "
2929 "%wu or more bytes into a region of size %wu"))
2930 : G_("%<%.*s%> directive writing %wu or more bytes "
2931 "into a region of size %wu"), (int) dir
.len
,
2932 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
2936 /* The size of the destination region is a range. */
2938 if (target_to_host (*dir
.beg
) != '%')
2940 unsigned HOST_WIDE_INT navail
= avail_range
.max
;
2942 /* For plain character directives (i.e., the format string itself)
2943 but not others, point the caret at the first character that's
2944 past the end of the destination. */
2945 if (navail
< dir
.len
)
2946 dirloc
.set_caret_index (dirloc
.get_caret_idx () + navail
);
2949 if (*dir
.beg
== '\0')
2951 gcc_assert (res
.min
== 1 && res
.min
== res
.max
);
2953 return fmtwarn (dirloc
, UNKNOWN_LOCATION
, NULL
, info
.warnopt (),
2956 ? G_("%qE output may be truncated before the last "
2958 : G_("%qE output truncated before the last format "
2961 ? G_("%qE may write a terminating nul past the end "
2962 "of the destination")
2963 : G_("%qE writing a terminating nul past the end "
2964 "of the destination")), info
.func
);
2967 if (res
.min
== res
.max
)
2969 const char *d
= target_to_host (hostdir
, sizeof hostdir
, dir
.beg
);
2971 return fmtwarn_n (dirloc
, argloc
, NULL
, info
.warnopt (), res
.min
,
2972 "%<%.*s%> directive writing %wu byte into a region "
2973 "of size between %wu and %wu",
2974 "%<%.*s%> directive writing %wu bytes into a region "
2975 "of size between %wu and %wu", (int) dir
.len
, d
,
2976 res
.min
, avail_range
.min
, avail_range
.max
);
2978 return fmtwarn_n (dirloc
, argloc
, NULL
, info
.warnopt (), res
.min
,
2979 "%<%.*s%> directive output may be truncated writing "
2980 "%wu byte into a region of size between %wu and %wu",
2981 "%<%.*s%> directive output may be truncated writing "
2982 "%wu bytes into a region of size between %wu and "
2983 "%wu", (int) dir
.len
, d
, res
.min
, avail_range
.min
,
2986 return fmtwarn_n (dirloc
, argloc
, NULL
, info
.warnopt (), res
.min
,
2987 "%<%.*s%> directive output truncated writing %wu "
2988 "byte into a region of size between %wu and %wu",
2989 "%<%.*s%> directive output truncated writing %wu "
2990 "bytes into a region of size between %wu and %wu",
2991 (int) dir
.len
, d
, res
.min
, avail_range
.min
,
2995 if (res
.min
== 0 && res
.max
< maxbytes
)
2996 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
2999 ? G_("%<%.*s%> directive output may be truncated "
3000 "writing up to %wu bytes into a region of size "
3001 "between %wu and %wu")
3002 : G_("%<%.*s%> directive output truncated writing "
3003 "up to %wu bytes into a region of size between "
3005 : G_("%<%.*s%> directive writing up to %wu bytes "
3006 "into a region of size between %wu and %wu"),
3008 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
3009 res
.max
, avail_range
.min
, avail_range
.max
);
3011 if (res
.min
== 0 && maxbytes
<= res
.max
)
3012 /* This is a special case to avoid issuing the potentially confusing
3014 writing 0 or more bytes into a region of size between 0 and N. */
3015 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3018 ? G_("%<%.*s%> directive output may be truncated "
3019 "writing likely %wu or more bytes into a region "
3020 "of size between %wu and %wu")
3021 : G_("%<%.*s%> directive output truncated writing "
3022 "likely %wu or more bytes into a region of size "
3023 "between %wu and %wu"))
3024 : G_("%<%.*s%> directive writing likely %wu or more bytes "
3025 "into a region of size between %wu and %wu"),
3027 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
3028 res
.likely
, avail_range
.min
, avail_range
.max
);
3030 if (res
.max
< maxbytes
)
3031 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3034 ? G_("%<%.*s%> directive output may be truncated "
3035 "writing between %wu and %wu bytes into a region "
3036 "of size between %wu and %wu")
3037 : G_("%<%.*s%> directive output truncated writing "
3038 "between %wu and %wu bytes into a region of size "
3039 "between %wu and %wu"))
3040 : G_("%<%.*s%> directive writing between %wu and "
3041 "%wu bytes into a region of size between %wu and "
3042 "%wu"), (int) dir
.len
,
3043 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
3044 res
.min
, res
.max
, avail_range
.min
, avail_range
.max
);
3046 return fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3049 ? G_("%<%.*s%> directive output may be truncated writing "
3050 "%wu or more bytes into a region of size between "
3052 : G_("%<%.*s%> directive output truncated writing "
3053 "%wu or more bytes into a region of size between "
3055 : G_("%<%.*s%> directive writing %wu or more bytes "
3056 "into a region of size between %wu and %wu"),
3058 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
3059 res
.min
, avail_range
.min
, avail_range
.max
);
3062 /* Given the formatting result described by RES and NAVAIL, the number
3063 of available bytes in the destination, return the range of bytes
3064 remaining in the destination. */
3066 static inline result_range
3067 bytes_remaining (unsigned HOST_WIDE_INT navail
, const format_result
&res
)
3071 if (HOST_WIDE_INT_MAX
<= navail
)
3073 range
.min
= range
.max
= range
.likely
= range
.unlikely
= navail
;
3077 /* The lower bound of the available range is the available size
3078 minus the maximum output size, and the upper bound is the size
3079 minus the minimum. */
3080 range
.max
= res
.range
.min
< navail
? navail
- res
.range
.min
: 0;
3082 range
.likely
= res
.range
.likely
< navail
? navail
- res
.range
.likely
: 0;
3084 if (res
.range
.max
< HOST_WIDE_INT_MAX
)
3085 range
.min
= res
.range
.max
< navail
? navail
- res
.range
.max
: 0;
3087 range
.min
= range
.likely
;
3089 range
.unlikely
= (res
.range
.unlikely
< navail
3090 ? navail
- res
.range
.unlikely
: 0);
3095 /* Compute the length of the output resulting from the directive DIR
3096 in a call described by INFO and update the overall result of the call
3097 in *RES. Return true if the directive has been handled. */
3100 format_directive (const call_info
&info
,
3101 format_result
*res
, const directive
&dir
,
3102 pointer_query
&ptr_qry
)
3104 /* Offset of the beginning of the directive from the beginning
3105 of the format string. */
3106 size_t offset
= dir
.beg
- info
.fmtstr
;
3107 size_t start
= offset
;
3108 size_t length
= offset
+ dir
.len
- !!dir
.len
;
3110 /* Create a location for the whole directive from the % to the format
3112 substring_loc
dirloc (info
.fmtloc
, TREE_TYPE (info
.format
),
3113 offset
, start
, length
);
3115 /* Also get the location of the argument if possible.
3116 This doesn't work for integer literals or function calls. */
3117 location_t argloc
= UNKNOWN_LOCATION
;
3119 argloc
= EXPR_LOCATION (dir
.arg
);
3121 /* Bail when there is no function to compute the output length,
3122 or when minimum length checking has been disabled. */
3123 if (!dir
.fmtfunc
|| res
->range
.min
>= HOST_WIDE_INT_MAX
)
3126 /* Compute the range of lengths of the formatted output. */
3127 fmtresult fmtres
= dir
.fmtfunc (dir
, dir
.arg
, ptr_qry
);
3129 /* Record whether the output of all directives is known to be
3130 bounded by some maximum, implying that their arguments are
3131 either known exactly or determined to be in a known range
3132 or, for strings, limited by the upper bounds of the arrays
3134 res
->knownrange
&= fmtres
.knownrange
;
3136 if (!fmtres
.knownrange
)
3138 /* Only when the range is known, check it against the host value
3139 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
3140 INT_MAX precision, which is the longest possible output of any
3141 single directive). That's the largest valid byte count (though
3142 not valid call to a printf-like function because it can never
3143 return such a count). Otherwise, the range doesn't correspond
3144 to known values of the argument. */
3145 if (fmtres
.range
.max
> target_dir_max ())
3147 /* Normalize the MAX counter to avoid having to deal with it
3148 later. The counter can be less than HOST_WIDE_INT_M1U
3149 when compiling for an ILP32 target on an LP64 host. */
3150 fmtres
.range
.max
= HOST_WIDE_INT_M1U
;
3151 /* Disable exact and maximum length checking after a failure
3152 to determine the maximum number of characters (for example
3153 for wide characters or wide character strings) but continue
3154 tracking the minimum number of characters. */
3155 res
->range
.max
= HOST_WIDE_INT_M1U
;
3158 if (fmtres
.range
.min
> target_dir_max ())
3160 /* Disable exact length checking after a failure to determine
3161 even the minimum number of characters (it shouldn't happen
3162 except in an error) but keep tracking the minimum and maximum
3163 number of characters. */
3168 /* Buffer for the directive in the host character set (used when
3169 the source character set is different). */
3172 int dirlen
= dir
.len
;
3176 fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3177 "%<%.*s%> directive argument is null",
3178 dirlen
, target_to_host (hostdir
, sizeof hostdir
, dir
.beg
));
3180 /* Don't bother processing the rest of the format string. */
3182 res
->range
.min
= HOST_WIDE_INT_M1U
;
3183 res
->range
.max
= HOST_WIDE_INT_M1U
;
3187 /* Compute the number of available bytes in the destination. There
3188 must always be at least one byte of space for the terminating
3189 NUL that's appended after the format string has been processed. */
3190 result_range avail_range
= bytes_remaining (info
.objsize
, *res
);
3192 /* If the argument aliases a part of the destination of the formatted
3193 call at offset FMTRES.DST_OFFSET append the directive and its result
3194 to the set of aliases for later processing. */
3195 if (fmtres
.dst_offset
!= HOST_WIDE_INT_MIN
)
3196 res
->append_alias (dir
, fmtres
.dst_offset
, fmtres
.range
);
3198 bool warned
= res
->warned
;
3201 warned
= maybe_warn (dirloc
, argloc
, info
, avail_range
,
3204 /* Bump up the total maximum if it isn't too big. */
3205 if (res
->range
.max
< HOST_WIDE_INT_MAX
3206 && fmtres
.range
.max
< HOST_WIDE_INT_MAX
)
3207 res
->range
.max
+= fmtres
.range
.max
;
3209 /* Raise the total unlikely maximum by the larger of the maximum
3210 and the unlikely maximum. */
3211 unsigned HOST_WIDE_INT save
= res
->range
.unlikely
;
3212 if (fmtres
.range
.max
< fmtres
.range
.unlikely
)
3213 res
->range
.unlikely
+= fmtres
.range
.unlikely
;
3215 res
->range
.unlikely
+= fmtres
.range
.max
;
3217 if (res
->range
.unlikely
< save
)
3218 res
->range
.unlikely
= HOST_WIDE_INT_M1U
;
3220 res
->range
.min
+= fmtres
.range
.min
;
3221 res
->range
.likely
+= fmtres
.range
.likely
;
3223 /* Has the minimum directive output length exceeded the maximum
3224 of 4095 bytes required to be supported? */
3225 bool minunder4k
= fmtres
.range
.min
< 4096;
3226 bool maxunder4k
= fmtres
.range
.max
< 4096;
3227 /* Clear POSUNDER4K in the overall result if the maximum has exceeded
3228 the 4k (this is necessary to avoid the return value optimization
3229 that may not be safe in the maximum case). */
3231 res
->posunder4k
= false;
3232 /* Also clear POSUNDER4K if the directive may fail. */
3234 res
->posunder4k
= false;
3237 /* Only warn at level 2. */
3239 /* Only warn for string functions. */
3240 && info
.is_string_func ()
3242 || (!maxunder4k
&& fmtres
.range
.max
< HOST_WIDE_INT_MAX
)))
3244 /* The directive output may be longer than the maximum required
3245 to be handled by an implementation according to 7.21.6.1, p15
3246 of C11. Warn on this only at level 2 but remember this and
3247 prevent folding the return value when done. This allows for
3248 the possibility of the actual libc call failing due to ENOMEM
3249 (like Glibc does with very large precision or width).
3250 Issue the "may exceed" warning only for string functions and
3251 not for fprintf or printf. */
3253 if (fmtres
.range
.min
== fmtres
.range
.max
)
3254 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3255 "%<%.*s%> directive output of %wu bytes exceeds "
3256 "minimum required size of 4095", dirlen
,
3257 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
3259 else if (!minunder4k
)
3260 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3261 "%<%.*s%> directive output between %wu and %wu "
3262 "bytes exceeds minimum required size of 4095",
3264 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
3265 fmtres
.range
.min
, fmtres
.range
.max
);
3266 else if (!info
.retval_used () && info
.is_string_func ())
3267 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3268 "%<%.*s%> directive output between %wu and %wu "
3269 "bytes may exceed minimum required size of "
3272 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
3273 fmtres
.range
.min
, fmtres
.range
.max
);
3276 /* Has the likely and maximum directive output exceeded INT_MAX? */
3277 bool likelyximax
= *dir
.beg
&& res
->range
.likely
> target_int_max ();
3278 /* Don't consider the maximum to be in excess when it's the result
3279 of a string of unknown length (i.e., whose maximum has been set
3280 to be greater than or equal to HOST_WIDE_INT_MAX. */
3281 bool maxximax
= (*dir
.beg
3282 && res
->range
.max
> target_int_max ()
3283 && res
->range
.max
< HOST_WIDE_INT_MAX
);
3286 /* Warn for the likely output size at level 1. */
3288 /* But only warn for the maximum at level 2. */
3291 && fmtres
.range
.max
< HOST_WIDE_INT_MAX
)))
3293 if (fmtres
.range
.min
> target_int_max ())
3295 /* The directive output exceeds INT_MAX bytes. */
3296 if (fmtres
.range
.min
== fmtres
.range
.max
)
3297 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3298 "%<%.*s%> directive output of %wu bytes exceeds "
3299 "%<INT_MAX%>", dirlen
,
3300 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
3303 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3304 "%<%.*s%> directive output between %wu and "
3305 "%wu bytes exceeds %<INT_MAX%>", dirlen
,
3306 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
3307 fmtres
.range
.min
, fmtres
.range
.max
);
3309 else if (res
->range
.min
> target_int_max ())
3311 /* The directive output is under INT_MAX but causes the result
3312 to exceed INT_MAX bytes. */
3313 if (fmtres
.range
.min
== fmtres
.range
.max
)
3314 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3315 "%<%.*s%> directive output of %wu bytes causes "
3316 "result to exceed %<INT_MAX%>", dirlen
,
3317 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
3320 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3321 "%<%.*s%> directive output between %wu and "
3322 "%wu bytes causes result to exceed %<INT_MAX%>",
3324 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
3325 fmtres
.range
.min
, fmtres
.range
.max
);
3327 else if ((!info
.retval_used () || !info
.bounded
)
3328 && (info
.is_string_func ()))
3329 /* Warn for calls to string functions that either aren't bounded
3330 (sprintf) or whose return value isn't used. */
3331 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3332 "%<%.*s%> directive output between %wu and "
3333 "%wu bytes may cause result to exceed "
3334 "%<INT_MAX%>", dirlen
,
3335 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
),
3336 fmtres
.range
.min
, fmtres
.range
.max
);
3339 if (!warned
&& fmtres
.nonstr
)
3341 warned
= fmtwarn (dirloc
, argloc
, NULL
, info
.warnopt (),
3342 "%<%.*s%> directive argument is not a nul-terminated "
3345 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
));
3346 if (warned
&& DECL_P (fmtres
.nonstr
))
3347 inform (DECL_SOURCE_LOCATION (fmtres
.nonstr
),
3348 "referenced argument declared here");
3352 if (warned
&& fmtres
.range
.min
< fmtres
.range
.likely
3353 && fmtres
.range
.likely
< fmtres
.range
.max
)
3354 inform_n (info
.fmtloc
, fmtres
.range
.likely
,
3355 "assuming directive output of %wu byte",
3356 "assuming directive output of %wu bytes",
3357 fmtres
.range
.likely
);
3359 if (warned
&& fmtres
.argmin
)
3361 if (fmtres
.argmin
== fmtres
.argmax
)
3362 inform (info
.fmtloc
, "directive argument %qE", fmtres
.argmin
);
3363 else if (fmtres
.knownrange
)
3364 inform (info
.fmtloc
, "directive argument in the range [%E, %E]",
3365 fmtres
.argmin
, fmtres
.argmax
);
3367 inform (info
.fmtloc
,
3368 "using the range [%E, %E] for directive argument",
3369 fmtres
.argmin
, fmtres
.argmax
);
3372 res
->warned
|= warned
;
3374 if (!dir
.beg
[0] && res
->warned
)
3376 location_t callloc
= gimple_location (info
.callstmt
);
3378 unsigned HOST_WIDE_INT min
= res
->range
.min
;
3379 unsigned HOST_WIDE_INT max
= res
->range
.max
;
3381 if (info
.objsize
< HOST_WIDE_INT_MAX
)
3383 /* If a warning has been issued for buffer overflow or truncation
3384 help the user figure out how big a buffer they need. */
3387 inform_n (callloc
, min
,
3388 "%qE output %wu byte into a destination of size %wu",
3389 "%qE output %wu bytes into a destination of size %wu",
3390 info
.func
, min
, info
.objsize
);
3391 else if (max
< HOST_WIDE_INT_MAX
)
3393 "%qE output between %wu and %wu bytes into "
3394 "a destination of size %wu",
3395 info
.func
, min
, max
, info
.objsize
);
3396 else if (min
< res
->range
.likely
&& res
->range
.likely
< max
)
3398 "%qE output %wu or more bytes (assuming %wu) into "
3399 "a destination of size %wu",
3400 info
.func
, min
, res
->range
.likely
, info
.objsize
);
3403 "%qE output %wu or more bytes into a destination of size "
3405 info
.func
, min
, info
.objsize
);
3407 else if (!info
.is_string_func ())
3409 /* If the warning is for a file function like fprintf
3410 of printf with no destination size just print the computed
3413 inform_n (callloc
, min
,
3414 "%qE output %wu byte", "%qE output %wu bytes",
3416 else if (max
< HOST_WIDE_INT_MAX
)
3418 "%qE output between %wu and %wu bytes",
3419 info
.func
, min
, max
);
3420 else if (min
< res
->range
.likely
&& res
->range
.likely
< max
)
3422 "%qE output %wu or more bytes (assuming %wu)",
3423 info
.func
, min
, res
->range
.likely
);
3426 "%qE output %wu or more bytes",
3431 if (dump_file
&& *dir
.beg
)
3435 HOST_WIDE_INT_PRINT_DEC
", " HOST_WIDE_INT_PRINT_DEC
", "
3436 HOST_WIDE_INT_PRINT_DEC
", " HOST_WIDE_INT_PRINT_DEC
" ("
3437 HOST_WIDE_INT_PRINT_DEC
", " HOST_WIDE_INT_PRINT_DEC
", "
3438 HOST_WIDE_INT_PRINT_DEC
", " HOST_WIDE_INT_PRINT_DEC
")\n",
3439 fmtres
.range
.min
, fmtres
.range
.likely
,
3440 fmtres
.range
.max
, fmtres
.range
.unlikely
,
3441 res
->range
.min
, res
->range
.likely
,
3442 res
->range
.max
, res
->range
.unlikely
);
3448 /* Parse a format directive in function call described by INFO starting
3449 at STR and populate DIR structure. Bump up *ARGNO by the number of
3450 arguments extracted for the directive. Return the length of
3454 parse_directive (call_info
&info
,
3455 directive
&dir
, format_result
*res
,
3456 const char *str
, unsigned *argno
,
3459 const char *pcnt
= strchr (str
, target_percent
);
3462 if (size_t len
= pcnt
? pcnt
- str
: *str
? strlen (str
) : 1)
3464 /* This directive is either a plain string or the terminating nul
3465 (which isn't really a directive but it simplifies things to
3466 handle it as if it were). */
3468 dir
.fmtfunc
= format_plain
;
3472 fprintf (dump_file
, " Directive %u at offset "
3473 HOST_WIDE_INT_PRINT_UNSIGNED
": \"%.*s\", "
3474 "length = " HOST_WIDE_INT_PRINT_UNSIGNED
"\n",
3476 (unsigned HOST_WIDE_INT
)(size_t)(dir
.beg
- info
.fmtstr
),
3477 (int)dir
.len
, dir
.beg
, (unsigned HOST_WIDE_INT
) dir
.len
);
3483 /* Set the directive argument's number to correspond to its position
3484 in the formatted function call's argument list. */
3487 const char *pf
= pcnt
+ 1;
3489 /* POSIX numbered argument index or zero when none. */
3490 HOST_WIDE_INT dollar
= 0;
3492 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3493 when given by a va_list argument, and a non-negative value
3494 when specified in the format string itself. */
3495 HOST_WIDE_INT width
= -1;
3496 HOST_WIDE_INT precision
= -1;
3498 /* Pointers to the beginning of the width and precision decimal
3499 string (if any) within the directive. */
3500 const char *pwidth
= 0;
3501 const char *pprec
= 0;
3503 /* When the value of the decimal string that specifies width or
3504 precision is out of range, points to the digit that causes
3505 the value to exceed the limit. */
3506 const char *werange
= NULL
;
3507 const char *perange
= NULL
;
3509 /* Width specified via the asterisk. Need not be INTEGER_CST.
3510 For vararg functions set to void_node. */
3511 tree star_width
= NULL_TREE
;
3513 /* Width specified via the asterisk. Need not be INTEGER_CST.
3514 For vararg functions set to void_node. */
3515 tree star_precision
= NULL_TREE
;
3517 if (ISDIGIT (target_to_host (*pf
)))
3519 /* This could be either a POSIX positional argument, the '0'
3520 flag, or a width, depending on what follows. Store it as
3521 width and sort it out later after the next character has
3524 width
= target_strtowi (&pf
, &werange
);
3526 else if (target_to_host (*pf
) == '*')
3528 /* Similarly to the block above, this could be either a POSIX
3529 positional argument or a width, depending on what follows. */
3530 if (*argno
< gimple_call_num_args (info
.callstmt
))
3531 star_width
= gimple_call_arg (info
.callstmt
, (*argno
)++);
3533 star_width
= void_node
;
3537 if (target_to_host (*pf
) == '$')
3539 /* Handle the POSIX dollar sign which references the 1-based
3540 positional argument number. */
3542 dollar
= width
+ info
.argidx
;
3544 && TREE_CODE (star_width
) == INTEGER_CST
3545 && (TYPE_PRECISION (TREE_TYPE (star_width
))
3546 <= TYPE_PRECISION (integer_type_node
)))
3547 dollar
= width
+ tree_to_shwi (star_width
);
3549 /* Bail when the numbered argument is out of range (it will
3550 have already been diagnosed by -Wformat). */
3552 || dollar
== (int)info
.argidx
3553 || dollar
> gimple_call_num_args (info
.callstmt
))
3558 star_width
= NULL_TREE
;
3563 if (dollar
|| !star_width
)
3569 /* The '0' that has been interpreted as a width above is
3570 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3571 and continue processing other flags. */
3577 /* (Non-zero) width has been seen. The next character
3578 is either a period or a digit. */
3579 goto start_precision
;
3582 /* When either '$' has been seen, or width has not been seen,
3583 the next field is the optional flags followed by an optional
3586 switch (target_to_host (*pf
))
3593 dir
.set_flag (target_to_host (*pf
++));
3602 if (ISDIGIT (target_to_host (*pf
)))
3606 width
= target_strtowi (&pf
, &werange
);
3608 else if (target_to_host (*pf
) == '*')
3610 if (*argno
< gimple_call_num_args (info
.callstmt
))
3611 star_width
= gimple_call_arg (info
.callstmt
, (*argno
)++);
3614 /* This is (likely) a va_list. It could also be an invalid
3615 call with insufficient arguments. */
3616 star_width
= void_node
;
3620 else if (target_to_host (*pf
) == '\'')
3622 /* The POSIX apostrophe indicating a numeric grouping
3623 in the current locale. Even though it's possible to
3624 estimate the upper bound on the size of the output
3625 based on the number of digits it probably isn't worth
3632 if (target_to_host (*pf
) == '.')
3636 if (ISDIGIT (target_to_host (*pf
)))
3639 precision
= target_strtowi (&pf
, &perange
);
3641 else if (target_to_host (*pf
) == '*')
3643 if (*argno
< gimple_call_num_args (info
.callstmt
))
3644 star_precision
= gimple_call_arg (info
.callstmt
, (*argno
)++);
3647 /* This is (likely) a va_list. It could also be an invalid
3648 call with insufficient arguments. */
3649 star_precision
= void_node
;
3655 /* The decimal precision or the asterisk are optional.
3656 When neither is specified it's taken to be zero. */
3661 switch (target_to_host (*pf
))
3664 if (target_to_host (pf
[1]) == 'h')
3667 dir
.modifier
= FMT_LEN_hh
;
3670 dir
.modifier
= FMT_LEN_h
;
3675 dir
.modifier
= FMT_LEN_j
;
3680 dir
.modifier
= FMT_LEN_L
;
3685 if (target_to_host (pf
[1]) == 'l')
3688 dir
.modifier
= FMT_LEN_ll
;
3691 dir
.modifier
= FMT_LEN_l
;
3696 dir
.modifier
= FMT_LEN_t
;
3701 dir
.modifier
= FMT_LEN_z
;
3706 switch (target_to_host (*pf
))
3708 /* Handle a sole '%' character the same as "%%" but since it's
3709 undefined prevent the result from being folded. */
3712 res
->range
.min
= res
->range
.max
= HOST_WIDE_INT_M1U
;
3715 dir
.fmtfunc
= format_percent
;
3726 res
->floating
= true;
3727 dir
.fmtfunc
= format_floating
;
3736 dir
.fmtfunc
= format_integer
;
3741 dir
.fmtfunc
= format_integer
;
3745 /* The %p output is implementation-defined. It's possible
3746 to determine this format but due to extensions (especially
3747 those of the Linux kernel -- see bug 78512) the first %p
3748 in the format string disables any further processing. */
3752 /* %n has side-effects even when nothing is actually printed to
3754 info
.nowrite
= false;
3755 dir
.fmtfunc
= format_none
;
3760 /* POSIX wide character and C/POSIX narrow character. */
3761 dir
.fmtfunc
= format_character
;
3766 /* POSIX wide string and C/POSIX narrow character string. */
3767 dir
.fmtfunc
= format_string
;
3771 /* Unknown conversion specification. */
3775 dir
.specifier
= target_to_host (*pf
++);
3777 /* Store the length of the format directive. */
3778 dir
.len
= pf
- pcnt
;
3780 /* Buffer for the directive in the host character set (used when
3781 the source character set is different). */
3786 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width
)))
3787 dir
.set_width (star_width
, query
);
3790 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3791 (width is the absolute value of that specified). */
3793 dir
.width
[1] = target_int_max () + 1;
3798 if (width
== HOST_WIDE_INT_MAX
&& werange
)
3800 size_t begin
= dir
.beg
- info
.fmtstr
+ (pwidth
- pcnt
);
3801 size_t caret
= begin
+ (werange
- pcnt
);
3802 size_t end
= pf
- info
.fmtstr
- 1;
3804 /* Create a location for the width part of the directive,
3805 pointing the caret at the first out-of-range digit. */
3806 substring_loc
dirloc (info
.fmtloc
, TREE_TYPE (info
.format
),
3809 fmtwarn (dirloc
, UNKNOWN_LOCATION
, NULL
, info
.warnopt (),
3810 "%<%.*s%> directive width out of range", (int) dir
.len
,
3811 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
));
3814 dir
.set_width (width
);
3819 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision
)))
3820 dir
.set_precision (star_precision
, query
);
3823 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3824 (unlike width, negative precision is ignored). */
3826 dir
.prec
[1] = target_int_max ();
3831 if (precision
== HOST_WIDE_INT_MAX
&& perange
)
3833 size_t begin
= dir
.beg
- info
.fmtstr
+ (pprec
- pcnt
) - 1;
3834 size_t caret
= dir
.beg
- info
.fmtstr
+ (perange
- pcnt
) - 1;
3835 size_t end
= pf
- info
.fmtstr
- 2;
3837 /* Create a location for the precision part of the directive,
3838 including the leading period, pointing the caret at the first
3839 out-of-range digit . */
3840 substring_loc
dirloc (info
.fmtloc
, TREE_TYPE (info
.format
),
3843 fmtwarn (dirloc
, UNKNOWN_LOCATION
, NULL
, info
.warnopt (),
3844 "%<%.*s%> directive precision out of range", (int) dir
.len
,
3845 target_to_host (hostdir
, sizeof hostdir
, dir
.beg
));
3848 dir
.set_precision (precision
);
3851 /* Extract the argument if the directive takes one and if it's
3852 available (e.g., the function doesn't take a va_list). Treat
3853 missing arguments the same as va_list, even though they will
3854 have likely already been diagnosed by -Wformat. */
3855 if (dir
.specifier
!= '%'
3856 && *argno
< gimple_call_num_args (info
.callstmt
))
3857 dir
.arg
= gimple_call_arg (info
.callstmt
, dollar
? dollar
: (*argno
)++);
3862 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3865 (unsigned HOST_WIDE_INT
)(size_t)(dir
.beg
- info
.fmtstr
),
3866 (int)dir
.len
, dir
.beg
);
3869 if (dir
.width
[0] == dir
.width
[1])
3870 fprintf (dump_file
, ", width = " HOST_WIDE_INT_PRINT_DEC
,
3874 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3875 ", " HOST_WIDE_INT_PRINT_DEC
"]",
3876 dir
.width
[0], dir
.width
[1]);
3881 if (dir
.prec
[0] == dir
.prec
[1])
3882 fprintf (dump_file
, ", precision = " HOST_WIDE_INT_PRINT_DEC
,
3886 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3887 HOST_WIDE_INT_PRINT_DEC
"]",
3888 dir
.prec
[0], dir
.prec
[1]);
3890 fputc ('\n', dump_file
);
3896 /* Diagnose overlap between destination and %s directive arguments. */
3899 maybe_warn_overlap (call_info
&info
, format_result
*res
)
3901 /* Two vectors of 1-based indices corresponding to either certainly
3902 or possibly aliasing arguments. */
3903 auto_vec
<int, 16> aliasarg
[2];
3905 /* Go through the array of potentially aliasing directives and collect
3906 argument numbers of those that do or may overlap the destination
3907 object given the full result. */
3908 for (unsigned i
= 0; i
!= res
->alias_count
; ++i
)
3910 const format_result::alias_info
&alias
= res
->aliases
[i
];
3912 enum { possible
= -1, none
= 0, certain
= 1 } overlap
= none
;
3914 /* If the precision is zero there is no overlap. (This only
3915 considers %s directives and ignores %n.) */
3916 if (alias
.dir
.prec
[0] == 0 && alias
.dir
.prec
[1] == 0)
3919 if (alias
.offset
== HOST_WIDE_INT_MAX
3920 || info
.dst_offset
== HOST_WIDE_INT_MAX
)
3922 else if (alias
.offset
== info
.dst_offset
)
3923 overlap
= alias
.dir
.prec
[0] == 0 ? possible
: certain
;
3926 /* Determine overlap from the range of output and offsets
3927 into the same destination as the source, and rule out
3928 impossible overlap. */
3929 unsigned HOST_WIDE_INT albeg
= alias
.offset
;
3930 unsigned HOST_WIDE_INT dstbeg
= info
.dst_offset
;
3932 unsigned HOST_WIDE_INT alend
= albeg
+ alias
.range
.min
;
3933 unsigned HOST_WIDE_INT dstend
= dstbeg
+ res
->range
.min
- 1;
3935 if ((albeg
<= dstbeg
&& alend
> dstbeg
)
3936 || (albeg
>= dstbeg
&& albeg
< dstend
))
3940 alend
= albeg
+ alias
.range
.max
;
3942 alend
= HOST_WIDE_INT_M1U
;
3944 dstend
= dstbeg
+ res
->range
.max
- 1;
3945 if (dstend
< dstbeg
)
3946 dstend
= HOST_WIDE_INT_M1U
;
3948 if ((albeg
>= dstbeg
&& albeg
<= dstend
)
3949 || (alend
>= dstbeg
&& alend
<= dstend
))
3954 if (overlap
== none
)
3957 /* Append the 1-based argument number. */
3958 aliasarg
[overlap
!= certain
].safe_push (alias
.dir
.argno
+ 1);
3960 /* Disable any kind of optimization. */
3961 res
->range
.unlikely
= HOST_WIDE_INT_M1U
;
3964 tree arg0
= gimple_call_arg (info
.callstmt
, 0);
3965 location_t loc
= gimple_location (info
.callstmt
);
3967 bool aliaswarn
= false;
3969 unsigned ncertain
= aliasarg
[0].length ();
3970 unsigned npossible
= aliasarg
[1].length ();
3971 if (ncertain
&& npossible
)
3973 /* If there are multiple arguments that overlap, some certainly
3974 and some possibly, handle both sets in a single diagnostic. */
3976 = warning_at (loc
, OPT_Wrestrict
,
3977 "%qE arguments %Z and maybe %Z overlap destination "
3979 info
.func
, aliasarg
[0].address (), ncertain
,
3980 aliasarg
[1].address (), npossible
,
3985 /* There is only one set of two or more arguments and they all
3986 certainly overlap the destination. */
3988 = warning_n (loc
, OPT_Wrestrict
, ncertain
,
3989 "%qE argument %Z overlaps destination object %qE",
3990 "%qE arguments %Z overlap destination object %qE",
3991 info
.func
, aliasarg
[0].address (), ncertain
,
3996 /* There is only one set of two or more arguments and they all
3997 may overlap (but need not). */
3999 = warning_n (loc
, OPT_Wrestrict
, npossible
,
4000 "%qE argument %Z may overlap destination object %qE",
4001 "%qE arguments %Z may overlap destination object %qE",
4002 info
.func
, aliasarg
[1].address (), npossible
,
4010 if (info
.dst_origin
!= arg0
)
4012 /* If its location is different from the first argument of the call
4013 point either at the destination object itself or at the expression
4014 that was used to determine the overlap. */
4015 loc
= (DECL_P (info
.dst_origin
)
4016 ? DECL_SOURCE_LOCATION (info
.dst_origin
)
4017 : EXPR_LOCATION (info
.dst_origin
));
4018 if (loc
!= UNKNOWN_LOCATION
)
4020 "destination object referenced by %<restrict%>-qualified "
4021 "argument 1 was declared here");
4026 /* Compute the length of the output resulting from the call to a formatted
4027 output function described by INFO and store the result of the call in
4028 *RES. Issue warnings for detected past the end writes. Return true
4029 if the complete format string has been processed and *RES can be relied
4030 on, false otherwise (e.g., when a unknown or unhandled directive was seen
4031 that caused the processing to be terminated early). */
4034 compute_format_length (call_info
&info
, format_result
*res
,
4035 pointer_query
&ptr_qry
)
4039 location_t callloc
= gimple_location (info
.callstmt
);
4040 fprintf (dump_file
, "%s:%i: ",
4041 LOCATION_FILE (callloc
), LOCATION_LINE (callloc
));
4042 print_generic_expr (dump_file
, info
.func
, dump_flags
);
4045 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
4046 ", fmtstr = \"%s\"\n",
4047 info
.objsize
, info
.fmtstr
);
4050 /* Reset the minimum and maximum byte counters. */
4051 res
->range
.min
= res
->range
.max
= 0;
4053 /* No directive has been seen yet so the length of output is bounded
4054 by the known range [0, 0] (with no conversion resulting in a failure
4055 or producing more than 4K bytes) until determined otherwise. */
4056 res
->knownrange
= true;
4057 res
->floating
= false;
4058 res
->warned
= false;
4060 /* 1-based directive counter. */
4063 /* The variadic argument counter. */
4064 unsigned argno
= info
.argidx
;
4066 bool success
= true;
4068 for (const char *pf
= info
.fmtstr
; ; ++dirno
)
4070 directive
dir (&info
, dirno
);
4072 size_t n
= parse_directive (info
, dir
, res
, pf
, &argno
, ptr_qry
.rvals
);
4074 /* Return failure if the format function fails. */
4075 if (!format_directive (info
, res
, dir
, ptr_qry
))
4078 /* Return success when the directive is zero bytes long and it's
4079 the last thing in the format string (i.e., it's the terminating
4080 nul, which isn't really a directive but handling it as one makes
4084 success
= *pf
== '\0';
4091 maybe_warn_overlap (info
, res
);
4093 /* The complete format string was processed (with or without warnings). */
4097 /* Return the size of the object referenced by the expression DEST in
4098 statement STMT, if available, or the maximum possible size otherwise. */
4100 static unsigned HOST_WIDE_INT
4101 get_destination_size (tree dest
, gimple
*stmt
, pointer_query
&ptr_qry
)
4103 /* When there is no destination return the maximum. */
4105 return HOST_WIDE_INT_MAX
;
4107 /* Use compute_objsize to determine the size of the destination object. */
4109 if (!ptr_qry
.get_ref (dest
, stmt
, &aref
))
4110 return HOST_WIDE_INT_MAX
;
4112 offset_int remsize
= aref
.size_remaining ();
4113 if (!wi::fits_uhwi_p (remsize
))
4114 return HOST_WIDE_INT_MAX
;
4116 return remsize
.to_uhwi ();
4119 /* Return true if the call described by INFO with result RES safe to
4120 optimize (i.e., no undefined behavior), and set RETVAL to the range
4121 of its return values. */
4124 is_call_safe (const call_info
&info
,
4125 const format_result
&res
, bool under4k
,
4126 unsigned HOST_WIDE_INT retval
[2])
4128 if (under4k
&& !res
.posunder4k
)
4131 /* The minimum return value. */
4132 retval
[0] = res
.range
.min
;
4134 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
4135 but in cases involving multibyte characters could be as large as
4136 RES.RANGE.UNLIKELY. */
4138 = res
.range
.unlikely
< res
.range
.max
? res
.range
.max
: res
.range
.unlikely
;
4140 /* Adjust the number of bytes which includes the terminating nul
4141 to reflect the return value of the function which does not.
4142 Because the valid range of the function is [INT_MIN, INT_MAX],
4143 a valid range before the adjustment below is [0, INT_MAX + 1]
4144 (the functions only return negative values on error or undefined
4146 if (retval
[0] <= target_int_max () + 1)
4148 if (retval
[1] <= target_int_max () + 1)
4151 /* Avoid the return value optimization when the behavior of the call
4152 is undefined either because any directive may have produced 4K or
4153 more of output, or the return value exceeds INT_MAX, or because
4154 the output overflows the destination object (but leave it enabled
4155 when the function is bounded because then the behavior is well-
4157 if (retval
[0] == retval
[1]
4158 && (info
.bounded
|| retval
[0] < info
.objsize
)
4159 && retval
[0] <= target_int_max ())
4162 if ((info
.bounded
|| retval
[1] < info
.objsize
)
4163 && (retval
[0] < target_int_max ()
4164 && retval
[1] < target_int_max ()))
4167 if (!under4k
&& (info
.bounded
|| retval
[0] < info
.objsize
))
4173 /* Given a suitable result RES of a call to a formatted output function
4174 described by INFO, substitute the result for the return value of
4175 the call. The result is suitable if the number of bytes it represents
4176 is known and exact. A result that isn't suitable for substitution may
4177 have its range set to the range of return values, if that is known.
4178 Return true if the call is removed and gsi_next should not be performed
4182 try_substitute_return_value (gimple_stmt_iterator
*gsi
,
4183 const call_info
&info
,
4184 const format_result
&res
)
4186 tree lhs
= gimple_get_lhs (info
.callstmt
);
4188 /* Set to true when the entire call has been removed. */
4189 bool removed
= false;
4191 /* The minimum and maximum return value. */
4192 unsigned HOST_WIDE_INT retval
[2] = {0};
4193 bool safe
= is_call_safe (info
, res
, true, retval
);
4196 && retval
[0] == retval
[1]
4197 /* Not prepared to handle possibly throwing calls here; they shouldn't
4198 appear in non-artificial testcases, except when the __*_chk routines
4199 are badly declared. */
4200 && !stmt_ends_bb_p (info
.callstmt
))
4202 tree cst
= build_int_cst (lhs
? TREE_TYPE (lhs
) : integer_type_node
,
4205 if (lhs
== NULL_TREE
&& info
.nowrite
)
4207 /* Remove the call to the bounded function with a zero size
4208 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
4209 unlink_stmt_vdef (info
.callstmt
);
4210 gsi_remove (gsi
, true);
4213 else if (info
.nowrite
)
4215 /* Replace the call to the bounded function with a zero size
4216 (e.g., snprintf(0, 0, "%i", 123) with the constant result
4218 gimplify_and_update_call_from_tree (gsi
, cst
);
4219 gimple
*callstmt
= gsi_stmt (*gsi
);
4220 update_stmt (callstmt
);
4224 /* Replace the left-hand side of the call with the constant
4225 result of the formatted function. */
4226 gimple_call_set_lhs (info
.callstmt
, NULL_TREE
);
4227 gimple
*g
= gimple_build_assign (lhs
, cst
);
4228 gsi_insert_after (gsi
, g
, GSI_NEW_STMT
);
4229 update_stmt (info
.callstmt
);
4235 fprintf (dump_file
, " Removing call statement.");
4238 fprintf (dump_file
, " Substituting ");
4239 print_generic_expr (dump_file
, cst
, dump_flags
);
4240 fprintf (dump_file
, " for %s.\n",
4241 info
.nowrite
? "statement" : "return value");
4245 else if (lhs
&& types_compatible_p (TREE_TYPE (lhs
), integer_type_node
))
4247 bool setrange
= false;
4250 && (info
.bounded
|| retval
[1] < info
.objsize
)
4251 && (retval
[0] < target_int_max ()
4252 && retval
[1] < target_int_max ()))
4254 /* If the result is in a valid range bounded by the size of
4255 the destination set it so that it can be used for subsequent
4257 int prec
= TYPE_PRECISION (integer_type_node
);
4259 wide_int min
= wi::shwi (retval
[0], prec
);
4260 wide_int max
= wi::shwi (retval
[1], prec
);
4261 value_range
r (TREE_TYPE (lhs
), min
, max
);
4262 set_range_info (lhs
, r
);
4269 const char *inbounds
4270 = (retval
[0] < info
.objsize
4271 ? (retval
[1] < info
.objsize
4272 ? "in" : "potentially out-of")
4275 const char *what
= setrange
? "Setting" : "Discarding";
4276 if (retval
[0] != retval
[1])
4278 " %s %s-bounds return value range ["
4279 HOST_WIDE_INT_PRINT_UNSIGNED
", "
4280 HOST_WIDE_INT_PRINT_UNSIGNED
"].\n",
4281 what
, inbounds
, retval
[0], retval
[1]);
4283 fprintf (dump_file
, " %s %s-bounds return value "
4284 HOST_WIDE_INT_PRINT_UNSIGNED
".\n",
4285 what
, inbounds
, retval
[0]);
4290 fputc ('\n', dump_file
);
4295 /* Try to simplify a s{,n}printf call described by INFO with result
4296 RES by replacing it with a simpler and presumably more efficient
4297 call (such as strcpy). */
4300 try_simplify_call (gimple_stmt_iterator
*gsi
,
4301 const call_info
&info
,
4302 const format_result
&res
)
4304 unsigned HOST_WIDE_INT dummy
[2];
4305 if (!is_call_safe (info
, res
, info
.retval_used (), dummy
))
4308 switch (info
.fncode
)
4310 case BUILT_IN_SNPRINTF
:
4311 return gimple_fold_builtin_snprintf (gsi
);
4313 case BUILT_IN_SPRINTF
:
4314 return gimple_fold_builtin_sprintf (gsi
);
4323 /* Return the zero-based index of the format string argument of a printf
4324 like function and set *IDX_ARGS to the first format argument. When
4325 no such index exists return UINT_MAX. */
4328 get_user_idx_format (tree fndecl
, unsigned *idx_args
)
4330 tree attrs
= lookup_attribute ("format", DECL_ATTRIBUTES (fndecl
));
4332 attrs
= lookup_attribute ("format", TYPE_ATTRIBUTES (TREE_TYPE (fndecl
)));
4337 attrs
= TREE_VALUE (attrs
);
4339 tree archetype
= TREE_VALUE (attrs
);
4340 if (strcmp ("printf", IDENTIFIER_POINTER (archetype
)))
4343 attrs
= TREE_CHAIN (attrs
);
4344 tree fmtarg
= TREE_VALUE (attrs
);
4346 attrs
= TREE_CHAIN (attrs
);
4347 tree elliparg
= TREE_VALUE (attrs
);
4349 /* Attribute argument indices are 1-based but we use zero-based. */
4350 *idx_args
= tree_to_uhwi (elliparg
) - 1;
4351 return tree_to_uhwi (fmtarg
) - 1;
4354 } /* Unnamed namespace. */
4356 /* Determine if a GIMPLE call at *GSI is to one of the sprintf-like built-in
4357 functions and if so, handle it. Return true if the call is removed and
4358 gsi_next should not be performed in the caller. */
4361 handle_printf_call (gimple_stmt_iterator
*gsi
, pointer_query
&ptr_qry
)
4363 init_target_to_host_charmap ();
4365 call_info info
= call_info ();
4367 info
.callstmt
= gsi_stmt (*gsi
);
4368 info
.func
= gimple_call_fndecl (info
.callstmt
);
4372 /* Format string argument number (valid for all functions). */
4373 unsigned idx_format
= UINT_MAX
;
4374 if (gimple_call_builtin_p (info
.callstmt
, BUILT_IN_NORMAL
))
4375 info
.fncode
= DECL_FUNCTION_CODE (info
.func
);
4379 idx_format
= get_user_idx_format (info
.func
, &idx_args
);
4380 if (idx_format
== UINT_MAX
4381 || idx_format
>= gimple_call_num_args (info
.callstmt
)
4382 || idx_args
> gimple_call_num_args (info
.callstmt
)
4383 || !POINTER_TYPE_P (TREE_TYPE (gimple_call_arg (info
.callstmt
,
4386 info
.fncode
= BUILT_IN_NONE
;
4387 info
.argidx
= idx_args
;
4390 /* The size of the destination as in snprintf(dest, size, ...). */
4391 unsigned HOST_WIDE_INT dstsize
= HOST_WIDE_INT_M1U
;
4393 /* The size of the destination determined by __builtin_object_size. */
4394 unsigned HOST_WIDE_INT objsize
= HOST_WIDE_INT_M1U
;
4396 /* Zero-based buffer size argument number (snprintf and vsnprintf). */
4397 unsigned idx_dstsize
= UINT_MAX
;
4399 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
4400 unsigned idx_objsize
= UINT_MAX
;
4402 /* Destinaton argument number (valid for sprintf functions only). */
4403 unsigned idx_dstptr
= 0;
4405 switch (info
.fncode
)
4408 // User-defined function with attribute format (printf).
4412 case BUILT_IN_FPRINTF
:
4414 // __builtin_fprintf (FILE*, format, ...)
4420 case BUILT_IN_FPRINTF_CHK
:
4422 // __builtin_fprintf_chk (FILE*, ost, format, ...)
4428 case BUILT_IN_FPRINTF_UNLOCKED
:
4430 // __builtin_fprintf_unnlocked (FILE*, format, ...)
4436 case BUILT_IN_PRINTF
:
4438 // __builtin_printf (format, ...)
4444 case BUILT_IN_PRINTF_CHK
:
4446 // __builtin_printf_chk (ost, format, ...)
4452 case BUILT_IN_PRINTF_UNLOCKED
:
4454 // __builtin_printf (format, ...)
4460 case BUILT_IN_SPRINTF
:
4462 // __builtin_sprintf (dst, format, ...)
4467 case BUILT_IN_SPRINTF_CHK
:
4469 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
4475 case BUILT_IN_SNPRINTF
:
4477 // __builtin_snprintf (dst, size, format, ...)
4481 info
.bounded
= true;
4484 case BUILT_IN_SNPRINTF_CHK
:
4486 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
4491 info
.bounded
= true;
4494 case BUILT_IN_VFPRINTF
:
4496 // __builtin_vprintf (FILE*, format, va_list)
4502 case BUILT_IN_VFPRINTF_CHK
:
4504 // __builtin___vfprintf_chk (FILE*, ost, format, va_list)
4510 case BUILT_IN_VPRINTF
:
4512 // __builtin_vprintf (format, va_list)
4518 case BUILT_IN_VPRINTF_CHK
:
4520 // __builtin___vprintf_chk (ost, format, va_list)
4526 case BUILT_IN_VSNPRINTF
:
4528 // __builtin_vsprintf (dst, size, format, va)
4532 info
.bounded
= true;
4535 case BUILT_IN_VSNPRINTF_CHK
:
4537 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
4542 info
.bounded
= true;
4545 case BUILT_IN_VSPRINTF
:
4547 // __builtin_vsprintf (dst, format, va)
4552 case BUILT_IN_VSPRINTF_CHK
:
4554 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
4564 /* Set the global warning level for this function. */
4565 warn_level
= info
.bounded
? warn_format_trunc
: warn_format_overflow
;
4567 /* For all string functions the first argument is a pointer to
4569 tree dstptr
= (idx_dstptr
< gimple_call_num_args (info
.callstmt
)
4570 ? gimple_call_arg (info
.callstmt
, 0) : NULL_TREE
);
4572 info
.format
= gimple_call_arg (info
.callstmt
, idx_format
);
4574 /* True when the destination size is constant as opposed to the lower
4575 or upper bound of a range. */
4576 bool dstsize_cst_p
= true;
4577 bool posunder4k
= true;
4579 if (idx_dstsize
== UINT_MAX
)
4581 /* For non-bounded functions like sprintf, determine the size
4582 of the destination from the object or pointer passed to it
4583 as the first argument. */
4584 dstsize
= get_destination_size (dstptr
, info
.callstmt
, ptr_qry
);
4586 else if (tree size
= gimple_call_arg (info
.callstmt
, idx_dstsize
))
4588 /* For bounded functions try to get the size argument. */
4590 if (TREE_CODE (size
) == INTEGER_CST
)
4592 dstsize
= tree_to_uhwi (size
);
4593 /* No object can be larger than SIZE_MAX bytes (half the address
4594 space) on the target.
4595 The functions are defined only for output of at most INT_MAX
4596 bytes. Specifying a bound in excess of that limit effectively
4597 defeats the bounds checking (and on some implementations such
4598 as Solaris cause the function to fail with EINVAL). */
4599 if (dstsize
> target_size_max () / 2)
4601 /* Avoid warning if -Wstringop-overflow is specified since
4602 it also warns for the same thing though only for the
4603 checking built-ins. */
4604 if ((idx_objsize
== UINT_MAX
4605 || !warn_stringop_overflow
))
4606 warning_at (gimple_location (info
.callstmt
), info
.warnopt (),
4607 "specified bound %wu exceeds maximum object size "
4609 dstsize
, target_size_max () / 2);
4610 /* POSIX requires snprintf to fail if DSTSIZE is greater
4611 than INT_MAX. Even though not all POSIX implementations
4612 conform to the requirement, avoid folding in this case. */
4615 else if (dstsize
> target_int_max ())
4617 warning_at (gimple_location (info
.callstmt
), info
.warnopt (),
4618 "specified bound %wu exceeds %<INT_MAX%>",
4620 /* POSIX requires snprintf to fail if DSTSIZE is greater
4621 than INT_MAX. Avoid folding in that case. */
4625 else if (TREE_CODE (size
) == SSA_NAME
)
4627 /* Try to determine the range of values of the argument
4628 and use the greater of the two at level 1 and the smaller
4629 of them at level 2. */
4631 ptr_qry
.rvals
->range_of_expr (vr
, size
, info
.callstmt
);
4633 if (!vr
.undefined_p ())
4635 tree type
= TREE_TYPE (size
);
4636 tree tmin
= wide_int_to_tree (type
, vr
.lower_bound ());
4637 tree tmax
= wide_int_to_tree (type
, vr
.upper_bound ());
4638 unsigned HOST_WIDE_INT minsize
= TREE_INT_CST_LOW (tmin
);
4639 unsigned HOST_WIDE_INT maxsize
= TREE_INT_CST_LOW (tmax
);
4640 dstsize
= warn_level
< 2 ? maxsize
: minsize
;
4642 if (minsize
> target_int_max ())
4643 warning_at (gimple_location (info
.callstmt
), info
.warnopt (),
4644 "specified bound range [%wu, %wu] exceeds "
4648 /* POSIX requires snprintf to fail if DSTSIZE is greater
4649 than INT_MAX. Avoid folding if that's possible. */
4650 if (maxsize
> target_int_max ())
4654 /* The destination size is not constant. If the function is
4655 bounded (e.g., snprintf) a lower bound of zero doesn't
4656 necessarily imply it can be eliminated. */
4657 dstsize_cst_p
= false;
4661 if (idx_objsize
!= UINT_MAX
)
4662 if (tree size
= gimple_call_arg (info
.callstmt
, idx_objsize
))
4663 if (tree_fits_uhwi_p (size
))
4664 objsize
= tree_to_uhwi (size
);
4666 if (info
.bounded
&& !dstsize
)
4668 /* As a special case, when the explicitly specified destination
4669 size argument (to a bounded function like snprintf) is zero
4670 it is a request to determine the number of bytes on output
4671 without actually producing any. Pretend the size is
4672 unlimited in this case. */
4673 info
.objsize
= HOST_WIDE_INT_MAX
;
4674 info
.nowrite
= dstsize_cst_p
;
4678 /* For calls to non-bounded functions or to those of bounded
4679 functions with a non-zero size, warn if the destination
4681 if (dstptr
&& integer_zerop (dstptr
))
4683 /* This is diagnosed with -Wformat only when the null is a constant
4684 pointer. The warning here diagnoses instances where the pointer
4686 location_t loc
= gimple_location (info
.callstmt
);
4687 warning_at (EXPR_LOC_OR_LOC (dstptr
, loc
),
4688 info
.warnopt (), "null destination pointer");
4692 /* Set the object size to the smaller of the two arguments
4693 of both have been specified and they're not equal. */
4694 info
.objsize
= dstsize
< objsize
? dstsize
: objsize
;
4697 && dstsize
< target_size_max () / 2 && objsize
< dstsize
4698 /* Avoid warning if -Wstringop-overflow is specified since
4699 it also warns for the same thing though only for the
4700 checking built-ins. */
4701 && (idx_objsize
== UINT_MAX
4702 || !warn_stringop_overflow
))
4704 warning_at (gimple_location (info
.callstmt
), info
.warnopt (),
4705 "specified bound %wu exceeds the size %wu "
4706 "of the destination object", dstsize
, objsize
);
4710 /* Determine if the format argument may be null and warn if not
4711 and if the argument is null. */
4712 if (integer_zerop (info
.format
)
4713 && gimple_call_builtin_p (info
.callstmt
, BUILT_IN_NORMAL
))
4715 location_t loc
= gimple_location (info
.callstmt
);
4716 warning_at (EXPR_LOC_OR_LOC (info
.format
, loc
),
4717 info
.warnopt (), "null format string");
4721 info
.fmtstr
= get_format_string (info
.format
, &info
.fmtloc
);
4727 /* Compute the origin of the destination pointer and its offset
4728 from the base object/pointer if possible. */
4729 info
.dst_offset
= 0;
4730 info
.dst_origin
= get_origin_and_offset (dstptr
, &info
.dst_field
,
4734 /* The result is the number of bytes output by the formatted function,
4735 including the terminating NUL. */
4738 /* I/O functions with no destination argument (i.e., all forms of fprintf
4739 and printf) may fail under any conditions. Others (i.e., all forms of
4740 sprintf) may only fail under specific conditions determined for each
4741 directive. Clear POSUNDER4K for the former set of functions and set
4742 it to true for the latter (it can only be cleared later, but it is
4743 never set to true again). */
4744 res
.posunder4k
= posunder4k
&& dstptr
;
4746 bool success
= compute_format_length (info
, &res
, ptr_qry
);
4748 suppress_warning (info
.callstmt
, info
.warnopt ());
4750 /* When optimizing and the printf return value optimization is enabled,
4751 attempt to substitute the computed result for the return value of
4752 the call. Avoid this optimization when -frounding-math is in effect
4753 and the format string contains a floating point directive. */
4754 bool call_removed
= false;
4755 if (success
&& optimize
> 0)
4757 /* Save a copy of the iterator pointing at the call. The iterator
4758 may change to point past the call in try_substitute_return_value
4759 but the original value is needed in try_simplify_call. */
4760 gimple_stmt_iterator gsi_call
= *gsi
;
4762 if (flag_printf_return_value
4763 && (!flag_rounding_math
|| !res
.floating
))
4764 call_removed
= try_substitute_return_value (gsi
, info
, res
);
4767 try_simplify_call (&gsi_call
, info
, res
);
4770 return call_removed
;