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