1# DExTer : Debugging Experience Tester
2# ~~~~~~   ~         ~~         ~   ~~
3#
4# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5# See https://llvm.org/LICENSE.txt for license information.
6# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7"""Conditional Controller Class for DExTer.-"""
8
9
10import os
11import time
12from collections import defaultdict
13from itertools import chain
14
15from dex.debugger.DebuggerControllers.ControllerHelpers import in_source_file, update_step_watches
16from dex.debugger.DebuggerControllers.DebuggerControllerBase import DebuggerControllerBase
17from dex.debugger.DebuggerBase import DebuggerBase
18from dex.utils.Exceptions import DebuggerException
19
20
21class BreakpointRange:
22    """A range of breakpoints and a set of conditions.
23
24    The leading breakpoint (on line `range_from`) is always active.
25
26    When the leading breakpoint is hit the trailing range should be activated
27    when `expression` evaluates to any value in `values`. If there are no
28    conditions (`expression` is None) then the trailing breakpoint range should
29    always be activated upon hitting the leading breakpoint.
30
31    Args:
32       expression: None for no conditions, or a str expression to compare
33       against `values`.
34
35       hit_count: None for no limit, or int to set the number of times the
36                  leading breakpoint is triggered before it is removed.
37    """
38
39    def __init__(self, expression: str, path: str, range_from: int, range_to: int,
40                 values: list, hit_count: int, finish_on_remove: bool):
41        self.expression = expression
42        self.path = path
43        self.range_from = range_from
44        self.range_to = range_to
45        self.conditional_values = values
46        self.max_hit_count = hit_count
47        self.current_hit_count = 0
48        self.finish_on_remove = finish_on_remove
49
50    def has_conditions(self):
51        return self.expression != None
52
53    def get_conditional_expression_list(self):
54        conditional_list = []
55        for value in self.conditional_values:
56            # (<expression>) == (<value>)
57            conditional_expression = '({}) == ({})'.format(self.expression, value)
58            conditional_list.append(conditional_expression)
59        return conditional_list
60
61    def add_hit(self):
62        self.current_hit_count += 1
63
64    def should_be_removed(self):
65        if self.max_hit_count == None:
66            return False
67        return self.current_hit_count >= self.max_hit_count
68
69
70class ConditionalController(DebuggerControllerBase):
71    def __init__(self, context, step_collection):
72      self.context = context
73      self.step_collection = step_collection
74      self._bp_ranges = None
75      self._build_bp_ranges()
76      self._watches = set()
77      self._step_index = 0
78      self._pause_between_steps = context.options.pause_between_steps
79      self._max_steps = context.options.max_steps
80      # Map {id: BreakpointRange}
81      self._leading_bp_handles = {}
82
83    def _build_bp_ranges(self):
84        commands = self.step_collection.commands
85        self._bp_ranges = []
86        try:
87            limit_commands = commands['DexLimitSteps']
88            for lc in limit_commands:
89                bpr = BreakpointRange(
90                  lc.expression,
91                  lc.path,
92                  lc.from_line,
93                  lc.to_line,
94                  lc.values,
95                  lc.hit_count,
96                  False)
97                self._bp_ranges.append(bpr)
98        except KeyError:
99            raise DebuggerException('Missing DexLimitSteps commands, cannot conditionally step.')
100        if 'DexFinishTest' in commands:
101            finish_commands = commands['DexFinishTest']
102            for ic in finish_commands:
103                bpr = BreakpointRange(
104                  ic.expression,
105                  ic.path,
106                  ic.on_line,
107                  ic.on_line,
108                  ic.values,
109                  ic.hit_count + 1,
110                  True)
111                self._bp_ranges.append(bpr)
112
113    def _set_leading_bps(self):
114        # Set a leading breakpoint for each BreakpointRange, building a
115        # map of {leading bp id: BreakpointRange}.
116        for bpr in self._bp_ranges:
117            if bpr.has_conditions():
118                # Add a conditional breakpoint for each condition.
119                for cond_expr in bpr.get_conditional_expression_list():
120                    id = self.debugger.add_conditional_breakpoint(bpr.path,
121                                                                  bpr.range_from,
122                                                                  cond_expr)
123                    self._leading_bp_handles[id] = bpr
124            else:
125                # Add an unconditional breakpoint.
126                id = self.debugger.add_breakpoint(bpr.path, bpr.range_from)
127                self._leading_bp_handles[id] = bpr
128
129    def _run_debugger_custom(self):
130        # TODO: Add conditional and unconditional breakpoint support to dbgeng.
131        if self.debugger.get_name() == 'dbgeng':
132            raise DebuggerException('DexLimitSteps commands are not supported by dbgeng')
133
134        self.step_collection.clear_steps()
135        self._set_leading_bps()
136
137        for command_obj in chain.from_iterable(self.step_collection.commands.values()):
138            self._watches.update(command_obj.get_watches())
139
140        self.debugger.launch()
141        time.sleep(self._pause_between_steps)
142
143        exit_desired = False
144
145        while not self.debugger.is_finished:
146            while self.debugger.is_running:
147                pass
148
149            step_info = self.debugger.get_step_info(self._watches, self._step_index)
150            if step_info.current_frame:
151                self._step_index += 1
152                update_step_watches(step_info, self._watches, self.step_collection.commands)
153                self.step_collection.new_step(self.context, step_info)
154
155            bp_to_delete = []
156            for bp_id in self.debugger.get_triggered_breakpoint_ids():
157                try:
158                    # See if this is one of our leading breakpoints.
159                    bpr = self._leading_bp_handles[bp_id]
160                except KeyError:
161                    # This is a trailing bp. Mark it for removal.
162                    bp_to_delete.append(bp_id)
163                    continue
164
165                bpr.add_hit()
166                if bpr.should_be_removed():
167                    if bpr.finish_on_remove:
168                        exit_desired = True
169                    bp_to_delete.append(bp_id)
170                    del self._leading_bp_handles[bp_id]
171                # Add a range of trailing breakpoints covering the lines
172                # requested in the DexLimitSteps command. Ignore first line as
173                # that's covered by the leading bp we just hit and include the
174                # final line.
175                for line in range(bpr.range_from + 1, bpr.range_to + 1):
176                    self.debugger.add_breakpoint(bpr.path, line)
177
178            # Remove any trailing or expired leading breakpoints we just hit.
179            for bp_id in bp_to_delete:
180                self.debugger.delete_breakpoint(bp_id)
181
182            if exit_desired:
183                break
184            self.debugger.go()
185            time.sleep(self._pause_between_steps)
186