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