gcc/ChangeLog:
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob262857c64ded53ff7b5c3ccc076ebdb1bb2b1681
1 /* Copyright (C) 2016-2017 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 bool handle_gimple_call (gimple_stmt_iterator *);
133 struct call_info;
134 bool compute_format_length (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_overflow > 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. Need not be INTEGER_CST.
487 For vararg functions set to void_node. */
488 tree star_width;
489 /* Precision specified via the asterisk. Need not be INTEGER_CST.
490 For vararg functions set to void_node. */
491 tree star_precision;
493 /* Length modifier. */
494 format_lengths modifier;
496 /* Format specifier character. */
497 char specifier;
499 /* Numeric width was given. */
500 unsigned have_width: 1;
501 /* Numeric precision was given. */
502 unsigned have_precision: 1;
503 /* Non-zero when certain flags should be interpreted even for a directive
504 that normally doesn't accept them (used when "%p" with flags such as
505 space or plus is interepreted as a "%x". */
506 unsigned force_flags: 1;
508 /* Format conversion function that given a conversion specification
509 and an argument returns the formatting result. */
510 fmtresult (*fmtfunc) (const conversion_spec &, tree);
512 /* Return True when a the format flag CHR has been used. */
513 bool get_flag (char chr) const
515 unsigned char c = chr & 0xff;
516 return (flags[c / (CHAR_BIT * sizeof *flags)]
517 & (1U << (c % (CHAR_BIT * sizeof *flags))));
520 /* Make a record of the format flag CHR having been used. */
521 void set_flag (char chr)
523 unsigned char c = chr & 0xff;
524 flags[c / (CHAR_BIT * sizeof *flags)]
525 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
528 /* Reset the format flag CHR. */
529 void clear_flag (char chr)
531 unsigned char c = chr & 0xff;
532 flags[c / (CHAR_BIT * sizeof *flags)]
533 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
537 /* Return the logarithm of X in BASE. */
539 static int
540 ilog (unsigned HOST_WIDE_INT x, int base)
542 int res = 0;
545 ++res;
546 x /= base;
547 } while (x);
548 return res;
551 /* Return the number of bytes resulting from converting into a string
552 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
553 PLUS indicates whether 1 for a plus sign should be added for positive
554 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
555 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
556 be represented. */
558 static HOST_WIDE_INT
559 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
561 unsigned HOST_WIDE_INT absval;
563 HOST_WIDE_INT res;
565 if (TYPE_UNSIGNED (TREE_TYPE (x)))
567 if (tree_fits_uhwi_p (x))
569 absval = tree_to_uhwi (x);
570 res = plus;
572 else
573 return -1;
575 else
577 if (tree_fits_shwi_p (x))
579 HOST_WIDE_INT i = tree_to_shwi (x);
580 if (i < 0)
582 absval = -i;
583 res = 1;
585 else
587 absval = i;
588 res = plus;
591 else
592 return -1;
595 int ndigs = ilog (absval, base);
597 res += prec < ndigs ? ndigs : prec;
599 if (prefix && absval)
601 if (base == 8)
602 res += 1;
603 else if (base == 16)
604 res += 2;
607 return res;
610 /* Given the formatting result described by RES and NAVAIL, the number
611 of available in the destination, return the number of bytes remaining
612 in the destination. */
614 static inline result_range
615 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
617 result_range range;
619 if (HOST_WIDE_INT_MAX <= navail)
621 range.min = range.max = navail;
622 return range;
625 if (res.number_chars < navail)
627 range.min = range.max = navail - res.number_chars;
629 else if (res.number_chars_min < navail)
631 range.max = navail - res.number_chars_min;
633 else
634 range.max = 0;
636 if (res.number_chars_max < navail)
637 range.min = navail - res.number_chars_max;
638 else
639 range.min = 0;
641 return range;
644 /* Given the formatting result described by RES and NAVAIL, the number
645 of available in the destination, return the minimum number of bytes
646 remaining in the destination. */
648 static inline unsigned HOST_WIDE_INT
649 min_bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
651 if (HOST_WIDE_INT_MAX <= navail)
652 return navail;
654 if (warn_format_overflow > 1 || res.knownrange)
656 /* At level 2, or when all directives output an exact number
657 of bytes or when their arguments were bounded by known
658 ranges, use the greater of the two byte counters if it's
659 valid to compute the result. */
660 if (res.number_chars_max < HOST_WIDE_INT_MAX)
661 navail -= res.number_chars_max;
662 else if (res.number_chars < HOST_WIDE_INT_MAX)
663 navail -= res.number_chars;
664 else if (res.number_chars_min < HOST_WIDE_INT_MAX)
665 navail -= res.number_chars_min;
667 else
669 /* At level 1 use the smaller of the byte counters to compute
670 the result. */
671 if (res.number_chars < HOST_WIDE_INT_MAX)
672 navail -= res.number_chars;
673 else if (res.number_chars_min < HOST_WIDE_INT_MAX)
674 navail -= res.number_chars_min;
675 else if (res.number_chars_max < HOST_WIDE_INT_MAX)
676 navail -= res.number_chars_max;
679 if (navail > HOST_WIDE_INT_MAX)
680 navail = 0;
682 return navail;
685 /* Description of a call to a formatted function. */
687 struct pass_sprintf_length::call_info
689 /* Function call statement. */
690 gimple *callstmt;
692 /* Function called. */
693 tree func;
695 /* Called built-in function code. */
696 built_in_function fncode;
698 /* Format argument and format string extracted from it. */
699 tree format;
700 const char *fmtstr;
702 /* The location of the format argument. */
703 location_t fmtloc;
705 /* The destination object size for __builtin___xxx_chk functions
706 typically determined by __builtin_object_size, or -1 if unknown. */
707 unsigned HOST_WIDE_INT objsize;
709 /* Number of the first variable argument. */
710 unsigned HOST_WIDE_INT argidx;
712 /* True for functions like snprintf that specify the size of
713 the destination, false for others like sprintf that don't. */
714 bool bounded;
716 /* True for bounded functions like snprintf that specify a zero-size
717 buffer as a request to compute the size of output without actually
718 writing any. NOWRITE is cleared in response to the %n directive
719 which has side-effects similar to writing output. */
720 bool nowrite;
722 /* Return true if the called function's return value is used. */
723 bool retval_used () const
725 return gimple_get_lhs (callstmt);
728 /* Return the warning option corresponding to the called function. */
729 int warnopt () const
731 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
735 /* Return the result of formatting the '%%' directive. */
737 static fmtresult
738 format_percent (const conversion_spec &, tree)
740 fmtresult res;
741 res.argmin = res.argmax = NULL_TREE;
742 res.range.min = res.range.max = 1;
743 res.bounded = res.constant = true;
744 return res;
748 /* Compute intmax_type_node and uintmax_type_node similarly to how
749 tree.c builds size_type_node. */
751 static void
752 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
754 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
756 *pintmax = integer_type_node;
757 *puintmax = unsigned_type_node;
759 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
761 *pintmax = long_integer_type_node;
762 *puintmax = long_unsigned_type_node;
764 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
766 *pintmax = long_long_integer_type_node;
767 *puintmax = long_long_unsigned_type_node;
769 else
771 for (int i = 0; i < NUM_INT_N_ENTS; i++)
772 if (int_n_enabled_p[i])
774 char name[50];
775 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
777 if (strcmp (name, UINTMAX_TYPE) == 0)
779 *pintmax = int_n_trees[i].signed_type;
780 *puintmax = int_n_trees[i].unsigned_type;
781 return;
784 gcc_unreachable ();
788 /* Set *PWIDTH and *PPREC according to the width and precision specified
789 in SPEC. Each is set to HOST_WIDE_INT_MIN when the corresponding
790 field is specified but unknown, to zero for width and -1 for precision,
791 respectively when it's not specified, or to a non-negative value
792 corresponding to the known value. */
794 static void
795 get_width_and_precision (const conversion_spec &spec,
796 HOST_WIDE_INT *pwidth, HOST_WIDE_INT *pprec)
798 HOST_WIDE_INT width = spec.have_width ? spec.width : 0;
799 HOST_WIDE_INT prec = spec.have_precision ? spec.precision : -1;
801 if (spec.star_width)
803 if (TREE_CODE (spec.star_width) == INTEGER_CST)
805 width = tree_to_shwi (spec.star_width);
806 if (width < 0)
808 if (width == HOST_WIDE_INT_MIN)
810 /* Avoid undefined behavior due to negating a minimum.
811 This case will be diagnosed since it will result in
812 more than INT_MAX bytes on output, either by the
813 directive itself (when INT_MAX < HOST_WIDE_INT_MAX)
814 or by the format function itself. */
815 width = HOST_WIDE_INT_MAX;
817 else
818 width = -width;
821 else
822 width = HOST_WIDE_INT_MIN;
825 if (spec.star_precision)
827 if (TREE_CODE (spec.star_precision) == INTEGER_CST)
829 prec = tree_to_shwi (spec.star_precision);
830 if (prec < 0)
831 prec = -1;
833 else
834 prec = HOST_WIDE_INT_MIN;
837 *pwidth = width;
838 *pprec = prec;
841 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
842 argument, due to the conversion from either *ARGMIN or *ARGMAX to
843 the type of the directive's formal argument it's possible for both
844 to result in the same number of bytes or a range of bytes that's
845 less than the number of bytes that would result from formatting
846 some other value in the range [*ARGMIN, *ARGMAX]. This can be
847 determined by checking for the actual argument being in the range
848 of the type of the directive. If it isn't it must be assumed to
849 take on the full range of the directive's type.
850 Return true when the range has been adjusted to the full unsigned
851 range of DIRTYPE, or [0, DIRTYPE_MAX], and false otherwise. */
853 static bool
854 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
856 tree argtype = TREE_TYPE (*argmin);
857 unsigned argprec = TYPE_PRECISION (argtype);
858 unsigned dirprec = TYPE_PRECISION (dirtype);
860 /* If the actual argument and the directive's argument have the same
861 precision and sign there can be no overflow and so there is nothing
862 to adjust. */
863 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
864 return false;
866 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
867 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
869 if (TREE_CODE (*argmin) == INTEGER_CST
870 && TREE_CODE (*argmax) == INTEGER_CST
871 && (dirprec >= argprec
872 || integer_zerop (int_const_binop (RSHIFT_EXPR,
873 int_const_binop (MINUS_EXPR,
874 *argmax,
875 *argmin),
876 size_int (dirprec)))))
878 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
879 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
881 /* If *ARGMIN is still less than *ARGMAX the conversion above
882 is safe. Otherwise, it has overflowed and would be unsafe. */
883 if (tree_int_cst_le (*argmin, *argmax))
884 return false;
887 tree dirmin = TYPE_MIN_VALUE (dirtype);
888 tree dirmax = TYPE_MAX_VALUE (dirtype);
890 if (TYPE_UNSIGNED (dirtype))
892 *argmin = dirmin;
893 *argmax = dirmax;
895 else
897 *argmin = integer_zero_node;
898 *argmax = dirmin;
901 return true;
904 /* Return a range representing the minimum and maximum number of bytes
905 that the conversion specification SPEC will write on output for the
906 integer argument ARG when non-null. ARG may be null (for vararg
907 functions). */
909 static fmtresult
910 format_integer (const conversion_spec &spec, tree arg)
912 tree intmax_type_node;
913 tree uintmax_type_node;
915 /* Set WIDTH and PRECISION based on the specification. */
916 HOST_WIDE_INT width;
917 HOST_WIDE_INT prec;
918 get_width_and_precision (spec, &width, &prec);
920 bool sign = spec.specifier == 'd' || spec.specifier == 'i';
922 /* The type of the "formal" argument expected by the directive. */
923 tree dirtype = NULL_TREE;
925 /* Determine the expected type of the argument from the length
926 modifier. */
927 switch (spec.modifier)
929 case FMT_LEN_none:
930 if (spec.specifier == 'p')
931 dirtype = ptr_type_node;
932 else
933 dirtype = sign ? integer_type_node : unsigned_type_node;
934 break;
936 case FMT_LEN_h:
937 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
938 break;
940 case FMT_LEN_hh:
941 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
942 break;
944 case FMT_LEN_l:
945 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
946 break;
948 case FMT_LEN_L:
949 case FMT_LEN_ll:
950 dirtype = (sign
951 ? long_long_integer_type_node
952 : long_long_unsigned_type_node);
953 break;
955 case FMT_LEN_z:
956 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
957 break;
959 case FMT_LEN_t:
960 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
961 break;
963 case FMT_LEN_j:
964 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
965 dirtype = sign ? intmax_type_node : uintmax_type_node;
966 break;
968 default:
969 return fmtresult ();
972 /* The type of the argument to the directive, either deduced from
973 the actual non-constant argument if one is known, or from
974 the directive itself when none has been provided because it's
975 a va_list. */
976 tree argtype = NULL_TREE;
978 if (!arg)
980 /* When the argument has not been provided, use the type of
981 the directive's argument as an approximation. This will
982 result in false positives for directives like %i with
983 arguments with smaller precision (such as short or char). */
984 argtype = dirtype;
986 else if (TREE_CODE (arg) == INTEGER_CST)
988 /* When a constant argument has been provided use its value
989 rather than type to determine the length of the output. */
991 /* Base to format the number in. */
992 int base;
994 /* True when a signed conversion is preceded by a sign or space. */
995 bool maybesign = false;
997 switch (spec.specifier)
999 case 'd':
1000 case 'i':
1001 /* Space and '+' are only meaningful for signed conversions. */
1002 maybesign = spec.get_flag (' ') | spec.get_flag ('+');
1003 base = 10;
1004 break;
1005 case 'u':
1006 base = 10;
1007 break;
1008 case 'o':
1009 base = 8;
1010 break;
1011 case 'X':
1012 case 'x':
1013 base = 16;
1014 break;
1015 default:
1016 gcc_unreachable ();
1019 HOST_WIDE_INT len;
1021 if ((prec == HOST_WIDE_INT_MIN || prec == 0) && integer_zerop (arg))
1023 /* As a special case, a precision of zero with a zero argument
1024 results in zero bytes except in base 8 when the '#' flag is
1025 specified, and for signed conversions in base 8 and 10 when
1026 flags when either the space or '+' flag has been specified
1027 when it results in just one byte (with width having the normal
1028 effect). This must extend to the case of a specified precision
1029 with an unknown value because it can be zero. */
1030 len = ((base == 8 && spec.get_flag ('#')) || maybesign);
1032 else
1034 /* Convert the argument to the type of the directive. */
1035 arg = fold_convert (dirtype, arg);
1037 /* True when a conversion is preceded by a prefix indicating the base
1038 of the argument (octal or hexadecimal). */
1039 bool maybebase = spec.get_flag ('#');
1040 len = tree_digits (arg, base, prec, maybesign, maybebase);
1041 if (len < 1)
1042 len = HOST_WIDE_INT_MAX;
1045 if (len < width)
1046 len = width;
1048 /* The minimum and maximum number of bytes produced by the directive. */
1049 fmtresult res;
1051 res.range.min = len;
1053 /* The upper bound of the number of bytes is unlimited when either
1054 width or precision is specified but its value is unknown, and
1055 the same as the lower bound otherwise. */
1056 if (width == HOST_WIDE_INT_MIN || prec == HOST_WIDE_INT_MIN)
1058 res.range.max = HOST_WIDE_INT_MAX;
1060 else
1062 res.range.max = len;
1063 res.bounded = true;
1064 res.constant = true;
1065 res.knownrange = true;
1066 res.bounded = true;
1069 return res;
1071 else if (TREE_CODE (TREE_TYPE (arg)) == INTEGER_TYPE
1072 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1073 /* Determine the type of the provided non-constant argument. */
1074 argtype = TREE_TYPE (arg);
1075 else
1076 /* Don't bother with invalid arguments since they likely would
1077 have already been diagnosed, and disable any further checking
1078 of the format string by returning [-1, -1]. */
1079 return fmtresult ();
1081 fmtresult res;
1083 /* The result is bounded unless width or precision has been specified
1084 whose value is unknown. */
1085 res.bounded = width != HOST_WIDE_INT_MIN && prec != HOST_WIDE_INT_MIN;
1087 /* Using either the range the non-constant argument is in, or its
1088 type (either "formal" or actual), create a range of values that
1089 constrain the length of output given the warning level. */
1090 tree argmin = NULL_TREE;
1091 tree argmax = NULL_TREE;
1093 if (arg
1094 && TREE_CODE (arg) == SSA_NAME
1095 && TREE_CODE (argtype) == INTEGER_TYPE)
1097 /* Try to determine the range of values of the integer argument
1098 (range information is not available for pointers). */
1099 wide_int min, max;
1100 enum value_range_type range_type = get_range_info (arg, &min, &max);
1101 if (range_type == VR_RANGE)
1103 argmin = build_int_cst (argtype, wi::fits_uhwi_p (min)
1104 ? min.to_uhwi () : min.to_shwi ());
1105 argmax = build_int_cst (argtype, wi::fits_uhwi_p (max)
1106 ? max.to_uhwi () : max.to_shwi ());
1108 /* Set KNOWNRANGE if the argument is in a known subrange
1109 of the directive's type (KNOWNRANGE may be reset below). */
1110 res.knownrange
1111 = (!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1112 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax));
1114 res.argmin = argmin;
1115 res.argmax = argmax;
1117 else if (range_type == VR_ANTI_RANGE)
1119 /* Handle anti-ranges if/when bug 71690 is resolved. */
1121 else if (range_type == VR_VARYING)
1123 /* The argument here may be the result of promoting the actual
1124 argument to int. Try to determine the type of the actual
1125 argument before promotion and narrow down its range that
1126 way. */
1127 gimple *def = SSA_NAME_DEF_STMT (arg);
1128 if (is_gimple_assign (def))
1130 tree_code code = gimple_assign_rhs_code (def);
1131 if (code == INTEGER_CST)
1133 arg = gimple_assign_rhs1 (def);
1134 return format_integer (spec, arg);
1137 if (code == NOP_EXPR)
1139 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1140 if (TREE_CODE (type) == INTEGER_TYPE
1141 || TREE_CODE (type) == POINTER_TYPE)
1142 argtype = type;
1148 if (!argmin)
1150 /* For an unknown argument (e.g., one passed to a vararg function)
1151 or one whose value range cannot be determined, create a T_MIN
1152 constant if the argument's type is signed and T_MAX otherwise,
1153 and use those to compute the range of bytes that the directive
1154 can output. When precision is specified but unknown, use zero
1155 as the minimum since it results in no bytes on output (unless
1156 width is specified to be greater than 0). */
1157 argmin = build_int_cst (argtype, prec && prec != HOST_WIDE_INT_MIN);
1159 int typeprec = TYPE_PRECISION (dirtype);
1160 int argprec = TYPE_PRECISION (argtype);
1162 if (argprec < typeprec)
1164 if (POINTER_TYPE_P (argtype))
1165 argmax = build_all_ones_cst (argtype);
1166 else if (TYPE_UNSIGNED (argtype))
1167 argmax = TYPE_MAX_VALUE (argtype);
1168 else
1169 argmax = TYPE_MIN_VALUE (argtype);
1171 else
1173 if (POINTER_TYPE_P (dirtype))
1174 argmax = build_all_ones_cst (dirtype);
1175 else if (TYPE_UNSIGNED (dirtype))
1176 argmax = TYPE_MAX_VALUE (dirtype);
1177 else
1178 argmax = TYPE_MIN_VALUE (dirtype);
1181 res.argmin = argmin;
1182 res.argmax = argmax;
1185 if (tree_int_cst_lt (argmax, argmin))
1187 tree tmp = argmax;
1188 argmax = argmin;
1189 argmin = tmp;
1192 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1193 of the directive. If it has been cleared then since ARGMIN and/or
1194 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1195 ARGMAX in the result to include in diagnostics. */
1196 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1198 res.knownrange = false;
1199 res.argmin = argmin;
1200 res.argmax = argmax;
1203 /* Recursively compute the minimum and maximum from the known range,
1204 taking care to swap them if the lower bound results in longer
1205 output than the upper bound (e.g., in the range [-1, 0]. */
1207 if (TYPE_UNSIGNED (dirtype))
1209 /* For unsigned conversions/directives, use the minimum (i.e., 0
1210 or 1) and maximum to compute the shortest and longest output,
1211 respectively. */
1212 res.range.min = format_integer (spec, argmin).range.min;
1213 res.range.max = format_integer (spec, argmax).range.max;
1215 else
1217 /* For signed conversions/directives, use the maximum (i.e., 0)
1218 to compute the shortest output and the minimum (i.e., TYPE_MIN)
1219 to compute the longest output. This is important when precision
1220 is specified but unknown because otherwise both output lengths
1221 would reflect the largest possible precision (i.e., INT_MAX). */
1222 res.range.min = format_integer (spec, argmax).range.min;
1223 res.range.max = format_integer (spec, argmin).range.max;
1226 /* The result is bounded either when the argument is determined to be
1227 (e.g., when it's within some range) or when the minimum and maximum
1228 are the same. That can happen here for example when the specified
1229 width is as wide as the greater of MIN and MAX, as would be the case
1230 with sprintf (d, "%08x", x) with a 32-bit integer x. */
1231 res.bounded |= res.range.min == res.range.max;
1233 if (res.range.max < res.range.min)
1235 unsigned HOST_WIDE_INT tmp = res.range.max;
1236 res.range.max = res.range.min;
1237 res.range.min = tmp;
1240 return res;
1243 /* Return the number of bytes that a format directive consisting of FLAGS,
1244 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1245 would result for argument X under ideal conditions (i.e., if PREC
1246 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1247 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1248 This function works around those problems. */
1250 static unsigned HOST_WIDE_INT
1251 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1252 char spec, char rndspec)
1254 char fmtstr[40];
1256 HOST_WIDE_INT len = strlen (flags);
1258 fmtstr[0] = '%';
1259 memcpy (fmtstr + 1, flags, len);
1260 memcpy (fmtstr + 1 + len, ".*R", 3);
1261 fmtstr[len + 4] = rndspec;
1262 fmtstr[len + 5] = spec;
1263 fmtstr[len + 6] = '\0';
1265 spec = TOUPPER (spec);
1266 if (spec == 'E' || spec == 'F')
1268 /* For %e, specify the precision explicitly since mpfr_sprintf
1269 does its own thing just to be different (see MPFR bug 21088). */
1270 if (prec < 0)
1271 prec = 6;
1273 else
1275 /* Avoid passing negative precisions with larger magnitude to MPFR
1276 to avoid exposing its bugs. (A negative precision is supposed
1277 to be ignored.) */
1278 if (prec < 0)
1279 prec = -1;
1282 HOST_WIDE_INT p = prec;
1284 if (spec == 'G')
1286 /* For G/g, precision gives the maximum number of significant
1287 digits which is bounded by LDBL_MAX_10_EXP, or, for a 128
1288 bit IEEE extended precision, 4932. Using twice as much
1289 here should be more than sufficient for any real format. */
1290 if ((IEEE_MAX_10_EXP * 2) < prec)
1291 prec = IEEE_MAX_10_EXP * 2;
1292 p = prec;
1294 else
1296 /* Cap precision arbitrarily at 1KB and add the difference
1297 (if any) to the MPFR result. */
1298 if (1024 < prec)
1299 p = 1024;
1302 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1304 /* Handle the unlikely (impossible?) error by returning more than
1305 the maximum dictated by the function's return type. */
1306 if (len < 0)
1307 return target_dir_max () + 1;
1309 /* Adjust the return value by the difference. */
1310 if (p < prec)
1311 len += prec - p;
1313 return len;
1316 /* Return the number of bytes to format using the format specifier
1317 SPEC and the precision PREC the largest value in the real floating
1318 TYPE. */
1320 static unsigned HOST_WIDE_INT
1321 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1323 machine_mode mode = TYPE_MODE (type);
1325 /* IBM Extended mode. */
1326 if (MODE_COMPOSITE_P (mode))
1327 mode = DFmode;
1329 /* Get the real type format desription for the target. */
1330 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1331 REAL_VALUE_TYPE rv;
1334 char buf[256];
1335 get_max_float (rfmt, buf, sizeof buf);
1336 real_from_string (&rv, buf);
1339 /* Convert the GCC real value representation with the precision
1340 of the real type to the mpfr_t format with the GCC default
1341 round-to-nearest mode. */
1342 mpfr_t x;
1343 mpfr_init2 (x, rfmt->p);
1344 mpfr_from_real (x, &rv, GMP_RNDN);
1346 /* Return a value one greater to account for the leading minus sign. */
1347 return 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1350 /* Return a range representing the minimum and maximum number of bytes
1351 that the conversion specification SPEC will output for any argument
1352 given the WIDTH and PRECISION (extracted from SPEC). This function
1353 is used when the directive argument or its value isn't known. */
1355 static fmtresult
1356 format_floating (const conversion_spec &spec, HOST_WIDE_INT width,
1357 HOST_WIDE_INT prec)
1359 tree type;
1361 switch (spec.modifier)
1363 case FMT_LEN_l:
1364 case FMT_LEN_none:
1365 type = double_type_node;
1366 break;
1368 case FMT_LEN_L:
1369 type = long_double_type_node;
1370 break;
1372 case FMT_LEN_ll:
1373 type = long_double_type_node;
1374 break;
1376 default:
1377 return fmtresult ();
1380 /* The minimum and maximum number of bytes produced by the directive. */
1381 fmtresult res;
1383 /* The result is always bounded (though the range may be all of int). */
1384 res.bounded = true;
1386 /* The minimum output as determined by flags. It's always at least 1. */
1387 int flagmin = (1 /* for the first digit */
1388 + (spec.get_flag ('+') | spec.get_flag (' '))
1389 + (prec == 0 && spec.get_flag ('#')));
1391 if (width == INT_MIN || prec == INT_MIN)
1393 /* When either width or precision is specified but unknown
1394 the upper bound is the maximum. Otherwise it will be
1395 computed for each directive below. */
1396 res.range.max = HOST_WIDE_INT_MAX;
1398 else
1399 res.range.max = HOST_WIDE_INT_M1U;
1401 switch (spec.specifier)
1403 case 'A':
1404 case 'a':
1406 res.range.min = flagmin + 5 + (prec > 0 ? prec + 1 : 0);
1407 if (res.range.max == HOST_WIDE_INT_M1U)
1409 /* Compute the upper bound for -TYPE_MAX. */
1410 res.range.max = format_floating_max (type, 'a', prec);
1413 break;
1416 case 'E':
1417 case 'e':
1419 /* The minimum output is "[-+]1.234567e+00" regardless
1420 of the value of the actual argument. */
1421 res.range.min = (flagmin
1422 + (prec == INT_MIN
1423 ? 0 : prec < 0 ? 7 : prec ? prec + 1 : 0)
1424 + 2 /* e+ */ + 2);
1426 if (res.range.max == HOST_WIDE_INT_M1U)
1428 /* MPFR uses a precision of 16 by default for some reason.
1429 Set it to the C default of 6. */
1430 res.range.max = format_floating_max (type, 'e',
1431 -1 == prec ? 6 : prec);
1433 break;
1436 case 'F':
1437 case 'f':
1439 /* The lower bound when precision isn't specified is 8 bytes
1440 ("1.23456" since precision is taken to be 6). When precision
1441 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1442 when precision is greater than zero, then the lower bound
1443 is 2 plus precision (plus flags). */
1444 res.range.min = (flagmin
1445 + (prec != INT_MIN) /* for decimal point */
1446 + (prec == INT_MIN
1447 ? 0 : prec < 0 ? 6 : prec ? prec : -1));
1449 if (res.range.max == HOST_WIDE_INT_M1U)
1451 /* Compute the upper bound for -TYPE_MAX. */
1452 res.range.max = format_floating_max (type, 'f', prec);
1454 break;
1457 case 'G':
1458 case 'g':
1460 /* The %g output depends on precision and the exponent of
1461 the argument. Since the value of the argument isn't known
1462 the lower bound on the range of bytes (not counting flags
1463 or width) is 1. */
1464 res.range.min = flagmin;
1465 if (res.range.max == HOST_WIDE_INT_M1U)
1467 /* Compute the upper bound for -TYPE_MAX which should be
1468 the lesser of %e and %f. */
1469 res.range.max = format_floating_max (type, 'g', prec);
1471 break;
1474 default:
1475 return fmtresult ();
1478 if (width > 0)
1480 /* If width has been specified use it to adjust the range. */
1481 if (res.range.min < (unsigned)width)
1482 res.range.min = width;
1483 if (res.range.max < (unsigned)width)
1484 res.range.max = width;
1487 return res;
1490 /* Return a range representing the minimum and maximum number of bytes
1491 that the conversion specification SPEC will write on output for the
1492 floating argument ARG. */
1494 static fmtresult
1495 format_floating (const conversion_spec &spec, tree arg)
1497 /* Set WIDTH to -1 when it's not specified, to HOST_WIDE_INT_MIN when
1498 it is specified by the asterisk to an unknown value, and otherwise
1499 to a non-negative value corresponding to the specified width. */
1500 HOST_WIDE_INT width = -1;
1501 HOST_WIDE_INT prec = -1;
1503 /* The minimum and maximum number of bytes produced by the directive. */
1504 fmtresult res;
1505 res.constant = arg && TREE_CODE (arg) == REAL_CST;
1507 if (spec.have_width)
1508 width = spec.width;
1509 else if (spec.star_width)
1511 if (TREE_CODE (spec.star_width) == INTEGER_CST)
1513 width = tree_to_shwi (spec.star_width);
1514 if (width < 0)
1515 width = -width;
1517 else
1518 width = INT_MIN;
1521 if (spec.have_precision)
1522 prec = spec.precision;
1523 else if (spec.star_precision)
1525 if (TREE_CODE (spec.star_precision) == INTEGER_CST)
1527 prec = tree_to_shwi (spec.star_precision);
1528 if (prec < 0)
1529 prec = -1;
1531 else
1532 prec = INT_MIN;
1534 else if (res.constant && TOUPPER (spec.specifier) != 'A')
1536 /* Specify the precision explicitly since mpfr_sprintf defaults
1537 to zero. */
1538 prec = 6;
1541 if (res.constant)
1543 /* Get the real type format desription for the target. */
1544 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1545 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1547 /* Convert the GCC real value representation with the precision
1548 of the real type to the mpfr_t format with the GCC default
1549 round-to-nearest mode. */
1550 mpfr_t mpfrval;
1551 mpfr_init2 (mpfrval, rfmt->p);
1552 mpfr_from_real (mpfrval, rvp, GMP_RNDN);
1554 char fmtstr [40];
1555 char *pfmt = fmtstr;
1557 /* Append flags. */
1558 for (const char *pf = "-+ #0"; *pf; ++pf)
1559 if (spec.get_flag (*pf))
1560 *pfmt++ = *pf;
1562 *pfmt = '\0';
1565 /* Set up an array to easily iterate over below. */
1566 unsigned HOST_WIDE_INT* const minmax[] = {
1567 &res.range.min, &res.range.max
1570 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1572 /* Use the MPFR rounding specifier to round down in the first
1573 iteration and then up. In most but not all cases this will
1574 result in the same number of bytes. */
1575 char rndspec = "DU"[i];
1577 /* Format it and store the result in the corresponding member
1578 of the result struct. */
1579 unsigned HOST_WIDE_INT len
1580 = get_mpfr_format_length (mpfrval, fmtstr, prec,
1581 spec.specifier, rndspec);
1582 if (0 < width && len < (unsigned)width)
1583 len = width;
1585 *minmax[i] = len;
1589 /* Make sure the minimum is less than the maximum (MPFR rounding
1590 in the call to mpfr_snprintf can result in the reverse. */
1591 if (res.range.max < res.range.min)
1593 unsigned HOST_WIDE_INT tmp = res.range.min;
1594 res.range.min = res.range.max;
1595 res.range.max = tmp;
1598 /* The range of output is known even if the result isn't bounded. */
1599 if (width == HOST_WIDE_INT_MIN)
1601 res.knownrange = false;
1602 res.range.max = HOST_WIDE_INT_MAX;
1604 else
1605 res.knownrange = true;
1607 /* The output of all directives except "%a" is fully specified
1608 and so the result is bounded unless it exceeds INT_MAX.
1609 For "%a" the output is fully specified only when precision
1610 is explicitly specified. */
1611 res.bounded = (res.knownrange
1612 && (TOUPPER (spec.specifier) != 'A'
1613 || (0 <= prec && (unsigned) prec < target_int_max ()))
1614 && res.range.min < target_int_max ());
1616 return res;
1619 return format_floating (spec, width, prec);
1622 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1623 strings referenced by the expression STR, or (-1, -1) when not known.
1624 Used by the format_string function below. */
1626 static fmtresult
1627 get_string_length (tree str)
1629 if (!str)
1630 return fmtresult ();
1632 if (tree slen = c_strlen (str, 1))
1634 /* Simply return the length of the string. */
1635 fmtresult res;
1636 res.range.min = res.range.max = tree_to_shwi (slen);
1637 res.bounded = true;
1638 res.constant = true;
1639 res.knownrange = true;
1640 return res;
1643 /* Determine the length of the shortest and longest string referenced
1644 by STR. Strings of unknown lengths are bounded by the sizes of
1645 arrays that subexpressions of STR may refer to. Pointers that
1646 aren't known to point any such arrays result in LENRANGE[1] set
1647 to SIZE_MAX. */
1648 tree lenrange[2];
1649 get_range_strlen (str, lenrange);
1651 if (lenrange [0] || lenrange [1])
1653 fmtresult res;
1655 res.range.min = (tree_fits_uhwi_p (lenrange[0])
1656 ? tree_to_uhwi (lenrange[0]) : warn_format_overflow > 1);
1657 res.range.max = (tree_fits_uhwi_p (lenrange[1])
1658 ? tree_to_uhwi (lenrange[1]) : HOST_WIDE_INT_M1U);
1660 /* Set RES.BOUNDED to true if and only if all strings referenced
1661 by STR are known to be bounded (though not necessarily by their
1662 actual length but perhaps by their maximum possible length). */
1663 res.bounded = res.range.max < target_int_max ();
1664 res.knownrange = res.bounded;
1666 /* Set RES.CONSTANT to false even though that may be overly
1667 conservative in rare cases like: 'x ? a : b' where a and
1668 b have the same lengths and consist of the same characters. */
1669 res.constant = false;
1671 return res;
1674 return get_string_length (NULL_TREE);
1677 /* Return the minimum and maximum number of characters formatted
1678 by the '%c' and '%s' format directives and ther wide character
1679 forms for the argument ARG. ARG can be null (for functions
1680 such as vsprinf). */
1682 static fmtresult
1683 format_string (const conversion_spec &spec, tree arg)
1685 /* Set WIDTH and PRECISION based on the specification. */
1686 HOST_WIDE_INT width;
1687 HOST_WIDE_INT prec;
1688 get_width_and_precision (spec, &width, &prec);
1690 fmtresult res;
1692 /* The maximum number of bytes for an unknown wide character argument
1693 to a "%lc" directive adjusted for precision but not field width.
1694 6 is the longest UTF-8 sequence for a single wide character. */
1695 const unsigned HOST_WIDE_INT max_bytes_for_unknown_wc
1696 = (0 <= prec ? prec : warn_format_overflow > 1 ? 6 : 1);
1698 /* The maximum number of bytes for an unknown string argument to either
1699 a "%s" or "%ls" directive adjusted for precision but not field width. */
1700 const unsigned HOST_WIDE_INT max_bytes_for_unknown_str
1701 = (0 <= prec ? prec : warn_format_overflow > 1);
1703 /* The result is bounded unless overriddden for a non-constant string
1704 of an unknown length. */
1705 bool bounded = true;
1707 if (spec.specifier == 'c')
1709 if (spec.modifier == FMT_LEN_l)
1711 /* Positive if the argument is a wide NUL character? */
1712 int nul = (arg && TREE_CODE (arg) == INTEGER_CST
1713 ? integer_zerop (arg) : -1);
1715 /* A '%lc' directive is the same as '%ls' for a two element
1716 wide string character with the second element of NUL, so
1717 when the character is unknown the minimum number of bytes
1718 is the smaller of either 0 (at level 1) or 1 (at level 2)
1719 and WIDTH, and the maximum is MB_CUR_MAX in the selected
1720 locale, which is unfortunately, unknown. */
1721 res.range.min = warn_format_overflow == 1 ? !nul : nul < 1;
1722 res.range.max = max_bytes_for_unknown_wc;
1723 /* The range above is good enough to issue warnings but not
1724 for value range propagation, so clear BOUNDED. */
1725 res.bounded = false;
1727 else
1729 /* A plain '%c' directive. Its ouput is exactly 1. */
1730 res.range.min = res.range.max = 1;
1731 res.bounded = true;
1732 res.knownrange = true;
1733 res.constant = arg && TREE_CODE (arg) == INTEGER_CST;
1736 else /* spec.specifier == 's' */
1738 /* Compute the range the argument's length can be in. */
1739 fmtresult slen = get_string_length (arg);
1740 if (slen.constant)
1742 gcc_checking_assert (slen.range.min == slen.range.max);
1744 /* A '%s' directive with a string argument with constant length. */
1745 res.range = slen.range;
1747 /* The output of "%s" and "%ls" directives with a constant
1748 string is in a known range unless width of an unknown value
1749 is specified. For "%s" it is the length of the string. For
1750 "%ls" it is in the range [length, length * MB_LEN_MAX].
1751 (The final range can be further constrained by width and
1752 precision but it's always known.) */
1753 res.knownrange = -1 < width;
1755 if (spec.modifier == FMT_LEN_l)
1757 bounded = false;
1759 if (warn_format_overflow > 1)
1761 /* Leave the minimum number of bytes the wide string
1762 converts to equal to its length and set the maximum
1763 to the worst case length which is the string length
1764 multiplied by MB_LEN_MAX. */
1766 /* It's possible to be smarter about computing the maximum
1767 by scanning the wide string for any 8-bit characters and
1768 if it contains none, using its length for the maximum.
1769 Even though this would be simple to do it's unlikely to
1770 be worth it when dealing with wide characters. */
1771 res.range.max *= target_mb_len_max;
1774 /* For a wide character string, use precision as the maximum
1775 even if precision is greater than the string length since
1776 the number of bytes the string converts to may be greater
1777 (due to MB_CUR_MAX). */
1778 if (0 <= prec)
1779 res.range.max = prec;
1781 else if (0 <= width)
1783 /* The output of a "%s" directive with a constant argument
1784 and constant or no width is bounded. It is constant if
1785 precision is either not specified or it is specified and
1786 its value is known. */
1787 res.bounded = true;
1788 res.constant = prec != HOST_WIDE_INT_MIN;
1790 else if (width == HOST_WIDE_INT_MIN)
1792 /* Specified but unknown width makes the output unbounded. */
1793 res.range.max = HOST_WIDE_INT_MAX;
1796 if (0 <= prec && (unsigned HOST_WIDE_INT)prec < res.range.min)
1798 res.range.min = prec;
1799 res.range.max = prec;
1801 else if (prec == HOST_WIDE_INT_MIN)
1803 /* When precision is specified but not known the lower
1804 bound is assumed to be as low as zero. */
1805 res.range.min = 0;
1808 else if (arg && integer_zerop (arg))
1810 /* Handle null pointer argument. */
1812 fmtresult res;
1813 res.range.min = 0;
1814 res.range.max = HOST_WIDE_INT_MAX;
1815 res.nullp = true;
1816 return res;
1818 else
1820 /* For a '%s' and '%ls' directive with a non-constant string,
1821 the minimum number of characters is the greater of WIDTH
1822 and either 0 in mode 1 or the smaller of PRECISION and 1
1823 in mode 2, and the maximum is PRECISION or -1 to disable
1824 tracking. */
1826 if (0 <= prec)
1828 if (slen.range.min >= target_int_max ())
1829 slen.range.min = 0;
1830 else if ((unsigned HOST_WIDE_INT)prec < slen.range.min)
1831 slen.range.min = prec;
1833 if ((unsigned HOST_WIDE_INT)prec < slen.range.max
1834 || slen.range.max >= target_int_max ())
1835 slen.range.max = prec;
1837 else if (slen.range.min >= target_int_max ())
1839 slen.range.min = max_bytes_for_unknown_str;
1840 slen.range.max = max_bytes_for_unknown_str;
1841 bounded = false;
1844 res.range = slen.range;
1846 /* The output is considered bounded when a precision has been
1847 specified to limit the number of bytes or when the number
1848 of bytes is known or contrained to some range. */
1849 res.bounded = 0 <= prec || slen.bounded;
1850 res.knownrange = slen.knownrange;
1851 res.constant = false;
1855 /* Adjust the lengths for field width. */
1856 if (0 < width)
1858 if (res.range.min < (unsigned HOST_WIDE_INT)width)
1859 res.range.min = width;
1861 if (res.range.max < (unsigned HOST_WIDE_INT)width)
1862 res.range.max = width;
1864 /* Adjust BOUNDED if width happens to make them equal. */
1865 if (res.range.min == res.range.max && res.range.min < target_int_max ()
1866 && bounded)
1867 res.bounded = true;
1870 /* When precision is specified the range of characters on output
1871 is known to be bounded by it. */
1872 if (-1 < width && -1 < prec)
1873 res.knownrange = true;
1875 return res;
1878 /* Compute the length of the output resulting from the conversion
1879 specification SPEC with the argument ARG in a call described by INFO
1880 and update the overall result of the call in *RES. The format directive
1881 corresponding to SPEC starts at CVTBEG and is CVTLEN characters long. */
1883 static void
1884 format_directive (const pass_sprintf_length::call_info &info,
1885 format_result *res, const char *cvtbeg, size_t cvtlen,
1886 const conversion_spec &spec, tree arg)
1888 /* Offset of the beginning of the directive from the beginning
1889 of the format string. */
1890 size_t offset = cvtbeg - info.fmtstr;
1892 /* Create a location for the whole directive from the % to the format
1893 specifier. */
1894 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
1895 offset, offset, offset + cvtlen - 1);
1897 /* Also create a location range for the argument if possible.
1898 This doesn't work for integer literals or function calls. */
1899 source_range argrange;
1900 source_range *pargrange;
1901 if (arg && CAN_HAVE_LOCATION_P (arg))
1903 argrange = EXPR_LOCATION_RANGE (arg);
1904 pargrange = &argrange;
1906 else
1907 pargrange = NULL;
1909 /* Bail when there is no function to compute the output length,
1910 or when minimum length checking has been disabled. */
1911 if (!spec.fmtfunc || res->number_chars_min >= HOST_WIDE_INT_MAX)
1912 return;
1914 /* Compute the (approximate) length of the formatted output. */
1915 fmtresult fmtres = spec.fmtfunc (spec, arg);
1917 /* The overall result is bounded and constant only if the output
1918 of every directive is bounded and constant, respectively. */
1919 res->bounded &= fmtres.bounded;
1920 res->constant &= fmtres.constant;
1922 /* Record whether the output of all directives is known to be
1923 bounded by some maximum, implying that their arguments are
1924 either known exactly or determined to be in a known range
1925 or, for strings, limited by the upper bounds of the arrays
1926 they refer to. */
1927 res->knownrange &= fmtres.knownrange;
1929 if (!fmtres.knownrange)
1931 /* Only when the range is known, check it against the host value
1932 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
1933 INT_MAX precision, which is the longest possible output of any
1934 single directive). That's the largest valid byte count (though
1935 not valid call to a printf-like function because it can never
1936 return such a count). Otherwise, the range doesn't correspond
1937 to known values of the argument. */
1938 if (fmtres.range.max > target_dir_max ())
1940 /* Normalize the MAX counter to avoid having to deal with it
1941 later. The counter can be less than HOST_WIDE_INT_M1U
1942 when compiling for an ILP32 target on an LP64 host. */
1943 fmtres.range.max = HOST_WIDE_INT_M1U;
1944 /* Disable exact and maximum length checking after a failure
1945 to determine the maximum number of characters (for example
1946 for wide characters or wide character strings) but continue
1947 tracking the minimum number of characters. */
1948 res->number_chars_max = HOST_WIDE_INT_M1U;
1949 res->number_chars = HOST_WIDE_INT_M1U;
1952 if (fmtres.range.min > target_dir_max ())
1954 /* Disable exact length checking after a failure to determine
1955 even the minimum number of characters (it shouldn't happen
1956 except in an error) but keep tracking the minimum and maximum
1957 number of characters. */
1958 res->number_chars = HOST_WIDE_INT_M1U;
1959 return;
1963 if (fmtres.nullp)
1965 fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
1966 "%<%.*s%> directive argument is null",
1967 (int)cvtlen, cvtbeg);
1969 /* Don't bother processing the rest of the format string. */
1970 res->warned = true;
1971 res->number_chars = HOST_WIDE_INT_M1U;
1972 res->number_chars_min = res->number_chars_max = res->number_chars;
1973 return;
1976 bool warned = res->warned;
1978 /* Compute the number of available bytes in the destination. There
1979 must always be at least one byte of space for the terminating
1980 NUL that's appended after the format string has been processed. */
1981 unsigned HOST_WIDE_INT navail = min_bytes_remaining (info.objsize, *res);
1983 if (fmtres.range.min < fmtres.range.max)
1985 /* The result is a range (i.e., it's inexact). */
1986 if (!warned)
1988 if (navail < fmtres.range.min)
1990 /* The minimum directive output is longer than there is
1991 room in the destination. */
1992 if (fmtres.range.min == fmtres.range.max)
1994 const char* fmtstr
1995 = (info.bounded
1996 ? G_("%<%.*s%> directive output truncated writing "
1997 "%wu bytes into a region of size %wu")
1998 : G_("%<%.*s%> directive writing %wu bytes "
1999 "into a region of size %wu"));
2000 warned = fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
2001 fmtstr,
2002 (int)cvtlen, cvtbeg, fmtres.range.min,
2003 navail);
2005 else if (fmtres.range.max < HOST_WIDE_INT_MAX)
2007 const char* fmtstr
2008 = (info.bounded
2009 ? G_("%<%.*s%> directive output truncated writing "
2010 "between %wu and %wu bytes into a region of "
2011 "size %wu")
2012 : G_("%<%.*s%> directive writing between %wu and "
2013 "%wu bytes into a region of size %wu"));
2014 warned = fmtwarn (dirloc, pargrange, NULL,
2015 info.warnopt (), fmtstr,
2016 (int)cvtlen, cvtbeg,
2017 fmtres.range.min, fmtres.range.max, navail);
2019 else
2021 const char* fmtstr
2022 = (info.bounded
2023 ? G_("%<%.*s%> directive output truncated writing "
2024 "%wu or more bytes into a region of size %wu")
2025 : G_("%<%.*s%> directive writing %wu or more bytes "
2026 "into a region of size %wu"));
2027 warned = fmtwarn (dirloc, pargrange, NULL,
2028 info.warnopt (), fmtstr,
2029 (int)cvtlen, cvtbeg,
2030 fmtres.range.min, navail);
2033 else if (navail < fmtres.range.max
2034 && (spec.specifier != 's'
2035 || fmtres.range.max < HOST_WIDE_INT_MAX)
2036 && ((info.bounded
2037 && (!info.retval_used ()
2038 || warn_format_trunc > 1))
2039 || (!info.bounded
2040 && (spec.specifier == 's'
2041 || warn_format_overflow > 1))))
2043 /* The maximum directive output is longer than there is
2044 room in the destination and the output length is either
2045 explicitly constrained by the precision (for strings)
2046 or the warning level is greater than 1. */
2047 if (fmtres.range.max >= HOST_WIDE_INT_MAX)
2049 const char* fmtstr
2050 = (info.bounded
2051 ? G_("%<%.*s%> directive output may be truncated "
2052 "writing %wu or more bytes into a region "
2053 "of size %wu")
2054 : G_("%<%.*s%> directive writing %wu or more bytes "
2055 "into a region of size %wu"));
2056 warned = fmtwarn (dirloc, pargrange, NULL,
2057 info.warnopt (), fmtstr,
2058 (int)cvtlen, cvtbeg,
2059 fmtres.range.min, navail);
2061 else
2063 const char* fmtstr
2064 = (info.bounded
2065 ? G_("%<%.*s%> directive output may be truncated "
2066 "writing between %wu and %wu bytes into a region "
2067 "of size %wu")
2068 : G_("%<%.*s%> directive writing between %wu and %wu "
2069 "bytes into a region of size %wu"));
2070 warned = fmtwarn (dirloc, pargrange, NULL,
2071 info.warnopt (), fmtstr,
2072 (int)cvtlen, cvtbeg,
2073 fmtres.range.min, fmtres.range.max,
2074 navail);
2079 /* Disable exact length checking but adjust the minimum and maximum. */
2080 res->number_chars = HOST_WIDE_INT_M1U;
2081 if (res->number_chars_max < HOST_WIDE_INT_MAX
2082 && fmtres.range.max < HOST_WIDE_INT_MAX)
2083 res->number_chars_max += fmtres.range.max;
2085 res->number_chars_min += fmtres.range.min;
2087 else
2089 if (!warned && fmtres.range.min > 0 && navail < fmtres.range.min)
2091 const char* fmtstr
2092 = (info.bounded
2093 ? (1 < fmtres.range.min
2094 ? G_("%<%.*s%> directive output truncated while writing "
2095 "%wu bytes into a region of size %wu")
2096 : G_("%<%.*s%> directive output truncated while writing "
2097 "%wu byte into a region of size %wu"))
2098 : (1 < fmtres.range.min
2099 ? G_("%<%.*s%> directive writing %wu bytes "
2100 "into a region of size %wu")
2101 : G_("%<%.*s%> directive writing %wu byte "
2102 "into a region of size %wu")));
2104 warned = fmtwarn (dirloc, pargrange, NULL,
2105 info.warnopt (), fmtstr,
2106 (int)cvtlen, cvtbeg, fmtres.range.min,
2107 navail);
2109 *res += fmtres.range.min;
2112 /* Has the minimum directive output length exceeded the maximum
2113 of 4095 bytes required to be supported? */
2114 bool minunder4k = fmtres.range.min < 4096;
2115 if (!minunder4k || fmtres.range.max > 4095)
2116 res->under4k = false;
2118 if (!warned && warn_format_overflow > 1
2119 && (!minunder4k || fmtres.range.max > 4095))
2121 /* The directive output may be longer than the maximum required
2122 to be handled by an implementation according to 7.21.6.1, p15
2123 of C11. Warn on this only at level 2 but remember this and
2124 prevent folding the return value when done. This allows for
2125 the possibility of the actual libc call failing due to ENOMEM
2126 (like Glibc does under some conditions). */
2128 if (fmtres.range.min == fmtres.range.max)
2129 warned = fmtwarn (dirloc, pargrange, NULL,
2130 info.warnopt (),
2131 "%<%.*s%> directive output of %wu bytes exceeds "
2132 "minimum required size of 4095",
2133 (int)cvtlen, cvtbeg, fmtres.range.min);
2134 else
2136 const char *fmtstr
2137 = (minunder4k
2138 ? G_("%<%.*s%> directive output between %qu and %wu "
2139 "bytes may exceed minimum required size of 4095")
2140 : G_("%<%.*s%> directive output between %qu and %wu "
2141 "bytes exceeds minimum required size of 4095"));
2143 warned = fmtwarn (dirloc, pargrange, NULL,
2144 info.warnopt (), fmtstr,
2145 (int)cvtlen, cvtbeg,
2146 fmtres.range.min, fmtres.range.max);
2150 /* Has the minimum directive output length exceeded INT_MAX? */
2151 bool exceedmin = res->number_chars_min > target_int_max ();
2153 if (!warned
2154 && (exceedmin
2155 || (warn_format_overflow > 1
2156 && res->number_chars_max > target_int_max ())))
2158 /* The directive output causes the total length of output
2159 to exceed INT_MAX bytes. */
2161 if (fmtres.range.min == fmtres.range.max)
2162 warned = fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
2163 "%<%.*s%> directive output of %wu bytes causes "
2164 "result to exceed %<INT_MAX%>",
2165 (int)cvtlen, cvtbeg, fmtres.range.min);
2166 else
2168 const char *fmtstr
2169 = (exceedmin
2170 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2171 "bytes causes result to exceed %<INT_MAX%>")
2172 : G_ ("%<%.*s%> directive output between %wu and %wu "
2173 "bytes may cause result to exceed %<INT_MAX%>"));
2174 warned = fmtwarn (dirloc, pargrange, NULL,
2175 info.warnopt (), fmtstr,
2176 (int)cvtlen, cvtbeg,
2177 fmtres.range.min, fmtres.range.max);
2181 if (warned && fmtres.argmin)
2183 if (fmtres.argmin == fmtres.argmax)
2184 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2185 else if (fmtres.knownrange)
2186 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2187 fmtres.argmin, fmtres.argmax);
2188 else
2189 inform (info.fmtloc,
2190 "using the range [%E, %E] for directive argument",
2191 fmtres.argmin, fmtres.argmax);
2194 res->warned |= warned;
2197 /* Account for the number of bytes between BEG and END (or between
2198 BEG + strlen (BEG) when END is null) in the format string in a call
2199 to a formatted output function described by INFO. Reflect the count
2200 in RES and issue warnings as appropriate. */
2202 static void
2203 add_bytes (const pass_sprintf_length::call_info &info,
2204 const char *beg, const char *end, format_result *res)
2206 if (res->number_chars_min >= HOST_WIDE_INT_MAX)
2207 return;
2209 /* The number of bytes to output is the number of bytes between
2210 the end of the last directive and the beginning of the next
2211 one if it exists, otherwise the number of characters remaining
2212 in the format string plus 1 for the terminating NUL. */
2213 size_t nbytes = end ? end - beg : strlen (beg) + 1;
2215 /* Return if there are no bytes to add at this time but there are
2216 directives remaining in the format string. */
2217 if (!nbytes)
2218 return;
2220 /* Compute the range of available bytes in the destination. There
2221 must always be at least one byte left for the terminating NUL
2222 that's appended after the format string has been processed. */
2223 result_range avail_range = bytes_remaining (info.objsize, *res);
2225 /* If issuing a diagnostic (only when one hasn't already been issued),
2226 distinguish between a possible overflow ("may write") and a certain
2227 overflow somewhere "past the end." (Ditto for truncation.)
2228 KNOWNRANGE is used to warn even at level 1 about possibly writing
2229 past the end or truncation due to strings of unknown lengths that
2230 are bounded by the arrays they are known to refer to. */
2231 if (!res->warned
2232 && (avail_range.max < nbytes
2233 || ((res->knownrange || warn_format_overflow > 1)
2234 && avail_range.min < nbytes)))
2236 /* Set NAVAIL to the number of available bytes used to decide
2237 whether or not to issue a warning below. The exact kind of
2238 warning will depend on AVAIL_RANGE. */
2239 unsigned HOST_WIDE_INT navail = avail_range.max;
2240 if (nbytes <= navail && avail_range.min < HOST_WIDE_INT_MAX
2241 && (res->knownrange || warn_format_overflow > 1))
2242 navail = avail_range.min;
2244 /* Compute the offset of the first format character that is beyond
2245 the end of the destination region and the length of the rest of
2246 the format string from that point on. */
2247 unsigned HOST_WIDE_INT off
2248 = (unsigned HOST_WIDE_INT)(beg - info.fmtstr) + navail;
2250 size_t len = strlen (info.fmtstr + off);
2252 /* Create a location that underscores the substring of the format
2253 string that is or may be written past the end (or is or may be
2254 truncated), pointing the caret at the first character of the
2255 substring. */
2256 substring_loc loc
2257 (info.fmtloc, TREE_TYPE (info.format), off, len ? off : 0,
2258 off + len - !!len);
2260 /* Is the output of the last directive the result of the argument
2261 being within a range whose lower bound would fit in the buffer
2262 but the upper bound would not? If so, use the word "may" to
2263 indicate that the overflow/truncation may (but need not) happen. */
2264 bool boundrange
2265 = (res->number_chars_min < res->number_chars_max
2266 && res->number_chars_min + nbytes <= info.objsize);
2268 if (!end && ((nbytes - navail) == 1 || boundrange))
2270 /* There is room for the rest of the format string but none
2271 for the terminating nul. */
2272 const char *text
2273 = (info.bounded // Snprintf and the like.
2274 ? (boundrange
2275 ? G_("output may be truncated before the last format character"
2276 : "output truncated before the last format character"))
2277 : (boundrange
2278 ? G_("may write a terminating nul past the end "
2279 "of the destination")
2280 : G_("writing a terminating nul past the end "
2281 "of the destination")));
2283 if (!info.bounded
2284 || !boundrange
2285 || !info.retval_used ()
2286 || warn_format_trunc > 1)
2287 res->warned = fmtwarn (loc, NULL, NULL, info.warnopt (), text);
2289 else
2291 /* There isn't enough room for 1 or more characters that remain
2292 to copy from the format string. */
2293 const char *text
2294 = (info.bounded // Snprintf and the like.
2295 ? (boundrange
2296 ? G_("output may be truncated at or before format character "
2297 "%qc at offset %wu")
2298 : G_("output truncated at format character %qc at offset %wu"))
2299 : (res->number_chars >= HOST_WIDE_INT_MAX
2300 ? G_("may write format character %#qc at offset %wu past "
2301 "the end of the destination")
2302 : G_("writing format character %#qc at offset %wu past "
2303 "the end of the destination")));
2305 if (!info.bounded
2306 || !boundrange
2307 || !info.retval_used ()
2308 || warn_format_trunc > 1)
2309 res->warned = fmtwarn (loc, NULL, NULL, info.warnopt (),
2310 text, info.fmtstr[off], off);
2314 if (res->warned && !end && info.objsize < HOST_WIDE_INT_MAX)
2316 /* If a warning has been issued for buffer overflow or truncation
2317 (but not otherwise) help the user figure out how big a buffer
2318 they need. */
2320 location_t callloc = gimple_location (info.callstmt);
2322 unsigned HOST_WIDE_INT min = res->number_chars_min;
2323 unsigned HOST_WIDE_INT max = res->number_chars_max;
2324 unsigned HOST_WIDE_INT exact
2325 = (res->number_chars < HOST_WIDE_INT_MAX
2326 ? res->number_chars : res->number_chars_min);
2328 if (min < max && max < HOST_WIDE_INT_MAX)
2329 inform (callloc,
2330 "format output between %wu and %wu bytes into "
2331 "a destination of size %wu",
2332 min + nbytes, max + nbytes, info.objsize);
2333 else
2334 inform (callloc,
2335 (nbytes + exact == 1
2336 ? G_("format output %wu byte into a destination of size %wu")
2337 : G_("format output %wu bytes into a destination of size %wu")),
2338 nbytes + exact, info.objsize);
2341 /* Add the number of bytes and then check for INT_MAX overflow. */
2342 *res += nbytes;
2344 /* Has the minimum output length minus the terminating nul exceeded
2345 INT_MAX? */
2346 bool exceedmin = (res->number_chars_min - !end) > target_int_max ();
2348 if (!res->warned
2349 && (exceedmin
2350 || (warn_format_overflow > 1
2351 && (res->number_chars_max - !end) > target_int_max ())))
2353 /* The function's output exceeds INT_MAX bytes. */
2355 /* Set NAVAIL to the number of available bytes used to decide
2356 whether or not to issue a warning below. The exact kind of
2357 warning will depend on AVAIL_RANGE. */
2358 unsigned HOST_WIDE_INT navail = avail_range.max;
2359 if (nbytes <= navail && avail_range.min < HOST_WIDE_INT_MAX
2360 && (res->bounded || warn_format_overflow > 1))
2361 navail = avail_range.min;
2363 /* Compute the offset of the first format character that is beyond
2364 the end of the destination region and the length of the rest of
2365 the format string from that point on. */
2366 unsigned HOST_WIDE_INT off = (unsigned HOST_WIDE_INT)(beg - info.fmtstr);
2367 if (navail < HOST_WIDE_INT_MAX)
2368 off += navail;
2370 size_t len = strlen (info.fmtstr + off);
2372 substring_loc loc
2373 (info.fmtloc, TREE_TYPE (info.format), off - !len, len ? off : 0,
2374 off + len - !!len);
2376 if (res->number_chars_min == res->number_chars_max)
2377 res->warned = fmtwarn (loc, NULL, NULL, info.warnopt (),
2378 "output of %wu bytes causes "
2379 "result to exceed %<INT_MAX%>",
2380 res->number_chars_min - !end);
2381 else
2383 const char *text
2384 = (exceedmin
2385 ? G_ ("output between %wu and %wu bytes causes "
2386 "result to exceed %<INT_MAX%>")
2387 : G_ ("output between %wu and %wu bytes may cause "
2388 "result to exceed %<INT_MAX%>"));
2389 res->warned = fmtwarn (loc, NULL, NULL, info.warnopt (), text,
2390 res->number_chars_min - !end,
2391 res->number_chars_max - !end);
2396 #pragma GCC diagnostic pop
2398 /* Compute the length of the output resulting from the call to a formatted
2399 output function described by INFO and store the result of the call in
2400 *RES. Issue warnings for detected past the end writes. Return true
2401 if the complete format string has been processed and *RES can be relied
2402 on, false otherwise (e.g., when a unknown or unhandled directive was seen
2403 that caused the processing to be terminated early). */
2405 bool
2406 pass_sprintf_length::compute_format_length (call_info &info,
2407 format_result *res)
2409 /* The variadic argument counter. */
2410 unsigned argno = info.argidx;
2412 /* Reset exact, minimum, and maximum character counters. */
2413 res->number_chars = res->number_chars_min = res->number_chars_max = 0;
2415 /* No directive has been seen yet so the length of output is bounded
2416 by the known range [0, 0] and constant (with no conversion producing
2417 more than 4K bytes) until determined otherwise. */
2418 res->bounded = true;
2419 res->knownrange = true;
2420 res->constant = true;
2421 res->under4k = true;
2422 res->floating = false;
2423 res->warned = false;
2425 const char *pf = info.fmtstr;
2427 for ( ; ; )
2429 /* The beginning of the next format directive. */
2430 const char *dir = strchr (pf, '%');
2432 /* Add the number of bytes between the end of the last directive
2433 and either the next if one exists, or the end of the format
2434 string. */
2435 add_bytes (info, pf, dir, res);
2437 if (!dir)
2438 break;
2440 pf = dir + 1;
2442 if (0 && *pf == 0)
2444 /* Incomplete directive. */
2445 return false;
2448 conversion_spec spec = conversion_spec ();
2450 /* POSIX numbered argument index or zero when none. */
2451 unsigned dollar = 0;
2453 if (ISDIGIT (*pf))
2455 /* This could be either a POSIX positional argument, the '0'
2456 flag, or a width, depending on what follows. Store it as
2457 width and sort it out later after the next character has
2458 been seen. */
2459 char *end;
2460 spec.width = strtol (pf, &end, 10);
2461 spec.have_width = true;
2462 pf = end;
2464 else if ('*' == *pf)
2466 /* Similarly to the block above, this could be either a POSIX
2467 positional argument or a width, depending on what follows. */
2468 if (argno < gimple_call_num_args (info.callstmt))
2469 spec.star_width = gimple_call_arg (info.callstmt, argno++);
2470 else
2471 spec.star_width = void_node;
2472 ++pf;
2475 if (*pf == '$')
2477 /* Handle the POSIX dollar sign which references the 1-based
2478 positional argument number. */
2479 if (spec.have_width)
2480 dollar = spec.width + info.argidx;
2481 else if (spec.star_width
2482 && TREE_CODE (spec.star_width) == INTEGER_CST)
2483 dollar = spec.width + tree_to_shwi (spec.star_width);
2485 /* Bail when the numbered argument is out of range (it will
2486 have already been diagnosed by -Wformat). */
2487 if (dollar == 0
2488 || dollar == info.argidx
2489 || dollar > gimple_call_num_args (info.callstmt))
2490 return false;
2492 --dollar;
2494 spec.star_width = NULL_TREE;
2495 spec.have_width = false;
2496 ++pf;
2499 if (dollar || !spec.star_width)
2501 if (spec.have_width)
2503 if (spec.width == 0)
2505 /* The '0' that has been interpreted as a width above is
2506 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
2507 and continue processing other flags. */
2508 spec.have_width = false;
2509 spec.set_flag ('0');
2511 else if (!dollar)
2513 /* (Non-zero) width has been seen. The next character
2514 is either a period or a digit. */
2515 goto start_precision;
2518 /* When either '$' has been seen, or width has not been seen,
2519 the next field is the optional flags followed by an optional
2520 width. */
2521 for ( ; ; ) {
2522 switch (*pf)
2524 case ' ':
2525 case '0':
2526 case '+':
2527 case '-':
2528 case '#':
2529 spec.set_flag (*pf++);
2530 break;
2532 default:
2533 goto start_width;
2537 start_width:
2538 if (ISDIGIT (*pf))
2540 char *end;
2541 spec.width = strtol (pf, &end, 10);
2542 spec.have_width = true;
2543 pf = end;
2545 else if ('*' == *pf)
2547 if (argno < gimple_call_num_args (info.callstmt))
2548 spec.star_width = gimple_call_arg (info.callstmt, argno++);
2549 else
2550 spec.star_width = void_node;
2551 ++pf;
2553 else if ('\'' == *pf)
2555 /* The POSIX apostrophe indicating a numeric grouping
2556 in the current locale. Even though it's possible to
2557 estimate the upper bound on the size of the output
2558 based on the number of digits it probably isn't worth
2559 continuing. */
2560 return false;
2564 start_precision:
2565 if ('.' == *pf)
2567 ++pf;
2569 if (ISDIGIT (*pf))
2571 char *end;
2572 spec.precision = strtol (pf, &end, 10);
2573 spec.have_precision = true;
2574 pf = end;
2576 else if ('*' == *pf)
2578 if (argno < gimple_call_num_args (info.callstmt))
2579 spec.star_precision = gimple_call_arg (info.callstmt, argno++);
2580 else
2581 spec.star_precision = void_node;
2582 ++pf;
2584 else
2586 /* The decimal precision or the asterisk are optional.
2587 When neither is specified it's taken to be zero. */
2588 spec.precision = 0;
2589 spec.have_precision = true;
2593 switch (*pf)
2595 case 'h':
2596 if (pf[1] == 'h')
2598 ++pf;
2599 spec.modifier = FMT_LEN_hh;
2601 else
2602 spec.modifier = FMT_LEN_h;
2603 ++pf;
2604 break;
2606 case 'j':
2607 spec.modifier = FMT_LEN_j;
2608 ++pf;
2609 break;
2611 case 'L':
2612 spec.modifier = FMT_LEN_L;
2613 ++pf;
2614 break;
2616 case 'l':
2617 if (pf[1] == 'l')
2619 ++pf;
2620 spec.modifier = FMT_LEN_ll;
2622 else
2623 spec.modifier = FMT_LEN_l;
2624 ++pf;
2625 break;
2627 case 't':
2628 spec.modifier = FMT_LEN_t;
2629 ++pf;
2630 break;
2632 case 'z':
2633 spec.modifier = FMT_LEN_z;
2634 ++pf;
2635 break;
2638 switch (*pf)
2640 /* Handle a sole '%' character the same as "%%" but since it's
2641 undefined prevent the result from being folded. */
2642 case '\0':
2643 --pf;
2644 res->bounded = false;
2645 /* FALLTHRU */
2646 case '%':
2647 spec.fmtfunc = format_percent;
2648 break;
2650 case 'a':
2651 case 'A':
2652 case 'e':
2653 case 'E':
2654 case 'f':
2655 case 'F':
2656 case 'g':
2657 case 'G':
2658 res->floating = true;
2659 spec.fmtfunc = format_floating;
2660 break;
2662 case 'd':
2663 case 'i':
2664 case 'o':
2665 case 'u':
2666 case 'x':
2667 case 'X':
2668 spec.fmtfunc = format_integer;
2669 break;
2671 case 'p':
2672 /* The %p output is implementation-defined. It's possible
2673 to determine this format but due to extensions (especially
2674 those of the Linux kernel -- see bug 78512) the first %p
2675 in the format string disables any further processing. */
2676 return false;
2678 case 'n':
2679 /* %n has side-effects even when nothing is actually printed to
2680 any buffer. */
2681 info.nowrite = false;
2682 break;
2684 case 'c':
2685 case 'S':
2686 case 's':
2687 spec.fmtfunc = format_string;
2688 break;
2690 default:
2691 /* Unknown conversion specification. */
2692 return false;
2695 spec.specifier = *pf++;
2697 /* Compute the length of the format directive. */
2698 size_t dirlen = pf - dir;
2700 /* Extract the argument if the directive takes one and if it's
2701 available (e.g., the function doesn't take a va_list). Treat
2702 missing arguments the same as va_list, even though they will
2703 have likely already been diagnosed by -Wformat. */
2704 tree arg = NULL_TREE;
2705 if (spec.specifier != '%'
2706 && argno < gimple_call_num_args (info.callstmt))
2707 arg = gimple_call_arg (info.callstmt, dollar ? dollar : argno++);
2709 ::format_directive (info, res, dir, dirlen, spec, arg);
2712 /* Complete format string was processed (with or without warnings). */
2713 return true;
2716 /* Return the size of the object referenced by the expression DEST if
2717 available, or -1 otherwise. */
2719 static unsigned HOST_WIDE_INT
2720 get_destination_size (tree dest)
2722 /* Use __builtin_object_size to determine the size of the destination
2723 object. When optimizing, determine the smallest object (such as
2724 a member array as opposed to the whole enclosing object), otherwise
2725 use type-zero object size to determine the size of the enclosing
2726 object (the function fails without optimization in this type). */
2728 init_object_sizes ();
2730 int ost = optimize > 0;
2731 unsigned HOST_WIDE_INT size;
2732 if (compute_builtin_object_size (dest, ost, &size))
2733 return size;
2735 return HOST_WIDE_INT_M1U;
2738 /* Given a suitable result RES of a call to a formatted output function
2739 described by INFO, substitute the result for the return value of
2740 the call. The result is suitable if the number of bytes it represents
2741 is known and exact. A result that isn't suitable for substitution may
2742 have its range set to the range of return values, if that is known.
2743 Return true if the call is removed and gsi_next should not be performed
2744 in the caller. */
2746 static bool
2747 try_substitute_return_value (gimple_stmt_iterator *gsi,
2748 const pass_sprintf_length::call_info &info,
2749 const format_result &res)
2751 tree lhs = gimple_get_lhs (info.callstmt);
2753 /* Avoid the return value optimization when the behavior of the call
2754 is undefined either because any directive may have produced 4K or
2755 more of output, or the return value exceeds INT_MAX, or because
2756 the output overflows the destination object (but leave it enabled
2757 when the function is bounded because then the behavior is well-
2758 defined). */
2759 if (lhs
2760 && res.bounded
2761 && res.under4k
2762 && (info.bounded || res.number_chars <= info.objsize)
2763 && res.number_chars - 1 <= target_int_max ()
2764 /* Not prepared to handle possibly throwing calls here; they shouldn't
2765 appear in non-artificial testcases, except when the __*_chk routines
2766 are badly declared. */
2767 && !stmt_ends_bb_p (info.callstmt))
2769 tree cst = build_int_cst (integer_type_node, res.number_chars - 1);
2771 if (info.nowrite)
2773 /* Replace the call to the bounded function with a zero size
2774 (e.g., snprintf(0, 0, "%i", 123) with the constant result
2775 of the function minus 1 for the terminating NUL which
2776 the function's return value does not include. */
2777 if (!update_call_from_tree (gsi, cst))
2778 gimplify_and_update_call_from_tree (gsi, cst);
2779 gimple *callstmt = gsi_stmt (*gsi);
2780 update_stmt (callstmt);
2782 else
2784 /* Replace the left-hand side of the call with the constant
2785 result of the formatted function minus 1 for the terminating
2786 NUL which the function's return value does not include. */
2787 gimple_call_set_lhs (info.callstmt, NULL_TREE);
2788 gimple *g = gimple_build_assign (lhs, cst);
2789 gsi_insert_after (gsi, g, GSI_NEW_STMT);
2790 update_stmt (info.callstmt);
2793 if (dump_file)
2795 location_t callloc = gimple_location (info.callstmt);
2796 fprintf (dump_file, "On line %i substituting ",
2797 LOCATION_LINE (callloc));
2798 print_generic_expr (dump_file, cst, dump_flags);
2799 fprintf (dump_file, " for ");
2800 print_generic_expr (dump_file, info.func, dump_flags);
2801 fprintf (dump_file, " %s (output %s).\n",
2802 info.nowrite ? "call" : "return value",
2803 res.constant ? "constant" : "variable");
2806 else if (lhs == NULL_TREE
2807 && info.nowrite
2808 && !stmt_ends_bb_p (info.callstmt))
2810 /* Remove the call to the bounded function with a zero size
2811 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
2812 unlink_stmt_vdef (info.callstmt);
2813 gsi_remove (gsi, true);
2814 if (dump_file)
2816 location_t callloc = gimple_location (info.callstmt);
2817 fprintf (dump_file, "On line %i removing ",
2818 LOCATION_LINE (callloc));
2819 print_generic_expr (dump_file, info.func, dump_flags);
2820 fprintf (dump_file, " call.\n");
2822 return true;
2824 else
2826 unsigned HOST_WIDE_INT maxbytes;
2828 if (lhs
2829 && res.bounded
2830 && ((maxbytes = res.number_chars - 1) <= target_int_max ()
2831 || (res.number_chars_min - 1 <= target_int_max ()
2832 && (maxbytes = res.number_chars_max - 1) <= target_int_max ()))
2833 && (info.bounded || maxbytes < info.objsize))
2835 /* If the result is in a valid range bounded by the size of
2836 the destination set it so that it can be used for subsequent
2837 optimizations. */
2838 int prec = TYPE_PRECISION (integer_type_node);
2840 if (res.number_chars < target_int_max () && res.under4k)
2842 wide_int num = wi::shwi (res.number_chars - 1, prec);
2843 set_range_info (lhs, VR_RANGE, num, num);
2845 else if (res.number_chars_min < target_int_max ()
2846 && res.number_chars_max < target_int_max ())
2848 wide_int min = wi::shwi (res.under4k ? res.number_chars_min - 1
2849 : target_int_min (), prec);
2850 wide_int max = wi::shwi (res.number_chars_max - 1, prec);
2851 set_range_info (lhs, VR_RANGE, min, max);
2855 if (dump_file)
2857 const char *inbounds
2858 = (res.number_chars_min <= info.objsize
2859 ? (res.number_chars_max <= info.objsize
2860 ? "in" : "potentially out-of")
2861 : "out-of");
2863 location_t callloc = gimple_location (info.callstmt);
2864 fprintf (dump_file, "On line %i ", LOCATION_LINE (callloc));
2865 print_generic_expr (dump_file, info.func, dump_flags);
2867 const char *ign = lhs ? "" : " ignored";
2868 if (res.number_chars >= HOST_WIDE_INT_MAX)
2869 fprintf (dump_file,
2870 " %s-bounds return value in range [%lu, %lu]%s.\n",
2871 inbounds,
2872 (unsigned long)res.number_chars_min - 1,
2873 (unsigned long)res.number_chars_max - 1, ign);
2874 else
2875 fprintf (dump_file, " %s-bounds return value %lu%s.\n",
2876 inbounds, (unsigned long)res.number_chars - 1, ign);
2880 return false;
2883 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
2884 functions and if so, handle it. Return true if the call is removed
2885 and gsi_next should not be performed in the caller. */
2887 bool
2888 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator *gsi)
2890 call_info info = call_info ();
2892 info.callstmt = gsi_stmt (*gsi);
2893 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
2894 return false;
2896 info.func = gimple_call_fndecl (info.callstmt);
2897 info.fncode = DECL_FUNCTION_CODE (info.func);
2899 /* The size of the destination as in snprintf(dest, size, ...). */
2900 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
2902 /* The size of the destination determined by __builtin_object_size. */
2903 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
2905 /* Buffer size argument number (snprintf and vsnprintf). */
2906 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
2908 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
2909 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
2911 /* Format string argument number (valid for all functions). */
2912 unsigned idx_format;
2914 switch (info.fncode)
2916 case BUILT_IN_SPRINTF:
2917 // Signature:
2918 // __builtin_sprintf (dst, format, ...)
2919 idx_format = 1;
2920 info.argidx = 2;
2921 break;
2923 case BUILT_IN_SPRINTF_CHK:
2924 // Signature:
2925 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
2926 idx_objsize = 2;
2927 idx_format = 3;
2928 info.argidx = 4;
2929 break;
2931 case BUILT_IN_SNPRINTF:
2932 // Signature:
2933 // __builtin_snprintf (dst, size, format, ...)
2934 idx_dstsize = 1;
2935 idx_format = 2;
2936 info.argidx = 3;
2937 info.bounded = true;
2938 break;
2940 case BUILT_IN_SNPRINTF_CHK:
2941 // Signature:
2942 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
2943 idx_dstsize = 1;
2944 idx_objsize = 3;
2945 idx_format = 4;
2946 info.argidx = 5;
2947 info.bounded = true;
2948 break;
2950 case BUILT_IN_VSNPRINTF:
2951 // Signature:
2952 // __builtin_vsprintf (dst, size, format, va)
2953 idx_dstsize = 1;
2954 idx_format = 2;
2955 info.argidx = -1;
2956 info.bounded = true;
2957 break;
2959 case BUILT_IN_VSNPRINTF_CHK:
2960 // Signature:
2961 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
2962 idx_dstsize = 1;
2963 idx_objsize = 3;
2964 idx_format = 4;
2965 info.argidx = -1;
2966 info.bounded = true;
2967 break;
2969 case BUILT_IN_VSPRINTF:
2970 // Signature:
2971 // __builtin_vsprintf (dst, format, va)
2972 idx_format = 1;
2973 info.argidx = -1;
2974 break;
2976 case BUILT_IN_VSPRINTF_CHK:
2977 // Signature:
2978 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
2979 idx_format = 3;
2980 idx_objsize = 2;
2981 info.argidx = -1;
2982 break;
2984 default:
2985 return false;
2988 /* The first argument is a pointer to the destination. */
2989 tree dstptr = gimple_call_arg (info.callstmt, 0);
2991 info.format = gimple_call_arg (info.callstmt, idx_format);
2993 if (idx_dstsize == HOST_WIDE_INT_M1U)
2995 /* For non-bounded functions like sprintf, determine the size
2996 of the destination from the object or pointer passed to it
2997 as the first argument. */
2998 dstsize = get_destination_size (dstptr);
3000 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3002 /* For bounded functions try to get the size argument. */
3004 if (TREE_CODE (size) == INTEGER_CST)
3006 dstsize = tree_to_uhwi (size);
3007 /* No object can be larger than SIZE_MAX bytes (half the address
3008 space) on the target.
3009 The functions are defined only for output of at most INT_MAX
3010 bytes. Specifying a bound in excess of that limit effectively
3011 defeats the bounds checking (and on some implementations such
3012 as Solaris cause the function to fail with EINVAL). */
3013 if (dstsize > target_size_max () / 2)
3015 /* Avoid warning if -Wstringop-overflow is specified since
3016 it also warns for the same thing though only for the
3017 checking built-ins. */
3018 if ((idx_objsize == HOST_WIDE_INT_M1U
3019 || !warn_stringop_overflow))
3020 warning_at (gimple_location (info.callstmt), info.warnopt (),
3021 "specified bound %wu exceeds maximum object size "
3022 "%wu",
3023 dstsize, target_size_max () / 2);
3025 else if (dstsize > target_int_max ())
3026 warning_at (gimple_location (info.callstmt), info.warnopt (),
3027 "specified bound %wu exceeds %<INT_MAX %>",
3028 dstsize);
3030 else if (TREE_CODE (size) == SSA_NAME)
3032 /* Try to determine the range of values of the argument
3033 and use the greater of the two at -Wformat-level 1 and
3034 the smaller of them at level 2. */
3035 wide_int min, max;
3036 enum value_range_type range_type
3037 = get_range_info (size, &min, &max);
3038 if (range_type == VR_RANGE)
3040 dstsize
3041 = (warn_format_overflow < 2
3042 ? wi::fits_uhwi_p (max) ? max.to_uhwi () : max.to_shwi ()
3043 : wi::fits_uhwi_p (min) ? min.to_uhwi () : min.to_shwi ());
3048 if (idx_objsize != HOST_WIDE_INT_M1U)
3049 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3050 if (tree_fits_uhwi_p (size))
3051 objsize = tree_to_uhwi (size);
3053 if (info.bounded && !dstsize)
3055 /* As a special case, when the explicitly specified destination
3056 size argument (to a bounded function like snprintf) is zero
3057 it is a request to determine the number of bytes on output
3058 without actually producing any. Pretend the size is
3059 unlimited in this case. */
3060 info.objsize = HOST_WIDE_INT_MAX;
3061 info.nowrite = true;
3063 else
3065 /* For calls to non-bounded functions or to those of bounded
3066 functions with a non-zero size, warn if the destination
3067 pointer is null. */
3068 if (integer_zerop (dstptr))
3070 /* This is diagnosed with -Wformat only when the null is a constant
3071 pointer. The warning here diagnoses instances where the pointer
3072 is not constant. */
3073 location_t loc = gimple_location (info.callstmt);
3074 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3075 info.warnopt (), "null destination pointer");
3076 return false;
3079 /* Set the object size to the smaller of the two arguments
3080 of both have been specified and they're not equal. */
3081 info.objsize = dstsize < objsize ? dstsize : objsize;
3083 if (info.bounded
3084 && dstsize < target_size_max () / 2 && objsize < dstsize
3085 /* Avoid warning if -Wstringop-overflow is specified since
3086 it also warns for the same thing though only for the
3087 checking built-ins. */
3088 && (idx_objsize == HOST_WIDE_INT_M1U
3089 || !warn_stringop_overflow))
3091 warning_at (gimple_location (info.callstmt), info.warnopt (),
3092 "specified bound %wu exceeds the size %wu "
3093 "of the destination object", dstsize, objsize);
3097 if (integer_zerop (info.format))
3099 /* This is diagnosed with -Wformat only when the null is a constant
3100 pointer. The warning here diagnoses instances where the pointer
3101 is not constant. */
3102 location_t loc = gimple_location (info.callstmt);
3103 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3104 info.warnopt (), "null format string");
3105 return false;
3108 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3109 if (!info.fmtstr)
3110 return false;
3112 /* The result is the number of bytes output by the formatted function,
3113 including the terminating NUL. */
3114 format_result res = format_result ();
3116 bool success = compute_format_length (info, &res);
3118 /* When optimizing and the printf return value optimization is enabled,
3119 attempt to substitute the computed result for the return value of
3120 the call. Avoid this optimization when -frounding-math is in effect
3121 and the format string contains a floating point directive. */
3122 if (success
3123 && optimize > 0
3124 && flag_printf_return_value
3125 && (!flag_rounding_math || !res.floating))
3126 return try_substitute_return_value (gsi, info, res);
3127 return false;
3130 /* Execute the pass for function FUN. */
3132 unsigned int
3133 pass_sprintf_length::execute (function *fun)
3135 basic_block bb;
3136 FOR_EACH_BB_FN (bb, fun)
3138 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
3140 /* Iterate over statements, looking for function calls. */
3141 gimple *stmt = gsi_stmt (si);
3143 if (is_gimple_call (stmt) && handle_gimple_call (&si))
3144 /* If handle_gimple_call returns true, the iterator is
3145 already pointing to the next statement. */
3146 continue;
3148 gsi_next (&si);
3152 fini_object_sizes ();
3154 return 0;
3157 } /* Unnamed namespace. */
3159 /* Return a pointer to a pass object newly constructed from the context
3160 CTXT. */
3162 gimple_opt_pass *
3163 make_pass_sprintf_length (gcc::context *ctxt)
3165 return new pass_sprintf_length (ctxt);