]> git.ipfire.org Git - thirdparty/gcc.git/blame - gcc/gimple-ssa-warn-access.cc
libstdc++: only define _GLIBCXX_HAVE_TLS for VxWorks >= 6.6
[thirdparty/gcc.git] / gcc / gimple-ssa-warn-access.cc
CommitLineData
2a837de2
MS
1/* Pass to detect and issue warnings for invalid accesses, including
2 invalid or mismatched allocation/deallocation calls.
3
4 Copyright (C) 2020-2021 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
b48d4e68 23#define INCLUDE_STRING
2a837de2
MS
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"
b48d4e68 40#include "langhooks.h"
2a837de2
MS
41#include "tree-dfa.h"
42#include "tree-ssa.h"
43#include "tree-cfg.h"
44#include "tree-object-size.h"
81d6cdd3 45#include "tree-ssa-strlen.h"
2a837de2
MS
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
81d6cdd3
MS
55/* Return true if tree node X has an associated location. */
56
57static inline location_t
58has_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
71static inline location_t
72get_location (const gimple *stmt)
73{
74 return gimple_location (stmt);
75}
76
77/* Return the associated location of tree node X. */
78
79static inline location_t
80get_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
93static inline tree
94get_callee_fndecl (const gimple *stmt)
95{
96 return gimple_call_fndecl (stmt);
97}
98
99static inline unsigned
100call_nargs (const gimple *stmt)
101{
102 return gimple_call_num_args (stmt);
103}
104
105static inline unsigned
106call_nargs (const_tree expr)
107{
108 return call_expr_nargs (expr);
109}
110
111
112static inline tree
113call_arg (const gimple *stmt, unsigned argno)
114{
115 return gimple_call_arg (stmt, argno);
116}
117
118static inline tree
119call_arg (tree expr, unsigned argno)
120{
121 return CALL_EXPR_ARG (expr, argno);
122}
123
2a837de2
MS
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
81d6cdd3
MS
131template <class GimpleOrTree>
132static void
133warn_string_no_nul (location_t loc, GimpleOrTree expr, const char *fname,
134 tree arg, tree decl, tree size, bool exact,
2a837de2
MS
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 {
81d6cdd3 227 inform (get_location (decl),
2a837de2
MS
228 "referenced argument declared here");
229 suppress_warning (arg, opt);
230 if (expr)
231 suppress_warning (expr, opt);
232 }
233}
234
81d6cdd3
MS
235void
236warn_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
245void
246warn_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
261tree
262unterminated_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
2a837de2
MS
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
81d6cdd3
MS
303 in which to expect the terminating NUL. When EXPR is nonnull also
304 issues a warning. */
2a837de2 305
81d6cdd3
MS
306template <class GimpleOrTree>
307static bool
308check_nul_terminated_array (GimpleOrTree expr, tree src, tree bound)
2a837de2
MS
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)
81d6cdd3 347 warn_string_no_nul (get_location (expr), expr, NULL, src, nonstr,
2a837de2
MS
348 size, exact, bound ? bndrng : NULL);
349
350 return false;
351}
352
81d6cdd3
MS
353bool
354check_nul_terminated_array (gimple *stmt, tree src, tree bound /* = NULL_TREE */)
355{
356 return check_nul_terminated_array<gimple *>(stmt, src, bound);
357}
2a837de2 358
81d6cdd3
MS
359bool
360check_nul_terminated_array (tree expr, tree src, tree bound /* = NULL_TREE */)
2a837de2 361{
81d6cdd3
MS
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
369template <class GimpleOrTree>
370static bool
371maybe_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]))
2a837de2 480 {
81d6cdd3
MS
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))
2a837de2 602 {
81d6cdd3 603 if ((arrbnd = TYPE_MAX_VALUE (arrbnd)))
2a837de2 604 {
81d6cdd3
MS
605 asize = wi::to_offset (arrbnd) + 1;
606 known_size = true;
2a837de2 607 }
2a837de2 608 }
81d6cdd3
MS
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]);
2a837de2 647 else
81d6cdd3
MS
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);
2a837de2 661
81d6cdd3
MS
662 if (warned)
663 {
664 inform (DECL_SOURCE_LOCATION (decl),
665 "argument %qD declared here", decl);
666 any_arg_warned = true;
2a837de2 667 }
81d6cdd3
MS
668 }
669
670 if (any_arg_warned)
671 suppress_warning (exp, OPT_Wstringop_overread);
672
673 return any_arg_warned;
674}
675
676bool
677maybe_warn_nonstring_arg (tree fndecl, gimple *stmt)
678{
679 return maybe_warn_nonstring_arg<gimple *>(fndecl, stmt);
680}
2a837de2 681
81d6cdd3
MS
682
683bool
684maybe_warn_nonstring_arg (tree fndecl, tree expr)
685{
686 return maybe_warn_nonstring_arg<tree>(fndecl, expr);
2a837de2
MS
687}
688
689/* Issue a warning OPT for a bounded call EXP with a bound in RANGE
690 accessing an object with SIZE. */
691
81d6cdd3
MS
692template <class GimpleOrTree>
693static bool
694maybe_warn_for_bound (opt_code opt, location_t loc, GimpleOrTree exp, tree func,
695 tree bndrng[2], tree size, const access_data *pad)
2a837de2
MS
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 ();
820f0940
MS
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 }
2a837de2
MS
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 {
81d6cdd3
MS
789 if (pad && pad->src.ref
790 && has_location (pad->src.ref))
791 inform (get_location (pad->src.ref),
792 "source object allocated here");
2a837de2
MS
793 suppress_warning (exp, opt);
794 }
795
796 return warned;
797 }
798
799 bool maybe = pad && pad->dst.phi ();
820f0940
MS
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 }
2a837de2
MS
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 {
81d6cdd3
MS
881 if (pad && pad->dst.ref
882 && has_location (pad->dst.ref))
883 inform (get_location (pad->dst.ref),
884 "destination object allocated here");
2a837de2
MS
885 suppress_warning (exp, opt);
886 }
887
888 return warned;
889}
890
81d6cdd3
MS
891bool
892maybe_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
900bool
901maybe_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
2a837de2
MS
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
81d6cdd3 915template <class GimpleOrTree>
2a837de2 916static bool
81d6cdd3
MS
917warn_for_access (location_t loc, tree func, GimpleOrTree exp, int opt,
918 tree range[2], tree size, bool write, bool read, bool maybe)
2a837de2
MS
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
81d6cdd3
MS
1173static bool
1174warn_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
1181static bool
1182warn_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
2a837de2
MS
1189/* Helper to set RANGE to the range of BOUND if it's nonnull, bounded
1190 by BNDRNG if nonnull and valid. */
1191
b48d4e68 1192static void
9a27acc3 1193get_size_range (range_query *query, tree bound, gimple *stmt, tree range[2],
ece28da9 1194 const offset_int bndrng[2])
2a837de2
MS
1195{
1196 if (bound)
9a27acc3 1197 get_size_range (query, bound, stmt, range);
2a837de2
MS
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
81d6cdd3
MS
1250template <class GimpleOrTree>
1251static bool
1252check_access (GimpleOrTree exp, tree dstwrite,
2a837de2 1253 tree maxread, tree srcstr, tree dstsize,
9a27acc3
MS
1254 access_mode mode, const access_data *pad,
1255 range_query *rvals)
2a837de2
MS
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))
81d6cdd3
MS
1282 /* Return if the array is not nul-terminated and a warning
1283 has been issued. */
2a837de2 1284 return false;
81d6cdd3 1285
2a837de2
MS
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. */
9a27acc3
MS
1342 gimple *stmt = pad ? pad->stmt : nullptr;
1343 get_size_range (rvals, dstwrite, stmt, range, pad ? pad->dst.bndrng : NULL);
2a837de2
MS
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 {
81d6cdd3 1358 location_t loc = get_location (exp);
2a837de2
MS
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
81d6cdd3 1386 location_t loc = get_location (exp);
2a837de2
MS
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. */
9a27acc3 1437 get_size_range (rvals, maxread, stmt, range, pad ? pad->src.bndrng : NULL);
2a837de2 1438
81d6cdd3 1439 location_t loc = get_location (exp);
2a837de2
MS
1440 tree size = dstsize;
1441 if (pad && pad->mode == access_read_only)
820f0940 1442 size = wide_int_to_tree (sizetype, pad->src.size_remaining ());
2a837de2
MS
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. */
9a27acc3 1484 get_size_range (rvals, maxread, stmt, range, pad ? pad->src.bndrng : NULL);
2a837de2
MS
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
81d6cdd3 1500 location_t loc = get_location (exp);
2a837de2
MS
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
9a27acc3 1517static bool
81d6cdd3
MS
1518check_access (gimple *stmt, tree dstwrite,
1519 tree maxread, tree srcstr, tree dstsize,
9a27acc3
MS
1520 access_mode mode, const access_data *pad,
1521 range_query *rvals)
81d6cdd3 1522{
9a27acc3
MS
1523 return check_access<gimple *> (stmt, dstwrite, maxread, srcstr, dstsize,
1524 mode, pad, rvals);
81d6cdd3
MS
1525}
1526
1527bool
1528check_access (tree expr, tree dstwrite,
1529 tree maxread, tree srcstr, tree dstsize,
1530 access_mode mode, const access_data *pad /* = NULL */)
1531{
9a27acc3
MS
1532 return check_access<tree> (expr, dstwrite, maxread, srcstr, dstsize,
1533 mode, pad, nullptr);
81d6cdd3
MS
1534}
1535
2a837de2
MS
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
1541static bool
1542fndecl_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
1596static bool
1597gimple_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
1606static bool
1607new_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
1721static bool
1722new_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
96194a07
MS
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))
2a837de2 1733 return false;
96194a07
MS
1734 /* CERTAIN is set when the negative result is certain. */
1735 if (certain)
1736 return true;
2a837de2
MS
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
1757static bool
1758matching_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
1961static bool
1962matching_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
1976static bool
1977warn_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))
81d6cdd3 2024 inform (get_location (aref.ref), "declared here");
2a837de2
MS
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 {
81d6cdd3 2030 location_t def_loc = get_location (def_stmt);
2a837de2
MS
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
2a837de2
MS
2046namespace {
2047
2048const 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. */
2061class pass_waccess : public gimple_opt_pass
2062{
2063 public:
b48d4e68
MS
2064 pass_waccess (gcc::context *);
2065
2066 ~pass_waccess ();
2a837de2
MS
2067
2068 opt_pass *clone () { return new pass_waccess (m_ctxt); }
2069
2070 virtual bool gate (function *);
2071 virtual unsigned int execute (function *);
2072
ece28da9
MS
2073private:
2074 /* Not copyable or assignable. */
2075 pass_waccess (pass_waccess &) = delete;
2076 void operator= (pass_waccess &) = delete;
2077
88b504b7
MS
2078 /* Check a call to an atomic built-in function. */
2079 bool check_atomic_builtin (gcall *);
2080
81d6cdd3
MS
2081 /* Check a call to a built-in function. */
2082 bool check_builtin (gcall *);
2083
b48d4e68
MS
2084 /* Check a call to an ordinary function. */
2085 bool check_call (gcall *);
2086
81d6cdd3 2087 /* Check statements in a basic block. */
2a837de2 2088 void check (basic_block);
81d6cdd3
MS
2089
2090 /* Check a call to a function. */
ece28da9 2091 void check (gcall *);
2a837de2 2092
ece28da9
MS
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);
9a27acc3 2102 void check_read_access (gimple *, tree, tree = NULL_TREE, int = 1);
ece28da9
MS
2103
2104 void maybe_check_dealloc_call (gcall *);
2105 void maybe_check_access_sizes (rdwr_map *, tree, tree, gimple *);
b48d4e68
MS
2106
2107 /* A pointer_query object and its cache to store information about
2108 pointers and their targets in. */
ece28da9
MS
2109 pointer_query m_ptr_qry;
2110 pointer_query::cache_type m_var_cache;
2a837de2
MS
2111};
2112
b48d4e68
MS
2113/* Construct the pass. */
2114
2115pass_waccess::pass_waccess (gcc::context *ctxt)
2116 : gimple_opt_pass (pass_data_waccess, ctxt),
ece28da9
MS
2117 m_ptr_qry (NULL, &m_var_cache),
2118 m_var_cache ()
b48d4e68
MS
2119{
2120}
2121
2122/* Release pointer_query cache. */
2123
2124pass_waccess::~pass_waccess ()
2125{
ece28da9 2126 m_ptr_qry.flush_cache ();
b48d4e68
MS
2127}
2128
2a837de2
MS
2129/* Return true when any checks performed by the pass are enabled. */
2130
2131bool
2132pass_waccess::gate (function *)
2133{
2134 return (warn_free_nonheap_object
2135 || warn_mismatched_alloc
2136 || warn_mismatched_new_delete);
2137}
2138
b48d4e68
MS
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
2143static tree
2144alloc_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
2161void
2162maybe_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
b3aa3288 2253 if (!argrange[0][0])
b48d4e68
MS
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
ece28da9
MS
2314void
2315pass_waccess::check_alloca (gcall *stmt)
b48d4e68
MS
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
ece28da9
MS
2335void
2336pass_waccess::check_alloc_size_call (gcall *stmt)
b48d4e68
MS
2337{
2338 if (gimple_call_num_args (stmt) < 1)
2339 /* Avoid invalid calls to functions without a prototype. */
2340 return;
2341
2342 tree fndecl = gimple_call_fndecl (stmt);
2343 if (fndecl && gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
2344 {
2345 /* Alloca is handled separately. */
2346 switch (DECL_FUNCTION_CODE (fndecl))
2347 {
2348 case BUILT_IN_ALLOCA:
2349 case BUILT_IN_ALLOCA_WITH_ALIGN:
2350 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
2351 return;
2352 default:
2353 break;
2354 }
2355 }
2356
2357 tree fntype = gimple_call_fntype (stmt);
2358 tree fntypeattrs = TYPE_ATTRIBUTES (fntype);
2359
2360 tree alloc_size = lookup_attribute ("alloc_size", fntypeattrs);
2361 if (!alloc_size)
2362 return;
2363
2364 /* Extract attribute alloc_size from the type of the called expression
2365 (which could be a function or a function pointer) and if set, store
2366 the indices of the corresponding arguments in ALLOC_IDX, and then
2367 the actual argument(s) at those indices in ALLOC_ARGS. */
2368 int idx[2] = { -1, -1 };
2369 tree alloc_args[] = { NULL_TREE, NULL_TREE };
2370
2371 tree args = TREE_VALUE (alloc_size);
2372 idx[0] = TREE_INT_CST_LOW (TREE_VALUE (args)) - 1;
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 alloc_args[1] = call_arg (stmt, idx[1]);
2378 }
2379
2380 maybe_warn_alloc_args_overflow (stmt, alloc_args, idx);
2381}
2382
81d6cdd3
MS
2383/* Check a call STMT to strcat() for overflow and warn if it does. */
2384
ece28da9
MS
2385void
2386pass_waccess::check_strcat (gcall *stmt)
81d6cdd3 2387{
b48d4e68 2388 if (!warn_stringop_overflow && !warn_stringop_overread)
81d6cdd3
MS
2389 return;
2390
2391 tree dest = call_arg (stmt, 0);
2392 tree src = call_arg (stmt, 1);
2393
2394 /* There is no way here to determine the length of the string in
2395 the destination to which the SRC string is being appended so
2396 just diagnose cases when the souce string is longer than
2397 the destination object. */
9a27acc3
MS
2398 access_data data (m_ptr_qry.rvals, stmt, access_read_write, NULL_TREE,
2399 true, NULL_TREE, true);
81d6cdd3 2400 const int ost = warn_stringop_overflow ? warn_stringop_overflow - 1 : 1;
9a27acc3
MS
2401 compute_objsize (src, stmt, ost, &data.src, &m_ptr_qry);
2402 tree destsize = compute_objsize (dest, stmt, ost, &data.dst, &m_ptr_qry);
81d6cdd3
MS
2403
2404 check_access (stmt, /*dstwrite=*/NULL_TREE, /*maxread=*/NULL_TREE,
9a27acc3 2405 src, destsize, data.mode, &data, m_ptr_qry.rvals);
81d6cdd3
MS
2406}
2407
2408/* Check a call STMT to strcat() for overflow and warn if it does. */
2409
ece28da9
MS
2410void
2411pass_waccess::check_strncat (gcall *stmt)
81d6cdd3 2412{
b48d4e68 2413 if (!warn_stringop_overflow && !warn_stringop_overread)
81d6cdd3
MS
2414 return;
2415
2416 tree dest = call_arg (stmt, 0);
2417 tree src = call_arg (stmt, 1);
2418 /* The upper bound on the number of bytes to write. */
2419 tree maxread = call_arg (stmt, 2);
2420
2421 /* Detect unterminated source (only). */
2422 if (!check_nul_terminated_array (stmt, src, maxread))
2423 return;
2424
2425 /* The length of the source sequence. */
2426 tree slen = c_strlen (src, 1);
2427
2428 /* Try to determine the range of lengths that the source expression
2429 refers to. Since the lengths are only used for warning and not
2430 for code generation disable strict mode below. */
2431 tree maxlen = slen;
2432 if (!maxlen)
2433 {
2434 c_strlen_data lendata = { };
2435 get_range_strlen (src, &lendata, /* eltsize = */ 1);
2436 maxlen = lendata.maxbound;
2437 }
2438
9a27acc3 2439 access_data data (m_ptr_qry.rvals, stmt, access_read_write);
81d6cdd3
MS
2440 /* Try to verify that the destination is big enough for the shortest
2441 string. First try to determine the size of the destination object
2442 into which the source is being copied. */
ece28da9 2443 const int ost = warn_stringop_overflow - 1;
9a27acc3 2444 tree destsize = compute_objsize (dest, stmt, ost, &data.dst, &m_ptr_qry);
81d6cdd3
MS
2445
2446 /* Add one for the terminating nul. */
2447 tree srclen = (maxlen
2448 ? fold_build2 (PLUS_EXPR, size_type_node, maxlen,
2449 size_one_node)
2450 : NULL_TREE);
2451
2452 /* The strncat function copies at most MAXREAD bytes and always appends
2453 the terminating nul so the specified upper bound should never be equal
2454 to (or greater than) the size of the destination. */
2455 if (tree_fits_uhwi_p (maxread) && tree_fits_uhwi_p (destsize)
2456 && tree_int_cst_equal (destsize, maxread))
2457 {
2458 location_t loc = get_location (stmt);
2459 warning_at (loc, OPT_Wstringop_overflow_,
2460 "%qD specified bound %E equals destination size",
2461 get_callee_fndecl (stmt), maxread);
2462
2463 return;
2464 }
2465
2466 if (!srclen
2467 || (maxread && tree_fits_uhwi_p (maxread)
2468 && tree_fits_uhwi_p (srclen)
2469 && tree_int_cst_lt (maxread, srclen)))
2470 srclen = maxread;
2471
2472 check_access (stmt, /*dstwrite=*/NULL_TREE, maxread, srclen,
9a27acc3 2473 destsize, data.mode, &data, m_ptr_qry.rvals);
81d6cdd3
MS
2474}
2475
2476/* Check a call STMT to stpcpy() or strcpy() for overflow and warn
2477 if it does. */
2478
ece28da9
MS
2479void
2480pass_waccess::check_stxcpy (gcall *stmt)
81d6cdd3
MS
2481{
2482 tree dst = call_arg (stmt, 0);
2483 tree src = call_arg (stmt, 1);
2484
2485 tree size;
2486 bool exact;
2487 if (tree nonstr = unterminated_array (src, &size, &exact))
2488 {
2489 /* NONSTR refers to the non-nul terminated constant array. */
2490 warn_string_no_nul (get_location (stmt), stmt, NULL, src, nonstr,
2491 size, exact);
2492 return;
2493 }
2494
2495 if (warn_stringop_overflow)
2496 {
9a27acc3
MS
2497 access_data data (m_ptr_qry.rvals, stmt, access_read_write, NULL_TREE,
2498 true, NULL_TREE, true);
81d6cdd3 2499 const int ost = warn_stringop_overflow ? warn_stringop_overflow - 1 : 1;
9a27acc3
MS
2500 compute_objsize (src, stmt, ost, &data.src, &m_ptr_qry);
2501 tree dstsize = compute_objsize (dst, stmt, ost, &data.dst, &m_ptr_qry);
81d6cdd3
MS
2502 check_access (stmt, /*dstwrite=*/ NULL_TREE,
2503 /*maxread=*/ NULL_TREE, /*srcstr=*/ src,
9a27acc3 2504 dstsize, data.mode, &data, m_ptr_qry.rvals);
81d6cdd3
MS
2505 }
2506
2507 /* Check to see if the argument was declared attribute nonstring
2508 and if so, issue a warning since at this point it's not known
2509 to be nul-terminated. */
2510 tree fndecl = get_callee_fndecl (stmt);
2511 maybe_warn_nonstring_arg (fndecl, stmt);
2512}
2513
2514/* Check a call STMT to stpncpy() or strncpy() for overflow and warn
2515 if it does. */
2516
ece28da9
MS
2517void
2518pass_waccess::check_stxncpy (gcall *stmt)
81d6cdd3
MS
2519{
2520 if (!warn_stringop_overflow)
2521 return;
2522
2523 tree dst = call_arg (stmt, 0);
2524 tree src = call_arg (stmt, 1);
2525 /* The number of bytes to write (not the maximum). */
2526 tree len = call_arg (stmt, 2);
2527
9a27acc3
MS
2528 access_data data (m_ptr_qry.rvals, stmt, access_read_write, len, true, len,
2529 true);
81d6cdd3 2530 const int ost = warn_stringop_overflow ? warn_stringop_overflow - 1 : 1;
9a27acc3
MS
2531 compute_objsize (src, stmt, ost, &data.src, &m_ptr_qry);
2532 tree dstsize = compute_objsize (dst, stmt, ost, &data.dst, &m_ptr_qry);
81d6cdd3 2533
9a27acc3
MS
2534 check_access (stmt, /*dstwrite=*/len, /*maxread=*/len, src, dstsize,
2535 data.mode, &data, m_ptr_qry.rvals);
81d6cdd3
MS
2536}
2537
2538/* Check a call STMT to stpncpy() or strncpy() for overflow and warn
2539 if it does. */
2540
ece28da9
MS
2541void
2542pass_waccess::check_strncmp (gcall *stmt)
81d6cdd3
MS
2543{
2544 if (!warn_stringop_overread)
2545 return;
2546
2547 tree arg1 = call_arg (stmt, 0);
2548 tree arg2 = call_arg (stmt, 1);
2549 tree bound = call_arg (stmt, 2);
2550
2551 /* First check each argument separately, considering the bound. */
2552 if (!check_nul_terminated_array (stmt, arg1, bound)
2553 || !check_nul_terminated_array (stmt, arg2, bound))
2554 return;
2555
2556 /* A strncmp read from each argument is constrained not just by
2557 the bound but also by the length of the shorter string. Specifying
2558 a bound that's larger than the size of either array makes no sense
2559 and is likely a bug. When the length of neither of the two strings
2560 is known but the sizes of both of the arrays they are stored in is,
2561 issue a warning if the bound is larger than than the size of
2562 the larger of the two arrays. */
2563
2564 c_strlen_data lendata1{ }, lendata2{ };
2565 tree len1 = c_strlen (arg1, 1, &lendata1);
2566 tree len2 = c_strlen (arg2, 1, &lendata2);
2567
9a27acc3
MS
2568 if (len1 && TREE_CODE (len1) != INTEGER_CST)
2569 len1 = NULL_TREE;
2570 if (len2 && TREE_CODE (len2) != INTEGER_CST)
2571 len2 = NULL_TREE;
2572
81d6cdd3
MS
2573 if (len1 && len2)
2574 /* If the length of both arguments was computed they must both be
2575 nul-terminated and no further checking is necessary regardless
2576 of the bound. */
2577 return;
2578
2579 /* Check to see if the argument was declared with attribute nonstring
2580 and if so, issue a warning since at this point it's not known to be
2581 nul-terminated. */
2582 if (maybe_warn_nonstring_arg (get_callee_fndecl (stmt), stmt))
2583 return;
2584
9a27acc3
MS
2585 access_data adata1 (m_ptr_qry.rvals, stmt, access_read_only, NULL_TREE, false,
2586 bound, true);
2587 access_data adata2 (m_ptr_qry.rvals, stmt, access_read_only, NULL_TREE, false,
2588 bound, true);
81d6cdd3
MS
2589
2590 /* Determine the range of the bound first and bail if it fails; it's
2591 cheaper than computing the size of the objects. */
2592 tree bndrng[2] = { NULL_TREE, NULL_TREE };
9a27acc3 2593 get_size_range (m_ptr_qry.rvals, bound, stmt, bndrng, adata1.src.bndrng);
81d6cdd3
MS
2594 if (!bndrng[0] || integer_zerop (bndrng[0]))
2595 return;
2596
2597 if (len1 && tree_int_cst_lt (len1, bndrng[0]))
2598 bndrng[0] = len1;
2599 if (len2 && tree_int_cst_lt (len2, bndrng[0]))
2600 bndrng[0] = len2;
2601
2602 /* compute_objsize almost never fails (and ultimately should never
2603 fail). Don't bother to handle the rare case when it does. */
9a27acc3
MS
2604 if (!compute_objsize (arg1, stmt, 1, &adata1.src, &m_ptr_qry)
2605 || !compute_objsize (arg2, stmt, 1, &adata2.src, &m_ptr_qry))
81d6cdd3
MS
2606 return;
2607
2608 /* Compute the size of the remaining space in each array after
2609 subtracting any offset into it. */
2610 offset_int rem1 = adata1.src.size_remaining ();
2611 offset_int rem2 = adata2.src.size_remaining ();
2612
2613 /* Cap REM1 and REM2 at the other if the other's argument is known
2614 to be an unterminated array, either because there's no space
2615 left in it after adding its offset or because it's constant and
2616 has no nul. */
2617 if (rem1 == 0 || (rem1 < rem2 && lendata1.decl))
2618 rem2 = rem1;
2619 else if (rem2 == 0 || (rem2 < rem1 && lendata2.decl))
2620 rem1 = rem2;
2621
2622 /* Point PAD at the array to reference in the note if a warning
2623 is issued. */
2624 access_data *pad = len1 ? &adata2 : &adata1;
2625 offset_int maxrem = wi::max (rem1, rem2, UNSIGNED);
2626 if (lendata1.decl || lendata2.decl
2627 || maxrem < wi::to_offset (bndrng[0]))
2628 {
2629 /* Warn when either argument isn't nul-terminated or the maximum
2630 remaining space in the two arrays is less than the bound. */
2631 tree func = get_callee_fndecl (stmt);
2632 location_t loc = gimple_location (stmt);
2633 maybe_warn_for_bound (OPT_Wstringop_overread, loc, stmt, func,
2634 bndrng, wide_int_to_tree (sizetype, maxrem),
2635 pad);
2636 }
2637}
2638
ece28da9
MS
2639/* Determine and check the sizes of the source and the destination
2640 of calls to __builtin_{bzero,memcpy,mempcpy,memset} calls. STMT is
2641 the call statement, DEST is the destination argument, SRC is the source
2642 argument or null, and SIZE is the number of bytes being accessed. Use
2643 Object Size type-0 regardless of the OPT_Wstringop_overflow_ setting.
2644 Return true on success (no overflow or invalid sizes), false otherwise. */
2645
2646void
2647pass_waccess::check_memop_access (gimple *stmt, tree dest, tree src, tree size)
2648{
2649 /* For functions like memset and memcpy that operate on raw memory
2650 try to determine the size of the largest source and destination
2651 object using type-0 Object Size regardless of the object size
2652 type specified by the option. */
9a27acc3 2653 access_data data (m_ptr_qry.rvals, stmt, access_read_write);
ece28da9 2654 tree srcsize
9a27acc3
MS
2655 = src ? compute_objsize (src, stmt, 0, &data.src, &m_ptr_qry) : NULL_TREE;
2656 tree dstsize = compute_objsize (dest, stmt, 0, &data.dst, &m_ptr_qry);
2657
2658 check_access (stmt, size, /*maxread=*/NULL_TREE, srcsize, dstsize,
2659 data.mode, &data, m_ptr_qry.rvals);
2660}
2661
2662/* A convenience wrapper for check_access to check access by a read-only
2663 function like puts or strcmp. */
2664
2665void
2666pass_waccess::check_read_access (gimple *stmt, tree src,
2667 tree bound /* = NULL_TREE */,
2668 int ost /* = 1 */)
2669{
2670 if (!warn_stringop_overread)
2671 return;
2672
2673 if (bound && !useless_type_conversion_p (size_type_node, TREE_TYPE (bound)))
2674 bound = fold_convert (size_type_node, bound);
2675
2676 tree fndecl = get_callee_fndecl (stmt);
2677 maybe_warn_nonstring_arg (fndecl, stmt);
ece28da9 2678
9a27acc3
MS
2679 access_data data (m_ptr_qry.rvals, stmt, access_read_only, NULL_TREE,
2680 false, bound, true);
2681 compute_objsize (src, stmt, ost, &data.src, &m_ptr_qry);
2682 check_access (stmt, /*dstwrite=*/ NULL_TREE, /*maxread=*/ bound,
2683 /*srcstr=*/ src, /*dstsize=*/ NULL_TREE, data.mode,
2684 &data, m_ptr_qry.rvals);
ece28da9
MS
2685}
2686
9a27acc3 2687
88b504b7
MS
2688/* Check a call STMT to an atomic or sync built-in. */
2689
2690bool
2691pass_waccess::check_atomic_builtin (gcall *stmt)
2692{
2693 tree callee = gimple_call_fndecl (stmt);
2694 if (!callee)
2695 return false;
2696
2697 /* The size in bytes of the access by the function, and the number
2698 of the second argument to check (if any). */
2699 unsigned bytes = 0, arg2 = UINT_MAX;
2700
2701 switch (DECL_FUNCTION_CODE (callee))
2702 {
2703#define BUILTIN_ACCESS_SIZE_FNSPEC(N) \
2704 BUILT_IN_ATOMIC_LOAD_ ## N: \
2705 case BUILT_IN_SYNC_FETCH_AND_ADD_ ## N: \
2706 case BUILT_IN_SYNC_FETCH_AND_SUB_ ## N: \
2707 case BUILT_IN_SYNC_FETCH_AND_OR_ ## N: \
2708 case BUILT_IN_SYNC_FETCH_AND_AND_ ## N: \
2709 case BUILT_IN_SYNC_FETCH_AND_XOR_ ## N: \
2710 case BUILT_IN_SYNC_FETCH_AND_NAND_ ## N: \
2711 case BUILT_IN_SYNC_ADD_AND_FETCH_ ## N: \
2712 case BUILT_IN_SYNC_SUB_AND_FETCH_ ## N: \
2713 case BUILT_IN_SYNC_OR_AND_FETCH_ ## N: \
2714 case BUILT_IN_SYNC_AND_AND_FETCH_ ## N: \
2715 case BUILT_IN_SYNC_XOR_AND_FETCH_ ## N: \
2716 case BUILT_IN_SYNC_NAND_AND_FETCH_ ## N: \
2717 case BUILT_IN_SYNC_LOCK_TEST_AND_SET_ ## N: \
2718 case BUILT_IN_SYNC_BOOL_COMPARE_AND_SWAP_ ## N: \
2719 case BUILT_IN_SYNC_VAL_COMPARE_AND_SWAP_ ## N: \
2720 case BUILT_IN_SYNC_LOCK_RELEASE_ ## N: \
2721 case BUILT_IN_ATOMIC_EXCHANGE_ ## N: \
2722 case BUILT_IN_ATOMIC_STORE_ ## N: \
2723 case BUILT_IN_ATOMIC_ADD_FETCH_ ## N: \
2724 case BUILT_IN_ATOMIC_SUB_FETCH_ ## N: \
2725 case BUILT_IN_ATOMIC_AND_FETCH_ ## N: \
2726 case BUILT_IN_ATOMIC_NAND_FETCH_ ## N: \
2727 case BUILT_IN_ATOMIC_XOR_FETCH_ ## N: \
2728 case BUILT_IN_ATOMIC_OR_FETCH_ ## N: \
2729 case BUILT_IN_ATOMIC_FETCH_ADD_ ## N: \
2730 case BUILT_IN_ATOMIC_FETCH_SUB_ ## N: \
2731 case BUILT_IN_ATOMIC_FETCH_AND_ ## N: \
2732 case BUILT_IN_ATOMIC_FETCH_NAND_ ## N: \
2733 case BUILT_IN_ATOMIC_FETCH_OR_ ## N: \
2734 case BUILT_IN_ATOMIC_FETCH_XOR_ ## N: \
2735 bytes = N; \
2736 break; \
2737 case BUILT_IN_ATOMIC_COMPARE_EXCHANGE_ ## N: \
2738 bytes = N; \
2739 arg2 = 1
2740
2741 case BUILTIN_ACCESS_SIZE_FNSPEC (1);
2742 break;
2743 case BUILTIN_ACCESS_SIZE_FNSPEC (2);
2744 break;
2745 case BUILTIN_ACCESS_SIZE_FNSPEC (4);
2746 break;
2747 case BUILTIN_ACCESS_SIZE_FNSPEC (8);
2748 break;
2749 case BUILTIN_ACCESS_SIZE_FNSPEC (16);
2750 break;
2751
2752 default:
2753 return false;
2754 }
2755
2756 tree size = build_int_cstu (sizetype, bytes);
2757 tree dst = gimple_call_arg (stmt, 0);
2758 check_memop_access (stmt, dst, NULL_TREE, size);
2759
2760 if (arg2 != UINT_MAX)
2761 {
2762 tree dst = gimple_call_arg (stmt, arg2);
2763 check_memop_access (stmt, dst, NULL_TREE, size);
2764 }
2765
2766 return true;
2767}
2768
81d6cdd3
MS
2769/* Check call STMT to a built-in function for invalid accesses. Return
2770 true if a call has been handled. */
2771
2772bool
2773pass_waccess::check_builtin (gcall *stmt)
2774{
2775 tree callee = gimple_call_fndecl (stmt);
2776 if (!callee)
2777 return false;
2778
2779 switch (DECL_FUNCTION_CODE (callee))
2780 {
b48d4e68
MS
2781 case BUILT_IN_ALLOCA:
2782 case BUILT_IN_ALLOCA_WITH_ALIGN:
2783 case BUILT_IN_ALLOCA_WITH_ALIGN_AND_MAX:
2784 check_alloca (stmt);
2785 return true;
2786
9a27acc3
MS
2787 case BUILT_IN_EXECL:
2788 case BUILT_IN_EXECLE:
2789 case BUILT_IN_EXECLP:
2790 case BUILT_IN_EXECV:
2791 case BUILT_IN_EXECVE:
2792 case BUILT_IN_EXECVP:
2793 check_read_access (stmt, call_arg (stmt, 0));
2794 return true;
2795
81d6cdd3
MS
2796 case BUILT_IN_GETTEXT:
2797 case BUILT_IN_PUTS:
2798 case BUILT_IN_PUTS_UNLOCKED:
2799 case BUILT_IN_STRDUP:
2800 check_read_access (stmt, call_arg (stmt, 0));
2801 return true;
2802
2803 case BUILT_IN_INDEX:
2804 case BUILT_IN_RINDEX:
2805 case BUILT_IN_STRCHR:
2806 case BUILT_IN_STRRCHR:
2807 case BUILT_IN_STRLEN:
2808 check_read_access (stmt, call_arg (stmt, 0));
2809 return true;
2810
2811 case BUILT_IN_FPUTS:
2812 case BUILT_IN_FPUTS_UNLOCKED:
2813 check_read_access (stmt, call_arg (stmt, 0));
2814 return true;
2815
2816 case BUILT_IN_STRNDUP:
2817 case BUILT_IN_STRNLEN:
9a27acc3
MS
2818 {
2819 tree str = call_arg (stmt, 0);
2820 tree len = call_arg (stmt, 1);
2821 check_read_access (stmt, str, len);
2822 return true;
2823 }
81d6cdd3
MS
2824
2825 case BUILT_IN_STRCAT:
2826 check_strcat (stmt);
2827 return true;
2828
2829 case BUILT_IN_STRNCAT:
2830 check_strncat (stmt);
2831 return true;
2832
2833 case BUILT_IN_STPCPY:
2834 case BUILT_IN_STRCPY:
2835 check_stxcpy (stmt);
2836 return true;
2837
2838 case BUILT_IN_STPNCPY:
2839 case BUILT_IN_STRNCPY:
2840 check_stxncpy (stmt);
2841 return true;
2842
2843 case BUILT_IN_STRCASECMP:
2844 case BUILT_IN_STRCMP:
2845 case BUILT_IN_STRPBRK:
2846 case BUILT_IN_STRSPN:
2847 case BUILT_IN_STRCSPN:
2848 case BUILT_IN_STRSTR:
2849 check_read_access (stmt, call_arg (stmt, 0));
2850 check_read_access (stmt, call_arg (stmt, 1));
2851 return true;
2852
2853 case BUILT_IN_STRNCASECMP:
2854 case BUILT_IN_STRNCMP:
2855 check_strncmp (stmt);
2856 return true;
2857
2858 case BUILT_IN_MEMCMP:
2859 {
2860 tree a1 = call_arg (stmt, 0);
2861 tree a2 = call_arg (stmt, 1);
2862 tree len = call_arg (stmt, 2);
2863 check_read_access (stmt, a1, len, 0);
2864 check_read_access (stmt, a2, len, 0);
2865 return true;
2866 }
2867
2868 case BUILT_IN_MEMCPY:
2869 case BUILT_IN_MEMPCPY:
2870 case BUILT_IN_MEMMOVE:
2871 {
2872 tree dst = call_arg (stmt, 0);
2873 tree src = call_arg (stmt, 1);
2874 tree len = call_arg (stmt, 2);
2875 check_memop_access (stmt, dst, src, len);
2876 return true;
2877 }
2878
2879 case BUILT_IN_MEMCHR:
2880 {
2881 tree src = call_arg (stmt, 0);
2882 tree len = call_arg (stmt, 2);
2883 check_read_access (stmt, src, len, 0);
2884 return true;
2885 }
2886
2887 case BUILT_IN_MEMSET:
2888 {
2889 tree dst = call_arg (stmt, 0);
2890 tree len = call_arg (stmt, 2);
2891 check_memop_access (stmt, dst, NULL_TREE, len);
2892 return true;
2893 }
2894
2895 default:
88b504b7
MS
2896 if (check_atomic_builtin (stmt))
2897 return true;
2898 break;
81d6cdd3 2899 }
88b504b7 2900 return false;
81d6cdd3
MS
2901}
2902
b48d4e68
MS
2903/* Returns the type of the argument ARGNO to function with type FNTYPE
2904 or null when the typoe cannot be determined or no such argument exists. */
2905
2906static tree
2907fntype_argno_type (tree fntype, unsigned argno)
2908{
2909 if (!prototype_p (fntype))
2910 return NULL_TREE;
2911
2912 tree argtype;
2913 function_args_iterator it;
2914 FOREACH_FUNCTION_ARGS (fntype, argtype, it)
2915 if (argno-- == 0)
2916 return argtype;
2917
2918 return NULL_TREE;
2919}
2920
2921/* Helper to append the "human readable" attribute access specification
2922 described by ACCESS to the array ATTRSTR with size STRSIZE. Used in
2923 diagnostics. */
2924
2925static inline void
2926append_attrname (const std::pair<int, attr_access> &access,
2927 char *attrstr, size_t strsize)
2928{
2929 if (access.second.internal_p)
2930 return;
2931
2932 tree str = access.second.to_external_string ();
2933 gcc_assert (strsize >= (size_t) TREE_STRING_LENGTH (str));
2934 strcpy (attrstr, TREE_STRING_POINTER (str));
2935}
2936
2937/* Iterate over attribute access read-only, read-write, and write-only
2938 arguments and diagnose past-the-end accesses and related problems
2939 in the function call EXP. */
2940
ece28da9
MS
2941void
2942pass_waccess::maybe_check_access_sizes (rdwr_map *rwm, tree fndecl, tree fntype,
2943 gimple *stmt)
b48d4e68
MS
2944{
2945 auto_diagnostic_group adg;
2946
2947 /* Set if a warning has been issued for any argument (used to decide
2948 whether to emit an informational note at the end). */
2949 opt_code opt_warned = no_warning;
2950
2951 /* A string describing the attributes that the warnings issued by this
2952 function apply to. Used to print one informational note per function
2953 call, rather than one per warning. That reduces clutter. */
2954 char attrstr[80];
2955 attrstr[0] = 0;
2956
2957 for (rdwr_map::iterator it = rwm->begin (); it != rwm->end (); ++it)
2958 {
2959 std::pair<int, attr_access> access = *it;
2960
2961 /* Get the function call arguments corresponding to the attribute's
2962 positional arguments. When both arguments have been specified
2963 there will be two entries in *RWM, one for each. They are
2964 cross-referenced by their respective argument numbers in
2965 ACCESS.PTRARG and ACCESS.SIZARG. */
2966 const int ptridx = access.second.ptrarg;
2967 const int sizidx = access.second.sizarg;
2968
2969 gcc_assert (ptridx != -1);
2970 gcc_assert (access.first == ptridx || access.first == sizidx);
2971
2972 /* The pointer is set to null for the entry corresponding to
2973 the size argument. Skip it. It's handled when the entry
2974 corresponding to the pointer argument comes up. */
2975 if (!access.second.ptr)
2976 continue;
2977
2978 tree ptrtype = fntype_argno_type (fntype, ptridx);
2979 tree argtype = TREE_TYPE (ptrtype);
2980
2981 /* The size of the access by the call. */
2982 tree access_size;
2983 if (sizidx == -1)
2984 {
2985 /* If only the pointer attribute operand was specified and
2986 not size, set SIZE to the greater of MINSIZE or size of
2987 one element of the pointed to type to detect smaller
2988 objects (null pointers are diagnosed in this case only
2989 if the pointer is also declared with attribute nonnull. */
2990 if (access.second.minsize
2991 && access.second.minsize != HOST_WIDE_INT_M1U)
2992 access_size = build_int_cstu (sizetype, access.second.minsize);
2993 else
2994 access_size = size_one_node;
2995 }
2996 else
2997 access_size = rwm->get (sizidx)->size;
2998
2999 /* Format the value or range to avoid an explosion of messages. */
3000 char sizstr[80];
3001 tree sizrng[2] = { size_zero_node, build_all_ones_cst (sizetype) };
9a27acc3 3002 if (get_size_range (m_ptr_qry.rvals, access_size, stmt, sizrng, 1))
b48d4e68
MS
3003 {
3004 char *s0 = print_generic_expr_to_str (sizrng[0]);
3005 if (tree_int_cst_equal (sizrng[0], sizrng[1]))
3006 {
3007 gcc_checking_assert (strlen (s0) < sizeof sizstr);
3008 strcpy (sizstr, s0);
3009 }
3010 else
3011 {
3012 char *s1 = print_generic_expr_to_str (sizrng[1]);
3013 gcc_checking_assert (strlen (s0) + strlen (s1)
3014 < sizeof sizstr - 4);
3015 sprintf (sizstr, "[%s, %s]", s0, s1);
3016 free (s1);
3017 }
3018 free (s0);
3019 }
3020 else
3021 *sizstr = '\0';
3022
3023 /* Set if a warning has been issued for the current argument. */
3024 opt_code arg_warned = no_warning;
3025 location_t loc = get_location (stmt);
3026 tree ptr = access.second.ptr;
3027 if (*sizstr
3028 && tree_int_cst_sgn (sizrng[0]) < 0
3029 && tree_int_cst_sgn (sizrng[1]) < 0)
3030 {
3031 /* Warn about negative sizes. */
3032 if (access.second.internal_p)
3033 {
3034 const std::string argtypestr
3035 = access.second.array_as_string (ptrtype);
3036
3037 if (warning_at (loc, OPT_Wstringop_overflow_,
3038 "bound argument %i value %s is "
3039 "negative for a variable length array "
3040 "argument %i of type %s",
3041 sizidx + 1, sizstr,
3042 ptridx + 1, argtypestr.c_str ()))
3043 arg_warned = OPT_Wstringop_overflow_;
3044 }
3045 else if (warning_at (loc, OPT_Wstringop_overflow_,
3046 "argument %i value %s is negative",
3047 sizidx + 1, sizstr))
3048 arg_warned = OPT_Wstringop_overflow_;
3049
3050 if (arg_warned != no_warning)
3051 {
3052 append_attrname (access, attrstr, sizeof attrstr);
3053 /* Remember a warning has been issued and avoid warning
3054 again below for the same attribute. */
3055 opt_warned = arg_warned;
3056 continue;
3057 }
3058 }
3059
3060 if (tree_int_cst_sgn (sizrng[0]) >= 0)
3061 {
3062 if (COMPLETE_TYPE_P (argtype))
3063 {
3064 /* Multiply ACCESS_SIZE by the size of the type the pointer
3065 argument points to. If it's incomplete the size is used
3066 as is. */
3067 if (tree argsize = TYPE_SIZE_UNIT (argtype))
3068 if (TREE_CODE (argsize) == INTEGER_CST)
3069 {
3070 const int prec = TYPE_PRECISION (sizetype);
3071 wide_int minsize = wi::to_wide (sizrng[0], prec);
3072 minsize *= wi::to_wide (argsize, prec);
3073 access_size = wide_int_to_tree (sizetype, minsize);
3074 }
3075 }
3076 }
3077 else
3078 access_size = NULL_TREE;
3079
3080 if (integer_zerop (ptr))
3081 {
3082 if (sizidx >= 0 && tree_int_cst_sgn (sizrng[0]) > 0)
3083 {
3084 /* Warn about null pointers with positive sizes. This is
3085 different from also declaring the pointer argument with
3086 attribute nonnull when the function accepts null pointers
3087 only when the corresponding size is zero. */
3088 if (access.second.internal_p)
3089 {
3090 const std::string argtypestr
3091 = access.second.array_as_string (ptrtype);
3092
3093 if (warning_at (loc, OPT_Wnonnull,
3094 "argument %i of variable length "
3095 "array %s is null but "
3096 "the corresponding bound argument "
3097 "%i value is %s",
3098 ptridx + 1, argtypestr.c_str (),
3099 sizidx + 1, sizstr))
3100 arg_warned = OPT_Wnonnull;
3101 }
3102 else if (warning_at (loc, OPT_Wnonnull,
3103 "argument %i is null but "
3104 "the corresponding size argument "
3105 "%i value is %s",
3106 ptridx + 1, sizidx + 1, sizstr))
3107 arg_warned = OPT_Wnonnull;
3108 }
3109 else if (access_size && access.second.static_p)
3110 {
3111 /* Warn about null pointers for [static N] array arguments
3112 but do not warn for ordinary (i.e., nonstatic) arrays. */
3113 if (warning_at (loc, OPT_Wnonnull,
3114 "argument %i to %<%T[static %E]%> "
3115 "is null where non-null expected",
3116 ptridx + 1, argtype, access_size))
3117 arg_warned = OPT_Wnonnull;
3118 }
3119
3120 if (arg_warned != no_warning)
3121 {
3122 append_attrname (access, attrstr, sizeof attrstr);
3123 /* Remember a warning has been issued and avoid warning
3124 again below for the same attribute. */
3125 opt_warned = OPT_Wnonnull;
3126 continue;
3127 }
3128 }
3129
9a27acc3
MS
3130 access_data data (m_ptr_qry.rvals, stmt, access.second.mode,
3131 NULL_TREE, false, NULL_TREE, false);
b48d4e68
MS
3132 access_ref* const pobj = (access.second.mode == access_write_only
3133 ? &data.dst : &data.src);
9a27acc3 3134 tree objsize = compute_objsize (ptr, stmt, 1, pobj, &m_ptr_qry);
b48d4e68
MS
3135
3136 /* The size of the destination or source object. */
3137 tree dstsize = NULL_TREE, srcsize = NULL_TREE;
3138 if (access.second.mode == access_read_only
3139 || access.second.mode == access_none)
3140 {
3141 /* For a read-only argument there is no destination. For
3142 no access, set the source as well and differentiate via
3143 the access flag below. */
3144 srcsize = objsize;
3145 if (access.second.mode == access_read_only
3146 || access.second.mode == access_none)
3147 {
3148 /* For a read-only attribute there is no destination so
3149 clear OBJSIZE. This emits "reading N bytes" kind of
3150 diagnostics instead of the "writing N bytes" kind,
3151 unless MODE is none. */
3152 objsize = NULL_TREE;
3153 }
3154 }
3155 else
3156 dstsize = objsize;
3157
3158 /* Clear the no-warning bit in case it was set by check_access
3159 in a prior iteration so that accesses via different arguments
3160 are diagnosed. */
3161 suppress_warning (stmt, OPT_Wstringop_overflow_, false);
3162 access_mode mode = data.mode;
3163 if (mode == access_deferred)
3164 mode = TYPE_READONLY (argtype) ? access_read_only : access_read_write;
3165 check_access (stmt, access_size, /*maxread=*/ NULL_TREE, srcsize,
9a27acc3 3166 dstsize, mode, &data, m_ptr_qry.rvals);
b48d4e68
MS
3167
3168 if (warning_suppressed_p (stmt, OPT_Wstringop_overflow_))
3169 opt_warned = OPT_Wstringop_overflow_;
3170 if (opt_warned != no_warning)
3171 {
3172 if (access.second.internal_p)
3173 inform (loc, "referencing argument %u of type %qT",
3174 ptridx + 1, ptrtype);
3175 else
3176 /* If check_access issued a warning above, append the relevant
3177 attribute to the string. */
3178 append_attrname (access, attrstr, sizeof attrstr);
3179 }
3180 }
3181
3182 if (*attrstr)
3183 {
3184 if (fndecl)
3185 inform (get_location (fndecl),
3186 "in a call to function %qD declared with attribute %qs",
3187 fndecl, attrstr);
3188 else
3189 inform (get_location (stmt),
3190 "in a call with type %qT and attribute %qs",
3191 fntype, attrstr);
3192 }
3193 else if (opt_warned != no_warning)
3194 {
3195 if (fndecl)
3196 inform (get_location (fndecl),
3197 "in a call to function %qD", fndecl);
3198 else
3199 inform (get_location (stmt),
3200 "in a call with type %qT", fntype);
3201 }
3202
3203 /* Set the bit in case if was cleared and not set above. */
3204 if (opt_warned != no_warning)
3205 suppress_warning (stmt, opt_warned);
3206}
3207
3208/* Check call STMT to an ordinary (non-built-in) function for invalid
3209 accesses. Return true if a call has been handled. */
3210
3211bool
3212pass_waccess::check_call (gcall *stmt)
3213{
3214 tree fntype = gimple_call_fntype (stmt);
3215 if (!fntype)
3216 return false;
3217
3218 tree fntypeattrs = TYPE_ATTRIBUTES (fntype);
3219 if (!fntypeattrs)
3220 return false;
3221
3222 /* Map of attribute accewss specifications for function arguments. */
3223 rdwr_map rdwr_idx;
3224 init_attr_rdwr_indices (&rdwr_idx, fntypeattrs);
3225
3226 unsigned nargs = call_nargs (stmt);
3227 for (unsigned i = 0; i != nargs; ++i)
3228 {
3229 tree arg = call_arg (stmt, i);
3230
3231 /* Save the actual argument that corresponds to the access attribute
3232 operand for later processing. */
3233 if (attr_access *access = rdwr_idx.get (i))
3234 {
3235 if (POINTER_TYPE_P (TREE_TYPE (arg)))
3236 {
3237 access->ptr = arg;
3238 // A nonnull ACCESS->SIZE contains VLA bounds. */
3239 }
3240 else
3241 {
3242 access->size = arg;
3243 gcc_assert (access->ptr == NULL_TREE);
3244 }
3245 }
3246 }
3247
3248 /* Check attribute access arguments. */
3249 tree fndecl = gimple_call_fndecl (stmt);
ece28da9 3250 maybe_check_access_sizes (&rdwr_idx, fndecl, fntype, stmt);
b48d4e68
MS
3251
3252 check_alloc_size_call (stmt);
3253 return true;
3254}
3255
3256/* Check arguments in a call STMT for attribute nonstring. */
3257
3258static void
3259check_nonstring_args (gcall *stmt)
3260{
3261 tree fndecl = gimple_call_fndecl (stmt);
3262
3263 /* Detect passing non-string arguments to functions expecting
3264 nul-terminated strings. */
3265 maybe_warn_nonstring_arg (fndecl, stmt);
3266}
3267
ece28da9
MS
3268/* Issue a warning if a deallocation function such as free, realloc,
3269 or C++ operator delete is called with an argument not returned by
3270 a matching allocation function such as malloc or the corresponding
3271 form of C++ operatorn new. */
3272
3273void
3274pass_waccess::maybe_check_dealloc_call (gcall *call)
3275{
3276 tree fndecl = gimple_call_fndecl (call);
3277 if (!fndecl)
3278 return;
3279
3280 unsigned argno = fndecl_dealloc_argno (fndecl);
3281 if ((unsigned) call_nargs (call) <= argno)
3282 return;
3283
3284 tree ptr = gimple_call_arg (call, argno);
3285 if (integer_zerop (ptr))
3286 return;
3287
3288 access_ref aref;
9a27acc3 3289 if (!compute_objsize (ptr, call, 0, &aref, &m_ptr_qry))
ece28da9
MS
3290 return;
3291
3292 tree ref = aref.ref;
3293 if (integer_zerop (ref))
3294 return;
3295
3296 tree dealloc_decl = fndecl;
3297 location_t loc = gimple_location (call);
3298
3299 if (DECL_P (ref) || EXPR_P (ref))
3300 {
3301 /* Diagnose freeing a declared object. */
3302 if (aref.ref_declared ()
3303 && warning_at (loc, OPT_Wfree_nonheap_object,
3304 "%qD called on unallocated object %qD",
3305 dealloc_decl, ref))
3306 {
3307 inform (get_location (ref), "declared here");
3308 return;
3309 }
3310
3311 /* Diagnose freeing a pointer that includes a positive offset.
3312 Such a pointer cannot refer to the beginning of an allocated
3313 object. A negative offset may refer to it. */
3314 if (aref.sizrng[0] != aref.sizrng[1]
3315 && warn_dealloc_offset (loc, call, aref))
3316 return;
3317 }
3318 else if (CONSTANT_CLASS_P (ref))
3319 {
3320 if (warning_at (loc, OPT_Wfree_nonheap_object,
3321 "%qD called on a pointer to an unallocated "
3322 "object %qE", dealloc_decl, ref))
3323 {
3324 if (TREE_CODE (ptr) == SSA_NAME)
3325 {
3326 gimple *def_stmt = SSA_NAME_DEF_STMT (ptr);
3327 if (is_gimple_assign (def_stmt))
3328 {
3329 location_t loc = gimple_location (def_stmt);
3330 inform (loc, "assigned here");
3331 }
3332 }
3333 return;
3334 }
3335 }
3336 else if (TREE_CODE (ref) == SSA_NAME)
3337 {
3338 /* Also warn if the pointer argument refers to the result
3339 of an allocation call like alloca or VLA. */
3340 gimple *def_stmt = SSA_NAME_DEF_STMT (ref);
3341 if (!def_stmt)
3342 return;
3343
3344 if (is_gimple_call (def_stmt))
3345 {
3346 bool warned = false;
3347 if (gimple_call_alloc_p (def_stmt))
3348 {
3349 if (matching_alloc_calls_p (def_stmt, dealloc_decl))
3350 {
3351 if (warn_dealloc_offset (loc, call, aref))
3352 return;
3353 }
3354 else
3355 {
3356 tree alloc_decl = gimple_call_fndecl (def_stmt);
3357 const opt_code opt =
3358 (DECL_IS_OPERATOR_NEW_P (alloc_decl)
3359 || DECL_IS_OPERATOR_DELETE_P (dealloc_decl)
3360 ? OPT_Wmismatched_new_delete
3361 : OPT_Wmismatched_dealloc);
3362 warned = warning_at (loc, opt,
3363 "%qD called on pointer returned "
3364 "from a mismatched allocation "
3365 "function", dealloc_decl);
3366 }
3367 }
3368 else if (gimple_call_builtin_p (def_stmt, BUILT_IN_ALLOCA)
3369 || gimple_call_builtin_p (def_stmt,
3370 BUILT_IN_ALLOCA_WITH_ALIGN))
3371 warned = warning_at (loc, OPT_Wfree_nonheap_object,
3372 "%qD called on pointer to "
3373 "an unallocated object",
3374 dealloc_decl);
3375 else if (warn_dealloc_offset (loc, call, aref))
3376 return;
3377
3378 if (warned)
3379 {
3380 tree fndecl = gimple_call_fndecl (def_stmt);
3381 inform (gimple_location (def_stmt),
3382 "returned from %qD", fndecl);
3383 return;
3384 }
3385 }
3386 else if (gimple_nop_p (def_stmt))
3387 {
3388 ref = SSA_NAME_VAR (ref);
3389 /* Diagnose freeing a pointer that includes a positive offset. */
3390 if (TREE_CODE (ref) == PARM_DECL
3391 && !aref.deref
3392 && aref.sizrng[0] != aref.sizrng[1]
3393 && aref.offrng[0] > 0 && aref.offrng[1] > 0
3394 && warn_dealloc_offset (loc, call, aref))
3395 return;
3396 }
3397 }
3398}
3399
2a837de2
MS
3400/* Check call STMT for invalid accesses. */
3401
3402void
3403pass_waccess::check (gcall *stmt)
3404{
b48d4e68
MS
3405 if (gimple_call_builtin_p (stmt, BUILT_IN_NORMAL))
3406 check_builtin (stmt);
81d6cdd3 3407
b48d4e68
MS
3408 if (is_gimple_call (stmt))
3409 check_call (stmt);
3410
3411 maybe_check_dealloc_call (stmt);
3412
3413 check_nonstring_args (stmt);
2a837de2
MS
3414}
3415
3416/* Check basic block BB for invalid accesses. */
3417
3418void
3419pass_waccess::check (basic_block bb)
3420{
3421 /* Iterate over statements, looking for function calls. */
3422 for (auto si = gsi_start_bb (bb); !gsi_end_p (si); gsi_next (&si))
3423 {
3424 if (gcall *call = dyn_cast <gcall *> (gsi_stmt (si)))
3425 check (call);
3426 }
3427}
3428
3429/* Check function FUN for invalid accesses. */
3430
3431unsigned
3432pass_waccess::execute (function *fun)
3433{
81501087 3434 /* Create a new ranger instance and associate it with FUN. */
ece28da9 3435 m_ptr_qry.rvals = enable_ranger (fun);
b48d4e68 3436
2a837de2
MS
3437 basic_block bb;
3438 FOR_EACH_BB_FN (bb, fun)
3439 check (bb);
3440
ece28da9
MS
3441 if (dump_file)
3442 m_ptr_qry.dump (dump_file, (dump_flags & TDF_DETAILS) != 0);
3443
3444 m_ptr_qry.flush_cache ();
3445
3446 /* Release the ranger instance and replace it with a global ranger.
3447 Also reset the pointer since calling disable_ranger() deletes it. */
81501087 3448 disable_ranger (fun);
ece28da9 3449 m_ptr_qry.rvals = NULL;
81501087 3450
2a837de2
MS
3451 return 0;
3452}
3453
3454} // namespace
3455
3456/* Return a new instance of the pass. */
3457
3458gimple_opt_pass *
3459make_pass_warn_access (gcc::context *ctxt)
3460{
3461 return new pass_waccess (ctxt);
3462}