]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/gimple-ssa-warn-access.cc
Update copyright years.
[thirdparty/gcc.git] / gcc / gimple-ssa-warn-access.cc
1 /* Pass to detect and issue warnings for invalid accesses, including
2 invalid or mismatched allocation/deallocation calls.
3
4 Copyright (C) 2020-2022 Free Software Foundation, Inc.
5 Contributed by Martin Sebor <msebor@redhat.com>.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
17 for more details.
18
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/>. */
22
23 #define INCLUDE_STRING
24 #include "config.h"
25 #include "system.h"
26 #include "coretypes.h"
27 #include "backend.h"
28 #include "tree.h"
29 #include "gimple.h"
30 #include "tree-pass.h"
31 #include "builtins.h"
32 #include "ssa.h"
33 #include "gimple-pretty-print.h"
34 #include "gimple-ssa-warn-access.h"
35 #include "gimple-ssa-warn-restrict.h"
36 #include "diagnostic-core.h"
37 #include "fold-const.h"
38 #include "gimple-fold.h"
39 #include "gimple-iterator.h"
40 #include "langhooks.h"
41 #include "tree-dfa.h"
42 #include "tree-ssa.h"
43 #include "tree-cfg.h"
44 #include "tree-object-size.h"
45 #include "tree-ssa-strlen.h"
46 #include "calls.h"
47 #include "cfgloop.h"
48 #include "intl.h"
49 #include "gimple-range.h"
50 #include "stringpool.h"
51 #include "attribs.h"
52 #include "demangle.h"
53 #include "pointer-query.h"
54
55 /* Return true if tree node X has an associated location. */
56
57 static inline location_t
58 has_location (const_tree x)
59 {
60 if (DECL_P (x))
61 return DECL_SOURCE_LOCATION (x) != UNKNOWN_LOCATION;
62
63 if (EXPR_P (x))
64 return EXPR_HAS_LOCATION (x);
65
66 return false;
67 }
68
69 /* Return the associated location of STMT. */
70
71 static inline location_t
72 get_location (const gimple *stmt)
73 {
74 return gimple_location (stmt);
75 }
76
77 /* Return the associated location of tree node X. */
78
79 static inline location_t
80 get_location (tree x)
81 {
82 if (DECL_P (x))
83 return DECL_SOURCE_LOCATION (x);
84
85 if (EXPR_P (x))
86 return EXPR_LOCATION (x);
87
88 return UNKNOWN_LOCATION;
89 }
90
91 /* Overload of the nascent tree function for GIMPLE STMT. */
92
93 static inline tree
94 get_callee_fndecl (const gimple *stmt)
95 {
96 return gimple_call_fndecl (stmt);
97 }
98
99 static inline unsigned
100 call_nargs (const gimple *stmt)
101 {
102 return gimple_call_num_args (stmt);
103 }
104
105 static inline unsigned
106 call_nargs (const_tree expr)
107 {
108 return call_expr_nargs (expr);
109 }
110
111
112 static inline tree
113 call_arg (const gimple *stmt, unsigned argno)
114 {
115 return gimple_call_arg (stmt, argno);
116 }
117
118 static inline tree
119 call_arg (tree expr, unsigned argno)
120 {
121 return CALL_EXPR_ARG (expr, argno);
122 }
123
124 /* For a call EXPR at LOC to a function FNAME that expects a string
125 in the argument ARG, issue a diagnostic due to it being a called
126 with an argument that is a character array with no terminating
127 NUL. SIZE is the EXACT size of the array, and BNDRNG the number
128 of characters in which the NUL is expected. Either EXPR or FNAME
129 may be null but noth both. SIZE may be null when BNDRNG is null. */
130
131 template <class GimpleOrTree>
132 static void
133 warn_string_no_nul (location_t loc, GimpleOrTree expr, const char *fname,
134 tree arg, tree decl, tree size, bool exact,
135 const wide_int bndrng[2] /* = NULL */)
136 {
137 const opt_code opt = OPT_Wstringop_overread;
138 if ((expr && warning_suppressed_p (expr, opt))
139 || warning_suppressed_p (arg, opt))
140 return;
141
142 loc = expansion_point_location_if_in_system_header (loc);
143 bool warned;
144
145 /* Format the bound range as a string to keep the nuber of messages
146 from exploding. */
147 char bndstr[80];
148 *bndstr = 0;
149 if (bndrng)
150 {
151 if (bndrng[0] == bndrng[1])
152 sprintf (bndstr, "%llu", (unsigned long long) bndrng[0].to_uhwi ());
153 else
154 sprintf (bndstr, "[%llu, %llu]",
155 (unsigned long long) bndrng[0].to_uhwi (),
156 (unsigned long long) bndrng[1].to_uhwi ());
157 }
158
159 const tree maxobjsize = max_object_size ();
160 const wide_int maxsiz = wi::to_wide (maxobjsize);
161 if (expr)
162 {
163 tree func = get_callee_fndecl (expr);
164 if (bndrng)
165 {
166 if (wi::ltu_p (maxsiz, bndrng[0]))
167 warned = warning_at (loc, opt,
168 "%qD specified bound %s exceeds "
169 "maximum object size %E",
170 func, bndstr, maxobjsize);
171 else
172 {
173 bool maybe = wi::to_wide (size) == bndrng[0];
174 warned = warning_at (loc, opt,
175 exact
176 ? G_("%qD specified bound %s exceeds "
177 "the size %E of unterminated array")
178 : (maybe
179 ? G_("%qD specified bound %s may "
180 "exceed the size of at most %E "
181 "of unterminated array")
182 : G_("%qD specified bound %s exceeds "
183 "the size of at most %E "
184 "of unterminated array")),
185 func, bndstr, size);
186 }
187 }
188 else
189 warned = warning_at (loc, opt,
190 "%qD argument missing terminating nul",
191 func);
192 }
193 else
194 {
195 if (bndrng)
196 {
197 if (wi::ltu_p (maxsiz, bndrng[0]))
198 warned = warning_at (loc, opt,
199 "%qs specified bound %s exceeds "
200 "maximum object size %E",
201 fname, bndstr, maxobjsize);
202 else
203 {
204 bool maybe = wi::to_wide (size) == bndrng[0];
205 warned = warning_at (loc, opt,
206 exact
207 ? G_("%qs specified bound %s exceeds "
208 "the size %E of unterminated array")
209 : (maybe
210 ? G_("%qs specified bound %s may "
211 "exceed the size of at most %E "
212 "of unterminated array")
213 : G_("%qs specified bound %s exceeds "
214 "the size of at most %E "
215 "of unterminated array")),
216 fname, bndstr, size);
217 }
218 }
219 else
220 warned = warning_at (loc, opt,
221 "%qs argument missing terminating nul",
222 fname);
223 }
224
225 if (warned)
226 {
227 inform (get_location (decl),
228 "referenced argument declared here");
229 suppress_warning (arg, opt);
230 if (expr)
231 suppress_warning (expr, opt);
232 }
233 }
234
235 void
236 warn_string_no_nul (location_t loc, gimple *stmt, const char *fname,
237 tree arg, tree decl, tree size /* = NULL_TREE */,
238 bool exact /* = false */,
239 const wide_int bndrng[2] /* = NULL */)
240 {
241 return warn_string_no_nul<gimple *> (loc, stmt, fname,
242 arg, decl, size, exact, bndrng);
243 }
244
245 void
246 warn_string_no_nul (location_t loc, tree expr, const char *fname,
247 tree arg, tree decl, tree size /* = NULL_TREE */,
248 bool exact /* = false */,
249 const wide_int bndrng[2] /* = NULL */)
250 {
251 return warn_string_no_nul<tree> (loc, expr, fname,
252 arg, decl, size, exact, bndrng);
253 }
254
255 /* If EXP refers to an unterminated constant character array return
256 the declaration of the object of which the array is a member or
257 element and if SIZE is not null, set *SIZE to the size of
258 the unterminated array and set *EXACT if the size is exact or
259 clear it otherwise. Otherwise return null. */
260
261 tree
262 unterminated_array (tree exp, tree *size /* = NULL */, bool *exact /* = NULL */)
263 {
264 /* C_STRLEN will return NULL and set DECL in the info
265 structure if EXP references a unterminated array. */
266 c_strlen_data lendata = { };
267 tree len = c_strlen (exp, 1, &lendata);
268 if (len || !lendata.minlen || !lendata.decl)
269 return NULL_TREE;
270
271 if (!size)
272 return lendata.decl;
273
274 len = lendata.minlen;
275 if (lendata.off)
276 {
277 /* Constant offsets are already accounted for in LENDATA.MINLEN,
278 but not in a SSA_NAME + CST expression. */
279 if (TREE_CODE (lendata.off) == INTEGER_CST)
280 *exact = true;
281 else if (TREE_CODE (lendata.off) == PLUS_EXPR
282 && TREE_CODE (TREE_OPERAND (lendata.off, 1)) == INTEGER_CST)
283 {
284 /* Subtract the offset from the size of the array. */
285 *exact = false;
286 tree temp = TREE_OPERAND (lendata.off, 1);
287 temp = fold_convert (ssizetype, temp);
288 len = fold_build2 (MINUS_EXPR, ssizetype, len, temp);
289 }
290 else
291 *exact = false;
292 }
293 else
294 *exact = true;
295
296 *size = len;
297 return lendata.decl;
298 }
299
300 /* For a call EXPR (which may be null) that expects a string argument
301 SRC as an argument, returns false if SRC is a character array with
302 no terminating NUL. When nonnull, BOUND is the number of characters
303 in which to expect the terminating NUL. When EXPR is nonnull also
304 issues a warning. */
305
306 template <class GimpleOrTree>
307 static bool
308 check_nul_terminated_array (GimpleOrTree expr, tree src, tree bound)
309 {
310 /* The constant size of the array SRC points to. The actual size
311 may be less of EXACT is true, but not more. */
312 tree size;
313 /* True if SRC involves a non-constant offset into the array. */
314 bool exact;
315 /* The unterminated constant array SRC points to. */
316 tree nonstr = unterminated_array (src, &size, &exact);
317 if (!nonstr)
318 return true;
319
320 /* NONSTR refers to the non-nul terminated constant array and SIZE
321 is the constant size of the array in bytes. EXACT is true when
322 SIZE is exact. */
323
324 wide_int bndrng[2];
325 if (bound)
326 {
327 value_range r;
328
329 get_global_range_query ()->range_of_expr (r, bound);
330
331 if (r.kind () != VR_RANGE)
332 return true;
333
334 bndrng[0] = r.lower_bound ();
335 bndrng[1] = r.upper_bound ();
336
337 if (exact)
338 {
339 if (wi::leu_p (bndrng[0], wi::to_wide (size)))
340 return true;
341 }
342 else if (wi::lt_p (bndrng[0], wi::to_wide (size), UNSIGNED))
343 return true;
344 }
345
346 if (expr)
347 warn_string_no_nul (get_location (expr), expr, NULL, src, nonstr,
348 size, exact, bound ? bndrng : NULL);
349
350 return false;
351 }
352
353 bool
354 check_nul_terminated_array (gimple *stmt, tree src, tree bound /* = NULL_TREE */)
355 {
356 return check_nul_terminated_array<gimple *>(stmt, src, bound);
357 }
358
359 bool
360 check_nul_terminated_array (tree expr, tree src, tree bound /* = NULL_TREE */)
361 {
362 return check_nul_terminated_array<tree>(expr, src, bound);
363 }
364
365 /* Warn about passing a non-string array/pointer to a built-in function
366 that expects a nul-terminated string argument. Returns true if
367 a warning has been issued.*/
368
369 template <class GimpleOrTree>
370 static bool
371 maybe_warn_nonstring_arg (tree fndecl, GimpleOrTree exp)
372 {
373 if (!fndecl || !fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
374 return false;
375
376 if (!warn_stringop_overread
377 || warning_suppressed_p (exp, OPT_Wstringop_overread))
378 return false;
379
380 /* Avoid clearly invalid calls (more checking done below). */
381 unsigned nargs = call_nargs (exp);
382 if (!nargs)
383 return false;
384
385 /* The bound argument to a bounded string function like strncpy. */
386 tree bound = NULL_TREE;
387
388 /* The longest known or possible string argument to one of the comparison
389 functions. If the length is less than the bound it is used instead.
390 Since the length is only used for warning and not for code generation
391 disable strict mode in the calls to get_range_strlen below. */
392 tree maxlen = NULL_TREE;
393
394 /* It's safe to call "bounded" string functions with a non-string
395 argument since the functions provide an explicit bound for this
396 purpose. The exception is strncat where the bound may refer to
397 either the destination or the source. */
398 int fncode = DECL_FUNCTION_CODE (fndecl);
399 switch (fncode)
400 {
401 case BUILT_IN_STRCMP:
402 case BUILT_IN_STRNCMP:
403 case BUILT_IN_STRNCASECMP:
404 {
405 /* For these, if one argument refers to one or more of a set
406 of string constants or arrays of known size, determine
407 the range of their known or possible lengths and use it
408 conservatively as the bound for the unbounded function,
409 and to adjust the range of the bound of the bounded ones. */
410 for (unsigned argno = 0;
411 argno < MIN (nargs, 2)
412 && !(maxlen && TREE_CODE (maxlen) == INTEGER_CST); argno++)
413 {
414 tree arg = call_arg (exp, argno);
415 if (!get_attr_nonstring_decl (arg))
416 {
417 c_strlen_data lendata = { };
418 /* Set MAXBOUND to an arbitrary non-null non-integer
419 node as a request to have it set to the length of
420 the longest string in a PHI. */
421 lendata.maxbound = arg;
422 get_range_strlen (arg, &lendata, /* eltsize = */ 1);
423 maxlen = lendata.maxbound;
424 }
425 }
426 }
427 /* Fall through. */
428
429 case BUILT_IN_STRNCAT:
430 case BUILT_IN_STPNCPY:
431 case BUILT_IN_STRNCPY:
432 if (nargs > 2)
433 bound = call_arg (exp, 2);
434 break;
435
436 case BUILT_IN_STRNDUP:
437 if (nargs < 2)
438 return false;
439 bound = call_arg (exp, 1);
440 break;
441
442 case BUILT_IN_STRNLEN:
443 {
444 tree arg = call_arg (exp, 0);
445 if (!get_attr_nonstring_decl (arg))
446 {
447 c_strlen_data lendata = { };
448 /* Set MAXBOUND to an arbitrary non-null non-integer
449 node as a request to have it set to the length of
450 the longest string in a PHI. */
451 lendata.maxbound = arg;
452 get_range_strlen (arg, &lendata, /* eltsize = */ 1);
453 maxlen = lendata.maxbound;
454 }
455 if (nargs > 1)
456 bound = call_arg (exp, 1);
457 break;
458 }
459
460 default:
461 break;
462 }
463
464 /* Determine the range of the bound argument (if specified). */
465 tree bndrng[2] = { NULL_TREE, NULL_TREE };
466 if (bound)
467 {
468 STRIP_NOPS (bound);
469 get_size_range (bound, bndrng);
470 }
471
472 location_t loc = get_location (exp);
473
474 if (bndrng[0])
475 {
476 /* Diagnose excessive bound prior to the adjustment below and
477 regardless of attribute nonstring. */
478 tree maxobjsize = max_object_size ();
479 if (tree_int_cst_lt (maxobjsize, bndrng[0]))
480 {
481 bool warned = false;
482 if (tree_int_cst_equal (bndrng[0], bndrng[1]))
483 warned = warning_at (loc, OPT_Wstringop_overread,
484 "%qD specified bound %E "
485 "exceeds maximum object size %E",
486 fndecl, bndrng[0], maxobjsize);
487 else
488 warned = warning_at (loc, OPT_Wstringop_overread,
489 "%qD specified bound [%E, %E] "
490 "exceeds maximum object size %E",
491 fndecl, bndrng[0], bndrng[1],
492 maxobjsize);
493 if (warned)
494 suppress_warning (exp, OPT_Wstringop_overread);
495
496 return warned;
497 }
498 }
499
500 if (maxlen && !integer_all_onesp (maxlen))
501 {
502 /* Add one for the nul. */
503 maxlen = const_binop (PLUS_EXPR, TREE_TYPE (maxlen), maxlen,
504 size_one_node);
505
506 if (!bndrng[0])
507 {
508 /* Conservatively use the upper bound of the lengths for
509 both the lower and the upper bound of the operation. */
510 bndrng[0] = maxlen;
511 bndrng[1] = maxlen;
512 bound = void_type_node;
513 }
514 else if (maxlen)
515 {
516 /* Replace the bound on the operation with the upper bound
517 of the length of the string if the latter is smaller. */
518 if (tree_int_cst_lt (maxlen, bndrng[0]))
519 bndrng[0] = maxlen;
520 else if (tree_int_cst_lt (maxlen, bndrng[1]))
521 bndrng[1] = maxlen;
522 }
523 }
524
525 bool any_arg_warned = false;
526 /* Iterate over the built-in function's formal arguments and check
527 each const char* against the actual argument. If the actual
528 argument is declared attribute non-string issue a warning unless
529 the argument's maximum length is bounded. */
530 function_args_iterator it;
531 function_args_iter_init (&it, TREE_TYPE (fndecl));
532
533 for (unsigned argno = 0; ; ++argno, function_args_iter_next (&it))
534 {
535 /* Avoid iterating past the declared argument in a call
536 to function declared without a prototype. */
537 if (argno >= nargs)
538 break;
539
540 tree argtype = function_args_iter_cond (&it);
541 if (!argtype)
542 break;
543
544 if (TREE_CODE (argtype) != POINTER_TYPE)
545 continue;
546
547 argtype = TREE_TYPE (argtype);
548
549 if (TREE_CODE (argtype) != INTEGER_TYPE
550 || !TYPE_READONLY (argtype))
551 continue;
552
553 argtype = TYPE_MAIN_VARIANT (argtype);
554 if (argtype != char_type_node)
555 continue;
556
557 tree callarg = call_arg (exp, argno);
558 if (TREE_CODE (callarg) == ADDR_EXPR)
559 callarg = TREE_OPERAND (callarg, 0);
560
561 /* See if the destination is declared with attribute "nonstring". */
562 tree decl = get_attr_nonstring_decl (callarg);
563 if (!decl)
564 continue;
565
566 /* The maximum number of array elements accessed. */
567 offset_int wibnd = 0;
568
569 if (argno && fncode == BUILT_IN_STRNCAT)
570 {
571 /* See if the bound in strncat is derived from the length
572 of the strlen of the destination (as it's expected to be).
573 If so, reset BOUND and FNCODE to trigger a warning. */
574 tree dstarg = call_arg (exp, 0);
575 if (is_strlen_related_p (dstarg, bound))
576 {
577 /* The bound applies to the destination, not to the source,
578 so reset these to trigger a warning without mentioning
579 the bound. */
580 bound = NULL;
581 fncode = 0;
582 }
583 else if (bndrng[1])
584 /* Use the upper bound of the range for strncat. */
585 wibnd = wi::to_offset (bndrng[1]);
586 }
587 else if (bndrng[0])
588 /* Use the lower bound of the range for functions other than
589 strncat. */
590 wibnd = wi::to_offset (bndrng[0]);
591
592 /* Determine the size of the argument array if it is one. */
593 offset_int asize = wibnd;
594 bool known_size = false;
595 tree type = TREE_TYPE (decl);
596
597 /* Determine the array size. For arrays of unknown bound and
598 pointers reset BOUND to trigger the appropriate warning. */
599 if (TREE_CODE (type) == ARRAY_TYPE)
600 {
601 if (tree arrbnd = TYPE_DOMAIN (type))
602 {
603 if ((arrbnd = TYPE_MAX_VALUE (arrbnd)))
604 {
605 asize = wi::to_offset (arrbnd) + 1;
606 known_size = true;
607 }
608 }
609 else if (bound == void_type_node)
610 bound = NULL_TREE;
611 }
612 else if (bound == void_type_node)
613 bound = NULL_TREE;
614
615 /* In a call to strncat with a bound in a range whose lower but
616 not upper bound is less than the array size, reset ASIZE to
617 be the same as the bound and the other variable to trigger
618 the apprpriate warning below. */
619 if (fncode == BUILT_IN_STRNCAT
620 && bndrng[0] != bndrng[1]
621 && wi::ltu_p (wi::to_offset (bndrng[0]), asize)
622 && (!known_size
623 || wi::ltu_p (asize, wibnd)))
624 {
625 asize = wibnd;
626 bound = NULL_TREE;
627 fncode = 0;
628 }
629
630 bool warned = false;
631
632 auto_diagnostic_group d;
633 if (wi::ltu_p (asize, wibnd))
634 {
635 if (bndrng[0] == bndrng[1])
636 warned = warning_at (loc, OPT_Wstringop_overread,
637 "%qD argument %i declared attribute "
638 "%<nonstring%> is smaller than the specified "
639 "bound %wu",
640 fndecl, argno + 1, wibnd.to_uhwi ());
641 else if (wi::ltu_p (asize, wi::to_offset (bndrng[0])))
642 warned = warning_at (loc, OPT_Wstringop_overread,
643 "%qD argument %i declared attribute "
644 "%<nonstring%> is smaller than "
645 "the specified bound [%E, %E]",
646 fndecl, argno + 1, bndrng[0], bndrng[1]);
647 else
648 warned = warning_at (loc, OPT_Wstringop_overread,
649 "%qD argument %i declared attribute "
650 "%<nonstring%> may be smaller than "
651 "the specified bound [%E, %E]",
652 fndecl, argno + 1, bndrng[0], bndrng[1]);
653 }
654 else if (fncode == BUILT_IN_STRNCAT)
655 ; /* Avoid warning for calls to strncat() when the bound
656 is equal to the size of the non-string argument. */
657 else if (!bound)
658 warned = warning_at (loc, OPT_Wstringop_overread,
659 "%qD argument %i declared attribute %<nonstring%>",
660 fndecl, argno + 1);
661
662 if (warned)
663 {
664 inform (DECL_SOURCE_LOCATION (decl),
665 "argument %qD declared here", decl);
666 any_arg_warned = true;
667 }
668 }
669
670 if (any_arg_warned)
671 suppress_warning (exp, OPT_Wstringop_overread);
672
673 return any_arg_warned;
674 }
675
676 bool
677 maybe_warn_nonstring_arg (tree fndecl, gimple *stmt)
678 {
679 return maybe_warn_nonstring_arg<gimple *>(fndecl, stmt);
680 }
681
682
683 bool
684 maybe_warn_nonstring_arg (tree fndecl, tree expr)
685 {
686 return maybe_warn_nonstring_arg<tree>(fndecl, expr);
687 }
688
689 /* Issue a warning OPT for a bounded call EXP with a bound in RANGE
690 accessing an object with SIZE. */
691
692 template <class GimpleOrTree>
693 static bool
694 maybe_warn_for_bound (opt_code opt, location_t loc, GimpleOrTree exp, tree func,
695 tree bndrng[2], tree size, const access_data *pad)
696 {
697 if (!bndrng[0] || warning_suppressed_p (exp, opt))
698 return false;
699
700 tree maxobjsize = max_object_size ();
701
702 bool warned = false;
703
704 if (opt == OPT_Wstringop_overread)
705 {
706 bool maybe = pad && pad->src.phi ();
707 if (maybe)
708 {
709 /* Issue a "maybe" warning only if the PHI refers to objects
710 at least one of which has more space remaining than the bound.
711 Otherwise, if the bound is greater, use the definitive form. */
712 offset_int remmax = pad->src.size_remaining ();
713 if (remmax < wi::to_offset (bndrng[0]))
714 maybe = false;
715 }
716
717 if (tree_int_cst_lt (maxobjsize, bndrng[0]))
718 {
719 if (bndrng[0] == bndrng[1])
720 warned = (func
721 ? warning_at (loc, opt,
722 (maybe
723 ? G_("%qD specified bound %E may "
724 "exceed maximum object size %E")
725 : G_("%qD specified bound %E "
726 "exceeds maximum object size %E")),
727 func, bndrng[0], maxobjsize)
728 : warning_at (loc, opt,
729 (maybe
730 ? G_("specified bound %E may "
731 "exceed maximum object size %E")
732 : G_("specified bound %E "
733 "exceeds maximum object size %E")),
734 bndrng[0], maxobjsize));
735 else
736 warned = (func
737 ? warning_at (loc, opt,
738 (maybe
739 ? G_("%qD specified bound [%E, %E] may "
740 "exceed maximum object size %E")
741 : G_("%qD specified bound [%E, %E] "
742 "exceeds maximum object size %E")),
743 func,
744 bndrng[0], bndrng[1], maxobjsize)
745 : warning_at (loc, opt,
746 (maybe
747 ? G_("specified bound [%E, %E] may "
748 "exceed maximum object size %E")
749 : G_("specified bound [%E, %E] "
750 "exceeds maximum object size %E")),
751 bndrng[0], bndrng[1], maxobjsize));
752 }
753 else if (!size || tree_int_cst_le (bndrng[0], size))
754 return false;
755 else if (tree_int_cst_equal (bndrng[0], bndrng[1]))
756 warned = (func
757 ? warning_at (loc, opt,
758 (maybe
759 ? G_("%qD specified bound %E may exceed "
760 "source size %E")
761 : G_("%qD specified bound %E exceeds "
762 "source size %E")),
763 func, bndrng[0], size)
764 : warning_at (loc, opt,
765 (maybe
766 ? G_("specified bound %E may exceed "
767 "source size %E")
768 : G_("specified bound %E exceeds "
769 "source size %E")),
770 bndrng[0], size));
771 else
772 warned = (func
773 ? warning_at (loc, opt,
774 (maybe
775 ? G_("%qD specified bound [%E, %E] may "
776 "exceed source size %E")
777 : G_("%qD specified bound [%E, %E] exceeds "
778 "source size %E")),
779 func, bndrng[0], bndrng[1], size)
780 : warning_at (loc, opt,
781 (maybe
782 ? G_("specified bound [%E, %E] may exceed "
783 "source size %E")
784 : G_("specified bound [%E, %E] exceeds "
785 "source size %E")),
786 bndrng[0], bndrng[1], size));
787 if (warned)
788 {
789 if (pad && pad->src.ref
790 && has_location (pad->src.ref))
791 inform (get_location (pad->src.ref),
792 "source object allocated here");
793 suppress_warning (exp, opt);
794 }
795
796 return warned;
797 }
798
799 bool maybe = pad && pad->dst.phi ();
800 if (maybe)
801 {
802 /* Issue a "maybe" warning only if the PHI refers to objects
803 at least one of which has more space remaining than the bound.
804 Otherwise, if the bound is greater, use the definitive form. */
805 offset_int remmax = pad->dst.size_remaining ();
806 if (remmax < wi::to_offset (bndrng[0]))
807 maybe = false;
808 }
809 if (tree_int_cst_lt (maxobjsize, bndrng[0]))
810 {
811 if (bndrng[0] == bndrng[1])
812 warned = (func
813 ? warning_at (loc, opt,
814 (maybe
815 ? G_("%qD specified size %E may "
816 "exceed maximum object size %E")
817 : G_("%qD specified size %E "
818 "exceeds maximum object size %E")),
819 func, bndrng[0], maxobjsize)
820 : warning_at (loc, opt,
821 (maybe
822 ? G_("specified size %E may exceed "
823 "maximum object size %E")
824 : G_("specified size %E exceeds "
825 "maximum object size %E")),
826 bndrng[0], maxobjsize));
827 else
828 warned = (func
829 ? warning_at (loc, opt,
830 (maybe
831 ? G_("%qD specified size between %E and %E "
832 "may exceed maximum object size %E")
833 : G_("%qD specified size between %E and %E "
834 "exceeds maximum object size %E")),
835 func, bndrng[0], bndrng[1], maxobjsize)
836 : warning_at (loc, opt,
837 (maybe
838 ? G_("specified size between %E and %E "
839 "may exceed maximum object size %E")
840 : G_("specified size between %E and %E "
841 "exceeds maximum object size %E")),
842 bndrng[0], bndrng[1], maxobjsize));
843 }
844 else if (!size || tree_int_cst_le (bndrng[0], size))
845 return false;
846 else if (tree_int_cst_equal (bndrng[0], bndrng[1]))
847 warned = (func
848 ? warning_at (loc, opt,
849 (maybe
850 ? G_("%qD specified bound %E may exceed "
851 "destination size %E")
852 : G_("%qD specified bound %E exceeds "
853 "destination size %E")),
854 func, bndrng[0], size)
855 : warning_at (loc, opt,
856 (maybe
857 ? G_("specified bound %E may exceed "
858 "destination size %E")
859 : G_("specified bound %E exceeds "
860 "destination size %E")),
861 bndrng[0], size));
862 else
863 warned = (func
864 ? warning_at (loc, opt,
865 (maybe
866 ? G_("%qD specified bound [%E, %E] may exceed "
867 "destination size %E")
868 : G_("%qD specified bound [%E, %E] exceeds "
869 "destination size %E")),
870 func, bndrng[0], bndrng[1], size)
871 : warning_at (loc, opt,
872 (maybe
873 ? G_("specified bound [%E, %E] exceeds "
874 "destination size %E")
875 : G_("specified bound [%E, %E] exceeds "
876 "destination size %E")),
877 bndrng[0], bndrng[1], size));
878
879 if (warned)
880 {
881 if (pad && pad->dst.ref
882 && has_location (pad->dst.ref))
883 inform (get_location (pad->dst.ref),
884 "destination object allocated here");
885 suppress_warning (exp, opt);
886 }
887
888 return warned;
889 }
890
891 bool
892 maybe_warn_for_bound (opt_code opt, location_t loc, gimple *stmt, tree func,
893 tree bndrng[2], tree size,
894 const access_data *pad /* = NULL */)
895 {
896 return maybe_warn_for_bound<gimple *> (opt, loc, stmt, func, bndrng, size,
897 pad);
898 }
899
900 bool
901 maybe_warn_for_bound (opt_code opt, location_t loc, tree expr, tree func,
902 tree bndrng[2], tree size,
903 const access_data *pad /* = NULL */)
904 {
905 return maybe_warn_for_bound<tree> (opt, loc, expr, func, bndrng, size, pad);
906 }
907
908 /* For an expression EXP issue an access warning controlled by option OPT
909 with access to a region SIZE bytes in size in the RANGE of sizes.
910 WRITE is true for a write access, READ for a read access, neither for
911 call that may or may not perform an access but for which the range
912 is expected to valid.
913 Returns true when a warning has been issued. */
914
915 template <class GimpleOrTree>
916 static bool
917 warn_for_access (location_t loc, tree func, GimpleOrTree exp, int opt,
918 tree range[2], tree size, bool write, bool read, bool maybe)
919 {
920 bool warned = false;
921
922 if (write && read)
923 {
924 if (tree_int_cst_equal (range[0], range[1]))
925 warned = (func
926 ? warning_n (loc, opt, tree_to_uhwi (range[0]),
927 (maybe
928 ? G_("%qD may access %E byte in a region "
929 "of size %E")
930 : G_("%qD accessing %E byte in a region "
931 "of size %E")),
932 (maybe
933 ? G_ ("%qD may access %E bytes in a region "
934 "of size %E")
935 : G_ ("%qD accessing %E bytes in a region "
936 "of size %E")),
937 func, range[0], size)
938 : warning_n (loc, opt, tree_to_uhwi (range[0]),
939 (maybe
940 ? G_("may access %E byte in a region "
941 "of size %E")
942 : G_("accessing %E byte in a region "
943 "of size %E")),
944 (maybe
945 ? G_("may access %E bytes in a region "
946 "of size %E")
947 : G_("accessing %E bytes in a region "
948 "of size %E")),
949 range[0], size));
950 else if (tree_int_cst_sign_bit (range[1]))
951 {
952 /* Avoid printing the upper bound if it's invalid. */
953 warned = (func
954 ? warning_at (loc, opt,
955 (maybe
956 ? G_("%qD may access %E or more bytes "
957 "in a region of size %E")
958 : G_("%qD accessing %E or more bytes "
959 "in a region of size %E")),
960 func, range[0], size)
961 : warning_at (loc, opt,
962 (maybe
963 ? G_("may access %E or more bytes "
964 "in a region of size %E")
965 : G_("accessing %E or more bytes "
966 "in a region of size %E")),
967 range[0], size));
968 }
969 else
970 warned = (func
971 ? warning_at (loc, opt,
972 (maybe
973 ? G_("%qD may access between %E and %E "
974 "bytes in a region of size %E")
975 : G_("%qD accessing between %E and %E "
976 "bytes in a region of size %E")),
977 func, range[0], range[1], size)
978 : warning_at (loc, opt,
979 (maybe
980 ? G_("may access between %E and %E bytes "
981 "in a region of size %E")
982 : G_("accessing between %E and %E bytes "
983 "in a region of size %E")),
984 range[0], range[1], size));
985 return warned;
986 }
987
988 if (write)
989 {
990 if (tree_int_cst_equal (range[0], range[1]))
991 warned = (func
992 ? warning_n (loc, opt, tree_to_uhwi (range[0]),
993 (maybe
994 ? G_("%qD may write %E byte into a region "
995 "of size %E")
996 : G_("%qD writing %E byte into a region "
997 "of size %E overflows the destination")),
998 (maybe
999 ? G_("%qD may write %E bytes into a region "
1000 "of size %E")
1001 : G_("%qD writing %E bytes into a region "
1002 "of size %E overflows the destination")),
1003 func, range[0], size)
1004 : warning_n (loc, opt, tree_to_uhwi (range[0]),
1005 (maybe
1006 ? G_("may write %E byte into a region "
1007 "of size %E")
1008 : G_("writing %E byte into a region "
1009 "of size %E overflows the destination")),
1010 (maybe
1011 ? G_("may write %E bytes into a region "
1012 "of size %E")
1013 : G_("writing %E bytes into a region "
1014 "of size %E overflows the destination")),
1015 range[0], size));
1016 else if (tree_int_cst_sign_bit (range[1]))
1017 {
1018 /* Avoid printing the upper bound if it's invalid. */
1019 warned = (func
1020 ? warning_at (loc, opt,
1021 (maybe
1022 ? G_("%qD may write %E or more bytes "
1023 "into a region of size %E")
1024 : G_("%qD writing %E or more bytes "
1025 "into a region of size %E overflows "
1026 "the destination")),
1027 func, range[0], size)
1028 : warning_at (loc, opt,
1029 (maybe
1030 ? G_("may write %E or more bytes into "
1031 "a region of size %E")
1032 : G_("writing %E or more bytes into "
1033 "a region of size %E overflows "
1034 "the destination")),
1035 range[0], size));
1036 }
1037 else
1038 warned = (func
1039 ? warning_at (loc, opt,
1040 (maybe
1041 ? G_("%qD may write between %E and %E bytes "
1042 "into a region of size %E")
1043 : G_("%qD writing between %E and %E bytes "
1044 "into a region of size %E overflows "
1045 "the destination")),
1046 func, range[0], range[1], size)
1047 : warning_at (loc, opt,
1048 (maybe
1049 ? G_("may write between %E and %E bytes "
1050 "into a region of size %E")
1051 : G_("writing between %E and %E bytes "
1052 "into a region of size %E overflows "
1053 "the destination")),
1054 range[0], range[1], size));
1055 return warned;
1056 }
1057
1058 if (read)
1059 {
1060 if (tree_int_cst_equal (range[0], range[1]))
1061 warned = (func
1062 ? warning_n (loc, OPT_Wstringop_overread,
1063 tree_to_uhwi (range[0]),
1064 (maybe
1065 ? G_("%qD may read %E byte from a region "
1066 "of size %E")
1067 : G_("%qD reading %E byte from a region "
1068 "of size %E")),
1069 (maybe
1070 ? G_("%qD may read %E bytes from a region "
1071 "of size %E")
1072 : G_("%qD reading %E bytes from a region "
1073 "of size %E")),
1074 func, range[0], size)
1075 : warning_n (loc, OPT_Wstringop_overread,
1076 tree_to_uhwi (range[0]),
1077 (maybe
1078 ? G_("may read %E byte from a region "
1079 "of size %E")
1080 : G_("reading %E byte from a region "
1081 "of size %E")),
1082 (maybe
1083 ? G_("may read %E bytes from a region "
1084 "of size %E")
1085 : G_("reading %E bytes from a region "
1086 "of size %E")),
1087 range[0], size));
1088 else if (tree_int_cst_sign_bit (range[1]))
1089 {
1090 /* Avoid printing the upper bound if it's invalid. */
1091 warned = (func
1092 ? warning_at (loc, OPT_Wstringop_overread,
1093 (maybe
1094 ? G_("%qD may read %E or more bytes "
1095 "from a region of size %E")
1096 : G_("%qD reading %E or more bytes "
1097 "from a region of size %E")),
1098 func, range[0], size)
1099 : warning_at (loc, OPT_Wstringop_overread,
1100 (maybe
1101 ? G_("may read %E or more bytes "
1102 "from a region of size %E")
1103 : G_("reading %E or more bytes "
1104 "from a region of size %E")),
1105 range[0], size));
1106 }
1107 else
1108 warned = (func
1109 ? warning_at (loc, OPT_Wstringop_overread,
1110 (maybe
1111 ? G_("%qD may read between %E and %E bytes "
1112 "from a region of size %E")
1113 : G_("%qD reading between %E and %E bytes "
1114 "from a region of size %E")),
1115 func, range[0], range[1], size)
1116 : warning_at (loc, opt,
1117 (maybe
1118 ? G_("may read between %E and %E bytes "
1119 "from a region of size %E")
1120 : G_("reading between %E and %E bytes "
1121 "from a region of size %E")),
1122 range[0], range[1], size));
1123
1124 if (warned)
1125 suppress_warning (exp, OPT_Wstringop_overread);
1126
1127 return warned;
1128 }
1129
1130 if (tree_int_cst_equal (range[0], range[1])
1131 || tree_int_cst_sign_bit (range[1]))
1132 warned = (func
1133 ? warning_n (loc, OPT_Wstringop_overread,
1134 tree_to_uhwi (range[0]),
1135 "%qD expecting %E byte in a region of size %E",
1136 "%qD expecting %E bytes in a region of size %E",
1137 func, range[0], size)
1138 : warning_n (loc, OPT_Wstringop_overread,
1139 tree_to_uhwi (range[0]),
1140 "expecting %E byte in a region of size %E",
1141 "expecting %E bytes in a region of size %E",
1142 range[0], size));
1143 else if (tree_int_cst_sign_bit (range[1]))
1144 {
1145 /* Avoid printing the upper bound if it's invalid. */
1146 warned = (func
1147 ? warning_at (loc, OPT_Wstringop_overread,
1148 "%qD expecting %E or more bytes in a region "
1149 "of size %E",
1150 func, range[0], size)
1151 : warning_at (loc, OPT_Wstringop_overread,
1152 "expecting %E or more bytes in a region "
1153 "of size %E",
1154 range[0], size));
1155 }
1156 else
1157 warned = (func
1158 ? warning_at (loc, OPT_Wstringop_overread,
1159 "%qD expecting between %E and %E bytes in "
1160 "a region of size %E",
1161 func, range[0], range[1], size)
1162 : warning_at (loc, OPT_Wstringop_overread,
1163 "expecting between %E and %E bytes in "
1164 "a region of size %E",
1165 range[0], range[1], size));
1166
1167 if (warned)
1168 suppress_warning (exp, OPT_Wstringop_overread);
1169
1170 return warned;
1171 }
1172
1173 static bool
1174 warn_for_access (location_t loc, tree func, gimple *stmt, int opt,
1175 tree range[2], tree size, bool write, bool read, bool maybe)
1176 {
1177 return warn_for_access<gimple *>(loc, func, stmt, opt, range, size,
1178 write, read, maybe);
1179 }
1180
1181 static bool
1182 warn_for_access (location_t loc, tree func, tree expr, int opt,
1183 tree range[2], tree size, bool write, bool read, bool maybe)
1184 {
1185 return warn_for_access<tree>(loc, func, expr, opt, range, size,
1186 write, read, maybe);
1187 }
1188
1189 /* Helper to set RANGE to the range of BOUND if it's nonnull, bounded
1190 by BNDRNG if nonnull and valid. */
1191
1192 static void
1193 get_size_range (range_query *query, tree bound, gimple *stmt, tree range[2],
1194 const offset_int bndrng[2])
1195 {
1196 if (bound)
1197 get_size_range (query, bound, stmt, range);
1198
1199 if (!bndrng || (bndrng[0] == 0 && bndrng[1] == HOST_WIDE_INT_M1U))
1200 return;
1201
1202 if (range[0] && TREE_CODE (range[0]) == INTEGER_CST)
1203 {
1204 offset_int r[] =
1205 { wi::to_offset (range[0]), wi::to_offset (range[1]) };
1206 if (r[0] < bndrng[0])
1207 range[0] = wide_int_to_tree (sizetype, bndrng[0]);
1208 if (bndrng[1] < r[1])
1209 range[1] = wide_int_to_tree (sizetype, bndrng[1]);
1210 }
1211 else
1212 {
1213 range[0] = wide_int_to_tree (sizetype, bndrng[0]);
1214 range[1] = wide_int_to_tree (sizetype, bndrng[1]);
1215 }
1216 }
1217
1218 /* Try to verify that the sizes and lengths of the arguments to a string
1219 manipulation function given by EXP are within valid bounds and that
1220 the operation does not lead to buffer overflow or read past the end.
1221 Arguments other than EXP may be null. When non-null, the arguments
1222 have the following meaning:
1223 DST is the destination of a copy call or NULL otherwise.
1224 SRC is the source of a copy call or NULL otherwise.
1225 DSTWRITE is the number of bytes written into the destination obtained
1226 from the user-supplied size argument to the function (such as in
1227 memcpy(DST, SRCs, DSTWRITE) or strncpy(DST, DRC, DSTWRITE).
1228 MAXREAD is the user-supplied bound on the length of the source sequence
1229 (such as in strncat(d, s, N). It specifies the upper limit on the number
1230 of bytes to write. If NULL, it's taken to be the same as DSTWRITE.
1231 SRCSTR is the source string (such as in strcpy(DST, SRC)) when the
1232 expression EXP is a string function call (as opposed to a memory call
1233 like memcpy). As an exception, SRCSTR can also be an integer denoting
1234 the precomputed size of the source string or object (for functions like
1235 memcpy).
1236 DSTSIZE is the size of the destination object.
1237
1238 When DSTWRITE is null LEN is checked to verify that it doesn't exceed
1239 SIZE_MAX.
1240
1241 WRITE is true for write accesses, READ is true for reads. Both are
1242 false for simple size checks in calls to functions that neither read
1243 from nor write to the region.
1244
1245 When nonnull, PAD points to a more detailed description of the access.
1246
1247 If the call is successfully verified as safe return true, otherwise
1248 return false. */
1249
1250 template <class GimpleOrTree>
1251 static bool
1252 check_access (GimpleOrTree exp, tree dstwrite,
1253 tree maxread, tree srcstr, tree dstsize,
1254 access_mode mode, const access_data *pad,
1255 range_query *rvals)
1256 {
1257 /* The size of the largest object is half the address space, or
1258 PTRDIFF_MAX. (This is way too permissive.) */
1259 tree maxobjsize = max_object_size ();
1260
1261 /* Either an approximate/minimum the length of the source string for
1262 string functions or the size of the source object for raw memory
1263 functions. */
1264 tree slen = NULL_TREE;
1265
1266 /* The range of the access in bytes; first set to the write access
1267 for functions that write and then read for those that also (or
1268 just) read. */
1269 tree range[2] = { NULL_TREE, NULL_TREE };
1270
1271 /* Set to true when the exact number of bytes written by a string
1272 function like strcpy is not known and the only thing that is
1273 known is that it must be at least one (for the terminating nul). */
1274 bool at_least_one = false;
1275 if (srcstr)
1276 {
1277 /* SRCSTR is normally a pointer to string but as a special case
1278 it can be an integer denoting the length of a string. */
1279 if (POINTER_TYPE_P (TREE_TYPE (srcstr)))
1280 {
1281 if (!check_nul_terminated_array (exp, srcstr, maxread))
1282 /* Return if the array is not nul-terminated and a warning
1283 has been issued. */
1284 return false;
1285
1286 /* Try to determine the range of lengths the source string
1287 refers to. If it can be determined and is less than
1288 the upper bound given by MAXREAD add one to it for
1289 the terminating nul. Otherwise, set it to one for
1290 the same reason, or to MAXREAD as appropriate. */
1291 c_strlen_data lendata = { };
1292 get_range_strlen (srcstr, &lendata, /* eltsize = */ 1);
1293 range[0] = lendata.minlen;
1294 range[1] = lendata.maxbound ? lendata.maxbound : lendata.maxlen;
1295 if (range[0]
1296 && TREE_CODE (range[0]) == INTEGER_CST
1297 && TREE_CODE (range[1]) == INTEGER_CST
1298 && (!maxread || TREE_CODE (maxread) == INTEGER_CST))
1299 {
1300 if (maxread && tree_int_cst_le (maxread, range[0]))
1301 range[0] = range[1] = maxread;
1302 else
1303 range[0] = fold_build2 (PLUS_EXPR, size_type_node,
1304 range[0], size_one_node);
1305
1306 if (maxread && tree_int_cst_le (maxread, range[1]))
1307 range[1] = maxread;
1308 else if (!integer_all_onesp (range[1]))
1309 range[1] = fold_build2 (PLUS_EXPR, size_type_node,
1310 range[1], size_one_node);
1311
1312 slen = range[0];
1313 }
1314 else
1315 {
1316 at_least_one = true;
1317 slen = size_one_node;
1318 }
1319 }
1320 else
1321 slen = srcstr;
1322 }
1323
1324 if (!dstwrite && !maxread)
1325 {
1326 /* When the only available piece of data is the object size
1327 there is nothing to do. */
1328 if (!slen)
1329 return true;
1330
1331 /* Otherwise, when the length of the source sequence is known
1332 (as with strlen), set DSTWRITE to it. */
1333 if (!range[0])
1334 dstwrite = slen;
1335 }
1336
1337 if (!dstsize)
1338 dstsize = maxobjsize;
1339
1340 /* Set RANGE to that of DSTWRITE if non-null, bounded by PAD->DST_BNDRNG
1341 if valid. */
1342 gimple *stmt = pad ? pad->stmt : nullptr;
1343 get_size_range (rvals, dstwrite, stmt, range, pad ? pad->dst_bndrng : NULL);
1344
1345 tree func = get_callee_fndecl (exp);
1346 /* Read vs write access by built-ins can be determined from the const
1347 qualifiers on the pointer argument. In the absence of attribute
1348 access, non-const qualified pointer arguments to user-defined
1349 functions are assumed to both read and write the objects. */
1350 const bool builtin = func ? fndecl_built_in_p (func) : false;
1351
1352 /* First check the number of bytes to be written against the maximum
1353 object size. */
1354 if (range[0]
1355 && TREE_CODE (range[0]) == INTEGER_CST
1356 && tree_int_cst_lt (maxobjsize, range[0]))
1357 {
1358 location_t loc = get_location (exp);
1359 maybe_warn_for_bound (OPT_Wstringop_overflow_, loc, exp, func, range,
1360 NULL_TREE, pad);
1361 return false;
1362 }
1363
1364 /* The number of bytes to write is "exact" if DSTWRITE is non-null,
1365 constant, and in range of unsigned HOST_WIDE_INT. */
1366 bool exactwrite = dstwrite && tree_fits_uhwi_p (dstwrite);
1367
1368 /* Next check the number of bytes to be written against the destination
1369 object size. */
1370 if (range[0] || !exactwrite || integer_all_onesp (dstwrite))
1371 {
1372 if (range[0]
1373 && TREE_CODE (range[0]) == INTEGER_CST
1374 && ((tree_fits_uhwi_p (dstsize)
1375 && tree_int_cst_lt (dstsize, range[0]))
1376 || (dstwrite
1377 && tree_fits_uhwi_p (dstwrite)
1378 && tree_int_cst_lt (dstwrite, range[0]))))
1379 {
1380 const opt_code opt = OPT_Wstringop_overflow_;
1381 if (warning_suppressed_p (exp, opt)
1382 || (pad && pad->dst.ref
1383 && warning_suppressed_p (pad->dst.ref, opt)))
1384 return false;
1385
1386 location_t loc = get_location (exp);
1387 bool warned = false;
1388 if (dstwrite == slen && at_least_one)
1389 {
1390 /* This is a call to strcpy with a destination of 0 size
1391 and a source of unknown length. The call will write
1392 at least one byte past the end of the destination. */
1393 warned = (func
1394 ? warning_at (loc, opt,
1395 "%qD writing %E or more bytes into "
1396 "a region of size %E overflows "
1397 "the destination",
1398 func, range[0], dstsize)
1399 : warning_at (loc, opt,
1400 "writing %E or more bytes into "
1401 "a region of size %E overflows "
1402 "the destination",
1403 range[0], dstsize));
1404 }
1405 else
1406 {
1407 const bool read
1408 = mode == access_read_only || mode == access_read_write;
1409 const bool write
1410 = mode == access_write_only || mode == access_read_write;
1411 const bool maybe = pad && pad->dst.parmarray;
1412 warned = warn_for_access (loc, func, exp,
1413 OPT_Wstringop_overflow_,
1414 range, dstsize,
1415 write, read && !builtin, maybe);
1416 }
1417
1418 if (warned)
1419 {
1420 suppress_warning (exp, OPT_Wstringop_overflow_);
1421 if (pad)
1422 pad->dst.inform_access (pad->mode);
1423 }
1424
1425 /* Return error when an overflow has been detected. */
1426 return false;
1427 }
1428 }
1429
1430 /* Check the maximum length of the source sequence against the size
1431 of the destination object if known, or against the maximum size
1432 of an object. */
1433 if (maxread)
1434 {
1435 /* Set RANGE to that of MAXREAD, bounded by PAD->SRC_BNDRNG if
1436 PAD is nonnull and BNDRNG is valid. */
1437 get_size_range (rvals, maxread, stmt, range, pad ? pad->src_bndrng : NULL);
1438
1439 location_t loc = get_location (exp);
1440 tree size = dstsize;
1441 if (pad && pad->mode == access_read_only)
1442 size = wide_int_to_tree (sizetype, pad->src.size_remaining ());
1443
1444 if (range[0] && maxread && tree_fits_uhwi_p (size))
1445 {
1446 if (tree_int_cst_lt (maxobjsize, range[0]))
1447 {
1448 maybe_warn_for_bound (OPT_Wstringop_overread, loc, exp, func,
1449 range, size, pad);
1450 return false;
1451 }
1452
1453 if (size != maxobjsize && tree_int_cst_lt (size, range[0]))
1454 {
1455 opt_code opt = (dstwrite || mode != access_read_only
1456 ? OPT_Wstringop_overflow_
1457 : OPT_Wstringop_overread);
1458 maybe_warn_for_bound (opt, loc, exp, func, range, size, pad);
1459 return false;
1460 }
1461 }
1462
1463 maybe_warn_nonstring_arg (func, exp);
1464 }
1465
1466 /* Check for reading past the end of SRC. */
1467 bool overread = (slen
1468 && slen == srcstr
1469 && dstwrite
1470 && range[0]
1471 && TREE_CODE (slen) == INTEGER_CST
1472 && tree_int_cst_lt (slen, range[0]));
1473 /* If none is determined try to get a better answer based on the details
1474 in PAD. */
1475 if (!overread
1476 && pad
1477 && pad->src.sizrng[1] >= 0
1478 && pad->src.offrng[0] >= 0
1479 && (pad->src.offrng[1] < 0
1480 || pad->src.offrng[0] <= pad->src.offrng[1]))
1481 {
1482 /* Set RANGE to that of MAXREAD, bounded by PAD->SRC_BNDRNG if
1483 PAD is nonnull and BNDRNG is valid. */
1484 get_size_range (rvals, maxread, stmt, range, pad ? pad->src_bndrng : NULL);
1485 /* Set OVERREAD for reads starting just past the end of an object. */
1486 overread = pad->src.sizrng[1] - pad->src.offrng[0] < pad->src_bndrng[0];
1487 range[0] = wide_int_to_tree (sizetype, pad->src_bndrng[0]);
1488 slen = size_zero_node;
1489 }
1490
1491 if (overread)
1492 {
1493 const opt_code opt = OPT_Wstringop_overread;
1494 if (warning_suppressed_p (exp, opt)
1495 || (srcstr && warning_suppressed_p (srcstr, opt))
1496 || (pad && pad->src.ref
1497 && warning_suppressed_p (pad->src.ref, opt)))
1498 return false;
1499
1500 location_t loc = get_location (exp);
1501 const bool read
1502 = mode == access_read_only || mode == access_read_write;
1503 const bool maybe = pad && pad->dst.parmarray;
1504 if (warn_for_access (loc, func, exp, opt, range, slen, false, read,
1505 maybe))
1506 {
1507 suppress_warning (exp, opt);
1508 if (pad)
1509 pad->src.inform_access (access_read_only);
1510 }
1511 return false;
1512 }
1513
1514 return true;
1515 }
1516
1517 static bool
1518 check_access (gimple *stmt, tree dstwrite,
1519 tree maxread, tree srcstr, tree dstsize,
1520 access_mode mode, const access_data *pad,
1521 range_query *rvals)
1522 {
1523 return check_access<gimple *> (stmt, dstwrite, maxread, srcstr, dstsize,
1524 mode, pad, rvals);
1525 }
1526
1527 bool
1528 check_access (tree expr, tree dstwrite,
1529 tree maxread, tree srcstr, tree dstsize,
1530 access_mode mode, const access_data *pad /* = NULL */)
1531 {
1532 return check_access<tree> (expr, dstwrite, maxread, srcstr, dstsize,
1533 mode, pad, nullptr);
1534 }
1535
1536 /* Return true if STMT is a call to an allocation function. Unless
1537 ALL_ALLOC is set, consider only functions that return dynmamically
1538 allocated objects. Otherwise return true even for all forms of
1539 alloca (including VLA). */
1540
1541 static bool
1542 fndecl_alloc_p (tree fndecl, bool all_alloc)
1543 {
1544 if (!fndecl)
1545 return false;
1546
1547 /* A call to operator new isn't recognized as one to a built-in. */
1548 if (DECL_IS_OPERATOR_NEW_P (fndecl))
1549 return true;
1550
1551 if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
1552 {
1553 switch (DECL_FUNCTION_CODE (fndecl))
1554 {
1555 case BUILT_IN_ALLOCA:
1556 case BUILT_IN_ALLOCA_WITH_ALIGN:
1557 return all_alloc;
1558 case BUILT_IN_ALIGNED_ALLOC:
1559 case BUILT_IN_CALLOC:
1560 case BUILT_IN_GOMP_ALLOC:
1561 case BUILT_IN_MALLOC:
1562 case BUILT_IN_REALLOC:
1563 case BUILT_IN_STRDUP:
1564 case BUILT_IN_STRNDUP:
1565 return true;
1566 default:
1567 break;
1568 }
1569 }
1570
1571 /* A function is considered an allocation function if it's declared
1572 with attribute malloc with an argument naming its associated
1573 deallocation function. */
1574 tree attrs = DECL_ATTRIBUTES (fndecl);
1575 if (!attrs)
1576 return false;
1577
1578 for (tree allocs = attrs;
1579 (allocs = lookup_attribute ("malloc", allocs));
1580 allocs = TREE_CHAIN (allocs))
1581 {
1582 tree args = TREE_VALUE (allocs);
1583 if (!args)
1584 continue;
1585
1586 if (TREE_VALUE (args))
1587 return true;
1588 }
1589
1590 return false;
1591 }
1592
1593 /* Return true if STMT is a call to an allocation function. A wrapper
1594 around fndecl_alloc_p. */
1595
1596 static bool
1597 gimple_call_alloc_p (gimple *stmt, bool all_alloc = false)
1598 {
1599 return fndecl_alloc_p (gimple_call_fndecl (stmt), all_alloc);
1600 }
1601
1602 /* Return true if DELC doesn't refer to an operator delete that's
1603 suitable to call with a pointer returned from the operator new
1604 described by NEWC. */
1605
1606 static bool
1607 new_delete_mismatch_p (const demangle_component &newc,
1608 const demangle_component &delc)
1609 {
1610 if (newc.type != delc.type)
1611 return true;
1612
1613 switch (newc.type)
1614 {
1615 case DEMANGLE_COMPONENT_NAME:
1616 {
1617 int len = newc.u.s_name.len;
1618 const char *news = newc.u.s_name.s;
1619 const char *dels = delc.u.s_name.s;
1620 if (len != delc.u.s_name.len || memcmp (news, dels, len))
1621 return true;
1622
1623 if (news[len] == 'n')
1624 {
1625 if (news[len + 1] == 'a')
1626 return dels[len] != 'd' || dels[len + 1] != 'a';
1627 if (news[len + 1] == 'w')
1628 return dels[len] != 'd' || dels[len + 1] != 'l';
1629 }
1630 return false;
1631 }
1632
1633 case DEMANGLE_COMPONENT_OPERATOR:
1634 /* Operator mismatches are handled above. */
1635 return false;
1636
1637 case DEMANGLE_COMPONENT_EXTENDED_OPERATOR:
1638 if (newc.u.s_extended_operator.args != delc.u.s_extended_operator.args)
1639 return true;
1640 return new_delete_mismatch_p (*newc.u.s_extended_operator.name,
1641 *delc.u.s_extended_operator.name);
1642
1643 case DEMANGLE_COMPONENT_FIXED_TYPE:
1644 if (newc.u.s_fixed.accum != delc.u.s_fixed.accum
1645 || newc.u.s_fixed.sat != delc.u.s_fixed.sat)
1646 return true;
1647 return new_delete_mismatch_p (*newc.u.s_fixed.length,
1648 *delc.u.s_fixed.length);
1649
1650 case DEMANGLE_COMPONENT_CTOR:
1651 if (newc.u.s_ctor.kind != delc.u.s_ctor.kind)
1652 return true;
1653 return new_delete_mismatch_p (*newc.u.s_ctor.name,
1654 *delc.u.s_ctor.name);
1655
1656 case DEMANGLE_COMPONENT_DTOR:
1657 if (newc.u.s_dtor.kind != delc.u.s_dtor.kind)
1658 return true;
1659 return new_delete_mismatch_p (*newc.u.s_dtor.name,
1660 *delc.u.s_dtor.name);
1661
1662 case DEMANGLE_COMPONENT_BUILTIN_TYPE:
1663 {
1664 /* The demangler API provides no better way to compare built-in
1665 types except to by comparing their demangled names. */
1666 size_t nsz, dsz;
1667 demangle_component *pnc = const_cast<demangle_component *>(&newc);
1668 demangle_component *pdc = const_cast<demangle_component *>(&delc);
1669 char *nts = cplus_demangle_print (0, pnc, 16, &nsz);
1670 char *dts = cplus_demangle_print (0, pdc, 16, &dsz);
1671 if (!nts != !dts)
1672 return true;
1673 bool mismatch = strcmp (nts, dts);
1674 free (nts);
1675 free (dts);
1676 return mismatch;
1677 }
1678
1679 case DEMANGLE_COMPONENT_SUB_STD:
1680 if (newc.u.s_string.len != delc.u.s_string.len)
1681 return true;
1682 return memcmp (newc.u.s_string.string, delc.u.s_string.string,
1683 newc.u.s_string.len);
1684
1685 case DEMANGLE_COMPONENT_FUNCTION_PARAM:
1686 case DEMANGLE_COMPONENT_TEMPLATE_PARAM:
1687 return newc.u.s_number.number != delc.u.s_number.number;
1688
1689 case DEMANGLE_COMPONENT_CHARACTER:
1690 return newc.u.s_character.character != delc.u.s_character.character;
1691
1692 case DEMANGLE_COMPONENT_DEFAULT_ARG:
1693 case DEMANGLE_COMPONENT_LAMBDA:
1694 if (newc.u.s_unary_num.num != delc.u.s_unary_num.num)
1695 return true;
1696 return new_delete_mismatch_p (*newc.u.s_unary_num.sub,
1697 *delc.u.s_unary_num.sub);
1698 default:
1699 break;
1700 }
1701
1702 if (!newc.u.s_binary.left != !delc.u.s_binary.left)
1703 return true;
1704
1705 if (!newc.u.s_binary.left)
1706 return false;
1707
1708 if (new_delete_mismatch_p (*newc.u.s_binary.left, *delc.u.s_binary.left)
1709 || !newc.u.s_binary.right != !delc.u.s_binary.right)
1710 return true;
1711
1712 if (newc.u.s_binary.right)
1713 return new_delete_mismatch_p (*newc.u.s_binary.right,
1714 *delc.u.s_binary.right);
1715 return false;
1716 }
1717
1718 /* Return true if DELETE_DECL is an operator delete that's not suitable
1719 to call with a pointer returned fron NEW_DECL. */
1720
1721 static bool
1722 new_delete_mismatch_p (tree new_decl, tree delete_decl)
1723 {
1724 tree new_name = DECL_ASSEMBLER_NAME (new_decl);
1725 tree delete_name = DECL_ASSEMBLER_NAME (delete_decl);
1726
1727 /* valid_new_delete_pair_p() returns a conservative result (currently
1728 it only handles global operators). A true result is reliable but
1729 a false result doesn't necessarily mean the operators don't match
1730 unless CERTAIN is set. */
1731 bool certain;
1732 if (valid_new_delete_pair_p (new_name, delete_name, &certain))
1733 return false;
1734 /* CERTAIN is set when the negative result is certain. */
1735 if (certain)
1736 return true;
1737
1738 /* For anything not handled by valid_new_delete_pair_p() such as member
1739 operators compare the individual demangled components of the mangled
1740 name. */
1741 const char *new_str = IDENTIFIER_POINTER (new_name);
1742 const char *del_str = IDENTIFIER_POINTER (delete_name);
1743
1744 void *np = NULL, *dp = NULL;
1745 demangle_component *ndc = cplus_demangle_v3_components (new_str, 0, &np);
1746 demangle_component *ddc = cplus_demangle_v3_components (del_str, 0, &dp);
1747 bool mismatch = new_delete_mismatch_p (*ndc, *ddc);
1748 free (np);
1749 free (dp);
1750 return mismatch;
1751 }
1752
1753 /* ALLOC_DECL and DEALLOC_DECL are pair of allocation and deallocation
1754 functions. Return true if the latter is suitable to deallocate objects
1755 allocated by calls to the former. */
1756
1757 static bool
1758 matching_alloc_calls_p (tree alloc_decl, tree dealloc_decl)
1759 {
1760 /* Set to alloc_kind_t::builtin if ALLOC_DECL is associated with
1761 a built-in deallocator. */
1762 enum class alloc_kind_t { none, builtin, user }
1763 alloc_dealloc_kind = alloc_kind_t::none;
1764
1765 if (DECL_IS_OPERATOR_NEW_P (alloc_decl))
1766 {
1767 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl))
1768 /* Return true iff both functions are of the same array or
1769 singleton form and false otherwise. */
1770 return !new_delete_mismatch_p (alloc_decl, dealloc_decl);
1771
1772 /* Return false for deallocation functions that are known not
1773 to match. */
1774 if (fndecl_built_in_p (dealloc_decl, BUILT_IN_FREE)
1775 || fndecl_built_in_p (dealloc_decl, BUILT_IN_REALLOC))
1776 return false;
1777 /* Otherwise proceed below to check the deallocation function's
1778 "*dealloc" attributes to look for one that mentions this operator
1779 new. */
1780 }
1781 else if (fndecl_built_in_p (alloc_decl, BUILT_IN_NORMAL))
1782 {
1783 switch (DECL_FUNCTION_CODE (alloc_decl))
1784 {
1785 case BUILT_IN_ALLOCA:
1786 case BUILT_IN_ALLOCA_WITH_ALIGN:
1787 return false;
1788
1789 case BUILT_IN_ALIGNED_ALLOC:
1790 case BUILT_IN_CALLOC:
1791 case BUILT_IN_GOMP_ALLOC:
1792 case BUILT_IN_MALLOC:
1793 case BUILT_IN_REALLOC:
1794 case BUILT_IN_STRDUP:
1795 case BUILT_IN_STRNDUP:
1796 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl))
1797 return false;
1798
1799 if (fndecl_built_in_p (dealloc_decl, BUILT_IN_FREE)
1800 || fndecl_built_in_p (dealloc_decl, BUILT_IN_REALLOC))
1801 return true;
1802
1803 alloc_dealloc_kind = alloc_kind_t::builtin;
1804 break;
1805
1806 default:
1807 break;
1808 }
1809 }
1810
1811 /* Set if DEALLOC_DECL both allocates and deallocates. */
1812 alloc_kind_t realloc_kind = alloc_kind_t::none;
1813
1814 if (fndecl_built_in_p (dealloc_decl, BUILT_IN_NORMAL))
1815 {
1816 built_in_function dealloc_code = DECL_FUNCTION_CODE (dealloc_decl);
1817 if (dealloc_code == BUILT_IN_REALLOC)
1818 realloc_kind = alloc_kind_t::builtin;
1819
1820 for (tree amats = DECL_ATTRIBUTES (alloc_decl);
1821 (amats = lookup_attribute ("malloc", amats));
1822 amats = TREE_CHAIN (amats))
1823 {
1824 tree args = TREE_VALUE (amats);
1825 if (!args)
1826 continue;
1827
1828 tree fndecl = TREE_VALUE (args);
1829 if (!fndecl || !DECL_P (fndecl))
1830 continue;
1831
1832 if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL)
1833 && dealloc_code == DECL_FUNCTION_CODE (fndecl))
1834 return true;
1835 }
1836 }
1837
1838 const bool alloc_builtin = fndecl_built_in_p (alloc_decl, BUILT_IN_NORMAL);
1839 alloc_kind_t realloc_dealloc_kind = alloc_kind_t::none;
1840
1841 /* If DEALLOC_DECL has an internal "*dealloc" attribute scan the list
1842 of its associated allocation functions for ALLOC_DECL.
1843 If the corresponding ALLOC_DECL is found they're a matching pair,
1844 otherwise they're not.
1845 With DDATS set to the Deallocator's *Dealloc ATtributes... */
1846 for (tree ddats = DECL_ATTRIBUTES (dealloc_decl);
1847 (ddats = lookup_attribute ("*dealloc", ddats));
1848 ddats = TREE_CHAIN (ddats))
1849 {
1850 tree args = TREE_VALUE (ddats);
1851 if (!args)
1852 continue;
1853
1854 tree alloc = TREE_VALUE (args);
1855 if (!alloc)
1856 continue;
1857
1858 if (alloc == DECL_NAME (dealloc_decl))
1859 realloc_kind = alloc_kind_t::user;
1860
1861 if (DECL_P (alloc))
1862 {
1863 gcc_checking_assert (fndecl_built_in_p (alloc, BUILT_IN_NORMAL));
1864
1865 switch (DECL_FUNCTION_CODE (alloc))
1866 {
1867 case BUILT_IN_ALIGNED_ALLOC:
1868 case BUILT_IN_CALLOC:
1869 case BUILT_IN_GOMP_ALLOC:
1870 case BUILT_IN_MALLOC:
1871 case BUILT_IN_REALLOC:
1872 case BUILT_IN_STRDUP:
1873 case BUILT_IN_STRNDUP:
1874 realloc_dealloc_kind = alloc_kind_t::builtin;
1875 break;
1876 default:
1877 break;
1878 }
1879
1880 if (!alloc_builtin)
1881 continue;
1882
1883 if (DECL_FUNCTION_CODE (alloc) != DECL_FUNCTION_CODE (alloc_decl))
1884 continue;
1885
1886 return true;
1887 }
1888
1889 if (alloc == DECL_NAME (alloc_decl))
1890 return true;
1891 }
1892
1893 if (realloc_kind == alloc_kind_t::none)
1894 return false;
1895
1896 hash_set<tree> common_deallocs;
1897 /* Special handling for deallocators. Iterate over both the allocator's
1898 and the reallocator's associated deallocator functions looking for
1899 the first one in common. If one is found, the de/reallocator is
1900 a match for the allocator even though the latter isn't directly
1901 associated with the former. This simplifies declarations in system
1902 headers.
1903 With AMATS set to the Allocator's Malloc ATtributes,
1904 and RMATS set to Reallocator's Malloc ATtributes... */
1905 for (tree amats = DECL_ATTRIBUTES (alloc_decl),
1906 rmats = DECL_ATTRIBUTES (dealloc_decl);
1907 (amats = lookup_attribute ("malloc", amats))
1908 || (rmats = lookup_attribute ("malloc", rmats));
1909 amats = amats ? TREE_CHAIN (amats) : NULL_TREE,
1910 rmats = rmats ? TREE_CHAIN (rmats) : NULL_TREE)
1911 {
1912 if (tree args = amats ? TREE_VALUE (amats) : NULL_TREE)
1913 if (tree adealloc = TREE_VALUE (args))
1914 {
1915 if (DECL_P (adealloc)
1916 && fndecl_built_in_p (adealloc, BUILT_IN_NORMAL))
1917 {
1918 built_in_function fncode = DECL_FUNCTION_CODE (adealloc);
1919 if (fncode == BUILT_IN_FREE || fncode == BUILT_IN_REALLOC)
1920 {
1921 if (realloc_kind == alloc_kind_t::builtin)
1922 return true;
1923 alloc_dealloc_kind = alloc_kind_t::builtin;
1924 }
1925 continue;
1926 }
1927
1928 common_deallocs.add (adealloc);
1929 }
1930
1931 if (tree args = rmats ? TREE_VALUE (rmats) : NULL_TREE)
1932 if (tree ddealloc = TREE_VALUE (args))
1933 {
1934 if (DECL_P (ddealloc)
1935 && fndecl_built_in_p (ddealloc, BUILT_IN_NORMAL))
1936 {
1937 built_in_function fncode = DECL_FUNCTION_CODE (ddealloc);
1938 if (fncode == BUILT_IN_FREE || fncode == BUILT_IN_REALLOC)
1939 {
1940 if (alloc_dealloc_kind == alloc_kind_t::builtin)
1941 return true;
1942 realloc_dealloc_kind = alloc_kind_t::builtin;
1943 }
1944 continue;
1945 }
1946
1947 if (common_deallocs.add (ddealloc))
1948 return true;
1949 }
1950 }
1951
1952 /* Succeed only if ALLOC_DECL and the reallocator DEALLOC_DECL share
1953 a built-in deallocator. */
1954 return (alloc_dealloc_kind == alloc_kind_t::builtin
1955 && realloc_dealloc_kind == alloc_kind_t::builtin);
1956 }
1957
1958 /* Return true if DEALLOC_DECL is a function suitable to deallocate
1959 objectes allocated by the ALLOC call. */
1960
1961 static bool
1962 matching_alloc_calls_p (gimple *alloc, tree dealloc_decl)
1963 {
1964 tree alloc_decl = gimple_call_fndecl (alloc);
1965 if (!alloc_decl)
1966 return true;
1967
1968 return matching_alloc_calls_p (alloc_decl, dealloc_decl);
1969 }
1970
1971 /* Diagnose a call EXP to deallocate a pointer referenced by AREF if it
1972 includes a nonzero offset. Such a pointer cannot refer to the beginning
1973 of an allocated object. A negative offset may refer to it only if
1974 the target pointer is unknown. */
1975
1976 static bool
1977 warn_dealloc_offset (location_t loc, gimple *call, const access_ref &aref)
1978 {
1979 if (aref.deref || aref.offrng[0] <= 0 || aref.offrng[1] <= 0)
1980 return false;
1981
1982 tree dealloc_decl = gimple_call_fndecl (call);
1983 if (!dealloc_decl)
1984 return false;
1985
1986 if (DECL_IS_OPERATOR_DELETE_P (dealloc_decl)
1987 && !DECL_IS_REPLACEABLE_OPERATOR (dealloc_decl))
1988 {
1989 /* A call to a user-defined operator delete with a pointer plus offset
1990 may be valid if it's returned from an unknown function (i.e., one
1991 that's not operator new). */
1992 if (TREE_CODE (aref.ref) == SSA_NAME)
1993 {
1994 gimple *def_stmt = SSA_NAME_DEF_STMT (aref.ref);
1995 if (is_gimple_call (def_stmt))
1996 {
1997 tree alloc_decl = gimple_call_fndecl (def_stmt);
1998 if (!alloc_decl || !DECL_IS_OPERATOR_NEW_P (alloc_decl))
1999 return false;
2000 }
2001 }
2002 }
2003
2004 char offstr[80];
2005 offstr[0] = '\0';
2006 if (wi::fits_shwi_p (aref.offrng[0]))
2007 {
2008 if (aref.offrng[0] == aref.offrng[1]
2009 || !wi::fits_shwi_p (aref.offrng[1]))
2010 sprintf (offstr, " %lli",
2011 (long long)aref.offrng[0].to_shwi ());
2012 else
2013 sprintf (offstr, " [%lli, %lli]",
2014 (long long)aref.offrng[0].to_shwi (),
2015 (long long)aref.offrng[1].to_shwi ());
2016 }
2017
2018 if (!warning_at (loc, OPT_Wfree_nonheap_object,
2019 "%qD called on pointer %qE with nonzero offset%s",
2020 dealloc_decl, aref.ref, offstr))
2021 return false;
2022
2023 if (DECL_P (aref.ref))
2024 inform (get_location (aref.ref), "declared here");
2025 else if (TREE_CODE (aref.ref) == SSA_NAME)
2026 {
2027 gimple *def_stmt = SSA_NAME_DEF_STMT (aref.ref);
2028 if (is_gimple_call (def_stmt))
2029 {
2030 location_t def_loc = get_location (def_stmt);
2031 tree alloc_decl = gimple_call_fndecl (def_stmt);
2032 if (alloc_decl)
2033 inform (def_loc,
2034 "returned from %qD", alloc_decl);
2035 else if (tree alloc_fntype = gimple_call_fntype (def_stmt))
2036 inform (def_loc,
2037 "returned from %qT", alloc_fntype);
2038 else
2039 inform (def_loc, "obtained here");
2040 }
2041 }
2042
2043 return true;
2044 }
2045
2046 namespace {
2047
2048 const pass_data pass_data_waccess = {
2049 GIMPLE_PASS,
2050 "waccess",
2051 OPTGROUP_NONE,
2052 TV_NONE,
2053 PROP_cfg, /* properties_required */
2054 0, /* properties_provided */
2055 0, /* properties_destroyed */
2056 0, /* properties_start */
2057 0, /* properties_finish */
2058 };
2059
2060 /* Pass to detect invalid accesses. */
2061 class pass_waccess : public gimple_opt_pass
2062 {
2063 public:
2064 pass_waccess (gcc::context *);
2065
2066 ~pass_waccess ();
2067
2068 opt_pass *clone () { return new pass_waccess (m_ctxt); }
2069
2070 virtual bool gate (function *);
2071 virtual unsigned int execute (function *);
2072
2073 private:
2074 /* Not copyable or assignable. */
2075 pass_waccess (pass_waccess &) = delete;
2076 void operator= (pass_waccess &) = delete;
2077
2078 /* Check a call to an atomic built-in function. */
2079 bool check_atomic_builtin (gcall *);
2080
2081 /* Check a call to a built-in function. */
2082 bool check_builtin (gcall *);
2083
2084 /* Check a call to an ordinary function. */
2085 bool check_call (gcall *);
2086
2087 /* Check statements in a basic block. */
2088 void check (basic_block);
2089
2090 /* Check a call to a function. */
2091 void check (gcall *);
2092
2093 /* Check a call to the named built-in function. */
2094 void check_alloca (gcall *);
2095 void check_alloc_size_call (gcall *);
2096 void check_strcat (gcall *);
2097 void check_strncat (gcall *);
2098 void check_stxcpy (gcall *);
2099 void check_stxncpy (gcall *);
2100 void check_strncmp (gcall *);
2101 void check_memop_access (gimple *, tree, tree, tree);
2102 void check_read_access (gimple *, tree, tree = NULL_TREE, int = 1);
2103
2104 void maybe_check_dealloc_call (gcall *);
2105 void maybe_check_access_sizes (rdwr_map *, tree, tree, gimple *);
2106
2107 /* A pointer_query object and its cache to store information about
2108 pointers and their targets in. */
2109 pointer_query m_ptr_qry;
2110 pointer_query::cache_type m_var_cache;
2111 };
2112
2113 /* Construct the pass. */
2114
2115 pass_waccess::pass_waccess (gcc::context *ctxt)
2116 : gimple_opt_pass (pass_data_waccess, ctxt),
2117 m_ptr_qry (NULL, &m_var_cache),
2118 m_var_cache ()
2119 {
2120 }
2121
2122 /* Release pointer_query cache. */
2123
2124 pass_waccess::~pass_waccess ()
2125 {
2126 m_ptr_qry.flush_cache ();
2127 }
2128
2129 /* Return true when any checks performed by the pass are enabled. */
2130
2131 bool
2132 pass_waccess::gate (function *)
2133 {
2134 return (warn_free_nonheap_object
2135 || warn_mismatched_alloc
2136 || warn_mismatched_new_delete);
2137 }
2138
2139 /* Initialize ALLOC_OBJECT_SIZE_LIMIT based on the -Walloc-size-larger-than=
2140 setting if the option is specified, or to the maximum object size if it
2141 is not. Return the initialized value. */
2142
2143 static tree
2144 alloc_max_size (void)
2145 {
2146 HOST_WIDE_INT limit = warn_alloc_size_limit;
2147 if (limit == HOST_WIDE_INT_MAX)
2148 limit = tree_to_shwi (TYPE_MAX_VALUE (ptrdiff_type_node));
2149
2150 return build_int_cst (size_type_node, limit);
2151 }
2152
2153 /* Diagnose a call EXP to function FN decorated with attribute alloc_size
2154 whose argument numbers given by IDX with values given by ARGS exceed
2155 the maximum object size or cause an unsigned oveflow (wrapping) when
2156 multiplied. FN is null when EXP is a call via a function pointer.
2157 When ARGS[0] is null the function does nothing. ARGS[1] may be null
2158 for functions like malloc, and non-null for those like calloc that
2159 are decorated with a two-argument attribute alloc_size. */
2160
2161 void
2162 maybe_warn_alloc_args_overflow (gimple *stmt, const tree args[2],
2163 const int idx[2])
2164 {
2165 /* The range each of the (up to) two arguments is known to be in. */
2166 tree argrange[2][2] = { { NULL_TREE, NULL_TREE }, { NULL_TREE, NULL_TREE } };
2167
2168 /* Maximum object size set by -Walloc-size-larger-than= or SIZE_MAX / 2. */
2169 tree maxobjsize = alloc_max_size ();
2170
2171 location_t loc = get_location (stmt);
2172
2173 tree fn = gimple_call_fndecl (stmt);
2174 tree fntype = fn ? TREE_TYPE (fn) : gimple_call_fntype (stmt);
2175 bool warned = false;
2176
2177 /* Validate each argument individually. */
2178 for (unsigned i = 0; i != 2 && args[i]; ++i)
2179 {
2180 if (TREE_CODE (args[i]) == INTEGER_CST)
2181 {
2182 argrange[i][0] = args[i];
2183 argrange[i][1] = args[i];
2184
2185 if (tree_int_cst_lt (args[i], integer_zero_node))
2186 {
2187 warned = warning_at (loc, OPT_Walloc_size_larger_than_,
2188 "argument %i value %qE is negative",
2189 idx[i] + 1, args[i]);
2190 }
2191 else if (integer_zerop (args[i]))
2192 {
2193 /* Avoid issuing -Walloc-zero for allocation functions other
2194 than __builtin_alloca that are declared with attribute
2195 returns_nonnull because there's no portability risk. This
2196 avoids warning for such calls to libiberty's xmalloc and
2197 friends.
2198 Also avoid issuing the warning for calls to function named
2199 "alloca". */
2200 if (fn && fndecl_built_in_p (fn, BUILT_IN_ALLOCA)
2201 ? IDENTIFIER_LENGTH (DECL_NAME (fn)) != 6
2202 : !lookup_attribute ("returns_nonnull",
2203 TYPE_ATTRIBUTES (fntype)))
2204 warned = warning_at (loc, OPT_Walloc_zero,
2205 "argument %i value is zero",
2206 idx[i] + 1);
2207 }
2208 else if (tree_int_cst_lt (maxobjsize, args[i]))
2209 {
2210 /* G++ emits calls to ::operator new[](SIZE_MAX) in C++98
2211 mode and with -fno-exceptions as a way to indicate array
2212 size overflow. There's no good way to detect C++98 here
2213 so avoid diagnosing these calls for all C++ modes. */
2214 if (i == 0
2215 && fn
2216 && !args[1]
2217 && lang_GNU_CXX ()
2218 && DECL_IS_OPERATOR_NEW_P (fn)
2219 && integer_all_onesp (args[i]))
2220 continue;
2221
2222 warned = warning_at (loc, OPT_Walloc_size_larger_than_,
2223 "argument %i value %qE exceeds "
2224 "maximum object size %E",
2225 idx[i] + 1, args[i], maxobjsize);
2226 }
2227 }
2228 else if (TREE_CODE (args[i]) == SSA_NAME
2229 && get_size_range (args[i], argrange[i]))
2230 {
2231 /* Verify that the argument's range is not negative (including
2232 upper bound of zero). */
2233 if (tree_int_cst_lt (argrange[i][0], integer_zero_node)
2234 && tree_int_cst_le (argrange[i][1], integer_zero_node))
2235 {
2236 warned = warning_at (loc, OPT_Walloc_size_larger_than_,
2237 "argument %i range [%E, %E] is negative",
2238 idx[i] + 1,
2239 argrange[i][0], argrange[i][1]);
2240 }
2241 else if (tree_int_cst_lt (maxobjsize, argrange[i][0]))
2242 {
2243 warned = warning_at (loc, OPT_Walloc_size_larger_than_,
2244 "argument %i range [%E, %E] exceeds "
2245 "maximum object size %E",
2246 idx[i] + 1,
2247 argrange[i][0], argrange[i][1],
2248 maxobjsize);
2249 }
2250 }
2251 }
2252
2253 if (!argrange[0][0])
2254 return;
2255
2256 /* For a two-argument alloc_size, validate the product of the two
2257 arguments if both of their values or ranges are known. */
2258 if (!warned && tree_fits_uhwi_p (argrange[0][0])
2259 && argrange[1][0] && tree_fits_uhwi_p (argrange[1][0])
2260 && !integer_onep (argrange[0][0])
2261 && !integer_onep (argrange[1][0]))
2262 {
2263 /* Check for overflow in the product of a function decorated with
2264 attribute alloc_size (X, Y). */
2265 unsigned szprec = TYPE_PRECISION (size_type_node);
2266 wide_int x = wi::to_wide (argrange[0][0], szprec);
2267 wide_int y = wi::to_wide (argrange[1][0], szprec);
2268
2269 wi::overflow_type vflow;
2270 wide_int prod = wi::umul (x, y, &vflow);
2271
2272 if (vflow)
2273 warned = warning_at (loc, OPT_Walloc_size_larger_than_,
2274 "product %<%E * %E%> of arguments %i and %i "
2275 "exceeds %<SIZE_MAX%>",
2276 argrange[0][0], argrange[1][0],
2277 idx[0] + 1, idx[1] + 1);
2278 else if (wi::ltu_p (wi::to_wide (maxobjsize, szprec), prod))
2279 warned = warning_at (loc, OPT_Walloc_size_larger_than_,
2280 "product %<%E * %E%> of arguments %i and %i "
2281 "exceeds maximum object size %E",
2282 argrange[0][0], argrange[1][0],
2283 idx[0] + 1, idx[1] + 1,
2284 maxobjsize);
2285
2286 if (warned)
2287 {
2288 /* Print the full range of each of the two arguments to make
2289 it clear when it is, in fact, in a range and not constant. */
2290 if (argrange[0][0] != argrange [0][1])
2291 inform (loc, "argument %i in the range [%E, %E]",
2292 idx[0] + 1, argrange[0][0], argrange[0][1]);
2293 if (argrange[1][0] != argrange [1][1])
2294 inform (loc, "argument %i in the range [%E, %E]",
2295 idx[1] + 1, argrange[1][0], argrange[1][1]);
2296 }
2297 }
2298
2299 if (warned && fn)
2300 {
2301 location_t fnloc = DECL_SOURCE_LOCATION (fn);
2302
2303 if (DECL_IS_UNDECLARED_BUILTIN (fn))
2304 inform (loc,
2305 "in a call to built-in allocation function %qD", fn);
2306 else
2307 inform (fnloc,
2308 "in a call to allocation function %qD declared here", fn);
2309 }
2310 }
2311
2312 /* Check a call to an alloca function for an excessive size. */
2313
2314 void
2315 pass_waccess::check_alloca (gcall *stmt)
2316 {
2317 if ((warn_vla_limit >= HOST_WIDE_INT_MAX
2318 && warn_alloc_size_limit < warn_vla_limit)
2319 || (warn_alloca_limit >= HOST_WIDE_INT_MAX
2320 && warn_alloc_size_limit < warn_alloca_limit))
2321 {
2322 /* -Walloca-larger-than and -Wvla-larger-than settings of less
2323 than HWI_MAX override the more general -Walloc-size-larger-than
2324 so unless either of the former options is smaller than the last
2325 one (wchich would imply that the call was already checked), check
2326 the alloca arguments for overflow. */
2327 const tree alloc_args[] = { call_arg (stmt, 0), NULL_TREE };
2328 const int idx[] = { 0, -1 };
2329 maybe_warn_alloc_args_overflow (stmt, alloc_args, idx);
2330 }
2331 }
2332
2333 /* Check a call to an allocation function for an excessive size. */
2334
2335 void
2336 pass_waccess::check_alloc_size_call (gcall *stmt)
2337 {
2338 tree fndecl = gimple_call_fndecl (stmt);
2339 if (fndecl && gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
2340 {
2341 /* Alloca is handled separately. */
2342 switch (DECL_FUNCTION_CODE (fndecl))
2343 {
2344 case BUILT_IN_ALLOCA:
2345 case BUILT_IN_ALLOCA_WITH_ALIGN:
2346 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
2347 return;
2348 default:
2349 break;
2350 }
2351 }
2352
2353 tree fntype = gimple_call_fntype (stmt);
2354 tree fntypeattrs = TYPE_ATTRIBUTES (fntype);
2355
2356 tree alloc_size = lookup_attribute ("alloc_size", fntypeattrs);
2357 if (!alloc_size)
2358 return;
2359
2360 /* Extract attribute alloc_size from the type of the called expression
2361 (which could be a function or a function pointer) and if set, store
2362 the indices of the corresponding arguments in ALLOC_IDX, and then
2363 the actual argument(s) at those indices in ALLOC_ARGS. */
2364 int idx[2] = { -1, -1 };
2365 tree alloc_args[] = { NULL_TREE, NULL_TREE };
2366 unsigned nargs = gimple_call_num_args (stmt);
2367
2368 tree args = TREE_VALUE (alloc_size);
2369 idx[0] = TREE_INT_CST_LOW (TREE_VALUE (args)) - 1;
2370 /* Avoid invalid calls to functions without a prototype. */
2371 if ((unsigned) idx[0] >= nargs)
2372 return;
2373 alloc_args[0] = call_arg (stmt, idx[0]);
2374 if (TREE_CHAIN (args))
2375 {
2376 idx[1] = TREE_INT_CST_LOW (TREE_VALUE (TREE_CHAIN (args))) - 1;
2377 if ((unsigned) idx[1] >= nargs)
2378 return;
2379 alloc_args[1] = call_arg (stmt, idx[1]);
2380 }
2381
2382 maybe_warn_alloc_args_overflow (stmt, alloc_args, idx);
2383 }
2384
2385 /* Check a call STMT to strcat() for overflow and warn if it does. */
2386
2387 void
2388 pass_waccess::check_strcat (gcall *stmt)
2389 {
2390 if (!warn_stringop_overflow && !warn_stringop_overread)
2391 return;
2392
2393 tree dest = call_arg (stmt, 0);
2394 tree src = call_arg (stmt, 1);
2395
2396 /* There is no way here to determine the length of the string in
2397 the destination to which the SRC string is being appended so
2398 just diagnose cases when the souce string is longer than
2399 the destination object. */
2400 access_data data (m_ptr_qry.rvals, stmt, access_read_write, NULL_TREE,
2401 true, NULL_TREE, true);
2402 const int ost = warn_stringop_overflow ? warn_stringop_overflow - 1 : 1;
2403 compute_objsize (src, stmt, ost, &data.src, &m_ptr_qry);
2404 tree destsize = compute_objsize (dest, stmt, ost, &data.dst, &m_ptr_qry);
2405
2406 check_access (stmt, /*dstwrite=*/NULL_TREE, /*maxread=*/NULL_TREE,
2407 src, destsize, data.mode, &data, m_ptr_qry.rvals);
2408 }
2409
2410 /* Check a call STMT to strcat() for overflow and warn if it does. */
2411
2412 void
2413 pass_waccess::check_strncat (gcall *stmt)
2414 {
2415 if (!warn_stringop_overflow && !warn_stringop_overread)
2416 return;
2417
2418 tree dest = call_arg (stmt, 0);
2419 tree src = call_arg (stmt, 1);
2420 /* The upper bound on the number of bytes to write. */
2421 tree maxread = call_arg (stmt, 2);
2422
2423 /* Detect unterminated source (only). */
2424 if (!check_nul_terminated_array (stmt, src, maxread))
2425 return;
2426
2427 /* The length of the source sequence. */
2428 tree slen = c_strlen (src, 1);
2429
2430 /* Try to determine the range of lengths that the source expression
2431 refers to. Since the lengths are only used for warning and not
2432 for code generation disable strict mode below. */
2433 tree maxlen = slen;
2434 if (!maxlen)
2435 {
2436 c_strlen_data lendata = { };
2437 get_range_strlen (src, &lendata, /* eltsize = */ 1);
2438 maxlen = lendata.maxbound;
2439 }
2440
2441 access_data data (m_ptr_qry.rvals, stmt, access_read_write);
2442 /* Try to verify that the destination is big enough for the shortest
2443 string. First try to determine the size of the destination object
2444 into which the source is being copied. */
2445 const int ost = warn_stringop_overflow - 1;
2446 tree destsize = compute_objsize (dest, stmt, ost, &data.dst, &m_ptr_qry);
2447
2448 /* Add one for the terminating nul. */
2449 tree srclen = (maxlen
2450 ? fold_build2 (PLUS_EXPR, size_type_node, maxlen,
2451 size_one_node)
2452 : NULL_TREE);
2453
2454 /* The strncat function copies at most MAXREAD bytes and always appends
2455 the terminating nul so the specified upper bound should never be equal
2456 to (or greater than) the size of the destination. */
2457 if (tree_fits_uhwi_p (maxread) && tree_fits_uhwi_p (destsize)
2458 && tree_int_cst_equal (destsize, maxread))
2459 {
2460 location_t loc = get_location (stmt);
2461 warning_at (loc, OPT_Wstringop_overflow_,
2462 "%qD specified bound %E equals destination size",
2463 get_callee_fndecl (stmt), maxread);
2464
2465 return;
2466 }
2467
2468 if (!srclen
2469 || (maxread && tree_fits_uhwi_p (maxread)
2470 && tree_fits_uhwi_p (srclen)
2471 && tree_int_cst_lt (maxread, srclen)))
2472 srclen = maxread;
2473
2474 check_access (stmt, /*dstwrite=*/NULL_TREE, maxread, srclen,
2475 destsize, data.mode, &data, m_ptr_qry.rvals);
2476 }
2477
2478 /* Check a call STMT to stpcpy() or strcpy() for overflow and warn
2479 if it does. */
2480
2481 void
2482 pass_waccess::check_stxcpy (gcall *stmt)
2483 {
2484 tree dst = call_arg (stmt, 0);
2485 tree src = call_arg (stmt, 1);
2486
2487 tree size;
2488 bool exact;
2489 if (tree nonstr = unterminated_array (src, &size, &exact))
2490 {
2491 /* NONSTR refers to the non-nul terminated constant array. */
2492 warn_string_no_nul (get_location (stmt), stmt, NULL, src, nonstr,
2493 size, exact);
2494 return;
2495 }
2496
2497 if (warn_stringop_overflow)
2498 {
2499 access_data data (m_ptr_qry.rvals, stmt, access_read_write, NULL_TREE,
2500 true, NULL_TREE, true);
2501 const int ost = warn_stringop_overflow ? warn_stringop_overflow - 1 : 1;
2502 compute_objsize (src, stmt, ost, &data.src, &m_ptr_qry);
2503 tree dstsize = compute_objsize (dst, stmt, ost, &data.dst, &m_ptr_qry);
2504 check_access (stmt, /*dstwrite=*/ NULL_TREE,
2505 /*maxread=*/ NULL_TREE, /*srcstr=*/ src,
2506 dstsize, data.mode, &data, m_ptr_qry.rvals);
2507 }
2508
2509 /* Check to see if the argument was declared attribute nonstring
2510 and if so, issue a warning since at this point it's not known
2511 to be nul-terminated. */
2512 tree fndecl = get_callee_fndecl (stmt);
2513 maybe_warn_nonstring_arg (fndecl, stmt);
2514 }
2515
2516 /* Check a call STMT to stpncpy() or strncpy() for overflow and warn
2517 if it does. */
2518
2519 void
2520 pass_waccess::check_stxncpy (gcall *stmt)
2521 {
2522 if (!warn_stringop_overflow)
2523 return;
2524
2525 tree dst = call_arg (stmt, 0);
2526 tree src = call_arg (stmt, 1);
2527 /* The number of bytes to write (not the maximum). */
2528 tree len = call_arg (stmt, 2);
2529
2530 access_data data (m_ptr_qry.rvals, stmt, access_read_write, len, true, len,
2531 true);
2532 const int ost = warn_stringop_overflow ? warn_stringop_overflow - 1 : 1;
2533 compute_objsize (src, stmt, ost, &data.src, &m_ptr_qry);
2534 tree dstsize = compute_objsize (dst, stmt, ost, &data.dst, &m_ptr_qry);
2535
2536 check_access (stmt, /*dstwrite=*/len, /*maxread=*/len, src, dstsize,
2537 data.mode, &data, m_ptr_qry.rvals);
2538 }
2539
2540 /* Check a call STMT to stpncpy() or strncpy() for overflow and warn
2541 if it does. */
2542
2543 void
2544 pass_waccess::check_strncmp (gcall *stmt)
2545 {
2546 if (!warn_stringop_overread)
2547 return;
2548
2549 tree arg1 = call_arg (stmt, 0);
2550 tree arg2 = call_arg (stmt, 1);
2551 tree bound = call_arg (stmt, 2);
2552
2553 /* First check each argument separately, considering the bound. */
2554 if (!check_nul_terminated_array (stmt, arg1, bound)
2555 || !check_nul_terminated_array (stmt, arg2, bound))
2556 return;
2557
2558 /* A strncmp read from each argument is constrained not just by
2559 the bound but also by the length of the shorter string. Specifying
2560 a bound that's larger than the size of either array makes no sense
2561 and is likely a bug. When the length of neither of the two strings
2562 is known but the sizes of both of the arrays they are stored in is,
2563 issue a warning if the bound is larger than than the size of
2564 the larger of the two arrays. */
2565
2566 c_strlen_data lendata1{ }, lendata2{ };
2567 tree len1 = c_strlen (arg1, 1, &lendata1);
2568 tree len2 = c_strlen (arg2, 1, &lendata2);
2569
2570 if (len1 && TREE_CODE (len1) != INTEGER_CST)
2571 len1 = NULL_TREE;
2572 if (len2 && TREE_CODE (len2) != INTEGER_CST)
2573 len2 = NULL_TREE;
2574
2575 if (len1 && len2)
2576 /* If the length of both arguments was computed they must both be
2577 nul-terminated and no further checking is necessary regardless
2578 of the bound. */
2579 return;
2580
2581 /* Check to see if the argument was declared with attribute nonstring
2582 and if so, issue a warning since at this point it's not known to be
2583 nul-terminated. */
2584 if (maybe_warn_nonstring_arg (get_callee_fndecl (stmt), stmt))
2585 return;
2586
2587 access_data adata1 (m_ptr_qry.rvals, stmt, access_read_only, NULL_TREE, false,
2588 bound, true);
2589 access_data adata2 (m_ptr_qry.rvals, stmt, access_read_only, NULL_TREE, false,
2590 bound, true);
2591
2592 /* Determine the range of the bound first and bail if it fails; it's
2593 cheaper than computing the size of the objects. */
2594 tree bndrng[2] = { NULL_TREE, NULL_TREE };
2595 get_size_range (m_ptr_qry.rvals, bound, stmt, bndrng, adata1.src_bndrng);
2596 if (!bndrng[0] || integer_zerop (bndrng[0]))
2597 return;
2598
2599 if (len1 && tree_int_cst_lt (len1, bndrng[0]))
2600 bndrng[0] = len1;
2601 if (len2 && tree_int_cst_lt (len2, bndrng[0]))
2602 bndrng[0] = len2;
2603
2604 /* compute_objsize almost never fails (and ultimately should never
2605 fail). Don't bother to handle the rare case when it does. */
2606 if (!compute_objsize (arg1, stmt, 1, &adata1.src, &m_ptr_qry)
2607 || !compute_objsize (arg2, stmt, 1, &adata2.src, &m_ptr_qry))
2608 return;
2609
2610 /* Compute the size of the remaining space in each array after
2611 subtracting any offset into it. */
2612 offset_int rem1 = adata1.src.size_remaining ();
2613 offset_int rem2 = adata2.src.size_remaining ();
2614
2615 /* Cap REM1 and REM2 at the other if the other's argument is known
2616 to be an unterminated array, either because there's no space
2617 left in it after adding its offset or because it's constant and
2618 has no nul. */
2619 if (rem1 == 0 || (rem1 < rem2 && lendata1.decl))
2620 rem2 = rem1;
2621 else if (rem2 == 0 || (rem2 < rem1 && lendata2.decl))
2622 rem1 = rem2;
2623
2624 /* Point PAD at the array to reference in the note if a warning
2625 is issued. */
2626 access_data *pad = len1 ? &adata2 : &adata1;
2627 offset_int maxrem = wi::max (rem1, rem2, UNSIGNED);
2628 if (lendata1.decl || lendata2.decl
2629 || maxrem < wi::to_offset (bndrng[0]))
2630 {
2631 /* Warn when either argument isn't nul-terminated or the maximum
2632 remaining space in the two arrays is less than the bound. */
2633 tree func = get_callee_fndecl (stmt);
2634 location_t loc = gimple_location (stmt);
2635 maybe_warn_for_bound (OPT_Wstringop_overread, loc, stmt, func,
2636 bndrng, wide_int_to_tree (sizetype, maxrem),
2637 pad);
2638 }
2639 }
2640
2641 /* Determine and check the sizes of the source and the destination
2642 of calls to __builtin_{bzero,memcpy,mempcpy,memset} calls. STMT is
2643 the call statement, DEST is the destination argument, SRC is the source
2644 argument or null, and SIZE is the number of bytes being accessed. Use
2645 Object Size type-0 regardless of the OPT_Wstringop_overflow_ setting.
2646 Return true on success (no overflow or invalid sizes), false otherwise. */
2647
2648 void
2649 pass_waccess::check_memop_access (gimple *stmt, tree dest, tree src, tree size)
2650 {
2651 /* For functions like memset and memcpy that operate on raw memory
2652 try to determine the size of the largest source and destination
2653 object using type-0 Object Size regardless of the object size
2654 type specified by the option. */
2655 access_data data (m_ptr_qry.rvals, stmt, access_read_write);
2656 tree srcsize
2657 = src ? compute_objsize (src, stmt, 0, &data.src, &m_ptr_qry) : NULL_TREE;
2658 tree dstsize = compute_objsize (dest, stmt, 0, &data.dst, &m_ptr_qry);
2659
2660 check_access (stmt, size, /*maxread=*/NULL_TREE, srcsize, dstsize,
2661 data.mode, &data, m_ptr_qry.rvals);
2662 }
2663
2664 /* A convenience wrapper for check_access to check access by a read-only
2665 function like puts or strcmp. */
2666
2667 void
2668 pass_waccess::check_read_access (gimple *stmt, tree src,
2669 tree bound /* = NULL_TREE */,
2670 int ost /* = 1 */)
2671 {
2672 if (!warn_stringop_overread)
2673 return;
2674
2675 if (bound && !useless_type_conversion_p (size_type_node, TREE_TYPE (bound)))
2676 bound = fold_convert (size_type_node, bound);
2677
2678 tree fndecl = get_callee_fndecl (stmt);
2679 maybe_warn_nonstring_arg (fndecl, stmt);
2680
2681 access_data data (m_ptr_qry.rvals, stmt, access_read_only, NULL_TREE,
2682 false, bound, true);
2683 compute_objsize (src, stmt, ost, &data.src, &m_ptr_qry);
2684 check_access (stmt, /*dstwrite=*/ NULL_TREE, /*maxread=*/ bound,
2685 /*srcstr=*/ src, /*dstsize=*/ NULL_TREE, data.mode,
2686 &data, m_ptr_qry.rvals);
2687 }
2688
2689
2690 /* Check a call STMT to an atomic or sync built-in. */
2691
2692 bool
2693 pass_waccess::check_atomic_builtin (gcall *stmt)
2694 {
2695 tree callee = gimple_call_fndecl (stmt);
2696 if (!callee)
2697 return false;
2698
2699 /* The size in bytes of the access by the function, and the number
2700 of the second argument to check (if any). */
2701 unsigned bytes = 0, arg2 = UINT_MAX;
2702
2703 switch (DECL_FUNCTION_CODE (callee))
2704 {
2705 #define BUILTIN_ACCESS_SIZE_FNSPEC(N) \
2706 BUILT_IN_ATOMIC_LOAD_ ## N: \
2707 case BUILT_IN_SYNC_FETCH_AND_ADD_ ## N: \
2708 case BUILT_IN_SYNC_FETCH_AND_SUB_ ## N: \
2709 case BUILT_IN_SYNC_FETCH_AND_OR_ ## N: \
2710 case BUILT_IN_SYNC_FETCH_AND_AND_ ## N: \
2711 case BUILT_IN_SYNC_FETCH_AND_XOR_ ## N: \
2712 case BUILT_IN_SYNC_FETCH_AND_NAND_ ## N: \
2713 case BUILT_IN_SYNC_ADD_AND_FETCH_ ## N: \
2714 case BUILT_IN_SYNC_SUB_AND_FETCH_ ## N: \
2715 case BUILT_IN_SYNC_OR_AND_FETCH_ ## N: \
2716 case BUILT_IN_SYNC_AND_AND_FETCH_ ## N: \
2717 case BUILT_IN_SYNC_XOR_AND_FETCH_ ## N: \
2718 case BUILT_IN_SYNC_NAND_AND_FETCH_ ## N: \
2719 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_ ## N: \
2720 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_ ## N: \
2721 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_ ## N: \
2722 case BUILT_IN_SYNC_LOCK_RELEASE_ ## N: \
2723 case BUILT_IN_ATOMIC_EXCHANGE_ ## N: \
2724 case BUILT_IN_ATOMIC_STORE_ ## N: \
2725 case BUILT_IN_ATOMIC_ADD_FETCH_ ## N: \
2726 case BUILT_IN_ATOMIC_SUB_FETCH_ ## N: \
2727 case BUILT_IN_ATOMIC_AND_FETCH_ ## N: \
2728 case BUILT_IN_ATOMIC_NAND_FETCH_ ## N: \
2729 case BUILT_IN_ATOMIC_XOR_FETCH_ ## N: \
2730 case BUILT_IN_ATOMIC_OR_FETCH_ ## N: \
2731 case BUILT_IN_ATOMIC_FETCH_ADD_ ## N: \
2732 case BUILT_IN_ATOMIC_FETCH_SUB_ ## N: \
2733 case BUILT_IN_ATOMIC_FETCH_AND_ ## N: \
2734 case BUILT_IN_ATOMIC_FETCH_NAND_ ## N: \
2735 case BUILT_IN_ATOMIC_FETCH_OR_ ## N: \
2736 case BUILT_IN_ATOMIC_FETCH_XOR_ ## N: \
2737 bytes = N; \
2738 break; \
2739 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_ ## N: \
2740 bytes = N; \
2741 arg2 = 1
2742
2743 case BUILTIN_ACCESS_SIZE_FNSPEC (1);
2744 break;
2745 case BUILTIN_ACCESS_SIZE_FNSPEC (2);
2746 break;
2747 case BUILTIN_ACCESS_SIZE_FNSPEC (4);
2748 break;
2749 case BUILTIN_ACCESS_SIZE_FNSPEC (8);
2750 break;
2751 case BUILTIN_ACCESS_SIZE_FNSPEC (16);
2752 break;
2753
2754 default:
2755 return false;
2756 }
2757
2758 tree size = build_int_cstu (sizetype, bytes);
2759 tree dst = gimple_call_arg (stmt, 0);
2760 check_memop_access (stmt, dst, NULL_TREE, size);
2761
2762 if (arg2 != UINT_MAX)
2763 {
2764 tree dst = gimple_call_arg (stmt, arg2);
2765 check_memop_access (stmt, dst, NULL_TREE, size);
2766 }
2767
2768 return true;
2769 }
2770
2771 /* Check call STMT to a built-in function for invalid accesses. Return
2772 true if a call has been handled. */
2773
2774 bool
2775 pass_waccess::check_builtin (gcall *stmt)
2776 {
2777 tree callee = gimple_call_fndecl (stmt);
2778 if (!callee)
2779 return false;
2780
2781 switch (DECL_FUNCTION_CODE (callee))
2782 {
2783 case BUILT_IN_ALLOCA:
2784 case BUILT_IN_ALLOCA_WITH_ALIGN:
2785 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
2786 check_alloca (stmt);
2787 return true;
2788
2789 case BUILT_IN_EXECL:
2790 case BUILT_IN_EXECLE:
2791 case BUILT_IN_EXECLP:
2792 case BUILT_IN_EXECV:
2793 case BUILT_IN_EXECVE:
2794 case BUILT_IN_EXECVP:
2795 check_read_access (stmt, call_arg (stmt, 0));
2796 return true;
2797
2798 case BUILT_IN_GETTEXT:
2799 case BUILT_IN_PUTS:
2800 case BUILT_IN_PUTS_UNLOCKED:
2801 case BUILT_IN_STRDUP:
2802 check_read_access (stmt, call_arg (stmt, 0));
2803 return true;
2804
2805 case BUILT_IN_INDEX:
2806 case BUILT_IN_RINDEX:
2807 case BUILT_IN_STRCHR:
2808 case BUILT_IN_STRRCHR:
2809 case BUILT_IN_STRLEN:
2810 check_read_access (stmt, call_arg (stmt, 0));
2811 return true;
2812
2813 case BUILT_IN_FPUTS:
2814 case BUILT_IN_FPUTS_UNLOCKED:
2815 check_read_access (stmt, call_arg (stmt, 0));
2816 return true;
2817
2818 case BUILT_IN_STRNDUP:
2819 case BUILT_IN_STRNLEN:
2820 {
2821 tree str = call_arg (stmt, 0);
2822 tree len = call_arg (stmt, 1);
2823 check_read_access (stmt, str, len);
2824 return true;
2825 }
2826
2827 case BUILT_IN_STRCAT:
2828 check_strcat (stmt);
2829 return true;
2830
2831 case BUILT_IN_STRNCAT:
2832 check_strncat (stmt);
2833 return true;
2834
2835 case BUILT_IN_STPCPY:
2836 case BUILT_IN_STRCPY:
2837 check_stxcpy (stmt);
2838 return true;
2839
2840 case BUILT_IN_STPNCPY:
2841 case BUILT_IN_STRNCPY:
2842 check_stxncpy (stmt);
2843 return true;
2844
2845 case BUILT_IN_STRCASECMP:
2846 case BUILT_IN_STRCMP:
2847 case BUILT_IN_STRPBRK:
2848 case BUILT_IN_STRSPN:
2849 case BUILT_IN_STRCSPN:
2850 case BUILT_IN_STRSTR:
2851 check_read_access (stmt, call_arg (stmt, 0));
2852 check_read_access (stmt, call_arg (stmt, 1));
2853 return true;
2854
2855 case BUILT_IN_STRNCASECMP:
2856 case BUILT_IN_STRNCMP:
2857 check_strncmp (stmt);
2858 return true;
2859
2860 case BUILT_IN_MEMCMP:
2861 {
2862 tree a1 = call_arg (stmt, 0);
2863 tree a2 = call_arg (stmt, 1);
2864 tree len = call_arg (stmt, 2);
2865 check_read_access (stmt, a1, len, 0);
2866 check_read_access (stmt, a2, len, 0);
2867 return true;
2868 }
2869
2870 case BUILT_IN_MEMCPY:
2871 case BUILT_IN_MEMPCPY:
2872 case BUILT_IN_MEMMOVE:
2873 {
2874 tree dst = call_arg (stmt, 0);
2875 tree src = call_arg (stmt, 1);
2876 tree len = call_arg (stmt, 2);
2877 check_memop_access (stmt, dst, src, len);
2878 return true;
2879 }
2880
2881 case BUILT_IN_MEMCHR:
2882 {
2883 tree src = call_arg (stmt, 0);
2884 tree len = call_arg (stmt, 2);
2885 check_read_access (stmt, src, len, 0);
2886 return true;
2887 }
2888
2889 case BUILT_IN_MEMSET:
2890 {
2891 tree dst = call_arg (stmt, 0);
2892 tree len = call_arg (stmt, 2);
2893 check_memop_access (stmt, dst, NULL_TREE, len);
2894 return true;
2895 }
2896
2897 default:
2898 if (check_atomic_builtin (stmt))
2899 return true;
2900 break;
2901 }
2902 return false;
2903 }
2904
2905 /* Returns the type of the argument ARGNO to function with type FNTYPE
2906 or null when the typoe cannot be determined or no such argument exists. */
2907
2908 static tree
2909 fntype_argno_type (tree fntype, unsigned argno)
2910 {
2911 if (!prototype_p (fntype))
2912 return NULL_TREE;
2913
2914 tree argtype;
2915 function_args_iterator it;
2916 FOREACH_FUNCTION_ARGS (fntype, argtype, it)
2917 if (argno-- == 0)
2918 return argtype;
2919
2920 return NULL_TREE;
2921 }
2922
2923 /* Helper to append the "human readable" attribute access specification
2924 described by ACCESS to the array ATTRSTR with size STRSIZE. Used in
2925 diagnostics. */
2926
2927 static inline void
2928 append_attrname (const std::pair<int, attr_access> &access,
2929 char *attrstr, size_t strsize)
2930 {
2931 if (access.second.internal_p)
2932 return;
2933
2934 tree str = access.second.to_external_string ();
2935 gcc_assert (strsize >= (size_t) TREE_STRING_LENGTH (str));
2936 strcpy (attrstr, TREE_STRING_POINTER (str));
2937 }
2938
2939 /* Iterate over attribute access read-only, read-write, and write-only
2940 arguments and diagnose past-the-end accesses and related problems
2941 in the function call EXP. */
2942
2943 void
2944 pass_waccess::maybe_check_access_sizes (rdwr_map *rwm, tree fndecl, tree fntype,
2945 gimple *stmt)
2946 {
2947 auto_diagnostic_group adg;
2948
2949 /* Set if a warning has been issued for any argument (used to decide
2950 whether to emit an informational note at the end). */
2951 opt_code opt_warned = no_warning;
2952
2953 /* A string describing the attributes that the warnings issued by this
2954 function apply to. Used to print one informational note per function
2955 call, rather than one per warning. That reduces clutter. */
2956 char attrstr[80];
2957 attrstr[0] = 0;
2958
2959 for (rdwr_map::iterator it = rwm->begin (); it != rwm->end (); ++it)
2960 {
2961 std::pair<int, attr_access> access = *it;
2962
2963 /* Get the function call arguments corresponding to the attribute's
2964 positional arguments. When both arguments have been specified
2965 there will be two entries in *RWM, one for each. They are
2966 cross-referenced by their respective argument numbers in
2967 ACCESS.PTRARG and ACCESS.SIZARG. */
2968 const int ptridx = access.second.ptrarg;
2969 const int sizidx = access.second.sizarg;
2970
2971 gcc_assert (ptridx != -1);
2972 gcc_assert (access.first == ptridx || access.first == sizidx);
2973
2974 /* The pointer is set to null for the entry corresponding to
2975 the size argument. Skip it. It's handled when the entry
2976 corresponding to the pointer argument comes up. */
2977 if (!access.second.ptr)
2978 continue;
2979
2980 tree ptrtype = fntype_argno_type (fntype, ptridx);
2981 if (!ptrtype)
2982 /* A function with a prototype was redeclared without one and
2983 the protype has been lost. See pr102759. Avoid dealing
2984 with this pathological case. */
2985 return;
2986
2987 tree argtype = TREE_TYPE (ptrtype);
2988
2989 /* The size of the access by the call in elements. */
2990 tree access_nelts;
2991 if (sizidx == -1)
2992 {
2993 /* If only the pointer attribute operand was specified and
2994 not size, set SIZE to the greater of MINSIZE or size of
2995 one element of the pointed to type to detect smaller
2996 objects (null pointers are diagnosed in this case only
2997 if the pointer is also declared with attribute nonnull. */
2998 if (access.second.minsize
2999 && access.second.minsize != HOST_WIDE_INT_M1U)
3000 access_nelts = build_int_cstu (sizetype, access.second.minsize);
3001 else if (VOID_TYPE_P (argtype) && access.second.mode == access_none)
3002 /* Treat access mode none on a void* argument as expecting
3003 as little as zero bytes. */
3004 access_nelts = size_zero_node;
3005 else
3006 access_nelts = size_one_node;
3007 }
3008 else
3009 access_nelts = rwm->get (sizidx)->size;
3010
3011 /* Format the value or range to avoid an explosion of messages. */
3012 char sizstr[80];
3013 tree sizrng[2] = { size_zero_node, build_all_ones_cst (sizetype) };
3014 if (get_size_range (m_ptr_qry.rvals, access_nelts, stmt, sizrng, 1))
3015 {
3016 char *s0 = print_generic_expr_to_str (sizrng[0]);
3017 if (tree_int_cst_equal (sizrng[0], sizrng[1]))
3018 {
3019 gcc_checking_assert (strlen (s0) < sizeof sizstr);
3020 strcpy (sizstr, s0);
3021 }
3022 else
3023 {
3024 char *s1 = print_generic_expr_to_str (sizrng[1]);
3025 gcc_checking_assert (strlen (s0) + strlen (s1)
3026 < sizeof sizstr - 4);
3027 sprintf (sizstr, "[%.37s, %.37s]", s0, s1);
3028 free (s1);
3029 }
3030 free (s0);
3031 }
3032 else
3033 *sizstr = '\0';
3034
3035 /* Set if a warning has been issued for the current argument. */
3036 opt_code arg_warned = no_warning;
3037 location_t loc = get_location (stmt);
3038 tree ptr = access.second.ptr;
3039 if (*sizstr
3040 && tree_int_cst_sgn (sizrng[0]) < 0
3041 && tree_int_cst_sgn (sizrng[1]) < 0)
3042 {
3043 /* Warn about negative sizes. */
3044 if (access.second.internal_p)
3045 {
3046 const std::string argtypestr
3047 = access.second.array_as_string (ptrtype);
3048
3049 if (warning_at (loc, OPT_Wstringop_overflow_,
3050 "bound argument %i value %s is "
3051 "negative for a variable length array "
3052 "argument %i of type %s",
3053 sizidx + 1, sizstr,
3054 ptridx + 1, argtypestr.c_str ()))
3055 arg_warned = OPT_Wstringop_overflow_;
3056 }
3057 else if (warning_at (loc, OPT_Wstringop_overflow_,
3058 "argument %i value %s is negative",
3059 sizidx + 1, sizstr))
3060 arg_warned = OPT_Wstringop_overflow_;
3061
3062 if (arg_warned != no_warning)
3063 {
3064 append_attrname (access, attrstr, sizeof attrstr);
3065 /* Remember a warning has been issued and avoid warning
3066 again below for the same attribute. */
3067 opt_warned = arg_warned;
3068 continue;
3069 }
3070 }
3071
3072 /* The size of the access by the call in bytes. */
3073 tree access_size = NULL_TREE;
3074 if (tree_int_cst_sgn (sizrng[0]) >= 0)
3075 {
3076 if (COMPLETE_TYPE_P (argtype))
3077 {
3078 /* Multiply ACCESS_SIZE by the size of the type the pointer
3079 argument points to. If it's incomplete the size is used
3080 as is. */
3081 if (tree argsize = TYPE_SIZE_UNIT (argtype))
3082 if (TREE_CODE (argsize) == INTEGER_CST)
3083 {
3084 const int prec = TYPE_PRECISION (sizetype);
3085 wide_int minsize = wi::to_wide (sizrng[0], prec);
3086 minsize *= wi::to_wide (argsize, prec);
3087 access_size = wide_int_to_tree (sizetype, minsize);
3088 }
3089 }
3090 else
3091 access_size = access_nelts;
3092 }
3093
3094 if (integer_zerop (ptr))
3095 {
3096 if (sizidx >= 0 && tree_int_cst_sgn (sizrng[0]) > 0)
3097 {
3098 /* Warn about null pointers with positive sizes. This is
3099 different from also declaring the pointer argument with
3100 attribute nonnull when the function accepts null pointers
3101 only when the corresponding size is zero. */
3102 if (access.second.internal_p)
3103 {
3104 const std::string argtypestr
3105 = access.second.array_as_string (ptrtype);
3106
3107 if (warning_at (loc, OPT_Wnonnull,
3108 "argument %i of variable length "
3109 "array %s is null but "
3110 "the corresponding bound argument "
3111 "%i value is %s",
3112 ptridx + 1, argtypestr.c_str (),
3113 sizidx + 1, sizstr))
3114 arg_warned = OPT_Wnonnull;
3115 }
3116 else if (warning_at (loc, OPT_Wnonnull,
3117 "argument %i is null but "
3118 "the corresponding size argument "
3119 "%i value is %s",
3120 ptridx + 1, sizidx + 1, sizstr))
3121 arg_warned = OPT_Wnonnull;
3122 }
3123 else if (access_size && access.second.static_p)
3124 {
3125 /* Warn about null pointers for [static N] array arguments
3126 but do not warn for ordinary (i.e., nonstatic) arrays. */
3127 if (warning_at (loc, OPT_Wnonnull,
3128 "argument %i to %<%T[static %E]%> "
3129 "is null where non-null expected",
3130 ptridx + 1, argtype, access_size))
3131 arg_warned = OPT_Wnonnull;
3132 }
3133
3134 if (arg_warned != no_warning)
3135 {
3136 append_attrname (access, attrstr, sizeof attrstr);
3137 /* Remember a warning has been issued and avoid warning
3138 again below for the same attribute. */
3139 opt_warned = OPT_Wnonnull;
3140 continue;
3141 }
3142 }
3143
3144 access_data data (m_ptr_qry.rvals, stmt, access.second.mode,
3145 NULL_TREE, false, NULL_TREE, false);
3146 access_ref* const pobj = (access.second.mode == access_write_only
3147 ? &data.dst : &data.src);
3148 tree objsize = compute_objsize (ptr, stmt, 1, pobj, &m_ptr_qry);
3149
3150 /* The size of the destination or source object. */
3151 tree dstsize = NULL_TREE, srcsize = NULL_TREE;
3152 if (access.second.mode == access_read_only
3153 || access.second.mode == access_none)
3154 {
3155 /* For a read-only argument there is no destination. For
3156 no access, set the source as well and differentiate via
3157 the access flag below. */
3158 srcsize = objsize;
3159 if (access.second.mode == access_read_only
3160 || access.second.mode == access_none)
3161 {
3162 /* For a read-only attribute there is no destination so
3163 clear OBJSIZE. This emits "reading N bytes" kind of
3164 diagnostics instead of the "writing N bytes" kind,
3165 unless MODE is none. */
3166 objsize = NULL_TREE;
3167 }
3168 }
3169 else
3170 dstsize = objsize;
3171
3172 /* Clear the no-warning bit in case it was set by check_access
3173 in a prior iteration so that accesses via different arguments
3174 are diagnosed. */
3175 suppress_warning (stmt, OPT_Wstringop_overflow_, false);
3176 access_mode mode = data.mode;
3177 if (mode == access_deferred)
3178 mode = TYPE_READONLY (argtype) ? access_read_only : access_read_write;
3179 check_access (stmt, access_size, /*maxread=*/ NULL_TREE, srcsize,
3180 dstsize, mode, &data, m_ptr_qry.rvals);
3181
3182 if (warning_suppressed_p (stmt, OPT_Wstringop_overflow_))
3183 opt_warned = OPT_Wstringop_overflow_;
3184 if (opt_warned != no_warning)
3185 {
3186 if (access.second.internal_p)
3187 {
3188 unsigned HOST_WIDE_INT nelts =
3189 access_nelts ? access.second.minsize : HOST_WIDE_INT_M1U;
3190 tree arrtype = build_printable_array_type (argtype, nelts);
3191 inform (loc, "referencing argument %u of type %qT",
3192 ptridx + 1, arrtype);
3193 }
3194 else
3195 /* If check_access issued a warning above, append the relevant
3196 attribute to the string. */
3197 append_attrname (access, attrstr, sizeof attrstr);
3198 }
3199 }
3200
3201 if (*attrstr)
3202 {
3203 if (fndecl)
3204 inform (get_location (fndecl),
3205 "in a call to function %qD declared with attribute %qs",
3206 fndecl, attrstr);
3207 else
3208 inform (get_location (stmt),
3209 "in a call with type %qT and attribute %qs",
3210 fntype, attrstr);
3211 }
3212 else if (opt_warned != no_warning)
3213 {
3214 if (fndecl)
3215 inform (get_location (fndecl),
3216 "in a call to function %qD", fndecl);
3217 else
3218 inform (get_location (stmt),
3219 "in a call with type %qT", fntype);
3220 }
3221
3222 /* Set the bit in case if was cleared and not set above. */
3223 if (opt_warned != no_warning)
3224 suppress_warning (stmt, opt_warned);
3225 }
3226
3227 /* Check call STMT to an ordinary (non-built-in) function for invalid
3228 accesses. Return true if a call has been handled. */
3229
3230 bool
3231 pass_waccess::check_call (gcall *stmt)
3232 {
3233 tree fntype = gimple_call_fntype (stmt);
3234 if (!fntype)
3235 return false;
3236
3237 tree fntypeattrs = TYPE_ATTRIBUTES (fntype);
3238 if (!fntypeattrs)
3239 return false;
3240
3241 /* Map of attribute accewss specifications for function arguments. */
3242 rdwr_map rdwr_idx;
3243 init_attr_rdwr_indices (&rdwr_idx, fntypeattrs);
3244
3245 unsigned nargs = call_nargs (stmt);
3246 for (unsigned i = 0; i != nargs; ++i)
3247 {
3248 tree arg = call_arg (stmt, i);
3249
3250 /* Save the actual argument that corresponds to the access attribute
3251 operand for later processing. */
3252 if (attr_access *access = rdwr_idx.get (i))
3253 {
3254 if (POINTER_TYPE_P (TREE_TYPE (arg)))
3255 {
3256 access->ptr = arg;
3257 // A nonnull ACCESS->SIZE contains VLA bounds. */
3258 }
3259 else
3260 {
3261 access->size = arg;
3262 gcc_assert (access->ptr == NULL_TREE);
3263 }
3264 }
3265 }
3266
3267 /* Check attribute access arguments. */
3268 tree fndecl = gimple_call_fndecl (stmt);
3269 maybe_check_access_sizes (&rdwr_idx, fndecl, fntype, stmt);
3270
3271 check_alloc_size_call (stmt);
3272 return true;
3273 }
3274
3275 /* Check arguments in a call STMT for attribute nonstring. */
3276
3277 static void
3278 check_nonstring_args (gcall *stmt)
3279 {
3280 tree fndecl = gimple_call_fndecl (stmt);
3281
3282 /* Detect passing non-string arguments to functions expecting
3283 nul-terminated strings. */
3284 maybe_warn_nonstring_arg (fndecl, stmt);
3285 }
3286
3287 /* Issue a warning if a deallocation function such as free, realloc,
3288 or C++ operator delete is called with an argument not returned by
3289 a matching allocation function such as malloc or the corresponding
3290 form of C++ operatorn new. */
3291
3292 void
3293 pass_waccess::maybe_check_dealloc_call (gcall *call)
3294 {
3295 tree fndecl = gimple_call_fndecl (call);
3296 if (!fndecl)
3297 return;
3298
3299 unsigned argno = fndecl_dealloc_argno (fndecl);
3300 if ((unsigned) call_nargs (call) <= argno)
3301 return;
3302
3303 tree ptr = gimple_call_arg (call, argno);
3304 if (integer_zerop (ptr))
3305 return;
3306
3307 access_ref aref;
3308 if (!compute_objsize (ptr, call, 0, &aref, &m_ptr_qry))
3309 return;
3310
3311 tree ref = aref.ref;
3312 if (integer_zerop (ref))
3313 return;
3314
3315 tree dealloc_decl = fndecl;
3316 location_t loc = gimple_location (call);
3317
3318 if (DECL_P (ref) || EXPR_P (ref))
3319 {
3320 /* Diagnose freeing a declared object. */
3321 if (aref.ref_declared ()
3322 && warning_at (loc, OPT_Wfree_nonheap_object,
3323 "%qD called on unallocated object %qD",
3324 dealloc_decl, ref))
3325 {
3326 inform (get_location (ref), "declared here");
3327 return;
3328 }
3329
3330 /* Diagnose freeing a pointer that includes a positive offset.
3331 Such a pointer cannot refer to the beginning of an allocated
3332 object. A negative offset may refer to it. */
3333 if (aref.sizrng[0] != aref.sizrng[1]
3334 && warn_dealloc_offset (loc, call, aref))
3335 return;
3336 }
3337 else if (CONSTANT_CLASS_P (ref))
3338 {
3339 if (warning_at (loc, OPT_Wfree_nonheap_object,
3340 "%qD called on a pointer to an unallocated "
3341 "object %qE", dealloc_decl, ref))
3342 {
3343 if (TREE_CODE (ptr) == SSA_NAME)
3344 {
3345 gimple *def_stmt = SSA_NAME_DEF_STMT (ptr);
3346 if (is_gimple_assign (def_stmt))
3347 {
3348 location_t loc = gimple_location (def_stmt);
3349 inform (loc, "assigned here");
3350 }
3351 }
3352 return;
3353 }
3354 }
3355 else if (TREE_CODE (ref) == SSA_NAME)
3356 {
3357 /* Also warn if the pointer argument refers to the result
3358 of an allocation call like alloca or VLA. */
3359 gimple *def_stmt = SSA_NAME_DEF_STMT (ref);
3360 if (!def_stmt)
3361 return;
3362
3363 if (is_gimple_call (def_stmt))
3364 {
3365 bool warned = false;
3366 if (gimple_call_alloc_p (def_stmt))
3367 {
3368 if (matching_alloc_calls_p (def_stmt, dealloc_decl))
3369 {
3370 if (warn_dealloc_offset (loc, call, aref))
3371 return;
3372 }
3373 else
3374 {
3375 tree alloc_decl = gimple_call_fndecl (def_stmt);
3376 const opt_code opt =
3377 (DECL_IS_OPERATOR_NEW_P (alloc_decl)
3378 || DECL_IS_OPERATOR_DELETE_P (dealloc_decl)
3379 ? OPT_Wmismatched_new_delete
3380 : OPT_Wmismatched_dealloc);
3381 warned = warning_at (loc, opt,
3382 "%qD called on pointer returned "
3383 "from a mismatched allocation "
3384 "function", dealloc_decl);
3385 }
3386 }
3387 else if (gimple_call_builtin_p (def_stmt, BUILT_IN_ALLOCA)
3388 || gimple_call_builtin_p (def_stmt,
3389 BUILT_IN_ALLOCA_WITH_ALIGN))
3390 warned = warning_at (loc, OPT_Wfree_nonheap_object,
3391 "%qD called on pointer to "
3392 "an unallocated object",
3393 dealloc_decl);
3394 else if (warn_dealloc_offset (loc, call, aref))
3395 return;
3396
3397 if (warned)
3398 {
3399 tree fndecl = gimple_call_fndecl (def_stmt);
3400 inform (gimple_location (def_stmt),
3401 "returned from %qD", fndecl);
3402 return;
3403 }
3404 }
3405 else if (gimple_nop_p (def_stmt))
3406 {
3407 ref = SSA_NAME_VAR (ref);
3408 /* Diagnose freeing a pointer that includes a positive offset. */
3409 if (TREE_CODE (ref) == PARM_DECL
3410 && !aref.deref
3411 && aref.sizrng[0] != aref.sizrng[1]
3412 && aref.offrng[0] > 0 && aref.offrng[1] > 0
3413 && warn_dealloc_offset (loc, call, aref))
3414 return;
3415 }
3416 }
3417 }
3418
3419 /* Check call STMT for invalid accesses. */
3420
3421 void
3422 pass_waccess::check (gcall *stmt)
3423 {
3424 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
3425 check_builtin (stmt);
3426
3427 if (is_gimple_call (stmt))
3428 check_call (stmt);
3429
3430 maybe_check_dealloc_call (stmt);
3431
3432 check_nonstring_args (stmt);
3433 }
3434
3435 /* Check basic block BB for invalid accesses. */
3436
3437 void
3438 pass_waccess::check (basic_block bb)
3439 {
3440 /* Iterate over statements, looking for function calls. */
3441 for (auto si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
3442 {
3443 if (gcall *call = dyn_cast <gcall *> (gsi_stmt (si)))
3444 check (call);
3445 }
3446 }
3447
3448 /* Check function FUN for invalid accesses. */
3449
3450 unsigned
3451 pass_waccess::execute (function *fun)
3452 {
3453 /* Create a new ranger instance and associate it with FUN. */
3454 m_ptr_qry.rvals = enable_ranger (fun);
3455
3456 basic_block bb;
3457 FOR_EACH_BB_FN (bb, fun)
3458 check (bb);
3459
3460 if (dump_file)
3461 m_ptr_qry.dump (dump_file, (dump_flags & TDF_DETAILS) != 0);
3462
3463 m_ptr_qry.flush_cache ();
3464
3465 /* Release the ranger instance and replace it with a global ranger.
3466 Also reset the pointer since calling disable_ranger() deletes it. */
3467 disable_ranger (fun);
3468 m_ptr_qry.rvals = NULL;
3469
3470 return 0;
3471 }
3472
3473 } // namespace
3474
3475 /* Return a new instance of the pass. */
3476
3477 gimple_opt_pass *
3478 make_pass_warn_access (gcc::context *ctxt)
3479 {
3480 return new pass_waccess (ctxt);
3481 }