1"""
2Test case for testing the gdbremote protocol.
3
4Tests run against debugserver and lldb-server (llgs).
5lldb-server tests run where the lldb-server exe is
6available.
7
8This class will be broken into smaller test case classes by
9gdb remote packet functional areas.  For now it contains
10the initial set of tests implemented.
11"""
12
13import unittest2
14import gdbremote_testcase
15import lldbgdbserverutils
16from lldbsuite.support import seven
17from lldbsuite.test.decorators import *
18from lldbsuite.test.lldbtest import *
19from lldbsuite.test.lldbdwarf import *
20from lldbsuite.test import lldbutil
21
22
23class LldbGdbServerTestCase(gdbremote_testcase.GdbRemoteTestCaseBase, DwarfOpcodeParser):
24
25    mydir = TestBase.compute_mydir(__file__)
26
27    @debugserver_test
28    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
29    def test_exe_starts_debugserver(self):
30        self.init_debugserver_test()
31        server = self.connect_to_debug_monitor()
32
33    @llgs_test
34    def test_exe_starts_llgs(self):
35        self.init_llgs_test()
36        server = self.connect_to_debug_monitor()
37
38    def start_no_ack_mode(self):
39        server = self.connect_to_debug_monitor()
40        self.assertIsNotNone(server)
41
42        self.add_no_ack_remote_stream()
43        self.expect_gdbremote_sequence()
44
45    @debugserver_test
46    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
47    def test_start_no_ack_mode_debugserver(self):
48        self.init_debugserver_test()
49        self.start_no_ack_mode()
50
51    @llgs_test
52    def test_start_no_ack_mode_llgs(self):
53        self.init_llgs_test()
54        self.start_no_ack_mode()
55
56    def thread_suffix_supported(self):
57        server = self.connect_to_debug_monitor()
58        self.assertIsNotNone(server)
59
60        self.add_no_ack_remote_stream()
61        self.test_sequence.add_log_lines(
62            ["lldb-server <  26> read packet: $QThreadSuffixSupported#e4",
63             "lldb-server <   6> send packet: $OK#9a"],
64            True)
65
66        self.expect_gdbremote_sequence()
67
68    @debugserver_test
69    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
70    def test_thread_suffix_supported_debugserver(self):
71        self.init_debugserver_test()
72        self.thread_suffix_supported()
73
74    @llgs_test
75    def test_thread_suffix_supported_llgs(self):
76        self.init_llgs_test()
77        self.thread_suffix_supported()
78
79    def list_threads_in_stop_reply_supported(self):
80        server = self.connect_to_debug_monitor()
81        self.assertIsNotNone(server)
82
83        self.add_no_ack_remote_stream()
84        self.test_sequence.add_log_lines(
85            ["lldb-server <  27> read packet: $QListThreadsInStopReply#21",
86             "lldb-server <   6> send packet: $OK#9a"],
87            True)
88        self.expect_gdbremote_sequence()
89
90    @debugserver_test
91    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
92    def test_list_threads_in_stop_reply_supported_debugserver(self):
93        self.init_debugserver_test()
94        self.list_threads_in_stop_reply_supported()
95
96    @llgs_test
97    def test_list_threads_in_stop_reply_supported_llgs(self):
98        self.init_llgs_test()
99        self.list_threads_in_stop_reply_supported()
100
101    def c_packet_works(self):
102        launch_args = self.install_and_create_launch_args()
103
104        server = self.connect_to_debug_monitor()
105        self.assertIsNotNone(server)
106
107        self.add_no_ack_remote_stream()
108        self.add_verified_launch_packets(launch_args)
109        self.test_sequence.add_log_lines(
110            ["read packet: $c#63",
111             "send packet: $W00#00"],
112            True)
113
114        self.expect_gdbremote_sequence()
115
116    @debugserver_test
117    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
118    def test_c_packet_works_debugserver(self):
119        self.init_debugserver_test()
120        self.build()
121        self.c_packet_works()
122
123    @llgs_test
124    def test_c_packet_works_llgs(self):
125        self.init_llgs_test()
126        self.build()
127        self.c_packet_works()
128
129    def inferior_print_exit(self):
130        launch_args = self.install_and_create_launch_args()
131
132        server = self.connect_to_debug_monitor()
133        self.assertIsNotNone(server)
134
135        # build launch args
136        launch_args += ["hello, world"]
137
138        self.add_no_ack_remote_stream()
139        self.add_verified_launch_packets(launch_args)
140        self.test_sequence.add_log_lines(
141            ["read packet: $vCont;c#a8",
142             {"type": "output_match", "regex": self.maybe_strict_output_regex(r"hello, world\r\n")},
143             "send packet: $W00#00"],
144            True)
145
146        context = self.expect_gdbremote_sequence()
147        self.assertIsNotNone(context)
148
149    @debugserver_test
150    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
151    def test_inferior_print_exit_debugserver(self):
152        self.init_debugserver_test()
153        self.build()
154        self.inferior_print_exit()
155
156    @skipIfWindows # No pty support to test any inferior output
157    @llgs_test
158    @expectedFlakeyLinux("llvm.org/pr25652")
159    def test_inferior_print_exit_llgs(self):
160        self.init_llgs_test()
161        self.build()
162        self.inferior_print_exit()
163
164    def first_launch_stop_reply_thread_matches_first_qC(self):
165        launch_args = self.install_and_create_launch_args()
166
167        server = self.connect_to_debug_monitor()
168        self.assertIsNotNone(server)
169
170        # build launch args
171        launch_args += ["hello, world"]
172
173        self.add_no_ack_remote_stream()
174        self.add_verified_launch_packets(launch_args)
175        self.test_sequence.add_log_lines(["read packet: $qC#00",
176                                          {"direction": "send",
177                                           "regex": r"^\$QC([0-9a-fA-F]+)#",
178                                           "capture": {1: "thread_id"}},
179                                          "read packet: $?#00",
180                                          {"direction": "send",
181                                              "regex": r"^\$T[0-9a-fA-F]{2}thread:([0-9a-fA-F]+)",
182                                              "expect_captures": {1: "thread_id"}}],
183                                         True)
184        self.expect_gdbremote_sequence()
185
186    @debugserver_test
187    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
188    def test_first_launch_stop_reply_thread_matches_first_qC_debugserver(self):
189        self.init_debugserver_test()
190        self.build()
191        self.first_launch_stop_reply_thread_matches_first_qC()
192
193    @llgs_test
194    def test_first_launch_stop_reply_thread_matches_first_qC_llgs(self):
195        self.init_llgs_test()
196        self.build()
197        self.first_launch_stop_reply_thread_matches_first_qC()
198
199    def attach_commandline_continue_app_exits(self):
200        procs = self.prep_debug_monitor_and_inferior()
201        self.test_sequence.add_log_lines(
202            ["read packet: $vCont;c#a8",
203             "send packet: $W00#00"],
204            True)
205        self.expect_gdbremote_sequence()
206
207        # Wait a moment for completed and now-detached inferior process to
208        # clear.
209        time.sleep(1)
210
211        if not lldb.remote_platform:
212            # Process should be dead now. Reap results.
213            poll_result = procs["inferior"].poll()
214            self.assertIsNotNone(poll_result)
215
216        # Where possible, verify at the system level that the process is not
217        # running.
218        self.assertFalse(
219            lldbgdbserverutils.process_is_running(
220                procs["inferior"].pid, False))
221
222    @debugserver_test
223    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
224    def test_attach_commandline_continue_app_exits_debugserver(self):
225        self.init_debugserver_test()
226        self.build()
227        self.set_inferior_startup_attach()
228        self.attach_commandline_continue_app_exits()
229
230    @llgs_test
231    def test_attach_commandline_continue_app_exits_llgs(self):
232        self.init_llgs_test()
233        self.build()
234        self.set_inferior_startup_attach()
235        self.attach_commandline_continue_app_exits()
236
237    def qRegisterInfo_returns_one_valid_result(self):
238        launch_args = self.install_and_create_launch_args()
239
240        server = self.connect_to_debug_monitor()
241        self.assertIsNotNone(server)
242
243        # Build the expected protocol stream
244        self.add_no_ack_remote_stream()
245        self.add_verified_launch_packets(launch_args)
246        self.test_sequence.add_log_lines(
247            ["read packet: $qRegisterInfo0#00",
248             {"direction": "send", "regex": r"^\$(.+);#[0-9A-Fa-f]{2}", "capture": {1: "reginfo_0"}}],
249            True)
250
251        # Run the stream
252        context = self.expect_gdbremote_sequence()
253        self.assertIsNotNone(context)
254
255        reg_info_packet = context.get("reginfo_0")
256        self.assertIsNotNone(reg_info_packet)
257        self.assert_valid_reg_info(
258            lldbgdbserverutils.parse_reg_info_response(reg_info_packet))
259
260    @debugserver_test
261    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
262    def test_qRegisterInfo_returns_one_valid_result_debugserver(self):
263        self.init_debugserver_test()
264        self.build()
265        self.qRegisterInfo_returns_one_valid_result()
266
267    @llgs_test
268    def test_qRegisterInfo_returns_one_valid_result_llgs(self):
269        self.init_llgs_test()
270        self.build()
271        self.qRegisterInfo_returns_one_valid_result()
272
273    def qRegisterInfo_returns_all_valid_results(self):
274        launch_args = self.install_and_create_launch_args()
275
276        server = self.connect_to_debug_monitor()
277        self.assertIsNotNone(server)
278
279        # Build the expected protocol stream.
280        self.add_no_ack_remote_stream()
281        self.add_verified_launch_packets(launch_args)
282        self.add_register_info_collection_packets()
283
284        # Run the stream.
285        context = self.expect_gdbremote_sequence()
286        self.assertIsNotNone(context)
287
288        # Validate that each register info returned validates.
289        for reg_info in self.parse_register_info_packets(context):
290            self.assert_valid_reg_info(reg_info)
291
292    @debugserver_test
293    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
294    def test_qRegisterInfo_returns_all_valid_results_debugserver(self):
295        self.init_debugserver_test()
296        self.build()
297        self.qRegisterInfo_returns_all_valid_results()
298
299    @llgs_test
300    def test_qRegisterInfo_returns_all_valid_results_llgs(self):
301        self.init_llgs_test()
302        self.build()
303        self.qRegisterInfo_returns_all_valid_results()
304
305    def qRegisterInfo_contains_required_generics(self):
306        launch_args = self.install_and_create_launch_args()
307
308        server = self.connect_to_debug_monitor()
309        self.assertIsNotNone(server)
310
311        # Build the expected protocol stream
312        self.add_no_ack_remote_stream()
313        self.add_verified_launch_packets(launch_args)
314        self.add_register_info_collection_packets()
315
316        # Run the packet stream.
317        context = self.expect_gdbremote_sequence()
318        self.assertIsNotNone(context)
319
320        # Gather register info entries.
321        reg_infos = self.parse_register_info_packets(context)
322
323        # Collect all generic registers found.
324        generic_regs = {
325            reg_info['generic']: 1 for reg_info in reg_infos if 'generic' in reg_info}
326
327        # Ensure we have a program counter register.
328        self.assertTrue('pc' in generic_regs)
329
330        # Ensure we have a frame pointer register. PPC64le's FP is the same as SP
331        if self.getArchitecture() != 'powerpc64le':
332            self.assertTrue('fp' in generic_regs)
333
334        # Ensure we have a stack pointer register.
335        self.assertTrue('sp' in generic_regs)
336
337        # Ensure we have a flags register.
338        self.assertTrue('flags' in generic_regs)
339
340    @debugserver_test
341    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
342    def test_qRegisterInfo_contains_required_generics_debugserver(self):
343        self.init_debugserver_test()
344        self.build()
345        self.qRegisterInfo_contains_required_generics()
346
347    @llgs_test
348    def test_qRegisterInfo_contains_required_generics_llgs(self):
349        self.init_llgs_test()
350        self.build()
351        self.qRegisterInfo_contains_required_generics()
352
353    def qRegisterInfo_contains_at_least_one_register_set(self):
354        launch_args = self.install_and_create_launch_args()
355
356        server = self.connect_to_debug_monitor()
357        self.assertIsNotNone(server)
358
359        # Build the expected protocol stream
360        self.add_no_ack_remote_stream()
361        self.add_verified_launch_packets(launch_args)
362        self.add_register_info_collection_packets()
363
364        # Run the packet stream.
365        context = self.expect_gdbremote_sequence()
366        self.assertIsNotNone(context)
367
368        # Gather register info entries.
369        reg_infos = self.parse_register_info_packets(context)
370
371        # Collect all register sets found.
372        register_sets = {
373            reg_info['set']: 1 for reg_info in reg_infos if 'set' in reg_info}
374        self.assertTrue(len(register_sets) >= 1)
375
376    @debugserver_test
377    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
378    def test_qRegisterInfo_contains_at_least_one_register_set_debugserver(
379            self):
380        self.init_debugserver_test()
381        self.build()
382        self.qRegisterInfo_contains_at_least_one_register_set()
383
384    @llgs_test
385    def test_qRegisterInfo_contains_at_least_one_register_set_llgs(self):
386        self.init_llgs_test()
387        self.build()
388        self.qRegisterInfo_contains_at_least_one_register_set()
389
390    def targetHasAVX(self):
391        triple = self.dbg.GetSelectedPlatform().GetTriple()
392
393        # TODO other platforms, please implement this function
394        if not re.match(".*-.*-linux", triple):
395            return True
396
397        # Need to do something different for non-Linux/Android targets
398        if lldb.remote_platform:
399            self.runCmd('platform get-file "/proc/cpuinfo" "cpuinfo"')
400            cpuinfo_path = "cpuinfo"
401            self.addTearDownHook(lambda: os.unlink("cpuinfo"))
402        else:
403            cpuinfo_path = "/proc/cpuinfo"
404
405        f = open(cpuinfo_path, 'r')
406        cpuinfo = f.read()
407        f.close()
408        return " avx " in cpuinfo
409
410    def qRegisterInfo_contains_avx_registers(self):
411        launch_args = self.install_and_create_launch_args()
412
413        server = self.connect_to_debug_monitor()
414        self.assertIsNotNone(server)
415
416        # Build the expected protocol stream
417        self.add_no_ack_remote_stream()
418        self.add_verified_launch_packets(launch_args)
419        self.add_register_info_collection_packets()
420
421        # Run the packet stream.
422        context = self.expect_gdbremote_sequence()
423        self.assertIsNotNone(context)
424
425        # Gather register info entries.
426        reg_infos = self.parse_register_info_packets(context)
427
428        # Collect all generics found.
429        register_sets = {
430            reg_info['set']: 1 for reg_info in reg_infos if 'set' in reg_info}
431        self.assertEqual(
432            self.targetHasAVX(),
433            "Advanced Vector Extensions" in register_sets)
434
435    @expectedFailureAll(oslist=["windows"]) # no avx for now.
436    @expectedFailureAll(oslist=["freebsd", "netbsd"])
437    @llgs_test
438    def test_qRegisterInfo_contains_avx_registers_llgs(self):
439        self.init_llgs_test()
440        self.build()
441        self.qRegisterInfo_contains_avx_registers()
442
443    def qThreadInfo_contains_thread(self):
444        procs = self.prep_debug_monitor_and_inferior()
445        self.add_threadinfo_collection_packets()
446
447        # Run the packet stream.
448        context = self.expect_gdbremote_sequence()
449        self.assertIsNotNone(context)
450
451        # Gather threadinfo entries.
452        threads = self.parse_threadinfo_packets(context)
453        self.assertIsNotNone(threads)
454
455        # We should have exactly one thread.
456        self.assertEqual(len(threads), 1)
457
458    @debugserver_test
459    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
460    def test_qThreadInfo_contains_thread_launch_debugserver(self):
461        self.init_debugserver_test()
462        self.build()
463        self.set_inferior_startup_launch()
464        self.qThreadInfo_contains_thread()
465
466    @llgs_test
467    def test_qThreadInfo_contains_thread_launch_llgs(self):
468        self.init_llgs_test()
469        self.build()
470        self.set_inferior_startup_launch()
471        self.qThreadInfo_contains_thread()
472
473    @debugserver_test
474    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
475    def test_qThreadInfo_contains_thread_attach_debugserver(self):
476        self.init_debugserver_test()
477        self.build()
478        self.set_inferior_startup_attach()
479        self.qThreadInfo_contains_thread()
480
481    @expectedFailureAll(oslist=["windows"]) # expect one more thread stopped
482    @llgs_test
483    def test_qThreadInfo_contains_thread_attach_llgs(self):
484        self.init_llgs_test()
485        self.build()
486        self.set_inferior_startup_attach()
487        self.qThreadInfo_contains_thread()
488
489    def qThreadInfo_matches_qC(self):
490        procs = self.prep_debug_monitor_and_inferior()
491
492        self.add_threadinfo_collection_packets()
493        self.test_sequence.add_log_lines(
494            ["read packet: $qC#00",
495             {"direction": "send", "regex": r"^\$QC([0-9a-fA-F]+)#", "capture": {1: "thread_id"}}
496             ], True)
497
498        # Run the packet stream.
499        context = self.expect_gdbremote_sequence()
500        self.assertIsNotNone(context)
501
502        # Gather threadinfo entries.
503        threads = self.parse_threadinfo_packets(context)
504        self.assertIsNotNone(threads)
505
506        # We should have exactly one thread from threadinfo.
507        self.assertEqual(len(threads), 1)
508
509        # We should have a valid thread_id from $QC.
510        QC_thread_id_hex = context.get("thread_id")
511        self.assertIsNotNone(QC_thread_id_hex)
512        QC_thread_id = int(QC_thread_id_hex, 16)
513
514        # Those two should be the same.
515        self.assertEqual(threads[0], QC_thread_id)
516
517    @debugserver_test
518    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
519    def test_qThreadInfo_matches_qC_launch_debugserver(self):
520        self.init_debugserver_test()
521        self.build()
522        self.set_inferior_startup_launch()
523        self.qThreadInfo_matches_qC()
524
525    @llgs_test
526    def test_qThreadInfo_matches_qC_launch_llgs(self):
527        self.init_llgs_test()
528        self.build()
529        self.set_inferior_startup_launch()
530        self.qThreadInfo_matches_qC()
531
532    @debugserver_test
533    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
534    def test_qThreadInfo_matches_qC_attach_debugserver(self):
535        self.init_debugserver_test()
536        self.build()
537        self.set_inferior_startup_attach()
538        self.qThreadInfo_matches_qC()
539
540    @expectedFailureAll(oslist=["windows"]) # expect one more thread stopped
541    @llgs_test
542    def test_qThreadInfo_matches_qC_attach_llgs(self):
543        self.init_llgs_test()
544        self.build()
545        self.set_inferior_startup_attach()
546        self.qThreadInfo_matches_qC()
547
548    def p_returns_correct_data_size_for_each_qRegisterInfo(self):
549        procs = self.prep_debug_monitor_and_inferior()
550        self.add_register_info_collection_packets()
551
552        # Run the packet stream.
553        context = self.expect_gdbremote_sequence()
554        self.assertIsNotNone(context)
555
556        # Gather register info entries.
557        reg_infos = self.parse_register_info_packets(context)
558        self.assertIsNotNone(reg_infos)
559        self.assertTrue(len(reg_infos) > 0)
560
561        byte_order = self.get_target_byte_order()
562
563        # Read value for each register.
564        reg_index = 0
565        for reg_info in reg_infos:
566            # Skip registers that don't have a register set.  For x86, these are
567            # the DRx registers, which have no LLDB-kind register number and thus
568            # cannot be read via normal
569            # NativeRegisterContext::ReadRegister(reg_info,...) calls.
570            if not "set" in reg_info:
571                continue
572
573            # Clear existing packet expectations.
574            self.reset_test_sequence()
575
576            # Run the register query
577            self.test_sequence.add_log_lines(
578                ["read packet: $p{0:x}#00".format(reg_index),
579                 {"direction": "send", "regex": r"^\$([0-9a-fA-F]+)#", "capture": {1: "p_response"}}],
580                True)
581            context = self.expect_gdbremote_sequence()
582            self.assertIsNotNone(context)
583
584            # Verify the response length.
585            p_response = context.get("p_response")
586            self.assertIsNotNone(p_response)
587
588            if "dynamic_size_dwarf_expr_bytes" in reg_info:
589                self.updateRegInfoBitsize(reg_info, byte_order)
590            self.assertEqual(len(p_response), 2 * int(reg_info["bitsize"]) / 8)
591
592            # Increment loop
593            reg_index += 1
594
595    @debugserver_test
596    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
597    def test_p_returns_correct_data_size_for_each_qRegisterInfo_launch_debugserver(
598            self):
599        self.init_debugserver_test()
600        self.build()
601        self.set_inferior_startup_launch()
602        self.p_returns_correct_data_size_for_each_qRegisterInfo()
603
604    @expectedFailureAll(oslist=["freebsd", "netbsd"])
605    @llgs_test
606    def test_p_returns_correct_data_size_for_each_qRegisterInfo_launch_llgs(
607            self):
608        self.init_llgs_test()
609        self.build()
610        self.set_inferior_startup_launch()
611        self.p_returns_correct_data_size_for_each_qRegisterInfo()
612
613    @debugserver_test
614    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
615    def test_p_returns_correct_data_size_for_each_qRegisterInfo_attach_debugserver(
616            self):
617        self.init_debugserver_test()
618        self.build()
619        self.set_inferior_startup_attach()
620        self.p_returns_correct_data_size_for_each_qRegisterInfo()
621
622    @expectedFailureAll(oslist=["freebsd", "netbsd"])
623    @llgs_test
624    def test_p_returns_correct_data_size_for_each_qRegisterInfo_attach_llgs(
625            self):
626        self.init_llgs_test()
627        self.build()
628        self.set_inferior_startup_attach()
629        self.p_returns_correct_data_size_for_each_qRegisterInfo()
630
631    def Hg_switches_to_3_threads(self):
632        # Startup the inferior with three threads (main + 2 new ones).
633        procs = self.prep_debug_monitor_and_inferior(
634            inferior_args=["thread:new", "thread:new"])
635
636        # Let the inferior process have a few moments to start up the thread
637        # when launched.  (The launch scenario has no time to run, so threads
638        # won't be there yet.)
639        self.run_process_then_stop(run_seconds=1)
640
641        # Wait at most x seconds for 3 threads to be present.
642        threads = self.wait_for_thread_count(3)
643        self.assertEqual(len(threads), 3)
644
645        # verify we can $H to each thead, and $qC matches the thread we set.
646        for thread in threads:
647            # Change to each thread, verify current thread id.
648            self.reset_test_sequence()
649            self.test_sequence.add_log_lines(
650                ["read packet: $Hg{0:x}#00".format(thread),  # Set current thread.
651                 "send packet: $OK#00",
652                 "read packet: $qC#00",
653                 {"direction": "send", "regex": r"^\$QC([0-9a-fA-F]+)#", "capture": {1: "thread_id"}}],
654                True)
655
656            context = self.expect_gdbremote_sequence()
657            self.assertIsNotNone(context)
658
659            # Verify the thread id.
660            self.assertIsNotNone(context.get("thread_id"))
661            self.assertEqual(int(context.get("thread_id"), 16), thread)
662
663    @debugserver_test
664    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
665    def test_Hg_switches_to_3_threads_launch_debugserver(self):
666        self.init_debugserver_test()
667        self.build()
668        self.set_inferior_startup_launch()
669        self.Hg_switches_to_3_threads()
670
671    @expectedFailureAll(oslist=["windows"]) # expect 4 threads
672    @llgs_test
673    def test_Hg_switches_to_3_threads_launch_llgs(self):
674        self.init_llgs_test()
675        self.build()
676        self.set_inferior_startup_launch()
677        self.Hg_switches_to_3_threads()
678
679    @debugserver_test
680    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
681    def test_Hg_switches_to_3_threads_attach_debugserver(self):
682        self.init_debugserver_test()
683        self.build()
684        self.set_inferior_startup_attach()
685        self.Hg_switches_to_3_threads()
686
687    @expectedFailureAll(oslist=["windows"]) # expecting one more thread
688    @llgs_test
689    def test_Hg_switches_to_3_threads_attach_llgs(self):
690        self.init_llgs_test()
691        self.build()
692        self.set_inferior_startup_attach()
693        self.Hg_switches_to_3_threads()
694
695    def Hc_then_Csignal_signals_correct_thread(self, segfault_signo):
696        # NOTE only run this one in inferior-launched mode: we can't grab inferior stdout when running attached,
697        # and the test requires getting stdout from the exe.
698
699        NUM_THREADS = 3
700
701        # Startup the inferior with three threads (main + NUM_THREADS-1 worker threads).
702        # inferior_args=["thread:print-ids"]
703        inferior_args = ["thread:segfault"]
704        for i in range(NUM_THREADS - 1):
705            # if i > 0:
706                # Give time between thread creation/segfaulting for the handler to work.
707                # inferior_args.append("sleep:1")
708            inferior_args.append("thread:new")
709        inferior_args.append("sleep:10")
710
711        # Launch/attach.  (In our case, this should only ever be launched since
712        # we need inferior stdout/stderr).
713        procs = self.prep_debug_monitor_and_inferior(
714            inferior_args=inferior_args)
715        self.test_sequence.add_log_lines(["read packet: $c#63"], True)
716        context = self.expect_gdbremote_sequence()
717
718        # Let the inferior process have a few moments to start up the thread when launched.
719        # context = self.run_process_then_stop(run_seconds=1)
720
721        # Wait at most x seconds for all threads to be present.
722        # threads = self.wait_for_thread_count(NUM_THREADS)
723        # self.assertEquals(len(threads), NUM_THREADS)
724
725        signaled_tids = {}
726        print_thread_ids = {}
727
728        # Switch to each thread, deliver a signal, and verify signal delivery
729        for i in range(NUM_THREADS - 1):
730            # Run until SIGSEGV comes in.
731            self.reset_test_sequence()
732            self.test_sequence.add_log_lines([{"direction": "send",
733                                               "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);",
734                                               "capture": {1: "signo",
735                                                            2: "thread_id"}}],
736                                             True)
737
738            context = self.expect_gdbremote_sequence()
739            self.assertIsNotNone(context)
740            signo = context.get("signo")
741            self.assertEqual(int(signo, 16), segfault_signo)
742
743            # Ensure we haven't seen this tid yet.
744            thread_id = int(context.get("thread_id"), 16)
745            self.assertFalse(thread_id in signaled_tids)
746            signaled_tids[thread_id] = 1
747
748            # Send SIGUSR1 to the thread that signaled the SIGSEGV.
749            self.reset_test_sequence()
750            self.test_sequence.add_log_lines(
751                [
752                    # Set the continue thread.
753                    # Set current thread.
754                    "read packet: $Hc{0:x}#00".format(thread_id),
755                    "send packet: $OK#00",
756
757                    # Continue sending the signal number to the continue thread.
758                    # The commented out packet is a way to do this same operation without using
759                    # a $Hc (but this test is testing $Hc, so we'll stick with the former).
760                    "read packet: $C{0:x}#00".format(lldbutil.get_signal_number('SIGUSR1')),
761                    # "read packet: $vCont;C{0:x}:{1:x};c#00".format(lldbutil.get_signal_number('SIGUSR1'), thread_id),
762
763                    # FIXME: Linux does not report the thread stop on the delivered signal (SIGUSR1 here).  MacOSX debugserver does.
764                    # But MacOSX debugserver isn't guaranteeing the thread the signal handler runs on, so currently its an XFAIL.
765                    # Need to rectify behavior here.  The linux behavior is more intuitive to me since we're essentially swapping out
766                    # an about-to-be-delivered signal (for which we already sent a stop packet) to a different signal.
767                    # {"direction":"send", "regex":r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture":{1:"stop_signo", 2:"stop_thread_id"} },
768                    #  "read packet: $c#63",
769                    {"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"}},
770                ],
771                True)
772
773            # Run the sequence.
774            context = self.expect_gdbremote_sequence()
775            self.assertIsNotNone(context)
776
777            # Ensure the stop signal is the signal we delivered.
778            # stop_signo = context.get("stop_signo")
779            # self.assertIsNotNone(stop_signo)
780            # self.assertEquals(int(stop_signo,16), lldbutil.get_signal_number('SIGUSR1'))
781
782            # Ensure the stop thread is the thread to which we delivered the signal.
783            # stop_thread_id = context.get("stop_thread_id")
784            # self.assertIsNotNone(stop_thread_id)
785            # self.assertEquals(int(stop_thread_id,16), thread_id)
786
787            # Ensure we haven't seen this thread id yet.  The inferior's
788            # self-obtained thread ids are not guaranteed to match the stub
789            # tids (at least on MacOSX).
790            print_thread_id = context.get("print_thread_id")
791            self.assertIsNotNone(print_thread_id)
792            print_thread_id = int(print_thread_id, 16)
793            self.assertFalse(print_thread_id in print_thread_ids)
794
795            # Now remember this print (i.e. inferior-reflected) thread id and
796            # ensure we don't hit it again.
797            print_thread_ids[print_thread_id] = 1
798
799            # Ensure post signal-handle thread id matches the thread that
800            # initially raised the SIGSEGV.
801            post_handle_thread_id = context.get("post_handle_thread_id")
802            self.assertIsNotNone(post_handle_thread_id)
803            post_handle_thread_id = int(post_handle_thread_id, 16)
804            self.assertEqual(post_handle_thread_id, print_thread_id)
805
806    @expectedFailure
807    @debugserver_test
808    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
809    def test_Hc_then_Csignal_signals_correct_thread_launch_debugserver(self):
810        self.init_debugserver_test()
811        self.build()
812        self.set_inferior_startup_launch()
813        # Darwin debugserver translates some signals like SIGSEGV into some gdb
814        # expectations about fixed signal numbers.
815        self.Hc_then_Csignal_signals_correct_thread(self.TARGET_EXC_BAD_ACCESS)
816
817    @skipIfWindows # no SIGSEGV support
818    @expectedFailureAll(oslist=["freebsd", "netbsd"])
819    @llgs_test
820    def test_Hc_then_Csignal_signals_correct_thread_launch_llgs(self):
821        self.init_llgs_test()
822        self.build()
823        self.set_inferior_startup_launch()
824        self.Hc_then_Csignal_signals_correct_thread(
825            lldbutil.get_signal_number('SIGSEGV'))
826
827    def m_packet_reads_memory(self):
828        # This is the memory we will write into the inferior and then ensure we
829        # can read back with $m.
830        MEMORY_CONTENTS = "Test contents 0123456789 ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"
831
832        # Start up the inferior.
833        procs = self.prep_debug_monitor_and_inferior(
834            inferior_args=[
835                "set-message:%s" %
836                MEMORY_CONTENTS,
837                "get-data-address-hex:g_message",
838                "sleep:5"])
839
840        # Run the process
841        self.test_sequence.add_log_lines(
842            [
843                # Start running after initial stop.
844                "read packet: $c#63",
845                # Match output line that prints the memory address of the message buffer within the inferior.
846                # Note we require launch-only testing so we can get inferior otuput.
847                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"data address: 0x([0-9a-fA-F]+)\r\n"),
848                 "capture": {1: "message_address"}},
849                # Now stop the inferior.
850                "read packet: {}".format(chr(3)),
851                # And wait for the stop notification.
852                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
853            True)
854
855        # Run the packet stream.
856        context = self.expect_gdbremote_sequence()
857        self.assertIsNotNone(context)
858
859        # Grab the message address.
860        self.assertIsNotNone(context.get("message_address"))
861        message_address = int(context.get("message_address"), 16)
862
863        # Grab contents from the inferior.
864        self.reset_test_sequence()
865        self.test_sequence.add_log_lines(
866            ["read packet: $m{0:x},{1:x}#00".format(message_address, len(MEMORY_CONTENTS)),
867             {"direction": "send", "regex": r"^\$(.+)#[0-9a-fA-F]{2}$", "capture": {1: "read_contents"}}],
868            True)
869
870        # Run the packet stream.
871        context = self.expect_gdbremote_sequence()
872        self.assertIsNotNone(context)
873
874        # Ensure what we read from inferior memory is what we wrote.
875        self.assertIsNotNone(context.get("read_contents"))
876        read_contents = seven.unhexlify(context.get("read_contents"))
877        self.assertEqual(read_contents, MEMORY_CONTENTS)
878
879    @debugserver_test
880    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
881    def test_m_packet_reads_memory_debugserver(self):
882        self.init_debugserver_test()
883        self.build()
884        self.set_inferior_startup_launch()
885        self.m_packet_reads_memory()
886
887    @skipIfWindows # No pty support to test any inferior output
888    @llgs_test
889    def test_m_packet_reads_memory_llgs(self):
890        self.init_llgs_test()
891        self.build()
892        self.set_inferior_startup_launch()
893        self.m_packet_reads_memory()
894
895    def qMemoryRegionInfo_is_supported(self):
896        # Start up the inferior.
897        procs = self.prep_debug_monitor_and_inferior()
898
899        # Ask if it supports $qMemoryRegionInfo.
900        self.test_sequence.add_log_lines(
901            ["read packet: $qMemoryRegionInfo#00",
902             "send packet: $OK#00"
903             ], True)
904        self.expect_gdbremote_sequence()
905
906    @debugserver_test
907    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
908    def test_qMemoryRegionInfo_is_supported_debugserver(self):
909        self.init_debugserver_test()
910        self.build()
911        self.set_inferior_startup_launch()
912        self.qMemoryRegionInfo_is_supported()
913
914    @llgs_test
915    @expectedFailureAll(oslist=["freebsd"])
916    def test_qMemoryRegionInfo_is_supported_llgs(self):
917        self.init_llgs_test()
918        self.build()
919        self.set_inferior_startup_launch()
920        self.qMemoryRegionInfo_is_supported()
921
922    def qMemoryRegionInfo_reports_code_address_as_executable(self):
923        # Start up the inferior.
924        procs = self.prep_debug_monitor_and_inferior(
925            inferior_args=["get-code-address-hex:hello", "sleep:5"])
926
927        # Run the process
928        self.test_sequence.add_log_lines(
929            [
930                # Start running after initial stop.
931                "read packet: $c#63",
932                # Match output line that prints the memory address of the message buffer within the inferior.
933                # Note we require launch-only testing so we can get inferior otuput.
934                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"code address: 0x([0-9a-fA-F]+)\r\n"),
935                 "capture": {1: "code_address"}},
936                # Now stop the inferior.
937                "read packet: {}".format(chr(3)),
938                # And wait for the stop notification.
939                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
940            True)
941
942        # Run the packet stream.
943        context = self.expect_gdbremote_sequence()
944        self.assertIsNotNone(context)
945
946        # Grab the code address.
947        self.assertIsNotNone(context.get("code_address"))
948        code_address = int(context.get("code_address"), 16)
949
950        # Grab memory region info from the inferior.
951        self.reset_test_sequence()
952        self.add_query_memory_region_packets(code_address)
953
954        # Run the packet stream.
955        context = self.expect_gdbremote_sequence()
956        self.assertIsNotNone(context)
957        mem_region_dict = self.parse_memory_region_packet(context)
958
959        # Ensure there are no errors reported.
960        self.assertFalse("error" in mem_region_dict)
961
962        # Ensure code address is readable and executable.
963        self.assertTrue("permissions" in mem_region_dict)
964        self.assertTrue("r" in mem_region_dict["permissions"])
965        self.assertTrue("x" in mem_region_dict["permissions"])
966
967        # Ensure the start address and size encompass the address we queried.
968        self.assert_address_within_memory_region(code_address, mem_region_dict)
969
970    @debugserver_test
971    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
972    def test_qMemoryRegionInfo_reports_code_address_as_executable_debugserver(
973            self):
974        self.init_debugserver_test()
975        self.build()
976        self.set_inferior_startup_launch()
977        self.qMemoryRegionInfo_reports_code_address_as_executable()
978
979    @skipIfWindows # No pty support to test any inferior output
980    @expectedFailureAll(oslist=["freebsd"])
981    @llgs_test
982    def test_qMemoryRegionInfo_reports_code_address_as_executable_llgs(self):
983        self.init_llgs_test()
984        self.build()
985        self.set_inferior_startup_launch()
986        self.qMemoryRegionInfo_reports_code_address_as_executable()
987
988    def qMemoryRegionInfo_reports_stack_address_as_readable_writeable(self):
989        # Start up the inferior.
990        procs = self.prep_debug_monitor_and_inferior(
991            inferior_args=["get-stack-address-hex:", "sleep:5"])
992
993        # Run the process
994        self.test_sequence.add_log_lines(
995            [
996                # Start running after initial stop.
997                "read packet: $c#63",
998                # Match output line that prints the memory address of the message buffer within the inferior.
999                # Note we require launch-only testing so we can get inferior otuput.
1000                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"stack address: 0x([0-9a-fA-F]+)\r\n"),
1001                 "capture": {1: "stack_address"}},
1002                # Now stop the inferior.
1003                "read packet: {}".format(chr(3)),
1004                # And wait for the stop notification.
1005                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
1006            True)
1007
1008        # Run the packet stream.
1009        context = self.expect_gdbremote_sequence()
1010        self.assertIsNotNone(context)
1011
1012        # Grab the address.
1013        self.assertIsNotNone(context.get("stack_address"))
1014        stack_address = int(context.get("stack_address"), 16)
1015
1016        # Grab memory region info from the inferior.
1017        self.reset_test_sequence()
1018        self.add_query_memory_region_packets(stack_address)
1019
1020        # Run the packet stream.
1021        context = self.expect_gdbremote_sequence()
1022        self.assertIsNotNone(context)
1023        mem_region_dict = self.parse_memory_region_packet(context)
1024
1025        # Ensure there are no errors reported.
1026        self.assertFalse("error" in mem_region_dict)
1027
1028        # Ensure address is readable and executable.
1029        self.assertTrue("permissions" in mem_region_dict)
1030        self.assertTrue("r" in mem_region_dict["permissions"])
1031        self.assertTrue("w" in mem_region_dict["permissions"])
1032
1033        # Ensure the start address and size encompass the address we queried.
1034        self.assert_address_within_memory_region(
1035            stack_address, mem_region_dict)
1036
1037    @debugserver_test
1038    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1039    def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_debugserver(
1040            self):
1041        self.init_debugserver_test()
1042        self.build()
1043        self.set_inferior_startup_launch()
1044        self.qMemoryRegionInfo_reports_stack_address_as_readable_writeable()
1045
1046    @skipIfWindows # No pty support to test any inferior output
1047    @expectedFailureAll(oslist=["freebsd"])
1048    @llgs_test
1049    def test_qMemoryRegionInfo_reports_stack_address_as_readable_writeable_llgs(
1050            self):
1051        self.init_llgs_test()
1052        self.build()
1053        self.set_inferior_startup_launch()
1054        self.qMemoryRegionInfo_reports_stack_address_as_readable_writeable()
1055
1056    def qMemoryRegionInfo_reports_heap_address_as_readable_writeable(self):
1057        # Start up the inferior.
1058        procs = self.prep_debug_monitor_and_inferior(
1059            inferior_args=["get-heap-address-hex:", "sleep:5"])
1060
1061        # Run the process
1062        self.test_sequence.add_log_lines(
1063            [
1064                # Start running after initial stop.
1065                "read packet: $c#63",
1066                # Match output line that prints the memory address of the message buffer within the inferior.
1067                # Note we require launch-only testing so we can get inferior otuput.
1068                {"type": "output_match", "regex": self.maybe_strict_output_regex(r"heap address: 0x([0-9a-fA-F]+)\r\n"),
1069                 "capture": {1: "heap_address"}},
1070                # Now stop the inferior.
1071                "read packet: {}".format(chr(3)),
1072                # And wait for the stop notification.
1073                {"direction": "send", "regex": r"^\$T([0-9a-fA-F]{2})thread:([0-9a-fA-F]+);", "capture": {1: "stop_signo", 2: "stop_thread_id"}}],
1074            True)
1075
1076        # Run the packet stream.
1077        context = self.expect_gdbremote_sequence()
1078        self.assertIsNotNone(context)
1079
1080        # Grab the address.
1081        self.assertIsNotNone(context.get("heap_address"))
1082        heap_address = int(context.get("heap_address"), 16)
1083
1084        # Grab memory region info from the inferior.
1085        self.reset_test_sequence()
1086        self.add_query_memory_region_packets(heap_address)
1087
1088        # Run the packet stream.
1089        context = self.expect_gdbremote_sequence()
1090        self.assertIsNotNone(context)
1091        mem_region_dict = self.parse_memory_region_packet(context)
1092
1093        # Ensure there are no errors reported.
1094        self.assertFalse("error" in mem_region_dict)
1095
1096        # Ensure address is readable and executable.
1097        self.assertTrue("permissions" in mem_region_dict)
1098        self.assertTrue("r" in mem_region_dict["permissions"])
1099        self.assertTrue("w" in mem_region_dict["permissions"])
1100
1101        # Ensure the start address and size encompass the address we queried.
1102        self.assert_address_within_memory_region(heap_address, mem_region_dict)
1103
1104    @debugserver_test
1105    @skipIfDarwinEmbedded # <rdar://problem/34539270> lldb-server tests not updated to work on ios etc yet
1106    def test_qMemoryRegionInfo_reports_heap_address_as_readable_writeable_debugserver(
1107            self):
1108        self.init_debugserver_test()
1109        self.build()
1110        self.set_inferior_startup_launch()
1111        self.qMemoryRegionInfo_reports_heap_address_as_readable_writeable()
1112
1113    @skipIfWindows # No pty support to test any inferior output
1114    @expectedFailureAll(oslist=["freebsd"])
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