PR middle-end/78519 - missing warning for sprintf %s with null pointer
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
bloba91dcb8fc0b1668d744a09dfde74dc52bc1c9806
1 /* Copyright (C) 2016 Free Software Foundation, Inc.
2 Contributed by Martin Sebor <msebor@redhat.com>.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /* This file implements the printf-return-value pass. The pass does
21 two things: 1) it analyzes calls to formatted output functions like
22 sprintf looking for possible buffer overflows and calls to bounded
23 functions like snprintf for early truncation (and under the control
24 of the -Wformat-length option issues warnings), and 2) under the
25 control of the -fprintf-return-value option it folds the return
26 value of safe calls into constants, making it possible to eliminate
27 code that depends on the value of those constants.
29 For all functions (bounded or not) the pass uses the size of the
30 destination object. That means that it will diagnose calls to
31 snprintf not on the basis of the size specified by the function's
32 second argument but rathger on the basis of the size the first
33 argument points to (if possible). For bound-checking built-ins
34 like __builtin___snprintf_chk the pass uses the size typically
35 determined by __builtin_object_size and passed to the built-in
36 by the Glibc inline wrapper.
38 The pass handles all forms standard sprintf format directives,
39 including character, integer, floating point, pointer, and strings,
40 with the standard C flags, widths, and precisions. For integers
41 and strings it computes the length of output itself. For floating
42 point it uses MPFR to fornmat known constants with up and down
43 rounding and uses the resulting range of output lengths. For
44 strings it uses the length of string literals and the sizes of
45 character arrays that a character pointer may point to as a bound
46 on the longest string. */
48 #include "config.h"
49 #include "system.h"
50 #include "coretypes.h"
51 #include "backend.h"
52 #include "tree.h"
53 #include "gimple.h"
54 #include "tree-pass.h"
55 #include "ssa.h"
56 #include "gimple-fold.h"
57 #include "gimple-pretty-print.h"
58 #include "diagnostic-core.h"
59 #include "fold-const.h"
60 #include "gimple-iterator.h"
61 #include "tree-ssa.h"
62 #include "tree-object-size.h"
63 #include "params.h"
64 #include "tree-cfg.h"
65 #include "tree-ssa-propagate.h"
66 #include "calls.h"
67 #include "cfgloop.h"
68 #include "intl.h"
70 #include "builtins.h"
71 #include "stor-layout.h"
73 #include "realmpfr.h"
74 #include "target.h"
76 #include "cpplib.h"
77 #include "input.h"
78 #include "toplev.h"
79 #include "substring-locations.h"
80 #include "diagnostic.h"
82 /* The likely worst case value of MB_LEN_MAX for the target, large enough
83 for UTF-8. Ideally, this would be obtained by a target hook if it were
84 to be used for optimization but it's good enough as is for warnings. */
85 #define target_mb_len_max 6
87 /* The maximum number of bytes a single non-string directive can result
88 in. This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
89 LDBL_MAX_10_EXP of 4932. */
90 #define IEEE_MAX_10_EXP 4932
91 #define target_dir_max() (target_int_max () + IEEE_MAX_10_EXP + 2)
93 namespace {
95 const pass_data pass_data_sprintf_length = {
96 GIMPLE_PASS, // pass type
97 "printf-return-value", // pass name
98 OPTGROUP_NONE, // optinfo_flags
99 TV_NONE, // tv_id
100 PROP_cfg, // properties_required
101 0, // properties_provided
102 0, // properties_destroyed
103 0, // properties_start
104 0, // properties_finish
107 struct format_result;
109 class pass_sprintf_length : public gimple_opt_pass
111 bool fold_return_value;
113 public:
114 pass_sprintf_length (gcc::context *ctxt)
115 : gimple_opt_pass (pass_data_sprintf_length, ctxt),
116 fold_return_value (false)
119 opt_pass * clone () { return new pass_sprintf_length (m_ctxt); }
121 virtual bool gate (function *);
123 virtual unsigned int execute (function *);
125 void set_pass_param (unsigned int n, bool param)
127 gcc_assert (n == 0);
128 fold_return_value = param;
131 void handle_gimple_call (gimple_stmt_iterator*);
133 struct call_info;
134 bool compute_format_length (const call_info &, format_result *);
137 bool
138 pass_sprintf_length::gate (function *)
140 /* Run the pass iff -Warn-format-length is specified and either
141 not optimizing and the pass is being invoked early, or when
142 optimizing and the pass is being invoked during optimization
143 (i.e., "late"). */
144 return ((warn_format_length > 0 || flag_printf_return_value)
145 && (optimize > 0) == fold_return_value);
148 /* The result of a call to a formatted function. */
150 struct format_result
152 /* Number of characters written by the formatted function, exact,
153 minimum and maximum when an exact number cannot be determined.
154 Setting the minimum to HOST_WIDE_INT_MAX disables all length
155 tracking for the remainder of the format string.
156 Setting either of the other two members to HOST_WIDE_INT_MAX
157 disables the exact or maximum length tracking, respectively,
158 but continues to track the maximum. */
159 unsigned HOST_WIDE_INT number_chars;
160 unsigned HOST_WIDE_INT number_chars_min;
161 unsigned HOST_WIDE_INT number_chars_max;
163 /* True when the range given by NUMBER_CHARS_MIN and NUMBER_CHARS_MAX
164 can be relied on for value range propagation, false otherwise.
165 This means that BOUNDED must not be set if the number of bytes
166 produced by any directive is unspecified or implementation-
167 defined (unless the implementation's behavior is known and
168 determined via a target hook).
169 Note that BOUNDED only implies that the length of a function's
170 output is known to be within some range, not that it's constant
171 and a candidate for string folding. BOUNDED is a stronger
172 guarantee than KNOWNRANGE. */
173 bool bounded;
175 /* True when the range above is obtained from known values of
176 directive arguments or their bounds and not the result of
177 heuristics that depend on warning levels. It is used to
178 issue stricter diagnostics in cases where strings of unknown
179 lengths are bounded by the arrays they are determined to
180 refer to. KNOWNRANGE must not be used to set the range of
181 the return value of a call. */
182 bool knownrange;
184 /* True when the output of the formatted call is constant (and
185 thus a candidate for string constant folding). This is rare
186 and typically requires that the arguments of all directives
187 are also constant. CONSTANT implies BOUNDED. */
188 bool constant;
190 /* True if no individual directive resulted in more than 4095 bytes
191 of output (the total NUMBER_CHARS might be greater). */
192 bool under4k;
194 /* True when a floating point directive has been seen in the format
195 string. */
196 bool floating;
198 /* True when an intermediate result has caused a warning. Used to
199 avoid issuing duplicate warnings while finishing the processing
200 of a call. */
201 bool warned;
203 /* Preincrement the number of output characters by 1. */
204 format_result& operator++ ()
206 return *this += 1;
209 /* Postincrement the number of output characters by 1. */
210 format_result operator++ (int)
212 format_result prev (*this);
213 *this += 1;
214 return prev;
217 /* Increment the number of output characters by N. */
218 format_result& operator+= (unsigned HOST_WIDE_INT n)
220 gcc_assert (n < HOST_WIDE_INT_MAX);
222 if (number_chars < HOST_WIDE_INT_MAX)
223 number_chars += n;
224 if (number_chars_min < HOST_WIDE_INT_MAX)
225 number_chars_min += n;
226 if (number_chars_max < HOST_WIDE_INT_MAX)
227 number_chars_max += n;
228 return *this;
232 /* Return the value of INT_MIN for the target. */
234 static inline HOST_WIDE_INT
235 target_int_min ()
237 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
240 /* Return the value of INT_MAX for the target. */
242 static inline unsigned HOST_WIDE_INT
243 target_int_max ()
245 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
248 /* Return the value of SIZE_MAX for the target. */
250 static inline unsigned HOST_WIDE_INT
251 target_size_max ()
253 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
256 /* Return the constant initial value of DECL if available or DECL
257 otherwise. Same as the synonymous function in c/c-typeck.c. */
259 static tree
260 decl_constant_value (tree decl)
262 if (/* Don't change a variable array bound or initial value to a constant
263 in a place where a variable is invalid. Note that DECL_INITIAL
264 isn't valid for a PARM_DECL. */
265 current_function_decl != 0
266 && TREE_CODE (decl) != PARM_DECL
267 && !TREE_THIS_VOLATILE (decl)
268 && TREE_READONLY (decl)
269 && DECL_INITIAL (decl) != 0
270 && TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK
271 /* This is invalid if initial value is not constant.
272 If it has either a function call, a memory reference,
273 or a variable, then re-evaluating it could give different results. */
274 && TREE_CONSTANT (DECL_INITIAL (decl))
275 /* Check for cases where this is sub-optimal, even though valid. */
276 && TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)
277 return DECL_INITIAL (decl);
278 return decl;
281 /* Given FORMAT, set *PLOC to the source location of the format string
282 and return the format string if it is known or null otherwise. */
284 static const char*
285 get_format_string (tree format, location_t *ploc)
287 if (VAR_P (format))
289 /* Pull out a constant value if the front end didn't. */
290 format = decl_constant_value (format);
291 STRIP_NOPS (format);
294 if (integer_zerop (format))
296 /* FIXME: Diagnose null format string if it hasn't been diagnosed
297 by -Wformat (the latter diagnoses only nul pointer constants,
298 this pass can do better). */
299 return NULL;
302 HOST_WIDE_INT offset = 0;
304 if (TREE_CODE (format) == POINTER_PLUS_EXPR)
306 tree arg0 = TREE_OPERAND (format, 0);
307 tree arg1 = TREE_OPERAND (format, 1);
308 STRIP_NOPS (arg0);
309 STRIP_NOPS (arg1);
311 if (TREE_CODE (arg1) != INTEGER_CST)
312 return NULL;
314 format = arg0;
316 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
317 if (!cst_and_fits_in_hwi (arg1))
318 return NULL;
320 offset = int_cst_value (arg1);
323 if (TREE_CODE (format) != ADDR_EXPR)
324 return NULL;
326 *ploc = EXPR_LOC_OR_LOC (format, input_location);
328 format = TREE_OPERAND (format, 0);
330 if (TREE_CODE (format) == ARRAY_REF
331 && tree_fits_shwi_p (TREE_OPERAND (format, 1))
332 && (offset += tree_to_shwi (TREE_OPERAND (format, 1))) >= 0)
333 format = TREE_OPERAND (format, 0);
335 if (offset < 0)
336 return NULL;
338 tree array_init;
339 tree array_size = NULL_TREE;
341 if (VAR_P (format)
342 && TREE_CODE (TREE_TYPE (format)) == ARRAY_TYPE
343 && (array_init = decl_constant_value (format)) != format
344 && TREE_CODE (array_init) == STRING_CST)
346 /* Extract the string constant initializer. Note that this may
347 include a trailing NUL character that is not in the array (e.g.
348 const char a[3] = "foo";). */
349 array_size = DECL_SIZE_UNIT (format);
350 format = array_init;
353 if (TREE_CODE (format) != STRING_CST)
354 return NULL;
356 if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format))) != char_type_node)
358 /* Wide format string. */
359 return NULL;
362 const char *fmtstr = TREE_STRING_POINTER (format);
363 unsigned fmtlen = TREE_STRING_LENGTH (format);
365 if (array_size)
367 /* Variable length arrays can't be initialized. */
368 gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
370 if (tree_fits_shwi_p (array_size))
372 HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
373 if (array_size_value > 0
374 && array_size_value == (int) array_size_value
375 && fmtlen > array_size_value)
376 fmtlen = array_size_value;
379 if (offset)
381 if (offset >= fmtlen)
382 return NULL;
384 fmtstr += offset;
385 fmtlen -= offset;
388 if (fmtlen < 1 || fmtstr[--fmtlen] != 0)
390 /* FIXME: Diagnose an unterminated format string if it hasn't been
391 diagnosed by -Wformat. Similarly to a null format pointer,
392 -Wformay diagnoses only nul pointer constants, this pass can
393 do better). */
394 return NULL;
397 return fmtstr;
400 /* The format_warning_at_substring function is not used here in a way
401 that makes using attribute format viable. Suppress the warning. */
403 #pragma GCC diagnostic push
404 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
406 /* For convenience and brevity. */
408 static bool
409 (* const fmtwarn) (const substring_loc &, const source_range *,
410 const char *, int, const char *, ...)
411 = format_warning_at_substring;
413 /* Format length modifiers. */
415 enum format_lengths
417 FMT_LEN_none,
418 FMT_LEN_hh, // char argument
419 FMT_LEN_h, // short
420 FMT_LEN_l, // long
421 FMT_LEN_ll, // long long
422 FMT_LEN_L, // long double (and GNU long long)
423 FMT_LEN_z, // size_t
424 FMT_LEN_t, // ptrdiff_t
425 FMT_LEN_j // intmax_t
429 /* A minimum and maximum number of bytes. */
431 struct result_range
433 unsigned HOST_WIDE_INT min, max;
436 /* Description of the result of conversion either of a single directive
437 or the whole format string. */
439 struct fmtresult
441 fmtresult ()
442 : argmin (), argmax (), knownrange (), bounded (), constant (), nullp ()
444 range.min = range.max = HOST_WIDE_INT_MAX;
447 /* The range a directive's argument is in. */
448 tree argmin, argmax;
450 /* The minimum and maximum number of bytes that a directive
451 results in on output for an argument in the range above. */
452 result_range range;
454 /* True when the range above is obtained from a known value of
455 a directive's argument or its bounds and not the result of
456 heuristics that depend on warning levels. */
457 bool knownrange;
459 /* True when the range is the result of an argument determined
460 to be bounded to a subrange of its type or value (such as by
461 value range propagation or the width of the formt directive),
462 false otherwise. */
463 bool bounded;
465 /* True when the output of a directive is constant. This is rare
466 and typically requires that the argument(s) of the directive
467 are also constant (such as determined by constant propagation,
468 though not value range propagation). */
469 bool constant;
471 /* True when the argument is a null pointer. */
472 bool nullp;
475 /* Description of a conversion specification. */
477 struct conversion_spec
479 /* A bitmap of flags, one for each character. */
480 unsigned flags[256 / sizeof (int)];
481 /* Numeric width as in "%8x". */
482 int width;
483 /* Numeric precision as in "%.32s". */
484 int precision;
486 /* Width specified via the '*' character. */
487 tree star_width;
488 /* Precision specified via the asterisk. */
489 tree star_precision;
491 /* Length modifier. */
492 format_lengths modifier;
494 /* Format specifier character. */
495 char specifier;
497 /* Numeric width was given. */
498 unsigned have_width: 1;
499 /* Numeric precision was given. */
500 unsigned have_precision: 1;
501 /* Non-zero when certain flags should be interpreted even for a directive
502 that normally doesn't accept them (used when "%p" with flags such as
503 space or plus is interepreted as a "%x". */
504 unsigned force_flags: 1;
506 /* Format conversion function that given a conversion specification
507 and an argument returns the formatting result. */
508 fmtresult (*fmtfunc) (const conversion_spec &, tree);
510 /* Return True when a the format flag CHR has been used. */
511 bool get_flag (char chr) const
513 unsigned char c = chr & 0xff;
514 return (flags[c / (CHAR_BIT * sizeof *flags)]
515 & (1U << (c % (CHAR_BIT * sizeof *flags))));
518 /* Make a record of the format flag CHR having been used. */
519 void set_flag (char chr)
521 unsigned char c = chr & 0xff;
522 flags[c / (CHAR_BIT * sizeof *flags)]
523 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
526 /* Reset the format flag CHR. */
527 void clear_flag (char chr)
529 unsigned char c = chr & 0xff;
530 flags[c / (CHAR_BIT * sizeof *flags)]
531 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
535 /* Return the logarithm of X in BASE. */
537 static int
538 ilog (unsigned HOST_WIDE_INT x, int base)
540 int res = 0;
543 ++res;
544 x /= base;
545 } while (x);
546 return res;
549 /* Return the number of bytes resulting from converting into a string
550 the INTEGER_CST tree node X in BASE. PLUS indicates whether 1 for
551 a plus sign should be added for positive numbers, and PREFIX whether
552 the length of an octal ('O') or hexadecimal ('0x') prefix should be
553 added for nonzero numbers. Return -1 if X cannot be represented. */
555 static int
556 tree_digits (tree x, int base, bool plus, bool prefix)
558 unsigned HOST_WIDE_INT absval;
560 int res;
562 if (TYPE_UNSIGNED (TREE_TYPE (x)))
564 if (tree_fits_uhwi_p (x))
566 absval = tree_to_uhwi (x);
567 res = plus;
569 else
570 return -1;
572 else
574 if (tree_fits_shwi_p (x))
576 HOST_WIDE_INT i = tree_to_shwi (x);
577 if (i < 0)
579 absval = -i;
580 res = 1;
582 else
584 absval = i;
585 res = plus;
588 else
589 return -1;
592 res += ilog (absval, base);
594 if (prefix && absval)
596 if (base == 8)
597 res += 1;
598 else if (base == 16)
599 res += 2;
602 return res;
605 /* Given the formatting result described by RES and NAVAIL, the number
606 of available in the destination, return the number of bytes remaining
607 in the destination. */
609 static inline result_range
610 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
612 result_range range;
614 if (HOST_WIDE_INT_MAX <= navail)
616 range.min = range.max = navail;
617 return range;
620 if (res.number_chars < navail)
622 range.min = range.max = navail - res.number_chars;
624 else if (res.number_chars_min < navail)
626 range.max = navail - res.number_chars_min;
628 else
629 range.max = 0;
631 if (res.number_chars_max < navail)
632 range.min = navail - res.number_chars_max;
633 else
634 range.min = 0;
636 return range;
639 /* Given the formatting result described by RES and NAVAIL, the number
640 of available in the destination, return the minimum number of bytes
641 remaining in the destination. */
643 static inline unsigned HOST_WIDE_INT
644 min_bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
646 if (HOST_WIDE_INT_MAX <= navail)
647 return navail;
649 if (1 < warn_format_length || res.knownrange)
651 /* At level 2, or when all directives output an exact number
652 of bytes or when their arguments were bounded by known
653 ranges, use the greater of the two byte counters if it's
654 valid to compute the result. */
655 if (res.number_chars_max < HOST_WIDE_INT_MAX)
656 navail -= res.number_chars_max;
657 else if (res.number_chars < HOST_WIDE_INT_MAX)
658 navail -= res.number_chars;
659 else if (res.number_chars_min < HOST_WIDE_INT_MAX)
660 navail -= res.number_chars_min;
662 else
664 /* At level 1 use the smaller of the byte counters to compute
665 the result. */
666 if (res.number_chars < HOST_WIDE_INT_MAX)
667 navail -= res.number_chars;
668 else if (res.number_chars_min < HOST_WIDE_INT_MAX)
669 navail -= res.number_chars_min;
670 else if (res.number_chars_max < HOST_WIDE_INT_MAX)
671 navail -= res.number_chars_max;
674 if (navail > HOST_WIDE_INT_MAX)
675 navail = 0;
677 return navail;
680 /* Description of a call to a formatted function. */
682 struct pass_sprintf_length::call_info
684 /* Function call statement. */
685 gimple *callstmt;
687 /* Function called. */
688 tree func;
690 /* Called built-in function code. */
691 built_in_function fncode;
693 /* Format argument and format string extracted from it. */
694 tree format;
695 const char *fmtstr;
697 /* The location of the format argument. */
698 location_t fmtloc;
700 /* The destination object size for __builtin___xxx_chk functions
701 typically determined by __builtin_object_size, or -1 if unknown. */
702 unsigned HOST_WIDE_INT objsize;
704 /* Number of the first variable argument. */
705 unsigned HOST_WIDE_INT argidx;
707 /* True for functions like snprintf that specify the size of
708 the destination, false for others like sprintf that don't. */
709 bool bounded;
711 /* True for bounded functions like snprintf that specify a zero-size
712 buffer as a request to compute the size of output without actually
713 writing any. */
714 bool nowrite;
717 /* Return the result of formatting the '%%' directive. */
719 static fmtresult
720 format_percent (const conversion_spec &, tree)
722 fmtresult res;
723 res.argmin = res.argmax = NULL_TREE;
724 res.range.min = res.range.max = 1;
725 res.bounded = res.constant = true;
726 return res;
730 /* Compute intmax_type_node and uintmax_type_node similarly to how
731 tree.c builds size_type_node. */
733 static void
734 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
736 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
738 *pintmax = integer_type_node;
739 *puintmax = unsigned_type_node;
741 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
743 *pintmax = long_integer_type_node;
744 *puintmax = long_unsigned_type_node;
746 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
748 *pintmax = long_long_integer_type_node;
749 *puintmax = long_long_unsigned_type_node;
751 else
753 for (int i = 0; i < NUM_INT_N_ENTS; i++)
754 if (int_n_enabled_p[i])
756 char name[50];
757 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
759 if (strcmp (name, UINTMAX_TYPE) == 0)
761 *pintmax = int_n_trees[i].signed_type;
762 *puintmax = int_n_trees[i].unsigned_type;
763 return;
766 gcc_unreachable ();
770 /* Set *PWIDTH and *PPREC according to the width and precision specified
771 in SPEC. Each is set to HOST_WIDE_INT_MIN when the corresponding
772 field is specified but unknown, to zero for width and -1 for precision,
773 respectively when it's not specified, or to a non-negative value
774 corresponding to the known value. */
776 static void
777 get_width_and_precision (const conversion_spec &spec,
778 HOST_WIDE_INT *pwidth, HOST_WIDE_INT *pprec)
780 HOST_WIDE_INT width = spec.have_width ? spec.width : 0;
781 HOST_WIDE_INT prec = spec.have_precision ? spec.precision : -1;
783 if (spec.star_width)
785 if (TREE_CODE (spec.star_width) == INTEGER_CST)
787 width = tree_to_shwi (spec.star_width);
788 if (width < 0)
790 if (width == HOST_WIDE_INT_MIN)
792 /* Avoid undefined behavior due to negating a minimum.
793 This case will be diagnosed since it will result in
794 more than INT_MAX bytes on output, either by the
795 directive itself (when INT_MAX < HOST_WIDE_INT_MAX)
796 or by the format function itself. */
797 width = HOST_WIDE_INT_MAX;
799 else
800 width = -width;
803 else
804 width = HOST_WIDE_INT_MIN;
807 if (spec.star_precision)
809 if (TREE_CODE (spec.star_precision) == INTEGER_CST)
811 prec = tree_to_shwi (spec.star_precision);
812 if (prec < 0)
813 prec = -1;
815 else
816 prec = HOST_WIDE_INT_MIN;
819 *pwidth = width;
820 *pprec = prec;
823 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
824 argument, due to the conversion from either *ARGMIN or *ARGMAX to
825 the type of the directive's formal argument it's possible for both
826 to result in the same number of bytes or a range of bytes that's
827 less than the number of bytes that would result from formatting
828 some other value in the range [*ARGMIN, *ARGMAX]. This can be
829 determined by checking for the actual argument being in the range
830 of the type of the directive. If it isn't it must be assumed to
831 take on the full range of the directive's type.
832 Return true when the range has been adjusted to the full unsigned
833 range of DIRTYPE, or [0, DIRTYPE_MAX], and false otherwise. */
835 static bool
836 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
838 tree argtype = TREE_TYPE (*argmin);
839 unsigned argprec = TYPE_PRECISION (argtype);
840 unsigned dirprec = TYPE_PRECISION (dirtype);
842 /* If the actual argument and the directive's argument have the same
843 precision and sign there can be no overflow and so there is nothing
844 to adjust. */
845 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
846 return false;
848 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
849 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
851 if (TREE_CODE (*argmin) == INTEGER_CST
852 && TREE_CODE (*argmax) == INTEGER_CST
853 && (dirprec >= argprec
854 || integer_zerop (int_const_binop (RSHIFT_EXPR,
855 int_const_binop (MINUS_EXPR,
856 *argmax,
857 *argmin),
858 size_int (dirprec)))))
860 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
861 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
863 /* If *ARGMIN is still less than *ARGMAX the conversion above
864 is safe. Otherwise, it has overflowed and would be unsafe. */
865 if (tree_int_cst_le (*argmin, *argmax))
866 return false;
869 tree dirmin = TYPE_MIN_VALUE (dirtype);
870 tree dirmax = TYPE_MAX_VALUE (dirtype);
872 if (TYPE_UNSIGNED (dirtype))
874 *argmin = dirmin;
875 *argmax = dirmax;
877 else
879 *argmin = integer_zero_node;
880 *argmax = dirmin;
883 return true;
886 /* Return a range representing the minimum and maximum number of bytes
887 that the conversion specification SPEC will write on output for the
888 integer argument ARG when non-null. ARG may be null (for vararg
889 functions). */
891 static fmtresult
892 format_integer (const conversion_spec &spec, tree arg)
894 tree intmax_type_node;
895 tree uintmax_type_node;
897 /* Set WIDTH and PRECISION based on the specification. */
898 HOST_WIDE_INT width;
899 HOST_WIDE_INT prec;
900 get_width_and_precision (spec, &width, &prec);
902 bool sign = spec.specifier == 'd' || spec.specifier == 'i';
904 /* The type of the "formal" argument expected by the directive. */
905 tree dirtype = NULL_TREE;
907 /* Determine the expected type of the argument from the length
908 modifier. */
909 switch (spec.modifier)
911 case FMT_LEN_none:
912 if (spec.specifier == 'p')
913 dirtype = ptr_type_node;
914 else
915 dirtype = sign ? integer_type_node : unsigned_type_node;
916 break;
918 case FMT_LEN_h:
919 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
920 break;
922 case FMT_LEN_hh:
923 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
924 break;
926 case FMT_LEN_l:
927 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
928 break;
930 case FMT_LEN_L:
931 case FMT_LEN_ll:
932 dirtype = (sign
933 ? long_long_integer_type_node
934 : long_long_unsigned_type_node);
935 break;
937 case FMT_LEN_z:
938 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
939 break;
941 case FMT_LEN_t:
942 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
943 break;
945 case FMT_LEN_j:
946 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
947 dirtype = sign ? intmax_type_node : uintmax_type_node;
948 break;
950 default:
951 return fmtresult ();
954 /* The type of the argument to the directive, either deduced from
955 the actual non-constant argument if one is known, or from
956 the directive itself when none has been provided because it's
957 a va_list. */
958 tree argtype = NULL_TREE;
960 if (!arg)
962 /* When the argument has not been provided, use the type of
963 the directive's argument as an approximation. This will
964 result in false positives for directives like %i with
965 arguments with smaller precision (such as short or char). */
966 argtype = dirtype;
968 else if (TREE_CODE (arg) == INTEGER_CST)
970 /* When a constant argument has been provided use its value
971 rather than type to determine the length of the output. */
973 /* Base to format the number in. */
974 int base;
976 /* True when a signed conversion is preceded by a sign or space. */
977 bool maybesign = false;
979 switch (spec.specifier)
981 case 'd':
982 case 'i':
983 /* Space and '+' are only meaningful for signed conversions. */
984 maybesign = spec.get_flag (' ') | spec.get_flag ('+');
985 base = 10;
986 break;
987 case 'u':
988 base = 10;
989 break;
990 case 'o':
991 base = 8;
992 break;
993 case 'X':
994 case 'x':
995 base = 16;
996 break;
997 default:
998 gcc_unreachable ();
1001 HOST_WIDE_INT len;
1003 if ((prec == HOST_WIDE_INT_MIN || prec == 0) && integer_zerop (arg))
1005 /* As a special case, a precision of zero with a zero argument
1006 results in zero bytes except in base 8 when the '#' flag is
1007 specified, and for signed conversions in base 8 and 10 when
1008 flags when either the space or '+' flag has been specified
1009 when it results in just one byte (with width having the normal
1010 effect). This must extend to the case of a specified precision
1011 with an unknown value because it can be zero. */
1012 len = ((base == 8 && spec.get_flag ('#')) || maybesign);
1014 else
1016 /* Convert the argument to the type of the directive. */
1017 arg = fold_convert (dirtype, arg);
1019 /* True when a conversion is preceded by a prefix indicating the base
1020 of the argument (octal or hexadecimal). */
1021 bool maybebase = spec.get_flag ('#');
1022 len = tree_digits (arg, base, maybesign, maybebase);
1024 if (len < prec)
1025 len = prec;
1028 if (len < width)
1029 len = width;
1031 /* The minimum and maximum number of bytes produced by the directive. */
1032 fmtresult res;
1034 res.range.min = len;
1036 /* The upper bound of the number of bytes is unlimited when either
1037 width or precision is specified but its value is unknown, and
1038 the same as the lower bound otherwise. */
1039 if (width == HOST_WIDE_INT_MIN || prec == HOST_WIDE_INT_MIN)
1041 res.range.max = HOST_WIDE_INT_MAX;
1043 else
1045 res.range.max = len;
1046 res.bounded = true;
1047 res.constant = true;
1048 res.knownrange = true;
1049 res.bounded = true;
1052 return res;
1054 else if (TREE_CODE (TREE_TYPE (arg)) == INTEGER_TYPE
1055 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1056 /* Determine the type of the provided non-constant argument. */
1057 argtype = TREE_TYPE (arg);
1058 else
1059 /* Don't bother with invalid arguments since they likely would
1060 have already been diagnosed, and disable any further checking
1061 of the format string by returning [-1, -1]. */
1062 return fmtresult ();
1064 fmtresult res;
1066 /* The result is bounded unless width or precision has been specified
1067 whose value is unknown. */
1068 res.bounded = width != HOST_WIDE_INT_MIN && prec != HOST_WIDE_INT_MIN;
1070 /* Using either the range the non-constant argument is in, or its
1071 type (either "formal" or actual), create a range of values that
1072 constrain the length of output given the warning level. */
1073 tree argmin = NULL_TREE;
1074 tree argmax = NULL_TREE;
1076 if (arg
1077 && TREE_CODE (arg) == SSA_NAME
1078 && TREE_CODE (argtype) == INTEGER_TYPE)
1080 /* Try to determine the range of values of the integer argument
1081 (range information is not available for pointers). */
1082 wide_int min, max;
1083 enum value_range_type range_type = get_range_info (arg, &min, &max);
1084 if (range_type == VR_RANGE)
1086 argmin = build_int_cst (argtype, wi::fits_uhwi_p (min)
1087 ? min.to_uhwi () : min.to_shwi ());
1088 argmax = build_int_cst (argtype, wi::fits_uhwi_p (max)
1089 ? max.to_uhwi () : max.to_shwi ());
1091 /* Set KNOWNRANGE if the argument is in a known subrange
1092 of the directive's type (KNOWNRANGE may be reset below). */
1093 res.knownrange
1094 = (!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1095 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax));
1097 res.argmin = argmin;
1098 res.argmax = argmax;
1100 else if (range_type == VR_ANTI_RANGE)
1102 /* Handle anti-ranges if/when bug 71690 is resolved. */
1104 else if (range_type == VR_VARYING)
1106 /* The argument here may be the result of promoting the actual
1107 argument to int. Try to determine the type of the actual
1108 argument before promotion and narrow down its range that
1109 way. */
1110 gimple *def = SSA_NAME_DEF_STMT (arg);
1111 if (is_gimple_assign (def))
1113 tree_code code = gimple_assign_rhs_code (def);
1114 if (code == INTEGER_CST)
1116 arg = gimple_assign_rhs1 (def);
1117 return format_integer (spec, arg);
1120 if (code == NOP_EXPR)
1122 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1123 if (TREE_CODE (type) == INTEGER_TYPE
1124 || TREE_CODE (type) == POINTER_TYPE)
1125 argtype = type;
1131 if (!argmin)
1133 /* For an unknown argument (e.g., one passed to a vararg function)
1134 or one whose value range cannot be determined, create a T_MIN
1135 constant if the argument's type is signed and T_MAX otherwise,
1136 and use those to compute the range of bytes that the directive
1137 can output. When precision is specified but unknown, use zero
1138 as the minimum since it results in no bytes on output (unless
1139 width is specified to be greater than 0). */
1140 argmin = build_int_cst (argtype, prec && prec != HOST_WIDE_INT_MIN);
1142 int typeprec = TYPE_PRECISION (dirtype);
1143 int argprec = TYPE_PRECISION (argtype);
1145 if (argprec < typeprec)
1147 if (POINTER_TYPE_P (argtype))
1148 argmax = build_all_ones_cst (argtype);
1149 else if (TYPE_UNSIGNED (argtype))
1150 argmax = TYPE_MAX_VALUE (argtype);
1151 else
1152 argmax = TYPE_MIN_VALUE (argtype);
1154 else
1156 if (POINTER_TYPE_P (dirtype))
1157 argmax = build_all_ones_cst (dirtype);
1158 else if (TYPE_UNSIGNED (dirtype))
1159 argmax = TYPE_MAX_VALUE (dirtype);
1160 else
1161 argmax = TYPE_MIN_VALUE (dirtype);
1164 res.argmin = argmin;
1165 res.argmax = argmax;
1168 if (tree_int_cst_lt (argmax, argmin))
1170 tree tmp = argmax;
1171 argmax = argmin;
1172 argmin = tmp;
1175 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1176 of the directive. If it has been cleared then since ARGMIN and/or
1177 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1178 ARGMAX in the result to include in diagnostics. */
1179 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1181 res.knownrange = false;
1182 res.argmin = argmin;
1183 res.argmax = argmax;
1186 /* Recursively compute the minimum and maximum from the known range,
1187 taking care to swap them if the lower bound results in longer
1188 output than the upper bound (e.g., in the range [-1, 0]. */
1190 if (TYPE_UNSIGNED (dirtype))
1192 /* For unsigned conversions/directives, use the minimum (i.e., 0
1193 or 1) and maximum to compute the shortest and longest output,
1194 respectively. */
1195 res.range.min = format_integer (spec, argmin).range.min;
1196 res.range.max = format_integer (spec, argmax).range.max;
1198 else
1200 /* For signed conversions/directives, use the maximum (i.e., 0)
1201 to compute the shortest output and the minimum (i.e., TYPE_MIN)
1202 to compute the longest output. This is important when precision
1203 is specified but unknown because otherwise both output lengths
1204 would reflect the largest possible precision (i.e., INT_MAX). */
1205 res.range.min = format_integer (spec, argmax).range.min;
1206 res.range.max = format_integer (spec, argmin).range.max;
1209 /* The result is bounded either when the argument is determined to be
1210 (e.g., when it's within some range) or when the minimum and maximum
1211 are the same. That can happen here for example when the specified
1212 width is as wide as the greater of MIN and MAX, as would be the case
1213 with sprintf (d, "%08x", x) with a 32-bit integer x. */
1214 res.bounded |= res.range.min == res.range.max;
1216 if (res.range.max < res.range.min)
1218 unsigned HOST_WIDE_INT tmp = res.range.max;
1219 res.range.max = res.range.min;
1220 res.range.min = tmp;
1223 return res;
1226 /* Return the number of bytes that a format directive consisting of FLAGS,
1227 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1228 would result for argument X under ideal conditions (i.e., if PREC
1229 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1230 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1231 This function works around those problems. */
1233 static unsigned HOST_WIDE_INT
1234 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1235 char spec, char rndspec)
1237 char fmtstr[40];
1239 HOST_WIDE_INT len = strlen (flags);
1241 fmtstr[0] = '%';
1242 memcpy (fmtstr + 1, flags, len);
1243 memcpy (fmtstr + 1 + len, ".*R", 3);
1244 fmtstr[len + 4] = rndspec;
1245 fmtstr[len + 5] = spec;
1246 fmtstr[len + 6] = '\0';
1248 /* Avoid passing negative precisions with larger magnitude to MPFR
1249 to avoid exposing its bugs. (A negative precision is supposed
1250 to be ignored.) */
1251 if (prec < 0)
1252 prec = -1;
1254 HOST_WIDE_INT p = prec;
1256 if (TOUPPER (spec) == 'G')
1258 /* For G/g, precision gives the maximum number of significant
1259 digits which is bounded by LDBL_MAX_10_EXP, or, for a 128
1260 bit IEEE extended precision, 4932. Using twice as much
1261 here should be more than sufficient for any real format. */
1262 if ((IEEE_MAX_10_EXP * 2) < prec)
1263 prec = IEEE_MAX_10_EXP * 2;
1264 p = prec;
1266 else
1268 /* Cap precision arbitrarily at 1KB and add the difference
1269 (if any) to the MPFR result. */
1270 if (1024 < prec)
1271 p = 1024;
1274 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1276 /* Handle the unlikely (impossible?) error by returning more than
1277 the maximum dictated by the function's return type. */
1278 if (len < 0)
1279 return target_dir_max () + 1;
1281 /* Adjust the return value by the difference. */
1282 if (p < prec)
1283 len += prec - p;
1285 return len;
1288 /* Return the number of bytes to format using the format specifier
1289 SPEC the largest value in the real floating TYPE. */
1291 static unsigned HOST_WIDE_INT
1292 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1294 machine_mode mode = TYPE_MODE (type);
1296 /* IBM Extended mode. */
1297 if (MODE_COMPOSITE_P (mode))
1298 mode = DFmode;
1300 /* Get the real type format desription for the target. */
1301 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1302 REAL_VALUE_TYPE rv;
1305 char buf[256];
1306 get_max_float (rfmt, buf, sizeof buf);
1307 real_from_string (&rv, buf);
1310 /* Convert the GCC real value representation with the precision
1311 of the real type to the mpfr_t format with the GCC default
1312 round-to-nearest mode. */
1313 mpfr_t x;
1314 mpfr_init2 (x, rfmt->p);
1315 mpfr_from_real (x, &rv, GMP_RNDN);
1317 /* Return a value one greater to account for the leading minus sign. */
1318 return 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1321 /* Return a range representing the minimum and maximum number of bytes
1322 that the conversion specification SPEC will output for any argument
1323 given the WIDTH and PRECISION (extracted from SPEC). This function
1324 is used when the directive argument or its value isn't known. */
1326 static fmtresult
1327 format_floating (const conversion_spec &spec, HOST_WIDE_INT width,
1328 HOST_WIDE_INT prec)
1330 tree type;
1331 bool ldbl = false;
1333 switch (spec.modifier)
1335 case FMT_LEN_l:
1336 case FMT_LEN_none:
1337 type = double_type_node;
1338 break;
1340 case FMT_LEN_L:
1341 type = long_double_type_node;
1342 ldbl = true;
1343 break;
1345 case FMT_LEN_ll:
1346 type = long_double_type_node;
1347 ldbl = true;
1348 break;
1350 default:
1351 return fmtresult ();
1354 /* The minimum and maximum number of bytes produced by the directive. */
1355 fmtresult res;
1357 /* Log10 of of the maximum number of exponent digits for the type. */
1358 int logexpdigs = 2;
1360 if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
1362 /* The base in which the exponent is represented should always
1363 be 2 in GCC. */
1365 const double log10_2 = .30102999566398119521;
1367 /* Compute T_MAX_EXP for base 2. */
1368 int expdigs = REAL_MODE_FORMAT (TYPE_MODE (type))->emax * log10_2;
1369 logexpdigs = ilog (expdigs, 10);
1372 switch (spec.specifier)
1374 case 'A':
1375 case 'a':
1377 /* The minimum output is "0x.p+0". */
1378 res.range.min = 6 + (prec > 0 ? prec : 0);
1379 res.range.max = (width == INT_MIN
1380 ? HOST_WIDE_INT_MAX
1381 : format_floating_max (type, 'a', prec));
1383 /* The output of "%a" is fully specified only when precision
1384 is explicitly specified and width isn't unknown. */
1385 res.bounded = INT_MIN != width && -1 < prec;
1386 break;
1389 case 'E':
1390 case 'e':
1392 bool sign = spec.get_flag ('+') || spec.get_flag (' ');
1393 /* The minimum output is "[-+]1.234567e+00" regardless
1394 of the value of the actual argument. */
1395 res.range.min = (sign
1396 + 1 /* unit */ + (prec < 0 ? 7 : prec ? prec + 1 : 0)
1397 + 2 /* e+ */ + 2);
1398 /* Unless width is uknown the maximum output is the minimum plus
1399 sign (unless already included), plus the difference between
1400 the minimum exponent of 2 and the maximum exponent for the type. */
1401 res.range.max = (width == INT_MIN
1402 ? HOST_WIDE_INT_M1U
1403 : res.range.min + !sign + logexpdigs - 2);
1405 /* "%e" is fully specified and the range of bytes is bounded
1406 unless width is unknown. */
1407 res.bounded = INT_MIN != width;
1408 break;
1411 case 'F':
1412 case 'f':
1414 /* The minimum output is "1.234567" regardless of the value
1415 of the actual argument. */
1416 res.range.min = 2 + (prec < 0 ? 6 : prec);
1418 /* Compute the maximum just once. */
1419 const HOST_WIDE_INT f_max[] = {
1420 format_floating_max (double_type_node, 'f', prec),
1421 format_floating_max (long_double_type_node, 'f', prec)
1423 res.range.max = width == INT_MIN ? HOST_WIDE_INT_MAX : f_max [ldbl];
1425 /* "%f" is fully specified and the range of bytes is bounded
1426 unless width is unknown. */
1427 res.bounded = INT_MIN != width;
1428 break;
1430 case 'G':
1431 case 'g':
1433 /* The minimum is the same as for '%F'. */
1434 res.range.min = 1;
1436 /* Compute the maximum just once. */
1437 const HOST_WIDE_INT g_max[] = {
1438 format_floating_max (double_type_node, 'g', prec),
1439 format_floating_max (long_double_type_node, 'g', prec)
1441 res.range.max = width == INT_MIN ? HOST_WIDE_INT_MAX : g_max [ldbl];
1443 /* "%g" is fully specified and the range of bytes is bounded
1444 unless width is unknown. */
1445 res.bounded = INT_MIN != width;
1446 break;
1449 default:
1450 return fmtresult ();
1453 if (width > 0)
1455 if (res.range.min < (unsigned)width)
1456 res.range.min = width;
1457 if (res.range.max < (unsigned)width)
1458 res.range.max = width;
1461 return res;
1464 /* Return a range representing the minimum and maximum number of bytes
1465 that the conversion specification SPEC will write on output for the
1466 floating argument ARG. */
1468 static fmtresult
1469 format_floating (const conversion_spec &spec, tree arg)
1471 /* Set WIDTH to -1 when it's not specified, to INT_MIN when it is
1472 specified by the asterisk to an unknown value, and otherwise to
1473 a non-negative value corresponding to the specified width. */
1474 HOST_WIDE_INT width = -1;
1475 HOST_WIDE_INT prec = -1;
1477 /* The minimum and maximum number of bytes produced by the directive. */
1478 fmtresult res;
1479 res.constant = arg && TREE_CODE (arg) == REAL_CST;
1481 if (spec.have_width)
1482 width = spec.width;
1483 else if (spec.star_width)
1485 if (TREE_CODE (spec.star_width) == INTEGER_CST)
1487 width = tree_to_shwi (spec.star_width);
1488 if (width < 0)
1489 width = -width;
1491 else
1492 width = INT_MIN;
1495 if (spec.have_precision)
1496 prec = spec.precision;
1497 else if (spec.star_precision)
1499 if (TREE_CODE (spec.star_precision) == INTEGER_CST)
1500 prec = tree_to_shwi (spec.star_precision);
1501 else
1503 /* FIXME: Handle non-constant precision. */
1504 res.range.min = res.range.max = HOST_WIDE_INT_M1U;
1505 return res;
1508 else if (res.constant && TOUPPER (spec.specifier) != 'A')
1510 /* Specify the precision explicitly since mpfr_sprintf defaults
1511 to zero. */
1512 prec = 6;
1515 if (res.constant)
1517 /* Set up an array to easily iterate over. */
1518 unsigned HOST_WIDE_INT* const minmax[] = {
1519 &res.range.min, &res.range.max
1522 /* Get the real type format desription for the target. */
1523 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1524 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1526 /* Convert the GCC real value representation with the precision
1527 of the real type to the mpfr_t format with the GCC default
1528 round-to-nearest mode. */
1529 mpfr_t mpfrval;
1530 mpfr_init2 (mpfrval, rfmt->p);
1531 mpfr_from_real (mpfrval, rvp, GMP_RNDN);
1533 char fmtstr [40];
1534 char *pfmt = fmtstr;
1536 /* Append flags. */
1537 for (const char *pf = "-+ #0"; *pf; ++pf)
1538 if (spec.get_flag (*pf))
1539 *pfmt++ = *pf;
1541 *pfmt = '\0';
1543 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1545 /* Use the MPFR rounding specifier to round down in the first
1546 iteration and then up. In most but not all cases this will
1547 result in the same number of bytes. */
1548 char rndspec = "DU"[i];
1550 /* Format it and store the result in the corresponding member
1551 of the result struct. */
1552 unsigned HOST_WIDE_INT len
1553 = get_mpfr_format_length (mpfrval, fmtstr, prec,
1554 spec.specifier, rndspec);
1555 if (0 < width && len < (unsigned)width)
1556 len = width;
1558 *minmax[i] = len;
1561 /* The range of output is known even if the result isn't bounded. */
1562 if (width == INT_MIN)
1564 res.knownrange = false;
1565 res.range.max = HOST_WIDE_INT_MAX;
1567 else
1568 res.knownrange = true;
1570 /* The output of all directives except "%a" is fully specified
1571 and so the result is bounded unless it exceeds INT_MAX.
1572 For "%a" the output is fully specified only when precision
1573 is explicitly specified. */
1574 res.bounded = (res.knownrange
1575 && (TOUPPER (spec.specifier) != 'A'
1576 || (0 <= prec && (unsigned) prec < target_int_max ()))
1577 && res.range.min < target_int_max ());
1579 return res;
1582 return format_floating (spec, width, prec);
1585 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1586 strings referenced by the expression STR, or (-1, -1) when not known.
1587 Used by the format_string function below. */
1589 static fmtresult
1590 get_string_length (tree str)
1592 if (!str)
1593 return fmtresult ();
1595 if (tree slen = c_strlen (str, 1))
1597 /* Simply return the length of the string. */
1598 fmtresult res;
1599 res.range.min = res.range.max = tree_to_shwi (slen);
1600 res.bounded = true;
1601 res.constant = true;
1602 res.knownrange = true;
1603 return res;
1606 /* Determine the length of the shortest and longest string referenced
1607 by STR. Strings of unknown lengths are bounded by the sizes of
1608 arrays that subexpressions of STR may refer to. Pointers that
1609 aren't known to point any such arrays result in LENRANGE[1] set
1610 to SIZE_MAX. */
1611 tree lenrange[2];
1612 get_range_strlen (str, lenrange);
1614 if (lenrange [0] || lenrange [1])
1616 fmtresult res;
1618 res.range.min = (tree_fits_uhwi_p (lenrange[0])
1619 ? tree_to_uhwi (lenrange[0]) : 1 < warn_format_length);
1620 res.range.max = (tree_fits_uhwi_p (lenrange[1])
1621 ? tree_to_uhwi (lenrange[1]) : HOST_WIDE_INT_M1U);
1623 /* Set RES.BOUNDED to true if and only if all strings referenced
1624 by STR are known to be bounded (though not necessarily by their
1625 actual length but perhaps by their maximum possible length). */
1626 res.bounded = res.range.max < target_int_max ();
1627 res.knownrange = res.bounded;
1629 /* Set RES.CONSTANT to false even though that may be overly
1630 conservative in rare cases like: 'x ? a : b' where a and
1631 b have the same lengths and consist of the same characters. */
1632 res.constant = false;
1634 return res;
1637 return get_string_length (NULL_TREE);
1640 /* Return the minimum and maximum number of characters formatted
1641 by the '%c' and '%s' format directives and ther wide character
1642 forms for the argument ARG. ARG can be null (for functions
1643 such as vsprinf). */
1645 static fmtresult
1646 format_string (const conversion_spec &spec, tree arg)
1648 /* Set WIDTH and PRECISION based on the specification. */
1649 HOST_WIDE_INT width;
1650 HOST_WIDE_INT prec;
1651 get_width_and_precision (spec, &width, &prec);
1653 fmtresult res;
1655 /* The maximum number of bytes for an unknown wide character argument
1656 to a "%lc" directive adjusted for precision but not field width.
1657 6 is the longest UTF-8 sequence for a single wide character. */
1658 const unsigned HOST_WIDE_INT max_bytes_for_unknown_wc
1659 = (0 <= prec ? prec : 1 < warn_format_length ? 6 : 1);
1661 /* The maximum number of bytes for an unknown string argument to either
1662 a "%s" or "%ls" directive adjusted for precision but not field width. */
1663 const unsigned HOST_WIDE_INT max_bytes_for_unknown_str
1664 = (0 <= prec ? prec : 1 < warn_format_length);
1666 /* The result is bounded unless overriddden for a non-constant string
1667 of an unknown length. */
1668 bool bounded = true;
1670 if (spec.specifier == 'c')
1672 if (spec.modifier == FMT_LEN_l)
1674 /* Positive if the argument is a wide NUL character? */
1675 int nul = (arg && TREE_CODE (arg) == INTEGER_CST
1676 ? integer_zerop (arg) : -1);
1678 /* A '%lc' directive is the same as '%ls' for a two element
1679 wide string character with the second element of NUL, so
1680 when the character is unknown the minimum number of bytes
1681 is the smaller of either 0 (at level 1) or 1 (at level 2)
1682 and WIDTH, and the maximum is MB_CUR_MAX in the selected
1683 locale, which is unfortunately, unknown. */
1684 res.range.min = 1 == warn_format_length ? !nul : nul < 1;
1685 res.range.max = max_bytes_for_unknown_wc;
1686 /* The range above is good enough to issue warnings but not
1687 for value range propagation, so clear BOUNDED. */
1688 res.bounded = false;
1690 else
1692 /* A plain '%c' directive. Its ouput is exactly 1. */
1693 res.range.min = res.range.max = 1;
1694 res.bounded = true;
1695 res.knownrange = true;
1696 res.constant = arg && TREE_CODE (arg) == INTEGER_CST;
1699 else /* spec.specifier == 's' */
1701 /* Compute the range the argument's length can be in. */
1702 fmtresult slen = get_string_length (arg);
1703 if (slen.constant)
1705 gcc_checking_assert (slen.range.min == slen.range.max);
1707 /* A '%s' directive with a string argument with constant length. */
1708 res.range = slen.range;
1710 /* The output of "%s" and "%ls" directives with a constant
1711 string is in a known range unless width of an unknown value
1712 is specified. For "%s" it is the length of the string. For
1713 "%ls" it is in the range [length, length * MB_LEN_MAX].
1714 (The final range can be further constrained by width and
1715 precision but it's always known.) */
1716 res.knownrange = -1 < width;
1718 if (spec.modifier == FMT_LEN_l)
1720 bounded = false;
1722 if (warn_format_length > 1)
1724 /* Leave the minimum number of bytes the wide string
1725 converts to equal to its length and set the maximum
1726 to the worst case length which is the string length
1727 multiplied by MB_LEN_MAX. */
1729 /* It's possible to be smarter about computing the maximum
1730 by scanning the wide string for any 8-bit characters and
1731 if it contains none, using its length for the maximum.
1732 Even though this would be simple to do it's unlikely to
1733 be worth it when dealing with wide characters. */
1734 res.range.max *= target_mb_len_max;
1737 /* For a wide character string, use precision as the maximum
1738 even if precision is greater than the string length since
1739 the number of bytes the string converts to may be greater
1740 (due to MB_CUR_MAX). */
1741 if (0 <= prec)
1742 res.range.max = prec;
1744 else if (0 <= width)
1746 /* The output of a "%s" directive with a constant argument
1747 and constant or no width is bounded. It is constant if
1748 precision is either not specified or it is specified and
1749 its value is known. */
1750 res.bounded = true;
1751 res.constant = prec != HOST_WIDE_INT_MIN;
1753 else if (width == HOST_WIDE_INT_MIN)
1755 /* Specified but unknown width makes the output unbounded. */
1756 res.range.max = HOST_WIDE_INT_MAX;
1759 if (0 <= prec && (unsigned HOST_WIDE_INT)prec < res.range.min)
1761 res.range.min = prec;
1762 res.range.max = prec;
1764 else if (prec == HOST_WIDE_INT_MIN)
1766 /* When precision is specified but not known the lower
1767 bound is assumed to be as low as zero. */
1768 res.range.min = 0;
1771 else if (arg && integer_zerop (arg))
1773 /* Handle null pointer argument. */
1775 fmtresult res;
1776 res.range.min = 0;
1777 res.range.max = HOST_WIDE_INT_MAX;
1778 res.nullp = true;
1779 return res;
1781 else
1783 /* For a '%s' and '%ls' directive with a non-constant string,
1784 the minimum number of characters is the greater of WIDTH
1785 and either 0 in mode 1 or the smaller of PRECISION and 1
1786 in mode 2, and the maximum is PRECISION or -1 to disable
1787 tracking. */
1789 if (0 <= prec)
1791 if (slen.range.min >= target_int_max ())
1792 slen.range.min = 0;
1793 else if ((unsigned HOST_WIDE_INT)prec < slen.range.min)
1794 slen.range.min = prec;
1796 if ((unsigned HOST_WIDE_INT)prec < slen.range.max
1797 || slen.range.max >= target_int_max ())
1798 slen.range.max = prec;
1800 else if (slen.range.min >= target_int_max ())
1802 slen.range.min = max_bytes_for_unknown_str;
1803 slen.range.max = max_bytes_for_unknown_str;
1804 bounded = false;
1807 res.range = slen.range;
1809 /* The output is considered bounded when a precision has been
1810 specified to limit the number of bytes or when the number
1811 of bytes is known or contrained to some range. */
1812 res.bounded = 0 <= prec || slen.bounded;
1813 res.knownrange = slen.knownrange;
1814 res.constant = false;
1818 /* Adjust the lengths for field width. */
1819 if (0 < width)
1821 if (res.range.min < (unsigned HOST_WIDE_INT)width)
1822 res.range.min = width;
1824 if (res.range.max < (unsigned HOST_WIDE_INT)width)
1825 res.range.max = width;
1827 /* Adjust BOUNDED if width happens to make them equal. */
1828 if (res.range.min == res.range.max && res.range.min < target_int_max ()
1829 && bounded)
1830 res.bounded = true;
1833 /* When precision is specified the range of characters on output
1834 is known to be bounded by it. */
1835 if (-1 < width && -1 < prec)
1836 res.knownrange = true;
1838 return res;
1841 /* Compute the length of the output resulting from the conversion
1842 specification SPEC with the argument ARG in a call described by INFO
1843 and update the overall result of the call in *RES. The format directive
1844 corresponding to SPEC starts at CVTBEG and is CVTLEN characters long. */
1846 static void
1847 format_directive (const pass_sprintf_length::call_info &info,
1848 format_result *res, const char *cvtbeg, size_t cvtlen,
1849 const conversion_spec &spec, tree arg)
1851 /* Offset of the beginning of the directive from the beginning
1852 of the format string. */
1853 size_t offset = cvtbeg - info.fmtstr;
1855 /* Create a location for the whole directive from the % to the format
1856 specifier. */
1857 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
1858 offset, offset, offset + cvtlen - 1);
1860 /* Also create a location range for the argument if possible.
1861 This doesn't work for integer literals or function calls. */
1862 source_range argrange;
1863 source_range *pargrange;
1864 if (arg && CAN_HAVE_LOCATION_P (arg))
1866 argrange = EXPR_LOCATION_RANGE (arg);
1867 pargrange = &argrange;
1869 else
1870 pargrange = NULL;
1872 /* Bail when there is no function to compute the output length,
1873 or when minimum length checking has been disabled. */
1874 if (!spec.fmtfunc || res->number_chars_min >= HOST_WIDE_INT_MAX)
1875 return;
1877 /* Compute the (approximate) length of the formatted output. */
1878 fmtresult fmtres = spec.fmtfunc (spec, arg);
1880 /* The overall result is bounded and constant only if the output
1881 of every directive is bounded and constant, respectively. */
1882 res->bounded &= fmtres.bounded;
1883 res->constant &= fmtres.constant;
1885 /* Record whether the output of all directives is known to be
1886 bounded by some maximum, implying that their arguments are
1887 either known exactly or determined to be in a known range
1888 or, for strings, limited by the upper bounds of the arrays
1889 they refer to. */
1890 res->knownrange &= fmtres.knownrange;
1892 if (!fmtres.knownrange)
1894 /* Only when the range is known, check it against the host value
1895 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
1896 INT_MAX precision, which is the longest possible output of any
1897 single directive). That's the largest valid byte count (though
1898 not valid call to a printf-like function because it can never
1899 return such a count). Otherwise, the range doesn't correspond
1900 to known values of the argument. */
1901 if (fmtres.range.max > target_dir_max ())
1903 /* Normalize the MAX counter to avoid having to deal with it
1904 later. The counter can be less than HOST_WIDE_INT_M1U
1905 when compiling for an ILP32 target on an LP64 host. */
1906 fmtres.range.max = HOST_WIDE_INT_M1U;
1907 /* Disable exact and maximum length checking after a failure
1908 to determine the maximum number of characters (for example
1909 for wide characters or wide character strings) but continue
1910 tracking the minimum number of characters. */
1911 res->number_chars_max = HOST_WIDE_INT_M1U;
1912 res->number_chars = HOST_WIDE_INT_M1U;
1915 if (fmtres.range.min > target_dir_max ())
1917 /* Disable exact length checking after a failure to determine
1918 even the minimum number of characters (it shouldn't happen
1919 except in an error) but keep tracking the minimum and maximum
1920 number of characters. */
1921 res->number_chars = HOST_WIDE_INT_M1U;
1922 return;
1926 if (fmtres.nullp)
1928 fmtwarn (dirloc, pargrange, NULL,
1929 OPT_Wformat_length_,
1930 "%<%.*s%> directive argument is null",
1931 (int)cvtlen, cvtbeg);
1933 /* Don't bother processing the rest of the format string. */
1934 res->warned = true;
1935 res->number_chars = HOST_WIDE_INT_M1U;
1936 res->number_chars_min = res->number_chars_max = res->number_chars;
1937 return;
1940 bool warned = res->warned;
1942 /* Compute the number of available bytes in the destination. There
1943 must always be at least one byte of space for the terminating
1944 NUL that's appended after the format string has been processed. */
1945 unsigned HOST_WIDE_INT navail = min_bytes_remaining (info.objsize, *res);
1947 if (fmtres.range.min < fmtres.range.max)
1949 /* The result is a range (i.e., it's inexact). */
1950 if (!warned)
1952 if (navail < fmtres.range.min)
1954 /* The minimum directive output is longer than there is
1955 room in the destination. */
1956 if (fmtres.range.min == fmtres.range.max)
1958 const char* fmtstr
1959 = (info.bounded
1960 ? G_("%<%.*s%> directive output truncated writing "
1961 "%wu bytes into a region of size %wu")
1962 : G_("%<%.*s%> directive writing %wu bytes "
1963 "into a region of size %wu"));
1964 warned = fmtwarn (dirloc, pargrange, NULL,
1965 OPT_Wformat_length_, fmtstr,
1966 (int)cvtlen, cvtbeg, fmtres.range.min,
1967 navail);
1969 else if (fmtres.range.max < HOST_WIDE_INT_MAX)
1971 const char* fmtstr
1972 = (info.bounded
1973 ? G_("%<%.*s%> directive output truncated writing "
1974 "between %wu and %wu bytes into a region of "
1975 "size %wu")
1976 : G_("%<%.*s%> directive writing between %wu and "
1977 "%wu bytes into a region of size %wu"));
1978 warned = fmtwarn (dirloc, pargrange, NULL,
1979 OPT_Wformat_length_, fmtstr,
1980 (int)cvtlen, cvtbeg,
1981 fmtres.range.min, fmtres.range.max, navail);
1983 else
1985 const char* fmtstr
1986 = (info.bounded
1987 ? G_("%<%.*s%> directive output truncated writing "
1988 "%wu or more bytes into a region of size %wu")
1989 : G_("%<%.*s%> directive writing %wu or more bytes "
1990 "into a region of size %wu"));
1991 warned = fmtwarn (dirloc, pargrange, NULL,
1992 OPT_Wformat_length_, fmtstr,
1993 (int)cvtlen, cvtbeg,
1994 fmtres.range.min, navail);
1997 else if (navail < fmtres.range.max
1998 && (((spec.specifier == 's'
1999 && fmtres.range.max < HOST_WIDE_INT_MAX)
2000 /* && (spec.precision || spec.star_precision) */)
2001 || 1 < warn_format_length))
2003 /* The maximum directive output is longer than there is
2004 room in the destination and the output length is either
2005 explicitly constrained by the precision (for strings)
2006 or the warning level is greater than 1. */
2007 if (fmtres.range.max >= HOST_WIDE_INT_MAX)
2009 const char* fmtstr
2010 = (info.bounded
2011 ? G_("%<%.*s%> directive output may be truncated "
2012 "writing %wu or more bytes a region of size %wu")
2013 : G_("%<%.*s%> directive writing %wu or more bytes "
2014 "into a region of size %wu"));
2015 warned = fmtwarn (dirloc, pargrange, NULL,
2016 OPT_Wformat_length_, fmtstr,
2017 (int)cvtlen, cvtbeg,
2018 fmtres.range.min, navail);
2020 else
2022 const char* fmtstr
2023 = (info.bounded
2024 ? G_("%<%.*s%> directive output may be truncated "
2025 "writing between %wu and %wu bytes into a region "
2026 "of size %wu")
2027 : G_("%<%.*s%> directive writing between %wu and %wu "
2028 "bytes into a region of size %wu"));
2029 warned = fmtwarn (dirloc, pargrange, NULL,
2030 OPT_Wformat_length_, fmtstr,
2031 (int)cvtlen, cvtbeg,
2032 fmtres.range.min, fmtres.range.max,
2033 navail);
2038 /* Disable exact length checking but adjust the minimum and maximum. */
2039 res->number_chars = HOST_WIDE_INT_M1U;
2040 if (res->number_chars_max < HOST_WIDE_INT_MAX
2041 && fmtres.range.max < HOST_WIDE_INT_MAX)
2042 res->number_chars_max += fmtres.range.max;
2044 res->number_chars_min += fmtres.range.min;
2046 else
2048 if (!warned && fmtres.range.min > 0 && navail < fmtres.range.min)
2050 const char* fmtstr
2051 = (info.bounded
2052 ? (1 < fmtres.range.min
2053 ? G_("%<%.*s%> directive output truncated while writing "
2054 "%wu bytes into a region of size %wu")
2055 : G_("%<%.*s%> directive output truncated while writing "
2056 "%wu byte into a region of size %wu"))
2057 : (1 < fmtres.range.min
2058 ? G_("%<%.*s%> directive writing %wu bytes "
2059 "into a region of size %wu")
2060 : G_("%<%.*s%> directive writing %wu byte "
2061 "into a region of size %wu")));
2063 warned = fmtwarn (dirloc, pargrange, NULL,
2064 OPT_Wformat_length_, fmtstr,
2065 (int)cvtlen, cvtbeg, fmtres.range.min,
2066 navail);
2068 *res += fmtres.range.min;
2071 /* Has the minimum directive output length exceeded the maximum
2072 of 4095 bytes required to be supported? */
2073 bool minunder4k = fmtres.range.min < 4096;
2074 if (!minunder4k || fmtres.range.max > 4095)
2075 res->under4k = false;
2077 if (!warned && 1 < warn_format_length
2078 && (!minunder4k || fmtres.range.max > 4095))
2080 /* The directive output may be longer than the maximum required
2081 to be handled by an implementation according to 7.21.6.1, p15
2082 of C11. Warn on this only at level 2 but remember this and
2083 prevent folding the return value when done. This allows for
2084 the possibility of the actual libc call failing due to ENOMEM
2085 (like Glibc does under some conditions). */
2087 if (fmtres.range.min == fmtres.range.max)
2088 warned = fmtwarn (dirloc, pargrange, NULL,
2089 OPT_Wformat_length_,
2090 "%<%.*s%> directive output of %wu bytes exceeds "
2091 "minimum required size of 4095",
2092 (int)cvtlen, cvtbeg, fmtres.range.min);
2093 else
2095 const char *fmtstr
2096 = (minunder4k
2097 ? G_("%<%.*s%> directive output between %qu and %wu "
2098 "bytes may exceed minimum required size of 4095")
2099 : G_("%<%.*s%> directive output between %qu and %wu "
2100 "bytes exceeds minimum required size of 4095"));
2102 warned = fmtwarn (dirloc, pargrange, NULL,
2103 OPT_Wformat_length_, fmtstr,
2104 (int)cvtlen, cvtbeg,
2105 fmtres.range.min, fmtres.range.max);
2109 /* Has the minimum directive output length exceeded INT_MAX? */
2110 bool exceedmin = res->number_chars_min > target_int_max ();
2112 if (!warned
2113 && (exceedmin
2114 || (1 < warn_format_length
2115 && res->number_chars_max > target_int_max ())))
2117 /* The directive output causes the total length of output
2118 to exceed INT_MAX bytes. */
2120 if (fmtres.range.min == fmtres.range.max)
2121 warned = fmtwarn (dirloc, pargrange, NULL,
2122 OPT_Wformat_length_,
2123 "%<%.*s%> directive output of %wu bytes causes "
2124 "result to exceed %<INT_MAX%>",
2125 (int)cvtlen, cvtbeg, fmtres.range.min);
2126 else
2128 const char *fmtstr
2129 = (exceedmin
2130 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2131 "bytes causes result to exceed %<INT_MAX%>")
2132 : G_ ("%<%.*s%> directive output between %wu and %wu "
2133 "bytes may cause result to exceed %<INT_MAX%>"));
2134 warned = fmtwarn (dirloc, pargrange, NULL,
2135 OPT_Wformat_length_, fmtstr,
2136 (int)cvtlen, cvtbeg,
2137 fmtres.range.min, fmtres.range.max);
2141 if (warned && fmtres.argmin)
2143 if (fmtres.argmin == fmtres.argmax)
2144 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2145 else if (fmtres.knownrange)
2146 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2147 fmtres.argmin, fmtres.argmax);
2148 else
2149 inform (info.fmtloc,
2150 "using the range [%E, %E] for directive argument",
2151 fmtres.argmin, fmtres.argmax);
2154 res->warned |= warned;
2157 /* Account for the number of bytes between BEG and END (or between
2158 BEG + strlen (BEG) when END is null) in the format string in a call
2159 to a formatted output function described by INFO. Reflect the count
2160 in RES and issue warnings as appropriate. */
2162 static void
2163 add_bytes (const pass_sprintf_length::call_info &info,
2164 const char *beg, const char *end, format_result *res)
2166 if (res->number_chars_min >= HOST_WIDE_INT_MAX)
2167 return;
2169 /* The number of bytes to output is the number of bytes between
2170 the end of the last directive and the beginning of the next
2171 one if it exists, otherwise the number of characters remaining
2172 in the format string plus 1 for the terminating NUL. */
2173 size_t nbytes = end ? end - beg : strlen (beg) + 1;
2175 /* Return if there are no bytes to add at this time but there are
2176 directives remaining in the format string. */
2177 if (!nbytes)
2178 return;
2180 /* Compute the range of available bytes in the destination. There
2181 must always be at least one byte left for the terminating NUL
2182 that's appended after the format string has been processed. */
2183 result_range avail_range = bytes_remaining (info.objsize, *res);
2185 /* If issuing a diagnostic (only when one hasn't already been issued),
2186 distinguish between a possible overflow ("may write") and a certain
2187 overflow somewhere "past the end." (Ditto for truncation.)
2188 KNOWNRANGE is used to warn even at level 1 about possibly writing
2189 past the end or truncation due to strings of unknown lengths that
2190 are bounded by the arrays they are known to refer to. */
2191 if (!res->warned
2192 && (avail_range.max < nbytes
2193 || ((res->knownrange || 1 < warn_format_length)
2194 && avail_range.min < nbytes)))
2196 /* Set NAVAIL to the number of available bytes used to decide
2197 whether or not to issue a warning below. The exact kind of
2198 warning will depend on AVAIL_RANGE. */
2199 unsigned HOST_WIDE_INT navail = avail_range.max;
2200 if (nbytes <= navail && avail_range.min < HOST_WIDE_INT_MAX
2201 && (res->knownrange || 1 < warn_format_length))
2202 navail = avail_range.min;
2204 /* Compute the offset of the first format character that is beyond
2205 the end of the destination region and the length of the rest of
2206 the format string from that point on. */
2207 unsigned HOST_WIDE_INT off
2208 = (unsigned HOST_WIDE_INT)(beg - info.fmtstr) + navail;
2210 size_t len = strlen (info.fmtstr + off);
2212 /* Create a location that underscores the substring of the format
2213 string that is or may be written past the end (or is or may be
2214 truncated), pointing the caret at the first character of the
2215 substring. */
2216 substring_loc loc
2217 (info.fmtloc, TREE_TYPE (info.format), off, len ? off : 0,
2218 off + len - !!len);
2220 /* Is the output of the last directive the result of the argument
2221 being within a range whose lower bound would fit in the buffer
2222 but the upper bound would not? If so, use the word "may" to
2223 indicate that the overflow/truncation may (but need not) happen. */
2224 bool boundrange
2225 = (res->number_chars_min < res->number_chars_max
2226 && res->number_chars_min + nbytes <= info.objsize);
2228 if (!end && ((nbytes - navail) == 1 || boundrange))
2230 /* There is room for the rest of the format string but none
2231 for the terminating nul. */
2232 const char *text
2233 = (info.bounded // Snprintf and the like.
2234 ? (boundrange
2235 ? G_("output may be truncated before the last format character"
2236 : "output truncated before the last format character"))
2237 : (boundrange
2238 ? G_("may write a terminating nul past the end "
2239 "of the destination")
2240 : G_("writing a terminating nul past the end "
2241 "of the destination")));
2243 res->warned = fmtwarn (loc, NULL, NULL, OPT_Wformat_length_, text);
2245 else
2247 /* There isn't enough room for 1 or more characters that remain
2248 to copy from the format string. */
2249 const char *text
2250 = (info.bounded // Snprintf and the like.
2251 ? (boundrange
2252 ? G_("output may be truncated at or before format character "
2253 "%qc at offset %wu")
2254 : G_("output truncated at format character %qc at offset %wu"))
2255 : (res->number_chars >= HOST_WIDE_INT_MAX
2256 ? G_("may write format character %#qc at offset %wu past "
2257 "the end of the destination")
2258 : G_("writing format character %#qc at offset %wu past "
2259 "the end of the destination")));
2261 res->warned = fmtwarn (loc, NULL, NULL, OPT_Wformat_length_,
2262 text, info.fmtstr[off], off);
2266 if (res->warned && !end && info.objsize < HOST_WIDE_INT_MAX)
2268 /* If a warning has been issued for buffer overflow or truncation
2269 (but not otherwise) help the user figure out how big a buffer
2270 they need. */
2272 location_t callloc = gimple_location (info.callstmt);
2274 unsigned HOST_WIDE_INT min = res->number_chars_min;
2275 unsigned HOST_WIDE_INT max = res->number_chars_max;
2276 unsigned HOST_WIDE_INT exact
2277 = (res->number_chars < HOST_WIDE_INT_MAX
2278 ? res->number_chars : res->number_chars_min);
2280 if (min < max && max < HOST_WIDE_INT_MAX)
2281 inform (callloc,
2282 "format output between %wu and %wu bytes into "
2283 "a destination of size %wu",
2284 min + nbytes, max + nbytes, info.objsize);
2285 else
2286 inform (callloc,
2287 (nbytes + exact == 1
2288 ? G_("format output %wu byte into a destination of size %wu")
2289 : G_("format output %wu bytes into a destination of size %wu")),
2290 nbytes + exact, info.objsize);
2293 /* Add the number of bytes and then check for INT_MAX overflow. */
2294 *res += nbytes;
2296 /* Has the minimum output length minus the terminating nul exceeded
2297 INT_MAX? */
2298 bool exceedmin = (res->number_chars_min - !end) > target_int_max ();
2300 if (!res->warned
2301 && (exceedmin
2302 || (1 < warn_format_length
2303 && (res->number_chars_max - !end) > target_int_max ())))
2305 /* The function's output exceeds INT_MAX bytes. */
2307 /* Set NAVAIL to the number of available bytes used to decide
2308 whether or not to issue a warning below. The exact kind of
2309 warning will depend on AVAIL_RANGE. */
2310 unsigned HOST_WIDE_INT navail = avail_range.max;
2311 if (nbytes <= navail && avail_range.min < HOST_WIDE_INT_MAX
2312 && (res->bounded || 1 < warn_format_length))
2313 navail = avail_range.min;
2315 /* Compute the offset of the first format character that is beyond
2316 the end of the destination region and the length of the rest of
2317 the format string from that point on. */
2318 unsigned HOST_WIDE_INT off = (unsigned HOST_WIDE_INT)(beg - info.fmtstr);
2319 if (navail < HOST_WIDE_INT_MAX)
2320 off += navail;
2322 size_t len = strlen (info.fmtstr + off);
2324 substring_loc loc
2325 (info.fmtloc, TREE_TYPE (info.format), off - !len, len ? off : 0,
2326 off + len - !!len);
2328 if (res->number_chars_min == res->number_chars_max)
2329 res->warned = fmtwarn (loc, NULL, NULL,
2330 OPT_Wformat_length_,
2331 "output of %wu bytes causes "
2332 "result to exceed %<INT_MAX%>",
2333 res->number_chars_min - !end);
2334 else
2336 const char *text
2337 = (exceedmin
2338 ? G_ ("output between %wu and %wu bytes causes "
2339 "result to exceed %<INT_MAX%>")
2340 : G_ ("output between %wu and %wu bytes may cause "
2341 "result to exceed %<INT_MAX%>"));
2342 res->warned = fmtwarn (loc, NULL, NULL, OPT_Wformat_length_,
2343 text,
2344 res->number_chars_min - !end,
2345 res->number_chars_max - !end);
2350 #pragma GCC diagnostic pop
2352 /* Compute the length of the output resulting from the call to a formatted
2353 output function described by INFO and store the result of the call in
2354 *RES. Issue warnings for detected past the end writes. Return true
2355 if the complete format string has been processed and *RES can be relied
2356 on, false otherwise (e.g., when a unknown or unhandled directive was seen
2357 that caused the processing to be terminated early). */
2359 bool
2360 pass_sprintf_length::compute_format_length (const call_info &info,
2361 format_result *res)
2363 /* The variadic argument counter. */
2364 unsigned argno = info.argidx;
2366 /* Reset exact, minimum, and maximum character counters. */
2367 res->number_chars = res->number_chars_min = res->number_chars_max = 0;
2369 /* No directive has been seen yet so the length of output is bounded
2370 by the known range [0, 0] and constant (with no conversion producing
2371 more than 4K bytes) until determined otherwise. */
2372 res->bounded = true;
2373 res->knownrange = true;
2374 res->constant = true;
2375 res->under4k = true;
2376 res->floating = false;
2377 res->warned = false;
2379 const char *pf = info.fmtstr;
2381 for ( ; ; )
2383 /* The beginning of the next format directive. */
2384 const char *dir = strchr (pf, '%');
2386 /* Add the number of bytes between the end of the last directive
2387 and either the next if one exists, or the end of the format
2388 string. */
2389 add_bytes (info, pf, dir, res);
2391 if (!dir)
2392 break;
2394 pf = dir + 1;
2396 if (0 && *pf == 0)
2398 /* Incomplete directive. */
2399 return false;
2402 conversion_spec spec = conversion_spec ();
2404 /* POSIX numbered argument index or zero when none. */
2405 unsigned dollar = 0;
2407 if (ISDIGIT (*pf))
2409 /* This could be either a POSIX positional argument, the '0'
2410 flag, or a width, depending on what follows. Store it as
2411 width and sort it out later after the next character has
2412 been seen. */
2413 char *end;
2414 spec.width = strtol (pf, &end, 10);
2415 spec.have_width = true;
2416 pf = end;
2418 else if ('*' == *pf)
2420 /* Similarly to the block above, this could be either a POSIX
2421 positional argument or a width, depending on what follows. */
2422 if (gimple_call_num_args (info.callstmt) <= argno)
2423 return false;
2425 spec.star_width = gimple_call_arg (info.callstmt, argno++);
2426 ++pf;
2429 if (*pf == '$')
2431 /* Handle the POSIX dollar sign which references the 1-based
2432 positional argument number. */
2433 if (spec.have_width)
2434 dollar = spec.width + info.argidx;
2435 else if (spec.star_width
2436 && TREE_CODE (spec.star_width) == INTEGER_CST)
2437 dollar = spec.width + tree_to_shwi (spec.star_width);
2439 /* Bail when the numbered argument is out of range (it will
2440 have already been diagnosed by -Wformat). */
2441 if (dollar == 0
2442 || dollar == info.argidx
2443 || dollar > gimple_call_num_args (info.callstmt))
2444 return false;
2446 --dollar;
2448 spec.star_width = NULL_TREE;
2449 spec.have_width = false;
2450 ++pf;
2453 if (dollar || !spec.star_width)
2455 if (spec.have_width)
2457 if (spec.width == 0)
2459 /* The '0' that has been interpreted as a width above is
2460 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
2461 and continue processing other flags. */
2462 spec.have_width = false;
2463 spec.set_flag ('0');
2465 else if (!dollar)
2467 /* (Non-zero) width has been seen. The next character
2468 is either a period or a digit. */
2469 goto start_precision;
2472 /* When either '$' has been seen, or width has not been seen,
2473 the next field is the optional flags followed by an optional
2474 width. */
2475 for ( ; ; ) {
2476 switch (*pf)
2478 case ' ':
2479 case '0':
2480 case '+':
2481 case '-':
2482 case '#':
2483 spec.set_flag (*pf++);
2484 break;
2486 default:
2487 goto start_width;
2491 start_width:
2492 if (ISDIGIT (*pf))
2494 char *end;
2495 spec.width = strtol (pf, &end, 10);
2496 spec.have_width = true;
2497 pf = end;
2499 else if ('*' == *pf)
2501 spec.star_width = gimple_call_arg (info.callstmt, argno++);
2502 ++pf;
2504 else if ('\'' == *pf)
2506 /* The POSIX apostrophe indicating a numeric grouping
2507 in the current locale. Even though it's possible to
2508 estimate the upper bound on the size of the output
2509 based on the number of digits it probably isn't worth
2510 continuing. */
2511 return false;
2515 start_precision:
2516 if ('.' == *pf)
2518 ++pf;
2520 if (ISDIGIT (*pf))
2522 char *end;
2523 spec.precision = strtol (pf, &end, 10);
2524 spec.have_precision = true;
2525 pf = end;
2527 else if ('*' == *pf)
2529 spec.star_precision = gimple_call_arg (info.callstmt, argno++);
2530 ++pf;
2532 else
2534 /* The decimal precision or the asterisk are optional.
2535 When neither is specified it's taken to be zero. */
2536 spec.precision = 0;
2537 spec.have_precision = true;
2541 switch (*pf)
2543 case 'h':
2544 if (pf[1] == 'h')
2546 ++pf;
2547 spec.modifier = FMT_LEN_hh;
2549 else
2550 spec.modifier = FMT_LEN_h;
2551 ++pf;
2552 break;
2554 case 'j':
2555 spec.modifier = FMT_LEN_j;
2556 ++pf;
2557 break;
2559 case 'L':
2560 spec.modifier = FMT_LEN_L;
2561 ++pf;
2562 break;
2564 case 'l':
2565 if (pf[1] == 'l')
2567 ++pf;
2568 spec.modifier = FMT_LEN_ll;
2570 else
2571 spec.modifier = FMT_LEN_l;
2572 ++pf;
2573 break;
2575 case 't':
2576 spec.modifier = FMT_LEN_t;
2577 ++pf;
2578 break;
2580 case 'z':
2581 spec.modifier = FMT_LEN_z;
2582 ++pf;
2583 break;
2586 switch (*pf)
2588 /* Handle a sole '%' character the same as "%%" but since it's
2589 undefined prevent the result from being folded. */
2590 case '\0':
2591 --pf;
2592 res->bounded = false;
2593 /* FALLTHRU */
2594 case '%':
2595 spec.fmtfunc = format_percent;
2596 break;
2598 case 'a':
2599 case 'A':
2600 case 'e':
2601 case 'E':
2602 case 'f':
2603 case 'F':
2604 case 'g':
2605 case 'G':
2606 res->floating = true;
2607 spec.fmtfunc = format_floating;
2608 break;
2610 case 'd':
2611 case 'i':
2612 case 'o':
2613 case 'u':
2614 case 'x':
2615 case 'X':
2616 spec.fmtfunc = format_integer;
2617 break;
2619 case 'p':
2620 /* The %p output is implementation-defined. It's possible
2621 to determine this format but due to extensions (especially
2622 those of the Linux kernel -- see bug 78512) the first %p
2623 in the format string disables any further processing. */
2624 return false;
2626 case 'n':
2627 break;
2629 case 'c':
2630 case 'S':
2631 case 's':
2632 spec.fmtfunc = format_string;
2633 break;
2635 default:
2636 /* Unknown conversion specification. */
2637 return false;
2640 spec.specifier = *pf++;
2642 /* Compute the length of the format directive. */
2643 size_t dirlen = pf - dir;
2645 /* Extract the argument if the directive takes one and if it's
2646 available (e.g., the function doesn't take a va_list). Treat
2647 missing arguments the same as va_list, even though they will
2648 have likely already been diagnosed by -Wformat. */
2649 tree arg = NULL_TREE;
2650 if (spec.specifier != '%'
2651 && argno < gimple_call_num_args (info.callstmt))
2652 arg = gimple_call_arg (info.callstmt, dollar ? dollar : argno++);
2654 ::format_directive (info, res, dir, dirlen, spec, arg);
2657 /* Complete format string was processed (with or without warnings). */
2658 return true;
2661 /* Return the size of the object referenced by the expression DEST if
2662 available, or -1 otherwise. */
2664 static unsigned HOST_WIDE_INT
2665 get_destination_size (tree dest)
2667 /* Use __builtin_object_size to determine the size of the destination
2668 object. When optimizing, determine the smallest object (such as
2669 a member array as opposed to the whole enclosing object), otherwise
2670 use type-zero object size to determine the size of the enclosing
2671 object (the function fails without optimization in this type). */
2672 int ost = optimize > 0;
2673 unsigned HOST_WIDE_INT size;
2674 if (compute_builtin_object_size (dest, ost, &size))
2675 return size;
2677 return HOST_WIDE_INT_M1U;
2680 /* Given a suitable result RES of a call to a formatted output function
2681 described by INFO, substitute the result for the return value of
2682 the call. The result is suitable if the number of bytes it represents
2683 is known and exact. A result that isn't suitable for substitution may
2684 have its range set to the range of return values, if that is known. */
2686 static void
2687 try_substitute_return_value (gimple_stmt_iterator *gsi,
2688 const pass_sprintf_length::call_info &info,
2689 const format_result &res)
2691 tree lhs = gimple_get_lhs (info.callstmt);
2693 /* Avoid the return value optimization when the behavior of the call
2694 is undefined either because any directive may have produced 4K or
2695 more of output, or the return value exceeds INT_MAX, or because
2696 the output overflows the destination object (but leave it enabled
2697 when the function is bounded because then the behavior is well-
2698 defined). */
2699 if (lhs && res.bounded && res.under4k
2700 && (info.bounded || res.number_chars <= info.objsize)
2701 && res.number_chars - 1 <= target_int_max ())
2703 tree cst = build_int_cst (integer_type_node, res.number_chars - 1);
2705 if (info.nowrite)
2707 /* Replace the call to the bounded function with a zero size
2708 (e.g., snprintf(0, 0, "%i", 123) with the constant result
2709 of the function minus 1 for the terminating NUL which
2710 the function's return value does not include. */
2711 if (!update_call_from_tree (gsi, cst))
2712 gimplify_and_update_call_from_tree (gsi, cst);
2713 gimple *callstmt = gsi_stmt (*gsi);
2714 update_stmt (callstmt);
2716 else
2718 /* Replace the left-hand side of the call with the constant
2719 result of the formatted function minus 1 for the terminating
2720 NUL which the function's return value does not include. */
2721 gimple_call_set_lhs (info.callstmt, NULL_TREE);
2722 gimple *g = gimple_build_assign (lhs, cst);
2723 gsi_insert_after (gsi, g, GSI_NEW_STMT);
2724 update_stmt (info.callstmt);
2727 if (dump_file)
2729 location_t callloc = gimple_location (info.callstmt);
2730 fprintf (dump_file, "On line %i substituting ",
2731 LOCATION_LINE (callloc));
2732 print_generic_expr (dump_file, cst, dump_flags);
2733 fprintf (dump_file, " for ");
2734 print_generic_expr (dump_file, info.func, dump_flags);
2735 fprintf (dump_file, " %s (output %s).\n",
2736 info.nowrite ? "call" : "return value",
2737 res.constant ? "constant" : "variable");
2740 else
2742 unsigned HOST_WIDE_INT maxbytes;
2744 if (lhs
2745 && res.bounded
2746 && ((maxbytes = res.number_chars - 1) <= target_int_max ()
2747 || (res.number_chars_min - 1 <= target_int_max ()
2748 && (maxbytes = res.number_chars_max - 1) <= target_int_max ()))
2749 && (info.bounded || maxbytes < info.objsize))
2751 /* If the result is in a valid range bounded by the size of
2752 the destination set it so that it can be used for subsequent
2753 optimizations. */
2754 int prec = TYPE_PRECISION (integer_type_node);
2756 if (res.number_chars < target_int_max () && res.under4k)
2758 wide_int num = wi::shwi (res.number_chars - 1, prec);
2759 set_range_info (lhs, VR_RANGE, num, num);
2761 else if (res.number_chars_min < target_int_max ()
2762 && res.number_chars_max < target_int_max ())
2764 wide_int min = wi::shwi (res.under4k ? res.number_chars_min - 1
2765 : target_int_min (), prec);
2766 wide_int max = wi::shwi (res.number_chars_max - 1, prec);
2767 set_range_info (lhs, VR_RANGE, min, max);
2771 if (dump_file)
2773 const char *inbounds
2774 = (res.number_chars_min <= info.objsize
2775 ? (res.number_chars_max <= info.objsize
2776 ? "in" : "potentially out-of")
2777 : "out-of");
2779 location_t callloc = gimple_location (info.callstmt);
2780 fprintf (dump_file, "On line %i ", LOCATION_LINE (callloc));
2781 print_generic_expr (dump_file, info.func, dump_flags);
2783 const char *ign = lhs ? "" : " ignored";
2784 if (res.number_chars >= HOST_WIDE_INT_MAX)
2785 fprintf (dump_file,
2786 " %s-bounds return value in range [%lu, %lu]%s.\n",
2787 inbounds,
2788 (unsigned long)res.number_chars_min,
2789 (unsigned long)res.number_chars_max, ign);
2790 else
2791 fprintf (dump_file, " %s-bounds return value %lu%s.\n",
2792 inbounds, (unsigned long)res.number_chars, ign);
2797 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
2798 functions and if so, handle it. */
2800 void
2801 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator *gsi)
2803 call_info info = call_info ();
2805 info.callstmt = gsi_stmt (*gsi);
2806 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
2807 return;
2809 info.func = gimple_call_fndecl (info.callstmt);
2810 info.fncode = DECL_FUNCTION_CODE (info.func);
2812 /* The size of the destination as in snprintf(dest, size, ...). */
2813 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
2815 /* The size of the destination determined by __builtin_object_size. */
2816 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
2818 /* Buffer size argument number (snprintf and vsnprintf). */
2819 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
2821 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
2822 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
2824 /* Format string argument number (valid for all functions). */
2825 unsigned idx_format;
2827 switch (info.fncode)
2829 case BUILT_IN_SPRINTF:
2830 // Signature:
2831 // __builtin_sprintf (dst, format, ...)
2832 idx_format = 1;
2833 info.argidx = 2;
2834 break;
2836 case BUILT_IN_SPRINTF_CHK:
2837 // Signature:
2838 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
2839 idx_objsize = 2;
2840 idx_format = 3;
2841 info.argidx = 4;
2842 break;
2844 case BUILT_IN_SNPRINTF:
2845 // Signature:
2846 // __builtin_snprintf (dst, size, format, ...)
2847 idx_dstsize = 1;
2848 idx_format = 2;
2849 info.argidx = 3;
2850 info.bounded = true;
2851 break;
2853 case BUILT_IN_SNPRINTF_CHK:
2854 // Signature:
2855 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
2856 idx_dstsize = 1;
2857 idx_objsize = 3;
2858 idx_format = 4;
2859 info.argidx = 5;
2860 info.bounded = true;
2861 break;
2863 case BUILT_IN_VSNPRINTF:
2864 // Signature:
2865 // __builtin_vsprintf (dst, size, format, va)
2866 idx_dstsize = 1;
2867 idx_format = 2;
2868 info.argidx = -1;
2869 info.bounded = true;
2870 break;
2872 case BUILT_IN_VSNPRINTF_CHK:
2873 // Signature:
2874 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
2875 idx_dstsize = 1;
2876 idx_objsize = 3;
2877 idx_format = 4;
2878 info.argidx = -1;
2879 info.bounded = true;
2880 break;
2882 case BUILT_IN_VSPRINTF:
2883 // Signature:
2884 // __builtin_vsprintf (dst, format, va)
2885 idx_format = 1;
2886 info.argidx = -1;
2887 break;
2889 case BUILT_IN_VSPRINTF_CHK:
2890 // Signature:
2891 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
2892 idx_format = 3;
2893 idx_objsize = 2;
2894 info.argidx = -1;
2895 break;
2897 default:
2898 return;
2901 /* The first argument is a pointer to the destination. */
2902 tree dstptr = gimple_call_arg (info.callstmt, 0);
2904 info.format = gimple_call_arg (info.callstmt, idx_format);
2906 if (idx_dstsize == HOST_WIDE_INT_M1U)
2908 /* For non-bounded functions like sprintf, determine the size
2909 of the destination from the object or pointer passed to it
2910 as the first argument. */
2911 dstsize = get_destination_size (dstptr);
2913 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
2915 /* For bounded functions try to get the size argument. */
2917 if (TREE_CODE (size) == INTEGER_CST)
2919 dstsize = tree_to_uhwi (size);
2920 /* No object can be larger than SIZE_MAX bytes (half the address
2921 space) on the target.
2922 The functions are defined only for output of at most INT_MAX
2923 bytes. Specifying a bound in excess of that limit effectively
2924 defeats the bounds checking (and on some implementations such
2925 as Solaris cause the function to fail with EINVAL). */
2926 if (dstsize > target_size_max () / 2)
2928 /* Avoid warning if -Wstringop-overflow is specified since
2929 it also warns for the same thing though only for the
2930 checking built-ins. */
2931 if ((idx_objsize == HOST_WIDE_INT_M1U
2932 || !warn_stringop_overflow))
2933 warning_at (gimple_location (info.callstmt),
2934 OPT_Wformat_length_,
2935 "specified bound %wu exceeds maximum object size "
2936 "%wu",
2937 dstsize, target_size_max () / 2);
2939 else if (dstsize > target_int_max ())
2940 warning_at (gimple_location (info.callstmt), OPT_Wformat_length_,
2941 "specified bound %wu exceeds %<INT_MAX %>",
2942 dstsize);
2944 else if (TREE_CODE (size) == SSA_NAME)
2946 /* Try to determine the range of values of the argument
2947 and use the greater of the two at -Wformat-level 1 and
2948 the smaller of them at level 2. */
2949 wide_int min, max;
2950 enum value_range_type range_type
2951 = get_range_info (size, &min, &max);
2952 if (range_type == VR_RANGE)
2954 dstsize
2955 = (warn_format_length < 2
2956 ? wi::fits_uhwi_p (max) ? max.to_uhwi () : max.to_shwi ()
2957 : wi::fits_uhwi_p (min) ? min.to_uhwi () : min.to_shwi ());
2962 if (idx_objsize != HOST_WIDE_INT_M1U)
2964 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
2965 if (tree_fits_uhwi_p (size))
2966 objsize = tree_to_uhwi (size);
2969 if (info.bounded && !dstsize)
2971 /* As a special case, when the explicitly specified destination
2972 size argument (to a bounded function like snprintf) is zero
2973 it is a request to determine the number of bytes on output
2974 without actually producing any. Pretend the size is
2975 unlimited in this case. */
2976 info.objsize = HOST_WIDE_INT_MAX;
2977 info.nowrite = true;
2979 else
2981 /* For calls to non-bounded functions or to those of bounded
2982 functions with a non-zero size, warn if the destination
2983 pointer is null. */
2984 if (integer_zerop (dstptr))
2986 /* This is diagnosed with -Wformat only when the null is a constant
2987 pointer. The warning here diagnoses instances where the pointer
2988 is not constant. */
2989 location_t loc = gimple_location (info.callstmt);
2990 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
2991 OPT_Wformat_length_, "null destination pointer");
2992 return;
2995 /* Set the object size to the smaller of the two arguments
2996 of both have been specified and they're not equal. */
2997 info.objsize = dstsize < objsize ? dstsize : objsize;
2999 if (info.bounded
3000 && dstsize < target_size_max () / 2 && objsize < dstsize
3001 /* Avoid warning if -Wstringop-overflow is specified since
3002 it also warns for the same thing though only for the
3003 checking built-ins. */
3004 && (idx_objsize == HOST_WIDE_INT_M1U
3005 || !warn_stringop_overflow))
3007 warning_at (gimple_location (info.callstmt), OPT_Wformat_length_,
3008 "specified bound %wu exceeds the size %wu "
3009 "of the destination object", dstsize, objsize);
3013 if (integer_zerop (info.format))
3015 /* This is diagnosed with -Wformat only when the null is a constant
3016 pointer. The warning here diagnoses instances where the pointer
3017 is not constant. */
3018 location_t loc = gimple_location (info.callstmt);
3019 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3020 OPT_Wformat_length_, "null format string");
3021 return;
3024 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3025 if (!info.fmtstr)
3026 return;
3028 /* The result is the number of bytes output by the formatted function,
3029 including the terminating NUL. */
3030 format_result res = format_result ();
3032 bool success = compute_format_length (info, &res);
3034 /* When optimizing and the printf return value optimization is enabled,
3035 attempt to substitute the computed result for the return value of
3036 the call. Avoid this optimization when -frounding-math is in effect
3037 and the format string contains a floating point directive. */
3038 if (success
3039 && optimize > 0
3040 && flag_printf_return_value
3041 && (!flag_rounding_math || !res.floating))
3042 try_substitute_return_value (gsi, info, res);
3045 /* Execute the pass for function FUN. */
3047 unsigned int
3048 pass_sprintf_length::execute (function *fun)
3050 basic_block bb;
3051 FOR_EACH_BB_FN (bb, fun)
3053 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
3054 gsi_next (&si))
3056 /* Iterate over statements, looking for function calls. */
3057 gimple *stmt = gsi_stmt (si);
3059 if (is_gimple_call (stmt))
3060 handle_gimple_call (&si);
3064 return 0;
3067 } /* Unnamed namespace. */
3069 /* Return a pointer to a pass object newly constructed from the context
3070 CTXT. */
3072 gimple_opt_pass *
3073 make_pass_sprintf_length (gcc::context *ctxt)
3075 return new pass_sprintf_length (ctxt);