* fi.po: Update.
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blobd468cd7f369d93a8061bbccd330f4e37a5ad928b
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 void 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_length > 0 || flag_printf_return_value)
145 && (optimize > 0) == fold_return_value);
148 /* The result of a call to a formatted function. */
150 struct format_result
152 /* Number of characters written by the formatted function, exact,
153 minimum and maximum when an exact number cannot be determined.
154 Setting the minimum to HOST_WIDE_INT_MAX disables all length
155 tracking for the remainder of the format string.
156 Setting either of the other two members to HOST_WIDE_INT_MAX
157 disables the exact or maximum length tracking, respectively,
158 but continues to track the maximum. */
159 unsigned HOST_WIDE_INT number_chars;
160 unsigned HOST_WIDE_INT number_chars_min;
161 unsigned HOST_WIDE_INT number_chars_max;
163 /* True when the range given by NUMBER_CHARS_MIN and NUMBER_CHARS_MAX
164 can be relied on for value range propagation, false otherwise.
165 This means that BOUNDED must not be set if the number of bytes
166 produced by any directive is unspecified or implementation-
167 defined (unless the implementation's behavior is known and
168 determined via a target hook).
169 Note that BOUNDED only implies that the length of a function's
170 output is known to be within some range, not that it's constant
171 and a candidate for string folding. BOUNDED is a stronger
172 guarantee than KNOWNRANGE. */
173 bool bounded;
175 /* True when the range above is obtained from known values of
176 directive arguments or their bounds and not the result of
177 heuristics that depend on warning levels. It is used to
178 issue stricter diagnostics in cases where strings of unknown
179 lengths are bounded by the arrays they are determined to
180 refer to. KNOWNRANGE must not be used to set the range of
181 the return value of a call. */
182 bool knownrange;
184 /* True when the output of the formatted call is constant (and
185 thus a candidate for string constant folding). This is rare
186 and typically requires that the arguments of all directives
187 are also constant. CONSTANT implies BOUNDED. */
188 bool constant;
190 /* True if no individual directive resulted in more than 4095 bytes
191 of output (the total NUMBER_CHARS might be greater). */
192 bool under4k;
194 /* True when a floating point directive has been seen in the format
195 string. */
196 bool floating;
198 /* True when an intermediate result has caused a warning. Used to
199 avoid issuing duplicate warnings while finishing the processing
200 of a call. */
201 bool warned;
203 /* Preincrement the number of output characters by 1. */
204 format_result& operator++ ()
206 return *this += 1;
209 /* Postincrement the number of output characters by 1. */
210 format_result operator++ (int)
212 format_result prev (*this);
213 *this += 1;
214 return prev;
217 /* Increment the number of output characters by N. */
218 format_result& operator+= (unsigned HOST_WIDE_INT n)
220 gcc_assert (n < HOST_WIDE_INT_MAX);
222 if (number_chars < HOST_WIDE_INT_MAX)
223 number_chars += n;
224 if (number_chars_min < HOST_WIDE_INT_MAX)
225 number_chars_min += n;
226 if (number_chars_max < HOST_WIDE_INT_MAX)
227 number_chars_max += n;
228 return *this;
232 /* Return the value of INT_MIN for the target. */
234 static inline HOST_WIDE_INT
235 target_int_min ()
237 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
240 /* Return the value of INT_MAX for the target. */
242 static inline unsigned HOST_WIDE_INT
243 target_int_max ()
245 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
248 /* Return the value of SIZE_MAX for the target. */
250 static inline unsigned HOST_WIDE_INT
251 target_size_max ()
253 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
256 /* Return the constant initial value of DECL if available or DECL
257 otherwise. Same as the synonymous function in c/c-typeck.c. */
259 static tree
260 decl_constant_value (tree decl)
262 if (/* Don't change a variable array bound or initial value to a constant
263 in a place where a variable is invalid. Note that DECL_INITIAL
264 isn't valid for a PARM_DECL. */
265 current_function_decl != 0
266 && TREE_CODE (decl) != PARM_DECL
267 && !TREE_THIS_VOLATILE (decl)
268 && TREE_READONLY (decl)
269 && DECL_INITIAL (decl) != 0
270 && TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK
271 /* This is invalid if initial value is not constant.
272 If it has either a function call, a memory reference,
273 or a variable, then re-evaluating it could give different results. */
274 && TREE_CONSTANT (DECL_INITIAL (decl))
275 /* Check for cases where this is sub-optimal, even though valid. */
276 && TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)
277 return DECL_INITIAL (decl);
278 return decl;
281 /* Given FORMAT, set *PLOC to the source location of the format string
282 and return the format string if it is known or null otherwise. */
284 static const char*
285 get_format_string (tree format, location_t *ploc)
287 if (VAR_P (format))
289 /* Pull out a constant value if the front end didn't. */
290 format = decl_constant_value (format);
291 STRIP_NOPS (format);
294 if (integer_zerop (format))
296 /* FIXME: Diagnose null format string if it hasn't been diagnosed
297 by -Wformat (the latter diagnoses only nul pointer constants,
298 this pass can do better). */
299 return NULL;
302 HOST_WIDE_INT offset = 0;
304 if (TREE_CODE (format) == POINTER_PLUS_EXPR)
306 tree arg0 = TREE_OPERAND (format, 0);
307 tree arg1 = TREE_OPERAND (format, 1);
308 STRIP_NOPS (arg0);
309 STRIP_NOPS (arg1);
311 if (TREE_CODE (arg1) != INTEGER_CST)
312 return NULL;
314 format = arg0;
316 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
317 if (!cst_and_fits_in_hwi (arg1))
318 return NULL;
320 offset = int_cst_value (arg1);
323 if (TREE_CODE (format) != ADDR_EXPR)
324 return NULL;
326 *ploc = EXPR_LOC_OR_LOC (format, input_location);
328 format = TREE_OPERAND (format, 0);
330 if (TREE_CODE (format) == ARRAY_REF
331 && tree_fits_shwi_p (TREE_OPERAND (format, 1))
332 && (offset += tree_to_shwi (TREE_OPERAND (format, 1))) >= 0)
333 format = TREE_OPERAND (format, 0);
335 if (offset < 0)
336 return NULL;
338 tree array_init;
339 tree array_size = NULL_TREE;
341 if (VAR_P (format)
342 && TREE_CODE (TREE_TYPE (format)) == ARRAY_TYPE
343 && (array_init = decl_constant_value (format)) != format
344 && TREE_CODE (array_init) == STRING_CST)
346 /* Extract the string constant initializer. Note that this may
347 include a trailing NUL character that is not in the array (e.g.
348 const char a[3] = "foo";). */
349 array_size = DECL_SIZE_UNIT (format);
350 format = array_init;
353 if (TREE_CODE (format) != STRING_CST)
354 return NULL;
356 if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format))) != char_type_node)
358 /* Wide format string. */
359 return NULL;
362 const char *fmtstr = TREE_STRING_POINTER (format);
363 unsigned fmtlen = TREE_STRING_LENGTH (format);
365 if (array_size)
367 /* Variable length arrays can't be initialized. */
368 gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
370 if (tree_fits_shwi_p (array_size))
372 HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
373 if (array_size_value > 0
374 && array_size_value == (int) array_size_value
375 && fmtlen > array_size_value)
376 fmtlen = array_size_value;
379 if (offset)
381 if (offset >= fmtlen)
382 return NULL;
384 fmtstr += offset;
385 fmtlen -= offset;
388 if (fmtlen < 1 || fmtstr[--fmtlen] != 0)
390 /* FIXME: Diagnose an unterminated format string if it hasn't been
391 diagnosed by -Wformat. Similarly to a null format pointer,
392 -Wformay diagnoses only nul pointer constants, this pass can
393 do better). */
394 return NULL;
397 return fmtstr;
400 /* The format_warning_at_substring function is not used here in a way
401 that makes using attribute format viable. Suppress the warning. */
403 #pragma GCC diagnostic push
404 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
406 /* For convenience and brevity. */
408 static bool
409 (* const fmtwarn) (const substring_loc &, const source_range *,
410 const char *, int, const char *, ...)
411 = format_warning_at_substring;
413 /* Format length modifiers. */
415 enum format_lengths
417 FMT_LEN_none,
418 FMT_LEN_hh, // char argument
419 FMT_LEN_h, // short
420 FMT_LEN_l, // long
421 FMT_LEN_ll, // long long
422 FMT_LEN_L, // long double (and GNU long long)
423 FMT_LEN_z, // size_t
424 FMT_LEN_t, // ptrdiff_t
425 FMT_LEN_j // intmax_t
429 /* A minimum and maximum number of bytes. */
431 struct result_range
433 unsigned HOST_WIDE_INT min, max;
436 /* Description of the result of conversion either of a single directive
437 or the whole format string. */
439 struct fmtresult
441 fmtresult ()
442 : argmin (), argmax (), knownrange (), bounded (), constant (), nullp ()
444 range.min = range.max = HOST_WIDE_INT_MAX;
447 /* The range a directive's argument is in. */
448 tree argmin, argmax;
450 /* The minimum and maximum number of bytes that a directive
451 results in on output for an argument in the range above. */
452 result_range range;
454 /* True when the range above is obtained from a known value of
455 a directive's argument or its bounds and not the result of
456 heuristics that depend on warning levels. */
457 bool knownrange;
459 /* True when the range is the result of an argument determined
460 to be bounded to a subrange of its type or value (such as by
461 value range propagation or the width of the formt directive),
462 false otherwise. */
463 bool bounded;
465 /* True when the output of a directive is constant. This is rare
466 and typically requires that the argument(s) of the directive
467 are also constant (such as determined by constant propagation,
468 though not value range propagation). */
469 bool constant;
471 /* True when the argument is a null pointer. */
472 bool nullp;
475 /* Description of a conversion specification. */
477 struct conversion_spec
479 /* A bitmap of flags, one for each character. */
480 unsigned flags[256 / sizeof (int)];
481 /* Numeric width as in "%8x". */
482 int width;
483 /* Numeric precision as in "%.32s". */
484 int precision;
486 /* Width specified via the '*' character. 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. PLUS indicates whether 1 for
553 a plus sign should be added for positive numbers, and PREFIX whether
554 the length of an octal ('O') or hexadecimal ('0x') prefix should be
555 added for nonzero numbers. Return -1 if X cannot be represented. */
557 static int
558 tree_digits (tree x, int base, bool plus, bool prefix)
560 unsigned HOST_WIDE_INT absval;
562 int res;
564 if (TYPE_UNSIGNED (TREE_TYPE (x)))
566 if (tree_fits_uhwi_p (x))
568 absval = tree_to_uhwi (x);
569 res = plus;
571 else
572 return -1;
574 else
576 if (tree_fits_shwi_p (x))
578 HOST_WIDE_INT i = tree_to_shwi (x);
579 if (i < 0)
581 absval = -i;
582 res = 1;
584 else
586 absval = i;
587 res = plus;
590 else
591 return -1;
594 res += ilog (absval, base);
596 if (prefix && absval)
598 if (base == 8)
599 res += 1;
600 else if (base == 16)
601 res += 2;
604 return res;
607 /* Given the formatting result described by RES and NAVAIL, the number
608 of available in the destination, return the number of bytes remaining
609 in the destination. */
611 static inline result_range
612 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
614 result_range range;
616 if (HOST_WIDE_INT_MAX <= navail)
618 range.min = range.max = navail;
619 return range;
622 if (res.number_chars < navail)
624 range.min = range.max = navail - res.number_chars;
626 else if (res.number_chars_min < navail)
628 range.max = navail - res.number_chars_min;
630 else
631 range.max = 0;
633 if (res.number_chars_max < navail)
634 range.min = navail - res.number_chars_max;
635 else
636 range.min = 0;
638 return range;
641 /* Given the formatting result described by RES and NAVAIL, the number
642 of available in the destination, return the minimum number of bytes
643 remaining in the destination. */
645 static inline unsigned HOST_WIDE_INT
646 min_bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
648 if (HOST_WIDE_INT_MAX <= navail)
649 return navail;
651 if (1 < warn_format_length || res.knownrange)
653 /* At level 2, or when all directives output an exact number
654 of bytes or when their arguments were bounded by known
655 ranges, use the greater of the two byte counters if it's
656 valid to compute the result. */
657 if (res.number_chars_max < HOST_WIDE_INT_MAX)
658 navail -= res.number_chars_max;
659 else if (res.number_chars < HOST_WIDE_INT_MAX)
660 navail -= res.number_chars;
661 else if (res.number_chars_min < HOST_WIDE_INT_MAX)
662 navail -= res.number_chars_min;
664 else
666 /* At level 1 use the smaller of the byte counters to compute
667 the result. */
668 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;
672 else if (res.number_chars_max < HOST_WIDE_INT_MAX)
673 navail -= res.number_chars_max;
676 if (navail > HOST_WIDE_INT_MAX)
677 navail = 0;
679 return navail;
682 /* Description of a call to a formatted function. */
684 struct pass_sprintf_length::call_info
686 /* Function call statement. */
687 gimple *callstmt;
689 /* Function called. */
690 tree func;
692 /* Called built-in function code. */
693 built_in_function fncode;
695 /* Format argument and format string extracted from it. */
696 tree format;
697 const char *fmtstr;
699 /* The location of the format argument. */
700 location_t fmtloc;
702 /* The destination object size for __builtin___xxx_chk functions
703 typically determined by __builtin_object_size, or -1 if unknown. */
704 unsigned HOST_WIDE_INT objsize;
706 /* Number of the first variable argument. */
707 unsigned HOST_WIDE_INT argidx;
709 /* True for functions like snprintf that specify the size of
710 the destination, false for others like sprintf that don't. */
711 bool bounded;
713 /* True for bounded functions like snprintf that specify a zero-size
714 buffer as a request to compute the size of output without actually
715 writing any. NOWRITE is cleared in response to the %n directive
716 which has side-effects similar to writing output. */
717 bool nowrite;
720 /* Return the result of formatting the '%%' directive. */
722 static fmtresult
723 format_percent (const conversion_spec &, tree)
725 fmtresult res;
726 res.argmin = res.argmax = NULL_TREE;
727 res.range.min = res.range.max = 1;
728 res.bounded = res.constant = true;
729 return res;
733 /* Compute intmax_type_node and uintmax_type_node similarly to how
734 tree.c builds size_type_node. */
736 static void
737 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
739 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
741 *pintmax = integer_type_node;
742 *puintmax = unsigned_type_node;
744 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
746 *pintmax = long_integer_type_node;
747 *puintmax = long_unsigned_type_node;
749 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
751 *pintmax = long_long_integer_type_node;
752 *puintmax = long_long_unsigned_type_node;
754 else
756 for (int i = 0; i < NUM_INT_N_ENTS; i++)
757 if (int_n_enabled_p[i])
759 char name[50];
760 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
762 if (strcmp (name, UINTMAX_TYPE) == 0)
764 *pintmax = int_n_trees[i].signed_type;
765 *puintmax = int_n_trees[i].unsigned_type;
766 return;
769 gcc_unreachable ();
773 /* Set *PWIDTH and *PPREC according to the width and precision specified
774 in SPEC. Each is set to HOST_WIDE_INT_MIN when the corresponding
775 field is specified but unknown, to zero for width and -1 for precision,
776 respectively when it's not specified, or to a non-negative value
777 corresponding to the known value. */
779 static void
780 get_width_and_precision (const conversion_spec &spec,
781 HOST_WIDE_INT *pwidth, HOST_WIDE_INT *pprec)
783 HOST_WIDE_INT width = spec.have_width ? spec.width : 0;
784 HOST_WIDE_INT prec = spec.have_precision ? spec.precision : -1;
786 if (spec.star_width)
788 if (TREE_CODE (spec.star_width) == INTEGER_CST)
790 width = tree_to_shwi (spec.star_width);
791 if (width < 0)
793 if (width == HOST_WIDE_INT_MIN)
795 /* Avoid undefined behavior due to negating a minimum.
796 This case will be diagnosed since it will result in
797 more than INT_MAX bytes on output, either by the
798 directive itself (when INT_MAX < HOST_WIDE_INT_MAX)
799 or by the format function itself. */
800 width = HOST_WIDE_INT_MAX;
802 else
803 width = -width;
806 else
807 width = HOST_WIDE_INT_MIN;
810 if (spec.star_precision)
812 if (TREE_CODE (spec.star_precision) == INTEGER_CST)
814 prec = tree_to_shwi (spec.star_precision);
815 if (prec < 0)
816 prec = -1;
818 else
819 prec = HOST_WIDE_INT_MIN;
822 *pwidth = width;
823 *pprec = prec;
826 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
827 argument, due to the conversion from either *ARGMIN or *ARGMAX to
828 the type of the directive's formal argument it's possible for both
829 to result in the same number of bytes or a range of bytes that's
830 less than the number of bytes that would result from formatting
831 some other value in the range [*ARGMIN, *ARGMAX]. This can be
832 determined by checking for the actual argument being in the range
833 of the type of the directive. If it isn't it must be assumed to
834 take on the full range of the directive's type.
835 Return true when the range has been adjusted to the full unsigned
836 range of DIRTYPE, or [0, DIRTYPE_MAX], and false otherwise. */
838 static bool
839 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
841 tree argtype = TREE_TYPE (*argmin);
842 unsigned argprec = TYPE_PRECISION (argtype);
843 unsigned dirprec = TYPE_PRECISION (dirtype);
845 /* If the actual argument and the directive's argument have the same
846 precision and sign there can be no overflow and so there is nothing
847 to adjust. */
848 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
849 return false;
851 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
852 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
854 if (TREE_CODE (*argmin) == INTEGER_CST
855 && TREE_CODE (*argmax) == INTEGER_CST
856 && (dirprec >= argprec
857 || integer_zerop (int_const_binop (RSHIFT_EXPR,
858 int_const_binop (MINUS_EXPR,
859 *argmax,
860 *argmin),
861 size_int (dirprec)))))
863 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
864 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
866 /* If *ARGMIN is still less than *ARGMAX the conversion above
867 is safe. Otherwise, it has overflowed and would be unsafe. */
868 if (tree_int_cst_le (*argmin, *argmax))
869 return false;
872 tree dirmin = TYPE_MIN_VALUE (dirtype);
873 tree dirmax = TYPE_MAX_VALUE (dirtype);
875 if (TYPE_UNSIGNED (dirtype))
877 *argmin = dirmin;
878 *argmax = dirmax;
880 else
882 *argmin = integer_zero_node;
883 *argmax = dirmin;
886 return true;
889 /* Return a range representing the minimum and maximum number of bytes
890 that the conversion specification SPEC will write on output for the
891 integer argument ARG when non-null. ARG may be null (for vararg
892 functions). */
894 static fmtresult
895 format_integer (const conversion_spec &spec, tree arg)
897 tree intmax_type_node;
898 tree uintmax_type_node;
900 /* Set WIDTH and PRECISION based on the specification. */
901 HOST_WIDE_INT width;
902 HOST_WIDE_INT prec;
903 get_width_and_precision (spec, &width, &prec);
905 bool sign = spec.specifier == 'd' || spec.specifier == 'i';
907 /* The type of the "formal" argument expected by the directive. */
908 tree dirtype = NULL_TREE;
910 /* Determine the expected type of the argument from the length
911 modifier. */
912 switch (spec.modifier)
914 case FMT_LEN_none:
915 if (spec.specifier == 'p')
916 dirtype = ptr_type_node;
917 else
918 dirtype = sign ? integer_type_node : unsigned_type_node;
919 break;
921 case FMT_LEN_h:
922 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
923 break;
925 case FMT_LEN_hh:
926 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
927 break;
929 case FMT_LEN_l:
930 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
931 break;
933 case FMT_LEN_L:
934 case FMT_LEN_ll:
935 dirtype = (sign
936 ? long_long_integer_type_node
937 : long_long_unsigned_type_node);
938 break;
940 case FMT_LEN_z:
941 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
942 break;
944 case FMT_LEN_t:
945 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
946 break;
948 case FMT_LEN_j:
949 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
950 dirtype = sign ? intmax_type_node : uintmax_type_node;
951 break;
953 default:
954 return fmtresult ();
957 /* The type of the argument to the directive, either deduced from
958 the actual non-constant argument if one is known, or from
959 the directive itself when none has been provided because it's
960 a va_list. */
961 tree argtype = NULL_TREE;
963 if (!arg)
965 /* When the argument has not been provided, use the type of
966 the directive's argument as an approximation. This will
967 result in false positives for directives like %i with
968 arguments with smaller precision (such as short or char). */
969 argtype = dirtype;
971 else if (TREE_CODE (arg) == INTEGER_CST)
973 /* When a constant argument has been provided use its value
974 rather than type to determine the length of the output. */
976 /* Base to format the number in. */
977 int base;
979 /* True when a signed conversion is preceded by a sign or space. */
980 bool maybesign = false;
982 switch (spec.specifier)
984 case 'd':
985 case 'i':
986 /* Space and '+' are only meaningful for signed conversions. */
987 maybesign = spec.get_flag (' ') | spec.get_flag ('+');
988 base = 10;
989 break;
990 case 'u':
991 base = 10;
992 break;
993 case 'o':
994 base = 8;
995 break;
996 case 'X':
997 case 'x':
998 base = 16;
999 break;
1000 default:
1001 gcc_unreachable ();
1004 HOST_WIDE_INT len;
1006 if ((prec == HOST_WIDE_INT_MIN || prec == 0) && integer_zerop (arg))
1008 /* As a special case, a precision of zero with a zero argument
1009 results in zero bytes except in base 8 when the '#' flag is
1010 specified, and for signed conversions in base 8 and 10 when
1011 flags when either the space or '+' flag has been specified
1012 when it results in just one byte (with width having the normal
1013 effect). This must extend to the case of a specified precision
1014 with an unknown value because it can be zero. */
1015 len = ((base == 8 && spec.get_flag ('#')) || maybesign);
1017 else
1019 /* Convert the argument to the type of the directive. */
1020 arg = fold_convert (dirtype, arg);
1022 /* True when a conversion is preceded by a prefix indicating the base
1023 of the argument (octal or hexadecimal). */
1024 bool maybebase = spec.get_flag ('#');
1025 len = tree_digits (arg, base, maybesign, maybebase);
1027 if (len < prec)
1028 len = prec;
1031 if (len < width)
1032 len = width;
1034 /* The minimum and maximum number of bytes produced by the directive. */
1035 fmtresult res;
1037 res.range.min = len;
1039 /* The upper bound of the number of bytes is unlimited when either
1040 width or precision is specified but its value is unknown, and
1041 the same as the lower bound otherwise. */
1042 if (width == HOST_WIDE_INT_MIN || prec == HOST_WIDE_INT_MIN)
1044 res.range.max = HOST_WIDE_INT_MAX;
1046 else
1048 res.range.max = len;
1049 res.bounded = true;
1050 res.constant = true;
1051 res.knownrange = true;
1052 res.bounded = true;
1055 return res;
1057 else if (TREE_CODE (TREE_TYPE (arg)) == INTEGER_TYPE
1058 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1059 /* Determine the type of the provided non-constant argument. */
1060 argtype = TREE_TYPE (arg);
1061 else
1062 /* Don't bother with invalid arguments since they likely would
1063 have already been diagnosed, and disable any further checking
1064 of the format string by returning [-1, -1]. */
1065 return fmtresult ();
1067 fmtresult res;
1069 /* The result is bounded unless width or precision has been specified
1070 whose value is unknown. */
1071 res.bounded = width != HOST_WIDE_INT_MIN && prec != HOST_WIDE_INT_MIN;
1073 /* Using either the range the non-constant argument is in, or its
1074 type (either "formal" or actual), create a range of values that
1075 constrain the length of output given the warning level. */
1076 tree argmin = NULL_TREE;
1077 tree argmax = NULL_TREE;
1079 if (arg
1080 && TREE_CODE (arg) == SSA_NAME
1081 && TREE_CODE (argtype) == INTEGER_TYPE)
1083 /* Try to determine the range of values of the integer argument
1084 (range information is not available for pointers). */
1085 wide_int min, max;
1086 enum value_range_type range_type = get_range_info (arg, &min, &max);
1087 if (range_type == VR_RANGE)
1089 argmin = build_int_cst (argtype, wi::fits_uhwi_p (min)
1090 ? min.to_uhwi () : min.to_shwi ());
1091 argmax = build_int_cst (argtype, wi::fits_uhwi_p (max)
1092 ? max.to_uhwi () : max.to_shwi ());
1094 /* Set KNOWNRANGE if the argument is in a known subrange
1095 of the directive's type (KNOWNRANGE may be reset below). */
1096 res.knownrange
1097 = (!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1098 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax));
1100 res.argmin = argmin;
1101 res.argmax = argmax;
1103 else if (range_type == VR_ANTI_RANGE)
1105 /* Handle anti-ranges if/when bug 71690 is resolved. */
1107 else if (range_type == VR_VARYING)
1109 /* The argument here may be the result of promoting the actual
1110 argument to int. Try to determine the type of the actual
1111 argument before promotion and narrow down its range that
1112 way. */
1113 gimple *def = SSA_NAME_DEF_STMT (arg);
1114 if (is_gimple_assign (def))
1116 tree_code code = gimple_assign_rhs_code (def);
1117 if (code == INTEGER_CST)
1119 arg = gimple_assign_rhs1 (def);
1120 return format_integer (spec, arg);
1123 if (code == NOP_EXPR)
1125 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1126 if (TREE_CODE (type) == INTEGER_TYPE
1127 || TREE_CODE (type) == POINTER_TYPE)
1128 argtype = type;
1134 if (!argmin)
1136 /* For an unknown argument (e.g., one passed to a vararg function)
1137 or one whose value range cannot be determined, create a T_MIN
1138 constant if the argument's type is signed and T_MAX otherwise,
1139 and use those to compute the range of bytes that the directive
1140 can output. When precision is specified but unknown, use zero
1141 as the minimum since it results in no bytes on output (unless
1142 width is specified to be greater than 0). */
1143 argmin = build_int_cst (argtype, prec && prec != HOST_WIDE_INT_MIN);
1145 int typeprec = TYPE_PRECISION (dirtype);
1146 int argprec = TYPE_PRECISION (argtype);
1148 if (argprec < typeprec)
1150 if (POINTER_TYPE_P (argtype))
1151 argmax = build_all_ones_cst (argtype);
1152 else if (TYPE_UNSIGNED (argtype))
1153 argmax = TYPE_MAX_VALUE (argtype);
1154 else
1155 argmax = TYPE_MIN_VALUE (argtype);
1157 else
1159 if (POINTER_TYPE_P (dirtype))
1160 argmax = build_all_ones_cst (dirtype);
1161 else if (TYPE_UNSIGNED (dirtype))
1162 argmax = TYPE_MAX_VALUE (dirtype);
1163 else
1164 argmax = TYPE_MIN_VALUE (dirtype);
1167 res.argmin = argmin;
1168 res.argmax = argmax;
1171 if (tree_int_cst_lt (argmax, argmin))
1173 tree tmp = argmax;
1174 argmax = argmin;
1175 argmin = tmp;
1178 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1179 of the directive. If it has been cleared then since ARGMIN and/or
1180 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1181 ARGMAX in the result to include in diagnostics. */
1182 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1184 res.knownrange = false;
1185 res.argmin = argmin;
1186 res.argmax = argmax;
1189 /* Recursively compute the minimum and maximum from the known range,
1190 taking care to swap them if the lower bound results in longer
1191 output than the upper bound (e.g., in the range [-1, 0]. */
1193 if (TYPE_UNSIGNED (dirtype))
1195 /* For unsigned conversions/directives, use the minimum (i.e., 0
1196 or 1) and maximum to compute the shortest and longest output,
1197 respectively. */
1198 res.range.min = format_integer (spec, argmin).range.min;
1199 res.range.max = format_integer (spec, argmax).range.max;
1201 else
1203 /* For signed conversions/directives, use the maximum (i.e., 0)
1204 to compute the shortest output and the minimum (i.e., TYPE_MIN)
1205 to compute the longest output. This is important when precision
1206 is specified but unknown because otherwise both output lengths
1207 would reflect the largest possible precision (i.e., INT_MAX). */
1208 res.range.min = format_integer (spec, argmax).range.min;
1209 res.range.max = format_integer (spec, argmin).range.max;
1212 /* The result is bounded either when the argument is determined to be
1213 (e.g., when it's within some range) or when the minimum and maximum
1214 are the same. That can happen here for example when the specified
1215 width is as wide as the greater of MIN and MAX, as would be the case
1216 with sprintf (d, "%08x", x) with a 32-bit integer x. */
1217 res.bounded |= res.range.min == res.range.max;
1219 if (res.range.max < res.range.min)
1221 unsigned HOST_WIDE_INT tmp = res.range.max;
1222 res.range.max = res.range.min;
1223 res.range.min = tmp;
1226 return res;
1229 /* Return the number of bytes that a format directive consisting of FLAGS,
1230 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1231 would result for argument X under ideal conditions (i.e., if PREC
1232 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1233 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1234 This function works around those problems. */
1236 static unsigned HOST_WIDE_INT
1237 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1238 char spec, char rndspec)
1240 char fmtstr[40];
1242 HOST_WIDE_INT len = strlen (flags);
1244 fmtstr[0] = '%';
1245 memcpy (fmtstr + 1, flags, len);
1246 memcpy (fmtstr + 1 + len, ".*R", 3);
1247 fmtstr[len + 4] = rndspec;
1248 fmtstr[len + 5] = spec;
1249 fmtstr[len + 6] = '\0';
1251 spec = TOUPPER (spec);
1252 if (spec == 'E' || spec == 'F')
1254 /* For %e, specify the precision explicitly since mpfr_sprintf
1255 does its own thing just to be different (see MPFR bug 21088). */
1256 if (prec < 0)
1257 prec = 6;
1259 else
1261 /* Avoid passing negative precisions with larger magnitude to MPFR
1262 to avoid exposing its bugs. (A negative precision is supposed
1263 to be ignored.) */
1264 if (prec < 0)
1265 prec = -1;
1268 HOST_WIDE_INT p = prec;
1270 if (spec == 'G')
1272 /* For G/g, precision gives the maximum number of significant
1273 digits which is bounded by LDBL_MAX_10_EXP, or, for a 128
1274 bit IEEE extended precision, 4932. Using twice as much
1275 here should be more than sufficient for any real format. */
1276 if ((IEEE_MAX_10_EXP * 2) < prec)
1277 prec = IEEE_MAX_10_EXP * 2;
1278 p = prec;
1280 else
1282 /* Cap precision arbitrarily at 1KB and add the difference
1283 (if any) to the MPFR result. */
1284 if (1024 < prec)
1285 p = 1024;
1288 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1290 /* Handle the unlikely (impossible?) error by returning more than
1291 the maximum dictated by the function's return type. */
1292 if (len < 0)
1293 return target_dir_max () + 1;
1295 /* Adjust the return value by the difference. */
1296 if (p < prec)
1297 len += prec - p;
1299 return len;
1302 /* Return the number of bytes to format using the format specifier
1303 SPEC and the precision PREC the largest value in the real floating
1304 TYPE. */
1306 static unsigned HOST_WIDE_INT
1307 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1309 machine_mode mode = TYPE_MODE (type);
1311 /* IBM Extended mode. */
1312 if (MODE_COMPOSITE_P (mode))
1313 mode = DFmode;
1315 /* Get the real type format desription for the target. */
1316 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1317 REAL_VALUE_TYPE rv;
1320 char buf[256];
1321 get_max_float (rfmt, buf, sizeof buf);
1322 real_from_string (&rv, buf);
1325 /* Convert the GCC real value representation with the precision
1326 of the real type to the mpfr_t format with the GCC default
1327 round-to-nearest mode. */
1328 mpfr_t x;
1329 mpfr_init2 (x, rfmt->p);
1330 mpfr_from_real (x, &rv, GMP_RNDN);
1332 /* Return a value one greater to account for the leading minus sign. */
1333 return 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1336 /* Return a range representing the minimum and maximum number of bytes
1337 that the conversion specification SPEC will output for any argument
1338 given the WIDTH and PRECISION (extracted from SPEC). This function
1339 is used when the directive argument or its value isn't known. */
1341 static fmtresult
1342 format_floating (const conversion_spec &spec, HOST_WIDE_INT width,
1343 HOST_WIDE_INT prec)
1345 tree type;
1347 switch (spec.modifier)
1349 case FMT_LEN_l:
1350 case FMT_LEN_none:
1351 type = double_type_node;
1352 break;
1354 case FMT_LEN_L:
1355 type = long_double_type_node;
1356 break;
1358 case FMT_LEN_ll:
1359 type = long_double_type_node;
1360 break;
1362 default:
1363 return fmtresult ();
1366 /* The minimum and maximum number of bytes produced by the directive. */
1367 fmtresult res;
1369 /* The result is always bounded (though the range may be all of int). */
1370 res.bounded = true;
1372 /* The minimum output as determined by flags. It's always at least 1. */
1373 int flagmin = (1 /* for the first digit */
1374 + (spec.get_flag ('+') | spec.get_flag (' '))
1375 + (prec == 0 && spec.get_flag ('#')));
1377 if (width == INT_MIN || prec == INT_MIN)
1379 /* When either width or precision is specified but unknown
1380 the upper bound is the maximum. Otherwise it will be
1381 computed for each directive below. */
1382 res.range.max = HOST_WIDE_INT_MAX;
1384 else
1385 res.range.max = HOST_WIDE_INT_M1U;
1387 switch (spec.specifier)
1389 case 'A':
1390 case 'a':
1392 res.range.min = flagmin + 5 + (prec > 0 ? prec + 1 : 0);
1393 if (res.range.max == HOST_WIDE_INT_M1U)
1395 /* Compute the upper bound for -TYPE_MAX. */
1396 res.range.max = format_floating_max (type, 'a', prec);
1399 break;
1402 case 'E':
1403 case 'e':
1405 /* The minimum output is "[-+]1.234567e+00" regardless
1406 of the value of the actual argument. */
1407 res.range.min = (flagmin
1408 + (prec == INT_MIN
1409 ? 0 : prec < 0 ? 7 : prec ? prec + 1 : 0)
1410 + 2 /* e+ */ + 2);
1412 if (res.range.max == HOST_WIDE_INT_M1U)
1414 /* MPFR uses a precision of 16 by default for some reason.
1415 Set it to the C default of 6. */
1416 res.range.max = format_floating_max (type, 'e',
1417 -1 == prec ? 6 : prec);
1419 break;
1422 case 'F':
1423 case 'f':
1425 /* The lower bound when precision isn't specified is 8 bytes
1426 ("1.23456" since precision is taken to be 6). When precision
1427 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1428 when precision is greater than zero, then the lower bound
1429 is 2 plus precision (plus flags). */
1430 res.range.min = (flagmin
1431 + (prec != INT_MIN) /* for decimal point */
1432 + (prec == INT_MIN
1433 ? 0 : prec < 0 ? 6 : prec ? prec : -1));
1435 if (res.range.max == HOST_WIDE_INT_M1U)
1437 /* Compute the upper bound for -TYPE_MAX. */
1438 res.range.max = format_floating_max (type, 'f', prec);
1440 break;
1443 case 'G':
1444 case 'g':
1446 /* The %g output depends on precision and the exponent of
1447 the argument. Since the value of the argument isn't known
1448 the lower bound on the range of bytes (not counting flags
1449 or width) is 1. */
1450 res.range.min = flagmin;
1451 if (res.range.max == HOST_WIDE_INT_M1U)
1453 /* Compute the upper bound for -TYPE_MAX which should be
1454 the lesser of %e and %f. */
1455 res.range.max = format_floating_max (type, 'g', prec);
1457 break;
1460 default:
1461 return fmtresult ();
1464 if (width > 0)
1466 /* If width has been specified use it to adjust the range. */
1467 if (res.range.min < (unsigned)width)
1468 res.range.min = width;
1469 if (res.range.max < (unsigned)width)
1470 res.range.max = width;
1473 return res;
1476 /* Return a range representing the minimum and maximum number of bytes
1477 that the conversion specification SPEC will write on output for the
1478 floating argument ARG. */
1480 static fmtresult
1481 format_floating (const conversion_spec &spec, tree arg)
1483 /* Set WIDTH to -1 when it's not specified, to HOST_WIDE_INT_MIN when
1484 it is specified by the asterisk to an unknown value, and otherwise
1485 to a non-negative value corresponding to the specified width. */
1486 HOST_WIDE_INT width = -1;
1487 HOST_WIDE_INT prec = -1;
1489 /* The minimum and maximum number of bytes produced by the directive. */
1490 fmtresult res;
1491 res.constant = arg && TREE_CODE (arg) == REAL_CST;
1493 if (spec.have_width)
1494 width = spec.width;
1495 else if (spec.star_width)
1497 if (TREE_CODE (spec.star_width) == INTEGER_CST)
1499 width = tree_to_shwi (spec.star_width);
1500 if (width < 0)
1501 width = -width;
1503 else
1504 width = INT_MIN;
1507 if (spec.have_precision)
1508 prec = spec.precision;
1509 else if (spec.star_precision)
1511 if (TREE_CODE (spec.star_precision) == INTEGER_CST)
1513 prec = tree_to_shwi (spec.star_precision);
1514 if (prec < 0)
1515 prec = -1;
1517 else
1518 prec = INT_MIN;
1520 else if (res.constant && TOUPPER (spec.specifier) != 'A')
1522 /* Specify the precision explicitly since mpfr_sprintf defaults
1523 to zero. */
1524 prec = 6;
1527 if (res.constant)
1529 /* Get the real type format desription for the target. */
1530 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1531 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1533 /* Convert the GCC real value representation with the precision
1534 of the real type to the mpfr_t format with the GCC default
1535 round-to-nearest mode. */
1536 mpfr_t mpfrval;
1537 mpfr_init2 (mpfrval, rfmt->p);
1538 mpfr_from_real (mpfrval, rvp, GMP_RNDN);
1540 char fmtstr [40];
1541 char *pfmt = fmtstr;
1543 /* Append flags. */
1544 for (const char *pf = "-+ #0"; *pf; ++pf)
1545 if (spec.get_flag (*pf))
1546 *pfmt++ = *pf;
1548 *pfmt = '\0';
1551 /* Set up an array to easily iterate over below. */
1552 unsigned HOST_WIDE_INT* const minmax[] = {
1553 &res.range.min, &res.range.max
1556 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1558 /* Use the MPFR rounding specifier to round down in the first
1559 iteration and then up. In most but not all cases this will
1560 result in the same number of bytes. */
1561 char rndspec = "DU"[i];
1563 /* Format it and store the result in the corresponding member
1564 of the result struct. */
1565 unsigned HOST_WIDE_INT len
1566 = get_mpfr_format_length (mpfrval, fmtstr, prec,
1567 spec.specifier, rndspec);
1568 if (0 < width && len < (unsigned)width)
1569 len = width;
1571 *minmax[i] = len;
1575 /* Make sure the minimum is less than the maximum (MPFR rounding
1576 in the call to mpfr_snprintf can result in the reverse. */
1577 if (res.range.max < res.range.min)
1579 unsigned HOST_WIDE_INT tmp = res.range.min;
1580 res.range.min = res.range.max;
1581 res.range.max = tmp;
1584 /* The range of output is known even if the result isn't bounded. */
1585 if (width == HOST_WIDE_INT_MIN)
1587 res.knownrange = false;
1588 res.range.max = HOST_WIDE_INT_MAX;
1590 else
1591 res.knownrange = true;
1593 /* The output of all directives except "%a" is fully specified
1594 and so the result is bounded unless it exceeds INT_MAX.
1595 For "%a" the output is fully specified only when precision
1596 is explicitly specified. */
1597 res.bounded = (res.knownrange
1598 && (TOUPPER (spec.specifier) != 'A'
1599 || (0 <= prec && (unsigned) prec < target_int_max ()))
1600 && res.range.min < target_int_max ());
1602 return res;
1605 return format_floating (spec, width, prec);
1608 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1609 strings referenced by the expression STR, or (-1, -1) when not known.
1610 Used by the format_string function below. */
1612 static fmtresult
1613 get_string_length (tree str)
1615 if (!str)
1616 return fmtresult ();
1618 if (tree slen = c_strlen (str, 1))
1620 /* Simply return the length of the string. */
1621 fmtresult res;
1622 res.range.min = res.range.max = tree_to_shwi (slen);
1623 res.bounded = true;
1624 res.constant = true;
1625 res.knownrange = true;
1626 return res;
1629 /* Determine the length of the shortest and longest string referenced
1630 by STR. Strings of unknown lengths are bounded by the sizes of
1631 arrays that subexpressions of STR may refer to. Pointers that
1632 aren't known to point any such arrays result in LENRANGE[1] set
1633 to SIZE_MAX. */
1634 tree lenrange[2];
1635 get_range_strlen (str, lenrange);
1637 if (lenrange [0] || lenrange [1])
1639 fmtresult res;
1641 res.range.min = (tree_fits_uhwi_p (lenrange[0])
1642 ? tree_to_uhwi (lenrange[0]) : 1 < warn_format_length);
1643 res.range.max = (tree_fits_uhwi_p (lenrange[1])
1644 ? tree_to_uhwi (lenrange[1]) : HOST_WIDE_INT_M1U);
1646 /* Set RES.BOUNDED to true if and only if all strings referenced
1647 by STR are known to be bounded (though not necessarily by their
1648 actual length but perhaps by their maximum possible length). */
1649 res.bounded = res.range.max < target_int_max ();
1650 res.knownrange = res.bounded;
1652 /* Set RES.CONSTANT to false even though that may be overly
1653 conservative in rare cases like: 'x ? a : b' where a and
1654 b have the same lengths and consist of the same characters. */
1655 res.constant = false;
1657 return res;
1660 return get_string_length (NULL_TREE);
1663 /* Return the minimum and maximum number of characters formatted
1664 by the '%c' and '%s' format directives and ther wide character
1665 forms for the argument ARG. ARG can be null (for functions
1666 such as vsprinf). */
1668 static fmtresult
1669 format_string (const conversion_spec &spec, tree arg)
1671 /* Set WIDTH and PRECISION based on the specification. */
1672 HOST_WIDE_INT width;
1673 HOST_WIDE_INT prec;
1674 get_width_and_precision (spec, &width, &prec);
1676 fmtresult res;
1678 /* The maximum number of bytes for an unknown wide character argument
1679 to a "%lc" directive adjusted for precision but not field width.
1680 6 is the longest UTF-8 sequence for a single wide character. */
1681 const unsigned HOST_WIDE_INT max_bytes_for_unknown_wc
1682 = (0 <= prec ? prec : 1 < warn_format_length ? 6 : 1);
1684 /* The maximum number of bytes for an unknown string argument to either
1685 a "%s" or "%ls" directive adjusted for precision but not field width. */
1686 const unsigned HOST_WIDE_INT max_bytes_for_unknown_str
1687 = (0 <= prec ? prec : 1 < warn_format_length);
1689 /* The result is bounded unless overriddden for a non-constant string
1690 of an unknown length. */
1691 bool bounded = true;
1693 if (spec.specifier == 'c')
1695 if (spec.modifier == FMT_LEN_l)
1697 /* Positive if the argument is a wide NUL character? */
1698 int nul = (arg && TREE_CODE (arg) == INTEGER_CST
1699 ? integer_zerop (arg) : -1);
1701 /* A '%lc' directive is the same as '%ls' for a two element
1702 wide string character with the second element of NUL, so
1703 when the character is unknown the minimum number of bytes
1704 is the smaller of either 0 (at level 1) or 1 (at level 2)
1705 and WIDTH, and the maximum is MB_CUR_MAX in the selected
1706 locale, which is unfortunately, unknown. */
1707 res.range.min = 1 == warn_format_length ? !nul : nul < 1;
1708 res.range.max = max_bytes_for_unknown_wc;
1709 /* The range above is good enough to issue warnings but not
1710 for value range propagation, so clear BOUNDED. */
1711 res.bounded = false;
1713 else
1715 /* A plain '%c' directive. Its ouput is exactly 1. */
1716 res.range.min = res.range.max = 1;
1717 res.bounded = true;
1718 res.knownrange = true;
1719 res.constant = arg && TREE_CODE (arg) == INTEGER_CST;
1722 else /* spec.specifier == 's' */
1724 /* Compute the range the argument's length can be in. */
1725 fmtresult slen = get_string_length (arg);
1726 if (slen.constant)
1728 gcc_checking_assert (slen.range.min == slen.range.max);
1730 /* A '%s' directive with a string argument with constant length. */
1731 res.range = slen.range;
1733 /* The output of "%s" and "%ls" directives with a constant
1734 string is in a known range unless width of an unknown value
1735 is specified. For "%s" it is the length of the string. For
1736 "%ls" it is in the range [length, length * MB_LEN_MAX].
1737 (The final range can be further constrained by width and
1738 precision but it's always known.) */
1739 res.knownrange = -1 < width;
1741 if (spec.modifier == FMT_LEN_l)
1743 bounded = false;
1745 if (warn_format_length > 1)
1747 /* Leave the minimum number of bytes the wide string
1748 converts to equal to its length and set the maximum
1749 to the worst case length which is the string length
1750 multiplied by MB_LEN_MAX. */
1752 /* It's possible to be smarter about computing the maximum
1753 by scanning the wide string for any 8-bit characters and
1754 if it contains none, using its length for the maximum.
1755 Even though this would be simple to do it's unlikely to
1756 be worth it when dealing with wide characters. */
1757 res.range.max *= target_mb_len_max;
1760 /* For a wide character string, use precision as the maximum
1761 even if precision is greater than the string length since
1762 the number of bytes the string converts to may be greater
1763 (due to MB_CUR_MAX). */
1764 if (0 <= prec)
1765 res.range.max = prec;
1767 else if (0 <= width)
1769 /* The output of a "%s" directive with a constant argument
1770 and constant or no width is bounded. It is constant if
1771 precision is either not specified or it is specified and
1772 its value is known. */
1773 res.bounded = true;
1774 res.constant = prec != HOST_WIDE_INT_MIN;
1776 else if (width == HOST_WIDE_INT_MIN)
1778 /* Specified but unknown width makes the output unbounded. */
1779 res.range.max = HOST_WIDE_INT_MAX;
1782 if (0 <= prec && (unsigned HOST_WIDE_INT)prec < res.range.min)
1784 res.range.min = prec;
1785 res.range.max = prec;
1787 else if (prec == HOST_WIDE_INT_MIN)
1789 /* When precision is specified but not known the lower
1790 bound is assumed to be as low as zero. */
1791 res.range.min = 0;
1794 else if (arg && integer_zerop (arg))
1796 /* Handle null pointer argument. */
1798 fmtresult res;
1799 res.range.min = 0;
1800 res.range.max = HOST_WIDE_INT_MAX;
1801 res.nullp = true;
1802 return res;
1804 else
1806 /* For a '%s' and '%ls' directive with a non-constant string,
1807 the minimum number of characters is the greater of WIDTH
1808 and either 0 in mode 1 or the smaller of PRECISION and 1
1809 in mode 2, and the maximum is PRECISION or -1 to disable
1810 tracking. */
1812 if (0 <= prec)
1814 if (slen.range.min >= target_int_max ())
1815 slen.range.min = 0;
1816 else if ((unsigned HOST_WIDE_INT)prec < slen.range.min)
1817 slen.range.min = prec;
1819 if ((unsigned HOST_WIDE_INT)prec < slen.range.max
1820 || slen.range.max >= target_int_max ())
1821 slen.range.max = prec;
1823 else if (slen.range.min >= target_int_max ())
1825 slen.range.min = max_bytes_for_unknown_str;
1826 slen.range.max = max_bytes_for_unknown_str;
1827 bounded = false;
1830 res.range = slen.range;
1832 /* The output is considered bounded when a precision has been
1833 specified to limit the number of bytes or when the number
1834 of bytes is known or contrained to some range. */
1835 res.bounded = 0 <= prec || slen.bounded;
1836 res.knownrange = slen.knownrange;
1837 res.constant = false;
1841 /* Adjust the lengths for field width. */
1842 if (0 < width)
1844 if (res.range.min < (unsigned HOST_WIDE_INT)width)
1845 res.range.min = width;
1847 if (res.range.max < (unsigned HOST_WIDE_INT)width)
1848 res.range.max = width;
1850 /* Adjust BOUNDED if width happens to make them equal. */
1851 if (res.range.min == res.range.max && res.range.min < target_int_max ()
1852 && bounded)
1853 res.bounded = true;
1856 /* When precision is specified the range of characters on output
1857 is known to be bounded by it. */
1858 if (-1 < width && -1 < prec)
1859 res.knownrange = true;
1861 return res;
1864 /* Compute the length of the output resulting from the conversion
1865 specification SPEC with the argument ARG in a call described by INFO
1866 and update the overall result of the call in *RES. The format directive
1867 corresponding to SPEC starts at CVTBEG and is CVTLEN characters long. */
1869 static void
1870 format_directive (const pass_sprintf_length::call_info &info,
1871 format_result *res, const char *cvtbeg, size_t cvtlen,
1872 const conversion_spec &spec, tree arg)
1874 /* Offset of the beginning of the directive from the beginning
1875 of the format string. */
1876 size_t offset = cvtbeg - info.fmtstr;
1878 /* Create a location for the whole directive from the % to the format
1879 specifier. */
1880 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
1881 offset, offset, offset + cvtlen - 1);
1883 /* Also create a location range for the argument if possible.
1884 This doesn't work for integer literals or function calls. */
1885 source_range argrange;
1886 source_range *pargrange;
1887 if (arg && CAN_HAVE_LOCATION_P (arg))
1889 argrange = EXPR_LOCATION_RANGE (arg);
1890 pargrange = &argrange;
1892 else
1893 pargrange = NULL;
1895 /* Bail when there is no function to compute the output length,
1896 or when minimum length checking has been disabled. */
1897 if (!spec.fmtfunc || res->number_chars_min >= HOST_WIDE_INT_MAX)
1898 return;
1900 /* Compute the (approximate) length of the formatted output. */
1901 fmtresult fmtres = spec.fmtfunc (spec, arg);
1903 /* The overall result is bounded and constant only if the output
1904 of every directive is bounded and constant, respectively. */
1905 res->bounded &= fmtres.bounded;
1906 res->constant &= fmtres.constant;
1908 /* Record whether the output of all directives is known to be
1909 bounded by some maximum, implying that their arguments are
1910 either known exactly or determined to be in a known range
1911 or, for strings, limited by the upper bounds of the arrays
1912 they refer to. */
1913 res->knownrange &= fmtres.knownrange;
1915 if (!fmtres.knownrange)
1917 /* Only when the range is known, check it against the host value
1918 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
1919 INT_MAX precision, which is the longest possible output of any
1920 single directive). That's the largest valid byte count (though
1921 not valid call to a printf-like function because it can never
1922 return such a count). Otherwise, the range doesn't correspond
1923 to known values of the argument. */
1924 if (fmtres.range.max > target_dir_max ())
1926 /* Normalize the MAX counter to avoid having to deal with it
1927 later. The counter can be less than HOST_WIDE_INT_M1U
1928 when compiling for an ILP32 target on an LP64 host. */
1929 fmtres.range.max = HOST_WIDE_INT_M1U;
1930 /* Disable exact and maximum length checking after a failure
1931 to determine the maximum number of characters (for example
1932 for wide characters or wide character strings) but continue
1933 tracking the minimum number of characters. */
1934 res->number_chars_max = HOST_WIDE_INT_M1U;
1935 res->number_chars = HOST_WIDE_INT_M1U;
1938 if (fmtres.range.min > target_dir_max ())
1940 /* Disable exact length checking after a failure to determine
1941 even the minimum number of characters (it shouldn't happen
1942 except in an error) but keep tracking the minimum and maximum
1943 number of characters. */
1944 res->number_chars = HOST_WIDE_INT_M1U;
1945 return;
1949 if (fmtres.nullp)
1951 fmtwarn (dirloc, pargrange, NULL,
1952 OPT_Wformat_length_,
1953 "%<%.*s%> directive argument is null",
1954 (int)cvtlen, cvtbeg);
1956 /* Don't bother processing the rest of the format string. */
1957 res->warned = true;
1958 res->number_chars = HOST_WIDE_INT_M1U;
1959 res->number_chars_min = res->number_chars_max = res->number_chars;
1960 return;
1963 bool warned = res->warned;
1965 /* Compute the number of available bytes in the destination. There
1966 must always be at least one byte of space for the terminating
1967 NUL that's appended after the format string has been processed. */
1968 unsigned HOST_WIDE_INT navail = min_bytes_remaining (info.objsize, *res);
1970 if (fmtres.range.min < fmtres.range.max)
1972 /* The result is a range (i.e., it's inexact). */
1973 if (!warned)
1975 if (navail < fmtres.range.min)
1977 /* The minimum directive output is longer than there is
1978 room in the destination. */
1979 if (fmtres.range.min == fmtres.range.max)
1981 const char* fmtstr
1982 = (info.bounded
1983 ? G_("%<%.*s%> directive output truncated writing "
1984 "%wu bytes into a region of size %wu")
1985 : G_("%<%.*s%> directive writing %wu bytes "
1986 "into a region of size %wu"));
1987 warned = fmtwarn (dirloc, pargrange, NULL,
1988 OPT_Wformat_length_, fmtstr,
1989 (int)cvtlen, cvtbeg, fmtres.range.min,
1990 navail);
1992 else if (fmtres.range.max < HOST_WIDE_INT_MAX)
1994 const char* fmtstr
1995 = (info.bounded
1996 ? G_("%<%.*s%> directive output truncated writing "
1997 "between %wu and %wu bytes into a region of "
1998 "size %wu")
1999 : G_("%<%.*s%> directive writing between %wu and "
2000 "%wu bytes into a region of size %wu"));
2001 warned = fmtwarn (dirloc, pargrange, NULL,
2002 OPT_Wformat_length_, fmtstr,
2003 (int)cvtlen, cvtbeg,
2004 fmtres.range.min, fmtres.range.max, navail);
2006 else
2008 const char* fmtstr
2009 = (info.bounded
2010 ? G_("%<%.*s%> directive output truncated writing "
2011 "%wu or more bytes into a region of size %wu")
2012 : G_("%<%.*s%> directive writing %wu or more bytes "
2013 "into a region of size %wu"));
2014 warned = fmtwarn (dirloc, pargrange, NULL,
2015 OPT_Wformat_length_, fmtstr,
2016 (int)cvtlen, cvtbeg,
2017 fmtres.range.min, navail);
2020 else if (navail < fmtres.range.max
2021 && (((spec.specifier == 's'
2022 && fmtres.range.max < HOST_WIDE_INT_MAX)
2023 /* && (spec.precision || spec.star_precision) */)
2024 || 1 < warn_format_length))
2026 /* The maximum directive output is longer than there is
2027 room in the destination and the output length is either
2028 explicitly constrained by the precision (for strings)
2029 or the warning level is greater than 1. */
2030 if (fmtres.range.max >= HOST_WIDE_INT_MAX)
2032 const char* fmtstr
2033 = (info.bounded
2034 ? G_("%<%.*s%> directive output may be truncated "
2035 "writing %wu or more bytes a region of size %wu")
2036 : G_("%<%.*s%> directive writing %wu or more bytes "
2037 "into a region of size %wu"));
2038 warned = fmtwarn (dirloc, pargrange, NULL,
2039 OPT_Wformat_length_, fmtstr,
2040 (int)cvtlen, cvtbeg,
2041 fmtres.range.min, navail);
2043 else
2045 const char* fmtstr
2046 = (info.bounded
2047 ? G_("%<%.*s%> directive output may be truncated "
2048 "writing between %wu and %wu bytes into a region "
2049 "of size %wu")
2050 : G_("%<%.*s%> directive writing between %wu and %wu "
2051 "bytes into a region of size %wu"));
2052 warned = fmtwarn (dirloc, pargrange, NULL,
2053 OPT_Wformat_length_, fmtstr,
2054 (int)cvtlen, cvtbeg,
2055 fmtres.range.min, fmtres.range.max,
2056 navail);
2061 /* Disable exact length checking but adjust the minimum and maximum. */
2062 res->number_chars = HOST_WIDE_INT_M1U;
2063 if (res->number_chars_max < HOST_WIDE_INT_MAX
2064 && fmtres.range.max < HOST_WIDE_INT_MAX)
2065 res->number_chars_max += fmtres.range.max;
2067 res->number_chars_min += fmtres.range.min;
2069 else
2071 if (!warned && fmtres.range.min > 0 && navail < fmtres.range.min)
2073 const char* fmtstr
2074 = (info.bounded
2075 ? (1 < fmtres.range.min
2076 ? G_("%<%.*s%> directive output truncated while writing "
2077 "%wu bytes into a region of size %wu")
2078 : G_("%<%.*s%> directive output truncated while writing "
2079 "%wu byte into a region of size %wu"))
2080 : (1 < fmtres.range.min
2081 ? G_("%<%.*s%> directive writing %wu bytes "
2082 "into a region of size %wu")
2083 : G_("%<%.*s%> directive writing %wu byte "
2084 "into a region of size %wu")));
2086 warned = fmtwarn (dirloc, pargrange, NULL,
2087 OPT_Wformat_length_, fmtstr,
2088 (int)cvtlen, cvtbeg, fmtres.range.min,
2089 navail);
2091 *res += fmtres.range.min;
2094 /* Has the minimum directive output length exceeded the maximum
2095 of 4095 bytes required to be supported? */
2096 bool minunder4k = fmtres.range.min < 4096;
2097 if (!minunder4k || fmtres.range.max > 4095)
2098 res->under4k = false;
2100 if (!warned && 1 < warn_format_length
2101 && (!minunder4k || fmtres.range.max > 4095))
2103 /* The directive output may be longer than the maximum required
2104 to be handled by an implementation according to 7.21.6.1, p15
2105 of C11. Warn on this only at level 2 but remember this and
2106 prevent folding the return value when done. This allows for
2107 the possibility of the actual libc call failing due to ENOMEM
2108 (like Glibc does under some conditions). */
2110 if (fmtres.range.min == fmtres.range.max)
2111 warned = fmtwarn (dirloc, pargrange, NULL,
2112 OPT_Wformat_length_,
2113 "%<%.*s%> directive output of %wu bytes exceeds "
2114 "minimum required size of 4095",
2115 (int)cvtlen, cvtbeg, fmtres.range.min);
2116 else
2118 const char *fmtstr
2119 = (minunder4k
2120 ? G_("%<%.*s%> directive output between %qu and %wu "
2121 "bytes may exceed minimum required size of 4095")
2122 : G_("%<%.*s%> directive output between %qu and %wu "
2123 "bytes exceeds minimum required size of 4095"));
2125 warned = fmtwarn (dirloc, pargrange, NULL,
2126 OPT_Wformat_length_, fmtstr,
2127 (int)cvtlen, cvtbeg,
2128 fmtres.range.min, fmtres.range.max);
2132 /* Has the minimum directive output length exceeded INT_MAX? */
2133 bool exceedmin = res->number_chars_min > target_int_max ();
2135 if (!warned
2136 && (exceedmin
2137 || (1 < warn_format_length
2138 && res->number_chars_max > target_int_max ())))
2140 /* The directive output causes the total length of output
2141 to exceed INT_MAX bytes. */
2143 if (fmtres.range.min == fmtres.range.max)
2144 warned = fmtwarn (dirloc, pargrange, NULL,
2145 OPT_Wformat_length_,
2146 "%<%.*s%> directive output of %wu bytes causes "
2147 "result to exceed %<INT_MAX%>",
2148 (int)cvtlen, cvtbeg, fmtres.range.min);
2149 else
2151 const char *fmtstr
2152 = (exceedmin
2153 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2154 "bytes causes result to exceed %<INT_MAX%>")
2155 : G_ ("%<%.*s%> directive output between %wu and %wu "
2156 "bytes may cause result to exceed %<INT_MAX%>"));
2157 warned = fmtwarn (dirloc, pargrange, NULL,
2158 OPT_Wformat_length_, fmtstr,
2159 (int)cvtlen, cvtbeg,
2160 fmtres.range.min, fmtres.range.max);
2164 if (warned && fmtres.argmin)
2166 if (fmtres.argmin == fmtres.argmax)
2167 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2168 else if (fmtres.knownrange)
2169 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2170 fmtres.argmin, fmtres.argmax);
2171 else
2172 inform (info.fmtloc,
2173 "using the range [%E, %E] for directive argument",
2174 fmtres.argmin, fmtres.argmax);
2177 res->warned |= warned;
2180 /* Account for the number of bytes between BEG and END (or between
2181 BEG + strlen (BEG) when END is null) in the format string in a call
2182 to a formatted output function described by INFO. Reflect the count
2183 in RES and issue warnings as appropriate. */
2185 static void
2186 add_bytes (const pass_sprintf_length::call_info &info,
2187 const char *beg, const char *end, format_result *res)
2189 if (res->number_chars_min >= HOST_WIDE_INT_MAX)
2190 return;
2192 /* The number of bytes to output is the number of bytes between
2193 the end of the last directive and the beginning of the next
2194 one if it exists, otherwise the number of characters remaining
2195 in the format string plus 1 for the terminating NUL. */
2196 size_t nbytes = end ? end - beg : strlen (beg) + 1;
2198 /* Return if there are no bytes to add at this time but there are
2199 directives remaining in the format string. */
2200 if (!nbytes)
2201 return;
2203 /* Compute the range of available bytes in the destination. There
2204 must always be at least one byte left for the terminating NUL
2205 that's appended after the format string has been processed. */
2206 result_range avail_range = bytes_remaining (info.objsize, *res);
2208 /* If issuing a diagnostic (only when one hasn't already been issued),
2209 distinguish between a possible overflow ("may write") and a certain
2210 overflow somewhere "past the end." (Ditto for truncation.)
2211 KNOWNRANGE is used to warn even at level 1 about possibly writing
2212 past the end or truncation due to strings of unknown lengths that
2213 are bounded by the arrays they are known to refer to. */
2214 if (!res->warned
2215 && (avail_range.max < nbytes
2216 || ((res->knownrange || 1 < warn_format_length)
2217 && avail_range.min < nbytes)))
2219 /* Set NAVAIL to the number of available bytes used to decide
2220 whether or not to issue a warning below. The exact kind of
2221 warning will depend on AVAIL_RANGE. */
2222 unsigned HOST_WIDE_INT navail = avail_range.max;
2223 if (nbytes <= navail && avail_range.min < HOST_WIDE_INT_MAX
2224 && (res->knownrange || 1 < warn_format_length))
2225 navail = avail_range.min;
2227 /* Compute the offset of the first format character that is beyond
2228 the end of the destination region and the length of the rest of
2229 the format string from that point on. */
2230 unsigned HOST_WIDE_INT off
2231 = (unsigned HOST_WIDE_INT)(beg - info.fmtstr) + navail;
2233 size_t len = strlen (info.fmtstr + off);
2235 /* Create a location that underscores the substring of the format
2236 string that is or may be written past the end (or is or may be
2237 truncated), pointing the caret at the first character of the
2238 substring. */
2239 substring_loc loc
2240 (info.fmtloc, TREE_TYPE (info.format), off, len ? off : 0,
2241 off + len - !!len);
2243 /* Is the output of the last directive the result of the argument
2244 being within a range whose lower bound would fit in the buffer
2245 but the upper bound would not? If so, use the word "may" to
2246 indicate that the overflow/truncation may (but need not) happen. */
2247 bool boundrange
2248 = (res->number_chars_min < res->number_chars_max
2249 && res->number_chars_min + nbytes <= info.objsize);
2251 if (!end && ((nbytes - navail) == 1 || boundrange))
2253 /* There is room for the rest of the format string but none
2254 for the terminating nul. */
2255 const char *text
2256 = (info.bounded // Snprintf and the like.
2257 ? (boundrange
2258 ? G_("output may be truncated before the last format character"
2259 : "output truncated before the last format character"))
2260 : (boundrange
2261 ? G_("may write a terminating nul past the end "
2262 "of the destination")
2263 : G_("writing a terminating nul past the end "
2264 "of the destination")));
2266 res->warned = fmtwarn (loc, NULL, NULL, OPT_Wformat_length_, text);
2268 else
2270 /* There isn't enough room for 1 or more characters that remain
2271 to copy from the format string. */
2272 const char *text
2273 = (info.bounded // Snprintf and the like.
2274 ? (boundrange
2275 ? G_("output may be truncated at or before format character "
2276 "%qc at offset %wu")
2277 : G_("output truncated at format character %qc at offset %wu"))
2278 : (res->number_chars >= HOST_WIDE_INT_MAX
2279 ? G_("may write format character %#qc at offset %wu past "
2280 "the end of the destination")
2281 : G_("writing format character %#qc at offset %wu past "
2282 "the end of the destination")));
2284 res->warned = fmtwarn (loc, NULL, NULL, OPT_Wformat_length_,
2285 text, info.fmtstr[off], off);
2289 if (res->warned && !end && info.objsize < HOST_WIDE_INT_MAX)
2291 /* If a warning has been issued for buffer overflow or truncation
2292 (but not otherwise) help the user figure out how big a buffer
2293 they need. */
2295 location_t callloc = gimple_location (info.callstmt);
2297 unsigned HOST_WIDE_INT min = res->number_chars_min;
2298 unsigned HOST_WIDE_INT max = res->number_chars_max;
2299 unsigned HOST_WIDE_INT exact
2300 = (res->number_chars < HOST_WIDE_INT_MAX
2301 ? res->number_chars : res->number_chars_min);
2303 if (min < max && max < HOST_WIDE_INT_MAX)
2304 inform (callloc,
2305 "format output between %wu and %wu bytes into "
2306 "a destination of size %wu",
2307 min + nbytes, max + nbytes, info.objsize);
2308 else
2309 inform (callloc,
2310 (nbytes + exact == 1
2311 ? G_("format output %wu byte into a destination of size %wu")
2312 : G_("format output %wu bytes into a destination of size %wu")),
2313 nbytes + exact, info.objsize);
2316 /* Add the number of bytes and then check for INT_MAX overflow. */
2317 *res += nbytes;
2319 /* Has the minimum output length minus the terminating nul exceeded
2320 INT_MAX? */
2321 bool exceedmin = (res->number_chars_min - !end) > target_int_max ();
2323 if (!res->warned
2324 && (exceedmin
2325 || (1 < warn_format_length
2326 && (res->number_chars_max - !end) > target_int_max ())))
2328 /* The function's output exceeds INT_MAX bytes. */
2330 /* Set NAVAIL to the number of available bytes used to decide
2331 whether or not to issue a warning below. The exact kind of
2332 warning will depend on AVAIL_RANGE. */
2333 unsigned HOST_WIDE_INT navail = avail_range.max;
2334 if (nbytes <= navail && avail_range.min < HOST_WIDE_INT_MAX
2335 && (res->bounded || 1 < warn_format_length))
2336 navail = avail_range.min;
2338 /* Compute the offset of the first format character that is beyond
2339 the end of the destination region and the length of the rest of
2340 the format string from that point on. */
2341 unsigned HOST_WIDE_INT off = (unsigned HOST_WIDE_INT)(beg - info.fmtstr);
2342 if (navail < HOST_WIDE_INT_MAX)
2343 off += navail;
2345 size_t len = strlen (info.fmtstr + off);
2347 substring_loc loc
2348 (info.fmtloc, TREE_TYPE (info.format), off - !len, len ? off : 0,
2349 off + len - !!len);
2351 if (res->number_chars_min == res->number_chars_max)
2352 res->warned = fmtwarn (loc, NULL, NULL,
2353 OPT_Wformat_length_,
2354 "output of %wu bytes causes "
2355 "result to exceed %<INT_MAX%>",
2356 res->number_chars_min - !end);
2357 else
2359 const char *text
2360 = (exceedmin
2361 ? G_ ("output between %wu and %wu bytes causes "
2362 "result to exceed %<INT_MAX%>")
2363 : G_ ("output between %wu and %wu bytes may cause "
2364 "result to exceed %<INT_MAX%>"));
2365 res->warned = fmtwarn (loc, NULL, NULL, OPT_Wformat_length_,
2366 text,
2367 res->number_chars_min - !end,
2368 res->number_chars_max - !end);
2373 #pragma GCC diagnostic pop
2375 /* Compute the length of the output resulting from the call to a formatted
2376 output function described by INFO and store the result of the call in
2377 *RES. Issue warnings for detected past the end writes. Return true
2378 if the complete format string has been processed and *RES can be relied
2379 on, false otherwise (e.g., when a unknown or unhandled directive was seen
2380 that caused the processing to be terminated early). */
2382 bool
2383 pass_sprintf_length::compute_format_length (call_info &info,
2384 format_result *res)
2386 /* The variadic argument counter. */
2387 unsigned argno = info.argidx;
2389 /* Reset exact, minimum, and maximum character counters. */
2390 res->number_chars = res->number_chars_min = res->number_chars_max = 0;
2392 /* No directive has been seen yet so the length of output is bounded
2393 by the known range [0, 0] and constant (with no conversion producing
2394 more than 4K bytes) until determined otherwise. */
2395 res->bounded = true;
2396 res->knownrange = true;
2397 res->constant = true;
2398 res->under4k = true;
2399 res->floating = false;
2400 res->warned = false;
2402 const char *pf = info.fmtstr;
2404 for ( ; ; )
2406 /* The beginning of the next format directive. */
2407 const char *dir = strchr (pf, '%');
2409 /* Add the number of bytes between the end of the last directive
2410 and either the next if one exists, or the end of the format
2411 string. */
2412 add_bytes (info, pf, dir, res);
2414 if (!dir)
2415 break;
2417 pf = dir + 1;
2419 if (0 && *pf == 0)
2421 /* Incomplete directive. */
2422 return false;
2425 conversion_spec spec = conversion_spec ();
2427 /* POSIX numbered argument index or zero when none. */
2428 unsigned dollar = 0;
2430 if (ISDIGIT (*pf))
2432 /* This could be either a POSIX positional argument, the '0'
2433 flag, or a width, depending on what follows. Store it as
2434 width and sort it out later after the next character has
2435 been seen. */
2436 char *end;
2437 spec.width = strtol (pf, &end, 10);
2438 spec.have_width = true;
2439 pf = end;
2441 else if ('*' == *pf)
2443 /* Similarly to the block above, this could be either a POSIX
2444 positional argument or a width, depending on what follows. */
2445 if (argno < gimple_call_num_args (info.callstmt))
2446 spec.star_width = gimple_call_arg (info.callstmt, argno++);
2447 else
2448 spec.star_width = void_node;
2449 ++pf;
2452 if (*pf == '$')
2454 /* Handle the POSIX dollar sign which references the 1-based
2455 positional argument number. */
2456 if (spec.have_width)
2457 dollar = spec.width + info.argidx;
2458 else if (spec.star_width
2459 && TREE_CODE (spec.star_width) == INTEGER_CST)
2460 dollar = spec.width + tree_to_shwi (spec.star_width);
2462 /* Bail when the numbered argument is out of range (it will
2463 have already been diagnosed by -Wformat). */
2464 if (dollar == 0
2465 || dollar == info.argidx
2466 || dollar > gimple_call_num_args (info.callstmt))
2467 return false;
2469 --dollar;
2471 spec.star_width = NULL_TREE;
2472 spec.have_width = false;
2473 ++pf;
2476 if (dollar || !spec.star_width)
2478 if (spec.have_width)
2480 if (spec.width == 0)
2482 /* The '0' that has been interpreted as a width above is
2483 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
2484 and continue processing other flags. */
2485 spec.have_width = false;
2486 spec.set_flag ('0');
2488 else if (!dollar)
2490 /* (Non-zero) width has been seen. The next character
2491 is either a period or a digit. */
2492 goto start_precision;
2495 /* When either '$' has been seen, or width has not been seen,
2496 the next field is the optional flags followed by an optional
2497 width. */
2498 for ( ; ; ) {
2499 switch (*pf)
2501 case ' ':
2502 case '0':
2503 case '+':
2504 case '-':
2505 case '#':
2506 spec.set_flag (*pf++);
2507 break;
2509 default:
2510 goto start_width;
2514 start_width:
2515 if (ISDIGIT (*pf))
2517 char *end;
2518 spec.width = strtol (pf, &end, 10);
2519 spec.have_width = true;
2520 pf = end;
2522 else if ('*' == *pf)
2524 if (argno < gimple_call_num_args (info.callstmt))
2525 spec.star_width = gimple_call_arg (info.callstmt, argno++);
2526 else
2527 spec.star_width = void_node;
2528 ++pf;
2530 else if ('\'' == *pf)
2532 /* The POSIX apostrophe indicating a numeric grouping
2533 in the current locale. Even though it's possible to
2534 estimate the upper bound on the size of the output
2535 based on the number of digits it probably isn't worth
2536 continuing. */
2537 return false;
2541 start_precision:
2542 if ('.' == *pf)
2544 ++pf;
2546 if (ISDIGIT (*pf))
2548 char *end;
2549 spec.precision = strtol (pf, &end, 10);
2550 spec.have_precision = true;
2551 pf = end;
2553 else if ('*' == *pf)
2555 if (argno < gimple_call_num_args (info.callstmt))
2556 spec.star_precision = gimple_call_arg (info.callstmt, argno++);
2557 else
2558 spec.star_precision = void_node;
2559 ++pf;
2561 else
2563 /* The decimal precision or the asterisk are optional.
2564 When neither is specified it's taken to be zero. */
2565 spec.precision = 0;
2566 spec.have_precision = true;
2570 switch (*pf)
2572 case 'h':
2573 if (pf[1] == 'h')
2575 ++pf;
2576 spec.modifier = FMT_LEN_hh;
2578 else
2579 spec.modifier = FMT_LEN_h;
2580 ++pf;
2581 break;
2583 case 'j':
2584 spec.modifier = FMT_LEN_j;
2585 ++pf;
2586 break;
2588 case 'L':
2589 spec.modifier = FMT_LEN_L;
2590 ++pf;
2591 break;
2593 case 'l':
2594 if (pf[1] == 'l')
2596 ++pf;
2597 spec.modifier = FMT_LEN_ll;
2599 else
2600 spec.modifier = FMT_LEN_l;
2601 ++pf;
2602 break;
2604 case 't':
2605 spec.modifier = FMT_LEN_t;
2606 ++pf;
2607 break;
2609 case 'z':
2610 spec.modifier = FMT_LEN_z;
2611 ++pf;
2612 break;
2615 switch (*pf)
2617 /* Handle a sole '%' character the same as "%%" but since it's
2618 undefined prevent the result from being folded. */
2619 case '\0':
2620 --pf;
2621 res->bounded = false;
2622 /* FALLTHRU */
2623 case '%':
2624 spec.fmtfunc = format_percent;
2625 break;
2627 case 'a':
2628 case 'A':
2629 case 'e':
2630 case 'E':
2631 case 'f':
2632 case 'F':
2633 case 'g':
2634 case 'G':
2635 res->floating = true;
2636 spec.fmtfunc = format_floating;
2637 break;
2639 case 'd':
2640 case 'i':
2641 case 'o':
2642 case 'u':
2643 case 'x':
2644 case 'X':
2645 spec.fmtfunc = format_integer;
2646 break;
2648 case 'p':
2649 /* The %p output is implementation-defined. It's possible
2650 to determine this format but due to extensions (especially
2651 those of the Linux kernel -- see bug 78512) the first %p
2652 in the format string disables any further processing. */
2653 return false;
2655 case 'n':
2656 /* %n has side-effects even when nothing is actually printed to
2657 any buffer. */
2658 info.nowrite = false;
2659 break;
2661 case 'c':
2662 case 'S':
2663 case 's':
2664 spec.fmtfunc = format_string;
2665 break;
2667 default:
2668 /* Unknown conversion specification. */
2669 return false;
2672 spec.specifier = *pf++;
2674 /* Compute the length of the format directive. */
2675 size_t dirlen = pf - dir;
2677 /* Extract the argument if the directive takes one and if it's
2678 available (e.g., the function doesn't take a va_list). Treat
2679 missing arguments the same as va_list, even though they will
2680 have likely already been diagnosed by -Wformat. */
2681 tree arg = NULL_TREE;
2682 if (spec.specifier != '%'
2683 && argno < gimple_call_num_args (info.callstmt))
2684 arg = gimple_call_arg (info.callstmt, dollar ? dollar : argno++);
2686 ::format_directive (info, res, dir, dirlen, spec, arg);
2689 /* Complete format string was processed (with or without warnings). */
2690 return true;
2693 /* Return the size of the object referenced by the expression DEST if
2694 available, or -1 otherwise. */
2696 static unsigned HOST_WIDE_INT
2697 get_destination_size (tree dest)
2699 /* Use __builtin_object_size to determine the size of the destination
2700 object. When optimizing, determine the smallest object (such as
2701 a member array as opposed to the whole enclosing object), otherwise
2702 use type-zero object size to determine the size of the enclosing
2703 object (the function fails without optimization in this type). */
2704 int ost = optimize > 0;
2705 unsigned HOST_WIDE_INT size;
2706 if (compute_builtin_object_size (dest, ost, &size))
2707 return size;
2709 return HOST_WIDE_INT_M1U;
2712 /* Given a suitable result RES of a call to a formatted output function
2713 described by INFO, substitute the result for the return value of
2714 the call. The result is suitable if the number of bytes it represents
2715 is known and exact. A result that isn't suitable for substitution may
2716 have its range set to the range of return values, if that is known. */
2718 static void
2719 try_substitute_return_value (gimple_stmt_iterator *gsi,
2720 const pass_sprintf_length::call_info &info,
2721 const format_result &res)
2723 tree lhs = gimple_get_lhs (info.callstmt);
2725 /* Avoid the return value optimization when the behavior of the call
2726 is undefined either because any directive may have produced 4K or
2727 more of output, or the return value exceeds INT_MAX, or because
2728 the output overflows the destination object (but leave it enabled
2729 when the function is bounded because then the behavior is well-
2730 defined). */
2731 if (lhs
2732 && res.bounded
2733 && res.under4k
2734 && (info.bounded || res.number_chars <= info.objsize)
2735 && res.number_chars - 1 <= target_int_max ()
2736 /* Not prepared to handle possibly throwing calls here; they shouldn't
2737 appear in non-artificial testcases, except when the __*_chk routines
2738 are badly declared. */
2739 && !stmt_ends_bb_p (info.callstmt))
2741 tree cst = build_int_cst (integer_type_node, res.number_chars - 1);
2743 if (info.nowrite)
2745 /* Replace the call to the bounded function with a zero size
2746 (e.g., snprintf(0, 0, "%i", 123) with the constant result
2747 of the function minus 1 for the terminating NUL which
2748 the function's return value does not include. */
2749 if (!update_call_from_tree (gsi, cst))
2750 gimplify_and_update_call_from_tree (gsi, cst);
2751 gimple *callstmt = gsi_stmt (*gsi);
2752 update_stmt (callstmt);
2754 else
2756 /* Replace the left-hand side of the call with the constant
2757 result of the formatted function minus 1 for the terminating
2758 NUL which the function's return value does not include. */
2759 gimple_call_set_lhs (info.callstmt, NULL_TREE);
2760 gimple *g = gimple_build_assign (lhs, cst);
2761 gsi_insert_after (gsi, g, GSI_NEW_STMT);
2762 update_stmt (info.callstmt);
2765 if (dump_file)
2767 location_t callloc = gimple_location (info.callstmt);
2768 fprintf (dump_file, "On line %i substituting ",
2769 LOCATION_LINE (callloc));
2770 print_generic_expr (dump_file, cst, dump_flags);
2771 fprintf (dump_file, " for ");
2772 print_generic_expr (dump_file, info.func, dump_flags);
2773 fprintf (dump_file, " %s (output %s).\n",
2774 info.nowrite ? "call" : "return value",
2775 res.constant ? "constant" : "variable");
2778 else
2780 unsigned HOST_WIDE_INT maxbytes;
2782 if (lhs
2783 && res.bounded
2784 && ((maxbytes = res.number_chars - 1) <= target_int_max ()
2785 || (res.number_chars_min - 1 <= target_int_max ()
2786 && (maxbytes = res.number_chars_max - 1) <= target_int_max ()))
2787 && (info.bounded || maxbytes < info.objsize))
2789 /* If the result is in a valid range bounded by the size of
2790 the destination set it so that it can be used for subsequent
2791 optimizations. */
2792 int prec = TYPE_PRECISION (integer_type_node);
2794 if (res.number_chars < target_int_max () && res.under4k)
2796 wide_int num = wi::shwi (res.number_chars - 1, prec);
2797 set_range_info (lhs, VR_RANGE, num, num);
2799 else if (res.number_chars_min < target_int_max ()
2800 && res.number_chars_max < target_int_max ())
2802 wide_int min = wi::shwi (res.under4k ? res.number_chars_min - 1
2803 : target_int_min (), prec);
2804 wide_int max = wi::shwi (res.number_chars_max - 1, prec);
2805 set_range_info (lhs, VR_RANGE, min, max);
2809 if (dump_file)
2811 const char *inbounds
2812 = (res.number_chars_min <= info.objsize
2813 ? (res.number_chars_max <= info.objsize
2814 ? "in" : "potentially out-of")
2815 : "out-of");
2817 location_t callloc = gimple_location (info.callstmt);
2818 fprintf (dump_file, "On line %i ", LOCATION_LINE (callloc));
2819 print_generic_expr (dump_file, info.func, dump_flags);
2821 const char *ign = lhs ? "" : " ignored";
2822 if (res.number_chars >= HOST_WIDE_INT_MAX)
2823 fprintf (dump_file,
2824 " %s-bounds return value in range [%lu, %lu]%s.\n",
2825 inbounds,
2826 (unsigned long)res.number_chars_min - 1,
2827 (unsigned long)res.number_chars_max - 1, ign);
2828 else
2829 fprintf (dump_file, " %s-bounds return value %lu%s.\n",
2830 inbounds, (unsigned long)res.number_chars - 1, ign);
2835 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
2836 functions and if so, handle it. */
2838 void
2839 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator *gsi)
2841 call_info info = call_info ();
2843 info.callstmt = gsi_stmt (*gsi);
2844 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
2845 return;
2847 info.func = gimple_call_fndecl (info.callstmt);
2848 info.fncode = DECL_FUNCTION_CODE (info.func);
2850 /* The size of the destination as in snprintf(dest, size, ...). */
2851 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
2853 /* The size of the destination determined by __builtin_object_size. */
2854 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
2856 /* Buffer size argument number (snprintf and vsnprintf). */
2857 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
2859 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
2860 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
2862 /* Format string argument number (valid for all functions). */
2863 unsigned idx_format;
2865 switch (info.fncode)
2867 case BUILT_IN_SPRINTF:
2868 // Signature:
2869 // __builtin_sprintf (dst, format, ...)
2870 idx_format = 1;
2871 info.argidx = 2;
2872 break;
2874 case BUILT_IN_SPRINTF_CHK:
2875 // Signature:
2876 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
2877 idx_objsize = 2;
2878 idx_format = 3;
2879 info.argidx = 4;
2880 break;
2882 case BUILT_IN_SNPRINTF:
2883 // Signature:
2884 // __builtin_snprintf (dst, size, format, ...)
2885 idx_dstsize = 1;
2886 idx_format = 2;
2887 info.argidx = 3;
2888 info.bounded = true;
2889 break;
2891 case BUILT_IN_SNPRINTF_CHK:
2892 // Signature:
2893 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
2894 idx_dstsize = 1;
2895 idx_objsize = 3;
2896 idx_format = 4;
2897 info.argidx = 5;
2898 info.bounded = true;
2899 break;
2901 case BUILT_IN_VSNPRINTF:
2902 // Signature:
2903 // __builtin_vsprintf (dst, size, format, va)
2904 idx_dstsize = 1;
2905 idx_format = 2;
2906 info.argidx = -1;
2907 info.bounded = true;
2908 break;
2910 case BUILT_IN_VSNPRINTF_CHK:
2911 // Signature:
2912 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
2913 idx_dstsize = 1;
2914 idx_objsize = 3;
2915 idx_format = 4;
2916 info.argidx = -1;
2917 info.bounded = true;
2918 break;
2920 case BUILT_IN_VSPRINTF:
2921 // Signature:
2922 // __builtin_vsprintf (dst, format, va)
2923 idx_format = 1;
2924 info.argidx = -1;
2925 break;
2927 case BUILT_IN_VSPRINTF_CHK:
2928 // Signature:
2929 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
2930 idx_format = 3;
2931 idx_objsize = 2;
2932 info.argidx = -1;
2933 break;
2935 default:
2936 return;
2939 /* The first argument is a pointer to the destination. */
2940 tree dstptr = gimple_call_arg (info.callstmt, 0);
2942 info.format = gimple_call_arg (info.callstmt, idx_format);
2944 if (idx_dstsize == HOST_WIDE_INT_M1U)
2946 /* For non-bounded functions like sprintf, determine the size
2947 of the destination from the object or pointer passed to it
2948 as the first argument. */
2949 dstsize = get_destination_size (dstptr);
2951 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
2953 /* For bounded functions try to get the size argument. */
2955 if (TREE_CODE (size) == INTEGER_CST)
2957 dstsize = tree_to_uhwi (size);
2958 /* No object can be larger than SIZE_MAX bytes (half the address
2959 space) on the target.
2960 The functions are defined only for output of at most INT_MAX
2961 bytes. Specifying a bound in excess of that limit effectively
2962 defeats the bounds checking (and on some implementations such
2963 as Solaris cause the function to fail with EINVAL). */
2964 if (dstsize > target_size_max () / 2)
2966 /* Avoid warning if -Wstringop-overflow is specified since
2967 it also warns for the same thing though only for the
2968 checking built-ins. */
2969 if ((idx_objsize == HOST_WIDE_INT_M1U
2970 || !warn_stringop_overflow))
2971 warning_at (gimple_location (info.callstmt),
2972 OPT_Wformat_length_,
2973 "specified bound %wu exceeds maximum object size "
2974 "%wu",
2975 dstsize, target_size_max () / 2);
2977 else if (dstsize > target_int_max ())
2978 warning_at (gimple_location (info.callstmt), OPT_Wformat_length_,
2979 "specified bound %wu exceeds %<INT_MAX %>",
2980 dstsize);
2982 else if (TREE_CODE (size) == SSA_NAME)
2984 /* Try to determine the range of values of the argument
2985 and use the greater of the two at -Wformat-level 1 and
2986 the smaller of them at level 2. */
2987 wide_int min, max;
2988 enum value_range_type range_type
2989 = get_range_info (size, &min, &max);
2990 if (range_type == VR_RANGE)
2992 dstsize
2993 = (warn_format_length < 2
2994 ? wi::fits_uhwi_p (max) ? max.to_uhwi () : max.to_shwi ()
2995 : wi::fits_uhwi_p (min) ? min.to_uhwi () : min.to_shwi ());
3000 if (idx_objsize != HOST_WIDE_INT_M1U)
3002 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3003 if (tree_fits_uhwi_p (size))
3004 objsize = tree_to_uhwi (size);
3007 if (info.bounded && !dstsize)
3009 /* As a special case, when the explicitly specified destination
3010 size argument (to a bounded function like snprintf) is zero
3011 it is a request to determine the number of bytes on output
3012 without actually producing any. Pretend the size is
3013 unlimited in this case. */
3014 info.objsize = HOST_WIDE_INT_MAX;
3015 info.nowrite = true;
3017 else
3019 /* For calls to non-bounded functions or to those of bounded
3020 functions with a non-zero size, warn if the destination
3021 pointer is null. */
3022 if (integer_zerop (dstptr))
3024 /* This is diagnosed with -Wformat only when the null is a constant
3025 pointer. The warning here diagnoses instances where the pointer
3026 is not constant. */
3027 location_t loc = gimple_location (info.callstmt);
3028 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3029 OPT_Wformat_length_, "null destination pointer");
3030 return;
3033 /* Set the object size to the smaller of the two arguments
3034 of both have been specified and they're not equal. */
3035 info.objsize = dstsize < objsize ? dstsize : objsize;
3037 if (info.bounded
3038 && dstsize < target_size_max () / 2 && objsize < dstsize
3039 /* Avoid warning if -Wstringop-overflow is specified since
3040 it also warns for the same thing though only for the
3041 checking built-ins. */
3042 && (idx_objsize == HOST_WIDE_INT_M1U
3043 || !warn_stringop_overflow))
3045 warning_at (gimple_location (info.callstmt), OPT_Wformat_length_,
3046 "specified bound %wu exceeds the size %wu "
3047 "of the destination object", dstsize, objsize);
3051 if (integer_zerop (info.format))
3053 /* This is diagnosed with -Wformat only when the null is a constant
3054 pointer. The warning here diagnoses instances where the pointer
3055 is not constant. */
3056 location_t loc = gimple_location (info.callstmt);
3057 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3058 OPT_Wformat_length_, "null format string");
3059 return;
3062 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3063 if (!info.fmtstr)
3064 return;
3066 /* The result is the number of bytes output by the formatted function,
3067 including the terminating NUL. */
3068 format_result res = format_result ();
3070 bool success = compute_format_length (info, &res);
3072 /* When optimizing and the printf return value optimization is enabled,
3073 attempt to substitute the computed result for the return value of
3074 the call. Avoid this optimization when -frounding-math is in effect
3075 and the format string contains a floating point directive. */
3076 if (success
3077 && optimize > 0
3078 && flag_printf_return_value
3079 && (!flag_rounding_math || !res.floating))
3080 try_substitute_return_value (gsi, info, res);
3083 /* Execute the pass for function FUN. */
3085 unsigned int
3086 pass_sprintf_length::execute (function *fun)
3088 basic_block bb;
3089 FOR_EACH_BB_FN (bb, fun)
3091 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
3092 gsi_next (&si))
3094 /* Iterate over statements, looking for function calls. */
3095 gimple *stmt = gsi_stmt (si);
3097 if (is_gimple_call (stmt))
3098 handle_gimple_call (&si);
3102 return 0;
3105 } /* Unnamed namespace. */
3107 /* Return a pointer to a pass object newly constructed from the context
3108 CTXT. */
3110 gimple_opt_pass *
3111 make_pass_sprintf_length (gcc::context *ctxt)
3113 return new pass_sprintf_length (ctxt);