1 /* Python frame unwinder interface.
3 Copyright (C) 2015-2016 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"
27 #include "python-internal.h"
30 #include "user-regs.h"
32 #define TRACE_PY_UNWIND(level, args...) if (pyuw_debug >= level) \
33 { fprintf_unfiltered (gdb_stdlog, args); }
39 /* Frame we are unwinding. */
40 struct frame_info *frame_info;
42 /* Its architecture, passed by the sniffer caller. */
43 struct gdbarch *gdbarch;
44 } pending_frame_object;
46 /* Saved registers array item. */
53 DEF_VEC_O (saved_reg);
55 /* The data we keep for the PyUnwindInfo: pending_frame, saved registers
62 /* gdb.PendingFrame for the frame we are unwinding. */
63 PyObject *pending_frame;
66 struct frame_id frame_id;
68 /* Saved registers array. */
69 VEC (saved_reg) *saved_regs;
72 /* The data we keep for a frame we can unwind: frame ID and an array of
73 (register_number, register_value) pairs. */
77 /* Register number. */
80 /* Register data bytes pointer. */
81 gdb_byte data[MAX_REGISTER_SIZE];
87 struct frame_id frame_id;
89 /* GDB Architecture. */
90 struct gdbarch *gdbarch;
92 /* Length of the `reg' array below. */
95 struct reg_info reg[];
98 extern PyTypeObject pending_frame_object_type
99 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("pending_frame_object");
101 extern PyTypeObject unwind_info_object_type
102 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("unwind_info_object");
104 static unsigned int pyuw_debug = 0;
106 static struct gdbarch_data *pyuw_gdbarch_data;
108 /* Parses register id, which can be either a number or a name.
109 Returns 1 on success, 0 otherwise. */
112 pyuw_parse_register_id (struct gdbarch *gdbarch, PyObject *pyo_reg_id,
115 if (pyo_reg_id == NULL)
117 if (gdbpy_is_string (pyo_reg_id))
119 const char *reg_name = gdbpy_obj_to_string (pyo_reg_id);
121 if (reg_name == NULL)
123 *reg_num = user_reg_map_name_to_regnum (gdbarch, reg_name,
125 return *reg_num >= 0;
127 else if (PyInt_Check (pyo_reg_id))
130 if (gdb_py_int_as_long (pyo_reg_id, &value) && (int) value == value)
132 *reg_num = (int) value;
133 return user_reg_map_regnum_to_name (gdbarch, *reg_num) != NULL;
139 /* Convert gdb.Value instance to inferior's pointer. Return 1 on success,
143 pyuw_value_obj_to_pointer (PyObject *pyo_value, CORE_ADDR *addr)
150 if ((value = value_object_to_value (pyo_value)) != NULL)
152 *addr = unpack_pointer (value_type (value),
153 value_contents (value));
157 CATCH (except, RETURN_MASK_ALL)
159 gdbpy_convert_exception (except);
165 /* Get attribute from an object and convert it to the inferior's
166 pointer value. Return 1 if attribute exists and its value can be
167 converted. Otherwise, if attribute does not exist or its value is
168 None, return 0. In all other cases set Python error and return
172 pyuw_object_attribute_to_pointer (PyObject *pyo, const char *attr_name,
177 if (PyObject_HasAttrString (pyo, attr_name))
179 PyObject *pyo_value = PyObject_GetAttrString (pyo, attr_name);
182 if (pyo_value != NULL && pyo_value != Py_None)
184 rc = pyuw_value_obj_to_pointer (pyo_value, addr);
188 _("The value of the '%s' attribute is not a pointer."),
191 Py_XDECREF (pyo_value);
196 /* Called by the Python interpreter to obtain string representation
197 of the UnwindInfo object. */
200 unwind_infopy_str (PyObject *self)
202 struct ui_file *strfile = mem_fileopen ();
203 unwind_info_object *unwind_info = (unwind_info_object *) self;
204 pending_frame_object *pending_frame
205 = (pending_frame_object *) (unwind_info->pending_frame);
208 fprintf_unfiltered (strfile, "Frame ID: ");
209 fprint_frame_id (strfile, unwind_info->frame_id);
213 struct value_print_options opts;
216 get_user_print_options (&opts);
217 fprintf_unfiltered (strfile, "\nSaved registers: (");
219 i < VEC_iterate (saved_reg, unwind_info->saved_regs, i, reg);
222 struct value *value = value_object_to_value (reg->value);
224 fprintf_unfiltered (strfile, "%s(%d, ", sep, reg->number);
229 value_print (value, strfile, &opts);
230 fprintf_unfiltered (strfile, ")");
232 CATCH (except, RETURN_MASK_ALL)
234 GDB_PY_HANDLE_EXCEPTION (except);
239 fprintf_unfiltered (strfile, "<BAD>)");
242 fprintf_unfiltered (strfile, ")");
245 char *s = ui_file_xstrdup (strfile, NULL);
247 result = PyString_FromString (s);
250 ui_file_delete (strfile);
254 /* Create UnwindInfo instance for given PendingFrame and frame ID.
255 Sets Python error and returns NULL on error. */
258 pyuw_create_unwind_info (PyObject *pyo_pending_frame,
259 struct frame_id frame_id)
261 unwind_info_object *unwind_info
262 = PyObject_New (unwind_info_object, &unwind_info_object_type);
264 if (((pending_frame_object *) pyo_pending_frame)->frame_info == NULL)
266 PyErr_SetString (PyExc_ValueError,
267 "Attempting to use stale PendingFrame");
270 unwind_info->frame_id = frame_id;
271 Py_INCREF (pyo_pending_frame);
272 unwind_info->pending_frame = pyo_pending_frame;
273 unwind_info->saved_regs = VEC_alloc (saved_reg, 4);
274 return (PyObject *) unwind_info;
277 /* The implementation of
278 gdb.UnwindInfo.add_saved_register (REG, VALUE) -> None. */
281 unwind_infopy_add_saved_register (PyObject *self, PyObject *args)
283 unwind_info_object *unwind_info = (unwind_info_object *) self;
284 pending_frame_object *pending_frame
285 = (pending_frame_object *) (unwind_info->pending_frame);
286 PyObject *pyo_reg_id;
287 PyObject *pyo_reg_value;
290 if (pending_frame->frame_info == NULL)
292 PyErr_SetString (PyExc_ValueError,
293 "UnwindInfo instance refers to a stale PendingFrame");
296 if (!PyArg_UnpackTuple (args, "previous_frame_register", 2, 2,
297 &pyo_reg_id, &pyo_reg_value))
299 if (!pyuw_parse_register_id (pending_frame->gdbarch, pyo_reg_id, ®num))
301 PyErr_SetString (PyExc_ValueError, "Bad register");
308 if (pyo_reg_value == NULL
309 || (value = value_object_to_value (pyo_reg_value)) == NULL)
311 PyErr_SetString (PyExc_ValueError, "Bad register value");
314 data_size = register_size (pending_frame->gdbarch, regnum);
315 if (data_size != TYPE_LENGTH (value_type (value)))
319 "The value of the register returned by the Python "
320 "sniffer has unexpected size: %u instead of %u.",
321 (unsigned) TYPE_LENGTH (value_type (value)),
322 (unsigned) data_size);
330 for (i = 0; VEC_iterate (saved_reg, unwind_info->saved_regs, i, reg); i++)
332 if (regnum == reg->number)
334 Py_DECREF (reg->value);
340 reg = VEC_safe_push (saved_reg, unwind_info->saved_regs, NULL);
341 reg->number = regnum;
343 Py_INCREF (pyo_reg_value);
344 reg->value = pyo_reg_value;
349 /* UnwindInfo cleanup. */
352 unwind_infopy_dealloc (PyObject *self)
354 unwind_info_object *unwind_info = (unwind_info_object *) self;
358 Py_XDECREF (unwind_info->pending_frame);
359 for (i = 0; VEC_iterate (saved_reg, unwind_info->saved_regs, i, reg); i++)
360 Py_DECREF (reg->value);
361 VEC_free (saved_reg, unwind_info->saved_regs);
362 Py_TYPE (self)->tp_free (self);
365 /* Called by the Python interpreter to obtain string representation
366 of the PendingFrame object. */
369 pending_framepy_str (PyObject *self)
371 struct frame_info *frame = ((pending_frame_object *) self)->frame_info;
372 const char *sp_str = NULL;
373 const char *pc_str = NULL;
376 return PyString_FromString ("Stale PendingFrame instance");
379 sp_str = core_addr_to_string_nz (get_frame_sp (frame));
380 pc_str = core_addr_to_string_nz (get_frame_pc (frame));
382 CATCH (except, RETURN_MASK_ALL)
384 GDB_PY_HANDLE_EXCEPTION (except);
388 return PyString_FromFormat ("SP=%s,PC=%s", sp_str, pc_str);
391 /* Implementation of gdb.PendingFrame.read_register (self, reg) -> gdb.Value.
392 Returns the value of register REG as gdb.Value instance. */
395 pending_framepy_read_register (PyObject *self, PyObject *args)
397 pending_frame_object *pending_frame = (pending_frame_object *) self;
398 struct value *val = NULL;
400 PyObject *pyo_reg_id;
402 if (pending_frame->frame_info == NULL)
404 PyErr_SetString (PyExc_ValueError,
405 "Attempting to read register from stale PendingFrame");
408 if (!PyArg_UnpackTuple (args, "read_register", 1, 1, &pyo_reg_id))
410 if (!pyuw_parse_register_id (pending_frame->gdbarch, pyo_reg_id, ®num))
412 PyErr_SetString (PyExc_ValueError, "Bad register");
418 val = get_frame_register_value (pending_frame->frame_info, regnum);
420 PyErr_Format (PyExc_ValueError,
421 "Cannot read register %d from frame.",
424 CATCH (except, RETURN_MASK_ALL)
426 GDB_PY_HANDLE_EXCEPTION (except);
430 return val == NULL ? NULL : value_to_value_object (val);
434 PendingFrame.create_unwind_info (self, frameId) -> UnwindInfo. */
437 pending_framepy_create_unwind_info (PyObject *self, PyObject *args)
439 PyObject *pyo_frame_id;
444 if (!PyArg_ParseTuple (args, "O:create_unwind_info", &pyo_frame_id))
446 if (!pyuw_object_attribute_to_pointer (pyo_frame_id, "sp", &sp))
448 PyErr_SetString (PyExc_ValueError,
449 _("frame_id should have 'sp' attribute."));
453 /* The logic of building frame_id depending on the attributes of
455 Has Has Has Function to call
456 'sp'? 'pc'? 'special'?
457 ------|------|--------------|-------------------------
458 Y N * frame_id_build_wild (sp)
459 Y Y N frame_id_build (sp, pc)
460 Y Y Y frame_id_build_special (sp, pc, special)
462 if (!pyuw_object_attribute_to_pointer (pyo_frame_id, "pc", &pc))
463 return pyuw_create_unwind_info (self, frame_id_build_wild (sp));
464 if (!pyuw_object_attribute_to_pointer (pyo_frame_id, "special", &special))
465 return pyuw_create_unwind_info (self, frame_id_build (sp, pc));
467 return pyuw_create_unwind_info (self,
468 frame_id_build_special (sp, pc, special));
471 /* Invalidate PendingFrame instance. */
474 pending_frame_invalidate (void *pyo_pending_frame)
476 if (pyo_pending_frame != NULL)
477 ((pending_frame_object *) pyo_pending_frame)->frame_info = NULL;
480 /* frame_unwind.this_id method. */
483 pyuw_this_id (struct frame_info *this_frame, void **cache_ptr,
484 struct frame_id *this_id)
486 *this_id = ((cached_frame_info *) *cache_ptr)->frame_id;
489 fprintf_unfiltered (gdb_stdlog, "%s: frame_id: ", __FUNCTION__);
490 fprint_frame_id (gdb_stdlog, *this_id);
491 fprintf_unfiltered (gdb_stdlog, "\n");
495 /* frame_unwind.prev_register. */
497 static struct value *
498 pyuw_prev_register (struct frame_info *this_frame, void **cache_ptr,
501 cached_frame_info *cached_frame = (cached_frame_info *) *cache_ptr;
502 struct reg_info *reg_info = cached_frame->reg;
503 struct reg_info *reg_info_end = reg_info + cached_frame->reg_count;
505 TRACE_PY_UNWIND (1, "%s (frame=%p,...,reg=%d)\n", __FUNCTION__, this_frame,
507 for (; reg_info < reg_info_end; ++reg_info)
509 if (regnum == reg_info->number)
510 return frame_unwind_got_bytes (this_frame, regnum, reg_info->data);
513 return frame_unwind_got_optimized (this_frame, regnum);
516 /* Frame sniffer dispatch. */
519 pyuw_sniffer (const struct frame_unwind *self, struct frame_info *this_frame,
522 struct gdbarch *gdbarch = (struct gdbarch *) (self->unwind_data);
523 struct cleanup *cleanups = ensure_python_env (gdbarch, current_language);
524 PyObject *pyo_execute;
525 PyObject *pyo_pending_frame;
526 PyObject *pyo_unwind_info;
527 cached_frame_info *cached_frame;
529 TRACE_PY_UNWIND (3, "%s (SP=%s, PC=%s)\n", __FUNCTION__,
530 paddress (gdbarch, get_frame_sp (this_frame)),
531 paddress (gdbarch, get_frame_pc (this_frame)));
533 /* Create PendingFrame instance to pass to sniffers. */
534 pyo_pending_frame = (PyObject *) PyObject_New (pending_frame_object,
535 &pending_frame_object_type);
536 if (pyo_pending_frame == NULL)
538 ((pending_frame_object *) pyo_pending_frame)->gdbarch = gdbarch;
539 ((pending_frame_object *) pyo_pending_frame)->frame_info = this_frame;
540 make_cleanup_py_decref (pyo_pending_frame);
541 make_cleanup (pending_frame_invalidate, (void *) pyo_pending_frame);
544 if (gdb_python_module == NULL
545 || ! PyObject_HasAttrString (gdb_python_module, "execute_unwinders"))
547 PyErr_SetString (PyExc_NameError,
548 "Installation error: gdb.execute_unwinders function "
552 pyo_execute = PyObject_GetAttrString (gdb_python_module, "execute_unwinders");
553 if (pyo_execute == NULL)
555 make_cleanup_py_decref (pyo_execute);
557 = PyObject_CallFunctionObjArgs (pyo_execute, pyo_pending_frame, NULL);
558 if (pyo_unwind_info == NULL)
560 make_cleanup_py_decref (pyo_unwind_info);
561 if (pyo_unwind_info == Py_None)
564 /* Received UnwindInfo, cache data. */
565 if (PyObject_IsInstance (pyo_unwind_info,
566 (PyObject *) &unwind_info_object_type) <= 0)
567 error (_("A Unwinder should return gdb.UnwindInfo instance."));
570 unwind_info_object *unwind_info = (unwind_info_object *) pyo_unwind_info;
571 int reg_count = VEC_length (saved_reg, unwind_info->saved_regs);
576 = ((cached_frame_info *)
577 xmalloc (sizeof (*cached_frame)
578 + reg_count * sizeof (cached_frame->reg[0])));
579 cached_frame->gdbarch = gdbarch;
580 cached_frame->frame_id = unwind_info->frame_id;
581 cached_frame->reg_count = reg_count;
583 /* Populate registers array. */
584 for (i = 0; VEC_iterate (saved_reg, unwind_info->saved_regs, i, reg); i++)
586 struct value *value = value_object_to_value (reg->value);
587 size_t data_size = register_size (gdbarch, reg->number);
589 cached_frame->reg[i].number = reg->number;
591 /* `value' validation was done before, just assert. */
592 gdb_assert (value != NULL);
593 gdb_assert (data_size == TYPE_LENGTH (value_type (value)));
594 gdb_assert (data_size <= MAX_REGISTER_SIZE);
596 memcpy (cached_frame->reg[i].data, value_contents (value), data_size);
600 *cache_ptr = cached_frame;
601 do_cleanups (cleanups);
605 gdbpy_print_stack ();
608 do_cleanups (cleanups);
612 /* Frame cache release shim. */
615 pyuw_dealloc_cache (struct frame_info *this_frame, void *cache)
617 TRACE_PY_UNWIND (3, "%s: enter", __FUNCTION__);
621 struct pyuw_gdbarch_data_type
623 /* Has the unwinder shim been prepended? */
624 int unwinder_registered;
628 pyuw_gdbarch_data_init (struct gdbarch *gdbarch)
630 return GDBARCH_OBSTACK_ZALLOC (gdbarch, struct pyuw_gdbarch_data_type);
633 /* New inferior architecture callback: register the Python unwinders
637 pyuw_on_new_gdbarch (struct gdbarch *newarch)
639 struct pyuw_gdbarch_data_type *data
640 = (struct pyuw_gdbarch_data_type *) gdbarch_data (newarch,
643 if (!data->unwinder_registered)
645 struct frame_unwind *unwinder
646 = GDBARCH_OBSTACK_ZALLOC (newarch, struct frame_unwind);
648 unwinder->type = NORMAL_FRAME;
649 unwinder->stop_reason = default_frame_unwind_stop_reason;
650 unwinder->this_id = pyuw_this_id;
651 unwinder->prev_register = pyuw_prev_register;
652 unwinder->unwind_data = (const struct frame_data *) newarch;
653 unwinder->sniffer = pyuw_sniffer;
654 unwinder->dealloc_cache = pyuw_dealloc_cache;
655 frame_unwind_prepend_unwinder (newarch, unwinder);
656 data->unwinder_registered = 1;
660 /* Initialize unwind machinery. */
663 gdbpy_initialize_unwind (void)
666 add_setshow_zuinteger_cmd
667 ("py-unwind", class_maintenance, &pyuw_debug,
668 _("Set Python unwinder debugging."),
669 _("Show Python unwinder debugging."),
670 _("When non-zero, Python unwinder debugging is enabled."),
673 &setdebuglist, &showdebuglist);
675 = gdbarch_data_register_post_init (pyuw_gdbarch_data_init);
676 observer_attach_architecture_changed (pyuw_on_new_gdbarch);
678 if (PyType_Ready (&pending_frame_object_type) < 0)
680 rc = gdb_pymodule_addobject (gdb_module, "PendingFrame",
681 (PyObject *) &pending_frame_object_type);
685 if (PyType_Ready (&unwind_info_object_type) < 0)
687 return gdb_pymodule_addobject (gdb_module, "UnwindInfo",
688 (PyObject *) &unwind_info_object_type);
691 static PyMethodDef pending_frame_object_methods[] =
693 { "read_register", pending_framepy_read_register, METH_VARARGS,
694 "read_register (REG) -> gdb.Value\n"
695 "Return the value of the REG in the frame." },
696 { "create_unwind_info",
697 pending_framepy_create_unwind_info, METH_VARARGS,
698 "create_unwind_info (FRAME_ID) -> gdb.UnwindInfo\n"
699 "Construct UnwindInfo for this PendingFrame, using FRAME_ID\n"
701 {NULL} /* Sentinel */
704 PyTypeObject pending_frame_object_type =
706 PyVarObject_HEAD_INIT (NULL, 0)
707 "gdb.PendingFrame", /* tp_name */
708 sizeof (pending_frame_object), /* tp_basicsize */
716 0, /* tp_as_number */
717 0, /* tp_as_sequence */
718 0, /* tp_as_mapping */
721 pending_framepy_str, /* tp_str */
724 0, /* tp_as_buffer */
725 Py_TPFLAGS_DEFAULT, /* tp_flags */
726 "GDB PendingFrame object", /* tp_doc */
729 0, /* tp_richcompare */
730 0, /* tp_weaklistoffset */
733 pending_frame_object_methods, /* tp_methods */
738 0, /* tp_descr_get */
739 0, /* tp_descr_set */
740 0, /* tp_dictoffset */
745 static PyMethodDef unwind_info_object_methods[] =
747 { "add_saved_register",
748 unwind_infopy_add_saved_register, METH_VARARGS,
749 "add_saved_register (REG, VALUE) -> None\n"
750 "Set the value of the REG in the previous frame to VALUE." },
751 { NULL } /* Sentinel */
754 PyTypeObject unwind_info_object_type =
756 PyVarObject_HEAD_INIT (NULL, 0)
757 "gdb.UnwindInfo", /* tp_name */
758 sizeof (unwind_info_object), /* tp_basicsize */
760 unwind_infopy_dealloc, /* tp_dealloc */
766 0, /* tp_as_number */
767 0, /* tp_as_sequence */
768 0, /* tp_as_mapping */
771 unwind_infopy_str, /* tp_str */
774 0, /* tp_as_buffer */
775 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
776 "GDB UnwindInfo object", /* tp_doc */
779 0, /* tp_richcompare */
780 0, /* tp_weaklistoffset */
783 unwind_info_object_methods, /* tp_methods */
788 0, /* tp_descr_get */
789 0, /* tp_descr_set */
790 0, /* tp_dictoffset */