builtins.h (c_srlen): Add argument.
[gcc.git] / gcc / gimple-ssa-sprintf.c
1 /* Copyright (C) 2016-2018 Free Software Foundation, Inc.
2 Contributed by Martin Sebor <msebor@redhat.com>.
3
4 This file is part of GCC.
5
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.
10
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.
15
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/>. */
19
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.
28
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.
37
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. */
47
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"
70
71 #include "builtins.h"
72 #include "stor-layout.h"
73
74 #include "realmpfr.h"
75 #include "target.h"
76
77 #include "cpplib.h"
78 #include "input.h"
79 #include "toplev.h"
80 #include "substring-locations.h"
81 #include "diagnostic.h"
82 #include "domwalk.h"
83 #include "alloc-pool.h"
84 #include "vr-values.h"
85 #include "gimple-ssa-evrp-analyze.h"
86
87 /* The likely worst case value of MB_LEN_MAX for the target, large enough
88 for UTF-8. Ideally, this would be obtained by a target hook if it were
89 to be used for optimization but it's good enough as is for warnings. */
90 #define target_mb_len_max() 6
91
92 /* The maximum number of bytes a single non-string directive can result
93 in. This is the result of printf("%.*Lf", INT_MAX, -LDBL_MAX) for
94 LDBL_MAX_10_EXP of 4932. */
95 #define IEEE_MAX_10_EXP 4932
96 #define target_dir_max() (target_int_max () + IEEE_MAX_10_EXP + 2)
97
98 namespace {
99
100 const pass_data pass_data_sprintf_length = {
101 GIMPLE_PASS, // pass type
102 "printf-return-value", // pass name
103 OPTGROUP_NONE, // optinfo_flags
104 TV_NONE, // tv_id
105 PROP_cfg, // properties_required
106 0, // properties_provided
107 0, // properties_destroyed
108 0, // properties_start
109 0, // properties_finish
110 };
111
112 /* Set to the warning level for the current function which is equal
113 either to warn_format_trunc for bounded functions or to
114 warn_format_overflow otherwise. */
115
116 static int warn_level;
117
118 struct format_result;
119
120 class sprintf_dom_walker : public dom_walker
121 {
122 public:
123 sprintf_dom_walker () : dom_walker (CDI_DOMINATORS) {}
124 ~sprintf_dom_walker () {}
125
126 edge before_dom_children (basic_block) FINAL OVERRIDE;
127 void after_dom_children (basic_block) FINAL OVERRIDE;
128 bool handle_gimple_call (gimple_stmt_iterator *);
129
130 struct call_info;
131 bool compute_format_length (call_info &, format_result *);
132 class evrp_range_analyzer evrp_range_analyzer;
133 };
134
135 class pass_sprintf_length : public gimple_opt_pass
136 {
137 bool fold_return_value;
138
139 public:
140 pass_sprintf_length (gcc::context *ctxt)
141 : gimple_opt_pass (pass_data_sprintf_length, ctxt),
142 fold_return_value (false)
143 { }
144
145 opt_pass * clone () { return new pass_sprintf_length (m_ctxt); }
146
147 virtual bool gate (function *);
148
149 virtual unsigned int execute (function *);
150
151 void set_pass_param (unsigned int n, bool param)
152 {
153 gcc_assert (n == 0);
154 fold_return_value = param;
155 }
156
157 };
158
159 bool
160 pass_sprintf_length::gate (function *)
161 {
162 /* Run the pass iff -Warn-format-overflow or -Warn-format-truncation
163 is specified and either not optimizing and the pass is being invoked
164 early, or when optimizing and the pass is being invoked during
165 optimization (i.e., "late"). */
166 return ((warn_format_overflow > 0
167 || warn_format_trunc > 0
168 || flag_printf_return_value)
169 && (optimize > 0) == fold_return_value);
170 }
171
172 /* The minimum, maximum, likely, and unlikely maximum number of bytes
173 of output either a formatting function or an individual directive
174 can result in. */
175
176 struct result_range
177 {
178 /* The absolute minimum number of bytes. The result of a successful
179 conversion is guaranteed to be no less than this. (An erroneous
180 conversion can be indicated by MIN > HOST_WIDE_INT_MAX.) */
181 unsigned HOST_WIDE_INT min;
182 /* The likely maximum result that is used in diagnostics. In most
183 cases MAX is the same as the worst case UNLIKELY result. */
184 unsigned HOST_WIDE_INT max;
185 /* The likely result used to trigger diagnostics. For conversions
186 that result in a range of bytes [MIN, MAX], LIKELY is somewhere
187 in that range. */
188 unsigned HOST_WIDE_INT likely;
189 /* In rare cases (e.g., for nultibyte characters) UNLIKELY gives
190 the worst cases maximum result of a directive. In most cases
191 UNLIKELY == MAX. UNLIKELY is used to control the return value
192 optimization but not in diagnostics. */
193 unsigned HOST_WIDE_INT unlikely;
194 };
195
196 /* The result of a call to a formatted function. */
197
198 struct format_result
199 {
200 /* Range of characters written by the formatted function.
201 Setting the minimum to HOST_WIDE_INT_MAX disables all
202 length tracking for the remainder of the format string. */
203 result_range range;
204
205 /* True when the range above is obtained from known values of
206 directive arguments, or bounds on the amount of output such
207 as width and precision, and not the result of heuristics that
208 depend on warning levels. It's used to issue stricter diagnostics
209 in cases where strings of unknown lengths are bounded by the arrays
210 they are determined to refer to. KNOWNRANGE must not be used for
211 the return value optimization. */
212 bool knownrange;
213
214 /* True if no individual directive could fail or result in more than
215 4095 bytes of output (the total NUMBER_CHARS_{MIN,MAX} might be
216 greater). Implementations are not required to handle directives
217 that produce more than 4K bytes (leading to undefined behavior)
218 and so when one is found it disables the return value optimization.
219 Similarly, directives that can fail (such as wide character
220 directives) disable the optimization. */
221 bool posunder4k;
222
223 /* True when a floating point directive has been seen in the format
224 string. */
225 bool floating;
226
227 /* True when an intermediate result has caused a warning. Used to
228 avoid issuing duplicate warnings while finishing the processing
229 of a call. WARNED also disables the return value optimization. */
230 bool warned;
231
232 /* Preincrement the number of output characters by 1. */
233 format_result& operator++ ()
234 {
235 return *this += 1;
236 }
237
238 /* Postincrement the number of output characters by 1. */
239 format_result operator++ (int)
240 {
241 format_result prev (*this);
242 *this += 1;
243 return prev;
244 }
245
246 /* Increment the number of output characters by N. */
247 format_result& operator+= (unsigned HOST_WIDE_INT);
248 };
249
250 format_result&
251 format_result::operator+= (unsigned HOST_WIDE_INT n)
252 {
253 gcc_assert (n < HOST_WIDE_INT_MAX);
254
255 if (range.min < HOST_WIDE_INT_MAX)
256 range.min += n;
257
258 if (range.max < HOST_WIDE_INT_MAX)
259 range.max += n;
260
261 if (range.likely < HOST_WIDE_INT_MAX)
262 range.likely += n;
263
264 if (range.unlikely < HOST_WIDE_INT_MAX)
265 range.unlikely += n;
266
267 return *this;
268 }
269
270 /* Return the value of INT_MIN for the target. */
271
272 static inline HOST_WIDE_INT
273 target_int_min ()
274 {
275 return tree_to_shwi (TYPE_MIN_VALUE (integer_type_node));
276 }
277
278 /* Return the value of INT_MAX for the target. */
279
280 static inline unsigned HOST_WIDE_INT
281 target_int_max ()
282 {
283 return tree_to_uhwi (TYPE_MAX_VALUE (integer_type_node));
284 }
285
286 /* Return the value of SIZE_MAX for the target. */
287
288 static inline unsigned HOST_WIDE_INT
289 target_size_max ()
290 {
291 return tree_to_uhwi (TYPE_MAX_VALUE (size_type_node));
292 }
293
294 /* A straightforward mapping from the execution character set to the host
295 character set indexed by execution character. */
296
297 static char target_to_host_charmap[256];
298
299 /* Initialize a mapping from the execution character set to the host
300 character set. */
301
302 static bool
303 init_target_to_host_charmap ()
304 {
305 /* If the percent sign is non-zero the mapping has already been
306 initialized. */
307 if (target_to_host_charmap['%'])
308 return true;
309
310 /* Initialize the target_percent character (done elsewhere). */
311 if (!init_target_chars ())
312 return false;
313
314 /* The subset of the source character set used by printf conversion
315 specifications (strictly speaking, not all letters are used but
316 they are included here for the sake of simplicity). The dollar
317 sign must be included even though it's not in the basic source
318 character set. */
319 const char srcset[] = " 0123456789!\"#%&'()*+,-./:;<=>?[\\]^_{|}~$"
320 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
321
322 /* Set the mapping for all characters to some ordinary value (i,e.,
323 not none used in printf conversion specifications) and overwrite
324 those that are used by conversion specifications with their
325 corresponding values. */
326 memset (target_to_host_charmap + 1, '?', sizeof target_to_host_charmap - 1);
327
328 /* Are the two sets of characters the same? */
329 bool all_same_p = true;
330
331 for (const char *pc = srcset; *pc; ++pc)
332 {
333 /* Slice off the high end bits in case target characters are
334 signed. All values are expected to be non-nul, otherwise
335 there's a problem. */
336 if (unsigned char tc = lang_hooks.to_target_charset (*pc))
337 {
338 target_to_host_charmap[tc] = *pc;
339 if (tc != *pc)
340 all_same_p = false;
341 }
342 else
343 return false;
344
345 }
346
347 /* Set the first element to a non-zero value if the mapping
348 is 1-to-1, otherwise leave it clear (NUL is assumed to be
349 the same in both character sets). */
350 target_to_host_charmap[0] = all_same_p;
351
352 return true;
353 }
354
355 /* Return the host source character corresponding to the character
356 CH in the execution character set if one exists, or some innocuous
357 (non-special, non-nul) source character otherwise. */
358
359 static inline unsigned char
360 target_to_host (unsigned char ch)
361 {
362 return target_to_host_charmap[ch];
363 }
364
365 /* Convert an initial substring of the string TARGSTR consisting of
366 characters in the execution character set into a string in the
367 source character set on the host and store up to HOSTSZ characters
368 in the buffer pointed to by HOSTR. Return HOSTR. */
369
370 static const char*
371 target_to_host (char *hostr, size_t hostsz, const char *targstr)
372 {
373 /* Make sure the buffer is reasonably big. */
374 gcc_assert (hostsz > 4);
375
376 /* The interesting subset of source and execution characters are
377 the same so no conversion is necessary. However, truncate
378 overlong strings just like the translated strings are. */
379 if (target_to_host_charmap['\0'] == 1)
380 {
381 strncpy (hostr, targstr, hostsz - 4);
382 if (strlen (targstr) >= hostsz)
383 strcpy (hostr + hostsz - 4, "...");
384 return hostr;
385 }
386
387 /* Convert the initial substring of TARGSTR to the corresponding
388 characters in the host set, appending "..." if TARGSTR is too
389 long to fit. Using the static buffer assumes the function is
390 not called in between sequence points (which it isn't). */
391 for (char *ph = hostr; ; ++targstr)
392 {
393 *ph++ = target_to_host (*targstr);
394 if (!*targstr)
395 break;
396
397 if (size_t (ph - hostr) == hostsz - 4)
398 {
399 *ph = '\0';
400 strcat (ph, "...");
401 break;
402 }
403 }
404
405 return hostr;
406 }
407
408 /* Convert the sequence of decimal digits in the execution character
409 starting at S to a long, just like strtol does. Return the result
410 and set *END to one past the last converted character. On range
411 error set ERANGE to the digit that caused it. */
412
413 static inline long
414 target_strtol10 (const char **ps, const char **erange)
415 {
416 unsigned HOST_WIDE_INT val = 0;
417 for ( ; ; ++*ps)
418 {
419 unsigned char c = target_to_host (**ps);
420 if (ISDIGIT (c))
421 {
422 c -= '0';
423
424 /* Check for overflow. */
425 if (val > (LONG_MAX - c) / 10LU)
426 {
427 val = LONG_MAX;
428 *erange = *ps;
429
430 /* Skip the remaining digits. */
431 do
432 c = target_to_host (*++*ps);
433 while (ISDIGIT (c));
434 break;
435 }
436 else
437 val = val * 10 + c;
438 }
439 else
440 break;
441 }
442
443 return val;
444 }
445
446 /* Given FORMAT, set *PLOC to the source location of the format string
447 and return the format string if it is known or null otherwise. */
448
449 static const char*
450 get_format_string (tree format, location_t *ploc)
451 {
452 *ploc = EXPR_LOC_OR_LOC (format, input_location);
453
454 return c_getstr (format);
455 }
456
457 /* For convenience and brevity, shorter named entrypoints of
458 format_warning_at_substring and format_warning_at_substring_n.
459 These have to be functions with the attribute so that exgettext
460 works properly. */
461
462 static bool
463 ATTRIBUTE_GCC_DIAG (5, 6)
464 fmtwarn (const substring_loc &fmt_loc, location_t param_loc,
465 const char *corrected_substring, int opt, const char *gmsgid, ...)
466 {
467 va_list ap;
468 va_start (ap, gmsgid);
469 bool warned = format_warning_va (fmt_loc, NULL, param_loc, NULL,
470 corrected_substring, opt, gmsgid, &ap);
471 va_end (ap);
472
473 return warned;
474 }
475
476 static bool
477 ATTRIBUTE_GCC_DIAG (6, 8) ATTRIBUTE_GCC_DIAG (7, 8)
478 fmtwarn_n (const substring_loc &fmt_loc, location_t param_loc,
479 const char *corrected_substring, int opt, unsigned HOST_WIDE_INT n,
480 const char *singular_gmsgid, const char *plural_gmsgid, ...)
481 {
482 va_list ap;
483 va_start (ap, plural_gmsgid);
484 bool warned = format_warning_n_va (fmt_loc, NULL, param_loc, NULL,
485 corrected_substring,
486 opt, n, singular_gmsgid, plural_gmsgid,
487 &ap);
488 va_end (ap);
489
490 return warned;
491 }
492
493 /* Format length modifiers. */
494
495 enum format_lengths
496 {
497 FMT_LEN_none,
498 FMT_LEN_hh, // char argument
499 FMT_LEN_h, // short
500 FMT_LEN_l, // long
501 FMT_LEN_ll, // long long
502 FMT_LEN_L, // long double (and GNU long long)
503 FMT_LEN_z, // size_t
504 FMT_LEN_t, // ptrdiff_t
505 FMT_LEN_j // intmax_t
506 };
507
508
509 /* Description of the result of conversion either of a single directive
510 or the whole format string. */
511
512 struct fmtresult
513 {
514 /* Construct a FMTRESULT object with all counters initialized
515 to MIN. KNOWNRANGE is set when MIN is valid. */
516 fmtresult (unsigned HOST_WIDE_INT min = HOST_WIDE_INT_MAX)
517 : argmin (), argmax (),
518 knownrange (min < HOST_WIDE_INT_MAX),
519 mayfail (), nullp ()
520 {
521 range.min = min;
522 range.max = min;
523 range.likely = min;
524 range.unlikely = min;
525 }
526
527 /* Construct a FMTRESULT object with MIN, MAX, and LIKELY counters.
528 KNOWNRANGE is set when both MIN and MAX are valid. */
529 fmtresult (unsigned HOST_WIDE_INT min, unsigned HOST_WIDE_INT max,
530 unsigned HOST_WIDE_INT likely = HOST_WIDE_INT_MAX)
531 : argmin (), argmax (),
532 knownrange (min < HOST_WIDE_INT_MAX && max < HOST_WIDE_INT_MAX),
533 mayfail (), nullp ()
534 {
535 range.min = min;
536 range.max = max;
537 range.likely = max < likely ? min : likely;
538 range.unlikely = max;
539 }
540
541 /* Adjust result upward to reflect the RANGE of values the specified
542 width or precision is known to be in. */
543 fmtresult& adjust_for_width_or_precision (const HOST_WIDE_INT[2],
544 tree = NULL_TREE,
545 unsigned = 0, unsigned = 0);
546
547 /* Return the maximum number of decimal digits a value of TYPE
548 formats as on output. */
549 static unsigned type_max_digits (tree, int);
550
551 /* The range a directive's argument is in. */
552 tree argmin, argmax;
553
554 /* The minimum and maximum number of bytes that a directive
555 results in on output for an argument in the range above. */
556 result_range range;
557
558 /* True when the range above is obtained from a known value of
559 a directive's argument or its bounds and not the result of
560 heuristics that depend on warning levels. */
561 bool knownrange;
562
563 /* True for a directive that may fail (such as wide character
564 directives). */
565 bool mayfail;
566
567 /* True when the argument is a null pointer. */
568 bool nullp;
569 };
570
571 /* Adjust result upward to reflect the range ADJUST of values the
572 specified width or precision is known to be in. When non-null,
573 TYPE denotes the type of the directive whose result is being
574 adjusted, BASE gives the base of the directive (octal, decimal,
575 or hex), and ADJ denotes the additional adjustment to the LIKELY
576 counter that may need to be added when ADJUST is a range. */
577
578 fmtresult&
579 fmtresult::adjust_for_width_or_precision (const HOST_WIDE_INT adjust[2],
580 tree type /* = NULL_TREE */,
581 unsigned base /* = 0 */,
582 unsigned adj /* = 0 */)
583 {
584 bool minadjusted = false;
585
586 /* Adjust the minimum and likely counters. */
587 if (adjust[0] >= 0)
588 {
589 if (range.min < (unsigned HOST_WIDE_INT)adjust[0])
590 {
591 range.min = adjust[0];
592 minadjusted = true;
593 }
594
595 /* Adjust the likely counter. */
596 if (range.likely < range.min)
597 range.likely = range.min;
598 }
599 else if (adjust[0] == target_int_min ()
600 && (unsigned HOST_WIDE_INT)adjust[1] == target_int_max ())
601 knownrange = false;
602
603 /* Adjust the maximum counter. */
604 if (adjust[1] > 0)
605 {
606 if (range.max < (unsigned HOST_WIDE_INT)adjust[1])
607 {
608 range.max = adjust[1];
609
610 /* Set KNOWNRANGE if both the minimum and maximum have been
611 adjusted. Otherwise leave it at what it was before. */
612 knownrange = minadjusted;
613 }
614 }
615
616 if (warn_level > 1 && type)
617 {
618 /* For large non-constant width or precision whose range spans
619 the maximum number of digits produced by the directive for
620 any argument, set the likely number of bytes to be at most
621 the number digits plus other adjustment determined by the
622 caller (one for sign or two for the hexadecimal "0x"
623 prefix). */
624 unsigned dirdigs = type_max_digits (type, base);
625 if (adjust[0] < dirdigs && dirdigs < adjust[1]
626 && range.likely < dirdigs)
627 range.likely = dirdigs + adj;
628 }
629 else if (range.likely < (range.min ? range.min : 1))
630 {
631 /* Conservatively, set LIKELY to at least MIN but no less than
632 1 unless MAX is zero. */
633 range.likely = (range.min
634 ? range.min
635 : range.max && (range.max < HOST_WIDE_INT_MAX
636 || warn_level > 1) ? 1 : 0);
637 }
638
639 /* Finally adjust the unlikely counter to be at least as large as
640 the maximum. */
641 if (range.unlikely < range.max)
642 range.unlikely = range.max;
643
644 return *this;
645 }
646
647 /* Return the maximum number of digits a value of TYPE formats in
648 BASE on output, not counting base prefix . */
649
650 unsigned
651 fmtresult::type_max_digits (tree type, int base)
652 {
653 unsigned prec = TYPE_PRECISION (type);
654 switch (base)
655 {
656 case 8:
657 return (prec + 2) / 3;
658 case 10:
659 /* Decimal approximation: yields 3, 5, 10, and 20 for precision
660 of 8, 16, 32, and 64 bits. */
661 return prec * 301 / 1000 + 1;
662 case 16:
663 return prec / 4;
664 }
665
666 gcc_unreachable ();
667 }
668
669 static bool
670 get_int_range (tree, HOST_WIDE_INT *, HOST_WIDE_INT *, bool, HOST_WIDE_INT,
671 class vr_values *vr_values);
672
673 /* Description of a format directive. A directive is either a plain
674 string or a conversion specification that starts with '%'. */
675
676 struct directive
677 {
678 /* The 1-based directive number (for debugging). */
679 unsigned dirno;
680
681 /* The first character of the directive and its length. */
682 const char *beg;
683 size_t len;
684
685 /* A bitmap of flags, one for each character. */
686 unsigned flags[256 / sizeof (int)];
687
688 /* The range of values of the specified width, or -1 if not specified. */
689 HOST_WIDE_INT width[2];
690 /* The range of values of the specified precision, or -1 if not
691 specified. */
692 HOST_WIDE_INT prec[2];
693
694 /* Length modifier. */
695 format_lengths modifier;
696
697 /* Format specifier character. */
698 char specifier;
699
700 /* The argument of the directive or null when the directive doesn't
701 take one or when none is available (such as for vararg functions). */
702 tree arg;
703
704 /* Format conversion function that given a directive and an argument
705 returns the formatting result. */
706 fmtresult (*fmtfunc) (const directive &, tree, vr_values *);
707
708 /* Return True when a the format flag CHR has been used. */
709 bool get_flag (char chr) const
710 {
711 unsigned char c = chr & 0xff;
712 return (flags[c / (CHAR_BIT * sizeof *flags)]
713 & (1U << (c % (CHAR_BIT * sizeof *flags))));
714 }
715
716 /* Make a record of the format flag CHR having been used. */
717 void set_flag (char chr)
718 {
719 unsigned char c = chr & 0xff;
720 flags[c / (CHAR_BIT * sizeof *flags)]
721 |= (1U << (c % (CHAR_BIT * sizeof *flags)));
722 }
723
724 /* Reset the format flag CHR. */
725 void clear_flag (char chr)
726 {
727 unsigned char c = chr & 0xff;
728 flags[c / (CHAR_BIT * sizeof *flags)]
729 &= ~(1U << (c % (CHAR_BIT * sizeof *flags)));
730 }
731
732 /* Set both bounds of the width range to VAL. */
733 void set_width (HOST_WIDE_INT val)
734 {
735 width[0] = width[1] = val;
736 }
737
738 /* Set the width range according to ARG, with both bounds being
739 no less than 0. For a constant ARG set both bounds to its value
740 or 0, whichever is greater. For a non-constant ARG in some range
741 set width to its range adjusting each bound to -1 if it's less.
742 For an indeterminate ARG set width to [0, INT_MAX]. */
743 void set_width (tree arg, vr_values *vr_values)
744 {
745 get_int_range (arg, width, width + 1, true, 0, vr_values);
746 }
747
748 /* Set both bounds of the precision range to VAL. */
749 void set_precision (HOST_WIDE_INT val)
750 {
751 prec[0] = prec[1] = val;
752 }
753
754 /* Set the precision range according to ARG, with both bounds being
755 no less than -1. For a constant ARG set both bounds to its value
756 or -1 whichever is greater. For a non-constant ARG in some range
757 set precision to its range adjusting each bound to -1 if it's less.
758 For an indeterminate ARG set precision to [-1, INT_MAX]. */
759 void set_precision (tree arg, vr_values *vr_values)
760 {
761 get_int_range (arg, prec, prec + 1, false, -1, vr_values);
762 }
763
764 /* Return true if both width and precision are known to be
765 either constant or in some range, false otherwise. */
766 bool known_width_and_precision () const
767 {
768 return ((width[1] < 0
769 || (unsigned HOST_WIDE_INT)width[1] <= target_int_max ())
770 && (prec[1] < 0
771 || (unsigned HOST_WIDE_INT)prec[1] < target_int_max ()));
772 }
773 };
774
775 /* Return the logarithm of X in BASE. */
776
777 static int
778 ilog (unsigned HOST_WIDE_INT x, int base)
779 {
780 int res = 0;
781 do
782 {
783 ++res;
784 x /= base;
785 } while (x);
786 return res;
787 }
788
789 /* Return the number of bytes resulting from converting into a string
790 the INTEGER_CST tree node X in BASE with a minimum of PREC digits.
791 PLUS indicates whether 1 for a plus sign should be added for positive
792 numbers, and PREFIX whether the length of an octal ('O') or hexadecimal
793 ('0x') prefix should be added for nonzero numbers. Return -1 if X cannot
794 be represented. */
795
796 static HOST_WIDE_INT
797 tree_digits (tree x, int base, HOST_WIDE_INT prec, bool plus, bool prefix)
798 {
799 unsigned HOST_WIDE_INT absval;
800
801 HOST_WIDE_INT res;
802
803 if (TYPE_UNSIGNED (TREE_TYPE (x)))
804 {
805 if (tree_fits_uhwi_p (x))
806 {
807 absval = tree_to_uhwi (x);
808 res = plus;
809 }
810 else
811 return -1;
812 }
813 else
814 {
815 if (tree_fits_shwi_p (x))
816 {
817 HOST_WIDE_INT i = tree_to_shwi (x);
818 if (HOST_WIDE_INT_MIN == i)
819 {
820 /* Avoid undefined behavior due to negating a minimum. */
821 absval = HOST_WIDE_INT_MAX;
822 res = 1;
823 }
824 else if (i < 0)
825 {
826 absval = -i;
827 res = 1;
828 }
829 else
830 {
831 absval = i;
832 res = plus;
833 }
834 }
835 else
836 return -1;
837 }
838
839 int ndigs = ilog (absval, base);
840
841 res += prec < ndigs ? ndigs : prec;
842
843 /* Adjust a non-zero value for the base prefix, either hexadecimal,
844 or, unless precision has resulted in a leading zero, also octal. */
845 if (prefix && absval && (base == 16 || prec <= ndigs))
846 {
847 if (base == 8)
848 res += 1;
849 else if (base == 16)
850 res += 2;
851 }
852
853 return res;
854 }
855
856 /* Given the formatting result described by RES and NAVAIL, the number
857 of available in the destination, return the range of bytes remaining
858 in the destination. */
859
860 static inline result_range
861 bytes_remaining (unsigned HOST_WIDE_INT navail, const format_result &res)
862 {
863 result_range range;
864
865 if (HOST_WIDE_INT_MAX <= navail)
866 {
867 range.min = range.max = range.likely = range.unlikely = navail;
868 return range;
869 }
870
871 /* The lower bound of the available range is the available size
872 minus the maximum output size, and the upper bound is the size
873 minus the minimum. */
874 range.max = res.range.min < navail ? navail - res.range.min : 0;
875
876 range.likely = res.range.likely < navail ? navail - res.range.likely : 0;
877
878 if (res.range.max < HOST_WIDE_INT_MAX)
879 range.min = res.range.max < navail ? navail - res.range.max : 0;
880 else
881 range.min = range.likely;
882
883 range.unlikely = (res.range.unlikely < navail
884 ? navail - res.range.unlikely : 0);
885
886 return range;
887 }
888
889 /* Description of a call to a formatted function. */
890
891 struct sprintf_dom_walker::call_info
892 {
893 /* Function call statement. */
894 gimple *callstmt;
895
896 /* Function called. */
897 tree func;
898
899 /* Called built-in function code. */
900 built_in_function fncode;
901
902 /* Format argument and format string extracted from it. */
903 tree format;
904 const char *fmtstr;
905
906 /* The location of the format argument. */
907 location_t fmtloc;
908
909 /* The destination object size for __builtin___xxx_chk functions
910 typically determined by __builtin_object_size, or -1 if unknown. */
911 unsigned HOST_WIDE_INT objsize;
912
913 /* Number of the first variable argument. */
914 unsigned HOST_WIDE_INT argidx;
915
916 /* True for functions like snprintf that specify the size of
917 the destination, false for others like sprintf that don't. */
918 bool bounded;
919
920 /* True for bounded functions like snprintf that specify a zero-size
921 buffer as a request to compute the size of output without actually
922 writing any. NOWRITE is cleared in response to the %n directive
923 which has side-effects similar to writing output. */
924 bool nowrite;
925
926 /* Return true if the called function's return value is used. */
927 bool retval_used () const
928 {
929 return gimple_get_lhs (callstmt);
930 }
931
932 /* Return the warning option corresponding to the called function. */
933 int warnopt () const
934 {
935 return bounded ? OPT_Wformat_truncation_ : OPT_Wformat_overflow_;
936 }
937 };
938
939 /* Return the result of formatting a no-op directive (such as '%n'). */
940
941 static fmtresult
942 format_none (const directive &, tree, vr_values *)
943 {
944 fmtresult res (0);
945 return res;
946 }
947
948 /* Return the result of formatting the '%%' directive. */
949
950 static fmtresult
951 format_percent (const directive &, tree, vr_values *)
952 {
953 fmtresult res (1);
954 return res;
955 }
956
957
958 /* Compute intmax_type_node and uintmax_type_node similarly to how
959 tree.c builds size_type_node. */
960
961 static void
962 build_intmax_type_nodes (tree *pintmax, tree *puintmax)
963 {
964 if (strcmp (UINTMAX_TYPE, "unsigned int") == 0)
965 {
966 *pintmax = integer_type_node;
967 *puintmax = unsigned_type_node;
968 }
969 else if (strcmp (UINTMAX_TYPE, "long unsigned int") == 0)
970 {
971 *pintmax = long_integer_type_node;
972 *puintmax = long_unsigned_type_node;
973 }
974 else if (strcmp (UINTMAX_TYPE, "long long unsigned int") == 0)
975 {
976 *pintmax = long_long_integer_type_node;
977 *puintmax = long_long_unsigned_type_node;
978 }
979 else
980 {
981 for (int i = 0; i < NUM_INT_N_ENTS; i++)
982 if (int_n_enabled_p[i])
983 {
984 char name[50];
985 sprintf (name, "__int%d unsigned", int_n_data[i].bitsize);
986
987 if (strcmp (name, UINTMAX_TYPE) == 0)
988 {
989 *pintmax = int_n_trees[i].signed_type;
990 *puintmax = int_n_trees[i].unsigned_type;
991 return;
992 }
993 }
994 gcc_unreachable ();
995 }
996 }
997
998 /* Determine the range [*PMIN, *PMAX] that the expression ARG is
999 in and that is representable in type int.
1000 Return true when the range is a subrange of that of int.
1001 When ARG is null it is as if it had the full range of int.
1002 When ABSOLUTE is true the range reflects the absolute value of
1003 the argument. When ABSOLUTE is false, negative bounds of
1004 the determined range are replaced with NEGBOUND. */
1005
1006 static bool
1007 get_int_range (tree arg, HOST_WIDE_INT *pmin, HOST_WIDE_INT *pmax,
1008 bool absolute, HOST_WIDE_INT negbound,
1009 class vr_values *vr_values)
1010 {
1011 /* The type of the result. */
1012 const_tree type = integer_type_node;
1013
1014 bool knownrange = false;
1015
1016 if (!arg)
1017 {
1018 *pmin = tree_to_shwi (TYPE_MIN_VALUE (type));
1019 *pmax = tree_to_shwi (TYPE_MAX_VALUE (type));
1020 }
1021 else if (TREE_CODE (arg) == INTEGER_CST
1022 && TYPE_PRECISION (TREE_TYPE (arg)) <= TYPE_PRECISION (type))
1023 {
1024 /* For a constant argument return its value adjusted as specified
1025 by NEGATIVE and NEGBOUND and return true to indicate that the
1026 result is known. */
1027 *pmin = tree_fits_shwi_p (arg) ? tree_to_shwi (arg) : tree_to_uhwi (arg);
1028 *pmax = *pmin;
1029 knownrange = true;
1030 }
1031 else
1032 {
1033 /* True if the argument's range cannot be determined. */
1034 bool unknown = true;
1035
1036 tree argtype = TREE_TYPE (arg);
1037
1038 /* Ignore invalid arguments with greater precision that that
1039 of the expected type (e.g., in sprintf("%*i", 12LL, i)).
1040 They will have been detected and diagnosed by -Wformat and
1041 so it's not important to complicate this code to try to deal
1042 with them again. */
1043 if (TREE_CODE (arg) == SSA_NAME
1044 && INTEGRAL_TYPE_P (argtype)
1045 && TYPE_PRECISION (argtype) <= TYPE_PRECISION (type))
1046 {
1047 /* Try to determine the range of values of the integer argument. */
1048 value_range *vr = vr_values->get_value_range (arg);
1049 if (vr->type == VR_RANGE
1050 && TREE_CODE (vr->min) == INTEGER_CST
1051 && TREE_CODE (vr->max) == INTEGER_CST)
1052 {
1053 HOST_WIDE_INT type_min
1054 = (TYPE_UNSIGNED (argtype)
1055 ? tree_to_uhwi (TYPE_MIN_VALUE (argtype))
1056 : tree_to_shwi (TYPE_MIN_VALUE (argtype)));
1057
1058 HOST_WIDE_INT type_max = tree_to_uhwi (TYPE_MAX_VALUE (argtype));
1059
1060 *pmin = TREE_INT_CST_LOW (vr->min);
1061 *pmax = TREE_INT_CST_LOW (vr->max);
1062
1063 if (*pmin < *pmax)
1064 {
1065 /* Return true if the adjusted range is a subrange of
1066 the full range of the argument's type. *PMAX may
1067 be less than *PMIN when the argument is unsigned
1068 and its upper bound is in excess of TYPE_MAX. In
1069 that (invalid) case disregard the range and use that
1070 of the expected type instead. */
1071 knownrange = type_min < *pmin || *pmax < type_max;
1072
1073 unknown = false;
1074 }
1075 }
1076 }
1077
1078 /* Handle an argument with an unknown range as if none had been
1079 provided. */
1080 if (unknown)
1081 return get_int_range (NULL_TREE, pmin, pmax, absolute,
1082 negbound, vr_values);
1083 }
1084
1085 /* Adjust each bound as specified by ABSOLUTE and NEGBOUND. */
1086 if (absolute)
1087 {
1088 if (*pmin < 0)
1089 {
1090 if (*pmin == *pmax)
1091 *pmin = *pmax = -*pmin;
1092 else
1093 {
1094 /* Make sure signed overlow is avoided. */
1095 gcc_assert (*pmin != HOST_WIDE_INT_MIN);
1096
1097 HOST_WIDE_INT tmp = -*pmin;
1098 *pmin = 0;
1099 if (*pmax < tmp)
1100 *pmax = tmp;
1101 }
1102 }
1103 }
1104 else if (*pmin < negbound)
1105 *pmin = negbound;
1106
1107 return knownrange;
1108 }
1109
1110 /* With the range [*ARGMIN, *ARGMAX] of an integer directive's actual
1111 argument, due to the conversion from either *ARGMIN or *ARGMAX to
1112 the type of the directive's formal argument it's possible for both
1113 to result in the same number of bytes or a range of bytes that's
1114 less than the number of bytes that would result from formatting
1115 some other value in the range [*ARGMIN, *ARGMAX]. This can be
1116 determined by checking for the actual argument being in the range
1117 of the type of the directive. If it isn't it must be assumed to
1118 take on the full range of the directive's type.
1119 Return true when the range has been adjusted to the full range
1120 of DIRTYPE, and false otherwise. */
1121
1122 static bool
1123 adjust_range_for_overflow (tree dirtype, tree *argmin, tree *argmax)
1124 {
1125 tree argtype = TREE_TYPE (*argmin);
1126 unsigned argprec = TYPE_PRECISION (argtype);
1127 unsigned dirprec = TYPE_PRECISION (dirtype);
1128
1129 /* If the actual argument and the directive's argument have the same
1130 precision and sign there can be no overflow and so there is nothing
1131 to adjust. */
1132 if (argprec == dirprec && TYPE_SIGN (argtype) == TYPE_SIGN (dirtype))
1133 return false;
1134
1135 /* The logic below was inspired/lifted from the CONVERT_EXPR_CODE_P
1136 branch in the extract_range_from_unary_expr function in tree-vrp.c. */
1137
1138 if (TREE_CODE (*argmin) == INTEGER_CST
1139 && TREE_CODE (*argmax) == INTEGER_CST
1140 && (dirprec >= argprec
1141 || integer_zerop (int_const_binop (RSHIFT_EXPR,
1142 int_const_binop (MINUS_EXPR,
1143 *argmax,
1144 *argmin),
1145 size_int (dirprec)))))
1146 {
1147 *argmin = force_fit_type (dirtype, wi::to_widest (*argmin), 0, false);
1148 *argmax = force_fit_type (dirtype, wi::to_widest (*argmax), 0, false);
1149
1150 /* If *ARGMIN is still less than *ARGMAX the conversion above
1151 is safe. Otherwise, it has overflowed and would be unsafe. */
1152 if (tree_int_cst_le (*argmin, *argmax))
1153 return false;
1154 }
1155
1156 *argmin = TYPE_MIN_VALUE (dirtype);
1157 *argmax = TYPE_MAX_VALUE (dirtype);
1158 return true;
1159 }
1160
1161 /* Return a range representing the minimum and maximum number of bytes
1162 that the format directive DIR will output for any argument given
1163 the WIDTH and PRECISION (extracted from DIR). This function is
1164 used when the directive argument or its value isn't known. */
1165
1166 static fmtresult
1167 format_integer (const directive &dir, tree arg, vr_values *vr_values)
1168 {
1169 tree intmax_type_node;
1170 tree uintmax_type_node;
1171
1172 /* Base to format the number in. */
1173 int base;
1174
1175 /* True when a conversion is preceded by a prefix indicating the base
1176 of the argument (octal or hexadecimal). */
1177 bool maybebase = dir.get_flag ('#');
1178
1179 /* True when a signed conversion is preceded by a sign or space. */
1180 bool maybesign = false;
1181
1182 /* True for signed conversions (i.e., 'd' and 'i'). */
1183 bool sign = false;
1184
1185 switch (dir.specifier)
1186 {
1187 case 'd':
1188 case 'i':
1189 /* Space and '+' are only meaningful for signed conversions. */
1190 maybesign = dir.get_flag (' ') | dir.get_flag ('+');
1191 sign = true;
1192 base = 10;
1193 break;
1194 case 'u':
1195 base = 10;
1196 break;
1197 case 'o':
1198 base = 8;
1199 break;
1200 case 'X':
1201 case 'x':
1202 base = 16;
1203 break;
1204 default:
1205 gcc_unreachable ();
1206 }
1207
1208 /* The type of the "formal" argument expected by the directive. */
1209 tree dirtype = NULL_TREE;
1210
1211 /* Determine the expected type of the argument from the length
1212 modifier. */
1213 switch (dir.modifier)
1214 {
1215 case FMT_LEN_none:
1216 if (dir.specifier == 'p')
1217 dirtype = ptr_type_node;
1218 else
1219 dirtype = sign ? integer_type_node : unsigned_type_node;
1220 break;
1221
1222 case FMT_LEN_h:
1223 dirtype = sign ? short_integer_type_node : short_unsigned_type_node;
1224 break;
1225
1226 case FMT_LEN_hh:
1227 dirtype = sign ? signed_char_type_node : unsigned_char_type_node;
1228 break;
1229
1230 case FMT_LEN_l:
1231 dirtype = sign ? long_integer_type_node : long_unsigned_type_node;
1232 break;
1233
1234 case FMT_LEN_L:
1235 case FMT_LEN_ll:
1236 dirtype = (sign
1237 ? long_long_integer_type_node
1238 : long_long_unsigned_type_node);
1239 break;
1240
1241 case FMT_LEN_z:
1242 dirtype = signed_or_unsigned_type_for (!sign, size_type_node);
1243 break;
1244
1245 case FMT_LEN_t:
1246 dirtype = signed_or_unsigned_type_for (!sign, ptrdiff_type_node);
1247 break;
1248
1249 case FMT_LEN_j:
1250 build_intmax_type_nodes (&intmax_type_node, &uintmax_type_node);
1251 dirtype = sign ? intmax_type_node : uintmax_type_node;
1252 break;
1253
1254 default:
1255 return fmtresult ();
1256 }
1257
1258 /* The type of the argument to the directive, either deduced from
1259 the actual non-constant argument if one is known, or from
1260 the directive itself when none has been provided because it's
1261 a va_list. */
1262 tree argtype = NULL_TREE;
1263
1264 if (!arg)
1265 {
1266 /* When the argument has not been provided, use the type of
1267 the directive's argument as an approximation. This will
1268 result in false positives for directives like %i with
1269 arguments with smaller precision (such as short or char). */
1270 argtype = dirtype;
1271 }
1272 else if (TREE_CODE (arg) == INTEGER_CST)
1273 {
1274 /* When a constant argument has been provided use its value
1275 rather than type to determine the length of the output. */
1276 fmtresult res;
1277
1278 if ((dir.prec[0] <= 0 && dir.prec[1] >= 0) && integer_zerop (arg))
1279 {
1280 /* As a special case, a precision of zero with a zero argument
1281 results in zero bytes except in base 8 when the '#' flag is
1282 specified, and for signed conversions in base 8 and 10 when
1283 either the space or '+' flag has been specified and it results
1284 in just one byte (with width having the normal effect). This
1285 must extend to the case of a specified precision with
1286 an unknown value because it can be zero. */
1287 res.range.min = ((base == 8 && dir.get_flag ('#')) || maybesign);
1288 if (res.range.min == 0 && dir.prec[0] != dir.prec[1])
1289 {
1290 res.range.max = 1;
1291 res.range.likely = 1;
1292 }
1293 else
1294 {
1295 res.range.max = res.range.min;
1296 res.range.likely = res.range.min;
1297 }
1298 }
1299 else
1300 {
1301 /* Convert the argument to the type of the directive. */
1302 arg = fold_convert (dirtype, arg);
1303
1304 res.range.min = tree_digits (arg, base, dir.prec[0],
1305 maybesign, maybebase);
1306 if (dir.prec[0] == dir.prec[1])
1307 res.range.max = res.range.min;
1308 else
1309 res.range.max = tree_digits (arg, base, dir.prec[1],
1310 maybesign, maybebase);
1311 res.range.likely = res.range.min;
1312 res.knownrange = true;
1313 }
1314
1315 res.range.unlikely = res.range.max;
1316
1317 /* Bump up the counters if WIDTH is greater than LEN. */
1318 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1319 (sign | maybebase) + (base == 16));
1320 /* Bump up the counters again if PRECision is greater still. */
1321 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1322 (sign | maybebase) + (base == 16));
1323
1324 return res;
1325 }
1326 else if (INTEGRAL_TYPE_P (TREE_TYPE (arg))
1327 || TREE_CODE (TREE_TYPE (arg)) == POINTER_TYPE)
1328 /* Determine the type of the provided non-constant argument. */
1329 argtype = TREE_TYPE (arg);
1330 else
1331 /* Don't bother with invalid arguments since they likely would
1332 have already been diagnosed, and disable any further checking
1333 of the format string by returning [-1, -1]. */
1334 return fmtresult ();
1335
1336 fmtresult res;
1337
1338 /* Using either the range the non-constant argument is in, or its
1339 type (either "formal" or actual), create a range of values that
1340 constrain the length of output given the warning level. */
1341 tree argmin = NULL_TREE;
1342 tree argmax = NULL_TREE;
1343
1344 if (arg
1345 && TREE_CODE (arg) == SSA_NAME
1346 && INTEGRAL_TYPE_P (argtype))
1347 {
1348 /* Try to determine the range of values of the integer argument
1349 (range information is not available for pointers). */
1350 value_range *vr = vr_values->get_value_range (arg);
1351 if (vr->type == VR_RANGE
1352 && TREE_CODE (vr->min) == INTEGER_CST
1353 && TREE_CODE (vr->max) == INTEGER_CST)
1354 {
1355 argmin = vr->min;
1356 argmax = vr->max;
1357
1358 /* Set KNOWNRANGE if the argument is in a known subrange
1359 of the directive's type and neither width nor precision
1360 is unknown. (KNOWNRANGE may be reset below). */
1361 res.knownrange
1362 = ((!tree_int_cst_equal (TYPE_MIN_VALUE (dirtype), argmin)
1363 || !tree_int_cst_equal (TYPE_MAX_VALUE (dirtype), argmax))
1364 && dir.known_width_and_precision ());
1365
1366 res.argmin = argmin;
1367 res.argmax = argmax;
1368 }
1369 else if (vr->type == VR_ANTI_RANGE)
1370 {
1371 /* Handle anti-ranges if/when bug 71690 is resolved. */
1372 }
1373 else if (vr->type == VR_VARYING
1374 || vr->type == VR_UNDEFINED)
1375 {
1376 /* The argument here may be the result of promoting the actual
1377 argument to int. Try to determine the type of the actual
1378 argument before promotion and narrow down its range that
1379 way. */
1380 gimple *def = SSA_NAME_DEF_STMT (arg);
1381 if (is_gimple_assign (def))
1382 {
1383 tree_code code = gimple_assign_rhs_code (def);
1384 if (code == INTEGER_CST)
1385 {
1386 arg = gimple_assign_rhs1 (def);
1387 return format_integer (dir, arg, vr_values);
1388 }
1389
1390 if (code == NOP_EXPR)
1391 {
1392 tree type = TREE_TYPE (gimple_assign_rhs1 (def));
1393 if (INTEGRAL_TYPE_P (type)
1394 || TREE_CODE (type) == POINTER_TYPE)
1395 argtype = type;
1396 }
1397 }
1398 }
1399 }
1400
1401 if (!argmin)
1402 {
1403 if (TREE_CODE (argtype) == POINTER_TYPE)
1404 {
1405 argmin = build_int_cst (pointer_sized_int_node, 0);
1406 argmax = build_all_ones_cst (pointer_sized_int_node);
1407 }
1408 else
1409 {
1410 argmin = TYPE_MIN_VALUE (argtype);
1411 argmax = TYPE_MAX_VALUE (argtype);
1412 }
1413 }
1414
1415 /* Clear KNOWNRANGE if the range has been adjusted to the maximum
1416 of the directive. If it has been cleared then since ARGMIN and/or
1417 ARGMAX have been adjusted also adjust the corresponding ARGMIN and
1418 ARGMAX in the result to include in diagnostics. */
1419 if (adjust_range_for_overflow (dirtype, &argmin, &argmax))
1420 {
1421 res.knownrange = false;
1422 res.argmin = argmin;
1423 res.argmax = argmax;
1424 }
1425
1426 /* Recursively compute the minimum and maximum from the known range. */
1427 if (TYPE_UNSIGNED (dirtype) || tree_int_cst_sgn (argmin) >= 0)
1428 {
1429 /* For unsigned conversions/directives or signed when
1430 the minimum is positive, use the minimum and maximum to compute
1431 the shortest and longest output, respectively. */
1432 res.range.min = format_integer (dir, argmin, vr_values).range.min;
1433 res.range.max = format_integer (dir, argmax, vr_values).range.max;
1434 }
1435 else if (tree_int_cst_sgn (argmax) < 0)
1436 {
1437 /* For signed conversions/directives if maximum is negative,
1438 use the minimum as the longest output and maximum as the
1439 shortest output. */
1440 res.range.min = format_integer (dir, argmax, vr_values).range.min;
1441 res.range.max = format_integer (dir, argmin, vr_values).range.max;
1442 }
1443 else
1444 {
1445 /* Otherwise, 0 is inside of the range and minimum negative. Use 0
1446 as the shortest output and for the longest output compute the
1447 length of the output of both minimum and maximum and pick the
1448 longer. */
1449 unsigned HOST_WIDE_INT max1
1450 = format_integer (dir, argmin, vr_values).range.max;
1451 unsigned HOST_WIDE_INT max2
1452 = format_integer (dir, argmax, vr_values).range.max;
1453 res.range.min
1454 = format_integer (dir, integer_zero_node, vr_values).range.min;
1455 res.range.max = MAX (max1, max2);
1456 }
1457
1458 /* If the range is known, use the maximum as the likely length. */
1459 if (res.knownrange)
1460 res.range.likely = res.range.max;
1461 else
1462 {
1463 /* Otherwise, use the minimum. Except for the case where for %#x or
1464 %#o the minimum is just for a single value in the range (0) and
1465 for all other values it is something longer, like 0x1 or 01.
1466 Use the length for value 1 in that case instead as the likely
1467 length. */
1468 res.range.likely = res.range.min;
1469 if (maybebase
1470 && base != 10
1471 && (tree_int_cst_sgn (argmin) < 0 || tree_int_cst_sgn (argmax) > 0))
1472 {
1473 if (res.range.min == 1)
1474 res.range.likely += base == 8 ? 1 : 2;
1475 else if (res.range.min == 2
1476 && base == 16
1477 && (dir.width[0] == 2 || dir.prec[0] == 2))
1478 ++res.range.likely;
1479 }
1480 }
1481
1482 res.range.unlikely = res.range.max;
1483 res.adjust_for_width_or_precision (dir.width, dirtype, base,
1484 (sign | maybebase) + (base == 16));
1485 res.adjust_for_width_or_precision (dir.prec, dirtype, base,
1486 (sign | maybebase) + (base == 16));
1487
1488 return res;
1489 }
1490
1491 /* Return the number of bytes that a format directive consisting of FLAGS,
1492 PRECision, format SPECification, and MPFR rounding specifier RNDSPEC,
1493 would result for argument X under ideal conditions (i.e., if PREC
1494 weren't excessive). MPFR 3.1 allocates large amounts of memory for
1495 values of PREC with large magnitude and can fail (see MPFR bug #21056).
1496 This function works around those problems. */
1497
1498 static unsigned HOST_WIDE_INT
1499 get_mpfr_format_length (mpfr_ptr x, const char *flags, HOST_WIDE_INT prec,
1500 char spec, char rndspec)
1501 {
1502 char fmtstr[40];
1503
1504 HOST_WIDE_INT len = strlen (flags);
1505
1506 fmtstr[0] = '%';
1507 memcpy (fmtstr + 1, flags, len);
1508 memcpy (fmtstr + 1 + len, ".*R", 3);
1509 fmtstr[len + 4] = rndspec;
1510 fmtstr[len + 5] = spec;
1511 fmtstr[len + 6] = '\0';
1512
1513 spec = TOUPPER (spec);
1514 if (spec == 'E' || spec == 'F')
1515 {
1516 /* For %e, specify the precision explicitly since mpfr_sprintf
1517 does its own thing just to be different (see MPFR bug 21088). */
1518 if (prec < 0)
1519 prec = 6;
1520 }
1521 else
1522 {
1523 /* Avoid passing negative precisions with larger magnitude to MPFR
1524 to avoid exposing its bugs. (A negative precision is supposed
1525 to be ignored.) */
1526 if (prec < 0)
1527 prec = -1;
1528 }
1529
1530 HOST_WIDE_INT p = prec;
1531
1532 if (spec == 'G' && !strchr (flags, '#'))
1533 {
1534 /* For G/g without the pound flag, precision gives the maximum number
1535 of significant digits which is bounded by LDBL_MAX_10_EXP, or, for
1536 a 128 bit IEEE extended precision, 4932. Using twice as much here
1537 should be more than sufficient for any real format. */
1538 if ((IEEE_MAX_10_EXP * 2) < prec)
1539 prec = IEEE_MAX_10_EXP * 2;
1540 p = prec;
1541 }
1542 else
1543 {
1544 /* Cap precision arbitrarily at 1KB and add the difference
1545 (if any) to the MPFR result. */
1546 if (prec > 1024)
1547 p = 1024;
1548 }
1549
1550 len = mpfr_snprintf (NULL, 0, fmtstr, (int)p, x);
1551
1552 /* Handle the unlikely (impossible?) error by returning more than
1553 the maximum dictated by the function's return type. */
1554 if (len < 0)
1555 return target_dir_max () + 1;
1556
1557 /* Adjust the return value by the difference. */
1558 if (p < prec)
1559 len += prec - p;
1560
1561 return len;
1562 }
1563
1564 /* Return the number of bytes to format using the format specifier
1565 SPEC and the precision PREC the largest value in the real floating
1566 TYPE. */
1567
1568 static unsigned HOST_WIDE_INT
1569 format_floating_max (tree type, char spec, HOST_WIDE_INT prec)
1570 {
1571 machine_mode mode = TYPE_MODE (type);
1572
1573 /* IBM Extended mode. */
1574 if (MODE_COMPOSITE_P (mode))
1575 mode = DFmode;
1576
1577 /* Get the real type format desription for the target. */
1578 const real_format *rfmt = REAL_MODE_FORMAT (mode);
1579 REAL_VALUE_TYPE rv;
1580
1581 real_maxval (&rv, 0, mode);
1582
1583 /* Convert the GCC real value representation with the precision
1584 of the real type to the mpfr_t format with the GCC default
1585 round-to-nearest mode. */
1586 mpfr_t x;
1587 mpfr_init2 (x, rfmt->p);
1588 mpfr_from_real (x, &rv, GMP_RNDN);
1589
1590 /* Return a value one greater to account for the leading minus sign. */
1591 unsigned HOST_WIDE_INT r
1592 = 1 + get_mpfr_format_length (x, "", prec, spec, 'D');
1593 mpfr_clear (x);
1594 return r;
1595 }
1596
1597 /* Return a range representing the minimum and maximum number of bytes
1598 that the directive DIR will output for any argument. PREC gives
1599 the adjusted precision range to account for negative precisions
1600 meaning the default 6. This function is used when the directive
1601 argument or its value isn't known. */
1602
1603 static fmtresult
1604 format_floating (const directive &dir, const HOST_WIDE_INT prec[2])
1605 {
1606 tree type;
1607
1608 switch (dir.modifier)
1609 {
1610 case FMT_LEN_l:
1611 case FMT_LEN_none:
1612 type = double_type_node;
1613 break;
1614
1615 case FMT_LEN_L:
1616 type = long_double_type_node;
1617 break;
1618
1619 case FMT_LEN_ll:
1620 type = long_double_type_node;
1621 break;
1622
1623 default:
1624 return fmtresult ();
1625 }
1626
1627 /* The minimum and maximum number of bytes produced by the directive. */
1628 fmtresult res;
1629
1630 /* The minimum output as determined by flags. It's always at least 1.
1631 When plus or space are set the output is preceded by either a sign
1632 or a space. */
1633 unsigned flagmin = (1 /* for the first digit */
1634 + (dir.get_flag ('+') | dir.get_flag (' ')));
1635
1636 /* The minimum is 3 for "inf" and "nan" for all specifiers, plus 1
1637 for the plus sign/space with the '+' and ' ' flags, respectively,
1638 unless reduced below. */
1639 res.range.min = 2 + flagmin;
1640
1641 /* When the pound flag is set the decimal point is included in output
1642 regardless of precision. Whether or not a decimal point is included
1643 otherwise depends on the specification and precision. */
1644 bool radix = dir.get_flag ('#');
1645
1646 switch (dir.specifier)
1647 {
1648 case 'A':
1649 case 'a':
1650 {
1651 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1652 if (dir.prec[0] <= 0)
1653 minprec = 0;
1654 else if (dir.prec[0] > 0)
1655 minprec = dir.prec[0] + !radix /* decimal point */;
1656
1657 res.range.likely = (2 /* 0x */
1658 + flagmin
1659 + radix
1660 + minprec
1661 + 3 /* p+0 */);
1662
1663 res.range.max = format_floating_max (type, 'a', prec[1]);
1664
1665 /* The unlikely maximum accounts for the longest multibyte
1666 decimal point character. */
1667 res.range.unlikely = res.range.max;
1668 if (dir.prec[1] > 0)
1669 res.range.unlikely += target_mb_len_max () - 1;
1670
1671 break;
1672 }
1673
1674 case 'E':
1675 case 'e':
1676 {
1677 /* Minimum output attributable to precision and, when it's
1678 non-zero, decimal point. */
1679 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1680
1681 /* The likely minimum output is "[-+]1.234567e+00" regardless
1682 of the value of the actual argument. */
1683 res.range.likely = (flagmin
1684 + radix
1685 + minprec
1686 + 2 /* e+ */ + 2);
1687
1688 res.range.max = format_floating_max (type, 'e', prec[1]);
1689
1690 /* The unlikely maximum accounts for the longest multibyte
1691 decimal point character. */
1692 if (dir.prec[0] != dir.prec[1]
1693 || dir.prec[0] == -1 || dir.prec[0] > 0)
1694 res.range.unlikely = res.range.max + target_mb_len_max () -1;
1695 else
1696 res.range.unlikely = res.range.max;
1697 break;
1698 }
1699
1700 case 'F':
1701 case 'f':
1702 {
1703 /* Minimum output attributable to precision and, when it's non-zero,
1704 decimal point. */
1705 HOST_WIDE_INT minprec = prec[0] ? prec[0] + !radix : 0;
1706
1707 /* For finite numbers (i.e., not infinity or NaN) the lower bound
1708 when precision isn't specified is 8 bytes ("1.23456" since
1709 precision is taken to be 6). When precision is zero, the lower
1710 bound is 1 byte (e.g., "1"). Otherwise, when precision is greater
1711 than zero, then the lower bound is 2 plus precision (plus flags).
1712 But in all cases, the lower bound is no greater than 3. */
1713 unsigned HOST_WIDE_INT min = flagmin + radix + minprec;
1714 if (min < res.range.min)
1715 res.range.min = min;
1716
1717 /* Compute the upper bound for -TYPE_MAX. */
1718 res.range.max = format_floating_max (type, 'f', prec[1]);
1719
1720 /* The minimum output with unknown precision is a single byte
1721 (e.g., "0") but the more likely output is 3 bytes ("0.0"). */
1722 if (dir.prec[0] < 0 && dir.prec[1] > 0)
1723 res.range.likely = 3;
1724 else
1725 res.range.likely = min;
1726
1727 /* The unlikely maximum accounts for the longest multibyte
1728 decimal point character. */
1729 if (dir.prec[0] != dir.prec[1]
1730 || dir.prec[0] == -1 || dir.prec[0] > 0)
1731 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1732 break;
1733 }
1734
1735 case 'G':
1736 case 'g':
1737 {
1738 /* The %g output depends on precision and the exponent of
1739 the argument. Since the value of the argument isn't known
1740 the lower bound on the range of bytes (not counting flags
1741 or width) is 1 plus radix (i.e., either "0" or "0." for
1742 "%g" and "%#g", respectively, with a zero argument). */
1743 unsigned HOST_WIDE_INT min = flagmin + radix;
1744 if (min < res.range.min)
1745 res.range.min = min;
1746
1747 char spec = 'g';
1748 HOST_WIDE_INT maxprec = dir.prec[1];
1749 if (radix && maxprec)
1750 {
1751 /* When the pound flag (radix) is set, trailing zeros aren't
1752 trimmed and so the longest output is the same as for %e,
1753 except with precision minus 1 (as specified in C11). */
1754 spec = 'e';
1755 if (maxprec > 0)
1756 --maxprec;
1757 else if (maxprec < 0)
1758 maxprec = 5;
1759 }
1760 else
1761 maxprec = prec[1];
1762
1763 res.range.max = format_floating_max (type, spec, maxprec);
1764
1765 /* The likely output is either the maximum computed above
1766 minus 1 (assuming the maximum is positive) when precision
1767 is known (or unspecified), or the same minimum as for %e
1768 (which is computed for a non-negative argument). Unlike
1769 for the other specifiers above the likely output isn't
1770 the minimum because for %g that's 1 which is unlikely. */
1771 if (dir.prec[1] < 0
1772 || (unsigned HOST_WIDE_INT)dir.prec[1] < target_int_max ())
1773 res.range.likely = res.range.max - 1;
1774 else
1775 {
1776 HOST_WIDE_INT minprec = 6 + !radix /* decimal point */;
1777 res.range.likely = (flagmin
1778 + radix
1779 + minprec
1780 + 2 /* e+ */ + 2);
1781 }
1782
1783 /* The unlikely maximum accounts for the longest multibyte
1784 decimal point character. */
1785 res.range.unlikely = res.range.max + target_mb_len_max () - 1;
1786 break;
1787 }
1788
1789 default:
1790 return fmtresult ();
1791 }
1792
1793 /* Bump up the byte counters if WIDTH is greater. */
1794 res.adjust_for_width_or_precision (dir.width);
1795 return res;
1796 }
1797
1798 /* Return a range representing the minimum and maximum number of bytes
1799 that the directive DIR will write on output for the floating argument
1800 ARG. */
1801
1802 static fmtresult
1803 format_floating (const directive &dir, tree arg, vr_values *)
1804 {
1805 HOST_WIDE_INT prec[] = { dir.prec[0], dir.prec[1] };
1806 tree type = (dir.modifier == FMT_LEN_L || dir.modifier == FMT_LEN_ll
1807 ? long_double_type_node : double_type_node);
1808
1809 /* For an indeterminate precision the lower bound must be assumed
1810 to be zero. */
1811 if (TOUPPER (dir.specifier) == 'A')
1812 {
1813 /* Get the number of fractional decimal digits needed to represent
1814 the argument without a loss of accuracy. */
1815 unsigned fmtprec
1816 = REAL_MODE_FORMAT (TYPE_MODE (type))->p;
1817
1818 /* The precision of the IEEE 754 double format is 53.
1819 The precision of all other GCC binary double formats
1820 is 56 or less. */
1821 unsigned maxprec = fmtprec <= 56 ? 13 : 15;
1822
1823 /* For %a, leave the minimum precision unspecified to let
1824 MFPR trim trailing zeros (as it and many other systems
1825 including Glibc happen to do) and set the maximum
1826 precision to reflect what it would be with trailing zeros
1827 present (as Solaris and derived systems do). */
1828 if (dir.prec[1] < 0)
1829 {
1830 /* Both bounds are negative implies that precision has
1831 not been specified. */
1832 prec[0] = maxprec;
1833 prec[1] = -1;
1834 }
1835 else if (dir.prec[0] < 0)
1836 {
1837 /* With a negative lower bound and a non-negative upper
1838 bound set the minimum precision to zero and the maximum
1839 to the greater of the maximum precision (i.e., with
1840 trailing zeros present) and the specified upper bound. */
1841 prec[0] = 0;
1842 prec[1] = dir.prec[1] < maxprec ? maxprec : dir.prec[1];
1843 }
1844 }
1845 else if (dir.prec[0] < 0)
1846 {
1847 if (dir.prec[1] < 0)
1848 {
1849 /* A precision in a strictly negative range is ignored and
1850 the default of 6 is used instead. */
1851 prec[0] = prec[1] = 6;
1852 }
1853 else
1854 {
1855 /* For a precision in a partly negative range, the lower bound
1856 must be assumed to be zero and the new upper bound is the
1857 greater of 6 (the default precision used when the specified
1858 precision is negative) and the upper bound of the specified
1859 range. */
1860 prec[0] = 0;
1861 prec[1] = dir.prec[1] < 6 ? 6 : dir.prec[1];
1862 }
1863 }
1864
1865 if (!arg
1866 || TREE_CODE (arg) != REAL_CST
1867 || !useless_type_conversion_p (type, TREE_TYPE (arg)))
1868 return format_floating (dir, prec);
1869
1870 /* The minimum and maximum number of bytes produced by the directive. */
1871 fmtresult res;
1872
1873 /* Get the real type format desription for the target. */
1874 const REAL_VALUE_TYPE *rvp = TREE_REAL_CST_PTR (arg);
1875 const real_format *rfmt = REAL_MODE_FORMAT (TYPE_MODE (TREE_TYPE (arg)));
1876
1877 if (!real_isfinite (rvp))
1878 {
1879 /* The format for Infinity and NaN is "[-]inf"/"[-]infinity"
1880 and "[-]nan" with the choice being implementation-defined
1881 but not locale dependent. */
1882 bool sign = dir.get_flag ('+') || real_isneg (rvp);
1883 res.range.min = 3 + sign;
1884
1885 res.range.likely = res.range.min;
1886 res.range.max = res.range.min;
1887 /* The unlikely maximum is "[-/+]infinity" or "[-/+][qs]nan".
1888 For NaN, the C/POSIX standards specify two formats:
1889 "[-/+]nan"
1890 and
1891 "[-/+]nan(n-char-sequence)"
1892 No known printf implementation outputs the latter format but AIX
1893 outputs QNaN and SNaN for quiet and signalling NaN, respectively,
1894 so the unlikely maximum reflects that. */
1895 res.range.unlikely = sign + (real_isinf (rvp) ? 8 : 4);
1896
1897 /* The range for infinity and NaN is known unless either width
1898 or precision is unknown. Width has the same effect regardless
1899 of whether the argument is finite. Precision is either ignored
1900 (e.g., Glibc) or can have an effect on the short vs long format
1901 such as inf/infinity (e.g., Solaris). */
1902 res.knownrange = dir.known_width_and_precision ();
1903
1904 /* Adjust the range for width but ignore precision. */
1905 res.adjust_for_width_or_precision (dir.width);
1906
1907 return res;
1908 }
1909
1910 char fmtstr [40];
1911 char *pfmt = fmtstr;
1912
1913 /* Append flags. */
1914 for (const char *pf = "-+ #0"; *pf; ++pf)
1915 if (dir.get_flag (*pf))
1916 *pfmt++ = *pf;
1917
1918 *pfmt = '\0';
1919
1920 {
1921 /* Set up an array to easily iterate over. */
1922 unsigned HOST_WIDE_INT* const minmax[] = {
1923 &res.range.min, &res.range.max
1924 };
1925
1926 for (int i = 0; i != sizeof minmax / sizeof *minmax; ++i)
1927 {
1928 /* Convert the GCC real value representation with the precision
1929 of the real type to the mpfr_t format rounding down in the
1930 first iteration that computes the minimm and up in the second
1931 that computes the maximum. This order is arbibtrary because
1932 rounding in either direction can result in longer output. */
1933 mpfr_t mpfrval;
1934 mpfr_init2 (mpfrval, rfmt->p);
1935 mpfr_from_real (mpfrval, rvp, i ? GMP_RNDU : GMP_RNDD);
1936
1937 /* Use the MPFR rounding specifier to round down in the first
1938 iteration and then up. In most but not all cases this will
1939 result in the same number of bytes. */
1940 char rndspec = "DU"[i];
1941
1942 /* Format it and store the result in the corresponding member
1943 of the result struct. */
1944 *minmax[i] = get_mpfr_format_length (mpfrval, fmtstr, prec[i],
1945 dir.specifier, rndspec);
1946 mpfr_clear (mpfrval);
1947 }
1948 }
1949
1950 /* Make sure the minimum is less than the maximum (MPFR rounding
1951 in the call to mpfr_snprintf can result in the reverse. */
1952 if (res.range.max < res.range.min)
1953 {
1954 unsigned HOST_WIDE_INT tmp = res.range.min;
1955 res.range.min = res.range.max;
1956 res.range.max = tmp;
1957 }
1958
1959 /* The range is known unless either width or precision is unknown. */
1960 res.knownrange = dir.known_width_and_precision ();
1961
1962 /* For the same floating point constant, unless width or precision
1963 is unknown, use the longer output as the likely maximum since
1964 with round to nearest either is equally likely. Otheriwse, when
1965 precision is unknown, use the greater of the minimum and 3 as
1966 the likely output (for "0.0" since zero precision is unlikely). */
1967 if (res.knownrange)
1968 res.range.likely = res.range.max;
1969 else if (res.range.min < 3
1970 && dir.prec[0] < 0
1971 && (unsigned HOST_WIDE_INT)dir.prec[1] == target_int_max ())
1972 res.range.likely = 3;
1973 else
1974 res.range.likely = res.range.min;
1975
1976 res.range.unlikely = res.range.max;
1977
1978 if (res.range.max > 2 && (prec[0] != 0 || prec[1] != 0))
1979 {
1980 /* Unless the precision is zero output longer than 2 bytes may
1981 include the decimal point which must be a single character
1982 up to MB_LEN_MAX in length. This is overly conservative
1983 since in some conversions some constants result in no decimal
1984 point (e.g., in %g). */
1985 res.range.unlikely += target_mb_len_max () - 1;
1986 }
1987
1988 res.adjust_for_width_or_precision (dir.width);
1989 return res;
1990 }
1991
1992 /* Return a FMTRESULT struct set to the lengths of the shortest and longest
1993 strings referenced by the expression STR, or (-1, -1) when not known.
1994 Used by the format_string function below. */
1995
1996 static fmtresult
1997 get_string_length (tree str, unsigned eltsize)
1998 {
1999 if (!str)
2000 return fmtresult ();
2001
2002 /* Determine the length of the shortest and longest string referenced
2003 by STR. Strings of unknown lengths are bounded by the sizes of
2004 arrays that subexpressions of STR may refer to. Pointers that
2005 aren't known to point any such arrays result in LENRANGE[1] set
2006 to SIZE_MAX. */
2007 tree lenrange[2];
2008 bool flexarray = get_range_strlen (str, lenrange, eltsize);
2009
2010 if (lenrange [0] || lenrange [1])
2011 {
2012 HOST_WIDE_INT min
2013 = (tree_fits_uhwi_p (lenrange[0])
2014 ? tree_to_uhwi (lenrange[0])
2015 : 0);
2016
2017 HOST_WIDE_INT max
2018 = (tree_fits_uhwi_p (lenrange[1])
2019 ? tree_to_uhwi (lenrange[1])
2020 : HOST_WIDE_INT_M1U);
2021
2022 /* get_range_strlen() returns the target value of SIZE_MAX for
2023 strings of unknown length. Bump it up to HOST_WIDE_INT_M1U
2024 which may be bigger. */
2025 if ((unsigned HOST_WIDE_INT)min == target_size_max ())
2026 min = HOST_WIDE_INT_M1U;
2027 if ((unsigned HOST_WIDE_INT)max == target_size_max ())
2028 max = HOST_WIDE_INT_M1U;
2029
2030 fmtresult res (min, max);
2031
2032 /* Set RES.KNOWNRANGE to true if and only if all strings referenced
2033 by STR are known to be bounded (though not necessarily by their
2034 actual length but perhaps by their maximum possible length). */
2035 if (res.range.max < target_int_max ())
2036 {
2037 res.knownrange = true;
2038 /* When the the length of the longest string is known and not
2039 excessive use it as the likely length of the string(s). */
2040 res.range.likely = res.range.max;
2041 }
2042 else
2043 {
2044 /* When the upper bound is unknown (it can be zero or excessive)
2045 set the likely length to the greater of 1 and the length of
2046 the shortest string and reset the lower bound to zero. */
2047 res.range.likely = res.range.min ? res.range.min : warn_level > 1;
2048 res.range.min = 0;
2049 }
2050
2051 /* If the range of string length has been estimated from the size
2052 of an array at the end of a struct assume that it's longer than
2053 the array bound says it is in case it's used as a poor man's
2054 flexible array member, such as in struct S { char a[4]; }; */
2055 res.range.unlikely = flexarray ? HOST_WIDE_INT_MAX : res.range.max;
2056
2057 return res;
2058 }
2059
2060 return fmtresult ();
2061 }
2062
2063 /* Return the minimum and maximum number of characters formatted
2064 by the '%c' format directives and its wide character form for
2065 the argument ARG. ARG can be null (for functions such as
2066 vsprinf). */
2067
2068 static fmtresult
2069 format_character (const directive &dir, tree arg, vr_values *vr_values)
2070 {
2071 fmtresult res;
2072
2073 res.knownrange = true;
2074
2075 if (dir.specifier == 'C'
2076 || dir.modifier == FMT_LEN_l)
2077 {
2078 /* A wide character can result in as few as zero bytes. */
2079 res.range.min = 0;
2080
2081 HOST_WIDE_INT min, max;
2082 if (get_int_range (arg, &min, &max, false, 0, vr_values))
2083 {
2084 if (min == 0 && max == 0)
2085 {
2086 /* The NUL wide character results in no bytes. */
2087 res.range.max = 0;
2088 res.range.likely = 0;
2089 res.range.unlikely = 0;
2090 }
2091 else if (min >= 0 && min < 128)
2092 {
2093 /* Be conservative if the target execution character set
2094 is not a 1-to-1 mapping to the source character set or
2095 if the source set is not ASCII. */
2096 bool one_2_one_ascii
2097 = (target_to_host_charmap[0] == 1 && target_to_host ('a') == 97);
2098
2099 /* A wide character in the ASCII range most likely results
2100 in a single byte, and only unlikely in up to MB_LEN_MAX. */
2101 res.range.max = one_2_one_ascii ? 1 : target_mb_len_max ();;
2102 res.range.likely = 1;
2103 res.range.unlikely = target_mb_len_max ();
2104 res.mayfail = !one_2_one_ascii;
2105 }
2106 else
2107 {
2108 /* A wide character outside the ASCII range likely results
2109 in up to two bytes, and only unlikely in up to MB_LEN_MAX. */
2110 res.range.max = target_mb_len_max ();
2111 res.range.likely = 2;
2112 res.range.unlikely = res.range.max;
2113 /* Converting such a character may fail. */
2114 res.mayfail = true;
2115 }
2116 }
2117 else
2118 {
2119 /* An unknown wide character is treated the same as a wide
2120 character outside the ASCII range. */
2121 res.range.max = target_mb_len_max ();
2122 res.range.likely = 2;
2123 res.range.unlikely = res.range.max;
2124 res.mayfail = true;
2125 }
2126 }
2127 else
2128 {
2129 /* A plain '%c' directive. Its ouput is exactly 1. */
2130 res.range.min = res.range.max = 1;
2131 res.range.likely = res.range.unlikely = 1;
2132 res.knownrange = true;
2133 }
2134
2135 /* Bump up the byte counters if WIDTH is greater. */
2136 return res.adjust_for_width_or_precision (dir.width);
2137 }
2138
2139 /* Return the minimum and maximum number of characters formatted
2140 by the '%s' format directive and its wide character form for
2141 the argument ARG. ARG can be null (for functions such as
2142 vsprinf). */
2143
2144 static fmtresult
2145 format_string (const directive &dir, tree arg, vr_values *)
2146 {
2147 fmtresult res;
2148
2149 /* Compute the range the argument's length can be in. */
2150 int count_by = dir.specifier == 'S' || dir.modifier == FMT_LEN_l ? 4 : 1;
2151 fmtresult slen = get_string_length (arg, count_by);
2152 if (slen.range.min == slen.range.max
2153 && slen.range.min < HOST_WIDE_INT_MAX)
2154 {
2155 /* The argument is either a string constant or it refers
2156 to one of a number of strings of the same length. */
2157
2158 /* A '%s' directive with a string argument with constant length. */
2159 res.range = slen.range;
2160
2161 if (dir.specifier == 'S'
2162 || dir.modifier == FMT_LEN_l)
2163 {
2164 /* In the worst case the length of output of a wide string S
2165 is bounded by MB_LEN_MAX * wcslen (S). */
2166 res.range.max *= target_mb_len_max ();
2167 res.range.unlikely = res.range.max;
2168 /* It's likely that the the total length is not more that
2169 2 * wcslen (S).*/
2170 res.range.likely = res.range.min * 2;
2171
2172 if (dir.prec[1] >= 0
2173 && (unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2174 {
2175 res.range.max = dir.prec[1];
2176 res.range.likely = dir.prec[1];
2177 res.range.unlikely = dir.prec[1];
2178 }
2179
2180 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2181 res.range.min = 0;
2182 else if (dir.prec[0] >= 0)
2183 res.range.likely = dir.prec[0];
2184
2185 /* Even a non-empty wide character string need not convert into
2186 any bytes. */
2187 res.range.min = 0;
2188
2189 /* A non-empty wide character conversion may fail. */
2190 if (slen.range.max > 0)
2191 res.mayfail = true;
2192 }
2193 else
2194 {
2195 res.knownrange = true;
2196
2197 if (dir.prec[0] < 0 && dir.prec[1] > -1)
2198 res.range.min = 0;
2199 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < res.range.min)
2200 res.range.min = dir.prec[0];
2201
2202 if ((unsigned HOST_WIDE_INT)dir.prec[1] < res.range.max)
2203 {
2204 res.range.max = dir.prec[1];
2205 res.range.likely = dir.prec[1];
2206 res.range.unlikely = dir.prec[1];
2207 }
2208 }
2209 }
2210 else if (arg && integer_zerop (arg))
2211 {
2212 /* Handle null pointer argument. */
2213
2214 fmtresult res (0);
2215 res.nullp = true;
2216 return res;
2217 }
2218 else
2219 {
2220 /* For a '%s' and '%ls' directive with a non-constant string (either
2221 one of a number of strings of known length or an unknown string)
2222 the minimum number of characters is lesser of PRECISION[0] and
2223 the length of the shortest known string or zero, and the maximum
2224 is the lessser of the length of the longest known string or
2225 PTRDIFF_MAX and PRECISION[1]. The likely length is either
2226 the minimum at level 1 and the greater of the minimum and 1
2227 at level 2. This result is adjust upward for width (if it's
2228 specified). */
2229
2230 if (dir.specifier == 'S'
2231 || dir.modifier == FMT_LEN_l)
2232 {
2233 /* A wide character converts to as few as zero bytes. */
2234 slen.range.min = 0;
2235 if (slen.range.max < target_int_max ())
2236 slen.range.max *= target_mb_len_max ();
2237
2238 if (slen.range.likely < target_int_max ())
2239 slen.range.likely *= 2;
2240
2241 if (slen.range.likely < target_int_max ())
2242 slen.range.unlikely *= target_mb_len_max ();
2243
2244 /* A non-empty wide character conversion may fail. */
2245 if (slen.range.max > 0)
2246 res.mayfail = true;
2247 }
2248
2249 res.range = slen.range;
2250
2251 if (dir.prec[0] >= 0)
2252 {
2253 /* Adjust the minimum to zero if the string length is unknown,
2254 or at most the lower bound of the precision otherwise. */
2255 if (slen.range.min >= target_int_max ())
2256 res.range.min = 0;
2257 else if ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.min)
2258 res.range.min = dir.prec[0];
2259
2260 /* Make both maxima no greater than the upper bound of precision. */
2261 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max
2262 || slen.range.max >= target_int_max ())
2263 {
2264 res.range.max = dir.prec[1];
2265 res.range.unlikely = dir.prec[1];
2266 }
2267
2268 /* If precision is constant, set the likely counter to the lesser
2269 of it and the maximum string length. Otherwise, if the lower
2270 bound of precision is greater than zero, set the likely counter
2271 to the minimum. Otherwise set it to zero or one based on
2272 the warning level. */
2273 if (dir.prec[0] == dir.prec[1])
2274 res.range.likely
2275 = ((unsigned HOST_WIDE_INT)dir.prec[0] < slen.range.max
2276 ? dir.prec[0] : slen.range.max);
2277 else if (dir.prec[0] > 0)
2278 res.range.likely = res.range.min;
2279 else
2280 res.range.likely = warn_level > 1;
2281 }
2282 else if (dir.prec[1] >= 0)
2283 {
2284 res.range.min = 0;
2285 if ((unsigned HOST_WIDE_INT)dir.prec[1] < slen.range.max)
2286 res.range.max = dir.prec[1];
2287 res.range.likely = dir.prec[1] ? warn_level > 1 : 0;
2288 }
2289 else if (slen.range.min >= target_int_max ())
2290 {
2291 res.range.min = 0;
2292 res.range.max = HOST_WIDE_INT_MAX;
2293 /* At level 1 strings of unknown length are assumed to be
2294 empty, while at level 1 they are assumed to be one byte
2295 long. */
2296 res.range.likely = warn_level > 1;
2297 }
2298 else
2299 {
2300 /* A string of unknown length unconstrained by precision is
2301 assumed to be empty at level 1 and just one character long
2302 at higher levels. */
2303 if (res.range.likely >= target_int_max ())
2304 res.range.likely = warn_level > 1;
2305 }
2306
2307 res.range.unlikely = res.range.max;
2308 }
2309
2310 /* Bump up the byte counters if WIDTH is greater. */
2311 return res.adjust_for_width_or_precision (dir.width);
2312 }
2313
2314 /* Format plain string (part of the format string itself). */
2315
2316 static fmtresult
2317 format_plain (const directive &dir, tree, vr_values *)
2318 {
2319 fmtresult res (dir.len);
2320 return res;
2321 }
2322
2323 /* Return true if the RESULT of a directive in a call describe by INFO
2324 should be diagnosed given the AVAILable space in the destination. */
2325
2326 static bool
2327 should_warn_p (const sprintf_dom_walker::call_info &info,
2328 const result_range &avail, const result_range &result)
2329 {
2330 if (result.max <= avail.min)
2331 {
2332 /* The least amount of space remaining in the destination is big
2333 enough for the longest output. */
2334 return false;
2335 }
2336
2337 if (info.bounded)
2338 {
2339 if (warn_format_trunc == 1 && result.min <= avail.max
2340 && info.retval_used ())
2341 {
2342 /* The likely amount of space remaining in the destination is big
2343 enough for the least output and the return value is used. */
2344 return false;
2345 }
2346
2347 if (warn_format_trunc == 1 && result.likely <= avail.likely
2348 && !info.retval_used ())
2349 {
2350 /* The likely amount of space remaining in the destination is big
2351 enough for the likely output and the return value is unused. */
2352 return false;
2353 }
2354
2355 if (warn_format_trunc == 2
2356 && result.likely <= avail.min
2357 && (result.max <= avail.min
2358 || result.max > HOST_WIDE_INT_MAX))
2359 {
2360 /* The minimum amount of space remaining in the destination is big
2361 enough for the longest output. */
2362 return false;
2363 }
2364 }
2365 else
2366 {
2367 if (warn_level == 1 && result.likely <= avail.likely)
2368 {
2369 /* The likely amount of space remaining in the destination is big
2370 enough for the likely output. */
2371 return false;
2372 }
2373
2374 if (warn_level == 2
2375 && result.likely <= avail.min
2376 && (result.max <= avail.min
2377 || result.max > HOST_WIDE_INT_MAX))
2378 {
2379 /* The minimum amount of space remaining in the destination is big
2380 enough for the longest output. */
2381 return false;
2382 }
2383 }
2384
2385 return true;
2386 }
2387
2388 /* At format string location describe by DIRLOC in a call described
2389 by INFO, issue a warning for a directive DIR whose output may be
2390 in excess of the available space AVAIL_RANGE in the destination
2391 given the formatting result FMTRES. This function does nothing
2392 except decide whether to issue a warning for a possible write
2393 past the end or truncation and, if so, format the warning.
2394 Return true if a warning has been issued. */
2395
2396 static bool
2397 maybe_warn (substring_loc &dirloc, location_t argloc,
2398 const sprintf_dom_walker::call_info &info,
2399 const result_range &avail_range, const result_range &res,
2400 const directive &dir)
2401 {
2402 if (!should_warn_p (info, avail_range, res))
2403 return false;
2404
2405 /* A warning will definitely be issued below. */
2406
2407 /* The maximum byte count to reference in the warning. Larger counts
2408 imply that the upper bound is unknown (and could be anywhere between
2409 RES.MIN + 1 and SIZE_MAX / 2) are printed as "N or more bytes" rather
2410 than "between N and X" where X is some huge number. */
2411 unsigned HOST_WIDE_INT maxbytes = target_dir_max ();
2412
2413 /* True when there is enough room in the destination for the least
2414 amount of a directive's output but not enough for its likely or
2415 maximum output. */
2416 bool maybe = (res.min <= avail_range.max
2417 && (avail_range.min < res.likely
2418 || (res.max < HOST_WIDE_INT_MAX
2419 && avail_range.min < res.max)));
2420
2421 /* Buffer for the directive in the host character set (used when
2422 the source character set is different). */
2423 char hostdir[32];
2424
2425 if (avail_range.min == avail_range.max)
2426 {
2427 /* The size of the destination region is exact. */
2428 unsigned HOST_WIDE_INT navail = avail_range.max;
2429
2430 if (target_to_host (*dir.beg) != '%')
2431 {
2432 /* For plain character directives (i.e., the format string itself)
2433 but not others, point the caret at the first character that's
2434 past the end of the destination. */
2435 if (navail < dir.len)
2436 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2437 }
2438
2439 if (*dir.beg == '\0')
2440 {
2441 /* This is the terminating nul. */
2442 gcc_assert (res.min == 1 && res.min == res.max);
2443
2444 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2445 info.bounded
2446 ? (maybe
2447 ? G_("%qE output may be truncated before the "
2448 "last format character")
2449 : G_("%qE output truncated before the last "
2450 "format character"))
2451 : (maybe
2452 ? G_("%qE may write a terminating nul past the "
2453 "end of the destination")
2454 : G_("%qE writing a terminating nul past the "
2455 "end of the destination")),
2456 info.func);
2457 }
2458
2459 if (res.min == res.max)
2460 {
2461 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2462 if (!info.bounded)
2463 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2464 "%<%.*s%> directive writing %wu byte into a "
2465 "region of size %wu",
2466 "%<%.*s%> directive writing %wu bytes into a "
2467 "region of size %wu",
2468 (int) dir.len, d, res.min, navail);
2469 else if (maybe)
2470 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2471 "%<%.*s%> directive output may be truncated "
2472 "writing %wu byte into a region of size %wu",
2473 "%<%.*s%> directive output may be truncated "
2474 "writing %wu bytes into a region of size %wu",
2475 (int) dir.len, d, res.min, navail);
2476 else
2477 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2478 "%<%.*s%> directive output truncated writing "
2479 "%wu byte into a region of size %wu",
2480 "%<%.*s%> directive output truncated writing "
2481 "%wu bytes into a region of size %wu",
2482 (int) dir.len, d, res.min, navail);
2483 }
2484 if (res.min == 0 && res.max < maxbytes)
2485 return fmtwarn (dirloc, argloc, NULL,
2486 info.warnopt (),
2487 info.bounded
2488 ? (maybe
2489 ? G_("%<%.*s%> directive output may be truncated "
2490 "writing up to %wu bytes into a region of "
2491 "size %wu")
2492 : G_("%<%.*s%> directive output truncated writing "
2493 "up to %wu bytes into a region of size %wu"))
2494 : G_("%<%.*s%> directive writing up to %wu bytes "
2495 "into a region of size %wu"), (int) dir.len,
2496 target_to_host (hostdir, sizeof hostdir, dir.beg),
2497 res.max, navail);
2498
2499 if (res.min == 0 && maxbytes <= res.max)
2500 /* This is a special case to avoid issuing the potentially
2501 confusing warning:
2502 writing 0 or more bytes into a region of size 0. */
2503 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2504 info.bounded
2505 ? (maybe
2506 ? G_("%<%.*s%> directive output may be truncated "
2507 "writing likely %wu or more bytes into a "
2508 "region of size %wu")
2509 : G_("%<%.*s%> directive output truncated writing "
2510 "likely %wu or more bytes into a region of "
2511 "size %wu"))
2512 : G_("%<%.*s%> directive writing likely %wu or more "
2513 "bytes into a region of size %wu"), (int) dir.len,
2514 target_to_host (hostdir, sizeof hostdir, dir.beg),
2515 res.likely, navail);
2516
2517 if (res.max < maxbytes)
2518 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2519 info.bounded
2520 ? (maybe
2521 ? G_("%<%.*s%> directive output may be truncated "
2522 "writing between %wu and %wu bytes into a "
2523 "region of size %wu")
2524 : G_("%<%.*s%> directive output truncated "
2525 "writing between %wu and %wu bytes into a "
2526 "region of size %wu"))
2527 : G_("%<%.*s%> directive writing between %wu and "
2528 "%wu bytes into a region of size %wu"),
2529 (int) dir.len,
2530 target_to_host (hostdir, sizeof hostdir, dir.beg),
2531 res.min, res.max, navail);
2532
2533 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2534 info.bounded
2535 ? (maybe
2536 ? G_("%<%.*s%> directive output may be truncated "
2537 "writing %wu or more bytes into a region of "
2538 "size %wu")
2539 : G_("%<%.*s%> directive output truncated writing "
2540 "%wu or more bytes into a region of size %wu"))
2541 : G_("%<%.*s%> directive writing %wu or more bytes "
2542 "into a region of size %wu"), (int) dir.len,
2543 target_to_host (hostdir, sizeof hostdir, dir.beg),
2544 res.min, navail);
2545 }
2546
2547 /* The size of the destination region is a range. */
2548
2549 if (target_to_host (*dir.beg) != '%')
2550 {
2551 unsigned HOST_WIDE_INT navail = avail_range.max;
2552
2553 /* For plain character directives (i.e., the format string itself)
2554 but not others, point the caret at the first character that's
2555 past the end of the destination. */
2556 if (navail < dir.len)
2557 dirloc.set_caret_index (dirloc.get_caret_idx () + navail);
2558 }
2559
2560 if (*dir.beg == '\0')
2561 {
2562 gcc_assert (res.min == 1 && res.min == res.max);
2563
2564 return fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
2565 info.bounded
2566 ? (maybe
2567 ? G_("%qE output may be truncated before the last "
2568 "format character")
2569 : G_("%qE output truncated before the last format "
2570 "character"))
2571 : (maybe
2572 ? G_("%qE may write a terminating nul past the end "
2573 "of the destination")
2574 : G_("%qE writing a terminating nul past the end "
2575 "of the destination")), info.func);
2576 }
2577
2578 if (res.min == res.max)
2579 {
2580 const char *d = target_to_host (hostdir, sizeof hostdir, dir.beg);
2581 if (!info.bounded)
2582 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2583 "%<%.*s%> directive writing %wu byte into a region "
2584 "of size between %wu and %wu",
2585 "%<%.*s%> directive writing %wu bytes into a region "
2586 "of size between %wu and %wu", (int) dir.len, d,
2587 res.min, avail_range.min, avail_range.max);
2588 else if (maybe)
2589 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2590 "%<%.*s%> directive output may be truncated writing "
2591 "%wu byte into a region of size between %wu and %wu",
2592 "%<%.*s%> directive output may be truncated writing "
2593 "%wu bytes into a region of size between %wu and "
2594 "%wu", (int) dir.len, d, res.min, avail_range.min,
2595 avail_range.max);
2596 else
2597 return fmtwarn_n (dirloc, argloc, NULL, info.warnopt (), res.min,
2598 "%<%.*s%> directive output truncated writing %wu "
2599 "byte into a region of size between %wu and %wu",
2600 "%<%.*s%> directive output truncated writing %wu "
2601 "bytes into a region of size between %wu and %wu",
2602 (int) dir.len, d, res.min, avail_range.min,
2603 avail_range.max);
2604 }
2605
2606 if (res.min == 0 && res.max < maxbytes)
2607 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2608 info.bounded
2609 ? (maybe
2610 ? G_("%<%.*s%> directive output may be truncated "
2611 "writing up to %wu bytes into a region of size "
2612 "between %wu and %wu")
2613 : G_("%<%.*s%> directive output truncated writing "
2614 "up to %wu bytes into a region of size between "
2615 "%wu and %wu"))
2616 : G_("%<%.*s%> directive writing up to %wu bytes "
2617 "into a region of size between %wu and %wu"),
2618 (int) dir.len,
2619 target_to_host (hostdir, sizeof hostdir, dir.beg),
2620 res.max, avail_range.min, avail_range.max);
2621
2622 if (res.min == 0 && maxbytes <= res.max)
2623 /* This is a special case to avoid issuing the potentially confusing
2624 warning:
2625 writing 0 or more bytes into a region of size between 0 and N. */
2626 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2627 info.bounded
2628 ? (maybe
2629 ? G_("%<%.*s%> directive output may be truncated "
2630 "writing likely %wu or more bytes into a region "
2631 "of size between %wu and %wu")
2632 : G_("%<%.*s%> directive output truncated writing "
2633 "likely %wu or more bytes into a region of size "
2634 "between %wu and %wu"))
2635 : G_("%<%.*s%> directive writing likely %wu or more bytes "
2636 "into a region of size between %wu and %wu"),
2637 (int) dir.len,
2638 target_to_host (hostdir, sizeof hostdir, dir.beg),
2639 res.likely, avail_range.min, avail_range.max);
2640
2641 if (res.max < maxbytes)
2642 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2643 info.bounded
2644 ? (maybe
2645 ? G_("%<%.*s%> directive output may be truncated "
2646 "writing between %wu and %wu bytes into a region "
2647 "of size between %wu and %wu")
2648 : G_("%<%.*s%> directive output truncated writing "
2649 "between %wu and %wu bytes into a region of size "
2650 "between %wu and %wu"))
2651 : G_("%<%.*s%> directive writing between %wu and "
2652 "%wu bytes into a region of size between %wu and "
2653 "%wu"), (int) dir.len,
2654 target_to_host (hostdir, sizeof hostdir, dir.beg),
2655 res.min, res.max, avail_range.min, avail_range.max);
2656
2657 return fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2658 info.bounded
2659 ? (maybe
2660 ? G_("%<%.*s%> directive output may be truncated writing "
2661 "%wu or more bytes into a region of size between "
2662 "%wu and %wu")
2663 : G_("%<%.*s%> directive output truncated writing "
2664 "%wu or more bytes into a region of size between "
2665 "%wu and %wu"))
2666 : G_("%<%.*s%> directive writing %wu or more bytes "
2667 "into a region of size between %wu and %wu"),
2668 (int) dir.len,
2669 target_to_host (hostdir, sizeof hostdir, dir.beg),
2670 res.min, avail_range.min, avail_range.max);
2671 }
2672
2673 /* Compute the length of the output resulting from the directive DIR
2674 in a call described by INFO and update the overall result of the call
2675 in *RES. Return true if the directive has been handled. */
2676
2677 static bool
2678 format_directive (const sprintf_dom_walker::call_info &info,
2679 format_result *res, const directive &dir,
2680 class vr_values *vr_values)
2681 {
2682 /* Offset of the beginning of the directive from the beginning
2683 of the format string. */
2684 size_t offset = dir.beg - info.fmtstr;
2685 size_t start = offset;
2686 size_t length = offset + dir.len - !!dir.len;
2687
2688 /* Create a location for the whole directive from the % to the format
2689 specifier. */
2690 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
2691 offset, start, length);
2692
2693 /* Also get the location of the argument if possible.
2694 This doesn't work for integer literals or function calls. */
2695 location_t argloc = UNKNOWN_LOCATION;
2696 if (dir.arg)
2697 argloc = EXPR_LOCATION (dir.arg);
2698
2699 /* Bail when there is no function to compute the output length,
2700 or when minimum length checking has been disabled. */
2701 if (!dir.fmtfunc || res->range.min >= HOST_WIDE_INT_MAX)
2702 return false;
2703
2704 /* Compute the range of lengths of the formatted output. */
2705 fmtresult fmtres = dir.fmtfunc (dir, dir.arg, vr_values);
2706
2707 /* Record whether the output of all directives is known to be
2708 bounded by some maximum, implying that their arguments are
2709 either known exactly or determined to be in a known range
2710 or, for strings, limited by the upper bounds of the arrays
2711 they refer to. */
2712 res->knownrange &= fmtres.knownrange;
2713
2714 if (!fmtres.knownrange)
2715 {
2716 /* Only when the range is known, check it against the host value
2717 of INT_MAX + (the number of bytes of the "%.*Lf" directive with
2718 INT_MAX precision, which is the longest possible output of any
2719 single directive). That's the largest valid byte count (though
2720 not valid call to a printf-like function because it can never
2721 return such a count). Otherwise, the range doesn't correspond
2722 to known values of the argument. */
2723 if (fmtres.range.max > target_dir_max ())
2724 {
2725 /* Normalize the MAX counter to avoid having to deal with it
2726 later. The counter can be less than HOST_WIDE_INT_M1U
2727 when compiling for an ILP32 target on an LP64 host. */
2728 fmtres.range.max = HOST_WIDE_INT_M1U;
2729 /* Disable exact and maximum length checking after a failure
2730 to determine the maximum number of characters (for example
2731 for wide characters or wide character strings) but continue
2732 tracking the minimum number of characters. */
2733 res->range.max = HOST_WIDE_INT_M1U;
2734 }
2735
2736 if (fmtres.range.min > target_dir_max ())
2737 {
2738 /* Disable exact length checking after a failure to determine
2739 even the minimum number of characters (it shouldn't happen
2740 except in an error) but keep tracking the minimum and maximum
2741 number of characters. */
2742 return true;
2743 }
2744 }
2745
2746 /* Buffer for the directive in the host character set (used when
2747 the source character set is different). */
2748 char hostdir[32];
2749
2750 int dirlen = dir.len;
2751
2752 if (fmtres.nullp)
2753 {
2754 fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2755 "%<%.*s%> directive argument is null",
2756 dirlen, target_to_host (hostdir, sizeof hostdir, dir.beg));
2757
2758 /* Don't bother processing the rest of the format string. */
2759 res->warned = true;
2760 res->range.min = HOST_WIDE_INT_M1U;
2761 res->range.max = HOST_WIDE_INT_M1U;
2762 return false;
2763 }
2764
2765 /* Compute the number of available bytes in the destination. There
2766 must always be at least one byte of space for the terminating
2767 NUL that's appended after the format string has been processed. */
2768 result_range avail_range = bytes_remaining (info.objsize, *res);
2769
2770 bool warned = res->warned;
2771
2772 if (!warned)
2773 warned = maybe_warn (dirloc, argloc, info, avail_range,
2774 fmtres.range, dir);
2775
2776 /* Bump up the total maximum if it isn't too big. */
2777 if (res->range.max < HOST_WIDE_INT_MAX
2778 && fmtres.range.max < HOST_WIDE_INT_MAX)
2779 res->range.max += fmtres.range.max;
2780
2781 /* Raise the total unlikely maximum by the larger of the maximum
2782 and the unlikely maximum. */
2783 unsigned HOST_WIDE_INT save = res->range.unlikely;
2784 if (fmtres.range.max < fmtres.range.unlikely)
2785 res->range.unlikely += fmtres.range.unlikely;
2786 else
2787 res->range.unlikely += fmtres.range.max;
2788
2789 if (res->range.unlikely < save)
2790 res->range.unlikely = HOST_WIDE_INT_M1U;
2791
2792 res->range.min += fmtres.range.min;
2793 res->range.likely += fmtres.range.likely;
2794
2795 /* Has the minimum directive output length exceeded the maximum
2796 of 4095 bytes required to be supported? */
2797 bool minunder4k = fmtres.range.min < 4096;
2798 bool maxunder4k = fmtres.range.max < 4096;
2799 /* Clear POSUNDER4K in the overall result if the maximum has exceeded
2800 the 4k (this is necessary to avoid the return value optimization
2801 that may not be safe in the maximum case). */
2802 if (!maxunder4k)
2803 res->posunder4k = false;
2804 /* Also clear POSUNDER4K if the directive may fail. */
2805 if (fmtres.mayfail)
2806 res->posunder4k = false;
2807
2808 if (!warned
2809 /* Only warn at level 2. */
2810 && warn_level > 1
2811 && (!minunder4k
2812 || (!maxunder4k && fmtres.range.max < HOST_WIDE_INT_MAX)))
2813 {
2814 /* The directive output may be longer than the maximum required
2815 to be handled by an implementation according to 7.21.6.1, p15
2816 of C11. Warn on this only at level 2 but remember this and
2817 prevent folding the return value when done. This allows for
2818 the possibility of the actual libc call failing due to ENOMEM
2819 (like Glibc does under some conditions). */
2820
2821 if (fmtres.range.min == fmtres.range.max)
2822 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2823 "%<%.*s%> directive output of %wu bytes exceeds "
2824 "minimum required size of 4095", dirlen,
2825 target_to_host (hostdir, sizeof hostdir, dir.beg),
2826 fmtres.range.min);
2827 else
2828 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2829 minunder4k
2830 ? G_("%<%.*s%> directive output between %wu and %wu "
2831 "bytes may exceed minimum required size of "
2832 "4095")
2833 : G_("%<%.*s%> directive output between %wu and %wu "
2834 "bytes exceeds minimum required size of 4095"),
2835 dirlen,
2836 target_to_host (hostdir, sizeof hostdir, dir.beg),
2837 fmtres.range.min, fmtres.range.max);
2838 }
2839
2840 /* Has the likely and maximum directive output exceeded INT_MAX? */
2841 bool likelyximax = *dir.beg && res->range.likely > target_int_max ();
2842 /* Don't consider the maximum to be in excess when it's the result
2843 of a string of unknown length (i.e., whose maximum has been set
2844 to be greater than or equal to HOST_WIDE_INT_MAX. */
2845 bool maxximax = (*dir.beg
2846 && res->range.max > target_int_max ()
2847 && res->range.max < HOST_WIDE_INT_MAX);
2848
2849 if (!warned
2850 /* Warn for the likely output size at level 1. */
2851 && (likelyximax
2852 /* But only warn for the maximum at level 2. */
2853 || (warn_level > 1
2854 && maxximax
2855 && fmtres.range.max < HOST_WIDE_INT_MAX)))
2856 {
2857 /* The directive output causes the total length of output
2858 to exceed INT_MAX bytes. */
2859
2860 if (fmtres.range.min == fmtres.range.max)
2861 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2862 "%<%.*s%> directive output of %wu bytes causes "
2863 "result to exceed %<INT_MAX%>", dirlen,
2864 target_to_host (hostdir, sizeof hostdir, dir.beg),
2865 fmtres.range.min);
2866 else
2867 warned = fmtwarn (dirloc, argloc, NULL, info.warnopt (),
2868 fmtres.range.min > target_int_max ()
2869 ? G_("%<%.*s%> directive output between %wu and "
2870 "%wu bytes causes result to exceed "
2871 "%<INT_MAX%>")
2872 : G_("%<%.*s%> directive output between %wu and "
2873 "%wu bytes may cause result to exceed "
2874 "%<INT_MAX%>"), dirlen,
2875 target_to_host (hostdir, sizeof hostdir, dir.beg),
2876 fmtres.range.min, fmtres.range.max);
2877 }
2878
2879 if (warned && fmtres.range.min < fmtres.range.likely
2880 && fmtres.range.likely < fmtres.range.max)
2881 inform_n (info.fmtloc, fmtres.range.likely,
2882 "assuming directive output of %wu byte",
2883 "assuming directive output of %wu bytes",
2884 fmtres.range.likely);
2885
2886 if (warned && fmtres.argmin)
2887 {
2888 if (fmtres.argmin == fmtres.argmax)
2889 inform (info.fmtloc, "directive argument %qE", fmtres.argmin);
2890 else if (fmtres.knownrange)
2891 inform (info.fmtloc, "directive argument in the range [%E, %E]",
2892 fmtres.argmin, fmtres.argmax);
2893 else
2894 inform (info.fmtloc,
2895 "using the range [%E, %E] for directive argument",
2896 fmtres.argmin, fmtres.argmax);
2897 }
2898
2899 res->warned |= warned;
2900
2901 if (!dir.beg[0] && res->warned && info.objsize < HOST_WIDE_INT_MAX)
2902 {
2903 /* If a warning has been issued for buffer overflow or truncation
2904 (but not otherwise) help the user figure out how big a buffer
2905 they need. */
2906
2907 location_t callloc = gimple_location (info.callstmt);
2908
2909 unsigned HOST_WIDE_INT min = res->range.min;
2910 unsigned HOST_WIDE_INT max = res->range.max;
2911
2912 if (min == max)
2913 inform (callloc,
2914 (min == 1
2915 ? G_("%qE output %wu byte into a destination of size %wu")
2916 : G_("%qE output %wu bytes into a destination of size %wu")),
2917 info.func, min, info.objsize);
2918 else if (max < HOST_WIDE_INT_MAX)
2919 inform (callloc,
2920 "%qE output between %wu and %wu bytes into "
2921 "a destination of size %wu",
2922 info.func, min, max, info.objsize);
2923 else if (min < res->range.likely && res->range.likely < max)
2924 inform (callloc,
2925 "%qE output %wu or more bytes (assuming %wu) into "
2926 "a destination of size %wu",
2927 info.func, min, res->range.likely, info.objsize);
2928 else
2929 inform (callloc,
2930 "%qE output %wu or more bytes into a destination of size %wu",
2931 info.func, min, info.objsize);
2932 }
2933
2934 if (dump_file && *dir.beg)
2935 {
2936 fprintf (dump_file,
2937 " Result: "
2938 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
2939 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC " ("
2940 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ", "
2941 HOST_WIDE_INT_PRINT_DEC ", " HOST_WIDE_INT_PRINT_DEC ")\n",
2942 fmtres.range.min, fmtres.range.likely,
2943 fmtres.range.max, fmtres.range.unlikely,
2944 res->range.min, res->range.likely,
2945 res->range.max, res->range.unlikely);
2946 }
2947
2948 return true;
2949 }
2950
2951 /* Parse a format directive in function call described by INFO starting
2952 at STR and populate DIR structure. Bump up *ARGNO by the number of
2953 arguments extracted for the directive. Return the length of
2954 the directive. */
2955
2956 static size_t
2957 parse_directive (sprintf_dom_walker::call_info &info,
2958 directive &dir, format_result *res,
2959 const char *str, unsigned *argno,
2960 vr_values *vr_values)
2961 {
2962 const char *pcnt = strchr (str, target_percent);
2963 dir.beg = str;
2964
2965 if (size_t len = pcnt ? pcnt - str : *str ? strlen (str) : 1)
2966 {
2967 /* This directive is either a plain string or the terminating nul
2968 (which isn't really a directive but it simplifies things to
2969 handle it as if it were). */
2970 dir.len = len;
2971 dir.fmtfunc = format_plain;
2972
2973 if (dump_file)
2974 {
2975 fprintf (dump_file, " Directive %u at offset "
2976 HOST_WIDE_INT_PRINT_UNSIGNED ": \"%.*s\", "
2977 "length = " HOST_WIDE_INT_PRINT_UNSIGNED "\n",
2978 dir.dirno,
2979 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
2980 (int)dir.len, dir.beg, (unsigned HOST_WIDE_INT) dir.len);
2981 }
2982
2983 return len - !*str;
2984 }
2985
2986 const char *pf = pcnt + 1;
2987
2988 /* POSIX numbered argument index or zero when none. */
2989 HOST_WIDE_INT dollar = 0;
2990
2991 /* With and precision. -1 when not specified, HOST_WIDE_INT_MIN
2992 when given by a va_list argument, and a non-negative value
2993 when specified in the format string itself. */
2994 HOST_WIDE_INT width = -1;
2995 HOST_WIDE_INT precision = -1;
2996
2997 /* Pointers to the beginning of the width and precision decimal
2998 string (if any) within the directive. */
2999 const char *pwidth = 0;
3000 const char *pprec = 0;
3001
3002 /* When the value of the decimal string that specifies width or
3003 precision is out of range, points to the digit that causes
3004 the value to exceed the limit. */
3005 const char *werange = NULL;
3006 const char *perange = NULL;
3007
3008 /* Width specified via the asterisk. Need not be INTEGER_CST.
3009 For vararg functions set to void_node. */
3010 tree star_width = NULL_TREE;
3011
3012 /* Width specified via the asterisk. Need not be INTEGER_CST.
3013 For vararg functions set to void_node. */
3014 tree star_precision = NULL_TREE;
3015
3016 if (ISDIGIT (target_to_host (*pf)))
3017 {
3018 /* This could be either a POSIX positional argument, the '0'
3019 flag, or a width, depending on what follows. Store it as
3020 width and sort it out later after the next character has
3021 been seen. */
3022 pwidth = pf;
3023 width = target_strtol10 (&pf, &werange);
3024 }
3025 else if (target_to_host (*pf) == '*')
3026 {
3027 /* Similarly to the block above, this could be either a POSIX
3028 positional argument or a width, depending on what follows. */
3029 if (*argno < gimple_call_num_args (info.callstmt))
3030 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3031 else
3032 star_width = void_node;
3033 ++pf;
3034 }
3035
3036 if (target_to_host (*pf) == '$')
3037 {
3038 /* Handle the POSIX dollar sign which references the 1-based
3039 positional argument number. */
3040 if (width != -1)
3041 dollar = width + info.argidx;
3042 else if (star_width
3043 && TREE_CODE (star_width) == INTEGER_CST
3044 && (TYPE_PRECISION (TREE_TYPE (star_width))
3045 <= TYPE_PRECISION (integer_type_node)))
3046 dollar = width + tree_to_shwi (star_width);
3047
3048 /* Bail when the numbered argument is out of range (it will
3049 have already been diagnosed by -Wformat). */
3050 if (dollar == 0
3051 || dollar == (int)info.argidx
3052 || dollar > gimple_call_num_args (info.callstmt))
3053 return false;
3054
3055 --dollar;
3056
3057 star_width = NULL_TREE;
3058 width = -1;
3059 ++pf;
3060 }
3061
3062 if (dollar || !star_width)
3063 {
3064 if (width != -1)
3065 {
3066 if (width == 0)
3067 {
3068 /* The '0' that has been interpreted as a width above is
3069 actually a flag. Reset HAVE_WIDTH, set the '0' flag,
3070 and continue processing other flags. */
3071 width = -1;
3072 dir.set_flag ('0');
3073 }
3074 else if (!dollar)
3075 {
3076 /* (Non-zero) width has been seen. The next character
3077 is either a period or a digit. */
3078 goto start_precision;
3079 }
3080 }
3081 /* When either '$' has been seen, or width has not been seen,
3082 the next field is the optional flags followed by an optional
3083 width. */
3084 for ( ; ; ) {
3085 switch (target_to_host (*pf))
3086 {
3087 case ' ':
3088 case '0':
3089 case '+':
3090 case '-':
3091 case '#':
3092 dir.set_flag (target_to_host (*pf++));
3093 break;
3094
3095 default:
3096 goto start_width;
3097 }
3098 }
3099
3100 start_width:
3101 if (ISDIGIT (target_to_host (*pf)))
3102 {
3103 werange = 0;
3104 pwidth = pf;
3105 width = target_strtol10 (&pf, &werange);
3106 }
3107 else if (target_to_host (*pf) == '*')
3108 {
3109 if (*argno < gimple_call_num_args (info.callstmt))
3110 star_width = gimple_call_arg (info.callstmt, (*argno)++);
3111 else
3112 {
3113 /* This is (likely) a va_list. It could also be an invalid
3114 call with insufficient arguments. */
3115 star_width = void_node;
3116 }
3117 ++pf;
3118 }
3119 else if (target_to_host (*pf) == '\'')
3120 {
3121 /* The POSIX apostrophe indicating a numeric grouping
3122 in the current locale. Even though it's possible to
3123 estimate the upper bound on the size of the output
3124 based on the number of digits it probably isn't worth
3125 continuing. */
3126 return 0;
3127 }
3128 }
3129
3130 start_precision:
3131 if (target_to_host (*pf) == '.')
3132 {
3133 ++pf;
3134
3135 if (ISDIGIT (target_to_host (*pf)))
3136 {
3137 pprec = pf;
3138 precision = target_strtol10 (&pf, &perange);
3139 }
3140 else if (target_to_host (*pf) == '*')
3141 {
3142 if (*argno < gimple_call_num_args (info.callstmt))
3143 star_precision = gimple_call_arg (info.callstmt, (*argno)++);
3144 else
3145 {
3146 /* This is (likely) a va_list. It could also be an invalid
3147 call with insufficient arguments. */
3148 star_precision = void_node;
3149 }
3150 ++pf;
3151 }
3152 else
3153 {
3154 /* The decimal precision or the asterisk are optional.
3155 When neither is dirified it's taken to be zero. */
3156 precision = 0;
3157 }
3158 }
3159
3160 switch (target_to_host (*pf))
3161 {
3162 case 'h':
3163 if (target_to_host (pf[1]) == 'h')
3164 {
3165 ++pf;
3166 dir.modifier = FMT_LEN_hh;
3167 }
3168 else
3169 dir.modifier = FMT_LEN_h;
3170 ++pf;
3171 break;
3172
3173 case 'j':
3174 dir.modifier = FMT_LEN_j;
3175 ++pf;
3176 break;
3177
3178 case 'L':
3179 dir.modifier = FMT_LEN_L;
3180 ++pf;
3181 break;
3182
3183 case 'l':
3184 if (target_to_host (pf[1]) == 'l')
3185 {
3186 ++pf;
3187 dir.modifier = FMT_LEN_ll;
3188 }
3189 else
3190 dir.modifier = FMT_LEN_l;
3191 ++pf;
3192 break;
3193
3194 case 't':
3195 dir.modifier = FMT_LEN_t;
3196 ++pf;
3197 break;
3198
3199 case 'z':
3200 dir.modifier = FMT_LEN_z;
3201 ++pf;
3202 break;
3203 }
3204
3205 switch (target_to_host (*pf))
3206 {
3207 /* Handle a sole '%' character the same as "%%" but since it's
3208 undefined prevent the result from being folded. */
3209 case '\0':
3210 --pf;
3211 res->range.min = res->range.max = HOST_WIDE_INT_M1U;
3212 /* FALLTHRU */
3213 case '%':
3214 dir.fmtfunc = format_percent;
3215 break;
3216
3217 case 'a':
3218 case 'A':
3219 case 'e':
3220 case 'E':
3221 case 'f':
3222 case 'F':
3223 case 'g':
3224 case 'G':
3225 res->floating = true;
3226 dir.fmtfunc = format_floating;
3227 break;
3228
3229 case 'd':
3230 case 'i':
3231 case 'o':
3232 case 'u':
3233 case 'x':
3234 case 'X':
3235 dir.fmtfunc = format_integer;
3236 break;
3237
3238 case 'p':
3239 /* The %p output is implementation-defined. It's possible
3240 to determine this format but due to extensions (edirially
3241 those of the Linux kernel -- see bug 78512) the first %p
3242 in the format string disables any further processing. */
3243 return false;
3244
3245 case 'n':
3246 /* %n has side-effects even when nothing is actually printed to
3247 any buffer. */
3248 info.nowrite = false;
3249 dir.fmtfunc = format_none;
3250 break;
3251
3252 case 'C':
3253 case 'c':
3254 /* POSIX wide character and C/POSIX narrow character. */
3255 dir.fmtfunc = format_character;
3256 break;
3257
3258 case 'S':
3259 case 's':
3260 /* POSIX wide string and C/POSIX narrow character string. */
3261 dir.fmtfunc = format_string;
3262 break;
3263
3264 default:
3265 /* Unknown conversion specification. */
3266 return 0;
3267 }
3268
3269 dir.specifier = target_to_host (*pf++);
3270
3271 /* Store the length of the format directive. */
3272 dir.len = pf - pcnt;
3273
3274 /* Buffer for the directive in the host character set (used when
3275 the source character set is different). */
3276 char hostdir[32];
3277
3278 if (star_width)
3279 {
3280 if (INTEGRAL_TYPE_P (TREE_TYPE (star_width)))
3281 dir.set_width (star_width, vr_values);
3282 else
3283 {
3284 /* Width specified by a va_list takes on the range [0, -INT_MIN]
3285 (width is the absolute value of that specified). */
3286 dir.width[0] = 0;
3287 dir.width[1] = target_int_max () + 1;
3288 }
3289 }
3290 else
3291 {
3292 if (width == LONG_MAX && werange)
3293 {
3294 size_t begin = dir.beg - info.fmtstr + (pwidth - pcnt);
3295 size_t caret = begin + (werange - pcnt);
3296 size_t end = pf - info.fmtstr - 1;
3297
3298 /* Create a location for the width part of the directive,
3299 pointing the caret at the first out-of-range digit. */
3300 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3301 caret, begin, end);
3302
3303 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3304 "%<%.*s%> directive width out of range", (int) dir.len,
3305 target_to_host (hostdir, sizeof hostdir, dir.beg));
3306 }
3307
3308 dir.set_width (width);
3309 }
3310
3311 if (star_precision)
3312 {
3313 if (INTEGRAL_TYPE_P (TREE_TYPE (star_precision)))
3314 dir.set_precision (star_precision, vr_values);
3315 else
3316 {
3317 /* Precision specified by a va_list takes on the range [-1, INT_MAX]
3318 (unlike width, negative precision is ignored). */
3319 dir.prec[0] = -1;
3320 dir.prec[1] = target_int_max ();
3321 }
3322 }
3323 else
3324 {
3325 if (precision == LONG_MAX && perange)
3326 {
3327 size_t begin = dir.beg - info.fmtstr + (pprec - pcnt) - 1;
3328 size_t caret = dir.beg - info.fmtstr + (perange - pcnt) - 1;
3329 size_t end = pf - info.fmtstr - 2;
3330
3331 /* Create a location for the precision part of the directive,
3332 including the leading period, pointing the caret at the first
3333 out-of-range digit . */
3334 substring_loc dirloc (info.fmtloc, TREE_TYPE (info.format),
3335 caret, begin, end);
3336
3337 fmtwarn (dirloc, UNKNOWN_LOCATION, NULL, info.warnopt (),
3338 "%<%.*s%> directive precision out of range", (int) dir.len,
3339 target_to_host (hostdir, sizeof hostdir, dir.beg));
3340 }
3341
3342 dir.set_precision (precision);
3343 }
3344
3345 /* Extract the argument if the directive takes one and if it's
3346 available (e.g., the function doesn't take a va_list). Treat
3347 missing arguments the same as va_list, even though they will
3348 have likely already been diagnosed by -Wformat. */
3349 if (dir.specifier != '%'
3350 && *argno < gimple_call_num_args (info.callstmt))
3351 dir.arg = gimple_call_arg (info.callstmt, dollar ? dollar : (*argno)++);
3352
3353 if (dump_file)
3354 {
3355 fprintf (dump_file,
3356 " Directive %u at offset " HOST_WIDE_INT_PRINT_UNSIGNED
3357 ": \"%.*s\"",
3358 dir.dirno,
3359 (unsigned HOST_WIDE_INT)(size_t)(dir.beg - info.fmtstr),
3360 (int)dir.len, dir.beg);
3361 if (star_width)
3362 {
3363 if (dir.width[0] == dir.width[1])
3364 fprintf (dump_file, ", width = " HOST_WIDE_INT_PRINT_DEC,
3365 dir.width[0]);
3366 else
3367 fprintf (dump_file,
3368 ", width in range [" HOST_WIDE_INT_PRINT_DEC
3369 ", " HOST_WIDE_INT_PRINT_DEC "]",
3370 dir.width[0], dir.width[1]);
3371 }
3372
3373 if (star_precision)
3374 {
3375 if (dir.prec[0] == dir.prec[1])
3376 fprintf (dump_file, ", precision = " HOST_WIDE_INT_PRINT_DEC,
3377 dir.prec[0]);
3378 else
3379 fprintf (dump_file,
3380 ", precision in range [" HOST_WIDE_INT_PRINT_DEC
3381 HOST_WIDE_INT_PRINT_DEC "]",
3382 dir.prec[0], dir.prec[1]);
3383 }
3384 fputc ('\n', dump_file);
3385 }
3386
3387 return dir.len;
3388 }
3389
3390 /* Compute the length of the output resulting from the call to a formatted
3391 output function described by INFO and store the result of the call in
3392 *RES. Issue warnings for detected past the end writes. Return true
3393 if the complete format string has been processed and *RES can be relied
3394 on, false otherwise (e.g., when a unknown or unhandled directive was seen
3395 that caused the processing to be terminated early). */
3396
3397 bool
3398 sprintf_dom_walker::compute_format_length (call_info &info,
3399 format_result *res)
3400 {
3401 if (dump_file)
3402 {
3403 location_t callloc = gimple_location (info.callstmt);
3404 fprintf (dump_file, "%s:%i: ",
3405 LOCATION_FILE (callloc), LOCATION_LINE (callloc));
3406 print_generic_expr (dump_file, info.func, dump_flags);
3407
3408 fprintf (dump_file,
3409 ": objsize = " HOST_WIDE_INT_PRINT_UNSIGNED
3410 ", fmtstr = \"%s\"\n",
3411 info.objsize, info.fmtstr);
3412 }
3413
3414 /* Reset the minimum and maximum byte counters. */
3415 res->range.min = res->range.max = 0;
3416
3417 /* No directive has been seen yet so the length of output is bounded
3418 by the known range [0, 0] (with no conversion resulting in a failure
3419 or producing more than 4K bytes) until determined otherwise. */
3420 res->knownrange = true;
3421 res->posunder4k = true;
3422 res->floating = false;
3423 res->warned = false;
3424
3425 /* 1-based directive counter. */
3426 unsigned dirno = 1;
3427
3428 /* The variadic argument counter. */
3429 unsigned argno = info.argidx;
3430
3431 for (const char *pf = info.fmtstr; ; ++dirno)
3432 {
3433 directive dir = directive ();
3434 dir.dirno = dirno;
3435
3436 size_t n = parse_directive (info, dir, res, pf, &argno,
3437 evrp_range_analyzer.get_vr_values ());
3438
3439 /* Return failure if the format function fails. */
3440 if (!format_directive (info, res, dir,
3441 evrp_range_analyzer.get_vr_values ()))
3442 return false;
3443
3444 /* Return success the directive is zero bytes long and it's
3445 the last think in the format string (i.e., it's the terminating
3446 nul, which isn't really a directive but handling it as one makes
3447 things simpler). */
3448 if (!n)
3449 return *pf == '\0';
3450
3451 pf += n;
3452 }
3453
3454 /* The complete format string was processed (with or without warnings). */
3455 return true;
3456 }
3457
3458 /* Return the size of the object referenced by the expression DEST if
3459 available, or -1 otherwise. */
3460
3461 static unsigned HOST_WIDE_INT
3462 get_destination_size (tree dest)
3463 {
3464 /* Initialize object size info before trying to compute it. */
3465 init_object_sizes ();
3466
3467 /* Use __builtin_object_size to determine the size of the destination
3468 object. When optimizing, determine the smallest object (such as
3469 a member array as opposed to the whole enclosing object), otherwise
3470 use type-zero object size to determine the size of the enclosing
3471 object (the function fails without optimization in this type). */
3472 int ost = optimize > 0;
3473 unsigned HOST_WIDE_INT size;
3474 if (compute_builtin_object_size (dest, ost, &size))
3475 return size;
3476
3477 return HOST_WIDE_INT_M1U;
3478 }
3479
3480 /* Return true if the call described by INFO with result RES safe to
3481 optimize (i.e., no undefined behavior), and set RETVAL to the range
3482 of its return values. */
3483
3484 static bool
3485 is_call_safe (const sprintf_dom_walker::call_info &info,
3486 const format_result &res, bool under4k,
3487 unsigned HOST_WIDE_INT retval[2])
3488 {
3489 if (under4k && !res.posunder4k)
3490 return false;
3491
3492 /* The minimum return value. */
3493 retval[0] = res.range.min;
3494
3495 /* The maximum return value is in most cases bounded by RES.RANGE.MAX
3496 but in cases involving multibyte characters could be as large as
3497 RES.RANGE.UNLIKELY. */
3498 retval[1]
3499 = res.range.unlikely < res.range.max ? res.range.max : res.range.unlikely;
3500
3501 /* Adjust the number of bytes which includes the terminating nul
3502 to reflect the return value of the function which does not.
3503 Because the valid range of the function is [INT_MIN, INT_MAX],
3504 a valid range before the adjustment below is [0, INT_MAX + 1]
3505 (the functions only return negative values on error or undefined
3506 behavior). */
3507 if (retval[0] <= target_int_max () + 1)
3508 --retval[0];
3509 if (retval[1] <= target_int_max () + 1)
3510 --retval[1];
3511
3512 /* Avoid the return value optimization when the behavior of the call
3513 is undefined either because any directive may have produced 4K or
3514 more of output, or the return value exceeds INT_MAX, or because
3515 the output overflows the destination object (but leave it enabled
3516 when the function is bounded because then the behavior is well-
3517 defined). */
3518 if (retval[0] == retval[1]
3519 && (info.bounded || retval[0] < info.objsize)
3520 && retval[0] <= target_int_max ())
3521 return true;
3522
3523 if ((info.bounded || retval[1] < info.objsize)
3524 && (retval[0] < target_int_max ()
3525 && retval[1] < target_int_max ()))
3526 return true;
3527
3528 if (!under4k && (info.bounded || retval[0] < info.objsize))
3529 return true;
3530
3531 return false;
3532 }
3533
3534 /* Given a suitable result RES of a call to a formatted output function
3535 described by INFO, substitute the result for the return value of
3536 the call. The result is suitable if the number of bytes it represents
3537 is known and exact. A result that isn't suitable for substitution may
3538 have its range set to the range of return values, if that is known.
3539 Return true if the call is removed and gsi_next should not be performed
3540 in the caller. */
3541
3542 static bool
3543 try_substitute_return_value (gimple_stmt_iterator *gsi,
3544 const sprintf_dom_walker::call_info &info,
3545 const format_result &res)
3546 {
3547 tree lhs = gimple_get_lhs (info.callstmt);
3548
3549 /* Set to true when the entire call has been removed. */
3550 bool removed = false;
3551
3552 /* The minimum and maximum return value. */
3553 unsigned HOST_WIDE_INT retval[2];
3554 bool safe = is_call_safe (info, res, true, retval);
3555
3556 if (safe
3557 && retval[0] == retval[1]
3558 /* Not prepared to handle possibly throwing calls here; they shouldn't
3559 appear in non-artificial testcases, except when the __*_chk routines
3560 are badly declared. */
3561 && !stmt_ends_bb_p (info.callstmt))
3562 {
3563 tree cst = build_int_cst (integer_type_node, retval[0]);
3564
3565 if (lhs == NULL_TREE
3566 && info.nowrite)
3567 {
3568 /* Remove the call to the bounded function with a zero size
3569 (e.g., snprintf(0, 0, "%i", 123)) if there is no lhs. */
3570 unlink_stmt_vdef (info.callstmt);
3571 gsi_remove (gsi, true);
3572 removed = true;
3573 }
3574 else if (info.nowrite)
3575 {
3576 /* Replace the call to the bounded function with a zero size
3577 (e.g., snprintf(0, 0, "%i", 123) with the constant result
3578 of the function. */
3579 if (!update_call_from_tree (gsi, cst))
3580 gimplify_and_update_call_from_tree (gsi, cst);
3581 gimple *callstmt = gsi_stmt (*gsi);
3582 update_stmt (callstmt);
3583 }
3584 else if (lhs)
3585 {
3586 /* Replace the left-hand side of the call with the constant
3587 result of the formatted function. */
3588 gimple_call_set_lhs (info.callstmt, NULL_TREE);
3589 gimple *g = gimple_build_assign (lhs, cst);
3590 gsi_insert_after (gsi, g, GSI_NEW_STMT);
3591 update_stmt (info.callstmt);
3592 }
3593
3594 if (dump_file)
3595 {
3596 if (removed)
3597 fprintf (dump_file, " Removing call statement.");
3598 else
3599 {
3600 fprintf (dump_file, " Substituting ");
3601 print_generic_expr (dump_file, cst, dump_flags);
3602 fprintf (dump_file, " for %s.\n",
3603 info.nowrite ? "statement" : "return value");
3604 }
3605 }
3606 }
3607 else if (lhs)
3608 {
3609 bool setrange = false;
3610
3611 if (safe
3612 && (info.bounded || retval[1] < info.objsize)
3613 && (retval[0] < target_int_max ()
3614 && retval[1] < target_int_max ()))
3615 {
3616 /* If the result is in a valid range bounded by the size of
3617 the destination set it so that it can be used for subsequent
3618 optimizations. */
3619 int prec = TYPE_PRECISION (integer_type_node);
3620
3621 wide_int min = wi::shwi (retval[0], prec);
3622 wide_int max = wi::shwi (retval[1], prec);
3623 set_range_info (lhs, VR_RANGE, min, max);
3624
3625 setrange = true;
3626 }
3627
3628 if (dump_file)
3629 {
3630 const char *inbounds
3631 = (retval[0] < info.objsize
3632 ? (retval[1] < info.objsize
3633 ? "in" : "potentially out-of")
3634 : "out-of");
3635
3636 const char *what = setrange ? "Setting" : "Discarding";
3637 if (retval[0] != retval[1])
3638 fprintf (dump_file,
3639 " %s %s-bounds return value range ["
3640 HOST_WIDE_INT_PRINT_UNSIGNED ", "
3641 HOST_WIDE_INT_PRINT_UNSIGNED "].\n",
3642 what, inbounds, retval[0], retval[1]);
3643 else
3644 fprintf (dump_file, " %s %s-bounds return value "
3645 HOST_WIDE_INT_PRINT_UNSIGNED ".\n",
3646 what, inbounds, retval[0]);
3647 }
3648 }
3649
3650 if (dump_file)
3651 fputc ('\n', dump_file);
3652
3653 return removed;
3654 }
3655
3656 /* Try to simplify a s{,n}printf call described by INFO with result
3657 RES by replacing it with a simpler and presumably more efficient
3658 call (such as strcpy). */
3659
3660 static bool
3661 try_simplify_call (gimple_stmt_iterator *gsi,
3662 const sprintf_dom_walker::call_info &info,
3663 const format_result &res)
3664 {
3665 unsigned HOST_WIDE_INT dummy[2];
3666 if (!is_call_safe (info, res, info.retval_used (), dummy))
3667 return false;
3668
3669 switch (info.fncode)
3670 {
3671 case BUILT_IN_SNPRINTF:
3672 return gimple_fold_builtin_snprintf (gsi);
3673
3674 case BUILT_IN_SPRINTF:
3675 return gimple_fold_builtin_sprintf (gsi);
3676
3677 default:
3678 ;
3679 }
3680
3681 return false;
3682 }
3683
3684 /* Determine if a GIMPLE CALL is to one of the sprintf-like built-in
3685 functions and if so, handle it. Return true if the call is removed
3686 and gsi_next should not be performed in the caller. */
3687
3688 bool
3689 sprintf_dom_walker::handle_gimple_call (gimple_stmt_iterator *gsi)
3690 {
3691 call_info info = call_info ();
3692
3693 info.callstmt = gsi_stmt (*gsi);
3694 if (!gimple_call_builtin_p (info.callstmt, BUILT_IN_NORMAL))
3695 return false;
3696
3697 info.func = gimple_call_fndecl (info.callstmt);
3698 info.fncode = DECL_FUNCTION_CODE (info.func);
3699
3700 /* The size of the destination as in snprintf(dest, size, ...). */
3701 unsigned HOST_WIDE_INT dstsize = HOST_WIDE_INT_M1U;
3702
3703 /* The size of the destination determined by __builtin_object_size. */
3704 unsigned HOST_WIDE_INT objsize = HOST_WIDE_INT_M1U;
3705
3706 /* Buffer size argument number (snprintf and vsnprintf). */
3707 unsigned HOST_WIDE_INT idx_dstsize = HOST_WIDE_INT_M1U;
3708
3709 /* Object size argument number (snprintf_chk and vsnprintf_chk). */
3710 unsigned HOST_WIDE_INT idx_objsize = HOST_WIDE_INT_M1U;
3711
3712 /* Format string argument number (valid for all functions). */
3713 unsigned idx_format;
3714
3715 switch (info.fncode)
3716 {
3717 case BUILT_IN_SPRINTF:
3718 // Signature:
3719 // __builtin_sprintf (dst, format, ...)
3720 idx_format = 1;
3721 info.argidx = 2;
3722 break;
3723
3724 case BUILT_IN_SPRINTF_CHK:
3725 // Signature:
3726 // __builtin___sprintf_chk (dst, ost, objsize, format, ...)
3727 idx_objsize = 2;
3728 idx_format = 3;
3729 info.argidx = 4;
3730 break;
3731
3732 case BUILT_IN_SNPRINTF:
3733 // Signature:
3734 // __builtin_snprintf (dst, size, format, ...)
3735 idx_dstsize = 1;
3736 idx_format = 2;
3737 info.argidx = 3;
3738 info.bounded = true;
3739 break;
3740
3741 case BUILT_IN_SNPRINTF_CHK:
3742 // Signature:
3743 // __builtin___snprintf_chk (dst, size, ost, objsize, format, ...)
3744 idx_dstsize = 1;
3745 idx_objsize = 3;
3746 idx_format = 4;
3747 info.argidx = 5;
3748 info.bounded = true;
3749 break;
3750
3751 case BUILT_IN_VSNPRINTF:
3752 // Signature:
3753 // __builtin_vsprintf (dst, size, format, va)
3754 idx_dstsize = 1;
3755 idx_format = 2;
3756 info.argidx = -1;
3757 info.bounded = true;
3758 break;
3759
3760 case BUILT_IN_VSNPRINTF_CHK:
3761 // Signature:
3762 // __builtin___vsnprintf_chk (dst, size, ost, objsize, format, va)
3763 idx_dstsize = 1;
3764 idx_objsize = 3;
3765 idx_format = 4;
3766 info.argidx = -1;
3767 info.bounded = true;
3768 break;
3769
3770 case BUILT_IN_VSPRINTF:
3771 // Signature:
3772 // __builtin_vsprintf (dst, format, va)
3773 idx_format = 1;
3774 info.argidx = -1;
3775 break;
3776
3777 case BUILT_IN_VSPRINTF_CHK:
3778 // Signature:
3779 // __builtin___vsprintf_chk (dst, ost, objsize, format, va)
3780 idx_format = 3;
3781 idx_objsize = 2;
3782 info.argidx = -1;
3783 break;
3784
3785 default:
3786 return false;
3787 }
3788
3789 /* Set the global warning level for this function. */
3790 warn_level = info.bounded ? warn_format_trunc : warn_format_overflow;
3791
3792 /* The first argument is a pointer to the destination. */
3793 tree dstptr = gimple_call_arg (info.callstmt, 0);
3794
3795 info.format = gimple_call_arg (info.callstmt, idx_format);
3796
3797 /* True when the destination size is constant as opposed to the lower
3798 or upper bound of a range. */
3799 bool dstsize_cst_p = true;
3800
3801 if (idx_dstsize == HOST_WIDE_INT_M1U)
3802 {
3803 /* For non-bounded functions like sprintf, determine the size
3804 of the destination from the object or pointer passed to it
3805 as the first argument. */
3806 dstsize = get_destination_size (dstptr);
3807 }
3808 else if (tree size = gimple_call_arg (info.callstmt, idx_dstsize))
3809 {
3810 /* For bounded functions try to get the size argument. */
3811
3812 if (TREE_CODE (size) == INTEGER_CST)
3813 {
3814 dstsize = tree_to_uhwi (size);
3815 /* No object can be larger than SIZE_MAX bytes (half the address
3816 space) on the target.
3817 The functions are defined only for output of at most INT_MAX
3818 bytes. Specifying a bound in excess of that limit effectively
3819 defeats the bounds checking (and on some implementations such
3820 as Solaris cause the function to fail with EINVAL). */
3821 if (dstsize > target_size_max () / 2)
3822 {
3823 /* Avoid warning if -Wstringop-overflow is specified since
3824 it also warns for the same thing though only for the
3825 checking built-ins. */
3826 if ((idx_objsize == HOST_WIDE_INT_M1U
3827 || !warn_stringop_overflow))
3828 warning_at (gimple_location (info.callstmt), info.warnopt (),
3829 "specified bound %wu exceeds maximum object size "
3830 "%wu",
3831 dstsize, target_size_max () / 2);
3832 }
3833 else if (dstsize > target_int_max ())
3834 warning_at (gimple_location (info.callstmt), info.warnopt (),
3835 "specified bound %wu exceeds %<INT_MAX%>",
3836 dstsize);
3837 }
3838 else if (TREE_CODE (size) == SSA_NAME)
3839 {
3840 /* Try to determine the range of values of the argument
3841 and use the greater of the two at level 1 and the smaller
3842 of them at level 2. */
3843 value_range *vr = evrp_range_analyzer.get_value_range (size);
3844 if (vr->type == VR_RANGE
3845 && TREE_CODE (vr->min) == INTEGER_CST
3846 && TREE_CODE (vr->max) == INTEGER_CST)
3847 dstsize = (warn_level < 2
3848 ? TREE_INT_CST_LOW (vr->max)
3849 : TREE_INT_CST_LOW (vr->min));
3850
3851 /* The destination size is not constant. If the function is
3852 bounded (e.g., snprintf) a lower bound of zero doesn't
3853 necessarily imply it can be eliminated. */
3854 dstsize_cst_p = false;
3855 }
3856 }
3857
3858 if (idx_objsize != HOST_WIDE_INT_M1U)
3859 if (tree size = gimple_call_arg (info.callstmt, idx_objsize))
3860 if (tree_fits_uhwi_p (size))
3861 objsize = tree_to_uhwi (size);
3862
3863 if (info.bounded && !dstsize)
3864 {
3865 /* As a special case, when the explicitly specified destination
3866 size argument (to a bounded function like snprintf) is zero
3867 it is a request to determine the number of bytes on output
3868 without actually producing any. Pretend the size is
3869 unlimited in this case. */
3870 info.objsize = HOST_WIDE_INT_MAX;
3871 info.nowrite = dstsize_cst_p;
3872 }
3873 else
3874 {
3875 /* For calls to non-bounded functions or to those of bounded
3876 functions with a non-zero size, warn if the destination
3877 pointer is null. */
3878 if (integer_zerop (dstptr))
3879 {
3880 /* This is diagnosed with -Wformat only when the null is a constant
3881 pointer. The warning here diagnoses instances where the pointer
3882 is not constant. */
3883 location_t loc = gimple_location (info.callstmt);
3884 warning_at (EXPR_LOC_OR_LOC (dstptr, loc),
3885 info.warnopt (), "null destination pointer");
3886 return false;
3887 }
3888
3889 /* Set the object size to the smaller of the two arguments
3890 of both have been specified and they're not equal. */
3891 info.objsize = dstsize < objsize ? dstsize : objsize;
3892
3893 if (info.bounded
3894 && dstsize < target_size_max () / 2 && objsize < dstsize
3895 /* Avoid warning if -Wstringop-overflow is specified since
3896 it also warns for the same thing though only for the
3897 checking built-ins. */
3898 && (idx_objsize == HOST_WIDE_INT_M1U
3899 || !warn_stringop_overflow))
3900 {
3901 warning_at (gimple_location (info.callstmt), info.warnopt (),
3902 "specified bound %wu exceeds the size %wu "
3903 "of the destination object", dstsize, objsize);
3904 }
3905 }
3906
3907 if (integer_zerop (info.format))
3908 {
3909 /* This is diagnosed with -Wformat only when the null is a constant
3910 pointer. The warning here diagnoses instances where the pointer
3911 is not constant. */
3912 location_t loc = gimple_location (info.callstmt);
3913 warning_at (EXPR_LOC_OR_LOC (info.format, loc),
3914 info.warnopt (), "null format string");
3915 return false;
3916 }
3917
3918 info.fmtstr = get_format_string (info.format, &info.fmtloc);
3919 if (!info.fmtstr)
3920 return false;
3921
3922 /* The result is the number of bytes output by the formatted function,
3923 including the terminating NUL. */
3924 format_result res = format_result ();
3925
3926 bool success = compute_format_length (info, &res);
3927
3928 /* When optimizing and the printf return value optimization is enabled,
3929 attempt to substitute the computed result for the return value of
3930 the call. Avoid this optimization when -frounding-math is in effect
3931 and the format string contains a floating point directive. */
3932 bool call_removed = false;
3933 if (success && optimize > 0)
3934 {
3935 /* Save a copy of the iterator pointing at the call. The iterator
3936 may change to point past the call in try_substitute_return_value
3937 but the original value is needed in try_simplify_call. */
3938 gimple_stmt_iterator gsi_call = *gsi;
3939
3940 if (flag_printf_return_value
3941 && (!flag_rounding_math || !res.floating))
3942 call_removed = try_substitute_return_value (gsi, info, res);
3943
3944 if (!call_removed)
3945 try_simplify_call (&gsi_call, info, res);
3946 }
3947
3948 return call_removed;
3949 }
3950
3951 edge
3952 sprintf_dom_walker::before_dom_children (basic_block bb)
3953 {
3954 evrp_range_analyzer.enter (bb);
3955 for (gimple_stmt_iterator si = gsi_start_bb (bb); !gsi_end_p (si); )
3956 {
3957 /* Iterate over statements, looking for function calls. */
3958 gimple *stmt = gsi_stmt (si);
3959
3960 /* First record ranges generated by this statement. */
3961 evrp_range_analyzer.record_ranges_from_stmt (stmt, false);
3962
3963 if (is_gimple_call (stmt) && handle_gimple_call (&si))
3964 /* If handle_gimple_call returns true, the iterator is
3965 already pointing to the next statement. */
3966 continue;
3967
3968 gsi_next (&si);
3969 }
3970 return NULL;
3971 }
3972
3973 void
3974 sprintf_dom_walker::after_dom_children (basic_block bb)
3975 {
3976 evrp_range_analyzer.leave (bb);
3977 }
3978
3979 /* Execute the pass for function FUN. */
3980
3981 unsigned int
3982 pass_sprintf_length::execute (function *fun)
3983 {
3984 init_target_to_host_charmap ();
3985
3986 calculate_dominance_info (CDI_DOMINATORS);
3987
3988 sprintf_dom_walker sprintf_dom_walker;
3989 sprintf_dom_walker.walk (ENTRY_BLOCK_PTR_FOR_FN (fun));
3990
3991 /* Clean up object size info. */
3992 fini_object_sizes ();
3993 return 0;
3994 }
3995
3996 } /* Unnamed namespace. */
3997
3998 /* Return a pointer to a pass object newly constructed from the context
3999 CTXT. */
4000
4001 gimple_opt_pass *
4002 make_pass_sprintf_length (gcc::context *ctxt)
4003 {
4004 return new pass_sprintf_length (ctxt);
4005 }