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