Don't warn when alignment of global common data exceeds maximum alignment.
[official-gcc.git] / gcc / gimple-ssa-warn-access.cc
blob4a2dd9ade77d1fac9b3b53cd6844ec4bc274b194
1 /* Pass to detect and issue warnings for invalid accesses, including
2 invalid or mismatched allocation/deallocation calls.
4 Copyright (C) 2020-2021 Free Software Foundation, Inc.
5 Contributed by Martin Sebor <msebor@redhat.com>.
7 This file is part of GCC.
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3. If not see
21 <http://www.gnu.org/licenses/>. */
23 #define INCLUDE_STRING
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "backend.h"
28 #include "tree.h"
29 #include "gimple.h"
30 #include "tree-pass.h"
31 #include "builtins.h"
32 #include "ssa.h"
33 #include "gimple-pretty-print.h"
34 #include "gimple-ssa-warn-access.h"
35 #include "gimple-ssa-warn-restrict.h"
36 #include "diagnostic-core.h"
37 #include "fold-const.h"
38 #include "gimple-fold.h"
39 #include "gimple-iterator.h"
40 #include "langhooks.h"
41 #include "tree-dfa.h"
42 #include "tree-ssa.h"
43 #include "tree-cfg.h"
44 #include "tree-object-size.h"
45 #include "tree-ssa-strlen.h"
46 #include "calls.h"
47 #include "cfgloop.h"
48 #include "intl.h"
49 #include "gimple-range.h"
50 #include "stringpool.h"
51 #include "attribs.h"
52 #include "demangle.h"
53 #include "pointer-query.h"
55 /* Return true if tree node X has an associated location. */
57 static inline location_t
58 has_location (const_tree x)
60 if (DECL_P (x))
61 return DECL_SOURCE_LOCATION (x) != UNKNOWN_LOCATION;
63 if (EXPR_P (x))
64 return EXPR_HAS_LOCATION (x);
66 return false;
69 /* Return the associated location of STMT. */
71 static inline location_t
72 get_location (const gimple *stmt)
74 return gimple_location (stmt);
77 /* Return the associated location of tree node X. */
79 static inline location_t
80 get_location (tree x)
82 if (DECL_P (x))
83 return DECL_SOURCE_LOCATION (x);
85 if (EXPR_P (x))
86 return EXPR_LOCATION (x);
88 return UNKNOWN_LOCATION;
91 /* Overload of the nascent tree function for GIMPLE STMT. */
93 static inline tree
94 get_callee_fndecl (const gimple *stmt)
96 return gimple_call_fndecl (stmt);
99 static inline unsigned
100 call_nargs (const gimple *stmt)
102 return gimple_call_num_args (stmt);
105 static inline unsigned
106 call_nargs (const_tree expr)
108 return call_expr_nargs (expr);
112 static inline tree
113 call_arg (const gimple *stmt, unsigned argno)
115 return gimple_call_arg (stmt, argno);
118 static inline tree
119 call_arg (tree expr, unsigned argno)
121 return CALL_EXPR_ARG (expr, argno);
124 /* For a call EXPR at LOC to a function FNAME that expects a string
125 in the argument ARG, issue a diagnostic due to it being a called
126 with an argument that is a character array with no terminating
127 NUL. SIZE is the EXACT size of the array, and BNDRNG the number
128 of characters in which the NUL is expected. Either EXPR or FNAME
129 may be null but noth both. SIZE may be null when BNDRNG is null. */
131 template <class GimpleOrTree>
132 static void
133 warn_string_no_nul (location_t loc, GimpleOrTree expr, const char *fname,
134 tree arg, tree decl, tree size, bool exact,
135 const wide_int bndrng[2] /* = NULL */)
137 const opt_code opt = OPT_Wstringop_overread;
138 if ((expr && warning_suppressed_p (expr, opt))
139 || warning_suppressed_p (arg, opt))
140 return;
142 loc = expansion_point_location_if_in_system_header (loc);
143 bool warned;
145 /* Format the bound range as a string to keep the nuber of messages
146 from exploding. */
147 char bndstr[80];
148 *bndstr = 0;
149 if (bndrng)
151 if (bndrng[0] == bndrng[1])
152 sprintf (bndstr, "%llu", (unsigned long long) bndrng[0].to_uhwi ());
153 else
154 sprintf (bndstr, "[%llu, %llu]",
155 (unsigned long long) bndrng[0].to_uhwi (),
156 (unsigned long long) bndrng[1].to_uhwi ());
159 const tree maxobjsize = max_object_size ();
160 const wide_int maxsiz = wi::to_wide (maxobjsize);
161 if (expr)
163 tree func = get_callee_fndecl (expr);
164 if (bndrng)
166 if (wi::ltu_p (maxsiz, bndrng[0]))
167 warned = warning_at (loc, opt,
168 "%qD specified bound %s exceeds "
169 "maximum object size %E",
170 func, bndstr, maxobjsize);
171 else
173 bool maybe = wi::to_wide (size) == bndrng[0];
174 warned = warning_at (loc, opt,
175 exact
176 ? G_("%qD specified bound %s exceeds "
177 "the size %E of unterminated array")
178 : (maybe
179 ? G_("%qD specified bound %s may "
180 "exceed the size of at most %E "
181 "of unterminated array")
182 : G_("%qD specified bound %s exceeds "
183 "the size of at most %E "
184 "of unterminated array")),
185 func, bndstr, size);
188 else
189 warned = warning_at (loc, opt,
190 "%qD argument missing terminating nul",
191 func);
193 else
195 if (bndrng)
197 if (wi::ltu_p (maxsiz, bndrng[0]))
198 warned = warning_at (loc, opt,
199 "%qs specified bound %s exceeds "
200 "maximum object size %E",
201 fname, bndstr, maxobjsize);
202 else
204 bool maybe = wi::to_wide (size) == bndrng[0];
205 warned = warning_at (loc, opt,
206 exact
207 ? G_("%qs specified bound %s exceeds "
208 "the size %E of unterminated array")
209 : (maybe
210 ? G_("%qs specified bound %s may "
211 "exceed the size of at most %E "
212 "of unterminated array")
213 : G_("%qs specified bound %s exceeds "
214 "the size of at most %E "
215 "of unterminated array")),
216 fname, bndstr, size);
219 else
220 warned = warning_at (loc, opt,
221 "%qs argument missing terminating nul",
222 fname);
225 if (warned)
227 inform (get_location (decl),
228 "referenced argument declared here");
229 suppress_warning (arg, opt);
230 if (expr)
231 suppress_warning (expr, opt);
235 void
236 warn_string_no_nul (location_t loc, gimple *stmt, const char *fname,
237 tree arg, tree decl, tree size /* = NULL_TREE */,
238 bool exact /* = false */,
239 const wide_int bndrng[2] /* = NULL */)
241 return warn_string_no_nul<gimple *> (loc, stmt, fname,
242 arg, decl, size, exact, bndrng);
245 void
246 warn_string_no_nul (location_t loc, tree expr, const char *fname,
247 tree arg, tree decl, tree size /* = NULL_TREE */,
248 bool exact /* = false */,
249 const wide_int bndrng[2] /* = NULL */)
251 return warn_string_no_nul<tree> (loc, expr, fname,
252 arg, decl, size, exact, bndrng);
255 /* If EXP refers to an unterminated constant character array return
256 the declaration of the object of which the array is a member or
257 element and if SIZE is not null, set *SIZE to the size of
258 the unterminated array and set *EXACT if the size is exact or
259 clear it otherwise. Otherwise return null. */
261 tree
262 unterminated_array (tree exp, tree *size /* = NULL */, bool *exact /* = NULL */)
264 /* C_STRLEN will return NULL and set DECL in the info
265 structure if EXP references a unterminated array. */
266 c_strlen_data lendata = { };
267 tree len = c_strlen (exp, 1, &lendata);
268 if (len || !lendata.minlen || !lendata.decl)
269 return NULL_TREE;
271 if (!size)
272 return lendata.decl;
274 len = lendata.minlen;
275 if (lendata.off)
277 /* Constant offsets are already accounted for in LENDATA.MINLEN,
278 but not in a SSA_NAME + CST expression. */
279 if (TREE_CODE (lendata.off) == INTEGER_CST)
280 *exact = true;
281 else if (TREE_CODE (lendata.off) == PLUS_EXPR
282 && TREE_CODE (TREE_OPERAND (lendata.off, 1)) == INTEGER_CST)
284 /* Subtract the offset from the size of the array. */
285 *exact = false;
286 tree temp = TREE_OPERAND (lendata.off, 1);
287 temp = fold_convert (ssizetype, temp);
288 len = fold_build2 (MINUS_EXPR, ssizetype, len, temp);
290 else
291 *exact = false;
293 else
294 *exact = true;
296 *size = len;
297 return lendata.decl;
300 /* For a call EXPR (which may be null) that expects a string argument
301 SRC as an argument, returns false if SRC is a character array with
302 no terminating NUL. When nonnull, BOUND is the number of characters
303 in which to expect the terminating NUL. When EXPR is nonnull also
304 issues a warning. */
306 template <class GimpleOrTree>
307 static bool
308 check_nul_terminated_array (GimpleOrTree expr, tree src, tree bound)
310 /* The constant size of the array SRC points to. The actual size
311 may be less of EXACT is true, but not more. */
312 tree size;
313 /* True if SRC involves a non-constant offset into the array. */
314 bool exact;
315 /* The unterminated constant array SRC points to. */
316 tree nonstr = unterminated_array (src, &size, &exact);
317 if (!nonstr)
318 return true;
320 /* NONSTR refers to the non-nul terminated constant array and SIZE
321 is the constant size of the array in bytes. EXACT is true when
322 SIZE is exact. */
324 wide_int bndrng[2];
325 if (bound)
327 value_range r;
329 get_global_range_query ()->range_of_expr (r, bound);
331 if (r.kind () != VR_RANGE)
332 return true;
334 bndrng[0] = r.lower_bound ();
335 bndrng[1] = r.upper_bound ();
337 if (exact)
339 if (wi::leu_p (bndrng[0], wi::to_wide (size)))
340 return true;
342 else if (wi::lt_p (bndrng[0], wi::to_wide (size), UNSIGNED))
343 return true;
346 if (expr)
347 warn_string_no_nul (get_location (expr), expr, NULL, src, nonstr,
348 size, exact, bound ? bndrng : NULL);
350 return false;
353 bool
354 check_nul_terminated_array (gimple *stmt, tree src, tree bound /* = NULL_TREE */)
356 return check_nul_terminated_array<gimple *>(stmt, src, bound);
359 bool
360 check_nul_terminated_array (tree expr, tree src, tree bound /* = NULL_TREE */)
362 return check_nul_terminated_array<tree>(expr, src, bound);
365 /* Warn about passing a non-string array/pointer to a built-in function
366 that expects a nul-terminated string argument. Returns true if
367 a warning has been issued.*/
369 template <class GimpleOrTree>
370 static bool
371 maybe_warn_nonstring_arg (tree fndecl, GimpleOrTree exp)
373 if (!fndecl || !fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
374 return false;
376 if (!warn_stringop_overread
377 || warning_suppressed_p (exp, OPT_Wstringop_overread))
378 return false;
380 /* Avoid clearly invalid calls (more checking done below). */
381 unsigned nargs = call_nargs (exp);
382 if (!nargs)
383 return false;
385 /* The bound argument to a bounded string function like strncpy. */
386 tree bound = NULL_TREE;
388 /* The longest known or possible string argument to one of the comparison
389 functions. If the length is less than the bound it is used instead.
390 Since the length is only used for warning and not for code generation
391 disable strict mode in the calls to get_range_strlen below. */
392 tree maxlen = NULL_TREE;
394 /* It's safe to call "bounded" string functions with a non-string
395 argument since the functions provide an explicit bound for this
396 purpose. The exception is strncat where the bound may refer to
397 either the destination or the source. */
398 int fncode = DECL_FUNCTION_CODE (fndecl);
399 switch (fncode)
401 case BUILT_IN_STRCMP:
402 case BUILT_IN_STRNCMP:
403 case BUILT_IN_STRNCASECMP:
405 /* For these, if one argument refers to one or more of a set
406 of string constants or arrays of known size, determine
407 the range of their known or possible lengths and use it
408 conservatively as the bound for the unbounded function,
409 and to adjust the range of the bound of the bounded ones. */
410 for (unsigned argno = 0;
411 argno < MIN (nargs, 2)
412 && !(maxlen && TREE_CODE (maxlen) == INTEGER_CST); argno++)
414 tree arg = call_arg (exp, argno);
415 if (!get_attr_nonstring_decl (arg))
417 c_strlen_data lendata = { };
418 /* Set MAXBOUND to an arbitrary non-null non-integer
419 node as a request to have it set to the length of
420 the longest string in a PHI. */
421 lendata.maxbound = arg;
422 get_range_strlen (arg, &lendata, /* eltsize = */ 1);
423 maxlen = lendata.maxbound;
427 /* Fall through. */
429 case BUILT_IN_STRNCAT:
430 case BUILT_IN_STPNCPY:
431 case BUILT_IN_STRNCPY:
432 if (nargs > 2)
433 bound = call_arg (exp, 2);
434 break;
436 case BUILT_IN_STRNDUP:
437 if (nargs < 2)
438 return false;
439 bound = call_arg (exp, 1);
440 break;
442 case BUILT_IN_STRNLEN:
444 tree arg = call_arg (exp, 0);
445 if (!get_attr_nonstring_decl (arg))
447 c_strlen_data lendata = { };
448 /* Set MAXBOUND to an arbitrary non-null non-integer
449 node as a request to have it set to the length of
450 the longest string in a PHI. */
451 lendata.maxbound = arg;
452 get_range_strlen (arg, &lendata, /* eltsize = */ 1);
453 maxlen = lendata.maxbound;
455 if (nargs > 1)
456 bound = call_arg (exp, 1);
457 break;
460 default:
461 break;
464 /* Determine the range of the bound argument (if specified). */
465 tree bndrng[2] = { NULL_TREE, NULL_TREE };
466 if (bound)
468 STRIP_NOPS (bound);
469 get_size_range (bound, bndrng);
472 location_t loc = get_location (exp);
474 if (bndrng[0])
476 /* Diagnose excessive bound prior to the adjustment below and
477 regardless of attribute nonstring. */
478 tree maxobjsize = max_object_size ();
479 if (tree_int_cst_lt (maxobjsize, bndrng[0]))
481 bool warned = false;
482 if (tree_int_cst_equal (bndrng[0], bndrng[1]))
483 warned = warning_at (loc, OPT_Wstringop_overread,
484 "%qD specified bound %E "
485 "exceeds maximum object size %E",
486 fndecl, bndrng[0], maxobjsize);
487 else
488 warned = warning_at (loc, OPT_Wstringop_overread,
489 "%qD specified bound [%E, %E] "
490 "exceeds maximum object size %E",
491 fndecl, bndrng[0], bndrng[1],
492 maxobjsize);
493 if (warned)
494 suppress_warning (exp, OPT_Wstringop_overread);
496 return warned;
500 if (maxlen && !integer_all_onesp (maxlen))
502 /* Add one for the nul. */
503 maxlen = const_binop (PLUS_EXPR, TREE_TYPE (maxlen), maxlen,
504 size_one_node);
506 if (!bndrng[0])
508 /* Conservatively use the upper bound of the lengths for
509 both the lower and the upper bound of the operation. */
510 bndrng[0] = maxlen;
511 bndrng[1] = maxlen;
512 bound = void_type_node;
514 else if (maxlen)
516 /* Replace the bound on the operation with the upper bound
517 of the length of the string if the latter is smaller. */
518 if (tree_int_cst_lt (maxlen, bndrng[0]))
519 bndrng[0] = maxlen;
520 else if (tree_int_cst_lt (maxlen, bndrng[1]))
521 bndrng[1] = maxlen;
525 bool any_arg_warned = false;
526 /* Iterate over the built-in function's formal arguments and check
527 each const char* against the actual argument. If the actual
528 argument is declared attribute non-string issue a warning unless
529 the argument's maximum length is bounded. */
530 function_args_iterator it;
531 function_args_iter_init (&it, TREE_TYPE (fndecl));
533 for (unsigned argno = 0; ; ++argno, function_args_iter_next (&it))
535 /* Avoid iterating past the declared argument in a call
536 to function declared without a prototype. */
537 if (argno >= nargs)
538 break;
540 tree argtype = function_args_iter_cond (&it);
541 if (!argtype)
542 break;
544 if (TREE_CODE (argtype) != POINTER_TYPE)
545 continue;
547 argtype = TREE_TYPE (argtype);
549 if (TREE_CODE (argtype) != INTEGER_TYPE
550 || !TYPE_READONLY (argtype))
551 continue;
553 argtype = TYPE_MAIN_VARIANT (argtype);
554 if (argtype != char_type_node)
555 continue;
557 tree callarg = call_arg (exp, argno);
558 if (TREE_CODE (callarg) == ADDR_EXPR)
559 callarg = TREE_OPERAND (callarg, 0);
561 /* See if the destination is declared with attribute "nonstring". */
562 tree decl = get_attr_nonstring_decl (callarg);
563 if (!decl)
564 continue;
566 /* The maximum number of array elements accessed. */
567 offset_int wibnd = 0;
569 if (argno && fncode == BUILT_IN_STRNCAT)
571 /* See if the bound in strncat is derived from the length
572 of the strlen of the destination (as it's expected to be).
573 If so, reset BOUND and FNCODE to trigger a warning. */
574 tree dstarg = call_arg (exp, 0);
575 if (is_strlen_related_p (dstarg, bound))
577 /* The bound applies to the destination, not to the source,
578 so reset these to trigger a warning without mentioning
579 the bound. */
580 bound = NULL;
581 fncode = 0;
583 else if (bndrng[1])
584 /* Use the upper bound of the range for strncat. */
585 wibnd = wi::to_offset (bndrng[1]);
587 else if (bndrng[0])
588 /* Use the lower bound of the range for functions other than
589 strncat. */
590 wibnd = wi::to_offset (bndrng[0]);
592 /* Determine the size of the argument array if it is one. */
593 offset_int asize = wibnd;
594 bool known_size = false;
595 tree type = TREE_TYPE (decl);
597 /* Determine the array size. For arrays of unknown bound and
598 pointers reset BOUND to trigger the appropriate warning. */
599 if (TREE_CODE (type) == ARRAY_TYPE)
601 if (tree arrbnd = TYPE_DOMAIN (type))
603 if ((arrbnd = TYPE_MAX_VALUE (arrbnd)))
605 asize = wi::to_offset (arrbnd) + 1;
606 known_size = true;
609 else if (bound == void_type_node)
610 bound = NULL_TREE;
612 else if (bound == void_type_node)
613 bound = NULL_TREE;
615 /* In a call to strncat with a bound in a range whose lower but
616 not upper bound is less than the array size, reset ASIZE to
617 be the same as the bound and the other variable to trigger
618 the apprpriate warning below. */
619 if (fncode == BUILT_IN_STRNCAT
620 && bndrng[0] != bndrng[1]
621 && wi::ltu_p (wi::to_offset (bndrng[0]), asize)
622 && (!known_size
623 || wi::ltu_p (asize, wibnd)))
625 asize = wibnd;
626 bound = NULL_TREE;
627 fncode = 0;
630 bool warned = false;
632 auto_diagnostic_group d;
633 if (wi::ltu_p (asize, wibnd))
635 if (bndrng[0] == bndrng[1])
636 warned = warning_at (loc, OPT_Wstringop_overread,
637 "%qD argument %i declared attribute "
638 "%<nonstring%> is smaller than the specified "
639 "bound %wu",
640 fndecl, argno + 1, wibnd.to_uhwi ());
641 else if (wi::ltu_p (asize, wi::to_offset (bndrng[0])))
642 warned = warning_at (loc, OPT_Wstringop_overread,
643 "%qD argument %i declared attribute "
644 "%<nonstring%> is smaller than "
645 "the specified bound [%E, %E]",
646 fndecl, argno + 1, bndrng[0], bndrng[1]);
647 else
648 warned = warning_at (loc, OPT_Wstringop_overread,
649 "%qD argument %i declared attribute "
650 "%<nonstring%> may be smaller than "
651 "the specified bound [%E, %E]",
652 fndecl, argno + 1, bndrng[0], bndrng[1]);
654 else if (fncode == BUILT_IN_STRNCAT)
655 ; /* Avoid warning for calls to strncat() when the bound
656 is equal to the size of the non-string argument. */
657 else if (!bound)
658 warned = warning_at (loc, OPT_Wstringop_overread,
659 "%qD argument %i declared attribute %<nonstring%>",
660 fndecl, argno + 1);
662 if (warned)
664 inform (DECL_SOURCE_LOCATION (decl),
665 "argument %qD declared here", decl);
666 any_arg_warned = true;
670 if (any_arg_warned)
671 suppress_warning (exp, OPT_Wstringop_overread);
673 return any_arg_warned;
676 bool
677 maybe_warn_nonstring_arg (tree fndecl, gimple *stmt)
679 return maybe_warn_nonstring_arg<gimple *>(fndecl, stmt);
683 bool
684 maybe_warn_nonstring_arg (tree fndecl, tree expr)
686 return maybe_warn_nonstring_arg<tree>(fndecl, expr);
689 /* Issue a warning OPT for a bounded call EXP with a bound in RANGE
690 accessing an object with SIZE. */
692 template <class GimpleOrTree>
693 static bool
694 maybe_warn_for_bound (opt_code opt, location_t loc, GimpleOrTree exp, tree func,
695 tree bndrng[2], tree size, const access_data *pad)
697 if (!bndrng[0] || warning_suppressed_p (exp, opt))
698 return false;
700 tree maxobjsize = max_object_size ();
702 bool warned = false;
704 if (opt == OPT_Wstringop_overread)
706 bool maybe = pad && pad->src.phi ();
708 if (tree_int_cst_lt (maxobjsize, bndrng[0]))
710 if (bndrng[0] == bndrng[1])
711 warned = (func
712 ? warning_at (loc, opt,
713 (maybe
714 ? G_("%qD specified bound %E may "
715 "exceed maximum object size %E")
716 : G_("%qD specified bound %E "
717 "exceeds maximum object size %E")),
718 func, bndrng[0], maxobjsize)
719 : warning_at (loc, opt,
720 (maybe
721 ? G_("specified bound %E may "
722 "exceed maximum object size %E")
723 : G_("specified bound %E "
724 "exceeds maximum object size %E")),
725 bndrng[0], maxobjsize));
726 else
727 warned = (func
728 ? warning_at (loc, opt,
729 (maybe
730 ? G_("%qD specified bound [%E, %E] may "
731 "exceed maximum object size %E")
732 : G_("%qD specified bound [%E, %E] "
733 "exceeds maximum object size %E")),
734 func,
735 bndrng[0], bndrng[1], maxobjsize)
736 : warning_at (loc, opt,
737 (maybe
738 ? G_("specified bound [%E, %E] may "
739 "exceed maximum object size %E")
740 : G_("specified bound [%E, %E] "
741 "exceeds maximum object size %E")),
742 bndrng[0], bndrng[1], maxobjsize));
744 else if (!size || tree_int_cst_le (bndrng[0], size))
745 return false;
746 else if (tree_int_cst_equal (bndrng[0], bndrng[1]))
747 warned = (func
748 ? warning_at (loc, opt,
749 (maybe
750 ? G_("%qD specified bound %E may exceed "
751 "source size %E")
752 : G_("%qD specified bound %E exceeds "
753 "source size %E")),
754 func, bndrng[0], size)
755 : warning_at (loc, opt,
756 (maybe
757 ? G_("specified bound %E may exceed "
758 "source size %E")
759 : G_("specified bound %E exceeds "
760 "source size %E")),
761 bndrng[0], size));
762 else
763 warned = (func
764 ? warning_at (loc, opt,
765 (maybe
766 ? G_("%qD specified bound [%E, %E] may "
767 "exceed source size %E")
768 : G_("%qD specified bound [%E, %E] exceeds "
769 "source size %E")),
770 func, bndrng[0], bndrng[1], size)
771 : warning_at (loc, opt,
772 (maybe
773 ? G_("specified bound [%E, %E] may exceed "
774 "source size %E")
775 : G_("specified bound [%E, %E] exceeds "
776 "source size %E")),
777 bndrng[0], bndrng[1], size));
778 if (warned)
780 if (pad && pad->src.ref
781 && has_location (pad->src.ref))
782 inform (get_location (pad->src.ref),
783 "source object allocated here");
784 suppress_warning (exp, opt);
787 return warned;
790 bool maybe = pad && pad->dst.phi ();
791 if (tree_int_cst_lt (maxobjsize, bndrng[0]))
793 if (bndrng[0] == bndrng[1])
794 warned = (func
795 ? warning_at (loc, opt,
796 (maybe
797 ? G_("%qD specified size %E may "
798 "exceed maximum object size %E")
799 : G_("%qD specified size %E "
800 "exceeds maximum object size %E")),
801 func, bndrng[0], maxobjsize)
802 : warning_at (loc, opt,
803 (maybe
804 ? G_("specified size %E may exceed "
805 "maximum object size %E")
806 : G_("specified size %E exceeds "
807 "maximum object size %E")),
808 bndrng[0], maxobjsize));
809 else
810 warned = (func
811 ? warning_at (loc, opt,
812 (maybe
813 ? G_("%qD specified size between %E and %E "
814 "may exceed maximum object size %E")
815 : G_("%qD specified size between %E and %E "
816 "exceeds maximum object size %E")),
817 func, bndrng[0], bndrng[1], maxobjsize)
818 : warning_at (loc, opt,
819 (maybe
820 ? G_("specified size between %E and %E "
821 "may exceed maximum object size %E")
822 : G_("specified size between %E and %E "
823 "exceeds maximum object size %E")),
824 bndrng[0], bndrng[1], maxobjsize));
826 else if (!size || tree_int_cst_le (bndrng[0], size))
827 return false;
828 else if (tree_int_cst_equal (bndrng[0], bndrng[1]))
829 warned = (func
830 ? warning_at (loc, opt,
831 (maybe
832 ? G_("%qD specified bound %E may exceed "
833 "destination size %E")
834 : G_("%qD specified bound %E exceeds "
835 "destination size %E")),
836 func, bndrng[0], size)
837 : warning_at (loc, opt,
838 (maybe
839 ? G_("specified bound %E may exceed "
840 "destination size %E")
841 : G_("specified bound %E exceeds "
842 "destination size %E")),
843 bndrng[0], size));
844 else
845 warned = (func
846 ? warning_at (loc, opt,
847 (maybe
848 ? G_("%qD specified bound [%E, %E] may exceed "
849 "destination size %E")
850 : G_("%qD specified bound [%E, %E] exceeds "
851 "destination size %E")),
852 func, bndrng[0], bndrng[1], size)
853 : warning_at (loc, opt,
854 (maybe
855 ? G_("specified bound [%E, %E] exceeds "
856 "destination size %E")
857 : G_("specified bound [%E, %E] exceeds "
858 "destination size %E")),
859 bndrng[0], bndrng[1], size));
861 if (warned)
863 if (pad && pad->dst.ref
864 && has_location (pad->dst.ref))
865 inform (get_location (pad->dst.ref),
866 "destination object allocated here");
867 suppress_warning (exp, opt);
870 return warned;
873 bool
874 maybe_warn_for_bound (opt_code opt, location_t loc, gimple *stmt, tree func,
875 tree bndrng[2], tree size,
876 const access_data *pad /* = NULL */)
878 return maybe_warn_for_bound<gimple *> (opt, loc, stmt, func, bndrng, size,
879 pad);
882 bool
883 maybe_warn_for_bound (opt_code opt, location_t loc, tree expr, tree func,
884 tree bndrng[2], tree size,
885 const access_data *pad /* = NULL */)
887 return maybe_warn_for_bound<tree> (opt, loc, expr, func, bndrng, size, pad);
890 /* For an expression EXP issue an access warning controlled by option OPT
891 with access to a region SIZE bytes in size in the RANGE of sizes.
892 WRITE is true for a write access, READ for a read access, neither for
893 call that may or may not perform an access but for which the range
894 is expected to valid.
895 Returns true when a warning has been issued. */
897 template <class GimpleOrTree>
898 static bool
899 warn_for_access (location_t loc, tree func, GimpleOrTree exp, int opt,
900 tree range[2], tree size, bool write, bool read, bool maybe)
902 bool warned = false;
904 if (write && read)
906 if (tree_int_cst_equal (range[0], range[1]))
907 warned = (func
908 ? warning_n (loc, opt, tree_to_uhwi (range[0]),
909 (maybe
910 ? G_("%qD may access %E byte in a region "
911 "of size %E")
912 : G_("%qD accessing %E byte in a region "
913 "of size %E")),
914 (maybe
915 ? G_ ("%qD may access %E bytes in a region "
916 "of size %E")
917 : G_ ("%qD accessing %E bytes in a region "
918 "of size %E")),
919 func, range[0], size)
920 : warning_n (loc, opt, tree_to_uhwi (range[0]),
921 (maybe
922 ? G_("may access %E byte in a region "
923 "of size %E")
924 : G_("accessing %E byte in a region "
925 "of size %E")),
926 (maybe
927 ? G_("may access %E bytes in a region "
928 "of size %E")
929 : G_("accessing %E bytes in a region "
930 "of size %E")),
931 range[0], size));
932 else if (tree_int_cst_sign_bit (range[1]))
934 /* Avoid printing the upper bound if it's invalid. */
935 warned = (func
936 ? warning_at (loc, opt,
937 (maybe
938 ? G_("%qD may access %E or more bytes "
939 "in a region of size %E")
940 : G_("%qD accessing %E or more bytes "
941 "in a region of size %E")),
942 func, range[0], size)
943 : warning_at (loc, opt,
944 (maybe
945 ? G_("may access %E or more bytes "
946 "in a region of size %E")
947 : G_("accessing %E or more bytes "
948 "in a region of size %E")),
949 range[0], size));
951 else
952 warned = (func
953 ? warning_at (loc, opt,
954 (maybe
955 ? G_("%qD may access between %E and %E "
956 "bytes in a region of size %E")
957 : G_("%qD accessing between %E and %E "
958 "bytes in a region of size %E")),
959 func, range[0], range[1], size)
960 : warning_at (loc, opt,
961 (maybe
962 ? G_("may access between %E and %E bytes "
963 "in a region of size %E")
964 : G_("accessing between %E and %E bytes "
965 "in a region of size %E")),
966 range[0], range[1], size));
967 return warned;
970 if (write)
972 if (tree_int_cst_equal (range[0], range[1]))
973 warned = (func
974 ? warning_n (loc, opt, tree_to_uhwi (range[0]),
975 (maybe
976 ? G_("%qD may write %E byte into a region "
977 "of size %E")
978 : G_("%qD writing %E byte into a region "
979 "of size %E overflows the destination")),
980 (maybe
981 ? G_("%qD may write %E bytes into a region "
982 "of size %E")
983 : G_("%qD writing %E bytes into a region "
984 "of size %E overflows the destination")),
985 func, range[0], size)
986 : warning_n (loc, opt, tree_to_uhwi (range[0]),
987 (maybe
988 ? G_("may write %E byte into a region "
989 "of size %E")
990 : G_("writing %E byte into a region "
991 "of size %E overflows the destination")),
992 (maybe
993 ? G_("may write %E bytes into a region "
994 "of size %E")
995 : G_("writing %E bytes into a region "
996 "of size %E overflows the destination")),
997 range[0], size));
998 else if (tree_int_cst_sign_bit (range[1]))
1000 /* Avoid printing the upper bound if it's invalid. */
1001 warned = (func
1002 ? warning_at (loc, opt,
1003 (maybe
1004 ? G_("%qD may write %E or more bytes "
1005 "into a region of size %E")
1006 : G_("%qD writing %E or more bytes "
1007 "into a region of size %E overflows "
1008 "the destination")),
1009 func, range[0], size)
1010 : warning_at (loc, opt,
1011 (maybe
1012 ? G_("may write %E or more bytes into "
1013 "a region of size %E")
1014 : G_("writing %E or more bytes into "
1015 "a region of size %E overflows "
1016 "the destination")),
1017 range[0], size));
1019 else
1020 warned = (func
1021 ? warning_at (loc, opt,
1022 (maybe
1023 ? G_("%qD may write between %E and %E bytes "
1024 "into a region of size %E")
1025 : G_("%qD writing between %E and %E bytes "
1026 "into a region of size %E overflows "
1027 "the destination")),
1028 func, range[0], range[1], size)
1029 : warning_at (loc, opt,
1030 (maybe
1031 ? G_("may write between %E and %E bytes "
1032 "into a region of size %E")
1033 : G_("writing between %E and %E bytes "
1034 "into a region of size %E overflows "
1035 "the destination")),
1036 range[0], range[1], size));
1037 return warned;
1040 if (read)
1042 if (tree_int_cst_equal (range[0], range[1]))
1043 warned = (func
1044 ? warning_n (loc, OPT_Wstringop_overread,
1045 tree_to_uhwi (range[0]),
1046 (maybe
1047 ? G_("%qD may read %E byte from a region "
1048 "of size %E")
1049 : G_("%qD reading %E byte from a region "
1050 "of size %E")),
1051 (maybe
1052 ? G_("%qD may read %E bytes from a region "
1053 "of size %E")
1054 : G_("%qD reading %E bytes from a region "
1055 "of size %E")),
1056 func, range[0], size)
1057 : warning_n (loc, OPT_Wstringop_overread,
1058 tree_to_uhwi (range[0]),
1059 (maybe
1060 ? G_("may read %E byte from a region "
1061 "of size %E")
1062 : G_("reading %E byte from a region "
1063 "of size %E")),
1064 (maybe
1065 ? G_("may read %E bytes from a region "
1066 "of size %E")
1067 : G_("reading %E bytes from a region "
1068 "of size %E")),
1069 range[0], size));
1070 else if (tree_int_cst_sign_bit (range[1]))
1072 /* Avoid printing the upper bound if it's invalid. */
1073 warned = (func
1074 ? warning_at (loc, OPT_Wstringop_overread,
1075 (maybe
1076 ? G_("%qD may read %E or more bytes "
1077 "from a region of size %E")
1078 : G_("%qD reading %E or more bytes "
1079 "from a region of size %E")),
1080 func, range[0], size)
1081 : warning_at (loc, OPT_Wstringop_overread,
1082 (maybe
1083 ? G_("may read %E or more bytes "
1084 "from a region of size %E")
1085 : G_("reading %E or more bytes "
1086 "from a region of size %E")),
1087 range[0], size));
1089 else
1090 warned = (func
1091 ? warning_at (loc, OPT_Wstringop_overread,
1092 (maybe
1093 ? G_("%qD may read between %E and %E bytes "
1094 "from a region of size %E")
1095 : G_("%qD reading between %E and %E bytes "
1096 "from a region of size %E")),
1097 func, range[0], range[1], size)
1098 : warning_at (loc, opt,
1099 (maybe
1100 ? G_("may read between %E and %E bytes "
1101 "from a region of size %E")
1102 : G_("reading between %E and %E bytes "
1103 "from a region of size %E")),
1104 range[0], range[1], size));
1106 if (warned)
1107 suppress_warning (exp, OPT_Wstringop_overread);
1109 return warned;
1112 if (tree_int_cst_equal (range[0], range[1])
1113 || tree_int_cst_sign_bit (range[1]))
1114 warned = (func
1115 ? warning_n (loc, OPT_Wstringop_overread,
1116 tree_to_uhwi (range[0]),
1117 "%qD expecting %E byte in a region of size %E",
1118 "%qD expecting %E bytes in a region of size %E",
1119 func, range[0], size)
1120 : warning_n (loc, OPT_Wstringop_overread,
1121 tree_to_uhwi (range[0]),
1122 "expecting %E byte in a region of size %E",
1123 "expecting %E bytes in a region of size %E",
1124 range[0], size));
1125 else if (tree_int_cst_sign_bit (range[1]))
1127 /* Avoid printing the upper bound if it's invalid. */
1128 warned = (func
1129 ? warning_at (loc, OPT_Wstringop_overread,
1130 "%qD expecting %E or more bytes in a region "
1131 "of size %E",
1132 func, range[0], size)
1133 : warning_at (loc, OPT_Wstringop_overread,
1134 "expecting %E or more bytes in a region "
1135 "of size %E",
1136 range[0], size));
1138 else
1139 warned = (func
1140 ? warning_at (loc, OPT_Wstringop_overread,
1141 "%qD expecting between %E and %E bytes in "
1142 "a region of size %E",
1143 func, range[0], range[1], size)
1144 : warning_at (loc, OPT_Wstringop_overread,
1145 "expecting between %E and %E bytes in "
1146 "a region of size %E",
1147 range[0], range[1], size));
1149 if (warned)
1150 suppress_warning (exp, OPT_Wstringop_overread);
1152 return warned;
1155 static bool
1156 warn_for_access (location_t loc, tree func, gimple *stmt, int opt,
1157 tree range[2], tree size, bool write, bool read, bool maybe)
1159 return warn_for_access<gimple *>(loc, func, stmt, opt, range, size,
1160 write, read, maybe);
1163 static bool
1164 warn_for_access (location_t loc, tree func, tree expr, int opt,
1165 tree range[2], tree size, bool write, bool read, bool maybe)
1167 return warn_for_access<tree>(loc, func, expr, opt, range, size,
1168 write, read, maybe);
1171 /* Helper to set RANGE to the range of BOUND if it's nonnull, bounded
1172 by BNDRNG if nonnull and valid. */
1174 static void
1175 get_size_range (tree bound, tree range[2], const offset_int bndrng[2])
1177 if (bound)
1178 get_size_range (bound, range);
1180 if (!bndrng || (bndrng[0] == 0 && bndrng[1] == HOST_WIDE_INT_M1U))
1181 return;
1183 if (range[0] && TREE_CODE (range[0]) == INTEGER_CST)
1185 offset_int r[] =
1186 { wi::to_offset (range[0]), wi::to_offset (range[1]) };
1187 if (r[0] < bndrng[0])
1188 range[0] = wide_int_to_tree (sizetype, bndrng[0]);
1189 if (bndrng[1] < r[1])
1190 range[1] = wide_int_to_tree (sizetype, bndrng[1]);
1192 else
1194 range[0] = wide_int_to_tree (sizetype, bndrng[0]);
1195 range[1] = wide_int_to_tree (sizetype, bndrng[1]);
1199 /* Try to verify that the sizes and lengths of the arguments to a string
1200 manipulation function given by EXP are within valid bounds and that
1201 the operation does not lead to buffer overflow or read past the end.
1202 Arguments other than EXP may be null. When non-null, the arguments
1203 have the following meaning:
1204 DST is the destination of a copy call or NULL otherwise.
1205 SRC is the source of a copy call or NULL otherwise.
1206 DSTWRITE is the number of bytes written into the destination obtained
1207 from the user-supplied size argument to the function (such as in
1208 memcpy(DST, SRCs, DSTWRITE) or strncpy(DST, DRC, DSTWRITE).
1209 MAXREAD is the user-supplied bound on the length of the source sequence
1210 (such as in strncat(d, s, N). It specifies the upper limit on the number
1211 of bytes to write. If NULL, it's taken to be the same as DSTWRITE.
1212 SRCSTR is the source string (such as in strcpy(DST, SRC)) when the
1213 expression EXP is a string function call (as opposed to a memory call
1214 like memcpy). As an exception, SRCSTR can also be an integer denoting
1215 the precomputed size of the source string or object (for functions like
1216 memcpy).
1217 DSTSIZE is the size of the destination object.
1219 When DSTWRITE is null LEN is checked to verify that it doesn't exceed
1220 SIZE_MAX.
1222 WRITE is true for write accesses, READ is true for reads. Both are
1223 false for simple size checks in calls to functions that neither read
1224 from nor write to the region.
1226 When nonnull, PAD points to a more detailed description of the access.
1228 If the call is successfully verified as safe return true, otherwise
1229 return false. */
1231 template <class GimpleOrTree>
1232 static bool
1233 check_access (GimpleOrTree exp, tree dstwrite,
1234 tree maxread, tree srcstr, tree dstsize,
1235 access_mode mode, const access_data *pad /* = NULL */)
1237 /* The size of the largest object is half the address space, or
1238 PTRDIFF_MAX. (This is way too permissive.) */
1239 tree maxobjsize = max_object_size ();
1241 /* Either an approximate/minimum the length of the source string for
1242 string functions or the size of the source object for raw memory
1243 functions. */
1244 tree slen = NULL_TREE;
1246 /* The range of the access in bytes; first set to the write access
1247 for functions that write and then read for those that also (or
1248 just) read. */
1249 tree range[2] = { NULL_TREE, NULL_TREE };
1251 /* Set to true when the exact number of bytes written by a string
1252 function like strcpy is not known and the only thing that is
1253 known is that it must be at least one (for the terminating nul). */
1254 bool at_least_one = false;
1255 if (srcstr)
1257 /* SRCSTR is normally a pointer to string but as a special case
1258 it can be an integer denoting the length of a string. */
1259 if (POINTER_TYPE_P (TREE_TYPE (srcstr)))
1261 if (!check_nul_terminated_array (exp, srcstr, maxread))
1262 /* Return if the array is not nul-terminated and a warning
1263 has been issued. */
1264 return false;
1266 /* Try to determine the range of lengths the source string
1267 refers to. If it can be determined and is less than
1268 the upper bound given by MAXREAD add one to it for
1269 the terminating nul. Otherwise, set it to one for
1270 the same reason, or to MAXREAD as appropriate. */
1271 c_strlen_data lendata = { };
1272 get_range_strlen (srcstr, &lendata, /* eltsize = */ 1);
1273 range[0] = lendata.minlen;
1274 range[1] = lendata.maxbound ? lendata.maxbound : lendata.maxlen;
1275 if (range[0]
1276 && TREE_CODE (range[0]) == INTEGER_CST
1277 && TREE_CODE (range[1]) == INTEGER_CST
1278 && (!maxread || TREE_CODE (maxread) == INTEGER_CST))
1280 if (maxread && tree_int_cst_le (maxread, range[0]))
1281 range[0] = range[1] = maxread;
1282 else
1283 range[0] = fold_build2 (PLUS_EXPR, size_type_node,
1284 range[0], size_one_node);
1286 if (maxread && tree_int_cst_le (maxread, range[1]))
1287 range[1] = maxread;
1288 else if (!integer_all_onesp (range[1]))
1289 range[1] = fold_build2 (PLUS_EXPR, size_type_node,
1290 range[1], size_one_node);
1292 slen = range[0];
1294 else
1296 at_least_one = true;
1297 slen = size_one_node;
1300 else
1301 slen = srcstr;
1304 if (!dstwrite && !maxread)
1306 /* When the only available piece of data is the object size
1307 there is nothing to do. */
1308 if (!slen)
1309 return true;
1311 /* Otherwise, when the length of the source sequence is known
1312 (as with strlen), set DSTWRITE to it. */
1313 if (!range[0])
1314 dstwrite = slen;
1317 if (!dstsize)
1318 dstsize = maxobjsize;
1320 /* Set RANGE to that of DSTWRITE if non-null, bounded by PAD->DST.BNDRNG
1321 if valid. */
1322 get_size_range (dstwrite, range, pad ? pad->dst.bndrng : NULL);
1324 tree func = get_callee_fndecl (exp);
1325 /* Read vs write access by built-ins can be determined from the const
1326 qualifiers on the pointer argument. In the absence of attribute
1327 access, non-const qualified pointer arguments to user-defined
1328 functions are assumed to both read and write the objects. */
1329 const bool builtin = func ? fndecl_built_in_p (func) : false;
1331 /* First check the number of bytes to be written against the maximum
1332 object size. */
1333 if (range[0]
1334 && TREE_CODE (range[0]) == INTEGER_CST
1335 && tree_int_cst_lt (maxobjsize, range[0]))
1337 location_t loc = get_location (exp);
1338 maybe_warn_for_bound (OPT_Wstringop_overflow_, loc, exp, func, range,
1339 NULL_TREE, pad);
1340 return false;
1343 /* The number of bytes to write is "exact" if DSTWRITE is non-null,
1344 constant, and in range of unsigned HOST_WIDE_INT. */
1345 bool exactwrite = dstwrite && tree_fits_uhwi_p (dstwrite);
1347 /* Next check the number of bytes to be written against the destination
1348 object size. */
1349 if (range[0] || !exactwrite || integer_all_onesp (dstwrite))
1351 if (range[0]
1352 && TREE_CODE (range[0]) == INTEGER_CST
1353 && ((tree_fits_uhwi_p (dstsize)
1354 && tree_int_cst_lt (dstsize, range[0]))
1355 || (dstwrite
1356 && tree_fits_uhwi_p (dstwrite)
1357 && tree_int_cst_lt (dstwrite, range[0]))))
1359 const opt_code opt = OPT_Wstringop_overflow_;
1360 if (warning_suppressed_p (exp, opt)
1361 || (pad && pad->dst.ref
1362 && warning_suppressed_p (pad->dst.ref, opt)))
1363 return false;
1365 location_t loc = get_location (exp);
1366 bool warned = false;
1367 if (dstwrite == slen && at_least_one)
1369 /* This is a call to strcpy with a destination of 0 size
1370 and a source of unknown length. The call will write
1371 at least one byte past the end of the destination. */
1372 warned = (func
1373 ? warning_at (loc, opt,
1374 "%qD writing %E or more bytes into "
1375 "a region of size %E overflows "
1376 "the destination",
1377 func, range[0], dstsize)
1378 : warning_at (loc, opt,
1379 "writing %E or more bytes into "
1380 "a region of size %E overflows "
1381 "the destination",
1382 range[0], dstsize));
1384 else
1386 const bool read
1387 = mode == access_read_only || mode == access_read_write;
1388 const bool write
1389 = mode == access_write_only || mode == access_read_write;
1390 const bool maybe = pad && pad->dst.parmarray;
1391 warned = warn_for_access (loc, func, exp,
1392 OPT_Wstringop_overflow_,
1393 range, dstsize,
1394 write, read && !builtin, maybe);
1397 if (warned)
1399 suppress_warning (exp, OPT_Wstringop_overflow_);
1400 if (pad)
1401 pad->dst.inform_access (pad->mode);
1404 /* Return error when an overflow has been detected. */
1405 return false;
1409 /* Check the maximum length of the source sequence against the size
1410 of the destination object if known, or against the maximum size
1411 of an object. */
1412 if (maxread)
1414 /* Set RANGE to that of MAXREAD, bounded by PAD->SRC.BNDRNG if
1415 PAD is nonnull and BNDRNG is valid. */
1416 get_size_range (maxread, range, pad ? pad->src.bndrng : NULL);
1418 location_t loc = get_location (exp);
1419 tree size = dstsize;
1420 if (pad && pad->mode == access_read_only)
1421 size = wide_int_to_tree (sizetype, pad->src.sizrng[1]);
1423 if (range[0] && maxread && tree_fits_uhwi_p (size))
1425 if (tree_int_cst_lt (maxobjsize, range[0]))
1427 maybe_warn_for_bound (OPT_Wstringop_overread, loc, exp, func,
1428 range, size, pad);
1429 return false;
1432 if (size != maxobjsize && tree_int_cst_lt (size, range[0]))
1434 opt_code opt = (dstwrite || mode != access_read_only
1435 ? OPT_Wstringop_overflow_
1436 : OPT_Wstringop_overread);
1437 maybe_warn_for_bound (opt, loc, exp, func, range, size, pad);
1438 return false;
1442 maybe_warn_nonstring_arg (func, exp);
1445 /* Check for reading past the end of SRC. */
1446 bool overread = (slen
1447 && slen == srcstr
1448 && dstwrite
1449 && range[0]
1450 && TREE_CODE (slen) == INTEGER_CST
1451 && tree_int_cst_lt (slen, range[0]));
1452 /* If none is determined try to get a better answer based on the details
1453 in PAD. */
1454 if (!overread
1455 && pad
1456 && pad->src.sizrng[1] >= 0
1457 && pad->src.offrng[0] >= 0
1458 && (pad->src.offrng[1] < 0
1459 || pad->src.offrng[0] <= pad->src.offrng[1]))
1461 /* Set RANGE to that of MAXREAD, bounded by PAD->SRC.BNDRNG if
1462 PAD is nonnull and BNDRNG is valid. */
1463 get_size_range (maxread, range, pad ? pad->src.bndrng : NULL);
1464 /* Set OVERREAD for reads starting just past the end of an object. */
1465 overread = pad->src.sizrng[1] - pad->src.offrng[0] < pad->src.bndrng[0];
1466 range[0] = wide_int_to_tree (sizetype, pad->src.bndrng[0]);
1467 slen = size_zero_node;
1470 if (overread)
1472 const opt_code opt = OPT_Wstringop_overread;
1473 if (warning_suppressed_p (exp, opt)
1474 || (srcstr && warning_suppressed_p (srcstr, opt))
1475 || (pad && pad->src.ref
1476 && warning_suppressed_p (pad->src.ref, opt)))
1477 return false;
1479 location_t loc = get_location (exp);
1480 const bool read
1481 = mode == access_read_only || mode == access_read_write;
1482 const bool maybe = pad && pad->dst.parmarray;
1483 if (warn_for_access (loc, func, exp, opt, range, slen, false, read,
1484 maybe))
1486 suppress_warning (exp, opt);
1487 if (pad)
1488 pad->src.inform_access (access_read_only);
1490 return false;
1493 return true;
1496 bool
1497 check_access (gimple *stmt, tree dstwrite,
1498 tree maxread, tree srcstr, tree dstsize,
1499 access_mode mode, const access_data *pad /* = NULL */)
1501 return check_access<gimple *>(stmt, dstwrite, maxread, srcstr, dstsize,
1502 mode, pad);
1505 bool
1506 check_access (tree expr, tree dstwrite,
1507 tree maxread, tree srcstr, tree dstsize,
1508 access_mode mode, const access_data *pad /* = NULL */)
1510 return check_access<tree>(expr, dstwrite, maxread, srcstr, dstsize,
1511 mode, pad);
1514 /* Helper to determine and check the sizes of the source and the destination
1515 of calls to __builtin_{bzero,memcpy,mempcpy,memset} calls. EXP is the
1516 call expression, DEST is the destination argument, SRC is the source
1517 argument or null, and LEN is the number of bytes. Use Object Size type-0
1518 regardless of the OPT_Wstringop_overflow_ setting. Return true on success
1519 (no overflow or invalid sizes), false otherwise. */
1521 template <class GimpleOrTree>
1522 static bool
1523 check_memop_access (GimpleOrTree expr, tree dest, tree src, tree size)
1525 /* For functions like memset and memcpy that operate on raw memory
1526 try to determine the size of the largest source and destination
1527 object using type-0 Object Size regardless of the object size
1528 type specified by the option. */
1529 access_data data (expr, access_read_write);
1530 tree srcsize = src ? compute_objsize (src, 0, &data.src) : NULL_TREE;
1531 tree dstsize = compute_objsize (dest, 0, &data.dst);
1533 return check_access (expr, size, /*maxread=*/NULL_TREE,
1534 srcsize, dstsize, data.mode, &data);
1537 bool
1538 check_memop_access (gimple *stmt, tree dest, tree src, tree size)
1540 return check_memop_access<gimple *>(stmt, dest, src, size);
1543 bool
1544 check_memop_access (tree expr, tree dest, tree src, tree size)
1546 return check_memop_access<tree>(expr, dest, src, size);
1549 /* A convenience wrapper for check_access above to check access
1550 by a read-only function like puts. */
1552 template <class GimpleOrTree>
1553 static bool
1554 check_read_access (GimpleOrTree expr, tree src, tree bound, int ost)
1556 if (!warn_stringop_overread)
1557 return true;
1559 if (bound && !useless_type_conversion_p (size_type_node, TREE_TYPE (bound)))
1560 bound = fold_convert (size_type_node, bound);
1562 tree fndecl = get_callee_fndecl (expr);
1563 maybe_warn_nonstring_arg (fndecl, expr);
1565 access_data data (expr, access_read_only, NULL_TREE, false, bound, true);
1566 compute_objsize (src, ost, &data.src);
1567 return check_access (expr, /*dstwrite=*/ NULL_TREE, /*maxread=*/ bound,
1568 /*srcstr=*/ src, /*dstsize=*/ NULL_TREE, data.mode,
1569 &data);
1572 bool
1573 check_read_access (gimple *stmt, tree src, tree bound /* = NULL_TREE */,
1574 int ost /* = 1 */)
1576 return check_read_access<gimple *>(stmt, src, bound, ost);
1579 bool
1580 check_read_access (tree expr, tree src, tree bound /* = NULL_TREE */,
1581 int ost /* = 1 */)
1583 return check_read_access<tree>(expr, src, bound, ost);
1586 /* Return true if STMT is a call to an allocation function. Unless
1587 ALL_ALLOC is set, consider only functions that return dynmamically
1588 allocated objects. Otherwise return true even for all forms of
1589 alloca (including VLA). */
1591 static bool
1592 fndecl_alloc_p (tree fndecl, bool all_alloc)
1594 if (!fndecl)
1595 return false;
1597 /* A call to operator new isn't recognized as one to a built-in. */
1598 if (DECL_IS_OPERATOR_NEW_P (fndecl))
1599 return true;
1601 if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
1603 switch (DECL_FUNCTION_CODE (fndecl))
1605 case BUILT_IN_ALLOCA:
1606 case BUILT_IN_ALLOCA_WITH_ALIGN:
1607 return all_alloc;
1608 case BUILT_IN_ALIGNED_ALLOC:
1609 case BUILT_IN_CALLOC:
1610 case BUILT_IN_GOMP_ALLOC:
1611 case BUILT_IN_MALLOC:
1612 case BUILT_IN_REALLOC:
1613 case BUILT_IN_STRDUP:
1614 case BUILT_IN_STRNDUP:
1615 return true;
1616 default:
1617 break;
1621 /* A function is considered an allocation function if it's declared
1622 with attribute malloc with an argument naming its associated
1623 deallocation function. */
1624 tree attrs = DECL_ATTRIBUTES (fndecl);
1625 if (!attrs)
1626 return false;
1628 for (tree allocs = attrs;
1629 (allocs = lookup_attribute ("malloc", allocs));
1630 allocs = TREE_CHAIN (allocs))
1632 tree args = TREE_VALUE (allocs);
1633 if (!args)
1634 continue;
1636 if (TREE_VALUE (args))
1637 return true;
1640 return false;
1643 /* Return true if STMT is a call to an allocation function. A wrapper
1644 around fndecl_alloc_p. */
1646 static bool
1647 gimple_call_alloc_p (gimple *stmt, bool all_alloc = false)
1649 return fndecl_alloc_p (gimple_call_fndecl (stmt), all_alloc);
1652 /* Return true if DELC doesn't refer to an operator delete that's
1653 suitable to call with a pointer returned from the operator new
1654 described by NEWC. */
1656 static bool
1657 new_delete_mismatch_p (const demangle_component &newc,
1658 const demangle_component &delc)
1660 if (newc.type != delc.type)
1661 return true;
1663 switch (newc.type)
1665 case DEMANGLE_COMPONENT_NAME:
1667 int len = newc.u.s_name.len;
1668 const char *news = newc.u.s_name.s;
1669 const char *dels = delc.u.s_name.s;
1670 if (len != delc.u.s_name.len || memcmp (news, dels, len))
1671 return true;
1673 if (news[len] == 'n')
1675 if (news[len + 1] == 'a')
1676 return dels[len] != 'd' || dels[len + 1] != 'a';
1677 if (news[len + 1] == 'w')
1678 return dels[len] != 'd' || dels[len + 1] != 'l';
1680 return false;
1683 case DEMANGLE_COMPONENT_OPERATOR:
1684 /* Operator mismatches are handled above. */
1685 return false;
1687 case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
1688 if (newc.u.s_extended_operator.args != delc.u.s_extended_operator.args)
1689 return true;
1690 return new_delete_mismatch_p (*newc.u.s_extended_operator.name,
1691 *delc.u.s_extended_operator.name);
1693 case DEMANGLE_COMPONENT_FIXED_TYPE:
1694 if (newc.u.s_fixed.accum != delc.u.s_fixed.accum
1695 || newc.u.s_fixed.sat != delc.u.s_fixed.sat)
1696 return true;
1697 return new_delete_mismatch_p (*newc.u.s_fixed.length,
1698 *delc.u.s_fixed.length);
1700 case DEMANGLE_COMPONENT_CTOR:
1701 if (newc.u.s_ctor.kind != delc.u.s_ctor.kind)
1702 return true;
1703 return new_delete_mismatch_p (*newc.u.s_ctor.name,
1704 *delc.u.s_ctor.name);
1706 case DEMANGLE_COMPONENT_DTOR:
1707 if (newc.u.s_dtor.kind != delc.u.s_dtor.kind)
1708 return true;
1709 return new_delete_mismatch_p (*newc.u.s_dtor.name,
1710 *delc.u.s_dtor.name);
1712 case DEMANGLE_COMPONENT_BUILTIN_TYPE:
1714 /* The demangler API provides no better way to compare built-in
1715 types except to by comparing their demangled names. */
1716 size_t nsz, dsz;
1717 demangle_component *pnc = const_cast<demangle_component *>(&newc);
1718 demangle_component *pdc = const_cast<demangle_component *>(&delc);
1719 char *nts = cplus_demangle_print (0, pnc, 16, &nsz);
1720 char *dts = cplus_demangle_print (0, pdc, 16, &dsz);
1721 if (!nts != !dts)
1722 return true;
1723 bool mismatch = strcmp (nts, dts);
1724 free (nts);
1725 free (dts);
1726 return mismatch;
1729 case DEMANGLE_COMPONENT_SUB_STD:
1730 if (newc.u.s_string.len != delc.u.s_string.len)
1731 return true;
1732 return memcmp (newc.u.s_string.string, delc.u.s_string.string,
1733 newc.u.s_string.len);
1735 case DEMANGLE_COMPONENT_FUNCTION_PARAM:
1736 case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
1737 return newc.u.s_number.number != delc.u.s_number.number;
1739 case DEMANGLE_COMPONENT_CHARACTER:
1740 return newc.u.s_character.character != delc.u.s_character.character;
1742 case DEMANGLE_COMPONENT_DEFAULT_ARG:
1743 case DEMANGLE_COMPONENT_LAMBDA:
1744 if (newc.u.s_unary_num.num != delc.u.s_unary_num.num)
1745 return true;
1746 return new_delete_mismatch_p (*newc.u.s_unary_num.sub,
1747 *delc.u.s_unary_num.sub);
1748 default:
1749 break;
1752 if (!newc.u.s_binary.left != !delc.u.s_binary.left)
1753 return true;
1755 if (!newc.u.s_binary.left)
1756 return false;
1758 if (new_delete_mismatch_p (*newc.u.s_binary.left, *delc.u.s_binary.left)
1759 || !newc.u.s_binary.right != !delc.u.s_binary.right)
1760 return true;
1762 if (newc.u.s_binary.right)
1763 return new_delete_mismatch_p (*newc.u.s_binary.right,
1764 *delc.u.s_binary.right);
1765 return false;
1768 /* Return true if DELETE_DECL is an operator delete that's not suitable
1769 to call with a pointer returned fron NEW_DECL. */
1771 static bool
1772 new_delete_mismatch_p (tree new_decl, tree delete_decl)
1774 tree new_name = DECL_ASSEMBLER_NAME (new_decl);
1775 tree delete_name = DECL_ASSEMBLER_NAME (delete_decl);
1777 /* valid_new_delete_pair_p() returns a conservative result (currently
1778 it only handles global operators). A true result is reliable but
1779 a false result doesn't necessarily mean the operators don't match
1780 unless CERTAIN is set. */
1781 bool certain;
1782 if (valid_new_delete_pair_p (new_name, delete_name, &certain))
1783 return false;
1784 /* CERTAIN is set when the negative result is certain. */
1785 if (certain)
1786 return true;
1788 /* For anything not handled by valid_new_delete_pair_p() such as member
1789 operators compare the individual demangled components of the mangled
1790 name. */
1791 const char *new_str = IDENTIFIER_POINTER (new_name);
1792 const char *del_str = IDENTIFIER_POINTER (delete_name);
1794 void *np = NULL, *dp = NULL;
1795 demangle_component *ndc = cplus_demangle_v3_components (new_str, 0, &np);
1796 demangle_component *ddc = cplus_demangle_v3_components (del_str, 0, &dp);
1797 bool mismatch = new_delete_mismatch_p (*ndc, *ddc);
1798 free (np);
1799 free (dp);
1800 return mismatch;
1803 /* ALLOC_DECL and DEALLOC_DECL are pair of allocation and deallocation
1804 functions. Return true if the latter is suitable to deallocate objects
1805 allocated by calls to the former. */
1807 static bool
1808 matching_alloc_calls_p (tree alloc_decl, tree dealloc_decl)
1810 /* Set to alloc_kind_t::builtin if ALLOC_DECL is associated with
1811 a built-in deallocator. */
1812 enum class alloc_kind_t { none, builtin, user }
1813 alloc_dealloc_kind = alloc_kind_t::none;
1815 if (DECL_IS_OPERATOR_NEW_P (alloc_decl))
1817 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl))
1818 /* Return true iff both functions are of the same array or
1819 singleton form and false otherwise. */
1820 return !new_delete_mismatch_p (alloc_decl, dealloc_decl);
1822 /* Return false for deallocation functions that are known not
1823 to match. */
1824 if (fndecl_built_in_p (dealloc_decl, BUILT_IN_FREE)
1825 || fndecl_built_in_p (dealloc_decl, BUILT_IN_REALLOC))
1826 return false;
1827 /* Otherwise proceed below to check the deallocation function's
1828 "*dealloc" attributes to look for one that mentions this operator
1829 new. */
1831 else if (fndecl_built_in_p (alloc_decl, BUILT_IN_NORMAL))
1833 switch (DECL_FUNCTION_CODE (alloc_decl))
1835 case BUILT_IN_ALLOCA:
1836 case BUILT_IN_ALLOCA_WITH_ALIGN:
1837 return false;
1839 case BUILT_IN_ALIGNED_ALLOC:
1840 case BUILT_IN_CALLOC:
1841 case BUILT_IN_GOMP_ALLOC:
1842 case BUILT_IN_MALLOC:
1843 case BUILT_IN_REALLOC:
1844 case BUILT_IN_STRDUP:
1845 case BUILT_IN_STRNDUP:
1846 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl))
1847 return false;
1849 if (fndecl_built_in_p (dealloc_decl, BUILT_IN_FREE)
1850 || fndecl_built_in_p (dealloc_decl, BUILT_IN_REALLOC))
1851 return true;
1853 alloc_dealloc_kind = alloc_kind_t::builtin;
1854 break;
1856 default:
1857 break;
1861 /* Set if DEALLOC_DECL both allocates and deallocates. */
1862 alloc_kind_t realloc_kind = alloc_kind_t::none;
1864 if (fndecl_built_in_p (dealloc_decl, BUILT_IN_NORMAL))
1866 built_in_function dealloc_code = DECL_FUNCTION_CODE (dealloc_decl);
1867 if (dealloc_code == BUILT_IN_REALLOC)
1868 realloc_kind = alloc_kind_t::builtin;
1870 for (tree amats = DECL_ATTRIBUTES (alloc_decl);
1871 (amats = lookup_attribute ("malloc", amats));
1872 amats = TREE_CHAIN (amats))
1874 tree args = TREE_VALUE (amats);
1875 if (!args)
1876 continue;
1878 tree fndecl = TREE_VALUE (args);
1879 if (!fndecl || !DECL_P (fndecl))
1880 continue;
1882 if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL)
1883 && dealloc_code == DECL_FUNCTION_CODE (fndecl))
1884 return true;
1888 const bool alloc_builtin = fndecl_built_in_p (alloc_decl, BUILT_IN_NORMAL);
1889 alloc_kind_t realloc_dealloc_kind = alloc_kind_t::none;
1891 /* If DEALLOC_DECL has an internal "*dealloc" attribute scan the list
1892 of its associated allocation functions for ALLOC_DECL.
1893 If the corresponding ALLOC_DECL is found they're a matching pair,
1894 otherwise they're not.
1895 With DDATS set to the Deallocator's *Dealloc ATtributes... */
1896 for (tree ddats = DECL_ATTRIBUTES (dealloc_decl);
1897 (ddats = lookup_attribute ("*dealloc", ddats));
1898 ddats = TREE_CHAIN (ddats))
1900 tree args = TREE_VALUE (ddats);
1901 if (!args)
1902 continue;
1904 tree alloc = TREE_VALUE (args);
1905 if (!alloc)
1906 continue;
1908 if (alloc == DECL_NAME (dealloc_decl))
1909 realloc_kind = alloc_kind_t::user;
1911 if (DECL_P (alloc))
1913 gcc_checking_assert (fndecl_built_in_p (alloc, BUILT_IN_NORMAL));
1915 switch (DECL_FUNCTION_CODE (alloc))
1917 case BUILT_IN_ALIGNED_ALLOC:
1918 case BUILT_IN_CALLOC:
1919 case BUILT_IN_GOMP_ALLOC:
1920 case BUILT_IN_MALLOC:
1921 case BUILT_IN_REALLOC:
1922 case BUILT_IN_STRDUP:
1923 case BUILT_IN_STRNDUP:
1924 realloc_dealloc_kind = alloc_kind_t::builtin;
1925 break;
1926 default:
1927 break;
1930 if (!alloc_builtin)
1931 continue;
1933 if (DECL_FUNCTION_CODE (alloc) != DECL_FUNCTION_CODE (alloc_decl))
1934 continue;
1936 return true;
1939 if (alloc == DECL_NAME (alloc_decl))
1940 return true;
1943 if (realloc_kind == alloc_kind_t::none)
1944 return false;
1946 hash_set<tree> common_deallocs;
1947 /* Special handling for deallocators. Iterate over both the allocator's
1948 and the reallocator's associated deallocator functions looking for
1949 the first one in common. If one is found, the de/reallocator is
1950 a match for the allocator even though the latter isn't directly
1951 associated with the former. This simplifies declarations in system
1952 headers.
1953 With AMATS set to the Allocator's Malloc ATtributes,
1954 and RMATS set to Reallocator's Malloc ATtributes... */
1955 for (tree amats = DECL_ATTRIBUTES (alloc_decl),
1956 rmats = DECL_ATTRIBUTES (dealloc_decl);
1957 (amats = lookup_attribute ("malloc", amats))
1958 || (rmats = lookup_attribute ("malloc", rmats));
1959 amats = amats ? TREE_CHAIN (amats) : NULL_TREE,
1960 rmats = rmats ? TREE_CHAIN (rmats) : NULL_TREE)
1962 if (tree args = amats ? TREE_VALUE (amats) : NULL_TREE)
1963 if (tree adealloc = TREE_VALUE (args))
1965 if (DECL_P (adealloc)
1966 && fndecl_built_in_p (adealloc, BUILT_IN_NORMAL))
1968 built_in_function fncode = DECL_FUNCTION_CODE (adealloc);
1969 if (fncode == BUILT_IN_FREE || fncode == BUILT_IN_REALLOC)
1971 if (realloc_kind == alloc_kind_t::builtin)
1972 return true;
1973 alloc_dealloc_kind = alloc_kind_t::builtin;
1975 continue;
1978 common_deallocs.add (adealloc);
1981 if (tree args = rmats ? TREE_VALUE (rmats) : NULL_TREE)
1982 if (tree ddealloc = TREE_VALUE (args))
1984 if (DECL_P (ddealloc)
1985 && fndecl_built_in_p (ddealloc, BUILT_IN_NORMAL))
1987 built_in_function fncode = DECL_FUNCTION_CODE (ddealloc);
1988 if (fncode == BUILT_IN_FREE || fncode == BUILT_IN_REALLOC)
1990 if (alloc_dealloc_kind == alloc_kind_t::builtin)
1991 return true;
1992 realloc_dealloc_kind = alloc_kind_t::builtin;
1994 continue;
1997 if (common_deallocs.add (ddealloc))
1998 return true;
2002 /* Succeed only if ALLOC_DECL and the reallocator DEALLOC_DECL share
2003 a built-in deallocator. */
2004 return (alloc_dealloc_kind == alloc_kind_t::builtin
2005 && realloc_dealloc_kind == alloc_kind_t::builtin);
2008 /* Return true if DEALLOC_DECL is a function suitable to deallocate
2009 objectes allocated by the ALLOC call. */
2011 static bool
2012 matching_alloc_calls_p (gimple *alloc, tree dealloc_decl)
2014 tree alloc_decl = gimple_call_fndecl (alloc);
2015 if (!alloc_decl)
2016 return true;
2018 return matching_alloc_calls_p (alloc_decl, dealloc_decl);
2021 /* Diagnose a call EXP to deallocate a pointer referenced by AREF if it
2022 includes a nonzero offset. Such a pointer cannot refer to the beginning
2023 of an allocated object. A negative offset may refer to it only if
2024 the target pointer is unknown. */
2026 static bool
2027 warn_dealloc_offset (location_t loc, gimple *call, const access_ref &aref)
2029 if (aref.deref || aref.offrng[0] <= 0 || aref.offrng[1] <= 0)
2030 return false;
2032 tree dealloc_decl = gimple_call_fndecl (call);
2033 if (!dealloc_decl)
2034 return false;
2036 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl)
2037 && !DECL_IS_REPLACEABLE_OPERATOR (dealloc_decl))
2039 /* A call to a user-defined operator delete with a pointer plus offset
2040 may be valid if it's returned from an unknown function (i.e., one
2041 that's not operator new). */
2042 if (TREE_CODE (aref.ref) == SSA_NAME)
2044 gimple *def_stmt = SSA_NAME_DEF_STMT (aref.ref);
2045 if (is_gimple_call (def_stmt))
2047 tree alloc_decl = gimple_call_fndecl (def_stmt);
2048 if (!alloc_decl || !DECL_IS_OPERATOR_NEW_P (alloc_decl))
2049 return false;
2054 char offstr[80];
2055 offstr[0] = '\0';
2056 if (wi::fits_shwi_p (aref.offrng[0]))
2058 if (aref.offrng[0] == aref.offrng[1]
2059 || !wi::fits_shwi_p (aref.offrng[1]))
2060 sprintf (offstr, " %lli",
2061 (long long)aref.offrng[0].to_shwi ());
2062 else
2063 sprintf (offstr, " [%lli, %lli]",
2064 (long long)aref.offrng[0].to_shwi (),
2065 (long long)aref.offrng[1].to_shwi ());
2068 if (!warning_at (loc, OPT_Wfree_nonheap_object,
2069 "%qD called on pointer %qE with nonzero offset%s",
2070 dealloc_decl, aref.ref, offstr))
2071 return false;
2073 if (DECL_P (aref.ref))
2074 inform (get_location (aref.ref), "declared here");
2075 else if (TREE_CODE (aref.ref) == SSA_NAME)
2077 gimple *def_stmt = SSA_NAME_DEF_STMT (aref.ref);
2078 if (is_gimple_call (def_stmt))
2080 location_t def_loc = get_location (def_stmt);
2081 tree alloc_decl = gimple_call_fndecl (def_stmt);
2082 if (alloc_decl)
2083 inform (def_loc,
2084 "returned from %qD", alloc_decl);
2085 else if (tree alloc_fntype = gimple_call_fntype (def_stmt))
2086 inform (def_loc,
2087 "returned from %qT", alloc_fntype);
2088 else
2089 inform (def_loc, "obtained here");
2093 return true;
2096 /* Issue a warning if a deallocation function such as free, realloc,
2097 or C++ operator delete is called with an argument not returned by
2098 a matching allocation function such as malloc or the corresponding
2099 form of C++ operatorn new. */
2101 static void
2102 maybe_check_dealloc_call (gcall *call)
2104 tree fndecl = gimple_call_fndecl (call);
2105 if (!fndecl)
2106 return;
2108 unsigned argno = fndecl_dealloc_argno (fndecl);
2109 if ((unsigned) call_nargs (call) <= argno)
2110 return;
2112 tree ptr = gimple_call_arg (call, argno);
2113 if (integer_zerop (ptr))
2114 return;
2116 access_ref aref;
2117 if (!compute_objsize (ptr, 0, &aref))
2118 return;
2120 tree ref = aref.ref;
2121 if (integer_zerop (ref))
2122 return;
2124 tree dealloc_decl = fndecl;
2125 location_t loc = gimple_location (call);
2127 if (DECL_P (ref) || EXPR_P (ref))
2129 /* Diagnose freeing a declared object. */
2130 if (aref.ref_declared ()
2131 && warning_at (loc, OPT_Wfree_nonheap_object,
2132 "%qD called on unallocated object %qD",
2133 dealloc_decl, ref))
2135 inform (get_location (ref), "declared here");
2136 return;
2139 /* Diagnose freeing a pointer that includes a positive offset.
2140 Such a pointer cannot refer to the beginning of an allocated
2141 object. A negative offset may refer to it. */
2142 if (aref.sizrng[0] != aref.sizrng[1]
2143 && warn_dealloc_offset (loc, call, aref))
2144 return;
2146 else if (CONSTANT_CLASS_P (ref))
2148 if (warning_at (loc, OPT_Wfree_nonheap_object,
2149 "%qD called on a pointer to an unallocated "
2150 "object %qE", dealloc_decl, ref))
2152 if (TREE_CODE (ptr) == SSA_NAME)
2154 gimple *def_stmt = SSA_NAME_DEF_STMT (ptr);
2155 if (is_gimple_assign (def_stmt))
2157 location_t loc = gimple_location (def_stmt);
2158 inform (loc, "assigned here");
2161 return;
2164 else if (TREE_CODE (ref) == SSA_NAME)
2166 /* Also warn if the pointer argument refers to the result
2167 of an allocation call like alloca or VLA. */
2168 gimple *def_stmt = SSA_NAME_DEF_STMT (ref);
2169 if (is_gimple_call (def_stmt))
2171 bool warned = false;
2172 if (gimple_call_alloc_p (def_stmt))
2174 if (matching_alloc_calls_p (def_stmt, dealloc_decl))
2176 if (warn_dealloc_offset (loc, call, aref))
2177 return;
2179 else
2181 tree alloc_decl = gimple_call_fndecl (def_stmt);
2182 const opt_code opt =
2183 (DECL_IS_OPERATOR_NEW_P (alloc_decl)
2184 || DECL_IS_OPERATOR_DELETE_P (dealloc_decl)
2185 ? OPT_Wmismatched_new_delete
2186 : OPT_Wmismatched_dealloc);
2187 warned = warning_at (loc, opt,
2188 "%qD called on pointer returned "
2189 "from a mismatched allocation "
2190 "function", dealloc_decl);
2193 else if (gimple_call_builtin_p (def_stmt, BUILT_IN_ALLOCA)
2194 || gimple_call_builtin_p (def_stmt,
2195 BUILT_IN_ALLOCA_WITH_ALIGN))
2196 warned = warning_at (loc, OPT_Wfree_nonheap_object,
2197 "%qD called on pointer to "
2198 "an unallocated object",
2199 dealloc_decl);
2200 else if (warn_dealloc_offset (loc, call, aref))
2201 return;
2203 if (warned)
2205 tree fndecl = gimple_call_fndecl (def_stmt);
2206 inform (gimple_location (def_stmt),
2207 "returned from %qD", fndecl);
2208 return;
2211 else if (gimple_nop_p (def_stmt))
2213 ref = SSA_NAME_VAR (ref);
2214 /* Diagnose freeing a pointer that includes a positive offset. */
2215 if (TREE_CODE (ref) == PARM_DECL
2216 && !aref.deref
2217 && aref.sizrng[0] != aref.sizrng[1]
2218 && aref.offrng[0] > 0 && aref.offrng[1] > 0
2219 && warn_dealloc_offset (loc, call, aref))
2220 return;
2225 namespace {
2227 const pass_data pass_data_waccess = {
2228 GIMPLE_PASS,
2229 "waccess",
2230 OPTGROUP_NONE,
2231 TV_NONE,
2232 PROP_cfg, /* properties_required */
2233 0, /* properties_provided */
2234 0, /* properties_destroyed */
2235 0, /* properties_start */
2236 0, /* properties_finish */
2239 /* Pass to detect invalid accesses. */
2240 class pass_waccess : public gimple_opt_pass
2242 public:
2243 pass_waccess (gcc::context *);
2245 ~pass_waccess ();
2247 opt_pass *clone () { return new pass_waccess (m_ctxt); }
2249 virtual bool gate (function *);
2250 virtual unsigned int execute (function *);
2252 /* Check a call to a built-in function. */
2253 bool check_builtin (gcall *);
2255 /* Check a call to an ordinary function. */
2256 bool check_call (gcall *);
2258 /* Check statements in a basic block. */
2259 void check (basic_block);
2261 /* Check a call to a function. */
2262 void check (gcall *);
2264 private:
2265 /* Not copyable or assignable. */
2266 pass_waccess (pass_waccess &) = delete;
2267 void operator= (pass_waccess &) = delete;
2269 /* A pointer_query object and its cache to store information about
2270 pointers and their targets in. */
2271 pointer_query ptr_qry;
2272 pointer_query::cache_type var_cache;
2274 gimple_ranger *m_ranger;
2277 /* Construct the pass. */
2279 pass_waccess::pass_waccess (gcc::context *ctxt)
2280 : gimple_opt_pass (pass_data_waccess, ctxt),
2281 ptr_qry (m_ranger, &var_cache),
2282 var_cache (),
2283 m_ranger ()
2287 /* Release pointer_query cache. */
2289 pass_waccess::~pass_waccess ()
2291 ptr_qry.flush_cache ();
2294 /* Return true when any checks performed by the pass are enabled. */
2296 bool
2297 pass_waccess::gate (function *)
2299 return (warn_free_nonheap_object
2300 || warn_mismatched_alloc
2301 || warn_mismatched_new_delete);
2304 /* Initialize ALLOC_OBJECT_SIZE_LIMIT based on the -Walloc-size-larger-than=
2305 setting if the option is specified, or to the maximum object size if it
2306 is not. Return the initialized value. */
2308 static tree
2309 alloc_max_size (void)
2311 HOST_WIDE_INT limit = warn_alloc_size_limit;
2312 if (limit == HOST_WIDE_INT_MAX)
2313 limit = tree_to_shwi (TYPE_MAX_VALUE (ptrdiff_type_node));
2315 return build_int_cst (size_type_node, limit);
2318 /* Diagnose a call EXP to function FN decorated with attribute alloc_size
2319 whose argument numbers given by IDX with values given by ARGS exceed
2320 the maximum object size or cause an unsigned oveflow (wrapping) when
2321 multiplied. FN is null when EXP is a call via a function pointer.
2322 When ARGS[0] is null the function does nothing. ARGS[1] may be null
2323 for functions like malloc, and non-null for those like calloc that
2324 are decorated with a two-argument attribute alloc_size. */
2326 void
2327 maybe_warn_alloc_args_overflow (gimple *stmt, const tree args[2],
2328 const int idx[2])
2330 /* The range each of the (up to) two arguments is known to be in. */
2331 tree argrange[2][2] = { { NULL_TREE, NULL_TREE }, { NULL_TREE, NULL_TREE } };
2333 /* Maximum object size set by -Walloc-size-larger-than= or SIZE_MAX / 2. */
2334 tree maxobjsize = alloc_max_size ();
2336 location_t loc = get_location (stmt);
2338 tree fn = gimple_call_fndecl (stmt);
2339 tree fntype = fn ? TREE_TYPE (fn) : gimple_call_fntype (stmt);
2340 bool warned = false;
2342 /* Validate each argument individually. */
2343 for (unsigned i = 0; i != 2 && args[i]; ++i)
2345 if (TREE_CODE (args[i]) == INTEGER_CST)
2347 argrange[i][0] = args[i];
2348 argrange[i][1] = args[i];
2350 if (tree_int_cst_lt (args[i], integer_zero_node))
2352 warned = warning_at (loc, OPT_Walloc_size_larger_than_,
2353 "argument %i value %qE is negative",
2354 idx[i] + 1, args[i]);
2356 else if (integer_zerop (args[i]))
2358 /* Avoid issuing -Walloc-zero for allocation functions other
2359 than __builtin_alloca that are declared with attribute
2360 returns_nonnull because there's no portability risk. This
2361 avoids warning for such calls to libiberty's xmalloc and
2362 friends.
2363 Also avoid issuing the warning for calls to function named
2364 "alloca". */
2365 if (fn && fndecl_built_in_p (fn, BUILT_IN_ALLOCA)
2366 ? IDENTIFIER_LENGTH (DECL_NAME (fn)) != 6
2367 : !lookup_attribute ("returns_nonnull",
2368 TYPE_ATTRIBUTES (fntype)))
2369 warned = warning_at (loc, OPT_Walloc_zero,
2370 "argument %i value is zero",
2371 idx[i] + 1);
2373 else if (tree_int_cst_lt (maxobjsize, args[i]))
2375 /* G++ emits calls to ::operator new[](SIZE_MAX) in C++98
2376 mode and with -fno-exceptions as a way to indicate array
2377 size overflow. There's no good way to detect C++98 here
2378 so avoid diagnosing these calls for all C++ modes. */
2379 if (i == 0
2380 && fn
2381 && !args[1]
2382 && lang_GNU_CXX ()
2383 && DECL_IS_OPERATOR_NEW_P (fn)
2384 && integer_all_onesp (args[i]))
2385 continue;
2387 warned = warning_at (loc, OPT_Walloc_size_larger_than_,
2388 "argument %i value %qE exceeds "
2389 "maximum object size %E",
2390 idx[i] + 1, args[i], maxobjsize);
2393 else if (TREE_CODE (args[i]) == SSA_NAME
2394 && get_size_range (args[i], argrange[i]))
2396 /* Verify that the argument's range is not negative (including
2397 upper bound of zero). */
2398 if (tree_int_cst_lt (argrange[i][0], integer_zero_node)
2399 && tree_int_cst_le (argrange[i][1], integer_zero_node))
2401 warned = warning_at (loc, OPT_Walloc_size_larger_than_,
2402 "argument %i range [%E, %E] is negative",
2403 idx[i] + 1,
2404 argrange[i][0], argrange[i][1]);
2406 else if (tree_int_cst_lt (maxobjsize, argrange[i][0]))
2408 warned = warning_at (loc, OPT_Walloc_size_larger_than_,
2409 "argument %i range [%E, %E] exceeds "
2410 "maximum object size %E",
2411 idx[i] + 1,
2412 argrange[i][0], argrange[i][1],
2413 maxobjsize);
2418 if (!argrange[0])
2419 return;
2421 /* For a two-argument alloc_size, validate the product of the two
2422 arguments if both of their values or ranges are known. */
2423 if (!warned && tree_fits_uhwi_p (argrange[0][0])
2424 && argrange[1][0] && tree_fits_uhwi_p (argrange[1][0])
2425 && !integer_onep (argrange[0][0])
2426 && !integer_onep (argrange[1][0]))
2428 /* Check for overflow in the product of a function decorated with
2429 attribute alloc_size (X, Y). */
2430 unsigned szprec = TYPE_PRECISION (size_type_node);
2431 wide_int x = wi::to_wide (argrange[0][0], szprec);
2432 wide_int y = wi::to_wide (argrange[1][0], szprec);
2434 wi::overflow_type vflow;
2435 wide_int prod = wi::umul (x, y, &vflow);
2437 if (vflow)
2438 warned = warning_at (loc, OPT_Walloc_size_larger_than_,
2439 "product %<%E * %E%> of arguments %i and %i "
2440 "exceeds %<SIZE_MAX%>",
2441 argrange[0][0], argrange[1][0],
2442 idx[0] + 1, idx[1] + 1);
2443 else if (wi::ltu_p (wi::to_wide (maxobjsize, szprec), prod))
2444 warned = warning_at (loc, OPT_Walloc_size_larger_than_,
2445 "product %<%E * %E%> of arguments %i and %i "
2446 "exceeds maximum object size %E",
2447 argrange[0][0], argrange[1][0],
2448 idx[0] + 1, idx[1] + 1,
2449 maxobjsize);
2451 if (warned)
2453 /* Print the full range of each of the two arguments to make
2454 it clear when it is, in fact, in a range and not constant. */
2455 if (argrange[0][0] != argrange [0][1])
2456 inform (loc, "argument %i in the range [%E, %E]",
2457 idx[0] + 1, argrange[0][0], argrange[0][1]);
2458 if (argrange[1][0] != argrange [1][1])
2459 inform (loc, "argument %i in the range [%E, %E]",
2460 idx[1] + 1, argrange[1][0], argrange[1][1]);
2464 if (warned && fn)
2466 location_t fnloc = DECL_SOURCE_LOCATION (fn);
2468 if (DECL_IS_UNDECLARED_BUILTIN (fn))
2469 inform (loc,
2470 "in a call to built-in allocation function %qD", fn);
2471 else
2472 inform (fnloc,
2473 "in a call to allocation function %qD declared here", fn);
2477 /* Check a call to an alloca function for an excessive size. */
2479 static void
2480 check_alloca (gimple *stmt)
2482 if ((warn_vla_limit >= HOST_WIDE_INT_MAX
2483 && warn_alloc_size_limit < warn_vla_limit)
2484 || (warn_alloca_limit >= HOST_WIDE_INT_MAX
2485 && warn_alloc_size_limit < warn_alloca_limit))
2487 /* -Walloca-larger-than and -Wvla-larger-than settings of less
2488 than HWI_MAX override the more general -Walloc-size-larger-than
2489 so unless either of the former options is smaller than the last
2490 one (wchich would imply that the call was already checked), check
2491 the alloca arguments for overflow. */
2492 const tree alloc_args[] = { call_arg (stmt, 0), NULL_TREE };
2493 const int idx[] = { 0, -1 };
2494 maybe_warn_alloc_args_overflow (stmt, alloc_args, idx);
2498 /* Check a call to an allocation function for an excessive size. */
2500 static void
2501 check_alloc_size_call (gimple *stmt)
2503 if (gimple_call_num_args (stmt) < 1)
2504 /* Avoid invalid calls to functions without a prototype. */
2505 return;
2507 tree fndecl = gimple_call_fndecl (stmt);
2508 if (fndecl && gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
2510 /* Alloca is handled separately. */
2511 switch (DECL_FUNCTION_CODE (fndecl))
2513 case BUILT_IN_ALLOCA:
2514 case BUILT_IN_ALLOCA_WITH_ALIGN:
2515 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
2516 return;
2517 default:
2518 break;
2522 tree fntype = gimple_call_fntype (stmt);
2523 tree fntypeattrs = TYPE_ATTRIBUTES (fntype);
2525 tree alloc_size = lookup_attribute ("alloc_size", fntypeattrs);
2526 if (!alloc_size)
2527 return;
2529 /* Extract attribute alloc_size from the type of the called expression
2530 (which could be a function or a function pointer) and if set, store
2531 the indices of the corresponding arguments in ALLOC_IDX, and then
2532 the actual argument(s) at those indices in ALLOC_ARGS. */
2533 int idx[2] = { -1, -1 };
2534 tree alloc_args[] = { NULL_TREE, NULL_TREE };
2536 tree args = TREE_VALUE (alloc_size);
2537 idx[0] = TREE_INT_CST_LOW (TREE_VALUE (args)) - 1;
2538 alloc_args[0] = call_arg (stmt, idx[0]);
2539 if (TREE_CHAIN (args))
2541 idx[1] = TREE_INT_CST_LOW (TREE_VALUE (TREE_CHAIN (args))) - 1;
2542 alloc_args[1] = call_arg (stmt, idx[1]);
2545 maybe_warn_alloc_args_overflow (stmt, alloc_args, idx);
2548 /* Check a call STMT to strcat() for overflow and warn if it does. */
2550 static void
2551 check_strcat (gimple *stmt)
2553 if (!warn_stringop_overflow && !warn_stringop_overread)
2554 return;
2556 tree dest = call_arg (stmt, 0);
2557 tree src = call_arg (stmt, 1);
2559 /* There is no way here to determine the length of the string in
2560 the destination to which the SRC string is being appended so
2561 just diagnose cases when the souce string is longer than
2562 the destination object. */
2563 access_data data (stmt, access_read_write, NULL_TREE, true,
2564 NULL_TREE, true);
2565 const int ost = warn_stringop_overflow ? warn_stringop_overflow - 1 : 1;
2566 compute_objsize (src, ost, &data.src);
2567 tree destsize = compute_objsize (dest, ost, &data.dst);
2569 check_access (stmt, /*dstwrite=*/NULL_TREE, /*maxread=*/NULL_TREE,
2570 src, destsize, data.mode, &data);
2573 /* Check a call STMT to strcat() for overflow and warn if it does. */
2575 static void
2576 check_strncat (gimple *stmt)
2578 if (!warn_stringop_overflow && !warn_stringop_overread)
2579 return;
2581 tree dest = call_arg (stmt, 0);
2582 tree src = call_arg (stmt, 1);
2583 /* The upper bound on the number of bytes to write. */
2584 tree maxread = call_arg (stmt, 2);
2586 /* Detect unterminated source (only). */
2587 if (!check_nul_terminated_array (stmt, src, maxread))
2588 return;
2590 /* The length of the source sequence. */
2591 tree slen = c_strlen (src, 1);
2593 /* Try to determine the range of lengths that the source expression
2594 refers to. Since the lengths are only used for warning and not
2595 for code generation disable strict mode below. */
2596 tree maxlen = slen;
2597 if (!maxlen)
2599 c_strlen_data lendata = { };
2600 get_range_strlen (src, &lendata, /* eltsize = */ 1);
2601 maxlen = lendata.maxbound;
2604 access_data data (stmt, access_read_write);
2605 /* Try to verify that the destination is big enough for the shortest
2606 string. First try to determine the size of the destination object
2607 into which the source is being copied. */
2608 tree destsize = compute_objsize (dest, warn_stringop_overflow - 1, &data.dst);
2610 /* Add one for the terminating nul. */
2611 tree srclen = (maxlen
2612 ? fold_build2 (PLUS_EXPR, size_type_node, maxlen,
2613 size_one_node)
2614 : NULL_TREE);
2616 /* The strncat function copies at most MAXREAD bytes and always appends
2617 the terminating nul so the specified upper bound should never be equal
2618 to (or greater than) the size of the destination. */
2619 if (tree_fits_uhwi_p (maxread) && tree_fits_uhwi_p (destsize)
2620 && tree_int_cst_equal (destsize, maxread))
2622 location_t loc = get_location (stmt);
2623 warning_at (loc, OPT_Wstringop_overflow_,
2624 "%qD specified bound %E equals destination size",
2625 get_callee_fndecl (stmt), maxread);
2627 return;
2630 if (!srclen
2631 || (maxread && tree_fits_uhwi_p (maxread)
2632 && tree_fits_uhwi_p (srclen)
2633 && tree_int_cst_lt (maxread, srclen)))
2634 srclen = maxread;
2636 check_access (stmt, /*dstwrite=*/NULL_TREE, maxread, srclen,
2637 destsize, data.mode, &data);
2640 /* Check a call STMT to stpcpy() or strcpy() for overflow and warn
2641 if it does. */
2643 static void
2644 check_stxcpy (gimple *stmt)
2646 tree dst = call_arg (stmt, 0);
2647 tree src = call_arg (stmt, 1);
2649 tree size;
2650 bool exact;
2651 if (tree nonstr = unterminated_array (src, &size, &exact))
2653 /* NONSTR refers to the non-nul terminated constant array. */
2654 warn_string_no_nul (get_location (stmt), stmt, NULL, src, nonstr,
2655 size, exact);
2656 return;
2659 if (warn_stringop_overflow)
2661 access_data data (stmt, access_read_write, NULL_TREE, true,
2662 NULL_TREE, true);
2663 const int ost = warn_stringop_overflow ? warn_stringop_overflow - 1 : 1;
2664 compute_objsize (src, ost, &data.src);
2665 tree dstsize = compute_objsize (dst, ost, &data.dst);
2666 check_access (stmt, /*dstwrite=*/ NULL_TREE,
2667 /*maxread=*/ NULL_TREE, /*srcstr=*/ src,
2668 dstsize, data.mode, &data);
2671 /* Check to see if the argument was declared attribute nonstring
2672 and if so, issue a warning since at this point it's not known
2673 to be nul-terminated. */
2674 tree fndecl = get_callee_fndecl (stmt);
2675 maybe_warn_nonstring_arg (fndecl, stmt);
2678 /* Check a call STMT to stpncpy() or strncpy() for overflow and warn
2679 if it does. */
2681 static void
2682 check_stxncpy (gimple *stmt)
2684 if (!warn_stringop_overflow)
2685 return;
2687 tree dst = call_arg (stmt, 0);
2688 tree src = call_arg (stmt, 1);
2689 /* The number of bytes to write (not the maximum). */
2690 tree len = call_arg (stmt, 2);
2692 access_data data (stmt, access_read_write, len, true, len, true);
2693 const int ost = warn_stringop_overflow ? warn_stringop_overflow - 1 : 1;
2694 compute_objsize (src, ost, &data.src);
2695 tree dstsize = compute_objsize (dst, ost, &data.dst);
2697 check_access (stmt, /*dstwrite=*/len,
2698 /*maxread=*/len, src, dstsize, data.mode, &data);
2701 /* Check a call STMT to stpncpy() or strncpy() for overflow and warn
2702 if it does. */
2704 static void
2705 check_strncmp (gimple *stmt)
2707 if (!warn_stringop_overread)
2708 return;
2710 tree arg1 = call_arg (stmt, 0);
2711 tree arg2 = call_arg (stmt, 1);
2712 tree bound = call_arg (stmt, 2);
2714 /* First check each argument separately, considering the bound. */
2715 if (!check_nul_terminated_array (stmt, arg1, bound)
2716 || !check_nul_terminated_array (stmt, arg2, bound))
2717 return;
2719 /* A strncmp read from each argument is constrained not just by
2720 the bound but also by the length of the shorter string. Specifying
2721 a bound that's larger than the size of either array makes no sense
2722 and is likely a bug. When the length of neither of the two strings
2723 is known but the sizes of both of the arrays they are stored in is,
2724 issue a warning if the bound is larger than than the size of
2725 the larger of the two arrays. */
2727 c_strlen_data lendata1{ }, lendata2{ };
2728 tree len1 = c_strlen (arg1, 1, &lendata1);
2729 tree len2 = c_strlen (arg2, 1, &lendata2);
2731 if (len1 && len2)
2732 /* If the length of both arguments was computed they must both be
2733 nul-terminated and no further checking is necessary regardless
2734 of the bound. */
2735 return;
2737 /* Check to see if the argument was declared with attribute nonstring
2738 and if so, issue a warning since at this point it's not known to be
2739 nul-terminated. */
2740 if (maybe_warn_nonstring_arg (get_callee_fndecl (stmt), stmt))
2741 return;
2743 access_data adata1 (stmt, access_read_only, NULL_TREE, false, bound, true);
2744 access_data adata2 (stmt, access_read_only, NULL_TREE, false, bound, true);
2746 /* Determine the range of the bound first and bail if it fails; it's
2747 cheaper than computing the size of the objects. */
2748 tree bndrng[2] = { NULL_TREE, NULL_TREE };
2749 get_size_range (bound, bndrng, adata1.src.bndrng);
2750 if (!bndrng[0] || integer_zerop (bndrng[0]))
2751 return;
2753 if (len1 && tree_int_cst_lt (len1, bndrng[0]))
2754 bndrng[0] = len1;
2755 if (len2 && tree_int_cst_lt (len2, bndrng[0]))
2756 bndrng[0] = len2;
2758 /* compute_objsize almost never fails (and ultimately should never
2759 fail). Don't bother to handle the rare case when it does. */
2760 if (!compute_objsize (arg1, 1, &adata1.src)
2761 || !compute_objsize (arg2, 1, &adata2.src))
2762 return;
2764 /* Compute the size of the remaining space in each array after
2765 subtracting any offset into it. */
2766 offset_int rem1 = adata1.src.size_remaining ();
2767 offset_int rem2 = adata2.src.size_remaining ();
2769 /* Cap REM1 and REM2 at the other if the other's argument is known
2770 to be an unterminated array, either because there's no space
2771 left in it after adding its offset or because it's constant and
2772 has no nul. */
2773 if (rem1 == 0 || (rem1 < rem2 && lendata1.decl))
2774 rem2 = rem1;
2775 else if (rem2 == 0 || (rem2 < rem1 && lendata2.decl))
2776 rem1 = rem2;
2778 /* Point PAD at the array to reference in the note if a warning
2779 is issued. */
2780 access_data *pad = len1 ? &adata2 : &adata1;
2781 offset_int maxrem = wi::max (rem1, rem2, UNSIGNED);
2782 if (lendata1.decl || lendata2.decl
2783 || maxrem < wi::to_offset (bndrng[0]))
2785 /* Warn when either argument isn't nul-terminated or the maximum
2786 remaining space in the two arrays is less than the bound. */
2787 tree func = get_callee_fndecl (stmt);
2788 location_t loc = gimple_location (stmt);
2789 maybe_warn_for_bound (OPT_Wstringop_overread, loc, stmt, func,
2790 bndrng, wide_int_to_tree (sizetype, maxrem),
2791 pad);
2795 /* Check call STMT to a built-in function for invalid accesses. Return
2796 true if a call has been handled. */
2798 bool
2799 pass_waccess::check_builtin (gcall *stmt)
2801 tree callee = gimple_call_fndecl (stmt);
2802 if (!callee)
2803 return false;
2805 switch (DECL_FUNCTION_CODE (callee))
2807 case BUILT_IN_ALLOCA:
2808 case BUILT_IN_ALLOCA_WITH_ALIGN:
2809 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
2810 check_alloca (stmt);
2811 return true;
2813 case BUILT_IN_GETTEXT:
2814 case BUILT_IN_PUTS:
2815 case BUILT_IN_PUTS_UNLOCKED:
2816 case BUILT_IN_STRDUP:
2817 check_read_access (stmt, call_arg (stmt, 0));
2818 return true;
2820 case BUILT_IN_INDEX:
2821 case BUILT_IN_RINDEX:
2822 case BUILT_IN_STRCHR:
2823 case BUILT_IN_STRRCHR:
2824 case BUILT_IN_STRLEN:
2825 check_read_access (stmt, call_arg (stmt, 0));
2826 return true;
2828 case BUILT_IN_FPUTS:
2829 case BUILT_IN_FPUTS_UNLOCKED:
2830 check_read_access (stmt, call_arg (stmt, 0));
2831 return true;
2833 case BUILT_IN_STRNDUP:
2834 case BUILT_IN_STRNLEN:
2835 check_read_access (stmt, call_arg (stmt, 0), call_arg (stmt, 1));
2836 return true;
2838 case BUILT_IN_STRCAT:
2839 check_strcat (stmt);
2840 return true;
2842 case BUILT_IN_STRNCAT:
2843 check_strncat (stmt);
2844 return true;
2846 case BUILT_IN_STPCPY:
2847 case BUILT_IN_STRCPY:
2848 check_stxcpy (stmt);
2849 return true;
2851 case BUILT_IN_STPNCPY:
2852 case BUILT_IN_STRNCPY:
2853 check_stxncpy (stmt);
2854 return true;
2856 case BUILT_IN_STRCASECMP:
2857 case BUILT_IN_STRCMP:
2858 case BUILT_IN_STRPBRK:
2859 case BUILT_IN_STRSPN:
2860 case BUILT_IN_STRCSPN:
2861 case BUILT_IN_STRSTR:
2862 check_read_access (stmt, call_arg (stmt, 0));
2863 check_read_access (stmt, call_arg (stmt, 1));
2864 return true;
2866 case BUILT_IN_STRNCASECMP:
2867 case BUILT_IN_STRNCMP:
2868 check_strncmp (stmt);
2869 return true;
2871 case BUILT_IN_MEMCMP:
2873 tree a1 = call_arg (stmt, 0);
2874 tree a2 = call_arg (stmt, 1);
2875 tree len = call_arg (stmt, 2);
2876 check_read_access (stmt, a1, len, 0);
2877 check_read_access (stmt, a2, len, 0);
2878 return true;
2881 case BUILT_IN_MEMCPY:
2882 case BUILT_IN_MEMPCPY:
2883 case BUILT_IN_MEMMOVE:
2885 tree dst = call_arg (stmt, 0);
2886 tree src = call_arg (stmt, 1);
2887 tree len = call_arg (stmt, 2);
2888 check_memop_access (stmt, dst, src, len);
2889 return true;
2892 case BUILT_IN_MEMCHR:
2894 tree src = call_arg (stmt, 0);
2895 tree len = call_arg (stmt, 2);
2896 check_read_access (stmt, src, len, 0);
2897 return true;
2900 case BUILT_IN_MEMSET:
2902 tree dst = call_arg (stmt, 0);
2903 tree len = call_arg (stmt, 2);
2904 check_memop_access (stmt, dst, NULL_TREE, len);
2905 return true;
2908 default:
2909 return false;
2912 return true;
2915 /* Returns the type of the argument ARGNO to function with type FNTYPE
2916 or null when the typoe cannot be determined or no such argument exists. */
2918 static tree
2919 fntype_argno_type (tree fntype, unsigned argno)
2921 if (!prototype_p (fntype))
2922 return NULL_TREE;
2924 tree argtype;
2925 function_args_iterator it;
2926 FOREACH_FUNCTION_ARGS (fntype, argtype, it)
2927 if (argno-- == 0)
2928 return argtype;
2930 return NULL_TREE;
2933 /* Helper to append the "human readable" attribute access specification
2934 described by ACCESS to the array ATTRSTR with size STRSIZE. Used in
2935 diagnostics. */
2937 static inline void
2938 append_attrname (const std::pair<int, attr_access> &access,
2939 char *attrstr, size_t strsize)
2941 if (access.second.internal_p)
2942 return;
2944 tree str = access.second.to_external_string ();
2945 gcc_assert (strsize >= (size_t) TREE_STRING_LENGTH (str));
2946 strcpy (attrstr, TREE_STRING_POINTER (str));
2949 /* Iterate over attribute access read-only, read-write, and write-only
2950 arguments and diagnose past-the-end accesses and related problems
2951 in the function call EXP. */
2953 static void
2954 maybe_warn_rdwr_sizes (rdwr_map *rwm, tree fndecl, tree fntype, gimple *stmt)
2956 auto_diagnostic_group adg;
2958 /* Set if a warning has been issued for any argument (used to decide
2959 whether to emit an informational note at the end). */
2960 opt_code opt_warned = no_warning;
2962 /* A string describing the attributes that the warnings issued by this
2963 function apply to. Used to print one informational note per function
2964 call, rather than one per warning. That reduces clutter. */
2965 char attrstr[80];
2966 attrstr[0] = 0;
2968 for (rdwr_map::iterator it = rwm->begin (); it != rwm->end (); ++it)
2970 std::pair<int, attr_access> access = *it;
2972 /* Get the function call arguments corresponding to the attribute's
2973 positional arguments. When both arguments have been specified
2974 there will be two entries in *RWM, one for each. They are
2975 cross-referenced by their respective argument numbers in
2976 ACCESS.PTRARG and ACCESS.SIZARG. */
2977 const int ptridx = access.second.ptrarg;
2978 const int sizidx = access.second.sizarg;
2980 gcc_assert (ptridx != -1);
2981 gcc_assert (access.first == ptridx || access.first == sizidx);
2983 /* The pointer is set to null for the entry corresponding to
2984 the size argument. Skip it. It's handled when the entry
2985 corresponding to the pointer argument comes up. */
2986 if (!access.second.ptr)
2987 continue;
2989 tree ptrtype = fntype_argno_type (fntype, ptridx);
2990 tree argtype = TREE_TYPE (ptrtype);
2992 /* The size of the access by the call. */
2993 tree access_size;
2994 if (sizidx == -1)
2996 /* If only the pointer attribute operand was specified and
2997 not size, set SIZE to the greater of MINSIZE or size of
2998 one element of the pointed to type to detect smaller
2999 objects (null pointers are diagnosed in this case only
3000 if the pointer is also declared with attribute nonnull. */
3001 if (access.second.minsize
3002 && access.second.minsize != HOST_WIDE_INT_M1U)
3003 access_size = build_int_cstu (sizetype, access.second.minsize);
3004 else
3005 access_size = size_one_node;
3007 else
3008 access_size = rwm->get (sizidx)->size;
3010 /* Format the value or range to avoid an explosion of messages. */
3011 char sizstr[80];
3012 tree sizrng[2] = { size_zero_node, build_all_ones_cst (sizetype) };
3013 if (get_size_range (access_size, sizrng, true))
3015 char *s0 = print_generic_expr_to_str (sizrng[0]);
3016 if (tree_int_cst_equal (sizrng[0], sizrng[1]))
3018 gcc_checking_assert (strlen (s0) < sizeof sizstr);
3019 strcpy (sizstr, s0);
3021 else
3023 char *s1 = print_generic_expr_to_str (sizrng[1]);
3024 gcc_checking_assert (strlen (s0) + strlen (s1)
3025 < sizeof sizstr - 4);
3026 sprintf (sizstr, "[%s, %s]", s0, s1);
3027 free (s1);
3029 free (s0);
3031 else
3032 *sizstr = '\0';
3034 /* Set if a warning has been issued for the current argument. */
3035 opt_code arg_warned = no_warning;
3036 location_t loc = get_location (stmt);
3037 tree ptr = access.second.ptr;
3038 if (*sizstr
3039 && tree_int_cst_sgn (sizrng[0]) < 0
3040 && tree_int_cst_sgn (sizrng[1]) < 0)
3042 /* Warn about negative sizes. */
3043 if (access.second.internal_p)
3045 const std::string argtypestr
3046 = access.second.array_as_string (ptrtype);
3048 if (warning_at (loc, OPT_Wstringop_overflow_,
3049 "bound argument %i value %s is "
3050 "negative for a variable length array "
3051 "argument %i of type %s",
3052 sizidx + 1, sizstr,
3053 ptridx + 1, argtypestr.c_str ()))
3054 arg_warned = OPT_Wstringop_overflow_;
3056 else if (warning_at (loc, OPT_Wstringop_overflow_,
3057 "argument %i value %s is negative",
3058 sizidx + 1, sizstr))
3059 arg_warned = OPT_Wstringop_overflow_;
3061 if (arg_warned != no_warning)
3063 append_attrname (access, attrstr, sizeof attrstr);
3064 /* Remember a warning has been issued and avoid warning
3065 again below for the same attribute. */
3066 opt_warned = arg_warned;
3067 continue;
3071 if (tree_int_cst_sgn (sizrng[0]) >= 0)
3073 if (COMPLETE_TYPE_P (argtype))
3075 /* Multiply ACCESS_SIZE by the size of the type the pointer
3076 argument points to. If it's incomplete the size is used
3077 as is. */
3078 if (tree argsize = TYPE_SIZE_UNIT (argtype))
3079 if (TREE_CODE (argsize) == INTEGER_CST)
3081 const int prec = TYPE_PRECISION (sizetype);
3082 wide_int minsize = wi::to_wide (sizrng[0], prec);
3083 minsize *= wi::to_wide (argsize, prec);
3084 access_size = wide_int_to_tree (sizetype, minsize);
3088 else
3089 access_size = NULL_TREE;
3091 if (integer_zerop (ptr))
3093 if (sizidx >= 0 && tree_int_cst_sgn (sizrng[0]) > 0)
3095 /* Warn about null pointers with positive sizes. This is
3096 different from also declaring the pointer argument with
3097 attribute nonnull when the function accepts null pointers
3098 only when the corresponding size is zero. */
3099 if (access.second.internal_p)
3101 const std::string argtypestr
3102 = access.second.array_as_string (ptrtype);
3104 if (warning_at (loc, OPT_Wnonnull,
3105 "argument %i of variable length "
3106 "array %s is null but "
3107 "the corresponding bound argument "
3108 "%i value is %s",
3109 ptridx + 1, argtypestr.c_str (),
3110 sizidx + 1, sizstr))
3111 arg_warned = OPT_Wnonnull;
3113 else if (warning_at (loc, OPT_Wnonnull,
3114 "argument %i is null but "
3115 "the corresponding size argument "
3116 "%i value is %s",
3117 ptridx + 1, sizidx + 1, sizstr))
3118 arg_warned = OPT_Wnonnull;
3120 else if (access_size && access.second.static_p)
3122 /* Warn about null pointers for [static N] array arguments
3123 but do not warn for ordinary (i.e., nonstatic) arrays. */
3124 if (warning_at (loc, OPT_Wnonnull,
3125 "argument %i to %<%T[static %E]%> "
3126 "is null where non-null expected",
3127 ptridx + 1, argtype, access_size))
3128 arg_warned = OPT_Wnonnull;
3131 if (arg_warned != no_warning)
3133 append_attrname (access, attrstr, sizeof attrstr);
3134 /* Remember a warning has been issued and avoid warning
3135 again below for the same attribute. */
3136 opt_warned = OPT_Wnonnull;
3137 continue;
3141 access_data data (ptr, access.second.mode, NULL_TREE, false,
3142 NULL_TREE, false);
3143 access_ref* const pobj = (access.second.mode == access_write_only
3144 ? &data.dst : &data.src);
3145 tree objsize = compute_objsize (ptr, 1, pobj);
3147 /* The size of the destination or source object. */
3148 tree dstsize = NULL_TREE, srcsize = NULL_TREE;
3149 if (access.second.mode == access_read_only
3150 || access.second.mode == access_none)
3152 /* For a read-only argument there is no destination. For
3153 no access, set the source as well and differentiate via
3154 the access flag below. */
3155 srcsize = objsize;
3156 if (access.second.mode == access_read_only
3157 || access.second.mode == access_none)
3159 /* For a read-only attribute there is no destination so
3160 clear OBJSIZE. This emits "reading N bytes" kind of
3161 diagnostics instead of the "writing N bytes" kind,
3162 unless MODE is none. */
3163 objsize = NULL_TREE;
3166 else
3167 dstsize = objsize;
3169 /* Clear the no-warning bit in case it was set by check_access
3170 in a prior iteration so that accesses via different arguments
3171 are diagnosed. */
3172 suppress_warning (stmt, OPT_Wstringop_overflow_, false);
3173 access_mode mode = data.mode;
3174 if (mode == access_deferred)
3175 mode = TYPE_READONLY (argtype) ? access_read_only : access_read_write;
3176 check_access (stmt, access_size, /*maxread=*/ NULL_TREE, srcsize,
3177 dstsize, mode, &data);
3179 if (warning_suppressed_p (stmt, OPT_Wstringop_overflow_))
3180 opt_warned = OPT_Wstringop_overflow_;
3181 if (opt_warned != no_warning)
3183 if (access.second.internal_p)
3184 inform (loc, "referencing argument %u of type %qT",
3185 ptridx + 1, ptrtype);
3186 else
3187 /* If check_access issued a warning above, append the relevant
3188 attribute to the string. */
3189 append_attrname (access, attrstr, sizeof attrstr);
3193 if (*attrstr)
3195 if (fndecl)
3196 inform (get_location (fndecl),
3197 "in a call to function %qD declared with attribute %qs",
3198 fndecl, attrstr);
3199 else
3200 inform (get_location (stmt),
3201 "in a call with type %qT and attribute %qs",
3202 fntype, attrstr);
3204 else if (opt_warned != no_warning)
3206 if (fndecl)
3207 inform (get_location (fndecl),
3208 "in a call to function %qD", fndecl);
3209 else
3210 inform (get_location (stmt),
3211 "in a call with type %qT", fntype);
3214 /* Set the bit in case if was cleared and not set above. */
3215 if (opt_warned != no_warning)
3216 suppress_warning (stmt, opt_warned);
3219 /* Check call STMT to an ordinary (non-built-in) function for invalid
3220 accesses. Return true if a call has been handled. */
3222 bool
3223 pass_waccess::check_call (gcall *stmt)
3225 tree fntype = gimple_call_fntype (stmt);
3226 if (!fntype)
3227 return false;
3229 tree fntypeattrs = TYPE_ATTRIBUTES (fntype);
3230 if (!fntypeattrs)
3231 return false;
3233 /* Map of attribute accewss specifications for function arguments. */
3234 rdwr_map rdwr_idx;
3235 init_attr_rdwr_indices (&rdwr_idx, fntypeattrs);
3237 unsigned nargs = call_nargs (stmt);
3238 for (unsigned i = 0; i != nargs; ++i)
3240 tree arg = call_arg (stmt, i);
3242 /* Save the actual argument that corresponds to the access attribute
3243 operand for later processing. */
3244 if (attr_access *access = rdwr_idx.get (i))
3246 if (POINTER_TYPE_P (TREE_TYPE (arg)))
3248 access->ptr = arg;
3249 // A nonnull ACCESS->SIZE contains VLA bounds. */
3251 else
3253 access->size = arg;
3254 gcc_assert (access->ptr == NULL_TREE);
3259 /* Check attribute access arguments. */
3260 tree fndecl = gimple_call_fndecl (stmt);
3261 maybe_warn_rdwr_sizes (&rdwr_idx, fndecl, fntype, stmt);
3263 check_alloc_size_call (stmt);
3264 return true;
3267 /* Check arguments in a call STMT for attribute nonstring. */
3269 static void
3270 check_nonstring_args (gcall *stmt)
3272 tree fndecl = gimple_call_fndecl (stmt);
3274 /* Detect passing non-string arguments to functions expecting
3275 nul-terminated strings. */
3276 maybe_warn_nonstring_arg (fndecl, stmt);
3279 /* Check call STMT for invalid accesses. */
3281 void
3282 pass_waccess::check (gcall *stmt)
3284 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
3285 check_builtin (stmt);
3287 if (is_gimple_call (stmt))
3288 check_call (stmt);
3290 maybe_check_dealloc_call (stmt);
3292 check_nonstring_args (stmt);
3295 /* Check basic block BB for invalid accesses. */
3297 void
3298 pass_waccess::check (basic_block bb)
3300 /* Iterate over statements, looking for function calls. */
3301 for (auto si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
3303 if (gcall *call = dyn_cast <gcall *> (gsi_stmt (si)))
3304 check (call);
3308 /* Check function FUN for invalid accesses. */
3310 unsigned
3311 pass_waccess::execute (function *fun)
3313 /* Create a new ranger instance and associate it with FUN. */
3314 m_ranger = enable_ranger (fun);
3316 basic_block bb;
3317 FOR_EACH_BB_FN (bb, fun)
3318 check (bb);
3320 /* Release the ranger instance and replace it with a global ranger. */
3321 disable_ranger (fun);
3323 return 0;
3326 } // namespace
3328 /* Return a new instance of the pass. */
3330 gimple_opt_pass *
3331 make_pass_warn_access (gcc::context *ctxt)
3333 return new pass_waccess (ctxt);