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, timeout_seconds=self._WAIT_TIMEOUT)
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, timeout_seconds=5)
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(timeout_seconds=self._DEFAULT_TIMEOUT)
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                timeout_seconds=self._DEFAULT_TIMEOUT)
780            self.assertIsNotNone(context)
781
782            # Ensure the stop signal is the signal we delivered.
783            # stop_signo = context.get("stop_signo")
784            # self.assertIsNotNone(stop_signo)
785            # self.assertEquals(int(stop_signo,16), lldbutil.get_signal_number('SIGUSR1'))
786
787            # Ensure the stop thread is the thread to which we delivered the signal.
788            # stop_thread_id = context.get("stop_thread_id")
789            # self.assertIsNotNone(stop_thread_id)
790            # self.assertEquals(int(stop_thread_id,16), thread_id)
791
792            # Ensure we haven't seen this thread id yet.  The inferior's
793            # self-obtained thread ids are not guaranteed to match the stub
794            # tids (at least on MacOSX).
795            print_thread_id = context.get("print_thread_id")
796            self.assertIsNotNone(print_thread_id)
797            print_thread_id = int(print_thread_id, 16)
798            self.assertFalse(print_thread_id in print_thread_ids)
799
800            # Now remember this print (i.e. inferior-reflected) thread id and
801            # ensure we don't hit it again.
802            print_thread_ids[print_thread_id] = 1
803
804            # Ensure post signal-handle thread id matches the thread that
805            # initially raised the SIGSEGV.
806            post_handle_thread_id = context.get("post_handle_thread_id")
807            self.assertIsNotNone(post_handle_thread_id)
808            post_handle_thread_id = int(post_handle_thread_id, 16)
809            self.assertEqual(post_handle_thread_id, print_thread_id)
810
811    @unittest2.expectedFailure()
812    @debugserver_test
813    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
814    def test_Hc_then_Csignal_signals_correct_thread_launch_debugserver(self):
815        self.init_debugserver_test()
816        self.build()
817        self.set_inferior_startup_launch()
818        # Darwin debugserver translates some signals like SIGSEGV into some gdb
819        # expectations about fixed signal numbers.
820        self.Hc_then_Csignal_signals_correct_thread(self.TARGET_EXC_BAD_ACCESS)
821
822    @skipIfWindows # no SIGSEGV support
823    @expectedFailureNetBSD
824    @llgs_test
825    def test_Hc_then_Csignal_signals_correct_thread_launch_llgs(self):
826        self.init_llgs_test()
827        self.build()
828        self.set_inferior_startup_launch()
829        self.Hc_then_Csignal_signals_correct_thread(
830            lldbutil.get_signal_number('SIGSEGV'))
831
832    def m_packet_reads_memory(self):
833        # This is the memory we will write into the inferior and then ensure we
834        # can read back with $m.
835        MEMORY_CONTENTS = "Test contents 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
836
837        # Start up the inferior.
838        procs = self.prep_debug_monitor_and_inferior(
839            inferior_args=[
840                "set-message:%s" %
841                MEMORY_CONTENTS,
842                "get-data-address-hex:g_message",
843                "sleep:5"])
844
845        # Run the process
846        self.test_sequence.add_log_lines(
847            [
848                # Start running after initial stop.
849                "read packet: $c#63",
850                # Match output line that prints the memory address of the message buffer within the inferior.
851                # Note we require launch-only testing so we can get inferior otuput.
852                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"data address: 0x([0-9a-fA-F]+)\r\n"),
853                 "capture": {1: "message_address"}},
854                # Now stop the inferior.
855                "read packet: {}".format(chr(3)),
856                # And wait for the stop notification.
857                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
858            True)
859
860        # Run the packet stream.
861        context = self.expect_gdbremote_sequence()
862        self.assertIsNotNone(context)
863
864        # Grab the message address.
865        self.assertIsNotNone(context.get("message_address"))
866        message_address = int(context.get("message_address"), 16)
867
868        # Grab contents from the inferior.
869        self.reset_test_sequence()
870        self.test_sequence.add_log_lines(
871            ["read packet: $m{0:x},{1:x}#00".format(message_address, len(MEMORY_CONTENTS)),
872             {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "read_contents"}}],
873            True)
874
875        # Run the packet stream.
876        context = self.expect_gdbremote_sequence()
877        self.assertIsNotNone(context)
878
879        # Ensure what we read from inferior memory is what we wrote.
880        self.assertIsNotNone(context.get("read_contents"))
881        read_contents = seven.unhexlify(context.get("read_contents"))
882        self.assertEqual(read_contents, MEMORY_CONTENTS)
883
884    @debugserver_test
885    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
886    def test_m_packet_reads_memory_debugserver(self):
887        self.init_debugserver_test()
888        self.build()
889        self.set_inferior_startup_launch()
890        self.m_packet_reads_memory()
891
892    @skipIfWindows # No pty support to test any inferior output
893    @llgs_test
894    def test_m_packet_reads_memory_llgs(self):
895        self.init_llgs_test()
896        self.build()
897        self.set_inferior_startup_launch()
898        self.m_packet_reads_memory()
899
900    def qMemoryRegionInfo_is_supported(self):
901        # Start up the inferior.
902        procs = self.prep_debug_monitor_and_inferior()
903
904        # Ask if it supports $qMemoryRegionInfo.
905        self.test_sequence.add_log_lines(
906            ["read packet: $qMemoryRegionInfo#00",
907             "send packet: $OK#00"
908             ], True)
909        self.expect_gdbremote_sequence()
910
911    @debugserver_test
912    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
913    def test_qMemoryRegionInfo_is_supported_debugserver(self):
914        self.init_debugserver_test()
915        self.build()
916        self.set_inferior_startup_launch()
917        self.qMemoryRegionInfo_is_supported()
918
919    @llgs_test
920    def test_qMemoryRegionInfo_is_supported_llgs(self):
921        self.init_llgs_test()
922        self.build()
923        self.set_inferior_startup_launch()
924        self.qMemoryRegionInfo_is_supported()
925
926    def qMemoryRegionInfo_reports_code_address_as_executable(self):
927        # Start up the inferior.
928        procs = self.prep_debug_monitor_and_inferior(
929            inferior_args=["get-code-address-hex:hello", "sleep:5"])
930
931        # Run the process
932        self.test_sequence.add_log_lines(
933            [
934                # Start running after initial stop.
935                "read packet: $c#63",
936                # Match output line that prints the memory address of the message buffer within the inferior.
937                # Note we require launch-only testing so we can get inferior otuput.
938                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"code address: 0x([0-9a-fA-F]+)\r\n"),
939                 "capture": {1: "code_address"}},
940                # Now stop the inferior.
941                "read packet: {}".format(chr(3)),
942                # And wait for the stop notification.
943                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
944            True)
945
946        # Run the packet stream.
947        context = self.expect_gdbremote_sequence()
948        self.assertIsNotNone(context)
949
950        # Grab the code address.
951        self.assertIsNotNone(context.get("code_address"))
952        code_address = int(context.get("code_address"), 16)
953
954        # Grab memory region info from the inferior.
955        self.reset_test_sequence()
956        self.add_query_memory_region_packets(code_address)
957
958        # Run the packet stream.
959        context = self.expect_gdbremote_sequence()
960        self.assertIsNotNone(context)
961        mem_region_dict = self.parse_memory_region_packet(context)
962
963        # Ensure there are no errors reported.
964        self.assertFalse("error" in mem_region_dict)
965
966        # Ensure code address is readable and executable.
967        self.assertTrue("permissions" in mem_region_dict)
968        self.assertTrue("r" in mem_region_dict["permissions"])
969        self.assertTrue("x" in mem_region_dict["permissions"])
970
971        # Ensure the start address and size encompass the address we queried.
972        self.assert_address_within_memory_region(code_address, mem_region_dict)
973
974    @debugserver_test
975    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
976    def test_qMemoryRegionInfo_reports_code_address_as_executable_debugserver(
977            self):
978        self.init_debugserver_test()
979        self.build()
980        self.set_inferior_startup_launch()
981        self.qMemoryRegionInfo_reports_code_address_as_executable()
982
983    @skipIfWindows # No pty support to test any inferior output
984    @llgs_test
985    def test_qMemoryRegionInfo_reports_code_address_as_executable_llgs(self):
986        self.init_llgs_test()
987        self.build()
988        self.set_inferior_startup_launch()
989        self.qMemoryRegionInfo_reports_code_address_as_executable()
990
991    def qMemoryRegionInfo_reports_stack_address_as_readable_writeable(self):
992        # Start up the inferior.
993        procs = self.prep_debug_monitor_and_inferior(
994            inferior_args=["get-stack-address-hex:", "sleep:5"])
995
996        # Run the process
997        self.test_sequence.add_log_lines(
998            [
999                # Start running after initial stop.
1000                "read packet: $c#63",
1001                # Match output line that prints the memory address of the message buffer within the inferior.
1002                # Note we require launch-only testing so we can get inferior otuput.
1003                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"stack address: 0x([0-9a-fA-F]+)\r\n"),
1004                 "capture": {1: "stack_address"}},
1005                # Now stop the inferior.
1006                "read packet: {}".format(chr(3)),
1007                # And wait for the stop notification.
1008                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
1009            True)
1010
1011        # Run the packet stream.
1012        context = self.expect_gdbremote_sequence()
1013        self.assertIsNotNone(context)
1014
1015        # Grab the address.
1016        self.assertIsNotNone(context.get("stack_address"))
1017        stack_address = int(context.get("stack_address"), 16)
1018
1019        # Grab memory region info from the inferior.
1020        self.reset_test_sequence()
1021        self.add_query_memory_region_packets(stack_address)
1022
1023        # Run the packet stream.
1024        context = self.expect_gdbremote_sequence()
1025        self.assertIsNotNone(context)
1026        mem_region_dict = self.parse_memory_region_packet(context)
1027
1028        # Ensure there are no errors reported.
1029        self.assertFalse("error" in mem_region_dict)
1030
1031        # Ensure address is readable and executable.
1032        self.assertTrue("permissions" in mem_region_dict)
1033        self.assertTrue("r" in mem_region_dict["permissions"])
1034        self.assertTrue("w" in mem_region_dict["permissions"])
1035
1036        # Ensure the start address and size encompass the address we queried.
1037        self.assert_address_within_memory_region(
1038            stack_address, mem_region_dict)
1039
1040    @debugserver_test
1041    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1042    def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_debugserver(
1043            self):
1044        self.init_debugserver_test()
1045        self.build()
1046        self.set_inferior_startup_launch()
1047        self.qMemoryRegionInfo_reports_stack_address_as_readable_writeable()
1048
1049    @skipIfWindows # No pty support to test any inferior output
1050    @llgs_test
1051    def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_llgs(
1052            self):
1053        self.init_llgs_test()
1054        self.build()
1055        self.set_inferior_startup_launch()
1056        self.qMemoryRegionInfo_reports_stack_address_as_readable_writeable()
1057
1058    def qMemoryRegionInfo_reports_heap_address_as_readable_writeable(self):
1059        # Start up the inferior.
1060        procs = self.prep_debug_monitor_and_inferior(
1061            inferior_args=["get-heap-address-hex:", "sleep:5"])
1062
1063        # Run the process
1064        self.test_sequence.add_log_lines(
1065            [
1066                # Start running after initial stop.
1067                "read packet: $c#63",
1068                # Match output line that prints the memory address of the message buffer within the inferior.
1069                # Note we require launch-only testing so we can get inferior otuput.
1070                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"heap address: 0x([0-9a-fA-F]+)\r\n"),
1071                 "capture": {1: "heap_address"}},
1072                # Now stop the inferior.
1073                "read packet: {}".format(chr(3)),
1074                # And wait for the stop notification.
1075                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
1076            True)
1077
1078        # Run the packet stream.
1079        context = self.expect_gdbremote_sequence()
1080        self.assertIsNotNone(context)
1081
1082        # Grab the address.
1083        self.assertIsNotNone(context.get("heap_address"))
1084        heap_address = int(context.get("heap_address"), 16)
1085
1086        # Grab memory region info from the inferior.
1087        self.reset_test_sequence()
1088        self.add_query_memory_region_packets(heap_address)
1089
1090        # Run the packet stream.
1091        context = self.expect_gdbremote_sequence()
1092        self.assertIsNotNone(context)
1093        mem_region_dict = self.parse_memory_region_packet(context)
1094
1095        # Ensure there are no errors reported.
1096        self.assertFalse("error" in mem_region_dict)
1097
1098        # Ensure address is readable and executable.
1099        self.assertTrue("permissions" in mem_region_dict)
1100        self.assertTrue("r" in mem_region_dict["permissions"])
1101        self.assertTrue("w" in mem_region_dict["permissions"])
1102
1103        # Ensure the start address and size encompass the address we queried.
1104        self.assert_address_within_memory_region(heap_address, mem_region_dict)
1105
1106    @debugserver_test
1107    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1108    def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_debugserver(
1109            self):
1110        self.init_debugserver_test()
1111        self.build()
1112        self.set_inferior_startup_launch()
1113        self.qMemoryRegionInfo_reports_heap_address_as_readable_writeable()
1114
1115    @skipIfWindows # No pty support to test any inferior output
1116    @llgs_test
1117    def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_llgs(
1118            self):
1119        self.init_llgs_test()
1120        self.build()
1121        self.set_inferior_startup_launch()
1122        self.qMemoryRegionInfo_reports_heap_address_as_readable_writeable()
1123
1124    def breakpoint_set_and_remove_work(self, want_hardware=False):
1125        # Start up the inferior.
1126        procs = self.prep_debug_monitor_and_inferior(
1127            inferior_args=[
1128                "get-code-address-hex:hello",
1129                "sleep:1",
1130                "call-function:hello"])
1131
1132        # Run the process
1133        self.add_register_info_collection_packets()
1134        self.add_process_info_collection_packets()
1135        self.test_sequence.add_log_lines(
1136            [  # Start running after initial stop.
1137                "read packet: $c#63",
1138                # Match output line that prints the memory address of the function call entry point.
1139                # Note we require launch-only testing so we can get inferior otuput.
1140                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"code address: 0x([0-9a-fA-F]+)\r\n"),
1141                 "capture": {1: "function_address"}},
1142                # Now stop the inferior.
1143                "read packet: {}".format(chr(3)),
1144                # And wait for the stop notification.
1145                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
1146            True)
1147
1148        # Run the packet stream.
1149        context = self.expect_gdbremote_sequence()
1150        self.assertIsNotNone(context)
1151
1152        # Gather process info - we need endian of target to handle register
1153        # value conversions.
1154        process_info = self.parse_process_info_response(context)
1155        endian = process_info.get("endian")
1156        self.assertIsNotNone(endian)
1157
1158        # Gather register info entries.
1159        reg_infos = self.parse_register_info_packets(context)
1160        (pc_lldb_reg_index, pc_reg_info) = self.find_pc_reg_info(reg_infos)
1161        self.assertIsNotNone(pc_lldb_reg_index)
1162        self.assertIsNotNone(pc_reg_info)
1163
1164        # Grab the function address.
1165        self.assertIsNotNone(context.get("function_address"))
1166        function_address = int(context.get("function_address"), 16)
1167
1168        # Get current target architecture
1169        target_arch = self.getArchitecture()
1170
1171        # Set the breakpoint.
1172        if (target_arch == "arm") or (target_arch == "aarch64"):
1173            # TODO: Handle case when setting breakpoint in thumb code
1174            BREAKPOINT_KIND = 4
1175        else:
1176            BREAKPOINT_KIND = 1
1177
1178        # Set default packet type to Z0 (software breakpoint)
1179        z_packet_type = 0
1180
1181        # If hardware breakpoint is requested set packet type to Z1
1182        if want_hardware == True:
1183            z_packet_type = 1
1184
1185        self.reset_test_sequence()
1186        self.add_set_breakpoint_packets(
1187            function_address,
1188            z_packet_type,
1189            do_continue=True,
1190            breakpoint_kind=BREAKPOINT_KIND)
1191
1192        # Run the packet stream.
1193        context = self.expect_gdbremote_sequence()
1194        self.assertIsNotNone(context)
1195
1196        # Verify the stop signal reported was the breakpoint signal number.
1197        stop_signo = context.get("stop_signo")
1198        self.assertIsNotNone(stop_signo)
1199        self.assertEqual(int(stop_signo, 16),
1200                         lldbutil.get_signal_number('SIGTRAP'))
1201
1202        # Ensure we did not receive any output.  If the breakpoint was not set, we would
1203        # see output (from a launched process with captured stdio) printing a hello, world message.
1204        # That would indicate the breakpoint didn't take.
1205        self.assertEqual(len(context["O_content"]), 0)
1206
1207        # Verify that the PC for the main thread is where we expect it - right at the breakpoint address.
1208        # This acts as a another validation on the register reading code.
1209        self.reset_test_sequence()
1210        self.test_sequence.add_log_lines(
1211            [
1212                # Print the PC.  This should match the breakpoint address.
1213                "read packet: $p{0:x}#00".format(pc_lldb_reg_index),
1214                # Capture $p results.
1215                {"direction": "send",
1216                 "regex": r"^\$([0-9a-fA-F]+)#",
1217                 "capture": {1: "p_response"}},
1218            ], True)
1219
1220        context = self.expect_gdbremote_sequence()
1221        self.assertIsNotNone(context)
1222
1223        # Verify the PC is where we expect.  Note response is in endianness of
1224        # the inferior.
1225        p_response = context.get("p_response")
1226        self.assertIsNotNone(p_response)
1227
1228        # Convert from target endian to int.
1229        returned_pc = lldbgdbserverutils.unpack_register_hex_unsigned(
1230            endian, p_response)
1231        self.assertEqual(returned_pc, function_address)
1232
1233        # Verify that a breakpoint remove and continue gets us the expected
1234        # output.
1235        self.reset_test_sequence()
1236
1237        # Add breakpoint remove packets
1238        self.add_remove_breakpoint_packets(
1239            function_address,
1240            z_packet_type,
1241            breakpoint_kind=BREAKPOINT_KIND)
1242
1243        self.test_sequence.add_log_lines(
1244            [
1245                # Continue running.
1246                "read packet: $c#63",
1247                # We should now receive the output from the call.
1248                {"type": "output_match", "regex": r"^hello, world\r\n$"},
1249                # And wait for program completion.
1250                {"direction": "send", "regex": r"^\$W00(.*)#[0-9a-fA-F]{2}$"},
1251            ], True)
1252
1253        context = self.expect_gdbremote_sequence()
1254        self.assertIsNotNone(context)
1255
1256    @debugserver_test
1257    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1258    def test_software_breakpoint_set_and_remove_work_debugserver(self):
1259        self.init_debugserver_test()
1260        if self.getArchitecture() == "arm":
1261            # TODO: Handle case when setting breakpoint in thumb code
1262            self.build(dictionary={'CFLAGS_EXTRAS': '-marm'})
1263        else:
1264            self.build()
1265        self.set_inferior_startup_launch()
1266        self.breakpoint_set_and_remove_work(want_hardware=False)
1267
1268    @skipIfWindows # No pty support to test any inferior output
1269    @llgs_test
1270    @expectedFlakeyLinux("llvm.org/pr25652")
1271    def test_software_breakpoint_set_and_remove_work_llgs(self):
1272        self.init_llgs_test()
1273        if self.getArchitecture() == "arm":
1274            # TODO: Handle case when setting breakpoint in thumb code
1275            self.build(dictionary={'CFLAGS_EXTRAS': '-marm'})
1276        else:
1277            self.build()
1278        self.set_inferior_startup_launch()
1279        self.breakpoint_set_and_remove_work(want_hardware=False)
1280
1281    @debugserver_test
1282    @skipUnlessPlatform(oslist=['linux'])
1283    @expectedFailureAndroid
1284    @skipIf(archs=no_match(['arm', 'aarch64']))
1285    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1286    def test_hardware_breakpoint_set_and_remove_work_debugserver(self):
1287        self.init_debugserver_test()
1288        if self.getArchitecture() == "arm":
1289            # TODO: Handle case when setting breakpoint in thumb code
1290            self.build(dictionary={'CFLAGS_EXTRAS': '-marm'})
1291        else:
1292            self.build()
1293        self.set_inferior_startup_launch()
1294        self.breakpoint_set_and_remove_work(want_hardware=True)
1295
1296    @llgs_test
1297    @skipUnlessPlatform(oslist=['linux'])
1298    @skipIf(archs=no_match(['arm', 'aarch64']))
1299    def test_hardware_breakpoint_set_and_remove_work_llgs(self):
1300        self.init_llgs_test()
1301        if self.getArchitecture() == "arm":
1302            # TODO: Handle case when setting breakpoint in thumb code
1303            self.build(dictionary={'CFLAGS_EXTRAS': '-marm'})
1304        else:
1305            self.build()
1306        self.set_inferior_startup_launch()
1307        self.breakpoint_set_and_remove_work(want_hardware=True)
1308
1309    def qSupported_returns_known_stub_features(self):
1310        # Start up the stub and start/prep the inferior.
1311        procs = self.prep_debug_monitor_and_inferior()
1312        self.add_qSupported_packets()
1313
1314        # Run the packet stream.
1315        context = self.expect_gdbremote_sequence()
1316        self.assertIsNotNone(context)
1317
1318        # Retrieve the qSupported features.
1319        supported_dict = self.parse_qSupported_response(context)
1320        self.assertIsNotNone(supported_dict)
1321        self.assertTrue(len(supported_dict) > 0)
1322
1323    @debugserver_test
1324    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1325    def test_qSupported_returns_known_stub_features_debugserver(self):
1326        self.init_debugserver_test()
1327        self.build()
1328        self.set_inferior_startup_launch()
1329        self.qSupported_returns_known_stub_features()
1330
1331    @llgs_test
1332    def test_qSupported_returns_known_stub_features_llgs(self):
1333        self.init_llgs_test()
1334        self.build()
1335        self.set_inferior_startup_launch()
1336        self.qSupported_returns_known_stub_features()
1337
1338    def written_M_content_reads_back_correctly(self):
1339        TEST_MESSAGE = "Hello, memory"
1340
1341        # Start up the stub and start/prep the inferior.
1342        procs = self.prep_debug_monitor_and_inferior(
1343            inferior_args=[
1344                "set-message:xxxxxxxxxxxxxX",
1345                "get-data-address-hex:g_message",
1346                "sleep:1",
1347                "print-message:"])
1348        self.test_sequence.add_log_lines(
1349            [
1350                # Start running after initial stop.
1351                "read packet: $c#63",
1352                # Match output line that prints the memory address of the message buffer within the inferior.
1353                # Note we require launch-only testing so we can get inferior otuput.
1354                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"data address: 0x([0-9a-fA-F]+)\r\n"),
1355                 "capture": {1: "message_address"}},
1356                # Now stop the inferior.
1357                "read packet: {}".format(chr(3)),
1358                # And wait for the stop notification.
1359                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
1360            True)
1361        context = self.expect_gdbremote_sequence()
1362        self.assertIsNotNone(context)
1363
1364        # Grab the message address.
1365        self.assertIsNotNone(context.get("message_address"))
1366        message_address = int(context.get("message_address"), 16)
1367
1368        # Hex-encode the test message, adding null termination.
1369        hex_encoded_message = seven.hexlify(TEST_MESSAGE)
1370
1371        # Write the message to the inferior. Verify that we can read it with the hex-encoded (m)
1372        # and binary (x) memory read packets.
1373        self.reset_test_sequence()
1374        self.test_sequence.add_log_lines(
1375            ["read packet: $M{0:x},{1:x}:{2}#00".format(message_address, len(TEST_MESSAGE), hex_encoded_message),
1376             "send packet: $OK#00",
1377             "read packet: $m{0:x},{1:x}#00".format(message_address, len(TEST_MESSAGE)),
1378             "send packet: ${0}#00".format(hex_encoded_message),
1379             "read packet: $x{0:x},{1:x}#00".format(message_address, len(TEST_MESSAGE)),
1380             "send packet: ${0}#00".format(TEST_MESSAGE),
1381             "read packet: $m{0:x},4#00".format(message_address),
1382             "send packet: ${0}#00".format(hex_encoded_message[0:8]),
1383             "read packet: $x{0:x},4#00".format(message_address),
1384             "send packet: ${0}#00".format(TEST_MESSAGE[0:4]),
1385             "read packet: $c#63",
1386             {"type": "output_match", "regex": r"^message: (.+)\r\n$", "capture": {1: "printed_message"}},
1387             "send packet: $W00#00",
1388             ], True)
1389        context = self.expect_gdbremote_sequence()
1390        self.assertIsNotNone(context)
1391
1392        # Ensure what we read from inferior memory is what we wrote.
1393        printed_message = context.get("printed_message")
1394        self.assertIsNotNone(printed_message)
1395        self.assertEqual(printed_message, TEST_MESSAGE + "X")
1396
1397    @debugserver_test
1398    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1399    def test_written_M_content_reads_back_correctly_debugserver(self):
1400        self.init_debugserver_test()
1401        self.build()
1402        self.set_inferior_startup_launch()
1403        self.written_M_content_reads_back_correctly()
1404
1405    @skipIfWindows # No pty support to test any inferior output
1406    @llgs_test
1407    @expectedFlakeyLinux("llvm.org/pr25652")
1408    def test_written_M_content_reads_back_correctly_llgs(self):
1409        self.init_llgs_test()
1410        self.build()
1411        self.set_inferior_startup_launch()
1412        self.written_M_content_reads_back_correctly()
1413
1414    def P_writes_all_gpr_registers(self):
1415        # Start inferior debug session, grab all register info.
1416        procs = self.prep_debug_monitor_and_inferior(inferior_args=["sleep:2"])
1417        self.add_register_info_collection_packets()
1418        self.add_process_info_collection_packets()
1419
1420        context = self.expect_gdbremote_sequence()
1421        self.assertIsNotNone(context)
1422
1423        # Process register infos.
1424        reg_infos = self.parse_register_info_packets(context)
1425        self.assertIsNotNone(reg_infos)
1426        self.add_lldb_register_index(reg_infos)
1427
1428        # Process endian.
1429        process_info = self.parse_process_info_response(context)
1430        endian = process_info.get("endian")
1431        self.assertIsNotNone(endian)
1432
1433        # Pull out the register infos that we think we can bit flip
1434        # successfully,.
1435        gpr_reg_infos = [
1436            reg_info for reg_info in reg_infos if self.is_bit_flippable_register(reg_info)]
1437        self.assertTrue(len(gpr_reg_infos) > 0)
1438
1439        # Write flipped bit pattern of existing value to each register.
1440        (successful_writes, failed_writes) = self.flip_all_bits_in_each_register_value(
1441            gpr_reg_infos, endian)
1442        self.trace("successful writes: {}, failed writes: {}".format(successful_writes, failed_writes))
1443        self.assertTrue(successful_writes > 0)
1444
1445    # Note: as of this moment, a hefty number of the GPR writes are failing with E32 (everything except rax-rdx, rdi, rsi, rbp).
1446    # Come back to this.  I have the test rigged to verify that at least some
1447    # of the bit-flip writes work.
1448    @debugserver_test
1449    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1450    def test_P_writes_all_gpr_registers_debugserver(self):
1451        self.init_debugserver_test()
1452        self.build()
1453        self.set_inferior_startup_launch()
1454        self.P_writes_all_gpr_registers()
1455
1456    @llgs_test
1457    def test_P_writes_all_gpr_registers_llgs(self):
1458        self.init_llgs_test()
1459        self.build()
1460        self.set_inferior_startup_launch()
1461        self.P_writes_all_gpr_registers()
1462
1463    def P_and_p_thread_suffix_work(self):
1464        # Startup the inferior with three threads.
1465        procs = self.prep_debug_monitor_and_inferior(
1466            inferior_args=["thread:new", "thread:new"])
1467        self.add_thread_suffix_request_packets()
1468        self.add_register_info_collection_packets()
1469        self.add_process_info_collection_packets()
1470
1471        context = self.expect_gdbremote_sequence()
1472        self.assertIsNotNone(context)
1473
1474        process_info = self.parse_process_info_response(context)
1475        self.assertIsNotNone(process_info)
1476        endian = process_info.get("endian")
1477        self.assertIsNotNone(endian)
1478
1479        reg_infos = self.parse_register_info_packets(context)
1480        self.assertIsNotNone(reg_infos)
1481        self.add_lldb_register_index(reg_infos)
1482
1483        reg_index = self.select_modifiable_register(reg_infos)
1484        self.assertIsNotNone(reg_index)
1485        reg_byte_size = int(reg_infos[reg_index]["bitsize"]) // 8
1486        self.assertTrue(reg_byte_size > 0)
1487
1488        # Run the process a bit so threads can start up, and collect register
1489        # info.
1490        context = self.run_process_then_stop(run_seconds=1)
1491        self.assertIsNotNone(context)
1492
1493        # Wait for 3 threads to be present.
1494        threads = self.wait_for_thread_count(3, timeout_seconds=self._WAIT_TIMEOUT)
1495        self.assertEqual(len(threads), 3)
1496
1497        expected_reg_values = []
1498        register_increment = 1
1499        next_value = None
1500
1501        # Set the same register in each of 3 threads to a different value.
1502        # Verify each one has the unique value.
1503        for thread in threads:
1504            # If we don't have a next value yet, start it with the initial read
1505            # value + 1
1506            if not next_value:
1507                # Read pre-existing register value.
1508                self.reset_test_sequence()
1509                self.test_sequence.add_log_lines(
1510                    ["read packet: $p{0:x};thread:{1:x}#00".format(reg_index, thread),
1511                     {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}},
1512                     ], True)
1513                context = self.expect_gdbremote_sequence()
1514                self.assertIsNotNone(context)
1515
1516                # Set the next value to use for writing as the increment plus
1517                # current value.
1518                p_response = context.get("p_response")
1519                self.assertIsNotNone(p_response)
1520                next_value = lldbgdbserverutils.unpack_register_hex_unsigned(
1521                    endian, p_response)
1522
1523            # Set new value using P and thread suffix.
1524            self.reset_test_sequence()
1525            self.test_sequence.add_log_lines(
1526                [
1527                    "read packet: $P{0:x}={1};thread:{2:x}#00".format(
1528                        reg_index,
1529                        lldbgdbserverutils.pack_register_hex(
1530                            endian,
1531                            next_value,
1532                            byte_size=reg_byte_size),
1533                        thread),
1534                    "send packet: $OK#00",
1535                ],
1536                True)
1537            context = self.expect_gdbremote_sequence()
1538            self.assertIsNotNone(context)
1539
1540            # Save the value we set.
1541            expected_reg_values.append(next_value)
1542
1543            # Increment value for next thread to use (we want them all
1544            # different so we can verify they wrote to each thread correctly
1545            # next.)
1546            next_value += register_increment
1547
1548        # Revisit each thread and verify they have the expected value set for
1549        # the register we wrote.
1550        thread_index = 0
1551        for thread in threads:
1552            # Read pre-existing register value.
1553            self.reset_test_sequence()
1554            self.test_sequence.add_log_lines(
1555                ["read packet: $p{0:x};thread:{1:x}#00".format(reg_index, thread),
1556                 {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}},
1557                 ], True)
1558            context = self.expect_gdbremote_sequence()
1559            self.assertIsNotNone(context)
1560
1561            # Get the register value.
1562            p_response = context.get("p_response")
1563            self.assertIsNotNone(p_response)
1564            read_value = lldbgdbserverutils.unpack_register_hex_unsigned(
1565                endian, p_response)
1566
1567            # Make sure we read back what we wrote.
1568            self.assertEqual(read_value, expected_reg_values[thread_index])
1569            thread_index += 1
1570
1571    # Note: as of this moment, a hefty number of the GPR writes are failing
1572    # with E32 (everything except rax-rdx, rdi, rsi, rbp).
1573    @debugserver_test
1574    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1575    def test_P_and_p_thread_suffix_work_debugserver(self):
1576        self.init_debugserver_test()
1577        self.build()
1578        self.set_inferior_startup_launch()
1579        self.P_and_p_thread_suffix_work()
1580
1581    @skipIfWindows
1582    @llgs_test
1583    def test_P_and_p_thread_suffix_work_llgs(self):
1584        self.init_llgs_test()
1585        self.build()
1586        self.set_inferior_startup_launch()
1587        self.P_and_p_thread_suffix_work()
1588