Debian Codegraph @

gcc/analyzer/sm-malloc.cc

raw
1 /* A state machine for detecting misuses of the malloc/free API.
2 Copyright (C) 2019-2025 Free Software Foundation, Inc.
3 Contributed by David Malcolm <[email protected]>.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful, but
13 WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
20
21 #include "config.h"
22 #define INCLUDE_VECTOR
23 #include "system.h"
24 #include "coretypes.h"
25 #include "make-unique.h"
26 #include "tree.h"
27 #include "function.h"
28 #include "basic-block.h"
29 #include "gimple.h"
30 #include "options.h"
31 #include "bitmap.h"
32 #include "diagnostic-core.h"
33 #include "diagnostic-path.h"
34 #include "analyzer/analyzer.h"
35 #include "diagnostic-event-id.h"
36 #include "analyzer/analyzer-logging.h"
37 #include "analyzer/sm.h"
38 #include "analyzer/pending-diagnostic.h"
39 #include "analyzer/call-string.h"
40 #include "analyzer/program-point.h"
41 #include "analyzer/store.h"
42 #include "analyzer/region-model.h"
43 #include "analyzer/call-details.h"
44 #include "stringpool.h"
45 #include "attribs.h"
46 #include "analyzer/function-set.h"
47 #include "analyzer/program-state.h"
48 #include "analyzer/checker-event.h"
49 #include "analyzer/exploded-graph.h"
50 #include "analyzer/inlining-iterator.h"
51
52 #if ENABLE_ANALYZER
53
54 namespace ana {
55
56 namespace {
57
58 /* This state machine and its various support classes track allocations
59 and deallocations.
60
61 It has a few standard allocation/deallocation pairs (e.g. new/delete),
62 and also supports user-defined ones via
63 __attribute__ ((malloc(DEALLOCATOR))).
64
65 There can be more than one valid deallocator for a given allocator,
66 for example:
67 __attribute__ ((malloc (fclose)))
68 __attribute__ ((malloc (freopen, 3)))
69 FILE* fopen (const char*, const char*);
70 A deallocator_set represents a particular set of valid deallocators.
71
72 We track the expected deallocator_set for a value, but not the allocation
73 function - there could be more than one allocator per deallocator_set.
74 For example, there could be dozens of allocators for "free" beyond just
75 malloc e.g. calloc, xstrdup, etc. We don't want to explode the number
76 of states by tracking individual allocators in the exploded graph;
77 we merely want to track "this value expects to have 'free' called on it".
78 Perhaps we can reconstruct which allocator was used later, when emitting
79 the path, if it's necessary for precision of wording of diagnostics. */
80
81 class deallocator;
82 class deallocator_set;
83 class malloc_state_machine;
84
85 /* An enum for discriminating between different kinds of allocation_state. */
86
87 enum resource_state
88 {
89 /* States that are independent of allocator/deallocator. */
90
91 /* The start state. */
92 RS_START,
93
94 /* State for a pointer that's been unconditionally dereferenced. */
95 RS_ASSUMED_NON_NULL,
96
97 /* State for a pointer that's known to be NULL. */
98 RS_NULL,
99
100 /* State for a pointer that's known to not be on the heap (e.g. to a local
101 or global). */
102 RS_NON_HEAP,
103
104 /* Stop state, for pointers we don't want to track any more. */
105 RS_STOP,
106
107 /* States that relate to a specific deallocator_set. */
108
109 /* State for a pointer returned from an allocator that hasn't
110 been checked for NULL.
111 It could be a pointer to heap-allocated memory, or could be NULL. */
112 RS_UNCHECKED,
113
114 /* State for a pointer returned from an allocator,
115 known to be non-NULL. */
116 RS_NONNULL,
117
118 /* State for a pointer passed to a deallocator. */
119 RS_FREED
120 };
121
122 /* Custom state subclass, which can optionally refer to an a
123 deallocator_set. */
124
125 struct allocation_state : public state_machine::state
126 {
127 allocation_state (const char *name, unsigned id,
128 enum resource_state rs,
129 const deallocator_set *deallocators,
130 const deallocator *deallocator)
131 : state (name, id), m_rs (rs),
132 m_deallocators (deallocators),
133 m_deallocator (deallocator)
134 {}
135
136 void dump_to_pp (pretty_printer *pp) const override;
137
138 const allocation_state *get_nonnull () const;
139
140 enum resource_state m_rs;
141 const deallocator_set *m_deallocators;
142 const deallocator *m_deallocator;
143 };
144
145 /* Custom state subclass, for the "assumed-non-null" state
146 where the assumption happens in a particular frame. */
147
148 struct assumed_non_null_state : public allocation_state
149 {
150 assumed_non_null_state (const char *name, unsigned id,
151 const frame_region *frame)
152 : allocation_state (name, id, RS_ASSUMED_NON_NULL,
153 NULL, NULL),
154 m_frame (frame)
155 {
156 gcc_assert (m_frame);
157 }
158
159 void dump_to_pp (pretty_printer *pp) const final override;
160
161 const frame_region *m_frame;
162 };
163
164 /* An enum for choosing which wording to use in various diagnostics
165 when describing deallocations. */
166
167 enum wording
168 {
169 WORDING_FREED,
170 WORDING_DELETED,
171 WORDING_DEALLOCATED,
172 WORDING_REALLOCATED
173 };
174
175 /* Base class representing a deallocation function,
176 either a built-in one we know about, or one exposed via
177 __attribute__((malloc(DEALLOCATOR))). */
178
179 struct deallocator
180 {
181 hashval_t hash () const;
182 void dump_to_pp (pretty_printer *pp) const;
183 static int cmp (const deallocator *a, const deallocator *b);
184 static int cmp_ptr_ptr (const void *, const void *);
185
186 /* Name to use in diagnostics. */
187 const char *m_name;
188
189 /* Which wording to use in diagnostics. */
190 enum wording m_wording;
191
192 /* State for a value passed to one of the deallocators. */
193 state_machine::state_t m_freed;
194
195 protected:
196 deallocator (malloc_state_machine *sm,
197 const char *name,
198 enum wording wording);
199 };
200
201 /* Subclass representing a predefined deallocator.
202 e.g. "delete []", without needing a specific FUNCTION_DECL
203 ahead of time. */
204
205 struct standard_deallocator : public deallocator
206 {
207 standard_deallocator (malloc_state_machine *sm,
208 const char *name,
209 enum wording wording);
210 };
211
212 /* Subclass representing a user-defined deallocator
213 via __attribute__((malloc(DEALLOCATOR))) given
214 a specific FUNCTION_DECL. */
215
216 struct custom_deallocator : public deallocator
217 {
218 custom_deallocator (malloc_state_machine *sm,
219 tree deallocator_fndecl,
220 enum wording wording)
221 : deallocator (sm, IDENTIFIER_POINTER (DECL_NAME (deallocator_fndecl)),
222 wording)
223 {
224 }
225 };
226
227 /* Base class representing a set of possible deallocators.
228 Often this will be just a single deallocator, but some
229 allocators have multiple valid deallocators (e.g. the result of
230 "fopen" can be closed by either "fclose" or "freopen"). */
231
232 struct deallocator_set
233 {
234 deallocator_set (malloc_state_machine *sm,
235 enum wording wording);
236 virtual ~deallocator_set () {}
237
238 virtual bool contains_p (const deallocator *d) const = 0;
239 virtual const deallocator *maybe_get_single () const = 0;
240 virtual void dump_to_pp (pretty_printer *pp) const = 0;
241 void dump () const;
242
243 /* Which wording to use in diagnostics. */
244 enum wording m_wording;
245
246 /* Pointers to states.
247 These states are owned by the state_machine base class. */
248
249 /* State for an unchecked result from an allocator using this set. */
250 state_machine::state_t m_unchecked;
251
252 /* State for a known non-NULL result from such an allocator. */
253 state_machine::state_t m_nonnull;
254 };
255
256 /* Subclass of deallocator_set representing a set of deallocators
257 defined by one or more __attribute__((malloc(DEALLOCATOR))). */
258
259 struct custom_deallocator_set : public deallocator_set
260 {
261 typedef const auto_vec <const deallocator *> *key_t;
262
263 custom_deallocator_set (malloc_state_machine *sm,
264 const auto_vec <const deallocator *> *vec,
265 //const char *name,
266 //const char *dealloc_funcname,
267 //unsigned arg_idx,
268 enum wording wording);
269
270 bool contains_p (const deallocator *d) const final override;
271 const deallocator *maybe_get_single () const final override;
272 void dump_to_pp (pretty_printer *pp) const final override;
273
274 auto_vec <const deallocator *> m_deallocator_vec;
275 };
276
277 /* Subclass of deallocator_set representing a set of deallocators
278 with a single standard_deallocator, e.g. "delete []". */
279
280 struct standard_deallocator_set : public deallocator_set
281 {
282 standard_deallocator_set (malloc_state_machine *sm,
283 const char *name,
284 enum wording wording);
285
286 bool contains_p (const deallocator *d) const final override;
287 const deallocator *maybe_get_single () const final override;
288 void dump_to_pp (pretty_printer *pp) const final override;
289
290 standard_deallocator m_deallocator;
291 };
292
293 /* Traits class for ensuring uniqueness of deallocator_sets within
294 malloc_state_machine. */
295
296 struct deallocator_set_map_traits
297 {
298 typedef custom_deallocator_set::key_t key_type;
299 typedef custom_deallocator_set *value_type;
300 typedef custom_deallocator_set *compare_type;
301
302 static inline hashval_t hash (const key_type &k)
303 {
304 gcc_assert (k != NULL);
305 gcc_assert (k != reinterpret_cast<key_type> (1));
306
307 hashval_t result = 0;
308 unsigned i;
309 const deallocator *d;
310 FOR_EACH_VEC_ELT (*k, i, d)
311 result ^= d->hash ();
312 return result;
313 }
314 static inline bool equal_keys (const key_type &k1, const key_type &k2)
315 {
316 if (k1->length () != k2->length ())
317 return false;
318
319 for (unsigned i = 0; i < k1->length (); i++)
320 if ((*k1)[i] != (*k2)[i])
321 return false;
322
323 return true;
324 }
325 template <typename T>
326 static inline void remove (T &)
327 {
328 /* empty; the nodes are handled elsewhere. */
329 }
330 template <typename T>
331 static inline void mark_deleted (T &entry)
332 {
333 entry.m_key = reinterpret_cast<key_type> (1);
334 }
335 template <typename T>
336 static inline void mark_empty (T &entry)
337 {
338 entry.m_key = NULL;
339 }
340 template <typename T>
341 static inline bool is_deleted (const T &entry)
342 {
343 return entry.m_key == reinterpret_cast<key_type> (1);
344 }
345 template <typename T>
346 static inline bool is_empty (const T &entry)
347 {
348 return entry.m_key == NULL;
349 }
350 static const bool empty_zero_p = false;
351 };
352
353 /* A state machine for detecting misuses of the malloc/free API.
354
355 See sm-malloc.dot for an overview (keep this in-sync with that file). */
356
357 class malloc_state_machine : public state_machine
358 {
359 public:
360 typedef allocation_state custom_data_t;
361
362 malloc_state_machine (logger *logger);
363 ~malloc_state_machine ();
364
365 state_t
366 add_state (const char *name, enum resource_state rs,
367 const deallocator_set *deallocators,
368 const deallocator *deallocator);
369
370 bool inherited_state_p () const final override { return false; }
371
372 state_machine::state_t
373 get_default_state (const svalue *sval) const final override
374 {
375 if (tree cst = sval->maybe_get_constant ())
376 {
377 if (zerop (cst))
378 return m_null;
379 }
380 if (const region_svalue *ptr = sval->dyn_cast_region_svalue ())
381 {
382 const region *reg = ptr->get_pointee ();
383 switch (reg->get_memory_space ())
384 {
385 default:
386 break;
387 case MEMSPACE_CODE:
388 case MEMSPACE_GLOBALS:
389 case MEMSPACE_STACK:
390 case MEMSPACE_READONLY_DATA:
391 return m_non_heap;
392 }
393 }
394 return m_start;
395 }
396
397 bool on_stmt (sm_context &sm_ctxt,
398 const supernode *node,
399 const gimple *stmt) const final override;
400
401 void on_phi (sm_context &sm_ctxt,
402 const supernode *node,
403 const gphi *phi,
404 tree rhs) const final override;
405
406 void on_condition (sm_context &sm_ctxt,
407 const supernode *node,
408 const gimple *stmt,
409 const svalue *lhs,
410 enum tree_code op,
411 const svalue *rhs) const final override;
412
413 void on_pop_frame (sm_state_map *smap,
414 const frame_region *) const final override;
415
416 bool can_purge_p (state_t s) const final override;
417 std::unique_ptr<pending_diagnostic> on_leak (tree var) const final override;
418
419 bool reset_when_passed_to_unknown_fn_p (state_t s,
420 bool is_mutable) const final override;
421
422 state_t
423 maybe_get_merged_states_nonequal (state_t state_a,
424 state_t state_b) const final override;
425
426 static bool unaffected_by_call_p (tree fndecl);
427
428 void maybe_assume_non_null (sm_context &sm_ctxt,
429 tree ptr,
430 const gimple *stmt) const;
431
432 void on_realloc_with_move (region_model *model,
433 sm_state_map *smap,
434 const svalue *old_ptr_sval,
435 const svalue *new_ptr_sval,
436 const extrinsic_state &ext_state) const;
437
438 void transition_ptr_sval_non_null (region_model *model,
439 sm_state_map *smap,
440 const svalue *new_ptr_sval,
441 const extrinsic_state &ext_state) const;
442
443 standard_deallocator_set m_free;
444 standard_deallocator_set m_scalar_delete;
445 standard_deallocator_set m_vector_delete;
446
447 standard_deallocator m_realloc;
448
449 /* States that are independent of api. */
450
451 /* States for a pointer that's been unconditionally dereferenced
452 in a particular stack frame. */
453 hash_map<const frame_region *, state_t> m_assumed_non_null;
454
455 /* State for a pointer that's known to be NULL. */
456 state_t m_null;
457
458 /* State for a pointer that's known to not be on the heap (e.g. to a local
459 or global). */
460 state_t m_non_heap; // TODO: or should this be a different state machine?
461 // or do we need child values etc?
462
463 /* Stop state, for pointers we don't want to track any more. */
464 state_t m_stop;
465
466 private:
467 const custom_deallocator_set *
468 get_or_create_custom_deallocator_set (tree allocator_fndecl);
469 custom_deallocator_set *
470 maybe_create_custom_deallocator_set (tree allocator_fndecl);
471 const deallocator *
472 get_or_create_deallocator (tree deallocator_fndecl);
473
474 state_t
475 get_or_create_assumed_non_null_state_for_frame (const frame_region *frame);
476
477 void
478 maybe_complain_about_deref_before_check (sm_context &sm_ctxt,
479 const supernode *node,
480 const gimple *stmt,
481 const assumed_non_null_state *,
482 tree ptr) const;
483
484 void on_allocator_call (sm_context &sm_ctxt,
485 const gcall *call,
486 const deallocator_set *deallocators,
487 bool returns_nonnull = false) const;
488 void handle_free_of_non_heap (sm_context &sm_ctxt,
489 const supernode *node,
490 const gcall *call,
491 tree arg,
492 const deallocator *d) const;
493 void on_deallocator_call (sm_context &sm_ctxt,
494 const supernode *node,
495 const gcall *call,
496 const deallocator *d,
497 unsigned argno) const;
498 void on_realloc_call (sm_context &sm_ctxt,
499 const supernode *node,
500 const gcall *call) const;
501 void on_zero_assignment (sm_context &sm_ctxt,
502 const gimple *stmt,
503 tree lhs) const;
504 void handle_nonnull (sm_context &sm_ctx,
505 const supernode *node,
506 const gimple *stmt,
507 tree fndecl,
508 tree arg,
509 unsigned i) const;
510
511 /* A map for consolidating deallocators so that they are
512 unique per deallocator FUNCTION_DECL. */
513 typedef hash_map<tree, deallocator *> deallocator_map_t;
514 deallocator_map_t m_deallocator_map;
515
516 /* Memoized lookups from FUNCTION_DECL to custom_deallocator_set *. */
517 typedef hash_map<tree, custom_deallocator_set *> deallocator_set_cache_t;
518 deallocator_set_cache_t m_custom_deallocator_set_cache;
519
520 /* A map for consolidating custom_deallocator_set instances. */
521 typedef hash_map<custom_deallocator_set::key_t,
522 custom_deallocator_set *,
523 deallocator_set_map_traits> custom_deallocator_set_map_t;
524 custom_deallocator_set_map_t m_custom_deallocator_set_map;
525
526 /* Record of dynamically-allocated objects, for cleanup. */
527 auto_vec <custom_deallocator_set *> m_dynamic_sets;
528 auto_vec <custom_deallocator *> m_dynamic_deallocators;
529 };
530
531 /* struct deallocator. */
532
533 deallocator::deallocator (malloc_state_machine *sm,
534 const char *name,
535 enum wording wording)
536 : m_name (name),
537 m_wording (wording),
538 m_freed (sm->add_state ("freed", RS_FREED, NULL, this))
539 {
540 }
541
542 hashval_t
543 deallocator::hash () const
544 {
545 return (hashval_t)m_freed->get_id ();
546 }
547
548 void
549 deallocator::dump_to_pp (pretty_printer *pp) const
550 {
551 pp_printf (pp, "%qs", m_name);
552 }
553
554 int
555 deallocator::cmp (const deallocator *a, const deallocator *b)
556 {
557 return (int)a->m_freed->get_id () - (int)b->m_freed->get_id ();
558 }
559
560 int
561 deallocator::cmp_ptr_ptr (const void *a, const void *b)
562 {
563 return cmp (*(const deallocator * const *)a,
564 *(const deallocator * const *)b);
565 }
566
567
568 /* struct standard_deallocator : public deallocator. */
569
570 standard_deallocator::standard_deallocator (malloc_state_machine *sm,
571 const char *name,
572 enum wording wording)
573 : deallocator (sm, name, wording)
574 {
575 }
576
577 /* struct deallocator_set. */
578
579 deallocator_set::deallocator_set (malloc_state_machine *sm,
580 enum wording wording)
581 : m_wording (wording),
582 m_unchecked (sm->add_state ("unchecked", RS_UNCHECKED, this, NULL)),
583 m_nonnull (sm->add_state ("nonnull", RS_NONNULL, this, NULL))
584 {
585 }
586
587 /* Dump a description of this deallocator_set to stderr. */
588
589 DEBUG_FUNCTION void
590 deallocator_set::dump () const
591 {
592 tree_dump_pretty_printer pp (stderr);
593 dump_to_pp (&pp);
594 pp_newline (&pp);
595 }
596
597 /* struct custom_deallocator_set : public deallocator_set. */
598
599 custom_deallocator_set::
600 custom_deallocator_set (malloc_state_machine *sm,
601 const auto_vec <const deallocator *> *vec,
602 enum wording wording)
603 : deallocator_set (sm, wording),
604 m_deallocator_vec (vec->length ())
605 {
606 unsigned i;
607 const deallocator *d;
608 FOR_EACH_VEC_ELT (*vec, i, d)
609 m_deallocator_vec.safe_push (d);
610 }
611
612 bool
613 custom_deallocator_set::contains_p (const deallocator *d) const
614 {
615 unsigned i;
616 const deallocator *cd;
617 FOR_EACH_VEC_ELT (m_deallocator_vec, i, cd)
618 if (cd == d)
619 return true;
620 return false;
621 }
622
623 const deallocator *
624 custom_deallocator_set::maybe_get_single () const
625 {
626 if (m_deallocator_vec.length () == 1)
627 return m_deallocator_vec[0];
628 return NULL;
629 }
630
631 void
632 custom_deallocator_set::dump_to_pp (pretty_printer *pp) const
633 {
634 pp_character (pp, '{');
635 unsigned i;
636 const deallocator *d;
637 FOR_EACH_VEC_ELT (m_deallocator_vec, i, d)
638 {
639 if (i > 0)
640 pp_string (pp, ", ");
641 d->dump_to_pp (pp);
642 }
643 pp_character (pp, '}');
644 }
645
646 /* struct standard_deallocator_set : public deallocator_set. */
647
648 standard_deallocator_set::standard_deallocator_set (malloc_state_machine *sm,
649 const char *name,
650 enum wording wording)
651 : deallocator_set (sm, wording),
652 m_deallocator (sm, name, wording)
653 {
654 }
655
656 bool
657 standard_deallocator_set::contains_p (const deallocator *d) const
658 {
659 return d == &m_deallocator;
660 }
661
662 const deallocator *
663 standard_deallocator_set::maybe_get_single () const
664 {
665 return &m_deallocator;
666 }
667
668 void
669 standard_deallocator_set::dump_to_pp (pretty_printer *pp) const
670 {
671 pp_character (pp, '{');
672 pp_string (pp, m_deallocator.m_name);
673 pp_character (pp, '}');
674 }
675
676 /* Return STATE cast to the custom state subclass, or NULL for the start state.
677 Everything should be an allocation_state apart from the start state. */
678
679 static const allocation_state *
680 dyn_cast_allocation_state (state_machine::state_t state)
681 {
682 if (state->get_id () == 0)
683 return NULL;
684 return static_cast <const allocation_state *> (state);
685 }
686
687 /* Return STATE cast to the custom state subclass, for a state that is
688 already known to not be the start state . */
689
690 static const allocation_state *
691 as_a_allocation_state (state_machine::state_t state)
692 {
693 gcc_assert (state->get_id () != 0);
694 return static_cast <const allocation_state *> (state);
695 }
696
697 /* Get the resource_state for STATE. */
698
699 static enum resource_state
700 get_rs (state_machine::state_t state)
701 {
702 if (const allocation_state *astate = dyn_cast_allocation_state (state))
703 return astate->m_rs;
704 else
705 return RS_START;
706 }
707
708 /* Return true if STATE is the start state. */
709
710 static bool
711 start_p (state_machine::state_t state)
712 {
713 return get_rs (state) == RS_START;
714 }
715
716 /* Return true if STATE is an unchecked result from an allocator. */
717
718 static bool
719 unchecked_p (state_machine::state_t state)
720 {
721 return get_rs (state) == RS_UNCHECKED;
722 }
723
724 /* Return true if STATE is a non-null result from an allocator. */
725
726 static bool
727 nonnull_p (state_machine::state_t state)
728 {
729 return get_rs (state) == RS_NONNULL;
730 }
731
732 /* Return true if STATE is a value that has been passed to a deallocator. */
733
734 static bool
735 freed_p (state_machine::state_t state)
736 {
737 return get_rs (state) == RS_FREED;
738 }
739
740 /* Return true if STATE is a value that has been assumed to be non-NULL. */
741
742 static bool
743 assumed_non_null_p (state_machine::state_t state)
744 {
745 return get_rs (state) == RS_ASSUMED_NON_NULL;
746 }
747
748 /* Class for diagnostics relating to malloc_state_machine. */
749
750 class malloc_diagnostic : public pending_diagnostic
751 {
752 public:
753 malloc_diagnostic (const malloc_state_machine &sm, tree arg)
754 : m_sm (sm), m_arg (arg)
755 {}
756
757 bool subclass_equal_p (const pending_diagnostic &base_other) const override
758 {
759 return same_tree_p (m_arg, ((const malloc_diagnostic &)base_other).m_arg);
760 }
761
762 bool
763 describe_state_change (pretty_printer &pp,
764 const evdesc::state_change &change) override
765 {
766 if (change.m_old_state == m_sm.get_start_state ()
767 && (unchecked_p (change.m_new_state) || nonnull_p (change.m_new_state)))
768 // TODO: verify that it's the allocation stmt, not a copy
769 {
770 pp_string (&pp, "allocated here");
771 return true;
772 }
773 if (unchecked_p (change.m_old_state)
774 && nonnull_p (change.m_new_state))
775 {
776 if (change.m_expr)
777 pp_printf (&pp, "assuming %qE is non-NULL",
778 change.m_expr);
779 else
780 pp_printf (&pp, "assuming %qs is non-NULL",
781 "<unknown>");
782 return true;
783 }
784 if (change.m_new_state == m_sm.m_null)
785 {
786 if (unchecked_p (change.m_old_state))
787 {
788 if (change.m_expr)
789 pp_printf (&pp, "assuming %qE is NULL",
790 change.m_expr);
791 else
792 pp_printf (&pp, "assuming %qs is NULL",
793 "<unknown>");
794 return true;
795 }
796 else
797 {
798 if (change.m_expr)
799 pp_printf (&pp, "%qE is NULL",
800 change.m_expr);
801 else
802 pp_printf (&pp, "%qs is NULL",
803 "<unknown>");
804 return true;
805 }
806 }
807
808 return false;
809 }
810
811 diagnostic_event::meaning
812 get_meaning_for_state_change (const evdesc::state_change &change)
813 const final override
814 {
815 if (change.m_old_state == m_sm.get_start_state ()
816 && unchecked_p (change.m_new_state))
817 return diagnostic_event::meaning (diagnostic_event::VERB_acquire,
818 diagnostic_event::NOUN_memory);
819 if (freed_p (change.m_new_state))
820 return diagnostic_event::meaning (diagnostic_event::VERB_release,
821 diagnostic_event::NOUN_memory);
822 return diagnostic_event::meaning ();
823 }
824
825 protected:
826 const malloc_state_machine &m_sm;
827 tree m_arg;
828 };
829
830 /* Concrete subclass for reporting mismatching allocator/deallocator
831 diagnostics. */
832
833 class mismatching_deallocation : public malloc_diagnostic
834 {
835 public:
836 mismatching_deallocation (const malloc_state_machine &sm, tree arg,
837 const deallocator_set *expected_deallocators,
838 const deallocator *actual_dealloc)
839 : malloc_diagnostic (sm, arg),
840 m_expected_deallocators (expected_deallocators),
841 m_actual_dealloc (actual_dealloc)
842 {}
843
844 const char *get_kind () const final override
845 {
846 return "mismatching_deallocation";
847 }
848
849 int get_controlling_option () const final override
850 {
851 return OPT_Wanalyzer_mismatching_deallocation;
852 }
853
854 bool emit (diagnostic_emission_context &ctxt) final override
855 {
856 auto_diagnostic_group d;
857 ctxt.add_cwe (762); /* CWE-762: Mismatched Memory Management Routines. */
858 if (const deallocator *expected_dealloc
859 = m_expected_deallocators->maybe_get_single ())
860 return ctxt.warn ("%qE should have been deallocated with %qs"
861 " but was deallocated with %qs",
862 m_arg, expected_dealloc->m_name,
863 m_actual_dealloc->m_name);
864 else
865 return ctxt.warn ("%qs called on %qE returned from a mismatched"
866 " allocation function",
867 m_actual_dealloc->m_name, m_arg);
868 }
869
870 bool
871 describe_state_change (pretty_printer &pp,
872 const evdesc::state_change &change) final override
873 {
874 if (unchecked_p (change.m_new_state))
875 {
876 m_alloc_event = change.m_event_id;
877 if (const deallocator *expected_dealloc
878 = m_expected_deallocators->maybe_get_single ())
879 pp_printf (&pp,
880 "allocated here (expects deallocation with %qs)",
881 expected_dealloc->m_name);
882 else
883 pp_string (&pp, "allocated here");
884 return true;
885 }
886 return malloc_diagnostic::describe_state_change (pp, change);
887 }
888
889 bool
890 describe_final_event (pretty_printer &pp,
891 const evdesc::final_event &) final override
892 {
893 if (m_alloc_event.known_p ())
894 {
895 if (const deallocator *expected_dealloc
896 = m_expected_deallocators->maybe_get_single ())
897 pp_printf (&pp,
898 "deallocated with %qs here;"
899 " allocation at %@ expects deallocation with %qs",
900 m_actual_dealloc->m_name, &m_alloc_event,
901 expected_dealloc->m_name);
902 else
903 pp_printf (&pp,
904 "deallocated with %qs here;"
905 " allocated at %@",
906 m_actual_dealloc->m_name, &m_alloc_event);
907 return true;
908 }
909 pp_printf (&pp, "deallocated with %qs here",
910 m_actual_dealloc->m_name);
911 return true;
912 }
913
914 private:
915 diagnostic_event_id_t m_alloc_event;
916 const deallocator_set *m_expected_deallocators;
917 const deallocator *m_actual_dealloc;
918 };
919
920 /* Concrete subclass for reporting double-free diagnostics. */
921
922 class double_free : public malloc_diagnostic
923 {
924 public:
925 double_free (const malloc_state_machine &sm, tree arg, const char *funcname)
926 : malloc_diagnostic (sm, arg), m_funcname (funcname)
927 {}
928
929 const char *get_kind () const final override { return "double_free"; }
930
931 int get_controlling_option () const final override
932 {
933 return OPT_Wanalyzer_double_free;
934 }
935
936 bool emit (diagnostic_emission_context &ctxt) final override
937 {
938 auto_diagnostic_group d;
939 ctxt.add_cwe (415); /* CWE-415: Double Free. */
940 return ctxt.warn ("double-%qs of %qE", m_funcname, m_arg);
941 }
942
943 bool
944 describe_state_change (pretty_printer &pp,
945 const evdesc::state_change &change) final override
946 {
947 if (freed_p (change.m_new_state))
948 {
949 m_first_free_event = change.m_event_id;
950 pp_printf (&pp, "first %qs here", m_funcname);
951 return true;
952 }
953 return malloc_diagnostic::describe_state_change (pp, change);
954 }
955
956 bool
957 describe_call_with_state (pretty_printer &pp,
958 const evdesc::call_with_state &info) final override
959 {
960 if (freed_p (info.m_state))
961 {
962 pp_printf (&pp,
963 "passing freed pointer %qE in call to %qE from %qE",
964 info.m_expr, info.m_callee_fndecl, info.m_caller_fndecl);
965 return true;
966 }
967 return false;
968 }
969
970 bool
971 describe_final_event (pretty_printer &pp,
972 const evdesc::final_event &) final override
973 {
974 if (m_first_free_event.known_p ())
975 pp_printf (&pp,
976 "second %qs here; first %qs was at %@",
977 m_funcname, m_funcname,
978 &m_first_free_event);
979 else
980 pp_printf (&pp, "second %qs here", m_funcname);
981 return true;
982 }
983
984 private:
985 diagnostic_event_id_t m_first_free_event;
986 const char *m_funcname;
987 };
988
989 /* Abstract subclass for describing possible bad uses of NULL.
990 Responsible for describing the call that could return NULL. */
991
992 class possible_null : public malloc_diagnostic
993 {
994 public:
995 possible_null (const malloc_state_machine &sm, tree arg)
996 : malloc_diagnostic (sm, arg)
997 {}
998
999 bool
1000 describe_state_change (pretty_printer &pp,
1001 const evdesc::state_change &change) final override
1002 {
1003 if (change.m_old_state == m_sm.get_start_state ()
1004 && unchecked_p (change.m_new_state))
1005 {
1006 m_origin_of_unchecked_event = change.m_event_id;
1007 pp_string (&pp, "this call could return NULL");
1008 return true;
1009 }
1010 return malloc_diagnostic::describe_state_change (pp, change);
1011 }
1012
1013 bool
1014 describe_return_of_state (pretty_printer &pp,
1015 const evdesc::return_of_state &info) final override
1016 {
1017 if (unchecked_p (info.m_state))
1018 {
1019 pp_printf (&pp,
1020 "possible return of NULL to %qE from %qE",
1021 info.m_caller_fndecl, info.m_callee_fndecl);
1022 return true;
1023 }
1024 return false;
1025 }
1026
1027 protected:
1028 diagnostic_event_id_t m_origin_of_unchecked_event;
1029 };
1030
1031 /* Concrete subclass for describing dereference of a possible NULL
1032 value. */
1033
1034 class possible_null_deref : public possible_null
1035 {
1036 public:
1037 possible_null_deref (const malloc_state_machine &sm, tree arg)
1038 : possible_null (sm, arg)
1039 {}
1040
1041 const char *get_kind () const final override { return "possible_null_deref"; }
1042
1043 int get_controlling_option () const final override
1044 {
1045 return OPT_Wanalyzer_possible_null_dereference;
1046 }
1047
1048 bool emit (diagnostic_emission_context &ctxt) final override
1049 {
1050 /* CWE-690: Unchecked Return Value to NULL Pointer Dereference. */
1051 ctxt.add_cwe (690);
1052 return ctxt.warn ("dereference of possibly-NULL %qE", m_arg);
1053 }
1054
1055 bool
1056 describe_final_event (pretty_printer &pp,
1057 const evdesc::final_event &ev) final override
1058 {
1059 if (m_origin_of_unchecked_event.known_p ())
1060 pp_printf (&pp,
1061 "%qE could be NULL: unchecked value from %@",
1062 ev.m_expr,
1063 &m_origin_of_unchecked_event);
1064 else
1065 pp_printf (&pp,"%qE could be NULL", ev.m_expr);
1066 return true;
1067 }
1068
1069 };
1070
1071 /* Return true if FNDECL is a C++ method. */
1072
1073 static bool
1074 method_p (tree fndecl)
1075 {
1076 return TREE_CODE (TREE_TYPE (fndecl)) == METHOD_TYPE;
1077 }
1078
1079 /* Return a 1-based description of ARG_IDX (0-based) of FNDECL.
1080 Compare with %P in the C++ FE (implemented in cp/error.cc: parm_to_string
1081 as called from cp_printer). */
1082
1083 static label_text
1084 describe_argument_index (tree fndecl, int arg_idx)
1085 {
1086 if (method_p (fndecl))
1087 if (arg_idx == 0)
1088 return label_text::borrow ("'this'");
1089 pretty_printer pp;
1090 pp_printf (&pp, "%u", arg_idx + 1 - method_p (fndecl));
1091 return label_text::take (xstrdup (pp_formatted_text (&pp)));
1092 }
1093
1094 /* Subroutine for use by possible_null_arg::emit and null_arg::emit.
1095 Issue a note informing that the pertinent argument must be non-NULL. */
1096
1097 static void
1098 inform_nonnull_attribute (tree fndecl, int arg_idx)
1099 {
1100 label_text arg_desc = describe_argument_index (fndecl, arg_idx);
1101 inform (DECL_SOURCE_LOCATION (fndecl),
1102 "argument %s of %qD must be non-null",
1103 arg_desc.get (), fndecl);
1104 /* Ideally we would use the location of the parm and underline the
1105 attribute also - but we don't have the location_t values at this point
1106 in the middle-end.
1107 For reference, the C and C++ FEs have get_fndecl_argument_location. */
1108 }
1109
1110 /* Concrete subclass for describing passing a possibly-NULL value to a
1111 function marked with __attribute__((nonnull)). */
1112
1113 class possible_null_arg : public possible_null
1114 {
1115 public:
1116 possible_null_arg (const malloc_state_machine &sm, tree arg,
1117 tree fndecl, int arg_idx)
1118 : possible_null (sm, arg),
1119 m_fndecl (fndecl), m_arg_idx (arg_idx)
1120 {}
1121
1122 const char *get_kind () const final override { return "possible_null_arg"; }
1123
1124 bool subclass_equal_p (const pending_diagnostic &base_other)
1125 const final override
1126 {
1127 const possible_null_arg &sub_other
1128 = (const possible_null_arg &)base_other;
1129 return (same_tree_p (m_arg, sub_other.m_arg)
1130 && m_fndecl == sub_other.m_fndecl
1131 && m_arg_idx == sub_other.m_arg_idx);
1132 }
1133
1134 int get_controlling_option () const final override
1135 {
1136 return OPT_Wanalyzer_possible_null_argument;
1137 }
1138
1139 bool emit (diagnostic_emission_context &ctxt) final override
1140 {
1141 /* CWE-690: Unchecked Return Value to NULL Pointer Dereference. */
1142 auto_diagnostic_group d;
1143 ctxt.add_cwe (690);
1144 bool warned
1145 = ctxt.warn ("use of possibly-NULL %qE where non-null expected",
1146 m_arg);
1147 if (warned)
1148 inform_nonnull_attribute (m_fndecl, m_arg_idx);
1149 return warned;
1150 }
1151
1152 bool
1153 describe_final_event (pretty_printer &pp,
1154 const evdesc::final_event &ev) final override
1155 {
1156 label_text arg_desc = describe_argument_index (m_fndecl, m_arg_idx);
1157 if (m_origin_of_unchecked_event.known_p ())
1158 pp_printf (&pp,"argument %s (%qE) from %@ could be NULL"
1159 " where non-null expected",
1160 arg_desc.get (), ev.m_expr,
1161 &m_origin_of_unchecked_event);
1162 else
1163 pp_printf (&pp,
1164 "argument %s (%qE) could be NULL"
1165 " where non-null expected",
1166 arg_desc.get (), ev.m_expr);
1167 return true;
1168 }
1169
1170 private:
1171 tree m_fndecl;
1172 int m_arg_idx;
1173 };
1174
1175 /* Concrete subclass for describing a dereference of a NULL value. */
1176
1177 class null_deref : public malloc_diagnostic
1178 {
1179 public:
1180 null_deref (const malloc_state_machine &sm, tree arg)
1181 : malloc_diagnostic (sm, arg) {}
1182
1183 const char *get_kind () const final override { return "null_deref"; }
1184
1185 int get_controlling_option () const final override
1186 {
1187 return OPT_Wanalyzer_null_dereference;
1188 }
1189
1190 bool terminate_path_p () const final override { return true; }
1191
1192 bool emit (diagnostic_emission_context &ctxt) final override
1193 {
1194 /* CWE-476: NULL Pointer Dereference. */
1195 ctxt.add_cwe (476);
1196 return ctxt.warn ("dereference of NULL %qE", m_arg);
1197 }
1198
1199 bool
1200 describe_return_of_state (pretty_printer &pp,
1201 const evdesc::return_of_state &info)
1202 final override
1203 {
1204 if (info.m_state == m_sm.m_null)
1205 {
1206 pp_printf (&pp, "return of NULL to %qE from %qE",
1207 info.m_caller_fndecl, info.m_callee_fndecl);
1208 return true;
1209 }
1210 return false;
1211 }
1212
1213 bool
1214 describe_final_event (pretty_printer &pp,
1215 const evdesc::final_event &ev) final override
1216 {
1217 pp_printf (&pp, "dereference of NULL %qE", ev.m_expr);
1218 return true;
1219 }
1220
1221 /* Implementation of pending_diagnostic::supercedes_p for
1222 null-deref.
1223
1224 We want null-deref to supercede use-of-unitialized-value,
1225 so that if we have these at the same stmt, we don't emit
1226 a use-of-uninitialized, just the null-deref. */
1227
1228 bool supercedes_p (const pending_diagnostic &other) const final override
1229 {
1230 if (other.use_of_uninit_p ())
1231 return true;
1232
1233 return false;
1234 }
1235 };
1236
1237 /* Concrete subclass for describing passing a NULL value to a
1238 function marked with __attribute__((nonnull)). */
1239
1240 class null_arg : public malloc_diagnostic
1241 {
1242 public:
1243 null_arg (const malloc_state_machine &sm, tree arg,
1244 tree fndecl, int arg_idx)
1245 : malloc_diagnostic (sm, arg),
1246 m_fndecl (fndecl), m_arg_idx (arg_idx)
1247 {}
1248
1249 const char *get_kind () const final override { return "null_arg"; }
1250
1251 bool subclass_equal_p (const pending_diagnostic &base_other)
1252 const final override
1253 {
1254 const null_arg &sub_other
1255 = (const null_arg &)base_other;
1256 return (same_tree_p (m_arg, sub_other.m_arg)
1257 && m_fndecl == sub_other.m_fndecl
1258 && m_arg_idx == sub_other.m_arg_idx);
1259 }
1260
1261 int get_controlling_option () const final override
1262 {
1263 return OPT_Wanalyzer_null_argument;
1264 }
1265
1266 bool terminate_path_p () const final override { return true; }
1267
1268 bool emit (diagnostic_emission_context &ctxt) final override
1269 {
1270 /* CWE-476: NULL Pointer Dereference. */
1271 auto_diagnostic_group d;
1272 ctxt.add_cwe (476);
1273
1274 bool warned;
1275 if (zerop (m_arg))
1276 warned = ctxt.warn ("use of NULL where non-null expected");
1277 else
1278 warned = ctxt.warn ("use of NULL %qE where non-null expected",
1279 m_arg);
1280 if (warned)
1281 inform_nonnull_attribute (m_fndecl, m_arg_idx);
1282 return warned;
1283 }
1284
1285 bool
1286 describe_final_event (pretty_printer &pp,
1287 const evdesc::final_event &ev) final override
1288 {
1289 label_text arg_desc = describe_argument_index (m_fndecl, m_arg_idx);
1290 if (zerop (ev.m_expr))
1291 pp_printf (&pp,
1292 "argument %s NULL where non-null expected",
1293 arg_desc.get ());
1294 else
1295 pp_printf (&pp,
1296 "argument %s (%qE) NULL"
1297 " where non-null expected",
1298 arg_desc.get (), ev.m_expr);
1299 return true;
1300 }
1301
1302 private:
1303 tree m_fndecl;
1304 int m_arg_idx;
1305 };
1306
1307 class use_after_free : public malloc_diagnostic
1308 {
1309 public:
1310 use_after_free (const malloc_state_machine &sm, tree arg,
1311 const deallocator *deallocator)
1312 : malloc_diagnostic (sm, arg),
1313 m_deallocator (deallocator)
1314 {
1315 gcc_assert (deallocator);
1316 }
1317
1318 const char *get_kind () const final override { return "use_after_free"; }
1319
1320 int get_controlling_option () const final override
1321 {
1322 return OPT_Wanalyzer_use_after_free;
1323 }
1324
1325 bool emit (diagnostic_emission_context &ctxt) final override
1326 {
1327 /* CWE-416: Use After Free. */
1328 ctxt.add_cwe (416);
1329 return ctxt.warn ("use after %qs of %qE",
1330 m_deallocator->m_name, m_arg);
1331 }
1332
1333 bool
1334 describe_state_change (pretty_printer &pp,
1335 const evdesc::state_change &change) final override
1336 {
1337 if (freed_p (change.m_new_state))
1338 {
1339 m_free_event = change.m_event_id;
1340 switch (m_deallocator->m_wording)
1341 {
1342 default:
1343 case WORDING_REALLOCATED:
1344 gcc_unreachable ();
1345 case WORDING_FREED:
1346 pp_string (&pp, "freed here");
1347 return true;
1348 case WORDING_DELETED:
1349 pp_string (&pp, "deleted here");
1350 return true;
1351 case WORDING_DEALLOCATED:
1352 pp_string (&pp, "deallocated here");
1353 return true;
1354 }
1355 }
1356 return malloc_diagnostic::describe_state_change (pp, change);
1357 }
1358
1359 bool
1360 describe_final_event (pretty_printer &pp,
1361 const evdesc::final_event &ev) final override
1362 {
1363 const char *funcname = m_deallocator->m_name;
1364 if (m_free_event.known_p ())
1365 switch (m_deallocator->m_wording)
1366 {
1367 default:
1368 case WORDING_REALLOCATED:
1369 gcc_unreachable ();
1370 case WORDING_FREED:
1371 pp_printf (&pp,
1372 "use after %qs of %qE; freed at %@",
1373 funcname, ev.m_expr, &m_free_event);
1374 return true;
1375 case WORDING_DELETED:
1376 pp_printf (&pp,
1377 "use after %qs of %qE; deleted at %@",
1378 funcname, ev.m_expr, &m_free_event);
1379 return true;
1380 case WORDING_DEALLOCATED:
1381 pp_printf (&pp,
1382 "use after %qs of %qE;"
1383 " deallocated at %@",
1384 funcname, ev.m_expr, &m_free_event);
1385 return true;
1386 }
1387 else
1388 {
1389 pp_printf (&pp,
1390 "use after %qs of %qE",
1391 funcname, ev.m_expr);
1392 return true;
1393 }
1394 }
1395
1396 /* Implementation of pending_diagnostic::supercedes_p for
1397 use_after_free.
1398
1399 We want use-after-free to supercede use-of-unitialized-value,
1400 so that if we have these at the same stmt, we don't emit
1401 a use-of-uninitialized, just the use-after-free.
1402 (this is because we fully purge information about freed
1403 buffers when we free them to avoid state explosions, so
1404 that if they are accessed after the free, it looks like
1405 they are uninitialized). */
1406
1407 bool supercedes_p (const pending_diagnostic &other) const final override
1408 {
1409 if (other.use_of_uninit_p ())
1410 return true;
1411
1412 return false;
1413 }
1414
1415 private:
1416 diagnostic_event_id_t m_free_event;
1417 const deallocator *m_deallocator;
1418 };
1419
1420 class malloc_leak : public malloc_diagnostic
1421 {
1422 public:
1423 malloc_leak (const malloc_state_machine &sm, tree arg)
1424 : malloc_diagnostic (sm, arg) {}
1425
1426 const char *get_kind () const final override { return "malloc_leak"; }
1427
1428 int get_controlling_option () const final override
1429 {
1430 return OPT_Wanalyzer_malloc_leak;
1431 }
1432
1433 bool emit (diagnostic_emission_context &ctxt) final override
1434 {
1435 /* "CWE-401: Missing Release of Memory after Effective Lifetime". */
1436 ctxt.add_cwe (401);
1437 if (m_arg)
1438 return ctxt.warn ("leak of %qE", m_arg);
1439 else
1440 return ctxt.warn ("leak of %qs", "<unknown>");
1441 }
1442
1443 bool
1444 describe_state_change (pretty_printer &pp,
1445 const evdesc::state_change &change) final override
1446 {
1447 if (unchecked_p (change.m_new_state)
1448 || (start_p (change.m_old_state) && nonnull_p (change.m_new_state)))
1449 {
1450 m_alloc_event = change.m_event_id;
1451 pp_string (&pp, "allocated here");
1452 return true;
1453 }
1454 return malloc_diagnostic::describe_state_change (pp, change);
1455 }
1456
1457 bool
1458 describe_final_event (pretty_printer &pp,
1459 const evdesc::final_event &ev) final override
1460 {
1461 if (ev.m_expr)
1462 {
1463 if (m_alloc_event.known_p ())
1464 pp_printf (&pp,
1465 "%qE leaks here; was allocated at %@",
1466 ev.m_expr, &m_alloc_event);
1467 else
1468 pp_printf (&pp,
1469 "%qE leaks here", ev.m_expr);
1470 }
1471 else
1472 {
1473 if (m_alloc_event.known_p ())
1474 pp_printf (&pp,
1475 "%qs leaks here; was allocated at %@",
1476 "<unknown>", &m_alloc_event);
1477 else
1478 pp_printf (&pp,
1479 "%qs leaks here", "<unknown>");
1480 }
1481 return true;
1482 }
1483
1484 private:
1485 diagnostic_event_id_t m_alloc_event;
1486 };
1487
1488 class free_of_non_heap : public malloc_diagnostic
1489 {
1490 public:
1491 free_of_non_heap (const malloc_state_machine &sm, tree arg,
1492 const region *freed_reg,
1493 const char *funcname)
1494 : malloc_diagnostic (sm, arg), m_freed_reg (freed_reg), m_funcname (funcname)
1495 {
1496 }
1497
1498 const char *get_kind () const final override { return "free_of_non_heap"; }
1499
1500 bool subclass_equal_p (const pending_diagnostic &base_other) const
1501 final override
1502 {
1503 const free_of_non_heap &other = (const free_of_non_heap &)base_other;
1504 return (same_tree_p (m_arg, other.m_arg)
1505 && m_freed_reg == other.m_freed_reg);
1506 }
1507
1508 int get_controlling_option () const final override
1509 {
1510 return OPT_Wanalyzer_free_of_non_heap;
1511 }
1512
1513 bool emit (diagnostic_emission_context &ctxt) final override
1514 {
1515 auto_diagnostic_group d;
1516 ctxt.add_cwe (590); /* CWE-590: Free of Memory not on the Heap. */
1517 switch (get_memory_space ())
1518 {
1519 default:
1520 case MEMSPACE_HEAP:
1521 gcc_unreachable ();
1522 case MEMSPACE_UNKNOWN:
1523 case MEMSPACE_CODE:
1524 case MEMSPACE_GLOBALS:
1525 case MEMSPACE_READONLY_DATA:
1526 return ctxt.warn ("%qs of %qE which points to memory"
1527 " not on the heap",
1528 m_funcname, m_arg);
1529 break;
1530 case MEMSPACE_STACK:
1531 return ctxt.warn ("%qs of %qE which points to memory"
1532 " on the stack",
1533 m_funcname, m_arg);
1534 break;
1535 }
1536 }
1537
1538 bool
1539 describe_state_change (pretty_printer &pp,
1540 const evdesc::state_change &) final override
1541 {
1542 pp_string (&pp, "pointer is from here");
1543 return true;
1544 }
1545
1546 bool
1547 describe_final_event (pretty_printer &pp,
1548 const evdesc::final_event &) final override
1549 {
1550 pp_printf (&pp, "call to %qs here", m_funcname);
1551 return true;
1552 }
1553
1554 void mark_interesting_stuff (interesting_t *interest) final override
1555 {
1556 if (m_freed_reg)
1557 interest->add_region_creation (m_freed_reg);
1558 }
1559
1560 private:
1561 enum memory_space get_memory_space () const
1562 {
1563 if (m_freed_reg)
1564 return m_freed_reg->get_memory_space ();
1565 else
1566 return MEMSPACE_UNKNOWN;
1567 }
1568
1569 const region *m_freed_reg;
1570 const char *m_funcname;
1571 };
1572
1573 /* Concrete pending_diagnostic subclass for -Wanalyzer-deref-before-check. */
1574
1575 class deref_before_check : public malloc_diagnostic
1576 {
1577 public:
1578 deref_before_check (const malloc_state_machine &sm, tree arg)
1579 : malloc_diagnostic (sm, arg),
1580 m_deref_enode (NULL),
1581 m_deref_expr (NULL),
1582 m_check_enode (NULL)
1583 {
1584 gcc_assert (arg);
1585 }
1586
1587 const char *get_kind () const final override { return "deref_before_check"; }
1588
1589 int get_controlling_option () const final override
1590 {
1591 return OPT_Wanalyzer_deref_before_check;
1592 }
1593
1594 bool emit (diagnostic_emission_context &ctxt) final override
1595 {
1596 /* Don't emit the warning if we can't show where the deref
1597 and the check occur. */
1598 if (!m_deref_enode)
1599 return false;
1600 if (!m_check_enode)
1601 return false;
1602 /* Only emit the warning for intraprocedural cases. */
1603 const program_point &deref_point = m_deref_enode->get_point ();
1604 const program_point &check_point = m_check_enode->get_point ();
1605
1606 if (!program_point::effectively_intraprocedural_p (deref_point,
1607 check_point))
1608 return false;
1609
1610 /* Reject the warning if the check occurs within a macro defintion.
1611 This avoids false positives for such code as:
1612
1613 #define throw_error \
1614 do { \
1615 if (p) \
1616 cleanup (p); \
1617 return; \
1618 } while (0)
1619
1620 if (p->idx >= n)
1621 throw_error ();
1622
1623 where the usage of "throw_error" implicitly adds a check
1624 on 'p'.
1625
1626 We do warn when the check is in a macro expansion if we can get
1627 at the location of the condition and it is't part of the
1628 definition, so that we warn for checks such as:
1629 if (words[0][0] == '@')
1630 return;
1631 g_assert(words[0] != NULL); <--- here
1632 Unfortunately we don't have locations for individual gimple
1633 arguments, so in:
1634 g_assert (ptr);
1635 we merely have a gimple_cond
1636 if (p_2(D) == 0B)
1637 with no way of getting at the location of the condition separately
1638 from that of the gimple_cond (where the "if" is within the macro
1639 definition). We reject the warning for such cases.
1640
1641 We do warn when the *deref* occurs in a macro, since this can be
1642 a source of real bugs; see e.g. PR 77425. */
1643 location_t check_loc = m_check_enode->get_point ().get_location ();
1644 if (linemap_location_from_macro_definition_p (line_table, check_loc))
1645 return false;
1646
1647 /* Reject warning if the check is in a loop header within a
1648 macro expansion. This rejects cases like:
1649 | deref of x;
1650 | [...snip...]
1651 | FOR_EACH(x) {
1652 | [...snip...]
1653 | }
1654 where the FOR_EACH macro tests for non-nullness of x, since
1655 the user is hoping to encapsulate the details of iteration
1656 in the macro, and the extra check on the first iteration
1657 would just be noise if we reported it. */
1658 if (loop_header_p (m_check_enode->get_point ())
1659 && linemap_location_from_macro_expansion_p (line_table, check_loc))
1660 return false;
1661
1662 /* Reject if m_deref_expr is sufficiently different from m_arg
1663 for cases where the dereference is spelled differently from
1664 the check, which is probably two different ways to get the
1665 same svalue, and thus not worth reporting. */
1666 if (!m_deref_expr)
1667 return false;
1668 if (!sufficiently_similar_p (m_deref_expr, m_arg))
1669 return false;
1670
1671 /* Reject the warning if the deref's BB doesn't dominate that
1672 of the check, so that we don't warn e.g. for shared cleanup
1673 code that checks a pointer for NULL, when that code is sometimes
1674 used before a deref and sometimes after.
1675 Using the dominance code requires setting cfun. */
1676 auto_cfun sentinel (m_deref_enode->get_function ());
1677 calculate_dominance_info (CDI_DOMINATORS);
1678 if (!dominated_by_p (CDI_DOMINATORS,
1679 m_check_enode->get_supernode ()->m_bb,
1680 m_deref_enode->get_supernode ()->m_bb))
1681 return false;
1682
1683 return ctxt.warn ("check of %qE for NULL after already"
1684 " dereferencing it",
1685 m_arg);
1686 }
1687
1688 bool
1689 describe_state_change (pretty_printer &pp,
1690 const evdesc::state_change &change) final override
1691 {
1692 if (change.m_old_state == m_sm.get_start_state ()
1693 && assumed_non_null_p (change.m_new_state))
1694 {
1695 m_first_deref_event = change.m_event_id;
1696 m_deref_enode = change.m_event.get_exploded_node ();
1697 m_deref_expr = change.m_expr;
1698 pp_printf (&pp,
1699 "pointer %qE is dereferenced here",
1700 m_arg);
1701 return true;
1702 }
1703 return malloc_diagnostic::describe_state_change (pp, change);
1704 }
1705
1706 bool
1707 describe_final_event (pretty_printer &pp,
1708 const evdesc::final_event &ev) final override
1709 {
1710 m_check_enode = ev.m_event.get_exploded_node ();
1711 if (m_first_deref_event.known_p ())
1712 pp_printf (&pp,
1713 "pointer %qE is checked for NULL here but"
1714 " it was already dereferenced at %@",
1715 m_arg, &m_first_deref_event);
1716 else
1717 pp_printf (&pp,
1718 "pointer %qE is checked for NULL here but"
1719 " it was already dereferenced",
1720 m_arg);
1721 return true;
1722 }
1723
1724 private:
1725 static bool loop_header_p (const program_point &point)
1726 {
1727 const supernode *snode = point.get_supernode ();
1728 if (!snode)
1729 return false;
1730 for (auto &in_edge : snode->m_preds)
1731 {
1732 if (const cfg_superedge *cfg_in_edge
1733 = in_edge->dyn_cast_cfg_superedge ())
1734 if (cfg_in_edge->back_edge_p ())
1735 return true;
1736 }
1737 return false;
1738 }
1739
1740 static bool sufficiently_similar_p (tree expr_a, tree expr_b)
1741 {
1742 auto pp_a = global_dc->clone_printer ();
1743 auto pp_b = global_dc->clone_printer ();
1744 pp_printf (pp_a.get (), "%qE", expr_a);
1745 pp_printf (pp_b.get (), "%qE", expr_b);
1746 bool result = (strcmp (pp_formatted_text (pp_a.get ()),
1747 pp_formatted_text (pp_b.get ()))
1748 == 0);
1749 return result;
1750 }
1751
1752 diagnostic_event_id_t m_first_deref_event;
1753 const exploded_node *m_deref_enode;
1754 tree m_deref_expr;
1755 const exploded_node *m_check_enode;
1756 };
1757
1758 /* struct allocation_state : public state_machine::state. */
1759
1760 /* Implementation of state_machine::state::dump_to_pp vfunc
1761 for allocation_state: append the API that this allocation is
1762 associated with. */
1763
1764 void
1765 allocation_state::dump_to_pp (pretty_printer *pp) const
1766 {
1767 state_machine::state::dump_to_pp (pp);
1768 if (m_deallocators)
1769 {
1770 pp_string (pp, " (");
1771 m_deallocators->dump_to_pp (pp);
1772 pp_character (pp, ')');
1773 }
1774 }
1775
1776 /* Given a allocation_state for a deallocator_set, get the "nonnull" state
1777 for the corresponding allocator(s). */
1778
1779 const allocation_state *
1780 allocation_state::get_nonnull () const
1781 {
1782 gcc_assert (m_deallocators);
1783 return as_a_allocation_state (m_deallocators->m_nonnull);
1784 }
1785
1786 /* struct assumed_non_null_state : public allocation_state. */
1787
1788 void
1789 assumed_non_null_state::dump_to_pp (pretty_printer *pp) const
1790 {
1791 allocation_state::dump_to_pp (pp);
1792 pp_string (pp, " (in ");
1793 m_frame->dump_to_pp (pp, true);
1794 pp_character (pp, ')');
1795 }
1796
1797 /* malloc_state_machine's ctor. */
1798
1799 malloc_state_machine::malloc_state_machine (logger *logger)
1800 : state_machine ("malloc", logger),
1801 m_free (this, "free", WORDING_FREED),
1802 m_scalar_delete (this, "delete", WORDING_DELETED),
1803 m_vector_delete (this, "delete[]", WORDING_DELETED),
1804 m_realloc (this, "realloc", WORDING_REALLOCATED)
1805 {
1806 gcc_assert (m_start->get_id () == 0);
1807 m_null = add_state ("null", RS_FREED, NULL, NULL);
1808 m_non_heap = add_state ("non-heap", RS_NON_HEAP, NULL, NULL);
1809 m_stop = add_state ("stop", RS_STOP, NULL, NULL);
1810 }
1811
1812 malloc_state_machine::~malloc_state_machine ()
1813 {
1814 unsigned i;
1815 custom_deallocator_set *set;
1816 FOR_EACH_VEC_ELT (m_dynamic_sets, i, set)
1817 delete set;
1818 custom_deallocator *d;
1819 FOR_EACH_VEC_ELT (m_dynamic_deallocators, i, d)
1820 delete d;
1821 }
1822
1823 state_machine::state_t
1824 malloc_state_machine::add_state (const char *name, enum resource_state rs,
1825 const deallocator_set *deallocators,
1826 const deallocator *deallocator)
1827 {
1828 return add_custom_state (new allocation_state (name, alloc_state_id (),
1829 rs, deallocators,
1830 deallocator));
1831 }
1832
1833 /* If ALLOCATOR_FNDECL has any "__attribute__((malloc(FOO)))",
1834 return a custom_deallocator_set for them, consolidating them
1835 to ensure uniqueness of the sets.
1836
1837 Return NULL if it has no such attributes. */
1838
1839 const custom_deallocator_set *
1840 malloc_state_machine::
1841 get_or_create_custom_deallocator_set (tree allocator_fndecl)
1842 {
1843 /* Early rejection of decls without attributes. */
1844 tree attrs = DECL_ATTRIBUTES (allocator_fndecl);
1845 if (!attrs)
1846 return NULL;
1847
1848 /* Otherwise, call maybe_create_custom_deallocator_set,
1849 memoizing the result. */
1850 if (custom_deallocator_set **slot
1851 = m_custom_deallocator_set_cache.get (allocator_fndecl))
1852 return *slot;
1853 custom_deallocator_set *set
1854 = maybe_create_custom_deallocator_set (allocator_fndecl);
1855 m_custom_deallocator_set_cache.put (allocator_fndecl, set);
1856 return set;
1857 }
1858
1859 /* Given ALLOCATOR_FNDECL, a FUNCTION_DECL with attributes,
1860 look for any "__attribute__((malloc(FOO)))" and return a
1861 custom_deallocator_set for them, consolidating them
1862 to ensure uniqueness of the sets.
1863
1864 Return NULL if it has no such attributes.
1865
1866 Subroutine of get_or_create_custom_deallocator_set which
1867 memoizes the result. */
1868
1869 custom_deallocator_set *
1870 malloc_state_machine::
1871 maybe_create_custom_deallocator_set (tree allocator_fndecl)
1872 {
1873 tree attrs = DECL_ATTRIBUTES (allocator_fndecl);
1874 gcc_assert (attrs);
1875
1876 /* Look for instances of __attribute__((malloc(FOO))). */
1877 auto_vec<const deallocator *> deallocator_vec;
1878 for (tree allocs = attrs;
1879 (allocs = lookup_attribute ("malloc", allocs));
1880 allocs = TREE_CHAIN (allocs))
1881 {
1882 tree args = TREE_VALUE (allocs);
1883 if (!args)
1884 continue;
1885 if (TREE_VALUE (args))
1886 {
1887 const deallocator *d
1888 = get_or_create_deallocator (TREE_VALUE (args));
1889 deallocator_vec.safe_push (d);
1890 }
1891 }
1892
1893 /* If there weren't any deallocators, bail. */
1894 if (deallocator_vec.length () == 0)
1895 return NULL;
1896
1897 /* Consolidate, so that we reuse existing deallocator_set
1898 instances. */
1899 deallocator_vec.qsort (deallocator::cmp_ptr_ptr);
1900 custom_deallocator_set **slot
1901 = m_custom_deallocator_set_map.get (&deallocator_vec);
1902 if (slot)
1903 return *slot;
1904 custom_deallocator_set *set
1905 = new custom_deallocator_set (this, &deallocator_vec, WORDING_DEALLOCATED);
1906 m_custom_deallocator_set_map.put (&set->m_deallocator_vec, set);
1907 m_dynamic_sets.safe_push (set);
1908 return set;
1909 }
1910
1911 /* Get the deallocator for DEALLOCATOR_FNDECL, creating it if necessary. */
1912
1913 const deallocator *
1914 malloc_state_machine::get_or_create_deallocator (tree deallocator_fndecl)
1915 {
1916 deallocator **slot = m_deallocator_map.get (deallocator_fndecl);
1917 if (slot)
1918 return *slot;
1919
1920 /* Reuse "free". */
1921 deallocator *d;
1922 if (is_named_call_p (deallocator_fndecl, "free")
1923 || is_std_named_call_p (deallocator_fndecl, "free")
1924 || is_named_call_p (deallocator_fndecl, "__builtin_free"))
1925 d = &m_free.m_deallocator;
1926 else
1927 {
1928 custom_deallocator *cd
1929 = new custom_deallocator (this, deallocator_fndecl,
1930 WORDING_DEALLOCATED);
1931 m_dynamic_deallocators.safe_push (cd);
1932 d = cd;
1933 }
1934 m_deallocator_map.put (deallocator_fndecl, d);
1935 return d;
1936 }
1937
1938 /* Get the "assumed-non-null" state for assumptions made within FRAME,
1939 creating it if necessary. */
1940
1941 state_machine::state_t
1942 malloc_state_machine::
1943 get_or_create_assumed_non_null_state_for_frame (const frame_region *frame)
1944 {
1945 if (state_t *slot = m_assumed_non_null.get (frame))
1946 return *slot;
1947 state_machine::state *new_state
1948 = new assumed_non_null_state ("assumed-non-null", alloc_state_id (), frame);
1949 add_custom_state (new_state);
1950 m_assumed_non_null.put (frame, new_state);
1951 return new_state;
1952 }
1953
1954 /* Try to identify the function declaration either by name or as a known malloc
1955 builtin. */
1956
1957 static bool
1958 known_allocator_p (const_tree fndecl, const gcall *call)
1959 {
1960 /* Either it is a function we know by name and number of arguments... */
1961 if (is_named_call_p (fndecl, "malloc", call, 1)
1962 || is_named_call_p (fndecl, "calloc", call, 2)
1963 || is_std_named_call_p (fndecl, "malloc", call, 1)
1964 || is_std_named_call_p (fndecl, "calloc", call, 2)
1965 || is_named_call_p (fndecl, "strdup", call, 1)
1966 || is_named_call_p (fndecl, "strndup", call, 2))
1967 return true;
1968
1969 /* ... or it is a builtin allocator that allocates objects freed with
1970 __builtin_free. */
1971 if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
1972 switch (DECL_FUNCTION_CODE (fndecl))
1973 {
1974 case BUILT_IN_MALLOC:
1975 case BUILT_IN_CALLOC:
1976 case BUILT_IN_STRDUP:
1977 case BUILT_IN_STRNDUP:
1978 return true;
1979 default:
1980 break;
1981 }
1982
1983 return false;
1984 }
1985
1986 /* If PTR's nullness is not known, transition it to the "assumed-non-null"
1987 state for the current frame. */
1988
1989 void
1990 malloc_state_machine::maybe_assume_non_null (sm_context &sm_ctxt,
1991 tree ptr,
1992 const gimple *stmt) const
1993 {
1994 const region_model *old_model = sm_ctxt.get_old_region_model ();
1995 if (!old_model)
1996 return;
1997
1998 tree null_ptr_cst = build_int_cst (TREE_TYPE (ptr), 0);
1999 tristate known_non_null
2000 = old_model->eval_condition (ptr, NE_EXPR, null_ptr_cst, NULL);
2001 if (known_non_null.is_unknown ())
2002 {
2003 /* Cast away const-ness for cache-like operations. */
2004 malloc_state_machine *mut_this
2005 = const_cast <malloc_state_machine *> (this);
2006 state_t next_state
2007 = mut_this->get_or_create_assumed_non_null_state_for_frame
2008 (old_model->get_current_frame ());
2009 sm_ctxt.set_next_state (stmt, ptr, next_state);
2010 }
2011 }
2012
2013 /* Helper method for malloc_state_machine::on_stmt. Handle a single
2014 argument (Ith argument ARG) if it is nonnull or nonnull_if_nonzero
2015 and size is nonzero. */
2016
2017 void
2018 malloc_state_machine::handle_nonnull (sm_context &sm_ctxt,
2019 const supernode *node,
2020 const gimple *stmt,
2021 tree fndecl,
2022 tree arg,
2023 unsigned i) const
2024 {
2025 state_t state = sm_ctxt.get_state (stmt, arg);
2026 /* Can't use a switch as the states are non-const. */
2027 /* Do use the fndecl that caused the warning so that the
2028 misused attributes are printed and the user not confused. */
2029 if (unchecked_p (state))
2030 {
2031 tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2032 sm_ctxt.warn (node, stmt, arg,
2033 make_unique<possible_null_arg> (*this, diag_arg, fndecl,
2034 i));
2035 const allocation_state *astate
2036 = as_a_allocation_state (state);
2037 sm_ctxt.set_next_state (stmt, arg, astate->get_nonnull ());
2038 }
2039 else if (state == m_null)
2040 {
2041 tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2042 sm_ctxt.warn (node, stmt, arg,
2043 make_unique<null_arg> (*this, diag_arg, fndecl, i));
2044 sm_ctxt.set_next_state (stmt, arg, m_stop);
2045 }
2046 else if (state == m_start)
2047 maybe_assume_non_null (sm_ctxt, arg, stmt);
2048 }
2049
2050 /* Implementation of state_machine::on_stmt vfunc for malloc_state_machine. */
2051
2052 bool
2053 malloc_state_machine::on_stmt (sm_context &sm_ctxt,
2054 const supernode *node,
2055 const gimple *stmt) const
2056 {
2057 if (const gcall *call = dyn_cast <const gcall *> (stmt))
2058 if (tree callee_fndecl = sm_ctxt.get_fndecl_for_call (call))
2059 {
2060 if (known_allocator_p (callee_fndecl, call))
2061 {
2062 on_allocator_call (sm_ctxt, call, &m_free);
2063 return true;
2064 }
2065
2066 if (!is_placement_new_p (call))
2067 {
2068 bool returns_nonnull = !TREE_NOTHROW (callee_fndecl)
2069 && flag_exceptions;
2070 if (is_named_call_p (callee_fndecl, "operator new"))
2071 on_allocator_call (sm_ctxt, call,
2072 &m_scalar_delete, returns_nonnull);
2073 else if (is_named_call_p (callee_fndecl, "operator new []"))
2074 on_allocator_call (sm_ctxt, call,
2075 &m_vector_delete, returns_nonnull);
2076 }
2077
2078 if (is_named_call_p (callee_fndecl, "operator delete", call, 1)
2079 || is_named_call_p (callee_fndecl, "operator delete", call, 2))
2080 {
2081 on_deallocator_call (sm_ctxt, node, call,
2082 &m_scalar_delete.m_deallocator, 0);
2083 return true;
2084 }
2085 else if (is_named_call_p (callee_fndecl, "operator delete []", call, 1))
2086 {
2087 on_deallocator_call (sm_ctxt, node, call,
2088 &m_vector_delete.m_deallocator, 0);
2089 return true;
2090 }
2091
2092 if (is_named_call_p (callee_fndecl, "alloca", call, 1)
2093 || is_named_call_p (callee_fndecl, "__builtin_alloca", call, 1))
2094 {
2095 tree lhs = gimple_call_lhs (call);
2096 if (lhs)
2097 sm_ctxt.on_transition (node, stmt, lhs, m_start, m_non_heap);
2098 return true;
2099 }
2100
2101 if (is_named_call_p (callee_fndecl, "free", call, 1)
2102 || is_std_named_call_p (callee_fndecl, "free", call, 1)
2103 || is_named_call_p (callee_fndecl, "__builtin_free", call, 1))
2104 {
2105 on_deallocator_call (sm_ctxt, node, call,
2106 &m_free.m_deallocator, 0);
2107 return true;
2108 }
2109
2110 if (is_named_call_p (callee_fndecl, "realloc", call, 2)
2111 || is_std_named_call_p (callee_fndecl, "realloc", call, 2)
2112 || is_named_call_p (callee_fndecl, "__builtin_realloc", call, 2))
2113 {
2114 on_realloc_call (sm_ctxt, node, call);
2115 return true;
2116 }
2117
2118 if (unaffected_by_call_p (callee_fndecl))
2119 return true;
2120
2121 /* Cast away const-ness for cache-like operations. */
2122 malloc_state_machine *mutable_this
2123 = const_cast <malloc_state_machine *> (this);
2124
2125 /* Handle interesting attributes of the callee_fndecl,
2126 or prioritize those of the builtin that callee_fndecl is expected
2127 to be.
2128 Might want this to be controlled by a flag. */
2129 {
2130 tree fndecl = callee_fndecl;
2131 /* If call is recognized as a builtin known_function, use that
2132 builtin's function_decl. */
2133 if (const region_model *old_model = sm_ctxt.get_old_region_model ())
2134 if (const builtin_known_function *builtin_kf
2135 = old_model->get_builtin_kf (call))
2136 fndecl = builtin_kf->builtin_decl ();
2137
2138 /* Handle "__attribute__((malloc(FOO)))". */
2139 if (const deallocator_set *deallocators
2140 = mutable_this->get_or_create_custom_deallocator_set
2141 (fndecl))
2142 {
2143 tree attrs = TYPE_ATTRIBUTES (TREE_TYPE (fndecl));
2144 bool returns_nonnull
2145 = lookup_attribute ("returns_nonnull", attrs);
2146 on_allocator_call (sm_ctxt, call, deallocators, returns_nonnull);
2147 }
2148
2149 {
2150 /* Handle "__attribute__((nonnull))". */
2151 tree fntype = TREE_TYPE (fndecl);
2152 bitmap nonnull_args = get_nonnull_args (fntype);
2153 if (nonnull_args)
2154 {
2155 for (unsigned i = 0; i < gimple_call_num_args (stmt); i++)
2156 {
2157 tree arg = gimple_call_arg (stmt, i);
2158 if (TREE_CODE (TREE_TYPE (arg)) != POINTER_TYPE)
2159 continue;
2160 /* If we have a nonnull-args, and either all pointers, or
2161 just the specified pointers. */
2162 if (bitmap_empty_p (nonnull_args)
2163 || bitmap_bit_p (nonnull_args, i))
2164 handle_nonnull (sm_ctxt, node, stmt, fndecl, arg, i);
2165 }
2166 BITMAP_FREE (nonnull_args);
2167 }
2168 /* Handle __attribute__((nonnull_if_nonzero (x, y))). */
2169 if (fntype)
2170 for (tree attrs = TYPE_ATTRIBUTES (fntype);
2171 (attrs = lookup_attribute ("nonnull_if_nonzero", attrs));
2172 attrs = TREE_CHAIN (attrs))
2173 {
2174 tree args = TREE_VALUE (attrs);
2175 unsigned int idx = TREE_INT_CST_LOW (TREE_VALUE (args)) - 1;
2176 unsigned int idx2
2177 = TREE_INT_CST_LOW (TREE_VALUE (TREE_CHAIN (args))) - 1;
2178 if (idx < gimple_call_num_args (stmt)
2179 && idx2 < gimple_call_num_args (stmt))
2180 {
2181 tree arg = gimple_call_arg (stmt, idx);
2182 tree arg2 = gimple_call_arg (stmt, idx2);
2183 if (TREE_CODE (TREE_TYPE (arg)) != POINTER_TYPE
2184 || !INTEGRAL_TYPE_P (TREE_TYPE (arg2))
2185 || integer_zerop (arg2))
2186 continue;
2187 if (integer_nonzerop (arg2))
2188 ;
2189 else
2190 /* FIXME: Use ranger here to query arg2 range? */
2191 continue;
2192 handle_nonnull (sm_ctxt, node, stmt, fndecl, arg, idx);
2193 }
2194 }
2195 }
2196
2197 /* Check for this after nonnull, so that if we have both
2198 then we transition to "freed", rather than "checked". */
2199 unsigned dealloc_argno = fndecl_dealloc_argno (fndecl);
2200 if (dealloc_argno != UINT_MAX)
2201 {
2202 const deallocator *d
2203 = mutable_this->get_or_create_deallocator (fndecl);
2204 on_deallocator_call (sm_ctxt, node, call, d, dealloc_argno);
2205 }
2206 }
2207 }
2208
2209 /* Look for pointers explicitly being compared against zero
2210 that are in state assumed_non_null i.e. we already defererenced
2211 them.
2212 We have to do this check here, rather than in on_condition
2213 because we add a constraint that the pointer is non-null when
2214 dereferencing it, and this makes the apply_constraints_for_gcond
2215 find known-true and known-false conditions; on_condition is only
2216 called when adding new constraints. */
2217 if (const gcond *cond_stmt = dyn_cast <const gcond *> (stmt))
2218 {
2219 enum tree_code op = gimple_cond_code (cond_stmt);
2220 if (op == EQ_EXPR || op == NE_EXPR)
2221 {
2222 tree lhs = gimple_cond_lhs (cond_stmt);
2223 tree rhs = gimple_cond_rhs (cond_stmt);
2224 if (any_pointer_p (lhs)
2225 && any_pointer_p (rhs)
2226 && zerop (rhs))
2227 {
2228 state_t state = sm_ctxt.get_state (stmt, lhs);
2229 if (assumed_non_null_p (state))
2230 maybe_complain_about_deref_before_check
2231 (sm_ctxt, node,
2232 stmt,
2233 (const assumed_non_null_state *)state,
2234 lhs);
2235 }
2236 }
2237 }
2238
2239 if (tree lhs = sm_ctxt.is_zero_assignment (stmt))
2240 if (any_pointer_p (lhs))
2241 on_zero_assignment (sm_ctxt, stmt,lhs);
2242
2243 /* Handle dereferences. */
2244 for (unsigned i = 0; i < gimple_num_ops (stmt); i++)
2245 {
2246 tree op = gimple_op (stmt, i);
2247 if (!op)
2248 continue;
2249 if (TREE_CODE (op) == COMPONENT_REF)
2250 op = TREE_OPERAND (op, 0);
2251
2252 if (TREE_CODE (op) == MEM_REF)
2253 {
2254 tree arg = TREE_OPERAND (op, 0);
2255
2256 state_t state = sm_ctxt.get_state (stmt, arg);
2257 if (state == m_start)
2258 maybe_assume_non_null (sm_ctxt, arg, stmt);
2259 else if (unchecked_p (state))
2260 {
2261 tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2262 sm_ctxt.warn (node, stmt, arg,
2263 make_unique<possible_null_deref> (*this,
2264 diag_arg));
2265 const allocation_state *astate = as_a_allocation_state (state);
2266 sm_ctxt.set_next_state (stmt, arg, astate->get_nonnull ());
2267 }
2268 else if (state == m_null)
2269 {
2270 tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2271 sm_ctxt.warn (node, stmt, arg,
2272 make_unique<null_deref> (*this, diag_arg));
2273 sm_ctxt.set_next_state (stmt, arg, m_stop);
2274 }
2275 else if (freed_p (state))
2276 {
2277 tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2278 const allocation_state *astate = as_a_allocation_state (state);
2279 sm_ctxt.warn (node, stmt, arg,
2280 make_unique<use_after_free>
2281 (*this, diag_arg, astate->m_deallocator));
2282 sm_ctxt.set_next_state (stmt, arg, m_stop);
2283 }
2284 }
2285 }
2286 return false;
2287 }
2288
2289 /* Given a check against null of PTR in assumed-non-null state STATE,
2290 potentially add a deref_before_check warning to SM_CTXT. */
2291
2292 void
2293 malloc_state_machine::
2294 maybe_complain_about_deref_before_check (sm_context &sm_ctxt,
2295 const supernode *node,
2296 const gimple *stmt,
2297 const assumed_non_null_state *state,
2298 tree ptr) const
2299 {
2300 const region_model *model = sm_ctxt.get_old_region_model ();
2301 if (!model)
2302 return;
2303
2304 /* Don't complain if the current frame (where the check is occurring) is
2305 deeper than the frame in which the "not null" assumption was made.
2306 This suppress false positives for cases like:
2307
2308 void foo (struct s *p)
2309 {
2310 int val = s->some_field; // deref here
2311 shared_helper (p);
2312 }
2313
2314 where "shared_helper" has:
2315
2316 void shared_helper (struct s *p)
2317 {
2318 if (!p) // check here
2319 return;
2320 // etc
2321 }
2322
2323 since the check in "shared_helper" is OK. */
2324 const frame_region *checked_in_frame = model->get_current_frame ();
2325 const frame_region *assumed_nonnull_in_frame = state->m_frame;
2326 if (checked_in_frame->get_index () > assumed_nonnull_in_frame->get_index ())
2327 return;
2328
2329 /* Don't complain if STMT was inlined from another function, to avoid
2330 similar false positives involving shared helper functions. */
2331 if (stmt->location)
2332 {
2333 inlining_info info (stmt->location);
2334 if (info.get_extra_frames () > 0)
2335 return;
2336 }
2337
2338 tree diag_ptr = sm_ctxt.get_diagnostic_tree (ptr);
2339 if (diag_ptr)
2340 sm_ctxt.warn
2341 (node, stmt, ptr,
2342 make_unique<deref_before_check> (*this, diag_ptr));
2343 sm_ctxt.set_next_state (stmt, ptr, m_stop);
2344 }
2345
2346 /* Handle a call to an allocator.
2347 RETURNS_NONNULL is true if CALL is to a fndecl known to have
2348 __attribute__((returns_nonnull)). */
2349
2350 void
2351 malloc_state_machine::on_allocator_call (sm_context &sm_ctxt,
2352 const gcall *call,
2353 const deallocator_set *deallocators,
2354 bool returns_nonnull) const
2355 {
2356 tree lhs = gimple_call_lhs (call);
2357 if (lhs)
2358 {
2359 if (sm_ctxt.get_state (call, lhs) == m_start)
2360 sm_ctxt.set_next_state (call, lhs,
2361 (returns_nonnull
2362 ? deallocators->m_nonnull
2363 : deallocators->m_unchecked));
2364 }
2365 else
2366 {
2367 /* TODO: report leak. */
2368 }
2369 }
2370
2371 /* Handle deallocations of non-heap pointers.
2372 non-heap -> stop, with warning. */
2373
2374 void
2375 malloc_state_machine::handle_free_of_non_heap (sm_context &sm_ctxt,
2376 const supernode *node,
2377 const gcall *call,
2378 tree arg,
2379 const deallocator *d) const
2380 {
2381 tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2382 const region *freed_reg = NULL;
2383 if (const program_state *old_state = sm_ctxt.get_old_program_state ())
2384 {
2385 const region_model *old_model = old_state->m_region_model;
2386 const svalue *ptr_sval = old_model->get_rvalue (arg, NULL);
2387 freed_reg = old_model->deref_rvalue (ptr_sval, arg, NULL);
2388 }
2389 sm_ctxt.warn (node, call, arg,
2390 make_unique<free_of_non_heap>
2391 (*this, diag_arg, freed_reg, d->m_name));
2392 sm_ctxt.set_next_state (call, arg, m_stop);
2393 }
2394
2395 void
2396 malloc_state_machine::on_deallocator_call (sm_context &sm_ctxt,
2397 const supernode *node,
2398 const gcall *call,
2399 const deallocator *d,
2400 unsigned argno) const
2401 {
2402 if (argno >= gimple_call_num_args (call))
2403 return;
2404 tree arg = gimple_call_arg (call, argno);
2405
2406 state_t state = sm_ctxt.get_state (call, arg);
2407
2408 /* start/assumed_non_null/unchecked/nonnull -> freed. */
2409 if (state == m_start || assumed_non_null_p (state))
2410 sm_ctxt.set_next_state (call, arg, d->m_freed);
2411 else if (unchecked_p (state) || nonnull_p (state))
2412 {
2413 const allocation_state *astate = as_a_allocation_state (state);
2414 gcc_assert (astate->m_deallocators);
2415 if (!astate->m_deallocators->contains_p (d))
2416 {
2417 /* Wrong allocator. */
2418 tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2419 sm_ctxt.warn (node, call, arg,
2420 make_unique<mismatching_deallocation>
2421 (*this, diag_arg,
2422 astate->m_deallocators,
2423 d));
2424 }
2425 sm_ctxt.set_next_state (call, arg, d->m_freed);
2426 }
2427
2428 /* Keep state "null" as-is, rather than transitioning to "freed";
2429 we don't want to complain about double-free of NULL. */
2430 else if (state == d->m_freed)
2431 {
2432 /* freed -> stop, with warning. */
2433 tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2434 sm_ctxt.warn (node, call, arg,
2435 make_unique<double_free> (*this, diag_arg, d->m_name));
2436 sm_ctxt.set_next_state (call, arg, m_stop);
2437 }
2438 else if (state == m_non_heap)
2439 {
2440 /* non-heap -> stop, with warning. */
2441 handle_free_of_non_heap (sm_ctxt, node, call, arg, d);
2442 }
2443 }
2444
2445 /* Handle a call to "realloc".
2446 Check for free of non-heap or mismatching allocators,
2447 transitioning to the "stop" state for such cases.
2448
2449 Otherwise, kf_realloc::impl_call_post will later
2450 get called (which will handle other sm-state transitions
2451 when the state is bifurcated). */
2452
2453 void
2454 malloc_state_machine::on_realloc_call (sm_context &sm_ctxt,
2455 const supernode *node,
2456 const gcall *call) const
2457 {
2458 const unsigned argno = 0;
2459 const deallocator *d = &m_realloc;
2460
2461 tree arg = gimple_call_arg (call, argno);
2462
2463 state_t state = sm_ctxt.get_state (call, arg);
2464
2465 if (unchecked_p (state) || nonnull_p (state))
2466 {
2467 const allocation_state *astate = as_a_allocation_state (state);
2468 gcc_assert (astate->m_deallocators);
2469 if (!astate->m_deallocators->contains_p (&m_free.m_deallocator))
2470 {
2471 /* Wrong allocator. */
2472 tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2473 sm_ctxt.warn (node, call, arg,
2474 make_unique<mismatching_deallocation>
2475 (*this, diag_arg,
2476 astate->m_deallocators, d));
2477 sm_ctxt.set_next_state (call, arg, m_stop);
2478 if (path_context *path_ctxt = sm_ctxt.get_path_context ())
2479 path_ctxt->terminate_path ();
2480 }
2481 }
2482 else if (state == m_free.m_deallocator.m_freed)
2483 {
2484 /* freed -> stop, with warning. */
2485 tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2486 sm_ctxt.warn (node, call, arg,
2487 make_unique<double_free> (*this, diag_arg, "free"));
2488 sm_ctxt.set_next_state (call, arg, m_stop);
2489 if (path_context *path_ctxt = sm_ctxt.get_path_context ())
2490 path_ctxt->terminate_path ();
2491 }
2492 else if (state == m_non_heap)
2493 {
2494 /* non-heap -> stop, with warning. */
2495 handle_free_of_non_heap (sm_ctxt, node, call, arg, d);
2496 if (path_context *path_ctxt = sm_ctxt.get_path_context ())
2497 path_ctxt->terminate_path ();
2498 }
2499 }
2500
2501 /* Implementation of state_machine::on_phi vfunc for malloc_state_machine. */
2502
2503 void
2504 malloc_state_machine::on_phi (sm_context &sm_ctxt,
2505 const supernode *node ATTRIBUTE_UNUSED,
2506 const gphi *phi,
2507 tree rhs) const
2508 {
2509 if (zerop (rhs))
2510 {
2511 tree lhs = gimple_phi_result (phi);
2512 on_zero_assignment (sm_ctxt, phi, lhs);
2513 }
2514 }
2515
2516 /* Implementation of state_machine::on_condition vfunc for malloc_state_machine.
2517 Potentially transition state 'unchecked' to 'nonnull' or to 'null'. */
2518
2519 void
2520 malloc_state_machine::on_condition (sm_context &sm_ctxt,
2521 const supernode *node ATTRIBUTE_UNUSED,
2522 const gimple *stmt,
2523 const svalue *lhs,
2524 enum tree_code op,
2525 const svalue *rhs) const
2526 {
2527 if (!rhs->all_zeroes_p ())
2528 return;
2529
2530 if (!any_pointer_p (lhs))
2531 return;
2532 if (!any_pointer_p (rhs))
2533 return;
2534
2535 if (op == NE_EXPR)
2536 {
2537 log ("got 'ARG != 0' match");
2538 state_t s = sm_ctxt.get_state (stmt, lhs);
2539 if (unchecked_p (s))
2540 {
2541 const allocation_state *astate = as_a_allocation_state (s);
2542 sm_ctxt.set_next_state (stmt, lhs, astate->get_nonnull ());
2543 }
2544 }
2545 else if (op == EQ_EXPR)
2546 {
2547 log ("got 'ARG == 0' match");
2548 state_t s = sm_ctxt.get_state (stmt, lhs);
2549 if (unchecked_p (s))
2550 sm_ctxt.set_next_state (stmt, lhs, m_null);
2551 }
2552 }
2553
2554 /* Implementation of state_machine::on_pop_frame vfunc for malloc_state_machine.
2555 Clear any "assumed-non-null" state where the assumption happened in
2556 FRAME_REG. */
2557
2558 void
2559 malloc_state_machine::on_pop_frame (sm_state_map *smap,
2560 const frame_region *frame_reg) const
2561 {
2562 hash_set<const svalue *> svals_to_clear;
2563 for (auto kv : *smap)
2564 {
2565 const svalue *sval = kv.first;
2566 state_t state = kv.second.m_state;
2567 if (assumed_non_null_p (state))
2568 {
2569 const assumed_non_null_state *assumed_state
2570 = (const assumed_non_null_state *)state;
2571 if (frame_reg == assumed_state->m_frame)
2572 svals_to_clear.add (sval);
2573 }
2574 }
2575 for (auto sval : svals_to_clear)
2576 smap->clear_any_state (sval);
2577 }
2578
2579 /* Implementation of state_machine::can_purge_p vfunc for malloc_state_machine.
2580 Don't allow purging of pointers in state 'unchecked' or 'nonnull'
2581 (to avoid false leak reports). */
2582
2583 bool
2584 malloc_state_machine::can_purge_p (state_t s) const
2585 {
2586 enum resource_state rs = get_rs (s);
2587 return rs != RS_UNCHECKED && rs != RS_NONNULL;
2588 }
2589
2590 /* Implementation of state_machine::on_leak vfunc for malloc_state_machine
2591 (for complaining about leaks of pointers in state 'unchecked' and
2592 'nonnull'). */
2593
2594 std::unique_ptr<pending_diagnostic>
2595 malloc_state_machine::on_leak (tree var) const
2596 {
2597 return make_unique<malloc_leak> (*this, var);
2598 }
2599
2600 /* Implementation of state_machine::reset_when_passed_to_unknown_fn_p vfunc
2601 for malloc_state_machine. */
2602
2603 bool
2604 malloc_state_machine::reset_when_passed_to_unknown_fn_p (state_t s,
2605 bool is_mutable) const
2606 {
2607 /* An on-stack ptr doesn't stop being stack-allocated when passed to an
2608 unknown fn. */
2609 if (s == m_non_heap)
2610 return false;
2611
2612 /* Otherwise, pointers passed as non-const can be freed. */
2613 return is_mutable;
2614 }
2615
2616 /* Implementation of state_machine::maybe_get_merged_states_nonequal vfunc
2617 for malloc_state_machine.
2618
2619 Support discarding "assumed-non-null" states when merging with
2620 start state. */
2621
2622 state_machine::state_t
2623 malloc_state_machine::maybe_get_merged_states_nonequal (state_t state_a,
2624 state_t state_b) const
2625 {
2626 if (assumed_non_null_p (state_a) && state_b == m_start)
2627 return m_start;
2628 if (state_a == m_start && assumed_non_null_p (state_b))
2629 return m_start;
2630 return NULL;
2631 }
2632
2633 /* Return true if calls to FNDECL are known to not affect this sm-state. */
2634
2635 bool
2636 malloc_state_machine::unaffected_by_call_p (tree fndecl)
2637 {
2638 /* A set of functions that are known to not affect allocation
2639 status, even if we haven't fully modelled the rest of their
2640 behavior yet. */
2641 static const char * const funcnames[] = {
2642 /* This array must be kept sorted. */
2643 "strsep",
2644 };
2645 const size_t count = ARRAY_SIZE (funcnames);
2646 function_set fs (funcnames, count);
2647
2648 if (fs.contains_decl_p (fndecl))
2649 return true;
2650
2651 return false;
2652 }
2653
2654 /* Shared logic for handling GIMPLE_ASSIGNs and GIMPLE_PHIs that
2655 assign zero to LHS. */
2656
2657 void
2658 malloc_state_machine::on_zero_assignment (sm_context &sm_ctxt,
2659 const gimple *stmt,
2660 tree lhs) const
2661 {
2662 state_t s = sm_ctxt.get_state (stmt, lhs);
2663 enum resource_state rs = get_rs (s);
2664 if (rs == RS_START
2665 || rs == RS_UNCHECKED
2666 || rs == RS_NONNULL
2667 || rs == RS_FREED)
2668 sm_ctxt.set_next_state (stmt, lhs, m_null);
2669 }
2670
2671 /* Special-case hook for handling realloc, for the "success with move to
2672 a new buffer" case, marking OLD_PTR_SVAL as freed and NEW_PTR_SVAL as
2673 non-null.
2674
2675 This is similar to on_deallocator_call and on_allocator_call,
2676 but the checks happen in on_realloc_call, and by splitting the states. */
2677
2678 void
2679 malloc_state_machine::
2680 on_realloc_with_move (region_model *model,
2681 sm_state_map *smap,
2682 const svalue *old_ptr_sval,
2683 const svalue *new_ptr_sval,
2684 const extrinsic_state &ext_state) const
2685 {
2686 smap->set_state (model, old_ptr_sval,
2687 m_free.m_deallocator.m_freed,
2688 NULL, ext_state);
2689
2690 smap->set_state (model, new_ptr_sval,
2691 m_free.m_nonnull,
2692 NULL, ext_state);
2693 }
2694
2695 /* Hook for get_or_create_region_for_heap_alloc for the case when we want
2696 ptr_sval to mark a newly created region as assumed non null on malloc SM. */
2697 void
2698 malloc_state_machine::transition_ptr_sval_non_null (region_model *model,
2699 sm_state_map *smap,
2700 const svalue *new_ptr_sval,
2701 const extrinsic_state &ext_state) const
2702 {
2703 smap->set_state (model, new_ptr_sval, m_free.m_nonnull, NULL, ext_state);
2704 }
2705
2706 } // anonymous namespace
2707
2708 /* Internal interface to this file. */
2709
2710 state_machine *
2711 make_malloc_state_machine (logger *logger)
2712 {
2713 return new malloc_state_machine (logger);
2714 }
2715
2716 /* Specialcase hook for handling realloc, for use by
2717 kf_realloc::impl_call_post::success_with_move::update_model. */
2718
2719 void
2720 region_model::on_realloc_with_move (const call_details &cd,
2721 const svalue *old_ptr_sval,
2722 const svalue *new_ptr_sval)
2723 {
2724 region_model_context *ctxt = cd.get_ctxt ();
2725 if (!ctxt)
2726 return;
2727 const extrinsic_state *ext_state = ctxt->get_ext_state ();
2728 if (!ext_state)
2729 return;
2730
2731 sm_state_map *smap;
2732 const state_machine *sm;
2733 unsigned sm_idx;
2734 if (!ctxt->get_malloc_map (&smap, &sm, &sm_idx))
2735 return;
2736
2737 gcc_assert (smap);
2738 gcc_assert (sm);
2739
2740 const malloc_state_machine &malloc_sm
2741 = (const malloc_state_machine &)*sm;
2742
2743 malloc_sm.on_realloc_with_move (this,
2744 smap,
2745 old_ptr_sval,
2746 new_ptr_sval,
2747 *ext_state);
2748 }
2749
2750 /* Moves ptr_sval from start to assumed non-null, for use by
2751 region_model::get_or_create_region_for_heap_alloc. */
2752 void
2753 region_model::transition_ptr_sval_non_null (region_model_context *ctxt,
2754 const svalue *ptr_sval)
2755 {
2756 if (!ctxt)
2757 return;
2758 const extrinsic_state *ext_state = ctxt->get_ext_state ();
2759 if (!ext_state)
2760 return;
2761
2762 sm_state_map *smap;
2763 const state_machine *sm;
2764 unsigned sm_idx;
2765 if (!ctxt->get_malloc_map (&smap, &sm, &sm_idx))
2766 return;
2767
2768 gcc_assert (smap);
2769 gcc_assert (sm);
2770
2771 const malloc_state_machine &malloc_sm = (const malloc_state_machine &)*sm;
2772
2773 malloc_sm.transition_ptr_sval_non_null (this, smap, ptr_sval, *ext_state);
2774 }
2775
2776 } // namespace ana
2777
2778 #endif /* #if ENABLE_ANALYZER */