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