* fr.po: Update.
[official-gcc.git] / gcc / gimple-ssa-sprintf.c
blobc3c717d9060273594d9626611000cc35e4b89257
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"
83 /* The likely worst case value of MB_LEN_MAX for the target, large enough
84 for UTF-8. Ideally, this would be obtained by a target hook if it were
85 to be used for optimization but it's good enough as is for warnings. */
86 #define target_mb_len_max() 6
88 /* The maximum number of bytes a single non-string directive can result
89 in. This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
90 LDBL_MAX_10_EXP of 4932. */
91 #define IEEE_MAX_10_EXP 4932
92 #define target_dir_max() (target_int_max () + IEEE_MAX_10_EXP + 2)
94 namespace {
96 const pass_data pass_data_sprintf_length = {
97 GIMPLE_PASS, // pass type
98 "printf-return-value", // pass name
99 OPTGROUP_NONE, // optinfo_flags
100 TV_NONE, // tv_id
101 PROP_cfg, // properties_required
102 0, // properties_provided
103 0, // properties_destroyed
104 0, // properties_start
105 0, // properties_finish
108 /* Set to the warning level for the current function which is equal
109 either to warn_format_trunc for bounded functions or to
110 warn_format_overflow otherwise. */
112 static int warn_level;
114 struct format_result;
116 class pass_sprintf_length : public gimple_opt_pass
118 bool fold_return_value;
120 public:
121 pass_sprintf_length (gcc::context *ctxt)
122 : gimple_opt_pass (pass_data_sprintf_length, ctxt),
123 fold_return_value (false)
126 opt_pass * clone () { return new pass_sprintf_length (m_ctxt); }
128 virtual bool gate (function *);
130 virtual unsigned int execute (function *);
132 void set_pass_param (unsigned int n, bool param)
134 gcc_assert (n == 0);
135 fold_return_value = param;
138 bool handle_gimple_call (gimple_stmt_iterator *);
140 struct call_info;
141 bool compute_format_length (call_info &, format_result *);
144 bool
145 pass_sprintf_length::gate (function *)
147 /* Run the pass iff -Warn-format-overflow or -Warn-format-truncation
148 is specified and either not optimizing and the pass is being invoked
149 early, or when optimizing and the pass is being invoked during
150 optimization (i.e., "late"). */
151 return ((warn_format_overflow > 0
152 || warn_format_trunc > 0
153 || flag_printf_return_value)
154 && (optimize > 0) == fold_return_value);
157 /* The minimum, maximum, likely, and unlikely maximum number of bytes
158 of output either a formatting function or an individual directive
159 can result in. */
161 struct result_range
163 /* The absolute minimum number of bytes. The result of a successful
164 conversion is guaranteed to be no less than this. (An erroneous
165 conversion can be indicated by MIN > HOST_WIDE_INT_MAX.) */
166 unsigned HOST_WIDE_INT min;
167 /* The likely maximum result that is used in diagnostics. In most
168 cases MAX is the same as the worst case UNLIKELY result. */
169 unsigned HOST_WIDE_INT max;
170 /* The likely result used to trigger diagnostics. For conversions
171 that result in a range of bytes [MIN, MAX], LIKELY is somewhere
172 in that range. */
173 unsigned HOST_WIDE_INT likely;
174 /* In rare cases (e.g., for nultibyte characters) UNLIKELY gives
175 the worst cases maximum result of a directive. In most cases
176 UNLIKELY == MAX. UNLIKELY is used to control the return value
177 optimization but not in diagnostics. */
178 unsigned HOST_WIDE_INT unlikely;
181 /* The result of a call to a formatted function. */
183 struct format_result
185 /* Range of characters written by the formatted function.
186 Setting the minimum to HOST_WIDE_INT_MAX disables all
187 length tracking for the remainder of the format string. */
188 result_range range;
190 /* True when the range above is obtained from known values of
191 directive arguments, or bounds on the amount of output such
192 as width and precision, and not the result of heuristics that
193 depend on warning levels. It's used to issue stricter diagnostics
194 in cases where strings of unknown lengths are bounded by the arrays
195 they are determined to refer to. KNOWNRANGE must not be used for
196 the return value optimization. */
197 bool knownrange;
199 /* True if no individual directive resulted in more than 4095 bytes
200 of output (the total NUMBER_CHARS_{MIN,MAX} might be greater).
201 Implementations are not required to handle directives that produce
202 more than 4K bytes (leading to undefined behavior) and so when one
203 is found it disables the return value optimization. */
204 bool under4k;
206 /* True when a floating point directive has been seen in the format
207 string. */
208 bool floating;
210 /* True when an intermediate result has caused a warning. Used to
211 avoid issuing duplicate warnings while finishing the processing
212 of a call. WARNED also disables the return value optimization. */
213 bool warned;
215 /* Preincrement the number of output characters by 1. */
216 format_result& operator++ ()
218 return *this += 1;
221 /* Postincrement the number of output characters by 1. */
222 format_result operator++ (int)
224 format_result prev (*this);
225 *this += 1;
226 return prev;
229 /* Increment the number of output characters by N. */
230 format_result& operator+= (unsigned HOST_WIDE_INT);
233 format_result&
234 format_result::operator+= (unsigned HOST_WIDE_INT n)
236 gcc_assert (n < HOST_WIDE_INT_MAX);
238 if (range.min < HOST_WIDE_INT_MAX)
239 range.min += n;
241 if (range.max < HOST_WIDE_INT_MAX)
242 range.max += n;
244 if (range.likely < HOST_WIDE_INT_MAX)
245 range.likely += n;
247 if (range.unlikely < HOST_WIDE_INT_MAX)
248 range.unlikely += n;
250 return *this;
253 /* Return the value of INT_MIN for the target. */
255 static inline HOST_WIDE_INT
256 target_int_min ()
258 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
261 /* Return the value of INT_MAX for the target. */
263 static inline unsigned HOST_WIDE_INT
264 target_int_max ()
266 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
269 /* Return the value of SIZE_MAX for the target. */
271 static inline unsigned HOST_WIDE_INT
272 target_size_max ()
274 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
277 /* A straightforward mapping from the execution character set to the host
278 character set indexed by execution character. */
280 static char target_to_host_charmap[256];
282 /* Initialize a mapping from the execution character set to the host
283 character set. */
285 static bool
286 init_target_to_host_charmap ()
288 /* If the percent sign is non-zero the mapping has already been
289 initialized. */
290 if (target_to_host_charmap['%'])
291 return true;
293 /* Initialize the target_percent character (done elsewhere). */
294 if (!init_target_chars ())
295 return false;
297 /* The subset of the source character set used by printf conversion
298 specifications (strictly speaking, not all letters are used but
299 they are included here for the sake of simplicity). The dollar
300 sign must be included even though it's not in the basic source
301 character set. */
302 const char srcset[] = " 0123456789!\"#%&'()*+,-./:;<=>?[\\]^_{|}~$"
303 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
305 /* Set the mapping for all characters to some ordinary value (i,e.,
306 not none used in printf conversion specifications) and overwrite
307 those that are used by conversion specifications with their
308 corresponding values. */
309 memset (target_to_host_charmap + 1, '?', sizeof target_to_host_charmap - 1);
311 /* Are the two sets of characters the same? */
312 bool all_same_p = true;
314 for (const char *pc = srcset; *pc; ++pc)
316 /* Slice off the high end bits in case target characters are
317 signed. All values are expected to be non-nul, otherwise
318 there's a problem. */
319 if (unsigned char tc = lang_hooks.to_target_charset (*pc))
321 target_to_host_charmap[tc] = *pc;
322 if (tc != *pc)
323 all_same_p = false;
325 else
326 return false;
330 /* Set the first element to a non-zero value if the mapping
331 is 1-to-1, otherwise leave it clear (NUL is assumed to be
332 the same in both character sets). */
333 target_to_host_charmap[0] = all_same_p;
335 return true;
338 /* Return the host source character corresponding to the character
339 CH in the execution character set if one exists, or some innocuous
340 (non-special, non-nul) source character otherwise. */
342 static inline unsigned char
343 target_to_host (unsigned char ch)
345 return target_to_host_charmap[ch];
348 /* Convert an initial substring of the string TARGSTR consisting of
349 characters in the execution character set into a string in the
350 source character set on the host and store up to HOSTSZ characters
351 in the buffer pointed to by HOSTR. Return HOSTR. */
353 static const char*
354 target_to_host (char *hostr, size_t hostsz, const char *targstr)
356 /* Make sure the buffer is reasonably big. */
357 gcc_assert (hostsz > 4);
359 /* The interesting subset of source and execution characters are
360 the same so no conversion is necessary. However, truncate
361 overlong strings just like the translated strings are. */
362 if (target_to_host_charmap['\0'] == 1)
364 strncpy (hostr, targstr, hostsz - 4);
365 if (strlen (targstr) >= hostsz)
366 strcpy (hostr + hostsz - 4, "...");
367 return hostr;
370 /* Convert the initial substring of TARGSTR to the corresponding
371 characters in the host set, appending "..." if TARGSTR is too
372 long to fit. Using the static buffer assumes the function is
373 not called in between sequence points (which it isn't). */
374 for (char *ph = hostr; ; ++targstr)
376 *ph++ = target_to_host (*targstr);
377 if (!*targstr)
378 break;
380 if (size_t (ph - hostr) == hostsz - 4)
382 *ph = '\0';
383 strcat (ph, "...");
384 break;
388 return hostr;
391 /* Convert the sequence of decimal digits in the execution character
392 starting at S to a long, just like strtol does. Return the result
393 and set *END to one past the last converted character. On range
394 error set ERANGE to the digit that caused it. */
396 static inline long
397 target_strtol10 (const char **ps, const char **erange)
399 unsigned HOST_WIDE_INT val = 0;
400 for ( ; ; ++*ps)
402 unsigned char c = target_to_host (**ps);
403 if (ISDIGIT (c))
405 c -= '0';
407 /* Check for overflow. */
408 if (val > (LONG_MAX - c) / 10LU)
410 val = LONG_MAX;
411 *erange = *ps;
413 /* Skip the remaining digits. */
415 c = target_to_host (*++*ps);
416 while (ISDIGIT (c));
417 break;
419 else
420 val = val * 10 + c;
422 else
423 break;
426 return val;
429 /* Return the constant initial value of DECL if available or DECL
430 otherwise. Same as the synonymous function in c/c-typeck.c. */
432 static tree
433 decl_constant_value (tree decl)
435 if (/* Don't change a variable array bound or initial value to a constant
436 in a place where a variable is invalid. Note that DECL_INITIAL
437 isn't valid for a PARM_DECL. */
438 current_function_decl != 0
439 && TREE_CODE (decl) != PARM_DECL
440 && !TREE_THIS_VOLATILE (decl)
441 && TREE_READONLY (decl)
442 && DECL_INITIAL (decl) != 0
443 && TREE_CODE (DECL_INITIAL (decl)) != ERROR_MARK
444 /* This is invalid if initial value is not constant.
445 If it has either a function call, a memory reference,
446 or a variable, then re-evaluating it could give different results. */
447 && TREE_CONSTANT (DECL_INITIAL (decl))
448 /* Check for cases where this is sub-optimal, even though valid. */
449 && TREE_CODE (DECL_INITIAL (decl)) != CONSTRUCTOR)
450 return DECL_INITIAL (decl);
451 return decl;
454 /* Given FORMAT, set *PLOC to the source location of the format string
455 and return the format string if it is known or null otherwise. */
457 static const char*
458 get_format_string (tree format, location_t *ploc)
460 if (VAR_P (format))
462 /* Pull out a constant value if the front end didn't. */
463 format = decl_constant_value (format);
464 STRIP_NOPS (format);
467 if (integer_zerop (format))
469 /* FIXME: Diagnose null format string if it hasn't been diagnosed
470 by -Wformat (the latter diagnoses only nul pointer constants,
471 this pass can do better). */
472 return NULL;
475 HOST_WIDE_INT offset = 0;
477 if (TREE_CODE (format) == POINTER_PLUS_EXPR)
479 tree arg0 = TREE_OPERAND (format, 0);
480 tree arg1 = TREE_OPERAND (format, 1);
481 STRIP_NOPS (arg0);
482 STRIP_NOPS (arg1);
484 if (TREE_CODE (arg1) != INTEGER_CST)
485 return NULL;
487 format = arg0;
489 /* POINTER_PLUS_EXPR offsets are to be interpreted signed. */
490 if (!cst_and_fits_in_hwi (arg1))
491 return NULL;
493 offset = int_cst_value (arg1);
496 if (TREE_CODE (format) != ADDR_EXPR)
497 return NULL;
499 *ploc = EXPR_LOC_OR_LOC (format, input_location);
501 format = TREE_OPERAND (format, 0);
503 if (TREE_CODE (format) == ARRAY_REF
504 && tree_fits_shwi_p (TREE_OPERAND (format, 1))
505 && (offset += tree_to_shwi (TREE_OPERAND (format, 1))) >= 0)
506 format = TREE_OPERAND (format, 0);
508 if (offset < 0)
509 return NULL;
511 tree array_init;
512 tree array_size = NULL_TREE;
514 if (VAR_P (format)
515 && TREE_CODE (TREE_TYPE (format)) == ARRAY_TYPE
516 && (array_init = decl_constant_value (format)) != format
517 && TREE_CODE (array_init) == STRING_CST)
519 /* Extract the string constant initializer. Note that this may
520 include a trailing NUL character that is not in the array (e.g.
521 const char a[3] = "foo";). */
522 array_size = DECL_SIZE_UNIT (format);
523 format = array_init;
526 if (TREE_CODE (format) != STRING_CST)
527 return NULL;
529 if (TYPE_MAIN_VARIANT (TREE_TYPE (TREE_TYPE (format))) != char_type_node)
531 /* Wide format string. */
532 return NULL;
535 const char *fmtstr = TREE_STRING_POINTER (format);
536 unsigned fmtlen = TREE_STRING_LENGTH (format);
538 if (array_size)
540 /* Variable length arrays can't be initialized. */
541 gcc_assert (TREE_CODE (array_size) == INTEGER_CST);
543 if (tree_fits_shwi_p (array_size))
545 HOST_WIDE_INT array_size_value = tree_to_shwi (array_size);
546 if (array_size_value > 0
547 && array_size_value == (int) array_size_value
548 && fmtlen > array_size_value)
549 fmtlen = array_size_value;
552 if (offset)
554 if (offset >= fmtlen)
555 return NULL;
557 fmtstr += offset;
558 fmtlen -= offset;
561 if (fmtlen < 1 || fmtstr[--fmtlen] != 0)
563 /* FIXME: Diagnose an unterminated format string if it hasn't been
564 diagnosed by -Wformat. Similarly to a null format pointer,
565 -Wformay diagnoses only nul pointer constants, this pass can
566 do better). */
567 return NULL;
570 return fmtstr;
573 /* The format_warning_at_substring function is not used here in a way
574 that makes using attribute format viable. Suppress the warning. */
576 #pragma GCC diagnostic push
577 #pragma GCC diagnostic ignored "-Wsuggest-attribute=format"
579 /* For convenience and brevity. */
581 static bool
582 (* const fmtwarn) (const substring_loc &, const source_range *,
583 const char *, int, const char *, ...)
584 = format_warning_at_substring;
586 /* Format length modifiers. */
588 enum format_lengths
590 FMT_LEN_none,
591 FMT_LEN_hh, // char argument
592 FMT_LEN_h, // short
593 FMT_LEN_l, // long
594 FMT_LEN_ll, // long long
595 FMT_LEN_L, // long double (and GNU long long)
596 FMT_LEN_z, // size_t
597 FMT_LEN_t, // ptrdiff_t
598 FMT_LEN_j // intmax_t
602 /* Description of the result of conversion either of a single directive
603 or the whole format string. */
605 struct fmtresult
607 /* Construct a FMTRESULT object with all counters initialized
608 to MIN. KNOWNRANGE is set when MIN is valid. */
609 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
610 : argmin (), argmax (),
611 knownrange (min < HOST_WIDE_INT_MAX),
612 nullp ()
614 range.min = min;
615 range.max = min;
616 range.likely = min;
617 range.unlikely = min;
620 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
621 KNOWNRANGE is set when both MIN and MAX are valid. */
622 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
623 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
624 : argmin (), argmax (),
625 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
626 nullp ()
628 range.min = min;
629 range.max = max;
630 range.likely = max < likely ? min : likely;
631 range.unlikely = max;
634 /* Adjust result upward to reflect the RANGE of values the specified
635 width or precision is known to be in. */
636 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
637 tree = NULL_TREE,
638 unsigned = 0, unsigned = 0);
640 /* Return the maximum number of decimal digits a value of TYPE
641 formats as on output. */
642 static unsigned type_max_digits (tree, int);
644 /* The range a directive's argument is in. */
645 tree argmin, argmax;
647 /* The minimum and maximum number of bytes that a directive
648 results in on output for an argument in the range above. */
649 result_range range;
651 /* True when the range above is obtained from a known value of
652 a directive's argument or its bounds and not the result of
653 heuristics that depend on warning levels. */
654 bool knownrange;
656 /* True when the argument is a null pointer. */
657 bool nullp;
660 /* Adjust result upward to reflect the range ADJUST of values the
661 specified width or precision is known to be in. When non-null,
662 TYPE denotes the type of the directive whose result is being
663 adjusted, BASE gives the base of the directive (octal, decimal,
664 or hex), and ADJ denotes the additional adjustment to the LIKELY
665 counter that may need to be added when ADJUST is a range. */
667 fmtresult&
668 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
669 tree type /* = NULL_TREE */,
670 unsigned base /* = 0 */,
671 unsigned adj /* = 0 */)
673 bool minadjusted = false;
675 /* Adjust the minimum and likely counters. */
676 if (adjust[0] >= 0)
678 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
680 range.min = adjust[0];
681 minadjusted = true;
684 /* Adjust the likely counter. */
685 if (range.likely < range.min)
686 range.likely = range.min;
688 else if (adjust[0] == target_int_min ()
689 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
690 knownrange = false;
692 /* Adjust the maximum counter. */
693 if (adjust[1] > 0)
695 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
697 range.max = adjust[1];
699 /* Set KNOWNRANGE if both the minimum and maximum have been
700 adjusted. Otherwise leave it at what it was before. */
701 knownrange = minadjusted;
705 if (warn_level > 1 && type)
707 /* For large non-constant width or precision whose range spans
708 the maximum number of digits produced by the directive for
709 any argument, set the likely number of bytes to be at most
710 the number digits plus other adjustment determined by the
711 caller (one for sign or two for the hexadecimal "0x"
712 prefix). */
713 unsigned dirdigs = type_max_digits (type, base);
714 if (adjust[0] < dirdigs && dirdigs < adjust[1]
715 && range.likely < dirdigs)
716 range.likely = dirdigs + adj;
718 else if (range.likely < (range.min ? range.min : 1))
720 /* Conservatively, set LIKELY to at least MIN but no less than
721 1 unless MAX is zero. */
722 range.likely = (range.min
723 ? range.min
724 : range.max && (range.max < HOST_WIDE_INT_MAX
725 || warn_level > 1) ? 1 : 0);
728 /* Finally adjust the unlikely counter to be at least as large as
729 the maximum. */
730 if (range.unlikely < range.max)
731 range.unlikely = range.max;
733 return *this;
736 /* Return the maximum number of digits a value of TYPE formats in
737 BASE on output, not counting base prefix . */
739 unsigned
740 fmtresult::type_max_digits (tree type, int base)
742 unsigned prec = TYPE_PRECISION (type);
743 if (base == 8)
744 return (prec + 2) / 3;
746 if (base == 16)
747 return prec / 4;
749 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
750 of 8, 16, 32, and 64 bits. */
751 return prec * 301 / 1000 + 1;
754 static bool
755 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT);
757 /* Description of a format directive. A directive is either a plain
758 string or a conversion specification that starts with '%'. */
760 struct directive
762 /* The 1-based directive number (for debugging). */
763 unsigned dirno;
765 /* The first character of the directive and its length. */
766 const char *beg;
767 size_t len;
769 /* A bitmap of flags, one for each character. */
770 unsigned flags[256 / sizeof (int)];
772 /* The range of values of the specified width, or -1 if not specified. */
773 HOST_WIDE_INT width[2];
774 /* The range of values of the specified precision, or -1 if not
775 specified. */
776 HOST_WIDE_INT prec[2];
778 /* Length modifier. */
779 format_lengths modifier;
781 /* Format specifier character. */
782 char specifier;
784 /* The argument of the directive or null when the directive doesn't
785 take one or when none is available (such as for vararg functions). */
786 tree arg;
788 /* Format conversion function that given a directive and an argument
789 returns the formatting result. */
790 fmtresult (*fmtfunc) (const directive &, tree);
792 /* Return True when a the format flag CHR has been used. */
793 bool get_flag (char chr) const
795 unsigned char c = chr & 0xff;
796 return (flags[c / (CHAR_BIT * sizeof *flags)]
797 & (1U << (c % (CHAR_BIT * sizeof *flags))));
800 /* Make a record of the format flag CHR having been used. */
801 void set_flag (char chr)
803 unsigned char c = chr & 0xff;
804 flags[c / (CHAR_BIT * sizeof *flags)]
805 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
808 /* Reset the format flag CHR. */
809 void clear_flag (char chr)
811 unsigned char c = chr & 0xff;
812 flags[c / (CHAR_BIT * sizeof *flags)]
813 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
816 /* Set both bounds of the width range to VAL. */
817 void set_width (HOST_WIDE_INT val)
819 width[0] = width[1] = val;
822 /* Set the width range according to ARG, with both bounds being
823 no less than 0. For a constant ARG set both bounds to its value
824 or 0, whichever is greater. For a non-constant ARG in some range
825 set width to its range adjusting each bound to -1 if it's less.
826 For an indeterminate ARG set width to [0, INT_MAX]. */
827 void set_width (tree arg)
829 get_int_range (arg, width, width + 1, true, 0);
832 /* Set both bounds of the precision range to VAL. */
833 void set_precision (HOST_WIDE_INT val)
835 prec[0] = prec[1] = val;
838 /* Set the precision range according to ARG, with both bounds being
839 no less than -1. For a constant ARG set both bounds to its value
840 or -1 whichever is greater. For a non-constant ARG in some range
841 set precision to its range adjusting each bound to -1 if it's less.
842 For an indeterminate ARG set precision to [-1, INT_MAX]. */
843 void set_precision (tree arg)
845 get_int_range (arg, prec, prec + 1, false, -1);
848 /* Return true if both width and precision are known to be
849 either constant or in some range, false otherwise. */
850 bool known_width_and_precision () const
852 return ((width[1] < 0
853 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
854 && (prec[1] < 0
855 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
859 /* Return the logarithm of X in BASE. */
861 static int
862 ilog (unsigned HOST_WIDE_INT x, int base)
864 int res = 0;
867 ++res;
868 x /= base;
869 } while (x);
870 return res;
873 /* Return the number of bytes resulting from converting into a string
874 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
875 PLUS indicates whether 1 for a plus sign should be added for positive
876 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
877 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
878 be represented. */
880 static HOST_WIDE_INT
881 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
883 unsigned HOST_WIDE_INT absval;
885 HOST_WIDE_INT res;
887 if (TYPE_UNSIGNED (TREE_TYPE (x)))
889 if (tree_fits_uhwi_p (x))
891 absval = tree_to_uhwi (x);
892 res = plus;
894 else
895 return -1;
897 else
899 if (tree_fits_shwi_p (x))
901 HOST_WIDE_INT i = tree_to_shwi (x);
902 if (HOST_WIDE_INT_MIN == i)
904 /* Avoid undefined behavior due to negating a minimum. */
905 absval = HOST_WIDE_INT_MAX;
906 res = 1;
908 else if (i < 0)
910 absval = -i;
911 res = 1;
913 else
915 absval = i;
916 res = plus;
919 else
920 return -1;
923 int ndigs = ilog (absval, base);
925 res += prec < ndigs ? ndigs : prec;
927 /* Adjust a non-zero value for the base prefix, either hexadecimal,
928 or, unless precision has resulted in a leading zero, also octal. */
929 if (prefix && absval && (base == 16 || prec <= ndigs))
931 if (base == 8)
932 res += 1;
933 else if (base == 16)
934 res += 2;
937 return res;
940 /* Given the formatting result described by RES and NAVAIL, the number
941 of available in the destination, return the range of bytes remaining
942 in the destination. */
944 static inline result_range
945 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
947 result_range range;
949 if (HOST_WIDE_INT_MAX <= navail)
951 range.min = range.max = range.likely = range.unlikely = navail;
952 return range;
955 /* The lower bound of the available range is the available size
956 minus the maximum output size, and the upper bound is the size
957 minus the minimum. */
958 range.max = res.range.min < navail ? navail - res.range.min : 0;
960 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
962 if (res.range.max < HOST_WIDE_INT_MAX)
963 range.min = res.range.max < navail ? navail - res.range.max : 0;
964 else
965 range.min = range.likely;
967 range.unlikely = (res.range.unlikely < navail
968 ? navail - res.range.unlikely : 0);
970 return range;
973 /* Description of a call to a formatted function. */
975 struct pass_sprintf_length::call_info
977 /* Function call statement. */
978 gimple *callstmt;
980 /* Function called. */
981 tree func;
983 /* Called built-in function code. */
984 built_in_function fncode;
986 /* Format argument and format string extracted from it. */
987 tree format;
988 const char *fmtstr;
990 /* The location of the format argument. */
991 location_t fmtloc;
993 /* The destination object size for __builtin___xxx_chk functions
994 typically determined by __builtin_object_size, or -1 if unknown. */
995 unsigned HOST_WIDE_INT objsize;
997 /* Number of the first variable argument. */
998 unsigned HOST_WIDE_INT argidx;
1000 /* True for functions like snprintf that specify the size of
1001 the destination, false for others like sprintf that don't. */
1002 bool bounded;
1004 /* True for bounded functions like snprintf that specify a zero-size
1005 buffer as a request to compute the size of output without actually
1006 writing any. NOWRITE is cleared in response to the %n directive
1007 which has side-effects similar to writing output. */
1008 bool nowrite;
1010 /* Return true if the called function's return value is used. */
1011 bool retval_used () const
1013 return gimple_get_lhs (callstmt);
1016 /* Return the warning option corresponding to the called function. */
1017 int warnopt () const
1019 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
1023 /* Return the result of formatting a no-op directive (such as '%n'). */
1025 static fmtresult
1026 format_none (const directive &, tree)
1028 fmtresult res (0);
1029 return res;
1032 /* Return the result of formatting the '%%' directive. */
1034 static fmtresult
1035 format_percent (const directive &, tree)
1037 fmtresult res (1);
1038 return res;
1042 /* Compute intmax_type_node and uintmax_type_node similarly to how
1043 tree.c builds size_type_node. */
1045 static void
1046 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
1048 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
1050 *pintmax = integer_type_node;
1051 *puintmax = unsigned_type_node;
1053 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
1055 *pintmax = long_integer_type_node;
1056 *puintmax = long_unsigned_type_node;
1058 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
1060 *pintmax = long_long_integer_type_node;
1061 *puintmax = long_long_unsigned_type_node;
1063 else
1065 for (int i = 0; i < NUM_INT_N_ENTS; i++)
1066 if (int_n_enabled_p[i])
1068 char name[50];
1069 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
1071 if (strcmp (name, UINTMAX_TYPE) == 0)
1073 *pintmax = int_n_trees[i].signed_type;
1074 *puintmax = int_n_trees[i].unsigned_type;
1075 return;
1078 gcc_unreachable ();
1082 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
1083 in and that is representable in type int.
1084 Return true when the range is a subrange of that of int.
1085 When ARG is null it is as if it had the full range of int.
1086 When ABSOLUTE is true the range reflects the absolute value of
1087 the argument. When ABSOLUTE is false, negative bounds of
1088 the determined range are replaced with NEGBOUND. */
1090 static bool
1091 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1092 bool absolute, HOST_WIDE_INT negbound)
1094 /* The type of the result. */
1095 const_tree type = integer_type_node;
1097 bool knownrange = false;
1099 if (!arg)
1101 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1102 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1104 else if (TREE_CODE (arg) == INTEGER_CST
1105 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1107 /* For a constant argument return its value adjusted as specified
1108 by NEGATIVE and NEGBOUND and return true to indicate that the
1109 result is known. */
1110 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1111 *pmax = *pmin;
1112 knownrange = true;
1114 else
1116 /* True if the argument's range cannot be determined. */
1117 bool unknown = true;
1119 tree argtype = TREE_TYPE (arg);
1121 /* Ignore invalid arguments with greater precision that that
1122 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1123 They will have been detected and diagnosed by -Wformat and
1124 so it's not important to complicate this code to try to deal
1125 with them again. */
1126 if (TREE_CODE (arg) == SSA_NAME
1127 && INTEGRAL_TYPE_P (argtype)
1128 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1130 /* Try to determine the range of values of the integer argument. */
1131 wide_int min, max;
1132 enum value_range_type range_type = get_range_info (arg, &min, &max);
1133 if (range_type == VR_RANGE)
1135 HOST_WIDE_INT type_min
1136 = (TYPE_UNSIGNED (argtype)
1137 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1138 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1140 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1142 *pmin = min.to_shwi ();
1143 *pmax = max.to_shwi ();
1145 if (*pmin < *pmax)
1147 /* Return true if the adjusted range is a subrange of
1148 the full range of the argument's type. *PMAX may
1149 be less than *PMIN when the argument is unsigned
1150 and its upper bound is in excess of TYPE_MAX. In
1151 that (invalid) case disregard the range and use that
1152 of the expected type instead. */
1153 knownrange = type_min < *pmin || *pmax < type_max;
1155 unknown = false;
1160 /* Handle an argument with an unknown range as if none had been
1161 provided. */
1162 if (unknown)
1163 return get_int_range (NULL_TREE, pmin, pmax, absolute, negbound);
1166 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1167 if (absolute)
1169 if (*pmin < 0)
1171 if (*pmin == *pmax)
1172 *pmin = *pmax = -*pmin;
1173 else
1175 /* Make sure signed overlow is avoided. */
1176 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1178 HOST_WIDE_INT tmp = -*pmin;
1179 *pmin = 0;
1180 if (*pmax < tmp)
1181 *pmax = tmp;
1185 else if (*pmin < negbound)
1186 *pmin = negbound;
1188 return knownrange;
1191 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1192 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1193 the type of the directive's formal argument it's possible for both
1194 to result in the same number of bytes or a range of bytes that's
1195 less than the number of bytes that would result from formatting
1196 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1197 determined by checking for the actual argument being in the range
1198 of the type of the directive. If it isn't it must be assumed to
1199 take on the full range of the directive's type.
1200 Return true when the range has been adjusted to the full range
1201 of DIRTYPE, and false otherwise. */
1203 static bool
1204 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1206 tree argtype = TREE_TYPE (*argmin);
1207 unsigned argprec = TYPE_PRECISION (argtype);
1208 unsigned dirprec = TYPE_PRECISION (dirtype);
1210 /* If the actual argument and the directive's argument have the same
1211 precision and sign there can be no overflow and so there is nothing
1212 to adjust. */
1213 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1214 return false;
1216 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1217 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1219 if (TREE_CODE (*argmin) == INTEGER_CST
1220 && TREE_CODE (*argmax) == INTEGER_CST
1221 && (dirprec >= argprec
1222 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1223 int_const_binop (MINUS_EXPR,
1224 *argmax,
1225 *argmin),
1226 size_int (dirprec)))))
1228 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1229 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1231 /* If *ARGMIN is still less than *ARGMAX the conversion above
1232 is safe. Otherwise, it has overflowed and would be unsafe. */
1233 if (tree_int_cst_le (*argmin, *argmax))
1234 return false;
1237 *argmin = TYPE_MIN_VALUE (dirtype);
1238 *argmax = TYPE_MAX_VALUE (dirtype);
1239 return true;
1242 /* Return a range representing the minimum and maximum number of bytes
1243 that the format directive DIR will output for any argument given
1244 the WIDTH and PRECISION (extracted from DIR). This function is
1245 used when the directive argument or its value isn't known. */
1247 static fmtresult
1248 format_integer (const directive &dir, tree arg)
1250 tree intmax_type_node;
1251 tree uintmax_type_node;
1253 /* Base to format the number in. */
1254 int base;
1256 /* True when a conversion is preceded by a prefix indicating the base
1257 of the argument (octal or hexadecimal). */
1258 bool maybebase = dir.get_flag ('#');
1260 /* True when a signed conversion is preceded by a sign or space. */
1261 bool maybesign = false;
1263 /* True for signed conversions (i.e., 'd' and 'i'). */
1264 bool sign = false;
1266 switch (dir.specifier)
1268 case 'd':
1269 case 'i':
1270 /* Space and '+' are only meaningful for signed conversions. */
1271 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1272 sign = true;
1273 base = 10;
1274 break;
1275 case 'u':
1276 base = 10;
1277 break;
1278 case 'o':
1279 base = 8;
1280 break;
1281 case 'X':
1282 case 'x':
1283 base = 16;
1284 break;
1285 default:
1286 gcc_unreachable ();
1289 /* The type of the "formal" argument expected by the directive. */
1290 tree dirtype = NULL_TREE;
1292 /* Determine the expected type of the argument from the length
1293 modifier. */
1294 switch (dir.modifier)
1296 case FMT_LEN_none:
1297 if (dir.specifier == 'p')
1298 dirtype = ptr_type_node;
1299 else
1300 dirtype = sign ? integer_type_node : unsigned_type_node;
1301 break;
1303 case FMT_LEN_h:
1304 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1305 break;
1307 case FMT_LEN_hh:
1308 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1309 break;
1311 case FMT_LEN_l:
1312 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1313 break;
1315 case FMT_LEN_L:
1316 case FMT_LEN_ll:
1317 dirtype = (sign
1318 ? long_long_integer_type_node
1319 : long_long_unsigned_type_node);
1320 break;
1322 case FMT_LEN_z:
1323 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1324 break;
1326 case FMT_LEN_t:
1327 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1328 break;
1330 case FMT_LEN_j:
1331 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1332 dirtype = sign ? intmax_type_node : uintmax_type_node;
1333 break;
1335 default:
1336 return fmtresult ();
1339 /* The type of the argument to the directive, either deduced from
1340 the actual non-constant argument if one is known, or from
1341 the directive itself when none has been provided because it's
1342 a va_list. */
1343 tree argtype = NULL_TREE;
1345 if (!arg)
1347 /* When the argument has not been provided, use the type of
1348 the directive's argument as an approximation. This will
1349 result in false positives for directives like %i with
1350 arguments with smaller precision (such as short or char). */
1351 argtype = dirtype;
1353 else if (TREE_CODE (arg) == INTEGER_CST)
1355 /* When a constant argument has been provided use its value
1356 rather than type to determine the length of the output. */
1357 fmtresult res;
1359 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1361 /* As a special case, a precision of zero with a zero argument
1362 results in zero bytes except in base 8 when the '#' flag is
1363 specified, and for signed conversions in base 8 and 10 when
1364 either the space or '+' flag has been specified and it results
1365 in just one byte (with width having the normal effect). This
1366 must extend to the case of a specified precision with
1367 an unknown value because it can be zero. */
1368 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1369 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1371 res.range.max = 1;
1372 res.range.likely = 1;
1374 else
1376 res.range.max = res.range.min;
1377 res.range.likely = res.range.min;
1380 else
1382 /* Convert the argument to the type of the directive. */
1383 arg = fold_convert (dirtype, arg);
1385 res.range.min = tree_digits (arg, base, dir.prec[0],
1386 maybesign, maybebase);
1387 if (dir.prec[0] == dir.prec[1])
1388 res.range.max = res.range.min;
1389 else
1390 res.range.max = tree_digits (arg, base, dir.prec[1],
1391 maybesign, maybebase);
1392 res.range.likely = res.range.min;
1395 res.range.unlikely = res.range.max;
1397 /* Bump up the counters if WIDTH is greater than LEN. */
1398 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1399 (sign | maybebase) + (base == 16));
1400 /* Bump up the counters again if PRECision is greater still. */
1401 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1402 (sign | maybebase) + (base == 16));
1404 return res;
1406 else if (TREE_CODE (TREE_TYPE (arg)) == INTEGER_TYPE
1407 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1408 /* Determine the type of the provided non-constant argument. */
1409 argtype = TREE_TYPE (arg);
1410 else
1411 /* Don't bother with invalid arguments since they likely would
1412 have already been diagnosed, and disable any further checking
1413 of the format string by returning [-1, -1]. */
1414 return fmtresult ();
1416 fmtresult res;
1418 /* Using either the range the non-constant argument is in, or its
1419 type (either "formal" or actual), create a range of values that
1420 constrain the length of output given the warning level. */
1421 tree argmin = NULL_TREE;
1422 tree argmax = NULL_TREE;
1424 if (arg
1425 && TREE_CODE (arg) == SSA_NAME
1426 && TREE_CODE (argtype) == INTEGER_TYPE)
1428 /* Try to determine the range of values of the integer argument
1429 (range information is not available for pointers). */
1430 wide_int min, max;
1431 enum value_range_type range_type = get_range_info (arg, &min, &max);
1432 if (range_type == VR_RANGE)
1434 argmin = wide_int_to_tree (argtype, min);
1435 argmax = wide_int_to_tree (argtype, max);
1437 /* Set KNOWNRANGE if the argument is in a known subrange
1438 of the directive's type and neither width nor precision
1439 is unknown. (KNOWNRANGE may be reset below). */
1440 res.knownrange
1441 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1442 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1443 && dir.known_width_and_precision ());
1445 res.argmin = argmin;
1446 res.argmax = argmax;
1448 else if (range_type == VR_ANTI_RANGE)
1450 /* Handle anti-ranges if/when bug 71690 is resolved. */
1452 else if (range_type == VR_VARYING)
1454 /* The argument here may be the result of promoting the actual
1455 argument to int. Try to determine the type of the actual
1456 argument before promotion and narrow down its range that
1457 way. */
1458 gimple *def = SSA_NAME_DEF_STMT (arg);
1459 if (is_gimple_assign (def))
1461 tree_code code = gimple_assign_rhs_code (def);
1462 if (code == INTEGER_CST)
1464 arg = gimple_assign_rhs1 (def);
1465 return format_integer (dir, arg);
1468 if (code == NOP_EXPR)
1470 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1471 if (TREE_CODE (type) == INTEGER_TYPE
1472 || TREE_CODE (type) == POINTER_TYPE)
1473 argtype = type;
1479 if (!argmin)
1481 if (TREE_CODE (argtype) == POINTER_TYPE)
1483 argmin = build_int_cst (pointer_sized_int_node, 0);
1484 argmax = build_all_ones_cst (pointer_sized_int_node);
1486 else
1488 argmin = TYPE_MIN_VALUE (argtype);
1489 argmax = TYPE_MAX_VALUE (argtype);
1493 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1494 of the directive. If it has been cleared then since ARGMIN and/or
1495 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1496 ARGMAX in the result to include in diagnostics. */
1497 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1499 res.knownrange = false;
1500 res.argmin = argmin;
1501 res.argmax = argmax;
1504 /* Recursively compute the minimum and maximum from the known range. */
1505 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1507 /* For unsigned conversions/directives or signed when
1508 the minimum is positive, use the minimum and maximum to compute
1509 the shortest and longest output, respectively. */
1510 res.range.min = format_integer (dir, argmin).range.min;
1511 res.range.max = format_integer (dir, argmax).range.max;
1513 else if (tree_int_cst_sgn (argmax) < 0)
1515 /* For signed conversions/directives if maximum is negative,
1516 use the minimum as the longest output and maximum as the
1517 shortest output. */
1518 res.range.min = format_integer (dir, argmax).range.min;
1519 res.range.max = format_integer (dir, argmin).range.max;
1521 else
1523 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1524 as the shortest output and for the longest output compute the
1525 length of the output of both minimum and maximum and pick the
1526 longer. */
1527 unsigned HOST_WIDE_INT max1 = format_integer (dir, argmin).range.max;
1528 unsigned HOST_WIDE_INT max2 = format_integer (dir, argmax).range.max;
1529 res.range.min = format_integer (dir, integer_zero_node).range.min;
1530 res.range.max = MAX (max1, max2);
1533 /* If the range is known, use the maximum as the likely length. */
1534 if (res.knownrange)
1535 res.range.likely = res.range.max;
1536 else
1538 /* Otherwise, use the minimum. Except for the case where for %#x or
1539 %#o the minimum is just for a single value in the range (0) and
1540 for all other values it is something longer, like 0x1 or 01.
1541 Use the length for value 1 in that case instead as the likely
1542 length. */
1543 res.range.likely = res.range.min;
1544 if (maybebase
1545 && base != 10
1546 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1548 if (res.range.min == 1)
1549 res.range.likely += base == 8 ? 1 : 2;
1550 else if (res.range.min == 2
1551 && base == 16
1552 && (dir.width[0] == 2 || dir.prec[0] == 2))
1553 ++res.range.likely;
1557 res.range.unlikely = res.range.max;
1558 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1559 (sign | maybebase) + (base == 16));
1560 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1561 (sign | maybebase) + (base == 16));
1563 return res;
1566 /* Return the number of bytes that a format directive consisting of FLAGS,
1567 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1568 would result for argument X under ideal conditions (i.e., if PREC
1569 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1570 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1571 This function works around those problems. */
1573 static unsigned HOST_WIDE_INT
1574 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1575 char spec, char rndspec)
1577 char fmtstr[40];
1579 HOST_WIDE_INT len = strlen (flags);
1581 fmtstr[0] = '%';
1582 memcpy (fmtstr + 1, flags, len);
1583 memcpy (fmtstr + 1 + len, ".*R", 3);
1584 fmtstr[len + 4] = rndspec;
1585 fmtstr[len + 5] = spec;
1586 fmtstr[len + 6] = '\0';
1588 spec = TOUPPER (spec);
1589 if (spec == 'E' || spec == 'F')
1591 /* For %e, specify the precision explicitly since mpfr_sprintf
1592 does its own thing just to be different (see MPFR bug 21088). */
1593 if (prec < 0)
1594 prec = 6;
1596 else
1598 /* Avoid passing negative precisions with larger magnitude to MPFR
1599 to avoid exposing its bugs. (A negative precision is supposed
1600 to be ignored.) */
1601 if (prec < 0)
1602 prec = -1;
1605 HOST_WIDE_INT p = prec;
1607 if (spec == 'G' && !strchr (flags, '#'))
1609 /* For G/g without the pound flag, precision gives the maximum number
1610 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1611 a 128 bit IEEE extended precision, 4932. Using twice as much here
1612 should be more than sufficient for any real format. */
1613 if ((IEEE_MAX_10_EXP * 2) < prec)
1614 prec = IEEE_MAX_10_EXP * 2;
1615 p = prec;
1617 else
1619 /* Cap precision arbitrarily at 1KB and add the difference
1620 (if any) to the MPFR result. */
1621 if (prec > 1024)
1622 p = 1024;
1625 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1627 /* Handle the unlikely (impossible?) error by returning more than
1628 the maximum dictated by the function's return type. */
1629 if (len < 0)
1630 return target_dir_max () + 1;
1632 /* Adjust the return value by the difference. */
1633 if (p < prec)
1634 len += prec - p;
1636 return len;
1639 /* Return the number of bytes to format using the format specifier
1640 SPEC and the precision PREC the largest value in the real floating
1641 TYPE. */
1643 static unsigned HOST_WIDE_INT
1644 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1646 machine_mode mode = TYPE_MODE (type);
1648 /* IBM Extended mode. */
1649 if (MODE_COMPOSITE_P (mode))
1650 mode = DFmode;
1652 /* Get the real type format desription for the target. */
1653 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1654 REAL_VALUE_TYPE rv;
1656 real_maxval (&rv, 0, mode);
1658 /* Convert the GCC real value representation with the precision
1659 of the real type to the mpfr_t format with the GCC default
1660 round-to-nearest mode. */
1661 mpfr_t x;
1662 mpfr_init2 (x, rfmt->p);
1663 mpfr_from_real (x, &rv, GMP_RNDN);
1665 /* Return a value one greater to account for the leading minus sign. */
1666 unsigned HOST_WIDE_INT r
1667 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1668 mpfr_clear (x);
1669 return r;
1672 /* Return a range representing the minimum and maximum number of bytes
1673 that the directive DIR will output for any argument. PREC gives
1674 the adjusted precision range to account for negative precisions
1675 meaning the default 6. This function is used when the directive
1676 argument or its value isn't known. */
1678 static fmtresult
1679 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1681 tree type;
1683 switch (dir.modifier)
1685 case FMT_LEN_l:
1686 case FMT_LEN_none:
1687 type = double_type_node;
1688 break;
1690 case FMT_LEN_L:
1691 type = long_double_type_node;
1692 break;
1694 case FMT_LEN_ll:
1695 type = long_double_type_node;
1696 break;
1698 default:
1699 return fmtresult ();
1702 /* The minimum and maximum number of bytes produced by the directive. */
1703 fmtresult res;
1705 /* The minimum output as determined by flags. It's always at least 1.
1706 When plus or space are set the output is preceded by either a sign
1707 or a space. */
1708 unsigned flagmin = (1 /* for the first digit */
1709 + (dir.get_flag ('+') | dir.get_flag (' ')));
1711 /* When the pound flag is set the decimal point is included in output
1712 regardless of precision. Whether or not a decimal point is included
1713 otherwise depends on the specification and precision. */
1714 bool radix = dir.get_flag ('#');
1716 switch (dir.specifier)
1718 case 'A':
1719 case 'a':
1721 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1722 if (dir.prec[0] <= 0)
1723 minprec = 0;
1724 else if (dir.prec[0] > 0)
1725 minprec = dir.prec[0] + !radix /* decimal point */;
1727 res.range.min = (2 /* 0x */
1728 + flagmin
1729 + radix
1730 + minprec
1731 + 3 /* p+0 */);
1733 res.range.max = format_floating_max (type, 'a', prec[1]);
1734 res.range.likely = res.range.min;
1736 /* The unlikely maximum accounts for the longest multibyte
1737 decimal point character. */
1738 res.range.unlikely = res.range.max;
1739 if (dir.prec[1] > 0)
1740 res.range.unlikely += target_mb_len_max () - 1;
1742 break;
1745 case 'E':
1746 case 'e':
1748 /* Minimum output attributable to precision and, when it's
1749 non-zero, decimal point. */
1750 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1752 /* The minimum output is "[-+]1.234567e+00" regardless
1753 of the value of the actual argument. */
1754 res.range.min = (flagmin
1755 + radix
1756 + minprec
1757 + 2 /* e+ */ + 2);
1759 res.range.max = format_floating_max (type, 'e', prec[1]);
1760 res.range.likely = res.range.min;
1762 /* The unlikely maximum accounts for the longest multibyte
1763 decimal point character. */
1764 if (dir.prec[0] != dir.prec[1]
1765 || dir.prec[0] == -1 || dir.prec[0] > 0)
1766 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1767 else
1768 res.range.unlikely = res.range.max;
1769 break;
1772 case 'F':
1773 case 'f':
1775 /* Minimum output attributable to precision and, when it's non-zero,
1776 decimal point. */
1777 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1779 /* The lower bound when precision isn't specified is 8 bytes
1780 ("1.23456" since precision is taken to be 6). When precision
1781 is zero, the lower bound is 1 byte (e.g., "1"). Otherwise,
1782 when precision is greater than zero, then the lower bound
1783 is 2 plus precision (plus flags). */
1784 res.range.min = flagmin + radix + minprec;
1786 /* Compute the upper bound for -TYPE_MAX. */
1787 res.range.max = format_floating_max (type, 'f', prec[1]);
1789 /* The minimum output with unknown precision is a single byte
1790 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1791 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1792 res.range.likely = 3;
1793 else
1794 res.range.likely = res.range.min;
1796 /* The unlikely maximum accounts for the longest multibyte
1797 decimal point character. */
1798 if (dir.prec[0] != dir.prec[1]
1799 || dir.prec[0] == -1 || dir.prec[0] > 0)
1800 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1801 break;
1804 case 'G':
1805 case 'g':
1807 /* The %g output depends on precision and the exponent of
1808 the argument. Since the value of the argument isn't known
1809 the lower bound on the range of bytes (not counting flags
1810 or width) is 1 plus radix (i.e., either "0" or "0." for
1811 "%g" and "%#g", respectively, with a zero argument). */
1812 res.range.min = flagmin + radix;
1814 char spec = 'g';
1815 HOST_WIDE_INT maxprec = dir.prec[1];
1816 if (radix && maxprec)
1818 /* When the pound flag (radix) is set, trailing zeros aren't
1819 trimmed and so the longest output is the same as for %e,
1820 except with precision minus 1 (as specified in C11). */
1821 spec = 'e';
1822 if (maxprec > 0)
1823 --maxprec;
1824 else if (maxprec < 0)
1825 maxprec = 5;
1827 else
1828 maxprec = prec[1];
1830 res.range.max = format_floating_max (type, spec, maxprec);
1832 /* The likely output is either the maximum computed above
1833 minus 1 (assuming the maximum is positive) when precision
1834 is known (or unspecified), or the same minimum as for %e
1835 (which is computed for a non-negative argument). Unlike
1836 for the other specifiers above the likely output isn't
1837 the minimum because for %g that's 1 which is unlikely. */
1838 if (dir.prec[1] < 0
1839 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1840 res.range.likely = res.range.max - 1;
1841 else
1843 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1844 res.range.likely = (flagmin
1845 + radix
1846 + minprec
1847 + 2 /* e+ */ + 2);
1850 /* The unlikely maximum accounts for the longest multibyte
1851 decimal point character. */
1852 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1853 break;
1856 default:
1857 return fmtresult ();
1860 /* Bump up the byte counters if WIDTH is greater. */
1861 res.adjust_for_width_or_precision (dir.width);
1862 return res;
1865 /* Return a range representing the minimum and maximum number of bytes
1866 that the directive DIR will write on output for the floating argument
1867 ARG. */
1869 static fmtresult
1870 format_floating (const directive &dir, tree arg)
1872 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1874 /* For an indeterminate precision the lower bound must be assumed
1875 to be zero. */
1876 if (TOUPPER (dir.specifier) == 'A')
1878 /* Get the number of fractional decimal digits needed to represent
1879 the argument without a loss of accuracy. */
1880 tree type = arg ? TREE_TYPE (arg) :
1881 (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1882 ? long_double_type_node : double_type_node);
1884 unsigned fmtprec
1885 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1887 /* The precision of the IEEE 754 double format is 53.
1888 The precision of all other GCC binary double formats
1889 is 56 or less. */
1890 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1892 /* For %a, leave the minimum precision unspecified to let
1893 MFPR trim trailing zeros (as it and many other systems
1894 including Glibc happen to do) and set the maximum
1895 precision to reflect what it would be with trailing zeros
1896 present (as Solaris and derived systems do). */
1897 if (dir.prec[1] < 0)
1899 /* Both bounds are negative implies that precision has
1900 not been specified. */
1901 prec[0] = maxprec;
1902 prec[1] = -1;
1904 else if (dir.prec[0] < 0)
1906 /* With a negative lower bound and a non-negative upper
1907 bound set the minimum precision to zero and the maximum
1908 to the greater of the maximum precision (i.e., with
1909 trailing zeros present) and the specified upper bound. */
1910 prec[0] = 0;
1911 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1914 else if (dir.prec[0] < 0)
1916 if (dir.prec[1] < 0)
1918 /* A precision in a strictly negative range is ignored and
1919 the default of 6 is used instead. */
1920 prec[0] = prec[1] = 6;
1922 else
1924 /* For a precision in a partly negative range, the lower bound
1925 must be assumed to be zero and the new upper bound is the
1926 greater of 6 (the default precision used when the specified
1927 precision is negative) and the upper bound of the specified
1928 range. */
1929 prec[0] = 0;
1930 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1934 if (!arg || TREE_CODE (arg) != REAL_CST)
1935 return format_floating (dir, prec);
1937 /* The minimum and maximum number of bytes produced by the directive. */
1938 fmtresult res;
1940 /* Get the real type format desription for the target. */
1941 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1942 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1944 char fmtstr [40];
1945 char *pfmt = fmtstr;
1947 /* Append flags. */
1948 for (const char *pf = "-+ #0"; *pf; ++pf)
1949 if (dir.get_flag (*pf))
1950 *pfmt++ = *pf;
1952 *pfmt = '\0';
1955 /* Set up an array to easily iterate over. */
1956 unsigned HOST_WIDE_INT* const minmax[] = {
1957 &res.range.min, &res.range.max
1960 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1962 /* Convert the GCC real value representation with the precision
1963 of the real type to the mpfr_t format rounding down in the
1964 first iteration that computes the minimm and up in the second
1965 that computes the maximum. This order is arbibtrary because
1966 rounding in either direction can result in longer output. */
1967 mpfr_t mpfrval;
1968 mpfr_init2 (mpfrval, rfmt->p);
1969 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1971 /* Use the MPFR rounding specifier to round down in the first
1972 iteration and then up. In most but not all cases this will
1973 result in the same number of bytes. */
1974 char rndspec = "DU"[i];
1976 /* Format it and store the result in the corresponding member
1977 of the result struct. */
1978 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1979 dir.specifier, rndspec);
1980 mpfr_clear (mpfrval);
1984 /* Make sure the minimum is less than the maximum (MPFR rounding
1985 in the call to mpfr_snprintf can result in the reverse. */
1986 if (res.range.max < res.range.min)
1988 unsigned HOST_WIDE_INT tmp = res.range.min;
1989 res.range.min = res.range.max;
1990 res.range.max = tmp;
1993 /* The range is known unless either width or precision is unknown. */
1994 res.knownrange = dir.known_width_and_precision ();
1996 /* For the same floating point constant, unless width or precision
1997 is unknown, use the longer output as the likely maximum since
1998 with round to nearest either is equally likely. Otheriwse, when
1999 precision is unknown, use the greater of the minimum and 3 as
2000 the likely output (for "0.0" since zero precision is unlikely). */
2001 if (res.knownrange)
2002 res.range.likely = res.range.max;
2003 else if (res.range.min < 3
2004 && dir.prec[0] < 0
2005 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
2006 res.range.likely = 3;
2007 else
2008 res.range.likely = res.range.min;
2010 res.range.unlikely = res.range.max;
2012 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
2014 /* Unless the precision is zero output longer than 2 bytes may
2015 include the decimal point which must be a single character
2016 up to MB_LEN_MAX in length. This is overly conservative
2017 since in some conversions some constants result in no decimal
2018 point (e.g., in %g). */
2019 res.range.unlikely += target_mb_len_max () - 1;
2022 res.adjust_for_width_or_precision (dir.width);
2023 return res;
2026 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
2027 strings referenced by the expression STR, or (-1, -1) when not known.
2028 Used by the format_string function below. */
2030 static fmtresult
2031 get_string_length (tree str)
2033 if (!str)
2034 return fmtresult ();
2036 if (tree slen = c_strlen (str, 1))
2038 /* Simply return the length of the string. */
2039 fmtresult res (tree_to_shwi (slen));
2040 return res;
2043 /* Determine the length of the shortest and longest string referenced
2044 by STR. Strings of unknown lengths are bounded by the sizes of
2045 arrays that subexpressions of STR may refer to. Pointers that
2046 aren't known to point any such arrays result in LENRANGE[1] set
2047 to SIZE_MAX. */
2048 tree lenrange[2];
2049 bool flexarray = get_range_strlen (str, lenrange);
2051 if (lenrange [0] || lenrange [1])
2053 HOST_WIDE_INT min
2054 = (tree_fits_uhwi_p (lenrange[0])
2055 ? tree_to_uhwi (lenrange[0])
2056 : 0);
2058 HOST_WIDE_INT max
2059 = (tree_fits_uhwi_p (lenrange[1])
2060 ? tree_to_uhwi (lenrange[1])
2061 : HOST_WIDE_INT_M1U);
2063 /* get_range_strlen() returns the target value of SIZE_MAX for
2064 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2065 which may be bigger. */
2066 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2067 min = HOST_WIDE_INT_M1U;
2068 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2069 max = HOST_WIDE_INT_M1U;
2071 fmtresult res (min, max);
2073 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2074 by STR are known to be bounded (though not necessarily by their
2075 actual length but perhaps by their maximum possible length). */
2076 if (res.range.max < target_int_max ())
2078 res.knownrange = true;
2079 /* When the the length of the longest string is known and not
2080 excessive use it as the likely length of the string(s). */
2081 res.range.likely = res.range.max;
2083 else
2085 /* When the upper bound is unknown (it can be zero or excessive)
2086 set the likely length to the greater of 1 and the length of
2087 the shortest string and reset the lower bound to zero. */
2088 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2089 res.range.min = 0;
2092 /* If the range of string length has been estimated from the size
2093 of an array at the end of a struct assume that it's longer than
2094 the array bound says it is in case it's used as a poor man's
2095 flexible array member, such as in struct S { char a[4]; }; */
2096 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
2098 return res;
2101 return get_string_length (NULL_TREE);
2104 /* Return the minimum and maximum number of characters formatted
2105 by the '%c' format directives and its wide character form for
2106 the argument ARG. ARG can be null (for functions such as
2107 vsprinf). */
2109 static fmtresult
2110 format_character (const directive &dir, tree arg)
2112 fmtresult res;
2114 res.knownrange = true;
2116 if (dir.modifier == FMT_LEN_l)
2118 /* A wide character can result in as few as zero bytes. */
2119 res.range.min = 0;
2121 HOST_WIDE_INT min, max;
2122 if (get_int_range (arg, &min, &max, false, 0))
2124 if (min == 0 && max == 0)
2126 /* The NUL wide character results in no bytes. */
2127 res.range.max = 0;
2128 res.range.likely = 0;
2129 res.range.unlikely = 0;
2131 else if (min > 0 && min < 128)
2133 /* A wide character in the ASCII range most likely results
2134 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2135 res.range.max = 1;
2136 res.range.likely = 1;
2137 res.range.unlikely = target_mb_len_max ();
2139 else
2141 /* A wide character outside the ASCII range likely results
2142 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2143 res.range.max = target_mb_len_max ();
2144 res.range.likely = 2;
2145 res.range.unlikely = res.range.max;
2148 else
2150 /* An unknown wide character is treated the same as a wide
2151 character outside the ASCII range. */
2152 res.range.max = target_mb_len_max ();
2153 res.range.likely = 2;
2154 res.range.unlikely = res.range.max;
2157 else
2159 /* A plain '%c' directive. Its ouput is exactly 1. */
2160 res.range.min = res.range.max = 1;
2161 res.range.likely = res.range.unlikely = 1;
2162 res.knownrange = true;
2165 /* Bump up the byte counters if WIDTH is greater. */
2166 return res.adjust_for_width_or_precision (dir.width);
2169 /* Return the minimum and maximum number of characters formatted
2170 by the '%s' format directive and its wide character form for
2171 the argument ARG. ARG can be null (for functions such as
2172 vsprinf). */
2174 static fmtresult
2175 format_string (const directive &dir, tree arg)
2177 fmtresult res;
2179 /* Compute the range the argument's length can be in. */
2180 fmtresult slen = get_string_length (arg);
2181 if (slen.range.min == slen.range.max
2182 && slen.range.min < HOST_WIDE_INT_MAX)
2184 /* The argument is either a string constant or it refers
2185 to one of a number of strings of the same length. */
2187 /* A '%s' directive with a string argument with constant length. */
2188 res.range = slen.range;
2190 if (dir.modifier == FMT_LEN_l)
2192 /* In the worst case the length of output of a wide string S
2193 is bounded by MB_LEN_MAX * wcslen (S). */
2194 res.range.max *= target_mb_len_max ();
2195 res.range.unlikely = res.range.max;
2196 /* It's likely that the the total length is not more that
2197 2 * wcslen (S).*/
2198 res.range.likely = res.range.min * 2;
2200 if (dir.prec[1] >= 0
2201 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2203 res.range.max = dir.prec[1];
2204 res.range.likely = dir.prec[1];
2205 res.range.unlikely = dir.prec[1];
2208 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2209 res.range.min = 0;
2210 else if (dir.prec[0] >= 0)
2211 res.range.likely = dir.prec[0];
2213 /* Even a non-empty wide character string need not convert into
2214 any bytes. */
2215 res.range.min = 0;
2217 else
2219 res.knownrange = true;
2221 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2222 res.range.min = 0;
2223 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2224 res.range.min = dir.prec[0];
2226 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2228 res.range.max = dir.prec[1];
2229 res.range.likely = dir.prec[1];
2230 res.range.unlikely = dir.prec[1];
2234 else if (arg && integer_zerop (arg))
2236 /* Handle null pointer argument. */
2238 fmtresult res (0);
2239 res.nullp = true;
2240 return res;
2242 else
2244 /* For a '%s' and '%ls' directive with a non-constant string (either
2245 one of a number of strings of known length or an unknown string)
2246 the minimum number of characters is lesser of PRECISION[0] and
2247 the length of the shortest known string or zero, and the maximum
2248 is the lessser of the length of the longest known string or
2249 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2250 the minimum at level 1 and the greater of the minimum and 1
2251 at level 2. This result is adjust upward for width (if it's
2252 specified). */
2254 if (dir.modifier == FMT_LEN_l)
2256 /* A wide character converts to as few as zero bytes. */
2257 slen.range.min = 0;
2258 if (slen.range.max < target_int_max ())
2259 slen.range.max *= target_mb_len_max ();
2261 if (slen.range.likely < target_int_max ())
2262 slen.range.likely *= 2;
2264 if (slen.range.likely < target_int_max ())
2265 slen.range.unlikely *= target_mb_len_max ();
2268 res.range = slen.range;
2270 if (dir.prec[0] >= 0)
2272 /* Adjust the minimum to zero if the string length is unknown,
2273 or at most the lower bound of the precision otherwise. */
2274 if (slen.range.min >= target_int_max ())
2275 res.range.min = 0;
2276 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2277 res.range.min = dir.prec[0];
2279 /* Make both maxima no greater than the upper bound of precision. */
2280 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2281 || slen.range.max >= target_int_max ())
2283 res.range.max = dir.prec[1];
2284 res.range.unlikely = dir.prec[1];
2287 /* If precision is constant, set the likely counter to the lesser
2288 of it and the maximum string length. Otherwise, if the lower
2289 bound of precision is greater than zero, set the likely counter
2290 to the minimum. Otherwise set it to zero or one based on
2291 the warning level. */
2292 if (dir.prec[0] == dir.prec[1])
2293 res.range.likely
2294 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2295 ? dir.prec[0] : slen.range.max);
2296 else if (dir.prec[0] > 0)
2297 res.range.likely = res.range.min;
2298 else
2299 res.range.likely = warn_level > 1;
2301 else if (dir.prec[1] >= 0)
2303 res.range.min = 0;
2304 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2305 res.range.max = dir.prec[1];
2306 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2308 else if (slen.range.min >= target_int_max ())
2310 res.range.min = 0;
2311 res.range.max = HOST_WIDE_INT_MAX;
2312 /* At level 1 strings of unknown length are assumed to be
2313 empty, while at level 1 they are assumed to be one byte
2314 long. */
2315 res.range.likely = warn_level > 1;
2317 else
2319 /* A string of unknown length unconstrained by precision is
2320 assumed to be empty at level 1 and just one character long
2321 at higher levels. */
2322 if (res.range.likely >= target_int_max ())
2323 res.range.likely = warn_level > 1;
2326 res.range.unlikely = res.range.max;
2329 /* Bump up the byte counters if WIDTH is greater. */
2330 return res.adjust_for_width_or_precision (dir.width);
2333 /* Format plain string (part of the format string itself). */
2335 static fmtresult
2336 format_plain (const directive &dir, tree)
2338 fmtresult res (dir.len);
2339 return res;
2342 /* Return true if the RESULT of a directive in a call describe by INFO
2343 should be diagnosed given the AVAILable space in the destination. */
2345 static bool
2346 should_warn_p (const pass_sprintf_length::call_info &info,
2347 const result_range &avail, const result_range &result)
2349 if (result.max <= avail.min)
2351 /* The least amount of space remaining in the destination is big
2352 enough for the longest output. */
2353 return false;
2356 if (info.bounded)
2358 if (warn_format_trunc == 1 && result.min <= avail.max
2359 && info.retval_used ())
2361 /* The likely amount of space remaining in the destination is big
2362 enough for the least output and the return value is used. */
2363 return false;
2366 if (warn_format_trunc == 1 && result.likely <= avail.likely
2367 && !info.retval_used ())
2369 /* The likely amount of space remaining in the destination is big
2370 enough for the likely output and the return value is unused. */
2371 return false;
2374 if (warn_format_trunc == 2
2375 && result.likely <= avail.min
2376 && (result.max <= avail.min
2377 || result.max > HOST_WIDE_INT_MAX))
2379 /* The minimum amount of space remaining in the destination is big
2380 enough for the longest output. */
2381 return false;
2384 else
2386 if (warn_level == 1 && result.likely <= avail.likely)
2388 /* The likely amount of space remaining in the destination is big
2389 enough for the likely output. */
2390 return false;
2393 if (warn_level == 2
2394 && result.likely <= avail.min
2395 && (result.max <= avail.min
2396 || result.max > HOST_WIDE_INT_MAX))
2398 /* The minimum amount of space remaining in the destination is big
2399 enough for the longest output. */
2400 return false;
2404 return true;
2407 /* At format string location describe by DIRLOC in a call described
2408 by INFO, issue a warning for a directive DIR whose output may be
2409 in excess of the available space AVAIL_RANGE in the destination
2410 given the formatting result FMTRES. This function does nothing
2411 except decide whether to issue a warning for a possible write
2412 past the end or truncation and, if so, format the warning.
2413 Return true if a warning has been issued. */
2415 static bool
2416 maybe_warn (substring_loc &dirloc, source_range *pargrange,
2417 const pass_sprintf_length::call_info &info,
2418 const result_range &avail_range, const result_range &res,
2419 const directive &dir)
2421 if (!should_warn_p (info, avail_range, res))
2422 return false;
2424 /* A warning will definitely be issued below. */
2426 /* The maximum byte count to reference in the warning. Larger counts
2427 imply that the upper bound is unknown (and could be anywhere between
2428 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2429 than "between N and X" where X is some huge number. */
2430 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2432 /* True when there is enough room in the destination for the least
2433 amount of a directive's output but not enough for its likely or
2434 maximum output. */
2435 bool maybe = (res.min <= avail_range.max
2436 && (avail_range.min < res.likely
2437 || (res.max < HOST_WIDE_INT_MAX
2438 && avail_range.min < res.max)));
2440 /* Buffer for the directive in the host character set (used when
2441 the source character set is different). */
2442 char hostdir[32];
2444 if (avail_range.min == avail_range.max)
2446 /* The size of the destination region is exact. */
2447 unsigned HOST_WIDE_INT navail = avail_range.max;
2449 if (target_to_host (*dir.beg) != '%')
2451 /* For plain character directives (i.e., the format string itself)
2452 but not others, point the caret at the first character that's
2453 past the end of the destination. */
2454 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2457 if (*dir.beg == '\0')
2459 /* This is the terminating nul. */
2460 gcc_assert (res.min == 1 && res.min == res.max);
2462 const char *fmtstr
2463 = (info.bounded
2464 ? (maybe
2465 ? G_("%qE output may be truncated before the last format "
2466 "character")
2467 : G_("%qE output truncated before the last format character"))
2468 : (maybe
2469 ? G_("%qE may write a terminating nul past the end "
2470 "of the destination")
2471 : G_("%qE writing a terminating nul past the end "
2472 "of the destination")));
2474 return fmtwarn (dirloc, NULL, NULL, info.warnopt (), fmtstr,
2475 info.func);
2478 if (res.min == res.max)
2480 const char* fmtstr
2481 = (res.min == 1
2482 ? (info.bounded
2483 ? (maybe
2484 ? G_("%<%.*s%> directive output may be truncated writing "
2485 "%wu byte into a region of size %wu")
2486 : G_("%<%.*s%> directive output truncated writing "
2487 "%wu byte into a region of size %wu"))
2488 : G_("%<%.*s%> directive writing %wu byte "
2489 "into a region of size %wu"))
2490 : (info.bounded
2491 ? (maybe
2492 ? G_("%<%.*s%> directive output may be truncated writing "
2493 "%wu bytes into a region of size %wu")
2494 : G_("%<%.*s%> directive output truncated writing "
2495 "%wu bytes into a region of size %wu"))
2496 : G_("%<%.*s%> directive writing %wu bytes "
2497 "into a region of size %wu")));
2498 return fmtwarn (dirloc, pargrange, NULL,
2499 info.warnopt (), fmtstr, dir.len,
2500 target_to_host (hostdir, sizeof hostdir, dir.beg),
2501 res.min, navail);
2504 if (res.min == 0 && res.max < maxbytes)
2506 const char* fmtstr
2507 = (info.bounded
2508 ? (maybe
2509 ? G_("%<%.*s%> directive output may be truncated writing "
2510 "up to %wu bytes into a region of size %wu")
2511 : G_("%<%.*s%> directive output truncated writing "
2512 "up to %wu bytes into a region of size %wu"))
2513 : G_("%<%.*s%> directive writing up to %wu bytes "
2514 "into a region of size %wu"));
2515 return fmtwarn (dirloc, pargrange, NULL,
2516 info.warnopt (), fmtstr, dir.len,
2517 target_to_host (hostdir, sizeof hostdir, dir.beg),
2518 res.max, navail);
2521 if (res.min == 0 && maxbytes <= res.max)
2523 /* This is a special case to avoid issuing the potentially
2524 confusing warning:
2525 writing 0 or more bytes into a region of size 0. */
2526 const char* fmtstr
2527 = (info.bounded
2528 ? (maybe
2529 ? G_("%<%.*s%> directive output may be truncated writing "
2530 "likely %wu or more bytes into a region of size %wu")
2531 : G_("%<%.*s%> directive output truncated writing "
2532 "likely %wu or more bytes into a region of size %wu"))
2533 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2534 "into a region of size %wu"));
2535 return fmtwarn (dirloc, pargrange, NULL,
2536 info.warnopt (), fmtstr, dir.len,
2537 target_to_host (hostdir, sizeof hostdir, dir.beg),
2538 res.likely, navail);
2541 if (res.max < maxbytes)
2543 const char* fmtstr
2544 = (info.bounded
2545 ? (maybe
2546 ? G_("%<%.*s%> directive output may be truncated writing "
2547 "between %wu and %wu bytes into a region of size %wu")
2548 : G_("%<%.*s%> directive output truncated writing "
2549 "between %wu and %wu bytes into a region of size %wu"))
2550 : G_("%<%.*s%> directive writing between %wu and "
2551 "%wu bytes into a region of size %wu"));
2552 return fmtwarn (dirloc, pargrange, NULL,
2553 info.warnopt (), fmtstr, dir.len,
2554 target_to_host (hostdir, sizeof hostdir, dir.beg),
2555 res.min, res.max, navail);
2558 const char* fmtstr
2559 = (info.bounded
2560 ? (maybe
2561 ? G_("%<%.*s%> directive output may be truncated writing "
2562 "%wu or more bytes into a region of size %wu")
2563 : G_("%<%.*s%> directive output truncated writing "
2564 "%wu or more bytes into a region of size %wu"))
2565 : G_("%<%.*s%> directive writing %wu or more bytes "
2566 "into a region of size %wu"));
2567 return fmtwarn (dirloc, pargrange, NULL,
2568 info.warnopt (), fmtstr, dir.len,
2569 target_to_host (hostdir, sizeof hostdir, dir.beg),
2570 res.min, navail);
2573 /* The size of the destination region is a range. */
2575 if (target_to_host (*dir.beg) != '%')
2577 unsigned HOST_WIDE_INT navail = avail_range.max;
2579 /* For plain character directives (i.e., the format string itself)
2580 but not others, point the caret at the first character that's
2581 past the end of the destination. */
2582 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2585 if (*dir.beg == '\0')
2587 gcc_assert (res.min == 1 && res.min == res.max);
2589 const char *fmtstr
2590 = (info.bounded
2591 ? (maybe
2592 ? G_("%qE output may be truncated before the last format "
2593 "character")
2594 : G_("%qE output truncated before the last format character"))
2595 : (maybe
2596 ? G_("%qE may write a terminating nul past the end "
2597 "of the destination")
2598 : G_("%qE writing a terminating nul past the end "
2599 "of the destination")));
2601 return fmtwarn (dirloc, NULL, NULL, info.warnopt (), fmtstr,
2602 info.func);
2605 if (res.min == res.max)
2607 const char* fmtstr
2608 = (res.min == 1
2609 ? (info.bounded
2610 ? (maybe
2611 ? G_("%<%.*s%> directive output may be truncated writing "
2612 "%wu byte into a region of size between %wu and %wu")
2613 : G_("%<%.*s%> directive output truncated writing "
2614 "%wu byte into a region of size between %wu and %wu"))
2615 : G_("%<%.*s%> directive writing %wu byte "
2616 "into a region of size between %wu and %wu"))
2617 : (info.bounded
2618 ? (maybe
2619 ? G_("%<%.*s%> directive output may be truncated writing "
2620 "%wu bytes into a region of size between %wu and %wu")
2621 : G_("%<%.*s%> directive output truncated writing "
2622 "%wu bytes into a region of size between %wu and %wu"))
2623 : G_("%<%.*s%> directive writing %wu bytes "
2624 "into a region of size between %wu and %wu")));
2626 return fmtwarn (dirloc, pargrange, NULL,
2627 info.warnopt (), fmtstr, dir.len,
2628 target_to_host (hostdir, sizeof hostdir, dir.beg),
2629 res.min, avail_range.min, avail_range.max);
2632 if (res.min == 0 && res.max < maxbytes)
2634 const char* fmtstr
2635 = (info.bounded
2636 ? (maybe
2637 ? G_("%<%.*s%> directive output may be truncated writing "
2638 "up to %wu bytes into a region of size between "
2639 "%wu and %wu")
2640 : G_("%<%.*s%> directive output truncated writing "
2641 "up to %wu bytes into a region of size between "
2642 "%wu and %wu"))
2643 : G_("%<%.*s%> directive writing up to %wu bytes "
2644 "into a region of size between %wu and %wu"));
2645 return fmtwarn (dirloc, pargrange, NULL,
2646 info.warnopt (), fmtstr, dir.len,
2647 target_to_host (hostdir, sizeof hostdir, dir.beg),
2648 res.max, avail_range.min, avail_range.max);
2651 if (res.min == 0 && maxbytes <= res.max)
2653 /* This is a special case to avoid issuing the potentially confusing
2654 warning:
2655 writing 0 or more bytes into a region of size between 0 and N. */
2656 const char* fmtstr
2657 = (info.bounded
2658 ? (maybe
2659 ? G_("%<%.*s%> directive output may be truncated writing "
2660 "likely %wu or more bytes into a region of size between "
2661 "%wu and %wu")
2662 : G_("%<%.*s%> directive output truncated writing likely "
2663 "%wu or more bytes into a region of size between "
2664 "%wu and %wu"))
2665 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2666 "into a region of size between %wu and %wu"));
2667 return fmtwarn (dirloc, pargrange, NULL,
2668 info.warnopt (), fmtstr, dir.len,
2669 target_to_host (hostdir, sizeof hostdir, dir.beg),
2670 res.likely, avail_range.min, avail_range.max);
2673 if (res.max < maxbytes)
2675 const char* fmtstr
2676 = (info.bounded
2677 ? (maybe
2678 ? G_("%<%.*s%> directive output may be truncated writing "
2679 "between %wu and %wu bytes into a region of size "
2680 "between %wu and %wu")
2681 : G_("%<%.*s%> directive output truncated writing "
2682 "between %wu and %wu bytes into a region of size "
2683 "between %wu and %wu"))
2684 : G_("%<%.*s%> directive writing between %wu and "
2685 "%wu bytes into a region of size between %wu and %wu"));
2686 return fmtwarn (dirloc, pargrange, NULL,
2687 info.warnopt (), fmtstr, dir.len,
2688 target_to_host (hostdir, sizeof hostdir, dir.beg),
2689 res.min, res.max, avail_range.min, avail_range.max);
2692 const char* fmtstr
2693 = (info.bounded
2694 ? (maybe
2695 ? G_("%<%.*s%> directive output may be truncated writing "
2696 "%wu or more bytes into a region of size between "
2697 "%wu and %wu")
2698 : G_("%<%.*s%> directive output truncated writing "
2699 "%wu or more bytes into a region of size between "
2700 "%wu and %wu"))
2701 : G_("%<%.*s%> directive writing %wu or more bytes "
2702 "into a region of size between %wu and %wu"));
2703 return fmtwarn (dirloc, pargrange, NULL,
2704 info.warnopt (), fmtstr, dir.len,
2705 target_to_host (hostdir, sizeof hostdir, dir.beg),
2706 res.min, avail_range.min, avail_range.max);
2709 /* Compute the length of the output resulting from the directive DIR
2710 in a call described by INFO and update the overall result of the call
2711 in *RES. Return true if the directive has been handled. */
2713 static bool
2714 format_directive (const pass_sprintf_length::call_info &info,
2715 format_result *res, const directive &dir)
2717 /* Offset of the beginning of the directive from the beginning
2718 of the format string. */
2719 size_t offset = dir.beg - info.fmtstr;
2720 size_t start = offset;
2721 size_t length = offset + dir.len - !!dir.len;
2723 /* Create a location for the whole directive from the % to the format
2724 specifier. */
2725 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2726 offset, start, length);
2728 /* Also create a location range for the argument if possible.
2729 This doesn't work for integer literals or function calls. */
2730 source_range argrange;
2731 source_range *pargrange;
2732 if (dir.arg && CAN_HAVE_LOCATION_P (dir.arg))
2734 argrange = EXPR_LOCATION_RANGE (dir.arg);
2735 pargrange = &argrange;
2737 else
2738 pargrange = NULL;
2740 /* Bail when there is no function to compute the output length,
2741 or when minimum length checking has been disabled. */
2742 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2743 return false;
2745 /* Compute the range of lengths of the formatted output. */
2746 fmtresult fmtres = dir.fmtfunc (dir, dir.arg);
2748 /* Record whether the output of all directives is known to be
2749 bounded by some maximum, implying that their arguments are
2750 either known exactly or determined to be in a known range
2751 or, for strings, limited by the upper bounds of the arrays
2752 they refer to. */
2753 res->knownrange &= fmtres.knownrange;
2755 if (!fmtres.knownrange)
2757 /* Only when the range is known, check it against the host value
2758 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2759 INT_MAX precision, which is the longest possible output of any
2760 single directive). That's the largest valid byte count (though
2761 not valid call to a printf-like function because it can never
2762 return such a count). Otherwise, the range doesn't correspond
2763 to known values of the argument. */
2764 if (fmtres.range.max > target_dir_max ())
2766 /* Normalize the MAX counter to avoid having to deal with it
2767 later. The counter can be less than HOST_WIDE_INT_M1U
2768 when compiling for an ILP32 target on an LP64 host. */
2769 fmtres.range.max = HOST_WIDE_INT_M1U;
2770 /* Disable exact and maximum length checking after a failure
2771 to determine the maximum number of characters (for example
2772 for wide characters or wide character strings) but continue
2773 tracking the minimum number of characters. */
2774 res->range.max = HOST_WIDE_INT_M1U;
2777 if (fmtres.range.min > target_dir_max ())
2779 /* Disable exact length checking after a failure to determine
2780 even the minimum number of characters (it shouldn't happen
2781 except in an error) but keep tracking the minimum and maximum
2782 number of characters. */
2783 return true;
2787 /* Buffer for the directive in the host character set (used when
2788 the source character set is different). */
2789 char hostdir[32];
2791 int dirlen = dir.len;
2793 if (fmtres.nullp)
2795 fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
2796 "%<%.*s%> directive argument is null",
2797 dirlen, target_to_host (hostdir, sizeof hostdir, dir.beg));
2799 /* Don't bother processing the rest of the format string. */
2800 res->warned = true;
2801 res->range.min = HOST_WIDE_INT_M1U;
2802 res->range.max = HOST_WIDE_INT_M1U;
2803 return false;
2806 /* Compute the number of available bytes in the destination. There
2807 must always be at least one byte of space for the terminating
2808 NUL that's appended after the format string has been processed. */
2809 result_range avail_range = bytes_remaining (info.objsize, *res);
2811 bool warned = res->warned;
2813 if (!warned)
2814 warned = maybe_warn (dirloc, pargrange, info, avail_range,
2815 fmtres.range, dir);
2817 /* Bump up the total maximum if it isn't too big. */
2818 if (res->range.max < HOST_WIDE_INT_MAX
2819 && fmtres.range.max < HOST_WIDE_INT_MAX)
2820 res->range.max += fmtres.range.max;
2822 /* Raise the total unlikely maximum by the larger of the maximum
2823 and the unlikely maximum. */
2824 unsigned HOST_WIDE_INT save = res->range.unlikely;
2825 if (fmtres.range.max < fmtres.range.unlikely)
2826 res->range.unlikely += fmtres.range.unlikely;
2827 else
2828 res->range.unlikely += fmtres.range.max;
2830 if (res->range.unlikely < save)
2831 res->range.unlikely = HOST_WIDE_INT_M1U;
2833 res->range.min += fmtres.range.min;
2834 res->range.likely += fmtres.range.likely;
2836 /* Has the minimum directive output length exceeded the maximum
2837 of 4095 bytes required to be supported? */
2838 bool minunder4k = fmtres.range.min < 4096;
2839 bool maxunder4k = fmtres.range.max < 4096;
2840 /* Clear UNDER4K in the overall result if the maximum has exceeded
2841 the 4k (this is necessary to avoid the return valuye optimization
2842 that may not be safe in the maximum case). */
2843 if (!maxunder4k)
2844 res->under4k = false;
2846 if (!warned
2847 /* Only warn at level 2. */
2848 && 1 < warn_level
2849 && (!minunder4k
2850 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2852 /* The directive output may be longer than the maximum required
2853 to be handled by an implementation according to 7.21.6.1, p15
2854 of C11. Warn on this only at level 2 but remember this and
2855 prevent folding the return value when done. This allows for
2856 the possibility of the actual libc call failing due to ENOMEM
2857 (like Glibc does under some conditions). */
2859 if (fmtres.range.min == fmtres.range.max)
2860 warned = fmtwarn (dirloc, pargrange, NULL,
2861 info.warnopt (),
2862 "%<%.*s%> directive output of %wu bytes exceeds "
2863 "minimum required size of 4095",
2864 dirlen,
2865 target_to_host (hostdir, sizeof hostdir, dir.beg),
2866 fmtres.range.min);
2867 else
2869 const char *fmtstr
2870 = (minunder4k
2871 ? G_("%<%.*s%> directive output between %wu and %wu "
2872 "bytes may exceed minimum required size of 4095")
2873 : G_("%<%.*s%> directive output between %wu and %wu "
2874 "bytes exceeds minimum required size of 4095"));
2876 warned = fmtwarn (dirloc, pargrange, NULL,
2877 info.warnopt (), fmtstr, dirlen,
2878 target_to_host (hostdir, sizeof hostdir, dir.beg),
2879 fmtres.range.min, fmtres.range.max);
2883 /* Has the likely and maximum directive output exceeded INT_MAX? */
2884 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2885 /* Don't consider the maximum to be in excess when it's the result
2886 of a string of unknown length (i.e., whose maximum has been set
2887 to be greater than or equal to HOST_WIDE_INT_MAX. */
2888 bool maxximax = (*dir.beg
2889 && res->range.max > target_int_max ()
2890 && res->range.max < HOST_WIDE_INT_MAX);
2892 if (!warned
2893 /* Warn for the likely output size at level 1. */
2894 && (likelyximax
2895 /* But only warn for the maximum at level 2. */
2896 || (1 < warn_level
2897 && maxximax
2898 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2900 /* The directive output causes the total length of output
2901 to exceed INT_MAX bytes. */
2903 if (fmtres.range.min == fmtres.range.max)
2904 warned = fmtwarn (dirloc, pargrange, NULL, info.warnopt (),
2905 "%<%.*s%> directive output of %wu bytes causes "
2906 "result to exceed %<INT_MAX%>",
2907 dirlen,
2908 target_to_host (hostdir, sizeof hostdir, dir.beg),
2909 fmtres.range.min);
2910 else
2912 const char *fmtstr
2913 = (fmtres.range.min > target_int_max ()
2914 ? G_ ("%<%.*s%> directive output between %wu and %wu "
2915 "bytes causes result to exceed %<INT_MAX%>")
2916 : G_ ("%<%.*s%> directive output between %wu and %wu "
2917 "bytes may cause result to exceed %<INT_MAX%>"));
2918 warned = fmtwarn (dirloc, pargrange, NULL,
2919 info.warnopt (), fmtstr, dirlen,
2920 target_to_host (hostdir, sizeof hostdir, dir.beg),
2921 fmtres.range.min, fmtres.range.max);
2925 if (warned && fmtres.range.min < fmtres.range.likely
2926 && fmtres.range.likely < fmtres.range.max)
2928 inform (info.fmtloc,
2929 (1 == fmtres.range.likely
2930 ? G_("assuming directive output of %wu byte")
2931 : G_("assuming directive output of %wu bytes")),
2932 fmtres.range.likely);
2935 if (warned && fmtres.argmin)
2937 if (fmtres.argmin == fmtres.argmax)
2938 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2939 else if (fmtres.knownrange)
2940 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2941 fmtres.argmin, fmtres.argmax);
2942 else
2943 inform (info.fmtloc,
2944 "using the range [%E, %E] for directive argument",
2945 fmtres.argmin, fmtres.argmax);
2948 res->warned |= warned;
2950 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2952 /* If a warning has been issued for buffer overflow or truncation
2953 (but not otherwise) help the user figure out how big a buffer
2954 they need. */
2956 location_t callloc = gimple_location (info.callstmt);
2958 unsigned HOST_WIDE_INT min = res->range.min;
2959 unsigned HOST_WIDE_INT max = res->range.max;
2961 if (min == max)
2962 inform (callloc,
2963 (min == 1
2964 ? G_("%qE output %wu byte into a destination of size %wu")
2965 : G_("%qE output %wu bytes into a destination of size %wu")),
2966 info.func, min, info.objsize);
2967 else if (max < HOST_WIDE_INT_MAX)
2968 inform (callloc,
2969 "%qE output between %wu and %wu bytes into "
2970 "a destination of size %wu",
2971 info.func, min, max, info.objsize);
2972 else if (min < res->range.likely && res->range.likely < max)
2973 inform (callloc,
2974 "%qE output %wu or more bytes (assuming %wu) into "
2975 "a destination of size %wu",
2976 info.func, min, res->range.likely, info.objsize);
2977 else
2978 inform (callloc,
2979 "%qE output %wu or more bytes into a destination of size %wu",
2980 info.func, min, info.objsize);
2983 if (dump_file && *dir.beg)
2985 fprintf (dump_file, " Result: %lli, %lli, %lli, %lli "
2986 "(%lli, %lli, %lli, %lli)\n",
2987 (long long)fmtres.range.min,
2988 (long long)fmtres.range.likely,
2989 (long long)fmtres.range.max,
2990 (long long)fmtres.range.unlikely,
2991 (long long)res->range.min,
2992 (long long)res->range.likely,
2993 (long long)res->range.max,
2994 (long long)res->range.unlikely);
2997 return true;
3000 #pragma GCC diagnostic pop
3002 /* Parse a format directive in function call described by INFO starting
3003 at STR and populate DIR structure. Bump up *ARGNO by the number of
3004 arguments extracted for the directive. Return the length of
3005 the directive. */
3007 static size_t
3008 parse_directive (pass_sprintf_length::call_info &info,
3009 directive &dir, format_result *res,
3010 const char *str, unsigned *argno)
3012 const char *pcnt = strchr (str, target_percent);
3013 dir.beg = str;
3015 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
3017 /* This directive is either a plain string or the terminating nul
3018 (which isn't really a directive but it simplifies things to
3019 handle it as if it were). */
3020 dir.len = len;
3021 dir.fmtfunc = format_plain;
3023 if (dump_file)
3025 fprintf (dump_file, " Directive %u at offset %llu: \"%.*s\", "
3026 "length = %llu\n",
3027 dir.dirno,
3028 (unsigned long long)(size_t)(dir.beg - info.fmtstr),
3029 (int)dir.len, dir.beg, (unsigned long long)dir.len);
3032 return len - !*str;
3035 const char *pf = pcnt + 1;
3037 /* POSIX numbered argument index or zero when none. */
3038 HOST_WIDE_INT dollar = 0;
3040 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
3041 when given by a va_list argument, and a non-negative value
3042 when specified in the format string itself. */
3043 HOST_WIDE_INT width = -1;
3044 HOST_WIDE_INT precision = -1;
3046 /* Pointers to the beginning of the width and precision decimal
3047 string (if any) within the directive. */
3048 const char *pwidth = 0;
3049 const char *pprec = 0;
3051 /* When the value of the decimal string that specifies width or
3052 precision is out of range, points to the digit that causes
3053 the value to exceed the limit. */
3054 const char *werange = NULL;
3055 const char *perange = NULL;
3057 /* Width specified via the asterisk. Need not be INTEGER_CST.
3058 For vararg functions set to void_node. */
3059 tree star_width = NULL_TREE;
3061 /* Width specified via the asterisk. Need not be INTEGER_CST.
3062 For vararg functions set to void_node. */
3063 tree star_precision = NULL_TREE;
3065 if (ISDIGIT (target_to_host (*pf)))
3067 /* This could be either a POSIX positional argument, the '0'
3068 flag, or a width, depending on what follows. Store it as
3069 width and sort it out later after the next character has
3070 been seen. */
3071 pwidth = pf;
3072 width = target_strtol10 (&pf, &werange);
3074 else if (target_to_host (*pf) == '*')
3076 /* Similarly to the block above, this could be either a POSIX
3077 positional argument or a width, depending on what follows. */
3078 if (*argno < gimple_call_num_args (info.callstmt))
3079 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3080 else
3081 star_width = void_node;
3082 ++pf;
3085 if (target_to_host (*pf) == '$')
3087 /* Handle the POSIX dollar sign which references the 1-based
3088 positional argument number. */
3089 if (width != -1)
3090 dollar = width + info.argidx;
3091 else if (star_width
3092 && TREE_CODE (star_width) == INTEGER_CST
3093 && (TYPE_PRECISION (TREE_TYPE (star_width))
3094 <= TYPE_PRECISION (integer_type_node)))
3095 dollar = width + tree_to_shwi (star_width);
3097 /* Bail when the numbered argument is out of range (it will
3098 have already been diagnosed by -Wformat). */
3099 if (dollar == 0
3100 || dollar == (int)info.argidx
3101 || dollar > gimple_call_num_args (info.callstmt))
3102 return false;
3104 --dollar;
3106 star_width = NULL_TREE;
3107 width = -1;
3108 ++pf;
3111 if (dollar || !star_width)
3113 if (width != -1)
3115 if (width == 0)
3117 /* The '0' that has been interpreted as a width above is
3118 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3119 and continue processing other flags. */
3120 width = -1;
3121 dir.set_flag ('0');
3123 else if (!dollar)
3125 /* (Non-zero) width has been seen. The next character
3126 is either a period or a digit. */
3127 goto start_precision;
3130 /* When either '$' has been seen, or width has not been seen,
3131 the next field is the optional flags followed by an optional
3132 width. */
3133 for ( ; ; ) {
3134 switch (target_to_host (*pf))
3136 case ' ':
3137 case '0':
3138 case '+':
3139 case '-':
3140 case '#':
3141 dir.set_flag (target_to_host (*pf++));
3142 break;
3144 default:
3145 goto start_width;
3149 start_width:
3150 if (ISDIGIT (target_to_host (*pf)))
3152 werange = 0;
3153 pwidth = pf;
3154 width = target_strtol10 (&pf, &werange);
3156 else if (target_to_host (*pf) == '*')
3158 if (*argno < gimple_call_num_args (info.callstmt))
3159 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3160 else
3162 /* This is (likely) a va_list. It could also be an invalid
3163 call with insufficient arguments. */
3164 star_width = void_node;
3166 ++pf;
3168 else if (target_to_host (*pf) == '\'')
3170 /* The POSIX apostrophe indicating a numeric grouping
3171 in the current locale. Even though it's possible to
3172 estimate the upper bound on the size of the output
3173 based on the number of digits it probably isn't worth
3174 continuing. */
3175 return 0;
3179 start_precision:
3180 if (target_to_host (*pf) == '.')
3182 ++pf;
3184 if (ISDIGIT (target_to_host (*pf)))
3186 pprec = pf;
3187 precision = target_strtol10 (&pf, &perange);
3189 else if (target_to_host (*pf) == '*')
3191 if (*argno < gimple_call_num_args (info.callstmt))
3192 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3193 else
3195 /* This is (likely) a va_list. It could also be an invalid
3196 call with insufficient arguments. */
3197 star_precision = void_node;
3199 ++pf;
3201 else
3203 /* The decimal precision or the asterisk are optional.
3204 When neither is dirified it's taken to be zero. */
3205 precision = 0;
3209 switch (target_to_host (*pf))
3211 case 'h':
3212 if (target_to_host (pf[1]) == 'h')
3214 ++pf;
3215 dir.modifier = FMT_LEN_hh;
3217 else
3218 dir.modifier = FMT_LEN_h;
3219 ++pf;
3220 break;
3222 case 'j':
3223 dir.modifier = FMT_LEN_j;
3224 ++pf;
3225 break;
3227 case 'L':
3228 dir.modifier = FMT_LEN_L;
3229 ++pf;
3230 break;
3232 case 'l':
3233 if (target_to_host (pf[1]) == 'l')
3235 ++pf;
3236 dir.modifier = FMT_LEN_ll;
3238 else
3239 dir.modifier = FMT_LEN_l;
3240 ++pf;
3241 break;
3243 case 't':
3244 dir.modifier = FMT_LEN_t;
3245 ++pf;
3246 break;
3248 case 'z':
3249 dir.modifier = FMT_LEN_z;
3250 ++pf;
3251 break;
3254 switch (target_to_host (*pf))
3256 /* Handle a sole '%' character the same as "%%" but since it's
3257 undefined prevent the result from being folded. */
3258 case '\0':
3259 --pf;
3260 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3261 /* FALLTHRU */
3262 case '%':
3263 dir.fmtfunc = format_percent;
3264 break;
3266 case 'a':
3267 case 'A':
3268 case 'e':
3269 case 'E':
3270 case 'f':
3271 case 'F':
3272 case 'g':
3273 case 'G':
3274 res->floating = true;
3275 dir.fmtfunc = format_floating;
3276 break;
3278 case 'd':
3279 case 'i':
3280 case 'o':
3281 case 'u':
3282 case 'x':
3283 case 'X':
3284 dir.fmtfunc = format_integer;
3285 break;
3287 case 'p':
3288 /* The %p output is implementation-defined. It's possible
3289 to determine this format but due to extensions (edirially
3290 those of the Linux kernel -- see bug 78512) the first %p
3291 in the format string disables any further processing. */
3292 return false;
3294 case 'n':
3295 /* %n has side-effects even when nothing is actually printed to
3296 any buffer. */
3297 info.nowrite = false;
3298 dir.fmtfunc = format_none;
3299 break;
3301 case 'c':
3302 dir.fmtfunc = format_character;
3303 break;
3305 case 'S':
3306 case 's':
3307 dir.fmtfunc = format_string;
3308 break;
3310 default:
3311 /* Unknown conversion specification. */
3312 return 0;
3315 dir.specifier = target_to_host (*pf++);
3317 /* Store the length of the format directive. */
3318 dir.len = pf - pcnt;
3320 /* Buffer for the directive in the host character set (used when
3321 the source character set is different). */
3322 char hostdir[32];
3324 if (star_width)
3326 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3327 dir.set_width (star_width);
3328 else
3330 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3331 (width is the absolute value of that specified). */
3332 dir.width[0] = 0;
3333 dir.width[1] = target_int_max () + 1;
3336 else
3338 if (width == LONG_MAX && werange)
3340 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3341 size_t caret = begin + (werange - pcnt);
3342 size_t end = pf - info.fmtstr - 1;
3344 /* Create a location for the width part of the directive,
3345 pointing the caret at the first out-of-range digit. */
3346 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3347 caret, begin, end);
3349 fmtwarn (dirloc, NULL, NULL,
3350 info.warnopt (), "%<%.*s%> directive width out of range",
3351 dir.len, target_to_host (hostdir, sizeof hostdir, dir.beg));
3354 dir.set_width (width);
3357 if (star_precision)
3359 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3360 dir.set_precision (star_precision);
3361 else
3363 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3364 (unlike width, negative precision is ignored). */
3365 dir.prec[0] = -1;
3366 dir.prec[1] = target_int_max ();
3369 else
3371 if (precision == LONG_MAX && perange)
3373 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3374 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3375 size_t end = pf - info.fmtstr - 2;
3377 /* Create a location for the precision part of the directive,
3378 including the leading period, pointing the caret at the first
3379 out-of-range digit . */
3380 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3381 caret, begin, end);
3383 fmtwarn (dirloc, NULL, NULL,
3384 info.warnopt (), "%<%.*s%> directive precision out of range",
3385 dir.len, target_to_host (hostdir, sizeof hostdir, dir.beg));
3388 dir.set_precision (precision);
3391 /* Extract the argument if the directive takes one and if it's
3392 available (e.g., the function doesn't take a va_list). Treat
3393 missing arguments the same as va_list, even though they will
3394 have likely already been diagnosed by -Wformat. */
3395 if (dir.specifier != '%'
3396 && *argno < gimple_call_num_args (info.callstmt))
3397 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3399 if (dump_file)
3401 fprintf (dump_file, " Directive %u at offset %llu: \"%.*s\"",
3402 dir.dirno, (unsigned long long)(size_t)(dir.beg - info.fmtstr),
3403 (int)dir.len, dir.beg);
3404 if (star_width)
3406 if (dir.width[0] == dir.width[1])
3407 fprintf (dump_file, ", width = %lli", (long long)dir.width[0]);
3408 else
3409 fprintf (dump_file, ", width in range [%lli, %lli]",
3410 (long long)dir.width[0], (long long)dir.width[1]);
3413 if (star_precision)
3415 if (dir.prec[0] == dir.prec[1])
3416 fprintf (dump_file, ", precision = %lli", (long long)dir.prec[0]);
3417 else
3418 fprintf (dump_file, ", precision in range [%lli, %lli]",
3419 (long long)dir.prec[0], (long long)dir.prec[1]);
3421 fputc ('\n', dump_file);
3424 return dir.len;
3427 /* Compute the length of the output resulting from the call to a formatted
3428 output function described by INFO and store the result of the call in
3429 *RES. Issue warnings for detected past the end writes. Return true
3430 if the complete format string has been processed and *RES can be relied
3431 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3432 that caused the processing to be terminated early). */
3434 bool
3435 pass_sprintf_length::compute_format_length (call_info &info,
3436 format_result *res)
3438 if (dump_file)
3440 location_t callloc = gimple_location (info.callstmt);
3441 fprintf (dump_file, "%s:%i: ",
3442 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3443 print_generic_expr (dump_file, info.func, dump_flags);
3445 fprintf (dump_file, ": objsize = %llu, fmtstr = \"%s\"\n",
3446 (unsigned long long)info.objsize, info.fmtstr);
3449 /* Reset the minimum and maximum byte counters. */
3450 res->range.min = res->range.max = 0;
3452 /* No directive has been seen yet so the length of output is bounded
3453 by the known range [0, 0] (with no conversion producing more than
3454 4K bytes) until determined otherwise. */
3455 res->knownrange = true;
3456 res->under4k = true;
3457 res->floating = false;
3458 res->warned = false;
3460 /* 1-based directive counter. */
3461 unsigned dirno = 1;
3463 /* The variadic argument counter. */
3464 unsigned argno = info.argidx;
3466 for (const char *pf = info.fmtstr; ; ++dirno)
3468 directive dir = directive ();
3469 dir.dirno = dirno;
3471 size_t n = parse_directive (info, dir, res, pf, &argno);
3473 /* Return failure if the format function fails. */
3474 if (!format_directive (info, res, dir))
3475 return false;
3477 /* Return success the directive is zero bytes long and it's
3478 the last think in the format string (i.e., it's the terminating
3479 nul, which isn't really a directive but handling it as one makes
3480 things simpler). */
3481 if (!n)
3482 return *pf == '\0';
3484 pf += n;
3487 /* The complete format string was processed (with or without warnings). */
3488 return true;
3491 /* Return the size of the object referenced by the expression DEST if
3492 available, or -1 otherwise. */
3494 static unsigned HOST_WIDE_INT
3495 get_destination_size (tree dest)
3497 /* Initialize object size info before trying to compute it. */
3498 init_object_sizes ();
3500 /* Use __builtin_object_size to determine the size of the destination
3501 object. When optimizing, determine the smallest object (such as
3502 a member array as opposed to the whole enclosing object), otherwise
3503 use type-zero object size to determine the size of the enclosing
3504 object (the function fails without optimization in this type). */
3505 int ost = optimize > 0;
3506 unsigned HOST_WIDE_INT size;
3507 if (compute_builtin_object_size (dest, ost, &size))
3508 return size;
3510 return HOST_WIDE_INT_M1U;
3513 /* Given a suitable result RES of a call to a formatted output function
3514 described by INFO, substitute the result for the return value of
3515 the call. The result is suitable if the number of bytes it represents
3516 is known and exact. A result that isn't suitable for substitution may
3517 have its range set to the range of return values, if that is known.
3518 Return true if the call is removed and gsi_next should not be performed
3519 in the caller. */
3521 static bool
3522 try_substitute_return_value (gimple_stmt_iterator *gsi,
3523 const pass_sprintf_length::call_info &info,
3524 const format_result &res)
3526 tree lhs = gimple_get_lhs (info.callstmt);
3528 /* Set to true when the entire call has been removed. */
3529 bool removed = false;
3531 /* The minimum return value. */
3532 unsigned HOST_WIDE_INT minretval = res.range.min;
3534 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3535 but in cases involving multibyte characters could be as large as
3536 RES.RANGE.UNLIKELY. */
3537 unsigned HOST_WIDE_INT maxretval
3538 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3540 /* Adjust the number of bytes which includes the terminating nul
3541 to reflect the return value of the function which does not.
3542 Because the valid range of the function is [INT_MIN, INT_MAX],
3543 a valid range before the adjustment below is [0, INT_MAX + 1]
3544 (the functions only return negative values on error or undefined
3545 behavior). */
3546 if (minretval <= target_int_max () + 1)
3547 --minretval;
3548 if (maxretval <= target_int_max () + 1)
3549 --maxretval;
3551 /* Avoid the return value optimization when the behavior of the call
3552 is undefined either because any directive may have produced 4K or
3553 more of output, or the return value exceeds INT_MAX, or because
3554 the output overflows the destination object (but leave it enabled
3555 when the function is bounded because then the behavior is well-
3556 defined). */
3557 if (res.under4k
3558 && minretval == maxretval
3559 && (info.bounded || minretval < info.objsize)
3560 && minretval <= target_int_max ()
3561 /* Not prepared to handle possibly throwing calls here; they shouldn't
3562 appear in non-artificial testcases, except when the __*_chk routines
3563 are badly declared. */
3564 && !stmt_ends_bb_p (info.callstmt))
3566 tree cst = build_int_cst (integer_type_node, minretval);
3568 if (lhs == NULL_TREE
3569 && info.nowrite)
3571 /* Remove the call to the bounded function with a zero size
3572 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3573 unlink_stmt_vdef (info.callstmt);
3574 gsi_remove (gsi, true);
3575 removed = true;
3577 else if (info.nowrite)
3579 /* Replace the call to the bounded function with a zero size
3580 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3581 of the function. */
3582 if (!update_call_from_tree (gsi, cst))
3583 gimplify_and_update_call_from_tree (gsi, cst);
3584 gimple *callstmt = gsi_stmt (*gsi);
3585 update_stmt (callstmt);
3587 else if (lhs)
3589 /* Replace the left-hand side of the call with the constant
3590 result of the formatted function. */
3591 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3592 gimple *g = gimple_build_assign (lhs, cst);
3593 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3594 update_stmt (info.callstmt);
3597 if (dump_file)
3599 if (removed)
3600 fprintf (dump_file, " Removing call statement.");
3601 else
3603 fprintf (dump_file, " Substituting ");
3604 print_generic_expr (dump_file, cst, dump_flags);
3605 fprintf (dump_file, " for %s.\n",
3606 info.nowrite ? "statement" : "return value");
3610 else if (lhs)
3612 bool setrange = false;
3614 if ((info.bounded || maxretval < info.objsize)
3615 && res.under4k
3616 && (minretval < target_int_max ()
3617 && maxretval < target_int_max ()))
3619 /* If the result is in a valid range bounded by the size of
3620 the destination set it so that it can be used for subsequent
3621 optimizations. */
3622 int prec = TYPE_PRECISION (integer_type_node);
3624 wide_int min = wi::shwi (minretval, prec);
3625 wide_int max = wi::shwi (maxretval, prec);
3626 set_range_info (lhs, VR_RANGE, min, max);
3628 setrange = true;
3631 if (dump_file)
3633 const char *inbounds
3634 = (minretval < info.objsize
3635 ? (maxretval < info.objsize
3636 ? "in" : "potentially out-of")
3637 : "out-of");
3639 const char *what = setrange ? "Setting" : "Discarding";
3640 if (minretval != maxretval)
3641 fprintf (dump_file,
3642 " %s %s-bounds return value range [%llu, %llu].\n",
3643 what, inbounds,
3644 (unsigned long long)minretval,
3645 (unsigned long long)maxretval);
3646 else
3647 fprintf (dump_file, " %s %s-bounds return value %llu.\n",
3648 what, inbounds, (unsigned long long)minretval);
3652 if (dump_file)
3653 fputc ('\n', dump_file);
3655 return removed;
3658 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3659 functions and if so, handle it. Return true if the call is removed
3660 and gsi_next should not be performed in the caller. */
3662 bool
3663 pass_sprintf_length::handle_gimple_call (gimple_stmt_iterator *gsi)
3665 call_info info = call_info ();
3667 info.callstmt = gsi_stmt (*gsi);
3668 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3669 return false;
3671 info.func = gimple_call_fndecl (info.callstmt);
3672 info.fncode = DECL_FUNCTION_CODE (info.func);
3674 /* The size of the destination as in snprintf(dest, size, ...). */
3675 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3677 /* The size of the destination determined by __builtin_object_size. */
3678 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3680 /* Buffer size argument number (snprintf and vsnprintf). */
3681 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3683 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3684 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3686 /* Format string argument number (valid for all functions). */
3687 unsigned idx_format;
3689 switch (info.fncode)
3691 case BUILT_IN_SPRINTF:
3692 // Signature:
3693 // __builtin_sprintf (dst, format, ...)
3694 idx_format = 1;
3695 info.argidx = 2;
3696 break;
3698 case BUILT_IN_SPRINTF_CHK:
3699 // Signature:
3700 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3701 idx_objsize = 2;
3702 idx_format = 3;
3703 info.argidx = 4;
3704 break;
3706 case BUILT_IN_SNPRINTF:
3707 // Signature:
3708 // __builtin_snprintf (dst, size, format, ...)
3709 idx_dstsize = 1;
3710 idx_format = 2;
3711 info.argidx = 3;
3712 info.bounded = true;
3713 break;
3715 case BUILT_IN_SNPRINTF_CHK:
3716 // Signature:
3717 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3718 idx_dstsize = 1;
3719 idx_objsize = 3;
3720 idx_format = 4;
3721 info.argidx = 5;
3722 info.bounded = true;
3723 break;
3725 case BUILT_IN_VSNPRINTF:
3726 // Signature:
3727 // __builtin_vsprintf (dst, size, format, va)
3728 idx_dstsize = 1;
3729 idx_format = 2;
3730 info.argidx = -1;
3731 info.bounded = true;
3732 break;
3734 case BUILT_IN_VSNPRINTF_CHK:
3735 // Signature:
3736 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3737 idx_dstsize = 1;
3738 idx_objsize = 3;
3739 idx_format = 4;
3740 info.argidx = -1;
3741 info.bounded = true;
3742 break;
3744 case BUILT_IN_VSPRINTF:
3745 // Signature:
3746 // __builtin_vsprintf (dst, format, va)
3747 idx_format = 1;
3748 info.argidx = -1;
3749 break;
3751 case BUILT_IN_VSPRINTF_CHK:
3752 // Signature:
3753 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3754 idx_format = 3;
3755 idx_objsize = 2;
3756 info.argidx = -1;
3757 break;
3759 default:
3760 return false;
3763 /* Set the global warning level for this function. */
3764 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3766 /* The first argument is a pointer to the destination. */
3767 tree dstptr = gimple_call_arg (info.callstmt, 0);
3769 info.format = gimple_call_arg (info.callstmt, idx_format);
3771 /* True when the destination size is constant as opposed to the lower
3772 or upper bound of a range. */
3773 bool dstsize_cst_p = true;
3775 if (idx_dstsize == HOST_WIDE_INT_M1U)
3777 /* For non-bounded functions like sprintf, determine the size
3778 of the destination from the object or pointer passed to it
3779 as the first argument. */
3780 dstsize = get_destination_size (dstptr);
3782 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3784 /* For bounded functions try to get the size argument. */
3786 if (TREE_CODE (size) == INTEGER_CST)
3788 dstsize = tree_to_uhwi (size);
3789 /* No object can be larger than SIZE_MAX bytes (half the address
3790 space) on the target.
3791 The functions are defined only for output of at most INT_MAX
3792 bytes. Specifying a bound in excess of that limit effectively
3793 defeats the bounds checking (and on some implementations such
3794 as Solaris cause the function to fail with EINVAL). */
3795 if (dstsize > target_size_max () / 2)
3797 /* Avoid warning if -Wstringop-overflow is specified since
3798 it also warns for the same thing though only for the
3799 checking built-ins. */
3800 if ((idx_objsize == HOST_WIDE_INT_M1U
3801 || !warn_stringop_overflow))
3802 warning_at (gimple_location (info.callstmt), info.warnopt (),
3803 "specified bound %wu exceeds maximum object size "
3804 "%wu",
3805 dstsize, target_size_max () / 2);
3807 else if (dstsize > target_int_max ())
3808 warning_at (gimple_location (info.callstmt), info.warnopt (),
3809 "specified bound %wu exceeds %<INT_MAX %>",
3810 dstsize);
3812 else if (TREE_CODE (size) == SSA_NAME)
3814 /* Try to determine the range of values of the argument
3815 and use the greater of the two at level 1 and the smaller
3816 of them at level 2. */
3817 wide_int min, max;
3818 enum value_range_type range_type
3819 = get_range_info (size, &min, &max);
3820 if (range_type == VR_RANGE)
3822 dstsize
3823 = (warn_level < 2
3824 ? wi::fits_uhwi_p (max) ? max.to_uhwi () : max.to_shwi ()
3825 : wi::fits_uhwi_p (min) ? min.to_uhwi () : min.to_shwi ());
3828 /* The destination size is not constant. If the function is
3829 bounded (e.g., snprintf) a lower bound of zero doesn't
3830 necessarily imply it can be eliminated. */
3831 dstsize_cst_p = false;
3835 if (idx_objsize != HOST_WIDE_INT_M1U)
3836 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3837 if (tree_fits_uhwi_p (size))
3838 objsize = tree_to_uhwi (size);
3840 if (info.bounded && !dstsize)
3842 /* As a special case, when the explicitly specified destination
3843 size argument (to a bounded function like snprintf) is zero
3844 it is a request to determine the number of bytes on output
3845 without actually producing any. Pretend the size is
3846 unlimited in this case. */
3847 info.objsize = HOST_WIDE_INT_MAX;
3848 info.nowrite = dstsize_cst_p;
3850 else
3852 /* For calls to non-bounded functions or to those of bounded
3853 functions with a non-zero size, warn if the destination
3854 pointer is null. */
3855 if (integer_zerop (dstptr))
3857 /* This is diagnosed with -Wformat only when the null is a constant
3858 pointer. The warning here diagnoses instances where the pointer
3859 is not constant. */
3860 location_t loc = gimple_location (info.callstmt);
3861 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3862 info.warnopt (), "null destination pointer");
3863 return false;
3866 /* Set the object size to the smaller of the two arguments
3867 of both have been specified and they're not equal. */
3868 info.objsize = dstsize < objsize ? dstsize : objsize;
3870 if (info.bounded
3871 && dstsize < target_size_max () / 2 && objsize < dstsize
3872 /* Avoid warning if -Wstringop-overflow is specified since
3873 it also warns for the same thing though only for the
3874 checking built-ins. */
3875 && (idx_objsize == HOST_WIDE_INT_M1U
3876 || !warn_stringop_overflow))
3878 warning_at (gimple_location (info.callstmt), info.warnopt (),
3879 "specified bound %wu exceeds the size %wu "
3880 "of the destination object", dstsize, objsize);
3884 if (integer_zerop (info.format))
3886 /* This is diagnosed with -Wformat only when the null is a constant
3887 pointer. The warning here diagnoses instances where the pointer
3888 is not constant. */
3889 location_t loc = gimple_location (info.callstmt);
3890 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3891 info.warnopt (), "null format string");
3892 return false;
3895 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3896 if (!info.fmtstr)
3897 return false;
3899 /* The result is the number of bytes output by the formatted function,
3900 including the terminating NUL. */
3901 format_result res = format_result ();
3903 bool success = compute_format_length (info, &res);
3905 /* When optimizing and the printf return value optimization is enabled,
3906 attempt to substitute the computed result for the return value of
3907 the call. Avoid this optimization when -frounding-math is in effect
3908 and the format string contains a floating point directive. */
3909 if (success
3910 && optimize > 0
3911 && flag_printf_return_value
3912 && (!flag_rounding_math || !res.floating))
3913 return try_substitute_return_value (gsi, info, res);
3915 return false;
3918 /* Execute the pass for function FUN. */
3920 unsigned int
3921 pass_sprintf_length::execute (function *fun)
3923 init_target_to_host_charmap ();
3925 basic_block bb;
3926 FOR_EACH_BB_FN (bb, fun)
3928 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
3930 /* Iterate over statements, looking for function calls. */
3931 gimple *stmt = gsi_stmt (si);
3933 if (is_gimple_call (stmt) && handle_gimple_call (&si))
3934 /* If handle_gimple_call returns true, the iterator is
3935 already pointing to the next statement. */
3936 continue;
3938 gsi_next (&si);
3942 /* Clean up object size info. */
3943 fini_object_sizes ();
3945 return 0;
3948 } /* Unnamed namespace. */
3950 /* Return a pointer to a pass object newly constructed from the context
3951 CTXT. */
3953 gimple_opt_pass *
3954 make_pass_sprintf_length (gcc::context *ctxt)
3956 return new pass_sprintf_length (ctxt);