aboutsummaryrefslogtreecommitdiff
path: root/packages/Python/lldbsuite/test/lang/c/register_variables/TestRegisterVariables.py
blob: 1f3ae3ffcb591ed707a89921e078d25ea639743a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
"""Check that compiler-generated register values work correctly"""

from __future__ import print_function

import os
import time
import re
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil

# This method attempts to figure out if a given variable
# is in a register.
#
# Return:
#   True if the value has a readable value and is in a register
#   False otherwise


def is_variable_in_register(frame, var_name):
    # Ensure we can lookup the variable.
    var = frame.FindVariable(var_name)
    # print("\nchecking {}...".format(var_name))
    if var is None or not var.IsValid():
        # print("{} cannot be found".format(var_name))
        return False

    # Check that we can get its value.  If not, this
    # may be a variable that is just out of scope at this point.
    value = var.GetValue()
    # print("checking value...")
    if value is None:
        # print("value is invalid")
        return False
    # else:
        # print("value is {}".format(value))

    # We have a variable and we can get its value.  The variable is in
    # a register if we cannot get an address for it, assuming it is
    # not a struct pointer.  (This is an approximation - compilers can
    # do other things with spitting up a value into multiple parts of
    # multiple registers, but what we're verifying here is much more
    # than it was doing before).
    var_addr = var.GetAddress()
    # print("checking address...")
    if var_addr.IsValid():
        # We have an address, it must not be in a register.
        # print("var {} is not in a register: has a valid address {}".format(var_name, var_addr))
        return False
    else:
        # We don't have an address but we can read the value.
        # It is likely stored in a register.
        # print("var {} is in a register (we don't have an address for it)".format(var_name))
        return True


def is_struct_pointer_in_register(frame, var_name, trace):
    # Ensure we can lookup the variable.
    var = frame.FindVariable(var_name)
    if trace:
        print("\nchecking {}...".format(var_name))

    if var is None or not var.IsValid():
        # print("{} cannot be found".format(var_name))
        return False

    # Check that we can get its value.  If not, this
    # may be a variable that is just out of scope at this point.
    value = var.GetValue()
    # print("checking value...")
    if value is None:
        if trace:
            print("value is invalid")
        return False
    else:
        if trace:
             print("value is {}".format(value))

    var_loc = var.GetLocation()
    if trace:
        print("checking location: {}".format(var_loc))
    if var_loc is None or var_loc.startswith("0x"):
        # The frame var is not in a register but rather a memory location.
        # print("frame var {} is not in a register".format(var_name))
        return False
    else:
        # print("frame var {} is in a register".format(var_name))
        return True


def re_expr_equals(val_type, val):
    # Match ({val_type}) ${sum_digits} = {val}
    return re.compile(r'\(' + val_type + '\) \$\d+ = ' + str(val))


class RegisterVariableTestCase(TestBase):

    mydir = TestBase.compute_mydir(__file__)

    @expectedFailureAll(compiler="clang", compiler_version=['<', '3.5'])
    @expectedFailureAll(compiler="gcc", compiler_version=[
            '>=', '4.8.2'], archs=["i386"])
    @expectedFailureAll(compiler="gcc", compiler_version=[
            '<', '4.9'], archs=["x86_64"])
    def test_and_run_command(self):
        """Test expressions on register values."""

        # This test now ensures that each probable
        # register variable location is actually a register, and
        # if so, whether we can print out the variable there.
        # It only requires one of them to be handled in a non-error
        # way.
        register_variables_count = 0

        self.build()
        exe = os.path.join(os.getcwd(), "a.out")
        self.runCmd("file " + exe, CURRENT_EXECUTABLE_SET)

        # Break inside the main.
        lldbutil.run_break_set_by_source_regexp(
            self, "break", num_expected_locations=3)

        ####################
        # First breakpoint

        self.runCmd("run", RUN_SUCCEEDED)

        # The stop reason of the thread should be breakpoint.
        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
                    substrs=['stopped',
                             'stop reason = breakpoint'])

        # The breakpoint should have a hit count of 1.
        self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
                    substrs=[' resolved, hit count = 1'])

        # Try some variables that should be visible
        frame = self.dbg.GetSelectedTarget().GetProcess(
        ).GetSelectedThread().GetSelectedFrame()
        if is_variable_in_register(frame, 'a'):
            register_variables_count += 1
            self.expect("expr a", VARIABLES_DISPLAYED_CORRECTLY,
                        patterns=[re_expr_equals('int', 2)])

        if is_struct_pointer_in_register(frame, 'b', self.TraceOn()):
            register_variables_count += 1
            self.expect("expr b->m1", VARIABLES_DISPLAYED_CORRECTLY,
                        patterns=[re_expr_equals('int', 3)])

        #####################
        # Second breakpoint

        self.runCmd("continue")

        # The stop reason of the thread should be breakpoint.
        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
                    substrs=['stopped',
                             'stop reason = breakpoint'])

        # The breakpoint should have a hit count of 1.
        self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
                    substrs=[' resolved, hit count = 1'])

        # Try some variables that should be visible
        frame = self.dbg.GetSelectedTarget().GetProcess(
        ).GetSelectedThread().GetSelectedFrame()
        if is_struct_pointer_in_register(frame, 'b', self.TraceOn()):
            register_variables_count += 1
            self.expect("expr b->m2", VARIABLES_DISPLAYED_CORRECTLY,
                        patterns=[re_expr_equals('int', 5)])

        if is_variable_in_register(frame, 'c'):
            register_variables_count += 1
            self.expect("expr c", VARIABLES_DISPLAYED_CORRECTLY,
                        patterns=[re_expr_equals('int', 5)])

        #####################
        # Third breakpoint

        self.runCmd("continue")

        # The stop reason of the thread should be breakpoint.
        self.expect("thread list", STOPPED_DUE_TO_BREAKPOINT,
                    substrs=['stopped',
                             'stop reason = breakpoint'])

        # The breakpoint should have a hit count of 1.
        self.expect("breakpoint list -f", BREAKPOINT_HIT_ONCE,
                    substrs=[' resolved, hit count = 1'])

        # Try some variables that should be visible
        frame = self.dbg.GetSelectedTarget().GetProcess(
        ).GetSelectedThread().GetSelectedFrame()
        if is_variable_in_register(frame, 'f'):
            register_variables_count += 1
            self.expect("expr f", VARIABLES_DISPLAYED_CORRECTLY,
                        patterns=[re_expr_equals('float', '3.1')])

        # Validate that we verified at least one register variable
        self.assertTrue(
            register_variables_count > 0,
            "expected to verify at least one variable in a register")
        # print("executed {} expressions with values in registers".format(register_variables_count))

        self.runCmd("kill")