1 /* Python frame unwinder interface.
3 Copyright (C) 2015-2021 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 "gdb_obstack.h"
26 #include "observable.h"
27 #include "python-internal.h"
31 /* Debugging of Python unwinders. */
33 static bool pyuw_debug;
35 /* Implementation of "show debug py-unwind". */
38 show_pyuw_debug (struct ui_file *file, int from_tty,
39 struct cmd_list_element *c, const char *value)
41 fprintf_filtered (file, _("Python unwinder debugging is %s.\n"), value);
44 /* Print a "py-unwind" debug statement. */
46 #define pyuw_debug_printf(fmt, ...) \
47 debug_prefixed_printf_cond (pyuw_debug, "py-unwind", fmt, ##__VA_ARGS__)
49 /* Print "py-unwind" enter/exit debug statements. */
51 #define PYUW_SCOPED_DEBUG_ENTER_EXIT \
52 scoped_debug_enter_exit (pyuw_debug, "py-unwind")
54 struct pending_frame_object
58 /* Frame we are unwinding. */
59 struct frame_info *frame_info;
61 /* Its architecture, passed by the sniffer caller. */
62 struct gdbarch *gdbarch;
65 /* Saved registers array item. */
69 saved_reg (int n, gdbpy_ref<> &&v)
79 /* The data we keep for the PyUnwindInfo: pending_frame, saved registers
82 struct unwind_info_object
86 /* gdb.PendingFrame for the frame we are unwinding. */
87 PyObject *pending_frame;
90 struct frame_id frame_id;
92 /* Saved registers array. */
93 std::vector<saved_reg> *saved_regs;
96 /* The data we keep for a frame we can unwind: frame ID and an array of
97 (register_number, register_value) pairs. */
99 struct cached_frame_info
102 struct frame_id frame_id;
104 /* GDB Architecture. */
105 struct gdbarch *gdbarch;
107 /* Length of the `reg' array below. */
113 extern PyTypeObject pending_frame_object_type
114 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("pending_frame_object");
116 extern PyTypeObject unwind_info_object_type
117 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("unwind_info_object");
119 static struct gdbarch_data *pyuw_gdbarch_data;
121 /* Convert gdb.Value instance to inferior's pointer. Return 1 on success,
125 pyuw_value_obj_to_pointer (PyObject *pyo_value, CORE_ADDR *addr)
132 if ((value = value_object_to_value (pyo_value)) != NULL)
134 *addr = unpack_pointer (value_type (value),
135 value_contents (value));
139 catch (const gdb_exception &except)
141 gdbpy_convert_exception (except);
146 /* Get attribute from an object and convert it to the inferior's
147 pointer value. Return 1 if attribute exists and its value can be
148 converted. Otherwise, if attribute does not exist or its value is
149 None, return 0. In all other cases set Python error and return
153 pyuw_object_attribute_to_pointer (PyObject *pyo, const char *attr_name,
158 if (PyObject_HasAttrString (pyo, attr_name))
160 gdbpy_ref<> pyo_value (PyObject_GetAttrString (pyo, attr_name));
162 if (pyo_value != NULL && pyo_value != Py_None)
164 rc = pyuw_value_obj_to_pointer (pyo_value.get (), addr);
168 _("The value of the '%s' attribute is not a pointer."),
175 /* Called by the Python interpreter to obtain string representation
176 of the UnwindInfo object. */
179 unwind_infopy_str (PyObject *self)
181 unwind_info_object *unwind_info = (unwind_info_object *) self;
184 stb.printf ("Frame ID: %s", unwind_info->frame_id.to_string ().c_str ());
186 const char *sep = "";
187 struct value_print_options opts;
189 get_user_print_options (&opts);
190 stb.printf ("\nSaved registers: (");
191 for (const saved_reg ® : *unwind_info->saved_regs)
193 struct value *value = value_object_to_value (reg.value.get ());
195 stb.printf ("%s(%d, ", sep, reg.number);
200 value_print (value, &stb, &opts);
203 catch (const gdb_exception &except)
205 GDB_PY_HANDLE_EXCEPTION (except);
215 return PyString_FromString (stb.c_str ());
218 /* Create UnwindInfo instance for given PendingFrame and frame ID.
219 Sets Python error and returns NULL on error. */
222 pyuw_create_unwind_info (PyObject *pyo_pending_frame,
223 struct frame_id frame_id)
225 unwind_info_object *unwind_info
226 = PyObject_New (unwind_info_object, &unwind_info_object_type);
228 if (((pending_frame_object *) pyo_pending_frame)->frame_info == NULL)
230 PyErr_SetString (PyExc_ValueError,
231 "Attempting to use stale PendingFrame");
234 unwind_info->frame_id = frame_id;
235 Py_INCREF (pyo_pending_frame);
236 unwind_info->pending_frame = pyo_pending_frame;
237 unwind_info->saved_regs = new std::vector<saved_reg>;
238 return (PyObject *) unwind_info;
241 /* The implementation of
242 gdb.UnwindInfo.add_saved_register (REG, VALUE) -> None. */
245 unwind_infopy_add_saved_register (PyObject *self, PyObject *args)
247 unwind_info_object *unwind_info = (unwind_info_object *) self;
248 pending_frame_object *pending_frame
249 = (pending_frame_object *) (unwind_info->pending_frame);
250 PyObject *pyo_reg_id;
251 PyObject *pyo_reg_value;
254 if (pending_frame->frame_info == NULL)
256 PyErr_SetString (PyExc_ValueError,
257 "UnwindInfo instance refers to a stale PendingFrame");
260 if (!PyArg_UnpackTuple (args, "previous_frame_register", 2, 2,
261 &pyo_reg_id, &pyo_reg_value))
263 if (!gdbpy_parse_register_id (pending_frame->gdbarch, pyo_reg_id, ®num))
265 PyErr_SetString (PyExc_ValueError, "Bad register");
272 if (pyo_reg_value == NULL
273 || (value = value_object_to_value (pyo_reg_value)) == NULL)
275 PyErr_SetString (PyExc_ValueError, "Bad register value");
278 data_size = register_size (pending_frame->gdbarch, regnum);
279 if (data_size != TYPE_LENGTH (value_type (value)))
283 "The value of the register returned by the Python "
284 "sniffer has unexpected size: %u instead of %u.",
285 (unsigned) TYPE_LENGTH (value_type (value)),
286 (unsigned) data_size);
291 gdbpy_ref<> new_value = gdbpy_ref<>::new_reference (pyo_reg_value);
293 for (saved_reg ® : *unwind_info->saved_regs)
295 if (regnum == reg.number)
298 reg.value = std::move (new_value);
303 unwind_info->saved_regs->emplace_back (regnum, std::move (new_value));
308 /* UnwindInfo cleanup. */
311 unwind_infopy_dealloc (PyObject *self)
313 unwind_info_object *unwind_info = (unwind_info_object *) self;
315 Py_XDECREF (unwind_info->pending_frame);
316 delete unwind_info->saved_regs;
317 Py_TYPE (self)->tp_free (self);
320 /* Called by the Python interpreter to obtain string representation
321 of the PendingFrame object. */
324 pending_framepy_str (PyObject *self)
326 struct frame_info *frame = ((pending_frame_object *) self)->frame_info;
327 const char *sp_str = NULL;
328 const char *pc_str = NULL;
331 return PyString_FromString ("Stale PendingFrame instance");
334 sp_str = core_addr_to_string_nz (get_frame_sp (frame));
335 pc_str = core_addr_to_string_nz (get_frame_pc (frame));
337 catch (const gdb_exception &except)
339 GDB_PY_HANDLE_EXCEPTION (except);
342 return PyString_FromFormat ("SP=%s,PC=%s", sp_str, pc_str);
345 /* Implementation of gdb.PendingFrame.read_register (self, reg) -> gdb.Value.
346 Returns the value of register REG as gdb.Value instance. */
349 pending_framepy_read_register (PyObject *self, PyObject *args)
351 pending_frame_object *pending_frame = (pending_frame_object *) self;
352 struct value *val = NULL;
354 PyObject *pyo_reg_id;
356 if (pending_frame->frame_info == NULL)
358 PyErr_SetString (PyExc_ValueError,
359 "Attempting to read register from stale PendingFrame");
362 if (!PyArg_UnpackTuple (args, "read_register", 1, 1, &pyo_reg_id))
364 if (!gdbpy_parse_register_id (pending_frame->gdbarch, pyo_reg_id, ®num))
366 PyErr_SetString (PyExc_ValueError, "Bad register");
372 /* Fetch the value associated with a register, whether it's
373 a real register or a so called "user" register, like "pc",
374 which maps to a real register. In the past,
375 get_frame_register_value() was used here, which did not
376 handle the user register case. */
377 val = value_of_register (regnum, pending_frame->frame_info);
379 PyErr_Format (PyExc_ValueError,
380 "Cannot read register %d from frame.",
383 catch (const gdb_exception &except)
385 GDB_PY_HANDLE_EXCEPTION (except);
388 return val == NULL ? NULL : value_to_value_object (val);
392 PendingFrame.create_unwind_info (self, frameId) -> UnwindInfo. */
395 pending_framepy_create_unwind_info (PyObject *self, PyObject *args)
397 PyObject *pyo_frame_id;
402 if (!PyArg_ParseTuple (args, "O:create_unwind_info", &pyo_frame_id))
404 if (!pyuw_object_attribute_to_pointer (pyo_frame_id, "sp", &sp))
406 PyErr_SetString (PyExc_ValueError,
407 _("frame_id should have 'sp' attribute."));
411 /* The logic of building frame_id depending on the attributes of
413 Has Has Has Function to call
414 'sp'? 'pc'? 'special'?
415 ------|------|--------------|-------------------------
416 Y N * frame_id_build_wild (sp)
417 Y Y N frame_id_build (sp, pc)
418 Y Y Y frame_id_build_special (sp, pc, special)
420 if (!pyuw_object_attribute_to_pointer (pyo_frame_id, "pc", &pc))
421 return pyuw_create_unwind_info (self, frame_id_build_wild (sp));
422 if (!pyuw_object_attribute_to_pointer (pyo_frame_id, "special", &special))
423 return pyuw_create_unwind_info (self, frame_id_build (sp, pc));
425 return pyuw_create_unwind_info (self,
426 frame_id_build_special (sp, pc, special));
429 /* Implementation of PendingFrame.architecture (self) -> gdb.Architecture. */
432 pending_framepy_architecture (PyObject *self, PyObject *args)
434 pending_frame_object *pending_frame = (pending_frame_object *) self;
436 if (pending_frame->frame_info == NULL)
438 PyErr_SetString (PyExc_ValueError,
439 "Attempting to read register from stale PendingFrame");
442 return gdbarch_to_arch_object (pending_frame->gdbarch);
445 /* frame_unwind.this_id method. */
448 pyuw_this_id (struct frame_info *this_frame, void **cache_ptr,
449 struct frame_id *this_id)
451 *this_id = ((cached_frame_info *) *cache_ptr)->frame_id;
452 pyuw_debug_printf ("frame_id: %s", this_id->to_string ().c_str ());
455 /* frame_unwind.prev_register. */
457 static struct value *
458 pyuw_prev_register (struct frame_info *this_frame, void **cache_ptr,
461 PYUW_SCOPED_DEBUG_ENTER_EXIT;
463 cached_frame_info *cached_frame = (cached_frame_info *) *cache_ptr;
464 cached_reg_t *reg_info = cached_frame->reg;
465 cached_reg_t *reg_info_end = reg_info + cached_frame->reg_count;
467 pyuw_debug_printf ("frame=%d, reg=%d",
468 frame_relative_level (this_frame), regnum);
469 for (; reg_info < reg_info_end; ++reg_info)
471 if (regnum == reg_info->num)
472 return frame_unwind_got_bytes (this_frame, regnum, reg_info->data);
475 return frame_unwind_got_optimized (this_frame, regnum);
478 /* Frame sniffer dispatch. */
481 pyuw_sniffer (const struct frame_unwind *self, struct frame_info *this_frame,
484 PYUW_SCOPED_DEBUG_ENTER_EXIT;
486 struct gdbarch *gdbarch = (struct gdbarch *) (self->unwind_data);
487 cached_frame_info *cached_frame;
489 gdbpy_enter enter_py (gdbarch, current_language);
491 pyuw_debug_printf ("frame=%d, sp=%s, pc=%s",
492 frame_relative_level (this_frame),
493 paddress (gdbarch, get_frame_sp (this_frame)),
494 paddress (gdbarch, get_frame_pc (this_frame)));
496 /* Create PendingFrame instance to pass to sniffers. */
497 pending_frame_object *pfo = PyObject_New (pending_frame_object,
498 &pending_frame_object_type);
499 gdbpy_ref<> pyo_pending_frame ((PyObject *) pfo);
500 if (pyo_pending_frame == NULL)
502 gdbpy_print_stack ();
505 pfo->gdbarch = gdbarch;
506 scoped_restore invalidate_frame = make_scoped_restore (&pfo->frame_info,
510 if (gdb_python_module == NULL
511 || ! PyObject_HasAttrString (gdb_python_module, "_execute_unwinders"))
513 PyErr_SetString (PyExc_NameError,
514 "Installation error: gdb._execute_unwinders function "
516 gdbpy_print_stack ();
519 gdbpy_ref<> pyo_execute (PyObject_GetAttrString (gdb_python_module,
520 "_execute_unwinders"));
521 if (pyo_execute == NULL)
523 gdbpy_print_stack ();
527 gdbpy_ref<> pyo_unwind_info
528 (PyObject_CallFunctionObjArgs (pyo_execute.get (),
529 pyo_pending_frame.get (), NULL));
530 if (pyo_unwind_info == NULL)
532 /* If the unwinder is cancelled due to a Ctrl-C, then propagate
533 the Ctrl-C as a GDB exception instead of swallowing it. */
534 gdbpy_print_stack_or_quit ();
537 if (pyo_unwind_info == Py_None)
540 /* Received UnwindInfo, cache data. */
541 if (PyObject_IsInstance (pyo_unwind_info.get (),
542 (PyObject *) &unwind_info_object_type) <= 0)
543 error (_("A Unwinder should return gdb.UnwindInfo instance."));
546 unwind_info_object *unwind_info =
547 (unwind_info_object *) pyo_unwind_info.get ();
548 int reg_count = unwind_info->saved_regs->size ();
551 = ((cached_frame_info *)
552 xmalloc (sizeof (*cached_frame)
553 + reg_count * sizeof (cached_frame->reg[0])));
554 cached_frame->gdbarch = gdbarch;
555 cached_frame->frame_id = unwind_info->frame_id;
556 cached_frame->reg_count = reg_count;
558 /* Populate registers array. */
559 for (int i = 0; i < unwind_info->saved_regs->size (); ++i)
561 saved_reg *reg = &(*unwind_info->saved_regs)[i];
563 struct value *value = value_object_to_value (reg->value.get ());
564 size_t data_size = register_size (gdbarch, reg->number);
566 cached_frame->reg[i].num = reg->number;
568 /* `value' validation was done before, just assert. */
569 gdb_assert (value != NULL);
570 gdb_assert (data_size == TYPE_LENGTH (value_type (value)));
572 cached_frame->reg[i].data = (gdb_byte *) xmalloc (data_size);
573 memcpy (cached_frame->reg[i].data, value_contents (value), data_size);
577 *cache_ptr = cached_frame;
578 pyuw_debug_printf ("frame claimed");
582 /* Frame cache release shim. */
585 pyuw_dealloc_cache (struct frame_info *this_frame, void *cache)
587 PYUW_SCOPED_DEBUG_ENTER_EXIT;
588 cached_frame_info *cached_frame = (cached_frame_info *) cache;
590 for (int i = 0; i < cached_frame->reg_count; i++)
591 xfree (cached_frame->reg[i].data);
596 struct pyuw_gdbarch_data_type
598 /* Has the unwinder shim been prepended? */
599 int unwinder_registered;
603 pyuw_gdbarch_data_init (struct gdbarch *gdbarch)
605 return GDBARCH_OBSTACK_ZALLOC (gdbarch, struct pyuw_gdbarch_data_type);
608 /* New inferior architecture callback: register the Python unwinders
612 pyuw_on_new_gdbarch (struct gdbarch *newarch)
614 struct pyuw_gdbarch_data_type *data
615 = (struct pyuw_gdbarch_data_type *) gdbarch_data (newarch,
618 if (!data->unwinder_registered)
620 struct frame_unwind *unwinder
621 = GDBARCH_OBSTACK_ZALLOC (newarch, struct frame_unwind);
623 unwinder->type = NORMAL_FRAME;
624 unwinder->stop_reason = default_frame_unwind_stop_reason;
625 unwinder->this_id = pyuw_this_id;
626 unwinder->prev_register = pyuw_prev_register;
627 unwinder->unwind_data = (const struct frame_data *) newarch;
628 unwinder->sniffer = pyuw_sniffer;
629 unwinder->dealloc_cache = pyuw_dealloc_cache;
630 frame_unwind_prepend_unwinder (newarch, unwinder);
631 data->unwinder_registered = 1;
635 void _initialize_py_unwind ();
637 _initialize_py_unwind ()
639 add_setshow_boolean_cmd
640 ("py-unwind", class_maintenance, &pyuw_debug,
641 _("Set Python unwinder debugging."),
642 _("Show Python unwinder debugging."),
643 _("When on, Python unwinder debugging is enabled."),
646 &setdebuglist, &showdebuglist);
648 = gdbarch_data_register_post_init (pyuw_gdbarch_data_init);
651 /* Initialize unwind machinery. */
654 gdbpy_initialize_unwind (void)
656 gdb::observers::architecture_changed.attach (pyuw_on_new_gdbarch,
659 if (PyType_Ready (&pending_frame_object_type) < 0)
661 int rc = gdb_pymodule_addobject (gdb_module, "PendingFrame",
662 (PyObject *) &pending_frame_object_type);
666 if (PyType_Ready (&unwind_info_object_type) < 0)
668 return gdb_pymodule_addobject (gdb_module, "UnwindInfo",
669 (PyObject *) &unwind_info_object_type);
672 static PyMethodDef pending_frame_object_methods[] =
674 { "read_register", pending_framepy_read_register, METH_VARARGS,
675 "read_register (REG) -> gdb.Value\n"
676 "Return the value of the REG in the frame." },
677 { "create_unwind_info",
678 pending_framepy_create_unwind_info, METH_VARARGS,
679 "create_unwind_info (FRAME_ID) -> gdb.UnwindInfo\n"
680 "Construct UnwindInfo for this PendingFrame, using FRAME_ID\n"
683 pending_framepy_architecture, METH_NOARGS,
684 "architecture () -> gdb.Architecture\n"
685 "The architecture for this PendingFrame." },
686 {NULL} /* Sentinel */
689 PyTypeObject pending_frame_object_type =
691 PyVarObject_HEAD_INIT (NULL, 0)
692 "gdb.PendingFrame", /* tp_name */
693 sizeof (pending_frame_object), /* tp_basicsize */
701 0, /* tp_as_number */
702 0, /* tp_as_sequence */
703 0, /* tp_as_mapping */
706 pending_framepy_str, /* tp_str */
709 0, /* tp_as_buffer */
710 Py_TPFLAGS_DEFAULT, /* tp_flags */
711 "GDB PendingFrame object", /* tp_doc */
714 0, /* tp_richcompare */
715 0, /* tp_weaklistoffset */
718 pending_frame_object_methods, /* tp_methods */
723 0, /* tp_descr_get */
724 0, /* tp_descr_set */
725 0, /* tp_dictoffset */
730 static PyMethodDef unwind_info_object_methods[] =
732 { "add_saved_register",
733 unwind_infopy_add_saved_register, METH_VARARGS,
734 "add_saved_register (REG, VALUE) -> None\n"
735 "Set the value of the REG in the previous frame to VALUE." },
736 { NULL } /* Sentinel */
739 PyTypeObject unwind_info_object_type =
741 PyVarObject_HEAD_INIT (NULL, 0)
742 "gdb.UnwindInfo", /* tp_name */
743 sizeof (unwind_info_object), /* tp_basicsize */
745 unwind_infopy_dealloc, /* tp_dealloc */
751 0, /* tp_as_number */
752 0, /* tp_as_sequence */
753 0, /* tp_as_mapping */
756 unwind_infopy_str, /* tp_str */
759 0, /* tp_as_buffer */
760 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
761 "GDB UnwindInfo object", /* tp_doc */
764 0, /* tp_richcompare */
765 0, /* tp_weaklistoffset */
768 unwind_info_object_methods, /* tp_methods */
773 0, /* tp_descr_get */
774 0, /* tp_descr_set */
775 0, /* tp_dictoffset */