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 49637 : allocation_state (const char *name, unsigned id,
120 : enum resource_state rs,
121 : const deallocator_set *deallocators,
122 : const deallocator *deallocator)
123 49637 : : state (name, id), m_rs (rs),
124 46825 : m_deallocators (deallocators),
125 46825 : 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 2812 : 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 2812 : m_frame (frame)
147 : {
148 2812 : gcc_assert (m_frame);
149 2812 : }
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 3585 : 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 3585 : 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 46605 : static inline void mark_empty (T &entry)
329 : {
330 46605 : 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 48878 : static inline bool is_empty (const T &entry)
339 : {
340 48878 : 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 708829 : bool inherited_state_p () const final override { return false; }
363 :
364 : state_machine::state_t
365 648762 : get_default_state (const svalue *sval) const final override
366 : {
367 648762 : if (sval->all_zeroes_p ())
368 48527 : return m_null;
369 600235 : if (auto *sym_ptr = sval->maybe_get_symbolic_pointer ())
370 : {
371 156409 : const region ® = sym_ptr->get_base_region ();
372 156409 : switch (reg.get_memory_space ())
373 : {
374 : default:
375 : break;
376 68202 : case MEMSPACE_CODE:
377 68202 : case MEMSPACE_GLOBALS:
378 68202 : case MEMSPACE_STACK:
379 68202 : case MEMSPACE_READONLY_DATA:
380 68202 : return m_non_heap;
381 : }
382 : }
383 532033 : 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 14410 : deallocator::deallocator (malloc_state_machine *sm,
523 : const char *name,
524 : enum wording wording)
525 14410 : : m_name (name),
526 14410 : m_wording (wording),
527 14410 : m_freed (sm->add_state ("freed", RS_FREED, nullptr, this))
528 : {
529 14410 : }
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 14340 : 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 10830 : deallocator_set::deallocator_set (malloc_state_machine *sm,
569 : enum wording wording)
570 10830 : : m_wording (wording),
571 21660 : m_unchecked (sm->add_state ("unchecked", RS_UNCHECKED, this, nullptr)),
572 10830 : m_nonnull (sm->add_state ("nonnull", RS_NONNULL, this, nullptr))
573 : {
574 10830 : }
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 10755 : standard_deallocator_set::standard_deallocator_set (malloc_state_machine *sm,
638 : const char *name,
639 : enum wording wording)
640 : : deallocator_set (sm, wording),
641 10755 : m_deallocator (sm, name, wording)
642 : {
643 10755 : }
644 :
645 : bool
646 5469 : standard_deallocator_set::contains_p (const deallocator *d) const
647 : {
648 5469 : 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 697974 : 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 8996 : as_a_allocation_state (state_machine::state_t state)
682 : {
683 8996 : gcc_assert (state->get_id () != 0);
684 8996 : return static_cast <const allocation_state *> (state);
685 : }
686 :
687 : /* Get the resource_state for STATE. */
688 :
689 : static enum resource_state
690 697974 : get_rs (state_machine::state_t state)
691 : {
692 0 : if (const allocation_state *astate = dyn_cast_allocation_state (state))
693 159289 : 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 252 : 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 42064 : 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 6546 : 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 14108 : 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 113343 : assumed_non_null_p (state_machine::state_t state)
734 : {
735 31952 : 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 6423 : malloc_diagnostic (const malloc_state_machine &sm, tree arg)
744 6423 : : m_sm (sm), m_arg (arg)
745 : {}
746 :
747 2006 : bool subclass_equal_p (const pending_diagnostic &base_other) const override
748 : {
749 2006 : return same_tree_p (m_arg, ((const malloc_diagnostic &)base_other).m_arg);
750 : }
751 :
752 : bool
753 1092 : describe_state_change (pretty_printer &pp,
754 : const evdesc::state_change &change) override
755 : {
756 1092 : if (change.m_old_state == m_sm.get_start_state ()
757 1092 : && (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 554 : pp_string (&pp, "allocated here");
761 554 : return true;
762 : }
763 538 : if (unchecked_p (change.m_old_state)
764 404 : && nonnull_p (change.m_new_state))
765 : {
766 356 : if (change.m_expr)
767 348 : 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 4462 : double_free (const malloc_state_machine &sm, tree arg, const char *funcname)
921 4462 : : malloc_diagnostic (sm, arg), m_funcname (funcname)
922 : {}
923 :
924 4495 : const char *get_kind () const final override { return "double_free"; }
925 :
926 4889 : int get_controlling_option () const final override
927 : {
928 4889 : return OPT_Wanalyzer_double_free;
929 : }
930 :
931 427 : bool emit (diagnostic_emission_context &ctxt) final override
932 : {
933 427 : auto_diagnostic_group d;
934 427 : ctxt.add_cwe (415); /* CWE-415: Double Free. */
935 427 : return ctxt.warn ("double-%qs of %qE", m_funcname, m_arg);
936 427 : }
937 :
938 : bool
939 1150 : describe_state_change (pretty_printer &pp,
940 : const evdesc::state_change &change) final override
941 : {
942 1150 : if (freed_p (change.m_new_state))
943 : {
944 872 : m_first_free_event = change.m_event_id;
945 872 : pp_printf (&pp, "first %qs here", m_funcname);
946 872 : return true;
947 : }
948 278 : 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 864 : describe_final_event (pretty_printer &pp,
967 : const evdesc::final_event &) final override
968 : {
969 864 : if (m_first_free_event.known_p ())
970 864 : 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 864 : 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 11028 : const char *get_kind () const final override { return "malloc_leak"; }
1428 :
1429 1282 : int get_controlling_option () const final override
1430 : {
1431 1282 : return OPT_Wanalyzer_malloc_leak;
1432 : }
1433 :
1434 399 : bool emit (diagnostic_emission_context &ctxt) final override
1435 : {
1436 : /* "CWE-401: Missing Release of Memory after Effective Lifetime". */
1437 399 : ctxt.add_cwe (401);
1438 399 : if (m_arg)
1439 366 : return ctxt.warn ("leak of %qE", m_arg);
1440 : else
1441 33 : return ctxt.warn ("leak of %qs", "<unknown>");
1442 : }
1443 :
1444 : bool
1445 976 : describe_state_change (pretty_printer &pp,
1446 : const evdesc::state_change &change) final override
1447 : {
1448 976 : if (unchecked_p (change.m_new_state)
1449 976 : || (start_p (change.m_old_state) && nonnull_p (change.m_new_state)))
1450 : {
1451 776 : m_alloc_event = change.m_event_id;
1452 776 : pp_string (&pp, "allocated here");
1453 776 : return true;
1454 : }
1455 200 : return malloc_diagnostic::describe_state_change (pp, change);
1456 : }
1457 :
1458 : bool
1459 794 : describe_final_event (pretty_printer &pp,
1460 : const evdesc::final_event &ev) final override
1461 : {
1462 794 : if (ev.m_expr)
1463 : {
1464 728 : if (m_alloc_event.known_p ())
1465 728 : 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 794 : return true;
1483 : }
1484 :
1485 : const program_state *
1486 399 : get_final_state () const final override
1487 : {
1488 399 : 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 62 : free_of_non_heap (const malloc_state_machine &sm, tree arg,
1500 : const region *freed_reg,
1501 : const char *funcname)
1502 62 : : malloc_diagnostic (sm, arg), m_freed_reg (freed_reg), m_funcname (funcname)
1503 : {
1504 : }
1505 :
1506 1244 : const char *get_kind () const final override { return "free_of_non_heap"; }
1507 :
1508 42 : bool subclass_equal_p (const pending_diagnostic &base_other) const
1509 : final override
1510 : {
1511 42 : const free_of_non_heap &other = (const free_of_non_heap &)base_other;
1512 42 : return (same_tree_p (m_arg, other.m_arg)
1513 42 : && m_freed_reg == other.m_freed_reg);
1514 : }
1515 :
1516 104 : int get_controlling_option () const final override
1517 : {
1518 104 : return OPT_Wanalyzer_free_of_non_heap;
1519 : }
1520 :
1521 42 : bool emit (diagnostic_emission_context &ctxt) final override
1522 : {
1523 42 : auto_diagnostic_group d;
1524 42 : ctxt.add_cwe (590); /* CWE-590: Free of Memory not on the Heap. */
1525 42 : switch (get_memory_space ())
1526 : {
1527 0 : default:
1528 0 : case MEMSPACE_HEAP:
1529 0 : gcc_unreachable ();
1530 11 : case MEMSPACE_UNKNOWN:
1531 11 : case MEMSPACE_CODE:
1532 11 : case MEMSPACE_GLOBALS:
1533 11 : case MEMSPACE_READONLY_DATA:
1534 11 : return ctxt.warn ("%qs of %qE which points to memory"
1535 : " not on the heap",
1536 11 : m_funcname, m_arg);
1537 31 : break;
1538 31 : case MEMSPACE_STACK:
1539 31 : return ctxt.warn ("%qs of %qE which points to memory"
1540 : " on the stack",
1541 31 : m_funcname, m_arg);
1542 42 : break;
1543 : }
1544 42 : }
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 84 : describe_final_event (pretty_printer &pp,
1556 : const evdesc::final_event &) final override
1557 : {
1558 84 : pp_printf (&pp, "call to %qs here", m_funcname);
1559 84 : return true;
1560 : }
1561 :
1562 84 : void mark_interesting_stuff (interesting_t *interest) final override
1563 : {
1564 84 : if (m_freed_reg)
1565 84 : interest->add_region_creation (m_freed_reg);
1566 84 : }
1567 :
1568 : private:
1569 42 : enum memory_space get_memory_space () const
1570 : {
1571 42 : if (m_freed_reg)
1572 42 : return m_freed_reg->get_memory_space ();
1573 : else
1574 : return MEMSPACE_UNKNOWN;
1575 : }
1576 :
1577 : const region *m_freed_reg;
1578 : const char *m_funcname;
1579 : };
1580 :
1581 : /* Concrete pending_diagnostic subclass for -Wanalyzer-deref-before-check. */
1582 :
1583 0 : class deref_before_check : public malloc_diagnostic
1584 : {
1585 : public:
1586 158 : deref_before_check (const malloc_state_machine &sm, tree arg)
1587 : : malloc_diagnostic (sm, arg),
1588 158 : m_deref_enode (nullptr),
1589 158 : m_deref_expr (nullptr),
1590 158 : m_check_enode (nullptr)
1591 : {
1592 158 : gcc_assert (arg);
1593 158 : }
1594 :
1595 1592 : const char *get_kind () const final override { return "deref_before_check"; }
1596 :
1597 228 : int get_controlling_option () const final override
1598 : {
1599 228 : return OPT_Wanalyzer_deref_before_check;
1600 : }
1601 :
1602 125 : bool emit (diagnostic_emission_context &ctxt) final override
1603 : {
1604 125 : LOG_SCOPE (ctxt.get_logger ());
1605 125 : logger *logger = ctxt.get_logger ();
1606 :
1607 : /* Don't emit the warning if we can't show where the deref
1608 : and the check occur. */
1609 125 : if (!m_deref_enode)
1610 : {
1611 0 : if (logger)
1612 0 : logger->log ("rejecting: no deref enode");
1613 : return false;
1614 : }
1615 125 : if (!m_check_enode)
1616 : {
1617 0 : if (logger)
1618 0 : logger->log ("rejecting: no check enode");
1619 : return false;
1620 : }
1621 : /* Only emit the warning for intraprocedural cases. */
1622 125 : const program_point &deref_point = m_deref_enode->get_point ();
1623 125 : const program_point &check_point = m_check_enode->get_point ();
1624 :
1625 125 : if (!program_point::effectively_intraprocedural_p (deref_point,
1626 : check_point))
1627 : {
1628 14 : if (logger)
1629 0 : logger->log ("rejecting: not effectively intraprocedural");
1630 : return false;
1631 : }
1632 :
1633 : /* Reject the warning if the check occurs within a macro definition.
1634 : This avoids false positives for such code as:
1635 :
1636 : #define throw_error \
1637 : do { \
1638 : if (p) \
1639 : cleanup (p); \
1640 : return; \
1641 : } while (0)
1642 :
1643 : if (p->idx >= n)
1644 : throw_error ();
1645 :
1646 : where the usage of "throw_error" implicitly adds a check
1647 : on 'p'.
1648 :
1649 : We do warn when the check is in a macro expansion if we can get
1650 : at the location of the condition and it is't part of the
1651 : definition, so that we warn for checks such as:
1652 : if (words[0][0] == '@')
1653 : return;
1654 : g_assert(words[0] != NULL); <--- here
1655 : Unfortunately we don't have locations for individual gimple
1656 : arguments, so in:
1657 : g_assert (ptr);
1658 : we merely have a gimple_cond
1659 : if (p_2(D) == 0B)
1660 : with no way of getting at the location of the condition separately
1661 : from that of the gimple_cond (where the "if" is within the macro
1662 : definition). We reject the warning for such cases.
1663 :
1664 : We do warn when the *deref* occurs in a macro, since this can be
1665 : a source of real bugs; see e.g. PR 77425. */
1666 111 : location_t check_loc = m_check_enode->get_point ().get_location ();
1667 111 : if (linemap_location_from_macro_definition_p (line_table, check_loc))
1668 : {
1669 10 : if (logger)
1670 0 : logger->log ("rejecting: check occurs within macro definition");
1671 : return false;
1672 : }
1673 :
1674 : /* Reject warning if the check is in a loop header within a
1675 : macro expansion. This rejects cases like:
1676 : | deref of x;
1677 : | [...snip...]
1678 : | FOR_EACH(x) {
1679 : | [...snip...]
1680 : | }
1681 : where the FOR_EACH macro tests for non-nullness of x, since
1682 : the user is hoping to encapsulate the details of iteration
1683 : in the macro, and the extra check on the first iteration
1684 : would just be noise if we reported it. */
1685 101 : if (loop_header_p (m_check_enode->get_point ())
1686 101 : && linemap_location_from_macro_expansion_p (line_table, check_loc))
1687 : {
1688 0 : if (logger)
1689 0 : logger->log
1690 0 : ("rejecting: check occurs in loop header macro expansion");
1691 : return false;
1692 : }
1693 :
1694 : /* Reject if m_deref_expr is sufficiently different from m_arg
1695 : for cases where the dereference is spelled differently from
1696 : the check, which is probably two different ways to get the
1697 : same svalue, and thus not worth reporting. */
1698 101 : if (!m_deref_expr)
1699 : {
1700 18 : if (logger)
1701 0 : logger->log ("rejecting: no deref_expr");
1702 : return false;
1703 : }
1704 83 : if (!sufficiently_similar_p (m_deref_expr, m_arg))
1705 : {
1706 5 : if (logger)
1707 0 : logger->log ("rejecting: not sufficiently similar to arg");
1708 : return false;
1709 : }
1710 :
1711 : /* Reject the warning if the deref's BB doesn't dominate that
1712 : of the check, so that we don't warn e.g. for shared cleanup
1713 : code that checks a pointer for NULL, when that code is sometimes
1714 : used before a deref and sometimes after.
1715 : Using the dominance code requires setting cfun. */
1716 156 : auto_cfun sentinel (m_deref_enode->get_function ());
1717 78 : calculate_dominance_info (CDI_DOMINATORS);
1718 78 : if (!dominated_by_p (CDI_DOMINATORS,
1719 78 : m_check_enode->get_supernode ()->m_bb,
1720 78 : m_deref_enode->get_supernode ()->m_bb))
1721 : {
1722 8 : if (logger)
1723 0 : logger->log ("rejecting: deref doesn't dominate the check");
1724 : return false;
1725 : }
1726 :
1727 70 : return ctxt.warn ("check of %qE for NULL after already"
1728 : " dereferencing it",
1729 70 : m_arg);
1730 125 : }
1731 :
1732 : bool
1733 195 : describe_state_change (pretty_printer &pp,
1734 : const evdesc::state_change &change) final override
1735 : {
1736 195 : if (change.m_old_state == m_sm.get_start_state ()
1737 195 : && assumed_non_null_p (change.m_new_state))
1738 : {
1739 195 : m_first_deref_event = change.m_event_id;
1740 195 : m_deref_enode = change.m_event.get_exploded_node ();
1741 195 : m_deref_expr = change.m_expr;
1742 195 : pp_printf (&pp,
1743 : "pointer %qE is dereferenced here",
1744 : m_arg);
1745 195 : return true;
1746 : }
1747 0 : return malloc_diagnostic::describe_state_change (pp, change);
1748 : }
1749 :
1750 : bool
1751 195 : describe_final_event (pretty_printer &pp,
1752 : const evdesc::final_event &ev) final override
1753 : {
1754 195 : m_check_enode = ev.m_event.get_exploded_node ();
1755 195 : if (m_first_deref_event.known_p ())
1756 195 : pp_printf (&pp,
1757 : "pointer %qE is checked for NULL here but"
1758 : " it was already dereferenced at %@",
1759 : m_arg, &m_first_deref_event);
1760 : else
1761 0 : pp_printf (&pp,
1762 : "pointer %qE is checked for NULL here but"
1763 : " it was already dereferenced",
1764 : m_arg);
1765 195 : return true;
1766 : }
1767 :
1768 : private:
1769 101 : static bool loop_header_p (const program_point &point)
1770 : {
1771 101 : const supernode *snode = point.get_supernode ();
1772 101 : if (!snode)
1773 : return false;
1774 433 : for (auto in_edge : snode->m_bb->preds)
1775 130 : if (in_edge->flags & EDGE_DFS_BACK)
1776 : return true;
1777 : return false;
1778 : }
1779 :
1780 83 : static bool sufficiently_similar_p (tree expr_a, tree expr_b)
1781 : {
1782 83 : auto pp_a = global_dc->clone_printer ();
1783 83 : auto pp_b = global_dc->clone_printer ();
1784 83 : pp_printf (pp_a.get (), "%qE", expr_a);
1785 83 : pp_printf (pp_b.get (), "%qE", expr_b);
1786 83 : bool result = (strcmp (pp_formatted_text (pp_a.get ()),
1787 : pp_formatted_text (pp_b.get ()))
1788 83 : == 0);
1789 166 : return result;
1790 83 : }
1791 :
1792 : diagnostics::paths::event_id_t m_first_deref_event;
1793 : const exploded_node *m_deref_enode;
1794 : tree m_deref_expr;
1795 : const exploded_node *m_check_enode;
1796 : };
1797 :
1798 : /* struct allocation_state : public state_machine::state. */
1799 :
1800 : /* Implementation of state_machine::state::dump_to_pp vfunc
1801 : for allocation_state: append the API that this allocation is
1802 : associated with. */
1803 :
1804 : void
1805 118 : allocation_state::dump_to_pp (pretty_printer *pp) const
1806 : {
1807 118 : state_machine::state::dump_to_pp (pp);
1808 118 : if (m_deallocators)
1809 : {
1810 14 : pp_string (pp, " (");
1811 14 : m_deallocators->dump_to_pp (pp);
1812 14 : pp_character (pp, ')');
1813 : }
1814 118 : }
1815 :
1816 : /* Given a allocation_state for a deallocator_set, get the "nonnull" state
1817 : for the corresponding allocator(s). */
1818 :
1819 : const allocation_state *
1820 1575 : allocation_state::get_nonnull () const
1821 : {
1822 1575 : gcc_assert (m_deallocators);
1823 1575 : return as_a_allocation_state (m_deallocators->m_nonnull);
1824 : }
1825 :
1826 : /* struct assumed_non_null_state : public allocation_state. */
1827 :
1828 : void
1829 70 : assumed_non_null_state::dump_to_pp (pretty_printer *pp) const
1830 : {
1831 70 : allocation_state::dump_to_pp (pp);
1832 70 : pp_string (pp, " (in ");
1833 70 : m_frame->dump_to_pp (pp, true);
1834 70 : pp_character (pp, ')');
1835 70 : }
1836 :
1837 : /* malloc_state_machine's ctor. */
1838 :
1839 3585 : malloc_state_machine::malloc_state_machine (logger *logger)
1840 : : state_machine ("malloc", logger),
1841 3585 : m_free (this, "free", WORDING_FREED),
1842 3585 : m_scalar_delete (this, "delete", WORDING_DELETED),
1843 3585 : m_vector_delete (this, "delete[]", WORDING_DELETED),
1844 7170 : m_realloc (this, "realloc", WORDING_REALLOCATED)
1845 : {
1846 3585 : gcc_assert (m_start->get_id () == 0);
1847 3585 : m_null = add_state ("null", RS_FREED, nullptr, nullptr);
1848 3585 : m_non_heap = add_state ("non-heap", RS_NON_HEAP, nullptr, nullptr);
1849 3585 : m_stop = add_state ("stop", RS_STOP, nullptr, nullptr);
1850 3585 : }
1851 :
1852 7170 : malloc_state_machine::~malloc_state_machine ()
1853 : {
1854 3585 : unsigned i;
1855 3585 : custom_deallocator_set *set;
1856 3660 : FOR_EACH_VEC_ELT (m_dynamic_sets, i, set)
1857 75 : delete set;
1858 : custom_deallocator *d;
1859 3655 : FOR_EACH_VEC_ELT (m_dynamic_deallocators, i, d)
1860 70 : delete d;
1861 7170 : }
1862 :
1863 : state_machine::state_t
1864 46825 : malloc_state_machine::add_state (const char *name, enum resource_state rs,
1865 : const deallocator_set *deallocators,
1866 : const deallocator *deallocator)
1867 : {
1868 93650 : return add_custom_state (new allocation_state (name, alloc_state_id (),
1869 : rs, deallocators,
1870 46825 : deallocator));
1871 : }
1872 :
1873 : /* If ALLOCATOR_FNDECL has any "__attribute__((malloc(FOO)))",
1874 : return a custom_deallocator_set for them, consolidating them
1875 : to ensure uniqueness of the sets.
1876 :
1877 : Return nullptr if it has no such attributes. */
1878 :
1879 : const custom_deallocator_set *
1880 27202 : malloc_state_machine::
1881 : get_or_create_custom_deallocator_set (tree allocator_fndecl)
1882 : {
1883 : /* Early rejection of decls without attributes. */
1884 27202 : tree attrs = DECL_ATTRIBUTES (allocator_fndecl);
1885 27202 : if (!attrs)
1886 : return nullptr;
1887 :
1888 : /* Otherwise, call maybe_create_custom_deallocator_set,
1889 : memoizing the result. */
1890 28072 : if (custom_deallocator_set **slot
1891 14036 : = m_custom_deallocator_set_cache.get (allocator_fndecl))
1892 11075 : return *slot;
1893 2961 : custom_deallocator_set *set
1894 2961 : = maybe_create_custom_deallocator_set (allocator_fndecl);
1895 2961 : m_custom_deallocator_set_cache.put (allocator_fndecl, set);
1896 2961 : return set;
1897 : }
1898 :
1899 : /* Given ALLOCATOR_FNDECL, a FUNCTION_DECL with attributes,
1900 : look for any "__attribute__((malloc(FOO)))" and return a
1901 : custom_deallocator_set for them, consolidating them
1902 : to ensure uniqueness of the sets.
1903 :
1904 : Return nullptr if it has no such attributes.
1905 :
1906 : Subroutine of get_or_create_custom_deallocator_set which
1907 : memoizes the result. */
1908 :
1909 : custom_deallocator_set *
1910 2961 : malloc_state_machine::
1911 : maybe_create_custom_deallocator_set (tree allocator_fndecl)
1912 : {
1913 2961 : tree attrs = DECL_ATTRIBUTES (allocator_fndecl);
1914 2961 : gcc_assert (attrs);
1915 :
1916 : /* Look for instances of __attribute__((malloc(FOO))). */
1917 2961 : auto_vec<const deallocator *> deallocator_vec;
1918 2961 : for (tree allocs = attrs;
1919 3201 : (allocs = lookup_attribute ("malloc", allocs));
1920 240 : allocs = TREE_CHAIN (allocs))
1921 : {
1922 240 : tree args = TREE_VALUE (allocs);
1923 240 : if (!args)
1924 132 : continue;
1925 108 : if (TREE_VALUE (args))
1926 : {
1927 108 : const deallocator *d
1928 108 : = get_or_create_deallocator (TREE_VALUE (args));
1929 108 : deallocator_vec.safe_push (d);
1930 : }
1931 : }
1932 :
1933 : /* If there weren't any deallocators, bail. */
1934 3049 : if (deallocator_vec.length () == 0)
1935 : return nullptr;
1936 :
1937 : /* Consolidate, so that we reuse existing deallocator_set
1938 : instances. */
1939 88 : deallocator_vec.qsort (deallocator::cmp_ptr_ptr);
1940 88 : custom_deallocator_set **slot
1941 88 : = m_custom_deallocator_set_map.get (&deallocator_vec);
1942 88 : if (slot)
1943 13 : return *slot;
1944 75 : custom_deallocator_set *set
1945 75 : = new custom_deallocator_set (this, &deallocator_vec, WORDING_DEALLOCATED);
1946 75 : m_custom_deallocator_set_map.put (&set->m_deallocator_vec, set);
1947 75 : m_dynamic_sets.safe_push (set);
1948 75 : return set;
1949 2961 : }
1950 :
1951 : /* Get the deallocator for DEALLOCATOR_FNDECL, creating it if necessary. */
1952 :
1953 : const deallocator *
1954 294 : malloc_state_machine::get_or_create_deallocator (tree deallocator_fndecl)
1955 : {
1956 294 : deallocator **slot = m_deallocator_map.get (deallocator_fndecl);
1957 294 : if (slot)
1958 214 : return *slot;
1959 :
1960 : /* Reuse "free". */
1961 80 : deallocator *d;
1962 80 : if (is_named_call_p (deallocator_fndecl, "free")
1963 71 : || is_std_named_call_p (deallocator_fndecl, "free")
1964 151 : || is_named_call_p (deallocator_fndecl, "__builtin_free"))
1965 10 : d = &m_free.m_deallocator;
1966 : else
1967 : {
1968 70 : custom_deallocator *cd
1969 : = new custom_deallocator (this, deallocator_fndecl,
1970 70 : WORDING_DEALLOCATED);
1971 70 : m_dynamic_deallocators.safe_push (cd);
1972 70 : d = cd;
1973 : }
1974 80 : m_deallocator_map.put (deallocator_fndecl, d);
1975 80 : return d;
1976 : }
1977 :
1978 : /* Get the "assumed-non-null" state for assumptions made within FRAME,
1979 : creating it if necessary. */
1980 :
1981 : state_machine::state_t
1982 8466 : malloc_state_machine::
1983 : get_or_create_assumed_non_null_state_for_frame (const frame_region *frame)
1984 : {
1985 8466 : if (state_t *slot = m_assumed_non_null.get (frame))
1986 5654 : return *slot;
1987 2812 : state_machine::state *new_state
1988 2812 : = new assumed_non_null_state ("assumed-non-null", alloc_state_id (), frame);
1989 2812 : add_custom_state (new_state);
1990 2812 : m_assumed_non_null.put (frame, new_state);
1991 2812 : return new_state;
1992 : }
1993 :
1994 : /* Try to identify the function declaration either by name or as a known malloc
1995 : builtin. */
1996 :
1997 : static bool
1998 45700 : known_allocator_p (const_tree fndecl, const gcall &call)
1999 : {
2000 : /* Either it is a function we know by name and number of arguments... */
2001 45700 : if (is_named_call_p (fndecl, "malloc", call, 1)
2002 44098 : || is_named_call_p (fndecl, "calloc", call, 2)
2003 44000 : || is_std_named_call_p (fndecl, "malloc", call, 1)
2004 43997 : || is_std_named_call_p (fndecl, "calloc", call, 2)
2005 43994 : || is_named_call_p (fndecl, "strdup", call, 1)
2006 89509 : || is_named_call_p (fndecl, "strndup", call, 2))
2007 : return true;
2008 :
2009 : /* ... or it is a builtin allocator that allocates objects freed with
2010 : __builtin_free. */
2011 43796 : if (fndecl_built_in_p (fndecl, BUILT_IN_NORMAL))
2012 20953 : switch (DECL_FUNCTION_CODE (fndecl))
2013 : {
2014 4682 : case BUILT_IN_MALLOC:
2015 4682 : case BUILT_IN_CALLOC:
2016 4682 : case BUILT_IN_STRDUP:
2017 4682 : case BUILT_IN_STRNDUP:
2018 4682 : return true;
2019 : default:
2020 : break;
2021 : }
2022 :
2023 : return false;
2024 : }
2025 :
2026 : /* If PTR's nullness is not known, transition it to the "assumed-non-null"
2027 : state for the current frame. */
2028 :
2029 : void
2030 19439 : malloc_state_machine::maybe_assume_non_null (sm_context &sm_ctxt,
2031 : tree ptr) const
2032 : {
2033 19439 : const region_model *old_model = sm_ctxt.get_old_region_model ();
2034 19439 : if (!old_model)
2035 0 : return;
2036 :
2037 19439 : tree null_ptr_cst = build_int_cst (TREE_TYPE (ptr), 0);
2038 19439 : tristate known_non_null
2039 19439 : = old_model->eval_condition (ptr, NE_EXPR, null_ptr_cst, nullptr);
2040 19439 : if (known_non_null.is_unknown ())
2041 : {
2042 : /* Cast away const-ness for cache-like operations. */
2043 8466 : malloc_state_machine *mut_this
2044 : = const_cast <malloc_state_machine *> (this);
2045 8466 : state_t next_state
2046 : = mut_this->get_or_create_assumed_non_null_state_for_frame
2047 8466 : (old_model->get_current_frame ());
2048 8466 : sm_ctxt.set_next_state (ptr, next_state);
2049 : }
2050 : }
2051 :
2052 : /* Helper method for malloc_state_machine::on_stmt. Handle a single
2053 : argument (Ith argument ARG) if it is nonnull or nonnull_if_nonzero
2054 : and size is nonzero. */
2055 :
2056 : void
2057 8126 : malloc_state_machine::handle_nonnull (sm_context &sm_ctxt,
2058 : tree fndecl,
2059 : tree arg,
2060 : unsigned i) const
2061 : {
2062 8126 : state_t state = sm_ctxt.get_state (arg);
2063 : /* Can't use a switch as the states are non-const. */
2064 : /* Do use the fndecl that caused the warning so that the
2065 : misused attributes are printed and the user not confused. */
2066 8126 : if (unchecked_p (state))
2067 : {
2068 73 : tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2069 73 : sm_ctxt.warn
2070 73 : (arg,
2071 73 : std::make_unique<possible_null_arg> (*this, diag_arg, fndecl,
2072 : i));
2073 73 : const allocation_state *astate
2074 73 : = as_a_allocation_state (state);
2075 73 : sm_ctxt.set_next_state (arg, astate->get_nonnull ());
2076 : }
2077 8053 : else if (state == m_null)
2078 : {
2079 79 : tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2080 79 : sm_ctxt.warn (arg,
2081 79 : std::make_unique<null_arg> (*this, diag_arg, fndecl, i));
2082 79 : sm_ctxt.set_next_state (arg, m_stop);
2083 : }
2084 7974 : else if (state == m_start)
2085 3728 : maybe_assume_non_null (sm_ctxt, arg);
2086 8126 : }
2087 :
2088 : /* Return true if it's valid to dereference the zero value of PTR_TYPE,
2089 : or false if we should warn on it. */
2090 :
2091 : static bool
2092 465 : zero_address_valid_p (const_tree ptr_type)
2093 : {
2094 465 : gcc_assert (POINTER_TYPE_P (ptr_type));
2095 :
2096 : /* Some targets have address spaces in which it's valid
2097 : to dereference zero. */
2098 465 : addr_space_t as = TYPE_ADDR_SPACE (TREE_TYPE (ptr_type));
2099 465 : if (!ADDR_SPACE_GENERIC_P (as)
2100 465 : && targetm.addr_space.zero_address_valid (as))
2101 : return true;
2102 :
2103 : /* Invalid. */
2104 : return false;
2105 : }
2106 :
2107 : /* Implementation of state_machine::on_stmt vfunc for malloc_state_machine. */
2108 :
2109 : bool
2110 228668 : malloc_state_machine::on_stmt (sm_context &sm_ctxt,
2111 : const gimple *stmt) const
2112 : {
2113 228668 : if (const gcall *call_stmt = dyn_cast <const gcall *> (stmt))
2114 49582 : if (tree callee_fndecl = sm_ctxt.get_fndecl_for_call (*call_stmt))
2115 : {
2116 45700 : const gcall &call = *call_stmt;
2117 :
2118 45700 : if (known_allocator_p (callee_fndecl, call))
2119 : {
2120 6586 : on_allocator_call (sm_ctxt, call, &m_free);
2121 6586 : return true;
2122 : }
2123 :
2124 39114 : if (!is_placement_new_p (call))
2125 : {
2126 78204 : bool returns_nonnull = !TREE_NOTHROW (callee_fndecl)
2127 39102 : && flag_exceptions;
2128 39102 : if (is_named_call_p (callee_fndecl, "operator new"))
2129 189 : on_allocator_call (sm_ctxt, call,
2130 : &m_scalar_delete, returns_nonnull);
2131 38913 : else if (is_named_call_p (callee_fndecl, "operator new []"))
2132 42 : on_allocator_call (sm_ctxt, call,
2133 : &m_vector_delete, returns_nonnull);
2134 : }
2135 :
2136 39114 : if (is_named_call_p (callee_fndecl, "operator delete", call, 1)
2137 39114 : || is_named_call_p (callee_fndecl, "operator delete", call, 2))
2138 : {
2139 377 : on_deallocator_call (sm_ctxt, call,
2140 : &m_scalar_delete.m_deallocator, 0);
2141 377 : return true;
2142 : }
2143 38737 : else if (is_named_call_p (callee_fndecl, "operator delete []", call, 1))
2144 : {
2145 36 : on_deallocator_call (sm_ctxt, call,
2146 : &m_vector_delete.m_deallocator, 0);
2147 36 : return true;
2148 : }
2149 :
2150 38701 : if (is_named_call_p (callee_fndecl, "alloca", call, 1)
2151 38701 : || is_named_call_p (callee_fndecl, "__builtin_alloca", call, 1))
2152 : {
2153 157 : tree lhs = gimple_call_lhs (&call);
2154 157 : if (lhs)
2155 157 : sm_ctxt.on_transition (lhs, m_start, m_non_heap);
2156 : return true;
2157 : }
2158 :
2159 38544 : if (is_named_call_p (callee_fndecl, "free", call, 1)
2160 36196 : || is_std_named_call_p (callee_fndecl, "free", call, 1)
2161 74734 : || is_named_call_p (callee_fndecl, "__builtin_free", call, 1))
2162 : {
2163 11052 : on_deallocator_call (sm_ctxt, call,
2164 : &m_free.m_deallocator, 0);
2165 11052 : return true;
2166 : }
2167 :
2168 27492 : if (is_named_call_p (callee_fndecl, "realloc", call, 2)
2169 27221 : || is_std_named_call_p (callee_fndecl, "realloc", call, 2)
2170 54713 : || is_named_call_p (callee_fndecl, "__builtin_realloc", call, 2))
2171 : {
2172 282 : on_realloc_call (sm_ctxt, call);
2173 282 : return true;
2174 : }
2175 :
2176 27210 : if (unaffected_by_call_p (callee_fndecl))
2177 : return true;
2178 :
2179 : /* Cast away const-ness for cache-like operations. */
2180 27202 : malloc_state_machine *mutable_this
2181 : = const_cast <malloc_state_machine *> (this);
2182 :
2183 : /* Handle interesting attributes of the callee_fndecl,
2184 : or prioritize those of the builtin that callee_fndecl is expected
2185 : to be.
2186 : Might want this to be controlled by a flag. */
2187 27202 : {
2188 27202 : tree fndecl = callee_fndecl;
2189 : /* If call is recognized as a builtin known_function, use that
2190 : builtin's function_decl. */
2191 27202 : if (const region_model *old_model = sm_ctxt.get_old_region_model ())
2192 54404 : if (const builtin_known_function *builtin_kf
2193 27202 : = old_model->get_builtin_kf (call))
2194 2244 : fndecl = builtin_kf->builtin_decl ();
2195 :
2196 : /* Handle "__attribute__((malloc(FOO)))". */
2197 54404 : if (const deallocator_set *deallocators
2198 : = mutable_this->get_or_create_custom_deallocator_set
2199 27202 : (fndecl))
2200 : {
2201 227 : tree attrs = TYPE_ATTRIBUTES (TREE_TYPE (fndecl));
2202 227 : bool returns_nonnull
2203 227 : = lookup_attribute ("returns_nonnull", attrs);
2204 227 : on_allocator_call (sm_ctxt, call, deallocators, returns_nonnull);
2205 : }
2206 :
2207 : /* Check for this after nonnull, so that if we have both
2208 : then we transition to "freed", rather than "checked". */
2209 27202 : unsigned dealloc_argno = fndecl_dealloc_argno (fndecl);
2210 27202 : if (dealloc_argno != UINT_MAX)
2211 : {
2212 186 : const deallocator *d
2213 186 : = mutable_this->get_or_create_deallocator (fndecl);
2214 186 : on_deallocator_call (sm_ctxt, call, d, dealloc_argno);
2215 : }
2216 : }
2217 : }
2218 :
2219 : /* Look for pointers explicitly being compared against zero
2220 : that are in state assumed_non_null i.e. we already defererenced
2221 : them.
2222 : We have to do this check here, rather than in on_condition
2223 : because we add a constraint that the pointer is non-null when
2224 : dereferencing it, and this makes the apply_constraints_for_gcond
2225 : find known-true and known-false conditions; on_condition is only
2226 : called when adding new constraints. */
2227 210170 : if (const gcond *cond_stmt = dyn_cast <const gcond *> (stmt))
2228 : {
2229 34247 : enum tree_code op = gimple_cond_code (cond_stmt);
2230 34247 : if (op == EQ_EXPR || op == NE_EXPR)
2231 : {
2232 24611 : tree lhs = gimple_cond_lhs (cond_stmt);
2233 24611 : tree rhs = gimple_cond_rhs (cond_stmt);
2234 24611 : if (any_pointer_p (lhs)
2235 9629 : && any_pointer_p (rhs)
2236 34240 : && zerop (rhs))
2237 : {
2238 8891 : state_t state = sm_ctxt.get_state (lhs);
2239 8891 : if (assumed_non_null_p (state))
2240 173 : maybe_complain_about_deref_before_check
2241 173 : (sm_ctxt,
2242 : (const assumed_non_null_state *)state,
2243 : lhs);
2244 : }
2245 : }
2246 : }
2247 :
2248 210170 : if (tree lhs = sm_ctxt.is_zero_assignment (stmt))
2249 13483 : if (any_pointer_p (lhs))
2250 3216 : on_zero_assignment (sm_ctxt, lhs);
2251 :
2252 : /* Handle dereferences. */
2253 1868965 : for (unsigned i = 0; i < gimple_num_ops (stmt); i++)
2254 : {
2255 1658795 : tree op = gimple_op (stmt, i);
2256 1658795 : if (!op)
2257 123305 : continue;
2258 1535490 : if (TREE_CODE (op) == COMPONENT_REF)
2259 19208 : op = TREE_OPERAND (op, 0);
2260 :
2261 1535490 : if (TREE_CODE (op) == MEM_REF)
2262 : {
2263 27979 : tree arg = TREE_OPERAND (op, 0);
2264 :
2265 27979 : state_t state = sm_ctxt.get_state (arg);
2266 27979 : if (state == m_start)
2267 15711 : maybe_assume_non_null (sm_ctxt, arg);
2268 12268 : else if (unchecked_p (state))
2269 : {
2270 259 : if (!zero_address_valid_p (TREE_TYPE (arg)))
2271 : {
2272 259 : tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2273 259 : sm_ctxt.warn (arg,
2274 259 : std::make_unique<possible_null_deref> (*this,
2275 : diag_arg));
2276 259 : const allocation_state *astate = as_a_allocation_state (state);
2277 259 : sm_ctxt.set_next_state (arg, astate->get_nonnull ());
2278 : }
2279 : }
2280 12009 : else if (state == m_null)
2281 : {
2282 206 : if (!zero_address_valid_p (TREE_TYPE (arg)))
2283 : {
2284 204 : tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2285 204 : sm_ctxt.warn (arg,
2286 204 : std::make_unique<null_deref> (*this, diag_arg));
2287 204 : sm_ctxt.set_next_state (arg, m_stop);
2288 : }
2289 : }
2290 1658950 : else if (freed_p (state))
2291 : {
2292 155 : tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2293 155 : const allocation_state *astate = as_a_allocation_state (state);
2294 155 : sm_ctxt.warn (arg,
2295 : std::make_unique<use_after_free>
2296 155 : (*this, diag_arg, astate->m_deallocator));
2297 155 : sm_ctxt.set_next_state (arg, m_stop);
2298 : }
2299 : }
2300 : }
2301 : return false;
2302 : }
2303 :
2304 : /* Given a check against null of PTR in assumed-non-null state STATE,
2305 : potentially add a deref_before_check warning to SM_CTXT. */
2306 :
2307 : void
2308 173 : malloc_state_machine::
2309 : maybe_complain_about_deref_before_check (sm_context &sm_ctxt,
2310 : const assumed_non_null_state *state,
2311 : tree ptr) const
2312 : {
2313 173 : const region_model *model = sm_ctxt.get_old_region_model ();
2314 173 : if (!model)
2315 15 : return;
2316 :
2317 : /* Don't complain if the current frame (where the check is occurring) is
2318 : deeper than the frame in which the "not null" assumption was made.
2319 : This suppress false positives for cases like:
2320 :
2321 : void foo (struct s *p)
2322 : {
2323 : int val = s->some_field; // deref here
2324 : shared_helper (p);
2325 : }
2326 :
2327 : where "shared_helper" has:
2328 :
2329 : void shared_helper (struct s *p)
2330 : {
2331 : if (!p) // check here
2332 : return;
2333 : // etc
2334 : }
2335 :
2336 : since the check in "shared_helper" is OK. */
2337 173 : const frame_region *checked_in_frame = model->get_current_frame ();
2338 173 : const frame_region *assumed_nonnull_in_frame = state->m_frame;
2339 173 : if (checked_in_frame->get_index () > assumed_nonnull_in_frame->get_index ())
2340 : return;
2341 :
2342 : /* Don't complain if code was inlined from another function, to avoid
2343 : similar false positives involving shared helper functions. */
2344 166 : if (location_t loc = sm_ctxt.get_emission_location ())
2345 : {
2346 166 : inlining_info info (loc);
2347 166 : if (info.get_extra_frames () > 0)
2348 8 : return;
2349 : }
2350 :
2351 158 : tree diag_ptr = sm_ctxt.get_diagnostic_tree (ptr);
2352 158 : if (diag_ptr)
2353 158 : sm_ctxt.warn
2354 158 : (ptr,
2355 158 : std::make_unique<deref_before_check> (*this, diag_ptr));
2356 158 : sm_ctxt.set_next_state (ptr, m_stop);
2357 : }
2358 :
2359 : /* Handle a call to an allocator.
2360 : RETURNS_NONNULL is true if CALL is to a fndecl known to have
2361 : __attribute__((returns_nonnull)). */
2362 :
2363 : void
2364 7044 : malloc_state_machine::on_allocator_call (sm_context &sm_ctxt,
2365 : const gcall &call,
2366 : const deallocator_set *deallocators,
2367 : bool returns_nonnull) const
2368 : {
2369 7044 : tree lhs = gimple_call_lhs (&call);
2370 7044 : if (lhs)
2371 : {
2372 7044 : if (sm_ctxt.get_state (lhs) == m_start)
2373 7020 : sm_ctxt.set_next_state (lhs,
2374 : (returns_nonnull
2375 : ? deallocators->m_nonnull
2376 : : deallocators->m_unchecked));
2377 : }
2378 : else
2379 : {
2380 : /* TODO: report leak. */
2381 : }
2382 7044 : }
2383 :
2384 : /* Handle deallocations of non-heap pointers.
2385 : non-heap -> stop, with warning. */
2386 :
2387 : void
2388 62 : malloc_state_machine::handle_free_of_non_heap (sm_context &sm_ctxt,
2389 : const gcall &,
2390 : tree arg,
2391 : const deallocator *d) const
2392 : {
2393 62 : tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2394 62 : const region *freed_reg = nullptr;
2395 62 : if (const program_state *old_state = sm_ctxt.get_old_program_state ())
2396 : {
2397 62 : const region_model *old_model = old_state->m_region_model;
2398 62 : const svalue *ptr_sval = old_model->get_rvalue (arg, nullptr);
2399 62 : freed_reg = old_model->deref_rvalue (ptr_sval, arg, nullptr);
2400 : }
2401 62 : sm_ctxt.warn (arg,
2402 : std::make_unique<free_of_non_heap>
2403 62 : (*this, diag_arg, freed_reg, d->m_name));
2404 62 : sm_ctxt.set_next_state (arg, m_stop);
2405 62 : }
2406 :
2407 : void
2408 11651 : malloc_state_machine::on_deallocator_call (sm_context &sm_ctxt,
2409 : const gcall &call,
2410 : const deallocator *d,
2411 : unsigned argno) const
2412 : {
2413 11651 : if (argno >= gimple_call_num_args (&call))
2414 : return;
2415 11651 : tree arg = gimple_call_arg (&call, argno);
2416 :
2417 11651 : state_t state = sm_ctxt.get_state (arg);
2418 :
2419 : /* start/assumed_non_null/unchecked/nonnull -> freed. */
2420 22032 : if (state == m_start || assumed_non_null_p (state))
2421 1297 : sm_ctxt.set_next_state (arg, d->m_freed);
2422 10354 : else if (unchecked_p (state) || nonnull_p (state))
2423 : {
2424 5511 : const allocation_state *astate = as_a_allocation_state (state);
2425 5511 : gcc_assert (astate->m_deallocators);
2426 5511 : if (!astate->m_deallocators->contains_p (d))
2427 : {
2428 : /* Wrong allocator. */
2429 72 : tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2430 72 : sm_ctxt.warn (arg,
2431 : std::make_unique<mismatching_deallocation>
2432 72 : (*this, diag_arg,
2433 72 : astate->m_deallocators,
2434 : d));
2435 : }
2436 5511 : sm_ctxt.set_next_state (arg, d->m_freed);
2437 : }
2438 :
2439 : /* Keep state "null" as-is, rather than transitioning to "freed";
2440 : we don't want to complain about double-free of NULL. */
2441 4843 : else if (state == d->m_freed)
2442 : {
2443 : /* freed -> stop, with warning. */
2444 4458 : tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2445 4458 : sm_ctxt.warn (arg,
2446 4458 : std::make_unique<double_free> (*this, diag_arg, d->m_name));
2447 4458 : sm_ctxt.set_next_state (arg, m_stop);
2448 : }
2449 385 : else if (state == m_non_heap)
2450 : {
2451 : /* non-heap -> stop, with warning. */
2452 57 : handle_free_of_non_heap (sm_ctxt, call, arg, d);
2453 : }
2454 : }
2455 :
2456 : /* Handle a call to "realloc".
2457 : Check for free of non-heap or mismatching allocators,
2458 : transitioning to the "stop" state for such cases.
2459 :
2460 : Otherwise, kf_realloc::impl_call_post will later
2461 : get called (which will handle other sm-state transitions
2462 : when the state is bifurcated). */
2463 :
2464 : void
2465 282 : malloc_state_machine::on_realloc_call (sm_context &sm_ctxt,
2466 : const gcall &call) const
2467 : {
2468 282 : const unsigned argno = 0;
2469 282 : const deallocator *d = &m_realloc;
2470 :
2471 282 : tree arg = gimple_call_arg (&call, argno);
2472 :
2473 282 : state_t state = sm_ctxt.get_state (arg);
2474 :
2475 282 : if (unchecked_p (state) || nonnull_p (state))
2476 : {
2477 136 : const allocation_state *astate = as_a_allocation_state (state);
2478 136 : gcc_assert (astate->m_deallocators);
2479 136 : if (!astate->m_deallocators->contains_p (&m_free.m_deallocator))
2480 : {
2481 : /* Wrong allocator. */
2482 16 : tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2483 16 : sm_ctxt.warn (arg,
2484 : std::make_unique<mismatching_deallocation>
2485 16 : (*this, diag_arg,
2486 16 : astate->m_deallocators, d));
2487 16 : sm_ctxt.set_next_state (arg, m_stop);
2488 16 : if (path_context *path_ctxt = sm_ctxt.get_path_context ())
2489 16 : path_ctxt->terminate_path ();
2490 : }
2491 : }
2492 146 : else if (state == m_free.m_deallocator.m_freed)
2493 : {
2494 : /* freed -> stop, with warning. */
2495 4 : tree diag_arg = sm_ctxt.get_diagnostic_tree (arg);
2496 4 : sm_ctxt.warn (arg,
2497 4 : std::make_unique<double_free> (*this, diag_arg, "free"));
2498 4 : sm_ctxt.set_next_state (arg, m_stop);
2499 4 : if (path_context *path_ctxt = sm_ctxt.get_path_context ())
2500 4 : path_ctxt->terminate_path ();
2501 : }
2502 142 : else if (state == m_non_heap)
2503 : {
2504 : /* non-heap -> stop, with warning. */
2505 5 : handle_free_of_non_heap (sm_ctxt, call, arg, d);
2506 5 : if (path_context *path_ctxt = sm_ctxt.get_path_context ())
2507 5 : path_ctxt->terminate_path ();
2508 : }
2509 282 : }
2510 :
2511 : /* Implementation of state_machine::on_phi vfunc for malloc_state_machine. */
2512 :
2513 : void
2514 0 : malloc_state_machine::on_phi (sm_context &sm_ctxt,
2515 : const gphi *phi,
2516 : tree rhs) const
2517 : {
2518 0 : if (zerop (rhs))
2519 : {
2520 0 : tree lhs = gimple_phi_result (phi);
2521 0 : on_zero_assignment (sm_ctxt, lhs);
2522 : }
2523 0 : }
2524 :
2525 : void
2526 59611 : malloc_state_machine::check_call_preconditions (sm_context &sm_ctxt,
2527 : const call_details &cd) const
2528 : {
2529 59611 : tree fndecl = cd.get_fndecl_for_call ();
2530 59611 : if (!fndecl)
2531 : return;
2532 :
2533 55729 : const tree fntype = TREE_TYPE (fndecl);
2534 55729 : const unsigned num_args = cd.num_args ();
2535 :
2536 : /* Handle "__attribute__((nonnull))". */
2537 55729 : if (bitmap nonnull_args = get_nonnull_args (fntype))
2538 : {
2539 17394 : for (unsigned i = 0; i < num_args; i++)
2540 : {
2541 11091 : tree arg = cd.get_arg_tree (i);
2542 11091 : if (TREE_CODE (TREE_TYPE (arg)) != POINTER_TYPE)
2543 2327 : continue;
2544 : /* If we have a nonnull-args, and either all pointers, or
2545 : just the specified pointers. */
2546 8764 : if (bitmap_empty_p (nonnull_args)
2547 8764 : || bitmap_bit_p (nonnull_args, i))
2548 7382 : handle_nonnull (sm_ctxt, fndecl, arg, i);
2549 : }
2550 6303 : BITMAP_FREE (nonnull_args);
2551 : }
2552 :
2553 : /* Handle __attribute__((nonnull_if_nonzero (x, y))). */
2554 55729 : if (fntype)
2555 55729 : for (tree attrs = TYPE_ATTRIBUTES (fntype);
2556 57474 : (attrs = lookup_attribute ("nonnull_if_nonzero", attrs));
2557 1745 : attrs = TREE_CHAIN (attrs))
2558 : {
2559 1745 : tree args = TREE_VALUE (attrs);
2560 1745 : unsigned int idx = TREE_INT_CST_LOW (TREE_VALUE (args)) - 1;
2561 1745 : unsigned int idx2
2562 1745 : = TREE_INT_CST_LOW (TREE_VALUE (TREE_CHAIN (args))) - 1;
2563 1745 : unsigned int idx3 = idx2;
2564 1745 : if (tree chain2 = TREE_CHAIN (TREE_CHAIN (args)))
2565 162 : idx3 = TREE_INT_CST_LOW (TREE_VALUE (chain2)) - 1;
2566 1745 : if (idx < num_args
2567 : && idx2 < num_args
2568 1745 : && idx3 < num_args)
2569 : {
2570 1745 : tree arg = cd.get_arg_tree (idx);
2571 1745 : tree arg2 = cd.get_arg_tree (idx2);
2572 1745 : tree arg3 = cd.get_arg_tree (idx3);
2573 1745 : if (TREE_CODE (TREE_TYPE (arg)) != POINTER_TYPE
2574 1745 : || !INTEGRAL_TYPE_P (TREE_TYPE (arg2))
2575 1745 : || !INTEGRAL_TYPE_P (TREE_TYPE (arg3))
2576 1745 : || integer_zerop (arg2)
2577 3486 : || integer_zerop (arg3))
2578 4 : continue;
2579 1741 : if (integer_nonzerop (arg2) && integer_nonzerop (arg3))
2580 : ;
2581 : else
2582 : /* FIXME: Use ranger here to query arg2 and arg3
2583 : ranges? */
2584 997 : continue;
2585 744 : handle_nonnull (sm_ctxt, fndecl, arg, idx);
2586 : }
2587 : }
2588 : }
2589 :
2590 : /* Implementation of state_machine::on_condition vfunc for malloc_state_machine.
2591 : Potentially transition state 'unchecked' to 'nonnull' or to 'null'. */
2592 :
2593 : void
2594 30585 : malloc_state_machine::on_condition (sm_context &sm_ctxt,
2595 : const svalue *lhs,
2596 : enum tree_code op,
2597 : const svalue *rhs) const
2598 : {
2599 30585 : if (!rhs->all_zeroes_p ())
2600 : return;
2601 :
2602 19336 : if (!any_pointer_p (lhs))
2603 : return;
2604 7917 : if (!any_pointer_p (rhs))
2605 : return;
2606 :
2607 7917 : if (op == NE_EXPR)
2608 : {
2609 4301 : log ("got 'ARG != 0' match");
2610 4301 : state_t s = sm_ctxt.get_state (lhs);
2611 4301 : if (unchecked_p (s))
2612 : {
2613 1243 : const allocation_state *astate = as_a_allocation_state (s);
2614 1243 : sm_ctxt.set_next_state (lhs, astate->get_nonnull ());
2615 : }
2616 : }
2617 3616 : else if (op == EQ_EXPR)
2618 : {
2619 3616 : log ("got 'ARG == 0' match");
2620 3616 : state_t s = sm_ctxt.get_state (lhs);
2621 3616 : if (unchecked_p (s))
2622 1226 : sm_ctxt.set_next_state (lhs, m_null);
2623 : }
2624 : }
2625 :
2626 : /* Implementation of state_machine::on_pop_frame vfunc for malloc_state_machine.
2627 : Clear any "assumed-non-null" state where the assumption happened in
2628 : FRAME_REG. */
2629 :
2630 : void
2631 26997 : malloc_state_machine::on_pop_frame (sm_state_map *smap,
2632 : const frame_region *frame_reg) const
2633 : {
2634 26997 : hash_set<const svalue *> svals_to_clear;
2635 37330 : for (auto kv : *smap)
2636 : {
2637 10333 : const svalue *sval = kv.first;
2638 10333 : state_t state = kv.second.m_state;
2639 14436 : if (assumed_non_null_p (state))
2640 : {
2641 4103 : const assumed_non_null_state *assumed_state
2642 : = (const assumed_non_null_state *)state;
2643 4103 : if (frame_reg == assumed_state->m_frame)
2644 2864 : svals_to_clear.add (sval);
2645 : }
2646 : }
2647 56858 : for (auto sval : svals_to_clear)
2648 2864 : smap->clear_any_state (sval);
2649 26997 : }
2650 :
2651 : /* Implementation of state_machine::can_purge_p vfunc for malloc_state_machine.
2652 : Don't allow purging of pointers in state 'unchecked' or 'nonnull'
2653 : (to avoid false leak reports). */
2654 :
2655 : bool
2656 518445 : malloc_state_machine::can_purge_p (state_t s) const
2657 : {
2658 518445 : enum resource_state rs = get_rs (s);
2659 518445 : return rs != RS_UNCHECKED && rs != RS_NONNULL;
2660 : }
2661 :
2662 : /* Implementation of state_machine::on_leak vfunc for malloc_state_machine
2663 : (for complaining about leaks of pointers in state 'unchecked' and
2664 : 'nonnull'). */
2665 :
2666 : std::unique_ptr<pending_diagnostic>
2667 883 : malloc_state_machine::on_leak (tree var,
2668 : const program_state *,
2669 : const program_state *new_state) const
2670 : {
2671 883 : return std::make_unique<malloc_leak> (*this, var, new_state);
2672 : }
2673 :
2674 : /* Implementation of state_machine::reset_when_passed_to_unknown_fn_p vfunc
2675 : for malloc_state_machine. */
2676 :
2677 : bool
2678 27536 : malloc_state_machine::reset_when_passed_to_unknown_fn_p (state_t s,
2679 : bool is_mutable) const
2680 : {
2681 : /* An on-stack ptr doesn't stop being stack-allocated when passed to an
2682 : unknown fn. */
2683 27536 : if (s == m_non_heap)
2684 0 : return false;
2685 :
2686 : /* Otherwise, pointers passed as non-const can be freed. */
2687 : return is_mutable;
2688 : }
2689 :
2690 : /* Implementation of state_machine::maybe_get_merged_states_nonequal vfunc
2691 : for malloc_state_machine.
2692 :
2693 : Support discarding "assumed-non-null" states when merging with
2694 : start state. */
2695 :
2696 : state_machine::state_t
2697 61972 : malloc_state_machine::maybe_get_merged_states_nonequal (state_t state_a,
2698 : state_t state_b) const
2699 : {
2700 61972 : if (assumed_non_null_p (state_a) && state_b == m_start)
2701 : return m_start;
2702 78790 : if (state_a == m_start && assumed_non_null_p (state_b))
2703 5951 : return m_start;
2704 : return nullptr;
2705 : }
2706 :
2707 : /* Return true if calls to FNDECL are known to not affect this sm-state. */
2708 :
2709 : bool
2710 27210 : malloc_state_machine::unaffected_by_call_p (tree fndecl)
2711 : {
2712 : /* A set of functions that are known to not affect allocation
2713 : status, even if we haven't fully modelled the rest of their
2714 : behavior yet. */
2715 27210 : static const char * const funcnames[] = {
2716 : /* This array must be kept sorted. */
2717 : "strsep",
2718 : };
2719 27210 : const size_t count = ARRAY_SIZE (funcnames);
2720 27210 : function_set fs (funcnames, count);
2721 :
2722 27210 : if (fs.contains_decl_p (fndecl))
2723 : return true;
2724 :
2725 : return false;
2726 : }
2727 :
2728 : /* Shared logic for handling GIMPLE_ASSIGNs and GIMPLE_PHIs that
2729 : assign zero to LHS. */
2730 :
2731 : void
2732 3216 : malloc_state_machine::on_zero_assignment (sm_context &sm_ctxt,
2733 : tree lhs) const
2734 : {
2735 3216 : state_t s = sm_ctxt.get_state (lhs);
2736 3216 : enum resource_state rs = get_rs (s);
2737 3216 : if (rs == RS_START
2738 3216 : || rs == RS_UNCHECKED
2739 : || rs == RS_NONNULL
2740 166 : || rs == RS_FREED)
2741 3204 : sm_ctxt.set_next_state (lhs, m_null);
2742 3216 : }
2743 :
2744 : /* Special-case hook for handling realloc, for the "success with move to
2745 : a new buffer" case, marking OLD_PTR_SVAL as freed and NEW_PTR_SVAL as
2746 : non-null.
2747 :
2748 : This is similar to on_deallocator_call and on_allocator_call,
2749 : but the checks happen in on_realloc_call, and by splitting the states. */
2750 :
2751 : void
2752 257 : malloc_state_machine::
2753 : on_realloc_with_move (region_model *model,
2754 : sm_state_map *smap,
2755 : const svalue *old_ptr_sval,
2756 : const svalue *new_ptr_sval,
2757 : const extrinsic_state &ext_state) const
2758 : {
2759 257 : smap->set_state (model, old_ptr_sval,
2760 257 : m_free.m_deallocator.m_freed,
2761 : nullptr, ext_state);
2762 :
2763 257 : smap->set_state (model, new_ptr_sval,
2764 257 : m_free.m_nonnull,
2765 : nullptr, ext_state);
2766 257 : }
2767 :
2768 : /* Hook for get_or_create_region_for_heap_alloc for the case when we want
2769 : ptr_sval to mark a newly created region as assumed non null on malloc SM. */
2770 : void
2771 0 : malloc_state_machine::transition_ptr_sval_non_null (region_model *model,
2772 : sm_state_map *smap,
2773 : const svalue *new_ptr_sval,
2774 : const extrinsic_state &ext_state) const
2775 : {
2776 0 : smap->set_state (model, new_ptr_sval, m_free.m_nonnull, nullptr, ext_state);
2777 0 : }
2778 :
2779 : static enum custom_sarif_properties::state_graphs::node::dynalloc_state_t
2780 44 : get_dynalloc_state_for_state (enum resource_state rs)
2781 : {
2782 44 : switch (rs)
2783 : {
2784 0 : default:
2785 0 : gcc_unreachable ();
2786 : case RS_START:
2787 : case RS_NULL:
2788 : case RS_NON_HEAP:
2789 : case RS_STOP:
2790 : return state_node_properties::dynalloc_state_t::unknown;
2791 :
2792 : case RS_ASSUMED_NON_NULL:
2793 : return state_node_properties::dynalloc_state_t::nonnull;
2794 :
2795 : case RS_UNCHECKED:
2796 : return state_node_properties::dynalloc_state_t::unchecked;
2797 : case RS_NONNULL:
2798 : return state_node_properties::dynalloc_state_t::nonnull;
2799 : case RS_FREED:
2800 : return state_node_properties::dynalloc_state_t::freed;
2801 : }
2802 : }
2803 :
2804 : void
2805 44 : malloc_state_machine::
2806 : add_state_to_state_graph (analyzer_state_graph &out_state_graph,
2807 : const svalue &sval,
2808 : state_machine::state_t state) const
2809 : {
2810 44 : if (auto *sym_ptr = sval.maybe_get_symbolic_pointer ())
2811 : {
2812 44 : const region ® = sym_ptr->get_base_region ();
2813 44 : auto ®_node = out_state_graph.get_or_create_state_node (reg);
2814 44 : auto alloc_state = as_a_allocation_state (state);
2815 44 : gcc_assert (alloc_state);
2816 :
2817 44 : reg_node.set_property (state_node_properties::dynalloc_state_prop,
2818 44 : get_dynalloc_state_for_state (alloc_state->m_rs));
2819 :
2820 44 : if (alloc_state->m_deallocators)
2821 : {
2822 42 : pretty_printer pp;
2823 42 : alloc_state->m_deallocators->dump_to_pp (&pp);
2824 42 : reg_node.set_property (state_node_properties::expected_deallocators,
2825 : pp_formatted_text (&pp));
2826 42 : }
2827 44 : if (alloc_state->m_deallocator)
2828 2 : reg_node.set_property (state_node_properties::deallocator,
2829 2 : alloc_state->m_deallocator->m_name);
2830 : }
2831 44 : }
2832 :
2833 : } // anonymous namespace
2834 :
2835 : /* Internal interface to this file. */
2836 :
2837 : std::unique_ptr<state_machine>
2838 3585 : make_malloc_state_machine (logger *logger)
2839 : {
2840 3585 : return std::make_unique<malloc_state_machine> (logger);
2841 : }
2842 :
2843 : /* Specialcase hook for handling realloc, for use by
2844 : kf_realloc::impl_call_post::success_with_move::update_model. */
2845 :
2846 : void
2847 356 : region_model::on_realloc_with_move (const call_details &cd,
2848 : const svalue *old_ptr_sval,
2849 : const svalue *new_ptr_sval)
2850 : {
2851 356 : region_model_context *ctxt = cd.get_ctxt ();
2852 356 : if (!ctxt)
2853 99 : return;
2854 259 : const extrinsic_state *ext_state = ctxt->get_ext_state ();
2855 259 : if (!ext_state)
2856 : return;
2857 :
2858 257 : sm_state_map *smap;
2859 257 : const state_machine *sm;
2860 257 : unsigned sm_idx;
2861 257 : if (!ctxt->get_malloc_map (&smap, &sm, &sm_idx))
2862 : return;
2863 :
2864 257 : gcc_assert (smap);
2865 257 : gcc_assert (sm);
2866 :
2867 257 : const malloc_state_machine &malloc_sm
2868 : = (const malloc_state_machine &)*sm;
2869 :
2870 257 : malloc_sm.on_realloc_with_move (this,
2871 : smap,
2872 : old_ptr_sval,
2873 : new_ptr_sval,
2874 : *ext_state);
2875 : }
2876 :
2877 : /* Moves ptr_sval from start to assumed non-null, for use by
2878 : region_model::get_or_create_region_for_heap_alloc. */
2879 : void
2880 0 : region_model::transition_ptr_sval_non_null (region_model_context *ctxt,
2881 : const svalue *ptr_sval)
2882 : {
2883 0 : if (!ctxt)
2884 0 : return;
2885 0 : const extrinsic_state *ext_state = ctxt->get_ext_state ();
2886 0 : if (!ext_state)
2887 : return;
2888 :
2889 0 : sm_state_map *smap;
2890 0 : const state_machine *sm;
2891 0 : unsigned sm_idx;
2892 0 : if (!ctxt->get_malloc_map (&smap, &sm, &sm_idx))
2893 : return;
2894 :
2895 0 : gcc_assert (smap);
2896 0 : gcc_assert (sm);
2897 :
2898 0 : const malloc_state_machine &malloc_sm = (const malloc_state_machine &)*sm;
2899 :
2900 0 : malloc_sm.transition_ptr_sval_non_null (this, smap, ptr_sval, *ext_state);
2901 : }
2902 :
2903 : } // namespace ana
2904 :
2905 : #endif /* #if ENABLE_ANALYZER */
|