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