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