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