Line data Source code
1 : /* Classes for modeling the state of memory.
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 : #define INCLUDE_ALGORITHM
22 : #include "analyzer/common.h"
23 :
24 : #include "ordered-hash-map.h"
25 : #include "options.h"
26 : #include "cgraph.h"
27 : #include "cfg.h"
28 : #include "sbitmap.h"
29 : #include "diagnostics/event-id.h"
30 : #include "stringpool.h"
31 : #include "attribs.h"
32 : #include "tree-object-size.h"
33 : #include "gimple-ssa.h"
34 : #include "tree-phinodes.h"
35 : #include "tree-ssa-operands.h"
36 : #include "ssa-iterators.h"
37 : #include "target.h"
38 : #include "calls.h"
39 : #include "is-a.h"
40 : #include "gcc-rich-location.h"
41 : #include "gcc-urlifier.h"
42 : #include "diagnostics/sarif-sink.h"
43 : #include "tree-pretty-print.h"
44 : #include "fold-const.h"
45 : #include "selftest-tree.h"
46 : #include "context.h"
47 : #include "channels.h"
48 : #include "value-relation.h"
49 : #include "range-op.h"
50 : #include "ipa-utils.h"
51 : #include "gimple-iterator.h"
52 : #include "gimple-fold.h"
53 :
54 : #include "diagnostics/markup.h"
55 : #include "text-art/tree-widget.h"
56 :
57 : #include "analyzer/analyzer-logging.h"
58 : #include "analyzer/supergraph.h"
59 : #include "analyzer/call-string.h"
60 : #include "analyzer/program-point.h"
61 : #include "analyzer/store.h"
62 : #include "analyzer/region-model.h"
63 : #include "analyzer/constraint-manager.h"
64 : #include "analyzer/sm.h"
65 : #include "analyzer/pending-diagnostic.h"
66 : #include "analyzer/region-model-reachability.h"
67 : #include "analyzer/analyzer-selftests.h"
68 : #include "analyzer/program-state.h"
69 : #include "analyzer/call-summary.h"
70 : #include "analyzer/checker-event.h"
71 : #include "analyzer/checker-path.h"
72 : #include "analyzer/feasible-graph.h"
73 : #include "analyzer/record-layout.h"
74 : #include "analyzer/function-set.h"
75 : #include "analyzer/state-transition.h"
76 :
77 : #if ENABLE_ANALYZER
78 :
79 : namespace ana {
80 :
81 : static bool
82 : unusable_in_infinite_loop_constraint_p (const svalue *sval);
83 :
84 : /* Dump T to PP in language-independent form, for debugging/logging/dumping
85 : purposes. */
86 :
87 : void
88 17307 : dump_tree (pretty_printer *pp, tree t)
89 : {
90 17307 : dump_generic_node (pp, t, 0, TDF_SLIM, 0);
91 17307 : }
92 :
93 : /* Dump T to PP in language-independent form in quotes, for
94 : debugging/logging/dumping purposes. */
95 :
96 : void
97 413 : dump_quoted_tree (pretty_printer *pp, tree t)
98 : {
99 413 : pp_begin_quote (pp, pp_show_color (pp));
100 413 : dump_tree (pp, t);
101 413 : pp_end_quote (pp, pp_show_color (pp));
102 413 : }
103 :
104 : /* Equivalent to pp_printf (pp, "%qT", t), to avoid nesting pp_printf
105 : calls within other pp_printf calls.
106 :
107 : default_tree_printer handles 'T' and some other codes by calling
108 : dump_generic_node (pp, t, 0, TDF_SLIM, 0);
109 : dump_generic_node calls pp_printf in various places, leading to
110 : garbled output.
111 :
112 : Ideally pp_printf could be made to be reentrant, but in the meantime
113 : this function provides a workaround. */
114 :
115 : void
116 1198 : print_quoted_type (pretty_printer *pp, tree t)
117 : {
118 1198 : if (!t)
119 : return;
120 1185 : pp_begin_quote (pp, pp_show_color (pp));
121 1185 : dump_generic_node (pp, t, 0, TDF_SLIM, 0);
122 1185 : pp_end_quote (pp, pp_show_color (pp));
123 : }
124 :
125 : /* Print EXPR to PP, without quotes.
126 : For use within svalue::maybe_print_for_user
127 : and region::maybe_print_for_user. */
128 :
129 : void
130 74 : print_expr_for_user (pretty_printer *pp, tree expr)
131 : {
132 : /* Workaround for C++'s lang_hooks.decl_printable_name,
133 : which unhelpfully (for us) prefixes the decl with its
134 : type. */
135 74 : if (DECL_P (expr))
136 74 : dump_generic_node (pp, expr, 0, TDF_SLIM, 0);
137 : else
138 0 : pp_printf (pp, "%E", expr);
139 74 : }
140 :
141 : /* class region_to_value_map. */
142 :
143 : /* Assignment operator for region_to_value_map. */
144 :
145 : region_to_value_map &
146 58968 : region_to_value_map::operator= (const region_to_value_map &other)
147 : {
148 58968 : m_hash_map.empty ();
149 98410 : for (auto iter : other.m_hash_map)
150 : {
151 39442 : const region *reg = iter.first;
152 39442 : const svalue *sval = iter.second;
153 39442 : m_hash_map.put (reg, sval);
154 : }
155 58968 : return *this;
156 : }
157 :
158 : /* Equality operator for region_to_value_map. */
159 :
160 : bool
161 425546 : region_to_value_map::operator== (const region_to_value_map &other) const
162 : {
163 425546 : if (m_hash_map.elements () != other.m_hash_map.elements ())
164 : return false;
165 :
166 557450 : for (auto iter : *this)
167 : {
168 134799 : const region *reg = iter.first;
169 134799 : const svalue *sval = iter.second;
170 134799 : const svalue * const *other_slot = other.get (reg);
171 134799 : if (other_slot == nullptr)
172 33 : return false;
173 134778 : if (sval != *other_slot)
174 : return false;
175 : }
176 :
177 422651 : return true;
178 : }
179 :
180 : /* Generate a JSON value for this region_to_value_map.
181 : This is intended for debugging the analyzer rather than
182 : serialization. */
183 :
184 : std::unique_ptr<json::object>
185 4 : region_to_value_map::to_json () const
186 : {
187 4 : auto map_obj = std::make_unique<json::object> ();
188 :
189 4 : auto_vec<const region *> regs;
190 4 : for (iterator iter = begin (); iter != end (); ++iter)
191 0 : regs.safe_push ((*iter).first);
192 4 : regs.qsort (region::cmp_ptr_ptr);
193 :
194 4 : unsigned i;
195 4 : const region *reg;
196 4 : FOR_EACH_VEC_ELT (regs, i, reg)
197 : {
198 0 : label_text reg_desc = reg->get_desc ();
199 0 : const svalue *sval = *get (reg);
200 0 : map_obj->set (reg_desc.get (), sval->to_json ());
201 0 : }
202 :
203 4 : return map_obj;
204 4 : }
205 :
206 : std::unique_ptr<text_art::tree_widget>
207 720 : region_to_value_map::
208 : make_dump_widget (symbolic::node_dump_state &nds) const
209 : {
210 720 : if (is_empty ())
211 720 : return nullptr;
212 :
213 0 : std::unique_ptr<text_art::tree_widget> w
214 0 : (text_art::tree_widget::make (nds, "Dynamic Extents"));
215 :
216 0 : auto_vec<const region *> regs;
217 0 : for (iterator iter = begin (); iter != end (); ++iter)
218 0 : regs.safe_push ((*iter).first);
219 0 : regs.qsort (region::cmp_ptr_ptr);
220 :
221 0 : unsigned i;
222 0 : const region *reg;
223 0 : FOR_EACH_VEC_ELT (regs, i, reg)
224 : {
225 0 : pretty_printer the_pp;
226 0 : pretty_printer * const pp = &the_pp;
227 0 : pp_format_decoder (pp) = default_tree_printer;
228 0 : const bool simple = true;
229 :
230 0 : reg->dump_to_pp (pp, simple);
231 0 : pp_string (pp, ": ");
232 0 : const svalue *sval = *get (reg);
233 0 : sval->dump_to_pp (pp, true);
234 0 : w->add_child (text_art::tree_widget::make (nds, pp));
235 0 : }
236 0 : return w;
237 0 : }
238 :
239 : /* Attempt to merge THIS with OTHER, writing the result
240 : to OUT.
241 :
242 : For now, write (region, value) mappings that are in common between THIS
243 : and OTHER to OUT, effectively taking the intersection.
244 :
245 : Reject merger of different values. */
246 :
247 : bool
248 45249 : region_to_value_map::can_merge_with_p (const region_to_value_map &other,
249 : region_to_value_map *out) const
250 : {
251 52800 : for (auto iter : *this)
252 : {
253 10457 : const region *iter_reg = iter.first;
254 10457 : const svalue *iter_sval = iter.second;
255 10457 : const svalue * const * other_slot = other.get (iter_reg);
256 10457 : if (other_slot)
257 : {
258 10193 : if (iter_sval == *other_slot)
259 7287 : out->put (iter_reg, iter_sval);
260 : else
261 2906 : return false;
262 : }
263 : }
264 42343 : return true;
265 : }
266 :
267 : /* Purge any state involving SVAL. */
268 :
269 : void
270 24941 : region_to_value_map::purge_state_involving (const symbolic::node &node)
271 : {
272 24941 : auto_vec<const region *> to_purge;
273 40951 : for (auto iter : *this)
274 : {
275 16010 : const region *iter_reg = iter.first;
276 16010 : const svalue *iter_sval = iter.second;
277 16010 : if (iter_reg->involves_p (node) || iter_sval->involves_p (node))
278 12 : to_purge.safe_push (iter_reg);
279 : }
280 24977 : for (auto iter : to_purge)
281 12 : m_hash_map.remove (iter);
282 24941 : }
283 :
284 : // struct exception_node
285 :
286 : bool
287 16068 : exception_node::operator== (const exception_node &other) const
288 : {
289 16068 : return (m_exception_sval == other.m_exception_sval
290 15774 : && m_typeinfo_sval == other.m_typeinfo_sval
291 27566 : && m_destructor_sval == other.m_destructor_sval);
292 : }
293 :
294 : DEBUG_FUNCTION void
295 0 : exception_node::dump () const
296 : {
297 0 : symbolic::dump_node_tree_to_stderr<exception_node> (*this);
298 0 : }
299 :
300 : void
301 0 : exception_node::dump_to_logger (logger &log) const
302 : {
303 0 : symbolic::dump_node_tree_to_logger<exception_node> (*this, log);
304 0 : }
305 :
306 : std::unique_ptr<json::object>
307 0 : exception_node::to_json () const
308 : {
309 0 : auto obj = std::make_unique<json::object> ();
310 0 : obj->set ("exception", m_exception_sval->to_json ());
311 0 : obj->set ("typeinfo", m_typeinfo_sval->to_json ());
312 0 : obj->set ("destructor", m_destructor_sval->to_json ());
313 0 : return obj;
314 : }
315 :
316 : std::unique_ptr<text_art::tree_widget>
317 0 : exception_node::make_dump_widget (symbolic::node_dump_state &nds) const
318 : {
319 0 : using text_art::tree_widget;
320 0 : std::unique_ptr<tree_widget> w
321 0 : (tree_widget::from_fmt (nds, nullptr, "Exception Node"));
322 :
323 0 : w->add_child (m_exception_sval->make_dump_widget (nds, "exception"));
324 0 : w->add_child (m_typeinfo_sval->make_dump_widget (nds, "typeinfo"));
325 0 : w->add_child (m_destructor_sval->make_dump_widget (nds, "destructor"));
326 :
327 0 : return w;
328 : }
329 :
330 : tree
331 712 : exception_node::maybe_get_type () const
332 : {
333 712 : return m_typeinfo_sval->maybe_get_type_from_typeinfo ();
334 : }
335 :
336 : void
337 70 : exception_node::add_to_reachable_regions (reachable_regions ®s) const
338 : {
339 70 : regs.handle_value (*m_exception_sval);
340 70 : regs.handle_value (*m_typeinfo_sval);
341 70 : regs.handle_value (*m_destructor_sval);
342 70 : }
343 :
344 : /* class region_model. */
345 :
346 : /* Ctor for region_model: construct an "empty" model. */
347 :
348 195403 : region_model::region_model (symbolic::node_manager &node_mgr)
349 195403 : : m_node_mgr (node_mgr),
350 195403 : m_mgr (&node_mgr.get_region_model_manager ()),
351 195403 : m_store (node_mgr),
352 195403 : m_current_frame (nullptr),
353 195403 : m_thrown_exceptions_stack (),
354 195403 : m_caught_exceptions_stack (),
355 195403 : m_dynamic_extents ()
356 : {
357 195403 : m_constraints = new constraint_manager (m_mgr);
358 195403 : }
359 :
360 : /* region_model's copy ctor. */
361 :
362 2720490 : region_model::region_model (const region_model &other)
363 2720490 : : m_node_mgr (other.m_node_mgr),
364 2720490 : m_mgr (other.m_mgr),
365 2720490 : m_store (other.m_store),
366 2720490 : m_constraints (new constraint_manager (*other.m_constraints)),
367 2720490 : m_current_frame (other.m_current_frame),
368 2720490 : m_thrown_exceptions_stack (other.m_thrown_exceptions_stack),
369 2720490 : m_caught_exceptions_stack (other.m_caught_exceptions_stack),
370 2720490 : m_dynamic_extents (other.m_dynamic_extents)
371 : {
372 2720490 : }
373 :
374 : /* region_model's dtor. */
375 :
376 2915893 : region_model::~region_model ()
377 : {
378 2915893 : delete m_constraints;
379 2915893 : }
380 :
381 : /* region_model's assignment operator. */
382 :
383 : region_model &
384 58968 : region_model::operator= (const region_model &other)
385 : {
386 : /* m_mgr is const. */
387 58968 : gcc_assert (m_mgr == other.m_mgr);
388 :
389 58968 : m_store = other.m_store;
390 :
391 58968 : delete m_constraints;
392 58968 : m_constraints = new constraint_manager (*other.m_constraints);
393 :
394 58968 : m_current_frame = other.m_current_frame;
395 :
396 58968 : m_thrown_exceptions_stack = other.m_thrown_exceptions_stack;
397 58968 : m_caught_exceptions_stack = other.m_caught_exceptions_stack;
398 :
399 58968 : m_dynamic_extents = other.m_dynamic_extents;
400 :
401 58968 : return *this;
402 : }
403 :
404 : /* Equality operator for region_model.
405 :
406 : Amongst other things this directly compares the stores and the constraint
407 : managers, so for this to be meaningful both this and OTHER should
408 : have been canonicalized. */
409 :
410 : bool
411 437680 : region_model::operator== (const region_model &other) const
412 : {
413 : /* We can only compare instances that use the same manager. */
414 437680 : gcc_assert (m_mgr == other.m_mgr);
415 :
416 437680 : if (m_store != other.m_store)
417 : return false;
418 :
419 384432 : if (*m_constraints != *other.m_constraints)
420 : return false;
421 :
422 379661 : if (m_current_frame != other.m_current_frame)
423 : return false;
424 :
425 379653 : if (m_thrown_exceptions_stack != other.m_thrown_exceptions_stack)
426 : return false;
427 379653 : if (m_caught_exceptions_stack != other.m_caught_exceptions_stack)
428 : return false;
429 :
430 379653 : if (m_dynamic_extents != other.m_dynamic_extents)
431 : return false;
432 :
433 379464 : gcc_checking_assert (hash () == other.hash ());
434 :
435 : return true;
436 : }
437 :
438 : /* Generate a hash value for this region_model. */
439 :
440 : hashval_t
441 1174711 : region_model::hash () const
442 : {
443 1174711 : hashval_t result = m_store.hash ();
444 1174711 : result ^= m_constraints->hash ();
445 1174711 : return result;
446 : }
447 :
448 : /* Dump a tree-like representation of this region_model to stderr. */
449 :
450 : DEBUG_FUNCTION void
451 0 : region_model::dump () const
452 : {
453 0 : symbolic::dump_node_tree_to_stderr<region_model> (*this);
454 0 : }
455 :
456 : /* Dump a tree-like representation of this region_model to PP. */
457 :
458 : void
459 74 : region_model::dump_to_pp (pretty_printer *pp) const
460 : {
461 74 : text_art::theme *theme = global_dc->get_diagram_theme ();
462 74 : symbolic::dump_node_tree_to_pp<region_model> (*this, theme, pp, true, true);
463 74 : }
464 :
465 : /* Dump a tree-like representation of this region_model to LOG. */
466 :
467 : void
468 3 : region_model::dump_to_logger (logger &log) const
469 : {
470 3 : symbolic::dump_node_tree_to_logger<region_model> (*this, log);
471 3 : }
472 :
473 : /* Generate a JSON value for this region_model.
474 : This is intended for debugging the analyzer rather than
475 : serialization. */
476 :
477 : std::unique_ptr<json::object>
478 4 : region_model::to_json () const
479 : {
480 4 : auto model_obj = std::make_unique<json::object> ();
481 4 : model_obj->set ("store", m_store.to_json ());
482 4 : model_obj->set ("constraints", m_constraints->to_json ());
483 4 : if (m_current_frame)
484 4 : model_obj->set ("current_frame", m_current_frame->to_json ());
485 :
486 4 : auto thrown_exceptions_arr = std::make_unique<json::array> ();
487 4 : for (auto &node : m_thrown_exceptions_stack)
488 0 : thrown_exceptions_arr->append (node.to_json ());
489 4 : model_obj->set ("thrown_exception_stack", std::move (thrown_exceptions_arr));
490 :
491 4 : auto caught_exceptions_arr = std::make_unique<json::array> ();
492 4 : for (auto &node : m_caught_exceptions_stack)
493 0 : caught_exceptions_arr->append (node.to_json ());
494 4 : model_obj->set ("caught_exception_stack", std::move (caught_exceptions_arr));
495 :
496 4 : model_obj->set ("dynamic_extents", m_dynamic_extents.to_json ());
497 8 : return model_obj;
498 4 : }
499 :
500 : std::unique_ptr<text_art::tree_widget>
501 720 : region_model::make_dump_widget (symbolic::node_dump_state &nds) const
502 : {
503 720 : using text_art::tree_widget;
504 720 : std::unique_ptr<tree_widget> model_widget
505 720 : (tree_widget::from_fmt (nds, nullptr, "Region Model"));
506 :
507 720 : if (m_current_frame)
508 : {
509 693 : pretty_printer the_pp;
510 693 : pretty_printer * const pp = &the_pp;
511 693 : pp_format_decoder (pp) = default_tree_printer;
512 693 : pp_show_color (pp) = true;
513 693 : const bool simple = true;
514 :
515 693 : pp_string (pp, "Current Frame: ");
516 693 : m_current_frame->dump_to_pp (pp, simple);
517 1386 : model_widget->add_child (tree_widget::make (nds, pp));
518 693 : }
519 :
520 720 : if (m_thrown_exceptions_stack.size () > 0)
521 : {
522 0 : auto thrown_exceptions_widget
523 0 : = tree_widget::make (nds, "Thrown Exceptions");
524 0 : for (auto &thrown_exception : m_thrown_exceptions_stack)
525 0 : thrown_exceptions_widget->add_child
526 0 : (thrown_exception.make_dump_widget (nds));
527 0 : model_widget->add_child (std::move (thrown_exceptions_widget));
528 0 : }
529 720 : if (m_caught_exceptions_stack.size () > 0)
530 : {
531 0 : auto caught_exceptions_widget
532 0 : = tree_widget::make (nds, "Caught Exceptions");
533 0 : for (auto &caught_exception : m_caught_exceptions_stack)
534 0 : caught_exceptions_widget->add_child
535 0 : (caught_exception.make_dump_widget (nds));
536 0 : model_widget->add_child (std::move (caught_exceptions_widget));
537 0 : }
538 :
539 1440 : model_widget->add_child (m_store.make_dump_widget (nds));
540 1197 : model_widget->add_child (m_constraints->make_dump_widget (nds));
541 720 : model_widget->add_child (m_dynamic_extents.make_dump_widget (nds));
542 720 : return model_widget;
543 : }
544 :
545 : /* Assert that this object is valid. */
546 :
547 : void
548 1599565 : region_model::validate () const
549 : {
550 1599565 : m_store.validate ();
551 1599565 : }
552 :
553 : /* Canonicalize the store and constraints, to maximize the chance of
554 : equality between region_model instances. */
555 :
556 : void
557 781679 : region_model::canonicalize ()
558 : {
559 781679 : m_store.canonicalize ();
560 781679 : m_constraints->canonicalize ();
561 781679 : }
562 :
563 : /* Return true if this region_model is in canonical form. */
564 :
565 : bool
566 371189 : region_model::canonicalized_p () const
567 : {
568 371189 : region_model copy (*this);
569 371189 : copy.canonicalize ();
570 371189 : return *this == copy;
571 371189 : }
572 :
573 : /* See the comment for store::loop_replay_fixup. */
574 :
575 : void
576 1554 : region_model::loop_replay_fixup (const region_model *dst_state)
577 : {
578 1554 : m_store.loop_replay_fixup (dst_state->get_store (),
579 : get_baseline_state (),
580 1554 : m_mgr);
581 1554 : }
582 :
583 : /* A subclass of pending_diagnostic for complaining about pointer
584 : subtractions involving unrelated buffers. */
585 :
586 : class undefined_ptrdiff_diagnostic
587 : : public pending_diagnostic_subclass<undefined_ptrdiff_diagnostic>
588 : {
589 : public:
590 : /* Region_creation_event subclass to give a custom wording when
591 : talking about creation of buffers for LHS and RHS of the
592 : subtraction. */
593 : class ptrdiff_region_creation_event : public region_creation_event
594 : {
595 : public:
596 56 : ptrdiff_region_creation_event (const event_loc_info &loc_info,
597 : bool is_lhs)
598 : : region_creation_event (loc_info),
599 56 : m_is_lhs (is_lhs)
600 : {
601 : }
602 :
603 112 : void print_desc (pretty_printer &pp) const final override
604 : {
605 112 : if (m_is_lhs)
606 56 : pp_string (&pp,
607 : "underlying object for left-hand side"
608 : " of subtraction created here");
609 : else
610 56 : pp_string (&pp,
611 : "underlying object for right-hand side"
612 : " of subtraction created here");
613 112 : }
614 :
615 : private:
616 : bool m_is_lhs;
617 : };
618 :
619 64 : undefined_ptrdiff_diagnostic (const gassign *assign,
620 : const svalue *sval_a,
621 : const svalue *sval_b,
622 : const region *base_reg_a,
623 : const region *base_reg_b)
624 64 : : m_assign (assign),
625 64 : m_sval_a (sval_a),
626 64 : m_sval_b (sval_b),
627 64 : m_base_reg_a (base_reg_a),
628 64 : m_base_reg_b (base_reg_b)
629 : {
630 64 : gcc_assert (m_base_reg_a != m_base_reg_b);
631 : }
632 :
633 428 : const char *get_kind () const final override
634 : {
635 428 : return "undefined_ptrdiff_diagnostic";
636 : }
637 :
638 56 : bool operator== (const undefined_ptrdiff_diagnostic &other) const
639 : {
640 56 : return (m_assign == other.m_assign
641 56 : && m_sval_a == other.m_sval_a
642 56 : && m_sval_b == other.m_sval_b
643 56 : && m_base_reg_a == other.m_base_reg_a
644 112 : && m_base_reg_b == other.m_base_reg_b);
645 : }
646 :
647 84 : int get_controlling_option () const final override
648 : {
649 84 : return OPT_Wanalyzer_undefined_behavior_ptrdiff;
650 : }
651 :
652 28 : bool emit (diagnostic_emission_context &ctxt) final override
653 : {
654 : /* CWE-469: Use of Pointer Subtraction to Determine Size. */
655 28 : ctxt.add_cwe (469);
656 28 : return ctxt.warn ("undefined behavior when subtracting pointers");
657 : }
658 :
659 56 : void add_region_creation_events (const region *reg,
660 : tree /*capacity*/,
661 : const event_loc_info &loc_info,
662 : checker_path &emission_path) final override
663 : {
664 56 : if (reg == m_base_reg_a)
665 28 : emission_path.add_event
666 28 : (std::make_unique<ptrdiff_region_creation_event> (loc_info, true));
667 28 : else if (reg == m_base_reg_b)
668 28 : emission_path.add_event
669 28 : (std::make_unique<ptrdiff_region_creation_event> (loc_info, false));
670 56 : }
671 :
672 : bool
673 56 : describe_final_event (pretty_printer &pp,
674 : const evdesc::final_event &) final override
675 : {
676 56 : pp_string (&pp,
677 : "subtraction of pointers has undefined behavior if"
678 : " they do not point into the same array object");
679 56 : return true;
680 : }
681 :
682 56 : void mark_interesting_stuff (interesting_t *interesting) final override
683 : {
684 56 : interesting->add_region_creation (m_base_reg_a);
685 56 : interesting->add_region_creation (m_base_reg_b);
686 56 : }
687 :
688 : private:
689 : const gassign *m_assign;
690 : const svalue *m_sval_a;
691 : const svalue *m_sval_b;
692 : const region *m_base_reg_a;
693 : const region *m_base_reg_b;
694 : };
695 :
696 : /* Locate the parameter with the given index within FNDECL.
697 : ARGNUM is zero based, -1 indicates the `this' argument of a method.
698 : Return the location of the FNDECL itself if there are problems. */
699 :
700 : bool
701 23 : callsite_expr::maybe_get_param_location (tree fndecl,
702 : location_t *out_loc) const
703 : {
704 23 : gcc_assert (fndecl);
705 :
706 23 : if (DECL_ARTIFICIAL (fndecl))
707 : return false;
708 :
709 23 : tree param = get_param_tree (fndecl);
710 23 : if (!param)
711 : return false;
712 :
713 22 : *out_loc = DECL_SOURCE_LOCATION (param);
714 22 : return true;
715 : }
716 :
717 : /* If this callsite_expr refers to a parameter, get the PARM_DECL from
718 : FNDECL.
719 : Return NULL_TREE on any problems. */
720 :
721 : tree
722 69 : callsite_expr::get_param_tree (tree fndecl) const
723 : {
724 69 : if (!param_p ())
725 : return NULL_TREE;
726 :
727 66 : int i;
728 66 : tree param;
729 :
730 : /* Locate param by index within DECL_ARGUMENTS (fndecl). */
731 66 : for (i = 1, param = DECL_ARGUMENTS (fndecl);
732 126 : i < param_num () && param;
733 60 : i++, param = TREE_CHAIN (param))
734 : ;
735 :
736 : return param;
737 : }
738 :
739 : class div_by_zero_diagnostic
740 : : public pending_diagnostic_subclass<div_by_zero_diagnostic>
741 : {
742 : public:
743 74 : div_by_zero_diagnostic (const gassign *assign,
744 : const region *divisor_reg)
745 74 : : m_assign (assign),
746 74 : m_divisor_reg (divisor_reg)
747 : {}
748 :
749 409 : const char *get_kind () const final override
750 : {
751 409 : return "div_by_zero_diagnostic";
752 : }
753 :
754 74 : bool operator== (const div_by_zero_diagnostic &other) const
755 : {
756 74 : return m_assign == other.m_assign;
757 : }
758 :
759 107 : int get_controlling_option () const final override
760 : {
761 107 : return OPT_Wanalyzer_div_by_zero;
762 : }
763 :
764 33 : bool emit (diagnostic_emission_context &ctxt) final override
765 : {
766 33 : return ctxt.warn ("division by zero");
767 : }
768 :
769 : bool
770 66 : describe_final_event (pretty_printer &pp,
771 : const evdesc::final_event &) final override
772 : {
773 66 : pp_printf (&pp, "division by zero");
774 66 : return true;
775 : }
776 :
777 : void
778 66 : mark_interesting_stuff (interesting_t *interest) override
779 : {
780 66 : interest->add_read_region (m_divisor_reg, "divisor zero value");
781 66 : }
782 :
783 : void
784 57 : add_function_entry_event (const exploded_edge &eedge,
785 : checker_path *emission_path,
786 : const state_transition_at_call *state_trans)
787 : override
788 : {
789 0 : class custom_function_entry_event : public function_entry_event
790 : {
791 : public:
792 57 : custom_function_entry_event (const event_loc_info &loc_info,
793 : const program_state &state,
794 : const state_transition_at_call *state_trans)
795 : : function_entry_event (loc_info,
796 : state,
797 57 : state_trans)
798 : {
799 : }
800 :
801 72 : void print_desc (pretty_printer &pp) const override
802 : {
803 72 : if (auto state_trans = get_state_transition_at_call ())
804 : {
805 4 : auto expr = state_trans->get_callsite_expr ();
806 4 : if (tree parm = expr.get_param_tree (m_effective_fndecl))
807 : {
808 4 : auto src_event_id = state_trans->get_src_event_id ();
809 4 : if (src_event_id.known_p ())
810 4 : pp_printf (&pp, "entry to %qE with zero from %@ for %qE",
811 4 : m_effective_fndecl,
812 : &src_event_id,
813 : parm);
814 : else
815 0 : pp_printf (&pp, "entry to %qE with zero for %qE",
816 0 : m_effective_fndecl, parm);
817 4 : return;
818 : }
819 : }
820 68 : return function_entry_event::print_desc (pp);
821 : }
822 : };
823 :
824 57 : const exploded_node *dst_node = eedge.m_dest;
825 57 : const program_point &dst_point = dst_node->get_point ();
826 57 : const program_state &dst_state = dst_node->get_state ();
827 57 : auto loc_info {event_loc_info_for_function_entry (dst_point, state_trans)};
828 57 : emission_path->add_event
829 57 : (std::make_unique<custom_function_entry_event> (loc_info,
830 : dst_state,
831 : state_trans));
832 57 : }
833 :
834 : bool
835 44 : describe_origin_of_state (pretty_printer &pp,
836 : const evdesc::origin_of_state &) final override
837 : {
838 44 : pp_printf (&pp, "zero value originates here");
839 44 : return true;
840 : }
841 :
842 : bool
843 4 : describe_call_with_state (pretty_printer &pp,
844 : const evdesc::call_with_state &evd) final override
845 : {
846 4 : if (evd.m_state_trans)
847 : {
848 4 : callsite_expr expr = evd.m_state_trans->get_callsite_expr ();
849 4 : if (expr.param_p ())
850 : {
851 4 : if (evd.m_src_event_id.known_p ())
852 4 : pp_printf (&pp, "passing zero from %@ from %qE to %qE via parameter %i",
853 : &evd.m_src_event_id,
854 4 : evd.m_caller_fndecl,
855 4 : evd.m_callee_fndecl,
856 : expr.param_num ());
857 : else
858 0 : pp_printf (&pp, "passing zero from %qE to %qE via parameter %i",
859 0 : evd.m_caller_fndecl,
860 0 : evd.m_callee_fndecl,
861 : expr.param_num ());
862 4 : return true;
863 : }
864 : }
865 :
866 : return false;
867 : }
868 :
869 : bool
870 24 : describe_return_of_state (pretty_printer &pp,
871 : const evdesc::return_of_state &evd) final override
872 : {
873 24 : if (evd.m_src_event_id.known_p ())
874 24 : pp_printf (&pp, "returning zero from %@ from %qE here",
875 : &evd.m_src_event_id,
876 24 : evd.m_callee_fndecl);
877 : else
878 0 : pp_printf (&pp, "returning zero from %qE here",
879 0 : evd.m_callee_fndecl);
880 24 : return true;
881 : }
882 :
883 : bool
884 12 : describe_copy_of_state (pretty_printer &pp,
885 : const evdesc::copy_of_state &evd) final override
886 : {
887 12 : if (evd.m_src_event_id.known_p ())
888 12 : pp_printf (&pp, "copying zero value from %@ from %qE to %qE",
889 : &evd.m_src_event_id,
890 12 : evd.m_src_reg_expr, evd.m_dst_reg_expr);
891 : else
892 0 : pp_printf (&pp, "copying zero value from %qE to %qE",
893 0 : evd.m_src_reg_expr, evd.m_dst_reg_expr);
894 12 : return true;
895 : }
896 :
897 : bool
898 16 : describe_use_of_state (pretty_printer &pp,
899 : const evdesc::use_of_state &evd) final override
900 : {
901 16 : if (evd.m_src_event_id.known_p ())
902 8 : pp_printf (&pp, "using zero value from %@ from %qE",
903 : &evd.m_src_event_id,
904 8 : evd.m_src_reg_expr);
905 : else
906 8 : pp_printf (&pp, "using zero value from %qE",
907 8 : evd.m_src_reg_expr);
908 16 : return true;
909 : }
910 :
911 : private:
912 : const gassign *m_assign;
913 : const region *m_divisor_reg;
914 : };
915 :
916 : /* Check the pointer subtraction SVAL_A - SVAL_B at ASSIGN and add
917 : a warning to CTXT if they're not within the same base region. */
918 :
919 : static void
920 610 : check_for_invalid_ptrdiff (const gassign *assign,
921 : region_model_context &ctxt,
922 : const svalue *sval_a, const svalue *sval_b)
923 : {
924 610 : const region *base_reg_a = sval_a->maybe_get_deref_base_region ();
925 610 : if (!base_reg_a)
926 546 : return;
927 170 : const region *base_reg_b = sval_b->maybe_get_deref_base_region ();
928 170 : if (!base_reg_b)
929 : return;
930 :
931 154 : if (base_reg_a == base_reg_b)
932 : return;
933 :
934 64 : if (base_reg_a->get_kind () == RK_SYMBOLIC)
935 : return;
936 64 : if (base_reg_b->get_kind () == RK_SYMBOLIC)
937 : return;
938 :
939 64 : ctxt.warn
940 64 : (std::make_unique<undefined_ptrdiff_diagnostic> (assign,
941 : sval_a,
942 : sval_b,
943 : base_reg_a,
944 : base_reg_b));
945 : }
946 :
947 : /* If ASSIGN is a stmt that can be modelled via
948 : set_value (lhs_reg, SVALUE, CTXT)
949 : for some SVALUE, get the SVALUE.
950 : Otherwise return nullptr. */
951 :
952 : const svalue *
953 315454 : region_model::get_gassign_result (const gassign *assign,
954 : region_model_context *ctxt)
955 : {
956 315454 : tree lhs = gimple_assign_lhs (assign);
957 :
958 315454 : if (gimple_has_volatile_ops (assign)
959 315454 : && !gimple_clobber_p (assign))
960 : {
961 116 : conjured_purge p (this, ctxt);
962 116 : return m_mgr->get_or_create_conjured_svalue (TREE_TYPE (lhs),
963 : assign,
964 : get_lvalue (lhs, ctxt),
965 : p);
966 : }
967 :
968 315338 : tree rhs1 = gimple_assign_rhs1 (assign);
969 315338 : enum tree_code op = gimple_assign_rhs_code (assign);
970 315338 : switch (op)
971 : {
972 : default:
973 : return nullptr;
974 :
975 26699 : case POINTER_PLUS_EXPR:
976 26699 : {
977 : /* e.g. "_1 = a_10(D) + 12;" */
978 26699 : tree ptr = rhs1;
979 26699 : tree offset = gimple_assign_rhs2 (assign);
980 :
981 26699 : const svalue *ptr_sval = get_rvalue (ptr, ctxt);
982 26699 : const svalue *offset_sval = get_rvalue (offset, ctxt);
983 : /* Quoting tree.def, "the second operand [of a POINTER_PLUS_EXPR]
984 : is an integer of type sizetype". */
985 26699 : offset_sval = m_mgr->get_or_create_cast (size_type_node, offset_sval);
986 :
987 26699 : const svalue *sval_binop
988 26699 : = m_mgr->get_or_create_binop (TREE_TYPE (lhs), op,
989 : ptr_sval, offset_sval);
990 26699 : return sval_binop;
991 : }
992 682 : break;
993 :
994 682 : case POINTER_DIFF_EXPR:
995 682 : {
996 : /* e.g. "_1 = p_2(D) - q_3(D);". */
997 682 : tree rhs2 = gimple_assign_rhs2 (assign);
998 682 : const svalue *rhs1_sval = get_rvalue (rhs1, ctxt);
999 682 : const svalue *rhs2_sval = get_rvalue (rhs2, ctxt);
1000 :
1001 : // TODO: perhaps fold to zero if they're known to be equal?
1002 :
1003 682 : if (ctxt)
1004 610 : check_for_invalid_ptrdiff (assign, *ctxt, rhs1_sval, rhs2_sval);
1005 :
1006 682 : const svalue *sval_binop
1007 682 : = m_mgr->get_or_create_binop (TREE_TYPE (lhs), op,
1008 : rhs1_sval, rhs2_sval);
1009 682 : return sval_binop;
1010 : }
1011 174668 : break;
1012 :
1013 : /* Assignments of the form
1014 : set_value (lvalue (LHS), rvalue (EXPR))
1015 : for various EXPR.
1016 : We already have the lvalue for the LHS above, as "lhs_reg". */
1017 174668 : case ADDR_EXPR: /* LHS = &RHS; */
1018 174668 : case BIT_FIELD_REF:
1019 174668 : case COMPONENT_REF: /* LHS = op0.op1; */
1020 174668 : case MEM_REF:
1021 174668 : case REAL_CST:
1022 174668 : case COMPLEX_CST:
1023 174668 : case VECTOR_CST:
1024 174668 : case INTEGER_CST:
1025 174668 : case ARRAY_REF:
1026 174668 : case SSA_NAME: /* LHS = VAR; */
1027 174668 : case VAR_DECL: /* LHS = VAR; */
1028 174668 : case PARM_DECL:/* LHS = VAR; */
1029 174668 : case REALPART_EXPR:
1030 174668 : case IMAGPART_EXPR:
1031 174668 : return get_rvalue (rhs1, ctxt);
1032 :
1033 37873 : case ABS_EXPR:
1034 37873 : case ABSU_EXPR:
1035 37873 : case CONJ_EXPR:
1036 37873 : case BIT_NOT_EXPR:
1037 37873 : case FIX_TRUNC_EXPR:
1038 37873 : case FLOAT_EXPR:
1039 37873 : case NEGATE_EXPR:
1040 37873 : case NOP_EXPR:
1041 37873 : case VIEW_CONVERT_EXPR:
1042 37873 : {
1043 : /* Unary ops. */
1044 37873 : const svalue *rhs_sval = get_rvalue (rhs1, ctxt);
1045 37873 : const svalue *sval_unaryop
1046 37873 : = m_mgr->get_or_create_unaryop (TREE_TYPE (lhs), op, rhs_sval);
1047 37873 : return sval_unaryop;
1048 : }
1049 :
1050 16161 : case EQ_EXPR:
1051 16161 : case GE_EXPR:
1052 16161 : case LE_EXPR:
1053 16161 : case NE_EXPR:
1054 16161 : case GT_EXPR:
1055 16161 : case LT_EXPR:
1056 16161 : case UNORDERED_EXPR:
1057 16161 : case ORDERED_EXPR:
1058 16161 : {
1059 16161 : tree rhs2 = gimple_assign_rhs2 (assign);
1060 :
1061 16161 : const svalue *rhs1_sval = get_rvalue (rhs1, ctxt);
1062 16161 : const svalue *rhs2_sval = get_rvalue (rhs2, ctxt);
1063 :
1064 16161 : if (TREE_TYPE (lhs) == boolean_type_node)
1065 : {
1066 : /* Consider constraints between svalues. */
1067 :
1068 : /* Update infinite loop detection before eval_condition
1069 : does any folding. */
1070 16005 : if (ctxt && ctxt->checking_for_infinite_loop_p ())
1071 825 : if (unusable_in_infinite_loop_constraint_p (rhs1_sval)
1072 16033 : || unusable_in_infinite_loop_constraint_p (rhs2_sval))
1073 28 : ctxt->on_unusable_in_infinite_loop ();
1074 :
1075 16005 : tristate t = eval_condition (rhs1_sval, op, rhs2_sval);
1076 16005 : if (t.is_known ())
1077 9415 : return m_mgr->get_or_create_constant_svalue
1078 9415 : (t.is_true () ? boolean_true_node : boolean_false_node);
1079 : }
1080 :
1081 : /* Otherwise, generate a symbolic binary op. */
1082 6746 : const svalue *sval_binop
1083 6746 : = m_mgr->get_or_create_binop (TREE_TYPE (lhs), op,
1084 : rhs1_sval, rhs2_sval);
1085 6746 : return sval_binop;
1086 : }
1087 44608 : break;
1088 :
1089 44608 : case PLUS_EXPR:
1090 44608 : case MINUS_EXPR:
1091 44608 : case MULT_EXPR:
1092 44608 : case MULT_HIGHPART_EXPR:
1093 44608 : case TRUNC_DIV_EXPR:
1094 44608 : case CEIL_DIV_EXPR:
1095 44608 : case FLOOR_DIV_EXPR:
1096 44608 : case ROUND_DIV_EXPR:
1097 44608 : case TRUNC_MOD_EXPR:
1098 44608 : case CEIL_MOD_EXPR:
1099 44608 : case FLOOR_MOD_EXPR:
1100 44608 : case ROUND_MOD_EXPR:
1101 44608 : case RDIV_EXPR:
1102 44608 : case EXACT_DIV_EXPR:
1103 44608 : case LSHIFT_EXPR:
1104 44608 : case RSHIFT_EXPR:
1105 44608 : case LROTATE_EXPR:
1106 44608 : case RROTATE_EXPR:
1107 44608 : case BIT_IOR_EXPR:
1108 44608 : case BIT_XOR_EXPR:
1109 44608 : case BIT_AND_EXPR:
1110 44608 : case MIN_EXPR:
1111 44608 : case MAX_EXPR:
1112 44608 : case COMPLEX_EXPR:
1113 44608 : {
1114 : /* Binary ops. */
1115 44608 : tree rhs2 = gimple_assign_rhs2 (assign);
1116 :
1117 44608 : const svalue *rhs1_sval = get_rvalue (rhs1, ctxt);
1118 44608 : const svalue *rhs2_sval = get_rvalue (rhs2, ctxt);
1119 :
1120 44608 : if (ctxt && (op == LSHIFT_EXPR || op == RSHIFT_EXPR))
1121 : {
1122 : /* "INT34-C. Do not shift an expression by a negative number of bits
1123 : or by greater than or equal to the number of bits that exist in
1124 : the operand." */
1125 2419 : if (const tree rhs2_cst = rhs2_sval->maybe_get_constant ())
1126 2135 : if (TREE_CODE (rhs2_cst) == INTEGER_CST
1127 2135 : && INTEGRAL_TYPE_P (TREE_TYPE (rhs1)))
1128 : {
1129 2133 : if (tree_int_cst_sgn (rhs2_cst) < 0)
1130 : {
1131 24 : const region *rhs2_reg
1132 48 : = get_lvalue (gimple_assign_rhs2 (assign), nullptr);
1133 24 : ctxt->warn
1134 24 : (make_shift_count_negative_diagnostic (assign,
1135 : rhs2_cst,
1136 : rhs2_reg));
1137 : }
1138 2109 : else if (compare_tree_int (rhs2_cst,
1139 2109 : TYPE_PRECISION (TREE_TYPE (rhs1)))
1140 : >= 0)
1141 : {
1142 24 : const region *rhs2_reg
1143 48 : = get_lvalue (gimple_assign_rhs2 (assign), nullptr);
1144 48 : ctxt->warn (make_shift_count_overflow_diagnostic
1145 24 : (assign,
1146 24 : int (TYPE_PRECISION (TREE_TYPE (rhs1))),
1147 : rhs2_cst,
1148 : rhs2_reg));
1149 : }
1150 : }
1151 : }
1152 :
1153 44608 : if (op == TRUNC_DIV_EXPR
1154 : || op == CEIL_DIV_EXPR
1155 : || op == FLOOR_DIV_EXPR
1156 : || op == ROUND_DIV_EXPR
1157 : || op == TRUNC_MOD_EXPR
1158 : || op == CEIL_MOD_EXPR
1159 : || op == FLOOR_MOD_EXPR
1160 : || op == ROUND_MOD_EXPR
1161 : || op == RDIV_EXPR
1162 44608 : || op == EXACT_DIV_EXPR)
1163 : {
1164 1181 : value_range rhs_vr;
1165 1181 : if (rhs2_sval->maybe_get_value_range (rhs_vr))
1166 1077 : if (rhs_vr.zero_p ())
1167 : {
1168 74 : if (ctxt)
1169 : {
1170 74 : const region *rhs2_reg
1171 148 : = get_lvalue (gimple_assign_rhs2 (assign), nullptr);
1172 74 : ctxt->warn
1173 74 : (std::make_unique<div_by_zero_diagnostic> (assign,
1174 : rhs2_reg));
1175 74 : ctxt->terminate_path ();
1176 : }
1177 74 : return nullptr;
1178 : }
1179 1181 : }
1180 :
1181 44534 : const svalue *sval_binop
1182 44534 : = m_mgr->get_or_create_binop (TREE_TYPE (lhs), op,
1183 : rhs1_sval, rhs2_sval);
1184 44534 : return sval_binop;
1185 : }
1186 :
1187 : /* Vector expressions. In theory we could implement these elementwise,
1188 : but for now, simply return unknown values. */
1189 0 : case VEC_DUPLICATE_EXPR:
1190 0 : case VEC_SERIES_EXPR:
1191 0 : case VEC_COND_EXPR:
1192 0 : case VEC_PERM_EXPR:
1193 0 : case VEC_WIDEN_MULT_HI_EXPR:
1194 0 : case VEC_WIDEN_MULT_LO_EXPR:
1195 0 : case VEC_WIDEN_MULT_EVEN_EXPR:
1196 0 : case VEC_WIDEN_MULT_ODD_EXPR:
1197 0 : case VEC_UNPACK_HI_EXPR:
1198 0 : case VEC_UNPACK_LO_EXPR:
1199 0 : case VEC_UNPACK_FLOAT_HI_EXPR:
1200 0 : case VEC_UNPACK_FLOAT_LO_EXPR:
1201 0 : case VEC_UNPACK_FIX_TRUNC_HI_EXPR:
1202 0 : case VEC_UNPACK_FIX_TRUNC_LO_EXPR:
1203 0 : case VEC_PACK_TRUNC_EXPR:
1204 0 : case VEC_PACK_SAT_EXPR:
1205 0 : case VEC_PACK_FIX_TRUNC_EXPR:
1206 0 : case VEC_PACK_FLOAT_EXPR:
1207 0 : case VEC_WIDEN_LSHIFT_HI_EXPR:
1208 0 : case VEC_WIDEN_LSHIFT_LO_EXPR:
1209 0 : return m_mgr->get_or_create_unknown_svalue (TREE_TYPE (lhs));
1210 : }
1211 : }
1212 :
1213 : /* Workaround for discarding certain false positives from
1214 : -Wanalyzer-use-of-uninitialized-value
1215 : of the form:
1216 : ((A OR-IF B) OR-IF C)
1217 : and:
1218 : ((A AND-IF B) AND-IF C)
1219 : where evaluating B is redundant, but could involve simple accesses of
1220 : uninitialized locals.
1221 :
1222 : When optimization is turned on the FE can immediately fold compound
1223 : conditionals. Specifically, c_parser_condition parses this condition:
1224 : ((A OR-IF B) OR-IF C)
1225 : and calls c_fully_fold on the condition.
1226 : Within c_fully_fold, fold_truth_andor is called, which bails when
1227 : optimization is off, but if any optimization is turned on can convert the
1228 : ((A OR-IF B) OR-IF C)
1229 : into:
1230 : ((A OR B) OR_IF C)
1231 : for sufficiently simple B
1232 : i.e. the inner OR-IF becomes an OR.
1233 : At gimplification time the inner OR becomes BIT_IOR_EXPR (in gimplify_expr),
1234 : giving this for the inner condition:
1235 : tmp = A | B;
1236 : if (tmp)
1237 : thus effectively synthesizing a redundant access of B when optimization
1238 : is turned on, when compared to:
1239 : if (A) goto L1; else goto L4;
1240 : L1: if (B) goto L2; else goto L4;
1241 : L2: if (C) goto L3; else goto L4;
1242 : for the unoptimized case.
1243 :
1244 : Return true if CTXT appears to be handling such a short-circuitable stmt,
1245 : such as the def-stmt for B for the:
1246 : tmp = A | B;
1247 : case above, for the case where A is true and thus B would have been
1248 : short-circuited without optimization, using MODEL for the value of A. */
1249 :
1250 : static bool
1251 1280 : within_short_circuited_stmt_p (const region_model *model,
1252 : const gassign *assign_stmt)
1253 : {
1254 : /* We must have an assignment to a temporary of _Bool type. */
1255 1280 : tree lhs = gimple_assign_lhs (assign_stmt);
1256 1280 : if (TREE_TYPE (lhs) != boolean_type_node)
1257 : return false;
1258 40 : if (TREE_CODE (lhs) != SSA_NAME)
1259 : return false;
1260 40 : if (SSA_NAME_VAR (lhs) != NULL_TREE)
1261 : return false;
1262 :
1263 : /* The temporary bool must be used exactly once: as the second arg of
1264 : a BIT_IOR_EXPR or BIT_AND_EXPR. */
1265 40 : use_operand_p use_op;
1266 40 : gimple *use_stmt;
1267 40 : if (!single_imm_use (lhs, &use_op, &use_stmt))
1268 : return false;
1269 40 : const gassign *use_assign = dyn_cast <const gassign *> (use_stmt);
1270 40 : if (!use_assign)
1271 : return false;
1272 40 : enum tree_code op = gimple_assign_rhs_code (use_assign);
1273 40 : if (!(op == BIT_IOR_EXPR ||op == BIT_AND_EXPR))
1274 : return false;
1275 28 : if (!(gimple_assign_rhs1 (use_assign) != lhs
1276 28 : && gimple_assign_rhs2 (use_assign) == lhs))
1277 : return false;
1278 :
1279 : /* The first arg of the bitwise stmt must have a known value in MODEL
1280 : that implies that the value of the second arg doesn't matter, i.e.
1281 : 1 for bitwise or, 0 for bitwise and. */
1282 28 : tree other_arg = gimple_assign_rhs1 (use_assign);
1283 : /* Use a nullptr ctxt here to avoid generating warnings. */
1284 28 : const svalue *other_arg_sval = model->get_rvalue (other_arg, nullptr);
1285 28 : tree other_arg_cst = other_arg_sval->maybe_get_constant ();
1286 28 : if (!other_arg_cst)
1287 : return false;
1288 12 : switch (op)
1289 : {
1290 : default:
1291 : gcc_unreachable ();
1292 12 : case BIT_IOR_EXPR:
1293 12 : if (zerop (other_arg_cst))
1294 0 : return false;
1295 : break;
1296 0 : case BIT_AND_EXPR:
1297 0 : if (!zerop (other_arg_cst))
1298 : return false;
1299 : break;
1300 : }
1301 :
1302 : /* All tests passed. We appear to be in a stmt that generates a boolean
1303 : temporary with a value that won't matter. */
1304 : return true;
1305 : }
1306 :
1307 : /* Workaround for discarding certain false positives from
1308 : -Wanalyzer-use-of-uninitialized-value
1309 : seen with -ftrivial-auto-var-init=.
1310 :
1311 : -ftrivial-auto-var-init= will generate calls to IFN_DEFERRED_INIT.
1312 :
1313 : If the address of the var is taken, gimplification will give us
1314 : something like:
1315 :
1316 : _1 = .DEFERRED_INIT (4, 2, &"len"[0]);
1317 : len = _1;
1318 :
1319 : The result of DEFERRED_INIT will be an uninit value; we don't
1320 : want to emit a false positive for "len = _1;"
1321 :
1322 : Return true if ASSIGN_STMT is such a stmt. */
1323 :
1324 : static bool
1325 1268 : due_to_ifn_deferred_init_p (const gassign *assign_stmt)
1326 :
1327 : {
1328 : /* We must have an assignment to a decl from an SSA name that's the
1329 : result of a IFN_DEFERRED_INIT call. */
1330 2356 : if (gimple_assign_rhs_code (assign_stmt) != SSA_NAME)
1331 : return false;
1332 323 : tree lhs = gimple_assign_lhs (assign_stmt);
1333 323 : if (TREE_CODE (lhs) != VAR_DECL)
1334 : return false;
1335 258 : tree rhs = gimple_assign_rhs1 (assign_stmt);
1336 258 : if (TREE_CODE (rhs) != SSA_NAME)
1337 : return false;
1338 258 : const gimple *def_stmt = SSA_NAME_DEF_STMT (rhs);
1339 258 : const gcall *call = dyn_cast <const gcall *> (def_stmt);
1340 258 : if (!call)
1341 : return false;
1342 258 : if (gimple_call_internal_p (call)
1343 258 : && gimple_call_internal_fn (call) == IFN_DEFERRED_INIT)
1344 246 : return true;
1345 : return false;
1346 : }
1347 :
1348 : const svalue *
1349 2687 : region_model::complain_about_poison (const svalue *sval,
1350 : tree expr,
1351 : const region *src_region,
1352 : region_model_context *ctxt,
1353 : enum poison_kind pkind) const
1354 : {
1355 : /* Ignore uninitialized uses of empty types; there's nothing
1356 : to initialize. */
1357 2687 : if (pkind == poison_kind::uninit
1358 2637 : && sval->get_type ()
1359 5218 : && is_empty_type (sval->get_type ()))
1360 : return sval;
1361 :
1362 2447 : if (pkind == poison_kind::uninit)
1363 2397 : if (const gimple *curr_stmt = ctxt->get_stmt ())
1364 1616 : if (const gassign *assign_stmt
1365 3469 : = dyn_cast <const gassign *> (curr_stmt))
1366 : {
1367 : /* Special case to avoid certain false positives. */
1368 1280 : if (within_short_circuited_stmt_p (this, assign_stmt))
1369 : return sval;
1370 :
1371 : /* Special case to avoid false positive on
1372 : -ftrivial-auto-var-init=. */
1373 1268 : if (due_to_ifn_deferred_init_p (assign_stmt))
1374 : return sval;
1375 : }
1376 :
1377 : /* If we have an SSA name for a temporary, we don't want to print
1378 : '<unknown>'.
1379 : Poisoned values are shared by type, and so we can't reconstruct
1380 : the tree other than via the def stmts, using
1381 : fixup_tree_for_diagnostic. */
1382 2189 : tree diag_arg = fixup_tree_for_diagnostic (expr);
1383 2189 : if (src_region == nullptr && pkind == poison_kind::uninit)
1384 2003 : src_region = get_region_for_poisoned_expr (expr);
1385 :
1386 : /* Can we reliably get the poisoned value from "expr"?
1387 : This is for use by poisoned_value_diagnostic::check_valid_fpath_p.
1388 : Unfortunately, we might not have a reliable value for EXPR.
1389 : Hence we only query its value now, and only use it if we get the
1390 : poisoned value back again. */
1391 2189 : tree check_expr = expr;
1392 2189 : const svalue *foo_sval = get_rvalue (expr, nullptr);
1393 2189 : if (foo_sval == sval)
1394 : check_expr = expr;
1395 : else
1396 147 : check_expr = nullptr;
1397 2189 : if (ctxt->warn (make_poisoned_value_diagnostic (diag_arg,
1398 : pkind,
1399 : src_region,
1400 : check_expr)))
1401 : {
1402 : /* We only want to report use of a poisoned value at the first
1403 : place it gets used; return an unknown value to avoid generating
1404 : a chain of followup warnings. */
1405 1415 : sval = m_mgr->get_or_create_unknown_svalue (sval->get_type ());
1406 : }
1407 :
1408 : return sval;
1409 : }
1410 :
1411 : /* Check for SVAL being poisoned, adding a warning to CTXT.
1412 : Return SVAL, or, if a warning is added, another value, to avoid
1413 : repeatedly complaining about the same poisoned value in followup code.
1414 : SRC_REGION is a hint about where SVAL came from, and can be nullptr. */
1415 :
1416 : const svalue *
1417 2863681 : region_model::check_for_poison (const svalue *sval,
1418 : tree expr,
1419 : const region *src_region,
1420 : region_model_context *ctxt) const
1421 : {
1422 2863681 : if (!ctxt)
1423 : return sval;
1424 :
1425 : // Complain about SVAL being fully poisoned:
1426 1481612 : if (auto *sval_from_bv = sval->dyn_cast_svalue_from_bit_vector ())
1427 : {
1428 81016 : auto &bv = sval_from_bv->get_bit_vector ();
1429 81016 : if (auto *poison = bv.dyn_cast_poisoned_bit_vector ())
1430 2581 : return complain_about_poison (sval, expr, src_region, ctxt,
1431 2581 : poison->get_poison_kind ());
1432 : }
1433 :
1434 : return sval;
1435 : }
1436 :
1437 : void
1438 4587 : region_model::
1439 : check_bytes_for_poison (const symbolic::bit_vector &bv,
1440 : symbolic::pointer sym_ptr,
1441 : tree sym_ptr_expr,
1442 : region_model_context *ctxt) const
1443 : {
1444 4587 : if (!ctxt)
1445 436 : return;
1446 :
1447 : // Complain about any poison being found in BV:
1448 4151 : auto *sval = m_mgr->get_svalue_from_bit_vector (NULL_TREE, bv);
1449 4151 : poison_finder v;
1450 4151 : sval->accept_node_visitor (v);
1451 4151 : if (v.m_found_poison)
1452 : {
1453 106 : auto &base_reg = sym_ptr.get_base_region ();
1454 106 : auto *byte_offset_sval
1455 106 : = m_mgr->get_svalue_from_scalar (size_type_node,
1456 106 : sym_ptr.get_byte_offset ());
1457 106 : auto *byte_size_sval
1458 106 : = m_mgr->get_svalue_from_scalar (size_type_node,
1459 106 : *bv.maybe_get_size_in_bytes ());
1460 :
1461 106 : auto *src_region = m_mgr->get_sized_region
1462 106 : (m_mgr->get_offset_region (&base_reg, NULL_TREE,
1463 : byte_offset_sval),
1464 : NULL_TREE,
1465 : byte_size_sval);
1466 106 : complain_about_poison (sval, sym_ptr_expr, src_region, ctxt, v.m_pkind);
1467 : }
1468 4151 : }
1469 :
1470 : /* Attempt to get a region for describing EXPR, the source of region of
1471 : a poisoned_svalue for use in a poisoned_value_diagnostic.
1472 : Return nullptr if there is no good region to use. */
1473 :
1474 : const region *
1475 2003 : region_model::get_region_for_poisoned_expr (tree expr) const
1476 : {
1477 2003 : if (TREE_CODE (expr) == SSA_NAME)
1478 : {
1479 1252 : tree decl = SSA_NAME_VAR (expr);
1480 1206 : if (decl && DECL_P (decl))
1481 : expr = decl;
1482 : else
1483 : return nullptr;
1484 : }
1485 1957 : return get_lvalue (expr, nullptr);
1486 : }
1487 :
1488 : /* Update this model for the ASSIGN stmt, using CTXT to report any
1489 : diagnostics. */
1490 :
1491 : void
1492 179732 : region_model::on_assignment (const gassign *assign, region_model_context *ctxt)
1493 : {
1494 179732 : tree lhs = gimple_assign_lhs (assign);
1495 179732 : tree rhs1 = gimple_assign_rhs1 (assign);
1496 :
1497 179732 : const region *lhs_reg = get_lvalue (lhs, ctxt);
1498 :
1499 : /* Any writes other than to the stack are treated
1500 : as externally visible. */
1501 179732 : if (ctxt)
1502 : {
1503 131213 : enum memory_space memspace = lhs_reg->get_memory_space ();
1504 131213 : if (memspace != MEMSPACE_STACK)
1505 12210 : ctxt->maybe_did_work ();
1506 : }
1507 :
1508 : /* Most assignments are handled by:
1509 : set_value (lhs_reg, SVALUE, CTXT)
1510 : for some SVALUE. */
1511 179732 : if (const svalue *sval = get_gassign_result (assign, ctxt))
1512 : {
1513 171634 : tree expr = get_diagnostic_tree_for_gassign (assign);
1514 171634 : check_for_poison (sval, expr, nullptr, ctxt);
1515 171634 : set_value (lhs_reg, sval, ctxt);
1516 171634 : return;
1517 : }
1518 :
1519 8098 : enum tree_code op = gimple_assign_rhs_code (assign);
1520 8098 : switch (op)
1521 : {
1522 37 : default:
1523 37 : {
1524 37 : if (0)
1525 : sorry_at (assign->location, "unhandled assignment op: %qs",
1526 : get_tree_code_name (op));
1527 37 : const svalue *unknown_sval
1528 37 : = m_mgr->get_or_create_unknown_svalue (TREE_TYPE (lhs));
1529 37 : set_value (lhs_reg, unknown_sval, ctxt);
1530 : }
1531 37 : break;
1532 :
1533 7502 : case CONSTRUCTOR:
1534 7502 : {
1535 7502 : if (TREE_CLOBBER_P (rhs1))
1536 : {
1537 : /* e.g. "x ={v} {CLOBBER};" */
1538 7338 : clobber_region (lhs_reg);
1539 : }
1540 : else
1541 : {
1542 : /* Any CONSTRUCTOR that survives to this point is either
1543 : just a zero-init of everything, or a vector. */
1544 164 : if (!CONSTRUCTOR_NO_CLEARING (rhs1))
1545 164 : zero_fill_region (lhs_reg, ctxt);
1546 164 : unsigned ix;
1547 164 : tree index;
1548 164 : tree val;
1549 326 : FOR_EACH_CONSTRUCTOR_ELT (CONSTRUCTOR_ELTS (rhs1), ix, index, val)
1550 : {
1551 162 : gcc_assert (TREE_CODE (TREE_TYPE (rhs1)) == VECTOR_TYPE);
1552 162 : if (!index)
1553 22 : index = build_int_cst (integer_type_node, ix);
1554 162 : gcc_assert (TREE_CODE (index) == INTEGER_CST);
1555 162 : const svalue *index_sval
1556 162 : = m_mgr->get_or_create_constant_svalue (index);
1557 162 : gcc_assert (index_sval);
1558 162 : const region *sub_reg
1559 162 : = m_mgr->get_element_region (lhs_reg,
1560 162 : TREE_TYPE (val),
1561 : index_sval);
1562 162 : const svalue *val_sval = get_rvalue (val, ctxt);
1563 162 : set_value (sub_reg, val_sval, ctxt);
1564 : }
1565 : }
1566 : }
1567 : break;
1568 :
1569 559 : case STRING_CST:
1570 559 : {
1571 : /* e.g. "struct s2 x = {{'A', 'B', 'C', 'D'}};". */
1572 559 : const svalue *rhs_sval = get_rvalue (rhs1, ctxt);
1573 559 : set_value (lhs_reg, rhs_sval, ctxt);
1574 : }
1575 559 : break;
1576 : }
1577 : }
1578 :
1579 : /* Handle the pre-sm-state part of STMT, modifying this object in-place.
1580 : Write true to *OUT_UNKNOWN_SIDE_EFFECTS if the stmt has unknown
1581 : side effects. */
1582 :
1583 : void
1584 257508 : region_model::on_stmt_pre (const gimple *stmt,
1585 : bool *out_unknown_side_effects,
1586 : region_model_context *ctxt)
1587 : {
1588 257508 : switch (gimple_code (stmt))
1589 : {
1590 : case GIMPLE_COND:
1591 : case GIMPLE_EH_DISPATCH:
1592 : case GIMPLE_GOTO:
1593 : case GIMPLE_LABEL:
1594 : case GIMPLE_NOP:
1595 : case GIMPLE_PREDICT:
1596 : case GIMPLE_RESX:
1597 : case GIMPLE_SWITCH:
1598 : /* No-ops here. */
1599 : break;
1600 :
1601 179732 : case GIMPLE_ASSIGN:
1602 179732 : {
1603 179732 : const gassign *assign = as_a <const gassign *> (stmt);
1604 179732 : on_assignment (assign, ctxt);
1605 : }
1606 179732 : break;
1607 :
1608 384 : case GIMPLE_ASM:
1609 384 : {
1610 384 : const gasm *asm_stmt = as_a <const gasm *> (stmt);
1611 384 : on_asm_stmt (asm_stmt, ctxt);
1612 384 : if (ctxt)
1613 342 : ctxt->maybe_did_work ();
1614 : }
1615 : break;
1616 :
1617 74012 : case GIMPLE_CALL:
1618 74012 : {
1619 : /* Track whether we have a gcall to a function that's not recognized by
1620 : anything, for which we don't have a function body, or for which we
1621 : don't know the fndecl. */
1622 74012 : const gcall *call = as_a <const gcall *> (stmt);
1623 74012 : *out_unknown_side_effects = on_call_pre (*call, ctxt);
1624 : }
1625 74012 : break;
1626 :
1627 0 : case GIMPLE_RETURN:
1628 0 : {
1629 0 : const greturn *return_ = as_a <const greturn *> (stmt);
1630 0 : on_return (return_, ctxt);
1631 : }
1632 0 : break;
1633 :
1634 : /* We don't expect to see any other statement kinds in the analyzer. */
1635 0 : case GIMPLE_DEBUG: // should have stripped these out when building the supergraph
1636 0 : default:
1637 0 : internal_error ("unexpected gimple stmt code: %qs",
1638 0 : gimple_code_name[gimple_code (stmt)]);
1639 257508 : break;
1640 : }
1641 257508 : }
1642 :
1643 : /* Given a call CD with function attribute FORMAT_ATTR, check that the
1644 : format arg to the call is a valid null-terminated string. */
1645 :
1646 : void
1647 1072 : region_model::check_call_format_attr (const call_details &cd,
1648 : tree format_attr) const
1649 : {
1650 : /* We assume that FORMAT_ATTR has already been validated. */
1651 :
1652 : /* arg0 of the attribute should be kind of format strings
1653 : that this function expects (e.g. "printf"). */
1654 1072 : const tree arg0_tree_list = TREE_VALUE (format_attr);
1655 1072 : if (!arg0_tree_list)
1656 0 : return;
1657 :
1658 : /* arg1 of the attribute should be the 1-based parameter index
1659 : to treat as the format string. */
1660 1072 : const tree arg1_tree_list = TREE_CHAIN (arg0_tree_list);
1661 1072 : if (!arg1_tree_list)
1662 : return;
1663 1072 : const tree arg1_value = TREE_VALUE (arg1_tree_list);
1664 1072 : if (!arg1_value)
1665 : return;
1666 :
1667 1072 : unsigned format_arg_idx = TREE_INT_CST_LOW (arg1_value) - 1;
1668 1072 : if (cd.num_args () <= format_arg_idx)
1669 : return;
1670 :
1671 : /* Subclass of annotating_context that
1672 : adds a note about the format attr to any saved diagnostics. */
1673 1072 : class annotating_ctxt : public annotating_context
1674 : {
1675 : public:
1676 1072 : annotating_ctxt (const call_details &cd,
1677 : unsigned fmt_param_idx)
1678 : : annotating_context (cd.get_ctxt ()),
1679 1072 : m_cd (cd),
1680 1072 : m_fmt_param_idx (fmt_param_idx)
1681 : {
1682 : }
1683 13 : void add_annotations () final override
1684 : {
1685 0 : class reason_format_attr
1686 : : public pending_note_subclass<reason_format_attr>
1687 : {
1688 : public:
1689 13 : reason_format_attr (const call_arg_details &arg_details)
1690 13 : : m_arg_details (arg_details)
1691 : {
1692 : }
1693 :
1694 74 : const char *get_kind () const final override
1695 : {
1696 74 : return "reason_format_attr";
1697 : }
1698 :
1699 13 : void emit () const final override
1700 : {
1701 13 : inform (DECL_SOURCE_LOCATION (m_arg_details.m_called_fndecl),
1702 : "parameter %i of %qD marked as a format string"
1703 : " via %qs attribute",
1704 13 : m_arg_details.m_arg_idx + 1, m_arg_details.m_called_fndecl,
1705 : "format");
1706 13 : }
1707 :
1708 37 : bool operator== (const reason_format_attr &other) const
1709 : {
1710 37 : return m_arg_details == other.m_arg_details;
1711 : }
1712 :
1713 : private:
1714 : call_arg_details m_arg_details;
1715 : };
1716 :
1717 13 : call_arg_details arg_details (m_cd, m_fmt_param_idx);
1718 13 : add_note (std::make_unique<reason_format_attr> (arg_details));
1719 13 : }
1720 : private:
1721 : const call_details &m_cd;
1722 : unsigned m_fmt_param_idx;
1723 : };
1724 :
1725 1072 : annotating_ctxt my_ctxt (cd, format_arg_idx);
1726 1072 : call_details my_cd (cd, &my_ctxt);
1727 1072 : my_cd.check_for_null_terminated_string_arg (format_arg_idx);
1728 : }
1729 :
1730 : /* Ensure that all arguments at the call described by CD are checked
1731 : for poisoned values, by calling get_rvalue on each argument.
1732 :
1733 : Check that calls to functions with "format" attribute have valid
1734 : null-terminated strings for their format argument. */
1735 :
1736 : void
1737 48766 : region_model::check_call_args (const call_details &cd) const
1738 : {
1739 111092 : for (unsigned arg_idx = 0; arg_idx < cd.num_args (); arg_idx++)
1740 62326 : cd.get_arg_svalue (arg_idx);
1741 :
1742 : /* Handle attribute "format". */
1743 48766 : if (tree format_attr = cd.lookup_function_attribute ("format"))
1744 1072 : check_call_format_attr (cd, format_attr);
1745 48766 : }
1746 :
1747 : /* Update this model for an outcome of a call that returns a specific
1748 : integer constant.
1749 : If UNMERGEABLE, then make the result unmergeable, e.g. to prevent
1750 : the state-merger code from merging success and failure outcomes. */
1751 :
1752 : void
1753 753 : region_model::update_for_int_cst_return (const call_details &cd,
1754 : int retval,
1755 : bool unmergeable)
1756 : {
1757 753 : if (!cd.get_lhs_type ())
1758 : return;
1759 515 : if (TREE_CODE (cd.get_lhs_type ()) != INTEGER_TYPE)
1760 : return;
1761 515 : const svalue *result
1762 515 : = m_mgr->get_or_create_int_cst (cd.get_lhs_type (), retval);
1763 515 : if (unmergeable)
1764 515 : result = m_mgr->get_or_create_unmergeable (result);
1765 515 : set_value (cd.get_lhs_region (), result, cd.get_ctxt ());
1766 : }
1767 :
1768 : /* Update this model for an outcome of a call that returns zero.
1769 : If UNMERGEABLE, then make the result unmergeable, e.g. to prevent
1770 : the state-merger code from merging success and failure outcomes. */
1771 :
1772 : void
1773 233 : region_model::update_for_zero_return (const call_details &cd,
1774 : bool unmergeable)
1775 : {
1776 233 : update_for_int_cst_return (cd, 0, unmergeable);
1777 233 : }
1778 :
1779 : /* Update this model for an outcome of a call that returns a NULL
1780 : pointer.
1781 : If UNMERGEABLE, then make the result unmergeable, e.g. to prevent
1782 : the state-merger code from merging success and failure outcomes. */
1783 :
1784 : void
1785 15 : region_model::update_for_null_return (const call_details &cd, bool unmergeable)
1786 : {
1787 15 : if (!cd.get_lhs_type ())
1788 : return;
1789 3 : if (!POINTER_TYPE_P (cd.get_lhs_type ()))
1790 : return;
1791 3 : const svalue *result = m_mgr->get_or_create_null_ptr (cd.get_lhs_type ());
1792 3 : if (unmergeable)
1793 3 : result = m_mgr->get_or_create_unmergeable (result);
1794 3 : set_value (cd.get_lhs_region (), result, cd.get_ctxt ());
1795 : }
1796 :
1797 : /* Update this model for an outcome of a call that returns non-zero.
1798 : Specifically, assign an svalue to the LHS, and add a constraint that
1799 : that svalue is non-zero. */
1800 :
1801 : void
1802 134 : region_model::update_for_nonzero_return (const call_details &cd)
1803 : {
1804 134 : if (!cd.get_lhs_type ())
1805 : return;
1806 98 : if (TREE_CODE (cd.get_lhs_type ()) != INTEGER_TYPE)
1807 : return;
1808 98 : cd.set_any_lhs_with_defaults ();
1809 98 : const svalue *zero
1810 98 : = m_mgr->get_or_create_int_cst (cd.get_lhs_type (), 0);
1811 98 : const svalue *result
1812 98 : = get_store_value (cd.get_lhs_region (), cd.get_ctxt ());
1813 98 : add_constraint (result, NE_EXPR, zero, cd.get_ctxt ());
1814 : }
1815 :
1816 : /* Subroutine of region_model::maybe_get_copy_bounds.
1817 : The Linux kernel commonly uses
1818 : min_t([unsigned] long, VAR, sizeof(T));
1819 : to set an upper bound on the size of a copy_to_user.
1820 : Attempt to simplify such sizes by trying to get the upper bound as a
1821 : constant.
1822 : Return the simplified svalue if possible, or nullptr otherwise. */
1823 :
1824 : static const svalue *
1825 48 : maybe_simplify_upper_bound (const svalue *num_bytes_sval,
1826 : region_model_manager *mgr)
1827 : {
1828 48 : tree type = num_bytes_sval->get_type ();
1829 69 : while (const svalue *raw = num_bytes_sval->maybe_undo_cast ())
1830 : num_bytes_sval = raw;
1831 48 : if (const binop_svalue *binop_sval = num_bytes_sval->dyn_cast_binop_svalue ())
1832 34 : if (binop_sval->get_op () == MIN_EXPR)
1833 10 : if (binop_sval->get_arg1 ()->get_kind () == SK_CONSTANT)
1834 : {
1835 10 : return mgr->get_or_create_cast (type, binop_sval->get_arg1 ());
1836 : /* TODO: we might want to also capture the constraint
1837 : when recording the diagnostic, or note that we're using
1838 : the upper bound. */
1839 : }
1840 : return nullptr;
1841 : }
1842 :
1843 : /* Attempt to get an upper bound for the size of a copy when simulating a
1844 : copy function.
1845 :
1846 : NUM_BYTES_SVAL is the symbolic value for the size of the copy.
1847 : Use it if it's constant, otherwise try to simplify it. Failing
1848 : that, use the size of SRC_REG if constant.
1849 :
1850 : Return a symbolic value for an upper limit on the number of bytes
1851 : copied, or nullptr if no such value could be determined. */
1852 :
1853 : const svalue *
1854 151 : region_model::maybe_get_copy_bounds (const region *src_reg,
1855 : const svalue *num_bytes_sval)
1856 : {
1857 151 : if (num_bytes_sval->maybe_get_constant ())
1858 : return num_bytes_sval;
1859 :
1860 96 : if (const svalue *simplified
1861 48 : = maybe_simplify_upper_bound (num_bytes_sval, m_mgr))
1862 10 : num_bytes_sval = simplified;
1863 :
1864 48 : if (num_bytes_sval->maybe_get_constant ())
1865 : return num_bytes_sval;
1866 :
1867 : /* For now, try just guessing the size as the capacity of the
1868 : base region of the src.
1869 : This is a hack; we might get too large a value. */
1870 38 : const region *src_base_reg = src_reg->get_base_region ();
1871 38 : num_bytes_sval = get_capacity (src_base_reg);
1872 :
1873 38 : if (num_bytes_sval->maybe_get_constant ())
1874 4 : return num_bytes_sval;
1875 :
1876 : /* Non-constant: give up. */
1877 : return nullptr;
1878 : }
1879 :
1880 : /* Get any known_function for FNDECL for call CD.
1881 :
1882 : The call must match all assumptions made by the known_function (such as
1883 : e.g. "argument 1's type must be a pointer type").
1884 :
1885 : Return nullptr if no known_function is found, or it does not match the
1886 : assumption(s). */
1887 :
1888 : const known_function *
1889 296460 : region_model::get_known_function (tree fndecl, const call_details &cd) const
1890 : {
1891 296460 : known_function_manager *known_fn_mgr = m_mgr->get_known_function_manager ();
1892 296460 : return known_fn_mgr->get_match (fndecl, cd);
1893 : }
1894 :
1895 : /* Get any known_function for IFN, or nullptr. */
1896 :
1897 : const known_function *
1898 1436 : region_model::get_known_function (enum internal_fn ifn) const
1899 : {
1900 1436 : known_function_manager *known_fn_mgr = m_mgr->get_known_function_manager ();
1901 1436 : return known_fn_mgr->get_internal_fn (ifn);
1902 : }
1903 :
1904 : /* Get any builtin_known_function for CALL and emit any warning to CTXT
1905 : if not nullptr.
1906 :
1907 : The call must match all assumptions made by the known_function (such as
1908 : e.g. "argument 1's type must be a pointer type").
1909 :
1910 : Return nullptr if no builtin_known_function is found, or it does
1911 : not match the assumption(s).
1912 :
1913 : Internally calls get_known_function to find a known_function and cast it
1914 : to a builtin_known_function.
1915 :
1916 : For instance, calloc is a C builtin, defined in gcc/builtins.def
1917 : by the DEF_LIB_BUILTIN macro. Such builtins are recognized by the
1918 : analyzer by their name, so that even in C++ or if the user redeclares
1919 : them but mismatch their signature, they are still recognized as builtins.
1920 :
1921 : Cases when a supposed builtin is not flagged as one by the FE:
1922 :
1923 : The C++ FE does not recognize calloc as a builtin if it has not been
1924 : included from a standard header, but the C FE does. Hence in C++ if
1925 : CALL comes from a calloc and stdlib is not included,
1926 : gcc/tree.h:fndecl_built_in_p (CALL) would be false.
1927 :
1928 : In C code, a __SIZE_TYPE__ calloc (__SIZE_TYPE__, __SIZE_TYPE__) user
1929 : declaration has obviously a mismatching signature from the standard, and
1930 : its function_decl tree won't be unified by
1931 : gcc/c-decl.cc:match_builtin_function_types.
1932 :
1933 : Yet in both cases the analyzer should treat the calls as a builtin calloc
1934 : so that extra attributes unspecified by the standard but added by GCC
1935 : (e.g. sprintf attributes in gcc/builtins.def), useful for the detection of
1936 : dangerous behavior, are indeed processed.
1937 :
1938 : Therefore for those cases when a "builtin flag" is not added by the FE,
1939 : builtins' kf are derived from builtin_known_function, whose method
1940 : builtin_known_function::builtin_decl returns the builtin's
1941 : function_decl tree as defined in gcc/builtins.def, with all the extra
1942 : attributes. */
1943 :
1944 : const builtin_known_function *
1945 162424 : region_model::get_builtin_kf (const gcall &call,
1946 : region_model_context *ctxt /* = nullptr */) const
1947 : {
1948 162424 : region_model *mut_this = const_cast <region_model *> (this);
1949 162424 : tree callee_fndecl = mut_this->get_fndecl_for_call (call, ctxt);
1950 162424 : if (! callee_fndecl)
1951 : return nullptr;
1952 :
1953 162424 : call_details cd (call, mut_this, ctxt);
1954 162424 : if (const known_function *kf = get_known_function (callee_fndecl, cd))
1955 111798 : return kf->dyn_cast_builtin_kf ();
1956 :
1957 : return nullptr;
1958 : }
1959 :
1960 : /* Subclass of custom_edge_info for use by exploded_edges that represent
1961 : an exception being thrown from a call we don't have the code for. */
1962 :
1963 : class exception_thrown_from_unrecognized_call : public custom_edge_info
1964 : {
1965 : public:
1966 5515 : exception_thrown_from_unrecognized_call (const gcall &call,
1967 : tree fndecl)
1968 5515 : : m_call (call),
1969 5515 : m_fndecl (fndecl)
1970 : {
1971 : }
1972 :
1973 12 : void print (pretty_printer *pp) const final override
1974 : {
1975 12 : if (m_fndecl)
1976 12 : pp_printf (pp, "if %qD throws an exception...", m_fndecl);
1977 : else
1978 0 : pp_printf (pp, "if the called function throws an exception...");
1979 12 : };
1980 :
1981 : bool
1982 5578 : update_model (region_model *model,
1983 : const exploded_edge *,
1984 : region_model_context *ctxt) const final override
1985 : {
1986 : /* Allocate an exception and set it as the current exception. */
1987 5578 : const region *exception_reg
1988 : = model->get_or_create_region_for_heap_alloc
1989 5578 : (nullptr, /* We don't know the size of the region. */
1990 : ctxt);
1991 :
1992 5578 : region_model_manager *mgr = model->get_manager ();
1993 5578 : conjured_purge p (model, ctxt);
1994 :
1995 : /* Conjure a bit_contents for the exception region. */
1996 5578 : auto &bc_mgr = mgr->get_node_manager ().get_bit_contents_manager ();
1997 11156 : auto &exception_bc = bc_mgr.get_conjured_bit_contents (*exception_reg,
1998 5578 : &m_call,
1999 : p, 0);
2000 5578 : model->set_bit_contents_raw (*exception_reg, exception_bc);
2001 :
2002 5578 : const svalue *exception_ptr_sval
2003 5578 : = mgr->get_ptr_svalue (ptr_type_node, exception_reg);
2004 5578 : const svalue *tinfo_sval
2005 11156 : = mgr->get_or_create_conjured_svalue (ptr_type_node,
2006 5578 : &m_call,
2007 : exception_reg, p, 1);
2008 5578 : const svalue *destructor_sval
2009 11156 : = mgr->get_or_create_conjured_svalue (ptr_type_node,
2010 5578 : &m_call,
2011 : exception_reg, p, 2);
2012 :
2013 : /* Push a new exception_node on the model's thrown exception stack. */
2014 5578 : exception_node eh_node (exception_ptr_sval, tinfo_sval, destructor_sval);
2015 5578 : model->push_thrown_exception (eh_node);
2016 :
2017 5578 : return true;
2018 : }
2019 :
2020 : void
2021 35 : add_events_to_path (checker_path *emission_path,
2022 : const exploded_edge &eedge,
2023 : pending_diagnostic &,
2024 : const state_transition *) const final override
2025 : {
2026 35 : const exploded_node *dst_node = eedge.m_dest;
2027 35 : const program_point &dst_point = dst_node->get_point ();
2028 35 : const int dst_stack_depth = dst_point.get_stack_depth ();
2029 :
2030 35 : emission_path->add_event
2031 35 : (std::make_unique<throw_from_call_to_external_fn_event>
2032 35 : (event_loc_info (m_call.location,
2033 : dst_point.get_fndecl (),
2034 35 : dst_stack_depth),
2035 : dst_node,
2036 : m_call,
2037 35 : m_fndecl));
2038 35 : }
2039 :
2040 : exploded_node *
2041 5408 : create_enode (exploded_graph &eg,
2042 : const program_point &point,
2043 : program_state &&state,
2044 : exploded_node *enode_for_diag,
2045 : region_model_context *ctxt) const final override
2046 : {
2047 5408 : exploded_node *thrown_enode
2048 5408 : = eg.get_or_create_node (point, state, enode_for_diag,
2049 : /* Don't add to worklist. */
2050 : false);
2051 5408 : if (!thrown_enode)
2052 : return nullptr;
2053 :
2054 : /* Add successor edges for thrown_enode "by hand" for the exception. */
2055 5378 : eg.unwind_from_exception (*thrown_enode,
2056 5378 : &m_call,
2057 : ctxt);
2058 5378 : return thrown_enode;
2059 : }
2060 :
2061 : private:
2062 : const gcall &m_call;
2063 : tree m_fndecl; // could be null
2064 : };
2065 :
2066 : /* Get a set of functions that are assumed to not throw exceptions. */
2067 :
2068 : static function_set
2069 5385 : get_fns_assumed_not_to_throw ()
2070 : {
2071 : // TODO: populate this list more fully
2072 5385 : static const char * const fn_names[] = {
2073 : /* This array must be kept sorted. */
2074 :
2075 : "fclose"
2076 : };
2077 5385 : const size_t count = ARRAY_SIZE (fn_names);
2078 5385 : function_set fs (fn_names, count);
2079 5385 : return fs;
2080 : }
2081 :
2082 : /* Return true if CALL could throw an exception.
2083 : FNDECL could be NULL_TREE. */
2084 :
2085 : static bool
2086 12477 : can_throw_p (const gcall &call, tree fndecl)
2087 : {
2088 12477 : if (!flag_exceptions)
2089 : return false;
2090 :
2091 : /* Compatibility flag to allow the user to assume external functions
2092 : never throw exceptions. This may be useful when using the analyzer
2093 : on C code that is compiled with -fexceptions, but for which the headers
2094 : haven't yet had "nothrow" attributes systematically added. */
2095 6078 : if (flag_analyzer_assume_nothrow)
2096 : return false;
2097 :
2098 6076 : if (gimple_call_nothrow_p (&call))
2099 : return false;
2100 :
2101 5525 : if (fndecl)
2102 : {
2103 : /* If we are checking a thunk, we want to verify whether or not the
2104 : underlying function is nothrow. */
2105 5388 : if (cgraph_node *n = cgraph_node::get (fndecl))
2106 5388 : fndecl = n->function_symbol ()->decl;
2107 :
2108 5388 : if (TREE_NOTHROW (fndecl))
2109 10 : return false;
2110 :
2111 5385 : const function_set fs = get_fns_assumed_not_to_throw ();
2112 5385 : if (fs.contains_decl_p (fndecl))
2113 : return false;
2114 : }
2115 :
2116 : return true;
2117 : }
2118 :
2119 : /* Given CALL where we don't know what code is being called
2120 : (by not having the body of FNDECL, or having NULL_TREE for FNDECL),
2121 : potentially bifurcate control flow to simulate the call throwing
2122 : an exception. */
2123 :
2124 : void
2125 18119 : region_model::check_for_throw_inside_call (const gcall &call,
2126 : tree fndecl,
2127 : region_model_context *ctxt)
2128 : {
2129 18119 : if (!ctxt)
2130 12604 : return;
2131 :
2132 : /* Could this function throw an exception?
2133 : If so, add an extra e-edge for that. */
2134 12477 : if (!can_throw_p (call, fndecl))
2135 : return;
2136 :
2137 5515 : auto throws_exception
2138 5515 : = std::make_unique<exception_thrown_from_unrecognized_call> (call, fndecl);
2139 5515 : ctxt->bifurcate (std::move (throws_exception));
2140 5515 : }
2141 :
2142 : /* A subclass of pending_diagnostic for complaining about jumps through NULL
2143 : function pointers. */
2144 :
2145 : class jump_through_null : public pending_diagnostic_subclass<jump_through_null>
2146 : {
2147 : public:
2148 16 : jump_through_null (const gcall &call)
2149 16 : : m_call (call)
2150 : {}
2151 :
2152 152 : const char *get_kind () const final override
2153 : {
2154 152 : return "jump_through_null";
2155 : }
2156 :
2157 16 : bool operator== (const jump_through_null &other) const
2158 : {
2159 16 : return &m_call == &other.m_call;
2160 : }
2161 :
2162 32 : int get_controlling_option () const final override
2163 : {
2164 32 : return OPT_Wanalyzer_jump_through_null;
2165 : }
2166 :
2167 16 : bool emit (diagnostic_emission_context &ctxt) final override
2168 : {
2169 16 : return ctxt.warn ("jump through null pointer");
2170 : }
2171 :
2172 32 : bool describe_final_event (pretty_printer &pp,
2173 : const evdesc::final_event &) final override
2174 : {
2175 32 : pp_string (&pp, "jump through null pointer here");
2176 32 : return true;
2177 : }
2178 :
2179 : private:
2180 : const gcall &m_call;
2181 : };
2182 : /* Update this model for the CALL stmt, using CTXT to report any
2183 : diagnostics - the first half.
2184 :
2185 : Updates to the region_model that should be made *before* sm-states
2186 : are updated are done here; other updates to the region_model are done
2187 : in region_model::on_call_post.
2188 :
2189 : Return true if the function call has unknown side effects (it wasn't
2190 : recognized and we don't have a body for it, or are unable to tell which
2191 : fndecl it is). */
2192 :
2193 : bool
2194 74012 : region_model::on_call_pre (const gcall &call, region_model_context *ctxt)
2195 : {
2196 74012 : call_details cd (call, this, ctxt);
2197 :
2198 : /* Special-case for IFN_DEFERRED_INIT.
2199 : We want to report uninitialized variables with -fanalyzer (treating
2200 : -ftrivial-auto-var-init= as purely a mitigation feature).
2201 : Handle IFN_DEFERRED_INIT by treating it as no-op: don't touch the
2202 : lhs of the call, so that it is still uninitialized from the point of
2203 : view of the analyzer. */
2204 74012 : if (gimple_call_internal_p (&call)
2205 74012 : && gimple_call_internal_fn (&call) == IFN_DEFERRED_INIT)
2206 : return false; /* No side effects. */
2207 :
2208 : /* Get svalues for all of the arguments at the callsite, to ensure that we
2209 : complain about any uninitialized arguments. This might lead to
2210 : duplicates if any of the handling below also looks up the svalues,
2211 : but the deduplication code should deal with that. */
2212 69042 : if (ctxt)
2213 48766 : check_call_args (cd);
2214 :
2215 69042 : tree callee_fndecl = get_fndecl_for_call (call, ctxt);
2216 :
2217 69042 : if (gimple_call_internal_p (&call))
2218 2872 : if (const known_function *kf
2219 1436 : = get_known_function (gimple_call_internal_fn (&call)))
2220 : {
2221 1402 : kf->impl_call_pre (cd);
2222 1402 : return false; /* No further side effects. */
2223 : }
2224 :
2225 67640 : if (!callee_fndecl)
2226 : {
2227 : /* Check for jump through nullptr. */
2228 519 : if (ctxt)
2229 411 : if (tree fn_ptr = gimple_call_fn (&call))
2230 : {
2231 385 : const svalue *fn_ptr_sval = get_rvalue (fn_ptr, ctxt);
2232 385 : if (fn_ptr_sval->all_zeroes_p ())
2233 : {
2234 16 : ctxt->warn
2235 16 : (std::make_unique<jump_through_null> (call));
2236 16 : ctxt->terminate_path ();
2237 16 : return true;
2238 : }
2239 : }
2240 :
2241 503 : check_for_throw_inside_call (call, NULL_TREE, ctxt);
2242 503 : cd.set_any_lhs_with_defaults ();
2243 503 : return true; /* Unknown side effects. */
2244 : }
2245 :
2246 67121 : if (const known_function *kf = get_known_function (callee_fndecl, cd))
2247 : {
2248 47542 : kf->impl_call_pre (cd);
2249 47542 : return false; /* No further side effects. */
2250 : }
2251 :
2252 19579 : cd.set_any_lhs_with_defaults ();
2253 :
2254 19579 : const int callee_fndecl_flags = flags_from_decl_or_type (callee_fndecl);
2255 19579 : if (callee_fndecl_flags & (ECF_CONST | ECF_PURE))
2256 : return false; /* No side effects. */
2257 :
2258 18417 : if (fndecl_built_in_p (callee_fndecl))
2259 : return true; /* Unknown side effects. */
2260 :
2261 17616 : if (!fndecl_has_gimple_body_p (callee_fndecl))
2262 : {
2263 17616 : check_for_throw_inside_call (call, callee_fndecl, ctxt);
2264 17616 : return true; /* Unknown side effects. */
2265 : }
2266 :
2267 : return false; /* No side effects. */
2268 : }
2269 :
2270 : /* Update this model for the CALL stmt, using CTXT to report any
2271 : diagnostics - the second half.
2272 :
2273 : Updates to the region_model that should be made *after* sm-states
2274 : are updated are done here; other updates to the region_model are done
2275 : in region_model::on_call_pre.
2276 :
2277 : If UNKNOWN_SIDE_EFFECTS is true, also call handle_unrecognized_call
2278 : to purge state. */
2279 :
2280 : void
2281 73759 : region_model::on_call_post (const gcall &call,
2282 : bool unknown_side_effects,
2283 : region_model_context *ctxt)
2284 : {
2285 73759 : if (tree callee_fndecl = get_fndecl_for_call (call, ctxt))
2286 : {
2287 66915 : call_details cd (call, this, ctxt);
2288 66915 : if (const known_function *kf = get_known_function (callee_fndecl, cd))
2289 : {
2290 47390 : kf->impl_call_post (cd);
2291 95262 : return;
2292 : }
2293 : /* Was this fndecl referenced by
2294 : __attribute__((malloc(FOO)))? */
2295 19525 : if (lookup_attribute ("*dealloc", DECL_ATTRIBUTES (callee_fndecl)))
2296 : {
2297 482 : impl_deallocation_call (cd);
2298 482 : return;
2299 : }
2300 : }
2301 :
2302 25887 : if (unknown_side_effects)
2303 : {
2304 17547 : handle_unrecognized_call (call, ctxt);
2305 17547 : if (ctxt)
2306 12166 : ctxt->maybe_did_work ();
2307 : }
2308 : }
2309 :
2310 : /* Purge state involving NODE from this region_model, using CTXT
2311 : (if non-NULL) to purge other state in a program_state.
2312 :
2313 : For example, if we're at the def-stmt of an SSA name, then we need to
2314 : purge any state for svalues that involve that SSA name. This avoids
2315 : false positives in loops, since a symbolic value referring to the
2316 : SSA name will be referring to the previous value of that SSA name.
2317 :
2318 : For example, in:
2319 : while ((e = hashmap_iter_next(&iter))) {
2320 : struct oid2strbuf *e_strbuf = (struct oid2strbuf *)e;
2321 : free (e_strbuf->value);
2322 : }
2323 : at the def-stmt of e_8:
2324 : e_8 = hashmap_iter_next (&iter);
2325 : we should purge the "freed" state of:
2326 : INIT_VAL(CAST_REG(‘struct oid2strbuf’, (*INIT_VAL(e_8))).value)
2327 : which is the "e_strbuf->value" value from the previous iteration,
2328 : or we will erroneously report a double-free - the "e_8" within it
2329 : refers to the previous value. */
2330 :
2331 : void
2332 24941 : region_model::purge_state_involving (const symbolic::node &node,
2333 : region_model_context *ctxt)
2334 : {
2335 24941 : m_store.purge_state_involving (node);
2336 24941 : m_constraints->purge_state_involving (node);
2337 24941 : m_dynamic_extents.purge_state_involving (node);
2338 24941 : if (ctxt)
2339 13527 : ctxt->purge_state_involving (node);
2340 24941 : }
2341 :
2342 : /* A pending_note subclass for adding a note about an
2343 : __attribute__((access, ...)) to a diagnostic. */
2344 :
2345 : class reason_attr_access : public pending_note_subclass<reason_attr_access>
2346 : {
2347 : public:
2348 22 : reason_attr_access (tree callee_fndecl, const attr_access &access)
2349 22 : : m_callee_fndecl (callee_fndecl),
2350 22 : m_ptr_argno (access.ptrarg),
2351 22 : m_access_str (TREE_STRING_POINTER (access.to_external_string ()))
2352 : {
2353 22 : }
2354 :
2355 116 : const char *get_kind () const final override { return "reason_attr_access"; }
2356 :
2357 18 : void emit () const final override
2358 : {
2359 18 : auto_urlify_attributes sentinel;
2360 18 : inform (DECL_SOURCE_LOCATION (m_callee_fndecl),
2361 : "parameter %i of %qD marked with attribute %qs",
2362 18 : m_ptr_argno + 1, m_callee_fndecl, m_access_str);
2363 18 : }
2364 :
2365 58 : bool operator== (const reason_attr_access &other) const
2366 : {
2367 58 : return (m_callee_fndecl == other.m_callee_fndecl
2368 22 : && m_ptr_argno == other.m_ptr_argno
2369 80 : && !strcmp (m_access_str, other.m_access_str));
2370 : }
2371 :
2372 : private:
2373 : tree m_callee_fndecl;
2374 : unsigned m_ptr_argno;
2375 : const char *m_access_str;
2376 : };
2377 :
2378 : /* Check CALL a call to external function CALLEE_FNDECL based on
2379 : any __attribute__ ((access, ....) on the latter, complaining to
2380 : CTXT about any issues.
2381 :
2382 : Currently we merely call check_region_for_write on any regions
2383 : pointed to by arguments marked with a "write_only" or "read_write"
2384 : attribute. */
2385 :
2386 : void
2387 1251 : region_model::check_function_attr_access (const gcall &call,
2388 : tree callee_fndecl,
2389 : region_model_context *ctxt,
2390 : rdwr_map &rdwr_idx) const
2391 : {
2392 1251 : gcc_assert (callee_fndecl);
2393 1251 : gcc_assert (ctxt);
2394 :
2395 1251 : tree fntype = TREE_TYPE (callee_fndecl);
2396 1251 : gcc_assert (fntype);
2397 :
2398 1251 : unsigned argno = 0;
2399 :
2400 4767 : for (tree iter = TYPE_ARG_TYPES (fntype); iter;
2401 3516 : iter = TREE_CHAIN (iter), ++argno)
2402 : {
2403 3516 : const attr_access* access = rdwr_idx.get (argno);
2404 3516 : if (!access)
2405 3238 : continue;
2406 :
2407 : /* Ignore any duplicate entry in the map for the size argument. */
2408 278 : if (access->ptrarg != argno)
2409 114 : continue;
2410 :
2411 164 : if (access->mode == access_write_only
2412 164 : || access->mode == access_read_write)
2413 : {
2414 : /* Subclass of annotating_context that
2415 : adds a note about the attr access to any saved diagnostics. */
2416 40 : class annotating_ctxt : public annotating_context
2417 : {
2418 : public:
2419 40 : annotating_ctxt (tree callee_fndecl,
2420 : const attr_access &access,
2421 : region_model_context *ctxt)
2422 : : annotating_context (ctxt),
2423 40 : m_callee_fndecl (callee_fndecl),
2424 40 : m_access (access)
2425 : {
2426 : }
2427 22 : void add_annotations () final override
2428 : {
2429 22 : add_note (std::make_unique<reason_attr_access>
2430 22 : (m_callee_fndecl, m_access));
2431 22 : }
2432 : private:
2433 : tree m_callee_fndecl;
2434 : const attr_access &m_access;
2435 : };
2436 :
2437 : /* Use this ctxt below so that any diagnostics get the
2438 : note added to them. */
2439 40 : annotating_ctxt my_ctxt (callee_fndecl, *access, ctxt);
2440 :
2441 40 : tree ptr_tree = gimple_call_arg (&call, access->ptrarg);
2442 40 : const svalue *ptr_sval = get_rvalue (ptr_tree, &my_ctxt);
2443 40 : const region *reg = deref_rvalue (ptr_sval, ptr_tree, &my_ctxt);
2444 40 : check_region_for_write (reg, nullptr, &my_ctxt);
2445 : /* We don't use the size arg for now. */
2446 : }
2447 : }
2448 1251 : }
2449 :
2450 : /* Subroutine of region_model::check_function_attr_null_terminated_string_arg,
2451 : checking one instance of __attribute__((null_terminated_string_arg)). */
2452 :
2453 : void
2454 200 : region_model::
2455 : check_one_function_attr_null_terminated_string_arg (const gcall &call,
2456 : tree callee_fndecl,
2457 : region_model_context *ctxt,
2458 : rdwr_map &rdwr_idx,
2459 : tree attr)
2460 : {
2461 200 : gcc_assert (callee_fndecl);
2462 200 : gcc_assert (ctxt);
2463 200 : gcc_assert (attr);
2464 :
2465 200 : tree arg = TREE_VALUE (attr);
2466 200 : if (!arg)
2467 76 : return;
2468 :
2469 : /* Convert from 1-based to 0-based index. */
2470 200 : unsigned int arg_idx = TREE_INT_CST_LOW (TREE_VALUE (arg)) - 1;
2471 :
2472 : /* If there's also an "access" attribute on the ptr param
2473 : for reading with a size param specified, then that size
2474 : limits the size of the possible read from the pointer. */
2475 200 : if (const attr_access* access = rdwr_idx.get (arg_idx))
2476 104 : if ((access->mode == access_read_only
2477 104 : || access->mode == access_read_write)
2478 104 : && access->sizarg != UINT_MAX)
2479 : {
2480 76 : call_details cd_checked (call, this, ctxt);
2481 76 : auto &limit_num_bytes = cd_checked.get_arg_as_num_bytes (access->sizarg);
2482 76 : auto sym_ptr = cd_checked.get_arg_as_sym_ptr (arg_idx);
2483 : /* Try reading all of the bytes expressed by the size param,
2484 : but without emitting warnings (via a null context). */
2485 76 : auto &bv = read_bytes (sym_ptr,
2486 : NULL_TREE,
2487 : limit_num_bytes,
2488 : nullptr);
2489 :
2490 76 : poison_finder v;
2491 76 : bv.accept_node_visitor (v);
2492 76 : if (v.m_found_poison)
2493 : {
2494 : /* Reading up to the truncation limit caused issues.
2495 : Assume that the string is meant to be terminated
2496 : before then, so perform a *checked* check for the
2497 : terminator. */
2498 36 : check_for_null_terminated_string_arg (cd_checked,
2499 : arg_idx);
2500 : }
2501 : else
2502 : {
2503 : /* Reading up to the truncation limit seems OK; repeat
2504 : the read, but with checking enabled. */
2505 40 : read_bytes (sym_ptr,
2506 : NULL_TREE,
2507 : limit_num_bytes,
2508 : ctxt);
2509 : }
2510 76 : return;
2511 76 : }
2512 :
2513 : /* Otherwise, we don't have an access-attribute limiting the read.
2514 : Simulate a read up to the null terminator (if any). */
2515 :
2516 124 : call_details cd (call, this, ctxt);
2517 124 : check_for_null_terminated_string_arg (cd, arg_idx);
2518 : }
2519 :
2520 : /* Check CALL a call to external function CALLEE_FNDECL for any uses
2521 : of __attribute__ ((null_terminated_string_arg)), complaining
2522 : to CTXT about any issues.
2523 :
2524 : Use RDWR_IDX for tracking uses of __attribute__ ((access, ....). */
2525 :
2526 : void
2527 1251 : region_model::
2528 : check_function_attr_null_terminated_string_arg (const gcall &call,
2529 : tree callee_fndecl,
2530 : region_model_context *ctxt,
2531 : rdwr_map &rdwr_idx)
2532 : {
2533 1251 : gcc_assert (callee_fndecl);
2534 1251 : gcc_assert (ctxt);
2535 :
2536 1251 : tree fntype = TREE_TYPE (callee_fndecl);
2537 1251 : gcc_assert (fntype);
2538 :
2539 : /* A function declaration can specify multiple attribute
2540 : null_terminated_string_arg, each with one argument. */
2541 1451 : for (tree attr = TYPE_ATTRIBUTES (fntype); attr; attr = TREE_CHAIN (attr))
2542 : {
2543 1275 : attr = lookup_attribute ("null_terminated_string_arg", attr);
2544 1275 : if (!attr)
2545 : return;
2546 :
2547 200 : check_one_function_attr_null_terminated_string_arg (call, callee_fndecl,
2548 : ctxt, rdwr_idx,
2549 : attr);
2550 : }
2551 : }
2552 :
2553 : /* Check CALL a call to external function CALLEE_FNDECL for any
2554 : function attributes, complaining to CTXT about any issues. */
2555 :
2556 : void
2557 11776 : region_model::check_function_attrs (const gcall &call,
2558 : tree callee_fndecl,
2559 : region_model_context *ctxt)
2560 : {
2561 11776 : gcc_assert (callee_fndecl);
2562 11776 : gcc_assert (ctxt);
2563 :
2564 11776 : tree fntype = TREE_TYPE (callee_fndecl);
2565 11776 : if (!fntype)
2566 10525 : return;
2567 :
2568 11776 : if (!TYPE_ATTRIBUTES (fntype))
2569 : return;
2570 :
2571 : /* Initialize a map of attribute access specifications for arguments
2572 : to the function call. */
2573 1251 : rdwr_map rdwr_idx;
2574 1251 : init_attr_rdwr_indices (&rdwr_idx, TYPE_ATTRIBUTES (fntype));
2575 :
2576 1251 : check_function_attr_access (call, callee_fndecl, ctxt, rdwr_idx);
2577 1251 : check_function_attr_null_terminated_string_arg (call, callee_fndecl,
2578 : ctxt, rdwr_idx);
2579 1251 : }
2580 :
2581 : /* Handle a call CALL to a function with unknown behavior.
2582 :
2583 : Traverse the regions in this model, determining what regions are
2584 : reachable from pointer arguments to CALL and from global variables,
2585 : recursively.
2586 :
2587 : Set all reachable regions to new unknown values and purge sm-state
2588 : from their values, and from values that point to them. */
2589 :
2590 : void
2591 17547 : region_model::handle_unrecognized_call (const gcall &call,
2592 : region_model_context *ctxt)
2593 : {
2594 17547 : tree fndecl = get_fndecl_for_call (call, ctxt);
2595 :
2596 17547 : if (fndecl && ctxt)
2597 11776 : check_function_attrs (call, fndecl, ctxt);
2598 :
2599 17547 : reachable_regions reachable_regs (this);
2600 :
2601 : /* Determine the reachable regions and their mutability. */
2602 17547 : {
2603 : /* Add globals and regions that already escaped in previous
2604 : unknown calls. */
2605 17547 : m_store.for_each_cluster (reachable_regions::init_cluster_cb,
2606 : &reachable_regs);
2607 :
2608 : /* Params that are pointers. */
2609 17547 : tree iter_param_types = NULL_TREE;
2610 17547 : if (fndecl)
2611 17049 : iter_param_types = TYPE_ARG_TYPES (TREE_TYPE (fndecl));
2612 36971 : for (unsigned arg_idx = 0; arg_idx < gimple_call_num_args (&call);
2613 : arg_idx++)
2614 : {
2615 : /* Track expected param type, where available. */
2616 19424 : tree param_type = NULL_TREE;
2617 19424 : if (iter_param_types)
2618 : {
2619 17932 : param_type = TREE_VALUE (iter_param_types);
2620 17932 : gcc_assert (param_type);
2621 17932 : iter_param_types = TREE_CHAIN (iter_param_types);
2622 : }
2623 :
2624 19424 : tree parm = gimple_call_arg (&call, arg_idx);
2625 19424 : const svalue *parm_sval = get_rvalue (parm, ctxt);
2626 19424 : reachable_regs.handle_parm (parm_sval, param_type);
2627 : }
2628 : }
2629 :
2630 17547 : uncertainty_t *uncertainty = ctxt ? ctxt->get_uncertainty () : nullptr;
2631 :
2632 : /* Purge sm-state for the svalues that were reachable,
2633 : both in non-mutable and mutable form. */
2634 31243 : for (value_set::iterator iter
2635 17547 : = reachable_regs.begin_reachable_svals ();
2636 31243 : iter != reachable_regs.end_reachable_svals (); ++iter)
2637 : {
2638 13696 : if (ctxt)
2639 10628 : ctxt->on_unknown_change (**iter, false);
2640 : }
2641 44197 : for (value_set::iterator iter
2642 17547 : = reachable_regs.begin_mutable_svals ();
2643 44197 : iter != reachable_regs.end_mutable_svals (); ++iter)
2644 : {
2645 26650 : if (ctxt)
2646 20989 : ctxt->on_unknown_change (**iter, true);
2647 26650 : if (uncertainty)
2648 20264 : uncertainty->on_mutable_value_at_unknown_call (**iter);
2649 : }
2650 :
2651 : /* Mark any clusters that have escaped. */
2652 17547 : reachable_regs.mark_escaped_clusters (ctxt);
2653 :
2654 : /* Update bindings for all clusters that have escaped, whether above,
2655 : or previously. */
2656 17547 : m_store.on_unknown_fncall (call,
2657 17547 : conjured_purge (this, ctxt));
2658 :
2659 : /* Purge dynamic extents from any regions that have escaped mutably:
2660 : realloc could have been called on them. */
2661 41144 : for (hash_set<const region *>::iterator
2662 17547 : iter = reachable_regs.begin_mutable_base_regs ();
2663 41144 : iter != reachable_regs.end_mutable_base_regs ();
2664 23597 : ++iter)
2665 : {
2666 23597 : const region *base_reg = (*iter);
2667 23597 : unset_dynamic_extents (base_reg);
2668 : }
2669 17547 : }
2670 :
2671 : /* Traverse the regions in this model, determining what regions are
2672 : reachable from the store and populating *OUT.
2673 :
2674 : If EXTRA_SVAL is non-NULL, treat it as an additional "root"
2675 : for reachability (for handling return values from functions when
2676 : analyzing return of the only function on the stack).
2677 :
2678 : If UNCERTAINTY is non-NULL, treat any svalues that were recorded
2679 : within it as being maybe-bound as additional "roots" for reachability.
2680 :
2681 : Find svalues that haven't leaked. */
2682 :
2683 : void
2684 867514 : region_model::get_reachable_svalues (value_set *out,
2685 : const svalue *extra_sval,
2686 : const uncertainty_t *uncertainty)
2687 : {
2688 867514 : reachable_regions reachable_regs (this);
2689 :
2690 : /* Add globals and regions that already escaped in previous
2691 : unknown calls. */
2692 867514 : m_store.for_each_cluster (reachable_regions::init_cluster_cb,
2693 : &reachable_regs);
2694 :
2695 867514 : if (extra_sval)
2696 5287 : reachable_regs.handle_value (*extra_sval);
2697 :
2698 867514 : if (uncertainty)
2699 410211 : for (uncertainty_t::iterator iter
2700 383020 : = uncertainty->begin_maybe_bound_svals ();
2701 793231 : iter != uncertainty->end_maybe_bound_svals (); ++iter)
2702 27191 : reachable_regs.handle_value (**iter);
2703 :
2704 : /* Get regions for locals that have explicitly bound values. */
2705 5873984 : for (store::cluster_map_t::iterator iter = m_store.begin ();
2706 5873984 : iter != m_store.end (); ++iter)
2707 : {
2708 5006470 : const region *base_reg = (*iter).first;
2709 5006470 : if (const region *parent = base_reg->get_parent_region ())
2710 5006470 : if (parent->get_kind () == RK_FRAME)
2711 3169935 : reachable_regs.add (base_reg, false);
2712 : }
2713 :
2714 : /* Populate *OUT based on the values that were reachable. */
2715 10109180 : for (value_set::iterator iter
2716 867514 : = reachable_regs.begin_reachable_svals ();
2717 10109180 : iter != reachable_regs.end_reachable_svals (); ++iter)
2718 9241666 : out->add (*iter);
2719 867514 : }
2720 :
2721 : /* Update this model for the RETURN_STMT, using CTXT to report any
2722 : diagnostics. */
2723 :
2724 : void
2725 0 : region_model::on_return (const greturn *return_stmt, region_model_context *ctxt)
2726 : {
2727 0 : tree callee = get_current_function ()->decl;
2728 0 : tree lhs = DECL_RESULT (callee);
2729 0 : tree rhs = gimple_return_retval (return_stmt);
2730 :
2731 0 : if (lhs && rhs)
2732 : {
2733 0 : const svalue *sval = get_rvalue (rhs, ctxt);
2734 0 : const region *ret_reg = get_lvalue (lhs, ctxt);
2735 0 : set_value (ret_reg, sval, ctxt);
2736 : }
2737 0 : }
2738 :
2739 : /* Implementation of region_model::get_lvalue; the latter adds type-checking.
2740 :
2741 : Get the id of the region for PV within this region_model,
2742 : emitting any diagnostics to CTXT. */
2743 :
2744 : const region *
2745 2293273 : region_model::get_lvalue_1 (path_var pv, region_model_context *ctxt) const
2746 : {
2747 2293273 : tree expr = pv.m_tree;
2748 :
2749 2293273 : gcc_assert (expr);
2750 :
2751 2293273 : switch (TREE_CODE (expr))
2752 : {
2753 122 : default:
2754 122 : return m_mgr->get_region_for_unexpected_tree_code (ctxt, expr,
2755 122 : dump_location_t ());
2756 :
2757 13642 : case ARRAY_REF:
2758 13642 : {
2759 13642 : tree array = TREE_OPERAND (expr, 0);
2760 13642 : tree index = TREE_OPERAND (expr, 1);
2761 :
2762 13642 : const region *array_reg = get_lvalue (array, ctxt);
2763 13642 : const svalue *index_sval = get_rvalue (index, ctxt);
2764 13642 : return m_mgr->get_element_region (array_reg,
2765 13642 : TREE_TYPE (TREE_TYPE (array)),
2766 13642 : index_sval);
2767 : }
2768 189 : break;
2769 :
2770 189 : case BIT_FIELD_REF:
2771 189 : {
2772 189 : tree inner_expr = TREE_OPERAND (expr, 0);
2773 189 : const region *inner_reg = get_lvalue (inner_expr, ctxt);
2774 189 : tree num_bits = TREE_OPERAND (expr, 1);
2775 189 : tree first_bit_offset = TREE_OPERAND (expr, 2);
2776 189 : gcc_assert (TREE_CODE (num_bits) == INTEGER_CST);
2777 189 : gcc_assert (TREE_CODE (first_bit_offset) == INTEGER_CST);
2778 189 : concrete_bit_range bits
2779 378 : (concrete_bit_offset (convert_from_integer_cst (first_bit_offset)),
2780 567 : concrete_bit_size (convert_from_integer_cst (num_bits)));
2781 189 : return m_mgr->get_bit_range (inner_reg, TREE_TYPE (expr), bits);
2782 189 : }
2783 70540 : break;
2784 :
2785 70540 : case MEM_REF:
2786 70540 : {
2787 70540 : tree ptr = TREE_OPERAND (expr, 0);
2788 70540 : tree offset = TREE_OPERAND (expr, 1);
2789 70540 : const svalue *ptr_sval = get_rvalue (ptr, ctxt);
2790 70540 : const svalue *offset_sval = get_rvalue (offset, ctxt);
2791 70540 : const region *star_ptr = deref_rvalue (ptr_sval, ptr, ctxt);
2792 70540 : return m_mgr->get_offset_region (star_ptr,
2793 70540 : TREE_TYPE (expr),
2794 70540 : offset_sval);
2795 : }
2796 885546 : break;
2797 :
2798 885546 : case FUNCTION_DECL:
2799 885546 : return m_mgr->get_region_for_fndecl (expr);
2800 :
2801 337 : case LABEL_DECL:
2802 337 : return m_mgr->get_region_for_label (expr);
2803 :
2804 130200 : case VAR_DECL:
2805 : /* Handle globals. */
2806 130200 : if (is_global_var (expr))
2807 45280 : return m_mgr->get_region_for_global (expr);
2808 :
2809 : /* Fall through. */
2810 :
2811 1204808 : case SSA_NAME:
2812 1204808 : case PARM_DECL:
2813 1204808 : case RESULT_DECL:
2814 1204808 : {
2815 1204808 : gcc_assert (TREE_CODE (expr) == SSA_NAME
2816 : || TREE_CODE (expr) == PARM_DECL
2817 : || VAR_P (expr)
2818 : || TREE_CODE (expr) == RESULT_DECL);
2819 :
2820 1204808 : int stack_index = pv.m_stack_depth;
2821 1204808 : const frame_region *frame = get_frame_at_index (stack_index);
2822 1204808 : gcc_assert (frame);
2823 1204808 : return frame->get_region_for_local (m_mgr, expr, ctxt);
2824 : }
2825 :
2826 58943 : case COMPONENT_REF:
2827 58943 : {
2828 : /* obj.field */
2829 58943 : tree obj = TREE_OPERAND (expr, 0);
2830 58943 : tree field = TREE_OPERAND (expr, 1);
2831 58943 : const region *obj_reg = get_lvalue (obj, ctxt);
2832 58943 : return m_mgr->get_field_region (obj_reg, field);
2833 : }
2834 13866 : break;
2835 :
2836 13866 : case STRING_CST:
2837 13866 : return m_mgr->get_region_for_string (expr);
2838 : }
2839 : }
2840 :
2841 : /* Assert that SRC_TYPE can be converted to DST_TYPE as a no-op. */
2842 :
2843 : static void
2844 4997568 : assert_compat_types (tree src_type, tree dst_type)
2845 : {
2846 4997568 : if (src_type && dst_type && !VOID_TYPE_P (dst_type))
2847 : {
2848 : #if CHECKING_P
2849 4997197 : if (!(useless_type_conversion_p (src_type, dst_type)))
2850 0 : internal_error ("incompatible types: %qT and %qT", src_type, dst_type);
2851 : #endif
2852 : }
2853 4997568 : }
2854 :
2855 : /* Return true if SRC_TYPE can be converted to DST_TYPE as a no-op. */
2856 :
2857 : bool
2858 14593 : compat_types_p (tree src_type, tree dst_type)
2859 : {
2860 14593 : if (src_type && dst_type && !VOID_TYPE_P (dst_type))
2861 14593 : if (!(useless_type_conversion_p (src_type, dst_type)))
2862 : return false;
2863 : return true;
2864 : }
2865 :
2866 : /* Get the region for PV within this region_model,
2867 : emitting any diagnostics to CTXT. */
2868 :
2869 : const region *
2870 2293273 : region_model::get_lvalue (path_var pv, region_model_context *ctxt) const
2871 : {
2872 2293273 : if (pv.m_tree == NULL_TREE)
2873 : return nullptr;
2874 :
2875 2293273 : const region *result_reg = get_lvalue_1 (pv, ctxt);
2876 2293273 : assert_compat_types (result_reg->get_type (), TREE_TYPE (pv.m_tree));
2877 2293273 : return result_reg;
2878 : }
2879 :
2880 : /* Get the region for EXPR within this region_model (assuming the most
2881 : recent stack frame if it's a local). */
2882 :
2883 : const region *
2884 1487365 : region_model::get_lvalue (tree expr, region_model_context *ctxt) const
2885 : {
2886 1487365 : return get_lvalue (path_var (expr, get_stack_depth () - 1), ctxt);
2887 : }
2888 :
2889 : /* Implementation of region_model::get_rvalue; the latter adds type-checking.
2890 :
2891 : Get the value of PV within this region_model,
2892 : emitting any diagnostics to CTXT. */
2893 :
2894 : const svalue *
2895 2690091 : region_model::get_rvalue_1 (path_var pv, region_model_context *ctxt) const
2896 : {
2897 2690091 : gcc_assert (pv.m_tree);
2898 :
2899 2690091 : switch (TREE_CODE (pv.m_tree))
2900 : {
2901 103 : default:
2902 103 : return m_mgr->get_or_create_unknown_svalue (TREE_TYPE (pv.m_tree));
2903 :
2904 943816 : case ADDR_EXPR:
2905 943816 : {
2906 : /* "&EXPR". */
2907 943816 : tree expr = pv.m_tree;
2908 943816 : tree op0 = TREE_OPERAND (expr, 0);
2909 943816 : const region *expr_reg = get_lvalue (op0, ctxt);
2910 943816 : return m_mgr->get_ptr_svalue (TREE_TYPE (expr), expr_reg);
2911 : }
2912 130 : break;
2913 :
2914 130 : case BIT_FIELD_REF:
2915 130 : {
2916 130 : tree expr = pv.m_tree;
2917 130 : tree op0 = TREE_OPERAND (expr, 0);
2918 130 : const region *reg = get_lvalue (op0, ctxt);
2919 130 : tree num_bits = TREE_OPERAND (expr, 1);
2920 130 : tree first_bit_offset = TREE_OPERAND (expr, 2);
2921 130 : gcc_assert (TREE_CODE (num_bits) == INTEGER_CST);
2922 130 : gcc_assert (TREE_CODE (first_bit_offset) == INTEGER_CST);
2923 130 : bit_range bits (TREE_INT_CST_LOW (first_bit_offset),
2924 130 : TREE_INT_CST_LOW (num_bits));
2925 130 : return get_rvalue_for_bits (TREE_TYPE (expr), reg, bits, ctxt);
2926 : }
2927 :
2928 28964 : case VAR_DECL:
2929 28964 : if (DECL_HARD_REGISTER (pv.m_tree))
2930 : {
2931 : /* If it has a hard register, it doesn't have a memory region
2932 : and can't be referred to as an lvalue. */
2933 43 : return m_mgr->get_or_create_unknown_svalue (TREE_TYPE (pv.m_tree));
2934 : }
2935 : /* Fall through. */
2936 756881 : case PARM_DECL:
2937 756881 : case SSA_NAME:
2938 756881 : case RESULT_DECL:
2939 756881 : case ARRAY_REF:
2940 756881 : {
2941 756881 : const region *reg = get_lvalue (pv, ctxt);
2942 756881 : return get_store_value (reg, ctxt);
2943 : }
2944 :
2945 174 : case REALPART_EXPR:
2946 174 : case IMAGPART_EXPR:
2947 174 : case VIEW_CONVERT_EXPR:
2948 174 : {
2949 174 : tree expr = pv.m_tree;
2950 174 : tree arg = TREE_OPERAND (expr, 0);
2951 174 : const svalue *arg_sval = get_rvalue (arg, ctxt);
2952 174 : const svalue *sval_unaryop
2953 174 : = m_mgr->get_or_create_unaryop (TREE_TYPE (expr), TREE_CODE (expr),
2954 : arg_sval);
2955 174 : return sval_unaryop;
2956 939691 : };
2957 :
2958 939691 : case INTEGER_CST:
2959 939691 : case REAL_CST:
2960 939691 : case COMPLEX_CST:
2961 939691 : case VECTOR_CST:
2962 939691 : case STRING_CST:
2963 939691 : case RAW_DATA_CST:
2964 939691 : return m_mgr->get_or_create_constant_svalue (pv.m_tree);
2965 :
2966 41 : case POINTER_PLUS_EXPR:
2967 41 : {
2968 41 : tree expr = pv.m_tree;
2969 41 : tree ptr = TREE_OPERAND (expr, 0);
2970 41 : tree offset = TREE_OPERAND (expr, 1);
2971 41 : const svalue *ptr_sval = get_rvalue (ptr, ctxt);
2972 41 : const svalue *offset_sval = get_rvalue (offset, ctxt);
2973 41 : const svalue *sval_binop
2974 41 : = m_mgr->get_or_create_binop (TREE_TYPE (expr), POINTER_PLUS_EXPR,
2975 : ptr_sval, offset_sval);
2976 41 : return sval_binop;
2977 : }
2978 :
2979 : /* Binary ops. */
2980 93 : case PLUS_EXPR:
2981 93 : case MULT_EXPR:
2982 93 : case BIT_AND_EXPR:
2983 93 : case BIT_IOR_EXPR:
2984 93 : case BIT_XOR_EXPR:
2985 93 : {
2986 93 : tree expr = pv.m_tree;
2987 93 : tree arg0 = TREE_OPERAND (expr, 0);
2988 93 : tree arg1 = TREE_OPERAND (expr, 1);
2989 93 : const svalue *arg0_sval = get_rvalue (arg0, ctxt);
2990 93 : const svalue *arg1_sval = get_rvalue (arg1, ctxt);
2991 93 : const svalue *sval_binop
2992 93 : = m_mgr->get_or_create_binop (TREE_TYPE (expr), TREE_CODE (expr),
2993 : arg0_sval, arg1_sval);
2994 93 : return sval_binop;
2995 : }
2996 :
2997 48987 : case COMPONENT_REF:
2998 48987 : case MEM_REF:
2999 48987 : {
3000 48987 : const region *ref_reg = get_lvalue (pv, ctxt);
3001 48987 : return get_store_value (ref_reg, ctxt);
3002 : }
3003 132 : case OBJ_TYPE_REF:
3004 132 : {
3005 132 : tree expr = OBJ_TYPE_REF_EXPR (pv.m_tree);
3006 132 : return get_rvalue (expr, ctxt);
3007 : }
3008 : }
3009 : }
3010 :
3011 : /* Get the value of PV within this region_model,
3012 : emitting any diagnostics to CTXT. */
3013 :
3014 : const svalue *
3015 2725538 : region_model::get_rvalue (path_var pv, region_model_context *ctxt) const
3016 : {
3017 2725538 : if (pv.m_tree == NULL_TREE)
3018 : return nullptr;
3019 :
3020 2690091 : const svalue *result_sval = get_rvalue_1 (pv, ctxt);
3021 :
3022 2690091 : assert_compat_types (result_sval->get_type (), TREE_TYPE (pv.m_tree));
3023 :
3024 2690091 : result_sval = check_for_poison (result_sval, pv.m_tree, nullptr, ctxt);
3025 :
3026 2690091 : return result_sval;
3027 : }
3028 :
3029 : /* Get the value of EXPR within this region_model (assuming the most
3030 : recent stack frame if it's a local). */
3031 :
3032 : const svalue *
3033 2724670 : region_model::get_rvalue (tree expr, region_model_context *ctxt) const
3034 : {
3035 2724670 : return get_rvalue (path_var (expr, get_stack_depth () - 1), ctxt);
3036 : }
3037 :
3038 : /* Return true if this model is on a path with "main" as the entrypoint
3039 : (as opposed to one in which we're merely analyzing a subset of the
3040 : path through the code). */
3041 :
3042 : bool
3043 3451680 : region_model::called_from_main_p () const
3044 : {
3045 3451680 : if (!m_current_frame)
3046 : return false;
3047 : /* Determine if the oldest stack frame in this model is for "main". */
3048 3443054 : const frame_region *frame0 = get_frame_at_index (0);
3049 3443054 : gcc_assert (frame0);
3050 3443054 : return id_equal (DECL_NAME (frame0->get_function ().decl), "main");
3051 : }
3052 :
3053 : baseline_state
3054 3451624 : region_model::get_baseline_state () const
3055 : {
3056 3451624 : if (called_from_main_p ())
3057 : return baseline_state::main;
3058 : else
3059 3316257 : return baseline_state::after_main;
3060 : }
3061 :
3062 : /* Subroutine of region_model::get_store_value for when REG is (or is within)
3063 : a global variable that hasn't been touched since the start of this path
3064 : (or was implicitly touched due to a call to an unknown function). */
3065 :
3066 : const svalue *
3067 0 : region_model::get_initial_value_for_global (const region *reg) const
3068 : {
3069 : /* Get the decl that REG is for (or is within). */
3070 0 : const decl_region *base_reg
3071 0 : = reg->get_base_region ()->dyn_cast_decl_region ();
3072 0 : gcc_assert (base_reg);
3073 0 : tree decl = base_reg->get_decl ();
3074 :
3075 : /* Special-case: to avoid having to explicitly update all previously
3076 : untracked globals when calling an unknown fn, they implicitly have
3077 : an unknown value if an unknown call has occurred, unless this is
3078 : static to-this-TU and hasn't escaped. Globals that have escaped
3079 : are explicitly tracked, so we shouldn't hit this case for them. */
3080 0 : if (m_store.called_unknown_fn_p ()
3081 0 : && TREE_PUBLIC (decl)
3082 0 : && !TREE_READONLY (decl))
3083 0 : return m_mgr->get_or_create_unknown_svalue (reg->get_type ());
3084 :
3085 : /* If we are on a path from the entrypoint from "main" and we have a
3086 : global decl defined in this TU that hasn't been touched yet, then
3087 : the initial value of REG can be taken from the initialization value
3088 : of the decl. */
3089 0 : if (called_from_main_p () || TREE_READONLY (decl))
3090 0 : return reg->get_initial_value_at_main (m_mgr);
3091 :
3092 : /* Otherwise, return INIT_VAL(REG). */
3093 0 : return m_mgr->get_or_create_initial_value (reg);
3094 : }
3095 :
3096 : /* Get a value for REG, looking it up in the store, or otherwise falling
3097 : back to "initial" or "unknown" values.
3098 : Use CTXT to report any warnings associated with reading from REG. */
3099 :
3100 : const svalue *
3101 2115734 : region_model::get_store_value (const region *reg,
3102 : region_model_context *ctxt) const
3103 : {
3104 : /* Getting the value of an empty region gives an unknown_svalue. */
3105 2115734 : if (reg->empty_p (*m_mgr))
3106 8 : return m_mgr->get_or_create_unknown_svalue (reg->get_type ());
3107 :
3108 : /* Special-case: handle var_decls in the constant pool. */
3109 2115726 : if (const decl_region *decl_reg = reg->dyn_cast_decl_region ())
3110 2051639 : if (const svalue *sval = decl_reg->maybe_get_constant_value (m_mgr))
3111 : return sval;
3112 :
3113 2115710 : auto &bv = get_store_bits (reg->get_memory_range (*m_mgr), ctxt);
3114 2115710 : return m_mgr->get_svalue_from_bit_vector (reg->get_type (), bv);
3115 : }
3116 :
3117 : /* Simulate reading the bits for MEM_RANGE.
3118 : If CTXT is non-null, complain to CTXT about any problems associated
3119 : with the read. */
3120 :
3121 : const symbolic::bit_vector &
3122 2120427 : region_model::get_store_bits (const symbolic::memory_range &mem_range,
3123 : region_model_context *ctxt) const
3124 : {
3125 2120427 : if (check_memory_range_access (mem_range,
3126 : access_direction::read,
3127 : nullptr,
3128 : ctxt))
3129 : {
3130 : /* Return a dummy bit_vector if any part of the access is invalid. */
3131 452 : auto &bv_mgr = m_mgr->get_node_manager ().get_bit_vector_manager ();
3132 452 : return bv_mgr.get_unknown_bits (mem_range.get_size ());
3133 : }
3134 2119975 : return m_store.get_bits (mem_range, get_baseline_state ());
3135 : }
3136 :
3137 : /* Get the bit_contents of BASE_REG.
3138 : No access checking is performed. */
3139 :
3140 : const symbolic::bit_contents &
3141 6649 : region_model::get_bit_contents (const region &base_reg) const
3142 : {
3143 6649 : return get_store ()->get_bit_contents (base_reg, get_baseline_state ());
3144 : }
3145 :
3146 : /* Set the bit_contents of BASE_REG.
3147 : No access checking or alias-handling is performed. */
3148 :
3149 : void
3150 5578 : region_model::set_bit_contents_raw (const region &base_reg,
3151 : const symbolic::bit_contents &new_bc)
3152 : {
3153 5578 : return get_store ()->set_bit_contents_raw (base_reg, new_bc, *this);
3154 : }
3155 :
3156 : /* Return false if REG does not exist, true if it may do.
3157 : This is for detecting regions within the stack that don't exist anymore
3158 : after frames are popped. */
3159 :
3160 : bool
3161 1125054 : region_model::region_exists_p (const region *reg) const
3162 : {
3163 : /* If within a stack frame, check that the stack frame is live. */
3164 1125054 : if (const frame_region *enclosing_frame = reg->maybe_get_frame_region ())
3165 : {
3166 : /* Check that the current frame is the enclosing frame, or is called
3167 : by it. */
3168 1558204 : for (const frame_region *iter_frame = get_current_frame (); iter_frame;
3169 535289 : iter_frame = iter_frame->get_calling_frame ())
3170 1543687 : if (iter_frame == enclosing_frame)
3171 : return true;
3172 : return false;
3173 : }
3174 :
3175 : return true;
3176 : }
3177 :
3178 : /* Get a region for referencing PTR_SVAL, creating a region if need be, and
3179 : potentially generating warnings via CTXT.
3180 : PTR_SVAL must be of pointer type.
3181 : PTR_TREE if non-NULL can be used when emitting diagnostics. */
3182 :
3183 : const region *
3184 110122 : region_model::deref_rvalue (const svalue *ptr_sval, tree ptr_tree,
3185 : region_model_context *ctxt,
3186 : bool add_nonnull_constraint) const
3187 : {
3188 110122 : gcc_assert (ptr_sval);
3189 110122 : gcc_assert (ptr_sval->get_type ());
3190 110122 : gcc_assert (POINTER_TYPE_P (ptr_sval->get_type ()));
3191 :
3192 : /* If we're dereferencing PTR_SVAL, assume that it is non-NULL; add this
3193 : as a constraint. This suppresses false positives from
3194 : -Wanalyzer-null-dereference for the case where we later have an
3195 : if (PTR_SVAL) that would occur if we considered the false branch
3196 : and transitioned the malloc state machine from start->null. */
3197 110122 : if (add_nonnull_constraint)
3198 : {
3199 99500 : tree null_ptr_cst = build_int_cst (ptr_sval->get_type (), 0);
3200 99500 : const svalue *null_ptr
3201 99500 : = m_mgr->get_or_create_constant_svalue (null_ptr_cst);
3202 99500 : m_constraints->add_constraint (ptr_sval, NE_EXPR, null_ptr);
3203 : }
3204 :
3205 110122 : switch (ptr_sval->get_kind ())
3206 : {
3207 : default:
3208 : break;
3209 :
3210 6696 : case SK_BINOP:
3211 6696 : {
3212 6696 : const binop_svalue *binop_sval
3213 6696 : = as_a <const binop_svalue *> (ptr_sval);
3214 6696 : switch (binop_sval->get_op ())
3215 : {
3216 6696 : case POINTER_PLUS_EXPR:
3217 6696 : {
3218 : /* If we have a symbolic value expressing pointer arithmetic,
3219 : try to convert it to a suitable region. */
3220 6696 : const region *parent_region
3221 6696 : = deref_rvalue (binop_sval->get_arg0 (), NULL_TREE, ctxt);
3222 6696 : const svalue *offset = binop_sval->get_arg1 ();
3223 6696 : tree type= TREE_TYPE (ptr_sval->get_type ());
3224 6696 : return m_mgr->get_offset_region (parent_region, type, offset);
3225 : }
3226 : default:
3227 : break;
3228 : }
3229 : }
3230 : break;
3231 :
3232 0 : case SK_POISONED:
3233 0 : {
3234 0 : if (ctxt)
3235 : {
3236 0 : tree ptr = get_representative_tree (ptr_sval);
3237 : /* If we can't get a representative tree for PTR_SVAL
3238 : (e.g. if it hasn't been bound into the store), then
3239 : fall back on PTR_TREE, if non-NULL. */
3240 0 : if (!ptr)
3241 0 : ptr = ptr_tree;
3242 0 : if (ptr)
3243 : {
3244 0 : const poisoned_svalue *poisoned_sval
3245 0 : = as_a <const poisoned_svalue *> (ptr_sval);
3246 0 : enum poison_kind pkind = poisoned_sval->get_poison_kind ();
3247 0 : ctxt->warn (make_poisoned_value_diagnostic
3248 0 : (ptr, pkind, nullptr, nullptr));
3249 : }
3250 : }
3251 : }
3252 : break;
3253 : }
3254 :
3255 103426 : return m_mgr->get_symbolic_region (ptr_sval);
3256 : }
3257 :
3258 : /* Attempt to get BITS within any value of REG, as TYPE.
3259 : In particular, extract values from compound_svalues for the case
3260 : where there's a concrete binding at BITS.
3261 : Return an unknown svalue if we can't handle the given case.
3262 : Use CTXT to report any warnings associated with reading from REG. */
3263 :
3264 : const svalue *
3265 130 : region_model::get_rvalue_for_bits (tree type,
3266 : const region *reg,
3267 : const bit_range &bits,
3268 : region_model_context *ctxt) const
3269 : {
3270 130 : auto &bv = get_store_bits (reg->get_memory_range (*m_mgr), ctxt);
3271 130 : auto &cropped = bv.get_cropped_bits (convert_from_bit_range (bits));
3272 130 : return get_manager ()->get_svalue_from_bit_vector (type, cropped);
3273 : }
3274 :
3275 : /* Use CTXT to warn If BASE_REG is a region that shouldn't be written to. */
3276 :
3277 : void
3278 201391 : region_model::check_for_writable_region (const region *base_reg,
3279 : region_model_context *ctxt) const
3280 : {
3281 : /* Fail gracefully if CTXT is nullptr. */
3282 201391 : if (!ctxt)
3283 : return;
3284 :
3285 201391 : switch (base_reg->get_kind ())
3286 : {
3287 : default:
3288 : break;
3289 9 : case RK_FUNCTION:
3290 9 : {
3291 9 : const function_region *func_reg = as_a <const function_region *> (base_reg);
3292 9 : tree fndecl = func_reg->get_fndecl ();
3293 9 : ctxt->warn (make_write_to_const_diagnostic (func_reg, fndecl));
3294 : }
3295 9 : break;
3296 4 : case RK_LABEL:
3297 4 : {
3298 4 : const label_region *label_reg = as_a <const label_region *> (base_reg);
3299 4 : tree label = label_reg->get_label ();
3300 4 : ctxt->warn (make_write_to_const_diagnostic (label_reg, label));
3301 : }
3302 4 : break;
3303 189178 : case RK_DECL:
3304 189178 : {
3305 189178 : const decl_region *decl_reg = as_a <const decl_region *> (base_reg);
3306 189178 : tree decl = decl_reg->get_decl ();
3307 : /* Warn about writes to const globals.
3308 : Don't warn for writes to const locals, and params in particular,
3309 : since we would warn in push_frame when setting them up (e.g the
3310 : "this" param is "T* const"). */
3311 189178 : if (TREE_READONLY (decl)
3312 189178 : && is_global_var (decl))
3313 20 : ctxt->warn (make_write_to_const_diagnostic (base_reg, decl));
3314 : }
3315 : break;
3316 51 : case RK_STRING:
3317 51 : ctxt->warn (make_write_to_string_literal_diagnostic (base_reg));
3318 51 : break;
3319 : }
3320 : }
3321 :
3322 : /* Get the capacity of REG in bytes. */
3323 :
3324 : const svalue *
3325 712007 : region_model::get_capacity (const region *reg) const
3326 : {
3327 714469 : switch (reg->get_kind ())
3328 : {
3329 : default:
3330 : break;
3331 617881 : case RK_DECL:
3332 617881 : {
3333 617881 : const decl_region *decl_reg = as_a <const decl_region *> (reg);
3334 617881 : tree decl = decl_reg->get_decl ();
3335 617881 : if (TREE_CODE (decl) == SSA_NAME)
3336 : {
3337 542237 : tree type = TREE_TYPE (decl);
3338 542237 : tree size = TYPE_SIZE (type);
3339 542237 : return get_rvalue (size, nullptr);
3340 : }
3341 : else
3342 : {
3343 75644 : tree size = decl_init_size (decl, false);
3344 75644 : if (size)
3345 75287 : return get_rvalue (size, nullptr);
3346 : }
3347 : }
3348 : break;
3349 2462 : case RK_SIZED:
3350 : /* Look through sized regions to get at the capacity
3351 : of the underlying regions. */
3352 2462 : return get_capacity (reg->get_parent_region ());
3353 3351 : case RK_STRING:
3354 3351 : {
3355 : /* "Capacity" here means "size". */
3356 3351 : const string_region *string_reg = as_a <const string_region *> (reg);
3357 3351 : tree string_cst = string_reg->get_string_cst ();
3358 3351 : return m_mgr->get_or_create_int_cst (size_type_node,
3359 3351 : TREE_STRING_LENGTH (string_cst));
3360 : }
3361 91132 : break;
3362 : }
3363 :
3364 91132 : if (const svalue *recorded = get_dynamic_extents (reg))
3365 : return recorded;
3366 :
3367 77282 : return m_mgr->get_or_create_unknown_svalue (sizetype);
3368 : }
3369 :
3370 : const symbolic::scalar<integer_with_unit<units::byte>> &
3371 662570 : region_model::get_capacity_as_scalar (const region *reg) const
3372 : {
3373 662570 : const svalue *sval = get_capacity (reg);
3374 :
3375 662570 : auto &byte_mgr = m_mgr->get_node_manager ().get_scalars ().get_bytes ();
3376 662570 : return byte_mgr.get_scalar_from_svalue (*sval);
3377 : }
3378 :
3379 : /* If CTXT is non-NULL, use it to warn about any problems accessing MEM_RANGE,
3380 : using DIR to determine if this access is a read or write.
3381 : Return TRUE if an OOB access was detected.
3382 : If SVAL_HINT is non-NULL, use it as a hint in diagnostics
3383 : about the value that would be written to the memory. */
3384 :
3385 : bool
3386 2401864 : region_model::
3387 : check_memory_range_access (const symbolic::memory_range &mem_range,
3388 : enum access_direction dir,
3389 : const svalue *sval_hint,
3390 : region_model_context *ctxt) const
3391 : {
3392 : /* Fail gracefully if CTXT is NULL. */
3393 2401864 : if (!ctxt)
3394 : return false;
3395 :
3396 661237 : bool oob_access_detected = false;
3397 661237 : check_memory_range_for_taint (mem_range, dir, ctxt);
3398 661237 : if (!check_memory_range_bounds (mem_range, dir, sval_hint, ctxt))
3399 837 : oob_access_detected = true;
3400 :
3401 661237 : switch (dir)
3402 : {
3403 0 : default:
3404 0 : gcc_unreachable ();
3405 : case access_direction::read:
3406 : /* Currently a no-op. */
3407 : break;
3408 201391 : case access_direction::write:
3409 201391 : check_for_writable_region (&mem_range.get_base_region (), ctxt);
3410 201391 : break;
3411 : }
3412 : return oob_access_detected;
3413 : }
3414 :
3415 : /* If CTXT is non-NULL, use it to warn about any problems accessing REG,
3416 : using DIR to determine if this access is a read or write.
3417 : Return TRUE if an OOB access was detected.
3418 : If SVAL_HINT is non-NULL, use it as a hint in diagnostics
3419 : about the value that would be written to REG. */
3420 :
3421 : bool
3422 97 : region_model::check_region_access (const region *reg,
3423 : enum access_direction dir,
3424 : const svalue *sval_hint,
3425 : region_model_context *ctxt) const
3426 : {
3427 97 : return check_memory_range_access (reg->get_memory_range (*get_manager ()),
3428 : dir,
3429 : sval_hint,
3430 97 : ctxt);
3431 : }
3432 :
3433 : /* If CTXT is non-NULL, use it to warn about any problems writing to REG. */
3434 :
3435 : void
3436 97 : region_model::check_region_for_write (const region *dest_reg,
3437 : const svalue *sval_hint,
3438 : region_model_context *ctxt) const
3439 : {
3440 97 : check_region_access (dest_reg, access_direction::write, sval_hint, ctxt);
3441 97 : }
3442 :
3443 : /* Concrete subclass for casts of pointers that lead to trailing bytes. */
3444 :
3445 : class dubious_allocation_size
3446 : : public pending_diagnostic_subclass<dubious_allocation_size>
3447 : {
3448 : public:
3449 114 : dubious_allocation_size (const region *lhs, const region *rhs,
3450 : const svalue *capacity_sval, tree expr,
3451 : const gimple *stmt)
3452 114 : : m_lhs (lhs), m_rhs (rhs),
3453 114 : m_capacity_sval (capacity_sval), m_expr (expr),
3454 114 : m_stmt (stmt),
3455 114 : m_has_allocation_event (false)
3456 : {
3457 114 : gcc_assert (m_capacity_sval);
3458 : }
3459 :
3460 1201 : const char *get_kind () const final override
3461 : {
3462 1201 : return "dubious_allocation_size";
3463 : }
3464 :
3465 114 : bool operator== (const dubious_allocation_size &other) const
3466 : {
3467 114 : return (m_stmt == other.m_stmt
3468 114 : && pending_diagnostic::same_tree_p (m_expr, other.m_expr));
3469 : }
3470 :
3471 228 : int get_controlling_option () const final override
3472 : {
3473 228 : return OPT_Wanalyzer_allocation_size;
3474 : }
3475 :
3476 114 : bool emit (diagnostic_emission_context &ctxt) final override
3477 : {
3478 114 : ctxt.add_cwe (131);
3479 :
3480 114 : return ctxt.warn ("allocated buffer size is not a multiple"
3481 114 : " of the pointee's size");
3482 : }
3483 :
3484 : bool
3485 228 : describe_final_event (pretty_printer &pp,
3486 : const evdesc::final_event &) final override
3487 : {
3488 228 : tree pointee_type = TREE_TYPE (m_lhs->get_type ());
3489 228 : if (m_has_allocation_event)
3490 : {
3491 220 : pp_printf (&pp,
3492 : "assigned to %qT here;"
3493 : " %<sizeof (%T)%> is %qE",
3494 220 : m_lhs->get_type (), pointee_type,
3495 : size_in_bytes (pointee_type));
3496 220 : return true;
3497 : }
3498 : /* Fallback: Typically, we should always see an allocation_event
3499 : before. */
3500 8 : if (m_expr)
3501 : {
3502 8 : if (TREE_CODE (m_expr) == INTEGER_CST)
3503 : {
3504 8 : pp_printf (&pp,
3505 : "allocated %E bytes and assigned to"
3506 : " %qT here; %<sizeof (%T)%> is %qE",
3507 8 : m_expr, m_lhs->get_type (), pointee_type,
3508 : size_in_bytes (pointee_type));
3509 8 : return true;
3510 : }
3511 : else
3512 : {
3513 0 : pp_printf (&pp,
3514 : "allocated %qE bytes and assigned to"
3515 : " %qT here; %<sizeof (%T)%> is %qE",
3516 0 : m_expr, m_lhs->get_type (), pointee_type,
3517 : size_in_bytes (pointee_type));
3518 0 : return true;
3519 : }
3520 : }
3521 :
3522 0 : pp_printf (&pp,
3523 : "allocated and assigned to %qT here;"
3524 : " %<sizeof (%T)%> is %qE",
3525 0 : m_lhs->get_type (), pointee_type,
3526 : size_in_bytes (pointee_type));
3527 0 : return true;
3528 : }
3529 :
3530 : void
3531 110 : add_region_creation_events (const region *,
3532 : tree capacity,
3533 : const event_loc_info &loc_info,
3534 : checker_path &emission_path) final override
3535 : {
3536 110 : emission_path.add_event
3537 110 : (std::make_unique<region_creation_event_allocation_size>
3538 110 : (capacity, loc_info));
3539 :
3540 110 : m_has_allocation_event = true;
3541 110 : }
3542 :
3543 228 : void mark_interesting_stuff (interesting_t *interest) final override
3544 : {
3545 228 : interest->add_region_creation (m_rhs);
3546 228 : }
3547 :
3548 : void
3549 0 : maybe_add_sarif_properties (diagnostics::sarif_object &result_obj)
3550 : const final override
3551 : {
3552 0 : auto &props = result_obj.get_or_create_properties ();
3553 : #define PROPERTY_PREFIX "gcc/analyzer/dubious_allocation_size/"
3554 0 : props.set (PROPERTY_PREFIX "lhs", m_lhs->to_json ());
3555 0 : props.set (PROPERTY_PREFIX "rhs", m_rhs->to_json ());
3556 0 : props.set (PROPERTY_PREFIX "capacity_sval", m_capacity_sval->to_json ());
3557 : #undef PROPERTY_PREFIX
3558 0 : }
3559 :
3560 : private:
3561 : const region *m_lhs;
3562 : const region *m_rhs;
3563 : const svalue *m_capacity_sval;
3564 : const tree m_expr;
3565 : const gimple *m_stmt;
3566 : bool m_has_allocation_event;
3567 : };
3568 :
3569 : /* Return true on dubious allocation sizes for constant sizes. */
3570 :
3571 : static bool
3572 2339 : capacity_compatible_with_type (tree cst, tree pointee_size_tree,
3573 : bool is_struct)
3574 : {
3575 2339 : gcc_assert (TREE_CODE (cst) == INTEGER_CST);
3576 2339 : gcc_assert (TREE_CODE (pointee_size_tree) == INTEGER_CST);
3577 :
3578 2339 : unsigned HOST_WIDE_INT pointee_size = TREE_INT_CST_LOW (pointee_size_tree);
3579 2339 : unsigned HOST_WIDE_INT alloc_size = TREE_INT_CST_LOW (cst);
3580 :
3581 2339 : if (is_struct)
3582 873 : return alloc_size == 0 || alloc_size >= pointee_size;
3583 1466 : return alloc_size % pointee_size == 0;
3584 : }
3585 :
3586 : static bool
3587 370 : capacity_compatible_with_type (tree cst, tree pointee_size_tree)
3588 : {
3589 0 : return capacity_compatible_with_type (cst, pointee_size_tree, false);
3590 : }
3591 :
3592 : /* Checks whether SVAL could be a multiple of SIZE_CST.
3593 :
3594 : It works by visiting all svalues inside SVAL until it reaches
3595 : atomic nodes. From those, it goes back up again and adds each
3596 : node that is not a multiple of SIZE_CST to the RESULT_SET. */
3597 :
3598 6756 : class size_visitor : public visitor
3599 : {
3600 : public:
3601 3378 : size_visitor (tree size_cst, const svalue *root_sval, constraint_manager *cm)
3602 3378 : : m_size_cst (size_cst), m_root_sval (root_sval), m_cm (cm)
3603 : {
3604 3378 : m_root_sval->accept (this);
3605 : }
3606 :
3607 3378 : bool is_dubious_capacity ()
3608 : {
3609 3378 : return result_set.contains (m_root_sval);
3610 : }
3611 :
3612 386 : void visit_constant_svalue (const constant_svalue *sval) final override
3613 : {
3614 386 : check_constant (sval->get_constant (), sval);
3615 386 : }
3616 :
3617 238 : void visit_unaryop_svalue (const unaryop_svalue *sval) final override
3618 : {
3619 238 : if (CONVERT_EXPR_CODE_P (sval->get_op ())
3620 238 : && result_set.contains (sval->get_arg ()))
3621 105 : result_set.add (sval);
3622 238 : }
3623 :
3624 374 : void visit_binop_svalue (const binop_svalue *sval) final override
3625 : {
3626 374 : const svalue *arg0 = sval->get_arg0 ();
3627 374 : const svalue *arg1 = sval->get_arg1 ();
3628 :
3629 374 : switch (sval->get_op ())
3630 : {
3631 268 : case MULT_EXPR:
3632 268 : if (result_set.contains (arg0) && result_set.contains (arg1))
3633 24 : result_set.add (sval);
3634 : break;
3635 86 : case PLUS_EXPR:
3636 86 : case MINUS_EXPR:
3637 86 : if (result_set.contains (arg0) || result_set.contains (arg1))
3638 28 : result_set.add (sval);
3639 : break;
3640 : default:
3641 : break;
3642 : }
3643 374 : }
3644 :
3645 0 : void visit_unmergeable_svalue (const unmergeable_svalue *sval) final override
3646 : {
3647 0 : if (result_set.contains (sval->get_arg ()))
3648 0 : result_set.add (sval);
3649 0 : }
3650 :
3651 12 : void visit_widening_svalue (const widening_svalue *sval) final override
3652 : {
3653 12 : const svalue *base = sval->get_base_svalue ();
3654 12 : const svalue *iter = sval->get_iter_svalue ();
3655 :
3656 12 : if (result_set.contains (base) || result_set.contains (iter))
3657 8 : result_set.add (sval);
3658 12 : }
3659 :
3660 283 : void visit_initial_svalue (const initial_svalue *sval) final override
3661 : {
3662 283 : equiv_class_id id = equiv_class_id::null ();
3663 283 : if (m_cm->get_equiv_class_by_svalue (sval, &id))
3664 : {
3665 63 : if (tree cst = id.get_obj (*m_cm).get_any_constant ())
3666 0 : check_constant (cst, sval);
3667 : }
3668 220 : else if (!m_cm->sval_constrained_p (sval))
3669 : {
3670 166 : result_set.add (sval);
3671 : }
3672 283 : }
3673 :
3674 : void
3675 30 : visit_svalue_from_bit_vector (const svalue_from_bit_vector *sval)
3676 : final override
3677 : {
3678 30 : equiv_class_id id = equiv_class_id::null ();
3679 30 : if (m_cm->get_equiv_class_by_svalue (sval, &id))
3680 13 : if (tree cst = id.get_obj (*m_cm).get_any_constant ())
3681 8 : check_constant (cst, sval);
3682 30 : }
3683 :
3684 : private:
3685 394 : void check_constant (tree cst, const svalue *sval)
3686 : {
3687 394 : switch (TREE_CODE (cst))
3688 : {
3689 : default:
3690 : /* Assume all unhandled operands are compatible. */
3691 : break;
3692 370 : case INTEGER_CST:
3693 370 : if (!capacity_compatible_with_type (cst, m_size_cst))
3694 60 : result_set.add (sval);
3695 : break;
3696 : }
3697 394 : }
3698 :
3699 : tree m_size_cst;
3700 : const svalue *m_root_sval;
3701 : constraint_manager *m_cm;
3702 : value_set result_set; /* Used as a mapping of svalue*->bool. */
3703 : };
3704 :
3705 : /* Return true if SIZE_CST is a power of 2, and we have
3706 : CAPACITY_SVAL == ((X | (Y - 1) ) + 1), since it is then a multiple
3707 : of SIZE_CST, as used by Linux kernel's round_up macro. */
3708 :
3709 : static bool
3710 3382 : is_round_up (tree size_cst,
3711 : const svalue *capacity_sval)
3712 : {
3713 3382 : if (!integer_pow2p (size_cst))
3714 : return false;
3715 3382 : const binop_svalue *binop_sval = capacity_sval->dyn_cast_binop_svalue ();
3716 3382 : if (!binop_sval)
3717 : return false;
3718 260 : if (binop_sval->get_op () != PLUS_EXPR)
3719 : return false;
3720 70 : tree rhs_cst = binop_sval->get_arg1 ()->maybe_get_constant ();
3721 70 : if (!rhs_cst)
3722 : return false;
3723 70 : if (!integer_onep (rhs_cst))
3724 : return false;
3725 :
3726 : /* We have CAPACITY_SVAL == (LHS + 1) for some LHS expression. */
3727 :
3728 4 : const binop_svalue *lhs_binop_sval
3729 4 : = binop_sval->get_arg0 ()->dyn_cast_binop_svalue ();
3730 4 : if (!lhs_binop_sval)
3731 : return false;
3732 4 : if (lhs_binop_sval->get_op () != BIT_IOR_EXPR)
3733 : return false;
3734 :
3735 4 : tree inner_rhs_cst = lhs_binop_sval->get_arg1 ()->maybe_get_constant ();
3736 4 : if (!inner_rhs_cst)
3737 : return false;
3738 :
3739 4 : if (wi::to_widest (inner_rhs_cst) + 1 != wi::to_widest (size_cst))
3740 : return false;
3741 : return true;
3742 : }
3743 :
3744 : /* Return true if CAPACITY_SVAL is known to be a multiple of SIZE_CST. */
3745 :
3746 : static bool
3747 3382 : is_multiple_p (tree size_cst,
3748 : const svalue *capacity_sval)
3749 : {
3750 3438 : if (const svalue *sval = capacity_sval->maybe_undo_cast ())
3751 : return is_multiple_p (size_cst, sval);
3752 :
3753 3382 : if (is_round_up (size_cst, capacity_sval))
3754 : return true;
3755 :
3756 : return false;
3757 : }
3758 :
3759 : /* Return true if we should emit a dubious_allocation_size warning
3760 : on assigning a region of capacity CAPACITY_SVAL bytes to a pointer
3761 : of type with size SIZE_CST, where CM expresses known constraints. */
3762 :
3763 : static bool
3764 3382 : is_dubious_capacity (tree size_cst,
3765 : const svalue *capacity_sval,
3766 : constraint_manager *cm)
3767 : {
3768 3382 : if (is_multiple_p (size_cst, capacity_sval))
3769 : return false;
3770 3378 : size_visitor v (size_cst, capacity_sval, cm);
3771 3378 : return v.is_dubious_capacity ();
3772 3378 : }
3773 :
3774 :
3775 : /* Return true if a struct or union either uses the inheritance pattern,
3776 : where the first field is a base struct, or the flexible array member
3777 : pattern, where the last field is an array without a specified size. */
3778 :
3779 : static bool
3780 4565 : struct_or_union_with_inheritance_p (tree struc)
3781 : {
3782 4565 : tree iter = TYPE_FIELDS (struc);
3783 4565 : if (iter == NULL_TREE)
3784 : return false;
3785 4557 : if (RECORD_OR_UNION_TYPE_P (TREE_TYPE (iter)))
3786 : return true;
3787 :
3788 : tree last_field;
3789 107013 : while (iter != NULL_TREE)
3790 : {
3791 102855 : last_field = iter;
3792 102855 : iter = DECL_CHAIN (iter);
3793 : }
3794 :
3795 4158 : if (last_field != NULL_TREE
3796 4158 : && TREE_CODE (TREE_TYPE (last_field)) == ARRAY_TYPE)
3797 38 : return true;
3798 :
3799 : return false;
3800 : }
3801 :
3802 : /* Return true if the lhs and rhs of an assignment have different types. */
3803 :
3804 : static bool
3805 154020 : is_any_cast_p (const gimple *stmt)
3806 : {
3807 154020 : if (const gassign *assign = dyn_cast <const gassign *> (stmt))
3808 117356 : return gimple_assign_cast_p (assign)
3809 220059 : || !pending_diagnostic::same_tree_p (
3810 102703 : TREE_TYPE (gimple_assign_lhs (assign)),
3811 102703 : TREE_TYPE (gimple_assign_rhs1 (assign)));
3812 36664 : else if (const gcall *call = dyn_cast <const gcall *> (stmt))
3813 : {
3814 36256 : tree lhs = gimple_call_lhs (call);
3815 65362 : return lhs != NULL_TREE && !pending_diagnostic::same_tree_p (
3816 29106 : TREE_TYPE (gimple_call_lhs (call)),
3817 : gimple_call_return_type (call));
3818 : }
3819 :
3820 : return false;
3821 : }
3822 :
3823 : /* On pointer assignments, check whether the buffer size of
3824 : RHS_SVAL is compatible with the type of the LHS_REG.
3825 : Use a non-null CTXT to report allocation size warnings. */
3826 :
3827 : void
3828 277317 : region_model::check_region_size (const region *lhs_reg, const svalue *rhs_sval,
3829 : region_model_context *ctxt) const
3830 : {
3831 277317 : if (!ctxt || ctxt->get_stmt () == nullptr)
3832 269184 : return;
3833 : /* Only report warnings on assignments that actually change the type. */
3834 154020 : if (!is_any_cast_p (ctxt->get_stmt ()))
3835 : return;
3836 :
3837 44991 : tree pointer_type = lhs_reg->get_type ();
3838 44991 : if (pointer_type == NULL_TREE || !POINTER_TYPE_P (pointer_type))
3839 : return;
3840 :
3841 13412 : tree pointee_type = TREE_TYPE (pointer_type);
3842 : /* Make sure that the type on the left-hand size actually has a size. */
3843 13412 : if (pointee_type == NULL_TREE || VOID_TYPE_P (pointee_type)
3844 26058 : || TYPE_SIZE_UNIT (pointee_type) == NULL_TREE)
3845 : return;
3846 :
3847 : /* Bail out early on function pointers. */
3848 12553 : if (TREE_CODE (pointee_type) == FUNCTION_TYPE)
3849 : return;
3850 :
3851 : /* Bail out early on pointers to structs where we can
3852 : not deduce whether the buffer size is compatible. */
3853 12269 : bool is_struct = RECORD_OR_UNION_TYPE_P (pointee_type);
3854 12269 : if (is_struct && struct_or_union_with_inheritance_p (pointee_type))
3855 : return;
3856 :
3857 11832 : tree pointee_size_tree = size_in_bytes (pointee_type);
3858 : /* We give up if the type size is not known at compile-time or the
3859 : type size is always compatible regardless of the buffer size. */
3860 11832 : if (TREE_CODE (pointee_size_tree) != INTEGER_CST
3861 11749 : || integer_zerop (pointee_size_tree)
3862 23568 : || integer_onep (pointee_size_tree))
3863 : return;
3864 :
3865 8133 : const region *rhs_reg = deref_rvalue (rhs_sval, NULL_TREE, ctxt, false);
3866 8133 : const svalue *capacity = get_capacity (rhs_reg);
3867 8133 : switch (capacity->get_kind ())
3868 : {
3869 1969 : case svalue_kind::SK_CONSTANT:
3870 1969 : {
3871 1969 : const constant_svalue *cst_cap_sval
3872 1969 : = as_a <const constant_svalue *> (capacity);
3873 1969 : tree cst_cap = cst_cap_sval->get_constant ();
3874 1969 : if (TREE_CODE (cst_cap) == INTEGER_CST
3875 1969 : && !capacity_compatible_with_type (cst_cap, pointee_size_tree,
3876 : is_struct))
3877 66 : ctxt->warn
3878 132 : (std::make_unique <dubious_allocation_size> (lhs_reg, rhs_reg,
3879 : capacity, cst_cap,
3880 132 : ctxt->get_stmt ()));
3881 : }
3882 1969 : break;
3883 6164 : default:
3884 6164 : {
3885 6164 : if (!is_struct)
3886 : {
3887 3382 : if (is_dubious_capacity (pointee_size_tree,
3888 : capacity,
3889 3382 : m_constraints))
3890 : {
3891 48 : tree expr = get_representative_tree (capacity);
3892 48 : ctxt->warn
3893 96 : (std::make_unique <dubious_allocation_size> (lhs_reg,
3894 : rhs_reg,
3895 : capacity, expr,
3896 96 : ctxt->get_stmt ()));
3897 : }
3898 : }
3899 : break;
3900 : }
3901 : }
3902 : }
3903 :
3904 : /* Write BIT_VEC to the memory starting at MEM_OFFSET.
3905 : If non-null, complain to CTXT about any problems that occur. */
3906 :
3907 : void
3908 281340 : region_model::
3909 : write_to_memory_offset (const symbolic::memory_offset &mem_offset,
3910 : const symbolic::bit_vector &bv,
3911 : region_model_context *ctxt)
3912 : {
3913 281340 : symbolic::memory_range mem_range
3914 : (mem_offset.get_base_region (),
3915 281340 : symbolic_bit_range (mem_offset.get_bit_offset (),
3916 281340 : bv.get_size ()));
3917 281340 : const svalue *sval_hint = nullptr;
3918 281340 : if (auto *bv_sval = bv.dyn_cast_bit_vector_from_svalue ())
3919 167294 : sval_hint = &bv_sval->get_svalue ();
3920 281340 : if (check_memory_range_access (mem_range,
3921 : access_direction::write,
3922 : sval_hint,
3923 : ctxt))
3924 : /* Bail out if any part of the access is invalid. */
3925 370 : return;
3926 481894 : m_store.set_bits (mem_range, bv,
3927 200924 : ctxt ? ctxt->get_uncertainty () : nullptr,
3928 : *this);
3929 : }
3930 :
3931 : /* Set the value of the region given by LHS_REG to the value given
3932 : by RHS_SVAL.
3933 : Use CTXT to report any warnings associated with writing to LHS_REG. */
3934 :
3935 : void
3936 277317 : region_model::set_value (const region *lhs_reg, const svalue *rhs_sval,
3937 : region_model_context *ctxt)
3938 : {
3939 277317 : gcc_assert (lhs_reg);
3940 277317 : gcc_assert (rhs_sval);
3941 :
3942 : /* Setting the value of an empty region is a no-op. */
3943 277317 : if (lhs_reg->empty_p (*m_mgr))
3944 : return;
3945 :
3946 277317 : check_region_size (lhs_reg, rhs_sval, ctxt);
3947 :
3948 277317 : auto &bv_mgr = m_mgr->get_node_manager ().get_bit_vector_manager ();
3949 277317 : auto &bv = bv_mgr.get_bit_vector_from_svalue (*rhs_sval);
3950 :
3951 277317 : symbolic::memory_offset mem_offset = lhs_reg->get_memory_offset (*m_mgr);
3952 277317 : write_to_memory_offset (mem_offset, bv, ctxt);
3953 : }
3954 :
3955 : /* Set the value of the region given by LHS to the value given by RHS. */
3956 :
3957 : void
3958 84 : region_model::set_value (tree lhs, tree rhs, region_model_context *ctxt)
3959 : {
3960 84 : const region *lhs_reg = get_lvalue (lhs, ctxt);
3961 84 : const svalue *rhs_sval = get_rvalue (rhs, ctxt);
3962 84 : gcc_assert (lhs_reg);
3963 84 : gcc_assert (rhs_sval);
3964 84 : set_value (lhs_reg, rhs_sval, ctxt);
3965 84 : }
3966 :
3967 : /* Issue a note specifying that a particular function parameter is expected
3968 : to be a valid null-terminated string. */
3969 :
3970 : static void
3971 167 : inform_about_expected_null_terminated_string_arg (const call_arg_details &ad)
3972 : {
3973 : // TODO: ideally we'd underline the param here
3974 167 : inform (DECL_SOURCE_LOCATION (ad.m_called_fndecl),
3975 : "argument %d of %qD must be a pointer to a null-terminated string",
3976 167 : ad.m_arg_idx + 1, ad.m_called_fndecl);
3977 167 : }
3978 :
3979 : static tree
3980 317 : get_tree_for_byte_offset (tree ptr_expr, concrete_byte_offset byte_offset)
3981 : {
3982 317 : gcc_assert (ptr_expr);
3983 317 : tree ptype = build_pointer_type_for_mode (char_type_node, ptr_mode, true);
3984 317 : return fold_build2
3985 : (MEM_REF,
3986 : char_type_node,
3987 : ptr_expr,
3988 : make_integer_cst_from_integer (ptype, byte_offset.get_integer (), true));
3989 : }
3990 :
3991 : /* Simulate a series of reads of REG until we find a 0 byte
3992 : (equivalent to calling strlen).
3993 :
3994 : Complain to CTXT and return NULL if:
3995 : - the buffer pointed to isn't null-terminated
3996 : - the buffer pointed to has any uninitialized bytes before any 0-terminator
3997 : - any of the reads aren't within the bounds of the underlying base region
3998 :
3999 : Otherwise, return a svalue for the number of bytes read (strlen + 1),
4000 : and, if OUT_BV is non-NULL, write to *OUT_BV with a bit_vector
4001 : representing the content of REG up to and including the terminator. */
4002 :
4003 : const svalue *
4004 6359 : region_model::
4005 : scan_for_null_terminator_1 (const region *reg,
4006 : tree expr,
4007 : const symbolic::bit_vector **out_bv,
4008 : region_model_context *ctxt) const
4009 : {
4010 6359 : logger *logger = ctxt ? ctxt->get_logger () : nullptr;
4011 :
4012 6359 : auto sym_ptr = reg->get_pointer (*m_mgr);
4013 6359 : auto &bc = m_store.get_bit_contents (sym_ptr.get_base_region (),
4014 : get_baseline_state ());
4015 :
4016 6359 : auto &bv_mgr = m_mgr->get_node_manager ().get_bit_vector_manager ();
4017 :
4018 6359 : integer_with_unit<units::byte> conc_offset;
4019 6359 : if (!concrete_from_symbolic (sym_ptr.get_byte_offset (), &conc_offset))
4020 : {
4021 47 : if (out_bv)
4022 0 : *out_bv = &bv_mgr.get_unknown_bits ();
4023 47 : if (logger)
4024 0 : logger->log ("offset is symbolic");
4025 47 : return m_mgr->get_or_create_unknown_svalue (size_type_node);
4026 : }
4027 6312 : string_scan scan = bc.scan_for_first_zero_byte (conc_offset);
4028 :
4029 6312 : if (scan.m_state == string_scan::state::cannot_scan)
4030 : {
4031 2780 : if (out_bv)
4032 279 : *out_bv = &bv_mgr.get_unknown_bits ();
4033 2780 : return m_mgr->get_or_create_unknown_svalue (size_type_node);
4034 : }
4035 :
4036 3532 : auto &byte_mgr = m_mgr->get_node_manager ().get_scalars ().get_bytes ();
4037 :
4038 : /* If we ran into a problem, then don't trust the bit_vector or the
4039 : bytes read: provide "unknown" for both. */
4040 3532 : if (scan.m_state == string_scan::state::found_poison)
4041 : {
4042 : /* Simulate reading from the bad byte to trigger a warning,
4043 : then give up. */
4044 325 : symbolic::pointer bad_byte_ptr (sym_ptr.get_base_region (),
4045 325 : symbolic_from_concrete (scan.m_byte_offset,
4046 325 : byte_mgr));
4047 325 : tree bad_byte_expr
4048 : = (expr
4049 959 : ? get_tree_for_byte_offset (expr, scan.m_byte_offset)
4050 : : NULL_TREE);
4051 650 : read_bytes (bad_byte_ptr,
4052 : bad_byte_expr,
4053 325 : byte_mgr.get_concrete (1_byte),
4054 : ctxt);
4055 325 : if (out_bv)
4056 47 : *out_bv = &bv_mgr.get_unknown_bits ();
4057 325 : return m_mgr->get_or_create_unknown_svalue (size_type_node);
4058 : }
4059 :
4060 : /* Simulate accessing the bytes read, which ought to trigger
4061 : any warnings (out-of-bounds, uninit, etc). */
4062 : // number of bytes read == offset of last byte read + 1:
4063 3207 : concrete_byte_size num_bytes_read = scan.m_byte_offset + 1_byte - conc_offset;
4064 3207 : auto &bv = read_bytes (sym_ptr, expr,
4065 3207 : byte_mgr.get_concrete (num_bytes_read),
4066 : ctxt);
4067 3207 : if (out_bv)
4068 360 : *out_bv = &bv;
4069 :
4070 3207 : return m_mgr->get_or_create_int_cst (size_type_node,
4071 3207 : num_bytes_read.as_unsigned_long ());
4072 9519 : }
4073 :
4074 : /* Like region_model::scan_for_null_terminator_1, but add logging. */
4075 :
4076 : const svalue *
4077 6359 : region_model::
4078 : scan_for_null_terminator (const region *reg,
4079 : tree expr,
4080 : const symbolic::bit_vector **out_bv,
4081 : region_model_context *ctxt) const
4082 : {
4083 6359 : logger *logger = ctxt ? ctxt->get_logger () : nullptr;
4084 6359 : LOG_SCOPE (logger);
4085 6359 : if (logger)
4086 : {
4087 2 : pretty_printer *pp = logger->get_printer ();
4088 2 : logger->start_log_line ();
4089 2 : logger->log_partial ("region: ");
4090 2 : reg->dump_to_pp (pp, true);
4091 2 : logger->end_log_line ();
4092 : }
4093 6359 : if (out_bv)
4094 686 : *out_bv = nullptr;
4095 6359 : const svalue *sval
4096 6359 : = scan_for_null_terminator_1 (reg, expr, out_bv, ctxt);
4097 6359 : if (sval && out_bv)
4098 686 : gcc_assert (*out_bv);
4099 6359 : if (logger)
4100 : {
4101 2 : pretty_printer *pp = logger->get_printer ();
4102 2 : logger->start_log_line ();
4103 2 : logger->log_partial ("length result: ");
4104 2 : if (sval)
4105 2 : sval->dump_to_pp (pp, true);
4106 : else
4107 0 : pp_printf (pp, "NULL");
4108 2 : logger->end_log_line ();
4109 2 : if (out_bv)
4110 : {
4111 2 : logger->start_log_line ();
4112 2 : logger->log_partial ("content result: ");
4113 2 : if (*out_bv)
4114 2 : (*out_bv)->dump_to_pp (pp);
4115 : else
4116 0 : pp_printf (pp, "NULL");
4117 2 : logger->end_log_line ();
4118 : }
4119 : }
4120 12718 : return sval;
4121 6359 : }
4122 :
4123 : /* Check that argument ARG_IDX (0-based) to the call described by CD
4124 : is a pointer to a valid null-terminated string.
4125 :
4126 : Simulate scanning through the buffer, reading until we find a 0 byte
4127 : (equivalent to calling strlen).
4128 :
4129 : Complain and return nullptr if:
4130 : - the buffer pointed to isn't null-terminated
4131 : - the buffer pointed to has any uninitialized bytes before any 0-terminator
4132 : - any of the reads aren't within the bounds of the underlying base region
4133 :
4134 : Otherwise, return a svalue for strlen of the buffer (*not* including
4135 : the null terminator).
4136 :
4137 : TODO: we should also complain if:
4138 : - the pointer is NULL (or could be). */
4139 :
4140 : const svalue *
4141 221 : region_model::check_for_null_terminated_string_arg (const call_details &cd,
4142 : unsigned arg_idx) const
4143 : {
4144 221 : return check_for_null_terminated_string_arg (cd,
4145 : arg_idx,
4146 : false, /* include_terminator */
4147 221 : nullptr); // out_sval
4148 : }
4149 :
4150 :
4151 : /* Check that argument ARG_IDX (0-based) to the call described by CD
4152 : is a pointer to a valid null-terminated string.
4153 :
4154 : Simulate scanning through the buffer, reading until we find a 0 byte
4155 : (equivalent to calling strlen).
4156 :
4157 : Complain and return nullptr if:
4158 : - the buffer pointed to isn't null-terminated
4159 : - the buffer pointed to has any uninitialized bytes before any 0-terminator
4160 : - any of the reads aren't within the bounds of the underlying base region
4161 :
4162 : Otherwise, return a svalue. This will be the number of bytes read
4163 : (including the null terminator) if INCLUDE_TERMINATOR is true, or strlen
4164 : of the buffer (not including the null terminator) if it is false.
4165 :
4166 : Also, when returning an svalue, if OUT_BV is non-nullptr, write to
4167 : *OUT_BV with a bit_vector representing the content of the buffer up to
4168 : and including the terminator.
4169 :
4170 : TODO: we should also complain if:
4171 : - the pointer is NULL (or could be). */
4172 :
4173 : const svalue *
4174 6000 : region_model::
4175 : check_for_null_terminated_string_arg (const call_details &cd,
4176 : unsigned arg_idx,
4177 : bool include_terminator,
4178 : const symbolic::bit_vector **out_bv)
4179 : const
4180 : {
4181 0 : class null_terminator_check_event : public custom_event
4182 : {
4183 : public:
4184 179 : null_terminator_check_event (const event_loc_info &loc_info,
4185 : const call_arg_details &arg_details)
4186 : : custom_event (loc_info),
4187 179 : m_arg_details (arg_details)
4188 : {
4189 : }
4190 :
4191 340 : void print_desc (pretty_printer &pp) const final override
4192 : {
4193 340 : if (m_arg_details.m_arg_expr)
4194 340 : pp_printf (&pp,
4195 : "while looking for null terminator"
4196 : " for argument %i (%qE) of %qD...",
4197 340 : m_arg_details.m_arg_idx + 1,
4198 : m_arg_details.m_arg_expr,
4199 340 : m_arg_details.m_called_fndecl);
4200 : else
4201 0 : pp_printf (&pp,
4202 : "while looking for null terminator"
4203 : " for argument %i of %qD...",
4204 0 : m_arg_details.m_arg_idx + 1,
4205 0 : m_arg_details.m_called_fndecl);
4206 340 : }
4207 :
4208 : private:
4209 : const call_arg_details m_arg_details;
4210 : };
4211 :
4212 0 : class null_terminator_check_decl_note
4213 : : public pending_note_subclass<null_terminator_check_decl_note>
4214 : {
4215 : public:
4216 179 : null_terminator_check_decl_note (const call_arg_details &arg_details)
4217 179 : : m_arg_details (arg_details)
4218 : {
4219 : }
4220 :
4221 1594 : const char *get_kind () const final override
4222 : {
4223 1594 : return "null_terminator_check_decl_note";
4224 : }
4225 :
4226 167 : void emit () const final override
4227 : {
4228 167 : inform_about_expected_null_terminated_string_arg (m_arg_details);
4229 167 : }
4230 :
4231 797 : bool operator== (const null_terminator_check_decl_note &other) const
4232 : {
4233 797 : return m_arg_details == other.m_arg_details;
4234 : }
4235 :
4236 : private:
4237 : const call_arg_details m_arg_details;
4238 : };
4239 :
4240 : /* Subclass of decorated_region_model_context that
4241 : adds the above event and note to any saved diagnostics. */
4242 6000 : class annotating_ctxt : public annotating_context
4243 : {
4244 : public:
4245 6000 : annotating_ctxt (const call_details &cd,
4246 : unsigned arg_idx)
4247 : : annotating_context (cd.get_ctxt ()),
4248 6000 : m_cd (cd),
4249 6000 : m_arg_idx (arg_idx)
4250 : {
4251 : }
4252 179 : void add_annotations () final override
4253 : {
4254 179 : call_arg_details arg_details (m_cd, m_arg_idx);
4255 358 : event_loc_info loc_info (m_cd.get_location (),
4256 179 : m_cd.get_model ()->get_current_function ()->decl,
4257 358 : m_cd.get_model ()->get_stack_depth ());
4258 :
4259 179 : add_event
4260 179 : (std::make_unique<null_terminator_check_event> (loc_info,
4261 : arg_details));
4262 179 : add_note
4263 179 : (std::make_unique <null_terminator_check_decl_note> (arg_details));
4264 179 : }
4265 : private:
4266 : const call_details &m_cd;
4267 : unsigned m_arg_idx;
4268 : };
4269 :
4270 : /* Use this ctxt below so that any diagnostics that get added
4271 : get annotated. */
4272 6000 : annotating_ctxt my_ctxt (cd, arg_idx);
4273 :
4274 6000 : const svalue *arg_sval = cd.get_arg_svalue (arg_idx);
4275 6000 : const region *buf_reg
4276 6000 : = deref_rvalue (arg_sval, cd.get_arg_tree (arg_idx), &my_ctxt);
4277 :
4278 12000 : if (const svalue *num_bytes_read_sval
4279 6000 : = scan_for_null_terminator (buf_reg,
4280 : cd.get_arg_tree (arg_idx),
4281 : out_bv,
4282 : &my_ctxt))
4283 : {
4284 6000 : if (out_bv)
4285 686 : gcc_assert (*out_bv);
4286 6000 : if (include_terminator)
4287 : return num_bytes_read_sval;
4288 : else
4289 : {
4290 : /* strlen is (bytes_read - 1). */
4291 5314 : const svalue *one = m_mgr->get_or_create_int_cst (size_type_node, 1);
4292 5314 : return m_mgr->get_or_create_binop (size_type_node,
4293 : MINUS_EXPR,
4294 : num_bytes_read_sval,
4295 5314 : one);
4296 : }
4297 : }
4298 : else
4299 : return nullptr;
4300 : }
4301 :
4302 : /* Remove all bindings overlapping REG within the store. */
4303 :
4304 : void
4305 7338 : region_model::clobber_region (const region *reg)
4306 : {
4307 7338 : m_store.clobber_region (reg, get_baseline_state (), *m_mgr);
4308 7338 : }
4309 :
4310 : /* Remove any bindings for REG within the store. */
4311 :
4312 : void
4313 173109 : region_model::purge_region (const region *reg)
4314 : {
4315 173109 : m_store.purge_region (reg);
4316 173109 : }
4317 :
4318 : /* Zero-fill REG.
4319 : Use CTXT to report any warnings associated with the write
4320 : (e.g. out-of-bounds). */
4321 :
4322 : void
4323 1448 : region_model::zero_fill_region (const region *reg,
4324 : region_model_context *ctxt)
4325 : {
4326 1448 : auto mem_range = reg->get_memory_range (*m_mgr);
4327 1448 : if (mem_range.get_size ().is_zero_p ())
4328 1448 : return;
4329 1422 : auto &bv_mgr = m_mgr->get_node_manager ().get_bit_vector_manager ();
4330 1422 : auto &all_zeros = bv_mgr.get_all_zeros (mem_range.get_size ());
4331 1422 : write_to_memory_offset
4332 1422 : (symbolic::memory_offset (mem_range.get_base_region (),
4333 1422 : mem_range.get_start_offset ()),
4334 : all_zeros,
4335 : ctxt);
4336 : }
4337 :
4338 : /* Copy BYTES to DEST_SYM_PTR.
4339 : Use CTXT to report any warnings associated with the copy
4340 : (e.g. out-of-bounds writes). */
4341 :
4342 : void
4343 1914 : region_model::write_bytes (symbolic::pointer dest_sym_ptr,
4344 : const symbolic::bit_vector &bytes,
4345 : region_model_context *ctxt)
4346 : {
4347 1914 : symbolic::memory_offset mem_offset (dest_sym_ptr.get_base_region (),
4348 1914 : bits_from_bytes (dest_sym_ptr.get_byte_offset ()));
4349 1914 : write_to_memory_offset (mem_offset, bytes, ctxt);
4350 1914 : }
4351 :
4352 : /* Read NUM_BYTES bytes from SRC_SYM_PTR.
4353 : Use CTXT to report any warnings associated with the copy
4354 : (e.g. out-of-bounds reads, copying of uninitialized values, etc). */
4355 :
4356 : const symbolic::bit_vector &
4357 4876 : region_model::read_bytes (symbolic::pointer src_sym_ptr,
4358 : tree src_ptr_expr,
4359 : const symbolic_byte_size &num_bytes,
4360 : region_model_context *ctxt) const
4361 : {
4362 4876 : auto &bv_mgr = m_mgr->get_node_manager ().get_bit_vector_manager ();
4363 4876 : if (auto *from_val = num_bytes.dyn_cast_scalar_from_svalue ())
4364 : {
4365 720 : if (from_val->get_svalue ().get_kind () == SK_UNKNOWN)
4366 289 : return bv_mgr.get_unknown_bytes (num_bytes);
4367 : }
4368 4587 : symbolic::memory_range src_mem_range (src_sym_ptr, num_bytes);
4369 4587 : auto &bytes = get_store_bits (src_mem_range, ctxt);
4370 4587 : check_bytes_for_poison (bytes, src_sym_ptr, src_ptr_expr, ctxt);
4371 4587 : return bytes;
4372 : }
4373 :
4374 : /* Copy NUM_BYTES_SVAL bytes from SRC_REG to DEST_REG.
4375 : Use CTXT to report any warnings associated with the copy
4376 : (e.g. out-of-bounds reads/writes, copying of uninitialized values,
4377 : etc). */
4378 :
4379 : void
4380 670 : region_model::copy_bytes (symbolic::pointer dest_sym_ptr,
4381 : symbolic::pointer src_sym_ptr,
4382 : tree src_ptr_expr,
4383 : const symbolic_byte_size &num_bytes,
4384 : region_model_context *ctxt)
4385 : {
4386 670 : if (num_bytes.is_zero_p ())
4387 : return;
4388 660 : auto &bytes = read_bytes (src_sym_ptr, src_ptr_expr, num_bytes, ctxt);
4389 660 : write_bytes (dest_sym_ptr, bytes, ctxt);
4390 : }
4391 :
4392 : /* Mark REG as having unknown content. */
4393 :
4394 : void
4395 558 : region_model::mark_region_as_unknown (const region *reg,
4396 : uncertainty_t *uncertainty)
4397 : {
4398 558 : m_store.mark_region_as_unknown (reg, get_baseline_state (),
4399 : uncertainty, *this);
4400 558 : }
4401 :
4402 : /* Conjure a new new bit_contents for the effect of STMT on BASE_REG
4403 : and update the region in the store accordingly. */
4404 :
4405 : void
4406 508 : region_model::mark_region_as_conjured (const region &base_reg,
4407 : const gimple &stmt,
4408 : region_model_context *ctxt)
4409 : {
4410 508 : m_store.mark_region_as_conjured (base_reg,
4411 : get_baseline_state (),
4412 : stmt,
4413 508 : conjured_purge (this, ctxt));
4414 508 : }
4415 :
4416 : bool
4417 157909 : equal_bit_vectors_p (const svalue &lhs,
4418 : const svalue &rhs,
4419 : const region_model_manager &rmm)
4420 : {
4421 157909 : auto &bv_mgr = rmm.get_node_manager ().get_bit_vector_manager ();
4422 157909 : auto &lhs_bv = bv_mgr.get_bit_vector_from_svalue (lhs);
4423 157909 : auto &rhs_bv = bv_mgr.get_bit_vector_from_svalue (rhs);
4424 :
4425 : // TODO: not necessarily true e.g. if contains unknown bits
4426 157909 : return &lhs_bv == &rhs_bv;
4427 : }
4428 :
4429 : const svalue *
4430 486057 : region_model::canonicalize_svalue_for_constraint (const svalue *sval) const
4431 : {
4432 : /* Unwrap any unmergeable values. */
4433 486057 : sval = sval->unwrap_any_unmergeable ();
4434 :
4435 : // Canonicalize pointers involved in constraints to use (void *)
4436 486057 : if (sval->get_type () && POINTER_TYPE_P (sval->get_type ()))
4437 140413 : sval = get_manager ()->get_or_create_cast (ptr_type_node, sval);
4438 486057 : if (auto *sym_ptr = sval->maybe_get_symbolic_pointer ())
4439 25643 : sval = get_manager ()->get_ptr_svalue (ptr_type_node, *sym_ptr);
4440 :
4441 486057 : return sval;
4442 : }
4443 :
4444 : /* Predicate for guarding against infinite recursion in eval_condition,
4445 : preventing a case where we cycle between canonicalization that adds
4446 : a cast and folding that tries to remove the cast. */
4447 :
4448 : bool
4449 3079 : region_model::
4450 : can_recurse_eval_condition_p (const unaryop_svalue *unary_op) const
4451 : {
4452 3079 : return (canonicalize_svalue_for_constraint (unary_op->get_arg ())
4453 3079 : != unary_op);
4454 : }
4455 :
4456 : /* Determine what is known about the condition "LHS_SVAL OP RHS_SVAL" within
4457 : this model. */
4458 :
4459 : tristate
4460 170323 : region_model::eval_condition (const svalue *lhs,
4461 : enum tree_code op,
4462 : const svalue *rhs) const
4463 : {
4464 170323 : gcc_assert (lhs);
4465 170323 : gcc_assert (rhs);
4466 :
4467 : /* For now, make no attempt to capture constraints on floating-point
4468 : values. */
4469 170323 : if ((lhs->get_type () && FLOAT_TYPE_P (lhs->get_type ()))
4470 340574 : || (rhs->get_type () && FLOAT_TYPE_P (rhs->get_type ())))
4471 72 : return tristate::unknown ();
4472 :
4473 : /* See what we know based on the values. */
4474 :
4475 170251 : lhs = canonicalize_svalue_for_constraint (lhs);
4476 170251 : rhs = canonicalize_svalue_for_constraint (rhs);
4477 :
4478 170251 : if (lhs == rhs
4479 170251 : || equal_bit_vectors_p (*lhs, *rhs, *get_manager ()))
4480 : {
4481 : /* If we have the same svalue, then we have equality
4482 : (apart from NaN-handling).
4483 : TODO: should this definitely be the case for poisoned values? */
4484 : /* Poisoned and unknown values are "unknowable". */
4485 13451 : if (lhs->get_kind () == SK_POISONED
4486 13451 : || lhs->get_kind () == SK_UNKNOWN)
4487 1021 : return tristate::TS_UNKNOWN;
4488 :
4489 12430 : switch (op)
4490 : {
4491 9419 : case EQ_EXPR:
4492 9419 : case GE_EXPR:
4493 9419 : case LE_EXPR:
4494 9419 : return tristate::TS_TRUE;
4495 :
4496 3011 : case NE_EXPR:
4497 3011 : case GT_EXPR:
4498 3011 : case LT_EXPR:
4499 3011 : return tristate::TS_FALSE;
4500 :
4501 : default:
4502 : /* For other ops, use the logic below. */
4503 : break;
4504 : }
4505 : }
4506 :
4507 : /* If we have a pair of pointer_svalues, compare them. */
4508 156800 : if (auto *lhs_sym_ptr = lhs->maybe_get_symbolic_pointer ())
4509 13165 : if (auto *rhs_sym_ptr = rhs->maybe_get_symbolic_pointer ())
4510 : {
4511 884 : tristate res = symbolic::pointer::eval_condition (*lhs_sym_ptr,
4512 : op,
4513 : *rhs_sym_ptr,
4514 : *this);
4515 884 : if (res.is_known ())
4516 593 : return res;
4517 : /* Otherwise, only known through constraints. */
4518 : }
4519 :
4520 156207 : if (const constant_svalue *cst_lhs = lhs->dyn_cast_constant_svalue ())
4521 : {
4522 : /* If we have a pair of constants, compare them. */
4523 42979 : if (const constant_svalue *cst_rhs = rhs->dyn_cast_constant_svalue ())
4524 11010 : return constant_svalue::eval_condition (cst_lhs, op, cst_rhs);
4525 : else
4526 : {
4527 : /* When we have one constant, put it on the RHS. */
4528 31969 : std::swap (lhs, rhs);
4529 31969 : op = swap_tree_comparison (op);
4530 : }
4531 : }
4532 145197 : gcc_assert (lhs->get_kind () != SK_CONSTANT);
4533 :
4534 : /* Handle comparison against zero. */
4535 145197 : if (const constant_svalue *cst_rhs = rhs->dyn_cast_constant_svalue ())
4536 120889 : if (zerop (cst_rhs->get_constant ()))
4537 : {
4538 71959 : if (const pointer_svalue *ptr = lhs->dyn_cast_pointer_svalue ())
4539 : {
4540 12177 : if (ptr->non_null_p ())
4541 : {
4542 4002 : switch (op)
4543 : {
4544 0 : default:
4545 0 : gcc_unreachable ();
4546 :
4547 324 : case EQ_EXPR:
4548 324 : case GE_EXPR:
4549 324 : case LE_EXPR:
4550 324 : return tristate::TS_FALSE;
4551 :
4552 3678 : case NE_EXPR:
4553 3678 : case GT_EXPR:
4554 3678 : case LT_EXPR:
4555 3678 : return tristate::TS_TRUE;
4556 : }
4557 : }
4558 : }
4559 59782 : else if (const binop_svalue *binop = lhs->dyn_cast_binop_svalue ())
4560 : {
4561 : /* Treat offsets from a non-NULL pointer as being non-NULL. This
4562 : isn't strictly true, in that eventually ptr++ will wrap
4563 : around and be NULL, but it won't occur in practise and thus
4564 : can be used to suppress effectively false positives that we
4565 : shouldn't warn for. */
4566 7860 : if (binop->get_op () == POINTER_PLUS_EXPR)
4567 : {
4568 1994 : tristate lhs_ts = eval_condition (binop->get_arg0 (), op, rhs);
4569 1994 : if (lhs_ts.is_known ())
4570 1320 : return lhs_ts;
4571 : }
4572 : }
4573 103844 : else if (const unaryop_svalue *unaryop
4574 51922 : = lhs->dyn_cast_unaryop_svalue ())
4575 : {
4576 2256 : if (unaryop->get_op () == NEGATE_EXPR)
4577 : {
4578 : /* e.g. "-X <= 0" is equivalent to X >= 0". */
4579 51 : tristate lhs_ts = eval_condition (unaryop->get_arg (),
4580 : swap_tree_comparison (op),
4581 : rhs);
4582 51 : if (lhs_ts.is_known ())
4583 48 : return lhs_ts;
4584 : }
4585 : }
4586 : }
4587 :
4588 : /* Handle rejection of equality for comparisons of the initial values of
4589 : "external" values (such as params) with the address of locals. */
4590 139827 : if (const initial_svalue *init_lhs = lhs->dyn_cast_initial_svalue ())
4591 31090 : if (auto *sym_ptr = rhs->maybe_get_symbolic_pointer ())
4592 : {
4593 138 : tristate res = compare_initial_and_pointer (init_lhs, *sym_ptr);
4594 138 : if (res.is_known ())
4595 72 : return res;
4596 : }
4597 139755 : if (const initial_svalue *init_rhs = rhs->dyn_cast_initial_svalue ())
4598 4917 : if (auto *sym_ptr = lhs->maybe_get_symbolic_pointer ())
4599 : {
4600 132 : tristate res = compare_initial_and_pointer (init_rhs, *sym_ptr);
4601 132 : if (res.is_known ())
4602 0 : return res;
4603 : }
4604 :
4605 139755 : if (const widening_svalue *widen_lhs = lhs->dyn_cast_widening_svalue ())
4606 4016 : if (tree rhs_cst = rhs->maybe_get_constant ())
4607 : {
4608 2053 : tristate res = widen_lhs->eval_condition_without_cm (op, rhs_cst);
4609 2053 : if (res.is_known ())
4610 49 : return res;
4611 : }
4612 :
4613 : /* Handle comparisons between two svalues with more than one operand. */
4614 139706 : if (const binop_svalue *binop = lhs->dyn_cast_binop_svalue ())
4615 : {
4616 21867 : switch (op)
4617 : {
4618 : default:
4619 : break;
4620 2487 : case EQ_EXPR:
4621 2487 : {
4622 : /* TODO: binops can be equal even if they are not structurally
4623 : equal in case of commutative operators. */
4624 2487 : tristate res = structural_equality (lhs, rhs);
4625 2487 : if (res.is_true ())
4626 44 : return res;
4627 : }
4628 2443 : break;
4629 693 : case LE_EXPR:
4630 693 : {
4631 693 : tristate res = structural_equality (lhs, rhs);
4632 693 : if (res.is_true ())
4633 0 : return res;
4634 : }
4635 693 : break;
4636 5699 : case GE_EXPR:
4637 5699 : {
4638 5699 : tristate res = structural_equality (lhs, rhs);
4639 5699 : if (res.is_true ())
4640 42 : return res;
4641 5657 : res = symbolic_greater_than (binop, rhs);
4642 5657 : if (res.is_true ())
4643 44 : return res;
4644 : }
4645 : break;
4646 7696 : case GT_EXPR:
4647 7696 : {
4648 7696 : tristate res = symbolic_greater_than (binop, rhs);
4649 7696 : if (res.is_true ())
4650 155 : return res;
4651 : }
4652 7541 : break;
4653 : }
4654 : }
4655 :
4656 : /* Try range_op, but avoid cases where we have been sloppy about types. */
4657 139421 : if (lhs->get_type ()
4658 139421 : && rhs->get_type ()
4659 278842 : && range_compatible_p (lhs->get_type (), rhs->get_type ()))
4660 : {
4661 136044 : value_range lhs_vr, rhs_vr;
4662 136044 : if (lhs->maybe_get_value_range (lhs_vr))
4663 59148 : if (rhs->maybe_get_value_range (rhs_vr))
4664 : {
4665 46870 : range_op_handler handler (op);
4666 46870 : if (handler)
4667 : {
4668 46870 : int_range_max out;
4669 46870 : if (handler.fold_range (out, boolean_type_node, lhs_vr, rhs_vr))
4670 : {
4671 46870 : if (out.zero_p ())
4672 293 : return tristate::TS_FALSE;
4673 46577 : if (!out.contains_zero_p ())
4674 207 : return tristate::TS_TRUE;
4675 : }
4676 46870 : }
4677 : }
4678 136044 : }
4679 :
4680 : /* Attempt to unwrap cast if there is one, and the types match.
4681 : Don't do it if the cast is due to the canonicalization above. */
4682 138921 : tree lhs_type = lhs->get_type ();
4683 138921 : tree rhs_type = rhs->get_type ();
4684 138921 : if (lhs_type && rhs_type)
4685 : {
4686 138921 : const unaryop_svalue *lhs_un_op = dyn_cast <const unaryop_svalue *> (lhs);
4687 138921 : const unaryop_svalue *rhs_un_op = dyn_cast <const unaryop_svalue *> (rhs);
4688 6317 : if (lhs_un_op && CONVERT_EXPR_CODE_P (lhs_un_op->get_op ())
4689 5992 : && rhs_un_op && CONVERT_EXPR_CODE_P (rhs_un_op->get_op ())
4690 161 : && lhs_type == rhs_type
4691 138964 : && (can_recurse_eval_condition_p (lhs_un_op)
4692 0 : || can_recurse_eval_condition_p (rhs_un_op)))
4693 : {
4694 43 : tristate res = eval_condition (lhs_un_op->get_arg (),
4695 : op,
4696 : rhs_un_op->get_arg ());
4697 43 : if (res.is_known ())
4698 3 : return res;
4699 : }
4700 6274 : else if (lhs_un_op && CONVERT_EXPR_CODE_P (lhs_un_op->get_op ())
4701 5949 : && lhs_type == rhs_type
4702 141420 : && can_recurse_eval_condition_p (lhs_un_op))
4703 : {
4704 2534 : tristate res = eval_condition (lhs_un_op->get_arg (), op, rhs);
4705 2534 : if (res.is_known ())
4706 34 : return res;
4707 : }
4708 890 : else if (rhs_un_op && CONVERT_EXPR_CODE_P (rhs_un_op->get_op ())
4709 890 : && lhs_type == rhs_type
4710 136838 : && can_recurse_eval_condition_p (rhs_un_op))
4711 : {
4712 494 : tristate res = eval_condition (lhs, op, rhs_un_op->get_arg ());
4713 494 : if (res.is_known ())
4714 0 : return res;
4715 : }
4716 : }
4717 :
4718 : /* Otherwise, try constraints.
4719 : Cast to const to ensure we don't change the constraint_manager as we
4720 : do this (e.g. by creating equivalence classes). */
4721 138884 : const constraint_manager *constraints = m_constraints;
4722 138884 : return constraints->eval_condition (lhs, op, rhs);
4723 : }
4724 :
4725 : /* Subroutine of region_model::eval_condition, for rejecting
4726 : equality of INIT_VAL(PARM) with &LOCAL. */
4727 :
4728 : tristate
4729 270 : region_model::compare_initial_and_pointer (const initial_svalue *init,
4730 : const symbolic::pointer &ptr) const
4731 : {
4732 : /* If we have a pointer to something within a stack frame, it can't be the
4733 : initial value of a param. */
4734 270 : if (ptr.get_base_region ().maybe_get_frame_region ())
4735 72 : if (init->initial_value_of_param_p ())
4736 72 : return tristate::TS_FALSE;
4737 :
4738 198 : return tristate::TS_UNKNOWN;
4739 : }
4740 :
4741 : /* Return true if SVAL is definitely positive. */
4742 :
4743 : static bool
4744 12811 : is_positive_svalue (const svalue *sval)
4745 : {
4746 12811 : if (tree cst = sval->maybe_get_constant ())
4747 12526 : return !zerop (cst) && get_range_pos_neg (cst) == 1;
4748 285 : tree type = sval->get_type ();
4749 285 : if (!type)
4750 : return false;
4751 : /* Consider a binary operation size_t + int. The analyzer wraps the int in
4752 : an unaryop_svalue, converting it to a size_t, but in the dynamic execution
4753 : the result is smaller than the first operand. Thus, we have to look if
4754 : the argument of the unaryop_svalue is also positive. */
4755 285 : if (const unaryop_svalue *un_op = dyn_cast <const unaryop_svalue *> (sval))
4756 45 : return CONVERT_EXPR_CODE_P (un_op->get_op ()) && TYPE_UNSIGNED (type)
4757 90 : && is_positive_svalue (un_op->get_arg ());
4758 :
4759 240 : if (const binop_svalue *bin_op = dyn_cast <const binop_svalue *> (sval))
4760 75 : if (bin_op->get_op () == MULT_EXPR)
4761 : /* (definitely +ve * definitely +ve) == definitely +ve. */
4762 18 : return (is_positive_svalue (bin_op->get_arg0 ())
4763 18 : && is_positive_svalue (bin_op->get_arg1 ()));
4764 :
4765 222 : return TYPE_UNSIGNED (type);
4766 : }
4767 :
4768 : /* Return true if A is definitely larger than B.
4769 :
4770 : Limitation: does not account for integer overflows and does not try to
4771 : return false, so it can not be used negated. */
4772 :
4773 : tristate
4774 13353 : region_model::symbolic_greater_than (const binop_svalue *bin_a,
4775 : const svalue *b) const
4776 : {
4777 13353 : if (bin_a->get_op () == PLUS_EXPR || bin_a->get_op () == MULT_EXPR)
4778 : {
4779 : /* Eliminate the right-hand side of both svalues. */
4780 12784 : if (const binop_svalue *bin_b = dyn_cast <const binop_svalue *> (b))
4781 1469 : if (bin_a->get_op () == bin_b->get_op ()
4782 812 : && eval_condition (bin_a->get_arg1 (),
4783 : GT_EXPR,
4784 812 : bin_b->get_arg1 ()).is_true ()
4785 2281 : && eval_condition (bin_a->get_arg0 (),
4786 : GE_EXPR,
4787 45 : bin_b->get_arg0 ()).is_true ())
4788 40 : return tristate (tristate::TS_TRUE);
4789 :
4790 : /* Otherwise, try to remove a positive offset or factor from BIN_A. */
4791 12744 : if (is_positive_svalue (bin_a->get_arg1 ())
4792 12744 : && eval_condition (bin_a->get_arg0 (),
4793 12081 : GE_EXPR, b).is_true ())
4794 159 : return tristate (tristate::TS_TRUE);
4795 : }
4796 13154 : return tristate::unknown ();
4797 : }
4798 :
4799 : /* Return true if A and B are equal structurally.
4800 :
4801 : Structural equality means that A and B are equal if the svalues A and B have
4802 : the same nodes at the same positions in the tree and the leafs are equal.
4803 : Equality for conjured_svalues and initial_svalues is determined by comparing
4804 : the pointers while constants are compared by value. That behavior is useful
4805 : to check for binaryop_svlaues that evaluate to the same concrete value but
4806 : might use one operand with a different type but the same constant value.
4807 :
4808 : For example,
4809 : binop_svalue (mult_expr,
4810 : initial_svalue (‘size_t’, decl_region (..., 'some_var')),
4811 : constant_svalue (‘size_t’, 4))
4812 : and
4813 : binop_svalue (mult_expr,
4814 : initial_svalue (‘size_t’, decl_region (..., 'some_var'),
4815 : constant_svalue (‘sizetype’, 4))
4816 : are structurally equal. A concrete C code example, where this occurs, can
4817 : be found in test7 of out-of-bounds-5.c. */
4818 :
4819 : tristate
4820 10666 : region_model::structural_equality (const svalue *a, const svalue *b) const
4821 : {
4822 : /* If A and B are referentially equal, they are also structurally equal. */
4823 10666 : if (a == b)
4824 378 : return tristate (tristate::TS_TRUE);
4825 :
4826 10288 : switch (a->get_kind ())
4827 : {
4828 678 : default:
4829 678 : return tristate::unknown ();
4830 : /* SK_CONJURED and SK_INITIAL are already handled
4831 : by the referential equality above. */
4832 517 : case SK_CONSTANT:
4833 517 : {
4834 517 : tree a_cst = a->maybe_get_constant ();
4835 517 : tree b_cst = b->maybe_get_constant ();
4836 517 : if (a_cst && b_cst)
4837 870 : return tristate (tree_int_cst_equal (a_cst, b_cst));
4838 : }
4839 66 : return tristate (tristate::TS_FALSE);
4840 169 : case SK_UNARYOP:
4841 169 : {
4842 169 : const unaryop_svalue *un_a = as_a <const unaryop_svalue *> (a);
4843 169 : if (const unaryop_svalue *un_b = dyn_cast <const unaryop_svalue *> (b))
4844 169 : return tristate (pending_diagnostic::same_tree_p (un_a->get_type (),
4845 : un_b->get_type ())
4846 173 : && un_a->get_op () == un_b->get_op ()
4847 : && structural_equality (un_a->get_arg (),
4848 338 : un_b->get_arg ()));
4849 : }
4850 0 : return tristate (tristate::TS_FALSE);
4851 8924 : case SK_BINOP:
4852 8924 : {
4853 8924 : const binop_svalue *bin_a = as_a <const binop_svalue *> (a);
4854 8924 : if (const binop_svalue *bin_b = dyn_cast <const binop_svalue *> (b))
4855 1240 : return tristate (bin_a->get_op () == bin_b->get_op ()
4856 : && structural_equality (bin_a->get_arg0 (),
4857 1618 : bin_b->get_arg0 ())
4858 : && structural_equality (bin_a->get_arg1 (),
4859 1618 : bin_b->get_arg1 ()));
4860 : }
4861 8115 : return tristate (tristate::TS_FALSE);
4862 : }
4863 : }
4864 :
4865 : /* Handle various constraints of the form:
4866 : LHS: ((bool)INNER_LHS INNER_OP INNER_RHS))
4867 : OP : == or !=
4868 : RHS: zero
4869 : and (with a cast):
4870 : LHS: CAST([long]int, ((bool)INNER_LHS INNER_OP INNER_RHS))
4871 : OP : == or !=
4872 : RHS: zero
4873 : by adding constraints for INNER_LHS INNEROP INNER_RHS.
4874 :
4875 : Return true if this function can fully handle the constraint; if
4876 : so, add the implied constraint(s) and write true to *OUT if they
4877 : are consistent with existing constraints, or write false to *OUT
4878 : if they contradicts existing constraints.
4879 :
4880 : Return false for cases that this function doeesn't know how to handle.
4881 :
4882 : For example, if we're checking a stored conditional, we'll have
4883 : something like:
4884 : LHS: CAST(long int, (&HEAP_ALLOCATED_REGION(8)!=(int *)0B))
4885 : OP : NE_EXPR
4886 : RHS: zero
4887 : which this function can turn into an add_constraint of:
4888 : (&HEAP_ALLOCATED_REGION(8) != (int *)0B)
4889 :
4890 : Similarly, optimized && and || conditionals lead to e.g.
4891 : if (p && q)
4892 : becoming gimple like this:
4893 : _1 = p_6 == 0B;
4894 : _2 = q_8 == 0B
4895 : _3 = _1 | _2
4896 : On the "_3 is false" branch we can have constraints of the form:
4897 : ((&HEAP_ALLOCATED_REGION(8)!=(int *)0B)
4898 : | (&HEAP_ALLOCATED_REGION(10)!=(int *)0B))
4899 : == 0
4900 : which implies that both _1 and _2 are false,
4901 : which this function can turn into a pair of add_constraints of
4902 : (&HEAP_ALLOCATED_REGION(8)!=(int *)0B)
4903 : and:
4904 : (&HEAP_ALLOCATED_REGION(10)!=(int *)0B). */
4905 :
4906 : bool
4907 48132 : region_model::add_constraints_from_binop (const svalue *outer_lhs,
4908 : enum tree_code outer_op,
4909 : const svalue *outer_rhs,
4910 : bool *out,
4911 : region_model_context *ctxt)
4912 : {
4913 49186 : while (const svalue *cast = outer_lhs->maybe_undo_cast ())
4914 : outer_lhs = cast;
4915 48132 : const binop_svalue *binop_sval = outer_lhs->dyn_cast_binop_svalue ();
4916 48132 : if (!binop_sval)
4917 : return false;
4918 5883 : if (!outer_rhs->all_zeroes_p ())
4919 : return false;
4920 :
4921 4266 : const svalue *inner_lhs = binop_sval->get_arg0 ();
4922 4266 : enum tree_code inner_op = binop_sval->get_op ();
4923 4266 : const svalue *inner_rhs = binop_sval->get_arg1 ();
4924 :
4925 4266 : if (outer_op != NE_EXPR && outer_op != EQ_EXPR)
4926 : return false;
4927 :
4928 : /* We have either
4929 : - "OUTER_LHS != false" (i.e. OUTER is true), or
4930 : - "OUTER_LHS == false" (i.e. OUTER is false). */
4931 3822 : bool is_true = outer_op == NE_EXPR;
4932 :
4933 3822 : switch (inner_op)
4934 : {
4935 : default:
4936 : return false;
4937 :
4938 2594 : case EQ_EXPR:
4939 2594 : case NE_EXPR:
4940 2594 : case GE_EXPR:
4941 2594 : case GT_EXPR:
4942 2594 : case LE_EXPR:
4943 2594 : case LT_EXPR:
4944 2594 : {
4945 : /* ...and "(inner_lhs OP inner_rhs) == 0"
4946 : then (inner_lhs OP inner_rhs) must have the same
4947 : logical value as LHS. */
4948 2594 : if (!is_true)
4949 1226 : inner_op = invert_tree_comparison (inner_op, false /* honor_nans */);
4950 2594 : *out = add_constraint (inner_lhs, inner_op, inner_rhs, ctxt);
4951 2594 : return true;
4952 : }
4953 479 : break;
4954 :
4955 479 : case BIT_AND_EXPR:
4956 479 : if (is_true)
4957 : {
4958 : /* ...and "(inner_lhs & inner_rhs) != 0"
4959 : then both inner_lhs and inner_rhs must be true. */
4960 256 : const svalue *false_sval
4961 256 : = m_mgr->get_or_create_constant_svalue (boolean_false_node);
4962 256 : bool sat1 = add_constraint (inner_lhs, NE_EXPR, false_sval, ctxt);
4963 256 : bool sat2 = add_constraint (inner_rhs, NE_EXPR, false_sval, ctxt);
4964 256 : *out = sat1 && sat2;
4965 256 : return true;
4966 : }
4967 : return false;
4968 :
4969 136 : case BIT_IOR_EXPR:
4970 136 : if (!is_true)
4971 : {
4972 : /* ...and "(inner_lhs | inner_rhs) == 0"
4973 : i.e. "(inner_lhs | inner_rhs)" is false
4974 : then both inner_lhs and inner_rhs must be false. */
4975 74 : const svalue *false_sval
4976 74 : = m_mgr->get_or_create_constant_svalue (boolean_false_node);
4977 74 : bool sat1 = add_constraint (inner_lhs, EQ_EXPR, false_sval, ctxt);
4978 74 : bool sat2 = add_constraint (inner_rhs, EQ_EXPR, false_sval, ctxt);
4979 74 : *out = sat1 && sat2;
4980 74 : return true;
4981 : }
4982 : return false;
4983 : }
4984 : }
4985 :
4986 : /* Attempt to add the constraint "LHS OP RHS" to this region_model.
4987 : If it is consistent with existing constraints, add it, and return true.
4988 : Return false if it contradicts existing constraints.
4989 : Use CTXT for reporting any diagnostics associated with the accesses. */
4990 :
4991 : bool
4992 63396 : region_model::add_constraint (tree lhs, enum tree_code op, tree rhs,
4993 : region_model_context *ctxt)
4994 : {
4995 : /* For now, make no attempt to capture constraints on floating-point
4996 : values. */
4997 63396 : if (FLOAT_TYPE_P (TREE_TYPE (lhs)) || FLOAT_TYPE_P (TREE_TYPE (rhs)))
4998 : return true;
4999 :
5000 63062 : const svalue *lhs_sval = get_rvalue (lhs, ctxt);
5001 63062 : const svalue *rhs_sval = get_rvalue (rhs, ctxt);
5002 :
5003 63062 : return add_constraint (lhs_sval, op, rhs_sval, ctxt);
5004 : }
5005 :
5006 : static bool
5007 11484 : unusable_in_infinite_loop_constraint_p (const svalue *sval)
5008 : {
5009 11095 : if (sval->get_kind () == SK_WIDENING)
5010 0 : return true;
5011 : return false;
5012 : }
5013 :
5014 : /* Attempt to add the constraint "LHS OP RHS" to this region_model.
5015 : If it is consistent with existing constraints, add it, and return true.
5016 : Return false if it contradicts existing constraints.
5017 : Use CTXT for reporting any diagnostics associated with the accesses. */
5018 :
5019 : bool
5020 71474 : region_model::add_constraint (const svalue *lhs,
5021 : enum tree_code op,
5022 : const svalue *rhs,
5023 : region_model_context *ctxt)
5024 : {
5025 71474 : const bool checking_for_infinite_loop
5026 71474 : = ctxt ? ctxt->checking_for_infinite_loop_p () : false;
5027 :
5028 5460 : if (checking_for_infinite_loop)
5029 : {
5030 10687 : if (unusable_in_infinite_loop_constraint_p (lhs)
5031 71474 : || unusable_in_infinite_loop_constraint_p (rhs))
5032 : {
5033 236 : gcc_assert (ctxt);
5034 236 : ctxt->on_unusable_in_infinite_loop ();
5035 236 : return false;
5036 : }
5037 : }
5038 :
5039 71238 : lhs = canonicalize_svalue_for_constraint (lhs);
5040 71238 : rhs = canonicalize_svalue_for_constraint (rhs);
5041 :
5042 71238 : tristate t_cond = eval_condition (lhs, op, rhs);
5043 :
5044 : /* If we already have the condition, do nothing. */
5045 71238 : if (t_cond.is_true ())
5046 : return true;
5047 :
5048 : /* Reject a constraint that would contradict existing knowledge, as
5049 : unsatisfiable. */
5050 59586 : if (t_cond.is_false ())
5051 : return false;
5052 :
5053 51376 : if (checking_for_infinite_loop)
5054 : {
5055 : /* Here, we don't have a definite true/false value, so bail out
5056 : when checking for infinite loops. */
5057 3244 : gcc_assert (ctxt);
5058 3244 : ctxt->on_unusable_in_infinite_loop ();
5059 3244 : return false;
5060 : }
5061 :
5062 48132 : bool out;
5063 48132 : if (add_constraints_from_binop (lhs, op, rhs, &out, ctxt))
5064 2924 : return out;
5065 :
5066 : /* Attempt to store the constraint. */
5067 45208 : if (!m_constraints->add_constraint (lhs, op, rhs))
5068 : return false;
5069 :
5070 : /* Notify the context, if any. This exists so that the state machines
5071 : in a program_state can be notified about the condition, and so can
5072 : set sm-state for e.g. unchecked->checked, both for cfg-edges, and
5073 : when synthesizing constraints as above. */
5074 45120 : if (ctxt)
5075 30661 : ctxt->on_condition (lhs, op, rhs);
5076 :
5077 : /* If we have ®ION == NULL, then drop dynamic extents for REGION (for
5078 : the case where REGION is heap-allocated and thus could be NULL). */
5079 45120 : if (tree rhs_cst = rhs->maybe_get_constant ())
5080 37870 : if (op == EQ_EXPR && zerop (rhs_cst))
5081 11063 : if (auto *sym_ptr = lhs->maybe_get_symbolic_pointer ())
5082 2092 : unset_dynamic_extents (&sym_ptr->get_base_region ());
5083 :
5084 : return true;
5085 : }
5086 :
5087 : /* As above, but when returning false, if OUT is non-NULL, write a
5088 : new rejected_constraint to *OUT. */
5089 :
5090 : bool
5091 62252 : region_model::add_constraint (tree lhs, enum tree_code op, tree rhs,
5092 : region_model_context *ctxt,
5093 : std::unique_ptr<rejected_constraint> *out)
5094 : {
5095 62252 : bool sat = add_constraint (lhs, op, rhs, ctxt);
5096 62252 : if (!sat && out)
5097 : {
5098 1611 : const svalue *lhs_sval = get_rvalue (lhs, nullptr);
5099 1611 : const svalue *rhs_sval = get_rvalue (rhs, nullptr);
5100 3222 : *out = std::make_unique <rejected_op_constraint> (*this,
5101 1611 : lhs_sval, op, rhs_sval);
5102 : }
5103 62252 : return sat;
5104 : }
5105 :
5106 : /* Determine what is known about the condition "LHS OP RHS" within
5107 : this model.
5108 : Use CTXT for reporting any diagnostics associated with the accesses. */
5109 :
5110 : tristate
5111 27730 : region_model::eval_condition (tree lhs,
5112 : enum tree_code op,
5113 : tree rhs,
5114 : region_model_context *ctxt) const
5115 : {
5116 : /* For now, make no attempt to model constraints on floating-point
5117 : values. */
5118 27730 : if (FLOAT_TYPE_P (TREE_TYPE (lhs)) || FLOAT_TYPE_P (TREE_TYPE (rhs)))
5119 16 : return tristate::unknown ();
5120 :
5121 27714 : return eval_condition (get_rvalue (lhs, ctxt), op, get_rvalue (rhs, ctxt));
5122 : }
5123 :
5124 : /* Convert EXPR to ORIG_TYPE.
5125 :
5126 : If EXPR is of RECORD_TYPE, then detect the case where the initial field
5127 : is of ORIG_TYPE (or we have a chain of such initial fields ending in
5128 : ORIG_TYPE), and return a COMPONENT_REF accessing the field.
5129 :
5130 : Otherwise, return a NOP_EXPR for a cast. */
5131 :
5132 : static tree
5133 346 : convert_to_type (tree orig_type, tree expr)
5134 : {
5135 346 : for (tree iter_expr = expr;
5136 368 : TREE_CODE (TREE_TYPE (iter_expr)) == RECORD_TYPE;
5137 : )
5138 : {
5139 84 : tree initial_field = TYPE_FIELDS (TREE_TYPE (iter_expr));
5140 84 : iter_expr = build3 (COMPONENT_REF,
5141 84 : TREE_TYPE (initial_field),
5142 : iter_expr, initial_field, NULL_TREE);
5143 84 : if (types_compatible_p (TREE_TYPE (iter_expr), orig_type))
5144 : return iter_expr;
5145 : }
5146 284 : return build1 (NOP_EXPR, orig_type, expr);
5147 : }
5148 :
5149 : /* Implementation of region_model::get_representative_path_var.
5150 : Attempt to return a path_var that represents SVAL, or return NULL_TREE.
5151 : Use VISITED to prevent infinite mutual recursion with the overload for
5152 : regions. */
5153 :
5154 : path_var
5155 11629 : region_model::get_representative_path_var_1 (const svalue *sval,
5156 : value_set *visited,
5157 : logger *logger) const
5158 : {
5159 11629 : gcc_assert (sval);
5160 :
5161 : /* Prevent infinite recursion. */
5162 11629 : if (visited->contains (sval))
5163 : {
5164 39 : if (sval->get_kind () == SK_CONSTANT)
5165 10 : return path_var (sval->maybe_get_constant (), 0);
5166 : else
5167 29 : return path_var (NULL_TREE, 0);
5168 : }
5169 11590 : visited->add (sval);
5170 :
5171 : /* Gather candidates. */
5172 11590 : auto_vec<path_var> pvs;
5173 :
5174 : /* Consider casts. */
5175 11590 : if (const svalue *cast_sval = sval->maybe_undo_cast ())
5176 : {
5177 368 : path_var result = get_representative_path_var (cast_sval, visited,
5178 : logger);
5179 368 : tree orig_type = sval->get_type ();
5180 : /* If necessary, wrap the result in a cast, or in a field lookup. */
5181 368 : if (result.m_tree && orig_type)
5182 346 : result.m_tree = convert_to_type (orig_type, result.m_tree);
5183 368 : if (result)
5184 346 : pvs.safe_push (result);
5185 : }
5186 :
5187 11590 : m_store.get_representative_path_vars (this, visited, sval, logger, &pvs);
5188 :
5189 11590 : if (tree cst = sval->maybe_get_constant ())
5190 1954 : pvs.safe_push (path_var (cst, 0));
5191 :
5192 : /* Handle string literals and various other pointers. */
5193 11590 : if (auto *sym_ptr = sval->maybe_get_symbolic_pointer ())
5194 4579 : if (sym_ptr->zero_offset_p ())
5195 : {
5196 4569 : auto ® = sym_ptr->get_base_region ();
5197 4569 : if (path_var pv = get_representative_path_var (®, visited, logger))
5198 33 : pvs.safe_push (path_var (build1 (ADDR_EXPR,
5199 : sval->get_type (),
5200 : pv.m_tree),
5201 33 : pv.m_stack_depth));
5202 : }
5203 :
5204 :
5205 : /* Handle binops. */
5206 11590 : if (const binop_svalue *binop_sval = sval->dyn_cast_binop_svalue ())
5207 386 : if (path_var lhs_pv
5208 386 : = get_representative_path_var (binop_sval->get_arg0 (), visited,
5209 386 : logger))
5210 351 : if (path_var rhs_pv
5211 351 : = get_representative_path_var (binop_sval->get_arg1 (), visited,
5212 351 : logger))
5213 350 : pvs.safe_push (path_var (build2 (binop_sval->get_op (),
5214 : sval->get_type (),
5215 : lhs_pv.m_tree, rhs_pv.m_tree),
5216 350 : lhs_pv.m_stack_depth));
5217 :
5218 : /* Handle bit vectors. */
5219 11590 : if (const auto *bv_sval = sval->dyn_cast_svalue_from_bit_vector ())
5220 : {
5221 2018 : const auto &bv = bv_sval->get_bit_vector ();
5222 2018 : if (const auto *sval_bv = bv.dyn_cast_bit_vector_from_svalue ())
5223 : {
5224 0 : path_var result
5225 0 : = get_representative_path_var (&sval_bv->get_svalue (),
5226 : visited,
5227 : logger);
5228 0 : tree orig_type = sval->get_type ();
5229 : /* If necessary, wrap the result in a cast. */
5230 0 : if (result.m_tree && orig_type)
5231 0 : result.m_tree = build1 (NOP_EXPR, orig_type, result.m_tree);
5232 0 : if (result)
5233 0 : pvs.safe_push (result);
5234 : }
5235 2018 : if (const auto *cropped_bv = bv.dyn_cast_cropped_bit_vector ())
5236 : {
5237 48 : auto &uncropped_bv = cropped_bv->get_uncropped_bit_vector ();
5238 48 : if (auto *from_sval = uncropped_bv.dyn_cast_bit_vector_from_svalue ())
5239 48 : if (auto *init_sval = from_sval->get_svalue ().dyn_cast_initial_svalue ())
5240 : {
5241 48 : symbolic_bit_range uncropped_bit_range
5242 48 : = cropped_bv->get_uncropped_bits_to_use ();
5243 48 : if (const region *reg
5244 48 : = maybe_get_subregion_for_symbolic_bit_range (*init_sval->get_region (),
5245 : sval->get_type (),
5246 : uncropped_bit_range))
5247 48 : if (path_var result = get_representative_path_var (reg,
5248 : visited,
5249 48 : logger))
5250 48 : pvs.safe_push (result);
5251 : }
5252 : }
5253 2018 : if (const auto *bv_from_ubc = bv.dyn_cast_bit_vector_from_ubc ())
5254 281 : if (auto *baseline_bc
5255 281 : = bv_from_ubc->get_bit_contents ().dyn_cast_baseline_bit_contents ())
5256 : {
5257 : /* Are the bits implicitly live due to the region
5258 : being untouched? */
5259 165 : const region *base_reg = baseline_bc->get_baseline_key ().m_base_reg;
5260 165 : symbolic::memory_range mem_range (*base_reg,
5261 165 : bv_from_ubc->get_bit_range ());
5262 165 : if (&m_store.get_bits (mem_range, get_baseline_state ())
5263 : == bv_from_ubc)
5264 149 : if (const region *reg
5265 : = maybe_get_subregion_for_symbolic_bit_range
5266 149 : (*base_reg,
5267 : sval->get_type (),
5268 149 : bv_from_ubc->get_bit_range ()))
5269 149 : if (path_var result = get_representative_path_var (reg,
5270 : visited,
5271 149 : logger))
5272 72 : pvs.safe_push (result);
5273 : }
5274 : }
5275 :
5276 11590 : if (pvs.length () < 1)
5277 919 : return path_var (NULL_TREE, 0);
5278 :
5279 10671 : pvs.qsort (readability_comparator);
5280 10671 : return pvs[0];
5281 11590 : }
5282 :
5283 : /* Attempt to return a path_var that represents SVAL, or return NULL_TREE.
5284 : Use VISITED to prevent infinite mutual recursion with the overload for
5285 : regions
5286 :
5287 : This function defers to get_representative_path_var_1 to do the work;
5288 : it adds verification that get_representative_path_var_1 returned a tree
5289 : of the correct type. */
5290 :
5291 : path_var
5292 17551 : region_model::get_representative_path_var (const svalue *sval,
5293 : value_set *visited,
5294 : logger *logger) const
5295 : {
5296 17551 : if (sval == nullptr)
5297 5922 : return path_var (NULL_TREE, 0);
5298 :
5299 11629 : LOG_SCOPE (logger);
5300 11629 : if (logger)
5301 : {
5302 0 : logger->start_log_line ();
5303 0 : logger->log_partial ("sval: ");
5304 0 : sval->dump_to_pp (logger->get_printer (), true);
5305 0 : logger->end_log_line ();
5306 : }
5307 :
5308 11629 : tree orig_type = sval->get_type ();
5309 :
5310 11629 : path_var result = get_representative_path_var_1 (sval, visited, logger);
5311 :
5312 : /* Verify that the result has compatible type with SVAL, if any. */
5313 11629 : if (result.m_tree && orig_type)
5314 9224 : gcc_assert (types_compatible_p (TREE_TYPE (result.m_tree), orig_type));
5315 :
5316 11629 : if (logger)
5317 : {
5318 0 : logger->start_log_line ();
5319 0 : logger->log_partial ("sval: ");
5320 0 : sval->dump_to_pp (logger->get_printer (), true);
5321 0 : logger->end_log_line ();
5322 :
5323 0 : if (result.m_tree)
5324 0 : logger->log ("tree: %qE", result.m_tree);
5325 : else
5326 0 : logger->log ("tree: NULL");
5327 : }
5328 :
5329 11629 : return result;
5330 11629 : }
5331 :
5332 : /* Attempt to return a tree that represents SVAL, or return NULL_TREE.
5333 :
5334 : Strip off any top-level cast, to avoid messages like
5335 : double-free of '(void *)ptr'
5336 : from analyzer diagnostics. */
5337 :
5338 : tree
5339 14652 : region_model::get_representative_tree (const svalue *sval, logger *logger) const
5340 : {
5341 14652 : value_set visited;
5342 14652 : tree expr = get_representative_path_var (sval, &visited, logger).m_tree;
5343 :
5344 : /* Strip off any top-level casts. */
5345 16892 : while (expr && TREE_CODE (expr) == NOP_EXPR)
5346 2240 : expr = TREE_OPERAND (expr, 0);
5347 :
5348 14652 : return fixup_tree_for_diagnostic (expr);
5349 14652 : }
5350 :
5351 : tree
5352 909 : region_model::get_representative_tree (const region *reg, logger *logger) const
5353 : {
5354 909 : value_set visited;
5355 909 : tree expr = get_representative_path_var (reg, &visited, logger).m_tree;
5356 :
5357 : /* Strip off any top-level cast. */
5358 909 : if (expr && TREE_CODE (expr) == NOP_EXPR)
5359 5 : expr = TREE_OPERAND (expr, 0);
5360 :
5361 909 : return fixup_tree_for_diagnostic (expr);
5362 909 : }
5363 :
5364 : const region *
5365 661547 : region_model::
5366 : maybe_get_region_for_mem_range (const symbolic::memory_range &mem_range,
5367 : tree desired_type,
5368 : logger *) const
5369 : {
5370 661547 : return maybe_get_subregion_for_symbolic_bit_range
5371 661547 : (mem_range.get_base_region (),
5372 : desired_type,
5373 661547 : mem_range.get_bit_range ());
5374 : }
5375 :
5376 : const region *
5377 667305 : region_model::
5378 : maybe_get_subregion_for_symbolic_bit_range (const region ®,
5379 : tree desired_type,
5380 : symbolic_bit_range bit_range) const
5381 : {
5382 667305 : concrete_bit_range conc_bit_range;
5383 667305 : if (concrete_from_symbolic (bit_range, &conc_bit_range))
5384 1306536 : return maybe_get_subregion_for_concrete_bit_range (reg,
5385 : desired_type,
5386 : conc_bit_range);
5387 :
5388 : /* Symbolic case. */
5389 14037 : if (reg.get_type ())
5390 12268 : switch (TREE_CODE (reg.get_type ()))
5391 : {
5392 : default:
5393 : break;
5394 :
5395 4143 : case ARRAY_TYPE:
5396 8286 : if (auto *result
5397 4143 : = maybe_get_subregion_for_symbolic_bit_range_in_array (reg,
5398 : desired_type,
5399 : bit_range))
5400 : return result;
5401 : break;
5402 :
5403 1567 : case RECORD_TYPE:
5404 3134 : if (auto *result
5405 1567 : = maybe_get_subregion_for_symbolic_bit_range_in_record (reg,
5406 : desired_type,
5407 : bit_range))
5408 : return result;
5409 : break;
5410 : }
5411 :
5412 : /* Fallback: see if we can express this using offset_region and
5413 : sized_region. */
5414 10487 : if (auto *byte_size = maybe_bytes_from_bits (bit_range.get_size ()))
5415 9794 : if (auto *byte_offset
5416 9794 : = maybe_bytes_from_bits (bit_range.get_start_offset ()))
5417 : {
5418 6022 : auto *byte_offset_sval
5419 6022 : = m_mgr->get_svalue_from_scalar<concrete_byte_offset>
5420 6022 : (ptrdiff_type_node, *byte_offset);
5421 6022 : auto *offset_reg = m_mgr->get_offset_region (®,
5422 : NULL_TREE,
5423 : byte_offset_sval);
5424 6022 : auto *byte_size_sval
5425 6022 : = m_mgr->get_svalue_from_scalar<concrete_byte_size> (size_type_node,
5426 : *byte_size);
5427 6022 : return m_mgr->get_sized_region (offset_reg, desired_type,
5428 6022 : byte_size_sval);
5429 : }
5430 :
5431 : return nullptr;
5432 667305 : }
5433 :
5434 : /* Subroutine of maybe_get_subregion_for_symbolic_bit_range for the
5435 : purely concrete case; we shouldn't need this region_model. */
5436 :
5437 : const region *
5438 653268 : region_model::
5439 : maybe_get_subregion_for_concrete_bit_range (const region ®,
5440 : tree desired_type,
5441 : concrete_bit_range conc_bit_range) const
5442 : {
5443 653268 : auto_vec<const region *> regions;
5444 653268 : reg.get_subregions_for_bit_range (m_mgr, conc_bit_range,
5445 : desired_type,
5446 : ®ions);
5447 653268 : if (regions.length () < 1)
5448 : {
5449 : /* Fallback: see if we can express this using offset_region and
5450 : sized_region. */
5451 15553 : concrete_byte_size conc_byte_size;
5452 15553 : if (maybe_bytes_from_bits (conc_bit_range.get_size (),
5453 : &conc_byte_size))
5454 : {
5455 15435 : concrete_byte_offset conc_byte_offset;
5456 15435 : if (maybe_bytes_from_bits (conc_bit_range.get_start_offset (),
5457 : &conc_byte_offset))
5458 : {
5459 15435 : auto &byte_mgr
5460 15435 : = m_mgr->get_node_manager ().get_scalars ().get_bytes ();
5461 15435 : auto *byte_offset_sval
5462 : = m_mgr->get_svalue_from_scalar<concrete_byte_offset>
5463 15435 : (ptrdiff_type_node,
5464 15435 : byte_mgr.get_concrete (conc_byte_offset));
5465 15435 : auto *offset_reg
5466 15435 : = m_mgr->get_offset_region (®,
5467 : NULL_TREE,
5468 : byte_offset_sval);
5469 15435 : auto *byte_size_sval
5470 15435 : = m_mgr->get_svalue_from_scalar<concrete_byte_size>
5471 15435 : (size_type_node,
5472 15435 : byte_mgr.get_concrete (conc_byte_size));
5473 15435 : return m_mgr->get_sized_region (offset_reg, desired_type,
5474 : byte_size_sval);
5475 : }
5476 15435 : }
5477 : return nullptr;
5478 15553 : }
5479 637715 : return regions[0]; // TODO: sort by readability?
5480 653268 : }
5481 :
5482 : /* Subroutine for ARRAY_TYPE case of
5483 : region_model::maybe_get_subregion_for_symbolic_bit_range
5484 : for getting a type for the index of an element_region. */
5485 :
5486 : template <typename ConcreteValueType>
5487 : static tree
5488 4142 : get_underlying_index_type (const symbolic::scalar<ConcreteValueType> &sym_offset)
5489 : {
5490 : /* Try to preserve the type of an underlying integral svalue. */
5491 4142 : if (auto *from_sval
5492 4142 : = sym_offset.dyn_cast_scalar_from_svalue ())
5493 : {
5494 1729 : auto &sval = from_sval->get_svalue ();
5495 1729 : if (sval.get_type ()
5496 1729 : && TREE_CODE (sval.get_type ()) == INTEGER_TYPE)
5497 : return sval.get_type ();
5498 : }
5499 :
5500 2415 : return integer_type_node;
5501 : }
5502 :
5503 : namespace {
5504 :
5505 : /* Support code for maybe_get_subregion_for_symbolic_bit_range_in_array
5506 : for reconstructing array indices from bit/byte offsets. */
5507 :
5508 : /* Result of splitting an expression into (quotient * divisor) + residual. */
5509 :
5510 : template <typename ConcreteValueType>
5511 : struct quotient_and_residual
5512 : {
5513 7303 : quotient_and_residual (const symbolic::scalar<integer> *quotient,
5514 : const symbolic::scalar<ConcreteValueType> *residual)
5515 7303 : : m_quotient (quotient),
5516 7303 : m_residual (residual)
5517 : {
5518 7303 : gcc_assert (quotient);
5519 7303 : gcc_assert (residual);
5520 7303 : }
5521 :
5522 : quotient_and_residual &
5523 850 : operator+= (const quotient_and_residual &other)
5524 : {
5525 850 : m_quotient = &(*m_quotient + *other.m_quotient);
5526 850 : m_residual = &(*m_residual + *other.m_residual);
5527 850 : return *this;
5528 : }
5529 :
5530 : DEBUG_FUNCTION void
5531 0 : dump () const
5532 : {
5533 0 : symbolic::dump_node_tree_to_stderr<quotient_and_residual> (*this);
5534 0 : }
5535 :
5536 : std::unique_ptr<text_art::tree_widget>
5537 0 : make_dump_widget (symbolic::node_dump_state &nds) const
5538 : {
5539 : using text_art::tree_widget;
5540 0 : std::unique_ptr<tree_widget> w
5541 : (tree_widget::from_fmt (nds, nullptr, "quotient_and_residual"));
5542 0 : w->add_child (m_quotient->make_dump_widget (nds));
5543 0 : w->add_child (m_residual->make_dump_widget (nds));
5544 0 : return w;
5545 : }
5546 :
5547 : const symbolic::scalar<integer> *m_quotient;
5548 : const symbolic::scalar<ConcreteValueType> *m_residual;
5549 : };
5550 :
5551 : template <typename ConcreteValueType>
5552 : quotient_and_residual<ConcreteValueType>
5553 : handle_bits_from_bytes (const symbolic::scalar<ConcreteValueType> &scalar,
5554 : ConcreteValueType divisor);
5555 :
5556 : /* Try to split SCALAR into the form
5557 : (quotient * DIVISOR) + residual
5558 : This is always possible with quotient == 0 and residual == SCALAR,
5559 : but we want it in a form that will help when trying to reconstruct
5560 : an array index from a bit offset. */
5561 :
5562 : template <typename ConcreteValueType>
5563 : quotient_and_residual<ConcreteValueType>
5564 7303 : try_split_exact_multiple (const symbolic::scalar<ConcreteValueType> &scalar,
5565 : ConcreteValueType divisor)
5566 : {
5567 7303 : auto &unit_mgr = scalar.get_mgr ();
5568 7303 : auto &unitless_mgr = unit_mgr.get_unitless_manager ();
5569 :
5570 7303 : auto &zero_quotient = unitless_mgr.get_concrete (0);
5571 7303 : auto &zero_units = unit_mgr.get_concrete (ConcreteValueType (0));
5572 :
5573 7303 : switch (scalar.get_kind ())
5574 : {
5575 0 : default:
5576 0 : gcc_unreachable ();
5577 :
5578 493 : case symbolic::scalar<ConcreteValueType>::kind::concrete:
5579 : {
5580 493 : auto &concrete
5581 : = static_cast<const symbolic::concrete_scalar<ConcreteValueType> &> (scalar);
5582 493 : auto &conc_val = concrete.get_concrete ();
5583 : return quotient_and_residual<ConcreteValueType>
5584 493 : {&unitless_mgr.get_concrete (conc_val.floor_div (divisor)),
5585 493 : &unit_mgr.get_concrete (conc_val.floor_mod (divisor))};
5586 : }
5587 : break;
5588 :
5589 414 : case symbolic::scalar<ConcreteValueType>::kind::sum:
5590 : {
5591 414 : auto &sum
5592 : = static_cast<const symbolic::sum<ConcreteValueType> &> (scalar);
5593 414 : quotient_and_residual<ConcreteValueType> result {&zero_quotient, &zero_units};
5594 877 : for (size_t i = 0; i < sum.get_num_symbolic_addends (); ++i)
5595 : {
5596 463 : auto result_for_term
5597 463 : = try_split_exact_multiple (sum.get_symbolic_addend (i),
5598 : divisor);
5599 463 : result += result_for_term;
5600 : }
5601 414 : if (auto *conc = sum.get_any_concrete_addend ())
5602 387 : result += try_split_exact_multiple (*conc, divisor);
5603 414 : return result;
5604 : }
5605 : break;
5606 :
5607 1478 : case symbolic::scalar<ConcreteValueType>::kind::product:
5608 : {
5609 1478 : auto &product
5610 : = static_cast<const symbolic::product<ConcreteValueType> &> (scalar);
5611 : // Does factor == divisor?
5612 1478 : ConcreteValueType conc_lhs;
5613 1478 : if (concrete_from_symbolic (product.get_lhs (), &conc_lhs)
5614 1478 : && conc_lhs == divisor)
5615 1322 : return quotient_and_residual<ConcreteValueType> {&product.get_rhs (),
5616 1322 : &zero_units};
5617 1322 : }
5618 156 : break;
5619 :
5620 2602 : case symbolic::scalar<ConcreteValueType>::kind::from_svalue:
5621 2602 : if (divisor.is_one_p ())
5622 : {
5623 407 : auto &from_sval
5624 : = static_cast<const symbolic::scalar_from_svalue<ConcreteValueType> &> (scalar);
5625 : return quotient_and_residual<ConcreteValueType>
5626 407 : {&unitless_mgr.get_scalar_from_svalue (from_sval.get_svalue ()),
5627 407 : &zero_units};
5628 : }
5629 : break;
5630 :
5631 : case symbolic::scalar<ConcreteValueType>::kind::named_test:
5632 : break;
5633 :
5634 2316 : case symbolic::scalar<ConcreteValueType>::kind::bits_from_bytes:
5635 2316 : return handle_bits_from_bytes (scalar, divisor);
5636 : }
5637 :
5638 : // Can't split:
5639 2351 : return quotient_and_residual<ConcreteValueType> {&zero_quotient, &scalar};
5640 : }
5641 :
5642 : template <>
5643 : quotient_and_residual<concrete_bit_offset>
5644 2316 : handle_bits_from_bytes (const symbolic::scalar<concrete_bit_offset> &scalar,
5645 : concrete_bit_offset divisor)
5646 : {
5647 2316 : auto &unit_mgr = scalar.get_mgr ();
5648 2316 : auto &unitless_mgr = unit_mgr.get_unitless_manager ();
5649 :
5650 2316 : auto &zero_quotient = unitless_mgr.get_concrete (0);
5651 :
5652 2316 : auto *bits_from_bytes
5653 2316 : = scalar.dyn_cast_bits_from_bytes_scalar ();
5654 2316 : gcc_assert (bits_from_bytes);
5655 :
5656 4632 : if (divisor.get_integer ().floor_mod (BITS_PER_UNIT) == 0)
5657 : {
5658 2311 : concrete_byte_offset divisor_as_bytes
5659 2311 : (divisor.get_integer ().floor_div (BITS_PER_UNIT));
5660 2311 : auto &bytes = bits_from_bytes->get_bytes ();
5661 2311 : auto bytes_result
5662 2311 : = try_split_exact_multiple<concrete_byte_offset> (bytes, divisor_as_bytes);
5663 4622 : return quotient_and_residual<concrete_bit_offset>
5664 : {bytes_result.m_quotient,
5665 2311 : &unit_mgr.get_bits_from_bytes (*bytes_result.m_residual)};
5666 2311 : }
5667 :
5668 : // Can't split:
5669 5 : return quotient_and_residual<concrete_bit_offset> {&zero_quotient, &scalar};
5670 : }
5671 :
5672 : template <>
5673 : quotient_and_residual<concrete_byte_offset>
5674 0 : handle_bits_from_bytes (const symbolic::scalar<concrete_byte_offset> &,
5675 : concrete_byte_offset)
5676 : {
5677 0 : gcc_unreachable ();
5678 : }
5679 :
5680 : } // anonymous namespace
5681 :
5682 : /* Subroutine of maybe_get_subregion_for_symbolic_bit_range for the
5683 : case where ARRAY_REG is of ARRAY_TYPE. */
5684 :
5685 : const region *
5686 4143 : region_model::
5687 : maybe_get_subregion_for_symbolic_bit_range_in_array (const region &array_reg,
5688 : tree desired_type,
5689 : symbolic_bit_range bit_range) const
5690 : {
5691 4143 : gcc_assert (TREE_CODE (array_reg.get_type ()) == ARRAY_TYPE);
5692 :
5693 4143 : tree element_type = TREE_TYPE (array_reg.get_type ());
5694 4143 : concrete_bit_size element_size;
5695 4143 : if (!get_type_size (element_type, &element_size))
5696 : return nullptr;
5697 :
5698 4142 : auto split = try_split_exact_multiple<concrete_bit_offset>
5699 4142 : (bit_range.get_start_offset (),
5700 : element_size);
5701 :
5702 4142 : tree index_type = get_underlying_index_type (*split.m_quotient);
5703 4142 : auto *index_sval = m_mgr->get_svalue_from_scalar<integer>
5704 4142 : (index_type, *split.m_quotient);
5705 :
5706 4142 : auto *element_reg = m_mgr->get_element_region (&array_reg,
5707 : element_type,
5708 : index_sval);
5709 4142 : symbolic_bit_range relative_bit_range (*split.m_residual,
5710 4142 : bit_range.get_size ());
5711 4142 : return maybe_get_subregion_for_symbolic_bit_range
5712 4142 : (*element_reg, desired_type, relative_bit_range);
5713 4143 : }
5714 :
5715 : const region *
5716 1567 : region_model::
5717 : maybe_get_subregion_for_symbolic_bit_range_in_record (const region &record_reg,
5718 : tree desired_type,
5719 : symbolic_bit_range bit_range) const
5720 : {
5721 1567 : auto &start_offset = bit_range.get_start_offset ();
5722 :
5723 : /* Determine if we have sum(X, concrete), possibly of bytes. */
5724 1567 : concrete_bit_offset conc_bit_offset;
5725 1567 : if (auto *bits_from_bytes_scalar = start_offset.dyn_cast_bits_from_bytes_scalar ())
5726 : {
5727 1179 : if (auto *byte_sum = bits_from_bytes_scalar->get_bytes ().dyn_cast_sum ())
5728 561 : if (auto *conc_byte_addend = byte_sum->get_any_concrete_addend_value ())
5729 558 : conc_bit_offset = bits_from_bytes (*conc_byte_addend);
5730 : }
5731 388 : else if (auto *bit_sum = start_offset.dyn_cast_sum ())
5732 0 : if (auto *conc_bit_addend = bit_sum->get_any_concrete_addend_value ())
5733 0 : conc_bit_offset = *conc_bit_addend;
5734 :
5735 : /* If we have sum(X, concrete), then offset into the struct
5736 : and do something with that... */
5737 1567 : {
5738 : /* Determine where the concrete addend is within the record. */
5739 : // TODO: amortize this?
5740 1567 : record_layout layout (record_reg.get_type ());
5741 1567 : if (auto *item = layout.get_item_at (conc_bit_offset))
5742 : {
5743 1419 : auto *field_reg
5744 2838 : = m_mgr->get_field_region (&record_reg,
5745 1419 : const_cast<tree> (item->m_field));
5746 1419 : symbolic_bit_range relative_bit_range
5747 2838 : (bit_range.get_start_offset () - item->get_start_offset (),
5748 1419 : bit_range.get_size ());
5749 1419 : return maybe_get_subregion_for_symbolic_bit_range
5750 1419 : (*field_reg, desired_type, relative_bit_range);
5751 : }
5752 1419 : }
5753 :
5754 148 : return nullptr;
5755 1567 : }
5756 :
5757 : /* Implementation of region_model::get_representative_path_var.
5758 :
5759 : Attempt to return a path_var that represents REG, or return
5760 : the NULL path_var.
5761 : For example, a region for a field of a local would be a path_var
5762 : wrapping a COMPONENT_REF.
5763 : Use VISITED to prevent infinite mutual recursion with the overload for
5764 : svalues. */
5765 :
5766 : path_var
5767 17906 : region_model::get_representative_path_var_1 (const region *reg,
5768 : value_set *visited,
5769 : logger *logger) const
5770 : {
5771 17906 : switch (reg->get_kind ())
5772 : {
5773 0 : default:
5774 0 : gcc_unreachable ();
5775 :
5776 0 : case RK_FRAME:
5777 0 : case RK_GLOBALS:
5778 0 : case RK_CODE:
5779 0 : case RK_HEAP:
5780 0 : case RK_STACK:
5781 0 : case RK_THREAD_LOCAL:
5782 0 : case RK_ROOT:
5783 : /* Regions that represent memory spaces are not expressible as trees. */
5784 0 : return path_var (NULL_TREE, 0);
5785 :
5786 1 : case RK_FUNCTION:
5787 1 : {
5788 1 : const function_region *function_reg
5789 1 : = as_a <const function_region *> (reg);
5790 1 : return path_var (function_reg->get_fndecl (), 0);
5791 : }
5792 1 : case RK_LABEL:
5793 1 : {
5794 1 : const label_region *label_reg = as_a <const label_region *> (reg);
5795 1 : return path_var (label_reg->get_label (), 0);
5796 : }
5797 :
5798 298 : case RK_SYMBOLIC:
5799 298 : {
5800 298 : const symbolic_region *symbolic_reg
5801 298 : = as_a <const symbolic_region *> (reg);
5802 298 : const svalue *pointer = symbolic_reg->get_pointer ();
5803 298 : path_var pointer_pv = get_representative_path_var (pointer, visited,
5804 : logger);
5805 298 : if (!pointer_pv)
5806 45 : return path_var (NULL_TREE, 0);
5807 253 : tree offset = build_int_cst (pointer->get_type (), 0);
5808 253 : return path_var (build2 (MEM_REF,
5809 : reg->get_type (),
5810 : pointer_pv.m_tree,
5811 : offset),
5812 253 : pointer_pv.m_stack_depth);
5813 : }
5814 10399 : case RK_DECL:
5815 10399 : {
5816 10399 : const decl_region *decl_reg = as_a <const decl_region *> (reg);
5817 10399 : return path_var (decl_reg->get_decl (), decl_reg->get_stack_depth ());
5818 : }
5819 2004 : case RK_FIELD:
5820 2004 : {
5821 2004 : const field_region *field_reg = as_a <const field_region *> (reg);
5822 2004 : path_var parent_pv
5823 2004 : = get_representative_path_var (reg->get_parent_region (), visited,
5824 : logger);
5825 2004 : if (!parent_pv)
5826 13 : return path_var (NULL_TREE, 0);
5827 1991 : return path_var (build3 (COMPONENT_REF,
5828 : reg->get_type (),
5829 : parent_pv.m_tree,
5830 : field_reg->get_field (),
5831 : NULL_TREE),
5832 1991 : parent_pv.m_stack_depth);
5833 : }
5834 :
5835 225 : case RK_ELEMENT:
5836 225 : {
5837 225 : const element_region *element_reg
5838 225 : = as_a <const element_region *> (reg);
5839 225 : path_var parent_pv
5840 225 : = get_representative_path_var (reg->get_parent_region (), visited,
5841 : logger);
5842 225 : if (!parent_pv)
5843 0 : return path_var (NULL_TREE, 0);
5844 225 : path_var index_pv
5845 225 : = get_representative_path_var (element_reg->get_index (), visited,
5846 : logger);
5847 225 : if (!index_pv)
5848 0 : return path_var (NULL_TREE, 0);
5849 225 : return path_var (build4 (ARRAY_REF,
5850 : reg->get_type (),
5851 : parent_pv.m_tree, index_pv.m_tree,
5852 : NULL_TREE, NULL_TREE),
5853 225 : parent_pv.m_stack_depth);
5854 : }
5855 :
5856 0 : case RK_OFFSET:
5857 0 : {
5858 0 : const offset_region *offset_reg
5859 0 : = as_a <const offset_region *> (reg);
5860 0 : path_var parent_pv
5861 0 : = get_representative_path_var (reg->get_parent_region (), visited,
5862 : logger);
5863 0 : if (!parent_pv)
5864 0 : return path_var (NULL_TREE, 0);
5865 0 : path_var offset_pv
5866 0 : = get_representative_path_var (offset_reg->get_byte_offset (),
5867 : visited, logger);
5868 0 : if (!offset_pv || TREE_CODE (offset_pv.m_tree) != INTEGER_CST)
5869 0 : return path_var (NULL_TREE, 0);
5870 0 : tree addr_parent = build1 (ADDR_EXPR,
5871 : build_pointer_type (reg->get_type ()),
5872 : parent_pv.m_tree);
5873 0 : tree ptype = build_pointer_type_for_mode (char_type_node, ptr_mode,
5874 : true);
5875 0 : return path_var (build2 (MEM_REF, reg->get_type (), addr_parent,
5876 : fold_convert (ptype, offset_pv.m_tree)),
5877 0 : parent_pv.m_stack_depth);
5878 : }
5879 :
5880 108 : case RK_SIZED:
5881 108 : return path_var (NULL_TREE, 0);
5882 :
5883 123 : case RK_CAST:
5884 123 : {
5885 123 : path_var parent_pv
5886 123 : = get_representative_path_var (reg->get_parent_region (), visited,
5887 : logger);
5888 123 : if (!parent_pv)
5889 1 : return path_var (NULL_TREE, 0);
5890 122 : return path_var (build1 (NOP_EXPR,
5891 : reg->get_type (),
5892 : parent_pv.m_tree),
5893 122 : parent_pv.m_stack_depth);
5894 : }
5895 :
5896 4737 : case RK_HEAP_ALLOCATED:
5897 4737 : case RK_ALLOCA:
5898 : /* No good way to express heap-allocated/alloca regions as trees. */
5899 4737 : return path_var (NULL_TREE, 0);
5900 :
5901 10 : case RK_STRING:
5902 10 : {
5903 10 : const string_region *string_reg = as_a <const string_region *> (reg);
5904 10 : return path_var (string_reg->get_string_cst (), 0);
5905 : }
5906 :
5907 0 : case RK_VAR_ARG:
5908 0 : case RK_ERRNO:
5909 0 : case RK_UNKNOWN:
5910 0 : case RK_PRIVATE:
5911 0 : return path_var (NULL_TREE, 0);
5912 : }
5913 : }
5914 :
5915 : /* Attempt to return a path_var that represents REG, or return
5916 : the NULL path_var.
5917 : For example, a region for a field of a local would be a path_var
5918 : wrapping a COMPONENT_REF.
5919 : Use VISITED to prevent infinite mutual recursion with the overload for
5920 : svalues.
5921 :
5922 : This function defers to get_representative_path_var_1 to do the work;
5923 : it adds verification that get_representative_path_var_1 returned a tree
5924 : of the correct type. */
5925 :
5926 : path_var
5927 17906 : region_model::get_representative_path_var (const region *reg,
5928 : value_set *visited,
5929 : logger *logger) const
5930 : {
5931 17906 : LOG_SCOPE (logger);
5932 17906 : if (logger)
5933 : {
5934 0 : logger->start_log_line ();
5935 0 : logger->log_partial ("reg: ");
5936 0 : reg->dump_to_pp (logger->get_printer (), true);
5937 0 : logger->end_log_line ();
5938 : }
5939 :
5940 17906 : path_var result = get_representative_path_var_1 (reg, visited, logger);
5941 :
5942 : /* Verify that the result has the same type as REG, if any. */
5943 17906 : if (result.m_tree && reg->get_type ())
5944 12926 : gcc_assert (TREE_TYPE (result.m_tree) == reg->get_type ());
5945 :
5946 17906 : if (logger)
5947 : {
5948 0 : logger->start_log_line ();
5949 0 : logger->log_partial ("reg: ");
5950 0 : reg->dump_to_pp (logger->get_printer (), true);
5951 0 : logger->end_log_line ();
5952 :
5953 0 : if (result.m_tree)
5954 0 : logger->log ("tree: %qE", result.m_tree);
5955 : else
5956 0 : logger->log ("tree: NULL");
5957 : }
5958 :
5959 35812 : return result;
5960 17906 : }
5961 :
5962 : /* Push a new frame_region on to the stack region.
5963 : Populate the frame_region with child regions for the function call's
5964 : parameters, using values from the arguments at the callsite in the
5965 : caller's frame. */
5966 :
5967 : void
5968 14799 : region_model::update_for_gcall (const gcall &call_stmt,
5969 : region_model_context *ctxt,
5970 : function *callee)
5971 : {
5972 : /* Build a vec of argument svalues, using the current top
5973 : frame for resolving tree expressions. */
5974 14799 : auto_vec<const svalue *> arg_svals (gimple_call_num_args (&call_stmt));
5975 :
5976 46953 : for (unsigned i = 0; i < gimple_call_num_args (&call_stmt); i++)
5977 : {
5978 17355 : tree arg = gimple_call_arg (&call_stmt, i);
5979 17355 : arg_svals.quick_push (get_rvalue (arg, ctxt));
5980 : }
5981 :
5982 14799 : if(!callee)
5983 : {
5984 : /* Get the function * from the gcall. */
5985 0 : tree fn_decl = get_fndecl_for_call (call_stmt, ctxt);
5986 0 : callee = DECL_STRUCT_FUNCTION (fn_decl);
5987 : }
5988 :
5989 0 : gcc_assert (callee);
5990 14799 : push_frame (*callee, &call_stmt, &arg_svals, ctxt);
5991 14799 : }
5992 :
5993 : /* Pop the top-most frame_region from the stack, and copy the return
5994 : region's values (if any) into the region for the lvalue of the LHS of
5995 : the call (if any). */
5996 :
5997 : void
5998 11050 : region_model::update_for_return_gcall (const gcall &call_stmt,
5999 : region_model_context *ctxt)
6000 : {
6001 : /* Get the lvalue for the result of the call, passing it to pop_frame,
6002 : so that pop_frame can determine the region with respect to the
6003 : *caller* frame. */
6004 11050 : tree lhs = gimple_call_lhs (&call_stmt);
6005 11050 : pop_frame (lhs, nullptr, ctxt, &call_stmt);
6006 11050 : }
6007 :
6008 : /* Attempt to use R to replay SUMMARY into this object.
6009 : Return true if it is possible. */
6010 :
6011 : bool
6012 677 : region_model::replay_call_summary (call_summary_replay &r,
6013 : const region_model &summary)
6014 : {
6015 677 : gcc_assert (summary.get_stack_depth () == 1);
6016 :
6017 677 : if (!m_store.replay_call_summary (r, summary.m_store))
6018 : return false;
6019 :
6020 507 : if (r.get_ctxt ())
6021 465 : r.get_ctxt ()->maybe_did_work ();
6022 :
6023 507 : if (!m_constraints->replay_call_summary (r, *summary.m_constraints))
6024 : return false;
6025 :
6026 528 : for (auto kv : summary.m_dynamic_extents)
6027 : {
6028 72 : const region *summary_reg = kv.first;
6029 72 : const region *caller_reg = r.convert_region_from_summary (summary_reg);
6030 72 : if (!caller_reg)
6031 2 : continue;
6032 70 : const svalue *summary_sval = kv.second;
6033 70 : const svalue *caller_sval = r.convert_svalue_from_summary (summary_sval);
6034 70 : if (!caller_sval)
6035 0 : continue;
6036 70 : m_dynamic_extents.put (caller_reg, caller_sval);
6037 : }
6038 :
6039 456 : return true;
6040 : }
6041 :
6042 : /* For use with push_frame when handling a top-level call within the analysis.
6043 : PARAM has a defined but unknown initial value.
6044 : Anything it points to has escaped, since the calling context "knows"
6045 : the pointer, and thus calls to unknown functions could read/write into
6046 : the region.
6047 : If NONNULL is true, then assume that PARAM must be non-NULL. */
6048 :
6049 : void
6050 23746 : region_model::on_top_level_param (tree param,
6051 : bool nonnull,
6052 : region_model_context *ctxt)
6053 : {
6054 23746 : if (POINTER_TYPE_P (TREE_TYPE (param)))
6055 : {
6056 11451 : const region *param_reg = get_lvalue (param, ctxt);
6057 11451 : const svalue *init_ptr_sval
6058 11451 : = m_mgr->get_or_create_initial_value (param_reg);
6059 11451 : const region *pointee_reg = m_mgr->get_symbolic_region (init_ptr_sval);
6060 11451 : m_store.mark_as_escaped (pointee_reg, get_baseline_state ());
6061 11451 : if (nonnull)
6062 : {
6063 1125 : const svalue *null_ptr_sval
6064 1125 : = m_mgr->get_or_create_null_ptr (TREE_TYPE (param));
6065 1125 : add_constraint (init_ptr_sval, NE_EXPR, null_ptr_sval, ctxt);
6066 : }
6067 : }
6068 23746 : }
6069 :
6070 : /* Update this region_model to reflect pushing a frame onto the stack
6071 : for a call to FUN.
6072 :
6073 : If CALL_STMT is non-NULL, this is for the interprocedural case where
6074 : we already have an execution path into the caller. It can be NULL for
6075 : top-level entrypoints into the analysis, or in selftests.
6076 :
6077 : If ARG_SVALS is non-NULL, use it to populate the parameters
6078 : in the new frame.
6079 : Otherwise, the params have their initial_svalues.
6080 :
6081 : Return the frame_region for the new frame. */
6082 :
6083 : const region *
6084 41050 : region_model::push_frame (const function &fun,
6085 : const gcall *call_stmt,
6086 : const vec<const svalue *> *arg_svals,
6087 : region_model_context *ctxt)
6088 : {
6089 41050 : tree fndecl = fun.decl;
6090 41050 : if (arg_svals)
6091 : {
6092 : /* If the result of the callee is DECL_BY_REFERENCE, then
6093 : we'll need to store a reference to the caller's lhs of
6094 : CALL_STMT within callee's result.
6095 : If so, determine the region of CALL_STMT's lhs within
6096 : the caller's frame before updating m_current_frame. */
6097 14799 : const region *caller_return_by_reference_reg = nullptr;
6098 14799 : if (tree result = DECL_RESULT (fndecl))
6099 14799 : if (DECL_BY_REFERENCE (result))
6100 : {
6101 55 : gcc_assert (call_stmt);
6102 55 : tree lhs = gimple_call_lhs (call_stmt);
6103 55 : gcc_assert (lhs);
6104 55 : caller_return_by_reference_reg = get_lvalue (lhs, ctxt);
6105 : }
6106 :
6107 : /* Update m_current_frame. */
6108 14799 : m_current_frame = m_mgr->get_frame_region (m_current_frame, fun);
6109 :
6110 : /* Arguments supplied from a caller frame. */
6111 14799 : unsigned idx = 0;
6112 31678 : for (tree iter_parm = DECL_ARGUMENTS (fndecl); iter_parm;
6113 16879 : iter_parm = DECL_CHAIN (iter_parm), ++idx)
6114 : {
6115 : /* If there's a mismatching declaration, the call stmt might
6116 : not have enough args. Handle this case by leaving the
6117 : rest of the params as uninitialized. */
6118 16883 : if (idx >= arg_svals->length ())
6119 : break;
6120 16879 : tree parm_lval = iter_parm;
6121 16879 : if (tree parm_default_ssa = get_ssa_default_def (fun, iter_parm))
6122 15441 : parm_lval = parm_default_ssa;
6123 16879 : const region *parm_reg = get_lvalue (parm_lval, ctxt);
6124 16879 : const svalue *arg_sval = (*arg_svals)[idx];
6125 16879 : set_value (parm_reg, arg_sval, ctxt);
6126 : }
6127 :
6128 : /* Handle any variadic args. */
6129 15275 : unsigned va_arg_idx = 0;
6130 15275 : for (; idx < arg_svals->length (); idx++, va_arg_idx++)
6131 : {
6132 476 : const svalue *arg_sval = (*arg_svals)[idx];
6133 : /* Try to preserve the type of arg_sval in the store,
6134 : by wrapping it in an "unmergeable" decorator. */
6135 476 : if (arg_sval->get_kind () == SK_CONSTANT)
6136 278 : arg_sval = m_mgr->get_or_create_unmergeable (arg_sval);
6137 476 : const region *var_arg_reg
6138 476 : = m_mgr->get_var_arg_region (m_current_frame,
6139 : va_arg_idx);
6140 476 : set_value (var_arg_reg, arg_sval, ctxt);
6141 : }
6142 :
6143 : /* If the result of the callee is DECL_BY_REFERENCE, then above
6144 : we should have determined the region within the
6145 : caller's frame that the callee will be writing back to.
6146 : Use this now to initialize the reference in callee's frame. */
6147 14799 : if (tree result = DECL_RESULT (fndecl))
6148 14799 : if (DECL_BY_REFERENCE (result))
6149 : {
6150 : /* Get reference to the caller lhs. */
6151 55 : gcc_assert (caller_return_by_reference_reg);
6152 55 : const svalue *ref_sval
6153 55 : = m_mgr->get_ptr_svalue (TREE_TYPE (result),
6154 : caller_return_by_reference_reg);
6155 :
6156 : /* Get region for default val of DECL_RESULT within the
6157 : callee. */
6158 55 : if (tree result_default_ssa = get_ssa_default_def (fun, result))
6159 : {
6160 52 : const region *callee_result_reg
6161 52 : = get_lvalue (result_default_ssa, ctxt);
6162 :
6163 : /* Set the callee's reference to refer to the caller's lhs. */
6164 52 : set_value (callee_result_reg, ref_sval, ctxt);
6165 : }
6166 : }
6167 : }
6168 : else
6169 : {
6170 : /* Otherwise we have a top-level call within the analysis. The params
6171 : have defined but unknown initial values.
6172 : Anything they point to has escaped. */
6173 :
6174 : /* Update m_current_frame. */
6175 26251 : m_current_frame = m_mgr->get_frame_region (m_current_frame, fun);
6176 :
6177 : /* Handle "__attribute__((nonnull))". */
6178 26251 : tree fntype = TREE_TYPE (fndecl);
6179 26251 : bitmap nonnull_args = get_nonnull_args (fntype);
6180 :
6181 26251 : unsigned parm_idx = 0;
6182 49997 : for (tree iter_parm = DECL_ARGUMENTS (fndecl); iter_parm;
6183 23746 : iter_parm = DECL_CHAIN (iter_parm))
6184 : {
6185 23746 : bool non_null = (nonnull_args
6186 23746 : ? (bitmap_empty_p (nonnull_args)
6187 1515 : || bitmap_bit_p (nonnull_args, parm_idx))
6188 23746 : : false);
6189 23746 : if (tree parm_default_ssa = get_ssa_default_def (fun, iter_parm))
6190 20293 : on_top_level_param (parm_default_ssa, non_null, ctxt);
6191 : else
6192 3453 : on_top_level_param (iter_parm, non_null, ctxt);
6193 23746 : parm_idx++;
6194 : }
6195 :
6196 26251 : BITMAP_FREE (nonnull_args);
6197 : }
6198 :
6199 41050 : return m_current_frame;
6200 : }
6201 :
6202 : /* Get the function of the top-most frame in this region_model's stack.
6203 : There must be such a frame. */
6204 :
6205 : const function *
6206 1192 : region_model::get_current_function () const
6207 : {
6208 1192 : const frame_region *frame = get_current_frame ();
6209 1192 : gcc_assert (frame);
6210 1192 : return &frame->get_function ();
6211 : }
6212 :
6213 : /* Custom region_model_context for the assignment to the result
6214 : at a call statement when popping a frame (PR analyzer/106203). */
6215 :
6216 : class caller_context : public region_model_context_decorator
6217 : {
6218 : public:
6219 5773 : caller_context (region_model_context *inner,
6220 : const gcall *call_stmt,
6221 : const frame_region &caller_frame)
6222 : : region_model_context_decorator (inner),
6223 5773 : m_call_stmt (call_stmt),
6224 5773 : m_caller_frame (caller_frame)
6225 : {}
6226 :
6227 : pending_location
6228 9 : get_pending_location_for_diag () const override
6229 : {
6230 9 : pending_location ploc
6231 9 : = region_model_context_decorator::get_pending_location_for_diag ();
6232 :
6233 9 : ploc.m_event_loc_info
6234 9 : = event_loc_info (m_call_stmt->location,
6235 9 : m_caller_frame.get_fndecl (),
6236 9 : m_caller_frame.get_stack_depth ());
6237 :
6238 9 : return ploc;
6239 : }
6240 :
6241 11555 : const gimple *get_stmt () const override
6242 : {
6243 11555 : return m_call_stmt;
6244 : };
6245 :
6246 : private:
6247 : const gcall *m_call_stmt;
6248 : const frame_region &m_caller_frame;
6249 : };
6250 :
6251 :
6252 : /* Pop the topmost frame_region from this region_model's stack;
6253 :
6254 : If RESULT_LVALUE is non-null, copy any return value from the frame
6255 : into the corresponding region (evaluated with respect to the *caller*
6256 : frame, rather than the called frame).
6257 : If OUT_RESULT is non-null, copy any return value from the frame
6258 : into *OUT_RESULT.
6259 :
6260 : If non-null, use CALL_STMT as the location when complaining about
6261 : assignment of the return value to RESULT_LVALUE.
6262 :
6263 : If EVAL_RETURN_SVALUE is false, then don't evaluate the return value.
6264 : This is for use when unwinding frames e.g. due to longjmp, to suppress
6265 : erroneously reporting uninitialized return values.
6266 :
6267 : Purge the frame region and all its descendent regions.
6268 : Convert any pointers that point into such regions into
6269 : poison_kind::popped_stack svalues. */
6270 :
6271 : void
6272 29930 : region_model::pop_frame (tree result_lvalue,
6273 : const svalue **out_result,
6274 : region_model_context *ctxt,
6275 : const gcall *call_stmt,
6276 : bool eval_return_svalue)
6277 : {
6278 29930 : gcc_assert (m_current_frame);
6279 :
6280 29930 : const region_model pre_popped_model = *this;
6281 29930 : const frame_region *frame_reg = m_current_frame;
6282 :
6283 : /* Notify state machines. */
6284 29930 : if (ctxt)
6285 27314 : ctxt->on_pop_frame (frame_reg);
6286 :
6287 : /* Evaluate the result, within the callee frame. */
6288 29930 : tree fndecl = m_current_frame->get_function ().decl;
6289 29930 : tree result = DECL_RESULT (fndecl);
6290 29930 : const svalue *retval = nullptr;
6291 29930 : if (result
6292 29922 : && TREE_TYPE (result) != void_type_node
6293 43679 : && eval_return_svalue)
6294 : {
6295 11461 : retval = get_rvalue (result, ctxt);
6296 11461 : if (out_result)
6297 5287 : *out_result = retval;
6298 : }
6299 :
6300 : /* Pop the frame. */
6301 29930 : m_current_frame = m_current_frame->get_calling_frame ();
6302 :
6303 29930 : if (result_lvalue
6304 29930 : && retval
6305 : /* Don't write back for DECL_BY_REFERENCE; the writes
6306 : should have happened within the callee already. */
6307 29930 : && !DECL_BY_REFERENCE (result))
6308 : {
6309 5773 : gcc_assert (eval_return_svalue);
6310 :
6311 : /* Compute result_dst_reg using RESULT_LVALUE *after* popping
6312 : the frame, but before poisoning pointers into the old frame. */
6313 5773 : const region *result_dst_reg = get_lvalue (result_lvalue, ctxt);
6314 :
6315 : /* Assign retval to result_dst_reg, using caller_context
6316 : to set the call_stmt and the popped_frame for any diagnostics
6317 : due to the assignment. */
6318 5773 : gcc_assert (m_current_frame);
6319 5773 : caller_context caller_ctxt (ctxt, call_stmt, *m_current_frame);
6320 11546 : set_value (result_dst_reg, retval, call_stmt ? &caller_ctxt : ctxt);
6321 : }
6322 :
6323 29930 : unbind_region_and_descendents (frame_reg,poison_kind::popped_stack);
6324 :
6325 29930 : if (auto chan = g->get_channels ().analyzer_events_channel.get_if_active ())
6326 : {
6327 227 : gcc::topics::analyzer_events::on_frame_popped msg
6328 227 : {this, &pre_popped_model, retval, ctxt};
6329 227 : chan->publish (msg);
6330 : }
6331 29930 : }
6332 :
6333 : /* Get the number of frames in this region_model's stack. */
6334 :
6335 : int
6336 4960993 : region_model::get_stack_depth () const
6337 : {
6338 4960993 : const frame_region *frame = get_current_frame ();
6339 4960993 : if (frame)
6340 4943193 : return frame->get_stack_depth ();
6341 : else
6342 : return 0;
6343 : }
6344 :
6345 : /* Get the frame_region with the given index within the stack.
6346 : The frame_region must exist. */
6347 :
6348 : const frame_region *
6349 4647901 : region_model::get_frame_at_index (int index) const
6350 : {
6351 4647901 : const frame_region *frame = get_current_frame ();
6352 4647901 : gcc_assert (frame);
6353 4647901 : gcc_assert (index >= 0);
6354 4647901 : gcc_assert (index <= frame->get_index ());
6355 7290249 : while (index != frame->get_index ())
6356 : {
6357 2642348 : frame = frame->get_calling_frame ();
6358 2642348 : gcc_assert (frame);
6359 : }
6360 4647901 : return frame;
6361 : }
6362 :
6363 : /* Unbind svalues for any regions in REG and below.
6364 : Find any pointers to such regions; convert them to
6365 : poisoned values of kind PKIND.
6366 : Also purge any dynamic extents. */
6367 :
6368 : void
6369 40916 : region_model::unbind_region_and_descendents (const region *reg,
6370 : enum poison_kind pkind)
6371 : {
6372 : /* Gather a set of base regions to be unbound. */
6373 40916 : hash_set<const region *> base_regs;
6374 198320 : for (store::cluster_map_t::iterator iter = m_store.begin ();
6375 198320 : iter != m_store.end (); ++iter)
6376 : {
6377 157404 : const region *iter_base_reg = (*iter).first;
6378 157404 : if (iter_base_reg->descendent_of_p (reg))
6379 31724 : base_regs.add (iter_base_reg);
6380 : }
6381 72640 : for (hash_set<const region *>::iterator iter = base_regs.begin ();
6382 72640 : iter != base_regs.end (); ++iter)
6383 31724 : m_store.purge_cluster (*iter);
6384 :
6385 : /* Find any pointers to REG or its descendents; convert to poisoned. */
6386 40916 : poison_any_pointers_to_descendents (reg, pkind);
6387 :
6388 : /* Purge dynamic extents of any base regions in REG and below
6389 : (e.g. VLAs and alloca stack regions). */
6390 96752 : for (auto iter : m_dynamic_extents)
6391 : {
6392 14920 : const region *iter_reg = iter.first;
6393 14920 : if (iter_reg->descendent_of_p (reg))
6394 6384 : unset_dynamic_extents (iter_reg);
6395 : }
6396 40916 : }
6397 :
6398 : /* Find any pointers to REG or its descendents; convert them to
6399 : poisoned values of kind PKIND. */
6400 :
6401 : void
6402 40916 : region_model::poison_any_pointers_to_descendents (const region *reg,
6403 : enum poison_kind pkind)
6404 : {
6405 166596 : for (const auto &cluster_iter : m_store)
6406 : {
6407 125680 : binding_cluster *cluster = cluster_iter.second;
6408 125680 : cluster->poison_any_pointers_to_descendents (reg, pkind);
6409 : }
6410 40916 : }
6411 :
6412 : /* Attempt to merge THIS with OTHER_MODEL, writing the result
6413 : to OUT_MODEL. Use POINT to distinguish values created as a
6414 : result of merging. */
6415 :
6416 : bool
6417 63282 : region_model::can_merge_with_p (const region_model &other_model,
6418 : const program_point &point,
6419 : region_model *out_model,
6420 : const extrinsic_state *ext_state,
6421 : const program_state *state_a,
6422 : const program_state *state_b) const
6423 : {
6424 63282 : gcc_assert (out_model);
6425 63282 : gcc_assert (m_mgr == other_model.m_mgr);
6426 63282 : gcc_assert (m_mgr == out_model->m_mgr);
6427 :
6428 63282 : if (m_current_frame != other_model.m_current_frame)
6429 : return false;
6430 63282 : out_model->m_current_frame = m_current_frame;
6431 :
6432 63282 : model_merger m (this, &other_model, point, out_model,
6433 63282 : ext_state, state_a, state_b);
6434 :
6435 63282 : if (!store::can_merge_p (&m_store, &other_model.m_store,
6436 : &out_model->m_store,
6437 : &m))
6438 : return false;
6439 :
6440 45249 : if (!m_dynamic_extents.can_merge_with_p (other_model.m_dynamic_extents,
6441 : &out_model->m_dynamic_extents))
6442 : return false;
6443 :
6444 : /* Merge constraints. */
6445 42343 : constraint_manager::merge (*m_constraints,
6446 42343 : *other_model.m_constraints,
6447 : out_model->m_constraints);
6448 :
6449 43198 : for (auto iter : m.m_svals_changing_meaning)
6450 855 : out_model->m_constraints->purge_state_involving (*iter);
6451 :
6452 42343 : if (m_thrown_exceptions_stack != other_model.m_thrown_exceptions_stack)
6453 : return false;
6454 38461 : out_model->m_thrown_exceptions_stack = m_thrown_exceptions_stack;
6455 :
6456 38461 : if (m_caught_exceptions_stack != other_model.m_caught_exceptions_stack)
6457 : return false;
6458 37744 : out_model->m_caught_exceptions_stack = m_caught_exceptions_stack;
6459 :
6460 37744 : return true;
6461 63282 : }
6462 :
6463 : /* Recover the vtable OBJ's vptr (for OBJ_TYPE) actually points to, plus the
6464 : byte offset into it, so callers can recover the most-derived type from the
6465 : vtable's DECL_CONTEXT and BINFO.
6466 :
6467 : Only recognizes the shape we model for a vptr store, "vptr_field =
6468 : &vtable_decl + offset", i.e. a POINTER_PLUS_EXPR binop_svalue of a
6469 : region_svalue for the _ZTV* decl and a constant offset. The offset is
6470 : nonzero when this vptr slot belongs to a non-primary base's own sub-vtable
6471 : group within the same decl; we return it via OUT for callers that need to
6472 : index into the vtable (e.g. gimple_get_virt_method_for_vtable). */
6473 :
6474 : tree
6475 2130 : region_model::get_vtable_from_obj (tree obj, tree obj_type,
6476 : region_model_manager *mgr,
6477 : region_model_context *ctxt,
6478 : unsigned HOST_WIDE_INT *out) const
6479 : {
6480 2130 : if (!obj_type)
6481 : return NULL_TREE;
6482 2130 : tree vfield = TYPE_VFIELD (obj_type);
6483 2130 : if (!vfield)
6484 : return NULL_TREE;
6485 :
6486 2130 : const svalue *obj_sval = get_rvalue (obj, ctxt);
6487 2130 : const region *obj_reg = deref_rvalue (obj_sval, obj, ctxt);
6488 2130 : const region *vptr_reg = mgr->get_field_region (obj_reg, vfield);
6489 :
6490 2130 : const svalue *vptr_sval = get_store_value (vptr_reg, ctxt);
6491 2130 : auto *sym_ptr = vptr_sval->maybe_get_symbolic_pointer ();
6492 2130 : if (!sym_ptr)
6493 : return NULL_TREE;
6494 261 : concrete_byte_offset conc_byte_offset;
6495 261 : if (!concrete_from_symbolic (sym_ptr->get_byte_offset (), &conc_byte_offset))
6496 : return NULL_TREE;
6497 261 : if (out)
6498 261 : *out = conc_byte_offset.get_integer ().as_unsigned_long ();
6499 261 : tree vtable = sym_ptr->get_base_region ().maybe_get_decl ();
6500 261 : return vtable;
6501 261 : }
6502 :
6503 : /* Attempt to get the fndecl for a virtual call via OBJ_TYPE_REF, or
6504 : NULL_TREE if it can't be resolved.
6505 :
6506 : A virtual call's callee is a GIMPLE OBJ_TYPE_REF:
6507 : OBJ_TYPE_REF(EXPR; (TYPE)OBJECT->TOKEN)
6508 : EXPR is the function pointer actually loaded and called; OBJECT, TYPE and
6509 : TOKEN are devirtualization metadata, not needed to perform the call itself.
6510 : OBJECT is the "this" pointer, TYPE its static type, TOKEN the vtable slot
6511 : index. We ignore EXPR and instead resolve TOKEN against OBJECT's modeled
6512 : dynamic type rather than its static TYPE.
6513 :
6514 : Reads the value bound to the object's vptr field (OBJ_TYPE_REF_OBJECT's
6515 : vfield).
6516 : If that value has the form "&vtable_decl + constant" (a region_svalue for a
6517 : _ZTV* decl plus a byte offset), recover the vtable decl and offset and use
6518 : gimple_get_virt_method_for_vtable, together with OBJ_TYPE_REF_TOKEN, to look
6519 : up the concrete fndecl in the vtable's initializer.
6520 :
6521 : Relies on the store having bound the vptr field to the _ZTV* instance, so no
6522 : separate modeling of the object's dynamic type is needed. */
6523 :
6524 : tree
6525 2031 : region_model::get_fndecl_for_virtual_call (const_tree obj_type_ref,
6526 : region_model_context *ctxt)
6527 : {
6528 2031 : tree obj = OBJ_TYPE_REF_OBJECT (obj_type_ref);
6529 2031 : tree obj_type = obj_type_ref_class (obj_type_ref);
6530 :
6531 2031 : unsigned HOST_WIDE_INT offset;
6532 2031 : tree vtable = get_vtable_from_obj (obj, obj_type, m_mgr, ctxt, &offset);
6533 2031 : if (!vtable)
6534 : return NULL_TREE;
6535 :
6536 165 : unsigned HOST_WIDE_INT token
6537 165 : = tree_to_uhwi (OBJ_TYPE_REF_TOKEN (obj_type_ref));
6538 165 : bool can_refer;
6539 165 : tree vptr_fn
6540 165 : = gimple_get_virt_method_for_vtable (token, vtable, offset, &can_refer);
6541 165 : if (!vptr_fn || !can_refer)
6542 : return NULL_TREE;
6543 :
6544 165 : if (cgraph_node *node = cgraph_node::get_create (vptr_fn))
6545 165 : if (const cgraph_node *ultimate = node->ultimate_alias_target ())
6546 165 : return ultimate->decl;
6547 :
6548 : return NULL_TREE;
6549 : }
6550 :
6551 : /* Attempt to get the fndecl used at CALL, if known, or NULL_TREE
6552 : otherwise. */
6553 :
6554 : tree
6555 936243 : region_model::get_fndecl_for_call (const gcall &call,
6556 : region_model_context *ctxt)
6557 : {
6558 936243 : tree fn_ptr = gimple_call_fn (&call);
6559 936243 : if (fn_ptr == NULL_TREE)
6560 : return NULL_TREE;
6561 :
6562 : /* Handle OBJ_TYPE_REF so that we can try to find the definition for a virtual
6563 : call and treat it like any other call. */
6564 892757 : if (TREE_CODE (fn_ptr) == OBJ_TYPE_REF)
6565 2031 : return get_fndecl_for_virtual_call (fn_ptr, ctxt);
6566 :
6567 890726 : const svalue *fn_ptr_sval = get_rvalue (fn_ptr, ctxt);
6568 890726 : if (auto sym_ptr = fn_ptr_sval->maybe_get_symbolic_pointer ())
6569 886318 : if (sym_ptr->zero_offset_p ())
6570 : {
6571 886318 : const region ® = sym_ptr->get_base_region ();
6572 886318 : if (const function_region *fn_reg = reg.dyn_cast_function_region ())
6573 : {
6574 886262 : tree fn_decl = fn_reg->get_fndecl ();
6575 886262 : cgraph_node *node = cgraph_node::get (fn_decl);
6576 886262 : if (!node)
6577 : return NULL_TREE;
6578 886262 : const cgraph_node *ultimate_node = node->ultimate_alias_target ();
6579 886262 : if (ultimate_node)
6580 886262 : return ultimate_node->decl;
6581 : }
6582 : }
6583 :
6584 : return NULL_TREE;
6585 : }
6586 :
6587 : /* Would be much simpler to use a lambda here, if it were supported. */
6588 :
6589 : struct append_regions_cb_data
6590 : {
6591 : const region_model *model;
6592 : auto_vec<const decl_region *> *out;
6593 : };
6594 :
6595 : /* Populate *OUT with all decl_regions in the current
6596 : frame that have clusters within the store. */
6597 :
6598 : void
6599 372136 : region_model::
6600 : get_regions_for_current_frame (auto_vec<const decl_region *> *out) const
6601 : {
6602 372136 : append_regions_cb_data data;
6603 372136 : data.model = this;
6604 372136 : data.out = out;
6605 372136 : m_store.for_each_cluster (append_regions_cb, &data);
6606 372136 : }
6607 :
6608 : /* Implementation detail of get_regions_for_current_frame. */
6609 :
6610 : void
6611 1965135 : region_model::append_regions_cb (const region *base_reg,
6612 : append_regions_cb_data *cb_data)
6613 : {
6614 1965135 : if (base_reg->get_parent_region () != cb_data->model->m_current_frame)
6615 : return;
6616 932148 : if (const decl_region *decl_reg = base_reg->dyn_cast_decl_region ())
6617 913857 : cb_data->out->safe_push (decl_reg);
6618 : }
6619 :
6620 :
6621 : /* Abstract class for diagnostics related to the use of
6622 : floating-point arithmetic where precision is needed. */
6623 :
6624 25 : class imprecise_floating_point_arithmetic : public pending_diagnostic
6625 : {
6626 : public:
6627 50 : int get_controlling_option () const final override
6628 : {
6629 50 : return OPT_Wanalyzer_imprecise_fp_arithmetic;
6630 : }
6631 : };
6632 :
6633 : /* Concrete diagnostic to complain about uses of floating-point arithmetic
6634 : in the size argument of malloc etc. */
6635 :
6636 : class float_as_size_arg : public imprecise_floating_point_arithmetic
6637 : {
6638 : public:
6639 25 : float_as_size_arg (tree arg) : m_arg (arg)
6640 : {}
6641 :
6642 305 : const char *get_kind () const final override
6643 : {
6644 305 : return "float_as_size_arg_diagnostic";
6645 : }
6646 :
6647 25 : bool subclass_equal_p (const pending_diagnostic &other) const final override
6648 : {
6649 25 : return same_tree_p (m_arg, ((const float_as_size_arg &) other).m_arg);
6650 : }
6651 :
6652 25 : bool emit (diagnostic_emission_context &ctxt) final override
6653 : {
6654 25 : bool warned = ctxt.warn ("use of floating-point arithmetic here might"
6655 : " yield unexpected results");
6656 25 : if (warned)
6657 25 : inform (ctxt.get_location (),
6658 : "only use operands of an integer type"
6659 : " inside the size argument");
6660 25 : return warned;
6661 : }
6662 :
6663 : bool
6664 50 : describe_final_event (pretty_printer &pp,
6665 : const evdesc::final_event &) final override
6666 : {
6667 50 : if (m_arg)
6668 50 : pp_printf (&pp,
6669 : "operand %qE is of type %qT",
6670 50 : m_arg, TREE_TYPE (m_arg));
6671 : else
6672 0 : pp_printf (&pp,
6673 : "at least one operand of the size argument is"
6674 : " of a floating-point type");
6675 50 : return true;
6676 : }
6677 :
6678 : private:
6679 : tree m_arg;
6680 : };
6681 :
6682 : /* Visitor to find uses of floating-point variables/constants in an svalue. */
6683 :
6684 : class contains_floating_point_visitor : public visitor
6685 : {
6686 : public:
6687 7967 : contains_floating_point_visitor (const svalue *root_sval) : m_result (nullptr)
6688 : {
6689 7967 : root_sval->accept (this);
6690 : }
6691 :
6692 7967 : const svalue *get_svalue_to_report ()
6693 : {
6694 7967 : return m_result;
6695 : }
6696 :
6697 7389 : void visit_constant_svalue (const constant_svalue *sval) final override
6698 : {
6699 : /* At the point the analyzer runs, constant integer operands in a floating
6700 : point expression are already implicitly converted to floating-points.
6701 : Thus, we do prefer to report non-constants such that the diagnostic
6702 : always reports a floating-point operand. */
6703 7389 : tree type = sval->get_type ();
6704 7389 : if (type && FLOAT_TYPE_P (type) && !m_result)
6705 9 : m_result = sval;
6706 7389 : }
6707 :
6708 765 : void visit_initial_svalue (const initial_svalue *sval) final override
6709 : {
6710 765 : tree type = sval->get_type ();
6711 765 : if (type && FLOAT_TYPE_P (type))
6712 16 : m_result = sval;
6713 765 : }
6714 :
6715 : private:
6716 : /* Non-null if at least one floating-point operand was found. */
6717 : const svalue *m_result;
6718 : };
6719 :
6720 : /* May complain about uses of floating-point operands in SIZE_IN_BYTES. */
6721 :
6722 : void
6723 7967 : region_model::check_dynamic_size_for_floats (const svalue *size_in_bytes,
6724 : region_model_context *ctxt) const
6725 : {
6726 7967 : gcc_assert (ctxt);
6727 :
6728 7967 : contains_floating_point_visitor v (size_in_bytes);
6729 7967 : if (const svalue *float_sval = v.get_svalue_to_report ())
6730 : {
6731 25 : tree diag_arg = get_representative_tree (float_sval);
6732 25 : ctxt->warn (std::make_unique<float_as_size_arg> (diag_arg));
6733 : }
6734 7967 : }
6735 :
6736 : /* Return a region describing a heap-allocated block of memory.
6737 : Use CTXT to complain about tainted sizes.
6738 :
6739 : Reuse an existing heap_allocated_region if it's not being referenced by
6740 : this region_model; otherwise create a new one.
6741 :
6742 : Optionally (update_state_machine) transitions the pointer pointing to the
6743 : heap_allocated_region from start to assumed non-null. */
6744 :
6745 : const region *
6746 18854 : region_model::get_or_create_region_for_heap_alloc (const svalue *size_in_bytes,
6747 : region_model_context *ctxt,
6748 : bool update_state_machine,
6749 : const call_details *cd)
6750 : {
6751 : /* Determine which regions are referenced in this region_model, so that
6752 : we can reuse an existing heap_allocated_region if it's not in use on
6753 : this path. */
6754 18854 : auto_bitmap base_regs_in_use;
6755 18854 : get_referenced_base_regions (base_regs_in_use);
6756 :
6757 : /* Don't reuse regions that are marked as TOUCHED. */
6758 90571 : for (store::cluster_map_t::iterator iter = m_store.begin ();
6759 90571 : iter != m_store.end (); ++iter)
6760 71717 : if ((*iter).second->touched_p ())
6761 : {
6762 3285 : const region *base_reg = (*iter).first;
6763 3285 : bitmap_set_bit (base_regs_in_use, base_reg->get_id ());
6764 : }
6765 :
6766 18854 : const region *reg
6767 18854 : = m_mgr->get_or_create_region_for_heap_alloc (base_regs_in_use);
6768 18854 : if (size_in_bytes)
6769 13243 : if (compat_types_p (size_in_bytes->get_type (), size_type_node))
6770 13243 : set_dynamic_extents (reg, size_in_bytes, ctxt);
6771 :
6772 18854 : if (update_state_machine && cd)
6773 : {
6774 0 : const svalue *ptr_sval
6775 0 : = m_mgr->get_ptr_svalue (cd->get_lhs_type (), reg);
6776 0 : transition_ptr_sval_non_null (ctxt, ptr_sval);
6777 : }
6778 :
6779 18854 : return reg;
6780 18854 : }
6781 :
6782 : /* Populate OUT_IDS with the set of IDs of those base regions which are
6783 : reachable in this region_model. */
6784 :
6785 : void
6786 18990 : region_model::get_referenced_base_regions (auto_bitmap &out_ids) const
6787 : {
6788 18990 : reachable_regions reachable_regs (const_cast<region_model *> (this));
6789 18990 : m_store.for_each_cluster (reachable_regions::init_cluster_cb,
6790 : &reachable_regs);
6791 : /* Get regions for locals that have explicitly bound values. */
6792 91121 : for (store::cluster_map_t::iterator iter = m_store.begin ();
6793 91121 : iter != m_store.end (); ++iter)
6794 : {
6795 72131 : const region *base_reg = (*iter).first;
6796 72131 : if (const region *parent = base_reg->get_parent_region ())
6797 72131 : if (parent->get_kind () == RK_FRAME)
6798 57266 : reachable_regs.add (base_reg, false);
6799 : }
6800 :
6801 18994 : for (auto &eh_node : m_thrown_exceptions_stack)
6802 4 : eh_node.add_to_reachable_regions (reachable_regs);
6803 19056 : for (auto &eh_node : m_caught_exceptions_stack)
6804 66 : eh_node.add_to_reachable_regions (reachable_regs);
6805 :
6806 :
6807 18990 : bitmap_clear (out_ids);
6808 95102 : for (auto iter_reg : reachable_regs)
6809 76112 : bitmap_set_bit (out_ids, iter_reg->get_id ());
6810 18990 : }
6811 :
6812 : /* Return a new region describing a block of memory allocated within the
6813 : current frame.
6814 : Use CTXT to complain about tainted sizes. */
6815 :
6816 : const region *
6817 520 : region_model::create_region_for_alloca (const svalue *size_in_bytes,
6818 : region_model_context *ctxt)
6819 : {
6820 520 : const region *reg = m_mgr->create_region_for_alloca (m_current_frame);
6821 520 : if (compat_types_p (size_in_bytes->get_type (), size_type_node))
6822 519 : set_dynamic_extents (reg, size_in_bytes, ctxt);
6823 520 : return reg;
6824 : }
6825 :
6826 : /* Record that the size of REG is SIZE_IN_BYTES.
6827 : Use CTXT to complain about tainted sizes. */
6828 :
6829 : void
6830 14204 : region_model::set_dynamic_extents (const region *reg,
6831 : const svalue *size_in_bytes,
6832 : region_model_context *ctxt)
6833 : {
6834 14204 : assert_compat_types (size_in_bytes->get_type (), size_type_node);
6835 14204 : if (ctxt)
6836 : {
6837 7967 : check_dynamic_size_for_taint (reg->get_memory_space (), size_in_bytes,
6838 : ctxt);
6839 7967 : check_dynamic_size_for_floats (size_in_bytes, ctxt);
6840 : }
6841 14204 : m_dynamic_extents.put (reg, size_in_bytes);
6842 14204 : }
6843 :
6844 : /* Get the recording of REG in bytes, or nullptr if no dynamic size was
6845 : recorded. */
6846 :
6847 : const svalue *
6848 93170 : region_model::get_dynamic_extents (const region *reg) const
6849 : {
6850 93170 : if (const svalue * const *slot = m_dynamic_extents.get (reg))
6851 15037 : return *slot;
6852 : return nullptr;
6853 : }
6854 :
6855 : /* Unset any recorded dynamic size of REG. */
6856 :
6857 : void
6858 49678 : region_model::unset_dynamic_extents (const region *reg)
6859 : {
6860 49678 : m_dynamic_extents.remove (reg);
6861 49678 : }
6862 :
6863 : /* Visitor that counts the number of uninitialized bites seen
6864 : in bit_vectors. */
6865 :
6866 25 : struct uninit_bit_counter : public symbolic::node_visitor
6867 : {
6868 25 : uninit_bit_counter (symbolic::scalar_manager<concrete_bit_size> &mgr)
6869 25 : : m_num_uninit_bits (&mgr.get_concrete (0_bits))
6870 : {
6871 25 : }
6872 :
6873 : bool
6874 78 : visit_svalue (const svalue &sval) final override
6875 : {
6876 78 : return symbolic::node_visitor::visit_svalue (sval);
6877 : }
6878 :
6879 : bool
6880 94 : visit_bit_vector (const symbolic::bit_vector &bv) final override
6881 : {
6882 94 : if (!symbolic::node_visitor::visit_bit_vector (bv))
6883 : return false;
6884 94 : if (auto *p = bv.dyn_cast_poisoned_bit_vector ())
6885 28 : if (p->get_poison_kind () == poison_kind::uninit)
6886 28 : m_num_uninit_bits = &(*m_num_uninit_bits + bv.get_size ());
6887 : return true;
6888 : }
6889 :
6890 : const symbolic_bit_size *m_num_uninit_bits;
6891 : };
6892 :
6893 : /* A subclass of pending_diagnostic for complaining about uninitialized data
6894 : being copied across a trust boundary to an untrusted output
6895 : (e.g. copy_to_user infoleaks in the Linux kernel). */
6896 :
6897 : class exposure_through_uninit_copy
6898 : : public pending_diagnostic_subclass<exposure_through_uninit_copy>
6899 : {
6900 : public:
6901 26 : exposure_through_uninit_copy (const region *src_region,
6902 : const region *dest_region,
6903 : const svalue *copied_sval,
6904 : symbolic::node_manager &node_mgr)
6905 26 : : m_src_region (src_region),
6906 26 : m_dest_region (dest_region),
6907 26 : m_copied_sval (copied_sval),
6908 26 : m_node_mgr (node_mgr)
6909 : {
6910 : }
6911 :
6912 294 : const char *get_kind () const final override
6913 : {
6914 294 : return "exposure_through_uninit_copy";
6915 : }
6916 :
6917 26 : bool operator== (const exposure_through_uninit_copy &other) const
6918 : {
6919 26 : return (m_src_region == other.m_src_region
6920 26 : && m_dest_region == other.m_dest_region
6921 52 : && m_copied_sval == other.m_copied_sval);
6922 : }
6923 :
6924 51 : int get_controlling_option () const final override
6925 : {
6926 51 : return OPT_Wanalyzer_exposure_through_uninit_copy;
6927 : }
6928 :
6929 25 : bool emit (diagnostic_emission_context &ctxt) final override
6930 : {
6931 : /* CWE-200: Exposure of Sensitive Information to an Unauthorized Actor. */
6932 25 : ctxt.add_cwe (200);
6933 51 : enum memory_space mem_space = get_src_memory_space ();
6934 25 : bool warned;
6935 25 : switch (mem_space)
6936 : {
6937 1 : default:
6938 1 : warned = ctxt.warn ("potential exposure of sensitive information"
6939 : " by copying uninitialized data"
6940 : " across trust boundary");
6941 1 : break;
6942 24 : case MEMSPACE_STACK:
6943 24 : warned = ctxt.warn ("potential exposure of sensitive information"
6944 : " by copying uninitialized data from stack"
6945 : " across trust boundary");
6946 24 : break;
6947 0 : case MEMSPACE_HEAP:
6948 0 : warned = ctxt.warn ("potential exposure of sensitive information"
6949 : " by copying uninitialized data from heap"
6950 : " across trust boundary");
6951 0 : break;
6952 : }
6953 25 : if (warned)
6954 : {
6955 25 : const location_t loc = ctxt.get_location ();
6956 25 : inform_number_of_uninit_bits (loc);
6957 25 : complain_about_uninit_ranges (loc);
6958 :
6959 25 : if (mem_space == MEMSPACE_STACK)
6960 24 : maybe_emit_fixit_hint ();
6961 : }
6962 25 : return warned;
6963 : }
6964 :
6965 : bool
6966 50 : describe_final_event (pretty_printer &pp,
6967 : const evdesc::final_event &) final override
6968 : {
6969 102 : enum memory_space mem_space = get_src_memory_space ();
6970 50 : switch (mem_space)
6971 : {
6972 2 : default:
6973 2 : pp_string (&pp, "uninitialized data copied here");
6974 2 : return true;
6975 :
6976 48 : case MEMSPACE_STACK:
6977 48 : pp_string (&pp, "uninitialized data copied from stack here");
6978 48 : return true;
6979 :
6980 0 : case MEMSPACE_HEAP:
6981 0 : pp_string (&pp, "uninitialized data copied from heap here");
6982 0 : return true;
6983 : }
6984 : }
6985 :
6986 50 : void mark_interesting_stuff (interesting_t *interest) final override
6987 : {
6988 50 : if (m_src_region)
6989 50 : interest->add_region_creation (m_src_region);
6990 50 : }
6991 :
6992 : void
6993 0 : maybe_add_sarif_properties (diagnostics::sarif_object &result_obj)
6994 : const final override
6995 : {
6996 0 : auto &props = result_obj.get_or_create_properties ();
6997 : #define PROPERTY_PREFIX "gcc/-Wanalyzer-exposure-through-uninit-copy/"
6998 0 : props.set (PROPERTY_PREFIX "src_region", m_src_region->to_json ());
6999 0 : props.set (PROPERTY_PREFIX "dest_region", m_dest_region->to_json ());
7000 0 : props.set (PROPERTY_PREFIX "copied_sval", m_copied_sval->to_json ());
7001 : #undef PROPERTY_PREFIX
7002 0 : }
7003 :
7004 : private:
7005 75 : enum memory_space get_src_memory_space () const
7006 : {
7007 75 : return m_src_region ? m_src_region->get_memory_space () : MEMSPACE_UNKNOWN;
7008 : }
7009 :
7010 : const symbolic_bit_size &
7011 25 : calc_num_uninit_bits () const
7012 : {
7013 25 : auto &bit_mgr = m_node_mgr.get_scalars ().get_bits ();
7014 25 : uninit_bit_counter v (bit_mgr);
7015 25 : m_copied_sval->accept_node_visitor (v);
7016 25 : return *v.m_num_uninit_bits;
7017 25 : }
7018 :
7019 25 : void inform_number_of_uninit_bits (location_t loc) const
7020 : {
7021 25 : auto &num_uninit_bits = calc_num_uninit_bits ();
7022 25 : concrete_bit_size conc_num_uninit_bits;
7023 25 : if (!concrete_from_symbolic (num_uninit_bits, &conc_num_uninit_bits))
7024 0 : return;
7025 25 : concrete_byte_size conc_num_uninit_bytes;
7026 25 : if (maybe_bytes_from_bits (conc_num_uninit_bits, &conc_num_uninit_bytes))
7027 : {
7028 : /* Express in bytes. */
7029 25 : if (conc_num_uninit_bytes == 1_byte)
7030 3 : inform (loc, "1 byte is uninitialized");
7031 : else
7032 : {
7033 22 : pp_element_integer e_num_bytes
7034 22 : (conc_num_uninit_bytes.get_integer ());
7035 22 : inform (loc,
7036 : "%e bytes are uninitialized", &e_num_bytes);
7037 22 : }
7038 : }
7039 : else
7040 : {
7041 : /* Express in bits. */
7042 0 : if (conc_num_uninit_bits == 1_bit)
7043 0 : inform (loc, "1 bit is uninitialized");
7044 : else
7045 : {
7046 0 : pp_element_integer e_num_bits
7047 0 : (conc_num_uninit_bits.get_integer ());
7048 0 : inform (loc,
7049 : "%e bits are uninitialized", &e_num_bits);
7050 0 : }
7051 : }
7052 25 : }
7053 :
7054 : bool
7055 25 : get_uninit_ranges (std::vector<concrete_bit_range> *out) const
7056 : {
7057 25 : auto *sval_from_bv = m_copied_sval->dyn_cast_svalue_from_bit_vector ();
7058 25 : if (!sval_from_bv)
7059 : return false;
7060 25 : auto &bv = sval_from_bv->get_bit_vector ();
7061 : /* Find keys for uninit svals. */
7062 25 : if (auto *p = bv.dyn_cast_poisoned_bit_vector ())
7063 : {
7064 4 : if (p->get_poison_kind () == poison_kind::uninit)
7065 : {
7066 4 : concrete_bit_size bit_size;
7067 4 : if (!concrete_from_symbolic (p->get_size (), &bit_size))
7068 : return false;
7069 12 : out->push_back (concrete_bit_range (0_bits, bit_size));
7070 4 : return true;
7071 4 : }
7072 : }
7073 21 : else if (auto *concat = bv.dyn_cast_concat_bit_vector ())
7074 : {
7075 20 : concrete_bit_offset start_offset (0_bits);
7076 73 : for (auto iter : *concat)
7077 : {
7078 53 : concrete_bit_size bit_size;
7079 53 : if (!concrete_from_symbolic (iter->get_size (), &bit_size))
7080 0 : return false;
7081 53 : if (auto *p = iter->dyn_cast_poisoned_bit_vector ())
7082 23 : if (p->get_poison_kind () == poison_kind::uninit)
7083 69 : out->push_back (concrete_bit_range (start_offset, bit_size));
7084 53 : start_offset += bit_size;
7085 53 : }
7086 : return true;
7087 20 : }
7088 : return false;
7089 : }
7090 :
7091 25 : void complain_about_uninit_ranges (location_t loc) const
7092 : {
7093 25 : std::vector<concrete_bit_range> uninit_bit_ranges;
7094 25 : if (!get_uninit_ranges (&uninit_bit_ranges))
7095 1 : return;
7096 :
7097 24 : std::unique_ptr<record_layout> layout;
7098 :
7099 24 : tree type = m_copied_sval->get_type ();
7100 24 : if (type && TREE_CODE (type) == RECORD_TYPE)
7101 : {
7102 19 : layout = std::make_unique<record_layout> (type);
7103 :
7104 19 : if (0)
7105 : layout->dump ();
7106 : }
7107 :
7108 51 : for (auto &bits : uninit_bit_ranges)
7109 : {
7110 27 : concrete_bit_offset start_bit = bits.get_start_offset ();
7111 27 : concrete_bit_offset next_bit = bits.get_next_offset ();
7112 27 : complain_about_uninit_range (loc, start_bit, next_bit,
7113 27 : layout.get ());
7114 27 : }
7115 25 : }
7116 :
7117 27 : void complain_about_uninit_range (location_t loc,
7118 : concrete_bit_offset start_bit,
7119 : concrete_bit_offset next_bit,
7120 : const record_layout *layout) const
7121 : {
7122 27 : if (layout)
7123 : {
7124 79 : while (start_bit < next_bit)
7125 : {
7126 171 : if (const record_layout::item *item
7127 57 : = layout->get_item_at (start_bit))
7128 : {
7129 57 : gcc_assert (start_bit >= item->get_start_offset ());
7130 57 : gcc_assert (start_bit < item->get_next_offset ());
7131 57 : if (item->get_start_offset () == start_bit
7132 167 : && item->get_next_offset () <= next_bit)
7133 55 : complain_about_fully_uninit_item (*item);
7134 : else
7135 2 : complain_about_partially_uninit_item (*item);
7136 57 : start_bit = item->get_next_offset ();
7137 57 : continue;
7138 : }
7139 : else
7140 : break;
7141 : }
7142 : }
7143 :
7144 27 : if (start_bit >= next_bit)
7145 22 : return;
7146 :
7147 5 : concrete_byte_offset start_byte;
7148 5 : concrete_byte_offset next_byte;
7149 10 : if (maybe_bytes_from_bits (start_bit, &start_byte)
7150 20 : && maybe_bytes_from_bits (next_bit, &next_byte))
7151 : {
7152 : /* Express in bytes. */
7153 5 : concrete_byte_offset last_byte = next_byte - 1_byte;
7154 5 : pp_element_integer e_start_byte (start_byte.get_integer ());
7155 5 : pp_element_integer e_last_byte (last_byte.get_integer ());
7156 5 : if (last_byte == start_byte)
7157 1 : inform (loc,
7158 : "byte %e is uninitialized",
7159 : &e_start_byte);
7160 : else
7161 4 : inform (loc,
7162 : "bytes %e - %e are uninitialized",
7163 : &e_start_byte, &e_last_byte);
7164 5 : }
7165 : else
7166 : {
7167 : /* Express in bits. */
7168 0 : concrete_bit_offset last_bit = next_bit - 1_bit;
7169 0 : pp_element_integer e_start_bit (start_bit.get_integer ());
7170 0 : pp_element_integer e_last_bit (last_bit.get_integer ());
7171 0 : if (last_bit == start_bit)
7172 0 : inform (loc,
7173 : "bit %e is uninitialized",
7174 : &e_start_bit);
7175 : else
7176 0 : inform (loc,
7177 : "bits %e - %e are uninitialized",
7178 : &e_start_bit, &e_last_bit);
7179 0 : }
7180 5 : }
7181 :
7182 : static void
7183 55 : complain_about_fully_uninit_item (const record_layout::item &item)
7184 : {
7185 55 : const_tree field = item.m_field;
7186 55 : concrete_bit_size num_bits = item.m_bit_range.get_size ();
7187 55 : if (item.m_is_padding)
7188 : {
7189 10 : concrete_byte_size num_bytes;
7190 10 : if (maybe_bytes_from_bits (num_bits, &num_bytes))
7191 : {
7192 : /* Express in bytes. */
7193 8 : if (num_bytes == 1_byte)
7194 2 : inform (DECL_SOURCE_LOCATION (field),
7195 : "padding after field %qD is uninitialized (1 byte)",
7196 : field);
7197 : else
7198 : {
7199 6 : pp_element_integer e_num_bytes (num_bytes.get_integer ());
7200 6 : inform (DECL_SOURCE_LOCATION (field),
7201 : "padding after field %qD is uninitialized (%e bytes)",
7202 : field, &e_num_bytes);
7203 6 : }
7204 : }
7205 : else
7206 : {
7207 : /* Express in bits. */
7208 2 : if (num_bits == 1_bit)
7209 0 : inform (DECL_SOURCE_LOCATION (field),
7210 : "padding after field %qD is uninitialized (1 bit)",
7211 : field);
7212 : else
7213 : {
7214 2 : pp_element_integer e_num_bits (num_bits.get_integer ());
7215 2 : inform (DECL_SOURCE_LOCATION (field),
7216 : "padding after field %qD is uninitialized (%e bits)",
7217 : field, &e_num_bits);
7218 2 : }
7219 : }
7220 10 : }
7221 : else
7222 : {
7223 45 : concrete_byte_size num_bytes;
7224 45 : if (maybe_bytes_from_bits (num_bits, &num_bytes))
7225 : {
7226 : /* Express in bytes. */
7227 35 : if (num_bytes == 1_byte)
7228 1 : inform (DECL_SOURCE_LOCATION (field),
7229 : "field %qD is uninitialized (1 byte)", field);
7230 : else
7231 : {
7232 34 : pp_element_integer e_num_bytes (num_bytes.get_integer ());
7233 34 : inform (DECL_SOURCE_LOCATION (field),
7234 : "field %qD is uninitialized (%e bytes)",
7235 : field, &e_num_bytes);
7236 34 : }
7237 : }
7238 : else
7239 : {
7240 : /* Express in bits. */
7241 10 : if (num_bits == 1_bit)
7242 9 : inform (DECL_SOURCE_LOCATION (field),
7243 : "field %qD is uninitialized (1 bit)", field);
7244 : else
7245 : {
7246 1 : pp_element_integer e_num_bits (num_bits.get_integer ());
7247 1 : inform (DECL_SOURCE_LOCATION (field),
7248 : "field %qD is uninitialized (%e bits)",
7249 : field, &e_num_bits);
7250 1 : }
7251 : }
7252 45 : }
7253 55 : }
7254 :
7255 : static void
7256 2 : complain_about_partially_uninit_item (const record_layout::item &item)
7257 : {
7258 2 : const_tree field = item.m_field;
7259 2 : if (item.m_is_padding)
7260 0 : inform (DECL_SOURCE_LOCATION (field),
7261 : "padding after field %qD is partially uninitialized",
7262 : field);
7263 : else
7264 2 : inform (DECL_SOURCE_LOCATION (field),
7265 : "field %qD is partially uninitialized",
7266 : field);
7267 : /* TODO: ideally we'd describe what parts are uninitialized. */
7268 2 : }
7269 :
7270 24 : void maybe_emit_fixit_hint () const
7271 : {
7272 24 : if (tree decl = m_src_region->maybe_get_decl ())
7273 : {
7274 24 : gcc_rich_location hint_richloc (DECL_SOURCE_LOCATION (decl));
7275 24 : hint_richloc.add_fixit_insert_after (" = {0}");
7276 24 : inform (&hint_richloc,
7277 : "suggest forcing zero-initialization by"
7278 : " providing a %<{0}%> initializer");
7279 24 : }
7280 24 : }
7281 :
7282 : private:
7283 : const region *m_src_region;
7284 : const region *m_dest_region;
7285 : const svalue *m_copied_sval;
7286 : symbolic::node_manager &m_node_mgr;
7287 : };
7288 :
7289 : /* Return true if any part of SVAL is uninitialized. */
7290 :
7291 : static bool
7292 78 : contains_uninit_p (const svalue *sval)
7293 : {
7294 78 : poison_finder v;
7295 78 : sval->accept_node_visitor (v);
7296 78 : if (!v.m_found_poison)
7297 : return false;
7298 26 : return v.m_pkind == poison_kind::uninit;
7299 78 : }
7300 :
7301 : /* Function for use by plugins when simulating writing data through a
7302 : pointer to an "untrusted" region DST_REG (and thus crossing a security
7303 : boundary), such as copying data to user space in an OS kernel.
7304 :
7305 : Check that COPIED_SVAL is fully initialized. If not, complain about
7306 : an infoleak to CTXT.
7307 :
7308 : SRC_REG can be nullptr; if non-NULL it is used as a hint in the diagnostic
7309 : as to where COPIED_SVAL came from. */
7310 :
7311 : void
7312 78 : region_model::maybe_complain_about_infoleak (const region *dst_reg,
7313 : const svalue *copied_sval,
7314 : const region *src_reg,
7315 : region_model_context *ctxt)
7316 : {
7317 : /* Check for exposure. */
7318 78 : if (contains_uninit_p (copied_sval))
7319 : {
7320 26 : auto &node_mgr = get_manager ()->get_node_manager ();
7321 26 : ctxt->warn
7322 26 : (std::make_unique<exposure_through_uninit_copy> (src_reg,
7323 : dst_reg,
7324 : copied_sval,
7325 : node_mgr));
7326 : }
7327 78 : }
7328 :
7329 : /* Set errno to a positive symbolic int, as if some error has occurred. */
7330 :
7331 : void
7332 439 : region_model::set_errno (const call_details &cd)
7333 : {
7334 439 : const region *errno_reg = m_mgr->get_errno_region ();
7335 439 : conjured_purge p (this, cd.get_ctxt ());
7336 439 : const svalue *new_errno_sval
7337 439 : = m_mgr->get_or_create_conjured_svalue (integer_type_node,
7338 439 : &cd.get_call_stmt (),
7339 : errno_reg, p);
7340 439 : const svalue *zero
7341 439 : = m_mgr->get_or_create_int_cst (integer_type_node, 0);
7342 439 : add_constraint (new_errno_sval, GT_EXPR, zero, cd.get_ctxt ());
7343 439 : set_value (errno_reg, new_errno_sval, cd.get_ctxt ());
7344 439 : }
7345 :
7346 : // class region_model_context
7347 :
7348 : bool
7349 4127 : region_model_context::
7350 : warn (std::unique_ptr<pending_diagnostic> d,
7351 : std::unique_ptr<pending_location::fixer_for_epath> ploc_fixer)
7352 : {
7353 4127 : pending_location ploc (get_pending_location_for_diag ());
7354 4127 : ploc.m_fixer_for_epath = std::move (ploc_fixer);
7355 4127 : return warn_at (std::move (d), std::move (ploc));
7356 4127 : }
7357 :
7358 : /* class noop_region_model_context : public region_model_context. */
7359 :
7360 : void
7361 0 : noop_region_model_context::add_note (std::unique_ptr<pending_note>)
7362 : {
7363 0 : }
7364 :
7365 : void
7366 0 : noop_region_model_context::add_event (std::unique_ptr<checker_event>)
7367 : {
7368 0 : }
7369 :
7370 : void
7371 75 : noop_region_model_context::bifurcate (std::unique_ptr<custom_edge_info>)
7372 : {
7373 75 : }
7374 :
7375 : void
7376 0 : noop_region_model_context::terminate_path ()
7377 : {
7378 0 : }
7379 :
7380 : /* class region_model_context_decorator : public region_model_context. */
7381 :
7382 : void
7383 187 : region_model_context_decorator::add_event (std::unique_ptr<checker_event> event)
7384 : {
7385 187 : if (m_inner)
7386 187 : m_inner->add_event (std::move (event));
7387 187 : }
7388 :
7389 : /* struct model_merger. */
7390 :
7391 : /* Return true if it's OK to merge SVAL with other svalues. */
7392 :
7393 : bool
7394 146759 : model_merger::mergeable_svalue_p (const svalue *sval) const
7395 : {
7396 146759 : if (m_ext_state)
7397 : {
7398 : /* Reject merging svalues that have non-purgeable sm-state,
7399 : to avoid falsely reporting memory leaks by merging them
7400 : with something else. For example, given a local var "p",
7401 : reject the merger of a:
7402 : store_a mapping "p" to a malloc-ed ptr
7403 : with:
7404 : store_b mapping "p" to a NULL ptr. */
7405 146671 : if (m_state_a)
7406 146671 : if (!m_state_a->can_purge_p (*m_ext_state, sval))
7407 : return false;
7408 144857 : if (m_state_b)
7409 144857 : if (!m_state_b->can_purge_p (*m_ext_state, sval))
7410 : return false;
7411 : }
7412 : return true;
7413 : }
7414 :
7415 : /* Return true if it's OK to merge BV with other bit vectors. */
7416 :
7417 : bool
7418 123191 : model_merger::mergeable_bit_vector_p (const symbolic::bit_vector &bv) const
7419 : {
7420 123191 : if (auto *from_sval = bv.dyn_cast_bit_vector_from_svalue ())
7421 54399 : return mergeable_svalue_p (&from_sval->get_svalue ());
7422 :
7423 : return true;
7424 : }
7425 :
7426 : /* Mark WIDENING_SVAL as changing meaning during the merge. */
7427 :
7428 : void
7429 919 : model_merger::on_widening_reuse (const widening_svalue *widening_sval)
7430 : {
7431 919 : m_svals_changing_meaning.add (widening_sval);
7432 919 : }
7433 :
7434 : } // namespace ana
7435 :
7436 : // class rejected_constraint
7437 :
7438 : std::unique_ptr<json::object>
7439 0 : rejected_constraint::make_base_json (const char *kind) const
7440 : {
7441 0 : auto obj = std::make_unique<json::object> ();
7442 0 : obj->set_string ("kind", kind);
7443 0 : obj->set<json::object> ("region_model", m_model.to_json ());
7444 0 : return obj;
7445 : }
7446 :
7447 : /* class rejected_op_constraint : public rejected_constraint. */
7448 :
7449 : void
7450 0 : rejected_op_constraint::dump_to_pp (pretty_printer *pp) const
7451 : {
7452 0 : region_model m (m_model);
7453 0 : m_lhs->dump_to_pp (pp, true);
7454 0 : pp_printf (pp, " %s ", op_symbol_code (m_op));
7455 0 : m_rhs->dump_to_pp (pp, true);
7456 0 : }
7457 :
7458 : std::unique_ptr<json::object>
7459 0 : rejected_op_constraint::to_json () const
7460 : {
7461 0 : auto obj = rejected_constraint::make_base_json ("rejected_op_constraint");
7462 0 : obj->set<json::value> ("lhs", m_lhs->to_json ());
7463 0 : obj->set_string ("op", op_symbol_code (m_op));
7464 0 : obj->set<json::value> ("rhs", m_rhs->to_json ());
7465 0 : return obj;
7466 : }
7467 :
7468 : /* class rejected_default_case : public rejected_constraint. */
7469 :
7470 : void
7471 0 : rejected_default_case::dump_to_pp (pretty_printer *pp) const
7472 : {
7473 0 : pp_string (pp, "implicit default for enum");
7474 0 : }
7475 :
7476 : std::unique_ptr<json::object>
7477 0 : rejected_default_case::to_json () const
7478 : {
7479 0 : return rejected_constraint::make_base_json ("rejected_default_case");
7480 : }
7481 :
7482 : /* class rejected_ranges_constraint : public rejected_constraint. */
7483 :
7484 : void
7485 0 : rejected_ranges_constraint::dump_to_pp (pretty_printer *pp) const
7486 : {
7487 0 : region_model m (m_model);
7488 0 : const svalue *sval = m.get_rvalue (m_expr, nullptr);
7489 0 : sval->dump_to_pp (pp, true);
7490 0 : pp_string (pp, " in ");
7491 0 : m_ranges->dump_to_pp (pp, true);
7492 0 : }
7493 :
7494 : std::unique_ptr<json::object>
7495 0 : rejected_ranges_constraint::to_json () const
7496 : {
7497 0 : auto obj = rejected_constraint::make_base_json ("rejected_ranges_constraint");
7498 0 : if (m_expr)
7499 0 : obj->set ("expr", tree_to_json (m_expr));
7500 0 : obj->set<json::value> ("ranges", m_ranges->to_json ());
7501 0 : return obj;
7502 : }
7503 :
7504 : /* class engine. */
7505 :
7506 : /* engine's ctor. */
7507 :
7508 3593 : engine::engine (symbolic::node_manager &node_mgr,
7509 : const supergraph *sg)
7510 3593 : : m_node_mgr (node_mgr),
7511 3593 : m_sg (sg)
7512 : {
7513 3593 : }
7514 :
7515 : /* Dump the managed objects by class to LOGGER, and the per-class totals. */
7516 :
7517 : void
7518 5 : engine::log_stats (logger *logger) const
7519 : {
7520 5 : m_node_mgr.log_stats (logger, true);
7521 5 : }
7522 :
7523 : namespace ana {
7524 :
7525 : #if CHECKING_P
7526 :
7527 : namespace selftest {
7528 :
7529 : /* Build a constant tree of the given type from STR. */
7530 :
7531 : static tree
7532 64 : build_real_cst_from_string (tree type, const char *str)
7533 : {
7534 64 : REAL_VALUE_TYPE real;
7535 64 : real_from_string (&real, str);
7536 64 : return build_real (type, real);
7537 : }
7538 :
7539 : /* Append various "interesting" constants to OUT (e.g. NaN). */
7540 :
7541 : static void
7542 8 : append_interesting_constants (auto_vec<tree> *out)
7543 : {
7544 8 : out->safe_push (integer_zero_node);
7545 8 : out->safe_push (build_int_cst (integer_type_node, 42));
7546 8 : out->safe_push (build_int_cst (unsigned_type_node, 0));
7547 8 : out->safe_push (build_int_cst (unsigned_type_node, 42));
7548 8 : out->safe_push (build_real_cst_from_string (float_type_node, "QNaN"));
7549 8 : out->safe_push (build_real_cst_from_string (float_type_node, "-QNaN"));
7550 8 : out->safe_push (build_real_cst_from_string (float_type_node, "SNaN"));
7551 8 : out->safe_push (build_real_cst_from_string (float_type_node, "-SNaN"));
7552 8 : out->safe_push (build_real_cst_from_string (float_type_node, "0.0"));
7553 8 : out->safe_push (build_real_cst_from_string (float_type_node, "-0.0"));
7554 8 : out->safe_push (build_real_cst_from_string (float_type_node, "Inf"));
7555 8 : out->safe_push (build_real_cst_from_string (float_type_node, "-Inf"));
7556 8 : }
7557 :
7558 : /* Verify that tree_cmp is a well-behaved comparator for qsort, even
7559 : if the underlying constants aren't comparable. */
7560 :
7561 : static void
7562 4 : test_tree_cmp_on_constants ()
7563 : {
7564 4 : auto_vec<tree> csts;
7565 4 : append_interesting_constants (&csts);
7566 :
7567 : /* Try sorting every triple. */
7568 4 : const unsigned num = csts.length ();
7569 52 : for (unsigned i = 0; i < num; i++)
7570 624 : for (unsigned j = 0; j < num; j++)
7571 7488 : for (unsigned k = 0; k < num; k++)
7572 : {
7573 6912 : auto_vec<tree> v (3);
7574 6912 : v.quick_push (csts[i]);
7575 6912 : v.quick_push (csts[j]);
7576 6912 : v.quick_push (csts[k]);
7577 6912 : v.qsort (tree_cmp);
7578 6912 : }
7579 4 : }
7580 :
7581 : /* Implementation detail of the ASSERT_CONDITION_* macros. */
7582 :
7583 : void
7584 8 : assert_condition (const location &loc,
7585 : region_model &model,
7586 : const svalue *lhs, tree_code op, const svalue *rhs,
7587 : tristate expected)
7588 : {
7589 8 : tristate actual = model.eval_condition (lhs, op, rhs);
7590 8 : ASSERT_EQ_AT (loc, actual, expected);
7591 8 : }
7592 :
7593 : /* Implementation detail of the ASSERT_CONDITION_* macros. */
7594 :
7595 : void
7596 3084 : assert_condition (const location &loc,
7597 : region_model &model,
7598 : tree lhs, tree_code op, tree rhs,
7599 : tristate expected)
7600 : {
7601 3084 : tristate actual = model.eval_condition (lhs, op, rhs, nullptr);
7602 3084 : ASSERT_EQ_AT (loc, actual, expected);
7603 3084 : }
7604 :
7605 : /* Implementation detail of ASSERT_DUMP_TREE_EQ. */
7606 :
7607 : static void
7608 24 : assert_dump_tree_eq (const location &loc, tree t, const char *expected)
7609 : {
7610 24 : auto_fix_quotes sentinel;
7611 24 : pretty_printer pp;
7612 24 : pp_format_decoder (&pp) = default_tree_printer;
7613 24 : dump_tree (&pp, t);
7614 24 : ASSERT_STREQ_AT (loc, pp_formatted_text (&pp), expected);
7615 24 : }
7616 :
7617 : /* Assert that dump_tree (T) is EXPECTED. */
7618 :
7619 : #define ASSERT_DUMP_TREE_EQ(T, EXPECTED) \
7620 : SELFTEST_BEGIN_STMT \
7621 : assert_dump_tree_eq ((SELFTEST_LOCATION), (T), (EXPECTED)); \
7622 : SELFTEST_END_STMT
7623 :
7624 : /* Smoketest for region_model::dump_to_pp. */
7625 :
7626 : static void
7627 4 : test_dump ()
7628 : {
7629 4 : symbolic::node_manager node_mgr;
7630 4 : region_model model (node_mgr);
7631 :
7632 4 : text_art::ascii_theme theme;
7633 4 : pretty_printer pp;
7634 4 : symbolic::dump_node_tree_to_pp<region_model> (model, &theme, &pp,
7635 : false, false);
7636 4 : ASSERT_STREQ ("Region Model\n"
7637 : "`- Store\n"
7638 : " `- m_called_unknown_fn: false\n",
7639 : pp_formatted_text (&pp));
7640 4 : }
7641 :
7642 : /* Verify usage of a struct. */
7643 :
7644 : static void
7645 4 : test_struct ()
7646 : {
7647 4 : coord_test ct;
7648 :
7649 4 : tree c = build_global_decl ("c", ct.m_coord_type);
7650 4 : tree c_x = build3 (COMPONENT_REF, TREE_TYPE (ct.m_x_field),
7651 : c, ct.m_x_field, NULL_TREE);
7652 4 : tree c_y = build3 (COMPONENT_REF, TREE_TYPE (ct.m_y_field),
7653 : c, ct.m_y_field, NULL_TREE);
7654 :
7655 4 : tree int_17 = build_int_cst (integer_type_node, 17);
7656 4 : tree int_m3 = build_int_cst (integer_type_node, -3);
7657 :
7658 4 : symbolic::node_manager node_mgr;
7659 4 : auto &mgr = node_mgr.get_region_model_manager ();
7660 4 : auto &bit_mgr = node_mgr.get_scalars ().get_bits ();
7661 4 : region_model model (node_mgr);
7662 : /* Set fields in order y, then x. */
7663 4 : model.set_value (c_y, int_m3, nullptr);
7664 4 : model.set_value (c_x, int_17, nullptr);
7665 :
7666 4 : const region *c_reg = model.get_lvalue (c, nullptr);
7667 :
7668 4 : diagnostics::markup::lowering_options opts;
7669 4 : ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*c_reg, opts, "c");
7670 :
7671 4 : auto int_size_bits = concrete_bit_size (INT_TYPE_SIZE);
7672 4 : auto int_size_bytes = concrete_byte_size (INT_TYPE_SIZE / BITS_PER_UNIT);
7673 :
7674 : /* Verify offsets/pointers for "c.x". */
7675 4 : {
7676 4 : const region *c_x_reg = model.get_lvalue (c_x, nullptr);
7677 :
7678 4 : ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*c_x_reg, opts, "c.x");
7679 :
7680 4 : ASSERT_SAME_SYMBOLIC_NODE
7681 : (c_x_reg->maybe_get_bit_offset_relative_to_parent (mgr),
7682 : &node_mgr.get_scalars ().get_bits ().get_concrete (0_bits));
7683 :
7684 4 : ASSERT_SAME_SYMBOLIC_NODE
7685 : (c_x_reg->maybe_get_byte_offset_relative_to_parent (mgr),
7686 : &node_mgr.get_scalars ().get_bytes ().get_concrete (0_bytes));
7687 :
7688 4 : auto sym_ptr = c_x_reg->get_pointer (mgr);
7689 4 : ASSERT_SAME_SYMBOLIC_NODE (sym_ptr.get_base_region (),
7690 : *c_reg);
7691 4 : ASSERT_SAME_SYMBOLIC_NODE
7692 : (sym_ptr.get_byte_offset (),
7693 : node_mgr.get_scalars ().get_bytes ().get_concrete (0_bytes));
7694 :
7695 8 : ASSERT_EQ (c_reg->get_pointer (mgr), c_x_reg->get_pointer (mgr));
7696 :
7697 4 : auto mem_range = c_x_reg->get_memory_range (mgr);
7698 4 : ASSERT_SAME_SYMBOLIC_NODE (mem_range.get_base_region (), *c_reg);
7699 16 : ASSERT_EQ
7700 : (mem_range.get_bit_range (),
7701 : symbolic_from_concrete (concrete_bit_range (0_bits, int_size_bits),
7702 : bit_mgr));
7703 4 : ASSERT_SAME_SYMBOLIC_NODE
7704 : (model.maybe_get_region_for_mem_range (mem_range, TREE_TYPE (c_x)),
7705 : c_x_reg);
7706 : }
7707 :
7708 : /* Verify offsets/pointers for "c.y". */
7709 4 : {
7710 4 : const region *c_y_reg = model.get_lvalue (c_y, nullptr);
7711 :
7712 4 : ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*c_y_reg, opts, "c.y");
7713 :
7714 4 : ASSERT_SAME_SYMBOLIC_NODE
7715 : (c_y_reg->maybe_get_bit_offset_relative_to_parent (mgr),
7716 : &node_mgr.get_scalars ().get_bits ().get_concrete (int_size_bits));
7717 :
7718 4 : ASSERT_SAME_SYMBOLIC_NODE
7719 : (c_y_reg->maybe_get_byte_offset_relative_to_parent (mgr),
7720 : &node_mgr.get_scalars ().get_bytes ().get_concrete (int_size_bytes));
7721 :
7722 4 : auto sym_ptr = c_y_reg->get_pointer (mgr);
7723 4 : ASSERT_SAME_SYMBOLIC_NODE (sym_ptr.get_base_region (),
7724 : *c_reg);
7725 4 : ASSERT_SAME_SYMBOLIC_NODE
7726 : (sym_ptr.get_byte_offset (),
7727 : node_mgr.get_scalars ().get_bytes ().get_concrete (int_size_bytes));
7728 :
7729 8 : ASSERT_NE (c_reg->get_pointer (mgr), c_y_reg->get_pointer (mgr));
7730 :
7731 4 : ASSERT_SAME_SYMBOLIC_NODE
7732 : (model.maybe_get_region_for_mem_range (c_y_reg->get_memory_range (mgr),
7733 : TREE_TYPE (c_x)),
7734 : c_y_reg);
7735 :
7736 4 : auto mem_range = c_y_reg->get_memory_range (mgr);
7737 4 : ASSERT_SAME_SYMBOLIC_NODE (mem_range.get_base_region (), *c_reg);
7738 16 : ASSERT_EQ
7739 : (mem_range.get_bit_range (),
7740 : symbolic_from_concrete (concrete_bit_range (int_size_bits,
7741 : int_size_bits),
7742 : bit_mgr));
7743 4 : ASSERT_SAME_SYMBOLIC_NODE
7744 : (model.maybe_get_region_for_mem_range (mem_range, TREE_TYPE (c_y)),
7745 : c_y_reg);
7746 : }
7747 4 : }
7748 :
7749 : /* Verify usage of an array element. */
7750 :
7751 : static void
7752 4 : test_array_1 ()
7753 : {
7754 4 : tree tlen = size_int (10);
7755 4 : tree arr_type = build_array_type (char_type_node, build_index_type (tlen));
7756 :
7757 4 : tree a = build_global_decl ("a", arr_type);
7758 :
7759 4 : symbolic::node_manager node_mgr;
7760 4 : region_model model (node_mgr);
7761 4 : tree int_0 = integer_zero_node;
7762 4 : tree a_0 = build4 (ARRAY_REF, char_type_node,
7763 : a, int_0, NULL_TREE, NULL_TREE);
7764 4 : tree char_A = build_int_cst (char_type_node, 'A');
7765 4 : model.set_value (a_0, char_A, nullptr);
7766 :
7767 4 : diagnostics::markup::lowering_options opts;
7768 4 : ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*model.get_lvalue (a_0, nullptr),
7769 : opts,
7770 : "a[0]");
7771 4 : }
7772 :
7773 : /* Verify that region_model::get_representative_tree works as expected. */
7774 :
7775 : static void
7776 4 : test_get_representative_tree ()
7777 : {
7778 4 : symbolic::node_manager node_mgr;
7779 :
7780 : /* STRING_CST. */
7781 4 : {
7782 4 : tree string_cst = build_string (4, "foo");
7783 4 : region_model m (node_mgr);
7784 4 : const svalue *str_sval = m.get_rvalue (string_cst, nullptr);
7785 4 : tree rep = m.get_representative_tree (str_sval);
7786 4 : ASSERT_EQ (rep, string_cst);
7787 4 : }
7788 :
7789 : /* String literal. */
7790 4 : {
7791 4 : tree string_cst_ptr = build_string_literal (4, "foo");
7792 4 : region_model m (node_mgr);
7793 4 : const svalue *str_sval = m.get_rvalue (string_cst_ptr, nullptr);
7794 4 : tree rep = m.get_representative_tree (str_sval);
7795 4 : ASSERT_DUMP_TREE_EQ (rep, "\"foo\"");
7796 4 : }
7797 :
7798 : /* Value of an element within an array. */
7799 4 : {
7800 4 : tree tlen = size_int (10);
7801 4 : tree arr_type = build_array_type (char_type_node, build_index_type (tlen));
7802 4 : tree a = build_global_decl ("a", arr_type);
7803 4 : placeholder_svalue test_sval (node_mgr.alloc_node_id (),
7804 4 : char_type_node, "test value");
7805 :
7806 : /* Value of a[3]. */
7807 4 : {
7808 4 : test_region_model_context ctxt;
7809 4 : region_model model (node_mgr);
7810 4 : tree int_3 = build_int_cst (integer_type_node, 3);
7811 4 : tree a_3 = build4 (ARRAY_REF, char_type_node,
7812 : a, int_3, NULL_TREE, NULL_TREE);
7813 4 : const region *a_3_reg = model.get_lvalue (a_3, &ctxt);
7814 4 : model.set_value (a_3_reg, &test_sval, &ctxt);
7815 4 : tree rep = model.get_representative_tree (&test_sval);
7816 4 : ASSERT_DUMP_TREE_EQ (rep, "a[3]");
7817 4 : }
7818 :
7819 : /* Value of a[0]. */
7820 4 : {
7821 4 : test_region_model_context ctxt;
7822 4 : region_model model (node_mgr);
7823 4 : tree idx = integer_zero_node;
7824 4 : tree a_0 = build4 (ARRAY_REF, char_type_node,
7825 : a, idx, NULL_TREE, NULL_TREE);
7826 4 : const region *a_0_reg = model.get_lvalue (a_0, &ctxt);
7827 4 : model.set_value (a_0_reg, &test_sval, &ctxt);
7828 4 : tree rep = model.get_representative_tree (&test_sval);
7829 4 : ASSERT_DUMP_TREE_EQ (rep, "a[0]");
7830 4 : }
7831 4 : }
7832 :
7833 : /* Value of a field within a struct. */
7834 4 : {
7835 4 : coord_test ct;
7836 :
7837 4 : tree c = build_global_decl ("c", ct.m_coord_type);
7838 4 : tree c_x = build3 (COMPONENT_REF, TREE_TYPE (ct.m_x_field),
7839 : c, ct.m_x_field, NULL_TREE);
7840 4 : tree c_y = build3 (COMPONENT_REF, TREE_TYPE (ct.m_y_field),
7841 : c, ct.m_y_field, NULL_TREE);
7842 :
7843 4 : test_region_model_context ctxt;
7844 :
7845 : /* Value of initial field. */
7846 4 : {
7847 4 : region_model m (node_mgr);
7848 4 : const region *c_x_reg = m.get_lvalue (c_x, &ctxt);
7849 4 : placeholder_svalue test_sval_x (node_mgr.alloc_node_id (),
7850 4 : integer_type_node, "test x val");
7851 4 : m.set_value (c_x_reg, &test_sval_x, &ctxt);
7852 4 : tree rep = m.get_representative_tree (&test_sval_x);
7853 4 : ASSERT_DUMP_TREE_EQ (rep, "c.x");
7854 4 : }
7855 :
7856 : /* Value of non-initial field. */
7857 4 : {
7858 4 : region_model m (node_mgr);
7859 4 : const region *c_y_reg = m.get_lvalue (c_y, &ctxt);
7860 4 : placeholder_svalue test_sval_y (node_mgr.alloc_node_id (),
7861 4 : integer_type_node, "test y val");
7862 4 : m.set_value (c_y_reg, &test_sval_y, &ctxt);
7863 4 : tree rep = m.get_representative_tree (&test_sval_y);
7864 4 : ASSERT_DUMP_TREE_EQ (rep, "c.y");
7865 4 : }
7866 4 : }
7867 :
7868 : /* Value of a single field within a struct,
7869 : so sizeof(field) == sizeof(struct).
7870 : */
7871 4 : {
7872 : /* Consider:
7873 : | struct foo {
7874 : | void *ptr;
7875 : | };
7876 : | c.ptr = VAL;
7877 : */
7878 4 : tree t_field_ptr = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
7879 : get_identifier ("ptr"), ptr_type_node);
7880 4 : tree t_struct_foo_type = make_test_compound_type ("foo", true, {t_field_ptr});
7881 4 : tree c = build_global_decl ("c", t_struct_foo_type);
7882 4 : tree c_ptr = build3 (COMPONENT_REF, TREE_TYPE (t_field_ptr),
7883 : c, t_field_ptr, NULL_TREE);
7884 :
7885 4 : test_region_model_context ctxt;
7886 :
7887 : /* Value of single field. */
7888 4 : region_model m (node_mgr);
7889 4 : const region *c_ptr_reg = m.get_lvalue (c_ptr, &ctxt);
7890 4 : placeholder_svalue test_val (node_mgr.alloc_node_id (),
7891 4 : ptr_type_node, "test val");
7892 4 : m.set_value (c_ptr_reg, &test_val, &ctxt);
7893 4 : tree rep = m.get_representative_tree (&test_val);
7894 4 : ASSERT_DUMP_TREE_EQ (rep, "c.ptr");
7895 4 : }
7896 4 : }
7897 :
7898 : /* Verify that calling region_model::get_rvalue repeatedly on the same
7899 : tree constant retrieves the same svalue *. */
7900 :
7901 : static void
7902 4 : test_unique_constants ()
7903 : {
7904 4 : tree int_0 = integer_zero_node;
7905 4 : tree int_42 = build_int_cst (integer_type_node, 42);
7906 :
7907 4 : test_region_model_context ctxt;
7908 4 : symbolic::node_manager node_mgr;
7909 4 : region_model model (node_mgr);
7910 4 : ASSERT_EQ (model.get_rvalue (int_0, &ctxt), model.get_rvalue (int_0, &ctxt));
7911 4 : ASSERT_EQ (model.get_rvalue (int_42, &ctxt),
7912 : model.get_rvalue (int_42, &ctxt));
7913 4 : ASSERT_NE (model.get_rvalue (int_0, &ctxt), model.get_rvalue (int_42, &ctxt));
7914 4 : ASSERT_EQ (ctxt.get_num_diagnostics (), 0);
7915 :
7916 4 : diagnostics::markup::lowering_options opts;
7917 4 : ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*model.get_rvalue (int_42, &ctxt),
7918 : opts,
7919 : "42");
7920 :
7921 : /* A "(const int)42" will be a different tree from "(int)42)"... */
7922 4 : tree const_int_type_node
7923 4 : = build_qualified_type (integer_type_node, TYPE_QUAL_CONST);
7924 4 : tree const_int_42 = build_int_cst (const_int_type_node, 42);
7925 4 : ASSERT_NE (int_42, const_int_42);
7926 : /* It should have a different const_svalue. */
7927 4 : const svalue *int_42_sval = model.get_rvalue (int_42, &ctxt);
7928 4 : const svalue *const_int_42_sval = model.get_rvalue (const_int_42, &ctxt);
7929 4 : ASSERT_NE (int_42_sval, const_int_42_sval);
7930 : /* But they should compare as equal. */
7931 4 : ASSERT_CONDITION_TRUE (model, int_42_sval, EQ_EXPR, const_int_42_sval);
7932 4 : ASSERT_CONDITION_FALSE (model, int_42_sval, NE_EXPR, const_int_42_sval);
7933 4 : }
7934 :
7935 : /* Verify that each type gets its own singleton unknown_svalue within a
7936 : region_model_manager, and that NULL_TREE gets its own singleton. */
7937 :
7938 : static void
7939 4 : test_unique_unknowns ()
7940 : {
7941 4 : symbolic::node_manager node_mgr;
7942 4 : auto &mgr = node_mgr.get_region_model_manager ();
7943 4 : const svalue *unknown_int
7944 4 : = mgr.get_or_create_unknown_svalue (integer_type_node);
7945 : /* Repeated calls with the same type should get the same "unknown"
7946 : svalue. */
7947 4 : const svalue *unknown_int_2
7948 4 : = mgr.get_or_create_unknown_svalue (integer_type_node);
7949 4 : ASSERT_EQ (unknown_int, unknown_int_2);
7950 :
7951 : /* Different types (or the NULL type) should have different
7952 : unknown_svalues. */
7953 4 : const svalue *unknown_NULL_type = mgr.get_or_create_unknown_svalue (nullptr);
7954 4 : ASSERT_NE (unknown_NULL_type, unknown_int);
7955 :
7956 : /* Repeated calls with NULL for the type should get the same "unknown"
7957 : svalue. */
7958 4 : const svalue *unknown_NULL_type_2 = mgr.get_or_create_unknown_svalue (nullptr);
7959 4 : ASSERT_EQ (unknown_NULL_type, unknown_NULL_type_2);
7960 :
7961 4 : diagnostics::markup::lowering_options opts;
7962 4 : ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*unknown_int, opts, "unknown");
7963 4 : }
7964 :
7965 : /* Verify that initial_svalue are handled as expected. */
7966 :
7967 : static void
7968 4 : test_initial_svalue_folding ()
7969 : {
7970 4 : symbolic::node_manager node_mgr;
7971 4 : auto &mgr = node_mgr.get_region_model_manager ();
7972 4 : tree x = build_global_decl ("x", integer_type_node);
7973 4 : tree y = build_global_decl ("y", integer_type_node);
7974 :
7975 4 : test_region_model_context ctxt;
7976 4 : region_model model (node_mgr);
7977 4 : const svalue *x_init = model.get_rvalue (x, &ctxt);
7978 4 : const svalue *y_init = model.get_rvalue (y, &ctxt);
7979 4 : ASSERT_NE (x_init, y_init);
7980 4 : const region *x_reg = model.get_lvalue (x, &ctxt);
7981 4 : ASSERT_SAME_SYMBOLIC_NODE (x_init,
7982 : mgr.get_or_create_initial_value (x_reg));
7983 :
7984 4 : diagnostics::markup::lowering_options opts;
7985 4 : ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*x_init, opts, "x");
7986 4 : }
7987 :
7988 : /* Verify that unary ops are folded as expected. */
7989 :
7990 : static void
7991 4 : test_unaryop_svalue_folding ()
7992 : {
7993 4 : symbolic::node_manager node_mgr;
7994 4 : auto &mgr = node_mgr.get_region_model_manager ();
7995 :
7996 4 : tree x = build_global_decl ("x", integer_type_node);
7997 4 : tree y = build_global_decl ("y", integer_type_node);
7998 :
7999 4 : test_region_model_context ctxt;
8000 4 : region_model model (node_mgr);
8001 4 : const svalue *x_init = model.get_rvalue (x, &ctxt);
8002 4 : const svalue *y_init = model.get_rvalue (y, &ctxt);
8003 4 : const region *x_reg = model.get_lvalue (x, &ctxt);
8004 4 : ASSERT_SAME_SYMBOLIC_NODE (x_init,
8005 : mgr.get_or_create_initial_value (x_reg));
8006 :
8007 : /* "(int)x" -> "x". */
8008 4 : ASSERT_EQ (x_init, mgr.get_or_create_cast (integer_type_node, x_init));
8009 :
8010 : /* "(void *)x" -> something other than "x". */
8011 4 : ASSERT_NE (x_init, mgr.get_or_create_cast (ptr_type_node, x_init));
8012 :
8013 : /* "!(x == y)" -> "x != y". */
8014 4 : ASSERT_EQ (mgr.get_or_create_unaryop
8015 : (boolean_type_node, TRUTH_NOT_EXPR,
8016 : mgr.get_or_create_binop (boolean_type_node, EQ_EXPR,
8017 : x_init, y_init)),
8018 : mgr.get_or_create_binop (boolean_type_node, NE_EXPR,
8019 : x_init, y_init));
8020 : /* "!(x > y)" -> "x <= y". */
8021 4 : ASSERT_EQ (mgr.get_or_create_unaryop
8022 : (boolean_type_node, TRUTH_NOT_EXPR,
8023 : mgr.get_or_create_binop (boolean_type_node, GT_EXPR,
8024 : x_init, y_init)),
8025 : mgr.get_or_create_binop (boolean_type_node, LE_EXPR,
8026 : x_init, y_init));
8027 4 : }
8028 :
8029 : /* Verify that binops on constant svalues are folded. */
8030 :
8031 : static void
8032 4 : test_binop_svalue_folding ()
8033 : {
8034 : #define NUM_CSTS 10
8035 4 : tree cst_int[NUM_CSTS];
8036 4 : symbolic::node_manager node_mgr;
8037 4 : auto &mgr = node_mgr.get_region_model_manager ();
8038 4 : const svalue *cst_sval[NUM_CSTS];
8039 44 : for (int i = 0; i < NUM_CSTS; i++)
8040 : {
8041 40 : cst_int[i] = build_int_cst (integer_type_node, i);
8042 40 : cst_sval[i] = mgr.get_or_create_constant_svalue (cst_int[i]);
8043 40 : ASSERT_EQ (cst_sval[i]->get_kind (), SK_CONSTANT);
8044 40 : ASSERT_EQ (cst_sval[i]->maybe_get_constant (), cst_int[i]);
8045 : }
8046 :
8047 44 : for (int i = 0; i < NUM_CSTS; i++)
8048 440 : for (int j = 0; j < NUM_CSTS; j++)
8049 : {
8050 400 : if (i != j)
8051 360 : ASSERT_NE (cst_sval[i], cst_sval[j]);
8052 400 : if (i + j < NUM_CSTS)
8053 : {
8054 220 : const svalue *sum
8055 220 : = mgr.get_or_create_binop (integer_type_node, PLUS_EXPR,
8056 : cst_sval[i], cst_sval[j]);
8057 220 : ASSERT_EQ (sum, cst_sval[i + j]);
8058 : }
8059 400 : if (i - j >= 0)
8060 : {
8061 220 : const svalue *difference
8062 220 : = mgr.get_or_create_binop (integer_type_node, MINUS_EXPR,
8063 : cst_sval[i], cst_sval[j]);
8064 220 : ASSERT_EQ (difference, cst_sval[i - j]);
8065 : }
8066 400 : if (i * j < NUM_CSTS)
8067 : {
8068 168 : const svalue *product
8069 168 : = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
8070 : cst_sval[i], cst_sval[j]);
8071 168 : ASSERT_EQ (product, cst_sval[i * j]);
8072 : }
8073 400 : const svalue *eq = mgr.get_or_create_binop (integer_type_node, EQ_EXPR,
8074 : cst_sval[i], cst_sval[j]);
8075 400 : ASSERT_EQ (eq, i == j ? cst_sval[1] : cst_sval [0]);
8076 400 : const svalue *neq = mgr.get_or_create_binop (integer_type_node, NE_EXPR,
8077 : cst_sval[i], cst_sval[j]);
8078 400 : ASSERT_EQ (neq, i != j ? cst_sval[1] : cst_sval [0]);
8079 : // etc
8080 : }
8081 :
8082 4 : tree x = build_global_decl ("x", integer_type_node);
8083 :
8084 4 : test_region_model_context ctxt;
8085 4 : region_model model (node_mgr);
8086 4 : const svalue *x_init = model.get_rvalue (x, &ctxt);
8087 :
8088 : /* PLUS_EXPR folding. */
8089 4 : const svalue *x_init_plus_zero
8090 4 : = mgr.get_or_create_binop (integer_type_node, PLUS_EXPR,
8091 : x_init, cst_sval[0]);
8092 4 : ASSERT_EQ (x_init_plus_zero, x_init);
8093 4 : const svalue *zero_plus_x_init
8094 4 : = mgr.get_or_create_binop (integer_type_node, PLUS_EXPR,
8095 : cst_sval[0], x_init);
8096 4 : ASSERT_EQ (zero_plus_x_init, x_init);
8097 :
8098 : /* MULT_EXPR folding. */
8099 4 : const svalue *x_init_times_zero
8100 4 : = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
8101 : x_init, cst_sval[0]);
8102 4 : ASSERT_EQ (x_init_times_zero, cst_sval[0]);
8103 4 : const svalue *zero_times_x_init
8104 4 : = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
8105 : cst_sval[0], x_init);
8106 4 : ASSERT_EQ (zero_times_x_init, cst_sval[0]);
8107 :
8108 4 : const svalue *x_init_times_one
8109 4 : = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
8110 : x_init, cst_sval[1]);
8111 4 : ASSERT_EQ (x_init_times_one, x_init);
8112 4 : const svalue *one_times_x_init
8113 4 : = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
8114 : cst_sval[1], x_init);
8115 4 : ASSERT_EQ (one_times_x_init, x_init);
8116 :
8117 : // etc
8118 : // TODO: do we want to use the match-and-simplify DSL for this?
8119 :
8120 : /* Verify that binops put any constants on the RHS. */
8121 4 : const svalue *four_times_x_init
8122 4 : = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
8123 : cst_sval[4], x_init);
8124 4 : const svalue *x_init_times_four
8125 4 : = mgr.get_or_create_binop (integer_type_node, MULT_EXPR,
8126 : x_init, cst_sval[4]);
8127 4 : ASSERT_EQ (four_times_x_init, x_init_times_four);
8128 4 : const binop_svalue *binop = four_times_x_init->dyn_cast_binop_svalue ();
8129 4 : ASSERT_EQ (binop->get_op (), MULT_EXPR);
8130 4 : ASSERT_EQ (binop->get_arg0 (), x_init);
8131 4 : ASSERT_EQ (binop->get_arg1 (), cst_sval[4]);
8132 :
8133 : /* Verify that ((x + 1) + 1) == (x + 2). */
8134 4 : const svalue *x_init_plus_one
8135 4 : = mgr.get_or_create_binop (integer_type_node, PLUS_EXPR,
8136 : x_init, cst_sval[1]);
8137 4 : const svalue *x_init_plus_two
8138 4 : = mgr.get_or_create_binop (integer_type_node, PLUS_EXPR,
8139 : x_init, cst_sval[2]);
8140 4 : const svalue *x_init_plus_one_plus_one
8141 4 : = mgr.get_or_create_binop (integer_type_node, PLUS_EXPR,
8142 : x_init_plus_one, cst_sval[1]);
8143 4 : ASSERT_EQ (x_init_plus_one_plus_one, x_init_plus_two);
8144 :
8145 4 : diagnostics::markup::lowering_options opts;
8146 4 : ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*x_init_plus_one, opts, "x + 1");
8147 :
8148 : /* Verify various binops on booleans. */
8149 4 : {
8150 4 : const svalue *sval_true = mgr.get_or_create_int_cst (boolean_type_node, 1);
8151 4 : const svalue *sval_false = mgr.get_or_create_int_cst (boolean_type_node, 0);
8152 4 : const svalue *sval_unknown
8153 4 : = mgr.get_or_create_unknown_svalue (boolean_type_node);
8154 4 : const placeholder_svalue sval_placeholder (mgr.alloc_node_id (),
8155 4 : boolean_type_node, "v");
8156 12 : for (auto op : {BIT_IOR_EXPR, TRUTH_OR_EXPR})
8157 : {
8158 8 : ASSERT_EQ (mgr.get_or_create_binop (boolean_type_node, op,
8159 : sval_true, sval_unknown),
8160 : sval_true);
8161 8 : ASSERT_EQ (mgr.get_or_create_binop (boolean_type_node, op,
8162 : sval_false, sval_unknown),
8163 : sval_unknown);
8164 8 : ASSERT_EQ (mgr.get_or_create_binop (boolean_type_node, op,
8165 : sval_false, &sval_placeholder),
8166 : &sval_placeholder);
8167 : }
8168 12 : for (auto op : {BIT_AND_EXPR, TRUTH_AND_EXPR})
8169 : {
8170 8 : ASSERT_SAME_SYMBOLIC_NODE
8171 : (mgr.get_or_create_binop (boolean_type_node, op,
8172 : sval_false, sval_unknown),
8173 : sval_false);
8174 8 : ASSERT_SAME_SYMBOLIC_NODE
8175 : (mgr.get_or_create_binop (boolean_type_node, op,
8176 : sval_true, sval_unknown),
8177 : sval_unknown);
8178 : }
8179 4 : }
8180 4 : }
8181 :
8182 : /* Test that region::descendent_of_p works as expected. */
8183 :
8184 : static void
8185 4 : test_descendent_of_p ()
8186 : {
8187 4 : symbolic::node_manager node_mgr;
8188 4 : auto &mgr = node_mgr.get_region_model_manager ();
8189 4 : const region *stack = mgr.get_stack_region ();
8190 4 : const region *heap = mgr.get_heap_region ();
8191 4 : const region *code = mgr.get_code_region ();
8192 4 : const region *globals = mgr.get_globals_region ();
8193 :
8194 : /* descendent_of_p should return true when used on the region itself. */
8195 4 : ASSERT_TRUE (stack->descendent_of_p (stack));
8196 4 : ASSERT_FALSE (stack->descendent_of_p (heap));
8197 4 : ASSERT_FALSE (stack->descendent_of_p (code));
8198 4 : ASSERT_FALSE (stack->descendent_of_p (globals));
8199 :
8200 4 : tree x = build_global_decl ("x", integer_type_node);
8201 4 : const region *x_reg = mgr.get_region_for_global (x);
8202 4 : ASSERT_TRUE (x_reg->descendent_of_p (globals));
8203 :
8204 : /* A cast_region should be a descendent of the original region. */
8205 4 : const region *cast_reg = mgr.get_cast_region (x_reg, ptr_type_node);
8206 4 : ASSERT_TRUE (cast_reg->descendent_of_p (x_reg));
8207 4 : }
8208 :
8209 : /* Verify that bit_range_region works as expected. */
8210 :
8211 : static void
8212 4 : test_bit_range_regions ()
8213 : {
8214 4 : tree x = build_global_decl ("x", integer_type_node);
8215 4 : symbolic::node_manager node_mgr;
8216 4 : auto &mgr = node_mgr.get_region_model_manager ();
8217 4 : const region *x_reg = mgr.get_region_for_global (x);
8218 4 : const region *byte0
8219 4 : = mgr.get_bit_range (x_reg, char_type_node,
8220 12 : concrete_bit_range (0_bits, 8_bits));
8221 4 : const region *byte1
8222 4 : = mgr.get_bit_range (x_reg, char_type_node,
8223 12 : concrete_bit_range (8_bits, 8_bits));
8224 4 : ASSERT_TRUE (byte0->descendent_of_p (x_reg));
8225 4 : ASSERT_TRUE (byte1->descendent_of_p (x_reg));
8226 4 : ASSERT_NE (byte0, byte1);
8227 :
8228 4 : diagnostics::markup::lowering_options opts;
8229 4 : ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*byte1, opts,
8230 : "bit_range_region (x, bits=[8, 16))");
8231 4 : }
8232 :
8233 : /* Verify that simple assignments work as expected. */
8234 :
8235 : static void
8236 4 : test_assignment ()
8237 : {
8238 4 : tree int_0 = integer_zero_node;
8239 4 : tree x = build_global_decl ("x", integer_type_node);
8240 4 : tree y = build_global_decl ("y", integer_type_node);
8241 :
8242 : /* "x == 0", then use of y, then "y = 0;". */
8243 4 : symbolic::node_manager node_mgr;
8244 4 : region_model model (node_mgr);
8245 4 : ADD_SAT_CONSTRAINT (model, x, EQ_EXPR, int_0);
8246 4 : ASSERT_CONDITION_UNKNOWN (model, y, EQ_EXPR, int_0);
8247 4 : model.set_value (model.get_lvalue (y, nullptr),
8248 : model.get_rvalue (int_0, nullptr),
8249 : nullptr);
8250 4 : ASSERT_CONDITION_TRUE (model, y, EQ_EXPR, int_0);
8251 4 : ASSERT_CONDITION_TRUE (model, y, EQ_EXPR, x);
8252 4 : }
8253 :
8254 : /* Verify that compound assignments work as expected. */
8255 :
8256 : static void
8257 4 : test_compound_assignment ()
8258 : {
8259 4 : coord_test ct;
8260 :
8261 4 : tree c = build_global_decl ("c", ct.m_coord_type);
8262 4 : tree c_x = build3 (COMPONENT_REF, TREE_TYPE (ct.m_x_field),
8263 : c, ct.m_x_field, NULL_TREE);
8264 4 : tree c_y = build3 (COMPONENT_REF, TREE_TYPE (ct.m_y_field),
8265 : c, ct.m_y_field, NULL_TREE);
8266 4 : tree d = build_global_decl ("d", ct.m_coord_type);
8267 4 : tree d_x = build3 (COMPONENT_REF, TREE_TYPE (ct.m_x_field),
8268 : d, ct.m_x_field, NULL_TREE);
8269 4 : tree d_y = build3 (COMPONENT_REF, TREE_TYPE (ct.m_y_field),
8270 : d, ct.m_y_field, NULL_TREE);
8271 :
8272 4 : tree int_17 = build_int_cst (integer_type_node, 17);
8273 4 : tree int_m3 = build_int_cst (integer_type_node, -3);
8274 :
8275 4 : symbolic::node_manager node_mgr;
8276 4 : region_model model (node_mgr);
8277 4 : model.set_value (c_x, int_17, nullptr);
8278 4 : model.set_value (c_y, int_m3, nullptr);
8279 :
8280 : /* Copy c to d. */
8281 4 : const svalue *sval = model.get_rvalue (c, nullptr);
8282 4 : model.set_value (model.get_lvalue (d, nullptr), sval, nullptr);
8283 :
8284 : /* Check that the fields have the same svalues. */
8285 4 : ASSERT_EQ (model.get_rvalue (c_x, nullptr), model.get_rvalue (d_x, nullptr));
8286 4 : ASSERT_EQ (model.get_rvalue (c_y, nullptr), model.get_rvalue (d_y, nullptr));
8287 4 : }
8288 :
8289 : /* Verify the details of pushing and popping stack frames. */
8290 :
8291 : static void
8292 4 : test_stack_frames ()
8293 : {
8294 4 : tree int_42 = build_int_cst (integer_type_node, 42);
8295 4 : tree int_10 = build_int_cst (integer_type_node, 10);
8296 4 : tree int_5 = build_int_cst (integer_type_node, 5);
8297 4 : tree int_0 = integer_zero_node;
8298 :
8299 4 : auto_vec <tree> param_types;
8300 4 : tree parent_fndecl = make_fndecl (integer_type_node,
8301 : "parent_fn",
8302 : param_types);
8303 4 : allocate_struct_function (parent_fndecl, true);
8304 :
8305 4 : tree child_fndecl = make_fndecl (integer_type_node,
8306 : "child_fn",
8307 : param_types);
8308 4 : allocate_struct_function (child_fndecl, true);
8309 :
8310 : /* "a" and "b" in the parent frame. */
8311 4 : tree a = build_decl (UNKNOWN_LOCATION, PARM_DECL,
8312 : get_identifier ("a"),
8313 : integer_type_node);
8314 4 : DECL_CONTEXT (a) = parent_fndecl;
8315 4 : tree b = build_decl (UNKNOWN_LOCATION, PARM_DECL,
8316 : get_identifier ("b"),
8317 : integer_type_node);
8318 4 : DECL_CONTEXT (b) = parent_fndecl;
8319 : /* "x" and "y" in a child frame. */
8320 4 : tree x = build_decl (UNKNOWN_LOCATION, PARM_DECL,
8321 : get_identifier ("x"),
8322 : integer_type_node);
8323 4 : DECL_CONTEXT (x) = child_fndecl;
8324 4 : tree y = build_decl (UNKNOWN_LOCATION, PARM_DECL,
8325 : get_identifier ("y"),
8326 : integer_type_node);
8327 4 : DECL_CONTEXT (y) = child_fndecl;
8328 :
8329 : /* "p" global. */
8330 4 : tree p = build_global_decl ("p", ptr_type_node);
8331 :
8332 : /* "q" global. */
8333 4 : tree q = build_global_decl ("q", ptr_type_node);
8334 :
8335 4 : symbolic::node_manager node_mgr;
8336 4 : auto &mgr = node_mgr.get_region_model_manager ();
8337 4 : test_region_model_context ctxt;
8338 4 : region_model model (node_mgr);
8339 :
8340 : /* Push stack frame for "parent_fn". */
8341 4 : const region *parent_frame_reg
8342 4 : = model.push_frame (*DECL_STRUCT_FUNCTION (parent_fndecl),
8343 : nullptr, nullptr, &ctxt);
8344 4 : ASSERT_EQ (model.get_current_frame (), parent_frame_reg);
8345 4 : ASSERT_TRUE (model.region_exists_p (parent_frame_reg));
8346 4 : const region *a_in_parent_reg = model.get_lvalue (a, &ctxt);
8347 4 : model.set_value (a_in_parent_reg,
8348 : model.get_rvalue (int_42, &ctxt),
8349 : &ctxt);
8350 4 : ASSERT_EQ (a_in_parent_reg->maybe_get_frame_region (), parent_frame_reg);
8351 :
8352 4 : model.add_constraint (b, LT_EXPR, int_10, &ctxt);
8353 4 : ASSERT_EQ (model.eval_condition (b, LT_EXPR, int_10, &ctxt),
8354 : tristate (tristate::TS_TRUE));
8355 :
8356 : /* Push stack frame for "child_fn". */
8357 4 : const region *child_frame_reg
8358 4 : = model.push_frame (*DECL_STRUCT_FUNCTION (child_fndecl),
8359 : nullptr, nullptr, &ctxt);
8360 4 : ASSERT_EQ (model.get_current_frame (), child_frame_reg);
8361 4 : ASSERT_TRUE (model.region_exists_p (child_frame_reg));
8362 4 : const region *x_in_child_reg = model.get_lvalue (x, &ctxt);
8363 4 : model.set_value (x_in_child_reg,
8364 : model.get_rvalue (int_0, &ctxt),
8365 : &ctxt);
8366 4 : ASSERT_EQ (x_in_child_reg->maybe_get_frame_region (), child_frame_reg);
8367 :
8368 4 : model.add_constraint (y, NE_EXPR, int_5, &ctxt);
8369 4 : ASSERT_EQ (model.eval_condition (y, NE_EXPR, int_5, &ctxt),
8370 : tristate (tristate::TS_TRUE));
8371 :
8372 : /* Point a global pointer at a local in the child frame: p = &x. */
8373 4 : const region *p_in_globals_reg = model.get_lvalue (p, &ctxt);
8374 4 : model.set_value (p_in_globals_reg,
8375 : mgr.get_ptr_svalue (ptr_type_node, x_in_child_reg),
8376 : &ctxt);
8377 4 : ASSERT_EQ (p_in_globals_reg->maybe_get_frame_region (), nullptr);
8378 :
8379 : /* Point another global pointer at p: q = &p. */
8380 4 : const region *q_in_globals_reg = model.get_lvalue (q, &ctxt);
8381 4 : model.set_value (q_in_globals_reg,
8382 : mgr.get_ptr_svalue (ptr_type_node, p_in_globals_reg),
8383 : &ctxt);
8384 :
8385 : /* Test region::descendent_of_p. */
8386 4 : ASSERT_TRUE (child_frame_reg->descendent_of_p (child_frame_reg));
8387 4 : ASSERT_TRUE (x_in_child_reg->descendent_of_p (child_frame_reg));
8388 4 : ASSERT_FALSE (a_in_parent_reg->descendent_of_p (child_frame_reg));
8389 :
8390 : /* Pop the "child_fn" frame from the stack. */
8391 4 : model.pop_frame (nullptr, nullptr, &ctxt, nullptr);
8392 4 : ASSERT_FALSE (model.region_exists_p (child_frame_reg));
8393 4 : ASSERT_TRUE (model.region_exists_p (parent_frame_reg));
8394 :
8395 : /* Verify that p (which was pointing at the local "x" in the popped
8396 : frame) has been poisoned. */
8397 4 : const svalue *new_p_sval = model.get_rvalue (p, nullptr);
8398 4 : ASSERT_EQ (new_p_sval->get_kind (), SK_BIT_VECTOR);
8399 4 : auto &new_p_bv
8400 4 : = new_p_sval->dyn_cast_svalue_from_bit_vector ()->get_bit_vector ();
8401 4 : ASSERT_EQ (new_p_bv.get_kind (), symbolic::bit_vector::kind::poisoned);
8402 4 : ASSERT_EQ (new_p_bv.dyn_cast_poisoned_bit_vector ()->get_poison_kind (),
8403 : poison_kind::popped_stack);
8404 :
8405 : /* Verify that q still points to p, in spite of the region
8406 : renumbering. */
8407 4 : const svalue *new_q_sval = model.get_rvalue (q, &ctxt);
8408 4 : ASSERT_EQ (new_q_sval->get_kind (), SK_POINTER);
8409 4 : ASSERT_SAME_SYMBOLIC_NODE
8410 : (new_q_sval->maybe_get_symbolic_pointer ()->get_base_region (),
8411 : *model.get_lvalue (p, &ctxt));
8412 :
8413 : /* Verify that top of stack has been updated. */
8414 4 : ASSERT_EQ (model.get_current_frame (), parent_frame_reg);
8415 :
8416 : /* Verify locals in parent frame. */
8417 : /* Verify "a" still has its value. */
8418 4 : const svalue *new_a_sval = model.get_rvalue (a, &ctxt);
8419 4 : ASSERT_EQ (new_a_sval->get_kind (), SK_CONSTANT);
8420 4 : ASSERT_EQ (new_a_sval->dyn_cast_constant_svalue ()->get_constant (),
8421 : int_42);
8422 : /* Verify "b" still has its constraint. */
8423 4 : ASSERT_EQ (model.eval_condition (b, LT_EXPR, int_10, &ctxt),
8424 : tristate (tristate::TS_TRUE));
8425 4 : }
8426 :
8427 : /* Verify that get_representative_path_var works as expected, that
8428 : we can map from regions to parms and back within a recursive call
8429 : stack. */
8430 :
8431 : static void
8432 4 : test_get_representative_path_var ()
8433 : {
8434 4 : auto_vec <tree> param_types;
8435 4 : tree fndecl = make_fndecl (integer_type_node,
8436 : "factorial",
8437 : param_types);
8438 4 : allocate_struct_function (fndecl, true);
8439 :
8440 : /* Parm "n". */
8441 4 : tree n = build_decl (UNKNOWN_LOCATION, PARM_DECL,
8442 : get_identifier ("n"),
8443 : integer_type_node);
8444 4 : DECL_CONTEXT (n) = fndecl;
8445 :
8446 4 : symbolic::node_manager node_mgr;
8447 4 : auto &mgr = node_mgr.get_region_model_manager ();
8448 4 : test_region_model_context ctxt;
8449 4 : region_model model (node_mgr);
8450 :
8451 : /* Push 5 stack frames for "factorial", each with a param */
8452 4 : auto_vec<const region *> parm_regs;
8453 4 : auto_vec<const svalue *> parm_svals;
8454 24 : for (int depth = 0; depth < 5; depth++)
8455 : {
8456 20 : const region *frame_n_reg
8457 20 : = model.push_frame (*DECL_STRUCT_FUNCTION (fndecl),
8458 : nullptr, nullptr, &ctxt);
8459 20 : const region *parm_n_reg = model.get_lvalue (path_var (n, depth), &ctxt);
8460 20 : parm_regs.safe_push (parm_n_reg);
8461 :
8462 20 : ASSERT_EQ (parm_n_reg->get_parent_region (), frame_n_reg);
8463 20 : const svalue *sval_n = mgr.get_or_create_initial_value (parm_n_reg);
8464 20 : parm_svals.safe_push (sval_n);
8465 : }
8466 :
8467 : /* Verify that we can recognize that the regions are the parms,
8468 : at every depth. */
8469 24 : for (int depth = 0; depth < 5; depth++)
8470 : {
8471 20 : {
8472 20 : value_set visited;
8473 40 : ASSERT_EQ (model.get_representative_path_var (parm_regs[depth],
8474 : &visited,
8475 : nullptr),
8476 : path_var (n, depth + 1));
8477 20 : }
8478 : /* ...and that we can lookup lvalues for locals for all frames,
8479 : not just the top. */
8480 20 : ASSERT_EQ (model.get_lvalue (path_var (n, depth), nullptr),
8481 : parm_regs[depth]);
8482 : /* ...and that we can locate the svalues. */
8483 20 : {
8484 20 : value_set visited;
8485 40 : ASSERT_EQ (model.get_representative_path_var (parm_svals[depth],
8486 : &visited,
8487 : nullptr),
8488 : path_var (n, depth + 1));
8489 20 : }
8490 : }
8491 4 : }
8492 :
8493 : /* Ensure that region_model::operator== works as expected. */
8494 :
8495 : static void
8496 4 : test_equality_1 ()
8497 : {
8498 4 : tree int_42 = build_int_cst (integer_type_node, 42);
8499 4 : tree int_17 = build_int_cst (integer_type_node, 17);
8500 :
8501 : /* Verify that "empty" region_model instances are equal to each other. */
8502 4 : symbolic::node_manager node_mgr;
8503 4 : region_model model0 (node_mgr);
8504 4 : region_model model1 (node_mgr);
8505 4 : ASSERT_EQ (model0, model1);
8506 :
8507 : /* Verify that setting state in model1 makes the models non-equal. */
8508 4 : tree x = build_global_decl ("x", integer_type_node);
8509 4 : model0.set_value (x, int_42, nullptr);
8510 4 : ASSERT_EQ (model0.get_rvalue (x, nullptr)->maybe_get_constant (), int_42);
8511 4 : ASSERT_NE (model0, model1);
8512 :
8513 : /* Verify the copy-ctor. */
8514 4 : region_model model2 (model0);
8515 4 : ASSERT_EQ (model0, model2);
8516 4 : ASSERT_EQ (model2.get_rvalue (x, nullptr)->maybe_get_constant (), int_42);
8517 4 : ASSERT_NE (model1, model2);
8518 :
8519 : /* Verify that models obtained from copy-ctor are independently editable
8520 : w/o affecting the original model. */
8521 4 : model2.set_value (x, int_17, nullptr);
8522 4 : ASSERT_NE (model0, model2);
8523 4 : ASSERT_EQ (model2.get_rvalue (x, nullptr)->maybe_get_constant (), int_17);
8524 4 : ASSERT_EQ (model0.get_rvalue (x, nullptr)->maybe_get_constant (), int_42);
8525 4 : }
8526 :
8527 : /* Verify that region models for
8528 : x = 42; y = 113;
8529 : and
8530 : y = 113; x = 42;
8531 : are equal. */
8532 :
8533 : static void
8534 4 : test_canonicalization_2 ()
8535 : {
8536 4 : tree int_42 = build_int_cst (integer_type_node, 42);
8537 4 : tree int_113 = build_int_cst (integer_type_node, 113);
8538 4 : tree x = build_global_decl ("x", integer_type_node);
8539 4 : tree y = build_global_decl ("y", integer_type_node);
8540 :
8541 4 : symbolic::node_manager node_mgr;
8542 4 : region_model model0 (node_mgr);
8543 4 : model0.set_value (model0.get_lvalue (x, nullptr),
8544 : model0.get_rvalue (int_42, nullptr),
8545 : nullptr);
8546 4 : model0.set_value (model0.get_lvalue (y, nullptr),
8547 : model0.get_rvalue (int_113, nullptr),
8548 : nullptr);
8549 :
8550 4 : region_model model1 (node_mgr);
8551 4 : model1.set_value (model1.get_lvalue (y, nullptr),
8552 : model1.get_rvalue (int_113, nullptr),
8553 : nullptr);
8554 4 : model1.set_value (model1.get_lvalue (x, nullptr),
8555 : model1.get_rvalue (int_42, nullptr),
8556 : nullptr);
8557 :
8558 4 : ASSERT_EQ (model0, model1);
8559 4 : }
8560 :
8561 : /* Verify that constraints for
8562 : x > 3 && y > 42
8563 : and
8564 : y > 42 && x > 3
8565 : are equal after canonicalization. */
8566 :
8567 : static void
8568 4 : test_canonicalization_3 ()
8569 : {
8570 4 : tree int_3 = build_int_cst (integer_type_node, 3);
8571 4 : tree int_42 = build_int_cst (integer_type_node, 42);
8572 4 : tree x = build_global_decl ("x", integer_type_node);
8573 4 : tree y = build_global_decl ("y", integer_type_node);
8574 :
8575 4 : symbolic::node_manager node_mgr;
8576 4 : region_model model0 (node_mgr);
8577 4 : model0.add_constraint (x, GT_EXPR, int_3, nullptr);
8578 4 : model0.add_constraint (y, GT_EXPR, int_42, nullptr);
8579 :
8580 4 : region_model model1 (node_mgr);
8581 4 : model1.add_constraint (y, GT_EXPR, int_42, nullptr);
8582 4 : model1.add_constraint (x, GT_EXPR, int_3, nullptr);
8583 :
8584 4 : model0.canonicalize ();
8585 4 : model1.canonicalize ();
8586 4 : ASSERT_EQ (model0, model1);
8587 4 : }
8588 :
8589 : /* Verify that we can canonicalize a model containing NaN and other real
8590 : constants. */
8591 :
8592 : static void
8593 4 : test_canonicalization_4 ()
8594 : {
8595 4 : auto_vec<tree> csts;
8596 4 : append_interesting_constants (&csts);
8597 :
8598 4 : symbolic::node_manager node_mgr;
8599 4 : region_model model (node_mgr);
8600 :
8601 60 : for (tree cst : csts)
8602 48 : model.get_rvalue (cst, nullptr);
8603 :
8604 4 : model.canonicalize ();
8605 4 : }
8606 :
8607 : /* Assert that if we have two region_model instances
8608 : with values VAL_A and VAL_B for EXPR that they are
8609 : mergeable. Write the merged model to *OUT_MERGED_MODEL,
8610 : and the merged svalue ptr to *OUT_MERGED_SVALUE.
8611 : If VAL_A or VAL_B are nullptr_TREE, don't populate EXPR
8612 : for that region_model. */
8613 :
8614 : static void
8615 20 : assert_region_models_merge (tree expr, tree val_a, tree val_b,
8616 : region_model *out_merged_model,
8617 : const svalue **out_merged_svalue)
8618 : {
8619 20 : region_model_manager *mgr = out_merged_model->get_manager ();
8620 20 : auto &node_mgr = mgr->get_node_manager ();
8621 20 : program_point point (program_point::origin (*mgr));
8622 20 : test_region_model_context ctxt;
8623 20 : region_model model0 (node_mgr);
8624 20 : region_model model1 (node_mgr);
8625 20 : if (val_a)
8626 16 : model0.set_value (model0.get_lvalue (expr, &ctxt),
8627 : model0.get_rvalue (val_a, &ctxt),
8628 : &ctxt);
8629 20 : if (val_b)
8630 16 : model1.set_value (model1.get_lvalue (expr, &ctxt),
8631 : model1.get_rvalue (val_b, &ctxt),
8632 : &ctxt);
8633 :
8634 : /* They should be mergeable. */
8635 20 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, out_merged_model));
8636 20 : *out_merged_svalue = out_merged_model->get_rvalue (expr, &ctxt);
8637 20 : }
8638 :
8639 : /* Verify that we can merge region_model instances. */
8640 :
8641 : static void
8642 4 : test_state_merging ()
8643 : {
8644 4 : tree int_42 = build_int_cst (integer_type_node, 42);
8645 4 : tree int_113 = build_int_cst (integer_type_node, 113);
8646 4 : tree x = build_global_decl ("x", integer_type_node);
8647 4 : tree y = build_global_decl ("y", integer_type_node);
8648 4 : tree z = build_global_decl ("z", integer_type_node);
8649 4 : tree p = build_global_decl ("p", ptr_type_node);
8650 :
8651 4 : tree addr_of_y = build1 (ADDR_EXPR, ptr_type_node, y);
8652 4 : tree addr_of_z = build1 (ADDR_EXPR, ptr_type_node, z);
8653 :
8654 4 : auto_vec <tree> param_types;
8655 4 : tree test_fndecl = make_fndecl (integer_type_node, "test_fn", param_types);
8656 4 : allocate_struct_function (test_fndecl, true);
8657 :
8658 : /* Param "a". */
8659 4 : tree a = build_decl (UNKNOWN_LOCATION, PARM_DECL,
8660 : get_identifier ("a"),
8661 : integer_type_node);
8662 4 : DECL_CONTEXT (a) = test_fndecl;
8663 4 : tree addr_of_a = build1 (ADDR_EXPR, ptr_type_node, a);
8664 :
8665 : /* Param "q", a pointer. */
8666 4 : tree q = build_decl (UNKNOWN_LOCATION, PARM_DECL,
8667 : get_identifier ("q"),
8668 : ptr_type_node);
8669 4 : DECL_CONTEXT (q) = test_fndecl;
8670 :
8671 4 : symbolic::node_manager node_mgr;
8672 4 : auto &mgr = node_mgr.get_region_model_manager ();
8673 4 : program_point point (program_point::origin (mgr));
8674 :
8675 4 : {
8676 4 : region_model model0 (node_mgr);
8677 4 : region_model model1 (node_mgr);
8678 4 : region_model merged (node_mgr);
8679 : /* Verify empty models can be merged. */
8680 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
8681 4 : ASSERT_EQ (model0, merged);
8682 4 : }
8683 :
8684 : /* Verify that we can merge two contradictory constraints on the
8685 : value for a global. */
8686 : /* TODO: verify that the merged model doesn't have a value for
8687 : the global */
8688 4 : {
8689 4 : region_model model0 (node_mgr);
8690 4 : region_model model1 (node_mgr);
8691 4 : region_model merged (node_mgr);
8692 4 : test_region_model_context ctxt;
8693 4 : model0.add_constraint (x, EQ_EXPR, int_42, &ctxt);
8694 4 : model1.add_constraint (x, EQ_EXPR, int_113, &ctxt);
8695 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
8696 4 : ASSERT_NE (model0, merged);
8697 4 : ASSERT_NE (model1, merged);
8698 4 : }
8699 :
8700 : /* Verify handling of a PARM_DECL. */
8701 4 : {
8702 4 : test_region_model_context ctxt;
8703 4 : region_model model0 (node_mgr);
8704 4 : region_model model1 (node_mgr);
8705 4 : ASSERT_EQ (model0.get_stack_depth (), 0);
8706 4 : model0.push_frame (*DECL_STRUCT_FUNCTION (test_fndecl),
8707 : nullptr, nullptr, &ctxt);
8708 4 : ASSERT_EQ (model0.get_stack_depth (), 1);
8709 4 : model1.push_frame (*DECL_STRUCT_FUNCTION (test_fndecl),
8710 : nullptr, nullptr, &ctxt);
8711 :
8712 4 : placeholder_svalue test_sval (mgr.alloc_node_id (),
8713 4 : integer_type_node, "test sval");
8714 4 : model0.set_value (model0.get_lvalue (a, &ctxt), &test_sval, &ctxt);
8715 4 : model1.set_value (model1.get_lvalue (a, &ctxt), &test_sval, &ctxt);
8716 4 : ASSERT_EQ (model0, model1);
8717 :
8718 : /* They should be mergeable, and the result should be the same. */
8719 4 : region_model merged (node_mgr);
8720 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
8721 4 : ASSERT_EQ (model0, merged);
8722 : /* In particular, "a" should have the placeholder value. */
8723 4 : ASSERT_EQ (merged.get_rvalue (a, &ctxt), &test_sval);
8724 4 : }
8725 :
8726 : /* Verify handling of a global. */
8727 4 : {
8728 4 : test_region_model_context ctxt;
8729 4 : region_model model0 (node_mgr);
8730 4 : region_model model1 (node_mgr);
8731 :
8732 4 : placeholder_svalue test_sval (mgr.alloc_node_id (),
8733 4 : integer_type_node, "test sval");
8734 4 : model0.set_value (model0.get_lvalue (x, &ctxt), &test_sval, &ctxt);
8735 4 : model1.set_value (model1.get_lvalue (x, &ctxt), &test_sval, &ctxt);
8736 4 : ASSERT_EQ (model0, model1);
8737 :
8738 : /* They should be mergeable, and the result should be the same. */
8739 4 : region_model merged (node_mgr);
8740 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
8741 4 : ASSERT_EQ (model0, merged);
8742 : /* In particular, "x" should have the placeholder value. */
8743 4 : ASSERT_EQ (merged.get_rvalue (x, &ctxt), &test_sval);
8744 4 : }
8745 :
8746 : /* Use global-handling to verify various combinations of values. */
8747 :
8748 : /* Two equal constant values. */
8749 4 : {
8750 4 : region_model merged (node_mgr);
8751 4 : const svalue *merged_x_sval;
8752 4 : assert_region_models_merge (x, int_42, int_42, &merged, &merged_x_sval);
8753 :
8754 : /* In particular, there should be a constant value for "x". */
8755 4 : ASSERT_EQ (merged_x_sval->get_kind (), SK_CONSTANT);
8756 4 : ASSERT_EQ (merged_x_sval->dyn_cast_constant_svalue ()->get_constant (),
8757 : int_42);
8758 4 : }
8759 :
8760 : /* Two non-equal constant values. */
8761 4 : {
8762 4 : region_model merged (node_mgr);
8763 4 : const svalue *merged_x_sval;
8764 4 : assert_region_models_merge (x, int_42, int_113, &merged, &merged_x_sval);
8765 :
8766 : /* In particular, there should be a "widening" value for "x". */
8767 4 : ASSERT_EQ (merged_x_sval->get_kind (), SK_WIDENING);
8768 4 : }
8769 :
8770 : /* Initial and constant. */
8771 4 : {
8772 4 : region_model merged (node_mgr);
8773 4 : const svalue *merged_x_sval;
8774 4 : assert_region_models_merge (x, NULL_TREE, int_113, &merged, &merged_x_sval);
8775 :
8776 : /* In particular, there should be an unknown value for "x". */
8777 4 : ASSERT_EQ (merged_x_sval->get_kind (), SK_UNKNOWN);
8778 4 : }
8779 :
8780 : /* Constant and initial. */
8781 4 : {
8782 4 : region_model merged (node_mgr);
8783 4 : const svalue *merged_x_sval;
8784 4 : assert_region_models_merge (x, int_42, NULL_TREE, &merged, &merged_x_sval);
8785 :
8786 : /* In particular, there should be an unknown value for "x". */
8787 4 : ASSERT_EQ (merged_x_sval->get_kind (), SK_UNKNOWN);
8788 4 : }
8789 :
8790 : /* Unknown and constant. */
8791 : // TODO
8792 :
8793 : /* Pointers: NULL and NULL. */
8794 : // TODO
8795 :
8796 : /* Pointers: NULL and non-NULL. */
8797 : // TODO
8798 :
8799 : /* Pointers: non-NULL and non-NULL: ptr to a local. */
8800 4 : {
8801 4 : region_model model0 (node_mgr);
8802 4 : model0.push_frame (*DECL_STRUCT_FUNCTION (test_fndecl),
8803 : nullptr, nullptr, nullptr);
8804 4 : model0.set_value (model0.get_lvalue (p, nullptr),
8805 : model0.get_rvalue (addr_of_a, nullptr), nullptr);
8806 :
8807 4 : region_model model1 (model0);
8808 4 : ASSERT_EQ (model0, model1);
8809 :
8810 : /* They should be mergeable, and the result should be the same. */
8811 4 : region_model merged (node_mgr);
8812 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
8813 4 : ASSERT_EQ (model0, merged);
8814 4 : }
8815 :
8816 : /* Pointers: non-NULL and non-NULL: ptr to a global. */
8817 4 : {
8818 4 : region_model merged (node_mgr);
8819 : /* p == &y in both input models. */
8820 4 : const svalue *merged_p_sval;
8821 4 : assert_region_models_merge (p, addr_of_y, addr_of_y, &merged,
8822 : &merged_p_sval);
8823 :
8824 : /* We should get p == &y in the merged model. */
8825 4 : auto *sym_ptr = merged_p_sval->maybe_get_symbolic_pointer ();
8826 4 : ASSERT_NE (sym_ptr, nullptr);
8827 4 : ASSERT_SAME_SYMBOLIC_NODE (sym_ptr->get_base_region (),
8828 : *merged.get_lvalue (y, nullptr));
8829 4 : ASSERT_TRUE (sym_ptr->get_byte_offset ().is_zero_p ());
8830 4 : }
8831 :
8832 : /* Pointers: non-NULL ptrs to different globals should not merge;
8833 : see e.g. gcc.dg/analyzer/torture/uninit-pr108725.c */
8834 4 : {
8835 4 : region_model merged_model (node_mgr);
8836 4 : program_point point (program_point::origin (mgr));
8837 4 : test_region_model_context ctxt;
8838 : /* p == &y vs p == &z in the input models. */
8839 4 : region_model model0 (node_mgr);
8840 4 : region_model model1 (node_mgr);
8841 4 : model0.set_value (model0.get_lvalue (p, &ctxt),
8842 : model0.get_rvalue (addr_of_y, &ctxt),
8843 : &ctxt);
8844 4 : model1.set_value (model1.get_lvalue (p, &ctxt),
8845 : model1.get_rvalue (addr_of_z, &ctxt),
8846 : &ctxt);
8847 : /* They should not be mergeable. */
8848 4 : ASSERT_FALSE (model0.can_merge_with_p (model1, point, &merged_model));
8849 4 : }
8850 :
8851 : /* Pointers: non-NULL and non-NULL: ptr to a heap region. */
8852 4 : {
8853 4 : test_region_model_context ctxt;
8854 4 : region_model model0 (node_mgr);
8855 4 : tree size = build_int_cst (size_type_node, 1024);
8856 4 : const svalue *size_sval = mgr.get_or_create_constant_svalue (size);
8857 4 : const region *new_reg
8858 4 : = model0.get_or_create_region_for_heap_alloc (size_sval, &ctxt);
8859 4 : const svalue *ptr_sval = mgr.get_ptr_svalue (ptr_type_node, new_reg);
8860 4 : model0.set_value (model0.get_lvalue (p, &ctxt),
8861 : ptr_sval, &ctxt);
8862 :
8863 4 : region_model model1 (model0);
8864 :
8865 4 : ASSERT_EQ (model0, model1);
8866 :
8867 4 : region_model merged (node_mgr);
8868 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
8869 :
8870 : /* The merged model ought to be identical. */
8871 4 : ASSERT_EQ (model0, merged);
8872 4 : }
8873 :
8874 : /* Two regions sharing the same placeholder svalue should continue sharing
8875 : it after self-merger. */
8876 4 : {
8877 4 : test_region_model_context ctxt;
8878 4 : region_model model0 (node_mgr);
8879 4 : placeholder_svalue placeholder_sval (mgr.alloc_node_id (),
8880 4 : integer_type_node, "test");
8881 4 : model0.set_value (model0.get_lvalue (x, &ctxt),
8882 : &placeholder_sval, &ctxt);
8883 4 : model0.set_value (model0.get_lvalue (y, &ctxt), &placeholder_sval, &ctxt);
8884 4 : region_model model1 (model0);
8885 :
8886 : /* They should be mergeable, and the result should be the same. */
8887 4 : region_model merged (node_mgr);
8888 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
8889 4 : ASSERT_EQ (model0, merged);
8890 :
8891 : /* In particular, we should have x == y. */
8892 4 : ASSERT_EQ (merged.eval_condition (x, EQ_EXPR, y, &ctxt),
8893 : tristate (tristate::TS_TRUE));
8894 4 : }
8895 :
8896 4 : {
8897 4 : region_model model0 (node_mgr);
8898 4 : region_model model1 (node_mgr);
8899 4 : test_region_model_context ctxt;
8900 4 : model0.add_constraint (x, EQ_EXPR, int_42, &ctxt);
8901 4 : model1.add_constraint (x, NE_EXPR, int_42, &ctxt);
8902 4 : region_model merged (node_mgr);
8903 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
8904 4 : }
8905 :
8906 4 : {
8907 4 : region_model model0 (node_mgr);
8908 4 : region_model model1 (node_mgr);
8909 4 : test_region_model_context ctxt;
8910 4 : model0.add_constraint (x, EQ_EXPR, int_42, &ctxt);
8911 4 : model1.add_constraint (x, NE_EXPR, int_42, &ctxt);
8912 4 : model1.add_constraint (x, EQ_EXPR, int_113, &ctxt);
8913 4 : region_model merged (node_mgr);
8914 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
8915 4 : }
8916 :
8917 : // TODO: what can't we merge? need at least one such test
8918 :
8919 : /* TODO: various things
8920 : - heap regions
8921 : - value merging:
8922 : - every combination, but in particular
8923 : - pairs of regions
8924 : */
8925 :
8926 : /* Views. */
8927 4 : {
8928 4 : test_region_model_context ctxt;
8929 4 : region_model model0 (node_mgr);
8930 :
8931 4 : const region *x_reg = model0.get_lvalue (x, &ctxt);
8932 4 : const region *x_as_ptr = mgr.get_cast_region (x_reg, ptr_type_node);
8933 4 : model0.set_value (x_as_ptr, model0.get_rvalue (addr_of_y, &ctxt), &ctxt);
8934 :
8935 4 : region_model model1 (model0);
8936 4 : ASSERT_EQ (model1, model0);
8937 :
8938 : /* They should be mergeable, and the result should be the same. */
8939 4 : region_model merged (node_mgr);
8940 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
8941 4 : }
8942 :
8943 : /* Verify that we can merge a model in which a local in an older stack
8944 : frame points to a local in a more recent stack frame. */
8945 4 : {
8946 4 : region_model model0 (node_mgr);
8947 4 : model0.push_frame (*DECL_STRUCT_FUNCTION (test_fndecl),
8948 : nullptr, nullptr, nullptr);
8949 4 : const region *q_in_first_frame = model0.get_lvalue (q, nullptr);
8950 :
8951 : /* Push a second frame. */
8952 4 : const region *reg_2nd_frame
8953 4 : = model0.push_frame (*DECL_STRUCT_FUNCTION (test_fndecl),
8954 : nullptr, nullptr, nullptr);
8955 :
8956 : /* Have a pointer in the older frame point to a local in the
8957 : more recent frame. */
8958 4 : const svalue *sval_ptr = model0.get_rvalue (addr_of_a, nullptr);
8959 4 : model0.set_value (q_in_first_frame, sval_ptr, nullptr);
8960 :
8961 : /* Verify that it's pointing at the newer frame. */
8962 4 : auto *sym_ptr = sval_ptr->maybe_get_symbolic_pointer ();
8963 4 : ASSERT_NE (sym_ptr, nullptr);
8964 4 : ASSERT_SAME_SYMBOLIC_NODE
8965 : (*sym_ptr->get_base_region ().get_parent_region (),
8966 : *reg_2nd_frame);
8967 4 : ASSERT_TRUE (sym_ptr->get_byte_offset ().is_zero_p ());
8968 4 : model0.canonicalize ();
8969 :
8970 4 : region_model model1 (model0);
8971 4 : ASSERT_EQ (model0, model1);
8972 :
8973 : /* They should be mergeable, and the result should be the same
8974 : (after canonicalization, at least). */
8975 4 : region_model merged (node_mgr);
8976 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
8977 4 : merged.canonicalize ();
8978 4 : ASSERT_EQ (model0, merged);
8979 4 : }
8980 :
8981 : /* Verify that we can merge a model in which a local points to a global. */
8982 4 : {
8983 4 : region_model model0 (node_mgr);
8984 4 : model0.push_frame (*DECL_STRUCT_FUNCTION (test_fndecl),
8985 : nullptr, nullptr, nullptr);
8986 4 : model0.set_value (model0.get_lvalue (q, nullptr),
8987 : model0.get_rvalue (addr_of_y, nullptr), nullptr);
8988 :
8989 4 : region_model model1 (model0);
8990 4 : ASSERT_EQ (model0, model1);
8991 :
8992 : /* They should be mergeable, and the result should be the same
8993 : (after canonicalization, at least). */
8994 4 : region_model merged (node_mgr);
8995 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
8996 4 : ASSERT_EQ (model0, merged);
8997 4 : }
8998 4 : }
8999 :
9000 : /* Verify that constraints are correctly merged when merging region_model
9001 : instances. */
9002 :
9003 : static void
9004 4 : test_constraint_merging ()
9005 : {
9006 4 : tree int_0 = integer_zero_node;
9007 4 : tree int_5 = build_int_cst (integer_type_node, 5);
9008 4 : tree x = build_global_decl ("x", integer_type_node);
9009 4 : tree y = build_global_decl ("y", integer_type_node);
9010 4 : tree z = build_global_decl ("z", integer_type_node);
9011 4 : tree n = build_global_decl ("n", integer_type_node);
9012 :
9013 4 : symbolic::node_manager node_mgr;
9014 4 : auto &mgr = node_mgr.get_region_model_manager ();
9015 4 : test_region_model_context ctxt;
9016 :
9017 : /* model0: 0 <= (x == y) < n. */
9018 4 : region_model model0 (node_mgr);
9019 4 : model0.add_constraint (x, EQ_EXPR, y, &ctxt);
9020 4 : model0.add_constraint (x, GE_EXPR, int_0, nullptr);
9021 4 : model0.add_constraint (x, LT_EXPR, n, nullptr);
9022 :
9023 : /* model1: z != 5 && (0 <= x < n). */
9024 4 : region_model model1 (node_mgr);
9025 4 : model1.add_constraint (z, NE_EXPR, int_5, nullptr);
9026 4 : model1.add_constraint (x, GE_EXPR, int_0, nullptr);
9027 4 : model1.add_constraint (x, LT_EXPR, n, nullptr);
9028 :
9029 : /* They should be mergeable; the merged constraints should
9030 : be: (0 <= x < n). */
9031 4 : program_point point (program_point::origin (mgr));
9032 4 : region_model merged (node_mgr);
9033 4 : ASSERT_TRUE (model0.can_merge_with_p (model1, point, &merged));
9034 :
9035 4 : ASSERT_EQ (merged.eval_condition (x, GE_EXPR, int_0, &ctxt),
9036 : tristate (tristate::TS_TRUE));
9037 4 : ASSERT_EQ (merged.eval_condition (x, LT_EXPR, n, &ctxt),
9038 : tristate (tristate::TS_TRUE));
9039 :
9040 4 : ASSERT_EQ (merged.eval_condition (z, NE_EXPR, int_5, &ctxt),
9041 : tristate (tristate::TS_UNKNOWN));
9042 4 : ASSERT_EQ (merged.eval_condition (x, LT_EXPR, y, &ctxt),
9043 : tristate (tristate::TS_UNKNOWN));
9044 4 : }
9045 :
9046 : /* Verify that widening_svalue::eval_condition_without_cm works as
9047 : expected. */
9048 :
9049 : static void
9050 4 : test_widening_constraints ()
9051 : {
9052 4 : symbolic::node_manager node_mgr;
9053 4 : auto &mgr = node_mgr.get_region_model_manager ();
9054 4 : const supernode *snode = nullptr;
9055 4 : tree int_0 = integer_zero_node;
9056 4 : tree int_m1 = build_int_cst (integer_type_node, -1);
9057 4 : tree int_1 = integer_one_node;
9058 4 : tree int_256 = build_int_cst (integer_type_node, 256);
9059 4 : test_region_model_context ctxt;
9060 4 : const svalue *int_0_sval = mgr.get_or_create_constant_svalue (int_0);
9061 4 : const svalue *int_1_sval = mgr.get_or_create_constant_svalue (int_1);
9062 4 : const svalue *w_zero_then_one_sval
9063 4 : = mgr.get_or_create_widening_svalue (integer_type_node, snode,
9064 : int_0_sval, int_1_sval);
9065 4 : const widening_svalue *w_zero_then_one
9066 4 : = w_zero_then_one_sval->dyn_cast_widening_svalue ();
9067 4 : ASSERT_EQ (w_zero_then_one->get_direction (),
9068 : widening_svalue::DIR_ASCENDING);
9069 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LT_EXPR, int_m1),
9070 : tristate::TS_FALSE);
9071 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LT_EXPR, int_0),
9072 : tristate::TS_FALSE);
9073 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LT_EXPR, int_1),
9074 : tristate::TS_UNKNOWN);
9075 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LT_EXPR, int_256),
9076 : tristate::TS_UNKNOWN);
9077 :
9078 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LE_EXPR, int_m1),
9079 : tristate::TS_FALSE);
9080 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LE_EXPR, int_0),
9081 : tristate::TS_UNKNOWN);
9082 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LE_EXPR, int_1),
9083 : tristate::TS_UNKNOWN);
9084 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (LE_EXPR, int_256),
9085 : tristate::TS_UNKNOWN);
9086 :
9087 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GT_EXPR, int_m1),
9088 : tristate::TS_TRUE);
9089 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GT_EXPR, int_0),
9090 : tristate::TS_UNKNOWN);
9091 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GT_EXPR, int_1),
9092 : tristate::TS_UNKNOWN);
9093 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GT_EXPR, int_256),
9094 : tristate::TS_UNKNOWN);
9095 :
9096 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GE_EXPR, int_m1),
9097 : tristate::TS_TRUE);
9098 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GE_EXPR, int_0),
9099 : tristate::TS_TRUE);
9100 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GE_EXPR, int_1),
9101 : tristate::TS_UNKNOWN);
9102 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (GE_EXPR, int_256),
9103 : tristate::TS_UNKNOWN);
9104 :
9105 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (EQ_EXPR, int_m1),
9106 : tristate::TS_FALSE);
9107 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (EQ_EXPR, int_0),
9108 : tristate::TS_UNKNOWN);
9109 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (EQ_EXPR, int_1),
9110 : tristate::TS_UNKNOWN);
9111 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (EQ_EXPR, int_256),
9112 : tristate::TS_UNKNOWN);
9113 :
9114 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (NE_EXPR, int_m1),
9115 : tristate::TS_TRUE);
9116 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (NE_EXPR, int_0),
9117 : tristate::TS_UNKNOWN);
9118 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (NE_EXPR, int_1),
9119 : tristate::TS_UNKNOWN);
9120 4 : ASSERT_EQ (w_zero_then_one->eval_condition_without_cm (NE_EXPR, int_256),
9121 : tristate::TS_UNKNOWN);
9122 4 : }
9123 :
9124 : /* Verify merging constraints for states simulating successive iterations
9125 : of a loop.
9126 : Simulate:
9127 : for (i = 0; i < 256; i++)
9128 : [...body...]
9129 : i.e. this gimple:.
9130 : i_15 = 0;
9131 : goto <bb 4>;
9132 :
9133 : <bb 4> :
9134 : i_11 = PHI <i_15(2), i_23(3)>
9135 : if (i_11 <= 255)
9136 : goto <bb 3>;
9137 : else
9138 : goto [AFTER LOOP]
9139 :
9140 : <bb 3> :
9141 : [LOOP BODY]
9142 : i_23 = i_11 + 1;
9143 :
9144 : and thus these ops (and resultant states):
9145 : i_11 = PHI()
9146 : {i_11: 0}
9147 : add_constraint (i_11 <= 255) [for the true edge]
9148 : {i_11: 0} [constraint was a no-op]
9149 : i_23 = i_11 + 1;
9150 : {i_22: 1}
9151 : i_11 = PHI()
9152 : {i_11: WIDENED (at phi, 0, 1)}
9153 : add_constraint (i_11 <= 255) [for the true edge]
9154 : {i_11: WIDENED (at phi, 0, 1); WIDENED <= 255}
9155 : i_23 = i_11 + 1;
9156 : {i_23: (WIDENED (at phi, 0, 1) + 1); WIDENED <= 255}
9157 : i_11 = PHI(); merge with state at phi above
9158 : {i_11: WIDENED (at phi, 0, 1); WIDENED <= 256}
9159 : [changing meaning of "WIDENED" here]
9160 : if (i_11 <= 255)
9161 : T: {i_11: WIDENED (at phi, 0, 1); WIDENED <= 255}; cache hit
9162 : F: {i_11: 256}
9163 : */
9164 :
9165 : static void
9166 4 : test_iteration_1 ()
9167 : {
9168 4 : symbolic::node_manager node_mgr;
9169 4 : auto &mgr = node_mgr.get_region_model_manager ();
9170 4 : program_point point (program_point::origin (mgr));
9171 :
9172 4 : tree int_0 = integer_zero_node;
9173 4 : tree int_1 = integer_one_node;
9174 4 : tree int_256 = build_int_cst (integer_type_node, 256);
9175 4 : tree i = build_global_decl ("i", integer_type_node);
9176 :
9177 4 : test_region_model_context ctxt;
9178 :
9179 : /* model0: i: 0. */
9180 4 : region_model model0 (node_mgr);
9181 4 : model0.set_value (i, int_0, &ctxt);
9182 :
9183 : /* model1: i: 1. */
9184 4 : region_model model1 (node_mgr);
9185 4 : model1.set_value (i, int_1, &ctxt);
9186 :
9187 : /* Should merge "i" to a widened value. */
9188 4 : region_model model2 (node_mgr);
9189 4 : ASSERT_TRUE (model1.can_merge_with_p (model0, point, &model2));
9190 4 : const svalue *merged_i = model2.get_rvalue (i, &ctxt);
9191 4 : ASSERT_EQ (merged_i->get_kind (), SK_WIDENING);
9192 4 : const widening_svalue *w = merged_i->dyn_cast_widening_svalue ();
9193 4 : ASSERT_EQ (w->get_direction (), widening_svalue::DIR_ASCENDING);
9194 :
9195 : /* Add constraint: i < 256 */
9196 4 : model2.add_constraint (i, LT_EXPR, int_256, &ctxt);
9197 4 : ASSERT_EQ (model2.eval_condition (i, LT_EXPR, int_256, &ctxt),
9198 : tristate (tristate::TS_TRUE));
9199 4 : ASSERT_EQ (model2.eval_condition (i, GE_EXPR, int_0, &ctxt),
9200 : tristate (tristate::TS_TRUE));
9201 :
9202 : /* Try merging with the initial state. */
9203 4 : region_model model3 (node_mgr);
9204 4 : ASSERT_TRUE (model2.can_merge_with_p (model0, point, &model3));
9205 : /* Merging the merged value with the initial value should be idempotent,
9206 : so that the analysis converges. */
9207 4 : ASSERT_EQ (model3.get_rvalue (i, &ctxt), merged_i);
9208 : /* Merger of 0 and a widening value with constraint < CST
9209 : should retain the constraint, even though it was implicit
9210 : for the 0 case. */
9211 4 : ASSERT_EQ (model3.eval_condition (i, LT_EXPR, int_256, &ctxt),
9212 : tristate (tristate::TS_TRUE));
9213 : /* ...and we should have equality: the analysis should have converged. */
9214 4 : ASSERT_EQ (model3, model2);
9215 :
9216 : /* "i_23 = i_11 + 1;" */
9217 4 : region_model model4 (model3);
9218 4 : ASSERT_EQ (model4, model2);
9219 4 : model4.set_value (i, build2 (PLUS_EXPR, integer_type_node, i, int_1), &ctxt);
9220 4 : const svalue *plus_one = model4.get_rvalue (i, &ctxt);
9221 4 : ASSERT_EQ (plus_one->get_kind (), SK_BINOP);
9222 :
9223 : /* Try merging with the "i: 1" state. */
9224 4 : region_model model5 (node_mgr);
9225 4 : ASSERT_TRUE (model4.can_merge_with_p (model1, point, &model5));
9226 4 : ASSERT_EQ (model5.get_rvalue (i, &ctxt), plus_one);
9227 4 : ASSERT_EQ (model5, model4);
9228 :
9229 : /* "i_11 = PHI();" merge with state at phi above.
9230 : For i, we should have a merger of WIDENING with WIDENING + 1,
9231 : and this should be WIDENING again. */
9232 4 : region_model model6 (node_mgr);
9233 4 : ASSERT_TRUE (model5.can_merge_with_p (model2, point, &model6));
9234 4 : const svalue *merged_widening = model6.get_rvalue (i, &ctxt);
9235 4 : ASSERT_EQ (merged_widening->get_kind (), SK_WIDENING);
9236 4 : }
9237 :
9238 : /* Verify that if we mark a pointer to a malloc-ed region as non-NULL,
9239 : all cast pointers to that region are also known to be non-NULL. */
9240 :
9241 : static void
9242 4 : test_malloc_constraints ()
9243 : {
9244 4 : symbolic::node_manager node_mgr;
9245 4 : auto &mgr = node_mgr.get_region_model_manager ();
9246 4 : region_model model (node_mgr);
9247 4 : tree p = build_global_decl ("p", ptr_type_node);
9248 4 : tree char_star = build_pointer_type (char_type_node);
9249 4 : tree q = build_global_decl ("q", char_star);
9250 4 : tree null_ptr = build_int_cst (ptr_type_node, 0);
9251 :
9252 4 : const svalue *size_in_bytes
9253 4 : = mgr.get_or_create_unknown_svalue (size_type_node);
9254 4 : const region *reg
9255 4 : = model.get_or_create_region_for_heap_alloc (size_in_bytes, nullptr);
9256 4 : const svalue *sval = mgr.get_ptr_svalue (ptr_type_node, reg);
9257 4 : model.set_value (model.get_lvalue (p, nullptr), sval, nullptr);
9258 4 : model.set_value (q, p, nullptr);
9259 :
9260 4 : ASSERT_CONDITION_UNKNOWN (model, p, NE_EXPR, null_ptr);
9261 4 : ASSERT_CONDITION_UNKNOWN (model, p, EQ_EXPR, null_ptr);
9262 4 : ASSERT_CONDITION_UNKNOWN (model, q, NE_EXPR, null_ptr);
9263 4 : ASSERT_CONDITION_UNKNOWN (model, q, EQ_EXPR, null_ptr);
9264 :
9265 4 : model.add_constraint (p, NE_EXPR, null_ptr, nullptr);
9266 :
9267 4 : ASSERT_CONDITION_TRUE (model, p, NE_EXPR, null_ptr);
9268 4 : ASSERT_CONDITION_FALSE (model, p, EQ_EXPR, null_ptr);
9269 4 : ASSERT_CONDITION_TRUE (model, q, NE_EXPR, null_ptr);
9270 4 : ASSERT_CONDITION_FALSE (model, q, EQ_EXPR, null_ptr);
9271 4 : }
9272 :
9273 : /* Smoketest of getting and setting the value of a variable. */
9274 :
9275 : static void
9276 4 : test_var ()
9277 : {
9278 : /* "int i;" */
9279 4 : tree i = build_global_decl ("i", integer_type_node);
9280 :
9281 4 : tree int_17 = build_int_cst (integer_type_node, 17);
9282 4 : tree int_m3 = build_int_cst (integer_type_node, -3);
9283 :
9284 4 : symbolic::node_manager node_mgr;
9285 4 : auto &mgr = node_mgr.get_region_model_manager ();
9286 4 : region_model model (node_mgr);
9287 :
9288 4 : const region *i_reg = model.get_lvalue (i, nullptr);
9289 4 : ASSERT_EQ (i_reg->get_kind (), RK_DECL);
9290 :
9291 : /* Reading "i" should give a symbolic "initial value". */
9292 4 : const svalue *sval_init = model.get_rvalue (i, nullptr);
9293 4 : ASSERT_EQ (sval_init->get_kind (), SK_INITIAL);
9294 4 : ASSERT_EQ (sval_init->dyn_cast_initial_svalue ()->get_region (), i_reg);
9295 : /* ..and doing it again should give the same "initial value". */
9296 4 : ASSERT_EQ (model.get_rvalue (i, nullptr), sval_init);
9297 :
9298 : /* "i = 17;". */
9299 4 : model.set_value (i, int_17, nullptr);
9300 4 : ASSERT_EQ (model.get_rvalue (i, nullptr),
9301 : model.get_rvalue (int_17, nullptr));
9302 :
9303 : /* "i = -3;". */
9304 4 : model.set_value (i, int_m3, nullptr);
9305 4 : ASSERT_EQ (model.get_rvalue (i, nullptr),
9306 : model.get_rvalue (int_m3, nullptr));
9307 :
9308 : /* Verify get_memory_range for "i". */
9309 4 : {
9310 4 : auto mem_range = i_reg->get_memory_range (mgr);
9311 4 : ASSERT_SAME_SYMBOLIC_NODE
9312 : (mem_range.get_base_region (),
9313 : *i_reg);
9314 4 : ASSERT_SAME_SYMBOLIC_NODE
9315 : (mem_range.get_start_offset (),
9316 : node_mgr.get_scalars ().get_bits ().get_concrete (0_bits));
9317 : }
9318 4 : }
9319 :
9320 : static void
9321 4 : test_array_2 ()
9322 : {
9323 : /* "int arr[10];" */
9324 4 : tree tlen = size_int (10);
9325 4 : tree arr_type
9326 4 : = build_array_type (integer_type_node, build_index_type (tlen));
9327 4 : tree arr = build_global_decl ("arr", arr_type);
9328 :
9329 : /* "int i;" */
9330 4 : tree i = build_global_decl ("i", integer_type_node);
9331 :
9332 4 : tree int_0 = integer_zero_node;
9333 4 : tree int_1 = integer_one_node;
9334 :
9335 4 : tree arr_0 = build4 (ARRAY_REF, integer_type_node,
9336 : arr, int_0, NULL_TREE, NULL_TREE);
9337 4 : tree arr_1 = build4 (ARRAY_REF, integer_type_node,
9338 : arr, int_1, NULL_TREE, NULL_TREE);
9339 4 : tree arr_i = build4 (ARRAY_REF, integer_type_node,
9340 : arr, i, NULL_TREE, NULL_TREE);
9341 :
9342 4 : tree int_17 = build_int_cst (integer_type_node, 17);
9343 4 : tree int_42 = build_int_cst (integer_type_node, 42);
9344 4 : tree int_m3 = build_int_cst (integer_type_node, -3);
9345 :
9346 4 : symbolic::node_manager node_mgr;
9347 4 : auto &mgr = node_mgr.get_region_model_manager ();
9348 4 : auto &bit_mgr = node_mgr.get_scalars ().get_bits ();
9349 4 : auto int_size_bits = concrete_bit_size (INT_TYPE_SIZE);
9350 4 : region_model model (node_mgr);
9351 : /* "arr[0] = 17;". */
9352 4 : model.set_value (arr_0, int_17, nullptr);
9353 : /* "arr[1] = -3;". */
9354 4 : model.set_value (arr_1, int_m3, nullptr);
9355 :
9356 4 : ASSERT_EQ (model.get_rvalue (arr_0, nullptr),
9357 : model.get_rvalue (int_17, nullptr));
9358 4 : ASSERT_EQ (model.get_rvalue (arr_1, nullptr),
9359 : model.get_rvalue (int_m3, nullptr));
9360 :
9361 : /* Overwrite a pre-existing binding: "arr[1] = 42;". */
9362 4 : model.set_value (arr_1, int_42, nullptr);
9363 4 : ASSERT_EQ (model.get_rvalue (arr_1, nullptr),
9364 : model.get_rvalue (int_42, nullptr));
9365 :
9366 : /* Verify get_memory_offset for "arr[0]". */
9367 4 : {
9368 4 : const region *arr_0_reg = model.get_lvalue (arr_0, nullptr);
9369 4 : auto mem_offset = arr_0_reg->get_memory_offset (mgr);
9370 4 : ASSERT_SAME_SYMBOLIC_NODE (mem_offset.get_base_region (),
9371 : *model.get_lvalue (arr, nullptr));
9372 4 : ASSERT_SAME_SYMBOLIC_NODE (mem_offset.get_bit_offset (),
9373 : bit_mgr.get_concrete (0_bits));
9374 4 : auto mem_range = arr_0_reg->get_memory_range (mgr);
9375 16 : ASSERT_EQ
9376 : (mem_range.get_bit_range (),
9377 : symbolic_from_concrete (concrete_bit_range (0_bits, int_size_bits),
9378 : bit_mgr));
9379 4 : ASSERT_SAME_SYMBOLIC_NODE
9380 : (model.maybe_get_region_for_mem_range (mem_range, integer_type_node),
9381 : arr_0_reg);
9382 : }
9383 :
9384 : /* Verify get_memory_offset for "arr[1]". */
9385 4 : {
9386 4 : const region *arr_1_reg = model.get_lvalue (arr_1, nullptr);
9387 4 : auto mem_offset = arr_1_reg->get_memory_offset (mgr);
9388 4 : ASSERT_SAME_SYMBOLIC_NODE
9389 : (mem_offset.get_base_region (),
9390 : *model.get_lvalue (arr, nullptr));
9391 4 : auto mem_range = arr_1_reg->get_memory_range (mgr);
9392 16 : ASSERT_EQ
9393 : (mem_range.get_bit_range (),
9394 : symbolic_from_concrete (concrete_bit_range (int_size_bits, int_size_bits),
9395 : bit_mgr));
9396 4 : ASSERT_SAME_SYMBOLIC_NODE
9397 : (model.maybe_get_region_for_mem_range (mem_range, integer_type_node),
9398 : arr_1_reg);
9399 : }
9400 :
9401 : /* Verify get_memory_offset for "arr[i]". */
9402 4 : {
9403 4 : const region *arr_i_reg = model.get_lvalue (arr_i, nullptr);
9404 4 : auto mem_offset = arr_i_reg->get_memory_offset (mgr);
9405 4 : ASSERT_SAME_SYMBOLIC_NODE (mem_offset.get_base_region (),
9406 : *model.get_lvalue (arr, nullptr));
9407 4 : auto mem_range = arr_i_reg->get_memory_range (mgr);
9408 8 : ASSERT_EQ
9409 : (mem_range.get_bit_range (),
9410 : symbolic_bit_range (mem_offset.get_bit_offset (),
9411 : bit_mgr.get_concrete (int_size_bits)));
9412 4 : ASSERT_SAME_SYMBOLIC_NODE
9413 : (model.maybe_get_region_for_mem_range (mem_range, integer_type_node),
9414 : arr_i_reg);
9415 : }
9416 :
9417 : /* "arr[i] = i;" - this should remove the earlier bindings. */
9418 4 : model.set_value (arr_i, i, nullptr);
9419 4 : ASSERT_EQ (model.get_rvalue (arr_i, nullptr), model.get_rvalue (i, nullptr));
9420 4 : ASSERT_EQ (model.get_rvalue (arr_0, nullptr)->get_kind (), SK_UNKNOWN);
9421 :
9422 : /* "arr[0] = 17;" - this should remove the arr[i] binding. */
9423 4 : model.set_value (arr_0, int_17, nullptr);
9424 4 : ASSERT_EQ (model.get_rvalue (arr_0, nullptr),
9425 : model.get_rvalue (int_17, nullptr));
9426 4 : ASSERT_EQ (model.get_rvalue (arr_i, nullptr)->get_kind (), SK_UNKNOWN);
9427 4 : }
9428 :
9429 : /* Smoketest of dereferencing a pointer via MEM_REF. */
9430 :
9431 : static void
9432 4 : test_mem_ref ()
9433 : {
9434 : /*
9435 : x = 17;
9436 : p = &x;
9437 : *p;
9438 : */
9439 4 : tree x = build_global_decl ("x", integer_type_node);
9440 4 : tree int_star = build_pointer_type (integer_type_node);
9441 4 : tree p = build_global_decl ("p", int_star);
9442 :
9443 4 : tree int_17 = build_int_cst (integer_type_node, 17);
9444 4 : tree addr_of_x = build1 (ADDR_EXPR, int_star, x);
9445 4 : tree ptype = build_pointer_type_for_mode (char_type_node, ptr_mode, true);
9446 4 : tree offset_0 = build_int_cst (ptype, 0);
9447 4 : tree star_p = build2 (MEM_REF, integer_type_node, p, offset_0);
9448 :
9449 4 : symbolic::node_manager node_mgr;
9450 4 : region_model model (node_mgr);
9451 :
9452 : /* "x = 17;". */
9453 4 : model.set_value (x, int_17, nullptr);
9454 :
9455 : /* "p = &x;". */
9456 4 : model.set_value (p, addr_of_x, nullptr);
9457 :
9458 4 : const svalue *sval = model.get_rvalue (star_p, nullptr);
9459 4 : ASSERT_EQ (sval->maybe_get_constant (), int_17);
9460 4 : }
9461 :
9462 : /* Test for a POINTER_PLUS_EXPR followed by a MEM_REF.
9463 : Analogous to this code:
9464 : void test_6 (int a[10])
9465 : {
9466 : __analyzer_eval (a[3] == 42); [should be UNKNOWN]
9467 : a[3] = 42;
9468 : __analyzer_eval (a[3] == 42); [should be TRUE]
9469 : }
9470 : from data-model-1.c, which looks like this at the gimple level:
9471 : # __analyzer_eval (a[3] == 42); [should be UNKNOWN]
9472 : int *_1 = a_10(D) + 12; # POINTER_PLUS_EXPR
9473 : int _2 = *_1; # MEM_REF
9474 : _Bool _3 = _2 == 42;
9475 : int _4 = (int) _3;
9476 : __analyzer_eval (_4);
9477 :
9478 : # a[3] = 42;
9479 : int *_5 = a_10(D) + 12; # POINTER_PLUS_EXPR
9480 : *_5 = 42; # MEM_REF
9481 :
9482 : # __analyzer_eval (a[3] == 42); [should be TRUE]
9483 : int *_6 = a_10(D) + 12; # POINTER_PLUS_EXPR
9484 : int _7 = *_6; # MEM_REF
9485 : _Bool _8 = _7 == 42;
9486 : int _9 = (int) _8;
9487 : __analyzer_eval (_9); */
9488 :
9489 : static void
9490 4 : test_POINTER_PLUS_EXPR_then_MEM_REF ()
9491 : {
9492 4 : tree int_star = build_pointer_type (integer_type_node);
9493 4 : tree a = build_global_decl ("a", int_star);
9494 4 : tree offset_12 = build_int_cst (size_type_node, 12);
9495 4 : tree pointer_plus_expr = build2 (POINTER_PLUS_EXPR, int_star, a, offset_12);
9496 4 : tree ptype = build_pointer_type_for_mode (char_type_node, ptr_mode, true);
9497 4 : tree offset_0 = build_int_cst (ptype, 0);
9498 4 : tree mem_ref = build2 (MEM_REF, integer_type_node,
9499 : pointer_plus_expr, offset_0);
9500 4 : symbolic::node_manager node_mgr;
9501 4 : region_model m (node_mgr);
9502 :
9503 4 : tree int_42 = build_int_cst (integer_type_node, 42);
9504 4 : m.set_value (mem_ref, int_42, nullptr);
9505 4 : ASSERT_EQ (m.get_rvalue (mem_ref, nullptr)->maybe_get_constant (), int_42);
9506 4 : }
9507 :
9508 : /* Verify that malloc works. */
9509 :
9510 : static void
9511 4 : test_malloc ()
9512 : {
9513 4 : tree int_star = build_pointer_type (integer_type_node);
9514 4 : tree p = build_global_decl ("p", int_star);
9515 4 : tree n = build_global_decl ("n", integer_type_node);
9516 4 : tree n_times_4 = build2 (MULT_EXPR, size_type_node,
9517 : n, build_int_cst (size_type_node, 4));
9518 :
9519 4 : symbolic::node_manager node_mgr;
9520 4 : test_region_model_context ctxt;
9521 4 : region_model model (node_mgr);
9522 :
9523 : /* "p = malloc (n * 4);". */
9524 4 : const svalue *size_sval = model.get_rvalue (n_times_4, &ctxt);
9525 4 : const region *reg
9526 4 : = model.get_or_create_region_for_heap_alloc (size_sval, &ctxt);
9527 4 : auto &mgr = node_mgr.get_region_model_manager ();
9528 4 : const svalue *ptr = mgr.get_ptr_svalue (int_star, reg);
9529 4 : model.set_value (model.get_lvalue (p, &ctxt), ptr, &ctxt);
9530 4 : ASSERT_EQ (model.get_capacity (reg), size_sval);
9531 4 : }
9532 :
9533 : /* Verify that alloca works. */
9534 :
9535 : static void
9536 4 : test_alloca ()
9537 : {
9538 4 : auto_vec <tree> param_types;
9539 4 : tree fndecl = make_fndecl (integer_type_node,
9540 : "test_fn",
9541 : param_types);
9542 4 : allocate_struct_function (fndecl, true);
9543 :
9544 :
9545 4 : tree int_star = build_pointer_type (integer_type_node);
9546 4 : tree p = build_global_decl ("p", int_star);
9547 4 : tree n = build_global_decl ("n", integer_type_node);
9548 4 : tree n_times_4 = build2 (MULT_EXPR, size_type_node,
9549 : n, build_int_cst (size_type_node, 4));
9550 :
9551 4 : symbolic::node_manager node_mgr;
9552 4 : auto &mgr = node_mgr.get_region_model_manager ();
9553 4 : test_region_model_context ctxt;
9554 4 : region_model model (node_mgr);
9555 :
9556 : /* Push stack frame. */
9557 4 : const region *frame_reg
9558 4 : = model.push_frame (*DECL_STRUCT_FUNCTION (fndecl),
9559 : nullptr, nullptr, &ctxt);
9560 : /* "p = alloca (n * 4);". */
9561 4 : const svalue *size_sval = model.get_rvalue (n_times_4, &ctxt);
9562 4 : const region *reg = model.create_region_for_alloca (size_sval, &ctxt);
9563 4 : ASSERT_EQ (reg->get_parent_region (), frame_reg);
9564 4 : const svalue *ptr = mgr.get_ptr_svalue (int_star, reg);
9565 4 : model.set_value (model.get_lvalue (p, &ctxt), ptr, &ctxt);
9566 4 : ASSERT_EQ (model.get_capacity (reg), size_sval);
9567 :
9568 : /* Verify that the pointers to the alloca region are replaced by
9569 : poisoned values when the frame is popped. */
9570 4 : model.pop_frame (nullptr, nullptr, &ctxt, nullptr);
9571 4 : auto *sval = model.get_rvalue (p, nullptr);
9572 4 : auto *sval_from_bv = sval->dyn_cast_svalue_from_bit_vector ();
9573 4 : ASSERT_NE (sval_from_bv, nullptr);
9574 4 : auto *poisoned_bv
9575 4 : = sval_from_bv->get_bit_vector ().dyn_cast_poisoned_bit_vector ();
9576 4 : ASSERT_NE (poisoned_bv, nullptr);
9577 4 : ASSERT_EQ (poisoned_bv->get_poison_kind (), poison_kind::popped_stack);
9578 4 : }
9579 :
9580 : /* Verify that svalue::involves_p works. */
9581 :
9582 : static void
9583 4 : test_involves_p ()
9584 : {
9585 4 : symbolic::node_manager node_mgr;
9586 4 : auto &mgr = node_mgr.get_region_model_manager ();
9587 :
9588 4 : tree int_star = build_pointer_type (integer_type_node);
9589 4 : tree p = build_global_decl ("p", int_star);
9590 4 : tree q = build_global_decl ("q", int_star);
9591 :
9592 4 : test_region_model_context ctxt;
9593 4 : region_model model (node_mgr);
9594 4 : const svalue *p_init = model.get_rvalue (p, &ctxt);
9595 4 : const svalue *q_init = model.get_rvalue (q, &ctxt);
9596 :
9597 4 : ASSERT_TRUE (p_init->involves_p (*p_init));
9598 4 : ASSERT_FALSE (p_init->involves_p (*q_init));
9599 :
9600 4 : const region *star_p_reg = mgr.get_symbolic_region (p_init);
9601 4 : const region *star_q_reg = mgr.get_symbolic_region (q_init);
9602 :
9603 4 : const svalue *init_star_p = mgr.get_or_create_initial_value (star_p_reg);
9604 4 : const svalue *init_star_q = mgr.get_or_create_initial_value (star_q_reg);
9605 :
9606 4 : ASSERT_TRUE (init_star_p->involves_p (*p_init));
9607 4 : ASSERT_FALSE (p_init->involves_p (*init_star_p));
9608 4 : ASSERT_FALSE (init_star_p->involves_p (*q_init));
9609 4 : ASSERT_TRUE (init_star_q->involves_p (*q_init));
9610 4 : ASSERT_FALSE (init_star_q->involves_p (*p_init));
9611 4 : }
9612 :
9613 : /* Simulate:
9614 :
9615 : | struct quad {
9616 : | int m_i;
9617 : | // padding, potentially //
9618 : | struct coord m_vertex[4];
9619 : | } q;
9620 :
9621 : Verify that we can roundtrip between regions and memory_range
9622 : for "q.m_coord[q.m_i].m_x" and "q.m_coord[q.m_i].m_y"
9623 : (which have symbolic start offsets). */
9624 :
9625 : static void
9626 4 : test_array_in_struct ()
9627 : {
9628 4 : coord_test ct;
9629 :
9630 4 : tree quad_i_field = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
9631 : get_identifier ("m_i"), integer_type_node);
9632 4 : tree vert_arr_type = build_array_type_nelts (ct.m_coord_type, 3);
9633 4 : tree quad_vertex_field
9634 4 : = build_decl (UNKNOWN_LOCATION, FIELD_DECL,
9635 : get_identifier ("m_vertex"), vert_arr_type);
9636 4 : tree quad_type = make_test_compound_type ("quad", true,
9637 : {quad_i_field, quad_vertex_field});
9638 :
9639 4 : tree q = build_global_decl ("q", quad_type);
9640 : // "q.m_i":
9641 4 : tree q_i = build3 (COMPONENT_REF, TREE_TYPE (quad_i_field),
9642 : q, quad_i_field, NULL_TREE);
9643 : // "q.m_vertex":
9644 4 : tree q_vertex = build3 (COMPONENT_REF, TREE_TYPE (quad_vertex_field),
9645 : q, quad_vertex_field, NULL_TREE);
9646 :
9647 : // "q.m_vertex[q.m_i]":
9648 4 : tree q_vertex_q_i = build4 (ARRAY_REF, TREE_TYPE (ct.m_coord_type),
9649 : q_vertex, q_i, NULL_TREE, NULL_TREE);
9650 : // "q.m_vertex[q.m_i].m_x":
9651 4 : tree q_vertex_q_i_x = build3 (COMPONENT_REF, TREE_TYPE (ct.m_y_field),
9652 : q_vertex_q_i, ct.m_x_field, NULL_TREE);
9653 : // "q.m_vertex[q.m_i].m_y":
9654 4 : tree q_vertex_q_i_y = build3 (COMPONENT_REF, TREE_TYPE (ct.m_y_field),
9655 : q_vertex_q_i, ct.m_y_field, NULL_TREE);
9656 :
9657 4 : symbolic::node_manager node_mgr;
9658 4 : auto &mgr = node_mgr.get_region_model_manager ();
9659 4 : auto &bit_mgr = node_mgr.get_scalars ().get_bits ();
9660 4 : region_model model (node_mgr);
9661 :
9662 4 : auto int_size_bits = concrete_bit_size (INT_TYPE_SIZE);
9663 :
9664 4 : const region *q_reg = model.get_lvalue (q, nullptr);
9665 4 : diagnostics::markup::lowering_options opts;
9666 4 : ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*q_reg, opts, "q");
9667 :
9668 4 : const region *vertex_reg = model.get_lvalue (q_vertex, nullptr);
9669 4 : ASSERT_SYMBOLIC_NODE_MARKUP_TEXT_EQ (*vertex_reg, opts, "q.m_vertex");
9670 :
9671 4 : const region *x_reg = model.get_lvalue (q_vertex_q_i_x, nullptr);
9672 4 : const region *y_reg = model.get_lvalue (q_vertex_q_i_y, nullptr);
9673 :
9674 : /* Verify memory range for the access of "q.m_vertex[q.m_i].m_x". */
9675 4 : {
9676 4 : auto mem_range = x_reg->get_memory_range (mgr);
9677 4 : ASSERT_SAME_SYMBOLIC_NODE (&mem_range.get_base_region (), q_reg);
9678 :
9679 4 : ASSERT_SAME_SYMBOLIC_NODE (mem_range.get_size (),
9680 : bit_mgr.get_concrete (int_size_bits));
9681 :
9682 4 : ASSERT_SAME_SYMBOLIC_NODE
9683 : (model.maybe_get_region_for_mem_range (mem_range, NULL_TREE),
9684 : x_reg);
9685 : }
9686 :
9687 : /* Verify memory range for the access of "q.m_vertex[q.m_i].m_y". */
9688 4 : {
9689 4 : auto mem_range = y_reg->get_memory_range (mgr);
9690 4 : ASSERT_SAME_SYMBOLIC_NODE (&mem_range.get_base_region (), q_reg);
9691 :
9692 4 : ASSERT_SAME_SYMBOLIC_NODE (mem_range.get_size (),
9693 : bit_mgr.get_concrete (int_size_bits));
9694 :
9695 : /* Verify that we can get the region back from the symbolic
9696 : memory range, even without a type. */
9697 4 : ASSERT_SAME_SYMBOLIC_NODE
9698 : (model.maybe_get_region_for_mem_range (mem_range, NULL_TREE),
9699 : y_reg);
9700 : }
9701 4 : }
9702 :
9703 : /* Check that we can construct a region from an awkward memory_range. */
9704 :
9705 : static void
9706 4 : test_maybe_get_region_for_mem_range ()
9707 : {
9708 4 : coord_test ct;
9709 4 : tree c = build_global_decl ("c", ct.m_coord_type);
9710 :
9711 4 : symbolic::node_manager node_mgr;
9712 4 : auto &rmm = node_mgr.get_region_model_manager ();
9713 4 : auto &bit_mgr = node_mgr.get_scalars ().get_bits ();
9714 4 : auto &byte_mgr = node_mgr.get_scalars ().get_bytes ();
9715 4 : region_model model (node_mgr);
9716 :
9717 4 : const region *base_reg = model.get_lvalue (c, nullptr);
9718 :
9719 : // Fully concrete case
9720 4 : {
9721 4 : symbolic::memory_range mem_range
9722 : (*base_reg,
9723 8 : symbolic_from_concrete (concrete_bit_range (16_bits, 8_bits),
9724 4 : bit_mgr));
9725 4 : auto *subreg = model.maybe_get_region_for_mem_range (mem_range, NULL_TREE);
9726 4 : ASSERT_NE (subreg, nullptr);
9727 : /* Check that the memory range roundtrips. */
9728 8 : ASSERT_EQ (subreg->get_memory_range (rmm),
9729 : mem_range);
9730 : }
9731 :
9732 : // Symbolic start offset
9733 4 : {
9734 4 : placeholder_svalue sval
9735 4 : (node_mgr.alloc_node_id (), size_type_node, "sval");
9736 4 : auto &num_bytes = byte_mgr.get_scalar_from_svalue (sval);
9737 4 : symbolic::memory_range mem_range
9738 : (*base_reg,
9739 4 : symbolic_bit_range (bits_from_bytes (num_bytes),
9740 4 : bit_mgr.get_concrete (8_bits)));
9741 4 : auto *subreg = model.maybe_get_region_for_mem_range (mem_range, NULL_TREE);
9742 4 : ASSERT_NE (subreg, nullptr);
9743 4 : }
9744 4 : }
9745 :
9746 : /* Run all of the selftests within this file. */
9747 :
9748 : void
9749 4 : analyzer_region_model_cc_tests ()
9750 : {
9751 4 : test_tree_cmp_on_constants ();
9752 4 : test_dump ();
9753 4 : test_struct ();
9754 4 : test_array_1 ();
9755 4 : test_get_representative_tree ();
9756 4 : test_unique_constants ();
9757 4 : test_unique_unknowns ();
9758 4 : test_initial_svalue_folding ();
9759 4 : test_unaryop_svalue_folding ();
9760 4 : test_binop_svalue_folding ();
9761 4 : test_descendent_of_p ();
9762 4 : test_bit_range_regions ();
9763 4 : test_assignment ();
9764 4 : test_compound_assignment ();
9765 4 : test_stack_frames ();
9766 4 : test_get_representative_path_var ();
9767 4 : test_equality_1 ();
9768 4 : test_canonicalization_2 ();
9769 4 : test_canonicalization_3 ();
9770 4 : test_canonicalization_4 ();
9771 4 : test_state_merging ();
9772 4 : test_constraint_merging ();
9773 4 : test_widening_constraints ();
9774 4 : test_iteration_1 ();
9775 4 : test_malloc_constraints ();
9776 4 : test_var ();
9777 4 : test_array_2 ();
9778 4 : test_mem_ref ();
9779 4 : test_POINTER_PLUS_EXPR_then_MEM_REF ();
9780 4 : test_malloc ();
9781 4 : test_alloca ();
9782 4 : test_involves_p ();
9783 4 : test_array_in_struct ();
9784 4 : test_maybe_get_region_for_mem_range ();
9785 4 : }
9786 :
9787 : } // namespace selftest
9788 :
9789 : #endif /* CHECKING_P */
9790 :
9791 : } // namespace ana
9792 :
9793 : #endif /* #if ENABLE_ANALYZER */
|