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