* config/spu/spu.md (floatunsdidf2): Remove unused local variable.
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blobead8b0ed5a05085bc2d23ff0d3379fed26b0e397
1 /* Copyright (C) 2016 Free Software Foundation, Inc.
2 Contributed by Martin Sebor <msebor@redhat.com>.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /* This file implements the printf-return-value pass. The pass does
21 two things: 1) it analyzes calls to formatted output functions like
22 sprintf looking for possible buffer overflows and calls to bounded
23 functions like snprintf for early truncation (and under the control
24 of the -Wformat-length option issues warnings), and 2) under the
25 control of the -fprintf-return-value option it folds the return
26 value of safe calls into constants, making it possible to eliminate
27 code that depends on the value of those constants.
29 For all functions (bounded or not) the pass uses the size of the
30 destination object. That means that it will diagnose calls to
31 snprintf not on the basis of the size specified by the function's
32 second argument but rathger on the basis of the size the first
33 argument points to (if possible). For bound-checking built-ins
34 like __builtin___snprintf_chk the pass uses the size typically
35 determined by __builtin_object_size and passed to the built-in
36 by the Glibc inline wrapper.
38 The pass handles all forms standard sprintf format directives,
39 including character, integer, floating point, pointer, and strings,
40 with the standard C flags, widths, and precisions. For integers
41 and strings it computes the length of output itself. For floating
42 point it uses MPFR to fornmat known constants with up and down
43 rounding and uses the resulting range of output lengths. For
44 strings it uses the length of string literals and the sizes of
45 character arrays that a character pointer may point to as a bound
46 on the longest string. */
48 #include "config.h"
49 #include "system.h"
50 #include "coretypes.h"
51 #include "backend.h"
52 #include "tree.h"
53 #include "gimple.h"
54 #include "tree-pass.h"
55 #include "ssa.h"
56 #include "gimple-fold.h"
57 #include "gimple-pretty-print.h"
58 #include "diagnostic-core.h"
59 #include "fold-const.h"
60 #include "gimple-iterator.h"
61 #include "tree-ssa.h"
62 #include "tree-object-size.h"
63 #include "params.h"
64 #include "tree-cfg.h"
65 #include "calls.h"
66 #include "cfgloop.h"
67 #include "intl.h"
69 #include "builtins.h"
70 #include "stor-layout.h"
72 #include "realmpfr.h"
73 #include "target.h"
74 #include "targhooks.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 namespace {
89 const pass_data pass_data_sprintf_length = {
90 GIMPLE_PASS, // pass type
91 "printf-return-value", // pass name
92 OPTGROUP_NONE, // optinfo_flags
93 TV_NONE, // tv_id
94 PROP_cfg, // properties_required
95 0, // properties_provided
96 0, // properties_destroyed
97 0, // properties_start
98 0, // properties_finish
101 struct format_result;
103 class pass_sprintf_length : public gimple_opt_pass
105 bool fold_return_value;
107 public:
108 pass_sprintf_length (gcc::context *ctxt)
109 : gimple_opt_pass (pass_data_sprintf_length, ctxt),
110 fold_return_value (false)
113 opt_pass * clone () { return new pass_sprintf_length (m_ctxt); }
115 virtual bool gate (function *);
117 virtual unsigned int execute (function *);
119 void set_pass_param (unsigned int n, bool param)
121 gcc_assert (n == 0);
122 fold_return_value = param;
125 void handle_gimple_call (gimple_stmt_iterator);
127 struct call_info;
128 void compute_format_length (const call_info &, format_result *);
131 bool
132 pass_sprintf_length::gate (function *)
134 /* Run the pass iff -Warn-format-length is specified and either
135 not optimizing and the pass is being invoked early, or when
136 optimizing and the pass is being invoked during optimization
137 (i.e., "late"). */
138 return ((warn_format_length > 0 || flag_printf_return_value)
139 && (optimize > 0) == fold_return_value);
142 /* The result of a call to a formatted function. */
144 struct format_result
146 /* Number of characters written by the formatted function, exact,
147 minimum and maximum when an exact number cannot be determined.
148 Setting the minimum to HOST_WIDE_INT_MAX disables all length
149 tracking for the remainder of the format string.
150 Setting either of the other two members to HOST_WIDE_INT_MAX
151 disables the exact or maximum length tracking, respectively,
152 but continues to track the maximum. */
153 unsigned HOST_WIDE_INT number_chars;
154 unsigned HOST_WIDE_INT number_chars_min;
155 unsigned HOST_WIDE_INT number_chars_max;
157 /* True when the range given by NUMBER_CHARS_MIN and NUMBER_CHARS_MAX
158 can be relied on for value range propagation, false otherwise.
159 This means that BOUNDED must not be set if the number of bytes
160 produced by any directive is unspecified or implementation-
161 defined (unless the implementation's behavior is known and
162 determined via a target hook).
163 Note that BOUNDED only implies that the length of a function's
164 output is known to be within some range, not that it's constant
165 and a candidate for string folding. BOUNDED is a stronger
166 guarantee than KNOWNRANGE. */
167 bool bounded;
169 /* True when the range above is obtained from known values of
170 directive arguments or their bounds and not the result of
171 heuristics that depend on warning levels. It is used to
172 issue stricter diagnostics in cases where strings of unknown
173 lengths are bounded by the arrays they are determined to
174 refer to. KNOWNRANGE must not be used to set the range of
175 the return value of a call. */
176 bool knownrange;
178 /* True when the output of the formatted call is constant (and
179 thus a candidate for string constant folding). This is rare
180 and typically requires that the arguments of all directives
181 are also constant. CONSTANT implies BOUNDED. */
182 bool constant;
184 /* True if no individual directive resulted in more than 4095 bytes
185 of output (the total NUMBER_CHARS might be greater). */
186 bool under4k;
188 /* True when a floating point directive has been seen in the format
189 string. */
190 bool floating;
192 /* True when an intermediate result has caused a warning. Used to
193 avoid issuing duplicate warnings while finishing the processing
194 of a call. */
195 bool warned;
197 /* Preincrement the number of output characters by 1. */
198 format_result& operator++ ()
200 return *this += 1;
203 /* Postincrement the number of output characters by 1. */
204 format_result operator++ (int)
206 format_result prev (*this);
207 *this += 1;
208 return prev;
211 /* Increment the number of output characters by N. */
212 format_result& operator+= (unsigned HOST_WIDE_INT n)
214 gcc_assert (n < HOST_WIDE_INT_MAX);
216 if (number_chars < HOST_WIDE_INT_MAX)
217 number_chars += n;
218 if (number_chars_min < HOST_WIDE_INT_MAX)
219 number_chars_min += n;
220 if (number_chars_max < HOST_WIDE_INT_MAX)
221 number_chars_max += n;
222 return *this;
226 /* Return the value of INT_MIN for the target. */
228 static HOST_WIDE_INT
229 target_int_min ()
231 const unsigned HOST_WIDE_INT int_min
232 = HOST_WIDE_INT_M1U << (TYPE_PRECISION (integer_type_node) - 1);
234 return int_min;
237 /* Return the largest value for TYPE on the target. */
239 static unsigned HOST_WIDE_INT
240 target_max_value (tree type)
242 const unsigned HOST_WIDE_INT max_value
243 = HOST_WIDE_INT_M1U >> (HOST_BITS_PER_WIDE_INT
244 - TYPE_PRECISION (type) + 1);
245 return max_value;
248 /* Return the value of INT_MAX for the target. */
250 static inline unsigned HOST_WIDE_INT
251 target_int_max ()
253 return target_max_value (integer_type_node);
256 /* Return the value of SIZE_MAX for the target. */
258 static inline unsigned HOST_WIDE_INT
259 target_size_max ()
261 return target_max_value (size_type_node);
264 /* Return the constant initial value of DECL if available or DECL
265 otherwise. Same as the synonymous function in c/c-typeck.c. */
267 static tree
268 decl_constant_value (tree decl)
270 if (/* Don't change a variable array bound or initial value to a constant
271 in a place where a variable is invalid. Note that DECL_INITIAL
272 isn't valid for a PARM_DECL. */
273 current_function_decl != 0
274 && TREE_CODE (decl) != PARM_DECL
275 && !TREE_THIS_VOLATILE (decl)
276 && TREE_READONLY (decl)
277 && DECL_INITIAL (decl) != 0
278 && TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK
279 /* This is invalid if initial value is not constant.
280 If it has either a function call, a memory reference,
281 or a variable, then re-evaluating it could give different results. */
282 && TREE_CONSTANT (DECL_INITIAL (decl))
283 /* Check for cases where this is sub-optimal, even though valid. */
284 && TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)
285 return DECL_INITIAL (decl);
286 return decl;
289 /* Given FORMAT, set *PLOC to the source location of the format string
290 and return the format string if it is known or null otherwise. */
292 static const char*
293 get_format_string (tree format, location_t *ploc)
295 if (VAR_P (format))
297 /* Pull out a constant value if the front end didn't. */
298 format = decl_constant_value (format);
299 STRIP_NOPS (format);
302 if (integer_zerop (format))
304 /* FIXME: Diagnose null format string if it hasn't been diagnosed
305 by -Wformat (the latter diagnoses only nul pointer constants,
306 this pass can do better). */
307 return NULL;
310 HOST_WIDE_INT offset = 0;
312 if (TREE_CODE (format) == POINTER_PLUS_EXPR)
314 tree arg0 = TREE_OPERAND (format, 0);
315 tree arg1 = TREE_OPERAND (format, 1);
316 STRIP_NOPS (arg0);
317 STRIP_NOPS (arg1);
319 if (TREE_CODE (arg1) != INTEGER_CST)
320 return NULL;
322 format = arg0;
324 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
325 if (!cst_and_fits_in_hwi (arg1))
326 return NULL;
328 offset = int_cst_value (arg1);
331 if (TREE_CODE (format) != ADDR_EXPR)
332 return NULL;
334 *ploc = EXPR_LOC_OR_LOC (format, input_location);
336 format = TREE_OPERAND (format, 0);
338 if (TREE_CODE (format) == ARRAY_REF
339 && tree_fits_shwi_p (TREE_OPERAND (format, 1))
340 && (offset += tree_to_shwi (TREE_OPERAND (format, 1))) >= 0)
341 format = TREE_OPERAND (format, 0);
343 if (offset < 0)
344 return NULL;
346 tree array_init;
347 tree array_size = NULL_TREE;
349 if (VAR_P (format)
350 && TREE_CODE (TREE_TYPE (format)) == ARRAY_TYPE
351 && (array_init = decl_constant_value (format)) != format
352 && TREE_CODE (array_init) == STRING_CST)
354 /* Extract the string constant initializer. Note that this may
355 include a trailing NUL character that is not in the array (e.g.
356 const char a[3] = "foo";). */
357 array_size = DECL_SIZE_UNIT (format);
358 format = array_init;
361 if (TREE_CODE (format) != STRING_CST)
362 return NULL;
364 if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format))) != char_type_node)
366 /* Wide format string. */
367 return NULL;
370 const char *fmtstr = TREE_STRING_POINTER (format);
371 unsigned fmtlen = TREE_STRING_LENGTH (format);
373 if (array_size)
375 /* Variable length arrays can't be initialized. */
376 gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
378 if (tree_fits_shwi_p (array_size))
380 HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
381 if (array_size_value > 0
382 && array_size_value == (int) array_size_value
383 && fmtlen > array_size_value)
384 fmtlen = array_size_value;
387 if (offset)
389 if (offset >= fmtlen)
390 return NULL;
392 fmtstr += offset;
393 fmtlen -= offset;
396 if (fmtlen < 1 || fmtstr[--fmtlen] != 0)
398 /* FIXME: Diagnose an unterminated format string if it hasn't been
399 diagnosed by -Wformat. Similarly to a null format pointer,
400 -Wformay diagnoses only nul pointer constants, this pass can
401 do better). */
402 return NULL;
405 return fmtstr;
408 /* The format_warning_at_substring function is not used here in a way
409 that makes using attribute format viable. Suppress the warning. */
411 #pragma GCC diagnostic push
412 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
414 /* For convenience and brevity. */
416 static bool
417 (* const fmtwarn) (const substring_loc &, const source_range *,
418 const char *, int, const char *, ...)
419 = format_warning_at_substring;
421 /* Format length modifiers. */
423 enum format_lengths
425 FMT_LEN_none,
426 FMT_LEN_hh, // char argument
427 FMT_LEN_h, // short
428 FMT_LEN_l, // long
429 FMT_LEN_ll, // long long
430 FMT_LEN_L, // long double (and GNU long long)
431 FMT_LEN_z, // size_t
432 FMT_LEN_t, // ptrdiff_t
433 FMT_LEN_j // intmax_t
437 /* A minimum and maximum number of bytes. */
439 struct result_range
441 unsigned HOST_WIDE_INT min, max;
444 /* Description of the result of conversion either of a single directive
445 or the whole format string. */
447 struct fmtresult
449 fmtresult ()
450 : argmin (), argmax (), knownrange (), bounded (), constant ()
452 range.min = range.max = HOST_WIDE_INT_MAX;
455 /* The range a directive's argument is in. */
456 tree argmin, argmax;
458 /* The minimum and maximum number of bytes that a directive
459 results in on output for an argument in the range above. */
460 result_range range;
462 /* True when the range above is obtained from a known value of
463 a directive's argument or its bounds and not the result of
464 heuristics that depend on warning levels. */
465 bool knownrange;
467 /* True when the range is the result of an argument determined
468 to be bounded to a subrange of its type or value (such as by
469 value range propagation or the width of the formt directive),
470 false otherwise. */
471 bool bounded;
473 /* True when the output of a directive is constant. This is rare
474 and typically requires that the argument(s) of the directive
475 are also constant (such as determined by constant propagation,
476 though not value range propagation). */
477 bool constant;
480 /* Description of a conversion specification. */
482 struct conversion_spec
484 /* A bitmap of flags, one for each character. */
485 unsigned flags[256 / sizeof (int)];
486 /* Numeric width as in "%8x". */
487 int width;
488 /* Numeric precision as in "%.32s". */
489 int precision;
491 /* Width specified via the '*' character. */
492 tree star_width;
493 /* Precision specified via the asterisk. */
494 tree star_precision;
496 /* Length modifier. */
497 format_lengths modifier;
499 /* Format specifier character. */
500 char specifier;
502 /* Numeric width was given. */
503 unsigned have_width: 1;
504 /* Numeric precision was given. */
505 unsigned have_precision: 1;
506 /* Non-zero when certain flags should be interpreted even for a directive
507 that normally doesn't accept them (used when "%p" with flags such as
508 space or plus is interepreted as a "%x". */
509 unsigned force_flags: 1;
511 /* Format conversion function that given a conversion specification
512 and an argument returns the formatting result. */
513 fmtresult (*fmtfunc) (const conversion_spec &, tree);
515 /* Return True when a the format flag CHR has been used. */
516 bool get_flag (char chr) const
518 unsigned char c = chr & 0xff;
519 return (flags[c / (CHAR_BIT * sizeof *flags)]
520 & (1U << (c % (CHAR_BIT * sizeof *flags))));
523 /* Make a record of the format flag CHR having been used. */
524 void set_flag (char chr)
526 unsigned char c = chr & 0xff;
527 flags[c / (CHAR_BIT * sizeof *flags)]
528 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
531 /* Reset the format flag CHR. */
532 void clear_flag (char chr)
534 unsigned char c = chr & 0xff;
535 flags[c / (CHAR_BIT * sizeof *flags)]
536 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
540 /* Return the logarithm of X in BASE. */
542 static int
543 ilog (unsigned HOST_WIDE_INT x, int base)
545 int res = 0;
548 ++res;
549 x /= base;
550 } while (x);
551 return res;
554 /* Return the number of bytes resulting from converting into a string
555 the INTEGER_CST tree node X in BASE. PLUS indicates whether 1 for
556 a plus sign should be added for positive numbers, and PREFIX whether
557 the length of an octal ('O') or hexadecimal ('0x') prefix should be
558 added for nonzero numbers. Return -1 if X cannot be represented. */
560 static int
561 tree_digits (tree x, int base, bool plus, bool prefix)
563 unsigned HOST_WIDE_INT absval;
565 int res;
567 if (TYPE_UNSIGNED (TREE_TYPE (x)))
569 if (tree_fits_uhwi_p (x))
571 absval = tree_to_uhwi (x);
572 res = plus;
574 else
575 return -1;
577 else
579 if (tree_fits_shwi_p (x))
581 HOST_WIDE_INT i = tree_to_shwi (x);
582 if (i < 0)
584 absval = -i;
585 res = 1;
587 else
589 absval = i;
590 res = plus;
593 else
594 return -1;
597 res += ilog (absval, base);
599 if (prefix && absval)
601 if (base == 8)
602 res += 1;
603 else if (base == 16)
604 res += 2;
607 return res;
610 /* Given the formatting result described by RES and NAVAIL, the number
611 of available in the destination, return the number of bytes remaining
612 in the destination. */
614 static inline result_range
615 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
617 result_range range;
619 if (HOST_WIDE_INT_MAX <= navail)
621 range.min = range.max = navail;
622 return range;
625 if (res.number_chars < navail)
627 range.min = range.max = navail - res.number_chars;
629 else if (res.number_chars_min < navail)
631 range.max = navail - res.number_chars_min;
633 else
634 range.max = 0;
636 if (res.number_chars_max < navail)
637 range.min = navail - res.number_chars_max;
638 else
639 range.min = 0;
641 return range;
644 /* Given the formatting result described by RES and NAVAIL, the number
645 of available in the destination, return the minimum number of bytes
646 remaining in the destination. */
648 static inline unsigned HOST_WIDE_INT
649 min_bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
651 if (HOST_WIDE_INT_MAX <= navail)
652 return navail;
654 if (1 < warn_format_length || res.bounded)
656 /* At level 2, or when all directives output an exact number
657 of bytes or when their arguments were bounded by known
658 ranges, use the greater of the two byte counters if it's
659 valid to compute the result. */
660 if (res.number_chars_max < HOST_WIDE_INT_MAX)
661 navail -= res.number_chars_max;
662 else if (res.number_chars < HOST_WIDE_INT_MAX)
663 navail -= res.number_chars;
664 else if (res.number_chars_min < HOST_WIDE_INT_MAX)
665 navail -= res.number_chars_min;
667 else
669 /* At level 1 use the smaller of the byte counters to compute
670 the result. */
671 if (res.number_chars < HOST_WIDE_INT_MAX)
672 navail -= res.number_chars;
673 else if (res.number_chars_min < HOST_WIDE_INT_MAX)
674 navail -= res.number_chars_min;
675 else if (res.number_chars_max < HOST_WIDE_INT_MAX)
676 navail -= res.number_chars_max;
679 if (navail > HOST_WIDE_INT_MAX)
680 navail = 0;
682 return navail;
685 /* Description of a call to a formatted function. */
687 struct pass_sprintf_length::call_info
689 /* Function call statement. */
690 gimple *callstmt;
692 /* Function called. */
693 tree func;
695 /* Called built-in function code. */
696 built_in_function fncode;
698 /* Format argument and format string extracted from it. */
699 tree format;
700 const char *fmtstr;
702 /* The location of the format argument. */
703 location_t fmtloc;
705 /* The destination object size for __builtin___xxx_chk functions
706 typically determined by __builtin_object_size, or -1 if unknown. */
707 unsigned HOST_WIDE_INT objsize;
709 /* Number of the first variable argument. */
710 unsigned HOST_WIDE_INT argidx;
712 /* True for functions like snprintf that specify the size of
713 the destination, false for others like sprintf that don't. */
714 bool bounded;
717 /* Return the result of formatting the '%%' directive. */
719 static fmtresult
720 format_percent (const conversion_spec &, tree)
722 fmtresult res;
723 res.argmin = res.argmax = NULL_TREE;
724 res.range.min = res.range.max = 1;
725 res.bounded = res.constant = true;
726 return res;
730 /* Ugh. Compute intmax_type_node and uintmax_type_node the same way
731 lto/lto-lang.c does it. This should be available in tree.h. */
733 static void
734 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
736 if (strcmp (SIZE_TYPE, "unsigned int") == 0)
738 *pintmax = integer_type_node;
739 *puintmax = unsigned_type_node;
741 else if (strcmp (SIZE_TYPE, "long unsigned int") == 0)
743 *pintmax = long_integer_type_node;
744 *puintmax = long_unsigned_type_node;
746 else if (strcmp (SIZE_TYPE, "long long unsigned int") == 0)
748 *pintmax = long_long_integer_type_node;
749 *puintmax = long_long_unsigned_type_node;
751 else
753 for (int i = 0; i < NUM_INT_N_ENTS; i++)
754 if (int_n_enabled_p[i])
756 char name[50];
757 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
759 if (strcmp (name, SIZE_TYPE) == 0)
761 *pintmax = int_n_trees[i].signed_type;
762 *puintmax = int_n_trees[i].unsigned_type;
768 static fmtresult
769 format_integer (const conversion_spec &, tree);
771 /* Return a range representing the minimum and maximum number of bytes
772 that the conversion specification SPEC will write on output for the
773 pointer argument ARG when non-null. ARG may be null (for vararg
774 functions). */
776 static fmtresult
777 format_pointer (const conversion_spec &spec, tree arg)
779 fmtresult res;
781 /* Determine the target's integer format corresponding to "%p". */
782 const char *flags;
783 const char *pfmt = targetm.printf_pointer_format (arg, &flags);
784 if (!pfmt)
786 /* The format couldn't be determined. */
787 res.range.min = res.range.max = HOST_WIDE_INT_M1U;
788 return res;
791 if (pfmt [0] == '%')
793 /* Format the pointer using the integer format string. */
794 conversion_spec pspec = spec;
796 /* Clear flags that are not listed as recognized. */
797 for (const char *pf = "+ #0"; *pf; ++pf)
799 if (!strchr (flags, *pf))
800 pspec.clear_flag (*pf);
803 /* Set flags that are specified in the format string. */
804 bool flag_p = true;
807 switch (*++pfmt)
809 case '+': case ' ': case '#': case '0':
810 pspec.set_flag (*pfmt);
811 break;
812 default:
813 flag_p = false;
816 while (flag_p);
818 /* Set the appropriate length modifier taking care to clear
819 the one that may be set (Glibc's %p accepts but ignores all
820 the integer length modifiers). */
821 switch (*pfmt)
823 case 'l': pspec.modifier = FMT_LEN_l; ++pfmt; break;
824 case 't': pspec.modifier = FMT_LEN_t; ++pfmt; break;
825 case 'z': pspec.modifier = FMT_LEN_z; ++pfmt; break;
826 default: pspec.modifier = FMT_LEN_none;
829 pspec.force_flags = 1;
830 pspec.specifier = *pfmt++;
831 gcc_assert (*pfmt == '\0');
832 return format_integer (pspec, arg);
835 /* The format is a plain string such as Glibc's "(nil)". */
836 res.range.min = res.range.max = strlen (pfmt);
837 return res;
840 /* Return a range representing the minimum and maximum number of bytes
841 that the conversion specification SPEC will write on output for the
842 integer argument ARG when non-null. ARG may be null (for vararg
843 functions). */
845 static fmtresult
846 format_integer (const conversion_spec &spec, tree arg)
848 /* These are available as macros in the C and C++ front ends but,
849 sadly, not here. */
850 static tree intmax_type_node;
851 static tree uintmax_type_node;
853 /* Initialize the intmax nodes above the first time through here. */
854 if (!intmax_type_node)
855 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
857 /* Set WIDTH and PRECISION to either the values in the format
858 specification or to zero. */
859 int width = spec.have_width ? spec.width : 0;
860 int prec = spec.have_precision ? spec.precision : 0;
862 if (spec.star_width)
863 width = (TREE_CODE (spec.star_width) == INTEGER_CST
864 ? tree_to_shwi (spec.star_width) : 0);
866 if (spec.star_precision)
867 prec = (TREE_CODE (spec.star_precision) == INTEGER_CST
868 ? tree_to_shwi (spec.star_precision) : 0);
870 bool sign = spec.specifier == 'd' || spec.specifier == 'i';
872 /* The type of the "formal" argument expected by the directive. */
873 tree dirtype = NULL_TREE;
875 /* Determine the expected type of the argument from the length
876 modifier. */
877 switch (spec.modifier)
879 case FMT_LEN_none:
880 if (spec.specifier == 'p')
881 dirtype = ptr_type_node;
882 else
883 dirtype = sign ? integer_type_node : unsigned_type_node;
884 break;
886 case FMT_LEN_h:
887 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
888 break;
890 case FMT_LEN_hh:
891 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
892 break;
894 case FMT_LEN_l:
895 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
896 break;
898 case FMT_LEN_L:
899 case FMT_LEN_ll:
900 dirtype = (sign
901 ? long_long_integer_type_node
902 : long_long_unsigned_type_node);
903 break;
905 case FMT_LEN_z:
906 dirtype = sign ? ptrdiff_type_node : size_type_node;
907 break;
909 case FMT_LEN_t:
910 dirtype = sign ? ptrdiff_type_node : size_type_node;
911 break;
913 case FMT_LEN_j:
914 dirtype = sign ? intmax_type_node : uintmax_type_node;
915 break;
917 default:
918 return fmtresult ();
921 /* The type of the argument to the directive, either deduced from
922 the actual non-constant argument if one is known, or from
923 the directive itself when none has been provided because it's
924 a va_list. */
925 tree argtype = NULL_TREE;
927 if (!arg)
929 /* When the argument has not been provided, use the type of
930 the directive's argument as an approximation. This will
931 result in false positives for directives like %i with
932 arguments with smaller precision (such as short or char). */
933 argtype = dirtype;
935 else if (TREE_CODE (arg) == INTEGER_CST)
937 /* The minimum and maximum number of bytes produced by
938 the directive. */
939 fmtresult res;
941 /* When a constant argument has been provided use its value
942 rather than type to determine the length of the output. */
943 res.bounded = true;
944 res.constant = true;
945 res.knownrange = true;
947 /* Base to format the number in. */
948 int base;
950 /* True when a signed conversion is preceded by a sign or space. */
951 bool maybesign;
953 switch (spec.specifier)
955 case 'd':
956 case 'i':
957 /* Space is only effective for signed conversions. */
958 maybesign = spec.get_flag (' ');
959 base = 10;
960 break;
961 case 'u':
962 maybesign = spec.force_flags ? spec.get_flag (' ') : false;
963 base = 10;
964 break;
965 case 'o':
966 maybesign = spec.force_flags ? spec.get_flag (' ') : false;
967 base = 8;
968 break;
969 case 'X':
970 case 'x':
971 maybesign = spec.force_flags ? spec.get_flag (' ') : false;
972 base = 16;
973 break;
974 default:
975 gcc_unreachable ();
978 /* Convert the argument to the type of the directive. */
979 arg = fold_convert (dirtype, arg);
981 maybesign |= spec.get_flag ('+');
983 /* True when a conversion is preceded by a prefix indicating the base
984 of the argument (octal or hexadecimal). */
985 bool maybebase = spec.get_flag ('#');
986 int len = tree_digits (arg, base, maybesign, maybebase);
988 if (len < prec)
989 len = prec;
991 if (len < width)
992 len = width;
994 res.range.max = len;
995 res.range.min = res.range.max;
996 res.bounded = true;
998 return res;
1000 else if (TREE_CODE (TREE_TYPE (arg)) == INTEGER_TYPE
1001 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1003 /* Determine the type of the provided non-constant argument. */
1004 if (TREE_CODE (arg) == NOP_EXPR)
1005 arg = TREE_OPERAND (arg, 0);
1006 else if (TREE_CODE (arg) == CONVERT_EXPR)
1007 arg = TREE_OPERAND (arg, 0);
1008 if (TREE_CODE (arg) == COMPONENT_REF)
1009 arg = TREE_OPERAND (arg, 1);
1011 argtype = TREE_TYPE (arg);
1013 else
1015 /* Don't bother with invalid arguments since they likely would
1016 have already been diagnosed, and disable any further checking
1017 of the format string by returning [-1, -1]. */
1018 return fmtresult ();
1021 fmtresult res;
1023 /* Using either the range the non-constant argument is in, or its
1024 type (either "formal" or actual), create a range of values that
1025 constrain the length of output given the warning level. */
1026 tree argmin = NULL_TREE;
1027 tree argmax = NULL_TREE;
1029 if (arg && TREE_CODE (arg) == SSA_NAME
1030 && TREE_CODE (argtype) == INTEGER_TYPE)
1032 /* Try to determine the range of values of the integer argument
1033 (range information is not available for pointers). */
1034 wide_int min, max;
1035 enum value_range_type range_type = get_range_info (arg, &min, &max);
1036 if (range_type == VR_RANGE)
1038 res.argmin = build_int_cst (argtype, wi::fits_uhwi_p (min)
1039 ? min.to_uhwi () : min.to_shwi ());
1040 res.argmax = build_int_cst (argtype, wi::fits_uhwi_p (max)
1041 ? max.to_uhwi () : max.to_shwi ());
1043 /* For a range with a negative lower bound and a non-negative
1044 upper bound, use one to determine the minimum number of bytes
1045 on output and whichever of the two bounds that results in
1046 the greater number of bytes on output for the upper bound.
1047 For example, for ARG in the range of [-3, 123], use 123 as
1048 the upper bound for %i but -3 for %u. */
1049 if (wi::neg_p (min) && !wi::neg_p (max))
1051 argmin = build_int_cst (argtype, wi::fits_uhwi_p (min)
1052 ? min.to_uhwi () : min.to_shwi ());
1054 argmax = build_int_cst (argtype, wi::fits_uhwi_p (max)
1055 ? max.to_uhwi () : max.to_shwi ());
1057 int minbytes = format_integer (spec, res.argmin).range.min;
1058 int maxbytes = format_integer (spec, res.argmax).range.max;
1059 if (maxbytes < minbytes)
1060 argmax = res.argmin;
1062 argmin = integer_zero_node;
1064 else
1066 argmin = res.argmin;
1067 argmax = res.argmax;
1070 /* The argument is bounded by the known range of values
1071 determined by Value Range Propagation. */
1072 res.bounded = true;
1073 res.knownrange = true;
1075 else if (range_type == VR_ANTI_RANGE)
1077 /* Handle anti-ranges if/when bug 71690 is resolved. */
1079 else if (range_type == VR_VARYING)
1081 /* The argument here may be the result of promoting the actual
1082 argument to int. Try to determine the type of the actual
1083 argument before promotion and narrow down its range that
1084 way. */
1085 gimple *def = SSA_NAME_DEF_STMT (arg);
1086 if (is_gimple_assign (def))
1088 tree_code code = gimple_assign_rhs_code (def);
1089 if (code == INTEGER_CST)
1091 arg = gimple_assign_rhs1 (def);
1092 return format_integer (spec, arg);
1095 if (code == NOP_EXPR)
1096 argtype = TREE_TYPE (gimple_assign_rhs1 (def));
1101 if (!argmin)
1103 /* For an unknown argument (e.g., one passed to a vararg function)
1104 or one whose value range cannot be determined, create a T_MIN
1105 constant if the argument's type is signed and T_MAX otherwise,
1106 and use those to compute the range of bytes that the directive
1107 can output. */
1108 argmin = build_int_cst (argtype, 1);
1110 int typeprec = TYPE_PRECISION (dirtype);
1111 int argprec = TYPE_PRECISION (argtype);
1113 if (argprec < typeprec || POINTER_TYPE_P (argtype))
1115 if (TYPE_UNSIGNED (argtype))
1116 argmax = build_all_ones_cst (argtype);
1117 else
1118 argmax = fold_build2 (LSHIFT_EXPR, argtype, integer_one_node,
1119 build_int_cst (integer_type_node,
1120 argprec - 1));
1122 else
1124 argmax = fold_build2 (LSHIFT_EXPR, dirtype, integer_one_node,
1125 build_int_cst (integer_type_node,
1126 typeprec - 1));
1128 res.argmin = argmin;
1129 res.argmax = argmax;
1132 /* Recursively compute the minimum and maximum from the known range,
1133 taking care to swap them if the lower bound results in longer
1134 output than the upper bound (e.g., in the range [-1, 0]. */
1135 res.range.min = format_integer (spec, argmin).range.min;
1136 res.range.max = format_integer (spec, argmax).range.max;
1138 /* The result is bounded either when the argument is determined to be
1139 (e.g., when it's within some range) or when the minimum and maximum
1140 are the same. That can happen here for example when the specified
1141 width is as wide as the greater of MIN and MAX, as would be the case
1142 with sprintf (d, "%08x", x) with a 32-bit integer x. */
1143 res.bounded |= res.range.min == res.range.max;
1145 if (res.range.max < res.range.min)
1147 unsigned HOST_WIDE_INT tmp = res.range.max;
1148 res.range.max = res.range.min;
1149 res.range.min = tmp;
1152 return res;
1155 /* Return the number of bytes to format using the format specifier
1156 SPEC the largest value in the real floating TYPE. */
1158 static int
1159 format_floating_max (tree type, char spec, int prec = -1)
1161 machine_mode mode = TYPE_MODE (type);
1163 /* IBM Extended mode. */
1164 if (MODE_COMPOSITE_P (mode))
1165 mode = DFmode;
1167 /* Get the real type format desription for the target. */
1168 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1169 REAL_VALUE_TYPE rv;
1172 char buf[256];
1173 get_max_float (rfmt, buf, sizeof buf);
1174 real_from_string (&rv, buf);
1177 /* Convert the GCC real value representation with the precision
1178 of the real type to the mpfr_t format with the GCC default
1179 round-to-nearest mode. */
1180 mpfr_t x;
1181 mpfr_init2 (x, rfmt->p);
1182 mpfr_from_real (x, &rv, GMP_RNDN);
1184 int n;
1186 if (-1 < prec)
1188 const char fmt[] = { '%', '.', '*', 'R', spec, '\0' };
1189 n = mpfr_snprintf (NULL, 0, fmt, prec, x);
1191 else
1193 const char fmt[] = { '%', 'R', spec, '\0' };
1194 n = mpfr_snprintf (NULL, 0, fmt, x);
1197 /* Return a value one greater to account for the leading minus sign. */
1198 return n + 1;
1201 /* Return a range representing the minimum and maximum number of bytes
1202 that the conversion specification SPEC will output for any argument
1203 given the WIDTH and PRECISION (extracted from SPEC). This function
1204 is used when the directive argument or its value isn't known. */
1206 static fmtresult
1207 format_floating (const conversion_spec &spec, int width, int prec)
1209 tree type;
1210 bool ldbl = false;
1212 switch (spec.modifier)
1214 case FMT_LEN_l:
1215 case FMT_LEN_none:
1216 type = double_type_node;
1217 break;
1219 case FMT_LEN_L:
1220 type = long_double_type_node;
1221 ldbl = true;
1222 break;
1224 case FMT_LEN_ll:
1225 type = long_double_type_node;
1226 ldbl = true;
1227 break;
1229 default:
1230 return fmtresult ();
1233 /* The minimum and maximum number of bytes produced by the directive. */
1234 fmtresult res;
1236 /* Log10 of of the maximum number of exponent digits for the type. */
1237 int logexpdigs = 2;
1239 if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
1241 /* The base in which the exponent is represented should always
1242 be 2 in GCC. */
1244 const double log10_2 = .30102999566398119521;
1246 /* Compute T_MAX_EXP for base 2. */
1247 int expdigs = REAL_MODE_FORMAT (TYPE_MODE (type))->emax * log10_2;
1248 logexpdigs = ilog (expdigs, 10);
1251 switch (spec.specifier)
1253 case 'A':
1254 case 'a':
1256 /* The minimum output is "0x.p+0". */
1257 res.range.min = 6 + (prec > 0 ? prec : 0);
1258 res.range.max = format_floating_max (type, 'a', prec);
1260 /* The output of "%a" is fully specified only when precision
1261 is explicitly specified. */
1262 res.bounded = -1 < prec;
1263 break;
1266 case 'E':
1267 case 'e':
1269 bool sign = spec.get_flag ('+') || spec.get_flag (' ');
1270 /* The minimum output is "[-+]1.234567e+00" regardless
1271 of the value of the actual argument. */
1272 res.range.min = (sign
1273 + 1 /* unit */ + (prec < 0 ? 7 : prec ? prec + 1 : 0)
1274 + 2 /* e+ */ + 2);
1275 /* The maximum output is the minimum plus sign (unless already
1276 included), plus the difference between the minimum exponent
1277 of 2 and the maximum exponent for the type. */
1278 res.range.max = res.range.min + !sign + logexpdigs - 2;
1280 /* "%e" is fully specified and the range of bytes is bounded. */
1281 res.bounded = true;
1282 break;
1285 case 'F':
1286 case 'f':
1288 /* The minimum output is "1.234567" regardless of the value
1289 of the actual argument. */
1290 res.range.min = 2 + (prec < 0 ? 6 : prec);
1292 /* Compute the maximum just once. */
1293 static const int f_max[] = {
1294 format_floating_max (double_type_node, 'f'),
1295 format_floating_max (long_double_type_node, 'f')
1297 res.range.max = f_max [ldbl];
1299 /* "%f" is fully specified and the range of bytes is bounded. */
1300 res.bounded = true;
1301 break;
1303 case 'G':
1304 case 'g':
1306 /* The minimum is the same as for '%F'. */
1307 res.range.min = 2 + (prec < 0 ? 6 : prec);
1309 /* Compute the maximum just once. */
1310 static const int g_max[] = {
1311 format_floating_max (double_type_node, 'g'),
1312 format_floating_max (long_double_type_node, 'g')
1314 res.range.max = g_max [ldbl];
1316 /* "%g" is fully specified and the range of bytes is bounded. */
1317 res.bounded = true;
1318 break;
1321 default:
1322 return fmtresult ();
1325 if (width > 0)
1327 if (res.range.min < (unsigned)width)
1328 res.range.min = width;
1329 if (res.range.max < (unsigned)width)
1330 res.range.max = width;
1333 return res;
1336 /* Return a range representing the minimum and maximum number of bytes
1337 that the conversion specification SPEC will write on output for the
1338 floating argument ARG. */
1340 static fmtresult
1341 format_floating (const conversion_spec &spec, tree arg)
1343 int width = -1;
1344 int prec = -1;
1346 /* The minimum and maximum number of bytes produced by the directive. */
1347 fmtresult res;
1348 res.constant = arg && TREE_CODE (arg) == REAL_CST;
1350 if (spec.have_width)
1351 width = spec.width;
1352 else if (spec.star_width)
1354 if (TREE_CODE (spec.star_width) == INTEGER_CST)
1355 width = tree_to_shwi (spec.star_width);
1356 else
1358 res.range.min = res.range.max = HOST_WIDE_INT_M1U;
1359 return res;
1363 if (spec.have_precision)
1364 prec = spec.precision;
1365 else if (spec.star_precision)
1367 if (TREE_CODE (spec.star_precision) == INTEGER_CST)
1368 prec = tree_to_shwi (spec.star_precision);
1369 else
1371 res.range.min = res.range.max = HOST_WIDE_INT_M1U;
1372 return res;
1375 else if (res.constant && TOUPPER (spec.specifier) != 'A')
1377 /* Specify the precision explicitly since mpfr_sprintf defaults
1378 to zero. */
1379 prec = 6;
1382 if (res.constant)
1384 /* Set up an array to easily iterate over. */
1385 unsigned HOST_WIDE_INT* const minmax[] = {
1386 &res.range.min, &res.range.max
1389 /* Get the real type format desription for the target. */
1390 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1391 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1393 /* Convert the GCC real value representation with the precision
1394 of the real type to the mpfr_t format with the GCC default
1395 round-to-nearest mode. */
1396 mpfr_t mpfrval;
1397 mpfr_init2 (mpfrval, rfmt->p);
1398 mpfr_from_real (mpfrval, rvp, GMP_RNDN);
1400 char fmtstr [40];
1401 char *pfmt = fmtstr;
1402 *pfmt++ = '%';
1404 /* Append flags. */
1405 for (const char *pf = "-+ #0"; *pf; ++pf)
1406 if (spec.get_flag (*pf))
1407 *pfmt++ = *pf;
1409 /* Append width when specified and precision. */
1410 if (width != -1)
1411 pfmt += sprintf (pfmt, "%i", width);
1412 if (prec != -1)
1413 pfmt += sprintf (pfmt, ".%i", prec);
1415 /* Append the MPFR 'R' floating type specifier (no length modifier
1416 is necessary or allowed by MPFR for mpfr_t values). */
1417 *pfmt++ = 'R';
1419 /* Save the position of the MPFR rounding specifier and skip over
1420 it. It will be set in each iteration in the loop below. */
1421 char* const rndspec = pfmt++;
1423 /* Append the C type specifier and nul-terminate. */
1424 *pfmt++ = spec.specifier;
1425 *pfmt = '\0';
1427 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1429 /* Use the MPFR rounding specifier to round down in the first
1430 iteration and then up. In most but not all cases this will
1431 result in the same number of bytes. */
1432 *rndspec = "DU"[i];
1434 /* Format it and store the result in the corresponding
1435 member of the result struct. */
1436 *minmax[i] = mpfr_snprintf (NULL, 0, fmtstr, mpfrval);
1439 /* The output of all directives except "%a" is fully specified
1440 and so the result is bounded unless it exceeds INT_MAX.
1441 For "%a" the output is fully specified only when precision
1442 is explicitly specified. */
1443 res.bounded = ((TOUPPER (spec.specifier) != 'A'
1444 || (0 <= prec && (unsigned) prec < target_int_max ()))
1445 && res.range.min < target_int_max ());
1447 /* The range of output is known even if the result isn't bounded. */
1448 res.knownrange = true;
1449 return res;
1452 return format_floating (spec, width, prec);
1455 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1456 strings referenced by the expression STR, or (-1, -1) when not known.
1457 Used by the format_string function below. */
1459 static fmtresult
1460 get_string_length (tree str)
1462 if (!str)
1463 return fmtresult ();
1465 if (tree slen = c_strlen (str, 1))
1467 /* Simply return the length of the string. */
1468 fmtresult res;
1469 res.range.min = res.range.max = tree_to_shwi (slen);
1470 res.bounded = true;
1471 res.constant = true;
1472 res.knownrange = true;
1473 return res;
1476 /* Determine the length of the shortest and longest string referenced
1477 by STR. Strings of unknown lengths are bounded by the sizes of
1478 arrays that subexpressions of STR may refer to. Pointers that
1479 aren't known to point any such arrays result in LENRANGE[1] set
1480 to SIZE_MAX. */
1481 tree lenrange[2];
1482 get_range_strlen (str, lenrange);
1484 if (lenrange [0] || lenrange [1])
1486 fmtresult res;
1488 res.range.min = (tree_fits_uhwi_p (lenrange[0])
1489 ? tree_to_uhwi (lenrange[0]) : 1 < warn_format_length);
1490 res.range.max = (tree_fits_uhwi_p (lenrange[1])
1491 ? tree_to_uhwi (lenrange[1]) : HOST_WIDE_INT_M1U);
1493 /* Set RES.BOUNDED to true if and only if all strings referenced
1494 by STR are known to be bounded (though not necessarily by their
1495 actual length but perhaps by their maximum possible length). */
1496 res.bounded = res.range.max < target_int_max ();
1497 res.knownrange = res.bounded;
1499 /* Set RES.CONSTANT to false even though that may be overly
1500 conservative in rare cases like: 'x ? a : b' where a and
1501 b have the same lengths and consist of the same characters. */
1502 res.constant = false;
1504 return res;
1507 return get_string_length (NULL_TREE);
1510 /* Return the minimum and maximum number of characters formatted
1511 by the '%c' and '%s' format directives and ther wide character
1512 forms for the argument ARG. ARG can be null (for functions
1513 such as vsprinf). */
1515 static fmtresult
1516 format_string (const conversion_spec &spec, tree arg)
1518 unsigned width = spec.have_width && spec.width > 0 ? spec.width : 0;
1519 int prec = spec.have_precision ? spec.precision : -1;
1521 if (spec.star_width)
1523 width = (TREE_CODE (spec.star_width) == INTEGER_CST
1524 ? tree_to_shwi (spec.star_width) : 0);
1525 if (width > INT_MAX)
1526 width = 0;
1529 if (spec.star_precision)
1530 prec = (TREE_CODE (spec.star_precision) == INTEGER_CST
1531 ? tree_to_shwi (spec.star_precision) : -1);
1533 fmtresult res;
1535 /* The maximum number of bytes for an unknown wide character argument
1536 to a "%lc" directive adjusted for precision but not field width.
1537 6 is the longest UTF-8 sequence for a single wide character. */
1538 const unsigned HOST_WIDE_INT max_bytes_for_unknown_wc
1539 = (0 <= prec ? prec : 1 < warn_format_length ? 6 : 1);
1541 /* The maximum number of bytes for an unknown string argument to either
1542 a "%s" or "%ls" directive adjusted for precision but not field width. */
1543 const unsigned HOST_WIDE_INT max_bytes_for_unknown_str
1544 = (0 <= prec ? prec : 1 < warn_format_length);
1546 /* The result is bounded unless overriddden for a non-constant string
1547 of an unknown length. */
1548 bool bounded = true;
1550 if (spec.specifier == 'c')
1552 if (spec.modifier == FMT_LEN_l)
1554 /* Positive if the argument is a wide NUL character? */
1555 int nul = (arg && TREE_CODE (arg) == INTEGER_CST
1556 ? integer_zerop (arg) : -1);
1558 /* A '%lc' directive is the same as '%ls' for a two element
1559 wide string character with the second element of NUL, so
1560 when the character is unknown the minimum number of bytes
1561 is the smaller of either 0 (at level 1) or 1 (at level 2)
1562 and WIDTH, and the maximum is MB_CUR_MAX in the selected
1563 locale, which is unfortunately, unknown. */
1564 res.range.min = 1 == warn_format_length ? !nul : nul < 1;
1565 res.range.max = max_bytes_for_unknown_wc;
1566 /* The range above is good enough to issue warnings but not
1567 for value range propagation, so clear BOUNDED. */
1568 res.bounded = false;
1570 else
1572 /* A plain '%c' directive. Its ouput is exactly 1. */
1573 res.range.min = res.range.max = 1;
1574 res.bounded = true;
1575 res.knownrange = true;
1576 res.constant = arg && TREE_CODE (arg) == INTEGER_CST;
1579 else /* spec.specifier == 's' */
1581 /* Compute the range the argument's length can be in. */
1582 fmtresult slen = get_string_length (arg);
1583 if (slen.constant)
1585 gcc_checking_assert (slen.range.min == slen.range.max);
1587 /* A '%s' directive with a string argument with constant length. */
1588 res.range = slen.range;
1590 /* The output of "%s" and "%ls" directives with a constant
1591 string is in a known range. For "%s" it is the length
1592 of the string. For "%ls" it is in the range [length,
1593 length * MB_LEN_MAX]. (The final range can be further
1594 constrained by width and precision but it's always known.) */
1595 res.knownrange = true;
1597 if (spec.modifier == FMT_LEN_l)
1599 bounded = false;
1601 if (warn_format_length > 1)
1603 /* Leave the minimum number of bytes the wide string
1604 converts to equal to its length and set the maximum
1605 to the worst case length which is the string length
1606 multiplied by MB_LEN_MAX. */
1608 /* It's possible to be smarter about computing the maximum
1609 by scanning the wide string for any 8-bit characters and
1610 if it contains none, using its length for the maximum.
1611 Even though this would be simple to do it's unlikely to
1612 be worth it when dealing with wide characters. */
1613 res.range.max *= target_mb_len_max;
1616 /* For a wide character string, use precision as the maximum
1617 even if precision is greater than the string length since
1618 the number of bytes the string converts to may be greater
1619 (due to MB_CUR_MAX). */
1620 if (0 <= prec)
1621 res.range.max = prec;
1623 else
1625 /* The output od a "%s" directive with a constant argument
1626 is bounded, constant, and obviously in a known range. */
1627 res.bounded = true;
1628 res.constant = true;
1631 if (0 <= prec && (unsigned)prec < res.range.min)
1633 res.range.min = prec;
1634 res.range.max = prec;
1637 else
1639 /* For a '%s' and '%ls' directive with a non-constant string,
1640 the minimum number of characters is the greater of WIDTH
1641 and either 0 in mode 1 or the smaller of PRECISION and 1
1642 in mode 2, and the maximum is PRECISION or -1 to disable
1643 tracking. */
1645 if (0 <= prec)
1647 if (slen.range.min >= target_int_max ())
1648 slen.range.min = 0;
1649 else if ((unsigned)prec < slen.range.min)
1650 slen.range.min = prec;
1652 if ((unsigned)prec < slen.range.max
1653 || slen.range.max >= target_int_max ())
1654 slen.range.max = prec;
1656 else if (slen.range.min >= target_int_max ())
1658 slen.range.min = max_bytes_for_unknown_str;
1659 slen.range.max = max_bytes_for_unknown_str;
1660 bounded = false;
1663 res.range = slen.range;
1665 /* The output is considered bounded when a precision has been
1666 specified to limit the number of bytes or when the number
1667 of bytes is known or contrained to some range. */
1668 res.bounded = 0 <= prec || slen.bounded;
1669 res.knownrange = slen.knownrange;
1670 res.constant = false;
1674 /* Adjust the lengths for field width. */
1675 if (res.range.min < width)
1676 res.range.min = width;
1678 if (res.range.max < width)
1679 res.range.max = width;
1681 /* Adjust BOUNDED if width happens to make them equal. */
1682 if (res.range.min == res.range.max && res.range.min < target_int_max ()
1683 && bounded)
1684 res.bounded = true;
1686 /* When precision is specified the range of characters on output
1687 is known to be bounded by it. */
1688 if (-1 < prec)
1689 res.knownrange = true;
1691 return res;
1694 /* Compute the length of the output resulting from the conversion
1695 specification SPEC with the argument ARG in a call described by INFO
1696 and update the overall result of the call in *RES. The format directive
1697 corresponding to SPEC starts at CVTBEG and is CVTLEN characters long. */
1699 static void
1700 format_directive (const pass_sprintf_length::call_info &info,
1701 format_result *res, const char *cvtbeg, size_t cvtlen,
1702 const conversion_spec &spec, tree arg)
1704 /* Offset of the beginning of the directive from the beginning
1705 of the format string. */
1706 size_t offset = cvtbeg - info.fmtstr;
1708 /* Create a location for the whole directive from the % to the format
1709 specifier. */
1710 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
1711 offset, offset, offset + cvtlen - 1);
1713 /* Also create a location range for the argument if possible.
1714 This doesn't work for integer literals or function calls. */
1715 source_range argrange;
1716 source_range *pargrange;
1717 if (arg && CAN_HAVE_LOCATION_P (arg))
1719 argrange = EXPR_LOCATION_RANGE (arg);
1720 pargrange = &argrange;
1722 else
1723 pargrange = NULL;
1725 /* Bail when there is no function to compute the output length,
1726 or when minimum length checking has been disabled. */
1727 if (!spec.fmtfunc || res->number_chars_min >= HOST_WIDE_INT_MAX)
1728 return;
1730 /* Compute the (approximate) length of the formatted output. */
1731 fmtresult fmtres = spec.fmtfunc (spec, arg);
1733 /* The overall result is bounded and constant only if the output
1734 of every directive is bounded and constant, respectively. */
1735 res->bounded &= fmtres.bounded;
1736 res->constant &= fmtres.constant;
1738 /* Record whether the output of all directives is known to be
1739 bounded by some maximum, implying that their arguments are
1740 either known exactly or determined to be in a known range
1741 or, for strings, limited by the upper bounds of the arrays
1742 they refer to. */
1743 res->knownrange &= fmtres.knownrange;
1745 if (!fmtres.knownrange)
1747 /* Only when the range is known, check it against the host value
1748 of INT_MAX. Otherwise the range doesn't correspond to known
1749 values of the argument. */
1750 if (fmtres.range.max >= target_int_max ())
1752 /* Normalize the MAX counter to avoid having to deal with it
1753 later. The counter can be less than HOST_WIDE_INT_M1U
1754 when compiling for an ILP32 target on an LP64 host. */
1755 fmtres.range.max = HOST_WIDE_INT_M1U;
1756 /* Disable exact and maximum length checking after a failure
1757 to determine the maximum number of characters (for example
1758 for wide characters or wide character strings) but continue
1759 tracking the minimum number of characters. */
1760 res->number_chars_max = HOST_WIDE_INT_M1U;
1761 res->number_chars = HOST_WIDE_INT_M1U;
1764 if (fmtres.range.min >= target_int_max ())
1766 /* Disable exact length checking after a failure to determine
1767 even the minimum number of characters (it shouldn't happen
1768 except in an error) but keep tracking the minimum and maximum
1769 number of characters. */
1770 res->number_chars = HOST_WIDE_INT_M1U;
1771 return;
1775 /* Compute the number of available bytes in the destination. There
1776 must always be at least one byte of space for the terminating
1777 NUL that's appended after the format string has been processed. */
1778 unsigned HOST_WIDE_INT navail = min_bytes_remaining (info.objsize, *res);
1780 if (fmtres.range.min < fmtres.range.max)
1782 /* The result is a range (i.e., it's inexact). */
1783 if (!res->warned)
1785 bool warned = false;
1787 if (navail < fmtres.range.min)
1789 /* The minimum directive output is longer than there is
1790 room in the destination. */
1791 if (fmtres.range.min == fmtres.range.max)
1793 const char* fmtstr
1794 = (info.bounded
1795 ? G_("%<%.*s%> directive output truncated writing "
1796 "%wu bytes into a region of size %wu")
1797 : G_("%<%.*s%> directive writing %wu bytes "
1798 "into a region of size %wu"));
1799 warned = fmtwarn (dirloc, pargrange, NULL,
1800 OPT_Wformat_length_, fmtstr,
1801 (int)cvtlen, cvtbeg, fmtres.range.min,
1802 navail);
1804 else
1806 const char* fmtstr
1807 = (info.bounded
1808 ? G_("%<%.*s%> directive output truncated writing "
1809 "between %wu and %wu bytes into a region of "
1810 "size %wu")
1811 : G_("%<%.*s%> directive writing between %wu and "
1812 "%wu bytes into a region of size %wu"));
1813 warned = fmtwarn (dirloc, pargrange, NULL,
1814 OPT_Wformat_length_, fmtstr,
1815 (int)cvtlen, cvtbeg,
1816 fmtres.range.min, fmtres.range.max, navail);
1819 else if (navail < fmtres.range.max
1820 && (((spec.specifier == 's'
1821 && fmtres.range.max < HOST_WIDE_INT_MAX)
1822 /* && (spec.precision || spec.star_precision) */)
1823 || 1 < warn_format_length))
1825 /* The maximum directive output is longer than there is
1826 room in the destination and the output length is either
1827 explicitly constrained by the precision (for strings)
1828 or the warning level is greater than 1. */
1829 if (fmtres.range.max >= HOST_WIDE_INT_MAX)
1831 const char* fmtstr
1832 = (info.bounded
1833 ? G_("%<%.*s%> directive output may be truncated "
1834 "writing %wu or more bytes a region of size %wu")
1835 : G_("%<%.*s%> directive writing %wu or more bytes "
1836 "into a region of size %wu"));
1837 warned = fmtwarn (dirloc, pargrange, NULL,
1838 OPT_Wformat_length_, fmtstr,
1839 (int)cvtlen, cvtbeg,
1840 fmtres.range.min, navail);
1842 else
1844 const char* fmtstr
1845 = (info.bounded
1846 ? G_("%<%.*s%> directive output may be truncated "
1847 "writing between %wu and %wu bytes into a region "
1848 "of size %wu")
1849 : G_("%<%.*s%> directive writing between %wu and %wu "
1850 "bytes into a region of size %wu"));
1851 warned = fmtwarn (dirloc, pargrange, NULL,
1852 OPT_Wformat_length_, fmtstr,
1853 (int)cvtlen, cvtbeg,
1854 fmtres.range.min, fmtres.range.max,
1855 navail);
1859 res->warned |= warned;
1861 if (warned && fmtres.argmin)
1863 if (fmtres.argmin == fmtres.argmax)
1864 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
1865 else if (fmtres.bounded)
1866 inform (info.fmtloc, "directive argument in the range [%E, %E]",
1867 fmtres.argmin, fmtres.argmax);
1868 else
1869 inform (info.fmtloc,
1870 "using the range [%qE, %qE] for directive argument",
1871 fmtres.argmin, fmtres.argmax);
1875 /* Disable exact length checking but adjust the minimum and maximum. */
1876 res->number_chars = HOST_WIDE_INT_M1U;
1877 if (res->number_chars_max < HOST_WIDE_INT_MAX
1878 && fmtres.range.max < HOST_WIDE_INT_MAX)
1879 res->number_chars_max += fmtres.range.max;
1881 res->number_chars_min += fmtres.range.min;
1883 else
1885 if (!res->warned && fmtres.range.min > 0 && navail < fmtres.range.min)
1887 const char* fmtstr
1888 = (info.bounded
1889 ? (1 < fmtres.range.min
1890 ? G_("%<%.*s%> directive output truncated while writing "
1891 "%wu bytes into a region of size %wu")
1892 : G_("%<%.*s%> directive output truncated while writing "
1893 "%wu byte into a region of size %wu"))
1894 : (1 < fmtres.range.min
1895 ? G_("%<%.*s%> directive writing %wu bytes "
1896 "into a region of size %wu")
1897 : G_("%<%.*s%> directive writing %wu byte "
1898 "into a region of size %wu")));
1900 res->warned = fmtwarn (dirloc, pargrange, NULL,
1901 OPT_Wformat_length_, fmtstr,
1902 (int)cvtlen, cvtbeg, fmtres.range.min,
1903 navail);
1905 *res += fmtres.range.min;
1908 /* Has the minimum directive output length exceeded the maximum
1909 of 4095 bytes required to be supported? */
1910 bool minunder4k = fmtres.range.min < 4096;
1911 if (!minunder4k || fmtres.range.max > 4095)
1912 res->under4k = false;
1914 if (!res->warned && 1 < warn_format_length
1915 && (!minunder4k || fmtres.range.max > 4095))
1917 /* The directive output may be longer than the maximum required
1918 to be handled by an implementation according to 7.21.6.1, p15
1919 of C11. Warn on this only at level 2 but remember this and
1920 prevent folding the return value when done. This allows for
1921 the possibility of the actual libc call failing due to ENOMEM
1922 (like Glibc does under some conditions). */
1924 if (fmtres.range.min == fmtres.range.max)
1925 res->warned = fmtwarn (dirloc, pargrange, NULL,
1926 OPT_Wformat_length_,
1927 "%<%.*s%> directive output of %wu bytes exceeds "
1928 "minimum required size of 4095",
1929 (int)cvtlen, cvtbeg, fmtres.range.min);
1930 else
1932 const char *fmtstr
1933 = (minunder4k
1934 ? G_("%<%.*s%> directive output between %qu and %wu "
1935 "bytes may exceed minimum required size of 4095")
1936 : G_("%<%.*s%> directive output between %qu and %wu "
1937 "bytes exceeds minimum required size of 4095"));
1939 res->warned = fmtwarn (dirloc, pargrange, NULL,
1940 OPT_Wformat_length_, fmtstr,
1941 (int)cvtlen, cvtbeg,
1942 fmtres.range.min, fmtres.range.max);
1946 /* Has the minimum directive output length exceeded INT_MAX? */
1947 bool exceedmin = res->number_chars_min > target_int_max ();
1949 if (!res->warned
1950 && (exceedmin
1951 || (1 < warn_format_length
1952 && res->number_chars_max > target_int_max ())))
1954 /* The directive output causes the total length of output
1955 to exceed INT_MAX bytes. */
1957 if (fmtres.range.min == fmtres.range.max)
1958 res->warned = fmtwarn (dirloc, pargrange, NULL,
1959 OPT_Wformat_length_,
1960 "%<%.*s%> directive output of %wu bytes causes "
1961 "result to exceed %<INT_MAX%>",
1962 (int)cvtlen, cvtbeg, fmtres.range.min);
1963 else
1965 const char *fmtstr
1966 = (exceedmin
1967 ? G_ ("%<%.*s%> directive output between %wu and %wu "
1968 "bytes causes result to exceed %<INT_MAX%>")
1969 : G_ ("%<%.*s%> directive output between %wu and %wu "
1970 "bytes may cause result to exceed %<INT_MAX%>"));
1971 res->warned = fmtwarn (dirloc, pargrange, NULL,
1972 OPT_Wformat_length_, fmtstr,
1973 (int)cvtlen, cvtbeg,
1974 fmtres.range.min, fmtres.range.max);
1979 /* Account for the number of bytes between BEG and END (or between
1980 BEG + strlen (BEG) when END is null) in the format string in a call
1981 to a formatted output function described by INFO. Reflect the count
1982 in RES and issue warnings as appropriate. */
1984 static void
1985 add_bytes (const pass_sprintf_length::call_info &info,
1986 const char *beg, const char *end, format_result *res)
1988 if (res->number_chars_min >= HOST_WIDE_INT_MAX)
1989 return;
1991 /* The number of bytes to output is the number of bytes between
1992 the end of the last directive and the beginning of the next
1993 one if it exists, otherwise the number of characters remaining
1994 in the format string plus 1 for the terminating NUL. */
1995 size_t nbytes = end ? end - beg : strlen (beg) + 1;
1997 /* Return if there are no bytes to add at this time but there are
1998 directives remaining in the format string. */
1999 if (!nbytes)
2000 return;
2002 /* Compute the range of available bytes in the destination. There
2003 must always be at least one byte left for the terminating NUL
2004 that's appended after the format string has been processed. */
2005 result_range avail_range = bytes_remaining (info.objsize, *res);
2007 /* If issuing a diagnostic (only when one hasn't already been issued),
2008 distinguish between a possible overflow ("may write") and a certain
2009 overflow somewhere "past the end." (Ditto for truncation.)
2010 KNOWNRANGE is used to warn even at level 1 about possibly writing
2011 past the end or truncation due to strings of unknown lengths that
2012 are bounded by the arrays they are known to refer to. */
2013 if (!res->warned
2014 && (avail_range.max < nbytes
2015 || ((res->knownrange || 1 < warn_format_length)
2016 && avail_range.min < nbytes)))
2018 /* Set NAVAIL to the number of available bytes used to decide
2019 whether or not to issue a warning below. The exact kind of
2020 warning will depend on AVAIL_RANGE. */
2021 unsigned HOST_WIDE_INT navail = avail_range.max;
2022 if (nbytes <= navail && avail_range.min < HOST_WIDE_INT_MAX
2023 && (res->knownrange || 1 < warn_format_length))
2024 navail = avail_range.min;
2026 /* Compute the offset of the first format character that is beyond
2027 the end of the destination region and the length of the rest of
2028 the format string from that point on. */
2029 unsigned HOST_WIDE_INT off
2030 = (unsigned HOST_WIDE_INT)(beg - info.fmtstr) + navail;
2032 size_t len = strlen (info.fmtstr + off);
2034 /* Create a location that underscores the substring of the format
2035 string that is or may be written past the end (or is or may be
2036 truncated), pointing the caret at the first character of the
2037 substring. */
2038 substring_loc loc
2039 (info.fmtloc, TREE_TYPE (info.format), off, len ? off : 0,
2040 off + len - !!len);
2042 /* Is the output of the last directive the result of the argument
2043 being within a range whose lower bound would fit in the buffer
2044 but the upper bound would not? If so, use the word "may" to
2045 indicate that the overflow/truncation may (but need not) happen. */
2046 bool boundrange
2047 = (res->number_chars_min < res->number_chars_max
2048 && res->number_chars_min < info.objsize);
2050 if (!end && ((nbytes - navail) == 1 || boundrange))
2052 /* There is room for the rest of the format string but none
2053 for the terminating nul. */
2054 const char *text
2055 = (info.bounded // Snprintf and the like.
2056 ? (boundrange
2057 ? G_("output may be truncated before the last format character"
2058 : "output truncated before the last format character"))
2059 : (boundrange
2060 ? G_("may write a terminating nul past the end "
2061 "of the destination")
2062 : G_("writing a terminating nul past the end "
2063 "of the destination")));
2065 res->warned = fmtwarn (loc, NULL, NULL, OPT_Wformat_length_, text);
2067 else
2069 /* There isn't enough room for 1 or more characters that remain
2070 to copy from the format string. */
2071 const char *text
2072 = (info.bounded // Snprintf and the like.
2073 ? (boundrange
2074 ? G_("output may be truncated at or before format character "
2075 "%qc at offset %wu")
2076 : G_("output truncated at format character %qc at offset %wu"))
2077 : (res->number_chars >= HOST_WIDE_INT_MAX
2078 ? G_("may write format character %#qc at offset %wu past "
2079 "the end of the destination")
2080 : G_("writing format character %#qc at offset %wu past "
2081 "the end of the destination")));
2083 res->warned = fmtwarn (loc, NULL, NULL, OPT_Wformat_length_,
2084 text, info.fmtstr[off], off);
2088 if (res->warned && !end && info.objsize < HOST_WIDE_INT_MAX)
2090 /* If a warning has been issued for buffer overflow or truncation
2091 (but not otherwise) help the user figure out how big a buffer
2092 they need. */
2094 location_t callloc = gimple_location (info.callstmt);
2096 unsigned HOST_WIDE_INT min = res->number_chars_min;
2097 unsigned HOST_WIDE_INT max = res->number_chars_max;
2098 unsigned HOST_WIDE_INT exact
2099 = (res->number_chars < HOST_WIDE_INT_MAX
2100 ? res->number_chars : res->number_chars_min);
2102 if (min < max && max < HOST_WIDE_INT_MAX)
2103 inform (callloc,
2104 "format output between %wu and %wu bytes into "
2105 "a destination of size %wu",
2106 min + nbytes, max + nbytes, info.objsize);
2107 else
2108 inform (callloc,
2109 (nbytes + exact == 1
2110 ? G_("format output %wu byte into a destination of size %wu")
2111 : G_("format output %wu bytes into a destination of size %wu")),
2112 nbytes + exact, info.objsize);
2115 /* Add the number of bytes and then check for INT_MAX overflow. */
2116 *res += nbytes;
2118 /* Has the minimum output length minus the terminating nul exceeded
2119 INT_MAX? */
2120 bool exceedmin = (res->number_chars_min - !end) > target_int_max ();
2122 if (!res->warned
2123 && (exceedmin
2124 || (1 < warn_format_length
2125 && (res->number_chars_max - !end) > target_int_max ())))
2127 /* The function's output exceeds INT_MAX bytes. */
2129 /* Set NAVAIL to the number of available bytes used to decide
2130 whether or not to issue a warning below. The exact kind of
2131 warning will depend on AVAIL_RANGE. */
2132 unsigned HOST_WIDE_INT navail = avail_range.max;
2133 if (nbytes <= navail && avail_range.min < HOST_WIDE_INT_MAX
2134 && (res->bounded || 1 < warn_format_length))
2135 navail = avail_range.min;
2137 /* Compute the offset of the first format character that is beyond
2138 the end of the destination region and the length of the rest of
2139 the format string from that point on. */
2140 unsigned HOST_WIDE_INT off = (unsigned HOST_WIDE_INT)(beg - info.fmtstr);
2141 if (navail < HOST_WIDE_INT_MAX)
2142 off += navail;
2144 size_t len = strlen (info.fmtstr + off);
2146 substring_loc loc
2147 (info.fmtloc, TREE_TYPE (info.format), off - !len, len ? off : 0,
2148 off + len - !!len);
2150 if (res->number_chars_min == res->number_chars_max)
2151 res->warned = fmtwarn (loc, NULL, NULL,
2152 OPT_Wformat_length_,
2153 "output of %wu bytes causes "
2154 "result to exceed %<INT_MAX%>",
2155 res->number_chars_min - !end);
2156 else
2158 const char *text
2159 = (exceedmin
2160 ? G_ ("output between %wu and %wu bytes causes "
2161 "result to exceed %<INT_MAX%>")
2162 : G_ ("output between %wu and %wu bytes may cause "
2163 "result to exceed %<INT_MAX%>"));
2164 res->warned = fmtwarn (loc, NULL, NULL, OPT_Wformat_length_,
2165 text,
2166 res->number_chars_min - !end,
2167 res->number_chars_max - !end);
2172 #pragma GCC diagnostic pop
2174 /* Compute the length of the output resulting from the call to a formatted
2175 output function described by INFO and store the result of the call in
2176 *RES. Issue warnings for detected past the end writes. */
2178 void
2179 pass_sprintf_length::compute_format_length (const call_info &info,
2180 format_result *res)
2182 /* The variadic argument counter. */
2183 unsigned argno = info.argidx;
2185 /* Reset exact, minimum, and maximum character counters. */
2186 res->number_chars = res->number_chars_min = res->number_chars_max = 0;
2188 /* No directive has been seen yet so the length of output is bounded
2189 by the known range [0, 0] and constant (with no conversion producing
2190 more than 4K bytes) until determined otherwise. */
2191 res->bounded = true;
2192 res->knownrange = true;
2193 res->constant = true;
2194 res->under4k = true;
2195 res->floating = false;
2196 res->warned = false;
2198 const char *pf = info.fmtstr;
2200 for ( ; ; )
2202 /* The beginning of the next format directive. */
2203 const char *dir = strchr (pf, '%');
2205 /* Add the number of bytes between the end of the last directive
2206 and either the next if one exists, or the end of the format
2207 string. */
2208 add_bytes (info, pf, dir, res);
2210 if (!dir)
2211 break;
2213 pf = dir + 1;
2215 if (0 && *pf == 0)
2217 /* Incomplete directive. */
2218 return;
2221 conversion_spec spec = conversion_spec ();
2223 /* POSIX numbered argument index or zero when none. */
2224 unsigned dollar = 0;
2226 if (ISDIGIT (*pf))
2228 /* This could be either a POSIX positional argument, the '0'
2229 flag, or a width, depending on what follows. Store it as
2230 width and sort it out later after the next character has
2231 been seen. */
2232 char *end;
2233 spec.width = strtol (pf, &end, 10);
2234 spec.have_width = true;
2235 pf = end;
2237 else if ('*' == *pf)
2239 /* Similarly to the block above, this could be either a POSIX
2240 positional argument or a width, depending on what follows. */
2241 if (argno < gimple_call_num_args (info.callstmt))
2242 spec.star_width = gimple_call_arg (info.callstmt, argno++);
2243 else
2244 return;
2245 ++pf;
2248 if (*pf == '$')
2250 /* Handle the POSIX dollar sign which references the 1-based
2251 positional argument number. */
2252 if (spec.have_width)
2253 dollar = spec.width + info.argidx;
2254 else if (spec.star_width
2255 && TREE_CODE (spec.star_width) == INTEGER_CST)
2256 dollar = spec.width + tree_to_shwi (spec.star_width);
2258 /* Bail when the numbered argument is out of range (it will
2259 have already been diagnosed by -Wformat). */
2260 if (dollar == 0
2261 || dollar == info.argidx
2262 || dollar > gimple_call_num_args (info.callstmt))
2263 return;
2265 --dollar;
2267 spec.star_width = NULL_TREE;
2268 spec.have_width = false;
2269 ++pf;
2272 if (dollar || !spec.star_width)
2274 if (spec.have_width && spec.width == 0)
2276 /* The '0' that has been interpreted as a width above is
2277 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
2278 and continue processing other flags. */
2279 spec.have_width = false;
2280 spec.set_flag ('0');
2282 /* When either '$' has been seen, or width has not been seen,
2283 the next field is the optional flags followed by an optional
2284 width. */
2285 for ( ; ; ) {
2286 switch (*pf)
2288 case ' ':
2289 case '0':
2290 case '+':
2291 case '-':
2292 case '#':
2293 spec.set_flag (*pf++);
2294 break;
2296 default:
2297 goto start_width;
2301 start_width:
2302 if (ISDIGIT (*pf))
2304 char *end;
2305 spec.width = strtol (pf, &end, 10);
2306 spec.have_width = true;
2307 pf = end;
2309 else if ('*' == *pf)
2311 spec.star_width = gimple_call_arg (info.callstmt, argno++);
2312 ++pf;
2314 else if ('\'' == *pf)
2316 /* The POSIX apostrophe indicating a numeric grouping
2317 in the current locale. Even though it's possible to
2318 estimate the upper bound on the size of the output
2319 based on the number of digits it probably isn't worth
2320 continuing. */
2321 return;
2325 if ('.' == *pf)
2327 ++pf;
2329 if (ISDIGIT (*pf))
2331 char *end;
2332 spec.precision = strtol (pf, &end, 10);
2333 spec.have_precision = true;
2334 pf = end;
2336 else if ('*' == *pf)
2338 spec.star_precision = gimple_call_arg (info.callstmt, argno++);
2339 ++pf;
2341 else
2342 return;
2345 switch (*pf)
2347 case 'h':
2348 if (pf[1] == 'h')
2350 ++pf;
2351 spec.modifier = FMT_LEN_hh;
2353 else
2354 spec.modifier = FMT_LEN_h;
2355 ++pf;
2356 break;
2358 case 'j':
2359 spec.modifier = FMT_LEN_j;
2360 ++pf;
2361 break;
2363 case 'L':
2364 spec.modifier = FMT_LEN_L;
2365 ++pf;
2366 break;
2368 case 'l':
2369 if (pf[1] == 'l')
2371 ++pf;
2372 spec.modifier = FMT_LEN_ll;
2374 else
2375 spec.modifier = FMT_LEN_l;
2376 ++pf;
2377 break;
2379 case 't':
2380 spec.modifier = FMT_LEN_t;
2381 ++pf;
2382 break;
2384 case 'z':
2385 spec.modifier = FMT_LEN_z;
2386 ++pf;
2387 break;
2390 switch (*pf)
2392 /* Handle a sole '%' character the same as "%%" but since it's
2393 undefined prevent the result from being folded. */
2394 case '\0':
2395 --pf;
2396 res->bounded = false;
2397 /* FALLTHRU */
2398 case '%':
2399 spec.fmtfunc = format_percent;
2400 break;
2402 case 'a':
2403 case 'A':
2404 case 'e':
2405 case 'E':
2406 case 'f':
2407 case 'F':
2408 case 'g':
2409 case 'G':
2410 res->floating = true;
2411 spec.fmtfunc = format_floating;
2412 break;
2414 case 'd':
2415 case 'i':
2416 case 'o':
2417 case 'u':
2418 case 'x':
2419 case 'X':
2420 spec.fmtfunc = format_integer;
2421 break;
2423 case 'p':
2424 spec.fmtfunc = format_pointer;
2425 break;
2427 case 'n':
2428 return;
2430 case 'c':
2431 case 'S':
2432 case 's':
2433 spec.fmtfunc = format_string;
2434 break;
2436 default:
2437 return;
2440 spec.specifier = *pf++;
2442 /* Compute the length of the format directive. */
2443 size_t dirlen = pf - dir;
2445 /* Extract the argument if the directive takes one and if it's
2446 available (e.g., the function doesn't take a va_list). Treat
2447 missing arguments the same as va_list, even though they will
2448 have likely already been diagnosed by -Wformat. */
2449 tree arg = NULL_TREE;
2450 if (spec.specifier != '%'
2451 && argno < gimple_call_num_args (info.callstmt))
2452 arg = gimple_call_arg (info.callstmt, dollar ? dollar : argno++);
2454 ::format_directive (info, res, dir, dirlen, spec, arg);
2458 /* Return the size of the object referenced by the expression DEST if
2459 available, or -1 otherwise. */
2461 static unsigned HOST_WIDE_INT
2462 get_destination_size (tree dest)
2464 /* Use __builtin_object_size to determine the size of the destination
2465 object. When optimizing, determine the smallest object (such as
2466 a member array as opposed to the whole enclosing object), otherwise
2467 use type-zero object size to determine the size of the enclosing
2468 object (the function fails without optimization in this type). */
2469 int ost = optimize > 0;
2470 unsigned HOST_WIDE_INT size;
2471 if (compute_builtin_object_size (dest, ost, &size))
2472 return size;
2474 return HOST_WIDE_INT_M1U;
2477 /* Given a suitable result RES of a call to a formatted output function
2478 described by INFO, substitute the result for the return value of
2479 the call. The result is suitable if the number of bytes it represents
2480 is known and exact. A result that isn't suitable for substitution may
2481 have its range set to the range of return values, if that is known. */
2483 static void
2484 try_substitute_return_value (gimple_stmt_iterator gsi,
2485 const pass_sprintf_length::call_info &info,
2486 const format_result &res)
2488 tree lhs = gimple_get_lhs (info.callstmt);
2490 /* Avoid the return value optimization when the behavior of the call
2491 is undefined either because any directive may have produced 4K or
2492 more of output, or the return value exceeds INT_MAX, or because
2493 the output overflows the destination object (but leave it enabled
2494 when the function is bounded because then the behavior is well-
2495 defined). */
2496 if (lhs && res.bounded && res.under4k
2497 && (info.bounded || res.number_chars <= info.objsize)
2498 && res.number_chars - 1 <= target_int_max ())
2500 /* Replace the left-hand side of the call with the constant
2501 result of the formatted function minus 1 for the terminating
2502 NUL which the functions' return value does not include. */
2503 gimple_call_set_lhs (info.callstmt, NULL_TREE);
2504 tree cst = build_int_cst (integer_type_node, res.number_chars - 1);
2505 gimple *g = gimple_build_assign (lhs, cst);
2506 gsi_insert_after (&gsi, g, GSI_NEW_STMT);
2507 update_stmt (info.callstmt);
2509 if (dump_file)
2511 location_t callloc = gimple_location (info.callstmt);
2512 fprintf (dump_file, "On line %i substituting ",
2513 LOCATION_LINE (callloc));
2514 print_generic_expr (dump_file, cst, dump_flags);
2515 fprintf (dump_file, " for ");
2516 print_generic_expr (dump_file, info.func, dump_flags);
2517 fprintf (dump_file, " return value (output %s).\n",
2518 res.constant ? "constant" : "variable");
2521 else
2523 unsigned HOST_WIDE_INT maxbytes;
2525 if (lhs
2526 && res.bounded
2527 && ((maxbytes = res.number_chars - 1) <= target_int_max ()
2528 || (res.number_chars_min - 1 <= target_int_max ()
2529 && (maxbytes = res.number_chars_max - 1) <= target_int_max ()))
2530 && (info.bounded || maxbytes < info.objsize))
2532 /* If the result is in a valid range bounded by the size of
2533 the destination set it so that it can be used for subsequent
2534 optimizations. */
2535 int prec = TYPE_PRECISION (integer_type_node);
2537 if (res.number_chars < target_int_max () && res.under4k)
2539 wide_int num = wi::shwi (res.number_chars - 1, prec);
2540 set_range_info (lhs, VR_RANGE, num, num);
2542 else if (res.number_chars_min < target_int_max ()
2543 && res.number_chars_max < target_int_max ())
2545 wide_int min = wi::shwi (res.under4k ? res.number_chars_min - 1
2546 : target_int_min (), prec);
2547 wide_int max = wi::shwi (res.number_chars_max - 1, prec);
2548 set_range_info (lhs, VR_RANGE, min, max);
2552 if (dump_file)
2554 const char *inbounds
2555 = (res.number_chars_min <= info.objsize
2556 ? (res.number_chars_max <= info.objsize
2557 ? "in" : "potentially out-of")
2558 : "out-of");
2560 location_t callloc = gimple_location (info.callstmt);
2561 fprintf (dump_file, "On line %i ", LOCATION_LINE (callloc));
2562 print_generic_expr (dump_file, info.func, dump_flags);
2564 const char *ign = lhs ? "" : " ignored";
2565 if (res.number_chars >= HOST_WIDE_INT_MAX)
2566 fprintf (dump_file,
2567 " %s-bounds return value in range [%lu, %lu]%s.\n",
2568 inbounds,
2569 (unsigned long)res.number_chars_min,
2570 (unsigned long)res.number_chars_max, ign);
2571 else
2572 fprintf (dump_file, " %s-bounds return value %lu%s.\n",
2573 inbounds, (unsigned long)res.number_chars, ign);
2578 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
2579 functions and if so, handle it. */
2581 void
2582 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator gsi)
2584 call_info info = call_info ();
2586 info.callstmt = gsi_stmt (gsi);
2587 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
2588 return;
2590 info.func = gimple_call_fndecl (info.callstmt);
2591 info.fncode = DECL_FUNCTION_CODE (info.func);
2593 /* The size of the destination as in snprintf(dest, size, ...). */
2594 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
2596 /* The size of the destination determined by __builtin_object_size. */
2597 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
2599 /* Buffer size argument number (snprintf and vsnprintf). */
2600 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
2602 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
2603 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
2605 /* Format string argument number (valid for all functions). */
2606 unsigned idx_format;
2608 switch (info.fncode)
2610 case BUILT_IN_SPRINTF:
2611 // Signature:
2612 // __builtin_sprintf (dst, format, ...)
2613 idx_format = 1;
2614 info.argidx = 2;
2615 break;
2617 case BUILT_IN_SPRINTF_CHK:
2618 // Signature:
2619 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
2620 idx_objsize = 2;
2621 idx_format = 3;
2622 info.argidx = 4;
2623 break;
2625 case BUILT_IN_SNPRINTF:
2626 // Signature:
2627 // __builtin_snprintf (dst, size, format, ...)
2628 idx_dstsize = 1;
2629 idx_format = 2;
2630 info.argidx = 3;
2631 info.bounded = true;
2632 break;
2634 case BUILT_IN_SNPRINTF_CHK:
2635 // Signature:
2636 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
2637 idx_dstsize = 1;
2638 idx_objsize = 3;
2639 idx_format = 4;
2640 info.argidx = 5;
2641 info.bounded = true;
2642 break;
2644 case BUILT_IN_VSNPRINTF:
2645 // Signature:
2646 // __builtin_vsprintf (dst, size, format, va)
2647 idx_dstsize = 1;
2648 idx_format = 2;
2649 info.argidx = -1;
2650 info.bounded = true;
2651 break;
2653 case BUILT_IN_VSNPRINTF_CHK:
2654 // Signature:
2655 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
2656 idx_dstsize = 1;
2657 idx_objsize = 3;
2658 idx_format = 4;
2659 info.argidx = -1;
2660 info.bounded = true;
2661 break;
2663 case BUILT_IN_VSPRINTF:
2664 // Signature:
2665 // __builtin_vsprintf (dst, format, va)
2666 idx_format = 1;
2667 info.argidx = -1;
2668 break;
2670 case BUILT_IN_VSPRINTF_CHK:
2671 // Signature:
2672 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
2673 idx_format = 3;
2674 idx_objsize = 2;
2675 info.argidx = -1;
2676 break;
2678 default:
2679 return;
2682 info.format = gimple_call_arg (info.callstmt, idx_format);
2684 if (idx_dstsize == HOST_WIDE_INT_M1U)
2686 // For non-bounded functions like sprintf, to determine
2687 // the size of the destination from the object or pointer
2688 // passed to it as the first argument.
2689 dstsize = get_destination_size (gimple_call_arg (info.callstmt, 0));
2691 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
2693 /* For bounded functions try to get the size argument. */
2695 if (TREE_CODE (size) == INTEGER_CST)
2697 dstsize = tree_to_uhwi (size);
2698 /* No object can be larger than SIZE_MAX bytes (half the address
2699 space) on the target. This imposes a limit that's one byte
2700 less than that. */
2701 if (dstsize >= target_size_max () / 2)
2702 warning_at (gimple_location (info.callstmt), OPT_Wformat_length_,
2703 "specified destination size %wu too large",
2704 dstsize);
2706 else if (TREE_CODE (size) == SSA_NAME)
2708 /* Try to determine the range of values of the argument
2709 and use the greater of the two at -Wformat-level 1 and
2710 the smaller of them at level 2. */
2711 wide_int min, max;
2712 enum value_range_type range_type
2713 = get_range_info (size, &min, &max);
2714 if (range_type == VR_RANGE)
2716 dstsize
2717 = (warn_format_length < 2
2718 ? wi::fits_uhwi_p (max) ? max.to_uhwi () : max.to_shwi ()
2719 : wi::fits_uhwi_p (min) ? min.to_uhwi () : min.to_shwi ());
2724 if (idx_objsize != HOST_WIDE_INT_M1U)
2726 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
2727 if (tree_fits_uhwi_p (size))
2728 objsize = tree_to_uhwi (size);
2731 if (info.bounded && !dstsize)
2733 /* As a special case, when the explicitly specified destination
2734 size argument (to a bounded function like snprintf) is zero
2735 it is a request to determine the number of bytes on output
2736 without actually producing any. Pretend the size is
2737 unlimited in this case. */
2738 info.objsize = HOST_WIDE_INT_MAX;
2740 else
2742 /* Set the object size to the smaller of the two arguments
2743 of both have been specified and they're not equal. */
2744 info.objsize = dstsize < objsize ? dstsize : objsize;
2746 if (info.bounded
2747 && dstsize < target_size_max () / 2 && objsize < dstsize)
2749 warning_at (gimple_location (info.callstmt), OPT_Wformat_length_,
2750 "specified size %wu exceeds the size %wu "
2751 "of the destination object", dstsize, objsize);
2755 if (integer_zerop (info.format))
2757 /* This is diagnosed with -Wformat only when the null is a constant
2758 pointer. The warning here diagnoses instances where the pointer
2759 is not constant. */
2760 warning_at (EXPR_LOC_OR_LOC (info.format, input_location),
2761 OPT_Wformat_length_, "null format string");
2762 return;
2765 info.fmtstr = get_format_string (info.format, &info.fmtloc);
2766 if (!info.fmtstr)
2767 return;
2769 /* The result is the number of bytes output by the formatted function,
2770 including the terminating NUL. */
2771 format_result res = format_result ();
2772 compute_format_length (info, &res);
2774 /* When optimizing and the printf return value optimization is enabled,
2775 attempt to substitute the computed result for the return value of
2776 the call. Avoid this optimization when -frounding-math is in effect
2777 and the format string contains a floating point directive. */
2778 if (optimize > 0
2779 && flag_printf_return_value
2780 && (!flag_rounding_math || !res.floating))
2781 try_substitute_return_value (gsi, info, res);
2784 /* Execute the pass for function FUN. */
2786 unsigned int
2787 pass_sprintf_length::execute (function *fun)
2789 basic_block bb;
2790 FOR_EACH_BB_FN (bb, fun)
2792 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
2793 gsi_next (&si))
2795 /* Iterate over statements, looking for function calls. */
2796 gimple *stmt = gsi_stmt (si);
2798 if (is_gimple_call (stmt))
2799 handle_gimple_call (si);
2803 return 0;
2806 } /* Unnamed namespace. */
2808 /* Return a pointer to a pass object newly constructed from the context
2809 CTXT. */
2811 gimple_opt_pass *
2812 make_pass_sprintf_length (gcc::context *ctxt)
2814 return new pass_sprintf_length (ctxt);