1 /* Pass to detect and issue warnings for invalid accesses, including
2 invalid or mismatched allocation/deallocation calls.
4 Copyright (C) 2020-2022 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-fold.h"
40 #include "gimple-iterator.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 nuber 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 const tree maxobjsize
= max_object_size ();
164 const wide_int maxsiz
= wi::to_wide (maxobjsize
);
167 tree func
= get_callee_fndecl (expr
);
170 if (wi::ltu_p (maxsiz
, bndrng
[0]))
171 warned
= warning_at (loc
, opt
,
172 "%qD specified bound %s exceeds "
173 "maximum object size %E",
174 func
, bndstr
, maxobjsize
);
177 bool maybe
= wi::to_wide (size
) == bndrng
[0];
178 warned
= warning_at (loc
, opt
,
180 ? G_("%qD specified bound %s exceeds "
181 "the size %E of unterminated array")
183 ? G_("%qD specified bound %s may "
184 "exceed the size of at most %E "
185 "of unterminated array")
186 : G_("%qD specified bound %s exceeds "
187 "the size of at most %E "
188 "of unterminated array")),
193 warned
= warning_at (loc
, opt
,
194 "%qD argument missing terminating nul",
201 if (wi::ltu_p (maxsiz
, bndrng
[0]))
202 warned
= warning_at (loc
, opt
,
203 "%qs specified bound %s exceeds "
204 "maximum object size %E",
205 fname
, bndstr
, maxobjsize
);
208 bool maybe
= wi::to_wide (size
) == bndrng
[0];
209 warned
= warning_at (loc
, opt
,
211 ? G_("%qs specified bound %s exceeds "
212 "the size %E of unterminated array")
214 ? G_("%qs specified bound %s may "
215 "exceed the size of at most %E "
216 "of unterminated array")
217 : G_("%qs specified bound %s exceeds "
218 "the size of at most %E "
219 "of unterminated array")),
220 fname
, bndstr
, size
);
224 warned
= warning_at (loc
, opt
,
225 "%qs argument missing terminating nul",
231 inform (get_location (decl
),
232 "referenced argument declared here");
233 suppress_warning (arg
, opt
);
235 suppress_warning (expr
, opt
);
240 warn_string_no_nul (location_t loc
, gimple
*stmt
, const char *fname
,
241 tree arg
, tree decl
, tree size
/* = NULL_TREE */,
242 bool exact
/* = false */,
243 const wide_int bndrng
[2] /* = NULL */)
245 return warn_string_no_nul
<gimple
*> (loc
, stmt
, fname
,
246 arg
, decl
, size
, exact
, bndrng
);
250 warn_string_no_nul (location_t loc
, tree expr
, const char *fname
,
251 tree arg
, tree decl
, tree size
/* = NULL_TREE */,
252 bool exact
/* = false */,
253 const wide_int bndrng
[2] /* = NULL */)
255 return warn_string_no_nul
<tree
> (loc
, expr
, fname
,
256 arg
, decl
, size
, exact
, bndrng
);
259 /* If EXP refers to an unterminated constant character array return
260 the declaration of the object of which the array is a member or
261 element and if SIZE is not null, set *SIZE to the size of
262 the unterminated array and set *EXACT if the size is exact or
263 clear it otherwise. Otherwise return null. */
266 unterminated_array (tree exp
, tree
*size
/* = NULL */, bool *exact
/* = NULL */)
268 /* C_STRLEN will return NULL and set DECL in the info
269 structure if EXP references a unterminated array. */
270 c_strlen_data lendata
= { };
271 tree len
= c_strlen (exp
, 1, &lendata
);
272 if (len
|| !lendata
.minlen
|| !lendata
.decl
)
278 len
= lendata
.minlen
;
281 /* Constant offsets are already accounted for in LENDATA.MINLEN,
282 but not in a SSA_NAME + CST expression. */
283 if (TREE_CODE (lendata
.off
) == INTEGER_CST
)
285 else if (TREE_CODE (lendata
.off
) == PLUS_EXPR
286 && TREE_CODE (TREE_OPERAND (lendata
.off
, 1)) == INTEGER_CST
)
288 /* Subtract the offset from the size of the array. */
290 tree temp
= TREE_OPERAND (lendata
.off
, 1);
291 temp
= fold_convert (ssizetype
, temp
);
292 len
= fold_build2 (MINUS_EXPR
, ssizetype
, len
, temp
);
304 /* For a call EXPR (which may be null) that expects a string argument
305 SRC as an argument, returns false if SRC is a character array with
306 no terminating NUL. When nonnull, BOUND is the number of characters
307 in which to expect the terminating NUL. When EXPR is nonnull also
310 template <class GimpleOrTree
>
312 check_nul_terminated_array (GimpleOrTree expr
, tree src
, tree bound
)
314 /* The constant size of the array SRC points to. The actual size
315 may be less of EXACT is true, but not more. */
317 /* True if SRC involves a non-constant offset into the array. */
319 /* The unterminated constant array SRC points to. */
320 tree nonstr
= unterminated_array (src
, &size
, &exact
);
324 /* NONSTR refers to the non-nul terminated constant array and SIZE
325 is the constant size of the array in bytes. EXACT is true when
333 get_global_range_query ()->range_of_expr (r
, bound
);
335 if (r
.kind () != VR_RANGE
)
338 bndrng
[0] = r
.lower_bound ();
339 bndrng
[1] = r
.upper_bound ();
343 if (wi::leu_p (bndrng
[0], wi::to_wide (size
)))
346 else if (wi::lt_p (bndrng
[0], wi::to_wide (size
), UNSIGNED
))
351 warn_string_no_nul (get_location (expr
), expr
, NULL
, src
, nonstr
,
352 size
, exact
, bound
? bndrng
: NULL
);
358 check_nul_terminated_array (gimple
*stmt
, tree src
, tree bound
/* = NULL_TREE */)
360 return check_nul_terminated_array
<gimple
*>(stmt
, src
, bound
);
364 check_nul_terminated_array (tree expr
, tree src
, tree bound
/* = NULL_TREE */)
366 return check_nul_terminated_array
<tree
>(expr
, src
, bound
);
369 /* Warn about passing a non-string array/pointer to a built-in function
370 that expects a nul-terminated string argument. Returns true if
371 a warning has been issued.*/
373 template <class GimpleOrTree
>
375 maybe_warn_nonstring_arg (tree fndecl
, GimpleOrTree exp
)
377 if (!fndecl
|| !fndecl_built_in_p (fndecl
, BUILT_IN_NORMAL
))
380 if (!warn_stringop_overread
381 || warning_suppressed_p (exp
, OPT_Wstringop_overread
))
384 /* Avoid clearly invalid calls (more checking done below). */
385 unsigned nargs
= call_nargs (exp
);
389 /* The bound argument to a bounded string function like strncpy. */
390 tree bound
= NULL_TREE
;
392 /* The longest known or possible string argument to one of the comparison
393 functions. If the length is less than the bound it is used instead.
394 Since the length is only used for warning and not for code generation
395 disable strict mode in the calls to get_range_strlen below. */
396 tree maxlen
= NULL_TREE
;
398 /* It's safe to call "bounded" string functions with a non-string
399 argument since the functions provide an explicit bound for this
400 purpose. The exception is strncat where the bound may refer to
401 either the destination or the source. */
402 int fncode
= DECL_FUNCTION_CODE (fndecl
);
405 case BUILT_IN_STRCMP
:
406 case BUILT_IN_STRNCMP
:
407 case BUILT_IN_STRNCASECMP
:
409 /* For these, if one argument refers to one or more of a set
410 of string constants or arrays of known size, determine
411 the range of their known or possible lengths and use it
412 conservatively as the bound for the unbounded function,
413 and to adjust the range of the bound of the bounded ones. */
414 for (unsigned argno
= 0;
415 argno
< MIN (nargs
, 2)
416 && !(maxlen
&& TREE_CODE (maxlen
) == INTEGER_CST
); argno
++)
418 tree arg
= call_arg (exp
, argno
);
419 if (!get_attr_nonstring_decl (arg
))
421 c_strlen_data lendata
= { };
422 /* Set MAXBOUND to an arbitrary non-null non-integer
423 node as a request to have it set to the length of
424 the longest string in a PHI. */
425 lendata
.maxbound
= arg
;
426 get_range_strlen (arg
, &lendata
, /* eltsize = */ 1);
427 maxlen
= lendata
.maxbound
;
433 case BUILT_IN_STRNCAT
:
434 case BUILT_IN_STPNCPY
:
435 case BUILT_IN_STRNCPY
:
437 bound
= call_arg (exp
, 2);
440 case BUILT_IN_STRNDUP
:
443 bound
= call_arg (exp
, 1);
446 case BUILT_IN_STRNLEN
:
448 tree arg
= call_arg (exp
, 0);
449 if (!get_attr_nonstring_decl (arg
))
451 c_strlen_data lendata
= { };
452 /* Set MAXBOUND to an arbitrary non-null non-integer
453 node as a request to have it set to the length of
454 the longest string in a PHI. */
455 lendata
.maxbound
= arg
;
456 get_range_strlen (arg
, &lendata
, /* eltsize = */ 1);
457 maxlen
= lendata
.maxbound
;
460 bound
= call_arg (exp
, 1);
468 /* Determine the range of the bound argument (if specified). */
469 tree bndrng
[2] = { NULL_TREE
, NULL_TREE
};
473 get_size_range (bound
, bndrng
);
476 location_t loc
= get_location (exp
);
480 /* Diagnose excessive bound prior to the adjustment below and
481 regardless of attribute nonstring. */
482 tree maxobjsize
= max_object_size ();
483 if (tree_int_cst_lt (maxobjsize
, bndrng
[0]))
486 if (tree_int_cst_equal (bndrng
[0], bndrng
[1]))
487 warned
= warning_at (loc
, OPT_Wstringop_overread
,
488 "%qD specified bound %E "
489 "exceeds maximum object size %E",
490 fndecl
, bndrng
[0], maxobjsize
);
492 warned
= warning_at (loc
, OPT_Wstringop_overread
,
493 "%qD specified bound [%E, %E] "
494 "exceeds maximum object size %E",
495 fndecl
, bndrng
[0], bndrng
[1],
498 suppress_warning (exp
, OPT_Wstringop_overread
);
504 if (maxlen
&& !integer_all_onesp (maxlen
))
506 /* Add one for the nul. */
507 maxlen
= const_binop (PLUS_EXPR
, TREE_TYPE (maxlen
), maxlen
,
512 /* Conservatively use the upper bound of the lengths for
513 both the lower and the upper bound of the operation. */
516 bound
= void_type_node
;
520 /* Replace the bound on the operation with the upper bound
521 of the length of the string if the latter is smaller. */
522 if (tree_int_cst_lt (maxlen
, bndrng
[0]))
524 else if (tree_int_cst_lt (maxlen
, bndrng
[1]))
529 bool any_arg_warned
= false;
530 /* Iterate over the built-in function's formal arguments and check
531 each const char* against the actual argument. If the actual
532 argument is declared attribute non-string issue a warning unless
533 the argument's maximum length is bounded. */
534 function_args_iterator it
;
535 function_args_iter_init (&it
, TREE_TYPE (fndecl
));
537 for (unsigned argno
= 0; ; ++argno
, function_args_iter_next (&it
))
539 /* Avoid iterating past the declared argument in a call
540 to function declared without a prototype. */
544 tree argtype
= function_args_iter_cond (&it
);
548 if (TREE_CODE (argtype
) != POINTER_TYPE
)
551 argtype
= TREE_TYPE (argtype
);
553 if (TREE_CODE (argtype
) != INTEGER_TYPE
554 || !TYPE_READONLY (argtype
))
557 argtype
= TYPE_MAIN_VARIANT (argtype
);
558 if (argtype
!= char_type_node
)
561 tree callarg
= call_arg (exp
, argno
);
562 if (TREE_CODE (callarg
) == ADDR_EXPR
)
563 callarg
= TREE_OPERAND (callarg
, 0);
565 /* See if the destination is declared with attribute "nonstring". */
566 tree decl
= get_attr_nonstring_decl (callarg
);
570 /* The maximum number of array elements accessed. */
571 offset_int wibnd
= 0;
573 if (argno
&& fncode
== BUILT_IN_STRNCAT
)
575 /* See if the bound in strncat is derived from the length
576 of the strlen of the destination (as it's expected to be).
577 If so, reset BOUND and FNCODE to trigger a warning. */
578 tree dstarg
= call_arg (exp
, 0);
579 if (is_strlen_related_p (dstarg
, bound
))
581 /* The bound applies to the destination, not to the source,
582 so reset these to trigger a warning without mentioning
588 /* Use the upper bound of the range for strncat. */
589 wibnd
= wi::to_offset (bndrng
[1]);
592 /* Use the lower bound of the range for functions other than
594 wibnd
= wi::to_offset (bndrng
[0]);
596 /* Determine the size of the argument array if it is one. */
597 offset_int asize
= wibnd
;
598 bool known_size
= false;
599 tree type
= TREE_TYPE (decl
);
601 /* Determine the array size. For arrays of unknown bound and
602 pointers reset BOUND to trigger the appropriate warning. */
603 if (TREE_CODE (type
) == ARRAY_TYPE
)
605 if (tree arrbnd
= TYPE_DOMAIN (type
))
607 if ((arrbnd
= TYPE_MAX_VALUE (arrbnd
)))
609 asize
= wi::to_offset (arrbnd
) + 1;
613 else if (bound
== void_type_node
)
616 else if (bound
== void_type_node
)
619 /* In a call to strncat with a bound in a range whose lower but
620 not upper bound is less than the array size, reset ASIZE to
621 be the same as the bound and the other variable to trigger
622 the apprpriate warning below. */
623 if (fncode
== BUILT_IN_STRNCAT
624 && bndrng
[0] != bndrng
[1]
625 && wi::ltu_p (wi::to_offset (bndrng
[0]), asize
)
627 || wi::ltu_p (asize
, wibnd
)))
636 auto_diagnostic_group d
;
637 if (wi::ltu_p (asize
, wibnd
))
639 if (bndrng
[0] == bndrng
[1])
640 warned
= warning_at (loc
, OPT_Wstringop_overread
,
641 "%qD argument %i declared attribute "
642 "%<nonstring%> is smaller than the specified "
644 fndecl
, argno
+ 1, wibnd
.to_uhwi ());
645 else if (wi::ltu_p (asize
, wi::to_offset (bndrng
[0])))
646 warned
= warning_at (loc
, OPT_Wstringop_overread
,
647 "%qD argument %i declared attribute "
648 "%<nonstring%> is smaller than "
649 "the specified bound [%E, %E]",
650 fndecl
, argno
+ 1, bndrng
[0], bndrng
[1]);
652 warned
= warning_at (loc
, OPT_Wstringop_overread
,
653 "%qD argument %i declared attribute "
654 "%<nonstring%> may be smaller than "
655 "the specified bound [%E, %E]",
656 fndecl
, argno
+ 1, bndrng
[0], bndrng
[1]);
658 else if (fncode
== BUILT_IN_STRNCAT
)
659 ; /* Avoid warning for calls to strncat() when the bound
660 is equal to the size of the non-string argument. */
662 warned
= warning_at (loc
, OPT_Wstringop_overread
,
663 "%qD argument %i declared attribute %<nonstring%>",
668 inform (DECL_SOURCE_LOCATION (decl
),
669 "argument %qD declared here", decl
);
670 any_arg_warned
= true;
675 suppress_warning (exp
, OPT_Wstringop_overread
);
677 return any_arg_warned
;
681 maybe_warn_nonstring_arg (tree fndecl
, gimple
*stmt
)
683 return maybe_warn_nonstring_arg
<gimple
*>(fndecl
, stmt
);
688 maybe_warn_nonstring_arg (tree fndecl
, tree expr
)
690 return maybe_warn_nonstring_arg
<tree
>(fndecl
, expr
);
693 /* Issue a warning OPT for a bounded call EXP with a bound in RANGE
694 accessing an object with SIZE. */
696 template <class GimpleOrTree
>
698 maybe_warn_for_bound (opt_code opt
, location_t loc
, GimpleOrTree exp
, tree func
,
699 tree bndrng
[2], tree size
, const access_data
*pad
)
701 if (!bndrng
[0] || warning_suppressed_p (exp
, opt
))
704 tree maxobjsize
= max_object_size ();
708 if (opt
== OPT_Wstringop_overread
)
710 bool maybe
= pad
&& pad
->src
.phi ();
713 /* Issue a "maybe" warning only if the PHI refers to objects
714 at least one of which has more space remaining than the bound.
715 Otherwise, if the bound is greater, use the definitive form. */
716 offset_int remmax
= pad
->src
.size_remaining ();
717 if (remmax
< wi::to_offset (bndrng
[0]))
721 if (tree_int_cst_lt (maxobjsize
, bndrng
[0]))
723 if (bndrng
[0] == bndrng
[1])
725 ? warning_at (loc
, opt
,
727 ? G_("%qD specified bound %E may "
728 "exceed maximum object size %E")
729 : G_("%qD specified bound %E "
730 "exceeds maximum object size %E")),
731 func
, bndrng
[0], maxobjsize
)
732 : warning_at (loc
, opt
,
734 ? G_("specified bound %E may "
735 "exceed maximum object size %E")
736 : G_("specified bound %E "
737 "exceeds maximum object size %E")),
738 bndrng
[0], maxobjsize
));
741 ? warning_at (loc
, opt
,
743 ? G_("%qD specified bound [%E, %E] may "
744 "exceed maximum object size %E")
745 : G_("%qD specified bound [%E, %E] "
746 "exceeds maximum object size %E")),
748 bndrng
[0], bndrng
[1], maxobjsize
)
749 : warning_at (loc
, opt
,
751 ? G_("specified bound [%E, %E] may "
752 "exceed maximum object size %E")
753 : G_("specified bound [%E, %E] "
754 "exceeds maximum object size %E")),
755 bndrng
[0], bndrng
[1], maxobjsize
));
757 else if (!size
|| tree_int_cst_le (bndrng
[0], size
))
759 else if (tree_int_cst_equal (bndrng
[0], bndrng
[1]))
761 ? warning_at (loc
, opt
,
763 ? G_("%qD specified bound %E may exceed "
765 : G_("%qD specified bound %E exceeds "
767 func
, bndrng
[0], size
)
768 : warning_at (loc
, opt
,
770 ? G_("specified bound %E may exceed "
772 : G_("specified bound %E exceeds "
777 ? warning_at (loc
, opt
,
779 ? G_("%qD specified bound [%E, %E] may "
780 "exceed source size %E")
781 : G_("%qD specified bound [%E, %E] exceeds "
783 func
, bndrng
[0], bndrng
[1], size
)
784 : warning_at (loc
, opt
,
786 ? G_("specified bound [%E, %E] may exceed "
788 : G_("specified bound [%E, %E] exceeds "
790 bndrng
[0], bndrng
[1], size
));
793 if (pad
&& pad
->src
.ref
794 && has_location (pad
->src
.ref
))
795 inform (get_location (pad
->src
.ref
),
796 "source object allocated here");
797 suppress_warning (exp
, opt
);
803 bool maybe
= pad
&& pad
->dst
.phi ();
806 /* Issue a "maybe" warning only if the PHI refers to objects
807 at least one of which has more space remaining than the bound.
808 Otherwise, if the bound is greater, use the definitive form. */
809 offset_int remmax
= pad
->dst
.size_remaining ();
810 if (remmax
< wi::to_offset (bndrng
[0]))
813 if (tree_int_cst_lt (maxobjsize
, bndrng
[0]))
815 if (bndrng
[0] == bndrng
[1])
817 ? warning_at (loc
, opt
,
819 ? G_("%qD specified size %E may "
820 "exceed maximum object size %E")
821 : G_("%qD specified size %E "
822 "exceeds maximum object size %E")),
823 func
, bndrng
[0], maxobjsize
)
824 : warning_at (loc
, opt
,
826 ? G_("specified size %E may exceed "
827 "maximum object size %E")
828 : G_("specified size %E exceeds "
829 "maximum object size %E")),
830 bndrng
[0], maxobjsize
));
833 ? warning_at (loc
, opt
,
835 ? G_("%qD specified size between %E and %E "
836 "may exceed maximum object size %E")
837 : G_("%qD specified size between %E and %E "
838 "exceeds maximum object size %E")),
839 func
, bndrng
[0], bndrng
[1], maxobjsize
)
840 : warning_at (loc
, opt
,
842 ? G_("specified size between %E and %E "
843 "may exceed maximum object size %E")
844 : G_("specified size between %E and %E "
845 "exceeds maximum object size %E")),
846 bndrng
[0], bndrng
[1], maxobjsize
));
848 else if (!size
|| tree_int_cst_le (bndrng
[0], size
))
850 else if (tree_int_cst_equal (bndrng
[0], bndrng
[1]))
852 ? warning_at (loc
, opt
,
854 ? G_("%qD specified bound %E may exceed "
855 "destination size %E")
856 : G_("%qD specified bound %E exceeds "
857 "destination size %E")),
858 func
, bndrng
[0], size
)
859 : warning_at (loc
, opt
,
861 ? G_("specified bound %E may exceed "
862 "destination size %E")
863 : G_("specified bound %E exceeds "
864 "destination size %E")),
868 ? warning_at (loc
, opt
,
870 ? G_("%qD specified bound [%E, %E] may exceed "
871 "destination size %E")
872 : G_("%qD specified bound [%E, %E] exceeds "
873 "destination size %E")),
874 func
, bndrng
[0], bndrng
[1], size
)
875 : warning_at (loc
, opt
,
877 ? G_("specified bound [%E, %E] exceeds "
878 "destination size %E")
879 : G_("specified bound [%E, %E] exceeds "
880 "destination size %E")),
881 bndrng
[0], bndrng
[1], size
));
885 if (pad
&& pad
->dst
.ref
886 && has_location (pad
->dst
.ref
))
887 inform (get_location (pad
->dst
.ref
),
888 "destination object allocated here");
889 suppress_warning (exp
, opt
);
896 maybe_warn_for_bound (opt_code opt
, location_t loc
, gimple
*stmt
, tree func
,
897 tree bndrng
[2], tree size
,
898 const access_data
*pad
/* = NULL */)
900 return maybe_warn_for_bound
<gimple
*> (opt
, loc
, stmt
, func
, bndrng
, size
,
905 maybe_warn_for_bound (opt_code opt
, location_t loc
, tree expr
, tree func
,
906 tree bndrng
[2], tree size
,
907 const access_data
*pad
/* = NULL */)
909 return maybe_warn_for_bound
<tree
> (opt
, loc
, expr
, func
, bndrng
, size
, pad
);
912 /* For an expression EXP issue an access warning controlled by option OPT
913 with access to a region SIZE bytes in size in the RANGE of sizes.
914 WRITE is true for a write access, READ for a read access, neither for
915 call that may or may not perform an access but for which the range
916 is expected to valid.
917 Returns true when a warning has been issued. */
919 template <class GimpleOrTree
>
921 warn_for_access (location_t loc
, tree func
, GimpleOrTree exp
, int opt
,
922 tree range
[2], tree size
, bool write
, bool read
, bool maybe
)
928 if (tree_int_cst_equal (range
[0], range
[1]))
930 ? warning_n (loc
, opt
, tree_to_uhwi (range
[0]),
932 ? G_("%qD may access %E byte in a region "
934 : G_("%qD accessing %E byte in a region "
937 ? G_ ("%qD may access %E bytes in a region "
939 : G_ ("%qD accessing %E bytes in a region "
941 func
, range
[0], size
)
942 : warning_n (loc
, opt
, tree_to_uhwi (range
[0]),
944 ? G_("may access %E byte in a region "
946 : G_("accessing %E byte in a region "
949 ? G_("may access %E bytes in a region "
951 : G_("accessing %E bytes in a region "
954 else if (tree_int_cst_sign_bit (range
[1]))
956 /* Avoid printing the upper bound if it's invalid. */
958 ? warning_at (loc
, opt
,
960 ? G_("%qD may access %E or more bytes "
961 "in a region of size %E")
962 : G_("%qD accessing %E or more bytes "
963 "in a region of size %E")),
964 func
, range
[0], size
)
965 : warning_at (loc
, opt
,
967 ? G_("may access %E or more bytes "
968 "in a region of size %E")
969 : G_("accessing %E or more bytes "
970 "in a region of size %E")),
975 ? warning_at (loc
, opt
,
977 ? G_("%qD may access between %E and %E "
978 "bytes in a region of size %E")
979 : G_("%qD accessing between %E and %E "
980 "bytes in a region of size %E")),
981 func
, range
[0], range
[1], size
)
982 : warning_at (loc
, opt
,
984 ? G_("may access between %E and %E bytes "
985 "in a region of size %E")
986 : G_("accessing between %E and %E bytes "
987 "in a region of size %E")),
988 range
[0], range
[1], size
));
994 if (tree_int_cst_equal (range
[0], range
[1]))
996 ? warning_n (loc
, opt
, tree_to_uhwi (range
[0]),
998 ? G_("%qD may write %E byte into a region "
1000 : G_("%qD writing %E byte into a region "
1001 "of size %E overflows the destination")),
1003 ? G_("%qD may write %E bytes into a region "
1005 : G_("%qD writing %E bytes into a region "
1006 "of size %E overflows the destination")),
1007 func
, range
[0], size
)
1008 : warning_n (loc
, opt
, tree_to_uhwi (range
[0]),
1010 ? G_("may write %E byte into a region "
1012 : G_("writing %E byte into a region "
1013 "of size %E overflows the destination")),
1015 ? G_("may write %E bytes into a region "
1017 : G_("writing %E bytes into a region "
1018 "of size %E overflows the destination")),
1020 else if (tree_int_cst_sign_bit (range
[1]))
1022 /* Avoid printing the upper bound if it's invalid. */
1024 ? warning_at (loc
, opt
,
1026 ? G_("%qD may write %E or more bytes "
1027 "into a region of size %E")
1028 : G_("%qD writing %E or more bytes "
1029 "into a region of size %E overflows "
1030 "the destination")),
1031 func
, range
[0], size
)
1032 : warning_at (loc
, opt
,
1034 ? G_("may write %E or more bytes into "
1035 "a region of size %E")
1036 : G_("writing %E or more bytes into "
1037 "a region of size %E overflows "
1038 "the destination")),
1043 ? warning_at (loc
, opt
,
1045 ? G_("%qD may write between %E and %E bytes "
1046 "into a region of size %E")
1047 : G_("%qD writing between %E and %E bytes "
1048 "into a region of size %E overflows "
1049 "the destination")),
1050 func
, range
[0], range
[1], size
)
1051 : warning_at (loc
, opt
,
1053 ? G_("may write between %E and %E bytes "
1054 "into a region of size %E")
1055 : G_("writing between %E and %E bytes "
1056 "into a region of size %E overflows "
1057 "the destination")),
1058 range
[0], range
[1], size
));
1064 if (tree_int_cst_equal (range
[0], range
[1]))
1066 ? warning_n (loc
, OPT_Wstringop_overread
,
1067 tree_to_uhwi (range
[0]),
1069 ? G_("%qD may read %E byte from a region "
1071 : G_("%qD reading %E byte from a region "
1074 ? G_("%qD may read %E bytes from a region "
1076 : G_("%qD reading %E bytes from a region "
1078 func
, range
[0], size
)
1079 : warning_n (loc
, OPT_Wstringop_overread
,
1080 tree_to_uhwi (range
[0]),
1082 ? G_("may read %E byte from a region "
1084 : G_("reading %E byte from a region "
1087 ? G_("may read %E bytes from a region "
1089 : G_("reading %E bytes from a region "
1092 else if (tree_int_cst_sign_bit (range
[1]))
1094 /* Avoid printing the upper bound if it's invalid. */
1096 ? warning_at (loc
, OPT_Wstringop_overread
,
1098 ? G_("%qD may read %E or more bytes "
1099 "from a region of size %E")
1100 : G_("%qD reading %E or more bytes "
1101 "from a region of size %E")),
1102 func
, range
[0], size
)
1103 : warning_at (loc
, OPT_Wstringop_overread
,
1105 ? G_("may read %E or more bytes "
1106 "from a region of size %E")
1107 : G_("reading %E or more bytes "
1108 "from a region of size %E")),
1113 ? warning_at (loc
, OPT_Wstringop_overread
,
1115 ? G_("%qD may read between %E and %E bytes "
1116 "from a region of size %E")
1117 : G_("%qD reading between %E and %E bytes "
1118 "from a region of size %E")),
1119 func
, range
[0], range
[1], size
)
1120 : warning_at (loc
, opt
,
1122 ? G_("may read between %E and %E bytes "
1123 "from a region of size %E")
1124 : G_("reading between %E and %E bytes "
1125 "from a region of size %E")),
1126 range
[0], range
[1], size
));
1129 suppress_warning (exp
, OPT_Wstringop_overread
);
1134 if (tree_int_cst_equal (range
[0], range
[1])
1135 || tree_int_cst_sign_bit (range
[1]))
1137 ? warning_n (loc
, OPT_Wstringop_overread
,
1138 tree_to_uhwi (range
[0]),
1139 "%qD expecting %E byte in a region of size %E",
1140 "%qD expecting %E bytes in a region of size %E",
1141 func
, range
[0], size
)
1142 : warning_n (loc
, OPT_Wstringop_overread
,
1143 tree_to_uhwi (range
[0]),
1144 "expecting %E byte in a region of size %E",
1145 "expecting %E bytes in a region of size %E",
1147 else if (tree_int_cst_sign_bit (range
[1]))
1149 /* Avoid printing the upper bound if it's invalid. */
1151 ? warning_at (loc
, OPT_Wstringop_overread
,
1152 "%qD expecting %E or more bytes in a region "
1154 func
, range
[0], size
)
1155 : warning_at (loc
, OPT_Wstringop_overread
,
1156 "expecting %E or more bytes in a region "
1162 ? warning_at (loc
, OPT_Wstringop_overread
,
1163 "%qD expecting between %E and %E bytes in "
1164 "a region of size %E",
1165 func
, range
[0], range
[1], size
)
1166 : warning_at (loc
, OPT_Wstringop_overread
,
1167 "expecting between %E and %E bytes in "
1168 "a region of size %E",
1169 range
[0], range
[1], size
));
1172 suppress_warning (exp
, OPT_Wstringop_overread
);
1178 warn_for_access (location_t loc
, tree func
, gimple
*stmt
, int opt
,
1179 tree range
[2], tree size
, bool write
, bool read
, bool maybe
)
1181 return warn_for_access
<gimple
*>(loc
, func
, stmt
, opt
, range
, size
,
1182 write
, read
, maybe
);
1186 warn_for_access (location_t loc
, tree func
, tree expr
, int opt
,
1187 tree range
[2], tree size
, bool write
, bool read
, bool maybe
)
1189 return warn_for_access
<tree
>(loc
, func
, expr
, opt
, range
, size
,
1190 write
, read
, maybe
);
1193 /* Helper to set RANGE to the range of BOUND if it's nonnull, bounded
1194 by BNDRNG if nonnull and valid. */
1197 get_size_range (range_query
*query
, tree bound
, gimple
*stmt
, tree range
[2],
1198 const offset_int bndrng
[2])
1201 get_size_range (query
, bound
, stmt
, range
);
1203 if (!bndrng
|| (bndrng
[0] == 0 && bndrng
[1] == HOST_WIDE_INT_M1U
))
1206 if (range
[0] && TREE_CODE (range
[0]) == INTEGER_CST
)
1209 { wi::to_offset (range
[0]), wi::to_offset (range
[1]) };
1210 if (r
[0] < bndrng
[0])
1211 range
[0] = wide_int_to_tree (sizetype
, bndrng
[0]);
1212 if (bndrng
[1] < r
[1])
1213 range
[1] = wide_int_to_tree (sizetype
, bndrng
[1]);
1217 range
[0] = wide_int_to_tree (sizetype
, bndrng
[0]);
1218 range
[1] = wide_int_to_tree (sizetype
, bndrng
[1]);
1222 /* Try to verify that the sizes and lengths of the arguments to a string
1223 manipulation function given by EXP are within valid bounds and that
1224 the operation does not lead to buffer overflow or read past the end.
1225 Arguments other than EXP may be null. When non-null, the arguments
1226 have the following meaning:
1227 DST is the destination of a copy call or NULL otherwise.
1228 SRC is the source of a copy call or NULL otherwise.
1229 DSTWRITE is the number of bytes written into the destination obtained
1230 from the user-supplied size argument to the function (such as in
1231 memcpy(DST, SRCs, DSTWRITE) or strncpy(DST, DRC, DSTWRITE).
1232 MAXREAD is the user-supplied bound on the length of the source sequence
1233 (such as in strncat(d, s, N). It specifies the upper limit on the number
1234 of bytes to write. If NULL, it's taken to be the same as DSTWRITE.
1235 SRCSTR is the source string (such as in strcpy(DST, SRC)) when the
1236 expression EXP is a string function call (as opposed to a memory call
1237 like memcpy). As an exception, SRCSTR can also be an integer denoting
1238 the precomputed size of the source string or object (for functions like
1240 DSTSIZE is the size of the destination object.
1242 When DSTWRITE is null LEN is checked to verify that it doesn't exceed
1245 WRITE is true for write accesses, READ is true for reads. Both are
1246 false for simple size checks in calls to functions that neither read
1247 from nor write to the region.
1249 When nonnull, PAD points to a more detailed description of the access.
1251 If the call is successfully verified as safe return true, otherwise
1254 template <class GimpleOrTree
>
1256 check_access (GimpleOrTree exp
, tree dstwrite
,
1257 tree maxread
, tree srcstr
, tree dstsize
,
1258 access_mode mode
, const access_data
*pad
,
1261 /* The size of the largest object is half the address space, or
1262 PTRDIFF_MAX. (This is way too permissive.) */
1263 tree maxobjsize
= max_object_size ();
1265 /* Either an approximate/minimum the length of the source string for
1266 string functions or the size of the source object for raw memory
1268 tree slen
= NULL_TREE
;
1270 /* The range of the access in bytes; first set to the write access
1271 for functions that write and then read for those that also (or
1273 tree range
[2] = { NULL_TREE
, NULL_TREE
};
1275 /* Set to true when the exact number of bytes written by a string
1276 function like strcpy is not known and the only thing that is
1277 known is that it must be at least one (for the terminating nul). */
1278 bool at_least_one
= false;
1281 /* SRCSTR is normally a pointer to string but as a special case
1282 it can be an integer denoting the length of a string. */
1283 if (POINTER_TYPE_P (TREE_TYPE (srcstr
)))
1285 if (!check_nul_terminated_array (exp
, srcstr
, maxread
))
1286 /* Return if the array is not nul-terminated and a warning
1290 /* Try to determine the range of lengths the source string
1291 refers to. If it can be determined and is less than
1292 the upper bound given by MAXREAD add one to it for
1293 the terminating nul. Otherwise, set it to one for
1294 the same reason, or to MAXREAD as appropriate. */
1295 c_strlen_data lendata
= { };
1296 get_range_strlen (srcstr
, &lendata
, /* eltsize = */ 1);
1297 range
[0] = lendata
.minlen
;
1298 range
[1] = lendata
.maxbound
? lendata
.maxbound
: lendata
.maxlen
;
1300 && TREE_CODE (range
[0]) == INTEGER_CST
1301 && TREE_CODE (range
[1]) == INTEGER_CST
1302 && (!maxread
|| TREE_CODE (maxread
) == INTEGER_CST
))
1304 if (maxread
&& tree_int_cst_le (maxread
, range
[0]))
1305 range
[0] = range
[1] = maxread
;
1307 range
[0] = fold_build2 (PLUS_EXPR
, size_type_node
,
1308 range
[0], size_one_node
);
1310 if (maxread
&& tree_int_cst_le (maxread
, range
[1]))
1312 else if (!integer_all_onesp (range
[1]))
1313 range
[1] = fold_build2 (PLUS_EXPR
, size_type_node
,
1314 range
[1], size_one_node
);
1320 at_least_one
= true;
1321 slen
= size_one_node
;
1328 if (!dstwrite
&& !maxread
)
1330 /* When the only available piece of data is the object size
1331 there is nothing to do. */
1335 /* Otherwise, when the length of the source sequence is known
1336 (as with strlen), set DSTWRITE to it. */
1342 dstsize
= maxobjsize
;
1344 /* Set RANGE to that of DSTWRITE if non-null, bounded by PAD->DST_BNDRNG
1346 gimple
*stmt
= pad
? pad
->stmt
: nullptr;
1347 get_size_range (rvals
, dstwrite
, stmt
, range
, pad
? pad
->dst_bndrng
: NULL
);
1349 tree func
= get_callee_fndecl (exp
);
1350 /* Read vs write access by built-ins can be determined from the const
1351 qualifiers on the pointer argument. In the absence of attribute
1352 access, non-const qualified pointer arguments to user-defined
1353 functions are assumed to both read and write the objects. */
1354 const bool builtin
= func
? fndecl_built_in_p (func
) : false;
1356 /* First check the number of bytes to be written against the maximum
1359 && TREE_CODE (range
[0]) == INTEGER_CST
1360 && tree_int_cst_lt (maxobjsize
, range
[0]))
1362 location_t loc
= get_location (exp
);
1363 maybe_warn_for_bound (OPT_Wstringop_overflow_
, loc
, exp
, func
, range
,
1368 /* The number of bytes to write is "exact" if DSTWRITE is non-null,
1369 constant, and in range of unsigned HOST_WIDE_INT. */
1370 bool exactwrite
= dstwrite
&& tree_fits_uhwi_p (dstwrite
);
1372 /* Next check the number of bytes to be written against the destination
1374 if (range
[0] || !exactwrite
|| integer_all_onesp (dstwrite
))
1377 && TREE_CODE (range
[0]) == INTEGER_CST
1378 && ((tree_fits_uhwi_p (dstsize
)
1379 && tree_int_cst_lt (dstsize
, range
[0]))
1381 && tree_fits_uhwi_p (dstwrite
)
1382 && tree_int_cst_lt (dstwrite
, range
[0]))))
1384 const opt_code opt
= OPT_Wstringop_overflow_
;
1385 if (warning_suppressed_p (exp
, opt
)
1386 || (pad
&& pad
->dst
.ref
1387 && warning_suppressed_p (pad
->dst
.ref
, opt
)))
1390 location_t loc
= get_location (exp
);
1391 bool warned
= false;
1392 if (dstwrite
== slen
&& at_least_one
)
1394 /* This is a call to strcpy with a destination of 0 size
1395 and a source of unknown length. The call will write
1396 at least one byte past the end of the destination. */
1398 ? warning_at (loc
, opt
,
1399 "%qD writing %E or more bytes into "
1400 "a region of size %E overflows "
1402 func
, range
[0], dstsize
)
1403 : warning_at (loc
, opt
,
1404 "writing %E or more bytes into "
1405 "a region of size %E overflows "
1407 range
[0], dstsize
));
1412 = mode
== access_read_only
|| mode
== access_read_write
;
1414 = mode
== access_write_only
|| mode
== access_read_write
;
1415 const bool maybe
= pad
&& pad
->dst
.parmarray
;
1416 warned
= warn_for_access (loc
, func
, exp
,
1417 OPT_Wstringop_overflow_
,
1419 write
, read
&& !builtin
, maybe
);
1424 suppress_warning (exp
, OPT_Wstringop_overflow_
);
1426 pad
->dst
.inform_access (pad
->mode
);
1429 /* Return error when an overflow has been detected. */
1434 /* Check the maximum length of the source sequence against the size
1435 of the destination object if known, or against the maximum size
1439 /* Set RANGE to that of MAXREAD, bounded by PAD->SRC_BNDRNG if
1440 PAD is nonnull and BNDRNG is valid. */
1441 get_size_range (rvals
, maxread
, stmt
, range
, pad
? pad
->src_bndrng
: NULL
);
1443 location_t loc
= get_location (exp
);
1444 tree size
= dstsize
;
1445 if (pad
&& pad
->mode
== access_read_only
)
1446 size
= wide_int_to_tree (sizetype
, pad
->src
.size_remaining ());
1448 if (range
[0] && maxread
&& tree_fits_uhwi_p (size
))
1450 if (tree_int_cst_lt (maxobjsize
, range
[0]))
1452 maybe_warn_for_bound (OPT_Wstringop_overread
, loc
, exp
, func
,
1457 if (size
!= maxobjsize
&& tree_int_cst_lt (size
, range
[0]))
1459 opt_code opt
= (dstwrite
|| mode
!= access_read_only
1460 ? OPT_Wstringop_overflow_
1461 : OPT_Wstringop_overread
);
1462 maybe_warn_for_bound (opt
, loc
, exp
, func
, range
, size
, pad
);
1467 maybe_warn_nonstring_arg (func
, exp
);
1470 /* Check for reading past the end of SRC. */
1471 bool overread
= (slen
1475 && TREE_CODE (slen
) == INTEGER_CST
1476 && tree_int_cst_lt (slen
, range
[0]));
1477 /* If none is determined try to get a better answer based on the details
1481 && pad
->src
.sizrng
[1] >= 0
1482 && pad
->src
.offrng
[0] >= 0
1483 && (pad
->src
.offrng
[1] < 0
1484 || pad
->src
.offrng
[0] <= pad
->src
.offrng
[1]))
1486 /* Set RANGE to that of MAXREAD, bounded by PAD->SRC_BNDRNG if
1487 PAD is nonnull and BNDRNG is valid. */
1488 get_size_range (rvals
, maxread
, stmt
, range
, pad
? pad
->src_bndrng
: NULL
);
1489 /* Set OVERREAD for reads starting just past the end of an object. */
1490 overread
= pad
->src
.sizrng
[1] - pad
->src
.offrng
[0] < pad
->src_bndrng
[0];
1491 range
[0] = wide_int_to_tree (sizetype
, pad
->src_bndrng
[0]);
1492 slen
= size_zero_node
;
1497 const opt_code opt
= OPT_Wstringop_overread
;
1498 if (warning_suppressed_p (exp
, opt
)
1499 || (srcstr
&& warning_suppressed_p (srcstr
, opt
))
1500 || (pad
&& pad
->src
.ref
1501 && warning_suppressed_p (pad
->src
.ref
, opt
)))
1504 location_t loc
= get_location (exp
);
1506 = mode
== access_read_only
|| mode
== access_read_write
;
1507 const bool maybe
= pad
&& pad
->dst
.parmarray
;
1508 if (warn_for_access (loc
, func
, exp
, opt
, range
, slen
, false, read
,
1511 suppress_warning (exp
, opt
);
1513 pad
->src
.inform_access (access_read_only
);
1522 check_access (gimple
*stmt
, tree dstwrite
,
1523 tree maxread
, tree srcstr
, tree dstsize
,
1524 access_mode mode
, const access_data
*pad
,
1527 return check_access
<gimple
*> (stmt
, dstwrite
, maxread
, srcstr
, dstsize
,
1532 check_access (tree expr
, tree dstwrite
,
1533 tree maxread
, tree srcstr
, tree dstsize
,
1534 access_mode mode
, const access_data
*pad
/* = NULL */)
1536 return check_access
<tree
> (expr
, dstwrite
, maxread
, srcstr
, dstsize
,
1537 mode
, pad
, nullptr);
1540 /* Return true if STMT is a call to an allocation function. Unless
1541 ALL_ALLOC is set, consider only functions that return dynmamically
1542 allocated objects. Otherwise return true even for all forms of
1543 alloca (including VLA). */
1546 fndecl_alloc_p (tree fndecl
, bool all_alloc
)
1551 /* A call to operator new isn't recognized as one to a built-in. */
1552 if (DECL_IS_OPERATOR_NEW_P (fndecl
))
1555 if (fndecl_built_in_p (fndecl
, BUILT_IN_NORMAL
))
1557 switch (DECL_FUNCTION_CODE (fndecl
))
1559 case BUILT_IN_ALLOCA
:
1560 case BUILT_IN_ALLOCA_WITH_ALIGN
:
1562 case BUILT_IN_ALIGNED_ALLOC
:
1563 case BUILT_IN_CALLOC
:
1564 case BUILT_IN_GOMP_ALLOC
:
1565 case BUILT_IN_MALLOC
:
1566 case BUILT_IN_REALLOC
:
1567 case BUILT_IN_STRDUP
:
1568 case BUILT_IN_STRNDUP
:
1575 /* A function is considered an allocation function if it's declared
1576 with attribute malloc with an argument naming its associated
1577 deallocation function. */
1578 tree attrs
= DECL_ATTRIBUTES (fndecl
);
1582 for (tree allocs
= attrs
;
1583 (allocs
= lookup_attribute ("malloc", allocs
));
1584 allocs
= TREE_CHAIN (allocs
))
1586 tree args
= TREE_VALUE (allocs
);
1590 if (TREE_VALUE (args
))
1597 /* Return true if STMT is a call to an allocation function. A wrapper
1598 around fndecl_alloc_p. */
1601 gimple_call_alloc_p (gimple
*stmt
, bool all_alloc
= false)
1603 return fndecl_alloc_p (gimple_call_fndecl (stmt
), all_alloc
);
1606 /* Return true if DELC doesn't refer to an operator delete that's
1607 suitable to call with a pointer returned from the operator new
1608 described by NEWC. */
1611 new_delete_mismatch_p (const demangle_component
&newc
,
1612 const demangle_component
&delc
)
1614 if (newc
.type
!= delc
.type
)
1619 case DEMANGLE_COMPONENT_NAME
:
1621 int len
= newc
.u
.s_name
.len
;
1622 const char *news
= newc
.u
.s_name
.s
;
1623 const char *dels
= delc
.u
.s_name
.s
;
1624 if (len
!= delc
.u
.s_name
.len
|| memcmp (news
, dels
, len
))
1627 if (news
[len
] == 'n')
1629 if (news
[len
+ 1] == 'a')
1630 return dels
[len
] != 'd' || dels
[len
+ 1] != 'a';
1631 if (news
[len
+ 1] == 'w')
1632 return dels
[len
] != 'd' || dels
[len
+ 1] != 'l';
1637 case DEMANGLE_COMPONENT_OPERATOR
:
1638 /* Operator mismatches are handled above. */
1641 case DEMANGLE_COMPONENT_EXTENDED_OPERATOR
:
1642 if (newc
.u
.s_extended_operator
.args
!= delc
.u
.s_extended_operator
.args
)
1644 return new_delete_mismatch_p (*newc
.u
.s_extended_operator
.name
,
1645 *delc
.u
.s_extended_operator
.name
);
1647 case DEMANGLE_COMPONENT_FIXED_TYPE
:
1648 if (newc
.u
.s_fixed
.accum
!= delc
.u
.s_fixed
.accum
1649 || newc
.u
.s_fixed
.sat
!= delc
.u
.s_fixed
.sat
)
1651 return new_delete_mismatch_p (*newc
.u
.s_fixed
.length
,
1652 *delc
.u
.s_fixed
.length
);
1654 case DEMANGLE_COMPONENT_CTOR
:
1655 if (newc
.u
.s_ctor
.kind
!= delc
.u
.s_ctor
.kind
)
1657 return new_delete_mismatch_p (*newc
.u
.s_ctor
.name
,
1658 *delc
.u
.s_ctor
.name
);
1660 case DEMANGLE_COMPONENT_DTOR
:
1661 if (newc
.u
.s_dtor
.kind
!= delc
.u
.s_dtor
.kind
)
1663 return new_delete_mismatch_p (*newc
.u
.s_dtor
.name
,
1664 *delc
.u
.s_dtor
.name
);
1666 case DEMANGLE_COMPONENT_BUILTIN_TYPE
:
1668 /* The demangler API provides no better way to compare built-in
1669 types except to by comparing their demangled names. */
1671 demangle_component
*pnc
= const_cast<demangle_component
*>(&newc
);
1672 demangle_component
*pdc
= const_cast<demangle_component
*>(&delc
);
1673 char *nts
= cplus_demangle_print (0, pnc
, 16, &nsz
);
1674 char *dts
= cplus_demangle_print (0, pdc
, 16, &dsz
);
1677 bool mismatch
= strcmp (nts
, dts
);
1683 case DEMANGLE_COMPONENT_SUB_STD
:
1684 if (newc
.u
.s_string
.len
!= delc
.u
.s_string
.len
)
1686 return memcmp (newc
.u
.s_string
.string
, delc
.u
.s_string
.string
,
1687 newc
.u
.s_string
.len
);
1689 case DEMANGLE_COMPONENT_FUNCTION_PARAM
:
1690 case DEMANGLE_COMPONENT_TEMPLATE_PARAM
:
1691 return newc
.u
.s_number
.number
!= delc
.u
.s_number
.number
;
1693 case DEMANGLE_COMPONENT_CHARACTER
:
1694 return newc
.u
.s_character
.character
!= delc
.u
.s_character
.character
;
1696 case DEMANGLE_COMPONENT_DEFAULT_ARG
:
1697 case DEMANGLE_COMPONENT_LAMBDA
:
1698 if (newc
.u
.s_unary_num
.num
!= delc
.u
.s_unary_num
.num
)
1700 return new_delete_mismatch_p (*newc
.u
.s_unary_num
.sub
,
1701 *delc
.u
.s_unary_num
.sub
);
1706 if (!newc
.u
.s_binary
.left
!= !delc
.u
.s_binary
.left
)
1709 if (!newc
.u
.s_binary
.left
)
1712 if (new_delete_mismatch_p (*newc
.u
.s_binary
.left
, *delc
.u
.s_binary
.left
)
1713 || !newc
.u
.s_binary
.right
!= !delc
.u
.s_binary
.right
)
1716 if (newc
.u
.s_binary
.right
)
1717 return new_delete_mismatch_p (*newc
.u
.s_binary
.right
,
1718 *delc
.u
.s_binary
.right
);
1722 /* Return true if DELETE_DECL is an operator delete that's not suitable
1723 to call with a pointer returned fron NEW_DECL. */
1726 new_delete_mismatch_p (tree new_decl
, tree delete_decl
)
1728 tree new_name
= DECL_ASSEMBLER_NAME (new_decl
);
1729 tree delete_name
= DECL_ASSEMBLER_NAME (delete_decl
);
1731 /* valid_new_delete_pair_p() returns a conservative result (currently
1732 it only handles global operators). A true result is reliable but
1733 a false result doesn't necessarily mean the operators don't match
1734 unless CERTAIN is set. */
1736 if (valid_new_delete_pair_p (new_name
, delete_name
, &certain
))
1738 /* CERTAIN is set when the negative result is certain. */
1742 /* For anything not handled by valid_new_delete_pair_p() such as member
1743 operators compare the individual demangled components of the mangled
1745 const char *new_str
= IDENTIFIER_POINTER (new_name
);
1746 const char *del_str
= IDENTIFIER_POINTER (delete_name
);
1748 void *np
= NULL
, *dp
= NULL
;
1749 demangle_component
*ndc
= cplus_demangle_v3_components (new_str
, 0, &np
);
1750 demangle_component
*ddc
= cplus_demangle_v3_components (del_str
, 0, &dp
);
1751 bool mismatch
= new_delete_mismatch_p (*ndc
, *ddc
);
1757 /* ALLOC_DECL and DEALLOC_DECL are pair of allocation and deallocation
1758 functions. Return true if the latter is suitable to deallocate objects
1759 allocated by calls to the former. */
1762 matching_alloc_calls_p (tree alloc_decl
, tree dealloc_decl
)
1764 /* Set to alloc_kind_t::builtin if ALLOC_DECL is associated with
1765 a built-in deallocator. */
1766 enum class alloc_kind_t
{ none
, builtin
, user
}
1767 alloc_dealloc_kind
= alloc_kind_t::none
;
1769 if (DECL_IS_OPERATOR_NEW_P (alloc_decl
))
1771 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl
))
1772 /* Return true iff both functions are of the same array or
1773 singleton form and false otherwise. */
1774 return !new_delete_mismatch_p (alloc_decl
, dealloc_decl
);
1776 /* Return false for deallocation functions that are known not
1778 if (fndecl_built_in_p (dealloc_decl
, BUILT_IN_FREE
)
1779 || fndecl_built_in_p (dealloc_decl
, BUILT_IN_REALLOC
))
1781 /* Otherwise proceed below to check the deallocation function's
1782 "*dealloc" attributes to look for one that mentions this operator
1785 else if (fndecl_built_in_p (alloc_decl
, BUILT_IN_NORMAL
))
1787 switch (DECL_FUNCTION_CODE (alloc_decl
))
1789 case BUILT_IN_ALLOCA
:
1790 case BUILT_IN_ALLOCA_WITH_ALIGN
:
1793 case BUILT_IN_ALIGNED_ALLOC
:
1794 case BUILT_IN_CALLOC
:
1795 case BUILT_IN_GOMP_ALLOC
:
1796 case BUILT_IN_MALLOC
:
1797 case BUILT_IN_REALLOC
:
1798 case BUILT_IN_STRDUP
:
1799 case BUILT_IN_STRNDUP
:
1800 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl
))
1803 if (fndecl_built_in_p (dealloc_decl
, BUILT_IN_FREE
)
1804 || fndecl_built_in_p (dealloc_decl
, BUILT_IN_REALLOC
))
1807 alloc_dealloc_kind
= alloc_kind_t::builtin
;
1815 /* Set if DEALLOC_DECL both allocates and deallocates. */
1816 alloc_kind_t realloc_kind
= alloc_kind_t::none
;
1818 if (fndecl_built_in_p (dealloc_decl
, BUILT_IN_NORMAL
))
1820 built_in_function dealloc_code
= DECL_FUNCTION_CODE (dealloc_decl
);
1821 if (dealloc_code
== BUILT_IN_REALLOC
)
1822 realloc_kind
= alloc_kind_t::builtin
;
1824 for (tree amats
= DECL_ATTRIBUTES (alloc_decl
);
1825 (amats
= lookup_attribute ("malloc", amats
));
1826 amats
= TREE_CHAIN (amats
))
1828 tree args
= TREE_VALUE (amats
);
1832 tree fndecl
= TREE_VALUE (args
);
1833 if (!fndecl
|| !DECL_P (fndecl
))
1836 if (fndecl_built_in_p (fndecl
, BUILT_IN_NORMAL
)
1837 && dealloc_code
== DECL_FUNCTION_CODE (fndecl
))
1842 const bool alloc_builtin
= fndecl_built_in_p (alloc_decl
, BUILT_IN_NORMAL
);
1843 alloc_kind_t realloc_dealloc_kind
= alloc_kind_t::none
;
1845 /* If DEALLOC_DECL has an internal "*dealloc" attribute scan the list
1846 of its associated allocation functions for ALLOC_DECL.
1847 If the corresponding ALLOC_DECL is found they're a matching pair,
1848 otherwise they're not.
1849 With DDATS set to the Deallocator's *Dealloc ATtributes... */
1850 for (tree ddats
= DECL_ATTRIBUTES (dealloc_decl
);
1851 (ddats
= lookup_attribute ("*dealloc", ddats
));
1852 ddats
= TREE_CHAIN (ddats
))
1854 tree args
= TREE_VALUE (ddats
);
1858 tree alloc
= TREE_VALUE (args
);
1862 if (alloc
== DECL_NAME (dealloc_decl
))
1863 realloc_kind
= alloc_kind_t::user
;
1867 gcc_checking_assert (fndecl_built_in_p (alloc
, BUILT_IN_NORMAL
));
1869 switch (DECL_FUNCTION_CODE (alloc
))
1871 case BUILT_IN_ALIGNED_ALLOC
:
1872 case BUILT_IN_CALLOC
:
1873 case BUILT_IN_GOMP_ALLOC
:
1874 case BUILT_IN_MALLOC
:
1875 case BUILT_IN_REALLOC
:
1876 case BUILT_IN_STRDUP
:
1877 case BUILT_IN_STRNDUP
:
1878 realloc_dealloc_kind
= alloc_kind_t::builtin
;
1887 if (DECL_FUNCTION_CODE (alloc
) != DECL_FUNCTION_CODE (alloc_decl
))
1893 if (alloc
== DECL_NAME (alloc_decl
))
1897 if (realloc_kind
== alloc_kind_t::none
)
1900 hash_set
<tree
> common_deallocs
;
1901 /* Special handling for deallocators. Iterate over both the allocator's
1902 and the reallocator's associated deallocator functions looking for
1903 the first one in common. If one is found, the de/reallocator is
1904 a match for the allocator even though the latter isn't directly
1905 associated with the former. This simplifies declarations in system
1907 With AMATS set to the Allocator's Malloc ATtributes,
1908 and RMATS set to Reallocator's Malloc ATtributes... */
1909 for (tree amats
= DECL_ATTRIBUTES (alloc_decl
),
1910 rmats
= DECL_ATTRIBUTES (dealloc_decl
);
1911 (amats
= lookup_attribute ("malloc", amats
))
1912 || (rmats
= lookup_attribute ("malloc", rmats
));
1913 amats
= amats
? TREE_CHAIN (amats
) : NULL_TREE
,
1914 rmats
= rmats
? TREE_CHAIN (rmats
) : NULL_TREE
)
1916 if (tree args
= amats
? TREE_VALUE (amats
) : NULL_TREE
)
1917 if (tree adealloc
= TREE_VALUE (args
))
1919 if (DECL_P (adealloc
)
1920 && fndecl_built_in_p (adealloc
, BUILT_IN_NORMAL
))
1922 built_in_function fncode
= DECL_FUNCTION_CODE (adealloc
);
1923 if (fncode
== BUILT_IN_FREE
|| fncode
== BUILT_IN_REALLOC
)
1925 if (realloc_kind
== alloc_kind_t::builtin
)
1927 alloc_dealloc_kind
= alloc_kind_t::builtin
;
1932 common_deallocs
.add (adealloc
);
1935 if (tree args
= rmats
? TREE_VALUE (rmats
) : NULL_TREE
)
1936 if (tree ddealloc
= TREE_VALUE (args
))
1938 if (DECL_P (ddealloc
)
1939 && fndecl_built_in_p (ddealloc
, BUILT_IN_NORMAL
))
1941 built_in_function fncode
= DECL_FUNCTION_CODE (ddealloc
);
1942 if (fncode
== BUILT_IN_FREE
|| fncode
== BUILT_IN_REALLOC
)
1944 if (alloc_dealloc_kind
== alloc_kind_t::builtin
)
1946 realloc_dealloc_kind
= alloc_kind_t::builtin
;
1951 if (common_deallocs
.add (ddealloc
))
1956 /* Succeed only if ALLOC_DECL and the reallocator DEALLOC_DECL share
1957 a built-in deallocator. */
1958 return (alloc_dealloc_kind
== alloc_kind_t::builtin
1959 && realloc_dealloc_kind
== alloc_kind_t::builtin
);
1962 /* Return true if DEALLOC_DECL is a function suitable to deallocate
1963 objectes allocated by the ALLOC call. */
1966 matching_alloc_calls_p (gimple
*alloc
, tree dealloc_decl
)
1968 tree alloc_decl
= gimple_call_fndecl (alloc
);
1972 return matching_alloc_calls_p (alloc_decl
, dealloc_decl
);
1975 /* Diagnose a call EXP to deallocate a pointer referenced by AREF if it
1976 includes a nonzero offset. Such a pointer cannot refer to the beginning
1977 of an allocated object. A negative offset may refer to it only if
1978 the target pointer is unknown. */
1981 warn_dealloc_offset (location_t loc
, gimple
*call
, const access_ref
&aref
)
1983 if (aref
.deref
|| aref
.offrng
[0] <= 0 || aref
.offrng
[1] <= 0)
1986 tree dealloc_decl
= gimple_call_fndecl (call
);
1990 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl
)
1991 && !DECL_IS_REPLACEABLE_OPERATOR (dealloc_decl
))
1993 /* A call to a user-defined operator delete with a pointer plus offset
1994 may be valid if it's returned from an unknown function (i.e., one
1995 that's not operator new). */
1996 if (TREE_CODE (aref
.ref
) == SSA_NAME
)
1998 gimple
*def_stmt
= SSA_NAME_DEF_STMT (aref
.ref
);
1999 if (is_gimple_call (def_stmt
))
2001 tree alloc_decl
= gimple_call_fndecl (def_stmt
);
2002 if (!alloc_decl
|| !DECL_IS_OPERATOR_NEW_P (alloc_decl
))
2010 if (wi::fits_shwi_p (aref
.offrng
[0]))
2012 if (aref
.offrng
[0] == aref
.offrng
[1]
2013 || !wi::fits_shwi_p (aref
.offrng
[1]))
2014 sprintf (offstr
, " %lli",
2015 (long long)aref
.offrng
[0].to_shwi ());
2017 sprintf (offstr
, " [%lli, %lli]",
2018 (long long)aref
.offrng
[0].to_shwi (),
2019 (long long)aref
.offrng
[1].to_shwi ());
2022 if (!warning_at (loc
, OPT_Wfree_nonheap_object
,
2023 "%qD called on pointer %qE with nonzero offset%s",
2024 dealloc_decl
, aref
.ref
, offstr
))
2027 if (DECL_P (aref
.ref
))
2028 inform (get_location (aref
.ref
), "declared here");
2029 else if (TREE_CODE (aref
.ref
) == SSA_NAME
)
2031 gimple
*def_stmt
= SSA_NAME_DEF_STMT (aref
.ref
);
2032 if (is_gimple_call (def_stmt
))
2034 location_t def_loc
= get_location (def_stmt
);
2035 tree alloc_decl
= gimple_call_fndecl (def_stmt
);
2038 "returned from %qD", alloc_decl
);
2039 else if (tree alloc_fntype
= gimple_call_fntype (def_stmt
))
2041 "returned from %qT", alloc_fntype
);
2043 inform (def_loc
, "obtained here");
2052 const pass_data pass_data_waccess
= {
2057 PROP_cfg
, /* properties_required */
2058 0, /* properties_provided */
2059 0, /* properties_destroyed */
2060 0, /* properties_start */
2061 0, /* properties_finish */
2064 /* Pass to detect invalid accesses. */
2065 class pass_waccess
: public gimple_opt_pass
2068 pass_waccess (gcc::context
*);
2072 opt_pass
*clone () { return new pass_waccess (m_ctxt
); }
2074 virtual bool gate (function
*);
2076 virtual unsigned int execute (function
*);
2079 /* Not copyable or assignable. */
2080 pass_waccess (pass_waccess
&) = delete;
2081 void operator= (pass_waccess
&) = delete;
2083 /* Check a call to an atomic built-in function. */
2084 bool check_atomic_builtin (gcall
*);
2086 /* Check a call to a built-in function. */
2087 bool check_builtin (gcall
*);
2089 /* Check a call to an ordinary function for invalid accesses. */
2090 bool check_call_access (gcall
*);
2092 /* Check statements in a basic block. */
2093 void check_block (basic_block
);
2095 /* Check a call to a function. */
2096 void check_call (gcall
*);
2098 /* Check a call to the named built-in function. */
2099 void check_alloca (gcall
*);
2100 void check_alloc_size_call (gcall
*);
2101 void check_strcat (gcall
*);
2102 void check_strncat (gcall
*);
2103 void check_stxcpy (gcall
*);
2104 void check_stxncpy (gcall
*);
2105 void check_strncmp (gcall
*);
2106 void check_memop_access (gimple
*, tree
, tree
, tree
);
2107 void check_read_access (gimple
*, tree
, tree
= NULL_TREE
, int = 1);
2109 void maybe_check_dealloc_call (gcall
*);
2110 void maybe_check_access_sizes (rdwr_map
*, tree
, tree
, gimple
*);
2111 bool maybe_warn_memmodel (gimple
*, tree
, tree
, const unsigned char *);
2112 void check_atomic_memmodel (gimple
*, tree
, tree
, const unsigned char *);
2114 /* Check for uses of indeterminate pointers. */
2115 void check_pointer_uses (gimple
*, tree
);
2117 /* Return the argument that a call returns. */
2118 tree
gimple_call_return_arg (gcall
*);
2120 void warn_invalid_pointer (tree
, gimple
*, gimple
*, bool, bool = false);
2122 /* Return true if use follows an invalidating statement. */
2123 bool use_after_inval_p (gimple
*, gimple
*);
2125 /* A pointer_query object and its cache to store information about
2126 pointers and their targets in. */
2127 pointer_query m_ptr_qry
;
2128 pointer_query::cache_type m_var_cache
;
2130 /* A bit is set for each basic block whose statements have been assigned
2132 bitmap m_bb_uids_set
;
2133 /* The current function. */
2137 /* Construct the pass. */
2139 pass_waccess::pass_waccess (gcc::context
*ctxt
)
2140 : gimple_opt_pass (pass_data_waccess
, ctxt
),
2141 m_ptr_qry (NULL
, &m_var_cache
),
2148 /* Release pointer_query cache. */
2150 pass_waccess::~pass_waccess ()
2152 m_ptr_qry
.flush_cache ();
2155 /* Return true when any checks performed by the pass are enabled. */
2158 pass_waccess::gate (function
*)
2160 return (warn_free_nonheap_object
2161 || warn_mismatched_alloc
2162 || warn_mismatched_new_delete
);
2165 /* Initialize ALLOC_OBJECT_SIZE_LIMIT based on the -Walloc-size-larger-than=
2166 setting if the option is specified, or to the maximum object size if it
2167 is not. Return the initialized value. */
2170 alloc_max_size (void)
2172 HOST_WIDE_INT limit
= warn_alloc_size_limit
;
2173 if (limit
== HOST_WIDE_INT_MAX
)
2174 limit
= tree_to_shwi (TYPE_MAX_VALUE (ptrdiff_type_node
));
2176 return build_int_cst (size_type_node
, limit
);
2179 /* Diagnose a call EXP to function FN decorated with attribute alloc_size
2180 whose argument numbers given by IDX with values given by ARGS exceed
2181 the maximum object size or cause an unsigned oveflow (wrapping) when
2182 multiplied. FN is null when EXP is a call via a function pointer.
2183 When ARGS[0] is null the function does nothing. ARGS[1] may be null
2184 for functions like malloc, and non-null for those like calloc that
2185 are decorated with a two-argument attribute alloc_size. */
2188 maybe_warn_alloc_args_overflow (gimple
*stmt
, const tree args
[2],
2191 /* The range each of the (up to) two arguments is known to be in. */
2192 tree argrange
[2][2] = { { NULL_TREE
, NULL_TREE
}, { NULL_TREE
, NULL_TREE
} };
2194 /* Maximum object size set by -Walloc-size-larger-than= or SIZE_MAX / 2. */
2195 tree maxobjsize
= alloc_max_size ();
2197 location_t loc
= get_location (stmt
);
2199 tree fn
= gimple_call_fndecl (stmt
);
2200 tree fntype
= fn
? TREE_TYPE (fn
) : gimple_call_fntype (stmt
);
2201 bool warned
= false;
2203 /* Validate each argument individually. */
2204 for (unsigned i
= 0; i
!= 2 && args
[i
]; ++i
)
2206 if (TREE_CODE (args
[i
]) == INTEGER_CST
)
2208 argrange
[i
][0] = args
[i
];
2209 argrange
[i
][1] = args
[i
];
2211 if (tree_int_cst_lt (args
[i
], integer_zero_node
))
2213 warned
= warning_at (loc
, OPT_Walloc_size_larger_than_
,
2214 "argument %i value %qE is negative",
2215 idx
[i
] + 1, args
[i
]);
2217 else if (integer_zerop (args
[i
]))
2219 /* Avoid issuing -Walloc-zero for allocation functions other
2220 than __builtin_alloca that are declared with attribute
2221 returns_nonnull because there's no portability risk. This
2222 avoids warning for such calls to libiberty's xmalloc and
2224 Also avoid issuing the warning for calls to function named
2226 if (fn
&& fndecl_built_in_p (fn
, BUILT_IN_ALLOCA
)
2227 ? IDENTIFIER_LENGTH (DECL_NAME (fn
)) != 6
2228 : !lookup_attribute ("returns_nonnull",
2229 TYPE_ATTRIBUTES (fntype
)))
2230 warned
= warning_at (loc
, OPT_Walloc_zero
,
2231 "argument %i value is zero",
2234 else if (tree_int_cst_lt (maxobjsize
, args
[i
]))
2236 /* G++ emits calls to ::operator new[](SIZE_MAX) in C++98
2237 mode and with -fno-exceptions as a way to indicate array
2238 size overflow. There's no good way to detect C++98 here
2239 so avoid diagnosing these calls for all C++ modes. */
2244 && DECL_IS_OPERATOR_NEW_P (fn
)
2245 && integer_all_onesp (args
[i
]))
2248 warned
= warning_at (loc
, OPT_Walloc_size_larger_than_
,
2249 "argument %i value %qE exceeds "
2250 "maximum object size %E",
2251 idx
[i
] + 1, args
[i
], maxobjsize
);
2254 else if (TREE_CODE (args
[i
]) == SSA_NAME
2255 && get_size_range (args
[i
], argrange
[i
]))
2257 /* Verify that the argument's range is not negative (including
2258 upper bound of zero). */
2259 if (tree_int_cst_lt (argrange
[i
][0], integer_zero_node
)
2260 && tree_int_cst_le (argrange
[i
][1], integer_zero_node
))
2262 warned
= warning_at (loc
, OPT_Walloc_size_larger_than_
,
2263 "argument %i range [%E, %E] is negative",
2265 argrange
[i
][0], argrange
[i
][1]);
2267 else if (tree_int_cst_lt (maxobjsize
, argrange
[i
][0]))
2269 warned
= warning_at (loc
, OPT_Walloc_size_larger_than_
,
2270 "argument %i range [%E, %E] exceeds "
2271 "maximum object size %E",
2273 argrange
[i
][0], argrange
[i
][1],
2279 if (!argrange
[0][0])
2282 /* For a two-argument alloc_size, validate the product of the two
2283 arguments if both of their values or ranges are known. */
2284 if (!warned
&& tree_fits_uhwi_p (argrange
[0][0])
2285 && argrange
[1][0] && tree_fits_uhwi_p (argrange
[1][0])
2286 && !integer_onep (argrange
[0][0])
2287 && !integer_onep (argrange
[1][0]))
2289 /* Check for overflow in the product of a function decorated with
2290 attribute alloc_size (X, Y). */
2291 unsigned szprec
= TYPE_PRECISION (size_type_node
);
2292 wide_int x
= wi::to_wide (argrange
[0][0], szprec
);
2293 wide_int y
= wi::to_wide (argrange
[1][0], szprec
);
2295 wi::overflow_type vflow
;
2296 wide_int prod
= wi::umul (x
, y
, &vflow
);
2299 warned
= warning_at (loc
, OPT_Walloc_size_larger_than_
,
2300 "product %<%E * %E%> of arguments %i and %i "
2301 "exceeds %<SIZE_MAX%>",
2302 argrange
[0][0], argrange
[1][0],
2303 idx
[0] + 1, idx
[1] + 1);
2304 else if (wi::ltu_p (wi::to_wide (maxobjsize
, szprec
), prod
))
2305 warned
= warning_at (loc
, OPT_Walloc_size_larger_than_
,
2306 "product %<%E * %E%> of arguments %i and %i "
2307 "exceeds maximum object size %E",
2308 argrange
[0][0], argrange
[1][0],
2309 idx
[0] + 1, idx
[1] + 1,
2314 /* Print the full range of each of the two arguments to make
2315 it clear when it is, in fact, in a range and not constant. */
2316 if (argrange
[0][0] != argrange
[0][1])
2317 inform (loc
, "argument %i in the range [%E, %E]",
2318 idx
[0] + 1, argrange
[0][0], argrange
[0][1]);
2319 if (argrange
[1][0] != argrange
[1][1])
2320 inform (loc
, "argument %i in the range [%E, %E]",
2321 idx
[1] + 1, argrange
[1][0], argrange
[1][1]);
2327 location_t fnloc
= DECL_SOURCE_LOCATION (fn
);
2329 if (DECL_IS_UNDECLARED_BUILTIN (fn
))
2331 "in a call to built-in allocation function %qD", fn
);
2334 "in a call to allocation function %qD declared here", fn
);
2338 /* Check a call to an alloca function for an excessive size. */
2341 pass_waccess::check_alloca (gcall
*stmt
)
2343 if ((warn_vla_limit
>= HOST_WIDE_INT_MAX
2344 && warn_alloc_size_limit
< warn_vla_limit
)
2345 || (warn_alloca_limit
>= HOST_WIDE_INT_MAX
2346 && warn_alloc_size_limit
< warn_alloca_limit
))
2348 /* -Walloca-larger-than and -Wvla-larger-than settings of less
2349 than HWI_MAX override the more general -Walloc-size-larger-than
2350 so unless either of the former options is smaller than the last
2351 one (wchich would imply that the call was already checked), check
2352 the alloca arguments for overflow. */
2353 const tree alloc_args
[] = { call_arg (stmt
, 0), NULL_TREE
};
2354 const int idx
[] = { 0, -1 };
2355 maybe_warn_alloc_args_overflow (stmt
, alloc_args
, idx
);
2359 /* Check a call to an allocation function for an excessive size. */
2362 pass_waccess::check_alloc_size_call (gcall
*stmt
)
2364 tree fndecl
= gimple_call_fndecl (stmt
);
2365 if (fndecl
&& gimple_call_builtin_p (stmt
, BUILT_IN_NORMAL
))
2367 /* Alloca is handled separately. */
2368 switch (DECL_FUNCTION_CODE (fndecl
))
2370 case BUILT_IN_ALLOCA
:
2371 case BUILT_IN_ALLOCA_WITH_ALIGN
:
2372 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX
:
2379 tree fntype
= gimple_call_fntype (stmt
);
2380 tree fntypeattrs
= TYPE_ATTRIBUTES (fntype
);
2382 tree alloc_size
= lookup_attribute ("alloc_size", fntypeattrs
);
2386 /* Extract attribute alloc_size from the type of the called expression
2387 (which could be a function or a function pointer) and if set, store
2388 the indices of the corresponding arguments in ALLOC_IDX, and then
2389 the actual argument(s) at those indices in ALLOC_ARGS. */
2390 int idx
[2] = { -1, -1 };
2391 tree alloc_args
[] = { NULL_TREE
, NULL_TREE
};
2392 unsigned nargs
= gimple_call_num_args (stmt
);
2394 tree args
= TREE_VALUE (alloc_size
);
2395 idx
[0] = TREE_INT_CST_LOW (TREE_VALUE (args
)) - 1;
2396 /* Avoid invalid calls to functions without a prototype. */
2397 if ((unsigned) idx
[0] >= nargs
)
2399 alloc_args
[0] = call_arg (stmt
, idx
[0]);
2400 if (TREE_CHAIN (args
))
2402 idx
[1] = TREE_INT_CST_LOW (TREE_VALUE (TREE_CHAIN (args
))) - 1;
2403 if ((unsigned) idx
[1] >= nargs
)
2405 alloc_args
[1] = call_arg (stmt
, idx
[1]);
2408 maybe_warn_alloc_args_overflow (stmt
, alloc_args
, idx
);
2411 /* Check a call STMT to strcat() for overflow and warn if it does. */
2414 pass_waccess::check_strcat (gcall
*stmt
)
2416 if (!warn_stringop_overflow
&& !warn_stringop_overread
)
2419 tree dest
= call_arg (stmt
, 0);
2420 tree src
= call_arg (stmt
, 1);
2422 /* There is no way here to determine the length of the string in
2423 the destination to which the SRC string is being appended so
2424 just diagnose cases when the souce string is longer than
2425 the destination object. */
2426 access_data
data (m_ptr_qry
.rvals
, stmt
, access_read_write
, NULL_TREE
,
2427 true, NULL_TREE
, true);
2428 const int ost
= warn_stringop_overflow
? warn_stringop_overflow
- 1 : 1;
2429 compute_objsize (src
, stmt
, ost
, &data
.src
, &m_ptr_qry
);
2430 tree destsize
= compute_objsize (dest
, stmt
, ost
, &data
.dst
, &m_ptr_qry
);
2432 check_access (stmt
, /*dstwrite=*/NULL_TREE
, /*maxread=*/NULL_TREE
,
2433 src
, destsize
, data
.mode
, &data
, m_ptr_qry
.rvals
);
2436 /* Check a call STMT to strcat() for overflow and warn if it does. */
2439 pass_waccess::check_strncat (gcall
*stmt
)
2441 if (!warn_stringop_overflow
&& !warn_stringop_overread
)
2444 tree dest
= call_arg (stmt
, 0);
2445 tree src
= call_arg (stmt
, 1);
2446 /* The upper bound on the number of bytes to write. */
2447 tree maxread
= call_arg (stmt
, 2);
2449 /* Detect unterminated source (only). */
2450 if (!check_nul_terminated_array (stmt
, src
, maxread
))
2453 /* The length of the source sequence. */
2454 tree slen
= c_strlen (src
, 1);
2456 /* Try to determine the range of lengths that the source expression
2457 refers to. Since the lengths are only used for warning and not
2458 for code generation disable strict mode below. */
2462 c_strlen_data lendata
= { };
2463 get_range_strlen (src
, &lendata
, /* eltsize = */ 1);
2464 maxlen
= lendata
.maxbound
;
2467 access_data
data (m_ptr_qry
.rvals
, stmt
, access_read_write
);
2468 /* Try to verify that the destination is big enough for the shortest
2469 string. First try to determine the size of the destination object
2470 into which the source is being copied. */
2471 const int ost
= warn_stringop_overflow
- 1;
2472 tree destsize
= compute_objsize (dest
, stmt
, ost
, &data
.dst
, &m_ptr_qry
);
2474 /* Add one for the terminating nul. */
2475 tree srclen
= (maxlen
2476 ? fold_build2 (PLUS_EXPR
, size_type_node
, maxlen
,
2480 /* The strncat function copies at most MAXREAD bytes and always appends
2481 the terminating nul so the specified upper bound should never be equal
2482 to (or greater than) the size of the destination. */
2483 if (tree_fits_uhwi_p (maxread
) && tree_fits_uhwi_p (destsize
)
2484 && tree_int_cst_equal (destsize
, maxread
))
2486 location_t loc
= get_location (stmt
);
2487 warning_at (loc
, OPT_Wstringop_overflow_
,
2488 "%qD specified bound %E equals destination size",
2489 get_callee_fndecl (stmt
), maxread
);
2495 || (maxread
&& tree_fits_uhwi_p (maxread
)
2496 && tree_fits_uhwi_p (srclen
)
2497 && tree_int_cst_lt (maxread
, srclen
)))
2500 check_access (stmt
, /*dstwrite=*/NULL_TREE
, maxread
, srclen
,
2501 destsize
, data
.mode
, &data
, m_ptr_qry
.rvals
);
2504 /* Check a call STMT to stpcpy() or strcpy() for overflow and warn
2508 pass_waccess::check_stxcpy (gcall
*stmt
)
2510 tree dst
= call_arg (stmt
, 0);
2511 tree src
= call_arg (stmt
, 1);
2515 if (tree nonstr
= unterminated_array (src
, &size
, &exact
))
2517 /* NONSTR refers to the non-nul terminated constant array. */
2518 warn_string_no_nul (get_location (stmt
), stmt
, NULL
, src
, nonstr
,
2523 if (warn_stringop_overflow
)
2525 access_data
data (m_ptr_qry
.rvals
, stmt
, access_read_write
, NULL_TREE
,
2526 true, NULL_TREE
, true);
2527 const int ost
= warn_stringop_overflow
? warn_stringop_overflow
- 1 : 1;
2528 compute_objsize (src
, stmt
, ost
, &data
.src
, &m_ptr_qry
);
2529 tree dstsize
= compute_objsize (dst
, stmt
, ost
, &data
.dst
, &m_ptr_qry
);
2530 check_access (stmt
, /*dstwrite=*/ NULL_TREE
,
2531 /*maxread=*/ NULL_TREE
, /*srcstr=*/ src
,
2532 dstsize
, data
.mode
, &data
, m_ptr_qry
.rvals
);
2535 /* Check to see if the argument was declared attribute nonstring
2536 and if so, issue a warning since at this point it's not known
2537 to be nul-terminated. */
2538 tree fndecl
= get_callee_fndecl (stmt
);
2539 maybe_warn_nonstring_arg (fndecl
, stmt
);
2542 /* Check a call STMT to stpncpy() or strncpy() for overflow and warn
2546 pass_waccess::check_stxncpy (gcall
*stmt
)
2548 if (!warn_stringop_overflow
)
2551 tree dst
= call_arg (stmt
, 0);
2552 tree src
= call_arg (stmt
, 1);
2553 /* The number of bytes to write (not the maximum). */
2554 tree len
= call_arg (stmt
, 2);
2556 access_data
data (m_ptr_qry
.rvals
, stmt
, access_read_write
, len
, true, len
,
2558 const int ost
= warn_stringop_overflow
? warn_stringop_overflow
- 1 : 1;
2559 compute_objsize (src
, stmt
, ost
, &data
.src
, &m_ptr_qry
);
2560 tree dstsize
= compute_objsize (dst
, stmt
, ost
, &data
.dst
, &m_ptr_qry
);
2562 check_access (stmt
, /*dstwrite=*/len
, /*maxread=*/len
, src
, dstsize
,
2563 data
.mode
, &data
, m_ptr_qry
.rvals
);
2566 /* Check a call STMT to stpncpy() or strncpy() for overflow and warn
2570 pass_waccess::check_strncmp (gcall
*stmt
)
2572 if (!warn_stringop_overread
)
2575 tree arg1
= call_arg (stmt
, 0);
2576 tree arg2
= call_arg (stmt
, 1);
2577 tree bound
= call_arg (stmt
, 2);
2579 /* First check each argument separately, considering the bound. */
2580 if (!check_nul_terminated_array (stmt
, arg1
, bound
)
2581 || !check_nul_terminated_array (stmt
, arg2
, bound
))
2584 /* A strncmp read from each argument is constrained not just by
2585 the bound but also by the length of the shorter string. Specifying
2586 a bound that's larger than the size of either array makes no sense
2587 and is likely a bug. When the length of neither of the two strings
2588 is known but the sizes of both of the arrays they are stored in is,
2589 issue a warning if the bound is larger than than the size of
2590 the larger of the two arrays. */
2592 c_strlen_data lendata1
{ }, lendata2
{ };
2593 tree len1
= c_strlen (arg1
, 1, &lendata1
);
2594 tree len2
= c_strlen (arg2
, 1, &lendata2
);
2596 if (len1
&& TREE_CODE (len1
) != INTEGER_CST
)
2598 if (len2
&& TREE_CODE (len2
) != INTEGER_CST
)
2602 /* If the length of both arguments was computed they must both be
2603 nul-terminated and no further checking is necessary regardless
2607 /* Check to see if the argument was declared with attribute nonstring
2608 and if so, issue a warning since at this point it's not known to be
2610 if (maybe_warn_nonstring_arg (get_callee_fndecl (stmt
), stmt
))
2613 access_data
adata1 (m_ptr_qry
.rvals
, stmt
, access_read_only
, NULL_TREE
, false,
2615 access_data
adata2 (m_ptr_qry
.rvals
, stmt
, access_read_only
, NULL_TREE
, false,
2618 /* Determine the range of the bound first and bail if it fails; it's
2619 cheaper than computing the size of the objects. */
2620 tree bndrng
[2] = { NULL_TREE
, NULL_TREE
};
2621 get_size_range (m_ptr_qry
.rvals
, bound
, stmt
, bndrng
, adata1
.src_bndrng
);
2622 if (!bndrng
[0] || integer_zerop (bndrng
[0]))
2625 if (len1
&& tree_int_cst_lt (len1
, bndrng
[0]))
2627 if (len2
&& tree_int_cst_lt (len2
, bndrng
[0]))
2630 /* compute_objsize almost never fails (and ultimately should never
2631 fail). Don't bother to handle the rare case when it does. */
2632 if (!compute_objsize (arg1
, stmt
, 1, &adata1
.src
, &m_ptr_qry
)
2633 || !compute_objsize (arg2
, stmt
, 1, &adata2
.src
, &m_ptr_qry
))
2636 /* Compute the size of the remaining space in each array after
2637 subtracting any offset into it. */
2638 offset_int rem1
= adata1
.src
.size_remaining ();
2639 offset_int rem2
= adata2
.src
.size_remaining ();
2641 /* Cap REM1 and REM2 at the other if the other's argument is known
2642 to be an unterminated array, either because there's no space
2643 left in it after adding its offset or because it's constant and
2645 if (rem1
== 0 || (rem1
< rem2
&& lendata1
.decl
))
2647 else if (rem2
== 0 || (rem2
< rem1
&& lendata2
.decl
))
2650 /* Point PAD at the array to reference in the note if a warning
2652 access_data
*pad
= len1
? &adata2
: &adata1
;
2653 offset_int maxrem
= wi::max (rem1
, rem2
, UNSIGNED
);
2654 if (lendata1
.decl
|| lendata2
.decl
2655 || maxrem
< wi::to_offset (bndrng
[0]))
2657 /* Warn when either argument isn't nul-terminated or the maximum
2658 remaining space in the two arrays is less than the bound. */
2659 tree func
= get_callee_fndecl (stmt
);
2660 location_t loc
= gimple_location (stmt
);
2661 maybe_warn_for_bound (OPT_Wstringop_overread
, loc
, stmt
, func
,
2662 bndrng
, wide_int_to_tree (sizetype
, maxrem
),
2667 /* Determine and check the sizes of the source and the destination
2668 of calls to __builtin_{bzero,memcpy,mempcpy,memset} calls. STMT is
2669 the call statement, DEST is the destination argument, SRC is the source
2670 argument or null, and SIZE is the number of bytes being accessed. Use
2671 Object Size type-0 regardless of the OPT_Wstringop_overflow_ setting.
2672 Return true on success (no overflow or invalid sizes), false otherwise. */
2675 pass_waccess::check_memop_access (gimple
*stmt
, tree dest
, tree src
, tree size
)
2677 /* For functions like memset and memcpy that operate on raw memory
2678 try to determine the size of the largest source and destination
2679 object using type-0 Object Size regardless of the object size
2680 type specified by the option. */
2681 access_data
data (m_ptr_qry
.rvals
, stmt
, access_read_write
);
2683 = src
? compute_objsize (src
, stmt
, 0, &data
.src
, &m_ptr_qry
) : NULL_TREE
;
2684 tree dstsize
= compute_objsize (dest
, stmt
, 0, &data
.dst
, &m_ptr_qry
);
2686 check_access (stmt
, size
, /*maxread=*/NULL_TREE
, srcsize
, dstsize
,
2687 data
.mode
, &data
, m_ptr_qry
.rvals
);
2690 /* A convenience wrapper for check_access to check access by a read-only
2691 function like puts or strcmp. */
2694 pass_waccess::check_read_access (gimple
*stmt
, tree src
,
2695 tree bound
/* = NULL_TREE */,
2698 if (!warn_stringop_overread
)
2701 if (bound
&& !useless_type_conversion_p (size_type_node
, TREE_TYPE (bound
)))
2702 bound
= fold_convert (size_type_node
, bound
);
2704 tree fndecl
= get_callee_fndecl (stmt
);
2705 maybe_warn_nonstring_arg (fndecl
, stmt
);
2707 access_data
data (m_ptr_qry
.rvals
, stmt
, access_read_only
, NULL_TREE
,
2708 false, bound
, true);
2709 compute_objsize (src
, stmt
, ost
, &data
.src
, &m_ptr_qry
);
2710 check_access (stmt
, /*dstwrite=*/ NULL_TREE
, /*maxread=*/ bound
,
2711 /*srcstr=*/ src
, /*dstsize=*/ NULL_TREE
, data
.mode
,
2712 &data
, m_ptr_qry
.rvals
);
2715 /* Return true if memory model ORD is constant in the context of STMT and
2716 set *CSTVAL to the constant value. Otherwise return false. Warn for
2720 memmodel_to_uhwi (tree ord
, gimple
*stmt
, unsigned HOST_WIDE_INT
*cstval
)
2722 unsigned HOST_WIDE_INT val
;
2724 if (TREE_CODE (ord
) == INTEGER_CST
)
2726 if (!tree_fits_uhwi_p (ord
))
2728 val
= tree_to_uhwi (ord
);
2732 /* Use the range query to determine constant values in the absence
2733 of constant proppagation (such as at -O0). */
2735 if (!get_range_query (cfun
)->range_of_expr (rng
, ord
, stmt
)
2736 || !rng
.constant_p ()
2737 || !rng
.singleton_p (&ord
))
2740 wide_int lob
= rng
.lower_bound ();
2741 if (!wi::fits_uhwi_p (lob
))
2744 val
= lob
.to_shwi ();
2747 if (targetm
.memmodel_check
)
2748 /* This might warn for an invalid VAL but return a conservatively
2750 val
= targetm
.memmodel_check (val
);
2751 else if (val
& ~MEMMODEL_MASK
)
2753 tree fndecl
= gimple_call_fndecl (stmt
);
2754 location_t loc
= gimple_location (stmt
);
2755 loc
= expansion_point_location_if_in_system_header (loc
);
2757 warning_at (loc
, OPT_Winvalid_memory_model
,
2758 "unknown architecture specifier in memory model "
2759 "%wi for %qD", val
, fndecl
);
2768 /* Valid memory model for each set of atomic built-in functions. */
2770 struct memmodel_pair
2773 const char* modname
;
2775 #define MEMMODEL_PAIR(val, str) \
2776 { MEMMODEL_ ## val, "memory_order_" str }
2779 /* Valid memory models in the order of increasing strength. */
2781 static const memmodel_pair memory_models
[] =
2782 { MEMMODEL_PAIR (RELAXED
, "relaxed"),
2783 MEMMODEL_PAIR (SEQ_CST
, "seq_cst"),
2784 MEMMODEL_PAIR (ACQUIRE
, "acquire"),
2785 MEMMODEL_PAIR (CONSUME
, "consume"),
2786 MEMMODEL_PAIR (RELEASE
, "release"),
2787 MEMMODEL_PAIR (ACQ_REL
, "acq_rel")
2790 /* Return the name of the memory model VAL. */
2793 memmodel_name (unsigned HOST_WIDE_INT val
)
2795 val
= memmodel_base (val
);
2797 for (unsigned i
= 0; i
!= sizeof memory_models
/ sizeof *memory_models
; ++i
)
2799 if (val
== memory_models
[i
].modval
)
2800 return memory_models
[i
].modname
;
2805 /* Indices of valid MEMORY_MODELS above for corresponding atomic operations. */
2806 static const unsigned char load_models
[] = { 0, 1, 2, 3, UCHAR_MAX
};
2807 static const unsigned char store_models
[] = { 0, 1, 4, UCHAR_MAX
};
2808 static const unsigned char xchg_models
[] = { 0, 1, 3, 4, 5, UCHAR_MAX
};
2809 static const unsigned char flag_clr_models
[] = { 0, 1, 4, UCHAR_MAX
};
2810 static const unsigned char all_models
[] = { 0, 1, 2, 3, 4, 5, UCHAR_MAX
};
2812 /* Check the success memory model argument ORD_SUCS to the call STMT to
2813 an atomic function and warn if it's invalid. If nonnull, also check
2814 the failure memory model ORD_FAIL and warn if it's invalid. Return
2815 true if a warning has been issued. */
2818 pass_waccess::maybe_warn_memmodel (gimple
*stmt
, tree ord_sucs
,
2819 tree ord_fail
, const unsigned char *valid
)
2821 unsigned HOST_WIDE_INT sucs
, fail
= 0;
2822 if (!memmodel_to_uhwi (ord_sucs
, stmt
, &sucs
)
2823 || (ord_fail
&& !memmodel_to_uhwi (ord_fail
, stmt
, &fail
)))
2826 bool is_valid
= false;
2828 for (unsigned i
= 0; valid
[i
] != UCHAR_MAX
; ++i
)
2830 memmodel model
= memory_models
[valid
[i
]].modval
;
2831 if (memmodel_base (sucs
) == model
)
2840 tree fndecl
= gimple_call_fndecl (stmt
);
2841 location_t loc
= gimple_location (stmt
);
2842 loc
= expansion_point_location_if_in_system_header (loc
);
2846 bool warned
= false;
2847 if (const char *modname
= memmodel_name (sucs
))
2848 warned
= warning_at (loc
, OPT_Winvalid_memory_model
,
2849 "invalid memory model %qs for %qD",
2852 warned
= warning_at (loc
, OPT_Winvalid_memory_model
,
2853 "invalid memory model %wi for %qD",
2859 /* Print a note with the valid memory models. */
2861 pp_show_color (&pp
) = pp_show_color (global_dc
->printer
);
2862 for (unsigned i
= 0; valid
[i
] != UCHAR_MAX
; ++i
)
2864 const char *modname
= memory_models
[valid
[i
]].modname
;
2865 pp_printf (&pp
, "%s%qs", i
? ", " : "", modname
);
2868 inform (loc
, "valid models are %s", pp_formatted_text (&pp
));
2875 if (fail
== MEMMODEL_RELEASE
|| fail
== MEMMODEL_ACQ_REL
)
2876 if (const char *failname
= memmodel_name (fail
))
2878 /* If both memory model arguments are valid but their combination
2879 is not, use their names in the warning. */
2880 if (!warning_at (loc
, OPT_Winvalid_memory_model
,
2881 "invalid failure memory model %qs for %qD",
2886 "valid failure models are %qs, %qs, %qs, %qs",
2887 "memory_order_relaxed", "memory_order_seq_cst",
2888 "memory_order_acquire", "memory_order_consume");
2892 if (memmodel_base (fail
) <= memmodel_base (sucs
))
2895 if (const char *sucsname
= memmodel_name (sucs
))
2896 if (const char *failname
= memmodel_name (fail
))
2898 /* If both memory model arguments are valid but their combination
2899 is not, use their names in the warning. */
2900 if (!warning_at (loc
, OPT_Winvalid_memory_model
,
2901 "failure memory model %qs cannot be stronger "
2902 "than success memory model %qs for %qD",
2903 failname
, sucsname
, fndecl
))
2906 /* Print a note with the valid failure memory models which are
2907 those with a value less than or equal to the success mode. */
2910 for (unsigned i
= 0;
2911 memory_models
[i
].modval
<= memmodel_base (sucs
); ++i
)
2916 const char *modname
= memory_models
[valid
[i
]].modname
;
2917 sprintf (buf
+ strlen (buf
), "'%s'", modname
);
2920 inform (loc
, "valid models are %s", buf
);
2924 /* If either memory model argument value is invalid use the numerical
2925 value of both in the message. */
2926 return warning_at (loc
, OPT_Winvalid_memory_model
,
2927 "failure memory model %wi cannot be stronger "
2928 "than success memory model %wi for %qD",
2929 fail
, sucs
, fndecl
);
2932 /* Wrapper for the above. */
2935 pass_waccess::check_atomic_memmodel (gimple
*stmt
, tree ord_sucs
,
2936 tree ord_fail
, const unsigned char *valid
)
2938 if (warning_suppressed_p (stmt
, OPT_Winvalid_memory_model
))
2941 if (maybe_warn_memmodel (stmt
, ord_sucs
, ord_fail
, valid
))
2944 suppress_warning (stmt
, OPT_Winvalid_memory_model
);
2947 /* Check a call STMT to an atomic or sync built-in. */
2950 pass_waccess::check_atomic_builtin (gcall
*stmt
)
2952 tree callee
= gimple_call_fndecl (stmt
);
2956 /* The size in bytes of the access by the function, and the number
2957 of the second argument to check (if any). */
2958 unsigned bytes
= 0, arg2
= UINT_MAX
;
2959 unsigned sucs_arg
= UINT_MAX
, fail_arg
= UINT_MAX
;
2960 /* Points to the array of indices of valid memory models. */
2961 const unsigned char *pvalid_models
= NULL
;
2963 switch (DECL_FUNCTION_CODE (callee
))
2965 #define BUILTIN_ACCESS_SIZE_FNSPEC(N) \
2966 BUILT_IN_SYNC_FETCH_AND_ADD_ ## N: \
2967 case BUILT_IN_SYNC_FETCH_AND_SUB_ ## N: \
2968 case BUILT_IN_SYNC_FETCH_AND_OR_ ## N: \
2969 case BUILT_IN_SYNC_FETCH_AND_AND_ ## N: \
2970 case BUILT_IN_SYNC_FETCH_AND_XOR_ ## N: \
2971 case BUILT_IN_SYNC_FETCH_AND_NAND_ ## N: \
2972 case BUILT_IN_SYNC_ADD_AND_FETCH_ ## N: \
2973 case BUILT_IN_SYNC_SUB_AND_FETCH_ ## N: \
2974 case BUILT_IN_SYNC_OR_AND_FETCH_ ## N: \
2975 case BUILT_IN_SYNC_AND_AND_FETCH_ ## N: \
2976 case BUILT_IN_SYNC_XOR_AND_FETCH_ ## N: \
2977 case BUILT_IN_SYNC_NAND_AND_FETCH_ ## N: \
2978 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_ ## N: \
2979 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_ ## N: \
2980 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_ ## N: \
2981 case BUILT_IN_SYNC_LOCK_RELEASE_ ## N: \
2984 case BUILT_IN_ATOMIC_LOAD_ ## N: \
2985 pvalid_models = load_models; \
2988 case BUILT_IN_ATOMIC_STORE_ ## N: \
2989 if (!pvalid_models) \
2990 pvalid_models = store_models; \
2992 case BUILT_IN_ATOMIC_ADD_FETCH_ ## N: \
2993 case BUILT_IN_ATOMIC_SUB_FETCH_ ## N: \
2994 case BUILT_IN_ATOMIC_AND_FETCH_ ## N: \
2995 case BUILT_IN_ATOMIC_NAND_FETCH_ ## N: \
2996 case BUILT_IN_ATOMIC_XOR_FETCH_ ## N: \
2997 case BUILT_IN_ATOMIC_OR_FETCH_ ## N: \
2998 case BUILT_IN_ATOMIC_FETCH_ADD_ ## N: \
2999 case BUILT_IN_ATOMIC_FETCH_SUB_ ## N: \
3000 case BUILT_IN_ATOMIC_FETCH_AND_ ## N: \
3001 case BUILT_IN_ATOMIC_FETCH_NAND_ ## N: \
3002 case BUILT_IN_ATOMIC_FETCH_OR_ ## N: \
3003 case BUILT_IN_ATOMIC_FETCH_XOR_ ## N: \
3005 if (sucs_arg == UINT_MAX) \
3007 if (!pvalid_models) \
3008 pvalid_models = all_models; \
3010 case BUILT_IN_ATOMIC_EXCHANGE_ ## N: \
3013 pvalid_models = xchg_models; \
3015 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_ ## N: \
3019 pvalid_models = all_models; \
3022 case BUILTIN_ACCESS_SIZE_FNSPEC (1);
3024 case BUILTIN_ACCESS_SIZE_FNSPEC (2);
3026 case BUILTIN_ACCESS_SIZE_FNSPEC (4);
3028 case BUILTIN_ACCESS_SIZE_FNSPEC (8);
3030 case BUILTIN_ACCESS_SIZE_FNSPEC (16);
3033 case BUILT_IN_ATOMIC_CLEAR
:
3035 pvalid_models
= flag_clr_models
;
3042 unsigned nargs
= gimple_call_num_args (stmt
);
3043 if (sucs_arg
< nargs
)
3045 tree ord_sucs
= gimple_call_arg (stmt
, sucs_arg
);
3046 tree ord_fail
= NULL_TREE
;
3047 if (fail_arg
< nargs
)
3048 ord_fail
= gimple_call_arg (stmt
, fail_arg
);
3049 check_atomic_memmodel (stmt
, ord_sucs
, ord_fail
, pvalid_models
);
3055 tree size
= build_int_cstu (sizetype
, bytes
);
3056 tree dst
= gimple_call_arg (stmt
, 0);
3057 check_memop_access (stmt
, dst
, NULL_TREE
, size
);
3059 if (arg2
!= UINT_MAX
)
3061 tree dst
= gimple_call_arg (stmt
, arg2
);
3062 check_memop_access (stmt
, dst
, NULL_TREE
, size
);
3068 /* Check call STMT to a built-in function for invalid accesses. Return
3069 true if a call has been handled. */
3072 pass_waccess::check_builtin (gcall
*stmt
)
3074 tree callee
= gimple_call_fndecl (stmt
);
3078 switch (DECL_FUNCTION_CODE (callee
))
3080 case BUILT_IN_ALLOCA
:
3081 case BUILT_IN_ALLOCA_WITH_ALIGN
:
3082 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX
:
3083 check_alloca (stmt
);
3086 case BUILT_IN_EXECL
:
3087 case BUILT_IN_EXECLE
:
3088 case BUILT_IN_EXECLP
:
3089 case BUILT_IN_EXECV
:
3090 case BUILT_IN_EXECVE
:
3091 case BUILT_IN_EXECVP
:
3092 check_read_access (stmt
, call_arg (stmt
, 0));
3096 case BUILT_IN_REALLOC
:
3098 tree arg
= call_arg (stmt
, 0);
3099 if (TREE_CODE (arg
) == SSA_NAME
)
3100 check_pointer_uses (stmt
, arg
);
3104 case BUILT_IN_GETTEXT
:
3106 case BUILT_IN_PUTS_UNLOCKED
:
3107 case BUILT_IN_STRDUP
:
3108 check_read_access (stmt
, call_arg (stmt
, 0));
3111 case BUILT_IN_INDEX
:
3112 case BUILT_IN_RINDEX
:
3113 case BUILT_IN_STRCHR
:
3114 case BUILT_IN_STRRCHR
:
3115 case BUILT_IN_STRLEN
:
3116 check_read_access (stmt
, call_arg (stmt
, 0));
3119 case BUILT_IN_FPUTS
:
3120 case BUILT_IN_FPUTS_UNLOCKED
:
3121 check_read_access (stmt
, call_arg (stmt
, 0));
3124 case BUILT_IN_STRNDUP
:
3125 case BUILT_IN_STRNLEN
:
3127 tree str
= call_arg (stmt
, 0);
3128 tree len
= call_arg (stmt
, 1);
3129 check_read_access (stmt
, str
, len
);
3133 case BUILT_IN_STRCAT
:
3134 check_strcat (stmt
);
3137 case BUILT_IN_STRNCAT
:
3138 check_strncat (stmt
);
3141 case BUILT_IN_STPCPY
:
3142 case BUILT_IN_STRCPY
:
3143 check_stxcpy (stmt
);
3146 case BUILT_IN_STPNCPY
:
3147 case BUILT_IN_STRNCPY
:
3148 check_stxncpy (stmt
);
3151 case BUILT_IN_STRCASECMP
:
3152 case BUILT_IN_STRCMP
:
3153 case BUILT_IN_STRPBRK
:
3154 case BUILT_IN_STRSPN
:
3155 case BUILT_IN_STRCSPN
:
3156 case BUILT_IN_STRSTR
:
3157 check_read_access (stmt
, call_arg (stmt
, 0));
3158 check_read_access (stmt
, call_arg (stmt
, 1));
3161 case BUILT_IN_STRNCASECMP
:
3162 case BUILT_IN_STRNCMP
:
3163 check_strncmp (stmt
);
3166 case BUILT_IN_MEMCMP
:
3168 tree a1
= call_arg (stmt
, 0);
3169 tree a2
= call_arg (stmt
, 1);
3170 tree len
= call_arg (stmt
, 2);
3171 check_read_access (stmt
, a1
, len
, 0);
3172 check_read_access (stmt
, a2
, len
, 0);
3176 case BUILT_IN_MEMCPY
:
3177 case BUILT_IN_MEMPCPY
:
3178 case BUILT_IN_MEMMOVE
:
3180 tree dst
= call_arg (stmt
, 0);
3181 tree src
= call_arg (stmt
, 1);
3182 tree len
= call_arg (stmt
, 2);
3183 check_memop_access (stmt
, dst
, src
, len
);
3187 case BUILT_IN_MEMCHR
:
3189 tree src
= call_arg (stmt
, 0);
3190 tree len
= call_arg (stmt
, 2);
3191 check_read_access (stmt
, src
, len
, 0);
3195 case BUILT_IN_MEMSET
:
3197 tree dst
= call_arg (stmt
, 0);
3198 tree len
= call_arg (stmt
, 2);
3199 check_memop_access (stmt
, dst
, NULL_TREE
, len
);
3204 if (check_atomic_builtin (stmt
))
3212 /* Returns the type of the argument ARGNO to function with type FNTYPE
3213 or null when the typoe cannot be determined or no such argument exists. */
3216 fntype_argno_type (tree fntype
, unsigned argno
)
3218 if (!prototype_p (fntype
))
3222 function_args_iterator it
;
3223 FOREACH_FUNCTION_ARGS (fntype
, argtype
, it
)
3230 /* Helper to append the "human readable" attribute access specification
3231 described by ACCESS to the array ATTRSTR with size STRSIZE. Used in
3235 append_attrname (const std::pair
<int, attr_access
> &access
,
3236 char *attrstr
, size_t strsize
)
3238 if (access
.second
.internal_p
)
3241 tree str
= access
.second
.to_external_string ();
3242 gcc_assert (strsize
>= (size_t) TREE_STRING_LENGTH (str
));
3243 strcpy (attrstr
, TREE_STRING_POINTER (str
));
3246 /* Iterate over attribute access read-only, read-write, and write-only
3247 arguments and diagnose past-the-end accesses and related problems
3248 in the function call EXP. */
3251 pass_waccess::maybe_check_access_sizes (rdwr_map
*rwm
, tree fndecl
, tree fntype
,
3254 auto_diagnostic_group adg
;
3256 /* Set if a warning has been issued for any argument (used to decide
3257 whether to emit an informational note at the end). */
3258 opt_code opt_warned
= no_warning
;
3260 /* A string describing the attributes that the warnings issued by this
3261 function apply to. Used to print one informational note per function
3262 call, rather than one per warning. That reduces clutter. */
3266 for (rdwr_map::iterator it
= rwm
->begin (); it
!= rwm
->end (); ++it
)
3268 std::pair
<int, attr_access
> access
= *it
;
3270 /* Get the function call arguments corresponding to the attribute's
3271 positional arguments. When both arguments have been specified
3272 there will be two entries in *RWM, one for each. They are
3273 cross-referenced by their respective argument numbers in
3274 ACCESS.PTRARG and ACCESS.SIZARG. */
3275 const int ptridx
= access
.second
.ptrarg
;
3276 const int sizidx
= access
.second
.sizarg
;
3278 gcc_assert (ptridx
!= -1);
3279 gcc_assert (access
.first
== ptridx
|| access
.first
== sizidx
);
3281 /* The pointer is set to null for the entry corresponding to
3282 the size argument. Skip it. It's handled when the entry
3283 corresponding to the pointer argument comes up. */
3284 if (!access
.second
.ptr
)
3287 tree ptrtype
= fntype_argno_type (fntype
, ptridx
);
3289 /* A function with a prototype was redeclared without one and
3290 the protype has been lost. See pr102759. Avoid dealing
3291 with this pathological case. */
3294 tree argtype
= TREE_TYPE (ptrtype
);
3296 /* The size of the access by the call in elements. */
3300 /* If only the pointer attribute operand was specified and
3301 not size, set SIZE to the greater of MINSIZE or size of
3302 one element of the pointed to type to detect smaller
3303 objects (null pointers are diagnosed in this case only
3304 if the pointer is also declared with attribute nonnull. */
3305 if (access
.second
.minsize
3306 && access
.second
.minsize
!= HOST_WIDE_INT_M1U
)
3307 access_nelts
= build_int_cstu (sizetype
, access
.second
.minsize
);
3308 else if (VOID_TYPE_P (argtype
) && access
.second
.mode
== access_none
)
3309 /* Treat access mode none on a void* argument as expecting
3310 as little as zero bytes. */
3311 access_nelts
= size_zero_node
;
3313 access_nelts
= size_one_node
;
3316 access_nelts
= rwm
->get (sizidx
)->size
;
3318 /* Format the value or range to avoid an explosion of messages. */
3320 tree sizrng
[2] = { size_zero_node
, build_all_ones_cst (sizetype
) };
3321 if (get_size_range (m_ptr_qry
.rvals
, access_nelts
, stmt
, sizrng
, 1))
3323 char *s0
= print_generic_expr_to_str (sizrng
[0]);
3324 if (tree_int_cst_equal (sizrng
[0], sizrng
[1]))
3326 gcc_checking_assert (strlen (s0
) < sizeof sizstr
);
3327 strcpy (sizstr
, s0
);
3331 char *s1
= print_generic_expr_to_str (sizrng
[1]);
3332 gcc_checking_assert (strlen (s0
) + strlen (s1
)
3333 < sizeof sizstr
- 4);
3334 sprintf (sizstr
, "[%.37s, %.37s]", s0
, s1
);
3342 /* Set if a warning has been issued for the current argument. */
3343 opt_code arg_warned
= no_warning
;
3344 location_t loc
= get_location (stmt
);
3345 tree ptr
= access
.second
.ptr
;
3347 && tree_int_cst_sgn (sizrng
[0]) < 0
3348 && tree_int_cst_sgn (sizrng
[1]) < 0)
3350 /* Warn about negative sizes. */
3351 if (access
.second
.internal_p
)
3353 const std::string argtypestr
3354 = access
.second
.array_as_string (ptrtype
);
3356 if (warning_at (loc
, OPT_Wstringop_overflow_
,
3357 "bound argument %i value %s is "
3358 "negative for a variable length array "
3359 "argument %i of type %s",
3361 ptridx
+ 1, argtypestr
.c_str ()))
3362 arg_warned
= OPT_Wstringop_overflow_
;
3364 else if (warning_at (loc
, OPT_Wstringop_overflow_
,
3365 "argument %i value %s is negative",
3366 sizidx
+ 1, sizstr
))
3367 arg_warned
= OPT_Wstringop_overflow_
;
3369 if (arg_warned
!= no_warning
)
3371 append_attrname (access
, attrstr
, sizeof attrstr
);
3372 /* Remember a warning has been issued and avoid warning
3373 again below for the same attribute. */
3374 opt_warned
= arg_warned
;
3379 /* The size of the access by the call in bytes. */
3380 tree access_size
= NULL_TREE
;
3381 if (tree_int_cst_sgn (sizrng
[0]) >= 0)
3383 if (COMPLETE_TYPE_P (argtype
))
3385 /* Multiply ACCESS_SIZE by the size of the type the pointer
3386 argument points to. If it's incomplete the size is used
3388 if (tree argsize
= TYPE_SIZE_UNIT (argtype
))
3389 if (TREE_CODE (argsize
) == INTEGER_CST
)
3391 const int prec
= TYPE_PRECISION (sizetype
);
3392 wide_int minsize
= wi::to_wide (sizrng
[0], prec
);
3393 minsize
*= wi::to_wide (argsize
, prec
);
3394 access_size
= wide_int_to_tree (sizetype
, minsize
);
3398 access_size
= access_nelts
;
3401 if (integer_zerop (ptr
))
3403 if (sizidx
>= 0 && tree_int_cst_sgn (sizrng
[0]) > 0)
3405 /* Warn about null pointers with positive sizes. This is
3406 different from also declaring the pointer argument with
3407 attribute nonnull when the function accepts null pointers
3408 only when the corresponding size is zero. */
3409 if (access
.second
.internal_p
)
3411 const std::string argtypestr
3412 = access
.second
.array_as_string (ptrtype
);
3414 if (warning_at (loc
, OPT_Wnonnull
,
3415 "argument %i of variable length "
3416 "array %s is null but "
3417 "the corresponding bound argument "
3419 ptridx
+ 1, argtypestr
.c_str (),
3420 sizidx
+ 1, sizstr
))
3421 arg_warned
= OPT_Wnonnull
;
3423 else if (warning_at (loc
, OPT_Wnonnull
,
3424 "argument %i is null but "
3425 "the corresponding size argument "
3427 ptridx
+ 1, sizidx
+ 1, sizstr
))
3428 arg_warned
= OPT_Wnonnull
;
3430 else if (access_size
&& access
.second
.static_p
)
3432 /* Warn about null pointers for [static N] array arguments
3433 but do not warn for ordinary (i.e., nonstatic) arrays. */
3434 if (warning_at (loc
, OPT_Wnonnull
,
3435 "argument %i to %<%T[static %E]%> "
3436 "is null where non-null expected",
3437 ptridx
+ 1, argtype
, access_size
))
3438 arg_warned
= OPT_Wnonnull
;
3441 if (arg_warned
!= no_warning
)
3443 append_attrname (access
, attrstr
, sizeof attrstr
);
3444 /* Remember a warning has been issued and avoid warning
3445 again below for the same attribute. */
3446 opt_warned
= OPT_Wnonnull
;
3451 access_data
data (m_ptr_qry
.rvals
, stmt
, access
.second
.mode
,
3452 NULL_TREE
, false, NULL_TREE
, false);
3453 access_ref
* const pobj
= (access
.second
.mode
== access_write_only
3454 ? &data
.dst
: &data
.src
);
3455 tree objsize
= compute_objsize (ptr
, stmt
, 1, pobj
, &m_ptr_qry
);
3457 /* The size of the destination or source object. */
3458 tree dstsize
= NULL_TREE
, srcsize
= NULL_TREE
;
3459 if (access
.second
.mode
== access_read_only
3460 || access
.second
.mode
== access_none
)
3462 /* For a read-only argument there is no destination. For
3463 no access, set the source as well and differentiate via
3464 the access flag below. */
3466 if (access
.second
.mode
== access_read_only
3467 || access
.second
.mode
== access_none
)
3469 /* For a read-only attribute there is no destination so
3470 clear OBJSIZE. This emits "reading N bytes" kind of
3471 diagnostics instead of the "writing N bytes" kind,
3472 unless MODE is none. */
3473 objsize
= NULL_TREE
;
3479 /* Clear the no-warning bit in case it was set by check_access
3480 in a prior iteration so that accesses via different arguments
3482 suppress_warning (stmt
, OPT_Wstringop_overflow_
, false);
3483 access_mode mode
= data
.mode
;
3484 if (mode
== access_deferred
)
3485 mode
= TYPE_READONLY (argtype
) ? access_read_only
: access_read_write
;
3486 check_access (stmt
, access_size
, /*maxread=*/ NULL_TREE
, srcsize
,
3487 dstsize
, mode
, &data
, m_ptr_qry
.rvals
);
3489 if (warning_suppressed_p (stmt
, OPT_Wstringop_overflow_
))
3490 opt_warned
= OPT_Wstringop_overflow_
;
3491 if (opt_warned
!= no_warning
)
3493 if (access
.second
.internal_p
)
3495 unsigned HOST_WIDE_INT nelts
=
3496 access_nelts
? access
.second
.minsize
: HOST_WIDE_INT_M1U
;
3497 tree arrtype
= build_printable_array_type (argtype
, nelts
);
3498 inform (loc
, "referencing argument %u of type %qT",
3499 ptridx
+ 1, arrtype
);
3502 /* If check_access issued a warning above, append the relevant
3503 attribute to the string. */
3504 append_attrname (access
, attrstr
, sizeof attrstr
);
3511 inform (get_location (fndecl
),
3512 "in a call to function %qD declared with attribute %qs",
3515 inform (get_location (stmt
),
3516 "in a call with type %qT and attribute %qs",
3519 else if (opt_warned
!= no_warning
)
3522 inform (get_location (fndecl
),
3523 "in a call to function %qD", fndecl
);
3525 inform (get_location (stmt
),
3526 "in a call with type %qT", fntype
);
3529 /* Set the bit in case if was cleared and not set above. */
3530 if (opt_warned
!= no_warning
)
3531 suppress_warning (stmt
, opt_warned
);
3534 /* Check call STMT to an ordinary (non-built-in) function for invalid
3535 accesses. Return true if a call has been handled. */
3538 pass_waccess::check_call_access (gcall
*stmt
)
3540 tree fntype
= gimple_call_fntype (stmt
);
3544 tree fntypeattrs
= TYPE_ATTRIBUTES (fntype
);
3548 /* Map of attribute accewss specifications for function arguments. */
3550 init_attr_rdwr_indices (&rdwr_idx
, fntypeattrs
);
3552 unsigned nargs
= call_nargs (stmt
);
3553 for (unsigned i
= 0; i
!= nargs
; ++i
)
3555 tree arg
= call_arg (stmt
, i
);
3557 /* Save the actual argument that corresponds to the access attribute
3558 operand for later processing. */
3559 if (attr_access
*access
= rdwr_idx
.get (i
))
3561 if (POINTER_TYPE_P (TREE_TYPE (arg
)))
3564 // A nonnull ACCESS->SIZE contains VLA bounds. */
3569 gcc_assert (access
->ptr
== NULL_TREE
);
3574 /* Check attribute access arguments. */
3575 tree fndecl
= gimple_call_fndecl (stmt
);
3576 maybe_check_access_sizes (&rdwr_idx
, fndecl
, fntype
, stmt
);
3578 check_alloc_size_call (stmt
);
3582 /* Check arguments in a call STMT for attribute nonstring. */
3585 check_nonstring_args (gcall
*stmt
)
3587 tree fndecl
= gimple_call_fndecl (stmt
);
3589 /* Detect passing non-string arguments to functions expecting
3590 nul-terminated strings. */
3591 maybe_warn_nonstring_arg (fndecl
, stmt
);
3594 /* Issue a warning if a deallocation function such as free, realloc,
3595 or C++ operator delete is called with an argument not returned by
3596 a matching allocation function such as malloc or the corresponding
3597 form of C++ operatorn new. */
3600 pass_waccess::maybe_check_dealloc_call (gcall
*call
)
3602 tree fndecl
= gimple_call_fndecl (call
);
3606 unsigned argno
= fndecl_dealloc_argno (fndecl
);
3607 if ((unsigned) call_nargs (call
) <= argno
)
3610 tree ptr
= gimple_call_arg (call
, argno
);
3611 if (integer_zerop (ptr
))
3615 if (!compute_objsize (ptr
, call
, 0, &aref
, &m_ptr_qry
))
3618 tree ref
= aref
.ref
;
3619 if (integer_zerop (ref
))
3622 tree dealloc_decl
= fndecl
;
3623 location_t loc
= gimple_location (call
);
3625 if (DECL_P (ref
) || EXPR_P (ref
))
3627 /* Diagnose freeing a declared object. */
3628 if (aref
.ref_declared ()
3629 && warning_at (loc
, OPT_Wfree_nonheap_object
,
3630 "%qD called on unallocated object %qD",
3633 inform (get_location (ref
), "declared here");
3637 /* Diagnose freeing a pointer that includes a positive offset.
3638 Such a pointer cannot refer to the beginning of an allocated
3639 object. A negative offset may refer to it. */
3640 if (aref
.sizrng
[0] != aref
.sizrng
[1]
3641 && warn_dealloc_offset (loc
, call
, aref
))
3644 else if (CONSTANT_CLASS_P (ref
))
3646 if (warning_at (loc
, OPT_Wfree_nonheap_object
,
3647 "%qD called on a pointer to an unallocated "
3648 "object %qE", dealloc_decl
, ref
))
3650 if (TREE_CODE (ptr
) == SSA_NAME
)
3652 gimple
*def_stmt
= SSA_NAME_DEF_STMT (ptr
);
3653 if (is_gimple_assign (def_stmt
))
3655 location_t loc
= gimple_location (def_stmt
);
3656 inform (loc
, "assigned here");
3662 else if (TREE_CODE (ref
) == SSA_NAME
)
3664 /* Also warn if the pointer argument refers to the result
3665 of an allocation call like alloca or VLA. */
3666 gimple
*def_stmt
= SSA_NAME_DEF_STMT (ref
);
3670 if (is_gimple_call (def_stmt
))
3672 bool warned
= false;
3673 if (gimple_call_alloc_p (def_stmt
))
3675 if (matching_alloc_calls_p (def_stmt
, dealloc_decl
))
3677 if (warn_dealloc_offset (loc
, call
, aref
))
3682 tree alloc_decl
= gimple_call_fndecl (def_stmt
);
3683 const opt_code opt
=
3684 (DECL_IS_OPERATOR_NEW_P (alloc_decl
)
3685 || DECL_IS_OPERATOR_DELETE_P (dealloc_decl
)
3686 ? OPT_Wmismatched_new_delete
3687 : OPT_Wmismatched_dealloc
);
3688 warned
= warning_at (loc
, opt
,
3689 "%qD called on pointer returned "
3690 "from a mismatched allocation "
3691 "function", dealloc_decl
);
3694 else if (gimple_call_builtin_p (def_stmt
, BUILT_IN_ALLOCA
)
3695 || gimple_call_builtin_p (def_stmt
,
3696 BUILT_IN_ALLOCA_WITH_ALIGN
))
3697 warned
= warning_at (loc
, OPT_Wfree_nonheap_object
,
3698 "%qD called on pointer to "
3699 "an unallocated object",
3701 else if (warn_dealloc_offset (loc
, call
, aref
))
3706 tree fndecl
= gimple_call_fndecl (def_stmt
);
3707 inform (gimple_location (def_stmt
),
3708 "returned from %qD", fndecl
);
3712 else if (gimple_nop_p (def_stmt
))
3714 ref
= SSA_NAME_VAR (ref
);
3715 /* Diagnose freeing a pointer that includes a positive offset. */
3716 if (TREE_CODE (ref
) == PARM_DECL
3718 && aref
.sizrng
[0] != aref
.sizrng
[1]
3719 && aref
.offrng
[0] > 0 && aref
.offrng
[1] > 0
3720 && warn_dealloc_offset (loc
, call
, aref
))
3726 /* Return true if either USE_STMT's basic block (that of a pointer's use)
3727 is dominated by INVAL_STMT's (that of a pointer's invalidating statement,
3728 or if they're in the same block, USE_STMT follows INVAL_STMT. */
3731 pass_waccess::use_after_inval_p (gimple
*inval_stmt
, gimple
*use_stmt
)
3733 basic_block inval_bb
= gimple_bb (inval_stmt
);
3734 basic_block use_bb
= gimple_bb (use_stmt
);
3736 if (inval_bb
!= use_bb
)
3737 return dominated_by_p (CDI_DOMINATORS
, use_bb
, inval_bb
);
3739 if (bitmap_set_bit (m_bb_uids_set
, inval_bb
->index
))
3740 /* The first time this basic block is visited assign increasing ids
3741 to consecutive statements in it. Use the ids to determine which
3742 precedes which. This avoids the linear traversal on subsequent
3743 visits to the same block. */
3744 for (auto si
= gsi_start_bb (inval_bb
); !gsi_end_p (si
);
3745 gsi_next_nondebug (&si
))
3747 gimple
*stmt
= gsi_stmt (si
);
3748 unsigned uid
= inc_gimple_stmt_max_uid (m_func
);
3749 gimple_set_uid (stmt
, uid
);
3752 return gimple_uid (inval_stmt
) < gimple_uid (use_stmt
);
3755 /* Issue a warning for the USE_STMT of pointer PTR rendered invalid
3756 by INVAL_STMT. PTR may be null when it's been optimized away.
3757 MAYBE is true to issue the "maybe" kind of warning. EQUALITY is
3758 true when the pointer is used in an equality expression. */
3761 pass_waccess::warn_invalid_pointer (tree ptr
, gimple
*use_stmt
,
3764 bool equality
/* = false */)
3766 /* Avoid printing the unhelpful "<unknown>" in the diagnostics. */
3767 if (ptr
&& TREE_CODE (ptr
) == SSA_NAME
3768 && (!SSA_NAME_VAR (ptr
) || DECL_ARTIFICIAL (SSA_NAME_VAR (ptr
))))
3771 location_t use_loc
= gimple_location (use_stmt
);
3772 if (use_loc
== UNKNOWN_LOCATION
)
3774 use_loc
= cfun
->function_end_locus
;
3776 /* Avoid issuing a warning with no context other than
3777 the function. That would make it difficult to debug
3778 in any but very simple cases. */
3782 if (is_gimple_call (inval_stmt
))
3784 if ((equality
&& warn_use_after_free
< 3)
3785 || (maybe
&& warn_use_after_free
< 2)
3786 || warning_suppressed_p (use_stmt
, OPT_Wuse_after_free
))
3789 const tree inval_decl
= gimple_call_fndecl (inval_stmt
);
3791 if ((ptr
&& warning_at (use_loc
, OPT_Wuse_after_free
,
3793 ? G_("pointer %qE may be used after %qD")
3794 : G_("pointer %qE used after %qD")),
3796 || (!ptr
&& warning_at (use_loc
, OPT_Wuse_after_free
,
3798 ? G_("pointer may be used after %qD")
3799 : G_("pointer used after %qD")),
3802 location_t loc
= gimple_location (inval_stmt
);
3803 inform (loc
, "call to %qD here", inval_decl
);
3804 suppress_warning (use_stmt
, OPT_Wuse_after_free
);
3810 /* If STMT is a call to either the standard realloc or to a user-defined
3811 reallocation function returns its LHS and set *PTR to the reallocated
3812 pointer. Otherwise return null. */
3815 get_realloc_lhs (gimple
*stmt
, tree
*ptr
)
3817 if (gimple_call_builtin_p (stmt
, BUILT_IN_REALLOC
))
3819 *ptr
= gimple_call_arg (stmt
, 0);
3820 return gimple_call_lhs (stmt
);
3823 gcall
*call
= dyn_cast
<gcall
*>(stmt
);
3827 tree fnattr
= NULL_TREE
;
3828 tree fndecl
= gimple_call_fndecl (call
);
3830 fnattr
= DECL_ATTRIBUTES (fndecl
);
3833 tree fntype
= gimple_call_fntype (stmt
);
3836 fnattr
= TYPE_ATTRIBUTES (fntype
);
3842 for (tree ats
= fnattr
; (ats
= lookup_attribute ("*dealloc", ats
));
3843 ats
= TREE_CHAIN (ats
))
3845 tree args
= TREE_VALUE (ats
);
3849 tree alloc
= TREE_VALUE (args
);
3853 if (alloc
== DECL_NAME (fndecl
))
3856 if (tree index
= TREE_CHAIN (args
))
3857 argno
= TREE_INT_CST_LOW (TREE_VALUE (index
)) - 1;
3858 *ptr
= gimple_call_arg (stmt
, argno
);
3859 return gimple_call_lhs (stmt
);
3866 /* Warn if STMT is a call to a deallocation function that's not a match
3867 for the REALLOC_STMT call. Return true if warned. */
3870 maybe_warn_mismatched_realloc (tree ptr
, gimple
*realloc_stmt
, gimple
*stmt
)
3872 if (!is_gimple_call (stmt
))
3875 tree fndecl
= gimple_call_fndecl (stmt
);
3879 unsigned argno
= fndecl_dealloc_argno (fndecl
);
3880 if (call_nargs (stmt
) <= argno
)
3883 if (matching_alloc_calls_p (realloc_stmt
, fndecl
))
3886 /* Avoid printing the unhelpful "<unknown>" in the diagnostics. */
3887 if (ptr
&& TREE_CODE (ptr
) == SSA_NAME
3888 && (!SSA_NAME_VAR (ptr
) || DECL_ARTIFICIAL (SSA_NAME_VAR (ptr
))))
3891 location_t loc
= gimple_location (stmt
);
3892 tree realloc_decl
= gimple_call_fndecl (realloc_stmt
);
3893 tree dealloc_decl
= gimple_call_fndecl (stmt
);
3894 if (ptr
&& !warning_at (loc
, OPT_Wmismatched_dealloc
,
3895 "%qD called on pointer %qE passed to mismatched "
3896 "allocation function %qD",
3897 dealloc_decl
, ptr
, realloc_decl
))
3899 if (!ptr
&& !warning_at (loc
, OPT_Wmismatched_dealloc
,
3900 "%qD called on a pointer passed to mismatched "
3901 "reallocation function %qD",
3902 dealloc_decl
, realloc_decl
))
3905 inform (gimple_location (realloc_stmt
),
3906 "call to %qD", realloc_decl
);
3910 /* Return true if P and Q point to the same object, and false if they
3911 either don't or their relationship cannot be determined. */
3914 pointers_related_p (gimple
*stmt
, tree p
, tree q
, pointer_query
&qry
)
3916 if (!ptr_derefs_may_alias_p (p
, q
))
3919 /* TODO: Work harder to rule out relatedness. */
3920 access_ref pref
, qref
;
3921 if (!qry
.get_ref (p
, stmt
, &pref
, 0)
3922 || !qry
.get_ref (q
, stmt
, &qref
, 0))
3925 return pref
.ref
== qref
.ref
;
3928 /* For a STMT either a call to a deallocation function or a clobber, warn
3929 for uses of the pointer PTR it was called with (including its copies
3930 or others derived from it by pointer arithmetic). */
3933 pass_waccess::check_pointer_uses (gimple
*stmt
, tree ptr
)
3935 gcc_assert (TREE_CODE (ptr
) == SSA_NAME
);
3937 const bool check_dangling
= !is_gimple_call (stmt
);
3938 basic_block stmt_bb
= gimple_bb (stmt
);
3940 /* If STMT is a reallocation function set to the reallocated pointer
3941 and the LHS of the call, respectively. */
3942 tree realloc_ptr
= NULL_TREE
;
3943 tree realloc_lhs
= get_realloc_lhs (stmt
, &realloc_ptr
);
3945 auto_bitmap visited
;
3947 auto_vec
<tree
> pointers
;
3948 pointers
.safe_push (ptr
);
3950 /* Starting with PTR, iterate over POINTERS added by the loop, and
3951 either warn for their uses in basic blocks dominated by the STMT
3952 or in statements that follow it in the same basic block, or add
3953 them to POINTERS if they point into the same object as PTR (i.e.,
3954 are obtained by pointer arithmetic on PTR). */
3955 for (unsigned i
= 0; i
!= pointers
.length (); ++i
)
3957 tree ptr
= pointers
[i
];
3958 if (TREE_CODE (ptr
) == SSA_NAME
3959 && !bitmap_set_bit (visited
, SSA_NAME_VERSION (ptr
)))
3960 /* Avoid revisiting the same pointer. */
3963 use_operand_p use_p
;
3964 imm_use_iterator iter
;
3965 FOR_EACH_IMM_USE_FAST (use_p
, iter
, ptr
)
3967 gimple
*use_stmt
= USE_STMT (use_p
);
3968 if (use_stmt
== stmt
|| is_gimple_debug (use_stmt
))
3973 /* Check to see if USE_STMT is a mismatched deallocation
3974 call for the pointer passed to realloc. That's a bug
3975 regardless of the pointer's value and so warn. */
3976 if (maybe_warn_mismatched_realloc (*use_p
->use
, stmt
, use_stmt
))
3979 /* Pointers passed to realloc that are used in basic blocks
3980 where the realloc call is known to have failed are valid.
3981 Ignore pointers that nothing is known about. Those could
3982 have escaped along with their nullness. */
3984 if (m_ptr_qry
.rvals
->range_of_expr (vr
, realloc_lhs
, use_stmt
))
3989 if (!pointers_related_p (stmt
, ptr
, realloc_ptr
, m_ptr_qry
))
3995 && gimple_code (use_stmt
) == GIMPLE_RETURN
)
3996 /* Avoid interfering with -Wreturn-local-addr (which runs only
3997 with optimization enabled so it won't diagnose cases that
3998 would be caught here when optimization is disabled). */
4001 bool equality
= false;
4002 if (is_gimple_assign (use_stmt
))
4004 tree_code code
= gimple_assign_rhs_code (use_stmt
);
4005 equality
= code
== EQ_EXPR
|| code
== NE_EXPR
;
4007 else if (gcond
*cond
= dyn_cast
<gcond
*>(use_stmt
))
4009 tree_code code
= gimple_cond_code (cond
);
4010 equality
= code
== EQ_EXPR
|| code
== NE_EXPR
;
4013 /* Warn if USE_STMT is dominated by the deallocation STMT.
4014 Otherwise, add the pointer to POINTERS so that the uses
4015 of any other pointers derived from it can be checked. */
4016 if (use_after_inval_p (stmt
, use_stmt
))
4018 /* TODO: Handle PHIs but careful of false positives. */
4019 if (gimple_code (use_stmt
) != GIMPLE_PHI
)
4021 basic_block use_bb
= gimple_bb (use_stmt
);
4023 = !dominated_by_p (CDI_POST_DOMINATORS
, use_bb
, stmt_bb
);
4024 warn_invalid_pointer (*use_p
->use
, use_stmt
, stmt
,
4025 this_maybe
, equality
);
4030 if (is_gimple_assign (use_stmt
))
4032 tree lhs
= gimple_assign_lhs (use_stmt
);
4033 if (TREE_CODE (lhs
) == SSA_NAME
)
4035 tree_code rhs_code
= gimple_assign_rhs_code (use_stmt
);
4036 if (rhs_code
== POINTER_PLUS_EXPR
|| rhs_code
== SSA_NAME
)
4037 pointers
.safe_push (lhs
);
4042 if (gcall
*call
= dyn_cast
<gcall
*>(use_stmt
))
4044 if (gimple_call_return_arg (call
))
4045 if (tree lhs
= gimple_call_lhs (call
))
4046 if (TREE_CODE (lhs
) == SSA_NAME
)
4047 pointers
.safe_push (lhs
);
4054 /* Check call STMT for invalid accesses. */
4057 pass_waccess::check_call (gcall
*stmt
)
4059 if (gimple_call_builtin_p (stmt
, BUILT_IN_NORMAL
))
4060 check_builtin (stmt
);
4062 if (tree callee
= gimple_call_fndecl (stmt
))
4064 /* Check for uses of the pointer passed to either a standard
4065 or a user-defined deallocation function. */
4066 unsigned argno
= fndecl_dealloc_argno (callee
);
4067 if (argno
< (unsigned) call_nargs (stmt
))
4069 tree arg
= call_arg (stmt
, argno
);
4070 if (TREE_CODE (arg
) == SSA_NAME
)
4071 check_pointer_uses (stmt
, arg
);
4075 check_call_access (stmt
);
4077 maybe_check_dealloc_call (stmt
);
4078 check_nonstring_args (stmt
);
4082 /* Check basic block BB for invalid accesses. */
4085 pass_waccess::check_block (basic_block bb
)
4087 /* Iterate over statements, looking for function calls. */
4088 for (auto si
= gsi_start_bb (bb
); !gsi_end_p (si
);
4089 gsi_next_nondebug (&si
))
4091 gimple
*stmt
= gsi_stmt (si
);
4092 if (gcall
*call
= dyn_cast
<gcall
*> (stmt
))
4097 /* Return the argument that the call STMT to a built-in function returns
4098 (including with an offset) or null if it doesn't. */
4101 pass_waccess::gimple_call_return_arg (gcall
*call
)
4103 /* Check for attribute fn spec to see if the function returns one
4104 of its arguments. */
4105 attr_fnspec fnspec
= gimple_call_fnspec (call
);
4107 if (!fnspec
.returns_arg (&argno
))
4109 if (gimple_call_num_args (call
) < 1)
4112 if (!gimple_call_builtin_p (call
, BUILT_IN_NORMAL
))
4115 tree fndecl
= gimple_call_fndecl (call
);
4116 switch (DECL_FUNCTION_CODE (fndecl
))
4118 case BUILT_IN_MEMPCPY
:
4119 case BUILT_IN_MEMPCPY_CHK
:
4120 case BUILT_IN_MEMCHR
:
4121 case BUILT_IN_STRCHR
:
4122 case BUILT_IN_STRRCHR
:
4123 case BUILT_IN_STRSTR
:
4124 case BUILT_IN_STPCPY
:
4125 case BUILT_IN_STPCPY_CHK
:
4126 case BUILT_IN_STPNCPY
:
4127 case BUILT_IN_STPNCPY_CHK
:
4136 if (gimple_call_num_args (call
) <= argno
)
4139 return gimple_call_arg (call
, argno
);
4142 /* Check function FUN for invalid accesses. */
4145 pass_waccess::execute (function
*fun
)
4147 calculate_dominance_info (CDI_DOMINATORS
);
4148 calculate_dominance_info (CDI_POST_DOMINATORS
);
4150 /* Create a new ranger instance and associate it with FUN. */
4151 m_ptr_qry
.rvals
= enable_ranger (fun
);
4154 auto_bitmap
bb_uids_set (&bitmap_default_obstack
);
4155 m_bb_uids_set
= bb_uids_set
;
4157 set_gimple_stmt_max_uid (m_func
, 0);
4160 FOR_EACH_BB_FN (bb
, fun
)
4164 m_ptr_qry
.dump (dump_file
, (dump_flags
& TDF_DETAILS
) != 0);
4166 m_ptr_qry
.flush_cache ();
4168 /* Release the ranger instance and replace it with a global ranger.
4169 Also reset the pointer since calling disable_ranger() deletes it. */
4170 disable_ranger (fun
);
4171 m_ptr_qry
.rvals
= NULL
;
4173 m_bb_uids_set
= NULL
;
4175 free_dominance_info (CDI_POST_DOMINATORS
);
4176 free_dominance_info (CDI_DOMINATORS
);
4182 /* Return a new instance of the pass. */
4185 make_pass_warn_access (gcc::context
*ctxt
)
4187 return new pass_waccess (ctxt
);