1"""
2Test setting breakpoints using a scripted resolver
3"""
4
5import os
6import lldb
7import lldbsuite.test.lldbutil as lldbutil
8from lldbsuite.test.decorators import *
9from lldbsuite.test.lldbtest import *
10
11
12class TestScriptedResolver(TestBase):
13
14    mydir = TestBase.compute_mydir(__file__)
15
16    NO_DEBUG_INFO_TESTCASE = True
17
18    @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24528")
19    def test_scripted_resolver(self):
20        """Use a scripted resolver to set a by symbol name breakpoint"""
21        self.build()
22        self.do_test()
23
24    @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24528")
25    def test_search_depths(self):
26        """ Make sure we are called at the right depths depending on what we return
27            from __get_depth__"""
28        self.build()
29        self.do_test_depths()
30
31    @expectedFailureAll(oslist=["windows"], bugnumber="llvm.org/pr24528")
32    def test_command_line(self):
33        """ Test setting a resolver breakpoint from the command line """
34        self.build()
35        self.do_test_cli()
36
37    def test_bad_command_lines(self):
38        """Make sure we get appropriate errors when we give invalid key/value
39           options"""
40        self.build()
41        self.do_test_bad_options()
42
43    def test_copy_from_dummy_target(self):
44        """Make sure we don't crash during scripted breakpoint copy from dummy target"""
45        self.build()
46        self.do_test_copy_from_dummy_target()
47
48    def make_target_and_import(self):
49        target = self.make_target()
50        self.import_resolver_script()
51        return target
52
53    def make_target(self):
54        return lldbutil.run_to_breakpoint_make_target(self)
55
56    def import_resolver_script(self):
57        interp = self.dbg.GetCommandInterpreter()
58        error = lldb.SBError()
59
60        script_name = os.path.join(self.getSourceDir(), "resolver.py")
61        source_name = os.path.join(self.getSourceDir(), "main.c")
62
63        command = "command script import " + script_name
64        result = lldb.SBCommandReturnObject()
65        interp.HandleCommand(command, result)
66        self.assertTrue(result.Succeeded(), "com scr imp failed: %s"%(result.GetError()))
67
68    def make_extra_args(self):
69        json_string = '{"symbol":"break_on_me", "test1": "value1"}'
70        json_stream = lldb.SBStream()
71        json_stream.Print(json_string)
72        extra_args = lldb.SBStructuredData()
73        error = extra_args.SetFromJSON(json_stream)
74        self.assertSuccess(error, "Error making SBStructuredData")
75        return extra_args
76
77    def do_test(self):
78        """This reads in a python file and sets a breakpoint using it."""
79
80        target = self.make_target_and_import()
81        extra_args = self.make_extra_args()
82
83        file_list = lldb.SBFileSpecList()
84        module_list = lldb.SBFileSpecList()
85
86        # Make breakpoints with this resolver using different filters, first ones that will take:
87        right = []
88        # one with no file or module spec - this one should fire:
89        right.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list))
90
91        # one with the right source file and no module - should also fire:
92        file_list.Append(lldb.SBFileSpec("main.c"))
93        right.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list))
94        # Make sure the help text shows up in the "break list" output:
95        self.expect("break list", substrs=["I am a python breakpoint resolver"], msg="Help is listed in break list")
96
97        # one with the right source file and right module - should also fire:
98        module_list.Append(lldb.SBFileSpec("a.out"))
99        right.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list))
100
101        # And one with no source file but the right module:
102        file_list.Clear()
103        right.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list))
104
105        # Make sure these all got locations:
106        for i in range (0, len(right)):
107            self.assertTrue(right[i].GetNumLocations() >= 1, "Breakpoint %d has no locations."%(i))
108
109        # Now some ones that won't take:
110
111        module_list.Clear()
112        file_list.Clear()
113        wrong = []
114
115        # one with the wrong module - should not fire:
116        module_list.Append(lldb.SBFileSpec("noSuchModule"))
117        wrong.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list))
118
119        # one with the wrong file - also should not fire:
120        file_list.Clear()
121        module_list.Clear()
122        file_list.Append(lldb.SBFileSpec("noFileOfThisName.xxx"))
123        wrong.append(target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list))
124
125        # Now make sure the CU level iteration obeys the file filters:
126        file_list.Clear()
127        module_list.Clear()
128        file_list.Append(lldb.SBFileSpec("no_such_file.xxx"))
129        wrong.append(target.BreakpointCreateFromScript("resolver.ResolverCUDepth", extra_args, module_list, file_list))
130
131        # And the Module filters:
132        file_list.Clear()
133        module_list.Clear()
134        module_list.Append(lldb.SBFileSpec("NoSuchModule.dylib"))
135        wrong.append(target.BreakpointCreateFromScript("resolver.ResolverCUDepth", extra_args, module_list, file_list))
136
137        # Now make sure the Function level iteration obeys the file filters:
138        file_list.Clear()
139        module_list.Clear()
140        file_list.Append(lldb.SBFileSpec("no_such_file.xxx"))
141        wrong.append(target.BreakpointCreateFromScript("resolver.ResolverFuncDepth", extra_args, module_list, file_list))
142
143        # And the Module filters:
144        file_list.Clear()
145        module_list.Clear()
146        module_list.Append(lldb.SBFileSpec("NoSuchModule.dylib"))
147        wrong.append(target.BreakpointCreateFromScript("resolver.ResolverFuncDepth", extra_args, module_list, file_list))
148
149        # Make sure these didn't get locations:
150        for i in range(0, len(wrong)):
151            self.assertEqual(wrong[i].GetNumLocations(), 0, "Breakpoint %d has locations."%(i))
152
153        # Now run to main and ensure we hit the breakpoints we should have:
154
155        lldbutil.run_to_breakpoint_do_run(self, target, right[0])
156
157        # Test the hit counts:
158        for i in range(0, len(right)):
159            self.assertEqual(right[i].GetHitCount(), 1, "Breakpoint %d has the wrong hit count"%(i))
160
161        for i in range(0, len(wrong)):
162            self.assertEqual(wrong[i].GetHitCount(), 0, "Breakpoint %d has the wrong hit count"%(i))
163
164    def do_test_depths(self):
165        """This test uses a class variable in resolver.Resolver which gets set to 1 if we saw
166           compile unit and 2 if we only saw modules.  If the search depth is module, you get passed just
167           the modules with no comp_unit.  If the depth is comp_unit you get comp_units.  So we can use
168           this to test that our callback gets called at the right depth."""
169
170        target = self.make_target_and_import()
171        extra_args = self.make_extra_args()
172
173        file_list = lldb.SBFileSpecList()
174        module_list = lldb.SBFileSpecList()
175        module_list.Append(lldb.SBFileSpec("a.out"))
176
177        # Make a breakpoint that has no __get_depth__, check that that is converted to eSearchDepthModule:
178        bkpt = target.BreakpointCreateFromScript("resolver.Resolver", extra_args, module_list, file_list)
179        self.assertTrue(bkpt.GetNumLocations() > 0, "Resolver got no locations.")
180        self.expect("script print(resolver.Resolver.got_files)", substrs=["2"], msg="Was only passed modules")
181
182        # Make a breakpoint that asks for modules, check that we didn't get any files:
183        bkpt = target.BreakpointCreateFromScript("resolver.ResolverModuleDepth", extra_args, module_list, file_list)
184        self.assertTrue(bkpt.GetNumLocations() > 0, "ResolverModuleDepth got no locations.")
185        self.expect("script print(resolver.Resolver.got_files)", substrs=["2"], msg="Was only passed modules")
186
187        # Make a breakpoint that asks for compile units, check that we didn't get any files:
188        bkpt = target.BreakpointCreateFromScript("resolver.ResolverCUDepth", extra_args, module_list, file_list)
189        self.assertTrue(bkpt.GetNumLocations() > 0, "ResolverCUDepth got no locations.")
190        self.expect("script print(resolver.Resolver.got_files)", substrs=["1"], msg="Was passed compile units")
191
192        # Make a breakpoint that returns a bad value - we should convert that to "modules" so check that:
193        bkpt = target.BreakpointCreateFromScript("resolver.ResolverBadDepth", extra_args, module_list, file_list)
194        self.assertTrue(bkpt.GetNumLocations() > 0, "ResolverBadDepth got no locations.")
195        self.expect("script print(resolver.Resolver.got_files)", substrs=["2"], msg="Was only passed modules")
196
197        # Make a breakpoint that searches at function depth:
198        bkpt = target.BreakpointCreateFromScript("resolver.ResolverFuncDepth", extra_args, module_list, file_list)
199        self.assertTrue(bkpt.GetNumLocations() > 0, "ResolverFuncDepth got no locations.")
200        self.expect("script print(resolver.Resolver.got_files)", substrs=["3"], msg="Was only passed modules")
201        self.expect("script print(resolver.Resolver.func_list)", substrs=['test_func', 'break_on_me', 'main'], msg="Saw all the functions")
202
203    def do_test_cli(self):
204        target = self.make_target_and_import()
205
206        lldbutil.run_break_set_by_script(self, "resolver.Resolver", extra_options="-k symbol -v break_on_me")
207
208        # Make sure setting a resolver breakpoint doesn't pollute further breakpoint setting
209        # by checking the description of a regular file & line breakpoint to make sure it
210        # doesn't mention the Python Resolver function:
211        bkpt_no = lldbutil.run_break_set_by_file_and_line(self, "main.c", 12)
212        bkpt = target.FindBreakpointByID(bkpt_no)
213        strm = lldb.SBStream()
214        bkpt.GetDescription(strm, False)
215        used_resolver = "I am a python breakpoint resolver" in strm.GetData()
216        self.assertFalse(used_resolver, "Found the resolver description in the file & line breakpoint description.")
217
218        # Also make sure the breakpoint was where we expected:
219        bp_loc = bkpt.GetLocationAtIndex(0)
220        bp_sc = bp_loc.GetAddress().GetSymbolContext(lldb.eSymbolContextEverything)
221        bp_se = bp_sc.GetLineEntry()
222        self.assertEqual(bp_se.GetLine(), 12, "Got the right line number")
223        self.assertEqual(bp_se.GetFileSpec().GetFilename(), "main.c", "Got the right filename")
224
225    def do_test_bad_options(self):
226        target = self.make_target_and_import()
227
228        self.expect("break set -P resolver.Resolver -k a_key", error = True, msg="Missing value at end",
229           substrs=['Key: "a_key" missing value'])
230        self.expect("break set -P resolver.Resolver -v a_value", error = True, msg="Missing key at end",
231           substrs=['Value: "a_value" missing matching key'])
232        self.expect("break set -P resolver.Resolver -v a_value -k a_key -v another_value", error = True, msg="Missing key among args",
233           substrs=['Value: "a_value" missing matching key'])
234        self.expect("break set -P resolver.Resolver -k a_key -k a_key -v another_value", error = True, msg="Missing value among args",
235           substrs=['Key: "a_key" missing value'])
236
237    def do_test_copy_from_dummy_target(self):
238        # Import breakpoint scripted resolver.
239        self.import_resolver_script()
240
241        # Create a scripted breakpoint.
242        self.runCmd("breakpoint set -P resolver.Resolver -k symbol -v break_on_me",
243                    BREAKPOINT_CREATED)
244
245        # This is the function to remove breakpoints from the dummy target
246        # to get a clean state for the next test case.
247        def cleanup():
248            self.runCmd('breakpoint delete -D -f', check=False)
249            self.runCmd('breakpoint list', check=False)
250
251        # Execute the cleanup function during test case tear down.
252        self.addTearDownHook(cleanup)
253
254        # Check that target creating doesn't crash.
255        target = self.make_target()
256