1 /* Python frame unwinder interface.
3 Copyright (C) 2015-2023 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
21 #include "arch-utils.h"
22 #include "frame-unwind.h"
23 #include "gdbsupport/gdb_obstack.h"
26 #include "observable.h"
27 #include "python-internal.h"
30 #include "user-regs.h"
32 /* Debugging of Python unwinders. */
34 static bool pyuw_debug
;
36 /* Implementation of "show debug py-unwind". */
39 show_pyuw_debug (struct ui_file
*file
, int from_tty
,
40 struct cmd_list_element
*c
, const char *value
)
42 gdb_printf (file
, _("Python unwinder debugging is %s.\n"), value
);
45 /* Print a "py-unwind" debug statement. */
47 #define pyuw_debug_printf(fmt, ...) \
48 debug_prefixed_printf_cond (pyuw_debug, "py-unwind", fmt, ##__VA_ARGS__)
50 /* Print "py-unwind" enter/exit debug statements. */
52 #define PYUW_SCOPED_DEBUG_ENTER_EXIT \
53 scoped_debug_enter_exit (pyuw_debug, "py-unwind")
55 struct pending_frame_object
59 /* Frame we are unwinding. */
60 frame_info_ptr frame_info
;
62 /* Its architecture, passed by the sniffer caller. */
63 struct gdbarch
*gdbarch
;
66 /* Saved registers array item. */
70 saved_reg (int n
, gdbpy_ref
<> &&v
)
80 /* The data we keep for the PyUnwindInfo: pending_frame, saved registers
83 struct unwind_info_object
87 /* gdb.PendingFrame for the frame we are unwinding. */
88 PyObject
*pending_frame
;
91 struct frame_id frame_id
;
93 /* Saved registers array. */
94 std::vector
<saved_reg
> *saved_regs
;
97 /* The data we keep for a frame we can unwind: frame ID and an array of
98 (register_number, register_value) pairs. */
100 struct cached_frame_info
103 struct frame_id frame_id
;
105 /* GDB Architecture. */
106 struct gdbarch
*gdbarch
;
108 /* Length of the `reg' array below. */
114 extern PyTypeObject pending_frame_object_type
115 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("pending_frame_object");
117 extern PyTypeObject unwind_info_object_type
118 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("unwind_info_object");
120 /* Convert gdb.Value instance to inferior's pointer. Return 1 on success,
124 pyuw_value_obj_to_pointer (PyObject
*pyo_value
, CORE_ADDR
*addr
)
131 if ((value
= value_object_to_value (pyo_value
)) != NULL
)
133 *addr
= unpack_pointer (value_type (value
),
134 value_contents (value
).data ());
138 catch (const gdb_exception
&except
)
140 gdbpy_convert_exception (except
);
145 /* Get attribute from an object and convert it to the inferior's
146 pointer value. Return 1 if attribute exists and its value can be
147 converted. Otherwise, if attribute does not exist or its value is
148 None, return 0. In all other cases set Python error and return
152 pyuw_object_attribute_to_pointer (PyObject
*pyo
, const char *attr_name
,
157 if (PyObject_HasAttrString (pyo
, attr_name
))
159 gdbpy_ref
<> pyo_value (PyObject_GetAttrString (pyo
, attr_name
));
161 if (pyo_value
!= NULL
&& pyo_value
!= Py_None
)
163 rc
= pyuw_value_obj_to_pointer (pyo_value
.get (), addr
);
167 _("The value of the '%s' attribute is not a pointer."),
174 /* Called by the Python interpreter to obtain string representation
175 of the UnwindInfo object. */
178 unwind_infopy_str (PyObject
*self
)
180 unwind_info_object
*unwind_info
= (unwind_info_object
*) self
;
183 stb
.printf ("Frame ID: %s", unwind_info
->frame_id
.to_string ().c_str ());
185 const char *sep
= "";
186 struct value_print_options opts
;
188 get_user_print_options (&opts
);
189 stb
.printf ("\nSaved registers: (");
190 for (const saved_reg
®
: *unwind_info
->saved_regs
)
192 struct value
*value
= value_object_to_value (reg
.value
.get ());
194 stb
.printf ("%s(%d, ", sep
, reg
.number
);
199 value_print (value
, &stb
, &opts
);
202 catch (const gdb_exception
&except
)
204 GDB_PY_HANDLE_EXCEPTION (except
);
214 return PyUnicode_FromString (stb
.c_str ());
217 /* Create UnwindInfo instance for given PendingFrame and frame ID.
218 Sets Python error and returns NULL on error. */
221 pyuw_create_unwind_info (PyObject
*pyo_pending_frame
,
222 struct frame_id frame_id
)
224 unwind_info_object
*unwind_info
225 = PyObject_New (unwind_info_object
, &unwind_info_object_type
);
227 if (((pending_frame_object
*) pyo_pending_frame
)->frame_info
== NULL
)
229 PyErr_SetString (PyExc_ValueError
,
230 "Attempting to use stale PendingFrame");
233 unwind_info
->frame_id
= frame_id
;
234 Py_INCREF (pyo_pending_frame
);
235 unwind_info
->pending_frame
= pyo_pending_frame
;
236 unwind_info
->saved_regs
= new std::vector
<saved_reg
>;
237 return (PyObject
*) unwind_info
;
240 /* The implementation of
241 gdb.UnwindInfo.add_saved_register (REG, VALUE) -> None. */
244 unwind_infopy_add_saved_register (PyObject
*self
, PyObject
*args
)
246 unwind_info_object
*unwind_info
= (unwind_info_object
*) self
;
247 pending_frame_object
*pending_frame
248 = (pending_frame_object
*) (unwind_info
->pending_frame
);
249 PyObject
*pyo_reg_id
;
250 PyObject
*pyo_reg_value
;
253 if (pending_frame
->frame_info
== NULL
)
255 PyErr_SetString (PyExc_ValueError
,
256 "UnwindInfo instance refers to a stale PendingFrame");
259 if (!PyArg_UnpackTuple (args
, "previous_frame_register", 2, 2,
260 &pyo_reg_id
, &pyo_reg_value
))
262 if (!gdbpy_parse_register_id (pending_frame
->gdbarch
, pyo_reg_id
, ®num
))
265 /* If REGNUM identifies a user register then *maybe* we can convert this
266 to a real (i.e. non-user) register. The maybe qualifier is because we
267 don't know what user registers each target might add, however, the
268 following logic should work for the usual style of user registers,
269 where the read function just forwards the register read on to some
270 other register with no adjusting the value. */
271 if (regnum
>= gdbarch_num_cooked_regs (pending_frame
->gdbarch
))
273 struct value
*user_reg_value
274 = value_of_user_reg (regnum
, pending_frame
->frame_info
);
275 if (VALUE_LVAL (user_reg_value
) == lval_register
)
276 regnum
= VALUE_REGNUM (user_reg_value
);
277 if (regnum
>= gdbarch_num_cooked_regs (pending_frame
->gdbarch
))
279 PyErr_SetString (PyExc_ValueError
, "Bad register");
288 if (pyo_reg_value
== NULL
289 || (value
= value_object_to_value (pyo_reg_value
)) == NULL
)
291 PyErr_SetString (PyExc_ValueError
, "Bad register value");
294 data_size
= register_size (pending_frame
->gdbarch
, regnum
);
295 if (data_size
!= value_type (value
)->length ())
299 "The value of the register returned by the Python "
300 "sniffer has unexpected size: %u instead of %u.",
301 (unsigned) value_type (value
)->length (),
302 (unsigned) data_size
);
307 gdbpy_ref
<> new_value
= gdbpy_ref
<>::new_reference (pyo_reg_value
);
309 for (saved_reg
®
: *unwind_info
->saved_regs
)
311 if (regnum
== reg
.number
)
314 reg
.value
= std::move (new_value
);
319 unwind_info
->saved_regs
->emplace_back (regnum
, std::move (new_value
));
324 /* UnwindInfo cleanup. */
327 unwind_infopy_dealloc (PyObject
*self
)
329 unwind_info_object
*unwind_info
= (unwind_info_object
*) self
;
331 Py_XDECREF (unwind_info
->pending_frame
);
332 delete unwind_info
->saved_regs
;
333 Py_TYPE (self
)->tp_free (self
);
336 /* Called by the Python interpreter to obtain string representation
337 of the PendingFrame object. */
340 pending_framepy_str (PyObject
*self
)
342 frame_info_ptr frame
= ((pending_frame_object
*) self
)->frame_info
;
343 const char *sp_str
= NULL
;
344 const char *pc_str
= NULL
;
347 return PyUnicode_FromString ("Stale PendingFrame instance");
350 sp_str
= core_addr_to_string_nz (get_frame_sp (frame
));
351 pc_str
= core_addr_to_string_nz (get_frame_pc (frame
));
353 catch (const gdb_exception
&except
)
355 GDB_PY_HANDLE_EXCEPTION (except
);
358 return PyUnicode_FromFormat ("SP=%s,PC=%s", sp_str
, pc_str
);
361 /* Implementation of gdb.PendingFrame.read_register (self, reg) -> gdb.Value.
362 Returns the value of register REG as gdb.Value instance. */
365 pending_framepy_read_register (PyObject
*self
, PyObject
*args
)
367 pending_frame_object
*pending_frame
= (pending_frame_object
*) self
;
368 struct value
*val
= NULL
;
370 PyObject
*pyo_reg_id
;
372 if (pending_frame
->frame_info
== NULL
)
374 PyErr_SetString (PyExc_ValueError
,
375 "Attempting to read register from stale PendingFrame");
378 if (!PyArg_UnpackTuple (args
, "read_register", 1, 1, &pyo_reg_id
))
380 if (!gdbpy_parse_register_id (pending_frame
->gdbarch
, pyo_reg_id
, ®num
))
385 /* Fetch the value associated with a register, whether it's
386 a real register or a so called "user" register, like "pc",
387 which maps to a real register. In the past,
388 get_frame_register_value() was used here, which did not
389 handle the user register case. */
390 val
= value_of_register (regnum
, pending_frame
->frame_info
);
392 PyErr_Format (PyExc_ValueError
,
393 "Cannot read register %d from frame.",
396 catch (const gdb_exception
&except
)
398 GDB_PY_HANDLE_EXCEPTION (except
);
401 return val
== NULL
? NULL
: value_to_value_object (val
);
405 PendingFrame.create_unwind_info (self, frameId) -> UnwindInfo. */
408 pending_framepy_create_unwind_info (PyObject
*self
, PyObject
*args
)
410 PyObject
*pyo_frame_id
;
415 if (!PyArg_ParseTuple (args
, "O:create_unwind_info", &pyo_frame_id
))
417 if (!pyuw_object_attribute_to_pointer (pyo_frame_id
, "sp", &sp
))
419 PyErr_SetString (PyExc_ValueError
,
420 _("frame_id should have 'sp' attribute."));
424 /* The logic of building frame_id depending on the attributes of
426 Has Has Has Function to call
427 'sp'? 'pc'? 'special'?
428 ------|------|--------------|-------------------------
429 Y N * frame_id_build_wild (sp)
430 Y Y N frame_id_build (sp, pc)
431 Y Y Y frame_id_build_special (sp, pc, special)
433 if (!pyuw_object_attribute_to_pointer (pyo_frame_id
, "pc", &pc
))
434 return pyuw_create_unwind_info (self
, frame_id_build_wild (sp
));
435 if (!pyuw_object_attribute_to_pointer (pyo_frame_id
, "special", &special
))
436 return pyuw_create_unwind_info (self
, frame_id_build (sp
, pc
));
438 return pyuw_create_unwind_info (self
,
439 frame_id_build_special (sp
, pc
, special
));
442 /* Implementation of PendingFrame.architecture (self) -> gdb.Architecture. */
445 pending_framepy_architecture (PyObject
*self
, PyObject
*args
)
447 pending_frame_object
*pending_frame
= (pending_frame_object
*) self
;
449 if (pending_frame
->frame_info
== NULL
)
451 PyErr_SetString (PyExc_ValueError
,
452 "Attempting to read register from stale PendingFrame");
455 return gdbarch_to_arch_object (pending_frame
->gdbarch
);
458 /* Implementation of PendingFrame.level (self) -> Integer. */
461 pending_framepy_level (PyObject
*self
, PyObject
*args
)
463 pending_frame_object
*pending_frame
= (pending_frame_object
*) self
;
465 if (pending_frame
->frame_info
== NULL
)
467 PyErr_SetString (PyExc_ValueError
,
468 "Attempting to read stack level from stale PendingFrame");
471 int level
= frame_relative_level (pending_frame
->frame_info
);
472 return gdb_py_object_from_longest (level
).release ();
475 /* frame_unwind.this_id method. */
478 pyuw_this_id (frame_info_ptr this_frame
, void **cache_ptr
,
479 struct frame_id
*this_id
)
481 *this_id
= ((cached_frame_info
*) *cache_ptr
)->frame_id
;
482 pyuw_debug_printf ("frame_id: %s", this_id
->to_string ().c_str ());
485 /* frame_unwind.prev_register. */
487 static struct value
*
488 pyuw_prev_register (frame_info_ptr this_frame
, void **cache_ptr
,
491 PYUW_SCOPED_DEBUG_ENTER_EXIT
;
493 cached_frame_info
*cached_frame
= (cached_frame_info
*) *cache_ptr
;
494 cached_reg_t
*reg_info
= cached_frame
->reg
;
495 cached_reg_t
*reg_info_end
= reg_info
+ cached_frame
->reg_count
;
497 pyuw_debug_printf ("frame=%d, reg=%d",
498 frame_relative_level (this_frame
), regnum
);
499 for (; reg_info
< reg_info_end
; ++reg_info
)
501 if (regnum
== reg_info
->num
)
502 return frame_unwind_got_bytes (this_frame
, regnum
, reg_info
->data
);
505 return frame_unwind_got_optimized (this_frame
, regnum
);
508 /* Frame sniffer dispatch. */
511 pyuw_sniffer (const struct frame_unwind
*self
, frame_info_ptr this_frame
,
514 PYUW_SCOPED_DEBUG_ENTER_EXIT
;
516 struct gdbarch
*gdbarch
= (struct gdbarch
*) (self
->unwind_data
);
517 cached_frame_info
*cached_frame
;
519 gdbpy_enter
enter_py (gdbarch
);
521 pyuw_debug_printf ("frame=%d, sp=%s, pc=%s",
522 frame_relative_level (this_frame
),
523 paddress (gdbarch
, get_frame_sp (this_frame
)),
524 paddress (gdbarch
, get_frame_pc (this_frame
)));
526 /* Create PendingFrame instance to pass to sniffers. */
527 pending_frame_object
*pfo
= PyObject_New (pending_frame_object
,
528 &pending_frame_object_type
);
529 gdbpy_ref
<> pyo_pending_frame ((PyObject
*) pfo
);
530 if (pyo_pending_frame
== NULL
)
532 gdbpy_print_stack ();
535 pfo
->gdbarch
= gdbarch
;
536 scoped_restore invalidate_frame
= make_scoped_restore (&pfo
->frame_info
,
540 if (gdb_python_module
== NULL
541 || ! PyObject_HasAttrString (gdb_python_module
, "_execute_unwinders"))
543 PyErr_SetString (PyExc_NameError
,
544 "Installation error: gdb._execute_unwinders function "
546 gdbpy_print_stack ();
549 gdbpy_ref
<> pyo_execute (PyObject_GetAttrString (gdb_python_module
,
550 "_execute_unwinders"));
551 if (pyo_execute
== nullptr)
553 gdbpy_print_stack ();
557 /* A (gdb.UnwindInfo, str) tuple, or None. */
558 gdbpy_ref
<> pyo_execute_ret
559 (PyObject_CallFunctionObjArgs (pyo_execute
.get (),
560 pyo_pending_frame
.get (), NULL
));
561 if (pyo_execute_ret
== nullptr)
563 /* If the unwinder is cancelled due to a Ctrl-C, then propagate
564 the Ctrl-C as a GDB exception instead of swallowing it. */
565 gdbpy_print_stack_or_quit ();
568 if (pyo_execute_ret
== Py_None
)
571 /* Verify the return value of _execute_unwinders is a tuple of size 2. */
572 gdb_assert (PyTuple_Check (pyo_execute_ret
.get ()));
573 gdb_assert (PyTuple_GET_SIZE (pyo_execute_ret
.get ()) == 2);
577 PyObject
*pyo_unwinder_name
= PyTuple_GET_ITEM (pyo_execute_ret
.get (), 1);
578 gdb::unique_xmalloc_ptr
<char> name
579 = python_string_to_host_string (pyo_unwinder_name
);
581 /* This could happen if the user passed something else than a string
582 as the unwinder's name. */
585 gdbpy_print_stack ();
586 name
= make_unique_xstrdup ("<failed to get unwinder name>");
589 pyuw_debug_printf ("frame claimed by unwinder %s", name
.get ());
592 /* Received UnwindInfo, cache data. */
593 PyObject
*pyo_unwind_info
= PyTuple_GET_ITEM (pyo_execute_ret
.get (), 0);
594 if (PyObject_IsInstance (pyo_unwind_info
,
595 (PyObject
*) &unwind_info_object_type
) <= 0)
596 error (_("A Unwinder should return gdb.UnwindInfo instance."));
599 unwind_info_object
*unwind_info
=
600 (unwind_info_object
*) pyo_unwind_info
;
601 int reg_count
= unwind_info
->saved_regs
->size ();
604 = ((cached_frame_info
*)
605 xmalloc (sizeof (*cached_frame
)
606 + reg_count
* sizeof (cached_frame
->reg
[0])));
607 cached_frame
->gdbarch
= gdbarch
;
608 cached_frame
->frame_id
= unwind_info
->frame_id
;
609 cached_frame
->reg_count
= reg_count
;
611 /* Populate registers array. */
612 for (int i
= 0; i
< unwind_info
->saved_regs
->size (); ++i
)
614 saved_reg
*reg
= &(*unwind_info
->saved_regs
)[i
];
616 struct value
*value
= value_object_to_value (reg
->value
.get ());
617 size_t data_size
= register_size (gdbarch
, reg
->number
);
619 cached_frame
->reg
[i
].num
= reg
->number
;
621 /* `value' validation was done before, just assert. */
622 gdb_assert (value
!= NULL
);
623 gdb_assert (data_size
== value_type (value
)->length ());
625 cached_frame
->reg
[i
].data
= (gdb_byte
*) xmalloc (data_size
);
626 memcpy (cached_frame
->reg
[i
].data
,
627 value_contents (value
).data (), data_size
);
631 *cache_ptr
= cached_frame
;
635 /* Frame cache release shim. */
638 pyuw_dealloc_cache (frame_info
*this_frame
, void *cache
)
640 PYUW_SCOPED_DEBUG_ENTER_EXIT
;
641 cached_frame_info
*cached_frame
= (cached_frame_info
*) cache
;
643 for (int i
= 0; i
< cached_frame
->reg_count
; i
++)
644 xfree (cached_frame
->reg
[i
].data
);
649 struct pyuw_gdbarch_data_type
651 /* Has the unwinder shim been prepended? */
652 int unwinder_registered
= 0;
655 static const registry
<gdbarch
>::key
<pyuw_gdbarch_data_type
> pyuw_gdbarch_data
;
657 /* New inferior architecture callback: register the Python unwinders
661 pyuw_on_new_gdbarch (struct gdbarch
*newarch
)
663 struct pyuw_gdbarch_data_type
*data
= pyuw_gdbarch_data
.get (newarch
);
665 data
= pyuw_gdbarch_data
.emplace (newarch
);
667 if (!data
->unwinder_registered
)
669 struct frame_unwind
*unwinder
670 = GDBARCH_OBSTACK_ZALLOC (newarch
, struct frame_unwind
);
672 unwinder
->name
= "python";
673 unwinder
->type
= NORMAL_FRAME
;
674 unwinder
->stop_reason
= default_frame_unwind_stop_reason
;
675 unwinder
->this_id
= pyuw_this_id
;
676 unwinder
->prev_register
= pyuw_prev_register
;
677 unwinder
->unwind_data
= (const struct frame_data
*) newarch
;
678 unwinder
->sniffer
= pyuw_sniffer
;
679 unwinder
->dealloc_cache
= pyuw_dealloc_cache
;
680 frame_unwind_prepend_unwinder (newarch
, unwinder
);
681 data
->unwinder_registered
= 1;
685 void _initialize_py_unwind ();
687 _initialize_py_unwind ()
689 add_setshow_boolean_cmd
690 ("py-unwind", class_maintenance
, &pyuw_debug
,
691 _("Set Python unwinder debugging."),
692 _("Show Python unwinder debugging."),
693 _("When on, Python unwinder debugging is enabled."),
696 &setdebuglist
, &showdebuglist
);
699 /* Initialize unwind machinery. */
702 gdbpy_initialize_unwind (void)
704 gdb::observers::architecture_changed
.attach (pyuw_on_new_gdbarch
,
707 if (PyType_Ready (&pending_frame_object_type
) < 0)
709 int rc
= gdb_pymodule_addobject (gdb_module
, "PendingFrame",
710 (PyObject
*) &pending_frame_object_type
);
714 if (PyType_Ready (&unwind_info_object_type
) < 0)
716 return gdb_pymodule_addobject (gdb_module
, "UnwindInfo",
717 (PyObject
*) &unwind_info_object_type
);
720 static PyMethodDef pending_frame_object_methods
[] =
722 { "read_register", pending_framepy_read_register
, METH_VARARGS
,
723 "read_register (REG) -> gdb.Value\n"
724 "Return the value of the REG in the frame." },
725 { "create_unwind_info",
726 pending_framepy_create_unwind_info
, METH_VARARGS
,
727 "create_unwind_info (FRAME_ID) -> gdb.UnwindInfo\n"
728 "Construct UnwindInfo for this PendingFrame, using FRAME_ID\n"
731 pending_framepy_architecture
, METH_NOARGS
,
732 "architecture () -> gdb.Architecture\n"
733 "The architecture for this PendingFrame." },
734 { "level", pending_framepy_level
, METH_NOARGS
,
735 "The stack level of this frame." },
736 {NULL
} /* Sentinel */
739 PyTypeObject pending_frame_object_type
=
741 PyVarObject_HEAD_INIT (NULL
, 0)
742 "gdb.PendingFrame", /* tp_name */
743 sizeof (pending_frame_object
), /* tp_basicsize */
751 0, /* tp_as_number */
752 0, /* tp_as_sequence */
753 0, /* tp_as_mapping */
756 pending_framepy_str
, /* tp_str */
759 0, /* tp_as_buffer */
760 Py_TPFLAGS_DEFAULT
, /* tp_flags */
761 "GDB PendingFrame object", /* tp_doc */
764 0, /* tp_richcompare */
765 0, /* tp_weaklistoffset */
768 pending_frame_object_methods
, /* tp_methods */
773 0, /* tp_descr_get */
774 0, /* tp_descr_set */
775 0, /* tp_dictoffset */
780 static PyMethodDef unwind_info_object_methods
[] =
782 { "add_saved_register",
783 unwind_infopy_add_saved_register
, METH_VARARGS
,
784 "add_saved_register (REG, VALUE) -> None\n"
785 "Set the value of the REG in the previous frame to VALUE." },
786 { NULL
} /* Sentinel */
789 PyTypeObject unwind_info_object_type
=
791 PyVarObject_HEAD_INIT (NULL
, 0)
792 "gdb.UnwindInfo", /* tp_name */
793 sizeof (unwind_info_object
), /* tp_basicsize */
795 unwind_infopy_dealloc
, /* tp_dealloc */
801 0, /* tp_as_number */
802 0, /* tp_as_sequence */
803 0, /* tp_as_mapping */
806 unwind_infopy_str
, /* tp_str */
809 0, /* tp_as_buffer */
810 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
811 "GDB UnwindInfo object", /* tp_doc */
814 0, /* tp_richcompare */
815 0, /* tp_weaklistoffset */
818 unwind_info_object_methods
, /* tp_methods */
823 0, /* tp_descr_get */
824 0, /* tp_descr_set */
825 0, /* tp_dictoffset */