• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""
2Test case for testing the gdbremote protocol.
3
4Tests run against debugserver and lldb-server (llgs).
5lldb-server tests run where the lldb-server exe is
6available.
7
8This class will be broken into smaller test case classes by
9gdb remote packet functional areas.  For now it contains
10the initial set of tests implemented.
11"""
12
13import unittest2
14import gdbremote_testcase
15import lldbgdbserverutils
16from lldbsuite.support import seven
17from lldbsuite.test.decorators import *
18from lldbsuite.test.lldbtest import *
19from lldbsuite.test.lldbdwarf import *
20from lldbsuite.test import lldbutil
21
22
23class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase, DwarfOpcodeParser):
24
25    mydir = TestBase.compute_mydir(__file__)
26
27    @debugserver_test
28    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
29    def test_exe_starts_debugserver(self):
30        self.init_debugserver_test()
31        server = self.connect_to_debug_monitor()
32
33    @llgs_test
34    def test_exe_starts_llgs(self):
35        self.init_llgs_test()
36        server = self.connect_to_debug_monitor()
37
38    def thread_suffix_supported(self):
39        server = self.connect_to_debug_monitor()
40        self.assertIsNotNone(server)
41
42        self.add_no_ack_remote_stream()
43        self.test_sequence.add_log_lines(
44            ["lldb-server <  26> read packet: $QThreadSuffixSupported#e4",
45             "lldb-server <   6> send packet: $OK#9a"],
46            True)
47
48        self.expect_gdbremote_sequence()
49
50    @debugserver_test
51    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
52    def test_thread_suffix_supported_debugserver(self):
53        self.init_debugserver_test()
54        self.thread_suffix_supported()
55
56    @llgs_test
57    def test_thread_suffix_supported_llgs(self):
58        self.init_llgs_test()
59        self.thread_suffix_supported()
60
61    def list_threads_in_stop_reply_supported(self):
62        server = self.connect_to_debug_monitor()
63        self.assertIsNotNone(server)
64
65        self.add_no_ack_remote_stream()
66        self.test_sequence.add_log_lines(
67            ["lldb-server <  27> read packet: $QListThreadsInStopReply#21",
68             "lldb-server <   6> send packet: $OK#9a"],
69            True)
70        self.expect_gdbremote_sequence()
71
72    @debugserver_test
73    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
74    def test_list_threads_in_stop_reply_supported_debugserver(self):
75        self.init_debugserver_test()
76        self.list_threads_in_stop_reply_supported()
77
78    @llgs_test
79    def test_list_threads_in_stop_reply_supported_llgs(self):
80        self.init_llgs_test()
81        self.list_threads_in_stop_reply_supported()
82
83    def c_packet_works(self):
84        procs = self.prep_debug_monitor_and_inferior()
85        self.test_sequence.add_log_lines(
86            ["read packet: $c#63",
87             "send packet: $W00#00"],
88            True)
89
90        self.expect_gdbremote_sequence()
91
92    @debugserver_test
93    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
94    def test_c_packet_works_debugserver(self):
95        self.init_debugserver_test()
96        self.build()
97        self.c_packet_works()
98
99    @llgs_test
100    def test_c_packet_works_llgs(self):
101        self.init_llgs_test()
102        self.build()
103        self.c_packet_works()
104
105    def inferior_print_exit(self):
106        procs = self.prep_debug_monitor_and_inferior(
107                inferior_args=["hello, world"])
108        self.test_sequence.add_log_lines(
109            ["read packet: $vCont;c#a8",
110             {"type": "output_match", "regex": self.maybe_strict_output_regex(r"hello, world\r\n")},
111             "send packet: $W00#00"],
112            True)
113
114        context = self.expect_gdbremote_sequence()
115        self.assertIsNotNone(context)
116
117    @debugserver_test
118    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
119    def test_inferior_print_exit_debugserver(self):
120        self.init_debugserver_test()
121        self.build()
122        self.inferior_print_exit()
123
124    @skipIfWindows # No pty support to test any inferior output
125    @llgs_test
126    @expectedFlakeyLinux("llvm.org/pr25652")
127    def test_inferior_print_exit_llgs(self):
128        self.init_llgs_test()
129        self.build()
130        self.inferior_print_exit()
131
132    def first_launch_stop_reply_thread_matches_first_qC(self):
133        procs = self.prep_debug_monitor_and_inferior()
134        self.test_sequence.add_log_lines(["read packet: $qC#00",
135                                          {"direction": "send",
136                                           "regex": r"^\$QC([0-9a-fA-F]+)#",
137                                           "capture": {1: "thread_id"}},
138                                          "read packet: $?#00",
139                                          {"direction": "send",
140                                              "regex": r"^\$T[0-9a-fA-F]{2}thread:([0-9a-fA-F]+)",
141                                              "expect_captures": {1: "thread_id"}}],
142                                         True)
143        self.expect_gdbremote_sequence()
144
145    @debugserver_test
146    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
147    def test_first_launch_stop_reply_thread_matches_first_qC_debugserver(self):
148        self.init_debugserver_test()
149        self.build()
150        self.first_launch_stop_reply_thread_matches_first_qC()
151
152    @llgs_test
153    def test_first_launch_stop_reply_thread_matches_first_qC_llgs(self):
154        self.init_llgs_test()
155        self.build()
156        self.first_launch_stop_reply_thread_matches_first_qC()
157
158    def attach_commandline_continue_app_exits(self):
159        procs = self.prep_debug_monitor_and_inferior()
160        self.test_sequence.add_log_lines(
161            ["read packet: $vCont;c#a8",
162             "send packet: $W00#00"],
163            True)
164        self.expect_gdbremote_sequence()
165
166        # Wait a moment for completed and now-detached inferior process to
167        # clear.
168        time.sleep(1)
169
170        if not lldb.remote_platform:
171            # Process should be dead now. Reap results.
172            poll_result = procs["inferior"].poll()
173            self.assertIsNotNone(poll_result)
174
175        # Where possible, verify at the system level that the process is not
176        # running.
177        self.assertFalse(
178            lldbgdbserverutils.process_is_running(
179                procs["inferior"].pid, False))
180
181    @debugserver_test
182    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
183    def test_attach_commandline_continue_app_exits_debugserver(self):
184        self.init_debugserver_test()
185        self.build()
186        self.set_inferior_startup_attach()
187        self.attach_commandline_continue_app_exits()
188
189    @llgs_test
190    def test_attach_commandline_continue_app_exits_llgs(self):
191        self.init_llgs_test()
192        self.build()
193        self.set_inferior_startup_attach()
194        self.attach_commandline_continue_app_exits()
195
196    def qRegisterInfo_returns_one_valid_result(self):
197        self.prep_debug_monitor_and_inferior()
198        self.test_sequence.add_log_lines(
199            ["read packet: $qRegisterInfo0#00",
200             {"direction": "send", "regex": r"^\$(.+);#[0-9A-Fa-f]{2}", "capture": {1: "reginfo_0"}}],
201            True)
202
203        # Run the stream
204        context = self.expect_gdbremote_sequence()
205        self.assertIsNotNone(context)
206
207        reg_info_packet = context.get("reginfo_0")
208        self.assertIsNotNone(reg_info_packet)
209        self.assert_valid_reg_info(
210            lldbgdbserverutils.parse_reg_info_response(reg_info_packet))
211
212    @debugserver_test
213    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
214    def test_qRegisterInfo_returns_one_valid_result_debugserver(self):
215        self.init_debugserver_test()
216        self.build()
217        self.qRegisterInfo_returns_one_valid_result()
218
219    @llgs_test
220    def test_qRegisterInfo_returns_one_valid_result_llgs(self):
221        self.init_llgs_test()
222        self.build()
223        self.qRegisterInfo_returns_one_valid_result()
224
225    def qRegisterInfo_returns_all_valid_results(self):
226        self.prep_debug_monitor_and_inferior()
227        self.add_register_info_collection_packets()
228
229        # Run the stream.
230        context = self.expect_gdbremote_sequence()
231        self.assertIsNotNone(context)
232
233        # Validate that each register info returned validates.
234        for reg_info in self.parse_register_info_packets(context):
235            self.assert_valid_reg_info(reg_info)
236
237    @debugserver_test
238    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
239    def test_qRegisterInfo_returns_all_valid_results_debugserver(self):
240        self.init_debugserver_test()
241        self.build()
242        self.qRegisterInfo_returns_all_valid_results()
243
244    @llgs_test
245    def test_qRegisterInfo_returns_all_valid_results_llgs(self):
246        self.init_llgs_test()
247        self.build()
248        self.qRegisterInfo_returns_all_valid_results()
249
250    def qRegisterInfo_contains_required_generics(self):
251        self.prep_debug_monitor_and_inferior()
252        self.add_register_info_collection_packets()
253
254        # Run the packet stream.
255        context = self.expect_gdbremote_sequence()
256        self.assertIsNotNone(context)
257
258        # Gather register info entries.
259        reg_infos = self.parse_register_info_packets(context)
260
261        # Collect all generic registers found.
262        generic_regs = {
263            reg_info['generic']: 1 for reg_info in reg_infos if 'generic' in reg_info}
264
265        # Ensure we have a program counter register.
266        self.assertTrue('pc' in generic_regs)
267
268        # Ensure we have a frame pointer register. PPC64le's FP is the same as SP
269        if self.getArchitecture() != 'powerpc64le':
270            self.assertTrue('fp' in generic_regs)
271
272        # Ensure we have a stack pointer register.
273        self.assertTrue('sp' in generic_regs)
274
275        # Ensure we have a flags register.
276        self.assertTrue('flags' in generic_regs)
277
278    @debugserver_test
279    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
280    def test_qRegisterInfo_contains_required_generics_debugserver(self):
281        self.init_debugserver_test()
282        self.build()
283        self.qRegisterInfo_contains_required_generics()
284
285    @llgs_test
286    def test_qRegisterInfo_contains_required_generics_llgs(self):
287        self.init_llgs_test()
288        self.build()
289        self.qRegisterInfo_contains_required_generics()
290
291    def qRegisterInfo_contains_at_least_one_register_set(self):
292        self.prep_debug_monitor_and_inferior()
293        self.add_register_info_collection_packets()
294
295        # Run the packet stream.
296        context = self.expect_gdbremote_sequence()
297        self.assertIsNotNone(context)
298
299        # Gather register info entries.
300        reg_infos = self.parse_register_info_packets(context)
301
302        # Collect all register sets found.
303        register_sets = {
304            reg_info['set']: 1 for reg_info in reg_infos if 'set' in reg_info}
305        self.assertTrue(len(register_sets) >= 1)
306
307    @debugserver_test
308    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
309    def test_qRegisterInfo_contains_at_least_one_register_set_debugserver(
310            self):
311        self.init_debugserver_test()
312        self.build()
313        self.qRegisterInfo_contains_at_least_one_register_set()
314
315    @llgs_test
316    def test_qRegisterInfo_contains_at_least_one_register_set_llgs(self):
317        self.init_llgs_test()
318        self.build()
319        self.qRegisterInfo_contains_at_least_one_register_set()
320
321    def targetHasAVX(self):
322        triple = self.dbg.GetSelectedPlatform().GetTriple()
323
324        # TODO other platforms, please implement this function
325        if not re.match(".*-.*-linux", triple):
326            return True
327
328        # Need to do something different for non-Linux/Android targets
329        if lldb.remote_platform:
330            self.runCmd('platform get-file "/proc/cpuinfo" "cpuinfo"')
331            cpuinfo_path = "cpuinfo"
332            self.addTearDownHook(lambda: os.unlink("cpuinfo"))
333        else:
334            cpuinfo_path = "/proc/cpuinfo"
335
336        f = open(cpuinfo_path, 'r')
337        cpuinfo = f.read()
338        f.close()
339        return " avx " in cpuinfo
340
341    def qRegisterInfo_contains_avx_registers(self):
342        self.prep_debug_monitor_and_inferior()
343        self.add_register_info_collection_packets()
344
345        # Run the packet stream.
346        context = self.expect_gdbremote_sequence()
347        self.assertIsNotNone(context)
348
349        # Gather register info entries.
350        reg_infos = self.parse_register_info_packets(context)
351
352        # Collect all generics found.
353        register_sets = {
354            reg_info['set']: 1 for reg_info in reg_infos if 'set' in reg_info}
355        self.assertEqual(
356            self.targetHasAVX(),
357            "Advanced Vector Extensions" in register_sets)
358
359    @expectedFailureAll(oslist=["windows"]) # no avx for now.
360    @expectedFailureAll(oslist=["netbsd"])
361    @llgs_test
362    def test_qRegisterInfo_contains_avx_registers_llgs(self):
363        self.init_llgs_test()
364        self.build()
365        self.qRegisterInfo_contains_avx_registers()
366
367    def qThreadInfo_contains_thread(self):
368        procs = self.prep_debug_monitor_and_inferior()
369        self.add_threadinfo_collection_packets()
370
371        # Run the packet stream.
372        context = self.expect_gdbremote_sequence()
373        self.assertIsNotNone(context)
374
375        # Gather threadinfo entries.
376        threads = self.parse_threadinfo_packets(context)
377        self.assertIsNotNone(threads)
378
379        # We should have exactly one thread.
380        self.assertEqual(len(threads), 1)
381
382    @debugserver_test
383    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
384    def test_qThreadInfo_contains_thread_launch_debugserver(self):
385        self.init_debugserver_test()
386        self.build()
387        self.set_inferior_startup_launch()
388        self.qThreadInfo_contains_thread()
389
390    @llgs_test
391    def test_qThreadInfo_contains_thread_launch_llgs(self):
392        self.init_llgs_test()
393        self.build()
394        self.set_inferior_startup_launch()
395        self.qThreadInfo_contains_thread()
396
397    @debugserver_test
398    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
399    def test_qThreadInfo_contains_thread_attach_debugserver(self):
400        self.init_debugserver_test()
401        self.build()
402        self.set_inferior_startup_attach()
403        self.qThreadInfo_contains_thread()
404
405    @expectedFailureAll(oslist=["windows"]) # expect one more thread stopped
406    @llgs_test
407    def test_qThreadInfo_contains_thread_attach_llgs(self):
408        self.init_llgs_test()
409        self.build()
410        self.set_inferior_startup_attach()
411        self.qThreadInfo_contains_thread()
412
413    def qThreadInfo_matches_qC(self):
414        procs = self.prep_debug_monitor_and_inferior()
415
416        self.add_threadinfo_collection_packets()
417        self.test_sequence.add_log_lines(
418            ["read packet: $qC#00",
419             {"direction": "send", "regex": r"^\$QC([0-9a-fA-F]+)#", "capture": {1: "thread_id"}}
420             ], True)
421
422        # Run the packet stream.
423        context = self.expect_gdbremote_sequence()
424        self.assertIsNotNone(context)
425
426        # Gather threadinfo entries.
427        threads = self.parse_threadinfo_packets(context)
428        self.assertIsNotNone(threads)
429
430        # We should have exactly one thread from threadinfo.
431        self.assertEqual(len(threads), 1)
432
433        # We should have a valid thread_id from $QC.
434        QC_thread_id_hex = context.get("thread_id")
435        self.assertIsNotNone(QC_thread_id_hex)
436        QC_thread_id = int(QC_thread_id_hex, 16)
437
438        # Those two should be the same.
439        self.assertEqual(threads[0], QC_thread_id)
440
441    @debugserver_test
442    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
443    def test_qThreadInfo_matches_qC_launch_debugserver(self):
444        self.init_debugserver_test()
445        self.build()
446        self.set_inferior_startup_launch()
447        self.qThreadInfo_matches_qC()
448
449    @llgs_test
450    def test_qThreadInfo_matches_qC_launch_llgs(self):
451        self.init_llgs_test()
452        self.build()
453        self.set_inferior_startup_launch()
454        self.qThreadInfo_matches_qC()
455
456    @debugserver_test
457    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
458    def test_qThreadInfo_matches_qC_attach_debugserver(self):
459        self.init_debugserver_test()
460        self.build()
461        self.set_inferior_startup_attach()
462        self.qThreadInfo_matches_qC()
463
464    @expectedFailureAll(oslist=["windows"]) # expect one more thread stopped
465    @llgs_test
466    def test_qThreadInfo_matches_qC_attach_llgs(self):
467        self.init_llgs_test()
468        self.build()
469        self.set_inferior_startup_attach()
470        self.qThreadInfo_matches_qC()
471
472    def p_returns_correct_data_size_for_each_qRegisterInfo(self):
473        procs = self.prep_debug_monitor_and_inferior()
474        self.add_register_info_collection_packets()
475
476        # Run the packet stream.
477        context = self.expect_gdbremote_sequence()
478        self.assertIsNotNone(context)
479
480        # Gather register info entries.
481        reg_infos = self.parse_register_info_packets(context)
482        self.assertIsNotNone(reg_infos)
483        self.assertTrue(len(reg_infos) > 0)
484
485        byte_order = self.get_target_byte_order()
486
487        # Read value for each register.
488        reg_index = 0
489        for reg_info in reg_infos:
490            # Skip registers that don't have a register set.  For x86, these are
491            # the DRx registers, which have no LLDB-kind register number and thus
492            # cannot be read via normal
493            # NativeRegisterContext::ReadRegister(reg_info,...) calls.
494            if not "set" in reg_info:
495                continue
496
497            # Clear existing packet expectations.
498            self.reset_test_sequence()
499
500            # Run the register query
501            self.test_sequence.add_log_lines(
502                ["read packet: $p{0:x}#00".format(reg_index),
503                 {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}],
504                True)
505            context = self.expect_gdbremote_sequence()
506            self.assertIsNotNone(context)
507
508            # Verify the response length.
509            p_response = context.get("p_response")
510            self.assertIsNotNone(p_response)
511
512            # Skip erraneous (unsupported) registers.
513            # TODO: remove this once we make unsupported registers disappear.
514            if p_response.startswith("E") and len(p_response) == 3:
515                continue
516
517            if "dynamic_size_dwarf_expr_bytes" in reg_info:
518                self.updateRegInfoBitsize(reg_info, byte_order)
519            self.assertEqual(len(p_response), 2 * int(reg_info["bitsize"]) / 8,
520                             reg_info)
521
522            # Increment loop
523            reg_index += 1
524
525    @debugserver_test
526    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
527    def test_p_returns_correct_data_size_for_each_qRegisterInfo_launch_debugserver(
528            self):
529        self.init_debugserver_test()
530        self.build()
531        self.set_inferior_startup_launch()
532        self.p_returns_correct_data_size_for_each_qRegisterInfo()
533
534    @expectedFailureAll(oslist=["netbsd"])
535    @llgs_test
536    def test_p_returns_correct_data_size_for_each_qRegisterInfo_launch_llgs(
537            self):
538        self.init_llgs_test()
539        self.build()
540        self.set_inferior_startup_launch()
541        self.p_returns_correct_data_size_for_each_qRegisterInfo()
542
543    @debugserver_test
544    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
545    def test_p_returns_correct_data_size_for_each_qRegisterInfo_attach_debugserver(
546            self):
547        self.init_debugserver_test()
548        self.build()
549        self.set_inferior_startup_attach()
550        self.p_returns_correct_data_size_for_each_qRegisterInfo()
551
552    @expectedFailureAll(oslist=["netbsd"])
553    @llgs_test
554    def test_p_returns_correct_data_size_for_each_qRegisterInfo_attach_llgs(
555            self):
556        self.init_llgs_test()
557        self.build()
558        self.set_inferior_startup_attach()
559        self.p_returns_correct_data_size_for_each_qRegisterInfo()
560
561    def Hg_switches_to_3_threads(self):
562        # Startup the inferior with three threads (main + 2 new ones).
563        procs = self.prep_debug_monitor_and_inferior(
564            inferior_args=["thread:new", "thread:new"])
565
566        # Let the inferior process have a few moments to start up the thread
567        # when launched.  (The launch scenario has no time to run, so threads
568        # won't be there yet.)
569        self.run_process_then_stop(run_seconds=1)
570
571        # Wait at most x seconds for 3 threads to be present.
572        threads = self.wait_for_thread_count(3)
573        self.assertEqual(len(threads), 3)
574
575        # verify we can $H to each thead, and $qC matches the thread we set.
576        for thread in threads:
577            # Change to each thread, verify current thread id.
578            self.reset_test_sequence()
579            self.test_sequence.add_log_lines(
580                ["read packet: $Hg{0:x}#00".format(thread),  # Set current thread.
581                 "send packet: $OK#00",
582                 "read packet: $qC#00",
583                 {"direction": "send", "regex": r"^\$QC([0-9a-fA-F]+)#", "capture": {1: "thread_id"}}],
584                True)
585
586            context = self.expect_gdbremote_sequence()
587            self.assertIsNotNone(context)
588
589            # Verify the thread id.
590            self.assertIsNotNone(context.get("thread_id"))
591            self.assertEqual(int(context.get("thread_id"), 16), thread)
592
593    @debugserver_test
594    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
595    def test_Hg_switches_to_3_threads_launch_debugserver(self):
596        self.init_debugserver_test()
597        self.build()
598        self.set_inferior_startup_launch()
599        self.Hg_switches_to_3_threads()
600
601    @expectedFailureAll(oslist=["windows"]) # expect 4 threads
602    @llgs_test
603    def test_Hg_switches_to_3_threads_launch_llgs(self):
604        self.init_llgs_test()
605        self.build()
606        self.set_inferior_startup_launch()
607        self.Hg_switches_to_3_threads()
608
609    @debugserver_test
610    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
611    def test_Hg_switches_to_3_threads_attach_debugserver(self):
612        self.init_debugserver_test()
613        self.build()
614        self.set_inferior_startup_attach()
615        self.Hg_switches_to_3_threads()
616
617    @expectedFailureAll(oslist=["windows"]) # expecting one more thread
618    @llgs_test
619    def test_Hg_switches_to_3_threads_attach_llgs(self):
620        self.init_llgs_test()
621        self.build()
622        self.set_inferior_startup_attach()
623        self.Hg_switches_to_3_threads()
624
625    def Hc_then_Csignal_signals_correct_thread(self, segfault_signo):
626        # NOTE only run this one in inferior-launched mode: we can't grab inferior stdout when running attached,
627        # and the test requires getting stdout from the exe.
628
629        NUM_THREADS = 3
630
631        # Startup the inferior with three threads (main + NUM_THREADS-1 worker threads).
632        # inferior_args=["thread:print-ids"]
633        inferior_args = ["thread:segfault"]
634        for i in range(NUM_THREADS - 1):
635            # if i > 0:
636                # Give time between thread creation/segfaulting for the handler to work.
637                # inferior_args.append("sleep:1")
638            inferior_args.append("thread:new")
639        inferior_args.append("sleep:10")
640
641        # Launch/attach.  (In our case, this should only ever be launched since
642        # we need inferior stdout/stderr).
643        procs = self.prep_debug_monitor_and_inferior(
644            inferior_args=inferior_args)
645        self.test_sequence.add_log_lines(["read packet: $c#63"], True)
646        context = self.expect_gdbremote_sequence()
647
648        # Let the inferior process have a few moments to start up the thread when launched.
649        # context = self.run_process_then_stop(run_seconds=1)
650
651        # Wait at most x seconds for all threads to be present.
652        # threads = self.wait_for_thread_count(NUM_THREADS)
653        # self.assertEquals(len(threads), NUM_THREADS)
654
655        signaled_tids = {}
656        print_thread_ids = {}
657
658        # Switch to each thread, deliver a signal, and verify signal delivery
659        for i in range(NUM_THREADS - 1):
660            # Run until SIGSEGV comes in.
661            self.reset_test_sequence()
662            self.test_sequence.add_log_lines([{"direction": "send",
663                                               "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);",
664                                               "capture": {1: "signo",
665                                                            2: "thread_id"}}],
666                                             True)
667
668            context = self.expect_gdbremote_sequence()
669            self.assertIsNotNone(context)
670            signo = context.get("signo")
671            self.assertEqual(int(signo, 16), segfault_signo)
672
673            # Ensure we haven't seen this tid yet.
674            thread_id = int(context.get("thread_id"), 16)
675            self.assertFalse(thread_id in signaled_tids)
676            signaled_tids[thread_id] = 1
677
678            # Send SIGUSR1 to the thread that signaled the SIGSEGV.
679            self.reset_test_sequence()
680            self.test_sequence.add_log_lines(
681                [
682                    # Set the continue thread.
683                    # Set current thread.
684                    "read packet: $Hc{0:x}#00".format(thread_id),
685                    "send packet: $OK#00",
686
687                    # Continue sending the signal number to the continue thread.
688                    # The commented out packet is a way to do this same operation without using
689                    # a $Hc (but this test is testing $Hc, so we'll stick with the former).
690                    "read packet: $C{0:x}#00".format(lldbutil.get_signal_number('SIGUSR1')),
691                    # "read packet: $vCont;C{0:x}:{1:x};c#00".format(lldbutil.get_signal_number('SIGUSR1'), thread_id),
692
693                    # FIXME: Linux does not report the thread stop on the delivered signal (SIGUSR1 here).  MacOSX debugserver does.
694                    # But MacOSX debugserver isn't guaranteeing the thread the signal handler runs on, so currently its an XFAIL.
695                    # Need to rectify behavior here.  The linux behavior is more intuitive to me since we're essentially swapping out
696                    # an about-to-be-delivered signal (for which we already sent a stop packet) to a different signal.
697                    # {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} },
698                    #  "read packet: $c#63",
699                    {"type": "output_match", "regex": r"^received SIGUSR1 on thread id: ([0-9a-fA-F]+)\r\nthread ([0-9a-fA-F]+): past SIGSEGV\r\n", "capture": {1: "print_thread_id", 2: "post_handle_thread_id"}},
700                ],
701                True)
702
703            # Run the sequence.
704            context = self.expect_gdbremote_sequence()
705            self.assertIsNotNone(context)
706
707            # Ensure the stop signal is the signal we delivered.
708            # stop_signo = context.get("stop_signo")
709            # self.assertIsNotNone(stop_signo)
710            # self.assertEquals(int(stop_signo,16), lldbutil.get_signal_number('SIGUSR1'))
711
712            # Ensure the stop thread is the thread to which we delivered the signal.
713            # stop_thread_id = context.get("stop_thread_id")
714            # self.assertIsNotNone(stop_thread_id)
715            # self.assertEquals(int(stop_thread_id,16), thread_id)
716
717            # Ensure we haven't seen this thread id yet.  The inferior's
718            # self-obtained thread ids are not guaranteed to match the stub
719            # tids (at least on MacOSX).
720            print_thread_id = context.get("print_thread_id")
721            self.assertIsNotNone(print_thread_id)
722            print_thread_id = int(print_thread_id, 16)
723            self.assertFalse(print_thread_id in print_thread_ids)
724
725            # Now remember this print (i.e. inferior-reflected) thread id and
726            # ensure we don't hit it again.
727            print_thread_ids[print_thread_id] = 1
728
729            # Ensure post signal-handle thread id matches the thread that
730            # initially raised the SIGSEGV.
731            post_handle_thread_id = context.get("post_handle_thread_id")
732            self.assertIsNotNone(post_handle_thread_id)
733            post_handle_thread_id = int(post_handle_thread_id, 16)
734            self.assertEqual(post_handle_thread_id, print_thread_id)
735
736    @expectedFailure
737    @debugserver_test
738    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
739    def test_Hc_then_Csignal_signals_correct_thread_launch_debugserver(self):
740        self.init_debugserver_test()
741        self.build()
742        self.set_inferior_startup_launch()
743        # Darwin debugserver translates some signals like SIGSEGV into some gdb
744        # expectations about fixed signal numbers.
745        self.Hc_then_Csignal_signals_correct_thread(self.TARGET_EXC_BAD_ACCESS)
746
747    @skipIfWindows # no SIGSEGV support
748    @expectedFailureAll(oslist=["freebsd"], bugnumber="llvm.org/pr48419")
749    @expectedFailureNetBSD
750    @llgs_test
751    def test_Hc_then_Csignal_signals_correct_thread_launch_llgs(self):
752        self.init_llgs_test()
753        self.build()
754        self.set_inferior_startup_launch()
755        self.Hc_then_Csignal_signals_correct_thread(
756            lldbutil.get_signal_number('SIGSEGV'))
757
758    def m_packet_reads_memory(self):
759        # This is the memory we will write into the inferior and then ensure we
760        # can read back with $m.
761        MEMORY_CONTENTS = "Test contents 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
762
763        # Start up the inferior.
764        procs = self.prep_debug_monitor_and_inferior(
765            inferior_args=[
766                "set-message:%s" %
767                MEMORY_CONTENTS,
768                "get-data-address-hex:g_message",
769                "sleep:5"])
770
771        # Run the process
772        self.test_sequence.add_log_lines(
773            [
774                # Start running after initial stop.
775                "read packet: $c#63",
776                # Match output line that prints the memory address of the message buffer within the inferior.
777                # Note we require launch-only testing so we can get inferior otuput.
778                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"data address: 0x([0-9a-fA-F]+)\r\n"),
779                 "capture": {1: "message_address"}},
780                # Now stop the inferior.
781                "read packet: {}".format(chr(3)),
782                # And wait for the stop notification.
783                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
784            True)
785
786        # Run the packet stream.
787        context = self.expect_gdbremote_sequence()
788        self.assertIsNotNone(context)
789
790        # Grab the message address.
791        self.assertIsNotNone(context.get("message_address"))
792        message_address = int(context.get("message_address"), 16)
793
794        # Grab contents from the inferior.
795        self.reset_test_sequence()
796        self.test_sequence.add_log_lines(
797            ["read packet: $m{0:x},{1:x}#00".format(message_address, len(MEMORY_CONTENTS)),
798             {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "read_contents"}}],
799            True)
800
801        # Run the packet stream.
802        context = self.expect_gdbremote_sequence()
803        self.assertIsNotNone(context)
804
805        # Ensure what we read from inferior memory is what we wrote.
806        self.assertIsNotNone(context.get("read_contents"))
807        read_contents = seven.unhexlify(context.get("read_contents"))
808        self.assertEqual(read_contents, MEMORY_CONTENTS)
809
810    @debugserver_test
811    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
812    def test_m_packet_reads_memory_debugserver(self):
813        self.init_debugserver_test()
814        self.build()
815        self.set_inferior_startup_launch()
816        self.m_packet_reads_memory()
817
818    @skipIfWindows # No pty support to test any inferior output
819    @llgs_test
820    def test_m_packet_reads_memory_llgs(self):
821        self.init_llgs_test()
822        self.build()
823        self.set_inferior_startup_launch()
824        self.m_packet_reads_memory()
825
826    def qMemoryRegionInfo_is_supported(self):
827        # Start up the inferior.
828        procs = self.prep_debug_monitor_and_inferior()
829
830        # Ask if it supports $qMemoryRegionInfo.
831        self.test_sequence.add_log_lines(
832            ["read packet: $qMemoryRegionInfo#00",
833             "send packet: $OK#00"
834             ], True)
835        self.expect_gdbremote_sequence()
836
837    @debugserver_test
838    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
839    def test_qMemoryRegionInfo_is_supported_debugserver(self):
840        self.init_debugserver_test()
841        self.build()
842        self.set_inferior_startup_launch()
843        self.qMemoryRegionInfo_is_supported()
844
845    @llgs_test
846    @expectedFailureAll(oslist=["freebsd"])
847    def test_qMemoryRegionInfo_is_supported_llgs(self):
848        self.init_llgs_test()
849        self.build()
850        self.set_inferior_startup_launch()
851        self.qMemoryRegionInfo_is_supported()
852
853    def qMemoryRegionInfo_reports_code_address_as_executable(self):
854        # Start up the inferior.
855        procs = self.prep_debug_monitor_and_inferior(
856            inferior_args=["get-code-address-hex:hello", "sleep:5"])
857
858        # Run the process
859        self.test_sequence.add_log_lines(
860            [
861                # Start running after initial stop.
862                "read packet: $c#63",
863                # Match output line that prints the memory address of the message buffer within the inferior.
864                # Note we require launch-only testing so we can get inferior otuput.
865                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"code address: 0x([0-9a-fA-F]+)\r\n"),
866                 "capture": {1: "code_address"}},
867                # Now stop the inferior.
868                "read packet: {}".format(chr(3)),
869                # And wait for the stop notification.
870                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
871            True)
872
873        # Run the packet stream.
874        context = self.expect_gdbremote_sequence()
875        self.assertIsNotNone(context)
876
877        # Grab the code address.
878        self.assertIsNotNone(context.get("code_address"))
879        code_address = int(context.get("code_address"), 16)
880
881        # Grab memory region info from the inferior.
882        self.reset_test_sequence()
883        self.add_query_memory_region_packets(code_address)
884
885        # Run the packet stream.
886        context = self.expect_gdbremote_sequence()
887        self.assertIsNotNone(context)
888        mem_region_dict = self.parse_memory_region_packet(context)
889
890        # Ensure there are no errors reported.
891        self.assertFalse("error" in mem_region_dict)
892
893        # Ensure code address is readable and executable.
894        self.assertTrue("permissions" in mem_region_dict)
895        self.assertTrue("r" in mem_region_dict["permissions"])
896        self.assertTrue("x" in mem_region_dict["permissions"])
897
898        # Ensure the start address and size encompass the address we queried.
899        self.assert_address_within_memory_region(code_address, mem_region_dict)
900
901    @debugserver_test
902    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
903    def test_qMemoryRegionInfo_reports_code_address_as_executable_debugserver(
904            self):
905        self.init_debugserver_test()
906        self.build()
907        self.set_inferior_startup_launch()
908        self.qMemoryRegionInfo_reports_code_address_as_executable()
909
910    @skipIfWindows # No pty support to test any inferior output
911    @expectedFailureAll(oslist=["freebsd"])
912    @llgs_test
913    def test_qMemoryRegionInfo_reports_code_address_as_executable_llgs(self):
914        self.init_llgs_test()
915        self.build()
916        self.set_inferior_startup_launch()
917        self.qMemoryRegionInfo_reports_code_address_as_executable()
918
919    def qMemoryRegionInfo_reports_stack_address_as_readable_writeable(self):
920        # Start up the inferior.
921        procs = self.prep_debug_monitor_and_inferior(
922            inferior_args=["get-stack-address-hex:", "sleep:5"])
923
924        # Run the process
925        self.test_sequence.add_log_lines(
926            [
927                # Start running after initial stop.
928                "read packet: $c#63",
929                # Match output line that prints the memory address of the message buffer within the inferior.
930                # Note we require launch-only testing so we can get inferior otuput.
931                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"stack address: 0x([0-9a-fA-F]+)\r\n"),
932                 "capture": {1: "stack_address"}},
933                # Now stop the inferior.
934                "read packet: {}".format(chr(3)),
935                # And wait for the stop notification.
936                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
937            True)
938
939        # Run the packet stream.
940        context = self.expect_gdbremote_sequence()
941        self.assertIsNotNone(context)
942
943        # Grab the address.
944        self.assertIsNotNone(context.get("stack_address"))
945        stack_address = int(context.get("stack_address"), 16)
946
947        # Grab memory region info from the inferior.
948        self.reset_test_sequence()
949        self.add_query_memory_region_packets(stack_address)
950
951        # Run the packet stream.
952        context = self.expect_gdbremote_sequence()
953        self.assertIsNotNone(context)
954        mem_region_dict = self.parse_memory_region_packet(context)
955
956        # Ensure there are no errors reported.
957        self.assertFalse("error" in mem_region_dict)
958
959        # Ensure address is readable and executable.
960        self.assertTrue("permissions" in mem_region_dict)
961        self.assertTrue("r" in mem_region_dict["permissions"])
962        self.assertTrue("w" in mem_region_dict["permissions"])
963
964        # Ensure the start address and size encompass the address we queried.
965        self.assert_address_within_memory_region(
966            stack_address, mem_region_dict)
967
968    @debugserver_test
969    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
970    def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_debugserver(
971            self):
972        self.init_debugserver_test()
973        self.build()
974        self.set_inferior_startup_launch()
975        self.qMemoryRegionInfo_reports_stack_address_as_readable_writeable()
976
977    @skipIfWindows # No pty support to test any inferior output
978    @expectedFailureAll(oslist=["freebsd"])
979    @llgs_test
980    def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_llgs(
981            self):
982        self.init_llgs_test()
983        self.build()
984        self.set_inferior_startup_launch()
985        self.qMemoryRegionInfo_reports_stack_address_as_readable_writeable()
986
987    def qMemoryRegionInfo_reports_heap_address_as_readable_writeable(self):
988        # Start up the inferior.
989        procs = self.prep_debug_monitor_and_inferior(
990            inferior_args=["get-heap-address-hex:", "sleep:5"])
991
992        # Run the process
993        self.test_sequence.add_log_lines(
994            [
995                # Start running after initial stop.
996                "read packet: $c#63",
997                # Match output line that prints the memory address of the message buffer within the inferior.
998                # Note we require launch-only testing so we can get inferior otuput.
999                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"heap address: 0x([0-9a-fA-F]+)\r\n"),
1000                 "capture": {1: "heap_address"}},
1001                # Now stop the inferior.
1002                "read packet: {}".format(chr(3)),
1003                # And wait for the stop notification.
1004                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
1005            True)
1006
1007        # Run the packet stream.
1008        context = self.expect_gdbremote_sequence()
1009        self.assertIsNotNone(context)
1010
1011        # Grab the address.
1012        self.assertIsNotNone(context.get("heap_address"))
1013        heap_address = int(context.get("heap_address"), 16)
1014
1015        # Grab memory region info from the inferior.
1016        self.reset_test_sequence()
1017        self.add_query_memory_region_packets(heap_address)
1018
1019        # Run the packet stream.
1020        context = self.expect_gdbremote_sequence()
1021        self.assertIsNotNone(context)
1022        mem_region_dict = self.parse_memory_region_packet(context)
1023
1024        # Ensure there are no errors reported.
1025        self.assertFalse("error" in mem_region_dict)
1026
1027        # Ensure address is readable and executable.
1028        self.assertTrue("permissions" in mem_region_dict)
1029        self.assertTrue("r" in mem_region_dict["permissions"])
1030        self.assertTrue("w" in mem_region_dict["permissions"])
1031
1032        # Ensure the start address and size encompass the address we queried.
1033        self.assert_address_within_memory_region(heap_address, mem_region_dict)
1034
1035    @debugserver_test
1036    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1037    def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_debugserver(
1038            self):
1039        self.init_debugserver_test()
1040        self.build()
1041        self.set_inferior_startup_launch()
1042        self.qMemoryRegionInfo_reports_heap_address_as_readable_writeable()
1043
1044    @skipIfWindows # No pty support to test any inferior output
1045    @expectedFailureAll(oslist=["freebsd"])
1046    @llgs_test
1047    def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_llgs(
1048            self):
1049        self.init_llgs_test()
1050        self.build()
1051        self.set_inferior_startup_launch()
1052        self.qMemoryRegionInfo_reports_heap_address_as_readable_writeable()
1053
1054    def breakpoint_set_and_remove_work(self, want_hardware=False):
1055        # Start up the inferior.
1056        procs = self.prep_debug_monitor_and_inferior(
1057            inferior_args=[
1058                "get-code-address-hex:hello",
1059                "sleep:1",
1060                "call-function:hello"])
1061
1062        # Run the process
1063        self.add_register_info_collection_packets()
1064        self.add_process_info_collection_packets()
1065        self.test_sequence.add_log_lines(
1066            [  # Start running after initial stop.
1067                "read packet: $c#63",
1068                # Match output line that prints the memory address of the function call entry point.
1069                # Note we require launch-only testing so we can get inferior otuput.
1070                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"code address: 0x([0-9a-fA-F]+)\r\n"),
1071                 "capture": {1: "function_address"}},
1072                # Now stop the inferior.
1073                "read packet: {}".format(chr(3)),
1074                # And wait for the stop notification.
1075                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
1076            True)
1077
1078        # Run the packet stream.
1079        context = self.expect_gdbremote_sequence()
1080        self.assertIsNotNone(context)
1081
1082        # Gather process info - we need endian of target to handle register
1083        # value conversions.
1084        process_info = self.parse_process_info_response(context)
1085        endian = process_info.get("endian")
1086        self.assertIsNotNone(endian)
1087
1088        # Gather register info entries.
1089        reg_infos = self.parse_register_info_packets(context)
1090        (pc_lldb_reg_index, pc_reg_info) = self.find_pc_reg_info(reg_infos)
1091        self.assertIsNotNone(pc_lldb_reg_index)
1092        self.assertIsNotNone(pc_reg_info)
1093
1094        # Grab the function address.
1095        self.assertIsNotNone(context.get("function_address"))
1096        function_address = int(context.get("function_address"), 16)
1097
1098        # Get current target architecture
1099        target_arch = self.getArchitecture()
1100
1101        # Set the breakpoint.
1102        if (target_arch == "arm") or (target_arch == "aarch64"):
1103            # TODO: Handle case when setting breakpoint in thumb code
1104            BREAKPOINT_KIND = 4
1105        else:
1106            BREAKPOINT_KIND = 1
1107
1108        # Set default packet type to Z0 (software breakpoint)
1109        z_packet_type = 0
1110
1111        # If hardware breakpoint is requested set packet type to Z1
1112        if want_hardware == True:
1113            z_packet_type = 1
1114
1115        self.reset_test_sequence()
1116        self.add_set_breakpoint_packets(
1117            function_address,
1118            z_packet_type,
1119            do_continue=True,
1120            breakpoint_kind=BREAKPOINT_KIND)
1121
1122        # Run the packet stream.
1123        context = self.expect_gdbremote_sequence()
1124        self.assertIsNotNone(context)
1125
1126        # Verify the stop signal reported was the breakpoint signal number.
1127        stop_signo = context.get("stop_signo")
1128        self.assertIsNotNone(stop_signo)
1129        self.assertEqual(int(stop_signo, 16),
1130                         lldbutil.get_signal_number('SIGTRAP'))
1131
1132        # Ensure we did not receive any output.  If the breakpoint was not set, we would
1133        # see output (from a launched process with captured stdio) printing a hello, world message.
1134        # That would indicate the breakpoint didn't take.
1135        self.assertEqual(len(context["O_content"]), 0)
1136
1137        # Verify that the PC for the main thread is where we expect it - right at the breakpoint address.
1138        # This acts as a another validation on the register reading code.
1139        self.reset_test_sequence()
1140        self.test_sequence.add_log_lines(
1141            [
1142                # Print the PC.  This should match the breakpoint address.
1143                "read packet: $p{0:x}#00".format(pc_lldb_reg_index),
1144                # Capture $p results.
1145                {"direction": "send",
1146                 "regex": r"^\$([0-9a-fA-F]+)#",
1147                 "capture": {1: "p_response"}},
1148            ], True)
1149
1150        context = self.expect_gdbremote_sequence()
1151        self.assertIsNotNone(context)
1152
1153        # Verify the PC is where we expect.  Note response is in endianness of
1154        # the inferior.
1155        p_response = context.get("p_response")
1156        self.assertIsNotNone(p_response)
1157
1158        # Convert from target endian to int.
1159        returned_pc = lldbgdbserverutils.unpack_register_hex_unsigned(
1160            endian, p_response)
1161        self.assertEqual(returned_pc, function_address)
1162
1163        # Verify that a breakpoint remove and continue gets us the expected
1164        # output.
1165        self.reset_test_sequence()
1166
1167        # Add breakpoint remove packets
1168        self.add_remove_breakpoint_packets(
1169            function_address,
1170            z_packet_type,
1171            breakpoint_kind=BREAKPOINT_KIND)
1172
1173        self.test_sequence.add_log_lines(
1174            [
1175                # Continue running.
1176                "read packet: $c#63",
1177                # We should now receive the output from the call.
1178                {"type": "output_match", "regex": r"^hello, world\r\n$"},
1179                # And wait for program completion.
1180                {"direction": "send", "regex": r"^\$W00(.*)#[0-9a-fA-F]{2}$"},
1181            ], True)
1182
1183        context = self.expect_gdbremote_sequence()
1184        self.assertIsNotNone(context)
1185
1186    @debugserver_test
1187    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1188    def test_software_breakpoint_set_and_remove_work_debugserver(self):
1189        self.init_debugserver_test()
1190        if self.getArchitecture() == "arm":
1191            # TODO: Handle case when setting breakpoint in thumb code
1192            self.build(dictionary={'CFLAGS_EXTRAS': '-marm'})
1193        else:
1194            self.build()
1195        self.set_inferior_startup_launch()
1196        self.breakpoint_set_and_remove_work(want_hardware=False)
1197
1198    @skipIfWindows # No pty support to test any inferior output
1199    @llgs_test
1200    @expectedFlakeyLinux("llvm.org/pr25652")
1201    def test_software_breakpoint_set_and_remove_work_llgs(self):
1202        self.init_llgs_test()
1203        if self.getArchitecture() == "arm":
1204            # TODO: Handle case when setting breakpoint in thumb code
1205            self.build(dictionary={'CFLAGS_EXTRAS': '-marm'})
1206        else:
1207            self.build()
1208        self.set_inferior_startup_launch()
1209        self.breakpoint_set_and_remove_work(want_hardware=False)
1210
1211    @debugserver_test
1212    @skipUnlessPlatform(oslist=['linux'])
1213    @expectedFailureAndroid
1214    @skipIf(archs=no_match(['arm', 'aarch64']))
1215    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1216    def test_hardware_breakpoint_set_and_remove_work_debugserver(self):
1217        self.init_debugserver_test()
1218        if self.getArchitecture() == "arm":
1219            # TODO: Handle case when setting breakpoint in thumb code
1220            self.build(dictionary={'CFLAGS_EXTRAS': '-marm'})
1221        else:
1222            self.build()
1223        self.set_inferior_startup_launch()
1224        self.breakpoint_set_and_remove_work(want_hardware=True)
1225
1226    @llgs_test
1227    @skipUnlessPlatform(oslist=['linux'])
1228    @skipIf(archs=no_match(['arm', 'aarch64']))
1229    def test_hardware_breakpoint_set_and_remove_work_llgs(self):
1230        self.init_llgs_test()
1231        if self.getArchitecture() == "arm":
1232            # TODO: Handle case when setting breakpoint in thumb code
1233            self.build(dictionary={'CFLAGS_EXTRAS': '-marm'})
1234        else:
1235            self.build()
1236        self.set_inferior_startup_launch()
1237        self.breakpoint_set_and_remove_work(want_hardware=True)
1238
1239    def qSupported_returns_known_stub_features(self):
1240        # Start up the stub and start/prep the inferior.
1241        procs = self.prep_debug_monitor_and_inferior()
1242        self.add_qSupported_packets()
1243
1244        # Run the packet stream.
1245        context = self.expect_gdbremote_sequence()
1246        self.assertIsNotNone(context)
1247
1248        # Retrieve the qSupported features.
1249        supported_dict = self.parse_qSupported_response(context)
1250        self.assertIsNotNone(supported_dict)
1251        self.assertTrue(len(supported_dict) > 0)
1252
1253    @debugserver_test
1254    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1255    def test_qSupported_returns_known_stub_features_debugserver(self):
1256        self.init_debugserver_test()
1257        self.build()
1258        self.set_inferior_startup_launch()
1259        self.qSupported_returns_known_stub_features()
1260
1261    @llgs_test
1262    def test_qSupported_returns_known_stub_features_llgs(self):
1263        self.init_llgs_test()
1264        self.build()
1265        self.set_inferior_startup_launch()
1266        self.qSupported_returns_known_stub_features()
1267
1268    def written_M_content_reads_back_correctly(self):
1269        TEST_MESSAGE = "Hello, memory"
1270
1271        # Start up the stub and start/prep the inferior.
1272        procs = self.prep_debug_monitor_and_inferior(
1273            inferior_args=[
1274                "set-message:xxxxxxxxxxxxxX",
1275                "get-data-address-hex:g_message",
1276                "sleep:1",
1277                "print-message:"])
1278        self.test_sequence.add_log_lines(
1279            [
1280                # Start running after initial stop.
1281                "read packet: $c#63",
1282                # Match output line that prints the memory address of the message buffer within the inferior.
1283                # Note we require launch-only testing so we can get inferior otuput.
1284                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"data address: 0x([0-9a-fA-F]+)\r\n"),
1285                 "capture": {1: "message_address"}},
1286                # Now stop the inferior.
1287                "read packet: {}".format(chr(3)),
1288                # And wait for the stop notification.
1289                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
1290            True)
1291        context = self.expect_gdbremote_sequence()
1292        self.assertIsNotNone(context)
1293
1294        # Grab the message address.
1295        self.assertIsNotNone(context.get("message_address"))
1296        message_address = int(context.get("message_address"), 16)
1297
1298        # Hex-encode the test message, adding null termination.
1299        hex_encoded_message = seven.hexlify(TEST_MESSAGE)
1300
1301        # Write the message to the inferior. Verify that we can read it with the hex-encoded (m)
1302        # and binary (x) memory read packets.
1303        self.reset_test_sequence()
1304        self.test_sequence.add_log_lines(
1305            ["read packet: $M{0:x},{1:x}:{2}#00".format(message_address, len(TEST_MESSAGE), hex_encoded_message),
1306             "send packet: $OK#00",
1307             "read packet: $m{0:x},{1:x}#00".format(message_address, len(TEST_MESSAGE)),
1308             "send packet: ${0}#00".format(hex_encoded_message),
1309             "read packet: $x{0:x},{1:x}#00".format(message_address, len(TEST_MESSAGE)),
1310             "send packet: ${0}#00".format(TEST_MESSAGE),
1311             "read packet: $m{0:x},4#00".format(message_address),
1312             "send packet: ${0}#00".format(hex_encoded_message[0:8]),
1313             "read packet: $x{0:x},4#00".format(message_address),
1314             "send packet: ${0}#00".format(TEST_MESSAGE[0:4]),
1315             "read packet: $c#63",
1316             {"type": "output_match", "regex": r"^message: (.+)\r\n$", "capture": {1: "printed_message"}},
1317             "send packet: $W00#00",
1318             ], True)
1319        context = self.expect_gdbremote_sequence()
1320        self.assertIsNotNone(context)
1321
1322        # Ensure what we read from inferior memory is what we wrote.
1323        printed_message = context.get("printed_message")
1324        self.assertIsNotNone(printed_message)
1325        self.assertEqual(printed_message, TEST_MESSAGE + "X")
1326
1327    @debugserver_test
1328    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1329    def test_written_M_content_reads_back_correctly_debugserver(self):
1330        self.init_debugserver_test()
1331        self.build()
1332        self.set_inferior_startup_launch()
1333        self.written_M_content_reads_back_correctly()
1334
1335    @skipIfWindows # No pty support to test any inferior output
1336    @llgs_test
1337    @expectedFlakeyLinux("llvm.org/pr25652")
1338    def test_written_M_content_reads_back_correctly_llgs(self):
1339        self.init_llgs_test()
1340        self.build()
1341        self.set_inferior_startup_launch()
1342        self.written_M_content_reads_back_correctly()
1343
1344    def P_writes_all_gpr_registers(self):
1345        # Start inferior debug session, grab all register info.
1346        procs = self.prep_debug_monitor_and_inferior(inferior_args=["sleep:2"])
1347        self.add_register_info_collection_packets()
1348        self.add_process_info_collection_packets()
1349
1350        context = self.expect_gdbremote_sequence()
1351        self.assertIsNotNone(context)
1352
1353        # Process register infos.
1354        reg_infos = self.parse_register_info_packets(context)
1355        self.assertIsNotNone(reg_infos)
1356        self.add_lldb_register_index(reg_infos)
1357
1358        # Process endian.
1359        process_info = self.parse_process_info_response(context)
1360        endian = process_info.get("endian")
1361        self.assertIsNotNone(endian)
1362
1363        # Pull out the register infos that we think we can bit flip
1364        # successfully,.
1365        gpr_reg_infos = [
1366            reg_info for reg_info in reg_infos if self.is_bit_flippable_register(reg_info)]
1367        self.assertTrue(len(gpr_reg_infos) > 0)
1368
1369        # Write flipped bit pattern of existing value to each register.
1370        (successful_writes, failed_writes) = self.flip_all_bits_in_each_register_value(
1371            gpr_reg_infos, endian)
1372        self.trace("successful writes: {}, failed writes: {}".format(successful_writes, failed_writes))
1373        self.assertTrue(successful_writes > 0)
1374
1375    # Note: as of this moment, a hefty number of the GPR writes are failing with E32 (everything except rax-rdx, rdi, rsi, rbp).
1376    # Come back to this.  I have the test rigged to verify that at least some
1377    # of the bit-flip writes work.
1378    @debugserver_test
1379    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1380    def test_P_writes_all_gpr_registers_debugserver(self):
1381        self.init_debugserver_test()
1382        self.build()
1383        self.set_inferior_startup_launch()
1384        self.P_writes_all_gpr_registers()
1385
1386    @llgs_test
1387    def test_P_writes_all_gpr_registers_llgs(self):
1388        self.init_llgs_test()
1389        self.build()
1390        self.set_inferior_startup_launch()
1391        self.P_writes_all_gpr_registers()
1392
1393    def P_and_p_thread_suffix_work(self):
1394        # Startup the inferior with three threads.
1395        procs = self.prep_debug_monitor_and_inferior(
1396            inferior_args=["thread:new", "thread:new"])
1397        self.add_thread_suffix_request_packets()
1398        self.add_register_info_collection_packets()
1399        self.add_process_info_collection_packets()
1400
1401        context = self.expect_gdbremote_sequence()
1402        self.assertIsNotNone(context)
1403
1404        process_info = self.parse_process_info_response(context)
1405        self.assertIsNotNone(process_info)
1406        endian = process_info.get("endian")
1407        self.assertIsNotNone(endian)
1408
1409        reg_infos = self.parse_register_info_packets(context)
1410        self.assertIsNotNone(reg_infos)
1411        self.add_lldb_register_index(reg_infos)
1412
1413        reg_index = self.select_modifiable_register(reg_infos)
1414        self.assertIsNotNone(reg_index)
1415        reg_byte_size = int(reg_infos[reg_index]["bitsize"]) // 8
1416        self.assertTrue(reg_byte_size > 0)
1417
1418        # Run the process a bit so threads can start up, and collect register
1419        # info.
1420        context = self.run_process_then_stop(run_seconds=1)
1421        self.assertIsNotNone(context)
1422
1423        # Wait for 3 threads to be present.
1424        threads = self.wait_for_thread_count(3)
1425        self.assertEqual(len(threads), 3)
1426
1427        expected_reg_values = []
1428        register_increment = 1
1429        next_value = None
1430
1431        # Set the same register in each of 3 threads to a different value.
1432        # Verify each one has the unique value.
1433        for thread in threads:
1434            # If we don't have a next value yet, start it with the initial read
1435            # value + 1
1436            if not next_value:
1437                # Read pre-existing register value.
1438                self.reset_test_sequence()
1439                self.test_sequence.add_log_lines(
1440                    ["read packet: $p{0:x};thread:{1:x}#00".format(reg_index, thread),
1441                     {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}},
1442                     ], True)
1443                context = self.expect_gdbremote_sequence()
1444                self.assertIsNotNone(context)
1445
1446                # Set the next value to use for writing as the increment plus
1447                # current value.
1448                p_response = context.get("p_response")
1449                self.assertIsNotNone(p_response)
1450                next_value = lldbgdbserverutils.unpack_register_hex_unsigned(
1451                    endian, p_response)
1452
1453            # Set new value using P and thread suffix.
1454            self.reset_test_sequence()
1455            self.test_sequence.add_log_lines(
1456                [
1457                    "read packet: $P{0:x}={1};thread:{2:x}#00".format(
1458                        reg_index,
1459                        lldbgdbserverutils.pack_register_hex(
1460                            endian,
1461                            next_value,
1462                            byte_size=reg_byte_size),
1463                        thread),
1464                    "send packet: $OK#00",
1465                ],
1466                True)
1467            context = self.expect_gdbremote_sequence()
1468            self.assertIsNotNone(context)
1469
1470            # Save the value we set.
1471            expected_reg_values.append(next_value)
1472
1473            # Increment value for next thread to use (we want them all
1474            # different so we can verify they wrote to each thread correctly
1475            # next.)
1476            next_value += register_increment
1477
1478        # Revisit each thread and verify they have the expected value set for
1479        # the register we wrote.
1480        thread_index = 0
1481        for thread in threads:
1482            # Read pre-existing register value.
1483            self.reset_test_sequence()
1484            self.test_sequence.add_log_lines(
1485                ["read packet: $p{0:x};thread:{1:x}#00".format(reg_index, thread),
1486                 {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}},
1487                 ], True)
1488            context = self.expect_gdbremote_sequence()
1489            self.assertIsNotNone(context)
1490
1491            # Get the register value.
1492            p_response = context.get("p_response")
1493            self.assertIsNotNone(p_response)
1494            read_value = lldbgdbserverutils.unpack_register_hex_unsigned(
1495                endian, p_response)
1496
1497            # Make sure we read back what we wrote.
1498            self.assertEqual(read_value, expected_reg_values[thread_index])
1499            thread_index += 1
1500
1501    # Note: as of this moment, a hefty number of the GPR writes are failing
1502    # with E32 (everything except rax-rdx, rdi, rsi, rbp).
1503    @debugserver_test
1504    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1505    def test_P_and_p_thread_suffix_work_debugserver(self):
1506        self.init_debugserver_test()
1507        self.build()
1508        self.set_inferior_startup_launch()
1509        self.P_and_p_thread_suffix_work()
1510
1511    @skipIfWindows
1512    @llgs_test
1513    def test_P_and_p_thread_suffix_work_llgs(self):
1514        self.init_llgs_test()
1515        self.build()
1516        self.set_inferior_startup_launch()
1517        self.P_and_p_thread_suffix_work()
1518