1 /* Pass to detect and issue warnings for invalid accesses, including
2 invalid or mismatched allocation/deallocation calls.
4 Copyright (C) 2020-2024 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
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
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
26 #include "coretypes.h"
30 #include "tree-pass.h"
32 #include "diagnostic.h"
34 #include "gimple-pretty-print.h"
35 #include "gimple-ssa-warn-access.h"
36 #include "gimple-ssa-warn-restrict.h"
37 #include "diagnostic-core.h"
38 #include "fold-const.h"
39 #include "gimple-iterator.h"
40 #include "gimple-fold.h"
41 #include "langhooks.h"
47 #include "tree-object-size.h"
48 #include "tree-ssa-strlen.h"
52 #include "gimple-range.h"
53 #include "stringpool.h"
56 #include "attr-fnspec.h"
57 #include "pointer-query.h"
59 /* Return true if tree node X has an associated location. */
61 static inline location_t
62 has_location (const_tree x
)
65 return DECL_SOURCE_LOCATION (x
) != UNKNOWN_LOCATION
;
68 return EXPR_HAS_LOCATION (x
);
73 /* Return the associated location of STMT. */
75 static inline location_t
76 get_location (const gimple
*stmt
)
78 return gimple_location (stmt
);
81 /* Return the associated location of tree node X. */
83 static inline location_t
87 return DECL_SOURCE_LOCATION (x
);
90 return EXPR_LOCATION (x
);
92 return UNKNOWN_LOCATION
;
95 /* Overload of the nascent tree function for GIMPLE STMT. */
98 get_callee_fndecl (const gimple
*stmt
)
100 return gimple_call_fndecl (stmt
);
103 static inline unsigned
104 call_nargs (const gimple
*stmt
)
106 return gimple_call_num_args (stmt
);
109 static inline unsigned
110 call_nargs (const_tree expr
)
112 return call_expr_nargs (expr
);
117 call_arg (const gimple
*stmt
, unsigned argno
)
119 return gimple_call_arg (stmt
, argno
);
123 call_arg (tree expr
, unsigned argno
)
125 return CALL_EXPR_ARG (expr
, argno
);
128 /* For a call EXPR at LOC to a function FNAME that expects a string
129 in the argument ARG, issue a diagnostic due to it being a called
130 with an argument that is a character array with no terminating
131 NUL. SIZE is the EXACT size of the array, and BNDRNG the number
132 of characters in which the NUL is expected. Either EXPR or FNAME
133 may be null but noth both. SIZE may be null when BNDRNG is null. */
135 template <class GimpleOrTree
>
137 warn_string_no_nul (location_t loc
, GimpleOrTree expr
, const char *fname
,
138 tree arg
, tree decl
, tree size
, bool exact
,
139 const wide_int bndrng
[2] /* = NULL */)
141 const opt_code opt
= OPT_Wstringop_overread
;
142 if ((expr
&& warning_suppressed_p (expr
, opt
))
143 || warning_suppressed_p (arg
, opt
))
146 loc
= expansion_point_location_if_in_system_header (loc
);
149 /* Format the bound range as a string to keep the number of messages
155 if (bndrng
[0] == bndrng
[1])
156 sprintf (bndstr
, "%llu", (unsigned long long) bndrng
[0].to_uhwi ());
158 sprintf (bndstr
, "[%llu, %llu]",
159 (unsigned long long) bndrng
[0].to_uhwi (),
160 (unsigned long long) bndrng
[1].to_uhwi ());
163 auto_diagnostic_group d
;
165 const tree maxobjsize
= max_object_size ();
166 const wide_int maxsiz
= wi::to_wide (maxobjsize
);
169 tree func
= get_callee_fndecl (expr
);
172 if (wi::ltu_p (maxsiz
, bndrng
[0]))
173 warned
= warning_at (loc
, opt
,
174 "%qD specified bound %s exceeds "
175 "maximum object size %E",
176 func
, bndstr
, maxobjsize
);
179 bool maybe
= wi::to_wide (size
) == bndrng
[0];
180 warned
= warning_at (loc
, opt
,
182 ? G_("%qD specified bound %s exceeds "
183 "the size %E of unterminated array")
185 ? G_("%qD specified bound %s may "
186 "exceed the size of at most %E "
187 "of unterminated array")
188 : G_("%qD specified bound %s exceeds "
189 "the size of at most %E "
190 "of unterminated array")),
195 warned
= warning_at (loc
, opt
,
196 "%qD argument missing terminating nul",
203 if (wi::ltu_p (maxsiz
, bndrng
[0]))
204 warned
= warning_at (loc
, opt
,
205 "%qs specified bound %s exceeds "
206 "maximum object size %E",
207 fname
, bndstr
, maxobjsize
);
210 bool maybe
= wi::to_wide (size
) == bndrng
[0];
211 warned
= warning_at (loc
, opt
,
213 ? G_("%qs specified bound %s exceeds "
214 "the size %E of unterminated array")
216 ? G_("%qs specified bound %s may "
217 "exceed the size of at most %E "
218 "of unterminated array")
219 : G_("%qs specified bound %s exceeds "
220 "the size of at most %E "
221 "of unterminated array")),
222 fname
, bndstr
, size
);
226 warned
= warning_at (loc
, opt
,
227 "%qs argument missing terminating nul",
233 inform (get_location (decl
),
234 "referenced argument declared here");
235 suppress_warning (arg
, opt
);
237 suppress_warning (expr
, opt
);
242 warn_string_no_nul (location_t loc
, gimple
*stmt
, const char *fname
,
243 tree arg
, tree decl
, tree size
/* = NULL_TREE */,
244 bool exact
/* = false */,
245 const wide_int bndrng
[2] /* = NULL */)
247 return warn_string_no_nul
<gimple
*> (loc
, stmt
, fname
,
248 arg
, decl
, size
, exact
, bndrng
);
252 warn_string_no_nul (location_t loc
, tree expr
, const char *fname
,
253 tree arg
, tree decl
, tree size
/* = NULL_TREE */,
254 bool exact
/* = false */,
255 const wide_int bndrng
[2] /* = NULL */)
257 return warn_string_no_nul
<tree
> (loc
, expr
, fname
,
258 arg
, decl
, size
, exact
, bndrng
);
261 /* If EXP refers to an unterminated constant character array return
262 the declaration of the object of which the array is a member or
263 element and if SIZE is not null, set *SIZE to the size of
264 the unterminated array and set *EXACT if the size is exact or
265 clear it otherwise. Otherwise return null. */
268 unterminated_array (tree exp
, tree
*size
/* = NULL */, bool *exact
/* = NULL */)
270 /* C_STRLEN will return NULL and set DECL in the info
271 structure if EXP references a unterminated array. */
272 c_strlen_data lendata
= { };
273 tree len
= c_strlen (exp
, 1, &lendata
);
274 if (len
|| !lendata
.minlen
|| !lendata
.decl
)
280 len
= lendata
.minlen
;
283 /* Constant offsets are already accounted for in LENDATA.MINLEN,
284 but not in a SSA_NAME + CST expression. */
285 if (TREE_CODE (lendata
.off
) == INTEGER_CST
)
287 else if (TREE_CODE (lendata
.off
) == PLUS_EXPR
288 && TREE_CODE (TREE_OPERAND (lendata
.off
, 1)) == INTEGER_CST
)
290 /* Subtract the offset from the size of the array. */
292 tree temp
= TREE_OPERAND (lendata
.off
, 1);
293 temp
= fold_convert (ssizetype
, temp
);
294 len
= fold_build2 (MINUS_EXPR
, ssizetype
, len
, temp
);
306 /* For a call EXPR (which may be null) that expects a string argument
307 SRC as an argument, returns false if SRC is a character array with
308 no terminating NUL. When nonnull, BOUND is the number of characters
309 in which to expect the terminating NUL. When EXPR is nonnull also
312 template <class GimpleOrTree
>
314 check_nul_terminated_array (GimpleOrTree expr
, tree src
, tree bound
)
316 /* The constant size of the array SRC points to. The actual size
317 may be less of EXACT is true, but not more. */
319 /* True if SRC involves a non-constant offset into the array. */
321 /* The unterminated constant array SRC points to. */
322 tree nonstr
= unterminated_array (src
, &size
, &exact
);
326 /* NONSTR refers to the non-nul terminated constant array and SIZE
327 is the constant size of the array in bytes. EXACT is true when
333 Value_Range
r (TREE_TYPE (bound
));
335 get_range_query (cfun
)->range_of_expr (r
, bound
);
337 if (r
.undefined_p () || r
.varying_p ())
340 bndrng
[0] = r
.lower_bound ();
341 bndrng
[1] = r
.upper_bound ();
345 if (wi::leu_p (bndrng
[0], wi::to_wide (size
)))
348 else if (wi::lt_p (bndrng
[0], wi::to_wide (size
), UNSIGNED
))
353 warn_string_no_nul (get_location (expr
), expr
, NULL
, src
, nonstr
,
354 size
, exact
, bound
? bndrng
: NULL
);
360 check_nul_terminated_array (gimple
*stmt
, tree src
, tree bound
/* = NULL_TREE */)
362 return check_nul_terminated_array
<gimple
*>(stmt
, src
, bound
);
366 check_nul_terminated_array (tree expr
, tree src
, tree bound
/* = NULL_TREE */)
368 return check_nul_terminated_array
<tree
>(expr
, src
, bound
);
371 /* Warn about passing a non-string array/pointer to a built-in function
372 that expects a nul-terminated string argument. Returns true if
373 a warning has been issued.*/
375 template <class GimpleOrTree
>
377 maybe_warn_nonstring_arg (tree fndecl
, GimpleOrTree exp
)
379 if (!fndecl
|| !fndecl_built_in_p (fndecl
, BUILT_IN_NORMAL
))
382 if (!warn_stringop_overread
383 || warning_suppressed_p (exp
, OPT_Wstringop_overread
))
386 /* Avoid clearly invalid calls (more checking done below). */
387 unsigned nargs
= call_nargs (exp
);
391 /* The bound argument to a bounded string function like strncpy. */
392 tree bound
= NULL_TREE
;
394 /* The longest known or possible string argument to one of the comparison
395 functions. If the length is less than the bound it is used instead.
396 Since the length is only used for warning and not for code generation
397 disable strict mode in the calls to get_range_strlen below. */
398 tree maxlen
= NULL_TREE
;
400 /* It's safe to call "bounded" string functions with a non-string
401 argument since the functions provide an explicit bound for this
402 purpose. The exception is strncat where the bound may refer to
403 either the destination or the source. */
404 int fncode
= DECL_FUNCTION_CODE (fndecl
);
407 case BUILT_IN_STRCMP
:
408 case BUILT_IN_STRNCMP
:
409 case BUILT_IN_STRNCASECMP
:
411 /* For these, if one argument refers to one or more of a set
412 of string constants or arrays of known size, determine
413 the range of their known or possible lengths and use it
414 conservatively as the bound for the unbounded function,
415 and to adjust the range of the bound of the bounded ones. */
416 for (unsigned argno
= 0;
417 argno
< MIN (nargs
, 2)
418 && !(maxlen
&& TREE_CODE (maxlen
) == INTEGER_CST
); argno
++)
420 tree arg
= call_arg (exp
, argno
);
421 if (!get_attr_nonstring_decl (arg
))
423 c_strlen_data lendata
= { };
424 /* Set MAXBOUND to an arbitrary non-null non-integer
425 node as a request to have it set to the length of
426 the longest string in a PHI. */
427 lendata
.maxbound
= arg
;
428 get_range_strlen (arg
, &lendata
, /* eltsize = */ 1);
429 maxlen
= lendata
.maxbound
;
435 case BUILT_IN_STRNCAT
:
436 case BUILT_IN_STPNCPY
:
437 case BUILT_IN_STRNCPY
:
439 bound
= call_arg (exp
, 2);
442 case BUILT_IN_STRNDUP
:
445 bound
= call_arg (exp
, 1);
448 case BUILT_IN_STRNLEN
:
450 tree arg
= call_arg (exp
, 0);
451 if (!get_attr_nonstring_decl (arg
))
453 c_strlen_data lendata
= { };
454 /* Set MAXBOUND to an arbitrary non-null non-integer
455 node as a request to have it set to the length of
456 the longest string in a PHI. */
457 lendata
.maxbound
= arg
;
458 get_range_strlen (arg
, &lendata
, /* eltsize = */ 1);
459 maxlen
= lendata
.maxbound
;
462 bound
= call_arg (exp
, 1);
470 /* Determine the range of the bound argument (if specified). */
471 tree bndrng
[2] = { NULL_TREE
, NULL_TREE
};
475 get_size_range (bound
, bndrng
);
478 location_t loc
= get_location (exp
);
482 /* Diagnose excessive bound prior to the adjustment below and
483 regardless of attribute nonstring. */
484 tree maxobjsize
= max_object_size ();
485 if (tree_int_cst_lt (maxobjsize
, bndrng
[0]))
488 if (tree_int_cst_equal (bndrng
[0], bndrng
[1]))
489 warned
= warning_at (loc
, OPT_Wstringop_overread
,
490 "%qD specified bound %E "
491 "exceeds maximum object size %E",
492 fndecl
, bndrng
[0], maxobjsize
);
494 warned
= warning_at (loc
, OPT_Wstringop_overread
,
495 "%qD specified bound [%E, %E] "
496 "exceeds maximum object size %E",
497 fndecl
, bndrng
[0], bndrng
[1],
500 suppress_warning (exp
, OPT_Wstringop_overread
);
506 if (maxlen
&& !integer_all_onesp (maxlen
))
508 /* Add one for the nul. */
509 maxlen
= const_binop (PLUS_EXPR
, TREE_TYPE (maxlen
), maxlen
,
514 /* Conservatively use the upper bound of the lengths for
515 both the lower and the upper bound of the operation. */
518 bound
= void_type_node
;
522 /* Replace the bound on the operation with the upper bound
523 of the length of the string if the latter is smaller. */
524 if (tree_int_cst_lt (maxlen
, bndrng
[0]))
526 else if (tree_int_cst_lt (maxlen
, bndrng
[1]))
531 bool any_arg_warned
= false;
532 /* Iterate over the built-in function's formal arguments and check
533 each const char* against the actual argument. If the actual
534 argument is declared attribute non-string issue a warning unless
535 the argument's maximum length is bounded. */
536 function_args_iterator it
;
537 function_args_iter_init (&it
, TREE_TYPE (fndecl
));
539 for (unsigned argno
= 0; ; ++argno
, function_args_iter_next (&it
))
541 /* Avoid iterating past the declared argument in a call
542 to function declared without a prototype. */
546 tree argtype
= function_args_iter_cond (&it
);
550 if (TREE_CODE (argtype
) != POINTER_TYPE
)
553 argtype
= TREE_TYPE (argtype
);
555 if (TREE_CODE (argtype
) != INTEGER_TYPE
556 || !TYPE_READONLY (argtype
))
559 argtype
= TYPE_MAIN_VARIANT (argtype
);
560 if (argtype
!= char_type_node
)
563 tree callarg
= call_arg (exp
, argno
);
564 if (TREE_CODE (callarg
) == ADDR_EXPR
)
565 callarg
= TREE_OPERAND (callarg
, 0);
567 /* See if the destination is declared with attribute "nonstring". */
568 tree decl
= get_attr_nonstring_decl (callarg
);
572 /* The maximum number of array elements accessed. */
573 offset_int wibnd
= 0;
575 if (argno
&& fncode
== BUILT_IN_STRNCAT
)
577 /* See if the bound in strncat is derived from the length
578 of the strlen of the destination (as it's expected to be).
579 If so, reset BOUND and FNCODE to trigger a warning. */
580 tree dstarg
= call_arg (exp
, 0);
581 if (is_strlen_related_p (dstarg
, bound
))
583 /* The bound applies to the destination, not to the source,
584 so reset these to trigger a warning without mentioning
590 /* Use the upper bound of the range for strncat. */
591 wibnd
= wi::to_offset (bndrng
[1]);
594 /* Use the lower bound of the range for functions other than
596 wibnd
= wi::to_offset (bndrng
[0]);
598 /* Determine the size of the argument array if it is one. */
599 offset_int asize
= wibnd
;
600 bool known_size
= false;
601 tree type
= TREE_TYPE (decl
);
603 /* Determine the array size. For arrays of unknown bound and
604 pointers reset BOUND to trigger the appropriate warning. */
605 if (TREE_CODE (type
) == ARRAY_TYPE
)
607 if (tree arrbnd
= TYPE_DOMAIN (type
))
609 if ((arrbnd
= TYPE_MAX_VALUE (arrbnd
)))
611 asize
= wi::to_offset (arrbnd
) + 1;
615 else if (bound
== void_type_node
)
618 else if (bound
== void_type_node
)
621 /* In a call to strncat with a bound in a range whose lower but
622 not upper bound is less than the array size, reset ASIZE to
623 be the same as the bound and the other variable to trigger
624 the appropriate warning below. */
625 if (fncode
== BUILT_IN_STRNCAT
626 && bndrng
[0] != bndrng
[1]
627 && wi::ltu_p (wi::to_offset (bndrng
[0]), asize
)
629 || wi::ltu_p (asize
, wibnd
)))
638 auto_diagnostic_group d
;
639 if (wi::ltu_p (asize
, wibnd
))
641 if (bndrng
[0] == bndrng
[1])
642 warned
= warning_at (loc
, OPT_Wstringop_overread
,
643 "%qD argument %i declared attribute "
644 "%<nonstring%> is smaller than the specified "
646 fndecl
, argno
+ 1, wibnd
.to_uhwi ());
647 else if (wi::ltu_p (asize
, wi::to_offset (bndrng
[0])))
648 warned
= warning_at (loc
, OPT_Wstringop_overread
,
649 "%qD argument %i declared attribute "
650 "%<nonstring%> is smaller than "
651 "the specified bound [%E, %E]",
652 fndecl
, argno
+ 1, bndrng
[0], bndrng
[1]);
654 warned
= warning_at (loc
, OPT_Wstringop_overread
,
655 "%qD argument %i declared attribute "
656 "%<nonstring%> may be smaller than "
657 "the specified bound [%E, %E]",
658 fndecl
, argno
+ 1, bndrng
[0], bndrng
[1]);
660 else if (fncode
== BUILT_IN_STRNCAT
)
661 ; /* Avoid warning for calls to strncat() when the bound
662 is equal to the size of the non-string argument. */
664 warned
= warning_at (loc
, OPT_Wstringop_overread
,
665 "%qD argument %i declared attribute %<nonstring%>",
670 inform (DECL_SOURCE_LOCATION (decl
),
671 "argument %qD declared here", decl
);
672 any_arg_warned
= true;
677 suppress_warning (exp
, OPT_Wstringop_overread
);
679 return any_arg_warned
;
683 maybe_warn_nonstring_arg (tree fndecl
, gimple
*stmt
)
685 return maybe_warn_nonstring_arg
<gimple
*>(fndecl
, stmt
);
690 maybe_warn_nonstring_arg (tree fndecl
, tree expr
)
692 return maybe_warn_nonstring_arg
<tree
>(fndecl
, expr
);
695 /* Issue a warning OPT for a bounded call EXP with a bound in RANGE
696 accessing an object with SIZE. */
698 template <class GimpleOrTree
>
700 maybe_warn_for_bound (opt_code opt
, location_t loc
, GimpleOrTree exp
, tree func
,
701 tree bndrng
[2], tree size
, const access_data
*pad
)
703 if (!bndrng
[0] || warning_suppressed_p (exp
, opt
))
706 tree maxobjsize
= max_object_size ();
710 if (opt
== OPT_Wstringop_overread
)
712 bool maybe
= pad
&& pad
->src
.phi ();
715 /* Issue a "maybe" warning only if the PHI refers to objects
716 at least one of which has more space remaining than the bound.
717 Otherwise, if the bound is greater, use the definitive form. */
718 offset_int remmax
= pad
->src
.size_remaining ();
719 if (remmax
< wi::to_offset (bndrng
[0]))
723 auto_diagnostic_group d
;
724 if (tree_int_cst_lt (maxobjsize
, bndrng
[0]))
726 if (bndrng
[0] == bndrng
[1])
728 ? warning_at (loc
, opt
,
730 ? G_("%qD specified bound %E may "
731 "exceed maximum object size %E")
732 : G_("%qD specified bound %E "
733 "exceeds maximum object size %E")),
734 func
, bndrng
[0], maxobjsize
)
735 : warning_at (loc
, opt
,
737 ? G_("specified bound %E may "
738 "exceed maximum object size %E")
739 : G_("specified bound %E "
740 "exceeds maximum object size %E")),
741 bndrng
[0], maxobjsize
));
744 ? warning_at (loc
, opt
,
746 ? G_("%qD specified bound [%E, %E] may "
747 "exceed maximum object size %E")
748 : G_("%qD specified bound [%E, %E] "
749 "exceeds maximum object size %E")),
751 bndrng
[0], bndrng
[1], maxobjsize
)
752 : warning_at (loc
, opt
,
754 ? G_("specified bound [%E, %E] may "
755 "exceed maximum object size %E")
756 : G_("specified bound [%E, %E] "
757 "exceeds maximum object size %E")),
758 bndrng
[0], bndrng
[1], maxobjsize
));
760 else if (!size
|| tree_int_cst_le (bndrng
[0], size
))
762 else if (tree_int_cst_equal (bndrng
[0], bndrng
[1]))
764 ? warning_at (loc
, opt
,
766 ? G_("%qD specified bound %E may exceed "
768 : G_("%qD specified bound %E exceeds "
770 func
, bndrng
[0], size
)
771 : warning_at (loc
, opt
,
773 ? G_("specified bound %E may exceed "
775 : G_("specified bound %E exceeds "
780 ? warning_at (loc
, opt
,
782 ? G_("%qD specified bound [%E, %E] may "
783 "exceed source size %E")
784 : G_("%qD specified bound [%E, %E] exceeds "
786 func
, bndrng
[0], bndrng
[1], size
)
787 : warning_at (loc
, opt
,
789 ? G_("specified bound [%E, %E] may exceed "
791 : G_("specified bound [%E, %E] exceeds "
793 bndrng
[0], bndrng
[1], size
));
796 if (pad
&& pad
->src
.ref
797 && has_location (pad
->src
.ref
))
798 inform (get_location (pad
->src
.ref
),
799 "source object allocated here");
800 suppress_warning (exp
, opt
);
806 bool maybe
= pad
&& pad
->dst
.phi ();
809 /* Issue a "maybe" warning only if the PHI refers to objects
810 at least one of which has more space remaining than the bound.
811 Otherwise, if the bound is greater, use the definitive form. */
812 offset_int remmax
= pad
->dst
.size_remaining ();
813 if (remmax
< wi::to_offset (bndrng
[0]))
816 if (tree_int_cst_lt (maxobjsize
, bndrng
[0]))
818 if (bndrng
[0] == bndrng
[1])
820 ? warning_at (loc
, opt
,
822 ? G_("%qD specified size %E may "
823 "exceed maximum object size %E")
824 : G_("%qD specified size %E "
825 "exceeds maximum object size %E")),
826 func
, bndrng
[0], maxobjsize
)
827 : warning_at (loc
, opt
,
829 ? G_("specified size %E may exceed "
830 "maximum object size %E")
831 : G_("specified size %E exceeds "
832 "maximum object size %E")),
833 bndrng
[0], maxobjsize
));
836 ? warning_at (loc
, opt
,
838 ? G_("%qD specified size between %E and %E "
839 "may exceed maximum object size %E")
840 : G_("%qD specified size between %E and %E "
841 "exceeds maximum object size %E")),
842 func
, bndrng
[0], bndrng
[1], maxobjsize
)
843 : warning_at (loc
, opt
,
845 ? G_("specified size between %E and %E "
846 "may exceed maximum object size %E")
847 : G_("specified size between %E and %E "
848 "exceeds maximum object size %E")),
849 bndrng
[0], bndrng
[1], maxobjsize
));
851 else if (!size
|| tree_int_cst_le (bndrng
[0], size
))
853 else if (tree_int_cst_equal (bndrng
[0], bndrng
[1]))
855 ? warning_at (loc
, opt
,
857 ? G_("%qD specified bound %E may exceed "
858 "destination size %E")
859 : G_("%qD specified bound %E exceeds "
860 "destination size %E")),
861 func
, bndrng
[0], size
)
862 : warning_at (loc
, opt
,
864 ? G_("specified bound %E may exceed "
865 "destination size %E")
866 : G_("specified bound %E exceeds "
867 "destination size %E")),
871 ? warning_at (loc
, opt
,
873 ? G_("%qD specified bound [%E, %E] may exceed "
874 "destination size %E")
875 : G_("%qD specified bound [%E, %E] exceeds "
876 "destination size %E")),
877 func
, bndrng
[0], bndrng
[1], size
)
878 : warning_at (loc
, opt
,
880 ? G_("specified bound [%E, %E] exceeds "
881 "destination size %E")
882 : G_("specified bound [%E, %E] exceeds "
883 "destination size %E")),
884 bndrng
[0], bndrng
[1], size
));
888 if (pad
&& pad
->dst
.ref
889 && has_location (pad
->dst
.ref
))
890 inform (get_location (pad
->dst
.ref
),
891 "destination object allocated here");
892 suppress_warning (exp
, opt
);
899 maybe_warn_for_bound (opt_code opt
, location_t loc
, gimple
*stmt
, tree func
,
900 tree bndrng
[2], tree size
,
901 const access_data
*pad
/* = NULL */)
903 return maybe_warn_for_bound
<gimple
*> (opt
, loc
, stmt
, func
, bndrng
, size
,
908 maybe_warn_for_bound (opt_code opt
, location_t loc
, tree expr
, tree func
,
909 tree bndrng
[2], tree size
,
910 const access_data
*pad
/* = NULL */)
912 return maybe_warn_for_bound
<tree
> (opt
, loc
, expr
, func
, bndrng
, size
, pad
);
915 /* For an expression EXP issue an access warning controlled by option OPT
916 with access to a region SIZE bytes in size in the RANGE of sizes.
917 WRITE is true for a write access, READ for a read access, neither for
918 call that may or may not perform an access but for which the range
919 is expected to valid.
920 Returns true when a warning has been issued. */
922 template <class GimpleOrTree
>
924 warn_for_access (location_t loc
, tree func
, GimpleOrTree exp
, int opt
,
925 tree range
[2], tree size
, bool write
, bool read
, bool maybe
)
931 if (tree_int_cst_equal (range
[0], range
[1]))
933 ? warning_n (loc
, opt
, tree_to_uhwi (range
[0]),
935 ? G_("%qD may access %E byte in a region "
937 : G_("%qD accessing %E byte in a region "
940 ? G_ ("%qD may access %E bytes in a region "
942 : G_ ("%qD accessing %E bytes in a region "
944 func
, range
[0], size
)
945 : warning_n (loc
, opt
, tree_to_uhwi (range
[0]),
947 ? G_("may access %E byte in a region "
949 : G_("accessing %E byte in a region "
952 ? G_("may access %E bytes in a region "
954 : G_("accessing %E bytes in a region "
957 else if (tree_int_cst_sign_bit (range
[1]))
959 /* Avoid printing the upper bound if it's invalid. */
961 ? warning_at (loc
, opt
,
963 ? G_("%qD may access %E or more bytes "
964 "in a region of size %E")
965 : G_("%qD accessing %E or more bytes "
966 "in a region of size %E")),
967 func
, range
[0], size
)
968 : warning_at (loc
, opt
,
970 ? G_("may access %E or more bytes "
971 "in a region of size %E")
972 : G_("accessing %E or more bytes "
973 "in a region of size %E")),
978 ? warning_at (loc
, opt
,
980 ? G_("%qD may access between %E and %E "
981 "bytes in a region of size %E")
982 : G_("%qD accessing between %E and %E "
983 "bytes in a region of size %E")),
984 func
, range
[0], range
[1], size
)
985 : warning_at (loc
, opt
,
987 ? G_("may access between %E and %E bytes "
988 "in a region of size %E")
989 : G_("accessing between %E and %E bytes "
990 "in a region of size %E")),
991 range
[0], range
[1], size
));
997 if (tree_int_cst_equal (range
[0], range
[1]))
999 ? warning_n (loc
, opt
, tree_to_uhwi (range
[0]),
1001 ? G_("%qD may write %E byte into a region "
1003 : G_("%qD writing %E byte into a region "
1004 "of size %E overflows the destination")),
1006 ? G_("%qD may write %E bytes into a region "
1008 : G_("%qD writing %E bytes into a region "
1009 "of size %E overflows the destination")),
1010 func
, range
[0], size
)
1011 : warning_n (loc
, opt
, tree_to_uhwi (range
[0]),
1013 ? G_("may write %E byte into a region "
1015 : G_("writing %E byte into a region "
1016 "of size %E overflows the destination")),
1018 ? G_("may write %E bytes into a region "
1020 : G_("writing %E bytes into a region "
1021 "of size %E overflows the destination")),
1023 else if (tree_int_cst_sign_bit (range
[1]))
1025 /* Avoid printing the upper bound if it's invalid. */
1027 ? warning_at (loc
, opt
,
1029 ? G_("%qD may write %E or more bytes "
1030 "into a region of size %E")
1031 : G_("%qD writing %E or more bytes "
1032 "into a region of size %E overflows "
1033 "the destination")),
1034 func
, range
[0], size
)
1035 : warning_at (loc
, opt
,
1037 ? G_("may write %E or more bytes into "
1038 "a region of size %E")
1039 : G_("writing %E or more bytes into "
1040 "a region of size %E overflows "
1041 "the destination")),
1046 ? warning_at (loc
, opt
,
1048 ? G_("%qD may write between %E and %E bytes "
1049 "into a region of size %E")
1050 : G_("%qD writing between %E and %E bytes "
1051 "into a region of size %E overflows "
1052 "the destination")),
1053 func
, range
[0], range
[1], size
)
1054 : warning_at (loc
, opt
,
1056 ? G_("may write between %E and %E bytes "
1057 "into a region of size %E")
1058 : G_("writing between %E and %E bytes "
1059 "into a region of size %E overflows "
1060 "the destination")),
1061 range
[0], range
[1], size
));
1067 if (tree_int_cst_equal (range
[0], range
[1]))
1069 ? warning_n (loc
, OPT_Wstringop_overread
,
1070 tree_to_uhwi (range
[0]),
1072 ? G_("%qD may read %E byte from a region "
1074 : G_("%qD reading %E byte from a region "
1077 ? G_("%qD may read %E bytes from a region "
1079 : G_("%qD reading %E bytes from a region "
1081 func
, range
[0], size
)
1082 : warning_n (loc
, OPT_Wstringop_overread
,
1083 tree_to_uhwi (range
[0]),
1085 ? G_("may read %E byte from a region "
1087 : G_("reading %E byte from a region "
1090 ? G_("may read %E bytes from a region "
1092 : G_("reading %E bytes from a region "
1095 else if (tree_int_cst_sign_bit (range
[1]))
1097 /* Avoid printing the upper bound if it's invalid. */
1099 ? warning_at (loc
, OPT_Wstringop_overread
,
1101 ? G_("%qD may read %E or more bytes "
1102 "from a region of size %E")
1103 : G_("%qD reading %E or more bytes "
1104 "from a region of size %E")),
1105 func
, range
[0], size
)
1106 : warning_at (loc
, OPT_Wstringop_overread
,
1108 ? G_("may read %E or more bytes "
1109 "from a region of size %E")
1110 : G_("reading %E or more bytes "
1111 "from a region of size %E")),
1116 ? warning_at (loc
, OPT_Wstringop_overread
,
1118 ? G_("%qD may read between %E and %E bytes "
1119 "from a region of size %E")
1120 : G_("%qD reading between %E and %E bytes "
1121 "from a region of size %E")),
1122 func
, range
[0], range
[1], size
)
1123 : warning_at (loc
, opt
,
1125 ? G_("may read between %E and %E bytes "
1126 "from a region of size %E")
1127 : G_("reading between %E and %E bytes "
1128 "from a region of size %E")),
1129 range
[0], range
[1], size
));
1132 suppress_warning (exp
, OPT_Wstringop_overread
);
1137 if (tree_int_cst_equal (range
[0], range
[1])
1138 || tree_int_cst_sign_bit (range
[1]))
1140 ? warning_n (loc
, OPT_Wstringop_overread
,
1141 tree_to_uhwi (range
[0]),
1142 "%qD expecting %E byte in a region of size %E",
1143 "%qD expecting %E bytes in a region of size %E",
1144 func
, range
[0], size
)
1145 : warning_n (loc
, OPT_Wstringop_overread
,
1146 tree_to_uhwi (range
[0]),
1147 "expecting %E byte in a region of size %E",
1148 "expecting %E bytes in a region of size %E",
1150 else if (tree_int_cst_sign_bit (range
[1]))
1152 /* Avoid printing the upper bound if it's invalid. */
1154 ? warning_at (loc
, OPT_Wstringop_overread
,
1155 "%qD expecting %E or more bytes in a region "
1157 func
, range
[0], size
)
1158 : warning_at (loc
, OPT_Wstringop_overread
,
1159 "expecting %E or more bytes in a region "
1165 ? warning_at (loc
, OPT_Wstringop_overread
,
1166 "%qD expecting between %E and %E bytes in "
1167 "a region of size %E",
1168 func
, range
[0], range
[1], size
)
1169 : warning_at (loc
, OPT_Wstringop_overread
,
1170 "expecting between %E and %E bytes in "
1171 "a region of size %E",
1172 range
[0], range
[1], size
));
1175 suppress_warning (exp
, OPT_Wstringop_overread
);
1181 warn_for_access (location_t loc
, tree func
, gimple
*stmt
, int opt
,
1182 tree range
[2], tree size
, bool write
, bool read
, bool maybe
)
1184 return warn_for_access
<gimple
*>(loc
, func
, stmt
, opt
, range
, size
,
1185 write
, read
, maybe
);
1189 warn_for_access (location_t loc
, tree func
, tree expr
, int opt
,
1190 tree range
[2], tree size
, bool write
, bool read
, bool maybe
)
1192 return warn_for_access
<tree
>(loc
, func
, expr
, opt
, range
, size
,
1193 write
, read
, maybe
);
1196 /* Helper to set RANGE to the range of BOUND if it's nonnull, bounded
1197 by BNDRNG if nonnull and valid. */
1200 get_size_range (range_query
*query
, tree bound
, gimple
*stmt
, tree range
[2],
1201 int flags
, const offset_int bndrng
[2])
1204 get_size_range (query
, bound
, stmt
, range
, flags
);
1206 if (!bndrng
|| (bndrng
[0] == 0 && bndrng
[1] == HOST_WIDE_INT_M1U
))
1209 if (range
[0] && TREE_CODE (range
[0]) == INTEGER_CST
)
1212 { wi::to_offset (range
[0]), wi::to_offset (range
[1]) };
1213 if (r
[0] < bndrng
[0])
1214 range
[0] = wide_int_to_tree (sizetype
, bndrng
[0]);
1215 if (bndrng
[1] < r
[1])
1216 range
[1] = wide_int_to_tree (sizetype
, bndrng
[1]);
1220 range
[0] = wide_int_to_tree (sizetype
, bndrng
[0]);
1221 range
[1] = wide_int_to_tree (sizetype
, bndrng
[1]);
1225 /* Try to verify that the sizes and lengths of the arguments to a string
1226 manipulation function given by EXP are within valid bounds and that
1227 the operation does not lead to buffer overflow or read past the end.
1228 Arguments other than EXP may be null. When non-null, the arguments
1229 have the following meaning:
1230 DST is the destination of a copy call or NULL otherwise.
1231 SRC is the source of a copy call or NULL otherwise.
1232 DSTWRITE is the number of bytes written into the destination obtained
1233 from the user-supplied size argument to the function (such as in
1234 memcpy(DST, SRCs, DSTWRITE) or strncpy(DST, DRC, DSTWRITE).
1235 MAXREAD is the user-supplied bound on the length of the source sequence
1236 (such as in strncat(d, s, N). It specifies the upper limit on the number
1237 of bytes to write. If NULL, it's taken to be the same as DSTWRITE.
1238 SRCSTR is the source string (such as in strcpy(DST, SRC)) when the
1239 expression EXP is a string function call (as opposed to a memory call
1240 like memcpy). As an exception, SRCSTR can also be an integer denoting
1241 the precomputed size of the source string or object (for functions like
1243 DSTSIZE is the size of the destination object.
1245 When DSTWRITE is null LEN is checked to verify that it doesn't exceed
1248 WRITE is true for write accesses, READ is true for reads. Both are
1249 false for simple size checks in calls to functions that neither read
1250 from nor write to the region.
1252 When nonnull, PAD points to a more detailed description of the access.
1254 If the call is successfully verified as safe return true, otherwise
1257 template <class GimpleOrTree
>
1259 check_access (GimpleOrTree exp
, tree dstwrite
,
1260 tree maxread
, tree srcstr
, tree dstsize
,
1261 access_mode mode
, const access_data
*pad
,
1264 /* The size of the largest object is half the address space, or
1265 PTRDIFF_MAX. (This is way too permissive.) */
1266 tree maxobjsize
= max_object_size ();
1268 /* Either an approximate/minimum the length of the source string for
1269 string functions or the size of the source object for raw memory
1271 tree slen
= NULL_TREE
;
1273 /* The range of the access in bytes; first set to the write access
1274 for functions that write and then read for those that also (or
1276 tree range
[2] = { NULL_TREE
, NULL_TREE
};
1278 /* Set to true when the exact number of bytes written by a string
1279 function like strcpy is not known and the only thing that is
1280 known is that it must be at least one (for the terminating nul). */
1281 bool at_least_one
= false;
1284 /* SRCSTR is normally a pointer to string but as a special case
1285 it can be an integer denoting the length of a string. */
1286 if (POINTER_TYPE_P (TREE_TYPE (srcstr
)))
1288 if (!check_nul_terminated_array (exp
, srcstr
, maxread
))
1289 /* Return if the array is not nul-terminated and a warning
1293 /* Try to determine the range of lengths the source string
1294 refers to. If it can be determined and is less than
1295 the upper bound given by MAXREAD add one to it for
1296 the terminating nul. Otherwise, set it to one for
1297 the same reason, or to MAXREAD as appropriate. */
1298 c_strlen_data lendata
= { };
1299 get_range_strlen (srcstr
, &lendata
, /* eltsize = */ 1);
1300 range
[0] = lendata
.minlen
;
1301 range
[1] = lendata
.maxbound
? lendata
.maxbound
: lendata
.maxlen
;
1303 && TREE_CODE (range
[0]) == INTEGER_CST
1304 && TREE_CODE (range
[1]) == INTEGER_CST
1305 && (!maxread
|| TREE_CODE (maxread
) == INTEGER_CST
))
1307 if (maxread
&& tree_int_cst_le (maxread
, range
[0]))
1308 range
[0] = range
[1] = maxread
;
1310 range
[0] = fold_build2 (PLUS_EXPR
, size_type_node
,
1311 range
[0], size_one_node
);
1313 if (maxread
&& tree_int_cst_le (maxread
, range
[1]))
1315 else if (!integer_all_onesp (range
[1]))
1316 range
[1] = fold_build2 (PLUS_EXPR
, size_type_node
,
1317 range
[1], size_one_node
);
1323 at_least_one
= true;
1324 slen
= size_one_node
;
1331 if (!dstwrite
&& !maxread
)
1333 /* When the only available piece of data is the object size
1334 there is nothing to do. */
1338 /* Otherwise, when the length of the source sequence is known
1339 (as with strlen), set DSTWRITE to it. */
1345 dstsize
= maxobjsize
;
1347 /* Set RANGE to that of DSTWRITE if non-null, bounded by PAD->DST_BNDRNG
1349 gimple
*stmt
= pad
? pad
->stmt
: nullptr;
1350 get_size_range (rvals
, dstwrite
, stmt
, range
,
1351 /* If the destination has known zero size prefer a zero
1352 size range to avoid false positives if that's a
1354 integer_zerop (dstsize
) ? SR_ALLOW_ZERO
: 0,
1355 pad
? pad
->dst_bndrng
: NULL
);
1357 tree func
= get_callee_fndecl (exp
);
1358 /* Read vs write access by built-ins can be determined from the const
1359 qualifiers on the pointer argument. In the absence of attribute
1360 access, non-const qualified pointer arguments to user-defined
1361 functions are assumed to both read and write the objects. */
1362 const bool builtin
= func
? fndecl_built_in_p (func
) : false;
1364 /* First check the number of bytes to be written against the maximum
1367 && TREE_CODE (range
[0]) == INTEGER_CST
1368 && tree_int_cst_lt (maxobjsize
, range
[0]))
1370 location_t loc
= get_location (exp
);
1371 maybe_warn_for_bound (OPT_Wstringop_overflow_
, loc
, exp
, func
, range
,
1376 /* The number of bytes to write is "exact" if DSTWRITE is non-null,
1377 constant, and in range of unsigned HOST_WIDE_INT. */
1378 bool exactwrite
= dstwrite
&& tree_fits_uhwi_p (dstwrite
);
1380 /* Next check the number of bytes to be written against the destination
1382 if (range
[0] || !exactwrite
|| integer_all_onesp (dstwrite
))
1385 && TREE_CODE (range
[0]) == INTEGER_CST
1386 && ((tree_fits_uhwi_p (dstsize
)
1387 && tree_int_cst_lt (dstsize
, range
[0]))
1389 && tree_fits_uhwi_p (dstwrite
)
1390 && tree_int_cst_lt (dstwrite
, range
[0]))))
1392 const opt_code opt
= OPT_Wstringop_overflow_
;
1393 if (warning_suppressed_p (exp
, opt
)
1394 || (pad
&& pad
->dst
.ref
1395 && warning_suppressed_p (pad
->dst
.ref
, opt
)))
1398 auto_diagnostic_group d
;
1399 location_t loc
= get_location (exp
);
1400 bool warned
= false;
1401 if (dstwrite
== slen
&& at_least_one
)
1403 /* This is a call to strcpy with a destination of 0 size
1404 and a source of unknown length. The call will write
1405 at least one byte past the end of the destination. */
1407 ? warning_at (loc
, opt
,
1408 "%qD writing %E or more bytes into "
1409 "a region of size %E overflows "
1411 func
, range
[0], dstsize
)
1412 : warning_at (loc
, opt
,
1413 "writing %E or more bytes into "
1414 "a region of size %E overflows "
1416 range
[0], dstsize
));
1421 = mode
== access_read_only
|| mode
== access_read_write
;
1423 = mode
== access_write_only
|| mode
== access_read_write
;
1424 const bool maybe
= pad
&& pad
->dst
.parmarray
;
1425 warned
= warn_for_access (loc
, func
, exp
,
1426 OPT_Wstringop_overflow_
,
1428 write
, read
&& !builtin
, maybe
);
1433 suppress_warning (exp
, OPT_Wstringop_overflow_
);
1435 pad
->dst
.inform_access (pad
->mode
);
1438 /* Return error when an overflow has been detected. */
1443 /* Check the maximum length of the source sequence against the size
1444 of the destination object if known, or against the maximum size
1448 /* Set RANGE to that of MAXREAD, bounded by PAD->SRC_BNDRNG if
1449 PAD is nonnull and BNDRNG is valid. */
1450 get_size_range (rvals
, maxread
, stmt
, range
, 0,
1451 pad
? pad
->src_bndrng
: NULL
);
1453 location_t loc
= get_location (exp
);
1454 tree size
= dstsize
;
1455 if (pad
&& pad
->mode
== access_read_only
)
1456 size
= wide_int_to_tree (sizetype
, pad
->src
.size_remaining ());
1458 if (range
[0] && maxread
&& tree_fits_uhwi_p (size
))
1460 if (tree_int_cst_lt (maxobjsize
, range
[0]))
1462 maybe_warn_for_bound (OPT_Wstringop_overread
, loc
, exp
, func
,
1467 if (size
!= maxobjsize
&& tree_int_cst_lt (size
, range
[0]))
1469 opt_code opt
= (dstwrite
|| mode
!= access_read_only
1470 ? OPT_Wstringop_overflow_
1471 : OPT_Wstringop_overread
);
1472 maybe_warn_for_bound (opt
, loc
, exp
, func
, range
, size
, pad
);
1477 maybe_warn_nonstring_arg (func
, exp
);
1480 /* Check for reading past the end of SRC. */
1481 bool overread
= (slen
1485 && TREE_CODE (slen
) == INTEGER_CST
1486 && tree_int_cst_lt (slen
, range
[0]));
1487 /* If none is determined try to get a better answer based on the details
1491 && pad
->src
.sizrng
[1] >= 0
1492 && pad
->src
.offrng
[0] >= 0
1493 && (pad
->src
.offrng
[1] < 0
1494 || pad
->src
.offrng
[0] <= pad
->src
.offrng
[1]))
1496 /* Set RANGE to that of MAXREAD, bounded by PAD->SRC_BNDRNG if
1497 PAD is nonnull and BNDRNG is valid. */
1498 get_size_range (rvals
, maxread
, stmt
, range
, 0,
1499 pad
? pad
->src_bndrng
: NULL
);
1500 /* Set OVERREAD for reads starting just past the end of an object. */
1501 overread
= pad
->src
.sizrng
[1] - pad
->src
.offrng
[0] < pad
->src_bndrng
[0];
1502 range
[0] = wide_int_to_tree (sizetype
, pad
->src_bndrng
[0]);
1503 slen
= size_zero_node
;
1508 const opt_code opt
= OPT_Wstringop_overread
;
1509 if (warning_suppressed_p (exp
, opt
)
1510 || (srcstr
&& warning_suppressed_p (srcstr
, opt
))
1511 || (pad
&& pad
->src
.ref
1512 && warning_suppressed_p (pad
->src
.ref
, opt
)))
1515 location_t loc
= get_location (exp
);
1517 = mode
== access_read_only
|| mode
== access_read_write
;
1518 const bool maybe
= pad
&& pad
->dst
.parmarray
;
1519 auto_diagnostic_group d
;
1520 if (warn_for_access (loc
, func
, exp
, opt
, range
, slen
, false, read
,
1523 suppress_warning (exp
, opt
);
1525 pad
->src
.inform_access (access_read_only
);
1534 check_access (gimple
*stmt
, tree dstwrite
,
1535 tree maxread
, tree srcstr
, tree dstsize
,
1536 access_mode mode
, const access_data
*pad
,
1539 return check_access
<gimple
*> (stmt
, dstwrite
, maxread
, srcstr
, dstsize
,
1544 check_access (tree expr
, tree dstwrite
,
1545 tree maxread
, tree srcstr
, tree dstsize
,
1546 access_mode mode
, const access_data
*pad
/* = NULL */)
1548 return check_access
<tree
> (expr
, dstwrite
, maxread
, srcstr
, dstsize
,
1549 mode
, pad
, nullptr);
1552 /* Return true if STMT is a call to an allocation function. Unless
1553 ALL_ALLOC is set, consider only functions that return dynamically
1554 allocated objects. Otherwise return true even for all forms of
1555 alloca (including VLA). */
1558 fndecl_alloc_p (tree fndecl
, bool all_alloc
)
1563 /* A call to operator new isn't recognized as one to a built-in. */
1564 if (DECL_IS_OPERATOR_NEW_P (fndecl
))
1567 if (fndecl_built_in_p (fndecl
, BUILT_IN_NORMAL
))
1569 switch (DECL_FUNCTION_CODE (fndecl
))
1571 case BUILT_IN_ALLOCA
:
1572 case BUILT_IN_ALLOCA_WITH_ALIGN
:
1574 case BUILT_IN_ALIGNED_ALLOC
:
1575 case BUILT_IN_CALLOC
:
1576 case BUILT_IN_GOMP_ALLOC
:
1577 case BUILT_IN_GOMP_REALLOC
:
1578 case BUILT_IN_MALLOC
:
1579 case BUILT_IN_REALLOC
:
1580 case BUILT_IN_STRDUP
:
1581 case BUILT_IN_STRNDUP
:
1588 /* A function is considered an allocation function if it's declared
1589 with attribute malloc with an argument naming its associated
1590 deallocation function. */
1591 tree attrs
= DECL_ATTRIBUTES (fndecl
);
1595 for (tree allocs
= attrs
;
1596 (allocs
= lookup_attribute ("malloc", allocs
));
1597 allocs
= TREE_CHAIN (allocs
))
1599 tree args
= TREE_VALUE (allocs
);
1603 if (TREE_VALUE (args
))
1610 /* Return true if STMT is a call to an allocation function. A wrapper
1611 around fndecl_alloc_p. */
1614 gimple_call_alloc_p (gimple
*stmt
, bool all_alloc
= false)
1616 return fndecl_alloc_p (gimple_call_fndecl (stmt
), all_alloc
);
1619 /* Return true if DELC doesn't refer to an operator delete that's
1620 suitable to call with a pointer returned from the operator new
1621 described by NEWC. */
1624 new_delete_mismatch_p (const demangle_component
&newc
,
1625 const demangle_component
&delc
)
1627 if (newc
.type
!= delc
.type
)
1632 case DEMANGLE_COMPONENT_NAME
:
1634 int len
= newc
.u
.s_name
.len
;
1635 const char *news
= newc
.u
.s_name
.s
;
1636 const char *dels
= delc
.u
.s_name
.s
;
1637 if (len
!= delc
.u
.s_name
.len
|| memcmp (news
, dels
, len
))
1640 if (news
[len
] == 'n')
1642 if (news
[len
+ 1] == 'a')
1643 return dels
[len
] != 'd' || dels
[len
+ 1] != 'a';
1644 if (news
[len
+ 1] == 'w')
1645 return dels
[len
] != 'd' || dels
[len
+ 1] != 'l';
1650 case DEMANGLE_COMPONENT_OPERATOR
:
1651 /* Operator mismatches are handled above. */
1654 case DEMANGLE_COMPONENT_EXTENDED_OPERATOR
:
1655 if (newc
.u
.s_extended_operator
.args
!= delc
.u
.s_extended_operator
.args
)
1657 return new_delete_mismatch_p (*newc
.u
.s_extended_operator
.name
,
1658 *delc
.u
.s_extended_operator
.name
);
1660 case DEMANGLE_COMPONENT_FIXED_TYPE
:
1661 if (newc
.u
.s_fixed
.accum
!= delc
.u
.s_fixed
.accum
1662 || newc
.u
.s_fixed
.sat
!= delc
.u
.s_fixed
.sat
)
1664 return new_delete_mismatch_p (*newc
.u
.s_fixed
.length
,
1665 *delc
.u
.s_fixed
.length
);
1667 case DEMANGLE_COMPONENT_CTOR
:
1668 if (newc
.u
.s_ctor
.kind
!= delc
.u
.s_ctor
.kind
)
1670 return new_delete_mismatch_p (*newc
.u
.s_ctor
.name
,
1671 *delc
.u
.s_ctor
.name
);
1673 case DEMANGLE_COMPONENT_DTOR
:
1674 if (newc
.u
.s_dtor
.kind
!= delc
.u
.s_dtor
.kind
)
1676 return new_delete_mismatch_p (*newc
.u
.s_dtor
.name
,
1677 *delc
.u
.s_dtor
.name
);
1679 case DEMANGLE_COMPONENT_BUILTIN_TYPE
:
1681 /* The demangler API provides no better way to compare built-in
1682 types except to by comparing their demangled names. */
1684 demangle_component
*pnc
= const_cast<demangle_component
*>(&newc
);
1685 demangle_component
*pdc
= const_cast<demangle_component
*>(&delc
);
1686 char *nts
= cplus_demangle_print (0, pnc
, 16, &nsz
);
1687 char *dts
= cplus_demangle_print (0, pdc
, 16, &dsz
);
1690 bool mismatch
= strcmp (nts
, dts
);
1696 case DEMANGLE_COMPONENT_SUB_STD
:
1697 if (newc
.u
.s_string
.len
!= delc
.u
.s_string
.len
)
1699 return memcmp (newc
.u
.s_string
.string
, delc
.u
.s_string
.string
,
1700 newc
.u
.s_string
.len
);
1702 case DEMANGLE_COMPONENT_FUNCTION_PARAM
:
1703 case DEMANGLE_COMPONENT_TEMPLATE_PARAM
:
1704 return newc
.u
.s_number
.number
!= delc
.u
.s_number
.number
;
1706 case DEMANGLE_COMPONENT_CHARACTER
:
1707 return newc
.u
.s_character
.character
!= delc
.u
.s_character
.character
;
1709 case DEMANGLE_COMPONENT_DEFAULT_ARG
:
1710 case DEMANGLE_COMPONENT_LAMBDA
:
1711 if (newc
.u
.s_unary_num
.num
!= delc
.u
.s_unary_num
.num
)
1713 return new_delete_mismatch_p (*newc
.u
.s_unary_num
.sub
,
1714 *delc
.u
.s_unary_num
.sub
);
1719 if (!newc
.u
.s_binary
.left
!= !delc
.u
.s_binary
.left
)
1722 if (!newc
.u
.s_binary
.left
)
1725 if (new_delete_mismatch_p (*newc
.u
.s_binary
.left
, *delc
.u
.s_binary
.left
)
1726 || !newc
.u
.s_binary
.right
!= !delc
.u
.s_binary
.right
)
1729 if (newc
.u
.s_binary
.right
)
1730 return new_delete_mismatch_p (*newc
.u
.s_binary
.right
,
1731 *delc
.u
.s_binary
.right
);
1735 /* Return true if DELETE_DECL is an operator delete that's not suitable
1736 to call with a pointer returned from NEW_DECL. */
1739 new_delete_mismatch_p (tree new_decl
, tree delete_decl
)
1741 tree new_name
= DECL_ASSEMBLER_NAME (new_decl
);
1742 tree delete_name
= DECL_ASSEMBLER_NAME (delete_decl
);
1744 /* valid_new_delete_pair_p() returns a conservative result (currently
1745 it only handles global operators). A true result is reliable but
1746 a false result doesn't necessarily mean the operators don't match
1747 unless CERTAIN is set. */
1749 if (valid_new_delete_pair_p (new_name
, delete_name
, &certain
))
1751 /* CERTAIN is set when the negative result is certain. */
1755 /* For anything not handled by valid_new_delete_pair_p() such as member
1756 operators compare the individual demangled components of the mangled
1758 const char *new_str
= IDENTIFIER_POINTER (new_name
);
1759 const char *del_str
= IDENTIFIER_POINTER (delete_name
);
1761 void *np
= NULL
, *dp
= NULL
;
1762 demangle_component
*ndc
= cplus_demangle_v3_components (new_str
, 0, &np
);
1763 demangle_component
*ddc
= cplus_demangle_v3_components (del_str
, 0, &dp
);
1764 bool mismatch
= new_delete_mismatch_p (*ndc
, *ddc
);
1770 /* ALLOC_DECL and DEALLOC_DECL are pair of allocation and deallocation
1771 functions. Return true if the latter is suitable to deallocate objects
1772 allocated by calls to the former. */
1775 matching_alloc_calls_p (tree alloc_decl
, tree dealloc_decl
)
1777 /* Set to alloc_kind_t::builtin if ALLOC_DECL is associated with
1778 a built-in deallocator. */
1779 enum class alloc_kind_t
{ none
, builtin
, user
}
1780 alloc_dealloc_kind
= alloc_kind_t::none
;
1782 if (DECL_IS_OPERATOR_NEW_P (alloc_decl
))
1784 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl
))
1785 /* Return true iff both functions are of the same array or
1786 singleton form and false otherwise. */
1787 return !new_delete_mismatch_p (alloc_decl
, dealloc_decl
);
1789 /* Return false for deallocation functions that are known not
1791 if (fndecl_built_in_p (dealloc_decl
, BUILT_IN_FREE
, BUILT_IN_REALLOC
))
1793 /* Otherwise proceed below to check the deallocation function's
1794 "*dealloc" attributes to look for one that mentions this operator
1797 else if (fndecl_built_in_p (alloc_decl
, BUILT_IN_NORMAL
))
1799 switch (DECL_FUNCTION_CODE (alloc_decl
))
1801 case BUILT_IN_ALLOCA
:
1802 case BUILT_IN_ALLOCA_WITH_ALIGN
:
1805 case BUILT_IN_GOMP_ALLOC
:
1806 case BUILT_IN_GOMP_REALLOC
:
1807 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl
))
1810 if (fndecl_built_in_p (dealloc_decl
, BUILT_IN_GOMP_FREE
,
1811 BUILT_IN_GOMP_REALLOC
))
1814 alloc_dealloc_kind
= alloc_kind_t::builtin
;
1817 case BUILT_IN_ALIGNED_ALLOC
:
1818 case BUILT_IN_CALLOC
:
1819 case BUILT_IN_MALLOC
:
1820 case BUILT_IN_REALLOC
:
1821 case BUILT_IN_STRDUP
:
1822 case BUILT_IN_STRNDUP
:
1823 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl
))
1826 if (fndecl_built_in_p (dealloc_decl
, BUILT_IN_FREE
,
1830 alloc_dealloc_kind
= alloc_kind_t::builtin
;
1838 /* Set if DEALLOC_DECL both allocates and deallocates. */
1839 alloc_kind_t realloc_kind
= alloc_kind_t::none
;
1841 if (fndecl_built_in_p (dealloc_decl
, BUILT_IN_NORMAL
))
1843 built_in_function dealloc_code
= DECL_FUNCTION_CODE (dealloc_decl
);
1844 if (dealloc_code
== BUILT_IN_REALLOC
1845 || dealloc_code
== BUILT_IN_GOMP_REALLOC
)
1846 realloc_kind
= alloc_kind_t::builtin
;
1848 for (tree amats
= DECL_ATTRIBUTES (alloc_decl
);
1849 (amats
= lookup_attribute ("malloc", amats
));
1850 amats
= TREE_CHAIN (amats
))
1852 tree args
= TREE_VALUE (amats
);
1856 tree fndecl
= TREE_VALUE (args
);
1857 if (!fndecl
|| !DECL_P (fndecl
))
1860 if (fndecl_built_in_p (fndecl
, BUILT_IN_NORMAL
)
1861 && dealloc_code
== DECL_FUNCTION_CODE (fndecl
))
1866 const bool alloc_builtin
= fndecl_built_in_p (alloc_decl
, BUILT_IN_NORMAL
);
1867 alloc_kind_t realloc_dealloc_kind
= alloc_kind_t::none
;
1869 /* If DEALLOC_DECL has an internal "*dealloc" attribute scan the list
1870 of its associated allocation functions for ALLOC_DECL.
1871 If the corresponding ALLOC_DECL is found they're a matching pair,
1872 otherwise they're not.
1873 With DDATS set to the Deallocator's *Dealloc ATtributes... */
1874 for (tree ddats
= DECL_ATTRIBUTES (dealloc_decl
);
1875 (ddats
= lookup_attribute ("*dealloc", ddats
));
1876 ddats
= TREE_CHAIN (ddats
))
1878 tree args
= TREE_VALUE (ddats
);
1882 tree alloc
= TREE_VALUE (args
);
1886 if (alloc
== DECL_NAME (dealloc_decl
))
1887 realloc_kind
= alloc_kind_t::user
;
1891 gcc_checking_assert (fndecl_built_in_p (alloc
, BUILT_IN_NORMAL
));
1893 switch (DECL_FUNCTION_CODE (alloc
))
1895 case BUILT_IN_ALIGNED_ALLOC
:
1896 case BUILT_IN_CALLOC
:
1897 case BUILT_IN_GOMP_ALLOC
:
1898 case BUILT_IN_GOMP_REALLOC
:
1899 case BUILT_IN_MALLOC
:
1900 case BUILT_IN_REALLOC
:
1901 case BUILT_IN_STRDUP
:
1902 case BUILT_IN_STRNDUP
:
1903 realloc_dealloc_kind
= alloc_kind_t::builtin
;
1912 if (DECL_FUNCTION_CODE (alloc
) != DECL_FUNCTION_CODE (alloc_decl
))
1918 if (alloc
== DECL_NAME (alloc_decl
))
1922 if (realloc_kind
== alloc_kind_t::none
)
1925 hash_set
<tree
> common_deallocs
;
1926 /* Special handling for deallocators. Iterate over both the allocator's
1927 and the reallocator's associated deallocator functions looking for
1928 the first one in common. If one is found, the de/reallocator is
1929 a match for the allocator even though the latter isn't directly
1930 associated with the former. This simplifies declarations in system
1932 With AMATS set to the Allocator's Malloc ATtributes,
1933 and RMATS set to Reallocator's Malloc ATtributes... */
1934 for (tree amats
= DECL_ATTRIBUTES (alloc_decl
),
1935 rmats
= DECL_ATTRIBUTES (dealloc_decl
);
1936 (amats
= lookup_attribute ("malloc", amats
))
1937 || (rmats
= lookup_attribute ("malloc", rmats
));
1938 amats
= amats
? TREE_CHAIN (amats
) : NULL_TREE
,
1939 rmats
= rmats
? TREE_CHAIN (rmats
) : NULL_TREE
)
1941 if (tree args
= amats
? TREE_VALUE (amats
) : NULL_TREE
)
1942 if (tree adealloc
= TREE_VALUE (args
))
1944 if (DECL_P (adealloc
)
1945 && fndecl_built_in_p (adealloc
, BUILT_IN_NORMAL
))
1947 built_in_function fncode
= DECL_FUNCTION_CODE (adealloc
);
1948 if (fncode
== BUILT_IN_FREE
|| fncode
== BUILT_IN_REALLOC
)
1950 if (realloc_kind
== alloc_kind_t::builtin
)
1952 alloc_dealloc_kind
= alloc_kind_t::builtin
;
1957 common_deallocs
.add (adealloc
);
1960 if (tree args
= rmats
? TREE_VALUE (rmats
) : NULL_TREE
)
1961 if (tree ddealloc
= TREE_VALUE (args
))
1963 if (DECL_P (ddealloc
)
1964 && fndecl_built_in_p (ddealloc
, BUILT_IN_NORMAL
))
1966 built_in_function fncode
= DECL_FUNCTION_CODE (ddealloc
);
1967 if (fncode
== BUILT_IN_FREE
|| fncode
== BUILT_IN_REALLOC
)
1969 if (alloc_dealloc_kind
== alloc_kind_t::builtin
)
1971 realloc_dealloc_kind
= alloc_kind_t::builtin
;
1976 if (common_deallocs
.add (ddealloc
))
1981 /* Succeed only if ALLOC_DECL and the reallocator DEALLOC_DECL share
1982 a built-in deallocator. */
1983 return (alloc_dealloc_kind
== alloc_kind_t::builtin
1984 && realloc_dealloc_kind
== alloc_kind_t::builtin
);
1987 /* Return true if DEALLOC_DECL is a function suitable to deallocate
1988 objects allocated by the ALLOC call. */
1991 matching_alloc_calls_p (gimple
*alloc
, tree dealloc_decl
)
1993 tree alloc_decl
= gimple_call_fndecl (alloc
);
1997 return matching_alloc_calls_p (alloc_decl
, dealloc_decl
);
2000 /* Diagnose a call EXP to deallocate a pointer referenced by AREF if it
2001 includes a nonzero offset. Such a pointer cannot refer to the beginning
2002 of an allocated object. A negative offset may refer to it only if
2003 the target pointer is unknown. */
2006 warn_dealloc_offset (location_t loc
, gimple
*call
, const access_ref
&aref
)
2008 if (aref
.deref
|| aref
.offrng
[0] <= 0 || aref
.offrng
[1] <= 0)
2011 tree dealloc_decl
= gimple_call_fndecl (call
);
2015 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl
)
2016 && !DECL_IS_REPLACEABLE_OPERATOR (dealloc_decl
))
2018 /* A call to a user-defined operator delete with a pointer plus offset
2019 may be valid if it's returned from an unknown function (i.e., one
2020 that's not operator new). */
2021 if (TREE_CODE (aref
.ref
) == SSA_NAME
)
2023 gimple
*def_stmt
= SSA_NAME_DEF_STMT (aref
.ref
);
2024 if (is_gimple_call (def_stmt
))
2026 tree alloc_decl
= gimple_call_fndecl (def_stmt
);
2027 if (!alloc_decl
|| !DECL_IS_OPERATOR_NEW_P (alloc_decl
))
2035 if (wi::fits_shwi_p (aref
.offrng
[0]))
2037 if (aref
.offrng
[0] == aref
.offrng
[1]
2038 || !wi::fits_shwi_p (aref
.offrng
[1]))
2039 sprintf (offstr
, " %lli",
2040 (long long)aref
.offrng
[0].to_shwi ());
2042 sprintf (offstr
, " [%lli, %lli]",
2043 (long long)aref
.offrng
[0].to_shwi (),
2044 (long long)aref
.offrng
[1].to_shwi ());
2047 auto_diagnostic_group d
;
2048 if (!warning_at (loc
, OPT_Wfree_nonheap_object
,
2049 "%qD called on pointer %qE with nonzero offset%s",
2050 dealloc_decl
, aref
.ref
, offstr
))
2053 if (DECL_P (aref
.ref
))
2054 inform (get_location (aref
.ref
), "declared here");
2055 else if (TREE_CODE (aref
.ref
) == SSA_NAME
)
2057 gimple
*def_stmt
= SSA_NAME_DEF_STMT (aref
.ref
);
2058 if (is_gimple_call (def_stmt
))
2060 location_t def_loc
= get_location (def_stmt
);
2061 tree alloc_decl
= gimple_call_fndecl (def_stmt
);
2064 "returned from %qD", alloc_decl
);
2065 else if (tree alloc_fntype
= gimple_call_fntype (def_stmt
))
2067 "returned from %qT", alloc_fntype
);
2069 inform (def_loc
, "obtained here");
2078 const pass_data pass_data_waccess
= {
2082 TV_WARN_ACCESS
, /* timer variable */
2083 PROP_cfg
, /* properties_required */
2084 0, /* properties_provided */
2085 0, /* properties_destroyed */
2086 0, /* properties_start */
2087 0, /* properties_finish */
2090 /* Pass to detect invalid accesses. */
2091 class pass_waccess
: public gimple_opt_pass
2094 pass_waccess (gcc::context
*);
2098 opt_pass
*clone () final override
;
2100 bool gate (function
*) final override
;
2102 void set_pass_param (unsigned, bool) final override
;
2104 unsigned int execute (function
*) final override
;
2107 /* Not copyable or assignable. */
2108 pass_waccess (pass_waccess
&) = delete;
2109 void operator= (pass_waccess
&) = delete;
2111 /* Check a call to an atomic built-in function. */
2112 bool check_atomic_builtin (gcall
*);
2114 /* Check a call to a built-in function. */
2115 bool check_builtin (gcall
*);
2117 /* Check a call to an ordinary function for invalid accesses. */
2118 bool check_call_access (gcall
*);
2120 /* Check a non-call statement. */
2121 void check_stmt (gimple
*);
2123 /* Check statements in a basic block. */
2124 void check_block (basic_block
);
2126 /* Check a call to a function. */
2127 void check_call (gcall
*);
2129 /* Check a call to the named built-in function. */
2130 void check_alloca (gcall
*);
2131 void check_alloc_size_call (gcall
*);
2132 void check_strcat (gcall
*);
2133 void check_strncat (gcall
*);
2134 void check_stxcpy (gcall
*);
2135 void check_stxncpy (gcall
*);
2136 void check_strncmp (gcall
*);
2137 void check_memop_access (gimple
*, tree
, tree
, tree
);
2138 void check_read_access (gimple
*, tree
, tree
= NULL_TREE
, int = 1);
2140 void maybe_check_dealloc_call (gcall
*);
2141 void maybe_check_access_sizes (rdwr_map
*, tree
, tree
, gimple
*);
2142 bool maybe_warn_memmodel (gimple
*, tree
, tree
, const unsigned char *);
2143 void check_atomic_memmodel (gimple
*, tree
, tree
, const unsigned char *);
2145 /* Check for uses of indeterminate pointers. */
2146 void check_pointer_uses (gimple
*, tree
, tree
= NULL_TREE
, bool = false);
2148 /* Return the argument that a call returns. */
2149 tree
gimple_call_return_arg (gcall
*);
2151 /* Check a call for uses of a dangling pointer arguments. */
2152 void check_call_dangling (gcall
*);
2154 /* Check uses of a dangling pointer or those derived from it. */
2155 void check_dangling_uses (tree
, tree
, bool = false, bool = false);
2156 void check_dangling_uses ();
2157 void check_dangling_stores ();
2158 bool check_dangling_stores (basic_block
, hash_set
<tree
> &);
2160 void warn_invalid_pointer (tree
, gimple
*, gimple
*, tree
, bool, bool = false);
2162 /* Return true if use follows an invalidating statement. */
2163 bool use_after_inval_p (gimple
*, gimple
*, bool = false);
2165 /* A pointer_query object to store information about pointers and
2166 their targets in. */
2167 pointer_query m_ptr_qry
;
2168 /* Mapping from DECLs and their clobber statements in the function. */
2169 hash_map
<tree
, gimple
*> m_clobbers
;
2170 /* A bit is set for each basic block whose statements have been assigned
2172 bitmap m_bb_uids_set
;
2173 /* The current function. */
2175 /* True to run checks for uses of dangling pointers. */
2176 bool m_check_dangling_p
;
2177 /* True to run checks early on in the optimization pipeline. */
2178 bool m_early_checks_p
;
2181 /* Construct the pass. */
2183 pass_waccess::pass_waccess (gcc::context
*ctxt
)
2184 : gimple_opt_pass (pass_data_waccess
, ctxt
),
2189 m_check_dangling_p (),
2194 /* Return a copy of the pass with RUN_NUMBER one greater than THIS. */
2197 pass_waccess::clone ()
2199 return new pass_waccess (m_ctxt
);
2202 /* Release pointer_query cache. */
2204 pass_waccess::~pass_waccess ()
2206 m_ptr_qry
.flush_cache ();
2210 pass_waccess::set_pass_param (unsigned int n
, bool early
)
2212 gcc_assert (n
== 0);
2214 m_early_checks_p
= early
;
2217 /* Return true when any checks performed by the pass are enabled. */
2220 pass_waccess::gate (function
*)
2222 return (warn_free_nonheap_object
2223 || warn_mismatched_alloc
2224 || warn_mismatched_new_delete
);
2227 /* Initialize ALLOC_OBJECT_SIZE_LIMIT based on the -Walloc-size-larger-than=
2228 setting if the option is specified, or to the maximum object size if it
2229 is not. Return the initialized value. */
2232 alloc_max_size (void)
2234 HOST_WIDE_INT limit
= warn_alloc_size_limit
;
2235 if (limit
== HOST_WIDE_INT_MAX
)
2236 limit
= tree_to_shwi (TYPE_MAX_VALUE (ptrdiff_type_node
));
2238 return build_int_cst (size_type_node
, limit
);
2241 /* Diagnose a call EXP to function FN decorated with attribute alloc_size
2242 whose argument numbers given by IDX with values given by ARGS exceed
2243 the maximum object size or cause an unsigned overflow (wrapping) when
2244 multiplied. FN is null when EXP is a call via a function pointer.
2245 When ARGS[0] is null the function does nothing. ARGS[1] may be null
2246 for functions like malloc, and non-null for those like calloc that
2247 are decorated with a two-argument attribute alloc_size. */
2250 maybe_warn_alloc_args_overflow (gimple
*stmt
, const tree args
[2],
2253 /* The range each of the (up to) two arguments is known to be in. */
2254 tree argrange
[2][2] = { { NULL_TREE
, NULL_TREE
}, { NULL_TREE
, NULL_TREE
} };
2256 /* Maximum object size set by -Walloc-size-larger-than= or SIZE_MAX / 2. */
2257 tree maxobjsize
= alloc_max_size ();
2259 location_t loc
= get_location (stmt
);
2261 tree fn
= gimple_call_fndecl (stmt
);
2262 tree fntype
= fn
? TREE_TYPE (fn
) : gimple_call_fntype (stmt
);
2263 bool warned
= false;
2265 /* Validate each argument individually. */
2266 for (unsigned i
= 0; i
!= 2 && args
[i
]; ++i
)
2268 if (TREE_CODE (args
[i
]) == INTEGER_CST
)
2270 argrange
[i
][0] = args
[i
];
2271 argrange
[i
][1] = args
[i
];
2273 if (tree_int_cst_lt (args
[i
], integer_zero_node
))
2275 warned
= warning_at (loc
, OPT_Walloc_size_larger_than_
,
2276 "argument %i value %qE is negative",
2277 idx
[i
] + 1, args
[i
]);
2279 else if (integer_zerop (args
[i
]))
2281 /* Avoid issuing -Walloc-zero for allocation functions other
2282 than __builtin_alloca that are declared with attribute
2283 returns_nonnull because there's no portability risk. This
2284 avoids warning for such calls to libiberty's xmalloc and
2286 Also avoid issuing the warning for calls to function named
2288 if (fn
&& fndecl_built_in_p (fn
, BUILT_IN_ALLOCA
)
2289 ? IDENTIFIER_LENGTH (DECL_NAME (fn
)) != 6
2290 : !lookup_attribute ("returns_nonnull",
2291 TYPE_ATTRIBUTES (fntype
)))
2292 warned
= warning_at (loc
, OPT_Walloc_zero
,
2293 "argument %i value is zero",
2296 else if (tree_int_cst_lt (maxobjsize
, args
[i
]))
2298 /* G++ emits calls to ::operator new[](SIZE_MAX) in C++98
2299 mode and with -fno-exceptions as a way to indicate array
2300 size overflow. There's no good way to detect C++98 here
2301 so avoid diagnosing these calls for all C++ modes. */
2306 && DECL_IS_OPERATOR_NEW_P (fn
)
2307 && integer_all_onesp (args
[i
]))
2310 warned
= warning_at (loc
, OPT_Walloc_size_larger_than_
,
2311 "argument %i value %qE exceeds "
2312 "maximum object size %E",
2313 idx
[i
] + 1, args
[i
], maxobjsize
);
2316 else if (TREE_CODE (args
[i
]) == SSA_NAME
2317 && get_size_range (args
[i
], argrange
[i
]))
2319 /* Verify that the argument's range is not negative (including
2320 upper bound of zero). */
2321 if (tree_int_cst_lt (argrange
[i
][0], integer_zero_node
)
2322 && tree_int_cst_le (argrange
[i
][1], integer_zero_node
))
2324 warned
= warning_at (loc
, OPT_Walloc_size_larger_than_
,
2325 "argument %i range [%E, %E] is negative",
2327 argrange
[i
][0], argrange
[i
][1]);
2329 else if (tree_int_cst_lt (maxobjsize
, argrange
[i
][0]))
2331 warned
= warning_at (loc
, OPT_Walloc_size_larger_than_
,
2332 "argument %i range [%E, %E] exceeds "
2333 "maximum object size %E",
2335 argrange
[i
][0], argrange
[i
][1],
2341 if (!argrange
[0][0])
2344 /* For a two-argument alloc_size, validate the product of the two
2345 arguments if both of their values or ranges are known. */
2346 if (!warned
&& tree_fits_uhwi_p (argrange
[0][0])
2347 && argrange
[1][0] && tree_fits_uhwi_p (argrange
[1][0])
2348 && !integer_onep (argrange
[0][0])
2349 && !integer_onep (argrange
[1][0]))
2351 /* Check for overflow in the product of a function decorated with
2352 attribute alloc_size (X, Y). */
2353 unsigned szprec
= TYPE_PRECISION (size_type_node
);
2354 wide_int x
= wi::to_wide (argrange
[0][0], szprec
);
2355 wide_int y
= wi::to_wide (argrange
[1][0], szprec
);
2357 wi::overflow_type vflow
;
2358 wide_int prod
= wi::umul (x
, y
, &vflow
);
2361 warned
= warning_at (loc
, OPT_Walloc_size_larger_than_
,
2362 "product %<%E * %E%> of arguments %i and %i "
2363 "exceeds %<SIZE_MAX%>",
2364 argrange
[0][0], argrange
[1][0],
2365 idx
[0] + 1, idx
[1] + 1);
2366 else if (wi::ltu_p (wi::to_wide (maxobjsize
, szprec
), prod
))
2367 warned
= warning_at (loc
, OPT_Walloc_size_larger_than_
,
2368 "product %<%E * %E%> of arguments %i and %i "
2369 "exceeds maximum object size %E",
2370 argrange
[0][0], argrange
[1][0],
2371 idx
[0] + 1, idx
[1] + 1,
2376 /* Print the full range of each of the two arguments to make
2377 it clear when it is, in fact, in a range and not constant. */
2378 if (argrange
[0][0] != argrange
[0][1])
2379 inform (loc
, "argument %i in the range [%E, %E]",
2380 idx
[0] + 1, argrange
[0][0], argrange
[0][1]);
2381 if (argrange
[1][0] != argrange
[1][1])
2382 inform (loc
, "argument %i in the range [%E, %E]",
2383 idx
[1] + 1, argrange
[1][0], argrange
[1][1]);
2389 location_t fnloc
= DECL_SOURCE_LOCATION (fn
);
2391 if (DECL_IS_UNDECLARED_BUILTIN (fn
))
2393 "in a call to built-in allocation function %qD", fn
);
2396 "in a call to allocation function %qD declared here", fn
);
2400 /* Check a call to an alloca function for an excessive size. */
2403 pass_waccess::check_alloca (gcall
*stmt
)
2405 if (m_early_checks_p
)
2408 if ((warn_vla_limit
>= HOST_WIDE_INT_MAX
2409 && warn_alloc_size_limit
< warn_vla_limit
)
2410 || (warn_alloca_limit
>= HOST_WIDE_INT_MAX
2411 && warn_alloc_size_limit
< warn_alloca_limit
))
2413 /* -Walloca-larger-than and -Wvla-larger-than settings of less
2414 than HWI_MAX override the more general -Walloc-size-larger-than
2415 so unless either of the former options is smaller than the last
2416 one (which would imply that the call was already checked), check
2417 the alloca arguments for overflow. */
2418 const tree alloc_args
[] = { call_arg (stmt
, 0), NULL_TREE
};
2419 const int idx
[] = { 0, -1 };
2420 maybe_warn_alloc_args_overflow (stmt
, alloc_args
, idx
);
2424 /* Check a call to an allocation function for an excessive size. */
2427 pass_waccess::check_alloc_size_call (gcall
*stmt
)
2429 if (m_early_checks_p
)
2432 if (gimple_call_num_args (stmt
) < 1)
2433 /* Avoid invalid calls to functions without a prototype. */
2436 tree fndecl
= gimple_call_fndecl (stmt
);
2437 if (fndecl
&& gimple_call_builtin_p (stmt
, BUILT_IN_NORMAL
))
2439 /* Alloca is handled separately. */
2440 switch (DECL_FUNCTION_CODE (fndecl
))
2442 case BUILT_IN_ALLOCA
:
2443 case BUILT_IN_ALLOCA_WITH_ALIGN
:
2444 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX
:
2451 tree fntype
= gimple_call_fntype (stmt
);
2452 tree fntypeattrs
= TYPE_ATTRIBUTES (fntype
);
2454 tree alloc_size
= lookup_attribute ("alloc_size", fntypeattrs
);
2458 /* Extract attribute alloc_size from the type of the called expression
2459 (which could be a function or a function pointer) and if set, store
2460 the indices of the corresponding arguments in ALLOC_IDX, and then
2461 the actual argument(s) at those indices in ALLOC_ARGS. */
2462 int idx
[2] = { -1, -1 };
2463 tree alloc_args
[] = { NULL_TREE
, NULL_TREE
};
2464 unsigned nargs
= gimple_call_num_args (stmt
);
2466 tree args
= TREE_VALUE (alloc_size
);
2467 idx
[0] = TREE_INT_CST_LOW (TREE_VALUE (args
)) - 1;
2468 /* Avoid invalid calls to functions without a prototype. */
2469 if ((unsigned) idx
[0] >= nargs
)
2471 alloc_args
[0] = call_arg (stmt
, idx
[0]);
2472 if (TREE_CHAIN (args
))
2474 idx
[1] = TREE_INT_CST_LOW (TREE_VALUE (TREE_CHAIN (args
))) - 1;
2475 if ((unsigned) idx
[1] >= nargs
)
2477 alloc_args
[1] = call_arg (stmt
, idx
[1]);
2480 maybe_warn_alloc_args_overflow (stmt
, alloc_args
, idx
);
2483 /* Check a call STMT to strcat() for overflow and warn if it does. */
2486 pass_waccess::check_strcat (gcall
*stmt
)
2488 if (m_early_checks_p
)
2491 if (!warn_stringop_overflow
&& !warn_stringop_overread
)
2494 tree dest
= call_arg (stmt
, 0);
2495 tree src
= call_arg (stmt
, 1);
2497 /* There is no way here to determine the length of the string in
2498 the destination to which the SRC string is being appended so
2499 just diagnose cases when the source string is longer than
2500 the destination object. */
2501 access_data
data (m_ptr_qry
.rvals
, stmt
, access_read_write
, NULL_TREE
,
2502 true, NULL_TREE
, true);
2503 const int ost
= warn_stringop_overflow
? warn_stringop_overflow
- 1 : 1;
2504 compute_objsize (src
, stmt
, ost
, &data
.src
, &m_ptr_qry
);
2505 tree destsize
= compute_objsize (dest
, stmt
, ost
, &data
.dst
, &m_ptr_qry
);
2507 check_access (stmt
, /*dstwrite=*/NULL_TREE
, /*maxread=*/NULL_TREE
,
2508 src
, destsize
, data
.mode
, &data
, m_ptr_qry
.rvals
);
2511 /* Check a call STMT to strcat() for overflow and warn if it does. */
2514 pass_waccess::check_strncat (gcall
*stmt
)
2516 if (m_early_checks_p
)
2519 if (!warn_stringop_overflow
&& !warn_stringop_overread
)
2522 tree dest
= call_arg (stmt
, 0);
2523 tree src
= call_arg (stmt
, 1);
2524 /* The upper bound on the number of bytes to write. */
2525 tree maxread
= call_arg (stmt
, 2);
2527 /* Detect unterminated source (only). */
2528 if (!check_nul_terminated_array (stmt
, src
, maxread
))
2531 /* The length of the source sequence. */
2532 tree slen
= c_strlen (src
, 1);
2534 /* Try to determine the range of lengths that the source expression
2535 refers to. Since the lengths are only used for warning and not
2536 for code generation disable strict mode below. */
2540 c_strlen_data lendata
= { };
2541 get_range_strlen (src
, &lendata
, /* eltsize = */ 1);
2542 maxlen
= lendata
.maxbound
;
2545 access_data
data (m_ptr_qry
.rvals
, stmt
, access_read_write
);
2546 /* Try to verify that the destination is big enough for the shortest
2547 string. First try to determine the size of the destination object
2548 into which the source is being copied. */
2549 const int ost
= warn_stringop_overflow
- 1;
2550 tree destsize
= compute_objsize (dest
, stmt
, ost
, &data
.dst
, &m_ptr_qry
);
2552 /* Add one for the terminating nul. */
2553 tree srclen
= (maxlen
2554 ? fold_build2 (PLUS_EXPR
, size_type_node
, maxlen
,
2558 /* The strncat function copies at most MAXREAD bytes and always appends
2559 the terminating nul so the specified upper bound should never be equal
2560 to (or greater than) the size of the destination. */
2561 if (tree_fits_uhwi_p (maxread
) && tree_fits_uhwi_p (destsize
)
2562 && tree_int_cst_equal (destsize
, maxread
))
2564 location_t loc
= get_location (stmt
);
2565 warning_at (loc
, OPT_Wstringop_overflow_
,
2566 "%qD specified bound %E equals destination size",
2567 get_callee_fndecl (stmt
), maxread
);
2573 || (maxread
&& tree_fits_uhwi_p (maxread
)
2574 && tree_fits_uhwi_p (srclen
)
2575 && tree_int_cst_lt (maxread
, srclen
)))
2578 check_access (stmt
, /*dstwrite=*/NULL_TREE
, maxread
, srclen
,
2579 destsize
, data
.mode
, &data
, m_ptr_qry
.rvals
);
2582 /* Check a call STMT to stpcpy() or strcpy() for overflow and warn
2586 pass_waccess::check_stxcpy (gcall
*stmt
)
2588 if (m_early_checks_p
)
2591 tree dst
= call_arg (stmt
, 0);
2592 tree src
= call_arg (stmt
, 1);
2596 if (tree nonstr
= unterminated_array (src
, &size
, &exact
))
2598 /* NONSTR refers to the non-nul terminated constant array. */
2599 warn_string_no_nul (get_location (stmt
), stmt
, NULL
, src
, nonstr
,
2604 if (warn_stringop_overflow
)
2606 access_data
data (m_ptr_qry
.rvals
, stmt
, access_read_write
, NULL_TREE
,
2607 true, NULL_TREE
, true);
2608 const int ost
= warn_stringop_overflow
? warn_stringop_overflow
- 1 : 1;
2609 compute_objsize (src
, stmt
, ost
, &data
.src
, &m_ptr_qry
);
2610 tree dstsize
= compute_objsize (dst
, stmt
, ost
, &data
.dst
, &m_ptr_qry
);
2611 check_access (stmt
, /*dstwrite=*/ NULL_TREE
,
2612 /*maxread=*/ NULL_TREE
, /*srcstr=*/ src
,
2613 dstsize
, data
.mode
, &data
, m_ptr_qry
.rvals
);
2616 /* Check to see if the argument was declared attribute nonstring
2617 and if so, issue a warning since at this point it's not known
2618 to be nul-terminated. */
2619 tree fndecl
= get_callee_fndecl (stmt
);
2620 maybe_warn_nonstring_arg (fndecl
, stmt
);
2623 /* Check a call STMT to stpncpy() or strncpy() for overflow and warn
2627 pass_waccess::check_stxncpy (gcall
*stmt
)
2629 if (m_early_checks_p
|| !warn_stringop_overflow
)
2632 tree dst
= call_arg (stmt
, 0);
2633 tree src
= call_arg (stmt
, 1);
2634 /* The number of bytes to write (not the maximum). */
2635 tree len
= call_arg (stmt
, 2);
2637 access_data
data (m_ptr_qry
.rvals
, stmt
, access_read_write
, len
, true, len
,
2639 const int ost
= warn_stringop_overflow
? warn_stringop_overflow
- 1 : 1;
2640 compute_objsize (src
, stmt
, ost
, &data
.src
, &m_ptr_qry
);
2641 tree dstsize
= compute_objsize (dst
, stmt
, ost
, &data
.dst
, &m_ptr_qry
);
2643 check_access (stmt
, /*dstwrite=*/len
, /*maxread=*/len
, src
, dstsize
,
2644 data
.mode
, &data
, m_ptr_qry
.rvals
);
2647 /* Check a call STMT to stpncpy() or strncpy() for overflow and warn
2651 pass_waccess::check_strncmp (gcall
*stmt
)
2653 if (m_early_checks_p
|| !warn_stringop_overread
)
2656 tree arg1
= call_arg (stmt
, 0);
2657 tree arg2
= call_arg (stmt
, 1);
2658 tree bound
= call_arg (stmt
, 2);
2660 /* First check each argument separately, considering the bound. */
2661 if (!check_nul_terminated_array (stmt
, arg1
, bound
)
2662 || !check_nul_terminated_array (stmt
, arg2
, bound
))
2665 /* A strncmp read from each argument is constrained not just by
2666 the bound but also by the length of the shorter string. Specifying
2667 a bound that's larger than the size of either array makes no sense
2668 and is likely a bug. When the length of neither of the two strings
2669 is known but the sizes of both of the arrays they are stored in is,
2670 issue a warning if the bound is larger than the size of
2671 the larger of the two arrays. */
2673 c_strlen_data lendata1
{ }, lendata2
{ };
2674 tree len1
= c_strlen (arg1
, 1, &lendata1
);
2675 tree len2
= c_strlen (arg2
, 1, &lendata2
);
2677 if (len1
&& TREE_CODE (len1
) != INTEGER_CST
)
2679 if (len2
&& TREE_CODE (len2
) != INTEGER_CST
)
2683 /* If the length of both arguments was computed they must both be
2684 nul-terminated and no further checking is necessary regardless
2688 /* Check to see if the argument was declared with attribute nonstring
2689 and if so, issue a warning since at this point it's not known to be
2691 if (maybe_warn_nonstring_arg (get_callee_fndecl (stmt
), stmt
))
2694 access_data
adata1 (m_ptr_qry
.rvals
, stmt
, access_read_only
, NULL_TREE
, false,
2696 access_data
adata2 (m_ptr_qry
.rvals
, stmt
, access_read_only
, NULL_TREE
, false,
2699 /* Determine the range of the bound first and bail if it fails; it's
2700 cheaper than computing the size of the objects. */
2701 tree bndrng
[2] = { NULL_TREE
, NULL_TREE
};
2702 get_size_range (m_ptr_qry
.rvals
, bound
, stmt
, bndrng
, 0, adata1
.src_bndrng
);
2703 if (!bndrng
[0] || integer_zerop (bndrng
[0]))
2706 if (len1
&& tree_int_cst_lt (len1
, bndrng
[0]))
2708 if (len2
&& tree_int_cst_lt (len2
, bndrng
[0]))
2711 /* compute_objsize almost never fails (and ultimately should never
2712 fail). Don't bother to handle the rare case when it does. */
2713 if (!compute_objsize (arg1
, stmt
, 1, &adata1
.src
, &m_ptr_qry
)
2714 || !compute_objsize (arg2
, stmt
, 1, &adata2
.src
, &m_ptr_qry
))
2717 /* Compute the size of the remaining space in each array after
2718 subtracting any offset into it. */
2719 offset_int rem1
= adata1
.src
.size_remaining ();
2720 offset_int rem2
= adata2
.src
.size_remaining ();
2722 /* Cap REM1 and REM2 at the other if the other's argument is known
2723 to be an unterminated array, either because there's no space
2724 left in it after adding its offset or because it's constant and
2726 if (rem1
== 0 || (rem1
< rem2
&& lendata1
.decl
))
2728 else if (rem2
== 0 || (rem2
< rem1
&& lendata2
.decl
))
2731 /* Point PAD at the array to reference in the note if a warning
2733 access_data
*pad
= len1
? &adata2
: &adata1
;
2734 offset_int maxrem
= wi::max (rem1
, rem2
, UNSIGNED
);
2735 if (lendata1
.decl
|| lendata2
.decl
2736 || maxrem
< wi::to_offset (bndrng
[0]))
2738 /* Warn when either argument isn't nul-terminated or the maximum
2739 remaining space in the two arrays is less than the bound. */
2740 tree func
= get_callee_fndecl (stmt
);
2741 location_t loc
= gimple_location (stmt
);
2742 maybe_warn_for_bound (OPT_Wstringop_overread
, loc
, stmt
, func
,
2743 bndrng
, wide_int_to_tree (sizetype
, maxrem
),
2748 /* Determine and check the sizes of the source and the destination
2749 of calls to __builtin_{bzero,memcpy,mempcpy,memset} calls. STMT is
2750 the call statement, DEST is the destination argument, SRC is the source
2751 argument or null, and SIZE is the number of bytes being accessed. Use
2752 Object Size type-0 regardless of the OPT_Wstringop_overflow_ setting.
2753 Return true on success (no overflow or invalid sizes), false otherwise. */
2756 pass_waccess::check_memop_access (gimple
*stmt
, tree dest
, tree src
, tree size
)
2758 if (m_early_checks_p
)
2761 /* For functions like memset and memcpy that operate on raw memory
2762 try to determine the size of the largest source and destination
2763 object using type-0 Object Size regardless of the object size
2764 type specified by the option. */
2765 access_data
data (m_ptr_qry
.rvals
, stmt
, access_read_write
);
2767 = src
? compute_objsize (src
, stmt
, 0, &data
.src
, &m_ptr_qry
) : NULL_TREE
;
2768 tree dstsize
= compute_objsize (dest
, stmt
, 0, &data
.dst
, &m_ptr_qry
);
2770 check_access (stmt
, size
, /*maxread=*/NULL_TREE
, srcsize
, dstsize
,
2771 data
.mode
, &data
, m_ptr_qry
.rvals
);
2774 /* A convenience wrapper for check_access to check access by a read-only
2775 function like puts or strcmp. */
2778 pass_waccess::check_read_access (gimple
*stmt
, tree src
,
2779 tree bound
/* = NULL_TREE */,
2782 if (m_early_checks_p
|| !warn_stringop_overread
)
2785 if (bound
&& !useless_type_conversion_p (size_type_node
, TREE_TYPE (bound
)))
2786 bound
= fold_convert (size_type_node
, bound
);
2788 tree fndecl
= get_callee_fndecl (stmt
);
2789 maybe_warn_nonstring_arg (fndecl
, stmt
);
2791 access_data
data (m_ptr_qry
.rvals
, stmt
, access_read_only
, NULL_TREE
,
2792 false, bound
, true);
2793 compute_objsize (src
, stmt
, ost
, &data
.src
, &m_ptr_qry
);
2794 check_access (stmt
, /*dstwrite=*/ NULL_TREE
, /*maxread=*/ bound
,
2795 /*srcstr=*/ src
, /*dstsize=*/ NULL_TREE
, data
.mode
,
2796 &data
, m_ptr_qry
.rvals
);
2799 /* Return true if memory model ORD is constant in the context of STMT and
2800 set *CSTVAL to the constant value. Otherwise return false. Warn for
2804 memmodel_to_uhwi (tree ord
, gimple
*stmt
, unsigned HOST_WIDE_INT
*cstval
)
2806 unsigned HOST_WIDE_INT val
;
2808 if (TREE_CODE (ord
) == INTEGER_CST
)
2810 if (!tree_fits_uhwi_p (ord
))
2812 val
= tree_to_uhwi (ord
);
2816 /* Use the range query to determine constant values in the absence
2817 of constant propagation (such as at -O0). */
2818 Value_Range
rng (TREE_TYPE (ord
));
2819 if (!get_range_query (cfun
)->range_of_expr (rng
, ord
, stmt
)
2820 || !rng
.singleton_p (&ord
))
2823 wide_int lob
= rng
.lower_bound ();
2824 if (!wi::fits_uhwi_p (lob
))
2827 val
= lob
.to_shwi ();
2830 if (targetm
.memmodel_check
)
2831 /* This might warn for an invalid VAL but return a conservatively
2833 val
= targetm
.memmodel_check (val
);
2834 else if (val
& ~MEMMODEL_MASK
)
2836 tree fndecl
= gimple_call_fndecl (stmt
);
2837 location_t loc
= gimple_location (stmt
);
2838 loc
= expansion_point_location_if_in_system_header (loc
);
2840 warning_at (loc
, OPT_Winvalid_memory_model
,
2841 "unknown architecture specifier in memory model "
2842 "%wi for %qD", val
, fndecl
);
2851 /* Valid memory model for each set of atomic built-in functions. */
2853 struct memmodel_pair
2856 const char* modname
;
2858 #define MEMMODEL_PAIR(val, str) \
2859 { MEMMODEL_ ## val, "memory_order_" str }
2862 /* Valid memory models in the order of increasing strength. */
2864 static const memmodel_pair memory_models
[] =
2865 { MEMMODEL_PAIR (RELAXED
, "relaxed"),
2866 MEMMODEL_PAIR (SEQ_CST
, "seq_cst"),
2867 MEMMODEL_PAIR (ACQUIRE
, "acquire"),
2868 MEMMODEL_PAIR (CONSUME
, "consume"),
2869 MEMMODEL_PAIR (RELEASE
, "release"),
2870 MEMMODEL_PAIR (ACQ_REL
, "acq_rel")
2873 /* Return the name of the memory model VAL. */
2876 memmodel_name (unsigned HOST_WIDE_INT val
)
2878 val
= memmodel_base (val
);
2880 for (unsigned i
= 0; i
!= ARRAY_SIZE (memory_models
); ++i
)
2882 if (val
== memory_models
[i
].modval
)
2883 return memory_models
[i
].modname
;
2888 /* Indices of valid MEMORY_MODELS above for corresponding atomic operations. */
2889 static const unsigned char load_models
[] = { 0, 1, 2, 3, UCHAR_MAX
};
2890 static const unsigned char store_models
[] = { 0, 1, 4, UCHAR_MAX
};
2891 static const unsigned char xchg_models
[] = { 0, 1, 3, 4, 5, UCHAR_MAX
};
2892 static const unsigned char flag_clr_models
[] = { 0, 1, 4, UCHAR_MAX
};
2893 static const unsigned char all_models
[] = { 0, 1, 2, 3, 4, 5, UCHAR_MAX
};
2895 /* Check the success memory model argument ORD_SUCS to the call STMT to
2896 an atomic function and warn if it's invalid. If nonnull, also check
2897 the failure memory model ORD_FAIL and warn if it's invalid. Return
2898 true if a warning has been issued. */
2901 pass_waccess::maybe_warn_memmodel (gimple
*stmt
, tree ord_sucs
,
2902 tree ord_fail
, const unsigned char *valid
)
2904 unsigned HOST_WIDE_INT sucs
, fail
= 0;
2905 if (!memmodel_to_uhwi (ord_sucs
, stmt
, &sucs
)
2906 || (ord_fail
&& !memmodel_to_uhwi (ord_fail
, stmt
, &fail
)))
2909 bool is_valid
= false;
2911 for (unsigned i
= 0; valid
[i
] != UCHAR_MAX
; ++i
)
2913 memmodel model
= memory_models
[valid
[i
]].modval
;
2914 if (memmodel_base (sucs
) == model
)
2923 tree fndecl
= gimple_call_fndecl (stmt
);
2924 location_t loc
= gimple_location (stmt
);
2925 loc
= expansion_point_location_if_in_system_header (loc
);
2929 bool warned
= false;
2930 auto_diagnostic_group d
;
2931 if (const char *modname
= memmodel_name (sucs
))
2932 warned
= warning_at (loc
, OPT_Winvalid_memory_model
,
2933 "invalid memory model %qs for %qD",
2936 warned
= warning_at (loc
, OPT_Winvalid_memory_model
,
2937 "invalid memory model %wi for %qD",
2943 /* Print a note with the valid memory models. */
2945 pp_show_color (&pp
) = pp_show_color (global_dc
->printer
);
2946 for (unsigned i
= 0; valid
[i
] != UCHAR_MAX
; ++i
)
2948 const char *modname
= memory_models
[valid
[i
]].modname
;
2949 pp_printf (&pp
, "%s%qs", i
? ", " : "", modname
);
2952 inform (loc
, "valid models are %s", pp_formatted_text (&pp
));
2959 if (fail
== MEMMODEL_RELEASE
|| fail
== MEMMODEL_ACQ_REL
)
2960 if (const char *failname
= memmodel_name (fail
))
2962 /* If both memory model arguments are valid but their combination
2963 is not, use their names in the warning. */
2964 auto_diagnostic_group d
;
2965 if (!warning_at (loc
, OPT_Winvalid_memory_model
,
2966 "invalid failure memory model %qs for %qD",
2971 "valid failure models are %qs, %qs, %qs, %qs",
2972 "memory_order_relaxed", "memory_order_seq_cst",
2973 "memory_order_acquire", "memory_order_consume");
2977 if (memmodel_base (fail
) <= memmodel_base (sucs
))
2980 if (const char *sucsname
= memmodel_name (sucs
))
2981 if (const char *failname
= memmodel_name (fail
))
2983 /* If both memory model arguments are valid but their combination
2984 is not, use their names in the warning. */
2985 auto_diagnostic_group d
;
2986 if (!warning_at (loc
, OPT_Winvalid_memory_model
,
2987 "failure memory model %qs cannot be stronger "
2988 "than success memory model %qs for %qD",
2989 failname
, sucsname
, fndecl
))
2992 /* Print a note with the valid failure memory models which are
2993 those with a value less than or equal to the success mode. */
2996 for (unsigned i
= 0;
2997 memory_models
[i
].modval
<= memmodel_base (sucs
); ++i
)
3002 const char *modname
= memory_models
[valid
[i
]].modname
;
3003 sprintf (buf
+ strlen (buf
), "'%s'", modname
);
3006 inform (loc
, "valid models are %s", buf
);
3010 /* If either memory model argument value is invalid use the numerical
3011 value of both in the message. */
3012 return warning_at (loc
, OPT_Winvalid_memory_model
,
3013 "failure memory model %wi cannot be stronger "
3014 "than success memory model %wi for %qD",
3015 fail
, sucs
, fndecl
);
3018 /* Wrapper for the above. */
3021 pass_waccess::check_atomic_memmodel (gimple
*stmt
, tree ord_sucs
,
3022 tree ord_fail
, const unsigned char *valid
)
3024 if (warning_suppressed_p (stmt
, OPT_Winvalid_memory_model
))
3027 if (!maybe_warn_memmodel (stmt
, ord_sucs
, ord_fail
, valid
))
3030 suppress_warning (stmt
, OPT_Winvalid_memory_model
);
3033 /* Check a call STMT to an atomic or sync built-in. */
3036 pass_waccess::check_atomic_builtin (gcall
*stmt
)
3038 tree callee
= gimple_call_fndecl (stmt
);
3042 /* The size in bytes of the access by the function, and the number
3043 of the second argument to check (if any). */
3044 unsigned bytes
= 0, arg2
= UINT_MAX
;
3045 unsigned sucs_arg
= UINT_MAX
, fail_arg
= UINT_MAX
;
3046 /* Points to the array of indices of valid memory models. */
3047 const unsigned char *pvalid_models
= NULL
;
3049 switch (DECL_FUNCTION_CODE (callee
))
3051 #define BUILTIN_ACCESS_SIZE_FNSPEC(N) \
3052 BUILT_IN_SYNC_FETCH_AND_ADD_ ## N: \
3053 case BUILT_IN_SYNC_FETCH_AND_SUB_ ## N: \
3054 case BUILT_IN_SYNC_FETCH_AND_OR_ ## N: \
3055 case BUILT_IN_SYNC_FETCH_AND_AND_ ## N: \
3056 case BUILT_IN_SYNC_FETCH_AND_XOR_ ## N: \
3057 case BUILT_IN_SYNC_FETCH_AND_NAND_ ## N: \
3058 case BUILT_IN_SYNC_ADD_AND_FETCH_ ## N: \
3059 case BUILT_IN_SYNC_SUB_AND_FETCH_ ## N: \
3060 case BUILT_IN_SYNC_OR_AND_FETCH_ ## N: \
3061 case BUILT_IN_SYNC_AND_AND_FETCH_ ## N: \
3062 case BUILT_IN_SYNC_XOR_AND_FETCH_ ## N: \
3063 case BUILT_IN_SYNC_NAND_AND_FETCH_ ## N: \
3064 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_ ## N: \
3065 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_ ## N: \
3066 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_ ## N: \
3067 case BUILT_IN_SYNC_LOCK_RELEASE_ ## N: \
3070 case BUILT_IN_ATOMIC_LOAD_ ## N: \
3071 pvalid_models = load_models; \
3074 case BUILT_IN_ATOMIC_STORE_ ## N: \
3075 if (!pvalid_models) \
3076 pvalid_models = store_models; \
3078 case BUILT_IN_ATOMIC_ADD_FETCH_ ## N: \
3079 case BUILT_IN_ATOMIC_SUB_FETCH_ ## N: \
3080 case BUILT_IN_ATOMIC_AND_FETCH_ ## N: \
3081 case BUILT_IN_ATOMIC_NAND_FETCH_ ## N: \
3082 case BUILT_IN_ATOMIC_XOR_FETCH_ ## N: \
3083 case BUILT_IN_ATOMIC_OR_FETCH_ ## N: \
3084 case BUILT_IN_ATOMIC_FETCH_ADD_ ## N: \
3085 case BUILT_IN_ATOMIC_FETCH_SUB_ ## N: \
3086 case BUILT_IN_ATOMIC_FETCH_AND_ ## N: \
3087 case BUILT_IN_ATOMIC_FETCH_NAND_ ## N: \
3088 case BUILT_IN_ATOMIC_FETCH_OR_ ## N: \
3089 case BUILT_IN_ATOMIC_FETCH_XOR_ ## N: \
3091 if (sucs_arg == UINT_MAX) \
3093 if (!pvalid_models) \
3094 pvalid_models = all_models; \
3096 case BUILT_IN_ATOMIC_EXCHANGE_ ## N: \
3099 pvalid_models = xchg_models; \
3101 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_ ## N: \
3105 pvalid_models = all_models; \
3108 case BUILTIN_ACCESS_SIZE_FNSPEC (1);
3110 case BUILTIN_ACCESS_SIZE_FNSPEC (2);
3112 case BUILTIN_ACCESS_SIZE_FNSPEC (4);
3114 case BUILTIN_ACCESS_SIZE_FNSPEC (8);
3116 case BUILTIN_ACCESS_SIZE_FNSPEC (16);
3119 case BUILT_IN_ATOMIC_CLEAR
:
3121 pvalid_models
= flag_clr_models
;
3128 unsigned nargs
= gimple_call_num_args (stmt
);
3129 if (sucs_arg
< nargs
)
3131 tree ord_sucs
= gimple_call_arg (stmt
, sucs_arg
);
3132 tree ord_fail
= NULL_TREE
;
3133 if (fail_arg
< nargs
)
3134 ord_fail
= gimple_call_arg (stmt
, fail_arg
);
3135 check_atomic_memmodel (stmt
, ord_sucs
, ord_fail
, pvalid_models
);
3141 tree size
= build_int_cstu (sizetype
, bytes
);
3142 tree dst
= gimple_call_arg (stmt
, 0);
3143 check_memop_access (stmt
, dst
, NULL_TREE
, size
);
3145 if (arg2
!= UINT_MAX
)
3147 tree dst
= gimple_call_arg (stmt
, arg2
);
3148 check_memop_access (stmt
, dst
, NULL_TREE
, size
);
3154 /* Check call STMT to a built-in function for invalid accesses. Return
3155 true if a call has been handled. */
3158 pass_waccess::check_builtin (gcall
*stmt
)
3160 tree callee
= gimple_call_fndecl (stmt
);
3164 switch (DECL_FUNCTION_CODE (callee
))
3166 case BUILT_IN_ALLOCA
:
3167 case BUILT_IN_ALLOCA_WITH_ALIGN
:
3168 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX
:
3169 check_alloca (stmt
);
3172 case BUILT_IN_EXECL
:
3173 case BUILT_IN_EXECLE
:
3174 case BUILT_IN_EXECLP
:
3175 case BUILT_IN_EXECV
:
3176 case BUILT_IN_EXECVE
:
3177 case BUILT_IN_EXECVP
:
3178 check_read_access (stmt
, call_arg (stmt
, 0));
3182 case BUILT_IN_REALLOC
:
3183 if (!m_early_checks_p
)
3185 tree arg
= call_arg (stmt
, 0);
3186 if (TREE_CODE (arg
) == SSA_NAME
)
3187 check_pointer_uses (stmt
, arg
);
3191 case BUILT_IN_GETTEXT
:
3193 case BUILT_IN_PUTS_UNLOCKED
:
3194 case BUILT_IN_STRDUP
:
3195 check_read_access (stmt
, call_arg (stmt
, 0));
3198 case BUILT_IN_INDEX
:
3199 case BUILT_IN_RINDEX
:
3200 case BUILT_IN_STRCHR
:
3201 case BUILT_IN_STRRCHR
:
3202 case BUILT_IN_STRLEN
:
3203 check_read_access (stmt
, call_arg (stmt
, 0));
3206 case BUILT_IN_FPUTS
:
3207 case BUILT_IN_FPUTS_UNLOCKED
:
3208 check_read_access (stmt
, call_arg (stmt
, 0));
3211 case BUILT_IN_STRNDUP
:
3212 case BUILT_IN_STRNLEN
:
3214 tree str
= call_arg (stmt
, 0);
3215 tree len
= call_arg (stmt
, 1);
3216 check_read_access (stmt
, str
, len
);
3220 case BUILT_IN_STRCAT
:
3221 check_strcat (stmt
);
3224 case BUILT_IN_STRNCAT
:
3225 check_strncat (stmt
);
3228 case BUILT_IN_STPCPY
:
3229 case BUILT_IN_STRCPY
:
3230 check_stxcpy (stmt
);
3233 case BUILT_IN_STPNCPY
:
3234 case BUILT_IN_STRNCPY
:
3235 check_stxncpy (stmt
);
3238 case BUILT_IN_STRCASECMP
:
3239 case BUILT_IN_STRCMP
:
3240 case BUILT_IN_STRPBRK
:
3241 case BUILT_IN_STRSPN
:
3242 case BUILT_IN_STRCSPN
:
3243 case BUILT_IN_STRSTR
:
3244 check_read_access (stmt
, call_arg (stmt
, 0));
3245 check_read_access (stmt
, call_arg (stmt
, 1));
3248 case BUILT_IN_STRNCASECMP
:
3249 case BUILT_IN_STRNCMP
:
3250 check_strncmp (stmt
);
3253 case BUILT_IN_MEMCMP
:
3255 tree a1
= call_arg (stmt
, 0);
3256 tree a2
= call_arg (stmt
, 1);
3257 tree len
= call_arg (stmt
, 2);
3258 check_read_access (stmt
, a1
, len
, 0);
3259 check_read_access (stmt
, a2
, len
, 0);
3263 case BUILT_IN_MEMCPY
:
3264 case BUILT_IN_MEMPCPY
:
3265 case BUILT_IN_MEMMOVE
:
3267 tree dst
= call_arg (stmt
, 0);
3268 tree src
= call_arg (stmt
, 1);
3269 tree len
= call_arg (stmt
, 2);
3270 check_memop_access (stmt
, dst
, src
, len
);
3274 case BUILT_IN_MEMCHR
:
3276 tree src
= call_arg (stmt
, 0);
3277 tree len
= call_arg (stmt
, 2);
3278 check_read_access (stmt
, src
, len
, 0);
3282 case BUILT_IN_MEMSET
:
3284 tree dst
= call_arg (stmt
, 0);
3285 tree len
= call_arg (stmt
, 2);
3286 check_memop_access (stmt
, dst
, NULL_TREE
, len
);
3291 if (check_atomic_builtin (stmt
))
3299 /* Returns the type of the argument ARGNO to function with type FNTYPE
3300 or null when the type cannot be determined or no such argument exists. */
3303 fntype_argno_type (tree fntype
, unsigned argno
)
3305 if (!prototype_p (fntype
))
3309 function_args_iterator it
;
3310 FOREACH_FUNCTION_ARGS (fntype
, argtype
, it
)
3317 /* Helper to append the "human readable" attribute access specification
3318 described by ACCESS to the array ATTRSTR with size STRSIZE. Used in
3322 append_attrname (const std::pair
<int, attr_access
> &access
,
3323 char *attrstr
, size_t strsize
)
3325 if (access
.second
.internal_p
)
3328 tree str
= access
.second
.to_external_string ();
3329 gcc_assert (strsize
>= (size_t) TREE_STRING_LENGTH (str
));
3330 strcpy (attrstr
, TREE_STRING_POINTER (str
));
3333 /* Iterate over attribute access read-only, read-write, and write-only
3334 arguments and diagnose past-the-end accesses and related problems
3335 in the function call EXP. */
3338 pass_waccess::maybe_check_access_sizes (rdwr_map
*rwm
, tree fndecl
, tree fntype
,
3341 if (warning_suppressed_p (stmt
, OPT_Wnonnull
)
3342 || warning_suppressed_p (stmt
, OPT_Wstringop_overflow_
))
3345 auto_diagnostic_group adg
;
3347 /* Set if a warning has been issued for any argument (used to decide
3348 whether to emit an informational note at the end). */
3349 opt_code opt_warned
= no_warning
;
3351 /* A string describing the attributes that the warnings issued by this
3352 function apply to. Used to print one informational note per function
3353 call, rather than one per warning. That reduces clutter. */
3357 for (rdwr_map::iterator it
= rwm
->begin (); it
!= rwm
->end (); ++it
)
3359 std::pair
<int, attr_access
> access
= *it
;
3361 /* Get the function call arguments corresponding to the attribute's
3362 positional arguments. When both arguments have been specified
3363 there will be two entries in *RWM, one for each. They are
3364 cross-referenced by their respective argument numbers in
3365 ACCESS.PTRARG and ACCESS.SIZARG. */
3366 const int ptridx
= access
.second
.ptrarg
;
3367 const int sizidx
= access
.second
.sizarg
;
3369 gcc_assert (ptridx
!= -1);
3370 gcc_assert (access
.first
== ptridx
|| access
.first
== sizidx
);
3372 /* The pointer is set to null for the entry corresponding to
3373 the size argument. Skip it. It's handled when the entry
3374 corresponding to the pointer argument comes up. */
3375 if (!access
.second
.ptr
)
3378 tree ptrtype
= fntype_argno_type (fntype
, ptridx
);
3380 /* A function with a prototype was redeclared without one and
3381 the prototype has been lost. See pr102759. Avoid dealing
3382 with this pathological case. */
3385 tree argtype
= TREE_TYPE (ptrtype
);
3387 /* The size of the access by the call in elements. */
3391 /* If only the pointer attribute operand was specified and
3392 not size, set SIZE to the greater of MINSIZE or size of
3393 one element of the pointed to type to detect smaller
3394 objects (null pointers are diagnosed in this case only
3395 if the pointer is also declared with attribute nonnull. */
3396 if (access
.second
.minsize
3397 && access
.second
.minsize
!= HOST_WIDE_INT_M1U
)
3398 access_nelts
= build_int_cstu (sizetype
, access
.second
.minsize
);
3399 else if (VOID_TYPE_P (argtype
) && access
.second
.mode
== access_none
)
3400 /* Treat access mode none on a void* argument as expecting
3401 as little as zero bytes. */
3402 access_nelts
= size_zero_node
;
3404 access_nelts
= size_one_node
;
3407 access_nelts
= rwm
->get (sizidx
)->size
;
3409 /* Format the value or range to avoid an explosion of messages. */
3411 tree sizrng
[2] = { size_zero_node
, build_all_ones_cst (sizetype
) };
3412 if (get_size_range (m_ptr_qry
.rvals
, access_nelts
, stmt
, sizrng
, 1))
3414 char *s0
= print_generic_expr_to_str (sizrng
[0]);
3415 if (tree_int_cst_equal (sizrng
[0], sizrng
[1]))
3417 gcc_checking_assert (strlen (s0
) < sizeof sizstr
);
3418 strcpy (sizstr
, s0
);
3422 char *s1
= print_generic_expr_to_str (sizrng
[1]);
3423 gcc_checking_assert (strlen (s0
) + strlen (s1
)
3424 < sizeof sizstr
- 4);
3425 sprintf (sizstr
, "[%.37s, %.37s]", s0
, s1
);
3433 /* Set if a warning has been issued for the current argument. */
3434 opt_code arg_warned
= no_warning
;
3435 location_t loc
= get_location (stmt
);
3436 tree ptr
= access
.second
.ptr
;
3438 && tree_int_cst_sgn (sizrng
[0]) < 0
3439 && tree_int_cst_sgn (sizrng
[1]) < 0)
3441 /* Warn about negative sizes. */
3442 if (access
.second
.internal_p
)
3444 const std::string argtypestr
3445 = access
.second
.array_as_string (ptrtype
);
3447 if (warning_at (loc
, OPT_Wstringop_overflow_
,
3448 "bound argument %i value %s is "
3449 "negative for a variable length array "
3450 "argument %i of type %s",
3452 ptridx
+ 1, argtypestr
.c_str ()))
3453 arg_warned
= OPT_Wstringop_overflow_
;
3455 else if (warning_at (loc
, OPT_Wstringop_overflow_
,
3456 "argument %i value %s is negative",
3457 sizidx
+ 1, sizstr
))
3458 arg_warned
= OPT_Wstringop_overflow_
;
3460 if (arg_warned
!= no_warning
)
3462 append_attrname (access
, attrstr
, sizeof attrstr
);
3463 /* Remember a warning has been issued and avoid warning
3464 again below for the same attribute. */
3465 opt_warned
= arg_warned
;
3470 /* The size of the access by the call in bytes. */
3471 tree access_size
= NULL_TREE
;
3472 if (tree_int_cst_sgn (sizrng
[0]) >= 0)
3474 if (COMPLETE_TYPE_P (argtype
))
3476 /* Multiply ACCESS_SIZE by the size of the type the pointer
3477 argument points to. If it's incomplete the size is used
3479 if (tree argsize
= TYPE_SIZE_UNIT (argtype
))
3480 if (TREE_CODE (argsize
) == INTEGER_CST
)
3482 const int prec
= TYPE_PRECISION (sizetype
);
3483 wide_int minsize
= wi::to_wide (sizrng
[0], prec
);
3484 minsize
*= wi::to_wide (argsize
, prec
);
3485 access_size
= wide_int_to_tree (sizetype
, minsize
);
3489 access_size
= access_nelts
;
3492 if (integer_zerop (ptr
))
3494 if (!access
.second
.internal_p
3495 && sizidx
>= 0 && tree_int_cst_sgn (sizrng
[0]) > 0)
3497 /* Warn about null pointers with positive sizes. This is
3498 different from also declaring the pointer argument with
3499 attribute nonnull when the function accepts null pointers
3500 only when the corresponding size is zero. */
3501 if (warning_at (loc
, OPT_Wnonnull
,
3502 "argument %i is null but "
3503 "the corresponding size argument "
3505 ptridx
+ 1, sizidx
+ 1, sizstr
))
3506 arg_warned
= OPT_Wnonnull
;
3509 if (arg_warned
!= no_warning
)
3511 append_attrname (access
, attrstr
, sizeof attrstr
);
3512 /* Remember a warning has been issued and avoid warning
3513 again below for the same attribute. */
3514 opt_warned
= OPT_Wnonnull
;
3519 access_data
data (m_ptr_qry
.rvals
, stmt
, access
.second
.mode
,
3520 NULL_TREE
, false, NULL_TREE
, false);
3521 access_ref
* const pobj
= (access
.second
.mode
== access_write_only
3522 ? &data
.dst
: &data
.src
);
3523 tree objsize
= compute_objsize (ptr
, stmt
, 1, pobj
, &m_ptr_qry
);
3525 /* The size of the destination or source object. */
3526 tree dstsize
= NULL_TREE
, srcsize
= NULL_TREE
;
3527 if (access
.second
.mode
== access_read_only
3528 || access
.second
.mode
== access_none
)
3530 /* For a read-only argument there is no destination. For
3531 no access, set the source as well and differentiate via
3532 the access flag below. */
3534 if (access
.second
.mode
== access_read_only
3535 || access
.second
.mode
== access_none
)
3537 /* For a read-only attribute there is no destination so
3538 clear OBJSIZE. This emits "reading N bytes" kind of
3539 diagnostics instead of the "writing N bytes" kind,
3540 unless MODE is none. */
3541 objsize
= NULL_TREE
;
3547 /* Clear the no-warning bit in case it was set by check_access
3548 in a prior iteration so that accesses via different arguments
3550 suppress_warning (stmt
, OPT_Wstringop_overflow_
, false);
3551 access_mode mode
= data
.mode
;
3552 if (mode
== access_deferred
)
3553 mode
= TYPE_READONLY (argtype
) ? access_read_only
: access_read_write
;
3554 check_access (stmt
, access_size
, /*maxread=*/ NULL_TREE
, srcsize
,
3555 dstsize
, mode
, &data
, m_ptr_qry
.rvals
);
3557 if (warning_suppressed_p (stmt
, OPT_Wstringop_overflow_
))
3558 opt_warned
= OPT_Wstringop_overflow_
;
3559 if (opt_warned
!= no_warning
)
3561 if (access
.second
.internal_p
)
3563 unsigned HOST_WIDE_INT nelts
=
3564 access_nelts
? access
.second
.minsize
: HOST_WIDE_INT_M1U
;
3565 tree arrtype
= build_printable_array_type (argtype
, nelts
);
3566 inform (loc
, "referencing argument %u of type %qT",
3567 ptridx
+ 1, arrtype
);
3570 /* If check_access issued a warning above, append the relevant
3571 attribute to the string. */
3572 append_attrname (access
, attrstr
, sizeof attrstr
);
3579 inform (get_location (fndecl
),
3580 "in a call to function %qD declared with attribute %qs",
3583 inform (get_location (stmt
),
3584 "in a call with type %qT and attribute %qs",
3587 else if (opt_warned
!= no_warning
)
3590 inform (get_location (fndecl
),
3591 "in a call to function %qD", fndecl
);
3593 inform (get_location (stmt
),
3594 "in a call with type %qT", fntype
);
3597 /* Set the bit in case it was cleared and not set above. */
3598 if (opt_warned
!= no_warning
)
3599 suppress_warning (stmt
, opt_warned
);
3602 /* Check call STMT to an ordinary (non-built-in) function for invalid
3603 accesses. Return true if a call has been handled. */
3606 pass_waccess::check_call_access (gcall
*stmt
)
3608 tree fntype
= gimple_call_fntype (stmt
);
3612 tree fntypeattrs
= TYPE_ATTRIBUTES (fntype
);
3616 /* Map of attribute access specifications for function arguments. */
3618 init_attr_rdwr_indices (&rdwr_idx
, fntypeattrs
);
3620 unsigned nargs
= call_nargs (stmt
);
3621 for (unsigned i
= 0; i
!= nargs
; ++i
)
3623 tree arg
= call_arg (stmt
, i
);
3625 /* Save the actual argument that corresponds to the access attribute
3626 operand for later processing. */
3627 if (attr_access
*access
= rdwr_idx
.get (i
))
3629 if (POINTER_TYPE_P (TREE_TYPE (arg
)))
3632 /* A nonnull ACCESS->SIZE contains VLA bounds. */
3637 gcc_assert (access
->ptr
== NULL_TREE
);
3642 /* Check attribute access arguments. */
3643 tree fndecl
= gimple_call_fndecl (stmt
);
3644 maybe_check_access_sizes (&rdwr_idx
, fndecl
, fntype
, stmt
);
3646 check_alloc_size_call (stmt
);
3650 /* Check arguments in a call STMT for attribute nonstring. */
3653 check_nonstring_args (gcall
*stmt
)
3655 tree fndecl
= gimple_call_fndecl (stmt
);
3657 /* Detect passing non-string arguments to functions expecting
3658 nul-terminated strings. */
3659 maybe_warn_nonstring_arg (fndecl
, stmt
);
3662 /* Issue a warning if a deallocation function such as free, realloc,
3663 or C++ operator delete is called with an argument not returned by
3664 a matching allocation function such as malloc or the corresponding
3665 form of C++ operator new. */
3668 pass_waccess::maybe_check_dealloc_call (gcall
*call
)
3670 tree fndecl
= gimple_call_fndecl (call
);
3674 unsigned argno
= fndecl_dealloc_argno (fndecl
);
3675 if ((unsigned) call_nargs (call
) <= argno
)
3678 tree ptr
= gimple_call_arg (call
, argno
);
3679 if (integer_zerop (ptr
))
3683 if (!compute_objsize (ptr
, call
, 0, &aref
, &m_ptr_qry
))
3686 tree ref
= aref
.ref
;
3687 if (integer_zerop (ref
))
3690 tree dealloc_decl
= fndecl
;
3691 location_t loc
= gimple_location (call
);
3693 if (DECL_P (ref
) || EXPR_P (ref
))
3695 /* Diagnose freeing a declared object. */
3696 if (aref
.ref_declared ())
3698 auto_diagnostic_group d
;
3699 if (warning_at (loc
, OPT_Wfree_nonheap_object
,
3700 "%qD called on unallocated object %qD",
3703 inform (get_location (ref
), "declared here");
3708 /* Diagnose freeing a pointer that includes a positive offset.
3709 Such a pointer cannot refer to the beginning of an allocated
3710 object. A negative offset may refer to it. */
3711 if (aref
.sizrng
[0] != aref
.sizrng
[1]
3712 && warn_dealloc_offset (loc
, call
, aref
))
3715 else if (CONSTANT_CLASS_P (ref
))
3717 auto_diagnostic_group d
;
3718 if (warning_at (loc
, OPT_Wfree_nonheap_object
,
3719 "%qD called on a pointer to an unallocated "
3720 "object %qE", dealloc_decl
, ref
))
3722 if (TREE_CODE (ptr
) == SSA_NAME
)
3724 gimple
*def_stmt
= SSA_NAME_DEF_STMT (ptr
);
3725 if (is_gimple_assign (def_stmt
))
3727 location_t loc
= gimple_location (def_stmt
);
3728 inform (loc
, "assigned here");
3734 else if (TREE_CODE (ref
) == SSA_NAME
)
3736 /* Also warn if the pointer argument refers to the result
3737 of an allocation call like alloca or VLA. */
3738 gimple
*def_stmt
= SSA_NAME_DEF_STMT (ref
);
3742 if (is_gimple_call (def_stmt
))
3744 bool warned
= false;
3745 if (gimple_call_alloc_p (def_stmt
))
3747 if (matching_alloc_calls_p (def_stmt
, dealloc_decl
))
3749 if (warn_dealloc_offset (loc
, call
, aref
))
3754 tree alloc_decl
= gimple_call_fndecl (def_stmt
);
3755 const opt_code opt
=
3756 (DECL_IS_OPERATOR_NEW_P (alloc_decl
)
3757 || DECL_IS_OPERATOR_DELETE_P (dealloc_decl
)
3758 ? OPT_Wmismatched_new_delete
3759 : OPT_Wmismatched_dealloc
);
3760 warned
= warning_at (loc
, opt
,
3761 "%qD called on pointer returned "
3762 "from a mismatched allocation "
3763 "function", dealloc_decl
);
3766 else if (gimple_call_builtin_p (def_stmt
, BUILT_IN_ALLOCA
)
3767 || gimple_call_builtin_p (def_stmt
,
3768 BUILT_IN_ALLOCA_WITH_ALIGN
))
3769 warned
= warning_at (loc
, OPT_Wfree_nonheap_object
,
3770 "%qD called on pointer to "
3771 "an unallocated object",
3773 else if (warn_dealloc_offset (loc
, call
, aref
))
3778 tree fndecl
= gimple_call_fndecl (def_stmt
);
3779 inform (gimple_location (def_stmt
),
3780 "returned from %qD", fndecl
);
3784 else if (gimple_nop_p (def_stmt
))
3786 ref
= SSA_NAME_VAR (ref
);
3787 /* Diagnose freeing a pointer that includes a positive offset. */
3788 if (TREE_CODE (ref
) == PARM_DECL
3790 && aref
.sizrng
[0] != aref
.sizrng
[1]
3791 && aref
.offrng
[0] > 0 && aref
.offrng
[1] > 0
3792 && warn_dealloc_offset (loc
, call
, aref
))
3798 /* Return true if either USE_STMT's basic block (that of a pointer's use)
3799 is dominated by INVAL_STMT's (that of a pointer's invalidating statement,
3800 which is either a clobber or a deallocation call), or if they're in
3801 the same block, USE_STMT follows INVAL_STMT. */
3804 pass_waccess::use_after_inval_p (gimple
*inval_stmt
, gimple
*use_stmt
,
3805 bool last_block
/* = false */)
3808 gimple_clobber_p (inval_stmt
) ? gimple_assign_lhs (inval_stmt
) : NULL_TREE
;
3810 basic_block inval_bb
= gimple_bb (inval_stmt
);
3811 basic_block use_bb
= gimple_bb (use_stmt
);
3813 if (!inval_bb
|| !use_bb
)
3816 if (inval_bb
!= use_bb
)
3818 if (dominated_by_p (CDI_DOMINATORS
, use_bb
, inval_bb
))
3821 if (!clobvar
|| !last_block
)
3824 /* Proceed only when looking for uses of dangling pointers. */
3825 auto gsi
= gsi_for_stmt (use_stmt
);
3827 /* A use statement in the last basic block in a function or one that
3828 falls through to it is after any other prior clobber of the used
3829 variable unless it's followed by a clobber of the same variable. */
3830 basic_block bb
= use_bb
;
3831 while (bb
!= inval_bb
3832 && single_succ_p (bb
)
3833 && !(single_succ_edge (bb
)->flags
3834 & (EDGE_EH
| EDGE_ABNORMAL
| EDGE_DFS_BACK
)))
3836 for (; !gsi_end_p (gsi
); gsi_next_nondebug (&gsi
))
3838 gimple
*stmt
= gsi_stmt (gsi
);
3839 if (gimple_clobber_p (stmt
))
3841 if (clobvar
== gimple_assign_lhs (stmt
))
3842 /* The use is followed by a clobber. */
3847 bb
= single_succ (bb
);
3848 gsi
= gsi_start_bb (bb
);
3851 /* The use is one of a dangling pointer if a clobber of the variable
3852 [the pointer points to] has not been found before the function exit
3854 return bb
== EXIT_BLOCK_PTR_FOR_FN (cfun
);
3857 if (bitmap_set_bit (m_bb_uids_set
, inval_bb
->index
))
3858 /* The first time this basic block is visited assign increasing ids
3859 to consecutive statements in it. Use the ids to determine which
3860 precedes which. This avoids the linear traversal on subsequent
3861 visits to the same block. */
3862 renumber_gimple_stmt_uids_in_block (m_func
, inval_bb
);
3864 return gimple_uid (inval_stmt
) < gimple_uid (use_stmt
);
3867 /* Issue a warning for the USE_STMT of pointer or reference REF rendered
3868 invalid by INVAL_STMT. REF may be null when it's been optimized away.
3869 When nonnull, INVAL_STMT is the deallocation function that rendered
3870 the pointer or reference dangling. Otherwise, VAR is the auto variable
3871 (including an unnamed temporary such as a compound literal) whose
3872 lifetime's rended it dangling. MAYBE is true to issue the "maybe"
3873 kind of warning. EQUALITY is true when the pointer is used in
3874 an equality expression. */
3877 pass_waccess::warn_invalid_pointer (tree ref
, gimple
*use_stmt
,
3878 gimple
*inval_stmt
, tree var
,
3879 bool maybe
, bool equality
/* = false */)
3881 /* Avoid printing the unhelpful "<unknown>" in the diagnostics. */
3882 if (ref
&& TREE_CODE (ref
) == SSA_NAME
)
3884 tree var
= SSA_NAME_VAR (ref
);
3887 /* Don't warn for cases like when a cdtor returns 'this' on ARM. */
3888 else if (warning_suppressed_p (var
, OPT_Wuse_after_free
))
3890 else if (DECL_ARTIFICIAL (var
))
3894 location_t use_loc
= gimple_location (use_stmt
);
3895 if (use_loc
== UNKNOWN_LOCATION
)
3897 use_loc
= m_func
->function_end_locus
;
3899 /* Avoid issuing a warning with no context other than
3900 the function. That would make it difficult to debug
3901 in any but very simple cases. */
3905 if (is_gimple_call (inval_stmt
))
3907 if (!m_early_checks_p
3908 || (equality
&& warn_use_after_free
< 3)
3909 || (maybe
&& warn_use_after_free
< 2)
3910 || warning_suppressed_p (use_stmt
, OPT_Wuse_after_free
))
3913 const tree inval_decl
= gimple_call_fndecl (inval_stmt
);
3915 auto_diagnostic_group d
;
3916 if ((ref
&& warning_at (use_loc
, OPT_Wuse_after_free
,
3918 ? G_("pointer %qE may be used after %qD")
3919 : G_("pointer %qE used after %qD")),
3921 || (!ref
&& warning_at (use_loc
, OPT_Wuse_after_free
,
3923 ? G_("pointer may be used after %qD")
3924 : G_("pointer used after %qD")),
3927 location_t loc
= gimple_location (inval_stmt
);
3928 inform (loc
, "call to %qD here", inval_decl
);
3929 suppress_warning (use_stmt
, OPT_Wuse_after_free
);
3935 || (maybe
&& warn_dangling_pointer
< 2)
3936 || warning_suppressed_p (use_stmt
, OPT_Wdangling_pointer_
))
3939 if (DECL_NAME (var
))
3941 auto_diagnostic_group d
;
3943 && warning_at (use_loc
, OPT_Wdangling_pointer_
,
3945 ? G_("dangling pointer %qE to %qD may be used")
3946 : G_("using dangling pointer %qE to %qD")),
3949 && warning_at (use_loc
, OPT_Wdangling_pointer_
,
3951 ? G_("dangling pointer to %qD may be used")
3952 : G_("using a dangling pointer to %qD")),
3954 inform (DECL_SOURCE_LOCATION (var
),
3955 "%qD declared here", var
);
3956 suppress_warning (use_stmt
, OPT_Wdangling_pointer_
);
3961 && warning_at (use_loc
, OPT_Wdangling_pointer_
,
3963 ? G_("dangling pointer %qE to an unnamed temporary "
3965 : G_("using dangling pointer %qE to an unnamed "
3969 && warning_at (use_loc
, OPT_Wdangling_pointer_
,
3971 ? G_("dangling pointer to an unnamed temporary "
3973 : G_("using a dangling pointer to an unnamed "
3976 inform (DECL_SOURCE_LOCATION (var
),
3977 "unnamed temporary defined here");
3978 suppress_warning (use_stmt
, OPT_Wdangling_pointer_
);
3982 /* If STMT is a call to either the standard realloc or to a user-defined
3983 reallocation function returns its LHS and set *PTR to the reallocated
3984 pointer. Otherwise return null. */
3987 get_realloc_lhs (gimple
*stmt
, tree
*ptr
)
3989 if (gimple_call_builtin_p (stmt
, BUILT_IN_REALLOC
))
3991 *ptr
= gimple_call_arg (stmt
, 0);
3992 return gimple_call_lhs (stmt
);
3995 gcall
*call
= dyn_cast
<gcall
*>(stmt
);
3999 tree fnattr
= NULL_TREE
;
4000 tree fndecl
= gimple_call_fndecl (call
);
4002 fnattr
= DECL_ATTRIBUTES (fndecl
);
4005 tree fntype
= gimple_call_fntype (stmt
);
4008 fnattr
= TYPE_ATTRIBUTES (fntype
);
4014 for (tree ats
= fnattr
; (ats
= lookup_attribute ("*dealloc", ats
));
4015 ats
= TREE_CHAIN (ats
))
4017 tree args
= TREE_VALUE (ats
);
4021 tree alloc
= TREE_VALUE (args
);
4025 if (alloc
== DECL_NAME (fndecl
))
4028 if (tree index
= TREE_CHAIN (args
))
4029 argno
= TREE_INT_CST_LOW (TREE_VALUE (index
)) - 1;
4030 *ptr
= gimple_call_arg (stmt
, argno
);
4031 return gimple_call_lhs (stmt
);
4038 /* Warn if STMT is a call to a deallocation function that's not a match
4039 for the REALLOC_STMT call. Return true if warned. */
4042 maybe_warn_mismatched_realloc (tree ptr
, gimple
*realloc_stmt
, gimple
*stmt
)
4044 if (!is_gimple_call (stmt
))
4047 tree fndecl
= gimple_call_fndecl (stmt
);
4051 unsigned argno
= fndecl_dealloc_argno (fndecl
);
4052 if (call_nargs (stmt
) <= argno
)
4055 if (matching_alloc_calls_p (realloc_stmt
, fndecl
))
4058 /* Avoid printing the unhelpful "<unknown>" in the diagnostics. */
4059 if (ptr
&& TREE_CODE (ptr
) == SSA_NAME
4060 && (!SSA_NAME_VAR (ptr
) || DECL_ARTIFICIAL (SSA_NAME_VAR (ptr
))))
4063 location_t loc
= gimple_location (stmt
);
4064 tree realloc_decl
= gimple_call_fndecl (realloc_stmt
);
4065 tree dealloc_decl
= gimple_call_fndecl (stmt
);
4066 if (ptr
&& !warning_at (loc
, OPT_Wmismatched_dealloc
,
4067 "%qD called on pointer %qE passed to mismatched "
4068 "allocation function %qD",
4069 dealloc_decl
, ptr
, realloc_decl
))
4071 if (!ptr
&& !warning_at (loc
, OPT_Wmismatched_dealloc
,
4072 "%qD called on a pointer passed to mismatched "
4073 "reallocation function %qD",
4074 dealloc_decl
, realloc_decl
))
4077 inform (gimple_location (realloc_stmt
),
4078 "call to %qD", realloc_decl
);
4082 /* Return true if P and Q point to the same object, and false if they
4083 either don't or their relationship cannot be determined. */
4086 pointers_related_p (gimple
*stmt
, tree p
, tree q
, pointer_query
&qry
,
4087 auto_bitmap
&visited
)
4089 if (!ptr_derefs_may_alias_p (p
, q
))
4092 /* TODO: Work harder to rule out relatedness. */
4093 access_ref pref
, qref
;
4094 if (!qry
.get_ref (p
, stmt
, &pref
, 0)
4095 || !qry
.get_ref (q
, stmt
, &qref
, 0))
4096 /* GET_REF() only rarely fails. When it does, it's likely because
4097 it involves a self-referential PHI. Return a conservative result. */
4100 if (pref
.ref
== qref
.ref
)
4103 /* If either pointer is a PHI, iterate over all its operands and
4104 return true if they're all related to the other pointer. */
4107 gphi
*phi
= pref
.phi ();
4109 version
= SSA_NAME_VERSION (pref
.ref
);
4117 version
= SSA_NAME_VERSION (qref
.ref
);
4120 if (!bitmap_set_bit (visited
, version
))
4123 unsigned nargs
= gimple_phi_num_args (phi
);
4124 for (unsigned i
= 0; i
!= nargs
; ++i
)
4126 tree arg
= gimple_phi_arg_def (phi
, i
);
4127 if (!pointers_related_p (stmt
, arg
, ptr
, qry
, visited
))
4134 /* Convenience wrapper for the above. */
4137 pointers_related_p (gimple
*stmt
, tree p
, tree q
, pointer_query
&qry
)
4139 auto_bitmap visited
;
4140 return pointers_related_p (stmt
, p
, q
, qry
, visited
);
4143 /* For a STMT either a call to a deallocation function or a clobber, warn
4144 for uses of the pointer PTR it was called with (including its copies
4145 or others derived from it by pointer arithmetic). If STMT is a clobber,
4146 VAR is the decl of the clobbered variable. When MAYBE is true use
4147 a "maybe" form of diagnostic. */
4150 pass_waccess::check_pointer_uses (gimple
*stmt
, tree ptr
,
4151 tree var
/* = NULL_TREE */,
4152 bool maybe
/* = false */)
4154 gcc_assert (TREE_CODE (ptr
) == SSA_NAME
);
4156 const bool check_dangling
= !is_gimple_call (stmt
);
4157 basic_block stmt_bb
= gimple_bb (stmt
);
4159 /* If STMT is a reallocation function set to the reallocated pointer
4160 and the LHS of the call, respectively. */
4161 tree realloc_ptr
= NULL_TREE
;
4162 tree realloc_lhs
= get_realloc_lhs (stmt
, &realloc_ptr
);
4164 auto_bitmap visited
;
4166 auto_vec
<tree
, 8> pointers
;
4167 pointers
.quick_push (ptr
);
4168 hash_map
<tree
, int> *phi_map
= nullptr;
4170 /* Starting with PTR, iterate over POINTERS added by the loop, and
4171 either warn for their uses in basic blocks dominated by the STMT
4172 or in statements that follow it in the same basic block, or add
4173 them to POINTERS if they point into the same object as PTR (i.e.,
4174 are obtained by pointer arithmetic on PTR). */
4175 for (unsigned i
= 0; i
!= pointers
.length (); ++i
)
4177 tree ptr
= pointers
[i
];
4178 if (!bitmap_set_bit (visited
, SSA_NAME_VERSION (ptr
)))
4179 /* Avoid revisiting the same pointer. */
4182 use_operand_p use_p
;
4183 imm_use_iterator iter
;
4184 FOR_EACH_IMM_USE_FAST (use_p
, iter
, ptr
)
4186 gimple
*use_stmt
= USE_STMT (use_p
);
4187 if (use_stmt
== stmt
|| is_gimple_debug (use_stmt
))
4190 /* A clobber isn't a use. */
4191 if (gimple_clobber_p (use_stmt
))
4196 /* Check to see if USE_STMT is a mismatched deallocation
4197 call for the pointer passed to realloc. That's a bug
4198 regardless of the pointer's value and so warn. */
4199 if (maybe_warn_mismatched_realloc (*use_p
->use
, stmt
, use_stmt
))
4202 /* Pointers passed to realloc that are used in basic blocks
4203 where the realloc call is known to have failed are valid.
4204 Ignore pointers that nothing is known about. Those could
4205 have escaped along with their nullness. */
4207 if (m_ptr_qry
.rvals
->range_of_expr (vr
, realloc_lhs
, use_stmt
))
4212 if (!pointers_related_p (stmt
, ptr
, realloc_ptr
, m_ptr_qry
))
4218 && gimple_code (use_stmt
) == GIMPLE_RETURN
)
4219 /* Avoid interfering with -Wreturn-local-addr (which runs only
4220 with optimization enabled so it won't diagnose cases that
4221 would be caught here when optimization is disabled). */
4224 bool equality
= false;
4225 if (is_gimple_assign (use_stmt
))
4227 tree_code code
= gimple_assign_rhs_code (use_stmt
);
4228 equality
= code
== EQ_EXPR
|| code
== NE_EXPR
;
4230 else if (gcond
*cond
= dyn_cast
<gcond
*>(use_stmt
))
4232 tree_code code
= gimple_cond_code (cond
);
4233 equality
= code
== EQ_EXPR
|| code
== NE_EXPR
;
4235 else if (gphi
*phi
= dyn_cast
<gphi
*> (use_stmt
))
4237 /* Only add a PHI result to POINTERS if all its
4238 operands are related to PTR, otherwise continue. The
4239 PHI result is related once we've reached all arguments
4240 through this iteration. That also means any invariant
4241 argument will make the PHI not related. For arguments
4242 flowing over natural loop backedges we are optimistic
4243 (and diagnose the first iteration). */
4244 tree lhs
= gimple_phi_result (phi
);
4246 phi_map
= new hash_map
<tree
, int>;
4248 int &related
= phi_map
->get_or_insert (lhs
, &existed_p
);
4251 related
= gimple_phi_num_args (phi
) - 1;
4252 for (unsigned j
= 0; j
< gimple_phi_num_args (phi
); ++j
)
4254 if ((unsigned) phi_arg_index_from_use (use_p
) == j
)
4256 tree arg
= gimple_phi_arg_def (phi
, j
);
4257 edge e
= gimple_phi_arg_edge (phi
, j
);
4259 if (dominated_by_p (CDI_DOMINATORS
, e
->src
, e
->dest
)
4260 /* Make sure we are not forward visiting a
4261 backedge argument. */
4262 && (TREE_CODE (arg
) != SSA_NAME
4263 || (!SSA_NAME_IS_DEFAULT_DEF (arg
)
4265 = gimple_bb (SSA_NAME_DEF_STMT (arg
)))
4267 && !dominated_by_p (CDI_DOMINATORS
,
4276 pointers
.safe_push (lhs
);
4280 /* Warn if USE_STMT is dominated by the deallocation STMT.
4281 Otherwise, add the pointer to POINTERS so that the uses
4282 of any other pointers derived from it can be checked. */
4283 if (use_after_inval_p (stmt
, use_stmt
, check_dangling
))
4285 basic_block use_bb
= gimple_bb (use_stmt
);
4288 || !dominated_by_p (CDI_POST_DOMINATORS
, stmt_bb
, use_bb
));
4289 warn_invalid_pointer (*use_p
->use
, use_stmt
, stmt
, var
,
4290 this_maybe
, equality
);
4294 if (is_gimple_assign (use_stmt
))
4296 tree lhs
= gimple_assign_lhs (use_stmt
);
4297 if (TREE_CODE (lhs
) == SSA_NAME
)
4299 tree_code rhs_code
= gimple_assign_rhs_code (use_stmt
);
4300 if (rhs_code
== POINTER_PLUS_EXPR
|| rhs_code
== SSA_NAME
)
4301 pointers
.safe_push (lhs
);
4306 if (gcall
*call
= dyn_cast
<gcall
*>(use_stmt
))
4308 if (gimple_call_return_arg (call
) == ptr
)
4309 if (tree lhs
= gimple_call_lhs (call
))
4310 if (TREE_CODE (lhs
) == SSA_NAME
)
4311 pointers
.safe_push (lhs
);
4321 /* Check call STMT for invalid accesses. */
4324 pass_waccess::check_call (gcall
*stmt
)
4326 /* Skip special calls generated by the compiler. */
4327 if (gimple_call_from_thunk_p (stmt
))
4330 /* .ASAN_MARK doesn't access any vars, only modifies shadow memory. */
4331 if (gimple_call_internal_p (stmt
)
4332 && gimple_call_internal_fn (stmt
) == IFN_ASAN_MARK
)
4335 if (gimple_call_builtin_p (stmt
, BUILT_IN_NORMAL
))
4336 check_builtin (stmt
);
4338 if (tree callee
= gimple_call_fndecl (stmt
))
4340 /* Check for uses of the pointer passed to either a standard
4341 or a user-defined deallocation function. */
4342 unsigned argno
= fndecl_dealloc_argno (callee
);
4343 if (argno
< (unsigned) call_nargs (stmt
))
4345 tree arg
= call_arg (stmt
, argno
);
4346 if (TREE_CODE (arg
) == SSA_NAME
)
4347 check_pointer_uses (stmt
, arg
);
4351 check_call_access (stmt
);
4352 check_call_dangling (stmt
);
4354 if (m_early_checks_p
)
4357 maybe_check_dealloc_call (stmt
);
4358 check_nonstring_args (stmt
);
4361 /* Check non-call STMT for invalid accesses. */
4364 pass_waccess::check_stmt (gimple
*stmt
)
4366 if (m_check_dangling_p
4367 && gimple_clobber_p (stmt
, CLOBBER_STORAGE_END
))
4369 /* Ignore clobber statements in blocks with exceptional edges. */
4370 basic_block bb
= gimple_bb (stmt
);
4371 edge e
= EDGE_PRED (bb
, 0);
4372 if (e
->flags
& EDGE_EH
)
4375 tree var
= gimple_assign_lhs (stmt
);
4376 m_clobbers
.put (var
, stmt
);
4380 if (is_gimple_assign (stmt
))
4382 /* Clobbered unnamed temporaries such as compound literals can be
4383 revived. Check for an assignment to one and remove it from
4385 tree lhs
= gimple_assign_lhs (stmt
);
4386 while (handled_component_p (lhs
))
4387 lhs
= TREE_OPERAND (lhs
, 0);
4389 if (auto_var_p (lhs
))
4390 m_clobbers
.remove (lhs
);
4394 if (greturn
*ret
= dyn_cast
<greturn
*> (stmt
))
4396 if (optimize
&& flag_isolate_erroneous_paths_dereference
)
4397 /* Avoid interfering with -Wreturn-local-addr (which runs only
4398 with optimization enabled). */
4401 tree arg
= gimple_return_retval (ret
);
4402 if (!arg
|| TREE_CODE (arg
) != ADDR_EXPR
)
4405 arg
= TREE_OPERAND (arg
, 0);
4406 while (handled_component_p (arg
))
4407 arg
= TREE_OPERAND (arg
, 0);
4409 if (!auto_var_p (arg
))
4412 gimple
**pclobber
= m_clobbers
.get (arg
);
4416 if (!use_after_inval_p (*pclobber
, stmt
))
4419 warn_invalid_pointer (NULL_TREE
, stmt
, *pclobber
, arg
, false);
4423 /* Check basic block BB for invalid accesses. */
4426 pass_waccess::check_block (basic_block bb
)
4428 /* Iterate over statements, looking for function calls. */
4429 for (auto si
= gsi_start_bb (bb
); !gsi_end_p (si
);
4430 gsi_next_nondebug (&si
))
4432 gimple
*stmt
= gsi_stmt (si
);
4433 if (gcall
*call
= dyn_cast
<gcall
*> (stmt
))
4440 /* Return the argument that the call STMT to a built-in function returns
4441 (including with an offset) or null if it doesn't. */
4444 pass_waccess::gimple_call_return_arg (gcall
*call
)
4446 /* Check for attribute fn spec to see if the function returns one
4447 of its arguments. */
4448 attr_fnspec fnspec
= gimple_call_fnspec (call
);
4450 if (!fnspec
.returns_arg (&argno
))
4452 if (gimple_call_num_args (call
) < 1)
4455 if (!gimple_call_builtin_p (call
, BUILT_IN_NORMAL
))
4458 tree fndecl
= gimple_call_fndecl (call
);
4459 switch (DECL_FUNCTION_CODE (fndecl
))
4461 case BUILT_IN_MEMPCPY
:
4462 case BUILT_IN_MEMPCPY_CHK
:
4463 case BUILT_IN_MEMCHR
:
4464 case BUILT_IN_STRCHR
:
4465 case BUILT_IN_STRRCHR
:
4466 case BUILT_IN_STRSTR
:
4467 case BUILT_IN_STPCPY
:
4468 case BUILT_IN_STPCPY_CHK
:
4469 case BUILT_IN_STPNCPY
:
4470 case BUILT_IN_STPNCPY_CHK
:
4479 if (gimple_call_num_args (call
) <= argno
)
4482 return gimple_call_arg (call
, argno
);
4485 /* Check for and diagnose all uses of the dangling pointer VAR to the auto
4486 object DECL whose lifetime has ended. OBJREF is true when VAR denotes
4487 an access to a DECL that may have been clobbered. */
4490 pass_waccess::check_dangling_uses (tree var
, tree decl
, bool maybe
/* = false */,
4491 bool objref
/* = false */)
4493 if (!decl
|| !auto_var_p (decl
))
4496 gimple
**pclob
= m_clobbers
.get (decl
);
4502 check_pointer_uses (*pclob
, var
, decl
, maybe
);
4506 gimple
*use_stmt
= SSA_NAME_DEF_STMT (var
);
4507 if (!use_after_inval_p (*pclob
, use_stmt
, true))
4510 basic_block use_bb
= gimple_bb (use_stmt
);
4511 basic_block clob_bb
= gimple_bb (*pclob
);
4512 maybe
= maybe
|| !dominated_by_p (CDI_POST_DOMINATORS
, clob_bb
, use_bb
);
4513 warn_invalid_pointer (var
, use_stmt
, *pclob
, decl
, maybe
, false);
4516 /* Diagnose stores in BB and (recursively) its predecessors of the addresses
4517 of local variables into nonlocal pointers that are left dangling after
4518 the function returns. Returns true when we can continue walking
4519 the CFG to predecessors. */
4522 pass_waccess::check_dangling_stores (basic_block bb
,
4523 hash_set
<tree
> &stores
)
4525 /* Iterate backwards over the statements looking for a store of
4526 the address of a local variable into a nonlocal pointer. */
4527 for (auto gsi
= gsi_last_nondebug_bb (bb
); ; gsi_prev_nondebug (&gsi
))
4529 gimple
*stmt
= gsi_stmt (gsi
);
4533 if (warning_suppressed_p (stmt
, OPT_Wdangling_pointer_
))
4536 if (is_gimple_call (stmt
)
4537 && !(gimple_call_flags (stmt
) & (ECF_CONST
| ECF_PURE
)))
4538 /* Avoid looking before nonconst, nonpure calls since those might
4539 use the escaped locals. */
4542 if (!is_gimple_assign (stmt
) || gimple_clobber_p (stmt
)
4543 || !gimple_store_p (stmt
))
4547 tree lhs
= gimple_assign_lhs (stmt
);
4548 if (!m_ptr_qry
.get_ref (lhs
, stmt
, &lhs_ref
, 0))
4551 if (TREE_CODE (lhs_ref
.ref
) == MEM_REF
)
4553 lhs_ref
.ref
= TREE_OPERAND (lhs_ref
.ref
, 0);
4556 if (TREE_CODE (lhs_ref
.ref
) == ADDR_EXPR
)
4558 lhs_ref
.ref
= TREE_OPERAND (lhs_ref
.ref
, 0);
4561 if (TREE_CODE (lhs_ref
.ref
) == SSA_NAME
)
4563 gimple
*def_stmt
= SSA_NAME_DEF_STMT (lhs_ref
.ref
);
4564 if (!gimple_nop_p (def_stmt
))
4565 /* Avoid looking at or before stores into unknown objects. */
4568 lhs_ref
.ref
= SSA_NAME_VAR (lhs_ref
.ref
);
4571 if (TREE_CODE (lhs_ref
.ref
) == PARM_DECL
4572 && (lhs_ref
.deref
- DECL_BY_REFERENCE (lhs_ref
.ref
)) > 0)
4573 /* Assignment through a (real) pointer/reference parameter. */;
4574 else if (VAR_P (lhs_ref
.ref
)
4575 && !auto_var_p (lhs_ref
.ref
))
4576 /* Assignment to/through a non-local variable. */;
4578 /* Something else, don't warn. */
4581 if (stores
.add (lhs_ref
.ref
))
4584 /* FIXME: Handle stores of alloca() and VLA. */
4586 tree rhs
= gimple_assign_rhs1 (stmt
);
4587 if (!m_ptr_qry
.get_ref (rhs
, stmt
, &rhs_ref
, 0)
4588 || rhs_ref
.deref
!= -1)
4591 if (!auto_var_p (rhs_ref
.ref
))
4594 auto_diagnostic_group d
;
4595 location_t loc
= gimple_location (stmt
);
4596 if (warning_at (loc
, OPT_Wdangling_pointer_
,
4597 "storing the address of local variable %qD in %qE",
4600 suppress_warning (stmt
, OPT_Wdangling_pointer_
);
4602 location_t loc
= DECL_SOURCE_LOCATION (rhs_ref
.ref
);
4603 inform (loc
, "%qD declared here", rhs_ref
.ref
);
4605 loc
= DECL_SOURCE_LOCATION (lhs_ref
.ref
);
4606 inform (loc
, "%qD declared here", lhs_ref
.ref
);
4613 /* Diagnose stores of the addresses of local variables into nonlocal
4614 pointers that are left dangling after the function returns. */
4617 pass_waccess::check_dangling_stores ()
4619 if (EDGE_COUNT (EXIT_BLOCK_PTR_FOR_FN (m_func
)->preds
) == 0)
4623 hash_set
<tree
> stores
;
4624 auto_vec
<edge_iterator
, 8> worklist (n_basic_blocks_for_fn (cfun
) + 1);
4625 worklist
.quick_push (ei_start (EXIT_BLOCK_PTR_FOR_FN (m_func
)->preds
));
4628 edge_iterator ei
= worklist
.last ();
4629 basic_block src
= ei_edge (ei
)->src
;
4630 if (bitmap_set_bit (bbs
, src
->index
))
4632 if (check_dangling_stores (src
, stores
)
4633 && EDGE_COUNT (src
->preds
) > 0)
4634 worklist
.quick_push (ei_start (src
->preds
));
4638 if (ei_one_before_end_p (ei
))
4641 ei_next (&worklist
.last ());
4644 while (!worklist
.is_empty ());
4647 /* Check for and diagnose uses of dangling pointers to auto objects
4648 whose lifetime has ended. */
4651 pass_waccess::check_dangling_uses ()
4655 FOR_EACH_SSA_NAME (i
, var
, m_func
)
4657 /* For each SSA_NAME pointer VAR find the object it points to.
4658 If the object is a clobbered local variable, check to see
4659 if any of VAR's uses (or those of other pointers derived
4660 from VAR) happens after the clobber. If so, warn. */
4662 gimple
*def_stmt
= SSA_NAME_DEF_STMT (var
);
4663 if (is_gimple_assign (def_stmt
))
4665 tree rhs
= gimple_assign_rhs1 (def_stmt
);
4666 if (TREE_CODE (rhs
) == ADDR_EXPR
)
4668 if (!POINTER_TYPE_P (TREE_TYPE (var
)))
4670 check_dangling_uses (var
, TREE_OPERAND (rhs
, 0));
4674 /* For other expressions, check the base DECL to see
4675 if it's been clobbered, most likely as a result of
4676 inlining a reference to it. */
4677 tree decl
= get_base_address (rhs
);
4679 check_dangling_uses (var
, decl
, false, true);
4682 else if (POINTER_TYPE_P (TREE_TYPE (var
)))
4684 if (gcall
*call
= dyn_cast
<gcall
*>(def_stmt
))
4686 if (tree arg
= gimple_call_return_arg (call
))
4689 if (m_ptr_qry
.get_ref (arg
, call
, &aref
, 0)
4691 check_dangling_uses (var
, aref
.ref
);
4694 else if (gphi
*phi
= dyn_cast
<gphi
*>(def_stmt
))
4696 unsigned nargs
= gimple_phi_num_args (phi
);
4697 for (unsigned i
= 0; i
!= nargs
; ++i
)
4700 tree arg
= gimple_phi_arg_def (phi
, i
);
4701 if (m_ptr_qry
.get_ref (arg
, phi
, &aref
, 0)
4703 check_dangling_uses (var
, aref
.ref
, true);
4710 /* Check CALL arguments for dangling pointers (those that have been
4711 clobbered) and warn if found. */
4714 pass_waccess::check_call_dangling (gcall
*call
)
4716 unsigned nargs
= gimple_call_num_args (call
);
4717 for (unsigned i
= 0; i
!= nargs
; ++i
)
4719 tree arg
= gimple_call_arg (call
, i
);
4720 if (TREE_CODE (arg
) != ADDR_EXPR
)
4723 arg
= TREE_OPERAND (arg
, 0);
4727 gimple
**pclobber
= m_clobbers
.get (arg
);
4731 if (!use_after_inval_p (*pclobber
, call
))
4734 warn_invalid_pointer (NULL_TREE
, call
, *pclobber
, arg
, false);
4738 /* Check function FUN for invalid accesses. */
4741 pass_waccess::execute (function
*fun
)
4743 calculate_dominance_info (CDI_DOMINATORS
);
4744 calculate_dominance_info (CDI_POST_DOMINATORS
);
4746 /* Set or clear EDGE_DFS_BACK bits on back edges. */
4747 mark_dfs_back_edges (fun
);
4749 /* Create a new ranger instance and associate it with FUN. */
4750 m_ptr_qry
.rvals
= enable_ranger (fun
);
4753 /* Check for dangling pointers in the earliest run of the pass.
4754 The latest point -Wdangling-pointer should run is just before
4755 loop unrolling which introduces uses after clobbers. Most cases
4756 can be detected without optimization; cases where the address of
4757 the local variable is passed to and then returned from a user-
4758 defined function before its lifetime ends and the returned pointer
4759 becomes dangling depend on inlining. */
4760 m_check_dangling_p
= m_early_checks_p
;
4762 auto_bitmap
bb_uids_set (&bitmap_default_obstack
);
4763 m_bb_uids_set
= bb_uids_set
;
4765 set_gimple_stmt_max_uid (m_func
, 0);
4768 FOR_EACH_BB_FN (bb
, fun
)
4771 if (m_check_dangling_p
)
4773 check_dangling_uses ();
4774 check_dangling_stores ();
4778 m_ptr_qry
.dump (dump_file
, (dump_flags
& TDF_DETAILS
) != 0);
4780 m_ptr_qry
.flush_cache ();
4782 /* Release the ranger instance and replace it with a global ranger.
4783 Also reset the pointer since calling disable_ranger() deletes it. */
4784 disable_ranger (fun
);
4785 m_ptr_qry
.rvals
= NULL
;
4787 m_clobbers
.empty ();
4788 m_bb_uids_set
= NULL
;
4790 free_dominance_info (CDI_POST_DOMINATORS
);
4791 free_dominance_info (CDI_DOMINATORS
);
4797 /* Return a new instance of the pass. */
4800 make_pass_warn_access (gcc::context
*ctxt
)
4802 return new pass_waccess (ctxt
);