[testsuite] Fix FAIL: gcc.dg/lto/pr69188 on bare-metal targets
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob76e851231d6bccb9007b2e941f82ac036ce08945
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 (HOST_WIDE_INT_MIN == i)
582 /* Avoid undefined behavior due to negating a minimum. */
583 absval = HOST_WIDE_INT_MAX;
584 res = 1;
586 else if (i < 0)
588 absval = -i;
589 res = 1;
591 else
593 absval = i;
594 res = plus;
597 else
598 return -1;
601 int ndigs = ilog (absval, base);
603 res += prec < ndigs ? ndigs : prec;
605 if (prefix && absval)
607 if (base == 8)
608 res += 1;
609 else if (base == 16)
610 res += 2;
613 return res;
616 /* Given the formatting result described by RES and NAVAIL, the number
617 of available in the destination, return the number of bytes remaining
618 in the destination. */
620 static inline result_range
621 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
623 result_range range;
625 if (HOST_WIDE_INT_MAX <= navail)
627 range.min = range.max = navail;
628 return range;
631 if (res.number_chars < navail)
633 range.min = range.max = navail - res.number_chars;
635 else if (res.number_chars_min < navail)
637 range.max = navail - res.number_chars_min;
639 else
640 range.max = 0;
642 if (res.number_chars_max < navail)
643 range.min = navail - res.number_chars_max;
644 else
645 range.min = 0;
647 return range;
650 /* Given the formatting result described by RES and NAVAIL, the number
651 of available in the destination, return the minimum number of bytes
652 remaining in the destination. */
654 static inline unsigned HOST_WIDE_INT
655 min_bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
657 if (HOST_WIDE_INT_MAX <= navail)
658 return navail;
660 if (warn_format_overflow > 1 || res.knownrange)
662 /* At level 2, or when all directives output an exact number
663 of bytes or when their arguments were bounded by known
664 ranges, use the greater of the two byte counters if it's
665 valid to compute the result. */
666 if (res.number_chars_max < HOST_WIDE_INT_MAX)
667 navail -= res.number_chars_max;
668 else if (res.number_chars < HOST_WIDE_INT_MAX)
669 navail -= res.number_chars;
670 else if (res.number_chars_min < HOST_WIDE_INT_MAX)
671 navail -= res.number_chars_min;
673 else
675 /* At level 1 use the smaller of the byte counters to compute
676 the result. */
677 if (res.number_chars < HOST_WIDE_INT_MAX)
678 navail -= res.number_chars;
679 else if (res.number_chars_min < HOST_WIDE_INT_MAX)
680 navail -= res.number_chars_min;
681 else if (res.number_chars_max < HOST_WIDE_INT_MAX)
682 navail -= res.number_chars_max;
685 if (navail > HOST_WIDE_INT_MAX)
686 navail = 0;
688 return navail;
691 /* Description of a call to a formatted function. */
693 struct pass_sprintf_length::call_info
695 /* Function call statement. */
696 gimple *callstmt;
698 /* Function called. */
699 tree func;
701 /* Called built-in function code. */
702 built_in_function fncode;
704 /* Format argument and format string extracted from it. */
705 tree format;
706 const char *fmtstr;
708 /* The location of the format argument. */
709 location_t fmtloc;
711 /* The destination object size for __builtin___xxx_chk functions
712 typically determined by __builtin_object_size, or -1 if unknown. */
713 unsigned HOST_WIDE_INT objsize;
715 /* Number of the first variable argument. */
716 unsigned HOST_WIDE_INT argidx;
718 /* True for functions like snprintf that specify the size of
719 the destination, false for others like sprintf that don't. */
720 bool bounded;
722 /* True for bounded functions like snprintf that specify a zero-size
723 buffer as a request to compute the size of output without actually
724 writing any. NOWRITE is cleared in response to the %n directive
725 which has side-effects similar to writing output. */
726 bool nowrite;
728 /* Return true if the called function's return value is used. */
729 bool retval_used () const
731 return gimple_get_lhs (callstmt);
734 /* Return the warning option corresponding to the called function. */
735 int warnopt () const
737 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
741 /* Return the result of formatting the '%%' directive. */
743 static fmtresult
744 format_percent (const conversion_spec &, tree)
746 fmtresult res;
747 res.argmin = res.argmax = NULL_TREE;
748 res.range.min = res.range.max = 1;
749 res.bounded = res.constant = true;
750 return res;
754 /* Compute intmax_type_node and uintmax_type_node similarly to how
755 tree.c builds size_type_node. */
757 static void
758 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
760 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
762 *pintmax = integer_type_node;
763 *puintmax = unsigned_type_node;
765 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
767 *pintmax = long_integer_type_node;
768 *puintmax = long_unsigned_type_node;
770 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
772 *pintmax = long_long_integer_type_node;
773 *puintmax = long_long_unsigned_type_node;
775 else
777 for (int i = 0; i < NUM_INT_N_ENTS; i++)
778 if (int_n_enabled_p[i])
780 char name[50];
781 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
783 if (strcmp (name, UINTMAX_TYPE) == 0)
785 *pintmax = int_n_trees[i].signed_type;
786 *puintmax = int_n_trees[i].unsigned_type;
787 return;
790 gcc_unreachable ();
794 /* Set *PWIDTH and *PPREC according to the width and precision specified
795 in SPEC. Each is set to HOST_WIDE_INT_MIN when the corresponding
796 field is specified but unknown, to zero for width and -1 for precision,
797 respectively when it's not specified, or to a non-negative value
798 corresponding to the known value. */
800 static void
801 get_width_and_precision (const conversion_spec &spec,
802 HOST_WIDE_INT *pwidth, HOST_WIDE_INT *pprec)
804 HOST_WIDE_INT width = spec.have_width ? spec.width : 0;
805 HOST_WIDE_INT prec = spec.have_precision ? spec.precision : -1;
807 if (spec.star_width)
809 if (TREE_CODE (spec.star_width) == INTEGER_CST)
811 width = tree_to_shwi (spec.star_width);
812 if (width < 0)
814 if (width == HOST_WIDE_INT_MIN)
816 /* Avoid undefined behavior due to negating a minimum.
817 This case will be diagnosed since it will result in
818 more than INT_MAX bytes on output, either by the
819 directive itself (when INT_MAX < HOST_WIDE_INT_MAX)
820 or by the format function itself. */
821 width = HOST_WIDE_INT_MAX;
823 else
824 width = -width;
827 else
828 width = HOST_WIDE_INT_MIN;
831 if (spec.star_precision)
833 if (TREE_CODE (spec.star_precision) == INTEGER_CST)
835 prec = tree_to_shwi (spec.star_precision);
836 if (prec < 0)
837 prec = -1;
839 else
840 prec = HOST_WIDE_INT_MIN;
843 *pwidth = width;
844 *pprec = prec;
847 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
848 argument, due to the conversion from either *ARGMIN or *ARGMAX to
849 the type of the directive's formal argument it's possible for both
850 to result in the same number of bytes or a range of bytes that's
851 less than the number of bytes that would result from formatting
852 some other value in the range [*ARGMIN, *ARGMAX]. This can be
853 determined by checking for the actual argument being in the range
854 of the type of the directive. If it isn't it must be assumed to
855 take on the full range of the directive's type.
856 Return true when the range has been adjusted to the full unsigned
857 range of DIRTYPE, or [0, DIRTYPE_MAX], and false otherwise. */
859 static bool
860 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
862 tree argtype = TREE_TYPE (*argmin);
863 unsigned argprec = TYPE_PRECISION (argtype);
864 unsigned dirprec = TYPE_PRECISION (dirtype);
866 /* If the actual argument and the directive's argument have the same
867 precision and sign there can be no overflow and so there is nothing
868 to adjust. */
869 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
870 return false;
872 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
873 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
875 if (TREE_CODE (*argmin) == INTEGER_CST
876 && TREE_CODE (*argmax) == INTEGER_CST
877 && (dirprec >= argprec
878 || integer_zerop (int_const_binop (RSHIFT_EXPR,
879 int_const_binop (MINUS_EXPR,
880 *argmax,
881 *argmin),
882 size_int (dirprec)))))
884 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
885 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
887 /* If *ARGMIN is still less than *ARGMAX the conversion above
888 is safe. Otherwise, it has overflowed and would be unsafe. */
889 if (tree_int_cst_le (*argmin, *argmax))
890 return false;
893 tree dirmin = TYPE_MIN_VALUE (dirtype);
894 tree dirmax = TYPE_MAX_VALUE (dirtype);
896 if (TYPE_UNSIGNED (dirtype))
898 *argmin = dirmin;
899 *argmax = dirmax;
901 else
903 *argmin = integer_zero_node;
904 *argmax = dirmin;
907 return true;
910 /* Return a range representing the minimum and maximum number of bytes
911 that the conversion specification SPEC will write on output for the
912 integer argument ARG when non-null. ARG may be null (for vararg
913 functions). */
915 static fmtresult
916 format_integer (const conversion_spec &spec, tree arg)
918 tree intmax_type_node;
919 tree uintmax_type_node;
921 /* Set WIDTH and PRECISION based on the specification. */
922 HOST_WIDE_INT width;
923 HOST_WIDE_INT prec;
924 get_width_and_precision (spec, &width, &prec);
926 bool sign = spec.specifier == 'd' || spec.specifier == 'i';
928 /* The type of the "formal" argument expected by the directive. */
929 tree dirtype = NULL_TREE;
931 /* Determine the expected type of the argument from the length
932 modifier. */
933 switch (spec.modifier)
935 case FMT_LEN_none:
936 if (spec.specifier == 'p')
937 dirtype = ptr_type_node;
938 else
939 dirtype = sign ? integer_type_node : unsigned_type_node;
940 break;
942 case FMT_LEN_h:
943 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
944 break;
946 case FMT_LEN_hh:
947 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
948 break;
950 case FMT_LEN_l:
951 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
952 break;
954 case FMT_LEN_L:
955 case FMT_LEN_ll:
956 dirtype = (sign
957 ? long_long_integer_type_node
958 : long_long_unsigned_type_node);
959 break;
961 case FMT_LEN_z:
962 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
963 break;
965 case FMT_LEN_t:
966 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
967 break;
969 case FMT_LEN_j:
970 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
971 dirtype = sign ? intmax_type_node : uintmax_type_node;
972 break;
974 default:
975 return fmtresult ();
978 /* The type of the argument to the directive, either deduced from
979 the actual non-constant argument if one is known, or from
980 the directive itself when none has been provided because it's
981 a va_list. */
982 tree argtype = NULL_TREE;
984 if (!arg)
986 /* When the argument has not been provided, use the type of
987 the directive's argument as an approximation. This will
988 result in false positives for directives like %i with
989 arguments with smaller precision (such as short or char). */
990 argtype = dirtype;
992 else if (TREE_CODE (arg) == INTEGER_CST)
994 /* When a constant argument has been provided use its value
995 rather than type to determine the length of the output. */
997 /* Base to format the number in. */
998 int base;
1000 /* True when a signed conversion is preceded by a sign or space. */
1001 bool maybesign = false;
1003 switch (spec.specifier)
1005 case 'd':
1006 case 'i':
1007 /* Space and '+' are only meaningful for signed conversions. */
1008 maybesign = spec.get_flag (' ') | spec.get_flag ('+');
1009 base = 10;
1010 break;
1011 case 'u':
1012 base = 10;
1013 break;
1014 case 'o':
1015 base = 8;
1016 break;
1017 case 'X':
1018 case 'x':
1019 base = 16;
1020 break;
1021 default:
1022 gcc_unreachable ();
1025 HOST_WIDE_INT len;
1027 if ((prec == HOST_WIDE_INT_MIN || prec == 0) && integer_zerop (arg))
1029 /* As a special case, a precision of zero with a zero argument
1030 results in zero bytes except in base 8 when the '#' flag is
1031 specified, and for signed conversions in base 8 and 10 when
1032 flags when either the space or '+' flag has been specified
1033 when it results in just one byte (with width having the normal
1034 effect). This must extend to the case of a specified precision
1035 with an unknown value because it can be zero. */
1036 len = ((base == 8 && spec.get_flag ('#')) || maybesign);
1038 else
1040 /* Convert the argument to the type of the directive. */
1041 arg = fold_convert (dirtype, arg);
1043 /* True when a conversion is preceded by a prefix indicating the base
1044 of the argument (octal or hexadecimal). */
1045 bool maybebase = spec.get_flag ('#');
1046 len = tree_digits (arg, base, prec, maybesign, maybebase);
1047 if (len < 1)
1048 len = HOST_WIDE_INT_MAX;
1051 if (len < width)
1052 len = width;
1054 /* The minimum and maximum number of bytes produced by the directive. */
1055 fmtresult res;
1057 res.range.min = len;
1059 /* The upper bound of the number of bytes is unlimited when either
1060 width or precision is specified but its value is unknown, and
1061 the same as the lower bound otherwise. */
1062 if (width == HOST_WIDE_INT_MIN || prec == HOST_WIDE_INT_MIN)
1064 res.range.max = HOST_WIDE_INT_MAX;
1066 else
1068 res.range.max = len;
1069 res.bounded = true;
1070 res.constant = true;
1071 res.knownrange = true;
1072 res.bounded = true;
1075 return res;
1077 else if (TREE_CODE (TREE_TYPE (arg)) == INTEGER_TYPE
1078 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1079 /* Determine the type of the provided non-constant argument. */
1080 argtype = TREE_TYPE (arg);
1081 else
1082 /* Don't bother with invalid arguments since they likely would
1083 have already been diagnosed, and disable any further checking
1084 of the format string by returning [-1, -1]. */
1085 return fmtresult ();
1087 fmtresult res;
1089 /* The result is bounded unless width or precision has been specified
1090 whose value is unknown. */
1091 res.bounded = width != HOST_WIDE_INT_MIN && prec != HOST_WIDE_INT_MIN;
1093 /* Using either the range the non-constant argument is in, or its
1094 type (either "formal" or actual), create a range of values that
1095 constrain the length of output given the warning level. */
1096 tree argmin = NULL_TREE;
1097 tree argmax = NULL_TREE;
1099 if (arg
1100 && TREE_CODE (arg) == SSA_NAME
1101 && TREE_CODE (argtype) == INTEGER_TYPE)
1103 /* Try to determine the range of values of the integer argument
1104 (range information is not available for pointers). */
1105 wide_int min, max;
1106 enum value_range_type range_type = get_range_info (arg, &min, &max);
1107 if (range_type == VR_RANGE)
1109 argmin = build_int_cst (argtype, wi::fits_uhwi_p (min)
1110 ? min.to_uhwi () : min.to_shwi ());
1111 argmax = build_int_cst (argtype, wi::fits_uhwi_p (max)
1112 ? max.to_uhwi () : max.to_shwi ());
1114 /* Set KNOWNRANGE if the argument is in a known subrange
1115 of the directive's type (KNOWNRANGE may be reset below). */
1116 res.knownrange
1117 = (!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1118 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax));
1120 res.argmin = argmin;
1121 res.argmax = argmax;
1123 else if (range_type == VR_ANTI_RANGE)
1125 /* Handle anti-ranges if/when bug 71690 is resolved. */
1127 else if (range_type == VR_VARYING)
1129 /* The argument here may be the result of promoting the actual
1130 argument to int. Try to determine the type of the actual
1131 argument before promotion and narrow down its range that
1132 way. */
1133 gimple *def = SSA_NAME_DEF_STMT (arg);
1134 if (is_gimple_assign (def))
1136 tree_code code = gimple_assign_rhs_code (def);
1137 if (code == INTEGER_CST)
1139 arg = gimple_assign_rhs1 (def);
1140 return format_integer (spec, arg);
1143 if (code == NOP_EXPR)
1145 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1146 if (TREE_CODE (type) == INTEGER_TYPE
1147 || TREE_CODE (type) == POINTER_TYPE)
1148 argtype = type;
1154 if (!argmin)
1156 /* For an unknown argument (e.g., one passed to a vararg function)
1157 or one whose value range cannot be determined, create a T_MIN
1158 constant if the argument's type is signed and T_MAX otherwise,
1159 and use those to compute the range of bytes that the directive
1160 can output. When precision is specified but unknown, use zero
1161 as the minimum since it results in no bytes on output (unless
1162 width is specified to be greater than 0). */
1163 argmin = build_int_cst (argtype, prec && prec != HOST_WIDE_INT_MIN);
1165 int typeprec = TYPE_PRECISION (dirtype);
1166 int argprec = TYPE_PRECISION (argtype);
1168 if (argprec < typeprec)
1170 if (POINTER_TYPE_P (argtype))
1171 argmax = build_all_ones_cst (argtype);
1172 else if (TYPE_UNSIGNED (argtype))
1173 argmax = TYPE_MAX_VALUE (argtype);
1174 else
1175 argmax = TYPE_MIN_VALUE (argtype);
1177 else
1179 if (POINTER_TYPE_P (dirtype))
1180 argmax = build_all_ones_cst (dirtype);
1181 else if (TYPE_UNSIGNED (dirtype))
1182 argmax = TYPE_MAX_VALUE (dirtype);
1183 else
1184 argmax = TYPE_MIN_VALUE (dirtype);
1187 res.argmin = argmin;
1188 res.argmax = argmax;
1191 if (tree_int_cst_lt (argmax, argmin))
1193 tree tmp = argmax;
1194 argmax = argmin;
1195 argmin = tmp;
1198 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1199 of the directive. If it has been cleared then since ARGMIN and/or
1200 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1201 ARGMAX in the result to include in diagnostics. */
1202 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1204 res.knownrange = false;
1205 res.argmin = argmin;
1206 res.argmax = argmax;
1209 /* Recursively compute the minimum and maximum from the known range,
1210 taking care to swap them if the lower bound results in longer
1211 output than the upper bound (e.g., in the range [-1, 0]. */
1213 if (TYPE_UNSIGNED (dirtype))
1215 /* For unsigned conversions/directives, use the minimum (i.e., 0
1216 or 1) and maximum to compute the shortest and longest output,
1217 respectively. */
1218 res.range.min = format_integer (spec, argmin).range.min;
1219 res.range.max = format_integer (spec, argmax).range.max;
1221 else
1223 /* For signed conversions/directives, use the maximum (i.e., 0)
1224 to compute the shortest output and the minimum (i.e., TYPE_MIN)
1225 to compute the longest output. This is important when precision
1226 is specified but unknown because otherwise both output lengths
1227 would reflect the largest possible precision (i.e., INT_MAX). */
1228 res.range.min = format_integer (spec, argmax).range.min;
1229 res.range.max = format_integer (spec, argmin).range.max;
1232 /* The result is bounded either when the argument is determined to be
1233 (e.g., when it's within some range) or when the minimum and maximum
1234 are the same. That can happen here for example when the specified
1235 width is as wide as the greater of MIN and MAX, as would be the case
1236 with sprintf (d, "%08x", x) with a 32-bit integer x. */
1237 res.bounded |= res.range.min == res.range.max;
1239 if (res.range.max < res.range.min)
1241 unsigned HOST_WIDE_INT tmp = res.range.max;
1242 res.range.max = res.range.min;
1243 res.range.min = tmp;
1246 return res;
1249 /* Return the number of bytes that a format directive consisting of FLAGS,
1250 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1251 would result for argument X under ideal conditions (i.e., if PREC
1252 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1253 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1254 This function works around those problems. */
1256 static unsigned HOST_WIDE_INT
1257 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1258 char spec, char rndspec)
1260 char fmtstr[40];
1262 HOST_WIDE_INT len = strlen (flags);
1264 fmtstr[0] = '%';
1265 memcpy (fmtstr + 1, flags, len);
1266 memcpy (fmtstr + 1 + len, ".*R", 3);
1267 fmtstr[len + 4] = rndspec;
1268 fmtstr[len + 5] = spec;
1269 fmtstr[len + 6] = '\0';
1271 spec = TOUPPER (spec);
1272 if (spec == 'E' || spec == 'F')
1274 /* For %e, specify the precision explicitly since mpfr_sprintf
1275 does its own thing just to be different (see MPFR bug 21088). */
1276 if (prec < 0)
1277 prec = 6;
1279 else
1281 /* Avoid passing negative precisions with larger magnitude to MPFR
1282 to avoid exposing its bugs. (A negative precision is supposed
1283 to be ignored.) */
1284 if (prec < 0)
1285 prec = -1;
1288 HOST_WIDE_INT p = prec;
1290 if (spec == 'G')
1292 /* For G/g, precision gives the maximum number of significant
1293 digits which is bounded by LDBL_MAX_10_EXP, or, for a 128
1294 bit IEEE extended precision, 4932. Using twice as much
1295 here should be more than sufficient for any real format. */
1296 if ((IEEE_MAX_10_EXP * 2) < prec)
1297 prec = IEEE_MAX_10_EXP * 2;
1298 p = prec;
1300 else
1302 /* Cap precision arbitrarily at 1KB and add the difference
1303 (if any) to the MPFR result. */
1304 if (1024 < prec)
1305 p = 1024;
1308 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1310 /* Handle the unlikely (impossible?) error by returning more than
1311 the maximum dictated by the function's return type. */
1312 if (len < 0)
1313 return target_dir_max () + 1;
1315 /* Adjust the return value by the difference. */
1316 if (p < prec)
1317 len += prec - p;
1319 return len;
1322 /* Return the number of bytes to format using the format specifier
1323 SPEC and the precision PREC the largest value in the real floating
1324 TYPE. */
1326 static unsigned HOST_WIDE_INT
1327 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1329 machine_mode mode = TYPE_MODE (type);
1331 /* IBM Extended mode. */
1332 if (MODE_COMPOSITE_P (mode))
1333 mode = DFmode;
1335 /* Get the real type format desription for the target. */
1336 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1337 REAL_VALUE_TYPE rv;
1340 char buf[256];
1341 get_max_float (rfmt, buf, sizeof buf);
1342 real_from_string (&rv, buf);
1345 /* Convert the GCC real value representation with the precision
1346 of the real type to the mpfr_t format with the GCC default
1347 round-to-nearest mode. */
1348 mpfr_t x;
1349 mpfr_init2 (x, rfmt->p);
1350 mpfr_from_real (x, &rv, GMP_RNDN);
1352 /* Return a value one greater to account for the leading minus sign. */
1353 return 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1356 /* Return a range representing the minimum and maximum number of bytes
1357 that the conversion specification SPEC will output for any argument
1358 given the WIDTH and PRECISION (extracted from SPEC). This function
1359 is used when the directive argument or its value isn't known. */
1361 static fmtresult
1362 format_floating (const conversion_spec &spec, HOST_WIDE_INT width,
1363 HOST_WIDE_INT prec)
1365 tree type;
1367 switch (spec.modifier)
1369 case FMT_LEN_l:
1370 case FMT_LEN_none:
1371 type = double_type_node;
1372 break;
1374 case FMT_LEN_L:
1375 type = long_double_type_node;
1376 break;
1378 case FMT_LEN_ll:
1379 type = long_double_type_node;
1380 break;
1382 default:
1383 return fmtresult ();
1386 /* The minimum and maximum number of bytes produced by the directive. */
1387 fmtresult res;
1389 /* The result is always bounded (though the range may be all of int). */
1390 res.bounded = true;
1392 /* The minimum output as determined by flags. It's always at least 1. */
1393 int flagmin = (1 /* for the first digit */
1394 + (spec.get_flag ('+') | spec.get_flag (' '))
1395 + (prec == 0 && spec.get_flag ('#')));
1397 if (width == INT_MIN || prec == INT_MIN)
1399 /* When either width or precision is specified but unknown
1400 the upper bound is the maximum. Otherwise it will be
1401 computed for each directive below. */
1402 res.range.max = HOST_WIDE_INT_MAX;
1404 else
1405 res.range.max = HOST_WIDE_INT_M1U;
1407 switch (spec.specifier)
1409 case 'A':
1410 case 'a':
1412 res.range.min = flagmin + 5 + (prec > 0 ? prec + 1 : 0);
1413 if (res.range.max == HOST_WIDE_INT_M1U)
1415 /* Compute the upper bound for -TYPE_MAX. */
1416 res.range.max = format_floating_max (type, 'a', prec);
1419 break;
1422 case 'E':
1423 case 'e':
1425 /* The minimum output is "[-+]1.234567e+00" regardless
1426 of the value of the actual argument. */
1427 res.range.min = (flagmin
1428 + (prec == INT_MIN
1429 ? 0 : prec < 0 ? 7 : prec ? prec + 1 : 0)
1430 + 2 /* e+ */ + 2);
1432 if (res.range.max == HOST_WIDE_INT_M1U)
1434 /* MPFR uses a precision of 16 by default for some reason.
1435 Set it to the C default of 6. */
1436 res.range.max = format_floating_max (type, 'e',
1437 -1 == prec ? 6 : prec);
1439 break;
1442 case 'F':
1443 case 'f':
1445 /* The lower bound when precision isn't specified is 8 bytes
1446 ("1.23456" since precision is taken to be 6). When precision
1447 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1448 when precision is greater than zero, then the lower bound
1449 is 2 plus precision (plus flags). */
1450 res.range.min = (flagmin
1451 + (prec != INT_MIN) /* for decimal point */
1452 + (prec == INT_MIN
1453 ? 0 : prec < 0 ? 6 : prec ? prec : -1));
1455 if (res.range.max == HOST_WIDE_INT_M1U)
1457 /* Compute the upper bound for -TYPE_MAX. */
1458 res.range.max = format_floating_max (type, 'f', prec);
1460 break;
1463 case 'G':
1464 case 'g':
1466 /* The %g output depends on precision and the exponent of
1467 the argument. Since the value of the argument isn't known
1468 the lower bound on the range of bytes (not counting flags
1469 or width) is 1. */
1470 res.range.min = flagmin;
1471 if (res.range.max == HOST_WIDE_INT_M1U)
1473 /* Compute the upper bound for -TYPE_MAX which should be
1474 the lesser of %e and %f. */
1475 res.range.max = format_floating_max (type, 'g', prec);
1477 break;
1480 default:
1481 return fmtresult ();
1484 if (width > 0)
1486 /* If width has been specified use it to adjust the range. */
1487 if (res.range.min < (unsigned)width)
1488 res.range.min = width;
1489 if (res.range.max < (unsigned)width)
1490 res.range.max = width;
1493 return res;
1496 /* Return a range representing the minimum and maximum number of bytes
1497 that the conversion specification SPEC will write on output for the
1498 floating argument ARG. */
1500 static fmtresult
1501 format_floating (const conversion_spec &spec, tree arg)
1503 /* Set WIDTH to -1 when it's not specified, to HOST_WIDE_INT_MIN when
1504 it is specified by the asterisk to an unknown value, and otherwise
1505 to a non-negative value corresponding to the specified width. */
1506 HOST_WIDE_INT width = -1;
1507 HOST_WIDE_INT prec = -1;
1509 /* The minimum and maximum number of bytes produced by the directive. */
1510 fmtresult res;
1511 res.constant = arg && TREE_CODE (arg) == REAL_CST;
1513 if (spec.have_width)
1514 width = spec.width;
1515 else if (spec.star_width)
1517 if (TREE_CODE (spec.star_width) == INTEGER_CST)
1519 width = tree_to_shwi (spec.star_width);
1520 if (width < 0)
1521 width = -width;
1523 else
1524 width = INT_MIN;
1527 if (spec.have_precision)
1528 prec = spec.precision;
1529 else if (spec.star_precision)
1531 if (TREE_CODE (spec.star_precision) == INTEGER_CST)
1533 prec = tree_to_shwi (spec.star_precision);
1534 if (prec < 0)
1535 prec = -1;
1537 else
1538 prec = INT_MIN;
1540 else if (res.constant && TOUPPER (spec.specifier) != 'A')
1542 /* Specify the precision explicitly since mpfr_sprintf defaults
1543 to zero. */
1544 prec = 6;
1547 if (res.constant)
1549 /* Get the real type format desription for the target. */
1550 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1551 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1553 /* Convert the GCC real value representation with the precision
1554 of the real type to the mpfr_t format with the GCC default
1555 round-to-nearest mode. */
1556 mpfr_t mpfrval;
1557 mpfr_init2 (mpfrval, rfmt->p);
1558 mpfr_from_real (mpfrval, rvp, GMP_RNDN);
1560 char fmtstr [40];
1561 char *pfmt = fmtstr;
1563 /* Append flags. */
1564 for (const char *pf = "-+ #0"; *pf; ++pf)
1565 if (spec.get_flag (*pf))
1566 *pfmt++ = *pf;
1568 *pfmt = '\0';
1571 /* Set up an array to easily iterate over below. */
1572 unsigned HOST_WIDE_INT* const minmax[] = {
1573 &res.range.min, &res.range.max
1576 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1578 /* Use the MPFR rounding specifier to round down in the first
1579 iteration and then up. In most but not all cases this will
1580 result in the same number of bytes. */
1581 char rndspec = "DU"[i];
1583 /* Format it and store the result in the corresponding member
1584 of the result struct. */
1585 unsigned HOST_WIDE_INT len
1586 = get_mpfr_format_length (mpfrval, fmtstr, prec,
1587 spec.specifier, rndspec);
1588 if (0 < width && len < (unsigned)width)
1589 len = width;
1591 *minmax[i] = len;
1595 /* Make sure the minimum is less than the maximum (MPFR rounding
1596 in the call to mpfr_snprintf can result in the reverse. */
1597 if (res.range.max < res.range.min)
1599 unsigned HOST_WIDE_INT tmp = res.range.min;
1600 res.range.min = res.range.max;
1601 res.range.max = tmp;
1604 /* The range of output is known even if the result isn't bounded. */
1605 if (width == HOST_WIDE_INT_MIN)
1607 res.knownrange = false;
1608 res.range.max = HOST_WIDE_INT_MAX;
1610 else
1611 res.knownrange = true;
1613 /* The output of all directives except "%a" is fully specified
1614 and so the result is bounded unless it exceeds INT_MAX.
1615 For "%a" the output is fully specified only when precision
1616 is explicitly specified. */
1617 res.bounded = (res.knownrange
1618 && (TOUPPER (spec.specifier) != 'A'
1619 || (0 <= prec && (unsigned) prec < target_int_max ()))
1620 && res.range.min < target_int_max ());
1622 return res;
1625 return format_floating (spec, width, prec);
1628 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1629 strings referenced by the expression STR, or (-1, -1) when not known.
1630 Used by the format_string function below. */
1632 static fmtresult
1633 get_string_length (tree str)
1635 if (!str)
1636 return fmtresult ();
1638 if (tree slen = c_strlen (str, 1))
1640 /* Simply return the length of the string. */
1641 fmtresult res;
1642 res.range.min = res.range.max = tree_to_shwi (slen);
1643 res.bounded = true;
1644 res.constant = true;
1645 res.knownrange = true;
1646 return res;
1649 /* Determine the length of the shortest and longest string referenced
1650 by STR. Strings of unknown lengths are bounded by the sizes of
1651 arrays that subexpressions of STR may refer to. Pointers that
1652 aren't known to point any such arrays result in LENRANGE[1] set
1653 to SIZE_MAX. */
1654 tree lenrange[2];
1655 get_range_strlen (str, lenrange);
1657 if (lenrange [0] || lenrange [1])
1659 fmtresult res;
1661 res.range.min = (tree_fits_uhwi_p (lenrange[0])
1662 ? tree_to_uhwi (lenrange[0]) : warn_format_overflow > 1);
1663 res.range.max = (tree_fits_uhwi_p (lenrange[1])
1664 ? tree_to_uhwi (lenrange[1]) : HOST_WIDE_INT_M1U);
1666 /* Set RES.BOUNDED to true if and only if all strings referenced
1667 by STR are known to be bounded (though not necessarily by their
1668 actual length but perhaps by their maximum possible length). */
1669 res.bounded = res.range.max < target_int_max ();
1670 res.knownrange = res.bounded;
1672 /* Set RES.CONSTANT to false even though that may be overly
1673 conservative in rare cases like: 'x ? a : b' where a and
1674 b have the same lengths and consist of the same characters. */
1675 res.constant = false;
1677 return res;
1680 return get_string_length (NULL_TREE);
1683 /* Return the minimum and maximum number of characters formatted
1684 by the '%c' and '%s' format directives and ther wide character
1685 forms for the argument ARG. ARG can be null (for functions
1686 such as vsprinf). */
1688 static fmtresult
1689 format_string (const conversion_spec &spec, tree arg)
1691 /* Set WIDTH and PRECISION based on the specification. */
1692 HOST_WIDE_INT width;
1693 HOST_WIDE_INT prec;
1694 get_width_and_precision (spec, &width, &prec);
1696 fmtresult res;
1698 /* The maximum number of bytes for an unknown wide character argument
1699 to a "%lc" directive adjusted for precision but not field width.
1700 6 is the longest UTF-8 sequence for a single wide character. */
1701 const unsigned HOST_WIDE_INT max_bytes_for_unknown_wc
1702 = (0 <= prec ? prec : warn_format_overflow > 1 ? 6 : 1);
1704 /* The maximum number of bytes for an unknown string argument to either
1705 a "%s" or "%ls" directive adjusted for precision but not field width. */
1706 const unsigned HOST_WIDE_INT max_bytes_for_unknown_str
1707 = (0 <= prec ? prec : warn_format_overflow > 1);
1709 /* The result is bounded unless overriddden for a non-constant string
1710 of an unknown length. */
1711 bool bounded = true;
1713 if (spec.specifier == 'c')
1715 if (spec.modifier == FMT_LEN_l)
1717 /* Positive if the argument is a wide NUL character? */
1718 int nul = (arg && TREE_CODE (arg) == INTEGER_CST
1719 ? integer_zerop (arg) : -1);
1721 /* A '%lc' directive is the same as '%ls' for a two element
1722 wide string character with the second element of NUL, so
1723 when the character is unknown the minimum number of bytes
1724 is the smaller of either 0 (at level 1) or 1 (at level 2)
1725 and WIDTH, and the maximum is MB_CUR_MAX in the selected
1726 locale, which is unfortunately, unknown. */
1727 res.range.min = warn_format_overflow == 1 ? !nul : nul < 1;
1728 res.range.max = max_bytes_for_unknown_wc;
1729 /* The range above is good enough to issue warnings but not
1730 for value range propagation, so clear BOUNDED. */
1731 res.bounded = false;
1733 else
1735 /* A plain '%c' directive. Its ouput is exactly 1. */
1736 res.range.min = res.range.max = 1;
1737 res.bounded = true;
1738 res.knownrange = true;
1739 res.constant = arg && TREE_CODE (arg) == INTEGER_CST;
1742 else /* spec.specifier == 's' */
1744 /* Compute the range the argument's length can be in. */
1745 fmtresult slen = get_string_length (arg);
1746 if (slen.constant)
1748 gcc_checking_assert (slen.range.min == slen.range.max);
1750 /* A '%s' directive with a string argument with constant length. */
1751 res.range = slen.range;
1753 /* The output of "%s" and "%ls" directives with a constant
1754 string is in a known range unless width of an unknown value
1755 is specified. For "%s" it is the length of the string. For
1756 "%ls" it is in the range [length, length * MB_LEN_MAX].
1757 (The final range can be further constrained by width and
1758 precision but it's always known.) */
1759 res.knownrange = -1 < width;
1761 if (spec.modifier == FMT_LEN_l)
1763 bounded = false;
1765 if (warn_format_overflow > 1)
1767 /* Leave the minimum number of bytes the wide string
1768 converts to equal to its length and set the maximum
1769 to the worst case length which is the string length
1770 multiplied by MB_LEN_MAX. */
1772 /* It's possible to be smarter about computing the maximum
1773 by scanning the wide string for any 8-bit characters and
1774 if it contains none, using its length for the maximum.
1775 Even though this would be simple to do it's unlikely to
1776 be worth it when dealing with wide characters. */
1777 res.range.max *= target_mb_len_max;
1780 /* For a wide character string, use precision as the maximum
1781 even if precision is greater than the string length since
1782 the number of bytes the string converts to may be greater
1783 (due to MB_CUR_MAX). */
1784 if (0 <= prec)
1785 res.range.max = prec;
1787 else if (0 <= width)
1789 /* The output of a "%s" directive with a constant argument
1790 and constant or no width is bounded. It is constant if
1791 precision is either not specified or it is specified and
1792 its value is known. */
1793 res.bounded = true;
1794 res.constant = prec != HOST_WIDE_INT_MIN;
1796 else if (width == HOST_WIDE_INT_MIN)
1798 /* Specified but unknown width makes the output unbounded. */
1799 res.range.max = HOST_WIDE_INT_MAX;
1802 if (0 <= prec && (unsigned HOST_WIDE_INT)prec < res.range.min)
1804 res.range.min = prec;
1805 res.range.max = prec;
1807 else if (prec == HOST_WIDE_INT_MIN)
1809 /* When precision is specified but not known the lower
1810 bound is assumed to be as low as zero. */
1811 res.range.min = 0;
1814 else if (arg && integer_zerop (arg))
1816 /* Handle null pointer argument. */
1818 fmtresult res;
1819 res.range.min = 0;
1820 res.range.max = HOST_WIDE_INT_MAX;
1821 res.nullp = true;
1822 return res;
1824 else
1826 /* For a '%s' and '%ls' directive with a non-constant string,
1827 the minimum number of characters is the greater of WIDTH
1828 and either 0 in mode 1 or the smaller of PRECISION and 1
1829 in mode 2, and the maximum is PRECISION or -1 to disable
1830 tracking. */
1832 if (0 <= prec)
1834 if (slen.range.min >= target_int_max ())
1835 slen.range.min = 0;
1836 else if ((unsigned HOST_WIDE_INT)prec < slen.range.min)
1837 slen.range.min = prec;
1839 if ((unsigned HOST_WIDE_INT)prec < slen.range.max
1840 || slen.range.max >= target_int_max ())
1841 slen.range.max = prec;
1843 else if (slen.range.min >= target_int_max ())
1845 slen.range.min = max_bytes_for_unknown_str;
1846 slen.range.max = max_bytes_for_unknown_str;
1847 bounded = false;
1850 res.range = slen.range;
1852 /* The output is considered bounded when a precision has been
1853 specified to limit the number of bytes or when the number
1854 of bytes is known or contrained to some range. */
1855 res.bounded = 0 <= prec || slen.bounded;
1856 res.knownrange = slen.knownrange;
1857 res.constant = false;
1861 /* Adjust the lengths for field width. */
1862 if (0 < width)
1864 if (res.range.min < (unsigned HOST_WIDE_INT)width)
1865 res.range.min = width;
1867 if (res.range.max < (unsigned HOST_WIDE_INT)width)
1868 res.range.max = width;
1870 /* Adjust BOUNDED if width happens to make them equal. */
1871 if (res.range.min == res.range.max && res.range.min < target_int_max ()
1872 && bounded)
1873 res.bounded = true;
1876 /* When precision is specified the range of characters on output
1877 is known to be bounded by it. */
1878 if (-1 < width && -1 < prec)
1879 res.knownrange = true;
1881 return res;
1884 /* Compute the length of the output resulting from the conversion
1885 specification SPEC with the argument ARG in a call described by INFO
1886 and update the overall result of the call in *RES. The format directive
1887 corresponding to SPEC starts at CVTBEG and is CVTLEN characters long. */
1889 static void
1890 format_directive (const pass_sprintf_length::call_info &info,
1891 format_result *res, const char *cvtbeg, size_t cvtlen,
1892 const conversion_spec &spec, tree arg)
1894 /* Offset of the beginning of the directive from the beginning
1895 of the format string. */
1896 size_t offset = cvtbeg - info.fmtstr;
1898 /* Create a location for the whole directive from the % to the format
1899 specifier. */
1900 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
1901 offset, offset, offset + cvtlen - 1);
1903 /* Also create a location range for the argument if possible.
1904 This doesn't work for integer literals or function calls. */
1905 source_range argrange;
1906 source_range *pargrange;
1907 if (arg && CAN_HAVE_LOCATION_P (arg))
1909 argrange = EXPR_LOCATION_RANGE (arg);
1910 pargrange = &argrange;
1912 else
1913 pargrange = NULL;
1915 /* Bail when there is no function to compute the output length,
1916 or when minimum length checking has been disabled. */
1917 if (!spec.fmtfunc || res->number_chars_min >= HOST_WIDE_INT_MAX)
1918 return;
1920 /* Compute the (approximate) length of the formatted output. */
1921 fmtresult fmtres = spec.fmtfunc (spec, arg);
1923 /* The overall result is bounded and constant only if the output
1924 of every directive is bounded and constant, respectively. */
1925 res->bounded &= fmtres.bounded;
1926 res->constant &= fmtres.constant;
1928 /* Record whether the output of all directives is known to be
1929 bounded by some maximum, implying that their arguments are
1930 either known exactly or determined to be in a known range
1931 or, for strings, limited by the upper bounds of the arrays
1932 they refer to. */
1933 res->knownrange &= fmtres.knownrange;
1935 if (!fmtres.knownrange)
1937 /* Only when the range is known, check it against the host value
1938 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
1939 INT_MAX precision, which is the longest possible output of any
1940 single directive). That's the largest valid byte count (though
1941 not valid call to a printf-like function because it can never
1942 return such a count). Otherwise, the range doesn't correspond
1943 to known values of the argument. */
1944 if (fmtres.range.max > target_dir_max ())
1946 /* Normalize the MAX counter to avoid having to deal with it
1947 later. The counter can be less than HOST_WIDE_INT_M1U
1948 when compiling for an ILP32 target on an LP64 host. */
1949 fmtres.range.max = HOST_WIDE_INT_M1U;
1950 /* Disable exact and maximum length checking after a failure
1951 to determine the maximum number of characters (for example
1952 for wide characters or wide character strings) but continue
1953 tracking the minimum number of characters. */
1954 res->number_chars_max = HOST_WIDE_INT_M1U;
1955 res->number_chars = HOST_WIDE_INT_M1U;
1958 if (fmtres.range.min > target_dir_max ())
1960 /* Disable exact length checking after a failure to determine
1961 even the minimum number of characters (it shouldn't happen
1962 except in an error) but keep tracking the minimum and maximum
1963 number of characters. */
1964 res->number_chars = HOST_WIDE_INT_M1U;
1965 return;
1969 if (fmtres.nullp)
1971 fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
1972 "%<%.*s%> directive argument is null",
1973 (int)cvtlen, cvtbeg);
1975 /* Don't bother processing the rest of the format string. */
1976 res->warned = true;
1977 res->number_chars = HOST_WIDE_INT_M1U;
1978 res->number_chars_min = res->number_chars_max = res->number_chars;
1979 return;
1982 bool warned = res->warned;
1984 /* Compute the number of available bytes in the destination. There
1985 must always be at least one byte of space for the terminating
1986 NUL that's appended after the format string has been processed. */
1987 unsigned HOST_WIDE_INT navail = min_bytes_remaining (info.objsize, *res);
1989 if (fmtres.range.min < fmtres.range.max)
1991 /* The result is a range (i.e., it's inexact). */
1992 if (!warned)
1994 if (navail < fmtres.range.min)
1996 /* The minimum directive output is longer than there is
1997 room in the destination. */
1998 if (fmtres.range.min == fmtres.range.max)
2000 const char* fmtstr
2001 = (info.bounded
2002 ? G_("%<%.*s%> directive output truncated writing "
2003 "%wu bytes into a region of size %wu")
2004 : G_("%<%.*s%> directive writing %wu bytes "
2005 "into a region of size %wu"));
2006 warned = fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
2007 fmtstr,
2008 (int)cvtlen, cvtbeg, fmtres.range.min,
2009 navail);
2011 else if (fmtres.range.max < HOST_WIDE_INT_MAX)
2013 const char* fmtstr
2014 = (info.bounded
2015 ? G_("%<%.*s%> directive output truncated writing "
2016 "between %wu and %wu bytes into a region of "
2017 "size %wu")
2018 : G_("%<%.*s%> directive writing between %wu and "
2019 "%wu bytes into a region of size %wu"));
2020 warned = fmtwarn (dirloc, pargrange, NULL,
2021 info.warnopt (), fmtstr,
2022 (int)cvtlen, cvtbeg,
2023 fmtres.range.min, fmtres.range.max, navail);
2025 else
2027 const char* fmtstr
2028 = (info.bounded
2029 ? G_("%<%.*s%> directive output truncated writing "
2030 "%wu or more bytes into a region of size %wu")
2031 : G_("%<%.*s%> directive writing %wu or more bytes "
2032 "into a region of size %wu"));
2033 warned = fmtwarn (dirloc, pargrange, NULL,
2034 info.warnopt (), fmtstr,
2035 (int)cvtlen, cvtbeg,
2036 fmtres.range.min, navail);
2039 else if (navail < fmtres.range.max
2040 && (spec.specifier != 's'
2041 || fmtres.range.max < HOST_WIDE_INT_MAX)
2042 && ((info.bounded
2043 && (!info.retval_used ()
2044 || warn_format_trunc > 1))
2045 || (!info.bounded
2046 && (spec.specifier == 's'
2047 || warn_format_overflow > 1))))
2049 /* The maximum directive output is longer than there is
2050 room in the destination and the output length is either
2051 explicitly constrained by the precision (for strings)
2052 or the warning level is greater than 1. */
2053 if (fmtres.range.max >= HOST_WIDE_INT_MAX)
2055 const char* fmtstr
2056 = (info.bounded
2057 ? G_("%<%.*s%> directive output may be truncated "
2058 "writing %wu or more bytes into a region "
2059 "of size %wu")
2060 : G_("%<%.*s%> directive writing %wu or more bytes "
2061 "into a region of size %wu"));
2062 warned = fmtwarn (dirloc, pargrange, NULL,
2063 info.warnopt (), fmtstr,
2064 (int)cvtlen, cvtbeg,
2065 fmtres.range.min, navail);
2067 else
2069 const char* fmtstr
2070 = (info.bounded
2071 ? G_("%<%.*s%> directive output may be truncated "
2072 "writing between %wu and %wu bytes into a region "
2073 "of size %wu")
2074 : G_("%<%.*s%> directive writing between %wu and %wu "
2075 "bytes into a region of size %wu"));
2076 warned = fmtwarn (dirloc, pargrange, NULL,
2077 info.warnopt (), fmtstr,
2078 (int)cvtlen, cvtbeg,
2079 fmtres.range.min, fmtres.range.max,
2080 navail);
2085 /* Disable exact length checking but adjust the minimum and maximum. */
2086 res->number_chars = HOST_WIDE_INT_M1U;
2087 if (res->number_chars_max < HOST_WIDE_INT_MAX
2088 && fmtres.range.max < HOST_WIDE_INT_MAX)
2089 res->number_chars_max += fmtres.range.max;
2091 res->number_chars_min += fmtres.range.min;
2093 else
2095 if (!warned && fmtres.range.min > 0 && navail < fmtres.range.min)
2097 const char* fmtstr
2098 = (info.bounded
2099 ? (1 < fmtres.range.min
2100 ? G_("%<%.*s%> directive output truncated while writing "
2101 "%wu bytes into a region of size %wu")
2102 : G_("%<%.*s%> directive output truncated while writing "
2103 "%wu byte into a region of size %wu"))
2104 : (1 < fmtres.range.min
2105 ? G_("%<%.*s%> directive writing %wu bytes "
2106 "into a region of size %wu")
2107 : G_("%<%.*s%> directive writing %wu byte "
2108 "into a region of size %wu")));
2110 warned = fmtwarn (dirloc, pargrange, NULL,
2111 info.warnopt (), fmtstr,
2112 (int)cvtlen, cvtbeg, fmtres.range.min,
2113 navail);
2115 *res += fmtres.range.min;
2118 /* Has the minimum directive output length exceeded the maximum
2119 of 4095 bytes required to be supported? */
2120 bool minunder4k = fmtres.range.min < 4096;
2121 if (!minunder4k || fmtres.range.max > 4095)
2122 res->under4k = false;
2124 if (!warned && warn_format_overflow > 1
2125 && (!minunder4k || fmtres.range.max > 4095))
2127 /* The directive output may be longer than the maximum required
2128 to be handled by an implementation according to 7.21.6.1, p15
2129 of C11. Warn on this only at level 2 but remember this and
2130 prevent folding the return value when done. This allows for
2131 the possibility of the actual libc call failing due to ENOMEM
2132 (like Glibc does under some conditions). */
2134 if (fmtres.range.min == fmtres.range.max)
2135 warned = fmtwarn (dirloc, pargrange, NULL,
2136 info.warnopt (),
2137 "%<%.*s%> directive output of %wu bytes exceeds "
2138 "minimum required size of 4095",
2139 (int)cvtlen, cvtbeg, fmtres.range.min);
2140 else
2142 const char *fmtstr
2143 = (minunder4k
2144 ? G_("%<%.*s%> directive output between %qu and %wu "
2145 "bytes may exceed minimum required size of 4095")
2146 : G_("%<%.*s%> directive output between %qu and %wu "
2147 "bytes exceeds minimum required size of 4095"));
2149 warned = fmtwarn (dirloc, pargrange, NULL,
2150 info.warnopt (), fmtstr,
2151 (int)cvtlen, cvtbeg,
2152 fmtres.range.min, fmtres.range.max);
2156 /* Has the minimum directive output length exceeded INT_MAX? */
2157 bool exceedmin = res->number_chars_min > target_int_max ();
2159 if (!warned
2160 && (exceedmin
2161 || (warn_format_overflow > 1
2162 && res->number_chars_max > target_int_max ())))
2164 /* The directive output causes the total length of output
2165 to exceed INT_MAX bytes. */
2167 if (fmtres.range.min == fmtres.range.max)
2168 warned = fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
2169 "%<%.*s%> directive output of %wu bytes causes "
2170 "result to exceed %<INT_MAX%>",
2171 (int)cvtlen, cvtbeg, fmtres.range.min);
2172 else
2174 const char *fmtstr
2175 = (exceedmin
2176 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2177 "bytes causes result to exceed %<INT_MAX%>")
2178 : G_ ("%<%.*s%> directive output between %wu and %wu "
2179 "bytes may cause result to exceed %<INT_MAX%>"));
2180 warned = fmtwarn (dirloc, pargrange, NULL,
2181 info.warnopt (), fmtstr,
2182 (int)cvtlen, cvtbeg,
2183 fmtres.range.min, fmtres.range.max);
2187 if (warned && fmtres.argmin)
2189 if (fmtres.argmin == fmtres.argmax)
2190 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2191 else if (fmtres.knownrange)
2192 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2193 fmtres.argmin, fmtres.argmax);
2194 else
2195 inform (info.fmtloc,
2196 "using the range [%E, %E] for directive argument",
2197 fmtres.argmin, fmtres.argmax);
2200 res->warned |= warned;
2203 /* Account for the number of bytes between BEG and END (or between
2204 BEG + strlen (BEG) when END is null) in the format string in a call
2205 to a formatted output function described by INFO. Reflect the count
2206 in RES and issue warnings as appropriate. */
2208 static void
2209 add_bytes (const pass_sprintf_length::call_info &info,
2210 const char *beg, const char *end, format_result *res)
2212 if (res->number_chars_min >= HOST_WIDE_INT_MAX)
2213 return;
2215 /* The number of bytes to output is the number of bytes between
2216 the end of the last directive and the beginning of the next
2217 one if it exists, otherwise the number of characters remaining
2218 in the format string plus 1 for the terminating NUL. */
2219 size_t nbytes = end ? end - beg : strlen (beg) + 1;
2221 /* Return if there are no bytes to add at this time but there are
2222 directives remaining in the format string. */
2223 if (!nbytes)
2224 return;
2226 /* Compute the range of available bytes in the destination. There
2227 must always be at least one byte left for the terminating NUL
2228 that's appended after the format string has been processed. */
2229 result_range avail_range = bytes_remaining (info.objsize, *res);
2231 /* If issuing a diagnostic (only when one hasn't already been issued),
2232 distinguish between a possible overflow ("may write") and a certain
2233 overflow somewhere "past the end." (Ditto for truncation.)
2234 KNOWNRANGE is used to warn even at level 1 about possibly writing
2235 past the end or truncation due to strings of unknown lengths that
2236 are bounded by the arrays they are known to refer to. */
2237 if (!res->warned
2238 && (avail_range.max < nbytes
2239 || ((res->knownrange || warn_format_overflow > 1)
2240 && avail_range.min < nbytes)))
2242 /* Set NAVAIL to the number of available bytes used to decide
2243 whether or not to issue a warning below. The exact kind of
2244 warning will depend on AVAIL_RANGE. */
2245 unsigned HOST_WIDE_INT navail = avail_range.max;
2246 if (nbytes <= navail && avail_range.min < HOST_WIDE_INT_MAX
2247 && (res->knownrange || warn_format_overflow > 1))
2248 navail = avail_range.min;
2250 /* Compute the offset of the first format character that is beyond
2251 the end of the destination region and the length of the rest of
2252 the format string from that point on. */
2253 unsigned HOST_WIDE_INT off
2254 = (unsigned HOST_WIDE_INT)(beg - info.fmtstr) + navail;
2256 size_t len = strlen (info.fmtstr + off);
2258 /* Create a location that underscores the substring of the format
2259 string that is or may be written past the end (or is or may be
2260 truncated), pointing the caret at the first character of the
2261 substring. */
2262 substring_loc loc
2263 (info.fmtloc, TREE_TYPE (info.format), off, len ? off : 0,
2264 off + len - !!len);
2266 /* Is the output of the last directive the result of the argument
2267 being within a range whose lower bound would fit in the buffer
2268 but the upper bound would not? If so, use the word "may" to
2269 indicate that the overflow/truncation may (but need not) happen. */
2270 bool boundrange
2271 = (res->number_chars_min < res->number_chars_max
2272 && res->number_chars_min + nbytes <= info.objsize);
2274 if (!end && ((nbytes - navail) == 1 || boundrange))
2276 /* There is room for the rest of the format string but none
2277 for the terminating nul. */
2278 const char *text
2279 = (info.bounded // Snprintf and the like.
2280 ? (boundrange
2281 ? G_("output may be truncated before the last format character"
2282 : "output truncated before the last format character"))
2283 : (boundrange
2284 ? G_("may write a terminating nul past the end "
2285 "of the destination")
2286 : G_("writing a terminating nul past the end "
2287 "of the destination")));
2289 if (!info.bounded
2290 || !boundrange
2291 || !info.retval_used ()
2292 || warn_format_trunc > 1)
2293 res->warned = fmtwarn (loc, NULL, NULL, info.warnopt (), text);
2295 else
2297 /* There isn't enough room for 1 or more characters that remain
2298 to copy from the format string. */
2299 const char *text
2300 = (info.bounded // Snprintf and the like.
2301 ? (boundrange
2302 ? G_("output may be truncated at or before format character "
2303 "%qc at offset %wu")
2304 : G_("output truncated at format character %qc at offset %wu"))
2305 : (res->number_chars >= HOST_WIDE_INT_MAX
2306 ? G_("may write format character %#qc at offset %wu past "
2307 "the end of the destination")
2308 : G_("writing format character %#qc at offset %wu past "
2309 "the end of the destination")));
2311 if (!info.bounded
2312 || !boundrange
2313 || !info.retval_used ()
2314 || warn_format_trunc > 1)
2315 res->warned = fmtwarn (loc, NULL, NULL, info.warnopt (),
2316 text, info.fmtstr[off], off);
2320 if (res->warned && !end && info.objsize < HOST_WIDE_INT_MAX)
2322 /* If a warning has been issued for buffer overflow or truncation
2323 (but not otherwise) help the user figure out how big a buffer
2324 they need. */
2326 location_t callloc = gimple_location (info.callstmt);
2328 unsigned HOST_WIDE_INT min = res->number_chars_min;
2329 unsigned HOST_WIDE_INT max = res->number_chars_max;
2330 unsigned HOST_WIDE_INT exact
2331 = (res->number_chars < HOST_WIDE_INT_MAX
2332 ? res->number_chars : res->number_chars_min);
2334 if (min < max && max < HOST_WIDE_INT_MAX)
2335 inform (callloc,
2336 "format output between %wu and %wu bytes into "
2337 "a destination of size %wu",
2338 min + nbytes, max + nbytes, info.objsize);
2339 else
2340 inform (callloc,
2341 (nbytes + exact == 1
2342 ? G_("format output %wu byte into a destination of size %wu")
2343 : G_("format output %wu bytes into a destination of size %wu")),
2344 nbytes + exact, info.objsize);
2347 /* Add the number of bytes and then check for INT_MAX overflow. */
2348 *res += nbytes;
2350 /* Has the minimum output length minus the terminating nul exceeded
2351 INT_MAX? */
2352 bool exceedmin = (res->number_chars_min - !end) > target_int_max ();
2354 if (!res->warned
2355 && (exceedmin
2356 || (warn_format_overflow > 1
2357 && (res->number_chars_max - !end) > target_int_max ())))
2359 /* The function's output exceeds INT_MAX bytes. */
2361 /* Set NAVAIL to the number of available bytes used to decide
2362 whether or not to issue a warning below. The exact kind of
2363 warning will depend on AVAIL_RANGE. */
2364 unsigned HOST_WIDE_INT navail = avail_range.max;
2365 if (nbytes <= navail && avail_range.min < HOST_WIDE_INT_MAX
2366 && (res->bounded || warn_format_overflow > 1))
2367 navail = avail_range.min;
2369 /* Compute the offset of the first format character that is beyond
2370 the end of the destination region and the length of the rest of
2371 the format string from that point on. */
2372 unsigned HOST_WIDE_INT off = (unsigned HOST_WIDE_INT)(beg - info.fmtstr);
2373 if (navail < HOST_WIDE_INT_MAX)
2374 off += navail;
2376 size_t len = strlen (info.fmtstr + off);
2378 substring_loc loc
2379 (info.fmtloc, TREE_TYPE (info.format), off - !len, len ? off : 0,
2380 off + len - !!len);
2382 if (res->number_chars_min == res->number_chars_max)
2383 res->warned = fmtwarn (loc, NULL, NULL, info.warnopt (),
2384 "output of %wu bytes causes "
2385 "result to exceed %<INT_MAX%>",
2386 res->number_chars_min - !end);
2387 else
2389 const char *text
2390 = (exceedmin
2391 ? G_ ("output between %wu and %wu bytes causes "
2392 "result to exceed %<INT_MAX%>")
2393 : G_ ("output between %wu and %wu bytes may cause "
2394 "result to exceed %<INT_MAX%>"));
2395 res->warned = fmtwarn (loc, NULL, NULL, info.warnopt (), text,
2396 res->number_chars_min - !end,
2397 res->number_chars_max - !end);
2402 #pragma GCC diagnostic pop
2404 /* Compute the length of the output resulting from the call to a formatted
2405 output function described by INFO and store the result of the call in
2406 *RES. Issue warnings for detected past the end writes. Return true
2407 if the complete format string has been processed and *RES can be relied
2408 on, false otherwise (e.g., when a unknown or unhandled directive was seen
2409 that caused the processing to be terminated early). */
2411 bool
2412 pass_sprintf_length::compute_format_length (call_info &info,
2413 format_result *res)
2415 /* The variadic argument counter. */
2416 unsigned argno = info.argidx;
2418 /* Reset exact, minimum, and maximum character counters. */
2419 res->number_chars = res->number_chars_min = res->number_chars_max = 0;
2421 /* No directive has been seen yet so the length of output is bounded
2422 by the known range [0, 0] and constant (with no conversion producing
2423 more than 4K bytes) until determined otherwise. */
2424 res->bounded = true;
2425 res->knownrange = true;
2426 res->constant = true;
2427 res->under4k = true;
2428 res->floating = false;
2429 res->warned = false;
2431 const char *pf = info.fmtstr;
2433 for ( ; ; )
2435 /* The beginning of the next format directive. */
2436 const char *dir = strchr (pf, '%');
2438 /* Add the number of bytes between the end of the last directive
2439 and either the next if one exists, or the end of the format
2440 string. */
2441 add_bytes (info, pf, dir, res);
2443 if (!dir)
2444 break;
2446 pf = dir + 1;
2448 if (0 && *pf == 0)
2450 /* Incomplete directive. */
2451 return false;
2454 conversion_spec spec = conversion_spec ();
2456 /* POSIX numbered argument index or zero when none. */
2457 unsigned dollar = 0;
2459 if (ISDIGIT (*pf))
2461 /* This could be either a POSIX positional argument, the '0'
2462 flag, or a width, depending on what follows. Store it as
2463 width and sort it out later after the next character has
2464 been seen. */
2465 char *end;
2466 spec.width = strtol (pf, &end, 10);
2467 spec.have_width = true;
2468 pf = end;
2470 else if ('*' == *pf)
2472 /* Similarly to the block above, this could be either a POSIX
2473 positional argument or a width, depending on what follows. */
2474 if (argno < gimple_call_num_args (info.callstmt))
2475 spec.star_width = gimple_call_arg (info.callstmt, argno++);
2476 else
2477 spec.star_width = void_node;
2478 ++pf;
2481 if (*pf == '$')
2483 /* Handle the POSIX dollar sign which references the 1-based
2484 positional argument number. */
2485 if (spec.have_width)
2486 dollar = spec.width + info.argidx;
2487 else if (spec.star_width
2488 && TREE_CODE (spec.star_width) == INTEGER_CST)
2489 dollar = spec.width + tree_to_shwi (spec.star_width);
2491 /* Bail when the numbered argument is out of range (it will
2492 have already been diagnosed by -Wformat). */
2493 if (dollar == 0
2494 || dollar == info.argidx
2495 || dollar > gimple_call_num_args (info.callstmt))
2496 return false;
2498 --dollar;
2500 spec.star_width = NULL_TREE;
2501 spec.have_width = false;
2502 ++pf;
2505 if (dollar || !spec.star_width)
2507 if (spec.have_width)
2509 if (spec.width == 0)
2511 /* The '0' that has been interpreted as a width above is
2512 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
2513 and continue processing other flags. */
2514 spec.have_width = false;
2515 spec.set_flag ('0');
2517 else if (!dollar)
2519 /* (Non-zero) width has been seen. The next character
2520 is either a period or a digit. */
2521 goto start_precision;
2524 /* When either '$' has been seen, or width has not been seen,
2525 the next field is the optional flags followed by an optional
2526 width. */
2527 for ( ; ; ) {
2528 switch (*pf)
2530 case ' ':
2531 case '0':
2532 case '+':
2533 case '-':
2534 case '#':
2535 spec.set_flag (*pf++);
2536 break;
2538 default:
2539 goto start_width;
2543 start_width:
2544 if (ISDIGIT (*pf))
2546 char *end;
2547 spec.width = strtol (pf, &end, 10);
2548 spec.have_width = true;
2549 pf = end;
2551 else if ('*' == *pf)
2553 if (argno < gimple_call_num_args (info.callstmt))
2554 spec.star_width = gimple_call_arg (info.callstmt, argno++);
2555 else
2556 spec.star_width = void_node;
2557 ++pf;
2559 else if ('\'' == *pf)
2561 /* The POSIX apostrophe indicating a numeric grouping
2562 in the current locale. Even though it's possible to
2563 estimate the upper bound on the size of the output
2564 based on the number of digits it probably isn't worth
2565 continuing. */
2566 return false;
2570 start_precision:
2571 if ('.' == *pf)
2573 ++pf;
2575 if (ISDIGIT (*pf))
2577 char *end;
2578 spec.precision = strtol (pf, &end, 10);
2579 spec.have_precision = true;
2580 pf = end;
2582 else if ('*' == *pf)
2584 if (argno < gimple_call_num_args (info.callstmt))
2585 spec.star_precision = gimple_call_arg (info.callstmt, argno++);
2586 else
2587 spec.star_precision = void_node;
2588 ++pf;
2590 else
2592 /* The decimal precision or the asterisk are optional.
2593 When neither is specified it's taken to be zero. */
2594 spec.precision = 0;
2595 spec.have_precision = true;
2599 switch (*pf)
2601 case 'h':
2602 if (pf[1] == 'h')
2604 ++pf;
2605 spec.modifier = FMT_LEN_hh;
2607 else
2608 spec.modifier = FMT_LEN_h;
2609 ++pf;
2610 break;
2612 case 'j':
2613 spec.modifier = FMT_LEN_j;
2614 ++pf;
2615 break;
2617 case 'L':
2618 spec.modifier = FMT_LEN_L;
2619 ++pf;
2620 break;
2622 case 'l':
2623 if (pf[1] == 'l')
2625 ++pf;
2626 spec.modifier = FMT_LEN_ll;
2628 else
2629 spec.modifier = FMT_LEN_l;
2630 ++pf;
2631 break;
2633 case 't':
2634 spec.modifier = FMT_LEN_t;
2635 ++pf;
2636 break;
2638 case 'z':
2639 spec.modifier = FMT_LEN_z;
2640 ++pf;
2641 break;
2644 switch (*pf)
2646 /* Handle a sole '%' character the same as "%%" but since it's
2647 undefined prevent the result from being folded. */
2648 case '\0':
2649 --pf;
2650 res->bounded = false;
2651 /* FALLTHRU */
2652 case '%':
2653 spec.fmtfunc = format_percent;
2654 break;
2656 case 'a':
2657 case 'A':
2658 case 'e':
2659 case 'E':
2660 case 'f':
2661 case 'F':
2662 case 'g':
2663 case 'G':
2664 res->floating = true;
2665 spec.fmtfunc = format_floating;
2666 break;
2668 case 'd':
2669 case 'i':
2670 case 'o':
2671 case 'u':
2672 case 'x':
2673 case 'X':
2674 spec.fmtfunc = format_integer;
2675 break;
2677 case 'p':
2678 /* The %p output is implementation-defined. It's possible
2679 to determine this format but due to extensions (especially
2680 those of the Linux kernel -- see bug 78512) the first %p
2681 in the format string disables any further processing. */
2682 return false;
2684 case 'n':
2685 /* %n has side-effects even when nothing is actually printed to
2686 any buffer. */
2687 info.nowrite = false;
2688 break;
2690 case 'c':
2691 case 'S':
2692 case 's':
2693 spec.fmtfunc = format_string;
2694 break;
2696 default:
2697 /* Unknown conversion specification. */
2698 return false;
2701 spec.specifier = *pf++;
2703 /* Compute the length of the format directive. */
2704 size_t dirlen = pf - dir;
2706 /* Extract the argument if the directive takes one and if it's
2707 available (e.g., the function doesn't take a va_list). Treat
2708 missing arguments the same as va_list, even though they will
2709 have likely already been diagnosed by -Wformat. */
2710 tree arg = NULL_TREE;
2711 if (spec.specifier != '%'
2712 && argno < gimple_call_num_args (info.callstmt))
2713 arg = gimple_call_arg (info.callstmt, dollar ? dollar : argno++);
2715 ::format_directive (info, res, dir, dirlen, spec, arg);
2718 /* Complete format string was processed (with or without warnings). */
2719 return true;
2722 /* Return the size of the object referenced by the expression DEST if
2723 available, or -1 otherwise. */
2725 static unsigned HOST_WIDE_INT
2726 get_destination_size (tree dest)
2728 /* Use __builtin_object_size to determine the size of the destination
2729 object. When optimizing, determine the smallest object (such as
2730 a member array as opposed to the whole enclosing object), otherwise
2731 use type-zero object size to determine the size of the enclosing
2732 object (the function fails without optimization in this type). */
2734 init_object_sizes ();
2736 int ost = optimize > 0;
2737 unsigned HOST_WIDE_INT size;
2738 if (compute_builtin_object_size (dest, ost, &size))
2739 return size;
2741 return HOST_WIDE_INT_M1U;
2744 /* Given a suitable result RES of a call to a formatted output function
2745 described by INFO, substitute the result for the return value of
2746 the call. The result is suitable if the number of bytes it represents
2747 is known and exact. A result that isn't suitable for substitution may
2748 have its range set to the range of return values, if that is known.
2749 Return true if the call is removed and gsi_next should not be performed
2750 in the caller. */
2752 static bool
2753 try_substitute_return_value (gimple_stmt_iterator *gsi,
2754 const pass_sprintf_length::call_info &info,
2755 const format_result &res)
2757 tree lhs = gimple_get_lhs (info.callstmt);
2759 /* Avoid the return value optimization when the behavior of the call
2760 is undefined either because any directive may have produced 4K or
2761 more of output, or the return value exceeds INT_MAX, or because
2762 the output overflows the destination object (but leave it enabled
2763 when the function is bounded because then the behavior is well-
2764 defined). */
2765 if (lhs
2766 && res.bounded
2767 && res.under4k
2768 && (info.bounded || res.number_chars <= info.objsize)
2769 && res.number_chars - 1 <= target_int_max ()
2770 /* Not prepared to handle possibly throwing calls here; they shouldn't
2771 appear in non-artificial testcases, except when the __*_chk routines
2772 are badly declared. */
2773 && !stmt_ends_bb_p (info.callstmt))
2775 tree cst = build_int_cst (integer_type_node, res.number_chars - 1);
2777 if (info.nowrite)
2779 /* Replace the call to the bounded function with a zero size
2780 (e.g., snprintf(0, 0, "%i", 123) with the constant result
2781 of the function minus 1 for the terminating NUL which
2782 the function's return value does not include. */
2783 if (!update_call_from_tree (gsi, cst))
2784 gimplify_and_update_call_from_tree (gsi, cst);
2785 gimple *callstmt = gsi_stmt (*gsi);
2786 update_stmt (callstmt);
2788 else
2790 /* Replace the left-hand side of the call with the constant
2791 result of the formatted function minus 1 for the terminating
2792 NUL which the function's return value does not include. */
2793 gimple_call_set_lhs (info.callstmt, NULL_TREE);
2794 gimple *g = gimple_build_assign (lhs, cst);
2795 gsi_insert_after (gsi, g, GSI_NEW_STMT);
2796 update_stmt (info.callstmt);
2799 if (dump_file)
2801 location_t callloc = gimple_location (info.callstmt);
2802 fprintf (dump_file, "On line %i substituting ",
2803 LOCATION_LINE (callloc));
2804 print_generic_expr (dump_file, cst, dump_flags);
2805 fprintf (dump_file, " for ");
2806 print_generic_expr (dump_file, info.func, dump_flags);
2807 fprintf (dump_file, " %s (output %s).\n",
2808 info.nowrite ? "call" : "return value",
2809 res.constant ? "constant" : "variable");
2812 else if (lhs == NULL_TREE
2813 && info.nowrite
2814 && !stmt_ends_bb_p (info.callstmt))
2816 /* Remove the call to the bounded function with a zero size
2817 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
2818 unlink_stmt_vdef (info.callstmt);
2819 gsi_remove (gsi, true);
2820 if (dump_file)
2822 location_t callloc = gimple_location (info.callstmt);
2823 fprintf (dump_file, "On line %i removing ",
2824 LOCATION_LINE (callloc));
2825 print_generic_expr (dump_file, info.func, dump_flags);
2826 fprintf (dump_file, " call.\n");
2828 return true;
2830 else
2832 unsigned HOST_WIDE_INT maxbytes;
2834 if (lhs
2835 && res.bounded
2836 && ((maxbytes = res.number_chars - 1) <= target_int_max ()
2837 || (res.number_chars_min - 1 <= target_int_max ()
2838 && (maxbytes = res.number_chars_max - 1) <= target_int_max ()))
2839 && (info.bounded || maxbytes < info.objsize))
2841 /* If the result is in a valid range bounded by the size of
2842 the destination set it so that it can be used for subsequent
2843 optimizations. */
2844 int prec = TYPE_PRECISION (integer_type_node);
2846 if (res.number_chars < target_int_max () && res.under4k)
2848 wide_int num = wi::shwi (res.number_chars - 1, prec);
2849 set_range_info (lhs, VR_RANGE, num, num);
2851 else if (res.number_chars_min < target_int_max ()
2852 && res.number_chars_max < target_int_max ())
2854 wide_int min = wi::shwi (res.under4k ? res.number_chars_min - 1
2855 : target_int_min (), prec);
2856 wide_int max = wi::shwi (res.number_chars_max - 1, prec);
2857 set_range_info (lhs, VR_RANGE, min, max);
2861 if (dump_file)
2863 const char *inbounds
2864 = (res.number_chars_min <= info.objsize
2865 ? (res.number_chars_max <= info.objsize
2866 ? "in" : "potentially out-of")
2867 : "out-of");
2869 location_t callloc = gimple_location (info.callstmt);
2870 fprintf (dump_file, "On line %i ", LOCATION_LINE (callloc));
2871 print_generic_expr (dump_file, info.func, dump_flags);
2873 const char *ign = lhs ? "" : " ignored";
2874 if (res.number_chars >= HOST_WIDE_INT_MAX)
2875 fprintf (dump_file,
2876 " %s-bounds return value in range [%lu, %lu]%s.\n",
2877 inbounds,
2878 (unsigned long)res.number_chars_min - 1,
2879 (unsigned long)res.number_chars_max - 1, ign);
2880 else
2881 fprintf (dump_file, " %s-bounds return value %lu%s.\n",
2882 inbounds, (unsigned long)res.number_chars - 1, ign);
2886 return false;
2889 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
2890 functions and if so, handle it. Return true if the call is removed
2891 and gsi_next should not be performed in the caller. */
2893 bool
2894 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator *gsi)
2896 call_info info = call_info ();
2898 info.callstmt = gsi_stmt (*gsi);
2899 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
2900 return false;
2902 info.func = gimple_call_fndecl (info.callstmt);
2903 info.fncode = DECL_FUNCTION_CODE (info.func);
2905 /* The size of the destination as in snprintf(dest, size, ...). */
2906 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
2908 /* The size of the destination determined by __builtin_object_size. */
2909 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
2911 /* Buffer size argument number (snprintf and vsnprintf). */
2912 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
2914 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
2915 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
2917 /* Format string argument number (valid for all functions). */
2918 unsigned idx_format;
2920 switch (info.fncode)
2922 case BUILT_IN_SPRINTF:
2923 // Signature:
2924 // __builtin_sprintf (dst, format, ...)
2925 idx_format = 1;
2926 info.argidx = 2;
2927 break;
2929 case BUILT_IN_SPRINTF_CHK:
2930 // Signature:
2931 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
2932 idx_objsize = 2;
2933 idx_format = 3;
2934 info.argidx = 4;
2935 break;
2937 case BUILT_IN_SNPRINTF:
2938 // Signature:
2939 // __builtin_snprintf (dst, size, format, ...)
2940 idx_dstsize = 1;
2941 idx_format = 2;
2942 info.argidx = 3;
2943 info.bounded = true;
2944 break;
2946 case BUILT_IN_SNPRINTF_CHK:
2947 // Signature:
2948 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
2949 idx_dstsize = 1;
2950 idx_objsize = 3;
2951 idx_format = 4;
2952 info.argidx = 5;
2953 info.bounded = true;
2954 break;
2956 case BUILT_IN_VSNPRINTF:
2957 // Signature:
2958 // __builtin_vsprintf (dst, size, format, va)
2959 idx_dstsize = 1;
2960 idx_format = 2;
2961 info.argidx = -1;
2962 info.bounded = true;
2963 break;
2965 case BUILT_IN_VSNPRINTF_CHK:
2966 // Signature:
2967 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
2968 idx_dstsize = 1;
2969 idx_objsize = 3;
2970 idx_format = 4;
2971 info.argidx = -1;
2972 info.bounded = true;
2973 break;
2975 case BUILT_IN_VSPRINTF:
2976 // Signature:
2977 // __builtin_vsprintf (dst, format, va)
2978 idx_format = 1;
2979 info.argidx = -1;
2980 break;
2982 case BUILT_IN_VSPRINTF_CHK:
2983 // Signature:
2984 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
2985 idx_format = 3;
2986 idx_objsize = 2;
2987 info.argidx = -1;
2988 break;
2990 default:
2991 return false;
2994 /* The first argument is a pointer to the destination. */
2995 tree dstptr = gimple_call_arg (info.callstmt, 0);
2997 info.format = gimple_call_arg (info.callstmt, idx_format);
2999 if (idx_dstsize == HOST_WIDE_INT_M1U)
3001 /* For non-bounded functions like sprintf, determine the size
3002 of the destination from the object or pointer passed to it
3003 as the first argument. */
3004 dstsize = get_destination_size (dstptr);
3006 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3008 /* For bounded functions try to get the size argument. */
3010 if (TREE_CODE (size) == INTEGER_CST)
3012 dstsize = tree_to_uhwi (size);
3013 /* No object can be larger than SIZE_MAX bytes (half the address
3014 space) on the target.
3015 The functions are defined only for output of at most INT_MAX
3016 bytes. Specifying a bound in excess of that limit effectively
3017 defeats the bounds checking (and on some implementations such
3018 as Solaris cause the function to fail with EINVAL). */
3019 if (dstsize > target_size_max () / 2)
3021 /* Avoid warning if -Wstringop-overflow is specified since
3022 it also warns for the same thing though only for the
3023 checking built-ins. */
3024 if ((idx_objsize == HOST_WIDE_INT_M1U
3025 || !warn_stringop_overflow))
3026 warning_at (gimple_location (info.callstmt), info.warnopt (),
3027 "specified bound %wu exceeds maximum object size "
3028 "%wu",
3029 dstsize, target_size_max () / 2);
3031 else if (dstsize > target_int_max ())
3032 warning_at (gimple_location (info.callstmt), info.warnopt (),
3033 "specified bound %wu exceeds %<INT_MAX %>",
3034 dstsize);
3036 else if (TREE_CODE (size) == SSA_NAME)
3038 /* Try to determine the range of values of the argument
3039 and use the greater of the two at -Wformat-level 1 and
3040 the smaller of them at level 2. */
3041 wide_int min, max;
3042 enum value_range_type range_type
3043 = get_range_info (size, &min, &max);
3044 if (range_type == VR_RANGE)
3046 dstsize
3047 = (warn_format_overflow < 2
3048 ? wi::fits_uhwi_p (max) ? max.to_uhwi () : max.to_shwi ()
3049 : wi::fits_uhwi_p (min) ? min.to_uhwi () : min.to_shwi ());
3054 if (idx_objsize != HOST_WIDE_INT_M1U)
3055 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3056 if (tree_fits_uhwi_p (size))
3057 objsize = tree_to_uhwi (size);
3059 if (info.bounded && !dstsize)
3061 /* As a special case, when the explicitly specified destination
3062 size argument (to a bounded function like snprintf) is zero
3063 it is a request to determine the number of bytes on output
3064 without actually producing any. Pretend the size is
3065 unlimited in this case. */
3066 info.objsize = HOST_WIDE_INT_MAX;
3067 info.nowrite = true;
3069 else
3071 /* For calls to non-bounded functions or to those of bounded
3072 functions with a non-zero size, warn if the destination
3073 pointer is null. */
3074 if (integer_zerop (dstptr))
3076 /* This is diagnosed with -Wformat only when the null is a constant
3077 pointer. The warning here diagnoses instances where the pointer
3078 is not constant. */
3079 location_t loc = gimple_location (info.callstmt);
3080 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3081 info.warnopt (), "null destination pointer");
3082 return false;
3085 /* Set the object size to the smaller of the two arguments
3086 of both have been specified and they're not equal. */
3087 info.objsize = dstsize < objsize ? dstsize : objsize;
3089 if (info.bounded
3090 && dstsize < target_size_max () / 2 && objsize < dstsize
3091 /* Avoid warning if -Wstringop-overflow is specified since
3092 it also warns for the same thing though only for the
3093 checking built-ins. */
3094 && (idx_objsize == HOST_WIDE_INT_M1U
3095 || !warn_stringop_overflow))
3097 warning_at (gimple_location (info.callstmt), info.warnopt (),
3098 "specified bound %wu exceeds the size %wu "
3099 "of the destination object", dstsize, objsize);
3103 if (integer_zerop (info.format))
3105 /* This is diagnosed with -Wformat only when the null is a constant
3106 pointer. The warning here diagnoses instances where the pointer
3107 is not constant. */
3108 location_t loc = gimple_location (info.callstmt);
3109 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3110 info.warnopt (), "null format string");
3111 return false;
3114 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3115 if (!info.fmtstr)
3116 return false;
3118 /* The result is the number of bytes output by the formatted function,
3119 including the terminating NUL. */
3120 format_result res = format_result ();
3122 bool success = compute_format_length (info, &res);
3124 /* When optimizing and the printf return value optimization is enabled,
3125 attempt to substitute the computed result for the return value of
3126 the call. Avoid this optimization when -frounding-math is in effect
3127 and the format string contains a floating point directive. */
3128 if (success
3129 && optimize > 0
3130 && flag_printf_return_value
3131 && (!flag_rounding_math || !res.floating))
3132 return try_substitute_return_value (gsi, info, res);
3133 return false;
3136 /* Execute the pass for function FUN. */
3138 unsigned int
3139 pass_sprintf_length::execute (function *fun)
3141 basic_block bb;
3142 FOR_EACH_BB_FN (bb, fun)
3144 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
3146 /* Iterate over statements, looking for function calls. */
3147 gimple *stmt = gsi_stmt (si);
3149 if (is_gimple_call (stmt) && handle_gimple_call (&si))
3150 /* If handle_gimple_call returns true, the iterator is
3151 already pointing to the next statement. */
3152 continue;
3154 gsi_next (&si);
3158 fini_object_sizes ();
3160 return 0;
3163 } /* Unnamed namespace. */
3165 /* Return a pointer to a pass object newly constructed from the context
3166 CTXT. */
3168 gimple_opt_pass *
3169 make_pass_sprintf_length (gcc::context *ctxt)
3171 return new pass_sprintf_length (ctxt);