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