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