1"""
2Test some SBValue APIs.
3"""
4
5from __future__ import print_function
6
7
8import lldb
9from lldbsuite.test.decorators import *
10from lldbsuite.test.lldbtest import *
11from lldbsuite.test import lldbutil
12
13
14class ValueAPITestCase(TestBase):
15
16    mydir = TestBase.compute_mydir(__file__)
17
18    def setUp(self):
19        # Call super's setUp().
20        TestBase.setUp(self)
21        # We'll use the test method name as the exe_name.
22        self.exe_name = self.testMethodName
23        # Find the line number to of function 'c'.
24        self.line = line_number('main.c', '// Break at this line')
25
26    @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24772")
27    @add_test_categories(['pyapi'])
28    def test(self):
29        """Exercise some SBValue APIs."""
30        d = {'EXE': self.exe_name}
31        self.build(dictionary=d)
32        self.setTearDownCleanup(dictionary=d)
33        exe = self.getBuildArtifact(self.exe_name)
34
35        # Create a target by the debugger.
36        target = self.dbg.CreateTarget(exe)
37        self.assertTrue(target, VALID_TARGET)
38
39        # Create the breakpoint inside function 'main'.
40        breakpoint = target.BreakpointCreateByLocation('main.c', self.line)
41        self.assertTrue(breakpoint, VALID_BREAKPOINT)
42
43        # Now launch the process, and do not stop at entry point.
44        process = target.LaunchSimple(
45            None, None, self.get_process_working_directory())
46        self.assertTrue(process, PROCESS_IS_VALID)
47
48        # Get Frame #0.
49        self.assertTrue(process.GetState() == lldb.eStateStopped)
50        thread = lldbutil.get_stopped_thread(
51            process, lldb.eStopReasonBreakpoint)
52        self.assertTrue(
53            thread.IsValid(),
54            "There should be a thread stopped due to breakpoint condition")
55        frame0 = thread.GetFrameAtIndex(0)
56
57        # Get global variable 'days_of_week'.
58        list = target.FindGlobalVariables('days_of_week', 1)
59        days_of_week = list.GetValueAtIndex(0)
60        self.assertTrue(days_of_week, VALID_VARIABLE)
61        self.assertEqual(days_of_week.GetNumChildren(), 7, VALID_VARIABLE)
62        self.DebugSBValue(days_of_week)
63
64        # Use this to test the "child" and "children" accessors:
65        children = days_of_week.children
66        self.assertEqual(len(children), 7, VALID_VARIABLE)
67        for i in range(0, len(children)):
68            day = days_of_week.child[i]
69            list_day = children[i]
70            self.assertNotEqual(day, None)
71            self.assertNotEqual(list_day, None)
72            self.assertEqual(day.GetSummary(), list_day.GetSummary(), VALID_VARIABLE)
73
74        # Spot check the actual value:
75        first_day = days_of_week.child[1]
76        self.assertEqual(first_day.GetSummary(), '"Monday"', VALID_VARIABLE)
77
78        # Get global variable 'weekdays'.
79        list = target.FindGlobalVariables('weekdays', 1)
80        weekdays = list.GetValueAtIndex(0)
81        self.assertTrue(weekdays, VALID_VARIABLE)
82        self.assertTrue(weekdays.GetNumChildren() == 5, VALID_VARIABLE)
83        self.DebugSBValue(weekdays)
84
85        # Get global variable 'g_table'.
86        list = target.FindGlobalVariables('g_table', 1)
87        g_table = list.GetValueAtIndex(0)
88        self.assertTrue(g_table, VALID_VARIABLE)
89        self.assertTrue(g_table.GetNumChildren() == 2, VALID_VARIABLE)
90        self.DebugSBValue(g_table)
91
92        fmt = lldbutil.BasicFormatter()
93        cvf = lldbutil.ChildVisitingFormatter(indent_child=2)
94        rdf = lldbutil.RecursiveDecentFormatter(indent_child=2)
95        if self.TraceOn():
96            print(fmt.format(days_of_week))
97            print(cvf.format(days_of_week))
98            print(cvf.format(weekdays))
99            print(rdf.format(g_table))
100
101        # Get variable 'my_int_ptr'.
102        value = frame0.FindVariable('my_int_ptr')
103        self.assertTrue(value, VALID_VARIABLE)
104        self.DebugSBValue(value)
105
106        # Get what 'my_int_ptr' points to.
107        pointed = value.GetChildAtIndex(0)
108        self.assertTrue(pointed, VALID_VARIABLE)
109        self.DebugSBValue(pointed)
110
111        # While we are at it, verify that 'my_int_ptr' points to 'g_my_int'.
112        symbol = target.ResolveLoadAddress(
113            int(pointed.GetLocation(), 0)).GetSymbol()
114        self.assertTrue(symbol)
115        self.expect(symbol.GetName(), exe=False,
116                    startstr='g_my_int')
117
118        # Get variable 'str_ptr'.
119        value = frame0.FindVariable('str_ptr')
120        self.assertTrue(value, VALID_VARIABLE)
121        self.DebugSBValue(value)
122
123        # SBValue::TypeIsPointerType() should return true.
124        self.assertTrue(value.TypeIsPointerType())
125
126        # Verify the SBValue::GetByteSize() API is working correctly.
127        arch = self.getArchitecture()
128        if arch == 'i386':
129            self.assertTrue(value.GetByteSize() == 4)
130        elif arch == 'x86_64':
131            self.assertTrue(value.GetByteSize() == 8)
132
133        # Get child at index 5 => 'Friday'.
134        child = value.GetChildAtIndex(5, lldb.eNoDynamicValues, True)
135        self.assertTrue(child, VALID_VARIABLE)
136        self.DebugSBValue(child)
137
138        self.expect(child.GetSummary(), exe=False,
139                    substrs=['Friday'])
140
141        # Now try to get at the same variable using GetValueForExpressionPath().
142        # These two SBValue objects should have the same value.
143        val2 = value.GetValueForExpressionPath('[5]')
144        self.assertTrue(val2, VALID_VARIABLE)
145        self.DebugSBValue(val2)
146        self.assertTrue(child.GetValue() == val2.GetValue() and
147                        child.GetSummary() == val2.GetSummary())
148
149        val_i = target.EvaluateExpression('i')
150        val_s = target.EvaluateExpression('s')
151        val_a = target.EvaluateExpression('a')
152        self.assertTrue(
153            val_s.GetChildMemberWithName('a').GetAddress().IsValid(),
154            VALID_VARIABLE)
155        self.assertTrue(
156            val_s.GetChildMemberWithName('a').AddressOf(),
157            VALID_VARIABLE)
158        self.assertTrue(
159            val_a.Cast(
160                val_i.GetType()).AddressOf(),
161            VALID_VARIABLE)
162
163        # Check that lldb.value implements truth testing.
164        self.assertFalse(lldb.value(frame0.FindVariable('bogus')))
165        self.assertTrue(lldb.value(frame0.FindVariable('uinthex')))
166
167        self.assertTrue(int(lldb.value(frame0.FindVariable('uinthex')))
168                        == 3768803088, 'uinthex == 3768803088')
169        self.assertTrue(int(lldb.value(frame0.FindVariable('sinthex')))
170                        == -526164208, 'sinthex == -526164208')
171
172        # Check value_iter works correctly.
173        for v in [
174                lldb.value(frame0.FindVariable('uinthex')),
175                lldb.value(frame0.FindVariable('sinthex'))
176        ]:
177            self.assertTrue(v)
178
179        self.assertTrue(
180            frame0.FindVariable('uinthex').GetValueAsUnsigned() == 3768803088,
181            'unsigned uinthex == 3768803088')
182        self.assertTrue(
183            frame0.FindVariable('sinthex').GetValueAsUnsigned() == 3768803088,
184            'unsigned sinthex == 3768803088')
185
186        self.assertTrue(
187            frame0.FindVariable('uinthex').GetValueAsSigned() == -
188            526164208,
189            'signed uinthex == -526164208')
190        self.assertTrue(
191            frame0.FindVariable('sinthex').GetValueAsSigned() == -
192            526164208,
193            'signed sinthex == -526164208')
194