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