summaryrefslogtreecommitdiff
path: root/gdb-helpers/libcr.py
blob: c07b679cb16911c6956daf2b6d218ed451e3efa2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
# gdb-helpers/libcr.py - GDB helpers for libcr.
#
# Copyright (C) 2024  Luke T. Shumaker <lukeshu@lukeshu.com>
# SPDX-License-Identifier: AGPL-3.0-or-later

import contextlib
import time
import typing

import gdb
import gdb.unwinder

# GDB helpers ##################################################################


class _gdb_Locus(typing.Protocol):
    @property
    def frame_unwinders(self) -> list["gdb._Unwinder"]: ...


def gdb_unregister_unwinder(
    locus: gdb.Objfile | gdb.Progspace | None, unwinder: "gdb._Unwinder"
) -> None:
    _locus: _gdb_Locus = typing.cast(_gdb_Locus, gdb) if locus is None else locus
    _locus.frame_unwinders.remove(unwinder)
    gdb.invalidate_cached_frames()


class gdb_JmpBuf:
    """Our own in-Python GDB-specific implementation of `jmp_buf`"""

    level: int
    registers: dict[str, str]


def gdb_setjmp() -> gdb_JmpBuf:
    """Our own in-Python GDB-specific implementation of `setjmp()`"""
    buf = gdb_JmpBuf()
    buf.level = gdb.selected_frame().level()
    gdb.execute("select-frame level 0")
    buf.registers = {}
    for line in gdb.execute("info registers", to_string=True).split("\n"):
        words = line.split(maxsplit=2)
        if len(words) < 2:
            continue
        buf.registers[words[0]] = words[1]
    gdb.execute(f"select-frame level {buf.level}")
    return buf


def gdb_longjmp(buf: gdb_JmpBuf) -> None:
    """Our own in-Python GDB-specific implementation of `longjmp()`"""

    gdb.execute("select-frame level 0")

    if (
        ("sp" in buf.registers)
        and ("msp" in buf.registers)
        and ("psp" in buf.registers)
        and ("control" in buf.registers)
    ):
        # On ARM, 'sp' is an alias for either 'msp' or 'psp'
        # (depending on 'control'&(1<<1)).  We must set all 3 before
        # fussing with 'xPSR' or frames, or GDB will get upset at us
        # about "Invalid state".
        gdb.execute(f"set $sp = {buf.registers['sp']}", to_string=True)
        gdb.execute(f"set $msp = {buf.registers['msp']}")
        gdb.execute(f"set $psp = {buf.registers['psp']}")

    for reg, val in buf.registers.items():
        gdb.execute(f"set ${reg} = {val}")
    gdb.invalidate_cached_frames()

    gdb.execute(f"select-frame level {buf.level}")


# Core libcr functionality #####################################################


class CrGlobals:
    coroutines: list["CrCoroutine"]
    _breakpoint: "CrBreakpoint"
    _known_threads: set[gdb.InferiorThread]

    def __init__(self) -> None:
        num = int(
            gdb.parse_and_eval("sizeof(coroutine_table)/sizeof(coroutine_table[0])")
        )

        self.coroutines = [CrCoroutine(self, i + 1) for i in range(num)]

        self._breakpoint = CrBreakpoint()
        self._breakpoint.enabled = False

        self._known_threads = set()

        gdb.events.cont.connect(self._on_cont)

    def delete(self) -> None:
        self.coroutines = []
        self._breakpoint.delete()
        gdb.events.cont.disconnect(self._on_cont)

    def readjmp(self, env_ptr_expr: str) -> gdb_JmpBuf:
        self._breakpoint.enabled = True
        gdb.execute(f"call (void)cr_gdb_readjmp({env_ptr_expr})")
        self._breakpoint.enabled = False
        gdb.execute("queue-signal SIGWINCH")
        return self._breakpoint.env

    def _on_cont(self, event: gdb.Event) -> None:
        cur_threads = set(gdb.selected_inferior().threads())
        if cur_threads - self._known_threads:
            # Ignore thread creation events.
            self._known_threads = cur_threads
            return
        if self.coroutine_running:
            if not self.coroutine_running.is_selected():
                if True:  # https://sourceware.org/bugzilla/show_bug.cgi?id=32428
                    print("Must return to running coroutine before continuing.")
                    print("Hit ^C twice then run:")
                    print(f"  cr select {self.coroutine_running.id}")
                    while True:
                        time.sleep(1)
                assert self.coroutine_running._cont_env
                gdb_longjmp(self.coroutine_running._cont_env)
        for cr in self.coroutines:
            cr._cont_env = None

    def is_valid_cid(self, cid: int) -> bool:
        return 0 < cid and cid <= len(self.coroutines)

    @property
    def coroutine_running(self) -> "CrCoroutine | None":
        cid = int(gdb.parse_and_eval("coroutine_running"))
        if not self.is_valid_cid(cid):
            return None
        return self.coroutines[cid - 1]

    @property
    def coroutine_selected(self) -> "CrCoroutine | None":
        for cr in self.coroutines:
            if cr.is_selected():
                return cr
        return None

    @property
    def CR_NONE(self) -> gdb.Value:
        return gdb.parse_and_eval("CR_NONE")

    @property
    def CR_RUNNING(self) -> gdb.Value:
        return gdb.parse_and_eval("CR_RUNNING")


class CrBreakpointUnwinder(gdb.unwinder.Unwinder):
    """Used to temporarily disable unwinding so that
    gdb/breakpoint.c:check_longjmp_breakpoint_for_call_dummy() doesn't
    prematurely garbage collect the `call`-dummy-frame.

    """

    def __init__(self) -> None:
        super().__init__("cr_breakpoint_unwinder")

    # The .pyi is wrong; it says `Frame` instead of `PendingFrame`.
    def __call__(self, pending_frame: gdb.PendingFrame) -> gdb.UnwindInfo | None:
        # Stop unwinding with stop_reason=UNWIND_NO_SAVED_PC by
        # returning an UnwindInfo that doesn't have
        # `.add_saved_register("pc", ...)`.
        return pending_frame.create_unwind_info(
            gdb.unwinder.FrameId(
                sp=pending_frame.read_register("sp"),
                pc=pending_frame.read_register("pc"),
            )
        )


class CrBreakpoint(gdb.Breakpoint):
    env: gdb_JmpBuf
    _unwinder_locus: gdb.Objfile
    _unwinder: CrBreakpointUnwinder

    def __init__(self) -> None:
        self.env = gdb_JmpBuf()

        self._unwinder = CrBreakpointUnwinder()
        readjmp_sym = gdb.lookup_global_symbol("cr_gdb_readjmp")
        assert readjmp_sym
        self._unwinder_locus = readjmp_sym.symtab.objfile
        gdb.unwinder.register_unwinder(self._unwinder_locus, self._unwinder, True)
        self._unwinder.enabled = False

        super().__init__(
            function="cr_gdb_breakpoint", type=gdb.BP_BREAKPOINT, internal=True
        )

    @property
    def enabled(self) -> bool:
        return super().enabled

    @enabled.setter
    def enabled(self, value: bool) -> None:
        self._unwinder.enabled = value
        gdb.Breakpoint.enabled.__set__(self, value)  # type: ignore

    def stop(self) -> bool:
        assert self._unwinder.enabled
        self._unwinder.enabled = False
        self.env = gdb_setjmp()
        self._unwinder.enabled = True
        return False  # don't stop

    def delete(self) -> None:
        gdb_unregister_unwinder(self._unwinder_locus, self._unwinder)
        super().delete()


def cr_select_top_frame() -> None:
    gdb.execute("select-frame level 0")
    base_frame = gdb.selected_frame()
    while True:
        fn = gdb.selected_frame().name()
        if fn and (fn.startswith("cr_") or fn.startswith("_cr_")):
            older = gdb.selected_frame().older()
            if not older:
                base_frame.select()
                break
            older.select()
        else:
            break


class CrCoroutine:
    cr_globals: CrGlobals
    cid: int
    _cont_env: gdb_JmpBuf | None

    def __init__(self, cr_globals: CrGlobals, cid: int) -> None:
        self.cr_globals = cr_globals
        self.cid = cid
        self._cont_env = None

    @property
    def id(self) -> int:
        return self.cid

    @property
    def state(self) -> gdb.Value:
        return gdb.parse_and_eval(f"coroutine_table[{self.cid-1}].state")

    @property
    def name(self) -> str:
        bs: list[int] = [0] * int(gdb.parse_and_eval("sizeof(coroutine_table[0].name)"))
        for i, _ in enumerate(bs):
            bs[i] = int(gdb.parse_and_eval(f"coroutine_table[{self.cid-1}].name[{i}]"))
        return bytes(bs).decode("UTF-8").split("\x00", maxsplit=1)[0]

    def is_selected(self) -> bool:
        sp = int(gdb.parse_and_eval("$sp"))
        lo = int(gdb.parse_and_eval(f"coroutine_table[{self.id-1}].stack"))
        hi = lo + int(gdb.parse_and_eval(f"coroutine_table[{self.id-1}].stack_size"))
        return lo <= sp and sp < hi

    def select(self, level: int = -1) -> None:
        if self.cr_globals.coroutine_selected:
            self.cr_globals.coroutine_selected._cont_env = gdb_setjmp()

        if self._cont_env:
            gdb_longjmp(self._cont_env)
        else:
            env: gdb_JmpBuf
            if self == self.cr_globals.coroutine_running:
                assert False  # self._cont_env should have been set
            elif self.state == self.cr_globals.CR_RUNNING:
                env = self.cr_globals.readjmp("&coroutine_add_env")
            else:
                env = self.cr_globals.readjmp(f"&coroutine_table[{self.id-1}].env")
            gdb_longjmp(env)
            cr_select_top_frame()

    @contextlib.contextmanager
    def with_selected(self) -> typing.Iterator[None]:
        saved_env = gdb_setjmp()
        self.select()
        try:
            yield
        finally:
            gdb_longjmp(saved_env)


# User-facing commands #########################################################


class CrCommand(gdb.Command):
    """Use this command for libcr coroutines."""

    cr_globals: CrGlobals

    def __init__(self, cr_globals: CrGlobals) -> None:
        self.cr_globals = cr_globals
        gdb.Command.__init__(self, "cr", gdb.COMMAND_RUNNING, gdb.COMPLETE_NONE, True)

    def invoke(self, arg: str, from_tty: bool) -> None:
        gdb.execute("help cr")


class CrListCommand(gdb.Command):
    """List libcr coroutines.
    Usage: cr list

    In the output:
    - the 'R' marker indicates the currently-running coroutine
    - the 'G' marker indicates the coroutine that GDB is viewing; this may be changed with `cr select`
    """

    cr_globals: CrGlobals

    def __init__(self, cr_globals: CrGlobals) -> None:
        self.cr_globals = cr_globals
        gdb.Command.__init__(self, "cr list", gdb.COMMAND_RUNNING, gdb.COMPLETE_NONE)

    def invoke(self, arg: str, from_tty: bool) -> None:
        argv = gdb.string_to_argv(arg)
        if len(argv) != 0:
            raise gdb.GdbError(f"Usage: cr list")

        rows: list[tuple[str, str, str, str, str]] = [
            ("", "Id", "Name", "State", "Frame")
        ]
        for cr in self.cr_globals.coroutines:
            if cr.state == self.cr_globals.CR_NONE:
                continue
            rows += [
                (
                    "".join(
                        [
                            "R" if cr == self.cr_globals.coroutine_running else " ",
                            "G" if cr.is_selected() else " ",
                        ]
                    ),
                    str(cr.id),
                    repr(cr.name),
                    str(cr.state),
                    self._pretty_frame(cr, from_tty),
                )
            ]

        widths: list[int] = [
            max(len(row[col]) for row in rows) for col in range(len(rows[0]))
        ]

        def line(row: tuple[str, str, str, str, str]) -> str:

            def cell(col: int) -> str:
                return row[col].ljust(widths[col])

            return f"{cell(0)} {cell(1)}  {cell(2)}  {cell(3)}  {row[4]}"

        maxline = 0
        if screenwidth := gdb.parameter("width"):
            assert isinstance(screenwidth, int)
            maxline = max(screenwidth, len(line(rows[0])))

        for row in rows:
            l = line(row)
            if maxline and len(l) > maxline:
                l = l[:maxline]
            print(l)

    def _pretty_frame(self, cr: CrCoroutine, from_tty: bool) -> str:
        try:
            with cr.with_selected():
                saved_level = gdb.selected_frame().level()
                cr_select_top_frame()
                full = gdb.execute("frame", from_tty=from_tty, to_string=True)
                gdb.execute(f"select-frame level {saved_level}")
        except Exception as e:
            full = "#0 err: " + str(e)
        line = full.split("\n", maxsplit=1)[0]
        return line.split(maxsplit=1)[1]


class CrSelectCommand(gdb.Command):
    """Select the coroutine that GDB is viewing
    Usage: cr select COROUTINE
    COROUTINE is either a coroutine ID or coroutine name."""

    cr_globals: CrGlobals

    def __init__(self, cr_globals: CrGlobals) -> None:
        self.cr_globals = cr_globals
        gdb.Command.__init__(self, "cr select", gdb.COMMAND_RUNNING, gdb.COMPLETE_NONE)

    def invoke(self, arg: str, from_tty: bool) -> None:
        argv = gdb.string_to_argv(arg)
        if len(argv) != 1:
            raise gdb.GdbError("Usage: cr select COROUTINE")
        cr = self._find(argv[0])
        cr.select()
        gdb.execute("frame")

    def _find(self, name: str) -> CrCoroutine:
        if name.isnumeric():
            cid = int(name)
            if (
                self.cr_globals.is_valid_cid(cid)
                and self.cr_globals.coroutines[cid - 1].state != self.cr_globals.CR_NONE
            ):
                return self.cr_globals.coroutines[cid - 1]
        crs: list[CrCoroutine] = []
        for cr in self.cr_globals.coroutines:
            if cr.state != self.cr_globals.CR_NONE and cr.name == name:
                crs += [cr]
        match len(crs):
            case 0:
                raise gdb.GdbError(f"No such coroutine: {repr(name)}")
            case 1:
                return crs[0]
            case _:
                raise gdb.GdbError(f"Ambiguous name, must use Id: {repr(name)}")


# Wire it all in ###############################################################

cr_globals: CrGlobals | None = None


def cr_initialize() -> None:
    global cr_globals
    if cr_globals:
        old = cr_globals
        new = CrGlobals()
        for i in range(min(len(old.coroutines), len(new.coroutines))):
            new.coroutines[i]._cont_env = old.coroutines[i]._cont_env
        old.delete()
        cr_globals = new
    else:
        cr_globals = CrGlobals()
    CrCommand(cr_globals)
    CrListCommand(cr_globals)
    CrSelectCommand(cr_globals)


def cr_on_new_objfile(event: gdb.Event) -> None:
    if any(
        objfile.lookup_global_symbol("cr_gdb_readjmp") for objfile in gdb.objfiles()
    ):
        print("Initializing libcr integration...")
        cr_initialize()
        gdb.events.new_objfile.disconnect(cr_on_new_objfile)


if cr_globals:
    cr_initialize()
else:
    gdb.events.new_objfile.connect(cr_on_new_objfile)