1import json
2import re
3
4import gdbremote_testcase
5from lldbsuite.test.decorators import *
6from lldbsuite.test.lldbtest import *
7from lldbsuite.test import lldbutil
8
9class TestGdbRemoteThreadsInStopReply(
10        gdbremote_testcase.GdbRemoteTestCaseBase):
11
12    mydir = TestBase.compute_mydir(__file__)
13
14    ENABLE_THREADS_IN_STOP_REPLY_ENTRIES = [
15        "read packet: $QListThreadsInStopReply#21",
16        "send packet: $OK#00",
17    ]
18
19    def gather_stop_reply_fields(self, thread_count, field_names):
20        context, threads = self.launch_with_threads(thread_count)
21        key_vals_text = context.get("stop_reply_kv")
22        self.assertIsNotNone(key_vals_text)
23
24        self.reset_test_sequence()
25        self.add_register_info_collection_packets()
26        self.add_process_info_collection_packets()
27
28        context = self.expect_gdbremote_sequence()
29        self.assertIsNotNone(context)
30        hw_info = self.parse_hw_info(context)
31
32        # Parse the stop reply contents.
33        kv_dict = self.parse_key_val_dict(key_vals_text)
34
35        result = dict();
36        result["pc_register"] = hw_info["pc_register"]
37        result["little_endian"] = hw_info["little_endian"]
38        for key_field in field_names:
39            result[key_field] = kv_dict.get(key_field)
40
41        return result
42
43    def gather_stop_reply_threads(self, thread_count):
44        # Pull out threads from stop response.
45        stop_reply_threads_text = self.gather_stop_reply_fields(
46                thread_count, ["threads"])["threads"]
47        if stop_reply_threads_text:
48            return [int(thread_id, 16)
49                    for thread_id in stop_reply_threads_text.split(",")]
50        else:
51            return []
52
53    def gather_stop_reply_pcs(self, thread_count):
54        results = self.gather_stop_reply_fields(thread_count, ["threads", "thread-pcs"])
55        if not results:
56            return []
57
58        threads_text = results["threads"]
59        pcs_text = results["thread-pcs"]
60        thread_ids = threads_text.split(",")
61        pcs = pcs_text.split(",")
62        self.assertEquals(len(thread_ids), len(pcs))
63
64        thread_pcs = dict()
65        for i in range(0, len(pcs)):
66            thread_pcs[int(thread_ids[i], 16)] = pcs[i]
67
68        result = dict()
69        result["thread_pcs"] = thread_pcs
70        result["pc_register"] = results["pc_register"]
71        result["little_endian"] = results["little_endian"]
72        return result
73
74    def switch_endian(self, egg):
75        return "".join(reversed(re.findall("..", egg)))
76
77    def parse_hw_info(self, context):
78        self.assertIsNotNone(context)
79        process_info = self.parse_process_info_response(context)
80        endian = process_info.get("endian")
81        reg_info = self.parse_register_info_packets(context)
82        (pc_lldb_reg_index, pc_reg_info) = self.find_pc_reg_info(reg_info)
83
84        hw_info = dict()
85        hw_info["pc_register"] = pc_lldb_reg_index
86        hw_info["little_endian"] = (endian == "little")
87        return hw_info
88
89    def gather_threads_info_pcs(self, pc_register, little_endian):
90        self.reset_test_sequence()
91        self.test_sequence.add_log_lines(
92                [
93                    "read packet: $jThreadsInfo#c1",
94                    {
95                        "direction": "send",
96                        "regex": r"^\$(.*)#[0-9a-fA-F]{2}$",
97                        "capture": {
98                            1: "threads_info"}},
99                ],
100                True)
101
102        context = self.expect_gdbremote_sequence()
103        self.assertIsNotNone(context)
104        threads_info = context.get("threads_info")
105        register = str(pc_register)
106        # The jThreadsInfo response is not valid JSON data, so we have to
107        # clean it up first.
108        jthreads_info = json.loads(re.sub(r"}]", "}", threads_info))
109        thread_pcs = dict()
110        for thread_info in jthreads_info:
111            tid = thread_info["tid"]
112            pc = thread_info["registers"][register]
113            thread_pcs[tid] = self.switch_endian(pc) if little_endian else pc
114
115        return thread_pcs
116
117
118    def test_QListThreadsInStopReply_supported(self):
119        self.build()
120        self.set_inferior_startup_launch()
121        procs = self.prep_debug_monitor_and_inferior()
122        self.test_sequence.add_log_lines(
123            self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, True)
124
125        context = self.expect_gdbremote_sequence()
126        self.assertIsNotNone(context)
127
128    # In current implementation of llgs on Windows, as a response to '\x03' packet, the debugger
129    # of the native process will trigger a call to DebugBreakProcess that will create a new thread
130    # to handle the exception debug event. So one more stop thread will be notified to the
131    # delegate, e.g. llgs.  So tests below to assert the stop threads number will all fail.
132    @expectedFailureAll(oslist=["windows"])
133    @skipIfNetBSD
134    def test_stop_reply_reports_multiple_threads(self):
135        self.build()
136        self.set_inferior_startup_launch()
137        # Gather threads from stop notification when QThreadsInStopReply is
138        # enabled.
139        self.test_sequence.add_log_lines(
140            self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, True)
141        stop_reply_threads = self.gather_stop_reply_threads(5)
142        self.assertEqual(len(stop_reply_threads), 5)
143
144    @expectedFailureAll(oslist=["windows"])
145    @skipIfNetBSD
146    def test_no_QListThreadsInStopReply_supplies_no_threads(self):
147        self.build()
148        self.set_inferior_startup_launch()
149        # Gather threads from stop notification when QThreadsInStopReply is not
150        # enabled.
151        stop_reply_threads = self.gather_stop_reply_threads(5)
152        self.assertEqual(len(stop_reply_threads), 0)
153
154    @expectedFailureAll(oslist=["windows"])
155    @skipIfNetBSD
156    def test_stop_reply_reports_correct_threads(self):
157        self.build()
158        self.set_inferior_startup_launch()
159        # Gather threads from stop notification when QThreadsInStopReply is
160        # enabled.
161        thread_count = 5
162        self.test_sequence.add_log_lines(
163            self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, True)
164        stop_reply_threads = self.gather_stop_reply_threads(thread_count)
165
166        # Gather threads from q{f,s}ThreadInfo.
167        self.reset_test_sequence()
168        self.add_threadinfo_collection_packets()
169
170        context = self.expect_gdbremote_sequence()
171        self.assertIsNotNone(context)
172
173        threads = self.parse_threadinfo_packets(context)
174        self.assertIsNotNone(threads)
175        self.assertEqual(len(threads), thread_count)
176
177        # Ensure each thread in q{f,s}ThreadInfo appears in stop reply threads
178        for tid in threads:
179            self.assertIn(tid, stop_reply_threads)
180
181    @expectedFailureAll(oslist=["windows"])
182    @skipIfNetBSD
183    def test_stop_reply_contains_thread_pcs(self):
184        self.build()
185        self.set_inferior_startup_launch()
186        thread_count = 5
187        self.test_sequence.add_log_lines(
188            self.ENABLE_THREADS_IN_STOP_REPLY_ENTRIES, True)
189        results = self.gather_stop_reply_pcs(thread_count)
190        stop_reply_pcs = results["thread_pcs"]
191        pc_register = results["pc_register"]
192        little_endian = results["little_endian"]
193        self.assertEqual(len(stop_reply_pcs), thread_count)
194
195        threads_info_pcs = self.gather_threads_info_pcs(pc_register,
196                little_endian)
197
198        self.assertEqual(len(threads_info_pcs), thread_count)
199        for thread_id in stop_reply_pcs:
200            self.assertIn(thread_id, threads_info_pcs)
201            self.assertEqual(int(stop_reply_pcs[thread_id], 16),
202                    int(threads_info_pcs[thread_id], 16))
203