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