* gcc-interface/trans.c (Subprogram_Body_to_gnu): Initialize locus.
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blob35ceb2cfb75914d26f4245ce25cda0205c4edd8a
1 /* Copyright (C) 2016-2017 Free Software Foundation, Inc.
2 Contributed by Martin Sebor <msebor@redhat.com>.
4 This file is part of GCC.
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
20 /* This file implements the printf-return-value pass. The pass does
21 two things: 1) it analyzes calls to formatted output functions like
22 sprintf looking for possible buffer overflows and calls to bounded
23 functions like snprintf for early truncation (and under the control
24 of the -Wformat-length option issues warnings), and 2) under the
25 control of the -fprintf-return-value option it folds the return
26 value of safe calls into constants, making it possible to eliminate
27 code that depends on the value of those constants.
29 For all functions (bounded or not) the pass uses the size of the
30 destination object. That means that it will diagnose calls to
31 snprintf not on the basis of the size specified by the function's
32 second argument but rathger on the basis of the size the first
33 argument points to (if possible). For bound-checking built-ins
34 like __builtin___snprintf_chk the pass uses the size typically
35 determined by __builtin_object_size and passed to the built-in
36 by the Glibc inline wrapper.
38 The pass handles all forms standard sprintf format directives,
39 including character, integer, floating point, pointer, and strings,
40 with the standard C flags, widths, and precisions. For integers
41 and strings it computes the length of output itself. For floating
42 point it uses MPFR to fornmat known constants with up and down
43 rounding and uses the resulting range of output lengths. For
44 strings it uses the length of string literals and the sizes of
45 character arrays that a character pointer may point to as a bound
46 on the longest string. */
48 #include "config.h"
49 #include "system.h"
50 #include "coretypes.h"
51 #include "backend.h"
52 #include "tree.h"
53 #include "gimple.h"
54 #include "tree-pass.h"
55 #include "ssa.h"
56 #include "gimple-fold.h"
57 #include "gimple-pretty-print.h"
58 #include "diagnostic-core.h"
59 #include "fold-const.h"
60 #include "gimple-iterator.h"
61 #include "tree-ssa.h"
62 #include "tree-object-size.h"
63 #include "params.h"
64 #include "tree-cfg.h"
65 #include "tree-ssa-propagate.h"
66 #include "calls.h"
67 #include "cfgloop.h"
68 #include "intl.h"
69 #include "langhooks.h"
71 #include "builtins.h"
72 #include "stor-layout.h"
74 #include "realmpfr.h"
75 #include "target.h"
77 #include "cpplib.h"
78 #include "input.h"
79 #include "toplev.h"
80 #include "substring-locations.h"
81 #include "diagnostic.h"
82 #include "domwalk.h"
84 /* The likely worst case value of MB_LEN_MAX for the target, large enough
85 for UTF-8. Ideally, this would be obtained by a target hook if it were
86 to be used for optimization but it's good enough as is for warnings. */
87 #define target_mb_len_max() 6
89 /* The maximum number of bytes a single non-string directive can result
90 in. This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
91 LDBL_MAX_10_EXP of 4932. */
92 #define IEEE_MAX_10_EXP 4932
93 #define target_dir_max() (target_int_max () + IEEE_MAX_10_EXP + 2)
95 namespace {
97 const pass_data pass_data_sprintf_length = {
98 GIMPLE_PASS, // pass type
99 "printf-return-value", // pass name
100 OPTGROUP_NONE, // optinfo_flags
101 TV_NONE, // tv_id
102 PROP_cfg, // properties_required
103 0, // properties_provided
104 0, // properties_destroyed
105 0, // properties_start
106 0, // properties_finish
109 /* Set to the warning level for the current function which is equal
110 either to warn_format_trunc for bounded functions or to
111 warn_format_overflow otherwise. */
113 static int warn_level;
115 struct format_result;
117 class sprintf_dom_walker : public dom_walker
119 public:
120 sprintf_dom_walker () : dom_walker (CDI_DOMINATORS) {}
121 ~sprintf_dom_walker () {}
123 edge before_dom_children (basic_block) FINAL OVERRIDE;
124 bool handle_gimple_call (gimple_stmt_iterator *);
126 struct call_info;
127 bool compute_format_length (call_info &, format_result *);
130 class pass_sprintf_length : public gimple_opt_pass
132 bool fold_return_value;
134 public:
135 pass_sprintf_length (gcc::context *ctxt)
136 : gimple_opt_pass (pass_data_sprintf_length, ctxt),
137 fold_return_value (false)
140 opt_pass * clone () { return new pass_sprintf_length (m_ctxt); }
142 virtual bool gate (function *);
144 virtual unsigned int execute (function *);
146 void set_pass_param (unsigned int n, bool param)
148 gcc_assert (n == 0);
149 fold_return_value = param;
154 bool
155 pass_sprintf_length::gate (function *)
157 /* Run the pass iff -Warn-format-overflow or -Warn-format-truncation
158 is specified and either not optimizing and the pass is being invoked
159 early, or when optimizing and the pass is being invoked during
160 optimization (i.e., "late"). */
161 return ((warn_format_overflow > 0
162 || warn_format_trunc > 0
163 || flag_printf_return_value)
164 && (optimize > 0) == fold_return_value);
167 /* The minimum, maximum, likely, and unlikely maximum number of bytes
168 of output either a formatting function or an individual directive
169 can result in. */
171 struct result_range
173 /* The absolute minimum number of bytes. The result of a successful
174 conversion is guaranteed to be no less than this. (An erroneous
175 conversion can be indicated by MIN > HOST_WIDE_INT_MAX.) */
176 unsigned HOST_WIDE_INT min;
177 /* The likely maximum result that is used in diagnostics. In most
178 cases MAX is the same as the worst case UNLIKELY result. */
179 unsigned HOST_WIDE_INT max;
180 /* The likely result used to trigger diagnostics. For conversions
181 that result in a range of bytes [MIN, MAX], LIKELY is somewhere
182 in that range. */
183 unsigned HOST_WIDE_INT likely;
184 /* In rare cases (e.g., for nultibyte characters) UNLIKELY gives
185 the worst cases maximum result of a directive. In most cases
186 UNLIKELY == MAX. UNLIKELY is used to control the return value
187 optimization but not in diagnostics. */
188 unsigned HOST_WIDE_INT unlikely;
191 /* The result of a call to a formatted function. */
193 struct format_result
195 /* Range of characters written by the formatted function.
196 Setting the minimum to HOST_WIDE_INT_MAX disables all
197 length tracking for the remainder of the format string. */
198 result_range range;
200 /* True when the range above is obtained from known values of
201 directive arguments, or bounds on the amount of output such
202 as width and precision, and not the result of heuristics that
203 depend on warning levels. It's used to issue stricter diagnostics
204 in cases where strings of unknown lengths are bounded by the arrays
205 they are determined to refer to. KNOWNRANGE must not be used for
206 the return value optimization. */
207 bool knownrange;
209 /* True if no individual directive resulted in more than 4095 bytes
210 of output (the total NUMBER_CHARS_{MIN,MAX} might be greater).
211 Implementations are not required to handle directives that produce
212 more than 4K bytes (leading to undefined behavior) and so when one
213 is found it disables the return value optimization. */
214 bool under4k;
216 /* True when a floating point directive has been seen in the format
217 string. */
218 bool floating;
220 /* True when an intermediate result has caused a warning. Used to
221 avoid issuing duplicate warnings while finishing the processing
222 of a call. WARNED also disables the return value optimization. */
223 bool warned;
225 /* Preincrement the number of output characters by 1. */
226 format_result& operator++ ()
228 return *this += 1;
231 /* Postincrement the number of output characters by 1. */
232 format_result operator++ (int)
234 format_result prev (*this);
235 *this += 1;
236 return prev;
239 /* Increment the number of output characters by N. */
240 format_result& operator+= (unsigned HOST_WIDE_INT);
243 format_result&
244 format_result::operator+= (unsigned HOST_WIDE_INT n)
246 gcc_assert (n < HOST_WIDE_INT_MAX);
248 if (range.min < HOST_WIDE_INT_MAX)
249 range.min += n;
251 if (range.max < HOST_WIDE_INT_MAX)
252 range.max += n;
254 if (range.likely < HOST_WIDE_INT_MAX)
255 range.likely += n;
257 if (range.unlikely < HOST_WIDE_INT_MAX)
258 range.unlikely += n;
260 return *this;
263 /* Return the value of INT_MIN for the target. */
265 static inline HOST_WIDE_INT
266 target_int_min ()
268 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
271 /* Return the value of INT_MAX for the target. */
273 static inline unsigned HOST_WIDE_INT
274 target_int_max ()
276 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
279 /* Return the value of SIZE_MAX for the target. */
281 static inline unsigned HOST_WIDE_INT
282 target_size_max ()
284 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
287 /* A straightforward mapping from the execution character set to the host
288 character set indexed by execution character. */
290 static char target_to_host_charmap[256];
292 /* Initialize a mapping from the execution character set to the host
293 character set. */
295 static bool
296 init_target_to_host_charmap ()
298 /* If the percent sign is non-zero the mapping has already been
299 initialized. */
300 if (target_to_host_charmap['%'])
301 return true;
303 /* Initialize the target_percent character (done elsewhere). */
304 if (!init_target_chars ())
305 return false;
307 /* The subset of the source character set used by printf conversion
308 specifications (strictly speaking, not all letters are used but
309 they are included here for the sake of simplicity). The dollar
310 sign must be included even though it's not in the basic source
311 character set. */
312 const char srcset[] = " 0123456789!\"#%&'()*+,-./:;<=>?[\\]^_{|}~$"
313 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
315 /* Set the mapping for all characters to some ordinary value (i,e.,
316 not none used in printf conversion specifications) and overwrite
317 those that are used by conversion specifications with their
318 corresponding values. */
319 memset (target_to_host_charmap + 1, '?', sizeof target_to_host_charmap - 1);
321 /* Are the two sets of characters the same? */
322 bool all_same_p = true;
324 for (const char *pc = srcset; *pc; ++pc)
326 /* Slice off the high end bits in case target characters are
327 signed. All values are expected to be non-nul, otherwise
328 there's a problem. */
329 if (unsigned char tc = lang_hooks.to_target_charset (*pc))
331 target_to_host_charmap[tc] = *pc;
332 if (tc != *pc)
333 all_same_p = false;
335 else
336 return false;
340 /* Set the first element to a non-zero value if the mapping
341 is 1-to-1, otherwise leave it clear (NUL is assumed to be
342 the same in both character sets). */
343 target_to_host_charmap[0] = all_same_p;
345 return true;
348 /* Return the host source character corresponding to the character
349 CH in the execution character set if one exists, or some innocuous
350 (non-special, non-nul) source character otherwise. */
352 static inline unsigned char
353 target_to_host (unsigned char ch)
355 return target_to_host_charmap[ch];
358 /* Convert an initial substring of the string TARGSTR consisting of
359 characters in the execution character set into a string in the
360 source character set on the host and store up to HOSTSZ characters
361 in the buffer pointed to by HOSTR. Return HOSTR. */
363 static const char*
364 target_to_host (char *hostr, size_t hostsz, const char *targstr)
366 /* Make sure the buffer is reasonably big. */
367 gcc_assert (hostsz > 4);
369 /* The interesting subset of source and execution characters are
370 the same so no conversion is necessary. However, truncate
371 overlong strings just like the translated strings are. */
372 if (target_to_host_charmap['\0'] == 1)
374 strncpy (hostr, targstr, hostsz - 4);
375 if (strlen (targstr) >= hostsz)
376 strcpy (hostr + hostsz - 4, "...");
377 return hostr;
380 /* Convert the initial substring of TARGSTR to the corresponding
381 characters in the host set, appending "..." if TARGSTR is too
382 long to fit. Using the static buffer assumes the function is
383 not called in between sequence points (which it isn't). */
384 for (char *ph = hostr; ; ++targstr)
386 *ph++ = target_to_host (*targstr);
387 if (!*targstr)
388 break;
390 if (size_t (ph - hostr) == hostsz - 4)
392 *ph = '\0';
393 strcat (ph, "...");
394 break;
398 return hostr;
401 /* Convert the sequence of decimal digits in the execution character
402 starting at S to a long, just like strtol does. Return the result
403 and set *END to one past the last converted character. On range
404 error set ERANGE to the digit that caused it. */
406 static inline long
407 target_strtol10 (const char **ps, const char **erange)
409 unsigned HOST_WIDE_INT val = 0;
410 for ( ; ; ++*ps)
412 unsigned char c = target_to_host (**ps);
413 if (ISDIGIT (c))
415 c -= '0';
417 /* Check for overflow. */
418 if (val > (LONG_MAX - c) / 10LU)
420 val = LONG_MAX;
421 *erange = *ps;
423 /* Skip the remaining digits. */
425 c = target_to_host (*++*ps);
426 while (ISDIGIT (c));
427 break;
429 else
430 val = val * 10 + c;
432 else
433 break;
436 return val;
439 /* Return the constant initial value of DECL if available or DECL
440 otherwise. Same as the synonymous function in c/c-typeck.c. */
442 static tree
443 decl_constant_value (tree decl)
445 if (/* Don't change a variable array bound or initial value to a constant
446 in a place where a variable is invalid. Note that DECL_INITIAL
447 isn't valid for a PARM_DECL. */
448 current_function_decl != 0
449 && TREE_CODE (decl) != PARM_DECL
450 && !TREE_THIS_VOLATILE (decl)
451 && TREE_READONLY (decl)
452 && DECL_INITIAL (decl) != 0
453 && TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK
454 /* This is invalid if initial value is not constant.
455 If it has either a function call, a memory reference,
456 or a variable, then re-evaluating it could give different results. */
457 && TREE_CONSTANT (DECL_INITIAL (decl))
458 /* Check for cases where this is sub-optimal, even though valid. */
459 && TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)
460 return DECL_INITIAL (decl);
461 return decl;
464 /* Given FORMAT, set *PLOC to the source location of the format string
465 and return the format string if it is known or null otherwise. */
467 static const char*
468 get_format_string (tree format, location_t *ploc)
470 if (VAR_P (format))
472 /* Pull out a constant value if the front end didn't. */
473 format = decl_constant_value (format);
474 STRIP_NOPS (format);
477 if (integer_zerop (format))
479 /* FIXME: Diagnose null format string if it hasn't been diagnosed
480 by -Wformat (the latter diagnoses only nul pointer constants,
481 this pass can do better). */
482 return NULL;
485 HOST_WIDE_INT offset = 0;
487 if (TREE_CODE (format) == POINTER_PLUS_EXPR)
489 tree arg0 = TREE_OPERAND (format, 0);
490 tree arg1 = TREE_OPERAND (format, 1);
491 STRIP_NOPS (arg0);
492 STRIP_NOPS (arg1);
494 if (TREE_CODE (arg1) != INTEGER_CST)
495 return NULL;
497 format = arg0;
499 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
500 if (!cst_and_fits_in_hwi (arg1))
501 return NULL;
503 offset = int_cst_value (arg1);
506 if (TREE_CODE (format) != ADDR_EXPR)
507 return NULL;
509 *ploc = EXPR_LOC_OR_LOC (format, input_location);
511 format = TREE_OPERAND (format, 0);
513 if (TREE_CODE (format) == ARRAY_REF
514 && tree_fits_shwi_p (TREE_OPERAND (format, 1))
515 && (offset += tree_to_shwi (TREE_OPERAND (format, 1))) >= 0)
516 format = TREE_OPERAND (format, 0);
518 if (offset < 0)
519 return NULL;
521 tree array_init;
522 tree array_size = NULL_TREE;
524 if (VAR_P (format)
525 && TREE_CODE (TREE_TYPE (format)) == ARRAY_TYPE
526 && (array_init = decl_constant_value (format)) != format
527 && TREE_CODE (array_init) == STRING_CST)
529 /* Extract the string constant initializer. Note that this may
530 include a trailing NUL character that is not in the array (e.g.
531 const char a[3] = "foo";). */
532 array_size = DECL_SIZE_UNIT (format);
533 format = array_init;
536 if (TREE_CODE (format) != STRING_CST)
537 return NULL;
539 tree type = TREE_TYPE (format);
541 scalar_int_mode char_mode;
542 if (!is_int_mode (TYPE_MODE (TREE_TYPE (type)), &char_mode)
543 || GET_MODE_SIZE (char_mode) != 1)
545 /* Wide format string. */
546 return NULL;
549 const char *fmtstr = TREE_STRING_POINTER (format);
550 unsigned fmtlen = TREE_STRING_LENGTH (format);
552 if (array_size)
554 /* Variable length arrays can't be initialized. */
555 gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
557 if (tree_fits_shwi_p (array_size))
559 HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
560 if (array_size_value > 0
561 && array_size_value == (int) array_size_value
562 && fmtlen > array_size_value)
563 fmtlen = array_size_value;
566 if (offset)
568 if (offset >= fmtlen)
569 return NULL;
571 fmtstr += offset;
572 fmtlen -= offset;
575 if (fmtlen < 1 || fmtstr[--fmtlen] != 0)
577 /* FIXME: Diagnose an unterminated format string if it hasn't been
578 diagnosed by -Wformat. Similarly to a null format pointer,
579 -Wformay diagnoses only nul pointer constants, this pass can
580 do better). */
581 return NULL;
584 return fmtstr;
587 /* The format_warning_at_substring function is not used here in a way
588 that makes using attribute format viable. Suppress the warning. */
590 #pragma GCC diagnostic push
591 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
593 /* For convenience and brevity. */
595 static bool
596 (* const fmtwarn) (const substring_loc &, location_t,
597 const char *, int, const char *, ...)
598 = format_warning_at_substring;
600 /* Format length modifiers. */
602 enum format_lengths
604 FMT_LEN_none,
605 FMT_LEN_hh, // char argument
606 FMT_LEN_h, // short
607 FMT_LEN_l, // long
608 FMT_LEN_ll, // long long
609 FMT_LEN_L, // long double (and GNU long long)
610 FMT_LEN_z, // size_t
611 FMT_LEN_t, // ptrdiff_t
612 FMT_LEN_j // intmax_t
616 /* Description of the result of conversion either of a single directive
617 or the whole format string. */
619 struct fmtresult
621 /* Construct a FMTRESULT object with all counters initialized
622 to MIN. KNOWNRANGE is set when MIN is valid. */
623 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
624 : argmin (), argmax (),
625 knownrange (min < HOST_WIDE_INT_MAX),
626 nullp ()
628 range.min = min;
629 range.max = min;
630 range.likely = min;
631 range.unlikely = min;
634 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
635 KNOWNRANGE is set when both MIN and MAX are valid. */
636 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
637 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
638 : argmin (), argmax (),
639 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
640 nullp ()
642 range.min = min;
643 range.max = max;
644 range.likely = max < likely ? min : likely;
645 range.unlikely = max;
648 /* Adjust result upward to reflect the RANGE of values the specified
649 width or precision is known to be in. */
650 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
651 tree = NULL_TREE,
652 unsigned = 0, unsigned = 0);
654 /* Return the maximum number of decimal digits a value of TYPE
655 formats as on output. */
656 static unsigned type_max_digits (tree, int);
658 /* The range a directive's argument is in. */
659 tree argmin, argmax;
661 /* The minimum and maximum number of bytes that a directive
662 results in on output for an argument in the range above. */
663 result_range range;
665 /* True when the range above is obtained from a known value of
666 a directive's argument or its bounds and not the result of
667 heuristics that depend on warning levels. */
668 bool knownrange;
670 /* True when the argument is a null pointer. */
671 bool nullp;
674 /* Adjust result upward to reflect the range ADJUST of values the
675 specified width or precision is known to be in. When non-null,
676 TYPE denotes the type of the directive whose result is being
677 adjusted, BASE gives the base of the directive (octal, decimal,
678 or hex), and ADJ denotes the additional adjustment to the LIKELY
679 counter that may need to be added when ADJUST is a range. */
681 fmtresult&
682 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
683 tree type /* = NULL_TREE */,
684 unsigned base /* = 0 */,
685 unsigned adj /* = 0 */)
687 bool minadjusted = false;
689 /* Adjust the minimum and likely counters. */
690 if (adjust[0] >= 0)
692 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
694 range.min = adjust[0];
695 minadjusted = true;
698 /* Adjust the likely counter. */
699 if (range.likely < range.min)
700 range.likely = range.min;
702 else if (adjust[0] == target_int_min ()
703 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
704 knownrange = false;
706 /* Adjust the maximum counter. */
707 if (adjust[1] > 0)
709 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
711 range.max = adjust[1];
713 /* Set KNOWNRANGE if both the minimum and maximum have been
714 adjusted. Otherwise leave it at what it was before. */
715 knownrange = minadjusted;
719 if (warn_level > 1 && type)
721 /* For large non-constant width or precision whose range spans
722 the maximum number of digits produced by the directive for
723 any argument, set the likely number of bytes to be at most
724 the number digits plus other adjustment determined by the
725 caller (one for sign or two for the hexadecimal "0x"
726 prefix). */
727 unsigned dirdigs = type_max_digits (type, base);
728 if (adjust[0] < dirdigs && dirdigs < adjust[1]
729 && range.likely < dirdigs)
730 range.likely = dirdigs + adj;
732 else if (range.likely < (range.min ? range.min : 1))
734 /* Conservatively, set LIKELY to at least MIN but no less than
735 1 unless MAX is zero. */
736 range.likely = (range.min
737 ? range.min
738 : range.max && (range.max < HOST_WIDE_INT_MAX
739 || warn_level > 1) ? 1 : 0);
742 /* Finally adjust the unlikely counter to be at least as large as
743 the maximum. */
744 if (range.unlikely < range.max)
745 range.unlikely = range.max;
747 return *this;
750 /* Return the maximum number of digits a value of TYPE formats in
751 BASE on output, not counting base prefix . */
753 unsigned
754 fmtresult::type_max_digits (tree type, int base)
756 unsigned prec = TYPE_PRECISION (type);
757 if (base == 8)
758 return (prec + 2) / 3;
760 if (base == 16)
761 return prec / 4;
763 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
764 of 8, 16, 32, and 64 bits. */
765 return prec * 301 / 1000 + 1;
768 static bool
769 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT);
771 /* Description of a format directive. A directive is either a plain
772 string or a conversion specification that starts with '%'. */
774 struct directive
776 /* The 1-based directive number (for debugging). */
777 unsigned dirno;
779 /* The first character of the directive and its length. */
780 const char *beg;
781 size_t len;
783 /* A bitmap of flags, one for each character. */
784 unsigned flags[256 / sizeof (int)];
786 /* The range of values of the specified width, or -1 if not specified. */
787 HOST_WIDE_INT width[2];
788 /* The range of values of the specified precision, or -1 if not
789 specified. */
790 HOST_WIDE_INT prec[2];
792 /* Length modifier. */
793 format_lengths modifier;
795 /* Format specifier character. */
796 char specifier;
798 /* The argument of the directive or null when the directive doesn't
799 take one or when none is available (such as for vararg functions). */
800 tree arg;
802 /* Format conversion function that given a directive and an argument
803 returns the formatting result. */
804 fmtresult (*fmtfunc) (const directive &, tree);
806 /* Return True when a the format flag CHR has been used. */
807 bool get_flag (char chr) const
809 unsigned char c = chr & 0xff;
810 return (flags[c / (CHAR_BIT * sizeof *flags)]
811 & (1U << (c % (CHAR_BIT * sizeof *flags))));
814 /* Make a record of the format flag CHR having been used. */
815 void set_flag (char chr)
817 unsigned char c = chr & 0xff;
818 flags[c / (CHAR_BIT * sizeof *flags)]
819 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
822 /* Reset the format flag CHR. */
823 void clear_flag (char chr)
825 unsigned char c = chr & 0xff;
826 flags[c / (CHAR_BIT * sizeof *flags)]
827 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
830 /* Set both bounds of the width range to VAL. */
831 void set_width (HOST_WIDE_INT val)
833 width[0] = width[1] = val;
836 /* Set the width range according to ARG, with both bounds being
837 no less than 0. For a constant ARG set both bounds to its value
838 or 0, whichever is greater. For a non-constant ARG in some range
839 set width to its range adjusting each bound to -1 if it's less.
840 For an indeterminate ARG set width to [0, INT_MAX]. */
841 void set_width (tree arg)
843 get_int_range (arg, width, width + 1, true, 0);
846 /* Set both bounds of the precision range to VAL. */
847 void set_precision (HOST_WIDE_INT val)
849 prec[0] = prec[1] = val;
852 /* Set the precision range according to ARG, with both bounds being
853 no less than -1. For a constant ARG set both bounds to its value
854 or -1 whichever is greater. For a non-constant ARG in some range
855 set precision to its range adjusting each bound to -1 if it's less.
856 For an indeterminate ARG set precision to [-1, INT_MAX]. */
857 void set_precision (tree arg)
859 get_int_range (arg, prec, prec + 1, false, -1);
862 /* Return true if both width and precision are known to be
863 either constant or in some range, false otherwise. */
864 bool known_width_and_precision () const
866 return ((width[1] < 0
867 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
868 && (prec[1] < 0
869 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
873 /* Return the logarithm of X in BASE. */
875 static int
876 ilog (unsigned HOST_WIDE_INT x, int base)
878 int res = 0;
881 ++res;
882 x /= base;
883 } while (x);
884 return res;
887 /* Return the number of bytes resulting from converting into a string
888 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
889 PLUS indicates whether 1 for a plus sign should be added for positive
890 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
891 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
892 be represented. */
894 static HOST_WIDE_INT
895 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
897 unsigned HOST_WIDE_INT absval;
899 HOST_WIDE_INT res;
901 if (TYPE_UNSIGNED (TREE_TYPE (x)))
903 if (tree_fits_uhwi_p (x))
905 absval = tree_to_uhwi (x);
906 res = plus;
908 else
909 return -1;
911 else
913 if (tree_fits_shwi_p (x))
915 HOST_WIDE_INT i = tree_to_shwi (x);
916 if (HOST_WIDE_INT_MIN == i)
918 /* Avoid undefined behavior due to negating a minimum. */
919 absval = HOST_WIDE_INT_MAX;
920 res = 1;
922 else if (i < 0)
924 absval = -i;
925 res = 1;
927 else
929 absval = i;
930 res = plus;
933 else
934 return -1;
937 int ndigs = ilog (absval, base);
939 res += prec < ndigs ? ndigs : prec;
941 /* Adjust a non-zero value for the base prefix, either hexadecimal,
942 or, unless precision has resulted in a leading zero, also octal. */
943 if (prefix && absval && (base == 16 || prec <= ndigs))
945 if (base == 8)
946 res += 1;
947 else if (base == 16)
948 res += 2;
951 return res;
954 /* Given the formatting result described by RES and NAVAIL, the number
955 of available in the destination, return the range of bytes remaining
956 in the destination. */
958 static inline result_range
959 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
961 result_range range;
963 if (HOST_WIDE_INT_MAX <= navail)
965 range.min = range.max = range.likely = range.unlikely = navail;
966 return range;
969 /* The lower bound of the available range is the available size
970 minus the maximum output size, and the upper bound is the size
971 minus the minimum. */
972 range.max = res.range.min < navail ? navail - res.range.min : 0;
974 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
976 if (res.range.max < HOST_WIDE_INT_MAX)
977 range.min = res.range.max < navail ? navail - res.range.max : 0;
978 else
979 range.min = range.likely;
981 range.unlikely = (res.range.unlikely < navail
982 ? navail - res.range.unlikely : 0);
984 return range;
987 /* Description of a call to a formatted function. */
989 struct sprintf_dom_walker::call_info
991 /* Function call statement. */
992 gimple *callstmt;
994 /* Function called. */
995 tree func;
997 /* Called built-in function code. */
998 built_in_function fncode;
1000 /* Format argument and format string extracted from it. */
1001 tree format;
1002 const char *fmtstr;
1004 /* The location of the format argument. */
1005 location_t fmtloc;
1007 /* The destination object size for __builtin___xxx_chk functions
1008 typically determined by __builtin_object_size, or -1 if unknown. */
1009 unsigned HOST_WIDE_INT objsize;
1011 /* Number of the first variable argument. */
1012 unsigned HOST_WIDE_INT argidx;
1014 /* True for functions like snprintf that specify the size of
1015 the destination, false for others like sprintf that don't. */
1016 bool bounded;
1018 /* True for bounded functions like snprintf that specify a zero-size
1019 buffer as a request to compute the size of output without actually
1020 writing any. NOWRITE is cleared in response to the %n directive
1021 which has side-effects similar to writing output. */
1022 bool nowrite;
1024 /* Return true if the called function's return value is used. */
1025 bool retval_used () const
1027 return gimple_get_lhs (callstmt);
1030 /* Return the warning option corresponding to the called function. */
1031 int warnopt () const
1033 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
1037 /* Return the result of formatting a no-op directive (such as '%n'). */
1039 static fmtresult
1040 format_none (const directive &, tree)
1042 fmtresult res (0);
1043 return res;
1046 /* Return the result of formatting the '%%' directive. */
1048 static fmtresult
1049 format_percent (const directive &, tree)
1051 fmtresult res (1);
1052 return res;
1056 /* Compute intmax_type_node and uintmax_type_node similarly to how
1057 tree.c builds size_type_node. */
1059 static void
1060 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
1062 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
1064 *pintmax = integer_type_node;
1065 *puintmax = unsigned_type_node;
1067 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
1069 *pintmax = long_integer_type_node;
1070 *puintmax = long_unsigned_type_node;
1072 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
1074 *pintmax = long_long_integer_type_node;
1075 *puintmax = long_long_unsigned_type_node;
1077 else
1079 for (int i = 0; i < NUM_INT_N_ENTS; i++)
1080 if (int_n_enabled_p[i])
1082 char name[50];
1083 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
1085 if (strcmp (name, UINTMAX_TYPE) == 0)
1087 *pintmax = int_n_trees[i].signed_type;
1088 *puintmax = int_n_trees[i].unsigned_type;
1089 return;
1092 gcc_unreachable ();
1096 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1097 in and that is representable in type int.
1098 Return true when the range is a subrange of that of int.
1099 When ARG is null it is as if it had the full range of int.
1100 When ABSOLUTE is true the range reflects the absolute value of
1101 the argument. When ABSOLUTE is false, negative bounds of
1102 the determined range are replaced with NEGBOUND. */
1104 static bool
1105 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1106 bool absolute, HOST_WIDE_INT negbound)
1108 /* The type of the result. */
1109 const_tree type = integer_type_node;
1111 bool knownrange = false;
1113 if (!arg)
1115 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1116 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1118 else if (TREE_CODE (arg) == INTEGER_CST
1119 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1121 /* For a constant argument return its value adjusted as specified
1122 by NEGATIVE and NEGBOUND and return true to indicate that the
1123 result is known. */
1124 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1125 *pmax = *pmin;
1126 knownrange = true;
1128 else
1130 /* True if the argument's range cannot be determined. */
1131 bool unknown = true;
1133 tree argtype = TREE_TYPE (arg);
1135 /* Ignore invalid arguments with greater precision that that
1136 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1137 They will have been detected and diagnosed by -Wformat and
1138 so it's not important to complicate this code to try to deal
1139 with them again. */
1140 if (TREE_CODE (arg) == SSA_NAME
1141 && INTEGRAL_TYPE_P (argtype)
1142 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1144 /* Try to determine the range of values of the integer argument. */
1145 wide_int min, max;
1146 enum value_range_type range_type = get_range_info (arg, &min, &max);
1147 if (range_type == VR_RANGE)
1149 HOST_WIDE_INT type_min
1150 = (TYPE_UNSIGNED (argtype)
1151 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1152 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1154 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1156 *pmin = min.to_shwi ();
1157 *pmax = max.to_shwi ();
1159 if (*pmin < *pmax)
1161 /* Return true if the adjusted range is a subrange of
1162 the full range of the argument's type. *PMAX may
1163 be less than *PMIN when the argument is unsigned
1164 and its upper bound is in excess of TYPE_MAX. In
1165 that (invalid) case disregard the range and use that
1166 of the expected type instead. */
1167 knownrange = type_min < *pmin || *pmax < type_max;
1169 unknown = false;
1174 /* Handle an argument with an unknown range as if none had been
1175 provided. */
1176 if (unknown)
1177 return get_int_range (NULL_TREE, pmin, pmax, absolute, negbound);
1180 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1181 if (absolute)
1183 if (*pmin < 0)
1185 if (*pmin == *pmax)
1186 *pmin = *pmax = -*pmin;
1187 else
1189 /* Make sure signed overlow is avoided. */
1190 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1192 HOST_WIDE_INT tmp = -*pmin;
1193 *pmin = 0;
1194 if (*pmax < tmp)
1195 *pmax = tmp;
1199 else if (*pmin < negbound)
1200 *pmin = negbound;
1202 return knownrange;
1205 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1206 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1207 the type of the directive's formal argument it's possible for both
1208 to result in the same number of bytes or a range of bytes that's
1209 less than the number of bytes that would result from formatting
1210 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1211 determined by checking for the actual argument being in the range
1212 of the type of the directive. If it isn't it must be assumed to
1213 take on the full range of the directive's type.
1214 Return true when the range has been adjusted to the full range
1215 of DIRTYPE, and false otherwise. */
1217 static bool
1218 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1220 tree argtype = TREE_TYPE (*argmin);
1221 unsigned argprec = TYPE_PRECISION (argtype);
1222 unsigned dirprec = TYPE_PRECISION (dirtype);
1224 /* If the actual argument and the directive's argument have the same
1225 precision and sign there can be no overflow and so there is nothing
1226 to adjust. */
1227 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1228 return false;
1230 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1231 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1233 if (TREE_CODE (*argmin) == INTEGER_CST
1234 && TREE_CODE (*argmax) == INTEGER_CST
1235 && (dirprec >= argprec
1236 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1237 int_const_binop (MINUS_EXPR,
1238 *argmax,
1239 *argmin),
1240 size_int (dirprec)))))
1242 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1243 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1245 /* If *ARGMIN is still less than *ARGMAX the conversion above
1246 is safe. Otherwise, it has overflowed and would be unsafe. */
1247 if (tree_int_cst_le (*argmin, *argmax))
1248 return false;
1251 *argmin = TYPE_MIN_VALUE (dirtype);
1252 *argmax = TYPE_MAX_VALUE (dirtype);
1253 return true;
1256 /* Return a range representing the minimum and maximum number of bytes
1257 that the format directive DIR will output for any argument given
1258 the WIDTH and PRECISION (extracted from DIR). This function is
1259 used when the directive argument or its value isn't known. */
1261 static fmtresult
1262 format_integer (const directive &dir, tree arg)
1264 tree intmax_type_node;
1265 tree uintmax_type_node;
1267 /* Base to format the number in. */
1268 int base;
1270 /* True when a conversion is preceded by a prefix indicating the base
1271 of the argument (octal or hexadecimal). */
1272 bool maybebase = dir.get_flag ('#');
1274 /* True when a signed conversion is preceded by a sign or space. */
1275 bool maybesign = false;
1277 /* True for signed conversions (i.e., 'd' and 'i'). */
1278 bool sign = false;
1280 switch (dir.specifier)
1282 case 'd':
1283 case 'i':
1284 /* Space and '+' are only meaningful for signed conversions. */
1285 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1286 sign = true;
1287 base = 10;
1288 break;
1289 case 'u':
1290 base = 10;
1291 break;
1292 case 'o':
1293 base = 8;
1294 break;
1295 case 'X':
1296 case 'x':
1297 base = 16;
1298 break;
1299 default:
1300 gcc_unreachable ();
1303 /* The type of the "formal" argument expected by the directive. */
1304 tree dirtype = NULL_TREE;
1306 /* Determine the expected type of the argument from the length
1307 modifier. */
1308 switch (dir.modifier)
1310 case FMT_LEN_none:
1311 if (dir.specifier == 'p')
1312 dirtype = ptr_type_node;
1313 else
1314 dirtype = sign ? integer_type_node : unsigned_type_node;
1315 break;
1317 case FMT_LEN_h:
1318 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1319 break;
1321 case FMT_LEN_hh:
1322 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1323 break;
1325 case FMT_LEN_l:
1326 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1327 break;
1329 case FMT_LEN_L:
1330 case FMT_LEN_ll:
1331 dirtype = (sign
1332 ? long_long_integer_type_node
1333 : long_long_unsigned_type_node);
1334 break;
1336 case FMT_LEN_z:
1337 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1338 break;
1340 case FMT_LEN_t:
1341 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1342 break;
1344 case FMT_LEN_j:
1345 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1346 dirtype = sign ? intmax_type_node : uintmax_type_node;
1347 break;
1349 default:
1350 return fmtresult ();
1353 /* The type of the argument to the directive, either deduced from
1354 the actual non-constant argument if one is known, or from
1355 the directive itself when none has been provided because it's
1356 a va_list. */
1357 tree argtype = NULL_TREE;
1359 if (!arg)
1361 /* When the argument has not been provided, use the type of
1362 the directive's argument as an approximation. This will
1363 result in false positives for directives like %i with
1364 arguments with smaller precision (such as short or char). */
1365 argtype = dirtype;
1367 else if (TREE_CODE (arg) == INTEGER_CST)
1369 /* When a constant argument has been provided use its value
1370 rather than type to determine the length of the output. */
1371 fmtresult res;
1373 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1375 /* As a special case, a precision of zero with a zero argument
1376 results in zero bytes except in base 8 when the '#' flag is
1377 specified, and for signed conversions in base 8 and 10 when
1378 either the space or '+' flag has been specified and it results
1379 in just one byte (with width having the normal effect). This
1380 must extend to the case of a specified precision with
1381 an unknown value because it can be zero. */
1382 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1383 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1385 res.range.max = 1;
1386 res.range.likely = 1;
1388 else
1390 res.range.max = res.range.min;
1391 res.range.likely = res.range.min;
1394 else
1396 /* Convert the argument to the type of the directive. */
1397 arg = fold_convert (dirtype, arg);
1399 res.range.min = tree_digits (arg, base, dir.prec[0],
1400 maybesign, maybebase);
1401 if (dir.prec[0] == dir.prec[1])
1402 res.range.max = res.range.min;
1403 else
1404 res.range.max = tree_digits (arg, base, dir.prec[1],
1405 maybesign, maybebase);
1406 res.range.likely = res.range.min;
1407 res.knownrange = true;
1410 res.range.unlikely = res.range.max;
1412 /* Bump up the counters if WIDTH is greater than LEN. */
1413 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1414 (sign | maybebase) + (base == 16));
1415 /* Bump up the counters again if PRECision is greater still. */
1416 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1417 (sign | maybebase) + (base == 16));
1419 return res;
1421 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1422 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1423 /* Determine the type of the provided non-constant argument. */
1424 argtype = TREE_TYPE (arg);
1425 else
1426 /* Don't bother with invalid arguments since they likely would
1427 have already been diagnosed, and disable any further checking
1428 of the format string by returning [-1, -1]. */
1429 return fmtresult ();
1431 fmtresult res;
1433 /* Using either the range the non-constant argument is in, or its
1434 type (either "formal" or actual), create a range of values that
1435 constrain the length of output given the warning level. */
1436 tree argmin = NULL_TREE;
1437 tree argmax = NULL_TREE;
1439 if (arg
1440 && TREE_CODE (arg) == SSA_NAME
1441 && INTEGRAL_TYPE_P (argtype))
1443 /* Try to determine the range of values of the integer argument
1444 (range information is not available for pointers). */
1445 wide_int min, max;
1446 enum value_range_type range_type = get_range_info (arg, &min, &max);
1447 if (range_type == VR_RANGE)
1449 argmin = wide_int_to_tree (argtype, min);
1450 argmax = wide_int_to_tree (argtype, max);
1452 /* Set KNOWNRANGE if the argument is in a known subrange
1453 of the directive's type and neither width nor precision
1454 is unknown. (KNOWNRANGE may be reset below). */
1455 res.knownrange
1456 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1457 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1458 && dir.known_width_and_precision ());
1460 res.argmin = argmin;
1461 res.argmax = argmax;
1463 else if (range_type == VR_ANTI_RANGE)
1465 /* Handle anti-ranges if/when bug 71690 is resolved. */
1467 else if (range_type == VR_VARYING)
1469 /* The argument here may be the result of promoting the actual
1470 argument to int. Try to determine the type of the actual
1471 argument before promotion and narrow down its range that
1472 way. */
1473 gimple *def = SSA_NAME_DEF_STMT (arg);
1474 if (is_gimple_assign (def))
1476 tree_code code = gimple_assign_rhs_code (def);
1477 if (code == INTEGER_CST)
1479 arg = gimple_assign_rhs1 (def);
1480 return format_integer (dir, arg);
1483 if (code == NOP_EXPR)
1485 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1486 if (INTEGRAL_TYPE_P (type)
1487 || TREE_CODE (type) == POINTER_TYPE)
1488 argtype = type;
1494 if (!argmin)
1496 if (TREE_CODE (argtype) == POINTER_TYPE)
1498 argmin = build_int_cst (pointer_sized_int_node, 0);
1499 argmax = build_all_ones_cst (pointer_sized_int_node);
1501 else
1503 argmin = TYPE_MIN_VALUE (argtype);
1504 argmax = TYPE_MAX_VALUE (argtype);
1508 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1509 of the directive. If it has been cleared then since ARGMIN and/or
1510 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1511 ARGMAX in the result to include in diagnostics. */
1512 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1514 res.knownrange = false;
1515 res.argmin = argmin;
1516 res.argmax = argmax;
1519 /* Recursively compute the minimum and maximum from the known range. */
1520 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1522 /* For unsigned conversions/directives or signed when
1523 the minimum is positive, use the minimum and maximum to compute
1524 the shortest and longest output, respectively. */
1525 res.range.min = format_integer (dir, argmin).range.min;
1526 res.range.max = format_integer (dir, argmax).range.max;
1528 else if (tree_int_cst_sgn (argmax) < 0)
1530 /* For signed conversions/directives if maximum is negative,
1531 use the minimum as the longest output and maximum as the
1532 shortest output. */
1533 res.range.min = format_integer (dir, argmax).range.min;
1534 res.range.max = format_integer (dir, argmin).range.max;
1536 else
1538 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1539 as the shortest output and for the longest output compute the
1540 length of the output of both minimum and maximum and pick the
1541 longer. */
1542 unsigned HOST_WIDE_INT max1 = format_integer (dir, argmin).range.max;
1543 unsigned HOST_WIDE_INT max2 = format_integer (dir, argmax).range.max;
1544 res.range.min = format_integer (dir, integer_zero_node).range.min;
1545 res.range.max = MAX (max1, max2);
1548 /* If the range is known, use the maximum as the likely length. */
1549 if (res.knownrange)
1550 res.range.likely = res.range.max;
1551 else
1553 /* Otherwise, use the minimum. Except for the case where for %#x or
1554 %#o the minimum is just for a single value in the range (0) and
1555 for all other values it is something longer, like 0x1 or 01.
1556 Use the length for value 1 in that case instead as the likely
1557 length. */
1558 res.range.likely = res.range.min;
1559 if (maybebase
1560 && base != 10
1561 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1563 if (res.range.min == 1)
1564 res.range.likely += base == 8 ? 1 : 2;
1565 else if (res.range.min == 2
1566 && base == 16
1567 && (dir.width[0] == 2 || dir.prec[0] == 2))
1568 ++res.range.likely;
1572 res.range.unlikely = res.range.max;
1573 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1574 (sign | maybebase) + (base == 16));
1575 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1576 (sign | maybebase) + (base == 16));
1578 return res;
1581 /* Return the number of bytes that a format directive consisting of FLAGS,
1582 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1583 would result for argument X under ideal conditions (i.e., if PREC
1584 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1585 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1586 This function works around those problems. */
1588 static unsigned HOST_WIDE_INT
1589 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1590 char spec, char rndspec)
1592 char fmtstr[40];
1594 HOST_WIDE_INT len = strlen (flags);
1596 fmtstr[0] = '%';
1597 memcpy (fmtstr + 1, flags, len);
1598 memcpy (fmtstr + 1 + len, ".*R", 3);
1599 fmtstr[len + 4] = rndspec;
1600 fmtstr[len + 5] = spec;
1601 fmtstr[len + 6] = '\0';
1603 spec = TOUPPER (spec);
1604 if (spec == 'E' || spec == 'F')
1606 /* For %e, specify the precision explicitly since mpfr_sprintf
1607 does its own thing just to be different (see MPFR bug 21088). */
1608 if (prec < 0)
1609 prec = 6;
1611 else
1613 /* Avoid passing negative precisions with larger magnitude to MPFR
1614 to avoid exposing its bugs. (A negative precision is supposed
1615 to be ignored.) */
1616 if (prec < 0)
1617 prec = -1;
1620 HOST_WIDE_INT p = prec;
1622 if (spec == 'G' && !strchr (flags, '#'))
1624 /* For G/g without the pound flag, precision gives the maximum number
1625 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1626 a 128 bit IEEE extended precision, 4932. Using twice as much here
1627 should be more than sufficient for any real format. */
1628 if ((IEEE_MAX_10_EXP * 2) < prec)
1629 prec = IEEE_MAX_10_EXP * 2;
1630 p = prec;
1632 else
1634 /* Cap precision arbitrarily at 1KB and add the difference
1635 (if any) to the MPFR result. */
1636 if (prec > 1024)
1637 p = 1024;
1640 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1642 /* Handle the unlikely (impossible?) error by returning more than
1643 the maximum dictated by the function's return type. */
1644 if (len < 0)
1645 return target_dir_max () + 1;
1647 /* Adjust the return value by the difference. */
1648 if (p < prec)
1649 len += prec - p;
1651 return len;
1654 /* Return the number of bytes to format using the format specifier
1655 SPEC and the precision PREC the largest value in the real floating
1656 TYPE. */
1658 static unsigned HOST_WIDE_INT
1659 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1661 machine_mode mode = TYPE_MODE (type);
1663 /* IBM Extended mode. */
1664 if (MODE_COMPOSITE_P (mode))
1665 mode = DFmode;
1667 /* Get the real type format desription for the target. */
1668 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1669 REAL_VALUE_TYPE rv;
1671 real_maxval (&rv, 0, mode);
1673 /* Convert the GCC real value representation with the precision
1674 of the real type to the mpfr_t format with the GCC default
1675 round-to-nearest mode. */
1676 mpfr_t x;
1677 mpfr_init2 (x, rfmt->p);
1678 mpfr_from_real (x, &rv, GMP_RNDN);
1680 /* Return a value one greater to account for the leading minus sign. */
1681 unsigned HOST_WIDE_INT r
1682 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1683 mpfr_clear (x);
1684 return r;
1687 /* Return a range representing the minimum and maximum number of bytes
1688 that the directive DIR will output for any argument. PREC gives
1689 the adjusted precision range to account for negative precisions
1690 meaning the default 6. This function is used when the directive
1691 argument or its value isn't known. */
1693 static fmtresult
1694 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1696 tree type;
1698 switch (dir.modifier)
1700 case FMT_LEN_l:
1701 case FMT_LEN_none:
1702 type = double_type_node;
1703 break;
1705 case FMT_LEN_L:
1706 type = long_double_type_node;
1707 break;
1709 case FMT_LEN_ll:
1710 type = long_double_type_node;
1711 break;
1713 default:
1714 return fmtresult ();
1717 /* The minimum and maximum number of bytes produced by the directive. */
1718 fmtresult res;
1720 /* The minimum output as determined by flags. It's always at least 1.
1721 When plus or space are set the output is preceded by either a sign
1722 or a space. */
1723 unsigned flagmin = (1 /* for the first digit */
1724 + (dir.get_flag ('+') | dir.get_flag (' ')));
1726 /* When the pound flag is set the decimal point is included in output
1727 regardless of precision. Whether or not a decimal point is included
1728 otherwise depends on the specification and precision. */
1729 bool radix = dir.get_flag ('#');
1731 switch (dir.specifier)
1733 case 'A':
1734 case 'a':
1736 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1737 if (dir.prec[0] <= 0)
1738 minprec = 0;
1739 else if (dir.prec[0] > 0)
1740 minprec = dir.prec[0] + !radix /* decimal point */;
1742 res.range.min = (2 /* 0x */
1743 + flagmin
1744 + radix
1745 + minprec
1746 + 3 /* p+0 */);
1748 res.range.max = format_floating_max (type, 'a', prec[1]);
1749 res.range.likely = res.range.min;
1751 /* The unlikely maximum accounts for the longest multibyte
1752 decimal point character. */
1753 res.range.unlikely = res.range.max;
1754 if (dir.prec[1] > 0)
1755 res.range.unlikely += target_mb_len_max () - 1;
1757 break;
1760 case 'E':
1761 case 'e':
1763 /* Minimum output attributable to precision and, when it's
1764 non-zero, decimal point. */
1765 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1767 /* The minimum output is "[-+]1.234567e+00" regardless
1768 of the value of the actual argument. */
1769 res.range.min = (flagmin
1770 + radix
1771 + minprec
1772 + 2 /* e+ */ + 2);
1774 res.range.max = format_floating_max (type, 'e', prec[1]);
1775 res.range.likely = res.range.min;
1777 /* The unlikely maximum accounts for the longest multibyte
1778 decimal point character. */
1779 if (dir.prec[0] != dir.prec[1]
1780 || dir.prec[0] == -1 || dir.prec[0] > 0)
1781 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1782 else
1783 res.range.unlikely = res.range.max;
1784 break;
1787 case 'F':
1788 case 'f':
1790 /* Minimum output attributable to precision and, when it's non-zero,
1791 decimal point. */
1792 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1794 /* The lower bound when precision isn't specified is 8 bytes
1795 ("1.23456" since precision is taken to be 6). When precision
1796 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1797 when precision is greater than zero, then the lower bound
1798 is 2 plus precision (plus flags). */
1799 res.range.min = flagmin + radix + minprec;
1801 /* Compute the upper bound for -TYPE_MAX. */
1802 res.range.max = format_floating_max (type, 'f', prec[1]);
1804 /* The minimum output with unknown precision is a single byte
1805 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1806 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1807 res.range.likely = 3;
1808 else
1809 res.range.likely = res.range.min;
1811 /* The unlikely maximum accounts for the longest multibyte
1812 decimal point character. */
1813 if (dir.prec[0] != dir.prec[1]
1814 || dir.prec[0] == -1 || dir.prec[0] > 0)
1815 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1816 break;
1819 case 'G':
1820 case 'g':
1822 /* The %g output depends on precision and the exponent of
1823 the argument. Since the value of the argument isn't known
1824 the lower bound on the range of bytes (not counting flags
1825 or width) is 1 plus radix (i.e., either "0" or "0." for
1826 "%g" and "%#g", respectively, with a zero argument). */
1827 res.range.min = flagmin + radix;
1829 char spec = 'g';
1830 HOST_WIDE_INT maxprec = dir.prec[1];
1831 if (radix && maxprec)
1833 /* When the pound flag (radix) is set, trailing zeros aren't
1834 trimmed and so the longest output is the same as for %e,
1835 except with precision minus 1 (as specified in C11). */
1836 spec = 'e';
1837 if (maxprec > 0)
1838 --maxprec;
1839 else if (maxprec < 0)
1840 maxprec = 5;
1842 else
1843 maxprec = prec[1];
1845 res.range.max = format_floating_max (type, spec, maxprec);
1847 /* The likely output is either the maximum computed above
1848 minus 1 (assuming the maximum is positive) when precision
1849 is known (or unspecified), or the same minimum as for %e
1850 (which is computed for a non-negative argument). Unlike
1851 for the other specifiers above the likely output isn't
1852 the minimum because for %g that's 1 which is unlikely. */
1853 if (dir.prec[1] < 0
1854 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1855 res.range.likely = res.range.max - 1;
1856 else
1858 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1859 res.range.likely = (flagmin
1860 + radix
1861 + minprec
1862 + 2 /* e+ */ + 2);
1865 /* The unlikely maximum accounts for the longest multibyte
1866 decimal point character. */
1867 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1868 break;
1871 default:
1872 return fmtresult ();
1875 /* Bump up the byte counters if WIDTH is greater. */
1876 res.adjust_for_width_or_precision (dir.width);
1877 return res;
1880 /* Return a range representing the minimum and maximum number of bytes
1881 that the directive DIR will write on output for the floating argument
1882 ARG. */
1884 static fmtresult
1885 format_floating (const directive &dir, tree arg)
1887 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1889 /* For an indeterminate precision the lower bound must be assumed
1890 to be zero. */
1891 if (TOUPPER (dir.specifier) == 'A')
1893 /* Get the number of fractional decimal digits needed to represent
1894 the argument without a loss of accuracy. */
1895 tree type = arg ? TREE_TYPE (arg) :
1896 (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1897 ? long_double_type_node : double_type_node);
1899 unsigned fmtprec
1900 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1902 /* The precision of the IEEE 754 double format is 53.
1903 The precision of all other GCC binary double formats
1904 is 56 or less. */
1905 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1907 /* For %a, leave the minimum precision unspecified to let
1908 MFPR trim trailing zeros (as it and many other systems
1909 including Glibc happen to do) and set the maximum
1910 precision to reflect what it would be with trailing zeros
1911 present (as Solaris and derived systems do). */
1912 if (dir.prec[1] < 0)
1914 /* Both bounds are negative implies that precision has
1915 not been specified. */
1916 prec[0] = maxprec;
1917 prec[1] = -1;
1919 else if (dir.prec[0] < 0)
1921 /* With a negative lower bound and a non-negative upper
1922 bound set the minimum precision to zero and the maximum
1923 to the greater of the maximum precision (i.e., with
1924 trailing zeros present) and the specified upper bound. */
1925 prec[0] = 0;
1926 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1929 else if (dir.prec[0] < 0)
1931 if (dir.prec[1] < 0)
1933 /* A precision in a strictly negative range is ignored and
1934 the default of 6 is used instead. */
1935 prec[0] = prec[1] = 6;
1937 else
1939 /* For a precision in a partly negative range, the lower bound
1940 must be assumed to be zero and the new upper bound is the
1941 greater of 6 (the default precision used when the specified
1942 precision is negative) and the upper bound of the specified
1943 range. */
1944 prec[0] = 0;
1945 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1949 if (!arg || TREE_CODE (arg) != REAL_CST)
1950 return format_floating (dir, prec);
1952 /* The minimum and maximum number of bytes produced by the directive. */
1953 fmtresult res;
1955 /* Get the real type format desription for the target. */
1956 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1957 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1959 char fmtstr [40];
1960 char *pfmt = fmtstr;
1962 /* Append flags. */
1963 for (const char *pf = "-+ #0"; *pf; ++pf)
1964 if (dir.get_flag (*pf))
1965 *pfmt++ = *pf;
1967 *pfmt = '\0';
1970 /* Set up an array to easily iterate over. */
1971 unsigned HOST_WIDE_INT* const minmax[] = {
1972 &res.range.min, &res.range.max
1975 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1977 /* Convert the GCC real value representation with the precision
1978 of the real type to the mpfr_t format rounding down in the
1979 first iteration that computes the minimm and up in the second
1980 that computes the maximum. This order is arbibtrary because
1981 rounding in either direction can result in longer output. */
1982 mpfr_t mpfrval;
1983 mpfr_init2 (mpfrval, rfmt->p);
1984 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1986 /* Use the MPFR rounding specifier to round down in the first
1987 iteration and then up. In most but not all cases this will
1988 result in the same number of bytes. */
1989 char rndspec = "DU"[i];
1991 /* Format it and store the result in the corresponding member
1992 of the result struct. */
1993 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1994 dir.specifier, rndspec);
1995 mpfr_clear (mpfrval);
1999 /* Make sure the minimum is less than the maximum (MPFR rounding
2000 in the call to mpfr_snprintf can result in the reverse. */
2001 if (res.range.max < res.range.min)
2003 unsigned HOST_WIDE_INT tmp = res.range.min;
2004 res.range.min = res.range.max;
2005 res.range.max = tmp;
2008 /* The range is known unless either width or precision is unknown. */
2009 res.knownrange = dir.known_width_and_precision ();
2011 /* For the same floating point constant, unless width or precision
2012 is unknown, use the longer output as the likely maximum since
2013 with round to nearest either is equally likely. Otheriwse, when
2014 precision is unknown, use the greater of the minimum and 3 as
2015 the likely output (for "0.0" since zero precision is unlikely). */
2016 if (res.knownrange)
2017 res.range.likely = res.range.max;
2018 else if (res.range.min < 3
2019 && dir.prec[0] < 0
2020 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
2021 res.range.likely = 3;
2022 else
2023 res.range.likely = res.range.min;
2025 res.range.unlikely = res.range.max;
2027 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
2029 /* Unless the precision is zero output longer than 2 bytes may
2030 include the decimal point which must be a single character
2031 up to MB_LEN_MAX in length. This is overly conservative
2032 since in some conversions some constants result in no decimal
2033 point (e.g., in %g). */
2034 res.range.unlikely += target_mb_len_max () - 1;
2037 res.adjust_for_width_or_precision (dir.width);
2038 return res;
2041 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
2042 strings referenced by the expression STR, or (-1, -1) when not known.
2043 Used by the format_string function below. */
2045 static fmtresult
2046 get_string_length (tree str)
2048 if (!str)
2049 return fmtresult ();
2051 if (tree slen = c_strlen (str, 1))
2053 /* Simply return the length of the string. */
2054 fmtresult res (tree_to_shwi (slen));
2055 return res;
2058 /* Determine the length of the shortest and longest string referenced
2059 by STR. Strings of unknown lengths are bounded by the sizes of
2060 arrays that subexpressions of STR may refer to. Pointers that
2061 aren't known to point any such arrays result in LENRANGE[1] set
2062 to SIZE_MAX. */
2063 tree lenrange[2];
2064 bool flexarray = get_range_strlen (str, lenrange);
2066 if (lenrange [0] || lenrange [1])
2068 HOST_WIDE_INT min
2069 = (tree_fits_uhwi_p (lenrange[0])
2070 ? tree_to_uhwi (lenrange[0])
2071 : 0);
2073 HOST_WIDE_INT max
2074 = (tree_fits_uhwi_p (lenrange[1])
2075 ? tree_to_uhwi (lenrange[1])
2076 : HOST_WIDE_INT_M1U);
2078 /* get_range_strlen() returns the target value of SIZE_MAX for
2079 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2080 which may be bigger. */
2081 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2082 min = HOST_WIDE_INT_M1U;
2083 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2084 max = HOST_WIDE_INT_M1U;
2086 fmtresult res (min, max);
2088 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2089 by STR are known to be bounded (though not necessarily by their
2090 actual length but perhaps by their maximum possible length). */
2091 if (res.range.max < target_int_max ())
2093 res.knownrange = true;
2094 /* When the the length of the longest string is known and not
2095 excessive use it as the likely length of the string(s). */
2096 res.range.likely = res.range.max;
2098 else
2100 /* When the upper bound is unknown (it can be zero or excessive)
2101 set the likely length to the greater of 1 and the length of
2102 the shortest string and reset the lower bound to zero. */
2103 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2104 res.range.min = 0;
2107 /* If the range of string length has been estimated from the size
2108 of an array at the end of a struct assume that it's longer than
2109 the array bound says it is in case it's used as a poor man's
2110 flexible array member, such as in struct S { char a[4]; }; */
2111 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
2113 return res;
2116 return get_string_length (NULL_TREE);
2119 /* Return the minimum and maximum number of characters formatted
2120 by the '%c' format directives and its wide character form for
2121 the argument ARG. ARG can be null (for functions such as
2122 vsprinf). */
2124 static fmtresult
2125 format_character (const directive &dir, tree arg)
2127 fmtresult res;
2129 res.knownrange = true;
2131 if (dir.modifier == FMT_LEN_l)
2133 /* A wide character can result in as few as zero bytes. */
2134 res.range.min = 0;
2136 HOST_WIDE_INT min, max;
2137 if (get_int_range (arg, &min, &max, false, 0))
2139 if (min == 0 && max == 0)
2141 /* The NUL wide character results in no bytes. */
2142 res.range.max = 0;
2143 res.range.likely = 0;
2144 res.range.unlikely = 0;
2146 else if (min > 0 && min < 128)
2148 /* A wide character in the ASCII range most likely results
2149 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2150 res.range.max = 1;
2151 res.range.likely = 1;
2152 res.range.unlikely = target_mb_len_max ();
2154 else
2156 /* A wide character outside the ASCII range likely results
2157 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2158 res.range.max = target_mb_len_max ();
2159 res.range.likely = 2;
2160 res.range.unlikely = res.range.max;
2163 else
2165 /* An unknown wide character is treated the same as a wide
2166 character outside the ASCII range. */
2167 res.range.max = target_mb_len_max ();
2168 res.range.likely = 2;
2169 res.range.unlikely = res.range.max;
2172 else
2174 /* A plain '%c' directive. Its ouput is exactly 1. */
2175 res.range.min = res.range.max = 1;
2176 res.range.likely = res.range.unlikely = 1;
2177 res.knownrange = true;
2180 /* Bump up the byte counters if WIDTH is greater. */
2181 return res.adjust_for_width_or_precision (dir.width);
2184 /* Return the minimum and maximum number of characters formatted
2185 by the '%s' format directive and its wide character form for
2186 the argument ARG. ARG can be null (for functions such as
2187 vsprinf). */
2189 static fmtresult
2190 format_string (const directive &dir, tree arg)
2192 fmtresult res;
2194 /* Compute the range the argument's length can be in. */
2195 fmtresult slen = get_string_length (arg);
2196 if (slen.range.min == slen.range.max
2197 && slen.range.min < HOST_WIDE_INT_MAX)
2199 /* The argument is either a string constant or it refers
2200 to one of a number of strings of the same length. */
2202 /* A '%s' directive with a string argument with constant length. */
2203 res.range = slen.range;
2205 if (dir.modifier == FMT_LEN_l)
2207 /* In the worst case the length of output of a wide string S
2208 is bounded by MB_LEN_MAX * wcslen (S). */
2209 res.range.max *= target_mb_len_max ();
2210 res.range.unlikely = res.range.max;
2211 /* It's likely that the the total length is not more that
2212 2 * wcslen (S).*/
2213 res.range.likely = res.range.min * 2;
2215 if (dir.prec[1] >= 0
2216 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2218 res.range.max = dir.prec[1];
2219 res.range.likely = dir.prec[1];
2220 res.range.unlikely = dir.prec[1];
2223 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2224 res.range.min = 0;
2225 else if (dir.prec[0] >= 0)
2226 res.range.likely = dir.prec[0];
2228 /* Even a non-empty wide character string need not convert into
2229 any bytes. */
2230 res.range.min = 0;
2232 else
2234 res.knownrange = true;
2236 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2237 res.range.min = 0;
2238 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2239 res.range.min = dir.prec[0];
2241 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2243 res.range.max = dir.prec[1];
2244 res.range.likely = dir.prec[1];
2245 res.range.unlikely = dir.prec[1];
2249 else if (arg && integer_zerop (arg))
2251 /* Handle null pointer argument. */
2253 fmtresult res (0);
2254 res.nullp = true;
2255 return res;
2257 else
2259 /* For a '%s' and '%ls' directive with a non-constant string (either
2260 one of a number of strings of known length or an unknown string)
2261 the minimum number of characters is lesser of PRECISION[0] and
2262 the length of the shortest known string or zero, and the maximum
2263 is the lessser of the length of the longest known string or
2264 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2265 the minimum at level 1 and the greater of the minimum and 1
2266 at level 2. This result is adjust upward for width (if it's
2267 specified). */
2269 if (dir.modifier == FMT_LEN_l)
2271 /* A wide character converts to as few as zero bytes. */
2272 slen.range.min = 0;
2273 if (slen.range.max < target_int_max ())
2274 slen.range.max *= target_mb_len_max ();
2276 if (slen.range.likely < target_int_max ())
2277 slen.range.likely *= 2;
2279 if (slen.range.likely < target_int_max ())
2280 slen.range.unlikely *= target_mb_len_max ();
2283 res.range = slen.range;
2285 if (dir.prec[0] >= 0)
2287 /* Adjust the minimum to zero if the string length is unknown,
2288 or at most the lower bound of the precision otherwise. */
2289 if (slen.range.min >= target_int_max ())
2290 res.range.min = 0;
2291 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2292 res.range.min = dir.prec[0];
2294 /* Make both maxima no greater than the upper bound of precision. */
2295 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2296 || slen.range.max >= target_int_max ())
2298 res.range.max = dir.prec[1];
2299 res.range.unlikely = dir.prec[1];
2302 /* If precision is constant, set the likely counter to the lesser
2303 of it and the maximum string length. Otherwise, if the lower
2304 bound of precision is greater than zero, set the likely counter
2305 to the minimum. Otherwise set it to zero or one based on
2306 the warning level. */
2307 if (dir.prec[0] == dir.prec[1])
2308 res.range.likely
2309 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2310 ? dir.prec[0] : slen.range.max);
2311 else if (dir.prec[0] > 0)
2312 res.range.likely = res.range.min;
2313 else
2314 res.range.likely = warn_level > 1;
2316 else if (dir.prec[1] >= 0)
2318 res.range.min = 0;
2319 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2320 res.range.max = dir.prec[1];
2321 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2323 else if (slen.range.min >= target_int_max ())
2325 res.range.min = 0;
2326 res.range.max = HOST_WIDE_INT_MAX;
2327 /* At level 1 strings of unknown length are assumed to be
2328 empty, while at level 1 they are assumed to be one byte
2329 long. */
2330 res.range.likely = warn_level > 1;
2332 else
2334 /* A string of unknown length unconstrained by precision is
2335 assumed to be empty at level 1 and just one character long
2336 at higher levels. */
2337 if (res.range.likely >= target_int_max ())
2338 res.range.likely = warn_level > 1;
2341 res.range.unlikely = res.range.max;
2344 /* Bump up the byte counters if WIDTH is greater. */
2345 return res.adjust_for_width_or_precision (dir.width);
2348 /* Format plain string (part of the format string itself). */
2350 static fmtresult
2351 format_plain (const directive &dir, tree)
2353 fmtresult res (dir.len);
2354 return res;
2357 /* Return true if the RESULT of a directive in a call describe by INFO
2358 should be diagnosed given the AVAILable space in the destination. */
2360 static bool
2361 should_warn_p (const sprintf_dom_walker::call_info &info,
2362 const result_range &avail, const result_range &result)
2364 if (result.max <= avail.min)
2366 /* The least amount of space remaining in the destination is big
2367 enough for the longest output. */
2368 return false;
2371 if (info.bounded)
2373 if (warn_format_trunc == 1 && result.min <= avail.max
2374 && info.retval_used ())
2376 /* The likely amount of space remaining in the destination is big
2377 enough for the least output and the return value is used. */
2378 return false;
2381 if (warn_format_trunc == 1 && result.likely <= avail.likely
2382 && !info.retval_used ())
2384 /* The likely amount of space remaining in the destination is big
2385 enough for the likely output and the return value is unused. */
2386 return false;
2389 if (warn_format_trunc == 2
2390 && result.likely <= avail.min
2391 && (result.max <= avail.min
2392 || result.max > HOST_WIDE_INT_MAX))
2394 /* The minimum amount of space remaining in the destination is big
2395 enough for the longest output. */
2396 return false;
2399 else
2401 if (warn_level == 1 && result.likely <= avail.likely)
2403 /* The likely amount of space remaining in the destination is big
2404 enough for the likely output. */
2405 return false;
2408 if (warn_level == 2
2409 && result.likely <= avail.min
2410 && (result.max <= avail.min
2411 || result.max > HOST_WIDE_INT_MAX))
2413 /* The minimum amount of space remaining in the destination is big
2414 enough for the longest output. */
2415 return false;
2419 return true;
2422 /* At format string location describe by DIRLOC in a call described
2423 by INFO, issue a warning for a directive DIR whose output may be
2424 in excess of the available space AVAIL_RANGE in the destination
2425 given the formatting result FMTRES. This function does nothing
2426 except decide whether to issue a warning for a possible write
2427 past the end or truncation and, if so, format the warning.
2428 Return true if a warning has been issued. */
2430 static bool
2431 maybe_warn (substring_loc &dirloc, location_t argloc,
2432 const sprintf_dom_walker::call_info &info,
2433 const result_range &avail_range, const result_range &res,
2434 const directive &dir)
2436 if (!should_warn_p (info, avail_range, res))
2437 return false;
2439 /* A warning will definitely be issued below. */
2441 /* The maximum byte count to reference in the warning. Larger counts
2442 imply that the upper bound is unknown (and could be anywhere between
2443 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2444 than "between N and X" where X is some huge number. */
2445 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2447 /* True when there is enough room in the destination for the least
2448 amount of a directive's output but not enough for its likely or
2449 maximum output. */
2450 bool maybe = (res.min <= avail_range.max
2451 && (avail_range.min < res.likely
2452 || (res.max < HOST_WIDE_INT_MAX
2453 && avail_range.min < res.max)));
2455 /* Buffer for the directive in the host character set (used when
2456 the source character set is different). */
2457 char hostdir[32];
2459 if (avail_range.min == avail_range.max)
2461 /* The size of the destination region is exact. */
2462 unsigned HOST_WIDE_INT navail = avail_range.max;
2464 if (target_to_host (*dir.beg) != '%')
2466 /* For plain character directives (i.e., the format string itself)
2467 but not others, point the caret at the first character that's
2468 past the end of the destination. */
2469 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2472 if (*dir.beg == '\0')
2474 /* This is the terminating nul. */
2475 gcc_assert (res.min == 1 && res.min == res.max);
2477 const char *fmtstr
2478 = (info.bounded
2479 ? (maybe
2480 ? G_("%qE output may be truncated before the last format "
2481 "character")
2482 : G_("%qE output truncated before the last format character"))
2483 : (maybe
2484 ? G_("%qE may write a terminating nul past the end "
2485 "of the destination")
2486 : G_("%qE writing a terminating nul past the end "
2487 "of the destination")));
2489 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2490 fmtstr, info.func);
2493 if (res.min == res.max)
2495 const char* fmtstr
2496 = (res.min == 1
2497 ? (info.bounded
2498 ? (maybe
2499 ? G_("%<%.*s%> directive output may be truncated writing "
2500 "%wu byte into a region of size %wu")
2501 : G_("%<%.*s%> directive output truncated writing "
2502 "%wu byte into a region of size %wu"))
2503 : G_("%<%.*s%> directive writing %wu byte "
2504 "into a region of size %wu"))
2505 : (info.bounded
2506 ? (maybe
2507 ? G_("%<%.*s%> directive output may be truncated writing "
2508 "%wu bytes into a region of size %wu")
2509 : G_("%<%.*s%> directive output truncated writing "
2510 "%wu bytes into a region of size %wu"))
2511 : G_("%<%.*s%> directive writing %wu bytes "
2512 "into a region of size %wu")));
2513 return fmtwarn (dirloc, argloc, NULL,
2514 info.warnopt (), fmtstr, dir.len,
2515 target_to_host (hostdir, sizeof hostdir, dir.beg),
2516 res.min, navail);
2519 if (res.min == 0 && res.max < maxbytes)
2521 const char* fmtstr
2522 = (info.bounded
2523 ? (maybe
2524 ? G_("%<%.*s%> directive output may be truncated writing "
2525 "up to %wu bytes into a region of size %wu")
2526 : G_("%<%.*s%> directive output truncated writing "
2527 "up to %wu bytes into a region of size %wu"))
2528 : G_("%<%.*s%> directive writing up to %wu bytes "
2529 "into a region of size %wu"));
2530 return fmtwarn (dirloc, argloc, NULL,
2531 info.warnopt (), fmtstr, dir.len,
2532 target_to_host (hostdir, sizeof hostdir, dir.beg),
2533 res.max, navail);
2536 if (res.min == 0 && maxbytes <= res.max)
2538 /* This is a special case to avoid issuing the potentially
2539 confusing warning:
2540 writing 0 or more bytes into a region of size 0. */
2541 const char* fmtstr
2542 = (info.bounded
2543 ? (maybe
2544 ? G_("%<%.*s%> directive output may be truncated writing "
2545 "likely %wu or more bytes into a region of size %wu")
2546 : G_("%<%.*s%> directive output truncated writing "
2547 "likely %wu or more bytes into a region of size %wu"))
2548 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2549 "into a region of size %wu"));
2550 return fmtwarn (dirloc, argloc, NULL,
2551 info.warnopt (), fmtstr, dir.len,
2552 target_to_host (hostdir, sizeof hostdir, dir.beg),
2553 res.likely, navail);
2556 if (res.max < maxbytes)
2558 const char* fmtstr
2559 = (info.bounded
2560 ? (maybe
2561 ? G_("%<%.*s%> directive output may be truncated writing "
2562 "between %wu and %wu bytes into a region of size %wu")
2563 : G_("%<%.*s%> directive output truncated writing "
2564 "between %wu and %wu bytes into a region of size %wu"))
2565 : G_("%<%.*s%> directive writing between %wu and "
2566 "%wu bytes into a region of size %wu"));
2567 return fmtwarn (dirloc, argloc, NULL,
2568 info.warnopt (), fmtstr, dir.len,
2569 target_to_host (hostdir, sizeof hostdir, dir.beg),
2570 res.min, res.max, navail);
2573 const char* fmtstr
2574 = (info.bounded
2575 ? (maybe
2576 ? G_("%<%.*s%> directive output may be truncated writing "
2577 "%wu or more bytes into a region of size %wu")
2578 : G_("%<%.*s%> directive output truncated writing "
2579 "%wu or more bytes into a region of size %wu"))
2580 : G_("%<%.*s%> directive writing %wu or more bytes "
2581 "into a region of size %wu"));
2582 return fmtwarn (dirloc, argloc, NULL,
2583 info.warnopt (), fmtstr, dir.len,
2584 target_to_host (hostdir, sizeof hostdir, dir.beg),
2585 res.min, navail);
2588 /* The size of the destination region is a range. */
2590 if (target_to_host (*dir.beg) != '%')
2592 unsigned HOST_WIDE_INT navail = avail_range.max;
2594 /* For plain character directives (i.e., the format string itself)
2595 but not others, point the caret at the first character that's
2596 past the end of the destination. */
2597 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2600 if (*dir.beg == '\0')
2602 gcc_assert (res.min == 1 && res.min == res.max);
2604 const char *fmtstr
2605 = (info.bounded
2606 ? (maybe
2607 ? G_("%qE output may be truncated before the last format "
2608 "character")
2609 : G_("%qE output truncated before the last format character"))
2610 : (maybe
2611 ? G_("%qE may write a terminating nul past the end "
2612 "of the destination")
2613 : G_("%qE writing a terminating nul past the end "
2614 "of the destination")));
2616 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (), fmtstr,
2617 info.func);
2620 if (res.min == res.max)
2622 const char* fmtstr
2623 = (res.min == 1
2624 ? (info.bounded
2625 ? (maybe
2626 ? G_("%<%.*s%> directive output may be truncated writing "
2627 "%wu byte into a region of size between %wu and %wu")
2628 : G_("%<%.*s%> directive output truncated writing "
2629 "%wu byte into a region of size between %wu and %wu"))
2630 : G_("%<%.*s%> directive writing %wu byte "
2631 "into a region of size between %wu and %wu"))
2632 : (info.bounded
2633 ? (maybe
2634 ? G_("%<%.*s%> directive output may be truncated writing "
2635 "%wu bytes into a region of size between %wu and %wu")
2636 : G_("%<%.*s%> directive output truncated writing "
2637 "%wu bytes into a region of size between %wu and %wu"))
2638 : G_("%<%.*s%> directive writing %wu bytes "
2639 "into a region of size between %wu and %wu")));
2641 return fmtwarn (dirloc, argloc, NULL,
2642 info.warnopt (), fmtstr, dir.len,
2643 target_to_host (hostdir, sizeof hostdir, dir.beg),
2644 res.min, avail_range.min, avail_range.max);
2647 if (res.min == 0 && res.max < maxbytes)
2649 const char* fmtstr
2650 = (info.bounded
2651 ? (maybe
2652 ? G_("%<%.*s%> directive output may be truncated writing "
2653 "up to %wu bytes into a region of size between "
2654 "%wu and %wu")
2655 : G_("%<%.*s%> directive output truncated writing "
2656 "up to %wu bytes into a region of size between "
2657 "%wu and %wu"))
2658 : G_("%<%.*s%> directive writing up to %wu bytes "
2659 "into a region of size between %wu and %wu"));
2660 return fmtwarn (dirloc, argloc, NULL,
2661 info.warnopt (), fmtstr, dir.len,
2662 target_to_host (hostdir, sizeof hostdir, dir.beg),
2663 res.max, avail_range.min, avail_range.max);
2666 if (res.min == 0 && maxbytes <= res.max)
2668 /* This is a special case to avoid issuing the potentially confusing
2669 warning:
2670 writing 0 or more bytes into a region of size between 0 and N. */
2671 const char* fmtstr
2672 = (info.bounded
2673 ? (maybe
2674 ? G_("%<%.*s%> directive output may be truncated writing "
2675 "likely %wu or more bytes into a region of size between "
2676 "%wu and %wu")
2677 : G_("%<%.*s%> directive output truncated writing likely "
2678 "%wu or more bytes into a region of size between "
2679 "%wu and %wu"))
2680 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2681 "into a region of size between %wu and %wu"));
2682 return fmtwarn (dirloc, argloc, NULL,
2683 info.warnopt (), fmtstr, dir.len,
2684 target_to_host (hostdir, sizeof hostdir, dir.beg),
2685 res.likely, avail_range.min, avail_range.max);
2688 if (res.max < maxbytes)
2690 const char* fmtstr
2691 = (info.bounded
2692 ? (maybe
2693 ? G_("%<%.*s%> directive output may be truncated writing "
2694 "between %wu and %wu bytes into a region of size "
2695 "between %wu and %wu")
2696 : G_("%<%.*s%> directive output truncated writing "
2697 "between %wu and %wu bytes into a region of size "
2698 "between %wu and %wu"))
2699 : G_("%<%.*s%> directive writing between %wu and "
2700 "%wu bytes into a region of size between %wu and %wu"));
2701 return fmtwarn (dirloc, argloc, NULL,
2702 info.warnopt (), fmtstr, dir.len,
2703 target_to_host (hostdir, sizeof hostdir, dir.beg),
2704 res.min, res.max, avail_range.min, avail_range.max);
2707 const char* fmtstr
2708 = (info.bounded
2709 ? (maybe
2710 ? G_("%<%.*s%> directive output may be truncated writing "
2711 "%wu or more bytes into a region of size between "
2712 "%wu and %wu")
2713 : G_("%<%.*s%> directive output truncated writing "
2714 "%wu or more bytes into a region of size between "
2715 "%wu and %wu"))
2716 : G_("%<%.*s%> directive writing %wu or more bytes "
2717 "into a region of size between %wu and %wu"));
2718 return fmtwarn (dirloc, argloc, NULL,
2719 info.warnopt (), fmtstr, dir.len,
2720 target_to_host (hostdir, sizeof hostdir, dir.beg),
2721 res.min, avail_range.min, avail_range.max);
2724 /* Compute the length of the output resulting from the directive DIR
2725 in a call described by INFO and update the overall result of the call
2726 in *RES. Return true if the directive has been handled. */
2728 static bool
2729 format_directive (const sprintf_dom_walker::call_info &info,
2730 format_result *res, const directive &dir)
2732 /* Offset of the beginning of the directive from the beginning
2733 of the format string. */
2734 size_t offset = dir.beg - info.fmtstr;
2735 size_t start = offset;
2736 size_t length = offset + dir.len - !!dir.len;
2738 /* Create a location for the whole directive from the % to the format
2739 specifier. */
2740 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2741 offset, start, length);
2743 /* Also get the location of the argument if possible.
2744 This doesn't work for integer literals or function calls. */
2745 location_t argloc = UNKNOWN_LOCATION;
2746 if (dir.arg)
2747 argloc = EXPR_LOCATION (dir.arg);
2749 /* Bail when there is no function to compute the output length,
2750 or when minimum length checking has been disabled. */
2751 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2752 return false;
2754 /* Compute the range of lengths of the formatted output. */
2755 fmtresult fmtres = dir.fmtfunc (dir, dir.arg);
2757 /* Record whether the output of all directives is known to be
2758 bounded by some maximum, implying that their arguments are
2759 either known exactly or determined to be in a known range
2760 or, for strings, limited by the upper bounds of the arrays
2761 they refer to. */
2762 res->knownrange &= fmtres.knownrange;
2764 if (!fmtres.knownrange)
2766 /* Only when the range is known, check it against the host value
2767 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2768 INT_MAX precision, which is the longest possible output of any
2769 single directive). That's the largest valid byte count (though
2770 not valid call to a printf-like function because it can never
2771 return such a count). Otherwise, the range doesn't correspond
2772 to known values of the argument. */
2773 if (fmtres.range.max > target_dir_max ())
2775 /* Normalize the MAX counter to avoid having to deal with it
2776 later. The counter can be less than HOST_WIDE_INT_M1U
2777 when compiling for an ILP32 target on an LP64 host. */
2778 fmtres.range.max = HOST_WIDE_INT_M1U;
2779 /* Disable exact and maximum length checking after a failure
2780 to determine the maximum number of characters (for example
2781 for wide characters or wide character strings) but continue
2782 tracking the minimum number of characters. */
2783 res->range.max = HOST_WIDE_INT_M1U;
2786 if (fmtres.range.min > target_dir_max ())
2788 /* Disable exact length checking after a failure to determine
2789 even the minimum number of characters (it shouldn't happen
2790 except in an error) but keep tracking the minimum and maximum
2791 number of characters. */
2792 return true;
2796 /* Buffer for the directive in the host character set (used when
2797 the source character set is different). */
2798 char hostdir[32];
2800 int dirlen = dir.len;
2802 if (fmtres.nullp)
2804 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2805 "%<%.*s%> directive argument is null",
2806 dirlen, target_to_host (hostdir, sizeof hostdir, dir.beg));
2808 /* Don't bother processing the rest of the format string. */
2809 res->warned = true;
2810 res->range.min = HOST_WIDE_INT_M1U;
2811 res->range.max = HOST_WIDE_INT_M1U;
2812 return false;
2815 /* Compute the number of available bytes in the destination. There
2816 must always be at least one byte of space for the terminating
2817 NUL that's appended after the format string has been processed. */
2818 result_range avail_range = bytes_remaining (info.objsize, *res);
2820 bool warned = res->warned;
2822 if (!warned)
2823 warned = maybe_warn (dirloc, argloc, info, avail_range,
2824 fmtres.range, dir);
2826 /* Bump up the total maximum if it isn't too big. */
2827 if (res->range.max < HOST_WIDE_INT_MAX
2828 && fmtres.range.max < HOST_WIDE_INT_MAX)
2829 res->range.max += fmtres.range.max;
2831 /* Raise the total unlikely maximum by the larger of the maximum
2832 and the unlikely maximum. */
2833 unsigned HOST_WIDE_INT save = res->range.unlikely;
2834 if (fmtres.range.max < fmtres.range.unlikely)
2835 res->range.unlikely += fmtres.range.unlikely;
2836 else
2837 res->range.unlikely += fmtres.range.max;
2839 if (res->range.unlikely < save)
2840 res->range.unlikely = HOST_WIDE_INT_M1U;
2842 res->range.min += fmtres.range.min;
2843 res->range.likely += fmtres.range.likely;
2845 /* Has the minimum directive output length exceeded the maximum
2846 of 4095 bytes required to be supported? */
2847 bool minunder4k = fmtres.range.min < 4096;
2848 bool maxunder4k = fmtres.range.max < 4096;
2849 /* Clear UNDER4K in the overall result if the maximum has exceeded
2850 the 4k (this is necessary to avoid the return valuye optimization
2851 that may not be safe in the maximum case). */
2852 if (!maxunder4k)
2853 res->under4k = false;
2855 if (!warned
2856 /* Only warn at level 2. */
2857 && 1 < warn_level
2858 && (!minunder4k
2859 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2861 /* The directive output may be longer than the maximum required
2862 to be handled by an implementation according to 7.21.6.1, p15
2863 of C11. Warn on this only at level 2 but remember this and
2864 prevent folding the return value when done. This allows for
2865 the possibility of the actual libc call failing due to ENOMEM
2866 (like Glibc does under some conditions). */
2868 if (fmtres.range.min == fmtres.range.max)
2869 warned = fmtwarn (dirloc, argloc, NULL,
2870 info.warnopt (),
2871 "%<%.*s%> directive output of %wu bytes exceeds "
2872 "minimum required size of 4095",
2873 dirlen,
2874 target_to_host (hostdir, sizeof hostdir, dir.beg),
2875 fmtres.range.min);
2876 else
2878 const char *fmtstr
2879 = (minunder4k
2880 ? G_("%<%.*s%> directive output between %wu and %wu "
2881 "bytes may exceed minimum required size of 4095")
2882 : G_("%<%.*s%> directive output between %wu and %wu "
2883 "bytes exceeds minimum required size of 4095"));
2885 warned = fmtwarn (dirloc, argloc, NULL,
2886 info.warnopt (), fmtstr, dirlen,
2887 target_to_host (hostdir, sizeof hostdir, dir.beg),
2888 fmtres.range.min, fmtres.range.max);
2892 /* Has the likely and maximum directive output exceeded INT_MAX? */
2893 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2894 /* Don't consider the maximum to be in excess when it's the result
2895 of a string of unknown length (i.e., whose maximum has been set
2896 to be greater than or equal to HOST_WIDE_INT_MAX. */
2897 bool maxximax = (*dir.beg
2898 && res->range.max > target_int_max ()
2899 && res->range.max < HOST_WIDE_INT_MAX);
2901 if (!warned
2902 /* Warn for the likely output size at level 1. */
2903 && (likelyximax
2904 /* But only warn for the maximum at level 2. */
2905 || (1 < warn_level
2906 && maxximax
2907 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2909 /* The directive output causes the total length of output
2910 to exceed INT_MAX bytes. */
2912 if (fmtres.range.min == fmtres.range.max)
2913 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2914 "%<%.*s%> directive output of %wu bytes causes "
2915 "result to exceed %<INT_MAX%>",
2916 dirlen,
2917 target_to_host (hostdir, sizeof hostdir, dir.beg),
2918 fmtres.range.min);
2919 else
2921 const char *fmtstr
2922 = (fmtres.range.min > target_int_max ()
2923 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2924 "bytes causes result to exceed %<INT_MAX%>")
2925 : G_ ("%<%.*s%> directive output between %wu and %wu "
2926 "bytes may cause result to exceed %<INT_MAX%>"));
2927 warned = fmtwarn (dirloc, argloc, NULL,
2928 info.warnopt (), fmtstr, dirlen,
2929 target_to_host (hostdir, sizeof hostdir, dir.beg),
2930 fmtres.range.min, fmtres.range.max);
2934 if (warned && fmtres.range.min < fmtres.range.likely
2935 && fmtres.range.likely < fmtres.range.max)
2937 inform (info.fmtloc,
2938 (1 == fmtres.range.likely
2939 ? G_("assuming directive output of %wu byte")
2940 : G_("assuming directive output of %wu bytes")),
2941 fmtres.range.likely);
2944 if (warned && fmtres.argmin)
2946 if (fmtres.argmin == fmtres.argmax)
2947 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2948 else if (fmtres.knownrange)
2949 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2950 fmtres.argmin, fmtres.argmax);
2951 else
2952 inform (info.fmtloc,
2953 "using the range [%E, %E] for directive argument",
2954 fmtres.argmin, fmtres.argmax);
2957 res->warned |= warned;
2959 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2961 /* If a warning has been issued for buffer overflow or truncation
2962 (but not otherwise) help the user figure out how big a buffer
2963 they need. */
2965 location_t callloc = gimple_location (info.callstmt);
2967 unsigned HOST_WIDE_INT min = res->range.min;
2968 unsigned HOST_WIDE_INT max = res->range.max;
2970 if (min == max)
2971 inform (callloc,
2972 (min == 1
2973 ? G_("%qE output %wu byte into a destination of size %wu")
2974 : G_("%qE output %wu bytes into a destination of size %wu")),
2975 info.func, min, info.objsize);
2976 else if (max < HOST_WIDE_INT_MAX)
2977 inform (callloc,
2978 "%qE output between %wu and %wu bytes into "
2979 "a destination of size %wu",
2980 info.func, min, max, info.objsize);
2981 else if (min < res->range.likely && res->range.likely < max)
2982 inform (callloc,
2983 "%qE output %wu or more bytes (assuming %wu) into "
2984 "a destination of size %wu",
2985 info.func, min, res->range.likely, info.objsize);
2986 else
2987 inform (callloc,
2988 "%qE output %wu or more bytes into a destination of size %wu",
2989 info.func, min, info.objsize);
2992 if (dump_file && *dir.beg)
2994 fprintf (dump_file, " Result: %lli, %lli, %lli, %lli "
2995 "(%lli, %lli, %lli, %lli)\n",
2996 (long long)fmtres.range.min,
2997 (long long)fmtres.range.likely,
2998 (long long)fmtres.range.max,
2999 (long long)fmtres.range.unlikely,
3000 (long long)res->range.min,
3001 (long long)res->range.likely,
3002 (long long)res->range.max,
3003 (long long)res->range.unlikely);
3006 return true;
3009 #pragma GCC diagnostic pop
3011 /* Parse a format directive in function call described by INFO starting
3012 at STR and populate DIR structure. Bump up *ARGNO by the number of
3013 arguments extracted for the directive. Return the length of
3014 the directive. */
3016 static size_t
3017 parse_directive (sprintf_dom_walker::call_info &info,
3018 directive &dir, format_result *res,
3019 const char *str, unsigned *argno)
3021 const char *pcnt = strchr (str, target_percent);
3022 dir.beg = str;
3024 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
3026 /* This directive is either a plain string or the terminating nul
3027 (which isn't really a directive but it simplifies things to
3028 handle it as if it were). */
3029 dir.len = len;
3030 dir.fmtfunc = format_plain;
3032 if (dump_file)
3034 fprintf (dump_file, " Directive %u at offset %llu: \"%.*s\", "
3035 "length = %llu\n",
3036 dir.dirno,
3037 (unsigned long long)(size_t)(dir.beg - info.fmtstr),
3038 (int)dir.len, dir.beg, (unsigned long long)dir.len);
3041 return len - !*str;
3044 const char *pf = pcnt + 1;
3046 /* POSIX numbered argument index or zero when none. */
3047 HOST_WIDE_INT dollar = 0;
3049 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3050 when given by a va_list argument, and a non-negative value
3051 when specified in the format string itself. */
3052 HOST_WIDE_INT width = -1;
3053 HOST_WIDE_INT precision = -1;
3055 /* Pointers to the beginning of the width and precision decimal
3056 string (if any) within the directive. */
3057 const char *pwidth = 0;
3058 const char *pprec = 0;
3060 /* When the value of the decimal string that specifies width or
3061 precision is out of range, points to the digit that causes
3062 the value to exceed the limit. */
3063 const char *werange = NULL;
3064 const char *perange = NULL;
3066 /* Width specified via the asterisk. Need not be INTEGER_CST.
3067 For vararg functions set to void_node. */
3068 tree star_width = NULL_TREE;
3070 /* Width specified via the asterisk. Need not be INTEGER_CST.
3071 For vararg functions set to void_node. */
3072 tree star_precision = NULL_TREE;
3074 if (ISDIGIT (target_to_host (*pf)))
3076 /* This could be either a POSIX positional argument, the '0'
3077 flag, or a width, depending on what follows. Store it as
3078 width and sort it out later after the next character has
3079 been seen. */
3080 pwidth = pf;
3081 width = target_strtol10 (&pf, &werange);
3083 else if (target_to_host (*pf) == '*')
3085 /* Similarly to the block above, this could be either a POSIX
3086 positional argument or a width, depending on what follows. */
3087 if (*argno < gimple_call_num_args (info.callstmt))
3088 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3089 else
3090 star_width = void_node;
3091 ++pf;
3094 if (target_to_host (*pf) == '$')
3096 /* Handle the POSIX dollar sign which references the 1-based
3097 positional argument number. */
3098 if (width != -1)
3099 dollar = width + info.argidx;
3100 else if (star_width
3101 && TREE_CODE (star_width) == INTEGER_CST
3102 && (TYPE_PRECISION (TREE_TYPE (star_width))
3103 <= TYPE_PRECISION (integer_type_node)))
3104 dollar = width + tree_to_shwi (star_width);
3106 /* Bail when the numbered argument is out of range (it will
3107 have already been diagnosed by -Wformat). */
3108 if (dollar == 0
3109 || dollar == (int)info.argidx
3110 || dollar > gimple_call_num_args (info.callstmt))
3111 return false;
3113 --dollar;
3115 star_width = NULL_TREE;
3116 width = -1;
3117 ++pf;
3120 if (dollar || !star_width)
3122 if (width != -1)
3124 if (width == 0)
3126 /* The '0' that has been interpreted as a width above is
3127 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3128 and continue processing other flags. */
3129 width = -1;
3130 dir.set_flag ('0');
3132 else if (!dollar)
3134 /* (Non-zero) width has been seen. The next character
3135 is either a period or a digit. */
3136 goto start_precision;
3139 /* When either '$' has been seen, or width has not been seen,
3140 the next field is the optional flags followed by an optional
3141 width. */
3142 for ( ; ; ) {
3143 switch (target_to_host (*pf))
3145 case ' ':
3146 case '0':
3147 case '+':
3148 case '-':
3149 case '#':
3150 dir.set_flag (target_to_host (*pf++));
3151 break;
3153 default:
3154 goto start_width;
3158 start_width:
3159 if (ISDIGIT (target_to_host (*pf)))
3161 werange = 0;
3162 pwidth = pf;
3163 width = target_strtol10 (&pf, &werange);
3165 else if (target_to_host (*pf) == '*')
3167 if (*argno < gimple_call_num_args (info.callstmt))
3168 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3169 else
3171 /* This is (likely) a va_list. It could also be an invalid
3172 call with insufficient arguments. */
3173 star_width = void_node;
3175 ++pf;
3177 else if (target_to_host (*pf) == '\'')
3179 /* The POSIX apostrophe indicating a numeric grouping
3180 in the current locale. Even though it's possible to
3181 estimate the upper bound on the size of the output
3182 based on the number of digits it probably isn't worth
3183 continuing. */
3184 return 0;
3188 start_precision:
3189 if (target_to_host (*pf) == '.')
3191 ++pf;
3193 if (ISDIGIT (target_to_host (*pf)))
3195 pprec = pf;
3196 precision = target_strtol10 (&pf, &perange);
3198 else if (target_to_host (*pf) == '*')
3200 if (*argno < gimple_call_num_args (info.callstmt))
3201 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3202 else
3204 /* This is (likely) a va_list. It could also be an invalid
3205 call with insufficient arguments. */
3206 star_precision = void_node;
3208 ++pf;
3210 else
3212 /* The decimal precision or the asterisk are optional.
3213 When neither is dirified it's taken to be zero. */
3214 precision = 0;
3218 switch (target_to_host (*pf))
3220 case 'h':
3221 if (target_to_host (pf[1]) == 'h')
3223 ++pf;
3224 dir.modifier = FMT_LEN_hh;
3226 else
3227 dir.modifier = FMT_LEN_h;
3228 ++pf;
3229 break;
3231 case 'j':
3232 dir.modifier = FMT_LEN_j;
3233 ++pf;
3234 break;
3236 case 'L':
3237 dir.modifier = FMT_LEN_L;
3238 ++pf;
3239 break;
3241 case 'l':
3242 if (target_to_host (pf[1]) == 'l')
3244 ++pf;
3245 dir.modifier = FMT_LEN_ll;
3247 else
3248 dir.modifier = FMT_LEN_l;
3249 ++pf;
3250 break;
3252 case 't':
3253 dir.modifier = FMT_LEN_t;
3254 ++pf;
3255 break;
3257 case 'z':
3258 dir.modifier = FMT_LEN_z;
3259 ++pf;
3260 break;
3263 switch (target_to_host (*pf))
3265 /* Handle a sole '%' character the same as "%%" but since it's
3266 undefined prevent the result from being folded. */
3267 case '\0':
3268 --pf;
3269 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3270 /* FALLTHRU */
3271 case '%':
3272 dir.fmtfunc = format_percent;
3273 break;
3275 case 'a':
3276 case 'A':
3277 case 'e':
3278 case 'E':
3279 case 'f':
3280 case 'F':
3281 case 'g':
3282 case 'G':
3283 res->floating = true;
3284 dir.fmtfunc = format_floating;
3285 break;
3287 case 'd':
3288 case 'i':
3289 case 'o':
3290 case 'u':
3291 case 'x':
3292 case 'X':
3293 dir.fmtfunc = format_integer;
3294 break;
3296 case 'p':
3297 /* The %p output is implementation-defined. It's possible
3298 to determine this format but due to extensions (edirially
3299 those of the Linux kernel -- see bug 78512) the first %p
3300 in the format string disables any further processing. */
3301 return false;
3303 case 'n':
3304 /* %n has side-effects even when nothing is actually printed to
3305 any buffer. */
3306 info.nowrite = false;
3307 dir.fmtfunc = format_none;
3308 break;
3310 case 'c':
3311 dir.fmtfunc = format_character;
3312 break;
3314 case 'S':
3315 case 's':
3316 dir.fmtfunc = format_string;
3317 break;
3319 default:
3320 /* Unknown conversion specification. */
3321 return 0;
3324 dir.specifier = target_to_host (*pf++);
3326 /* Store the length of the format directive. */
3327 dir.len = pf - pcnt;
3329 /* Buffer for the directive in the host character set (used when
3330 the source character set is different). */
3331 char hostdir[32];
3333 if (star_width)
3335 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3336 dir.set_width (star_width);
3337 else
3339 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3340 (width is the absolute value of that specified). */
3341 dir.width[0] = 0;
3342 dir.width[1] = target_int_max () + 1;
3345 else
3347 if (width == LONG_MAX && werange)
3349 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3350 size_t caret = begin + (werange - pcnt);
3351 size_t end = pf - info.fmtstr - 1;
3353 /* Create a location for the width part of the directive,
3354 pointing the caret at the first out-of-range digit. */
3355 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3356 caret, begin, end);
3358 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL,
3359 info.warnopt (), "%<%.*s%> directive width out of range",
3360 dir.len, target_to_host (hostdir, sizeof hostdir, dir.beg));
3363 dir.set_width (width);
3366 if (star_precision)
3368 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3369 dir.set_precision (star_precision);
3370 else
3372 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3373 (unlike width, negative precision is ignored). */
3374 dir.prec[0] = -1;
3375 dir.prec[1] = target_int_max ();
3378 else
3380 if (precision == LONG_MAX && perange)
3382 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3383 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3384 size_t end = pf - info.fmtstr - 2;
3386 /* Create a location for the precision part of the directive,
3387 including the leading period, pointing the caret at the first
3388 out-of-range digit . */
3389 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3390 caret, begin, end);
3392 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL,
3393 info.warnopt (), "%<%.*s%> directive precision out of range",
3394 dir.len, target_to_host (hostdir, sizeof hostdir, dir.beg));
3397 dir.set_precision (precision);
3400 /* Extract the argument if the directive takes one and if it's
3401 available (e.g., the function doesn't take a va_list). Treat
3402 missing arguments the same as va_list, even though they will
3403 have likely already been diagnosed by -Wformat. */
3404 if (dir.specifier != '%'
3405 && *argno < gimple_call_num_args (info.callstmt))
3406 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3408 if (dump_file)
3410 fprintf (dump_file, " Directive %u at offset %llu: \"%.*s\"",
3411 dir.dirno, (unsigned long long)(size_t)(dir.beg - info.fmtstr),
3412 (int)dir.len, dir.beg);
3413 if (star_width)
3415 if (dir.width[0] == dir.width[1])
3416 fprintf (dump_file, ", width = %lli", (long long)dir.width[0]);
3417 else
3418 fprintf (dump_file, ", width in range [%lli, %lli]",
3419 (long long)dir.width[0], (long long)dir.width[1]);
3422 if (star_precision)
3424 if (dir.prec[0] == dir.prec[1])
3425 fprintf (dump_file, ", precision = %lli", (long long)dir.prec[0]);
3426 else
3427 fprintf (dump_file, ", precision in range [%lli, %lli]",
3428 (long long)dir.prec[0], (long long)dir.prec[1]);
3430 fputc ('\n', dump_file);
3433 return dir.len;
3436 /* Compute the length of the output resulting from the call to a formatted
3437 output function described by INFO and store the result of the call in
3438 *RES. Issue warnings for detected past the end writes. Return true
3439 if the complete format string has been processed and *RES can be relied
3440 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3441 that caused the processing to be terminated early). */
3443 bool
3444 sprintf_dom_walker::compute_format_length (call_info &info,
3445 format_result *res)
3447 if (dump_file)
3449 location_t callloc = gimple_location (info.callstmt);
3450 fprintf (dump_file, "%s:%i: ",
3451 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3452 print_generic_expr (dump_file, info.func, dump_flags);
3454 fprintf (dump_file, ": objsize = %llu, fmtstr = \"%s\"\n",
3455 (unsigned long long)info.objsize, info.fmtstr);
3458 /* Reset the minimum and maximum byte counters. */
3459 res->range.min = res->range.max = 0;
3461 /* No directive has been seen yet so the length of output is bounded
3462 by the known range [0, 0] (with no conversion producing more than
3463 4K bytes) until determined otherwise. */
3464 res->knownrange = true;
3465 res->under4k = true;
3466 res->floating = false;
3467 res->warned = false;
3469 /* 1-based directive counter. */
3470 unsigned dirno = 1;
3472 /* The variadic argument counter. */
3473 unsigned argno = info.argidx;
3475 for (const char *pf = info.fmtstr; ; ++dirno)
3477 directive dir = directive ();
3478 dir.dirno = dirno;
3480 size_t n = parse_directive (info, dir, res, pf, &argno);
3482 /* Return failure if the format function fails. */
3483 if (!format_directive (info, res, dir))
3484 return false;
3486 /* Return success the directive is zero bytes long and it's
3487 the last think in the format string (i.e., it's the terminating
3488 nul, which isn't really a directive but handling it as one makes
3489 things simpler). */
3490 if (!n)
3491 return *pf == '\0';
3493 pf += n;
3496 /* The complete format string was processed (with or without warnings). */
3497 return true;
3500 /* Return the size of the object referenced by the expression DEST if
3501 available, or -1 otherwise. */
3503 static unsigned HOST_WIDE_INT
3504 get_destination_size (tree dest)
3506 /* Initialize object size info before trying to compute it. */
3507 init_object_sizes ();
3509 /* Use __builtin_object_size to determine the size of the destination
3510 object. When optimizing, determine the smallest object (such as
3511 a member array as opposed to the whole enclosing object), otherwise
3512 use type-zero object size to determine the size of the enclosing
3513 object (the function fails without optimization in this type). */
3514 int ost = optimize > 0;
3515 unsigned HOST_WIDE_INT size;
3516 if (compute_builtin_object_size (dest, ost, &size))
3517 return size;
3519 return HOST_WIDE_INT_M1U;
3522 /* Return true if the call described by INFO with result RES safe to
3523 optimize (i.e., no undefined behavior), and set RETVAL to the range
3524 of its return values. */
3526 static bool
3527 is_call_safe (const sprintf_dom_walker::call_info &info,
3528 const format_result &res, bool under4k,
3529 unsigned HOST_WIDE_INT retval[2])
3531 if (under4k && !res.under4k)
3532 return false;
3534 /* The minimum return value. */
3535 retval[0] = res.range.min;
3537 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3538 but in cases involving multibyte characters could be as large as
3539 RES.RANGE.UNLIKELY. */
3540 retval[1]
3541 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3543 /* Adjust the number of bytes which includes the terminating nul
3544 to reflect the return value of the function which does not.
3545 Because the valid range of the function is [INT_MIN, INT_MAX],
3546 a valid range before the adjustment below is [0, INT_MAX + 1]
3547 (the functions only return negative values on error or undefined
3548 behavior). */
3549 if (retval[0] <= target_int_max () + 1)
3550 --retval[0];
3551 if (retval[1] <= target_int_max () + 1)
3552 --retval[1];
3554 /* Avoid the return value optimization when the behavior of the call
3555 is undefined either because any directive may have produced 4K or
3556 more of output, or the return value exceeds INT_MAX, or because
3557 the output overflows the destination object (but leave it enabled
3558 when the function is bounded because then the behavior is well-
3559 defined). */
3560 if (retval[0] == retval[1]
3561 && (info.bounded || retval[0] < info.objsize)
3562 && retval[0] <= target_int_max ())
3563 return true;
3565 if ((info.bounded || retval[1] < info.objsize)
3566 && (retval[0] < target_int_max ()
3567 && retval[1] < target_int_max ()))
3568 return true;
3570 if (!under4k && (info.bounded || retval[0] < info.objsize))
3571 return true;
3573 return false;
3576 /* Given a suitable result RES of a call to a formatted output function
3577 described by INFO, substitute the result for the return value of
3578 the call. The result is suitable if the number of bytes it represents
3579 is known and exact. A result that isn't suitable for substitution may
3580 have its range set to the range of return values, if that is known.
3581 Return true if the call is removed and gsi_next should not be performed
3582 in the caller. */
3584 static bool
3585 try_substitute_return_value (gimple_stmt_iterator *gsi,
3586 const sprintf_dom_walker::call_info &info,
3587 const format_result &res)
3589 tree lhs = gimple_get_lhs (info.callstmt);
3591 /* Set to true when the entire call has been removed. */
3592 bool removed = false;
3594 /* The minimum and maximum return value. */
3595 unsigned HOST_WIDE_INT retval[2];
3596 bool safe = is_call_safe (info, res, true, retval);
3598 if (safe
3599 && retval[0] == retval[1]
3600 /* Not prepared to handle possibly throwing calls here; they shouldn't
3601 appear in non-artificial testcases, except when the __*_chk routines
3602 are badly declared. */
3603 && !stmt_ends_bb_p (info.callstmt))
3605 tree cst = build_int_cst (integer_type_node, retval[0]);
3607 if (lhs == NULL_TREE
3608 && info.nowrite)
3610 /* Remove the call to the bounded function with a zero size
3611 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3612 unlink_stmt_vdef (info.callstmt);
3613 gsi_remove (gsi, true);
3614 removed = true;
3616 else if (info.nowrite)
3618 /* Replace the call to the bounded function with a zero size
3619 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3620 of the function. */
3621 if (!update_call_from_tree (gsi, cst))
3622 gimplify_and_update_call_from_tree (gsi, cst);
3623 gimple *callstmt = gsi_stmt (*gsi);
3624 update_stmt (callstmt);
3626 else if (lhs)
3628 /* Replace the left-hand side of the call with the constant
3629 result of the formatted function. */
3630 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3631 gimple *g = gimple_build_assign (lhs, cst);
3632 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3633 update_stmt (info.callstmt);
3636 if (dump_file)
3638 if (removed)
3639 fprintf (dump_file, " Removing call statement.");
3640 else
3642 fprintf (dump_file, " Substituting ");
3643 print_generic_expr (dump_file, cst, dump_flags);
3644 fprintf (dump_file, " for %s.\n",
3645 info.nowrite ? "statement" : "return value");
3649 else if (lhs)
3651 bool setrange = false;
3653 if (safe
3654 && (info.bounded || retval[1] < info.objsize)
3655 && (retval[0] < target_int_max ()
3656 && retval[1] < target_int_max ()))
3658 /* If the result is in a valid range bounded by the size of
3659 the destination set it so that it can be used for subsequent
3660 optimizations. */
3661 int prec = TYPE_PRECISION (integer_type_node);
3663 wide_int min = wi::shwi (retval[0], prec);
3664 wide_int max = wi::shwi (retval[1], prec);
3665 set_range_info (lhs, VR_RANGE, min, max);
3667 setrange = true;
3670 if (dump_file)
3672 const char *inbounds
3673 = (retval[0] < info.objsize
3674 ? (retval[1] < info.objsize
3675 ? "in" : "potentially out-of")
3676 : "out-of");
3678 const char *what = setrange ? "Setting" : "Discarding";
3679 if (retval[0] != retval[1])
3680 fprintf (dump_file,
3681 " %s %s-bounds return value range [%llu, %llu].\n",
3682 what, inbounds,
3683 (unsigned long long)retval[0],
3684 (unsigned long long)retval[1]);
3685 else
3686 fprintf (dump_file, " %s %s-bounds return value %llu.\n",
3687 what, inbounds, (unsigned long long)retval[0]);
3691 if (dump_file)
3692 fputc ('\n', dump_file);
3694 return removed;
3697 /* Try to simplify a s{,n}printf call described by INFO with result
3698 RES by replacing it with a simpler and presumably more efficient
3699 call (such as strcpy). */
3701 static bool
3702 try_simplify_call (gimple_stmt_iterator *gsi,
3703 const sprintf_dom_walker::call_info &info,
3704 const format_result &res)
3706 unsigned HOST_WIDE_INT dummy[2];
3707 if (!is_call_safe (info, res, info.retval_used (), dummy))
3708 return false;
3710 switch (info.fncode)
3712 case BUILT_IN_SNPRINTF:
3713 return gimple_fold_builtin_snprintf (gsi);
3715 case BUILT_IN_SPRINTF:
3716 return gimple_fold_builtin_sprintf (gsi);
3718 default:
3722 return false;
3725 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3726 functions and if so, handle it. Return true if the call is removed
3727 and gsi_next should not be performed in the caller. */
3729 bool
3730 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3732 call_info info = call_info ();
3734 info.callstmt = gsi_stmt (*gsi);
3735 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3736 return false;
3738 info.func = gimple_call_fndecl (info.callstmt);
3739 info.fncode = DECL_FUNCTION_CODE (info.func);
3741 /* The size of the destination as in snprintf(dest, size, ...). */
3742 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3744 /* The size of the destination determined by __builtin_object_size. */
3745 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3747 /* Buffer size argument number (snprintf and vsnprintf). */
3748 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3750 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3751 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3753 /* Format string argument number (valid for all functions). */
3754 unsigned idx_format;
3756 switch (info.fncode)
3758 case BUILT_IN_SPRINTF:
3759 // Signature:
3760 // __builtin_sprintf (dst, format, ...)
3761 idx_format = 1;
3762 info.argidx = 2;
3763 break;
3765 case BUILT_IN_SPRINTF_CHK:
3766 // Signature:
3767 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3768 idx_objsize = 2;
3769 idx_format = 3;
3770 info.argidx = 4;
3771 break;
3773 case BUILT_IN_SNPRINTF:
3774 // Signature:
3775 // __builtin_snprintf (dst, size, format, ...)
3776 idx_dstsize = 1;
3777 idx_format = 2;
3778 info.argidx = 3;
3779 info.bounded = true;
3780 break;
3782 case BUILT_IN_SNPRINTF_CHK:
3783 // Signature:
3784 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3785 idx_dstsize = 1;
3786 idx_objsize = 3;
3787 idx_format = 4;
3788 info.argidx = 5;
3789 info.bounded = true;
3790 break;
3792 case BUILT_IN_VSNPRINTF:
3793 // Signature:
3794 // __builtin_vsprintf (dst, size, format, va)
3795 idx_dstsize = 1;
3796 idx_format = 2;
3797 info.argidx = -1;
3798 info.bounded = true;
3799 break;
3801 case BUILT_IN_VSNPRINTF_CHK:
3802 // Signature:
3803 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3804 idx_dstsize = 1;
3805 idx_objsize = 3;
3806 idx_format = 4;
3807 info.argidx = -1;
3808 info.bounded = true;
3809 break;
3811 case BUILT_IN_VSPRINTF:
3812 // Signature:
3813 // __builtin_vsprintf (dst, format, va)
3814 idx_format = 1;
3815 info.argidx = -1;
3816 break;
3818 case BUILT_IN_VSPRINTF_CHK:
3819 // Signature:
3820 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3821 idx_format = 3;
3822 idx_objsize = 2;
3823 info.argidx = -1;
3824 break;
3826 default:
3827 return false;
3830 /* Set the global warning level for this function. */
3831 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3833 /* The first argument is a pointer to the destination. */
3834 tree dstptr = gimple_call_arg (info.callstmt, 0);
3836 info.format = gimple_call_arg (info.callstmt, idx_format);
3838 /* True when the destination size is constant as opposed to the lower
3839 or upper bound of a range. */
3840 bool dstsize_cst_p = true;
3842 if (idx_dstsize == HOST_WIDE_INT_M1U)
3844 /* For non-bounded functions like sprintf, determine the size
3845 of the destination from the object or pointer passed to it
3846 as the first argument. */
3847 dstsize = get_destination_size (dstptr);
3849 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3851 /* For bounded functions try to get the size argument. */
3853 if (TREE_CODE (size) == INTEGER_CST)
3855 dstsize = tree_to_uhwi (size);
3856 /* No object can be larger than SIZE_MAX bytes (half the address
3857 space) on the target.
3858 The functions are defined only for output of at most INT_MAX
3859 bytes. Specifying a bound in excess of that limit effectively
3860 defeats the bounds checking (and on some implementations such
3861 as Solaris cause the function to fail with EINVAL). */
3862 if (dstsize > target_size_max () / 2)
3864 /* Avoid warning if -Wstringop-overflow is specified since
3865 it also warns for the same thing though only for the
3866 checking built-ins. */
3867 if ((idx_objsize == HOST_WIDE_INT_M1U
3868 || !warn_stringop_overflow))
3869 warning_at (gimple_location (info.callstmt), info.warnopt (),
3870 "specified bound %wu exceeds maximum object size "
3871 "%wu",
3872 dstsize, target_size_max () / 2);
3874 else if (dstsize > target_int_max ())
3875 warning_at (gimple_location (info.callstmt), info.warnopt (),
3876 "specified bound %wu exceeds %<INT_MAX%>",
3877 dstsize);
3879 else if (TREE_CODE (size) == SSA_NAME)
3881 /* Try to determine the range of values of the argument
3882 and use the greater of the two at level 1 and the smaller
3883 of them at level 2. */
3884 wide_int min, max;
3885 enum value_range_type range_type
3886 = get_range_info (size, &min, &max);
3887 if (range_type == VR_RANGE)
3889 dstsize
3890 = (warn_level < 2
3891 ? wi::fits_uhwi_p (max) ? max.to_uhwi () : max.to_shwi ()
3892 : wi::fits_uhwi_p (min) ? min.to_uhwi () : min.to_shwi ());
3895 /* The destination size is not constant. If the function is
3896 bounded (e.g., snprintf) a lower bound of zero doesn't
3897 necessarily imply it can be eliminated. */
3898 dstsize_cst_p = false;
3902 if (idx_objsize != HOST_WIDE_INT_M1U)
3903 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3904 if (tree_fits_uhwi_p (size))
3905 objsize = tree_to_uhwi (size);
3907 if (info.bounded && !dstsize)
3909 /* As a special case, when the explicitly specified destination
3910 size argument (to a bounded function like snprintf) is zero
3911 it is a request to determine the number of bytes on output
3912 without actually producing any. Pretend the size is
3913 unlimited in this case. */
3914 info.objsize = HOST_WIDE_INT_MAX;
3915 info.nowrite = dstsize_cst_p;
3917 else
3919 /* For calls to non-bounded functions or to those of bounded
3920 functions with a non-zero size, warn if the destination
3921 pointer is null. */
3922 if (integer_zerop (dstptr))
3924 /* This is diagnosed with -Wformat only when the null is a constant
3925 pointer. The warning here diagnoses instances where the pointer
3926 is not constant. */
3927 location_t loc = gimple_location (info.callstmt);
3928 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3929 info.warnopt (), "null destination pointer");
3930 return false;
3933 /* Set the object size to the smaller of the two arguments
3934 of both have been specified and they're not equal. */
3935 info.objsize = dstsize < objsize ? dstsize : objsize;
3937 if (info.bounded
3938 && dstsize < target_size_max () / 2 && objsize < dstsize
3939 /* Avoid warning if -Wstringop-overflow is specified since
3940 it also warns for the same thing though only for the
3941 checking built-ins. */
3942 && (idx_objsize == HOST_WIDE_INT_M1U
3943 || !warn_stringop_overflow))
3945 warning_at (gimple_location (info.callstmt), info.warnopt (),
3946 "specified bound %wu exceeds the size %wu "
3947 "of the destination object", dstsize, objsize);
3951 if (integer_zerop (info.format))
3953 /* This is diagnosed with -Wformat only when the null is a constant
3954 pointer. The warning here diagnoses instances where the pointer
3955 is not constant. */
3956 location_t loc = gimple_location (info.callstmt);
3957 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3958 info.warnopt (), "null format string");
3959 return false;
3962 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3963 if (!info.fmtstr)
3964 return false;
3966 /* The result is the number of bytes output by the formatted function,
3967 including the terminating NUL. */
3968 format_result res = format_result ();
3970 bool success = compute_format_length (info, &res);
3972 /* When optimizing and the printf return value optimization is enabled,
3973 attempt to substitute the computed result for the return value of
3974 the call. Avoid this optimization when -frounding-math is in effect
3975 and the format string contains a floating point directive. */
3976 bool call_removed = false;
3977 if (success && optimize > 0)
3979 /* Save a copy of the iterator pointing at the call. The iterator
3980 may change to point past the call in try_substitute_return_value
3981 but the original value is needed in try_simplify_call. */
3982 gimple_stmt_iterator gsi_call = *gsi;
3984 if (flag_printf_return_value
3985 && (!flag_rounding_math || !res.floating))
3986 call_removed = try_substitute_return_value (gsi, info, res);
3988 if (!call_removed)
3989 try_simplify_call (&gsi_call, info, res);
3992 return call_removed;
3995 edge
3996 sprintf_dom_walker::before_dom_children (basic_block bb)
3998 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
4000 /* Iterate over statements, looking for function calls. */
4001 gimple *stmt = gsi_stmt (si);
4003 if (is_gimple_call (stmt) && handle_gimple_call (&si))
4004 /* If handle_gimple_call returns true, the iterator is
4005 already pointing to the next statement. */
4006 continue;
4008 gsi_next (&si);
4010 return NULL;
4013 /* Execute the pass for function FUN. */
4015 unsigned int
4016 pass_sprintf_length::execute (function *fun)
4018 init_target_to_host_charmap ();
4020 calculate_dominance_info (CDI_DOMINATORS);
4022 sprintf_dom_walker sprintf_dom_walker;
4023 sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
4025 /* Clean up object size info. */
4026 fini_object_sizes ();
4027 return 0;
4030 } /* Unnamed namespace. */
4032 /* Return a pointer to a pass object newly constructed from the context
4033 CTXT. */
4035 gimple_opt_pass *
4036 make_pass_sprintf_length (gcc::context *ctxt)
4038 return new pass_sprintf_length (ctxt);