Define arm_arch_core_flags in a single file
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob8de9a1e31d2c2d44d920d5102171b25ebfc376b1
1 /* Copyright (C) 2016 Free Software Foundation, Inc.
2 Contributed by Martin Sebor <msebor@redhat.com>.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /* This file implements the printf-return-value pass. The pass does
21 two things: 1) it analyzes calls to formatted output functions like
22 sprintf looking for possible buffer overflows and calls to bounded
23 functions like snprintf for early truncation (and under the control
24 of the -Wformat-length option issues warnings), and 2) under the
25 control of the -fprintf-return-value option it folds the return
26 value of safe calls into constants, making it possible to eliminate
27 code that depends on the value of those constants.
29 For all functions (bounded or not) the pass uses the size of the
30 destination object. That means that it will diagnose calls to
31 snprintf not on the basis of the size specified by the function's
32 second argument but rathger on the basis of the size the first
33 argument points to (if possible). For bound-checking built-ins
34 like __builtin___snprintf_chk the pass uses the size typically
35 determined by __builtin_object_size and passed to the built-in
36 by the Glibc inline wrapper.
38 The pass handles all forms standard sprintf format directives,
39 including character, integer, floating point, pointer, and strings,
40 with the standard C flags, widths, and precisions. For integers
41 and strings it computes the length of output itself. For floating
42 point it uses MPFR to fornmat known constants with up and down
43 rounding and uses the resulting range of output lengths. For
44 strings it uses the length of string literals and the sizes of
45 character arrays that a character pointer may point to as a bound
46 on the longest string. */
48 #include "config.h"
49 #include "system.h"
50 #include "coretypes.h"
51 #include "backend.h"
52 #include "tree.h"
53 #include "gimple.h"
54 #include "tree-pass.h"
55 #include "ssa.h"
56 #include "gimple-fold.h"
57 #include "gimple-pretty-print.h"
58 #include "diagnostic-core.h"
59 #include "fold-const.h"
60 #include "gimple-iterator.h"
61 #include "tree-ssa.h"
62 #include "tree-object-size.h"
63 #include "params.h"
64 #include "tree-cfg.h"
65 #include "tree-ssa-propagate.h"
66 #include "calls.h"
67 #include "cfgloop.h"
68 #include "intl.h"
70 #include "builtins.h"
71 #include "stor-layout.h"
73 #include "realmpfr.h"
74 #include "target.h"
76 #include "cpplib.h"
77 #include "input.h"
78 #include "toplev.h"
79 #include "substring-locations.h"
80 #include "diagnostic.h"
82 /* The likely worst case value of MB_LEN_MAX for the target, large enough
83 for UTF-8. Ideally, this would be obtained by a target hook if it were
84 to be used for optimization but it's good enough as is for warnings. */
85 #define target_mb_len_max 6
87 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 bool 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 inline HOST_WIDE_INT
229 target_int_min ()
231 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
234 /* Return the value of INT_MAX for the target. */
236 static inline unsigned HOST_WIDE_INT
237 target_int_max ()
239 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
242 /* Return the value of SIZE_MAX for the target. */
244 static inline unsigned HOST_WIDE_INT
245 target_size_max ()
247 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
250 /* Return the constant initial value of DECL if available or DECL
251 otherwise. Same as the synonymous function in c/c-typeck.c. */
253 static tree
254 decl_constant_value (tree decl)
256 if (/* Don't change a variable array bound or initial value to a constant
257 in a place where a variable is invalid. Note that DECL_INITIAL
258 isn't valid for a PARM_DECL. */
259 current_function_decl != 0
260 && TREE_CODE (decl) != PARM_DECL
261 && !TREE_THIS_VOLATILE (decl)
262 && TREE_READONLY (decl)
263 && DECL_INITIAL (decl) != 0
264 && TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK
265 /* This is invalid if initial value is not constant.
266 If it has either a function call, a memory reference,
267 or a variable, then re-evaluating it could give different results. */
268 && TREE_CONSTANT (DECL_INITIAL (decl))
269 /* Check for cases where this is sub-optimal, even though valid. */
270 && TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)
271 return DECL_INITIAL (decl);
272 return decl;
275 /* Given FORMAT, set *PLOC to the source location of the format string
276 and return the format string if it is known or null otherwise. */
278 static const char*
279 get_format_string (tree format, location_t *ploc)
281 if (VAR_P (format))
283 /* Pull out a constant value if the front end didn't. */
284 format = decl_constant_value (format);
285 STRIP_NOPS (format);
288 if (integer_zerop (format))
290 /* FIXME: Diagnose null format string if it hasn't been diagnosed
291 by -Wformat (the latter diagnoses only nul pointer constants,
292 this pass can do better). */
293 return NULL;
296 HOST_WIDE_INT offset = 0;
298 if (TREE_CODE (format) == POINTER_PLUS_EXPR)
300 tree arg0 = TREE_OPERAND (format, 0);
301 tree arg1 = TREE_OPERAND (format, 1);
302 STRIP_NOPS (arg0);
303 STRIP_NOPS (arg1);
305 if (TREE_CODE (arg1) != INTEGER_CST)
306 return NULL;
308 format = arg0;
310 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
311 if (!cst_and_fits_in_hwi (arg1))
312 return NULL;
314 offset = int_cst_value (arg1);
317 if (TREE_CODE (format) != ADDR_EXPR)
318 return NULL;
320 *ploc = EXPR_LOC_OR_LOC (format, input_location);
322 format = TREE_OPERAND (format, 0);
324 if (TREE_CODE (format) == ARRAY_REF
325 && tree_fits_shwi_p (TREE_OPERAND (format, 1))
326 && (offset += tree_to_shwi (TREE_OPERAND (format, 1))) >= 0)
327 format = TREE_OPERAND (format, 0);
329 if (offset < 0)
330 return NULL;
332 tree array_init;
333 tree array_size = NULL_TREE;
335 if (VAR_P (format)
336 && TREE_CODE (TREE_TYPE (format)) == ARRAY_TYPE
337 && (array_init = decl_constant_value (format)) != format
338 && TREE_CODE (array_init) == STRING_CST)
340 /* Extract the string constant initializer. Note that this may
341 include a trailing NUL character that is not in the array (e.g.
342 const char a[3] = "foo";). */
343 array_size = DECL_SIZE_UNIT (format);
344 format = array_init;
347 if (TREE_CODE (format) != STRING_CST)
348 return NULL;
350 if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format))) != char_type_node)
352 /* Wide format string. */
353 return NULL;
356 const char *fmtstr = TREE_STRING_POINTER (format);
357 unsigned fmtlen = TREE_STRING_LENGTH (format);
359 if (array_size)
361 /* Variable length arrays can't be initialized. */
362 gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
364 if (tree_fits_shwi_p (array_size))
366 HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
367 if (array_size_value > 0
368 && array_size_value == (int) array_size_value
369 && fmtlen > array_size_value)
370 fmtlen = array_size_value;
373 if (offset)
375 if (offset >= fmtlen)
376 return NULL;
378 fmtstr += offset;
379 fmtlen -= offset;
382 if (fmtlen < 1 || fmtstr[--fmtlen] != 0)
384 /* FIXME: Diagnose an unterminated format string if it hasn't been
385 diagnosed by -Wformat. Similarly to a null format pointer,
386 -Wformay diagnoses only nul pointer constants, this pass can
387 do better). */
388 return NULL;
391 return fmtstr;
394 /* The format_warning_at_substring function is not used here in a way
395 that makes using attribute format viable. Suppress the warning. */
397 #pragma GCC diagnostic push
398 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
400 /* For convenience and brevity. */
402 static bool
403 (* const fmtwarn) (const substring_loc &, const source_range *,
404 const char *, int, const char *, ...)
405 = format_warning_at_substring;
407 /* Format length modifiers. */
409 enum format_lengths
411 FMT_LEN_none,
412 FMT_LEN_hh, // char argument
413 FMT_LEN_h, // short
414 FMT_LEN_l, // long
415 FMT_LEN_ll, // long long
416 FMT_LEN_L, // long double (and GNU long long)
417 FMT_LEN_z, // size_t
418 FMT_LEN_t, // ptrdiff_t
419 FMT_LEN_j // intmax_t
423 /* A minimum and maximum number of bytes. */
425 struct result_range
427 unsigned HOST_WIDE_INT min, max;
430 /* Description of the result of conversion either of a single directive
431 or the whole format string. */
433 struct fmtresult
435 fmtresult ()
436 : argmin (), argmax (), knownrange (), bounded (), constant ()
438 range.min = range.max = HOST_WIDE_INT_MAX;
441 /* The range a directive's argument is in. */
442 tree argmin, argmax;
444 /* The minimum and maximum number of bytes that a directive
445 results in on output for an argument in the range above. */
446 result_range range;
448 /* True when the range above is obtained from a known value of
449 a directive's argument or its bounds and not the result of
450 heuristics that depend on warning levels. */
451 bool knownrange;
453 /* True when the range is the result of an argument determined
454 to be bounded to a subrange of its type or value (such as by
455 value range propagation or the width of the formt directive),
456 false otherwise. */
457 bool bounded;
459 /* True when the output of a directive is constant. This is rare
460 and typically requires that the argument(s) of the directive
461 are also constant (such as determined by constant propagation,
462 though not value range propagation). */
463 bool constant;
466 /* Description of a conversion specification. */
468 struct conversion_spec
470 /* A bitmap of flags, one for each character. */
471 unsigned flags[256 / sizeof (int)];
472 /* Numeric width as in "%8x". */
473 int width;
474 /* Numeric precision as in "%.32s". */
475 int precision;
477 /* Width specified via the '*' character. */
478 tree star_width;
479 /* Precision specified via the asterisk. */
480 tree star_precision;
482 /* Length modifier. */
483 format_lengths modifier;
485 /* Format specifier character. */
486 char specifier;
488 /* Numeric width was given. */
489 unsigned have_width: 1;
490 /* Numeric precision was given. */
491 unsigned have_precision: 1;
492 /* Non-zero when certain flags should be interpreted even for a directive
493 that normally doesn't accept them (used when "%p" with flags such as
494 space or plus is interepreted as a "%x". */
495 unsigned force_flags: 1;
497 /* Format conversion function that given a conversion specification
498 and an argument returns the formatting result. */
499 fmtresult (*fmtfunc) (const conversion_spec &, tree);
501 /* Return True when a the format flag CHR has been used. */
502 bool get_flag (char chr) const
504 unsigned char c = chr & 0xff;
505 return (flags[c / (CHAR_BIT * sizeof *flags)]
506 & (1U << (c % (CHAR_BIT * sizeof *flags))));
509 /* Make a record of the format flag CHR having been used. */
510 void set_flag (char chr)
512 unsigned char c = chr & 0xff;
513 flags[c / (CHAR_BIT * sizeof *flags)]
514 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
517 /* Reset the format flag CHR. */
518 void clear_flag (char chr)
520 unsigned char c = chr & 0xff;
521 flags[c / (CHAR_BIT * sizeof *flags)]
522 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
526 /* Return the logarithm of X in BASE. */
528 static int
529 ilog (unsigned HOST_WIDE_INT x, int base)
531 int res = 0;
534 ++res;
535 x /= base;
536 } while (x);
537 return res;
540 /* Return the number of bytes resulting from converting into a string
541 the INTEGER_CST tree node X in BASE. PLUS indicates whether 1 for
542 a plus sign should be added for positive numbers, and PREFIX whether
543 the length of an octal ('O') or hexadecimal ('0x') prefix should be
544 added for nonzero numbers. Return -1 if X cannot be represented. */
546 static int
547 tree_digits (tree x, int base, bool plus, bool prefix)
549 unsigned HOST_WIDE_INT absval;
551 int res;
553 if (TYPE_UNSIGNED (TREE_TYPE (x)))
555 if (tree_fits_uhwi_p (x))
557 absval = tree_to_uhwi (x);
558 res = plus;
560 else
561 return -1;
563 else
565 if (tree_fits_shwi_p (x))
567 HOST_WIDE_INT i = tree_to_shwi (x);
568 if (i < 0)
570 absval = -i;
571 res = 1;
573 else
575 absval = i;
576 res = plus;
579 else
580 return -1;
583 res += ilog (absval, base);
585 if (prefix && absval)
587 if (base == 8)
588 res += 1;
589 else if (base == 16)
590 res += 2;
593 return res;
596 /* Given the formatting result described by RES and NAVAIL, the number
597 of available in the destination, return the number of bytes remaining
598 in the destination. */
600 static inline result_range
601 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
603 result_range range;
605 if (HOST_WIDE_INT_MAX <= navail)
607 range.min = range.max = navail;
608 return range;
611 if (res.number_chars < navail)
613 range.min = range.max = navail - res.number_chars;
615 else if (res.number_chars_min < navail)
617 range.max = navail - res.number_chars_min;
619 else
620 range.max = 0;
622 if (res.number_chars_max < navail)
623 range.min = navail - res.number_chars_max;
624 else
625 range.min = 0;
627 return range;
630 /* Given the formatting result described by RES and NAVAIL, the number
631 of available in the destination, return the minimum number of bytes
632 remaining in the destination. */
634 static inline unsigned HOST_WIDE_INT
635 min_bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
637 if (HOST_WIDE_INT_MAX <= navail)
638 return navail;
640 if (1 < warn_format_length || res.bounded)
642 /* At level 2, or when all directives output an exact number
643 of bytes or when their arguments were bounded by known
644 ranges, use the greater of the two byte counters if it's
645 valid to compute the result. */
646 if (res.number_chars_max < HOST_WIDE_INT_MAX)
647 navail -= res.number_chars_max;
648 else if (res.number_chars < HOST_WIDE_INT_MAX)
649 navail -= res.number_chars;
650 else if (res.number_chars_min < HOST_WIDE_INT_MAX)
651 navail -= res.number_chars_min;
653 else
655 /* At level 1 use the smaller of the byte counters to compute
656 the result. */
657 if (res.number_chars < HOST_WIDE_INT_MAX)
658 navail -= res.number_chars;
659 else if (res.number_chars_min < HOST_WIDE_INT_MAX)
660 navail -= res.number_chars_min;
661 else if (res.number_chars_max < HOST_WIDE_INT_MAX)
662 navail -= res.number_chars_max;
665 if (navail > HOST_WIDE_INT_MAX)
666 navail = 0;
668 return navail;
671 /* Description of a call to a formatted function. */
673 struct pass_sprintf_length::call_info
675 /* Function call statement. */
676 gimple *callstmt;
678 /* Function called. */
679 tree func;
681 /* Called built-in function code. */
682 built_in_function fncode;
684 /* Format argument and format string extracted from it. */
685 tree format;
686 const char *fmtstr;
688 /* The location of the format argument. */
689 location_t fmtloc;
691 /* The destination object size for __builtin___xxx_chk functions
692 typically determined by __builtin_object_size, or -1 if unknown. */
693 unsigned HOST_WIDE_INT objsize;
695 /* Number of the first variable argument. */
696 unsigned HOST_WIDE_INT argidx;
698 /* True for functions like snprintf that specify the size of
699 the destination, false for others like sprintf that don't. */
700 bool bounded;
702 /* True for bounded functions like snprintf that specify a zero-size
703 buffer as a request to compute the size of output without actually
704 writing any. */
705 bool nowrite;
708 /* Return the result of formatting the '%%' directive. */
710 static fmtresult
711 format_percent (const conversion_spec &, tree)
713 fmtresult res;
714 res.argmin = res.argmax = NULL_TREE;
715 res.range.min = res.range.max = 1;
716 res.bounded = res.constant = true;
717 return res;
721 /* Compute intmax_type_node and uintmax_type_node similarly to how
722 tree.c builds size_type_node. */
724 static void
725 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
727 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
729 *pintmax = integer_type_node;
730 *puintmax = unsigned_type_node;
732 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
734 *pintmax = long_integer_type_node;
735 *puintmax = long_unsigned_type_node;
737 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
739 *pintmax = long_long_integer_type_node;
740 *puintmax = long_long_unsigned_type_node;
742 else
744 for (int i = 0; i < NUM_INT_N_ENTS; i++)
745 if (int_n_enabled_p[i])
747 char name[50];
748 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
750 if (strcmp (name, UINTMAX_TYPE) == 0)
752 *pintmax = int_n_trees[i].signed_type;
753 *puintmax = int_n_trees[i].unsigned_type;
754 return;
757 gcc_unreachable ();
761 /* Set *PWIDTH and *PPREC according to the width and precision specified
762 in SPEC. Each is set to HOST_WIDE_INT_MIN when the corresponding
763 field is specified but unknown, to zero for width and -1 for precision,
764 respectively when it's not specified, or to a non-negative value
765 corresponding to the known value. */
767 static void
768 get_width_and_precision (const conversion_spec &spec,
769 HOST_WIDE_INT *pwidth, HOST_WIDE_INT *pprec)
771 HOST_WIDE_INT width = spec.have_width ? spec.width : 0;
772 HOST_WIDE_INT prec = spec.have_precision ? spec.precision : -1;
774 if (spec.star_width)
776 if (TREE_CODE (spec.star_width) == INTEGER_CST)
778 width = tree_to_shwi (spec.star_width);
779 if (width < 0)
781 if (width == HOST_WIDE_INT_MIN)
783 /* Avoid undefined behavior due to negating a minimum.
784 This case will be diagnosed since it will result in
785 more than INT_MAX bytes on output, either by the
786 directive itself (when INT_MAX < HOST_WIDE_INT_MAX)
787 or by the format function itself. */
788 width = HOST_WIDE_INT_MAX;
790 else
791 width = -width;
794 else
795 width = HOST_WIDE_INT_MIN;
798 if (spec.star_precision)
800 if (TREE_CODE (spec.star_precision) == INTEGER_CST)
802 prec = tree_to_shwi (spec.star_precision);
803 if (prec < 0)
804 prec = 0;
806 else
807 prec = HOST_WIDE_INT_MIN;
810 *pwidth = width;
811 *pprec = prec;
814 /* Return a range representing the minimum and maximum number of bytes
815 that the conversion specification SPEC will write on output for the
816 integer argument ARG when non-null. ARG may be null (for vararg
817 functions). */
819 static fmtresult
820 format_integer (const conversion_spec &spec, tree arg)
822 tree intmax_type_node;
823 tree uintmax_type_node;
825 /* Set WIDTH and PRECISION based on the specification. */
826 HOST_WIDE_INT width;
827 HOST_WIDE_INT prec;
828 get_width_and_precision (spec, &width, &prec);
830 bool sign = spec.specifier == 'd' || spec.specifier == 'i';
832 /* The type of the "formal" argument expected by the directive. */
833 tree dirtype = NULL_TREE;
835 /* Determine the expected type of the argument from the length
836 modifier. */
837 switch (spec.modifier)
839 case FMT_LEN_none:
840 if (spec.specifier == 'p')
841 dirtype = ptr_type_node;
842 else
843 dirtype = sign ? integer_type_node : unsigned_type_node;
844 break;
846 case FMT_LEN_h:
847 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
848 break;
850 case FMT_LEN_hh:
851 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
852 break;
854 case FMT_LEN_l:
855 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
856 break;
858 case FMT_LEN_L:
859 case FMT_LEN_ll:
860 dirtype = (sign
861 ? long_long_integer_type_node
862 : long_long_unsigned_type_node);
863 break;
865 case FMT_LEN_z:
866 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
867 break;
869 case FMT_LEN_t:
870 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
871 break;
873 case FMT_LEN_j:
874 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
875 dirtype = sign ? intmax_type_node : uintmax_type_node;
876 break;
878 default:
879 return fmtresult ();
882 /* The type of the argument to the directive, either deduced from
883 the actual non-constant argument if one is known, or from
884 the directive itself when none has been provided because it's
885 a va_list. */
886 tree argtype = NULL_TREE;
888 if (!arg)
890 /* When the argument has not been provided, use the type of
891 the directive's argument as an approximation. This will
892 result in false positives for directives like %i with
893 arguments with smaller precision (such as short or char). */
894 argtype = dirtype;
896 else if (TREE_CODE (arg) == INTEGER_CST)
898 /* When a constant argument has been provided use its value
899 rather than type to determine the length of the output. */
901 /* Base to format the number in. */
902 int base;
904 /* True when a signed conversion is preceded by a sign or space. */
905 bool maybesign;
907 switch (spec.specifier)
909 case 'd':
910 case 'i':
911 /* Space is only effective for signed conversions. */
912 maybesign = spec.get_flag (' ');
913 base = 10;
914 break;
915 case 'u':
916 maybesign = spec.force_flags ? spec.get_flag (' ') : false;
917 base = 10;
918 break;
919 case 'o':
920 maybesign = spec.force_flags ? spec.get_flag (' ') : false;
921 base = 8;
922 break;
923 case 'X':
924 case 'x':
925 maybesign = spec.force_flags ? spec.get_flag (' ') : false;
926 base = 16;
927 break;
928 default:
929 gcc_unreachable ();
932 int len;
934 if ((prec == HOST_WIDE_INT_MIN || prec == 0) && integer_zerop (arg))
936 /* As a special case, a precision of zero with an argument
937 of zero results in zero bytes regardless of flags (with
938 width having the normal effect). This must extend to
939 the case of a specified precision with an unknown value
940 because it can be zero. */
941 len = 0;
943 else
945 /* Convert the argument to the type of the directive. */
946 arg = fold_convert (dirtype, arg);
948 maybesign |= spec.get_flag ('+');
950 /* True when a conversion is preceded by a prefix indicating the base
951 of the argument (octal or hexadecimal). */
952 bool maybebase = spec.get_flag ('#');
953 len = tree_digits (arg, base, maybesign, maybebase);
955 if (len < prec)
956 len = prec;
959 if (len < width)
960 len = width;
962 /* The minimum and maximum number of bytes produced by the directive. */
963 fmtresult res;
965 res.range.min = len;
967 /* The upper bound of the number of bytes is unlimited when either
968 width or precision is specified but its value is unknown, and
969 the same as the lower bound otherwise. */
970 if (width == HOST_WIDE_INT_MIN || prec == HOST_WIDE_INT_MIN)
972 res.range.max = HOST_WIDE_INT_MAX;
974 else
976 res.range.max = len;
977 res.bounded = true;
978 res.constant = true;
979 res.knownrange = true;
980 res.bounded = true;
983 return res;
985 else if (TREE_CODE (TREE_TYPE (arg)) == INTEGER_TYPE
986 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
987 /* Determine the type of the provided non-constant argument. */
988 argtype = TREE_TYPE (arg);
989 else
990 /* Don't bother with invalid arguments since they likely would
991 have already been diagnosed, and disable any further checking
992 of the format string by returning [-1, -1]. */
993 return fmtresult ();
995 fmtresult res;
997 /* Using either the range the non-constant argument is in, or its
998 type (either "formal" or actual), create a range of values that
999 constrain the length of output given the warning level. */
1000 tree argmin = NULL_TREE;
1001 tree argmax = NULL_TREE;
1003 if (arg
1004 && TREE_CODE (arg) == SSA_NAME
1005 && TREE_CODE (argtype) == INTEGER_TYPE)
1007 /* Try to determine the range of values of the integer argument
1008 (range information is not available for pointers). */
1009 wide_int min, max;
1010 enum value_range_type range_type = get_range_info (arg, &min, &max);
1011 if (range_type == VR_RANGE)
1013 res.argmin = build_int_cst (argtype, wi::fits_uhwi_p (min)
1014 ? min.to_uhwi () : min.to_shwi ());
1015 res.argmax = build_int_cst (argtype, wi::fits_uhwi_p (max)
1016 ? max.to_uhwi () : max.to_shwi ());
1018 /* For a range with a negative lower bound and a non-negative
1019 upper bound, use one to determine the minimum number of bytes
1020 on output and whichever of the two bounds that results in
1021 the greater number of bytes on output for the upper bound.
1022 For example, for ARG in the range of [-3, 123], use 123 as
1023 the upper bound for %i but -3 for %u. */
1024 if (wi::neg_p (min) && !wi::neg_p (max))
1026 argmin = res.argmin;
1027 argmax = res.argmax;
1028 int minbytes = format_integer (spec, res.argmin).range.min;
1029 int maxbytes = format_integer (spec, res.argmax).range.max;
1030 if (maxbytes < minbytes)
1031 argmax = res.argmin;
1033 argmin = integer_zero_node;
1035 else
1037 argmin = res.argmin;
1038 argmax = res.argmax;
1041 /* The argument is bounded by the known range of values
1042 determined by Value Range Propagation. */
1043 res.bounded = true;
1044 res.knownrange = true;
1046 else if (range_type == VR_ANTI_RANGE)
1048 /* Handle anti-ranges if/when bug 71690 is resolved. */
1050 else if (range_type == VR_VARYING)
1052 /* The argument here may be the result of promoting the actual
1053 argument to int. Try to determine the type of the actual
1054 argument before promotion and narrow down its range that
1055 way. */
1056 gimple *def = SSA_NAME_DEF_STMT (arg);
1057 if (is_gimple_assign (def))
1059 tree_code code = gimple_assign_rhs_code (def);
1060 if (code == INTEGER_CST)
1062 arg = gimple_assign_rhs1 (def);
1063 return format_integer (spec, arg);
1066 if (code == NOP_EXPR)
1068 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1069 if (TREE_CODE (type) == INTEGER_TYPE
1070 || TREE_CODE (type) == POINTER_TYPE)
1071 argtype = type;
1077 if (!argmin)
1079 /* For an unknown argument (e.g., one passed to a vararg function)
1080 or one whose value range cannot be determined, create a T_MIN
1081 constant if the argument's type is signed and T_MAX otherwise,
1082 and use those to compute the range of bytes that the directive
1083 can output. When precision is specified but unknown, use zero
1084 as the minimum since it results in no bytes on output (unless
1085 width is specified to be greater than 0). */
1086 argmin = build_int_cst (argtype, prec != HOST_WIDE_INT_MIN);
1088 int typeprec = TYPE_PRECISION (dirtype);
1089 int argprec = TYPE_PRECISION (argtype);
1091 if (argprec < typeprec)
1093 if (POINTER_TYPE_P (argtype))
1094 argmax = build_all_ones_cst (argtype);
1095 else if (TYPE_UNSIGNED (argtype))
1096 argmax = TYPE_MAX_VALUE (argtype);
1097 else
1098 argmax = TYPE_MIN_VALUE (argtype);
1100 else
1102 if (POINTER_TYPE_P (dirtype))
1103 argmax = build_all_ones_cst (dirtype);
1104 else if (TYPE_UNSIGNED (dirtype))
1105 argmax = TYPE_MAX_VALUE (dirtype);
1106 else
1107 argmax = TYPE_MIN_VALUE (dirtype);
1110 res.argmin = argmin;
1111 res.argmax = argmax;
1114 /* Recursively compute the minimum and maximum from the known range,
1115 taking care to swap them if the lower bound results in longer
1116 output than the upper bound (e.g., in the range [-1, 0]. */
1117 res.range.min = format_integer (spec, argmin).range.min;
1118 res.range.max = format_integer (spec, argmax).range.max;
1120 /* The result is bounded either when the argument is determined to be
1121 (e.g., when it's within some range) or when the minimum and maximum
1122 are the same. That can happen here for example when the specified
1123 width is as wide as the greater of MIN and MAX, as would be the case
1124 with sprintf (d, "%08x", x) with a 32-bit integer x. */
1125 res.bounded |= res.range.min == res.range.max;
1127 if (res.range.max < res.range.min)
1129 unsigned HOST_WIDE_INT tmp = res.range.max;
1130 res.range.max = res.range.min;
1131 res.range.min = tmp;
1134 return res;
1137 /* Return the number of bytes to format using the format specifier
1138 SPEC the largest value in the real floating TYPE. */
1140 static int
1141 format_floating_max (tree type, char spec, int prec = -1)
1143 machine_mode mode = TYPE_MODE (type);
1145 /* IBM Extended mode. */
1146 if (MODE_COMPOSITE_P (mode))
1147 mode = DFmode;
1149 /* Get the real type format desription for the target. */
1150 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1151 REAL_VALUE_TYPE rv;
1154 char buf[256];
1155 get_max_float (rfmt, buf, sizeof buf);
1156 real_from_string (&rv, buf);
1159 /* Convert the GCC real value representation with the precision
1160 of the real type to the mpfr_t format with the GCC default
1161 round-to-nearest mode. */
1162 mpfr_t x;
1163 mpfr_init2 (x, rfmt->p);
1164 mpfr_from_real (x, &rv, GMP_RNDN);
1166 int n;
1168 if (-1 < prec)
1170 const char fmt[] = { '%', '.', '*', 'R', spec, '\0' };
1171 n = mpfr_snprintf (NULL, 0, fmt, prec, x);
1173 else
1175 const char fmt[] = { '%', 'R', spec, '\0' };
1176 n = mpfr_snprintf (NULL, 0, fmt, x);
1179 /* Return a value one greater to account for the leading minus sign. */
1180 return n + 1;
1183 /* Return a range representing the minimum and maximum number of bytes
1184 that the conversion specification SPEC will output for any argument
1185 given the WIDTH and PRECISION (extracted from SPEC). This function
1186 is used when the directive argument or its value isn't known. */
1188 static fmtresult
1189 format_floating (const conversion_spec &spec, int width, int prec)
1191 tree type;
1192 bool ldbl = false;
1194 switch (spec.modifier)
1196 case FMT_LEN_l:
1197 case FMT_LEN_none:
1198 type = double_type_node;
1199 break;
1201 case FMT_LEN_L:
1202 type = long_double_type_node;
1203 ldbl = true;
1204 break;
1206 case FMT_LEN_ll:
1207 type = long_double_type_node;
1208 ldbl = true;
1209 break;
1211 default:
1212 return fmtresult ();
1215 /* The minimum and maximum number of bytes produced by the directive. */
1216 fmtresult res;
1218 /* Log10 of of the maximum number of exponent digits for the type. */
1219 int logexpdigs = 2;
1221 if (REAL_MODE_FORMAT (TYPE_MODE (type))->b == 2)
1223 /* The base in which the exponent is represented should always
1224 be 2 in GCC. */
1226 const double log10_2 = .30102999566398119521;
1228 /* Compute T_MAX_EXP for base 2. */
1229 int expdigs = REAL_MODE_FORMAT (TYPE_MODE (type))->emax * log10_2;
1230 logexpdigs = ilog (expdigs, 10);
1233 switch (spec.specifier)
1235 case 'A':
1236 case 'a':
1238 /* The minimum output is "0x.p+0". */
1239 res.range.min = 6 + (prec > 0 ? prec : 0);
1240 res.range.max = (width == INT_MIN
1241 ? HOST_WIDE_INT_MAX
1242 : format_floating_max (type, 'a', prec));
1244 /* The output of "%a" is fully specified only when precision
1245 is explicitly specified and width isn't unknown. */
1246 res.bounded = INT_MIN != width && -1 < prec;
1247 break;
1250 case 'E':
1251 case 'e':
1253 bool sign = spec.get_flag ('+') || spec.get_flag (' ');
1254 /* The minimum output is "[-+]1.234567e+00" regardless
1255 of the value of the actual argument. */
1256 res.range.min = (sign
1257 + 1 /* unit */ + (prec < 0 ? 7 : prec ? prec + 1 : 0)
1258 + 2 /* e+ */ + 2);
1259 /* Unless width is uknown the maximum output is the minimum plus
1260 sign (unless already included), plus the difference between
1261 the minimum exponent of 2 and the maximum exponent for the type. */
1262 res.range.max = (width == INT_MIN
1263 ? HOST_WIDE_INT_M1U
1264 : res.range.min + !sign + logexpdigs - 2);
1266 /* "%e" is fully specified and the range of bytes is bounded
1267 unless width is unknown. */
1268 res.bounded = INT_MIN != width;
1269 break;
1272 case 'F':
1273 case 'f':
1275 /* The minimum output is "1.234567" regardless of the value
1276 of the actual argument. */
1277 res.range.min = 2 + (prec < 0 ? 6 : prec);
1279 /* Compute the maximum just once. */
1280 const int f_max[] = {
1281 format_floating_max (double_type_node, 'f', prec),
1282 format_floating_max (long_double_type_node, 'f', prec)
1284 res.range.max = width == INT_MIN ? HOST_WIDE_INT_MAX : f_max [ldbl];
1286 /* "%f" is fully specified and the range of bytes is bounded
1287 unless width is unknown. */
1288 res.bounded = INT_MIN != width;
1289 break;
1291 case 'G':
1292 case 'g':
1294 /* The minimum is the same as for '%F'. */
1295 res.range.min = 2 + (prec < 0 ? 6 : prec);
1297 /* Compute the maximum just once. */
1298 const int g_max[] = {
1299 format_floating_max (double_type_node, 'g', prec),
1300 format_floating_max (long_double_type_node, 'g', prec)
1302 res.range.max = width == INT_MIN ? HOST_WIDE_INT_MAX : g_max [ldbl];
1304 /* "%g" is fully specified and the range of bytes is bounded
1305 unless width is unknown. */
1306 res.bounded = INT_MIN != width;
1307 break;
1310 default:
1311 return fmtresult ();
1314 if (width > 0)
1316 if (res.range.min < (unsigned)width)
1317 res.range.min = width;
1318 if (res.range.max < (unsigned)width)
1319 res.range.max = width;
1322 return res;
1325 /* Return a range representing the minimum and maximum number of bytes
1326 that the conversion specification SPEC will write on output for the
1327 floating argument ARG. */
1329 static fmtresult
1330 format_floating (const conversion_spec &spec, tree arg)
1332 /* Set WIDTH to -1 when it's not specified, to INT_MIN when it is
1333 specified by the asterisk to an unknown value, and otherwise to
1334 a non-negative value corresponding to the specified width. */
1335 int width = -1;
1336 int prec = -1;
1338 /* The minimum and maximum number of bytes produced by the directive. */
1339 fmtresult res;
1340 res.constant = arg && TREE_CODE (arg) == REAL_CST;
1342 if (spec.have_width)
1343 width = spec.width;
1344 else if (spec.star_width)
1346 if (TREE_CODE (spec.star_width) == INTEGER_CST)
1348 width = tree_to_shwi (spec.star_width);
1349 if (width < 0)
1350 width = -width;
1352 else
1353 width = INT_MIN;
1356 if (spec.have_precision)
1357 prec = spec.precision;
1358 else if (spec.star_precision)
1360 if (TREE_CODE (spec.star_precision) == INTEGER_CST)
1361 prec = tree_to_shwi (spec.star_precision);
1362 else
1364 /* FIXME: Handle non-constant precision. */
1365 res.range.min = res.range.max = HOST_WIDE_INT_M1U;
1366 return res;
1369 else if (res.constant && TOUPPER (spec.specifier) != 'A')
1371 /* Specify the precision explicitly since mpfr_sprintf defaults
1372 to zero. */
1373 prec = 6;
1376 if (res.constant)
1378 /* Set up an array to easily iterate over. */
1379 unsigned HOST_WIDE_INT* const minmax[] = {
1380 &res.range.min, &res.range.max
1383 /* Get the real type format desription for the target. */
1384 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1385 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1387 /* Convert the GCC real value representation with the precision
1388 of the real type to the mpfr_t format with the GCC default
1389 round-to-nearest mode. */
1390 mpfr_t mpfrval;
1391 mpfr_init2 (mpfrval, rfmt->p);
1392 mpfr_from_real (mpfrval, rvp, GMP_RNDN);
1394 char fmtstr [40];
1395 char *pfmt = fmtstr;
1396 *pfmt++ = '%';
1398 /* Append flags. */
1399 for (const char *pf = "-+ #0"; *pf; ++pf)
1400 if (spec.get_flag (*pf))
1401 *pfmt++ = *pf;
1403 /* Append width when specified and precision. */
1404 if (-1 < width)
1405 pfmt += sprintf (pfmt, "%i", width);
1406 if (-1 < prec)
1407 pfmt += sprintf (pfmt, ".%i", prec);
1409 /* Append the MPFR 'R' floating type specifier (no length modifier
1410 is necessary or allowed by MPFR for mpfr_t values). */
1411 *pfmt++ = 'R';
1413 /* Save the position of the MPFR rounding specifier and skip over
1414 it. It will be set in each iteration in the loop below. */
1415 char* const rndspec = pfmt++;
1417 /* Append the C type specifier and nul-terminate. */
1418 *pfmt++ = spec.specifier;
1419 *pfmt = '\0';
1421 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1423 /* Use the MPFR rounding specifier to round down in the first
1424 iteration and then up. In most but not all cases this will
1425 result in the same number of bytes. */
1426 *rndspec = "DU"[i];
1428 /* Format it and store the result in the corresponding
1429 member of the result struct. */
1430 *minmax[i] = mpfr_snprintf (NULL, 0, fmtstr, mpfrval);
1433 /* The range of output is known even if the result isn't bounded. */
1434 if (width == INT_MIN)
1436 res.knownrange = false;
1437 res.range.max = HOST_WIDE_INT_MAX;
1439 else
1440 res.knownrange = true;
1442 /* The output of all directives except "%a" is fully specified
1443 and so the result is bounded unless it exceeds INT_MAX.
1444 For "%a" the output is fully specified only when precision
1445 is explicitly specified. */
1446 res.bounded = (res.knownrange
1447 && (TOUPPER (spec.specifier) != 'A'
1448 || (0 <= prec && (unsigned) prec < target_int_max ()))
1449 && res.range.min < target_int_max ());
1451 return res;
1454 return format_floating (spec, width, prec);
1457 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1458 strings referenced by the expression STR, or (-1, -1) when not known.
1459 Used by the format_string function below. */
1461 static fmtresult
1462 get_string_length (tree str)
1464 if (!str)
1465 return fmtresult ();
1467 if (tree slen = c_strlen (str, 1))
1469 /* Simply return the length of the string. */
1470 fmtresult res;
1471 res.range.min = res.range.max = tree_to_shwi (slen);
1472 res.bounded = true;
1473 res.constant = true;
1474 res.knownrange = true;
1475 return res;
1478 /* Determine the length of the shortest and longest string referenced
1479 by STR. Strings of unknown lengths are bounded by the sizes of
1480 arrays that subexpressions of STR may refer to. Pointers that
1481 aren't known to point any such arrays result in LENRANGE[1] set
1482 to SIZE_MAX. */
1483 tree lenrange[2];
1484 get_range_strlen (str, lenrange);
1486 if (lenrange [0] || lenrange [1])
1488 fmtresult res;
1490 res.range.min = (tree_fits_uhwi_p (lenrange[0])
1491 ? tree_to_uhwi (lenrange[0]) : 1 < warn_format_length);
1492 res.range.max = (tree_fits_uhwi_p (lenrange[1])
1493 ? tree_to_uhwi (lenrange[1]) : HOST_WIDE_INT_M1U);
1495 /* Set RES.BOUNDED to true if and only if all strings referenced
1496 by STR are known to be bounded (though not necessarily by their
1497 actual length but perhaps by their maximum possible length). */
1498 res.bounded = res.range.max < target_int_max ();
1499 res.knownrange = res.bounded;
1501 /* Set RES.CONSTANT to false even though that may be overly
1502 conservative in rare cases like: 'x ? a : b' where a and
1503 b have the same lengths and consist of the same characters. */
1504 res.constant = false;
1506 return res;
1509 return get_string_length (NULL_TREE);
1512 /* Return the minimum and maximum number of characters formatted
1513 by the '%c' and '%s' format directives and ther wide character
1514 forms for the argument ARG. ARG can be null (for functions
1515 such as vsprinf). */
1517 static fmtresult
1518 format_string (const conversion_spec &spec, tree arg)
1520 /* Set WIDTH and PRECISION based on the specification. */
1521 HOST_WIDE_INT width;
1522 HOST_WIDE_INT prec;
1523 get_width_and_precision (spec, &width, &prec);
1525 fmtresult res;
1527 /* The maximum number of bytes for an unknown wide character argument
1528 to a "%lc" directive adjusted for precision but not field width.
1529 6 is the longest UTF-8 sequence for a single wide character. */
1530 const unsigned HOST_WIDE_INT max_bytes_for_unknown_wc
1531 = (0 <= prec ? prec : 1 < warn_format_length ? 6 : 1);
1533 /* The maximum number of bytes for an unknown string argument to either
1534 a "%s" or "%ls" directive adjusted for precision but not field width. */
1535 const unsigned HOST_WIDE_INT max_bytes_for_unknown_str
1536 = (0 <= prec ? prec : 1 < warn_format_length);
1538 /* The result is bounded unless overriddden for a non-constant string
1539 of an unknown length. */
1540 bool bounded = true;
1542 if (spec.specifier == 'c')
1544 if (spec.modifier == FMT_LEN_l)
1546 /* Positive if the argument is a wide NUL character? */
1547 int nul = (arg && TREE_CODE (arg) == INTEGER_CST
1548 ? integer_zerop (arg) : -1);
1550 /* A '%lc' directive is the same as '%ls' for a two element
1551 wide string character with the second element of NUL, so
1552 when the character is unknown the minimum number of bytes
1553 is the smaller of either 0 (at level 1) or 1 (at level 2)
1554 and WIDTH, and the maximum is MB_CUR_MAX in the selected
1555 locale, which is unfortunately, unknown. */
1556 res.range.min = 1 == warn_format_length ? !nul : nul < 1;
1557 res.range.max = max_bytes_for_unknown_wc;
1558 /* The range above is good enough to issue warnings but not
1559 for value range propagation, so clear BOUNDED. */
1560 res.bounded = false;
1562 else
1564 /* A plain '%c' directive. Its ouput is exactly 1. */
1565 res.range.min = res.range.max = 1;
1566 res.bounded = true;
1567 res.knownrange = true;
1568 res.constant = arg && TREE_CODE (arg) == INTEGER_CST;
1571 else /* spec.specifier == 's' */
1573 /* Compute the range the argument's length can be in. */
1574 fmtresult slen = get_string_length (arg);
1575 if (slen.constant)
1577 gcc_checking_assert (slen.range.min == slen.range.max);
1579 /* A '%s' directive with a string argument with constant length. */
1580 res.range = slen.range;
1582 /* The output of "%s" and "%ls" directives with a constant
1583 string is in a known range unless width of an unknown value
1584 is specified. For "%s" it is the length of the string. For
1585 "%ls" it is in the range [length, length * MB_LEN_MAX].
1586 (The final range can be further constrained by width and
1587 precision but it's always known.) */
1588 res.knownrange = -1 < width;
1590 if (spec.modifier == FMT_LEN_l)
1592 bounded = false;
1594 if (warn_format_length > 1)
1596 /* Leave the minimum number of bytes the wide string
1597 converts to equal to its length and set the maximum
1598 to the worst case length which is the string length
1599 multiplied by MB_LEN_MAX. */
1601 /* It's possible to be smarter about computing the maximum
1602 by scanning the wide string for any 8-bit characters and
1603 if it contains none, using its length for the maximum.
1604 Even though this would be simple to do it's unlikely to
1605 be worth it when dealing with wide characters. */
1606 res.range.max *= target_mb_len_max;
1609 /* For a wide character string, use precision as the maximum
1610 even if precision is greater than the string length since
1611 the number of bytes the string converts to may be greater
1612 (due to MB_CUR_MAX). */
1613 if (0 <= prec)
1614 res.range.max = prec;
1616 else if (0 <= width)
1618 /* The output of a "%s" directive with a constant argument
1619 and constant or no width is bounded. It is constant if
1620 precision is either not specified or it is specified and
1621 its value is known. */
1622 res.bounded = true;
1623 res.constant = prec != HOST_WIDE_INT_MIN;
1625 else if (width == HOST_WIDE_INT_MIN)
1627 /* Specified but unknown width makes the output unbounded. */
1628 res.range.max = HOST_WIDE_INT_MAX;
1631 if (0 <= prec && (unsigned HOST_WIDE_INT)prec < res.range.min)
1633 res.range.min = prec;
1634 res.range.max = prec;
1636 else if (prec == HOST_WIDE_INT_MIN)
1638 /* When precision is specified but not known the lower
1639 bound is assumed to be as low as zero. */
1640 res.range.min = 0;
1643 else
1645 /* For a '%s' and '%ls' directive with a non-constant string,
1646 the minimum number of characters is the greater of WIDTH
1647 and either 0 in mode 1 or the smaller of PRECISION and 1
1648 in mode 2, and the maximum is PRECISION or -1 to disable
1649 tracking. */
1651 if (0 <= prec)
1653 if (slen.range.min >= target_int_max ())
1654 slen.range.min = 0;
1655 else if ((unsigned HOST_WIDE_INT)prec < slen.range.min)
1656 slen.range.min = prec;
1658 if ((unsigned HOST_WIDE_INT)prec < slen.range.max
1659 || slen.range.max >= target_int_max ())
1660 slen.range.max = prec;
1662 else if (slen.range.min >= target_int_max ())
1664 slen.range.min = max_bytes_for_unknown_str;
1665 slen.range.max = max_bytes_for_unknown_str;
1666 bounded = false;
1669 res.range = slen.range;
1671 /* The output is considered bounded when a precision has been
1672 specified to limit the number of bytes or when the number
1673 of bytes is known or contrained to some range. */
1674 res.bounded = 0 <= prec || slen.bounded;
1675 res.knownrange = slen.knownrange;
1676 res.constant = false;
1680 /* Adjust the lengths for field width. */
1681 if (0 < width)
1683 if (res.range.min < (unsigned HOST_WIDE_INT)width)
1684 res.range.min = width;
1686 if (res.range.max < (unsigned HOST_WIDE_INT)width)
1687 res.range.max = width;
1689 /* Adjust BOUNDED if width happens to make them equal. */
1690 if (res.range.min == res.range.max && res.range.min < target_int_max ()
1691 && bounded)
1692 res.bounded = true;
1695 /* When precision is specified the range of characters on output
1696 is known to be bounded by it. */
1697 if (-1 < width && -1 < prec)
1698 res.knownrange = true;
1700 return res;
1703 /* Compute the length of the output resulting from the conversion
1704 specification SPEC with the argument ARG in a call described by INFO
1705 and update the overall result of the call in *RES. The format directive
1706 corresponding to SPEC starts at CVTBEG and is CVTLEN characters long. */
1708 static void
1709 format_directive (const pass_sprintf_length::call_info &info,
1710 format_result *res, const char *cvtbeg, size_t cvtlen,
1711 const conversion_spec &spec, tree arg)
1713 /* Offset of the beginning of the directive from the beginning
1714 of the format string. */
1715 size_t offset = cvtbeg - info.fmtstr;
1717 /* Create a location for the whole directive from the % to the format
1718 specifier. */
1719 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
1720 offset, offset, offset + cvtlen - 1);
1722 /* Also create a location range for the argument if possible.
1723 This doesn't work for integer literals or function calls. */
1724 source_range argrange;
1725 source_range *pargrange;
1726 if (arg && CAN_HAVE_LOCATION_P (arg))
1728 argrange = EXPR_LOCATION_RANGE (arg);
1729 pargrange = &argrange;
1731 else
1732 pargrange = NULL;
1734 /* Bail when there is no function to compute the output length,
1735 or when minimum length checking has been disabled. */
1736 if (!spec.fmtfunc || res->number_chars_min >= HOST_WIDE_INT_MAX)
1737 return;
1739 /* Compute the (approximate) length of the formatted output. */
1740 fmtresult fmtres = spec.fmtfunc (spec, arg);
1742 /* The overall result is bounded and constant only if the output
1743 of every directive is bounded and constant, respectively. */
1744 res->bounded &= fmtres.bounded;
1745 res->constant &= fmtres.constant;
1747 /* Record whether the output of all directives is known to be
1748 bounded by some maximum, implying that their arguments are
1749 either known exactly or determined to be in a known range
1750 or, for strings, limited by the upper bounds of the arrays
1751 they refer to. */
1752 res->knownrange &= fmtres.knownrange;
1754 if (!fmtres.knownrange)
1756 /* Only when the range is known, check it against the host value
1757 of INT_MAX. Otherwise the range doesn't correspond to known
1758 values of the argument. */
1759 if (fmtres.range.max >= target_int_max ())
1761 /* Normalize the MAX counter to avoid having to deal with it
1762 later. The counter can be less than HOST_WIDE_INT_M1U
1763 when compiling for an ILP32 target on an LP64 host. */
1764 fmtres.range.max = HOST_WIDE_INT_M1U;
1765 /* Disable exact and maximum length checking after a failure
1766 to determine the maximum number of characters (for example
1767 for wide characters or wide character strings) but continue
1768 tracking the minimum number of characters. */
1769 res->number_chars_max = HOST_WIDE_INT_M1U;
1770 res->number_chars = HOST_WIDE_INT_M1U;
1773 if (fmtres.range.min >= target_int_max ())
1775 /* Disable exact length checking after a failure to determine
1776 even the minimum number of characters (it shouldn't happen
1777 except in an error) but keep tracking the minimum and maximum
1778 number of characters. */
1779 res->number_chars = HOST_WIDE_INT_M1U;
1780 return;
1784 /* Compute the number of available bytes in the destination. There
1785 must always be at least one byte of space for the terminating
1786 NUL that's appended after the format string has been processed. */
1787 unsigned HOST_WIDE_INT navail = min_bytes_remaining (info.objsize, *res);
1789 if (fmtres.range.min < fmtres.range.max)
1791 /* The result is a range (i.e., it's inexact). */
1792 if (!res->warned)
1794 bool warned = false;
1796 if (navail < fmtres.range.min)
1798 /* The minimum directive output is longer than there is
1799 room in the destination. */
1800 if (fmtres.range.min == fmtres.range.max)
1802 const char* fmtstr
1803 = (info.bounded
1804 ? G_("%<%.*s%> directive output truncated writing "
1805 "%wu bytes into a region of size %wu")
1806 : G_("%<%.*s%> directive writing %wu bytes "
1807 "into a region of size %wu"));
1808 warned = fmtwarn (dirloc, pargrange, NULL,
1809 OPT_Wformat_length_, fmtstr,
1810 (int)cvtlen, cvtbeg, fmtres.range.min,
1811 navail);
1813 else if (fmtres.range.max < HOST_WIDE_INT_MAX)
1815 const char* fmtstr
1816 = (info.bounded
1817 ? G_("%<%.*s%> directive output truncated writing "
1818 "between %wu and %wu bytes into a region of "
1819 "size %wu")
1820 : G_("%<%.*s%> directive writing between %wu and "
1821 "%wu bytes into a region of size %wu"));
1822 warned = fmtwarn (dirloc, pargrange, NULL,
1823 OPT_Wformat_length_, fmtstr,
1824 (int)cvtlen, cvtbeg,
1825 fmtres.range.min, fmtres.range.max, navail);
1827 else
1829 const char* fmtstr
1830 = (info.bounded
1831 ? G_("%<%.*s%> directive output truncated writing "
1832 "%wu or more bytes into a region of size %wu")
1833 : G_("%<%.*s%> directive writing %wu or more bytes "
1834 "into a region of size %wu"));
1835 warned = fmtwarn (dirloc, pargrange, NULL,
1836 OPT_Wformat_length_, fmtstr,
1837 (int)cvtlen, cvtbeg,
1838 fmtres.range.min, navail);
1841 else if (navail < fmtres.range.max
1842 && (((spec.specifier == 's'
1843 && fmtres.range.max < HOST_WIDE_INT_MAX)
1844 /* && (spec.precision || spec.star_precision) */)
1845 || 1 < warn_format_length))
1847 /* The maximum directive output is longer than there is
1848 room in the destination and the output length is either
1849 explicitly constrained by the precision (for strings)
1850 or the warning level is greater than 1. */
1851 if (fmtres.range.max >= HOST_WIDE_INT_MAX)
1853 const char* fmtstr
1854 = (info.bounded
1855 ? G_("%<%.*s%> directive output may be truncated "
1856 "writing %wu or more bytes a region of size %wu")
1857 : G_("%<%.*s%> directive writing %wu or more bytes "
1858 "into a region of size %wu"));
1859 warned = fmtwarn (dirloc, pargrange, NULL,
1860 OPT_Wformat_length_, fmtstr,
1861 (int)cvtlen, cvtbeg,
1862 fmtres.range.min, navail);
1864 else
1866 const char* fmtstr
1867 = (info.bounded
1868 ? G_("%<%.*s%> directive output may be truncated "
1869 "writing between %wu and %wu bytes into a region "
1870 "of size %wu")
1871 : G_("%<%.*s%> directive writing between %wu and %wu "
1872 "bytes into a region of size %wu"));
1873 warned = fmtwarn (dirloc, pargrange, NULL,
1874 OPT_Wformat_length_, fmtstr,
1875 (int)cvtlen, cvtbeg,
1876 fmtres.range.min, fmtres.range.max,
1877 navail);
1881 res->warned |= warned;
1883 if (warned && fmtres.argmin)
1885 if (fmtres.argmin == fmtres.argmax)
1886 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
1887 else if (fmtres.bounded)
1888 inform (info.fmtloc, "directive argument in the range [%E, %E]",
1889 fmtres.argmin, fmtres.argmax);
1890 else
1891 inform (info.fmtloc,
1892 "using the range [%qE, %qE] for directive argument",
1893 fmtres.argmin, fmtres.argmax);
1897 /* Disable exact length checking but adjust the minimum and maximum. */
1898 res->number_chars = HOST_WIDE_INT_M1U;
1899 if (res->number_chars_max < HOST_WIDE_INT_MAX
1900 && fmtres.range.max < HOST_WIDE_INT_MAX)
1901 res->number_chars_max += fmtres.range.max;
1903 res->number_chars_min += fmtres.range.min;
1905 else
1907 if (!res->warned && fmtres.range.min > 0 && navail < fmtres.range.min)
1909 const char* fmtstr
1910 = (info.bounded
1911 ? (1 < fmtres.range.min
1912 ? G_("%<%.*s%> directive output truncated while writing "
1913 "%wu bytes into a region of size %wu")
1914 : G_("%<%.*s%> directive output truncated while writing "
1915 "%wu byte into a region of size %wu"))
1916 : (1 < fmtres.range.min
1917 ? G_("%<%.*s%> directive writing %wu bytes "
1918 "into a region of size %wu")
1919 : G_("%<%.*s%> directive writing %wu byte "
1920 "into a region of size %wu")));
1922 res->warned = fmtwarn (dirloc, pargrange, NULL,
1923 OPT_Wformat_length_, fmtstr,
1924 (int)cvtlen, cvtbeg, fmtres.range.min,
1925 navail);
1927 *res += fmtres.range.min;
1930 /* Has the minimum directive output length exceeded the maximum
1931 of 4095 bytes required to be supported? */
1932 bool minunder4k = fmtres.range.min < 4096;
1933 if (!minunder4k || fmtres.range.max > 4095)
1934 res->under4k = false;
1936 if (!res->warned && 1 < warn_format_length
1937 && (!minunder4k || fmtres.range.max > 4095))
1939 /* The directive output may be longer than the maximum required
1940 to be handled by an implementation according to 7.21.6.1, p15
1941 of C11. Warn on this only at level 2 but remember this and
1942 prevent folding the return value when done. This allows for
1943 the possibility of the actual libc call failing due to ENOMEM
1944 (like Glibc does under some conditions). */
1946 if (fmtres.range.min == fmtres.range.max)
1947 res->warned = fmtwarn (dirloc, pargrange, NULL,
1948 OPT_Wformat_length_,
1949 "%<%.*s%> directive output of %wu bytes exceeds "
1950 "minimum required size of 4095",
1951 (int)cvtlen, cvtbeg, fmtres.range.min);
1952 else
1954 const char *fmtstr
1955 = (minunder4k
1956 ? G_("%<%.*s%> directive output between %qu and %wu "
1957 "bytes may exceed minimum required size of 4095")
1958 : G_("%<%.*s%> directive output between %qu and %wu "
1959 "bytes exceeds minimum required size of 4095"));
1961 res->warned = fmtwarn (dirloc, pargrange, NULL,
1962 OPT_Wformat_length_, fmtstr,
1963 (int)cvtlen, cvtbeg,
1964 fmtres.range.min, fmtres.range.max);
1968 /* Has the minimum directive output length exceeded INT_MAX? */
1969 bool exceedmin = res->number_chars_min > target_int_max ();
1971 if (!res->warned
1972 && (exceedmin
1973 || (1 < warn_format_length
1974 && res->number_chars_max > target_int_max ())))
1976 /* The directive output causes the total length of output
1977 to exceed INT_MAX bytes. */
1979 if (fmtres.range.min == fmtres.range.max)
1980 res->warned = fmtwarn (dirloc, pargrange, NULL,
1981 OPT_Wformat_length_,
1982 "%<%.*s%> directive output of %wu bytes causes "
1983 "result to exceed %<INT_MAX%>",
1984 (int)cvtlen, cvtbeg, fmtres.range.min);
1985 else
1987 const char *fmtstr
1988 = (exceedmin
1989 ? G_ ("%<%.*s%> directive output between %wu and %wu "
1990 "bytes causes result to exceed %<INT_MAX%>")
1991 : G_ ("%<%.*s%> directive output between %wu and %wu "
1992 "bytes may cause result to exceed %<INT_MAX%>"));
1993 res->warned = fmtwarn (dirloc, pargrange, NULL,
1994 OPT_Wformat_length_, fmtstr,
1995 (int)cvtlen, cvtbeg,
1996 fmtres.range.min, fmtres.range.max);
2001 /* Account for the number of bytes between BEG and END (or between
2002 BEG + strlen (BEG) when END is null) in the format string in a call
2003 to a formatted output function described by INFO. Reflect the count
2004 in RES and issue warnings as appropriate. */
2006 static void
2007 add_bytes (const pass_sprintf_length::call_info &info,
2008 const char *beg, const char *end, format_result *res)
2010 if (res->number_chars_min >= HOST_WIDE_INT_MAX)
2011 return;
2013 /* The number of bytes to output is the number of bytes between
2014 the end of the last directive and the beginning of the next
2015 one if it exists, otherwise the number of characters remaining
2016 in the format string plus 1 for the terminating NUL. */
2017 size_t nbytes = end ? end - beg : strlen (beg) + 1;
2019 /* Return if there are no bytes to add at this time but there are
2020 directives remaining in the format string. */
2021 if (!nbytes)
2022 return;
2024 /* Compute the range of available bytes in the destination. There
2025 must always be at least one byte left for the terminating NUL
2026 that's appended after the format string has been processed. */
2027 result_range avail_range = bytes_remaining (info.objsize, *res);
2029 /* If issuing a diagnostic (only when one hasn't already been issued),
2030 distinguish between a possible overflow ("may write") and a certain
2031 overflow somewhere "past the end." (Ditto for truncation.)
2032 KNOWNRANGE is used to warn even at level 1 about possibly writing
2033 past the end or truncation due to strings of unknown lengths that
2034 are bounded by the arrays they are known to refer to. */
2035 if (!res->warned
2036 && (avail_range.max < nbytes
2037 || ((res->knownrange || 1 < warn_format_length)
2038 && avail_range.min < nbytes)))
2040 /* Set NAVAIL to the number of available bytes used to decide
2041 whether or not to issue a warning below. The exact kind of
2042 warning will depend on AVAIL_RANGE. */
2043 unsigned HOST_WIDE_INT navail = avail_range.max;
2044 if (nbytes <= navail && avail_range.min < HOST_WIDE_INT_MAX
2045 && (res->knownrange || 1 < warn_format_length))
2046 navail = avail_range.min;
2048 /* Compute the offset of the first format character that is beyond
2049 the end of the destination region and the length of the rest of
2050 the format string from that point on. */
2051 unsigned HOST_WIDE_INT off
2052 = (unsigned HOST_WIDE_INT)(beg - info.fmtstr) + navail;
2054 size_t len = strlen (info.fmtstr + off);
2056 /* Create a location that underscores the substring of the format
2057 string that is or may be written past the end (or is or may be
2058 truncated), pointing the caret at the first character of the
2059 substring. */
2060 substring_loc loc
2061 (info.fmtloc, TREE_TYPE (info.format), off, len ? off : 0,
2062 off + len - !!len);
2064 /* Is the output of the last directive the result of the argument
2065 being within a range whose lower bound would fit in the buffer
2066 but the upper bound would not? If so, use the word "may" to
2067 indicate that the overflow/truncation may (but need not) happen. */
2068 bool boundrange
2069 = (res->number_chars_min < res->number_chars_max
2070 && res->number_chars_min < info.objsize);
2072 if (!end && ((nbytes - navail) == 1 || boundrange))
2074 /* There is room for the rest of the format string but none
2075 for the terminating nul. */
2076 const char *text
2077 = (info.bounded // Snprintf and the like.
2078 ? (boundrange
2079 ? G_("output may be truncated before the last format character"
2080 : "output truncated before the last format character"))
2081 : (boundrange
2082 ? G_("may write a terminating nul past the end "
2083 "of the destination")
2084 : G_("writing a terminating nul past the end "
2085 "of the destination")));
2087 res->warned = fmtwarn (loc, NULL, NULL, OPT_Wformat_length_, text);
2089 else
2091 /* There isn't enough room for 1 or more characters that remain
2092 to copy from the format string. */
2093 const char *text
2094 = (info.bounded // Snprintf and the like.
2095 ? (boundrange
2096 ? G_("output may be truncated at or before format character "
2097 "%qc at offset %wu")
2098 : G_("output truncated at format character %qc at offset %wu"))
2099 : (res->number_chars >= HOST_WIDE_INT_MAX
2100 ? G_("may write format character %#qc at offset %wu past "
2101 "the end of the destination")
2102 : G_("writing format character %#qc at offset %wu past "
2103 "the end of the destination")));
2105 res->warned = fmtwarn (loc, NULL, NULL, OPT_Wformat_length_,
2106 text, info.fmtstr[off], off);
2110 if (res->warned && !end && info.objsize < HOST_WIDE_INT_MAX)
2112 /* If a warning has been issued for buffer overflow or truncation
2113 (but not otherwise) help the user figure out how big a buffer
2114 they need. */
2116 location_t callloc = gimple_location (info.callstmt);
2118 unsigned HOST_WIDE_INT min = res->number_chars_min;
2119 unsigned HOST_WIDE_INT max = res->number_chars_max;
2120 unsigned HOST_WIDE_INT exact
2121 = (res->number_chars < HOST_WIDE_INT_MAX
2122 ? res->number_chars : res->number_chars_min);
2124 if (min < max && max < HOST_WIDE_INT_MAX)
2125 inform (callloc,
2126 "format output between %wu and %wu bytes into "
2127 "a destination of size %wu",
2128 min + nbytes, max + nbytes, info.objsize);
2129 else
2130 inform (callloc,
2131 (nbytes + exact == 1
2132 ? G_("format output %wu byte into a destination of size %wu")
2133 : G_("format output %wu bytes into a destination of size %wu")),
2134 nbytes + exact, info.objsize);
2137 /* Add the number of bytes and then check for INT_MAX overflow. */
2138 *res += nbytes;
2140 /* Has the minimum output length minus the terminating nul exceeded
2141 INT_MAX? */
2142 bool exceedmin = (res->number_chars_min - !end) > target_int_max ();
2144 if (!res->warned
2145 && (exceedmin
2146 || (1 < warn_format_length
2147 && (res->number_chars_max - !end) > target_int_max ())))
2149 /* The function's output exceeds INT_MAX bytes. */
2151 /* Set NAVAIL to the number of available bytes used to decide
2152 whether or not to issue a warning below. The exact kind of
2153 warning will depend on AVAIL_RANGE. */
2154 unsigned HOST_WIDE_INT navail = avail_range.max;
2155 if (nbytes <= navail && avail_range.min < HOST_WIDE_INT_MAX
2156 && (res->bounded || 1 < warn_format_length))
2157 navail = avail_range.min;
2159 /* Compute the offset of the first format character that is beyond
2160 the end of the destination region and the length of the rest of
2161 the format string from that point on. */
2162 unsigned HOST_WIDE_INT off = (unsigned HOST_WIDE_INT)(beg - info.fmtstr);
2163 if (navail < HOST_WIDE_INT_MAX)
2164 off += navail;
2166 size_t len = strlen (info.fmtstr + off);
2168 substring_loc loc
2169 (info.fmtloc, TREE_TYPE (info.format), off - !len, len ? off : 0,
2170 off + len - !!len);
2172 if (res->number_chars_min == res->number_chars_max)
2173 res->warned = fmtwarn (loc, NULL, NULL,
2174 OPT_Wformat_length_,
2175 "output of %wu bytes causes "
2176 "result to exceed %<INT_MAX%>",
2177 res->number_chars_min - !end);
2178 else
2180 const char *text
2181 = (exceedmin
2182 ? G_ ("output between %wu and %wu bytes causes "
2183 "result to exceed %<INT_MAX%>")
2184 : G_ ("output between %wu and %wu bytes may cause "
2185 "result to exceed %<INT_MAX%>"));
2186 res->warned = fmtwarn (loc, NULL, NULL, OPT_Wformat_length_,
2187 text,
2188 res->number_chars_min - !end,
2189 res->number_chars_max - !end);
2194 #pragma GCC diagnostic pop
2196 /* Compute the length of the output resulting from the call to a formatted
2197 output function described by INFO and store the result of the call in
2198 *RES. Issue warnings for detected past the end writes. Return true
2199 if the complete format string has been processed and *RES can be relied
2200 on, false otherwise (e.g., when a unknown or unhandled directive was seen
2201 that caused the processing to be terminated early). */
2203 bool
2204 pass_sprintf_length::compute_format_length (const call_info &info,
2205 format_result *res)
2207 /* The variadic argument counter. */
2208 unsigned argno = info.argidx;
2210 /* Reset exact, minimum, and maximum character counters. */
2211 res->number_chars = res->number_chars_min = res->number_chars_max = 0;
2213 /* No directive has been seen yet so the length of output is bounded
2214 by the known range [0, 0] and constant (with no conversion producing
2215 more than 4K bytes) until determined otherwise. */
2216 res->bounded = true;
2217 res->knownrange = true;
2218 res->constant = true;
2219 res->under4k = true;
2220 res->floating = false;
2221 res->warned = false;
2223 const char *pf = info.fmtstr;
2225 for ( ; ; )
2227 /* The beginning of the next format directive. */
2228 const char *dir = strchr (pf, '%');
2230 /* Add the number of bytes between the end of the last directive
2231 and either the next if one exists, or the end of the format
2232 string. */
2233 add_bytes (info, pf, dir, res);
2235 if (!dir)
2236 break;
2238 pf = dir + 1;
2240 if (0 && *pf == 0)
2242 /* Incomplete directive. */
2243 return false;
2246 conversion_spec spec = conversion_spec ();
2248 /* POSIX numbered argument index or zero when none. */
2249 unsigned dollar = 0;
2251 if (ISDIGIT (*pf))
2253 /* This could be either a POSIX positional argument, the '0'
2254 flag, or a width, depending on what follows. Store it as
2255 width and sort it out later after the next character has
2256 been seen. */
2257 char *end;
2258 spec.width = strtol (pf, &end, 10);
2259 spec.have_width = true;
2260 pf = end;
2262 else if ('*' == *pf)
2264 /* Similarly to the block above, this could be either a POSIX
2265 positional argument or a width, depending on what follows. */
2266 if (gimple_call_num_args (info.callstmt) <= argno)
2267 return false;
2269 spec.star_width = gimple_call_arg (info.callstmt, argno++);
2270 ++pf;
2273 if (*pf == '$')
2275 /* Handle the POSIX dollar sign which references the 1-based
2276 positional argument number. */
2277 if (spec.have_width)
2278 dollar = spec.width + info.argidx;
2279 else if (spec.star_width
2280 && TREE_CODE (spec.star_width) == INTEGER_CST)
2281 dollar = spec.width + tree_to_shwi (spec.star_width);
2283 /* Bail when the numbered argument is out of range (it will
2284 have already been diagnosed by -Wformat). */
2285 if (dollar == 0
2286 || dollar == info.argidx
2287 || dollar > gimple_call_num_args (info.callstmt))
2288 return false;
2290 --dollar;
2292 spec.star_width = NULL_TREE;
2293 spec.have_width = false;
2294 ++pf;
2297 if (dollar || !spec.star_width)
2299 if (spec.have_width)
2301 if (spec.width == 0)
2303 /* The '0' that has been interpreted as a width above is
2304 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
2305 and continue processing other flags. */
2306 spec.have_width = false;
2307 spec.set_flag ('0');
2309 else if (!dollar)
2311 /* (Non-zero) width has been seen. The next character
2312 is either a period or a digit. */
2313 goto start_precision;
2316 /* When either '$' has been seen, or width has not been seen,
2317 the next field is the optional flags followed by an optional
2318 width. */
2319 for ( ; ; ) {
2320 switch (*pf)
2322 case ' ':
2323 case '0':
2324 case '+':
2325 case '-':
2326 case '#':
2327 spec.set_flag (*pf++);
2328 break;
2330 default:
2331 goto start_width;
2335 start_width:
2336 if (ISDIGIT (*pf))
2338 char *end;
2339 spec.width = strtol (pf, &end, 10);
2340 spec.have_width = true;
2341 pf = end;
2343 else if ('*' == *pf)
2345 spec.star_width = gimple_call_arg (info.callstmt, argno++);
2346 ++pf;
2348 else if ('\'' == *pf)
2350 /* The POSIX apostrophe indicating a numeric grouping
2351 in the current locale. Even though it's possible to
2352 estimate the upper bound on the size of the output
2353 based on the number of digits it probably isn't worth
2354 continuing. */
2355 return false;
2359 start_precision:
2360 if ('.' == *pf)
2362 ++pf;
2364 if (ISDIGIT (*pf))
2366 char *end;
2367 spec.precision = strtol (pf, &end, 10);
2368 spec.have_precision = true;
2369 pf = end;
2371 else if ('*' == *pf)
2373 spec.star_precision = gimple_call_arg (info.callstmt, argno++);
2374 ++pf;
2376 else
2378 /* The decimal precision or the asterisk are optional.
2379 When neither is specified it's taken to be zero. */
2380 spec.precision = 0;
2381 spec.have_precision = true;
2385 switch (*pf)
2387 case 'h':
2388 if (pf[1] == 'h')
2390 ++pf;
2391 spec.modifier = FMT_LEN_hh;
2393 else
2394 spec.modifier = FMT_LEN_h;
2395 ++pf;
2396 break;
2398 case 'j':
2399 spec.modifier = FMT_LEN_j;
2400 ++pf;
2401 break;
2403 case 'L':
2404 spec.modifier = FMT_LEN_L;
2405 ++pf;
2406 break;
2408 case 'l':
2409 if (pf[1] == 'l')
2411 ++pf;
2412 spec.modifier = FMT_LEN_ll;
2414 else
2415 spec.modifier = FMT_LEN_l;
2416 ++pf;
2417 break;
2419 case 't':
2420 spec.modifier = FMT_LEN_t;
2421 ++pf;
2422 break;
2424 case 'z':
2425 spec.modifier = FMT_LEN_z;
2426 ++pf;
2427 break;
2430 switch (*pf)
2432 /* Handle a sole '%' character the same as "%%" but since it's
2433 undefined prevent the result from being folded. */
2434 case '\0':
2435 --pf;
2436 res->bounded = false;
2437 /* FALLTHRU */
2438 case '%':
2439 spec.fmtfunc = format_percent;
2440 break;
2442 case 'a':
2443 case 'A':
2444 case 'e':
2445 case 'E':
2446 case 'f':
2447 case 'F':
2448 case 'g':
2449 case 'G':
2450 res->floating = true;
2451 spec.fmtfunc = format_floating;
2452 break;
2454 case 'd':
2455 case 'i':
2456 case 'o':
2457 case 'u':
2458 case 'x':
2459 case 'X':
2460 spec.fmtfunc = format_integer;
2461 break;
2463 case 'p':
2464 /* The %p output is implementation-defined. It's possible
2465 to determine this format but due to extensions (especially
2466 those of the Linux kernel -- see bug 78512) the first %p
2467 in the format string disables any further processing. */
2468 return false;
2470 case 'n':
2471 break;
2473 case 'c':
2474 case 'S':
2475 case 's':
2476 spec.fmtfunc = format_string;
2477 break;
2479 default:
2480 /* Unknown conversion specification. */
2481 return false;
2484 spec.specifier = *pf++;
2486 /* Compute the length of the format directive. */
2487 size_t dirlen = pf - dir;
2489 /* Extract the argument if the directive takes one and if it's
2490 available (e.g., the function doesn't take a va_list). Treat
2491 missing arguments the same as va_list, even though they will
2492 have likely already been diagnosed by -Wformat. */
2493 tree arg = NULL_TREE;
2494 if (spec.specifier != '%'
2495 && argno < gimple_call_num_args (info.callstmt))
2496 arg = gimple_call_arg (info.callstmt, dollar ? dollar : argno++);
2498 ::format_directive (info, res, dir, dirlen, spec, arg);
2501 /* Complete format string was processed (with or without warnings). */
2502 return true;
2505 /* Return the size of the object referenced by the expression DEST if
2506 available, or -1 otherwise. */
2508 static unsigned HOST_WIDE_INT
2509 get_destination_size (tree dest)
2511 /* Use __builtin_object_size to determine the size of the destination
2512 object. When optimizing, determine the smallest object (such as
2513 a member array as opposed to the whole enclosing object), otherwise
2514 use type-zero object size to determine the size of the enclosing
2515 object (the function fails without optimization in this type). */
2516 int ost = optimize > 0;
2517 unsigned HOST_WIDE_INT size;
2518 if (compute_builtin_object_size (dest, ost, &size))
2519 return size;
2521 return HOST_WIDE_INT_M1U;
2524 /* Given a suitable result RES of a call to a formatted output function
2525 described by INFO, substitute the result for the return value of
2526 the call. The result is suitable if the number of bytes it represents
2527 is known and exact. A result that isn't suitable for substitution may
2528 have its range set to the range of return values, if that is known. */
2530 static void
2531 try_substitute_return_value (gimple_stmt_iterator *gsi,
2532 const pass_sprintf_length::call_info &info,
2533 const format_result &res)
2535 tree lhs = gimple_get_lhs (info.callstmt);
2537 /* Avoid the return value optimization when the behavior of the call
2538 is undefined either because any directive may have produced 4K or
2539 more of output, or the return value exceeds INT_MAX, or because
2540 the output overflows the destination object (but leave it enabled
2541 when the function is bounded because then the behavior is well-
2542 defined). */
2543 if (lhs && res.bounded && res.under4k
2544 && (info.bounded || res.number_chars <= info.objsize)
2545 && res.number_chars - 1 <= target_int_max ())
2547 tree cst = build_int_cst (integer_type_node, res.number_chars - 1);
2549 if (info.nowrite)
2551 /* Replace the call to the bounded function with a zero size
2552 (e.g., snprintf(0, 0, "%i", 123) with the constant result
2553 of the function minus 1 for the terminating NUL which
2554 the function's return value does not include. */
2555 if (!update_call_from_tree (gsi, cst))
2556 gimplify_and_update_call_from_tree (gsi, cst);
2557 gimple *callstmt = gsi_stmt (*gsi);
2558 update_stmt (callstmt);
2560 else
2562 /* Replace the left-hand side of the call with the constant
2563 result of the formatted function minus 1 for the terminating
2564 NUL which the function's return value does not include. */
2565 gimple_call_set_lhs (info.callstmt, NULL_TREE);
2566 gimple *g = gimple_build_assign (lhs, cst);
2567 gsi_insert_after (gsi, g, GSI_NEW_STMT);
2568 update_stmt (info.callstmt);
2571 if (dump_file)
2573 location_t callloc = gimple_location (info.callstmt);
2574 fprintf (dump_file, "On line %i substituting ",
2575 LOCATION_LINE (callloc));
2576 print_generic_expr (dump_file, cst, dump_flags);
2577 fprintf (dump_file, " for ");
2578 print_generic_expr (dump_file, info.func, dump_flags);
2579 fprintf (dump_file, " %s (output %s).\n",
2580 info.nowrite ? "call" : "return value",
2581 res.constant ? "constant" : "variable");
2584 else
2586 unsigned HOST_WIDE_INT maxbytes;
2588 if (lhs
2589 && res.bounded
2590 && ((maxbytes = res.number_chars - 1) <= target_int_max ()
2591 || (res.number_chars_min - 1 <= target_int_max ()
2592 && (maxbytes = res.number_chars_max - 1) <= target_int_max ()))
2593 && (info.bounded || maxbytes < info.objsize))
2595 /* If the result is in a valid range bounded by the size of
2596 the destination set it so that it can be used for subsequent
2597 optimizations. */
2598 int prec = TYPE_PRECISION (integer_type_node);
2600 if (res.number_chars < target_int_max () && res.under4k)
2602 wide_int num = wi::shwi (res.number_chars - 1, prec);
2603 set_range_info (lhs, VR_RANGE, num, num);
2605 else if (res.number_chars_min < target_int_max ()
2606 && res.number_chars_max < target_int_max ())
2608 wide_int min = wi::shwi (res.under4k ? res.number_chars_min - 1
2609 : target_int_min (), prec);
2610 wide_int max = wi::shwi (res.number_chars_max - 1, prec);
2611 set_range_info (lhs, VR_RANGE, min, max);
2615 if (dump_file)
2617 const char *inbounds
2618 = (res.number_chars_min <= info.objsize
2619 ? (res.number_chars_max <= info.objsize
2620 ? "in" : "potentially out-of")
2621 : "out-of");
2623 location_t callloc = gimple_location (info.callstmt);
2624 fprintf (dump_file, "On line %i ", LOCATION_LINE (callloc));
2625 print_generic_expr (dump_file, info.func, dump_flags);
2627 const char *ign = lhs ? "" : " ignored";
2628 if (res.number_chars >= HOST_WIDE_INT_MAX)
2629 fprintf (dump_file,
2630 " %s-bounds return value in range [%lu, %lu]%s.\n",
2631 inbounds,
2632 (unsigned long)res.number_chars_min,
2633 (unsigned long)res.number_chars_max, ign);
2634 else
2635 fprintf (dump_file, " %s-bounds return value %lu%s.\n",
2636 inbounds, (unsigned long)res.number_chars, ign);
2641 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
2642 functions and if so, handle it. */
2644 void
2645 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator *gsi)
2647 call_info info = call_info ();
2649 info.callstmt = gsi_stmt (*gsi);
2650 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
2651 return;
2653 info.func = gimple_call_fndecl (info.callstmt);
2654 info.fncode = DECL_FUNCTION_CODE (info.func);
2656 /* The size of the destination as in snprintf(dest, size, ...). */
2657 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
2659 /* The size of the destination determined by __builtin_object_size. */
2660 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
2662 /* Buffer size argument number (snprintf and vsnprintf). */
2663 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
2665 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
2666 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
2668 /* Format string argument number (valid for all functions). */
2669 unsigned idx_format;
2671 switch (info.fncode)
2673 case BUILT_IN_SPRINTF:
2674 // Signature:
2675 // __builtin_sprintf (dst, format, ...)
2676 idx_format = 1;
2677 info.argidx = 2;
2678 break;
2680 case BUILT_IN_SPRINTF_CHK:
2681 // Signature:
2682 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
2683 idx_objsize = 2;
2684 idx_format = 3;
2685 info.argidx = 4;
2686 break;
2688 case BUILT_IN_SNPRINTF:
2689 // Signature:
2690 // __builtin_snprintf (dst, size, format, ...)
2691 idx_dstsize = 1;
2692 idx_format = 2;
2693 info.argidx = 3;
2694 info.bounded = true;
2695 break;
2697 case BUILT_IN_SNPRINTF_CHK:
2698 // Signature:
2699 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
2700 idx_dstsize = 1;
2701 idx_objsize = 3;
2702 idx_format = 4;
2703 info.argidx = 5;
2704 info.bounded = true;
2705 break;
2707 case BUILT_IN_VSNPRINTF:
2708 // Signature:
2709 // __builtin_vsprintf (dst, size, format, va)
2710 idx_dstsize = 1;
2711 idx_format = 2;
2712 info.argidx = -1;
2713 info.bounded = true;
2714 break;
2716 case BUILT_IN_VSNPRINTF_CHK:
2717 // Signature:
2718 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
2719 idx_dstsize = 1;
2720 idx_objsize = 3;
2721 idx_format = 4;
2722 info.argidx = -1;
2723 info.bounded = true;
2724 break;
2726 case BUILT_IN_VSPRINTF:
2727 // Signature:
2728 // __builtin_vsprintf (dst, format, va)
2729 idx_format = 1;
2730 info.argidx = -1;
2731 break;
2733 case BUILT_IN_VSPRINTF_CHK:
2734 // Signature:
2735 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
2736 idx_format = 3;
2737 idx_objsize = 2;
2738 info.argidx = -1;
2739 break;
2741 default:
2742 return;
2745 info.format = gimple_call_arg (info.callstmt, idx_format);
2747 if (idx_dstsize == HOST_WIDE_INT_M1U)
2749 /* For non-bounded functions like sprintf, determine the size
2750 of the destination from the object or pointer passed to it
2751 as the first argument. */
2752 dstsize = get_destination_size (gimple_call_arg (info.callstmt, 0));
2754 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
2756 /* For bounded functions try to get the size argument. */
2758 if (TREE_CODE (size) == INTEGER_CST)
2760 dstsize = tree_to_uhwi (size);
2761 /* No object can be larger than SIZE_MAX bytes (half the address
2762 space) on the target.
2763 The functions are defined only for output of at most INT_MAX
2764 bytes. Specifying a bound in excess of that limit effectively
2765 defeats the bounds checking (and on some implementations such
2766 as Solaris cause the function to fail with EINVAL). */
2767 if (dstsize > target_size_max () / 2)
2769 /* Avoid warning if -Wstringop-overflow is specified since
2770 it also warns for the same thing though only for the
2771 checking built-ins. */
2772 if ((idx_objsize == HOST_WIDE_INT_M1U
2773 || !warn_stringop_overflow))
2774 warning_at (gimple_location (info.callstmt),
2775 OPT_Wformat_length_,
2776 "specified bound %wu exceeds maximum object size "
2777 "%wu",
2778 dstsize, target_size_max () / 2);
2780 else if (dstsize > target_int_max ())
2781 warning_at (gimple_location (info.callstmt), OPT_Wformat_length_,
2782 "specified bound %wu exceeds %<INT_MAX %>",
2783 dstsize);
2785 else if (TREE_CODE (size) == SSA_NAME)
2787 /* Try to determine the range of values of the argument
2788 and use the greater of the two at -Wformat-level 1 and
2789 the smaller of them at level 2. */
2790 wide_int min, max;
2791 enum value_range_type range_type
2792 = get_range_info (size, &min, &max);
2793 if (range_type == VR_RANGE)
2795 dstsize
2796 = (warn_format_length < 2
2797 ? wi::fits_uhwi_p (max) ? max.to_uhwi () : max.to_shwi ()
2798 : wi::fits_uhwi_p (min) ? min.to_uhwi () : min.to_shwi ());
2803 if (idx_objsize != HOST_WIDE_INT_M1U)
2805 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
2806 if (tree_fits_uhwi_p (size))
2807 objsize = tree_to_uhwi (size);
2810 if (info.bounded && !dstsize)
2812 /* As a special case, when the explicitly specified destination
2813 size argument (to a bounded function like snprintf) is zero
2814 it is a request to determine the number of bytes on output
2815 without actually producing any. Pretend the size is
2816 unlimited in this case. */
2817 info.objsize = HOST_WIDE_INT_MAX;
2818 info.nowrite = true;
2820 else
2822 /* Set the object size to the smaller of the two arguments
2823 of both have been specified and they're not equal. */
2824 info.objsize = dstsize < objsize ? dstsize : objsize;
2826 if (info.bounded
2827 && dstsize < target_size_max () / 2 && objsize < dstsize
2828 /* Avoid warning if -Wstringop-overflow is specified since
2829 it also warns for the same thing though only for the
2830 checking built-ins. */
2831 && (idx_objsize == HOST_WIDE_INT_M1U
2832 || !warn_stringop_overflow))
2834 warning_at (gimple_location (info.callstmt), OPT_Wformat_length_,
2835 "specified bound %wu exceeds the size %wu "
2836 "of the destination object", dstsize, objsize);
2840 if (integer_zerop (info.format))
2842 /* This is diagnosed with -Wformat only when the null is a constant
2843 pointer. The warning here diagnoses instances where the pointer
2844 is not constant. */
2845 warning_at (EXPR_LOC_OR_LOC (info.format, input_location),
2846 OPT_Wformat_length_, "null format string");
2847 return;
2850 info.fmtstr = get_format_string (info.format, &info.fmtloc);
2851 if (!info.fmtstr)
2852 return;
2854 /* The result is the number of bytes output by the formatted function,
2855 including the terminating NUL. */
2856 format_result res = format_result ();
2858 bool success = compute_format_length (info, &res);
2860 /* When optimizing and the printf return value optimization is enabled,
2861 attempt to substitute the computed result for the return value of
2862 the call. Avoid this optimization when -frounding-math is in effect
2863 and the format string contains a floating point directive. */
2864 if (success
2865 && optimize > 0
2866 && flag_printf_return_value
2867 && (!flag_rounding_math || !res.floating))
2868 try_substitute_return_value (gsi, info, res);
2871 /* Execute the pass for function FUN. */
2873 unsigned int
2874 pass_sprintf_length::execute (function *fun)
2876 basic_block bb;
2877 FOR_EACH_BB_FN (bb, fun)
2879 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si);
2880 gsi_next (&si))
2882 /* Iterate over statements, looking for function calls. */
2883 gimple *stmt = gsi_stmt (si);
2885 if (is_gimple_call (stmt))
2886 handle_gimple_call (&si);
2890 return 0;
2893 } /* Unnamed namespace. */
2895 /* Return a pointer to a pass object newly constructed from the context
2896 CTXT. */
2898 gimple_opt_pass *
2899 make_pass_sprintf_length (gcc::context *ctxt)
2901 return new pass_sprintf_length (ctxt);