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);
181 if (pyo_value != NULL && pyo_value != Py_None)
183 rc = pyuw_value_obj_to_pointer (pyo_value, addr);
187 _("The value of the '%s' attribute is not a pointer."),
190 Py_XDECREF (pyo_value);
195 /* Called by the Python interpreter to obtain string representation
196 of the UnwindInfo object. */
199 unwind_infopy_str (PyObject *self)
201 struct ui_file *strfile = mem_fileopen ();
202 unwind_info_object *unwind_info = (unwind_info_object *) self;
205 fprintf_unfiltered (strfile, "Frame ID: ");
206 fprint_frame_id (strfile, unwind_info->frame_id);
210 struct value_print_options opts;
213 get_user_print_options (&opts);
214 fprintf_unfiltered (strfile, "\nSaved registers: (");
215 for (i = 0; VEC_iterate (saved_reg, unwind_info->saved_regs, i, reg); i++)
217 struct value *value = value_object_to_value (reg->value);
219 fprintf_unfiltered (strfile, "%s(%d, ", sep, reg->number);
224 value_print (value, strfile, &opts);
225 fprintf_unfiltered (strfile, ")");
227 CATCH (except, RETURN_MASK_ALL)
229 GDB_PY_HANDLE_EXCEPTION (except);
234 fprintf_unfiltered (strfile, "<BAD>)");
237 fprintf_unfiltered (strfile, ")");
240 char *s = ui_file_xstrdup (strfile, NULL);
242 result = PyString_FromString (s);
245 ui_file_delete (strfile);
249 /* Create UnwindInfo instance for given PendingFrame and frame ID.
250 Sets Python error and returns NULL on error. */
253 pyuw_create_unwind_info (PyObject *pyo_pending_frame,
254 struct frame_id frame_id)
256 unwind_info_object *unwind_info
257 = PyObject_New (unwind_info_object, &unwind_info_object_type);
259 if (((pending_frame_object *) pyo_pending_frame)->frame_info == NULL)
261 PyErr_SetString (PyExc_ValueError,
262 "Attempting to use stale PendingFrame");
265 unwind_info->frame_id = frame_id;
266 Py_INCREF (pyo_pending_frame);
267 unwind_info->pending_frame = pyo_pending_frame;
268 unwind_info->saved_regs = VEC_alloc (saved_reg, 4);
269 return (PyObject *) unwind_info;
272 /* The implementation of
273 gdb.UnwindInfo.add_saved_register (REG, VALUE) -> None. */
276 unwind_infopy_add_saved_register (PyObject *self, PyObject *args)
278 unwind_info_object *unwind_info = (unwind_info_object *) self;
279 pending_frame_object *pending_frame
280 = (pending_frame_object *) (unwind_info->pending_frame);
281 PyObject *pyo_reg_id;
282 PyObject *pyo_reg_value;
285 if (pending_frame->frame_info == NULL)
287 PyErr_SetString (PyExc_ValueError,
288 "UnwindInfo instance refers to a stale PendingFrame");
291 if (!PyArg_UnpackTuple (args, "previous_frame_register", 2, 2,
292 &pyo_reg_id, &pyo_reg_value))
294 if (!pyuw_parse_register_id (pending_frame->gdbarch, pyo_reg_id, ®num))
296 PyErr_SetString (PyExc_ValueError, "Bad register");
303 if (pyo_reg_value == NULL
304 || (value = value_object_to_value (pyo_reg_value)) == NULL)
306 PyErr_SetString (PyExc_ValueError, "Bad register value");
309 data_size = register_size (pending_frame->gdbarch, regnum);
310 if (data_size != TYPE_LENGTH (value_type (value)))
314 "The value of the register returned by the Python "
315 "sniffer has unexpected size: %u instead of %u.",
316 (unsigned) TYPE_LENGTH (value_type (value)),
317 (unsigned) data_size);
325 for (i = 0; VEC_iterate (saved_reg, unwind_info->saved_regs, i, reg); i++)
327 if (regnum == reg->number)
329 Py_DECREF (reg->value);
335 reg = VEC_safe_push (saved_reg, unwind_info->saved_regs, NULL);
336 reg->number = regnum;
338 Py_INCREF (pyo_reg_value);
339 reg->value = pyo_reg_value;
344 /* UnwindInfo cleanup. */
347 unwind_infopy_dealloc (PyObject *self)
349 unwind_info_object *unwind_info = (unwind_info_object *) self;
353 Py_XDECREF (unwind_info->pending_frame);
354 for (i = 0; VEC_iterate (saved_reg, unwind_info->saved_regs, i, reg); i++)
355 Py_DECREF (reg->value);
356 VEC_free (saved_reg, unwind_info->saved_regs);
357 Py_TYPE (self)->tp_free (self);
360 /* Called by the Python interpreter to obtain string representation
361 of the PendingFrame object. */
364 pending_framepy_str (PyObject *self)
366 struct frame_info *frame = ((pending_frame_object *) self)->frame_info;
367 const char *sp_str = NULL;
368 const char *pc_str = NULL;
371 return PyString_FromString ("Stale PendingFrame instance");
374 sp_str = core_addr_to_string_nz (get_frame_sp (frame));
375 pc_str = core_addr_to_string_nz (get_frame_pc (frame));
377 CATCH (except, RETURN_MASK_ALL)
379 GDB_PY_HANDLE_EXCEPTION (except);
383 return PyString_FromFormat ("SP=%s,PC=%s", sp_str, pc_str);
386 /* Implementation of gdb.PendingFrame.read_register (self, reg) -> gdb.Value.
387 Returns the value of register REG as gdb.Value instance. */
390 pending_framepy_read_register (PyObject *self, PyObject *args)
392 pending_frame_object *pending_frame = (pending_frame_object *) self;
393 struct value *val = NULL;
395 PyObject *pyo_reg_id;
397 if (pending_frame->frame_info == NULL)
399 PyErr_SetString (PyExc_ValueError,
400 "Attempting to read register from stale PendingFrame");
403 if (!PyArg_UnpackTuple (args, "read_register", 1, 1, &pyo_reg_id))
405 if (!pyuw_parse_register_id (pending_frame->gdbarch, pyo_reg_id, ®num))
407 PyErr_SetString (PyExc_ValueError, "Bad register");
413 val = get_frame_register_value (pending_frame->frame_info, regnum);
415 PyErr_Format (PyExc_ValueError,
416 "Cannot read register %d from frame.",
419 CATCH (except, RETURN_MASK_ALL)
421 GDB_PY_HANDLE_EXCEPTION (except);
425 return val == NULL ? NULL : value_to_value_object (val);
429 PendingFrame.create_unwind_info (self, frameId) -> UnwindInfo. */
432 pending_framepy_create_unwind_info (PyObject *self, PyObject *args)
434 PyObject *pyo_frame_id;
439 if (!PyArg_ParseTuple (args, "O:create_unwind_info", &pyo_frame_id))
441 if (!pyuw_object_attribute_to_pointer (pyo_frame_id, "sp", &sp))
443 PyErr_SetString (PyExc_ValueError,
444 _("frame_id should have 'sp' attribute."));
448 /* The logic of building frame_id depending on the attributes of
450 Has Has Has Function to call
451 'sp'? 'pc'? 'special'?
452 ------|------|--------------|-------------------------
453 Y N * frame_id_build_wild (sp)
454 Y Y N frame_id_build (sp, pc)
455 Y Y Y frame_id_build_special (sp, pc, special)
457 if (!pyuw_object_attribute_to_pointer (pyo_frame_id, "pc", &pc))
458 return pyuw_create_unwind_info (self, frame_id_build_wild (sp));
459 if (!pyuw_object_attribute_to_pointer (pyo_frame_id, "special", &special))
460 return pyuw_create_unwind_info (self, frame_id_build (sp, pc));
462 return pyuw_create_unwind_info (self,
463 frame_id_build_special (sp, pc, special));
466 /* Invalidate PendingFrame instance. */
469 pending_frame_invalidate (void *pyo_pending_frame)
471 if (pyo_pending_frame != NULL)
472 ((pending_frame_object *) pyo_pending_frame)->frame_info = NULL;
475 /* frame_unwind.this_id method. */
478 pyuw_this_id (struct frame_info *this_frame, void **cache_ptr,
479 struct frame_id *this_id)
481 *this_id = ((cached_frame_info *) *cache_ptr)->frame_id;
484 fprintf_unfiltered (gdb_stdlog, "%s: frame_id: ", __FUNCTION__);
485 fprint_frame_id (gdb_stdlog, *this_id);
486 fprintf_unfiltered (gdb_stdlog, "\n");
490 /* frame_unwind.prev_register. */
492 static struct value *
493 pyuw_prev_register (struct frame_info *this_frame, void **cache_ptr,
496 cached_frame_info *cached_frame = (cached_frame_info *) *cache_ptr;
497 struct reg_info *reg_info = cached_frame->reg;
498 struct reg_info *reg_info_end = reg_info + cached_frame->reg_count;
500 TRACE_PY_UNWIND (1, "%s (frame=%p,...,reg=%d)\n", __FUNCTION__, this_frame,
502 for (; reg_info < reg_info_end; ++reg_info)
504 if (regnum == reg_info->number)
505 return frame_unwind_got_bytes (this_frame, regnum, reg_info->data);
508 return frame_unwind_got_optimized (this_frame, regnum);
511 /* Frame sniffer dispatch. */
514 pyuw_sniffer (const struct frame_unwind *self, struct frame_info *this_frame,
517 struct gdbarch *gdbarch = (struct gdbarch *) (self->unwind_data);
518 struct cleanup *cleanups = ensure_python_env (gdbarch, current_language);
519 PyObject *pyo_execute;
520 PyObject *pyo_pending_frame;
521 PyObject *pyo_unwind_info;
522 cached_frame_info *cached_frame;
524 TRACE_PY_UNWIND (3, "%s (SP=%s, PC=%s)\n", __FUNCTION__,
525 paddress (gdbarch, get_frame_sp (this_frame)),
526 paddress (gdbarch, get_frame_pc (this_frame)));
528 /* Create PendingFrame instance to pass to sniffers. */
529 pyo_pending_frame = (PyObject *) PyObject_New (pending_frame_object,
530 &pending_frame_object_type);
531 if (pyo_pending_frame == NULL)
533 ((pending_frame_object *) pyo_pending_frame)->gdbarch = gdbarch;
534 ((pending_frame_object *) pyo_pending_frame)->frame_info = this_frame;
535 make_cleanup_py_decref (pyo_pending_frame);
536 make_cleanup (pending_frame_invalidate, (void *) pyo_pending_frame);
539 if (gdb_python_module == NULL
540 || ! PyObject_HasAttrString (gdb_python_module, "execute_unwinders"))
542 PyErr_SetString (PyExc_NameError,
543 "Installation error: gdb.execute_unwinders function "
547 pyo_execute = PyObject_GetAttrString (gdb_python_module, "execute_unwinders");
548 if (pyo_execute == NULL)
550 make_cleanup_py_decref (pyo_execute);
552 = PyObject_CallFunctionObjArgs (pyo_execute, pyo_pending_frame, NULL);
553 if (pyo_unwind_info == NULL)
555 make_cleanup_py_decref (pyo_unwind_info);
556 if (pyo_unwind_info == Py_None)
559 /* Received UnwindInfo, cache data. */
560 if (PyObject_IsInstance (pyo_unwind_info,
561 (PyObject *) &unwind_info_object_type) <= 0)
562 error (_("A Unwinder should return gdb.UnwindInfo instance."));
565 unwind_info_object *unwind_info = (unwind_info_object *) pyo_unwind_info;
566 int reg_count = VEC_length (saved_reg, unwind_info->saved_regs);
571 = ((cached_frame_info *)
572 xmalloc (sizeof (*cached_frame)
573 + reg_count * sizeof (cached_frame->reg[0])));
574 cached_frame->gdbarch = gdbarch;
575 cached_frame->frame_id = unwind_info->frame_id;
576 cached_frame->reg_count = reg_count;
578 /* Populate registers array. */
579 for (i = 0; VEC_iterate (saved_reg, unwind_info->saved_regs, i, reg); i++)
581 struct value *value = value_object_to_value (reg->value);
582 size_t data_size = register_size (gdbarch, reg->number);
584 cached_frame->reg[i].number = reg->number;
586 /* `value' validation was done before, just assert. */
587 gdb_assert (value != NULL);
588 gdb_assert (data_size == TYPE_LENGTH (value_type (value)));
589 gdb_assert (data_size <= MAX_REGISTER_SIZE);
591 memcpy (cached_frame->reg[i].data, value_contents (value), data_size);
595 *cache_ptr = cached_frame;
596 do_cleanups (cleanups);
600 gdbpy_print_stack ();
603 do_cleanups (cleanups);
607 /* Frame cache release shim. */
610 pyuw_dealloc_cache (struct frame_info *this_frame, void *cache)
612 TRACE_PY_UNWIND (3, "%s: enter", __FUNCTION__);
616 struct pyuw_gdbarch_data_type
618 /* Has the unwinder shim been prepended? */
619 int unwinder_registered;
623 pyuw_gdbarch_data_init (struct gdbarch *gdbarch)
625 return GDBARCH_OBSTACK_ZALLOC (gdbarch, struct pyuw_gdbarch_data_type);
628 /* New inferior architecture callback: register the Python unwinders
632 pyuw_on_new_gdbarch (struct gdbarch *newarch)
634 struct pyuw_gdbarch_data_type *data
635 = (struct pyuw_gdbarch_data_type *) gdbarch_data (newarch,
638 if (!data->unwinder_registered)
640 struct frame_unwind *unwinder
641 = GDBARCH_OBSTACK_ZALLOC (newarch, struct frame_unwind);
643 unwinder->type = NORMAL_FRAME;
644 unwinder->stop_reason = default_frame_unwind_stop_reason;
645 unwinder->this_id = pyuw_this_id;
646 unwinder->prev_register = pyuw_prev_register;
647 unwinder->unwind_data = (const struct frame_data *) newarch;
648 unwinder->sniffer = pyuw_sniffer;
649 unwinder->dealloc_cache = pyuw_dealloc_cache;
650 frame_unwind_prepend_unwinder (newarch, unwinder);
651 data->unwinder_registered = 1;
655 /* Initialize unwind machinery. */
658 gdbpy_initialize_unwind (void)
661 add_setshow_zuinteger_cmd
662 ("py-unwind", class_maintenance, &pyuw_debug,
663 _("Set Python unwinder debugging."),
664 _("Show Python unwinder debugging."),
665 _("When non-zero, Python unwinder debugging is enabled."),
668 &setdebuglist, &showdebuglist);
670 = gdbarch_data_register_post_init (pyuw_gdbarch_data_init);
671 observer_attach_architecture_changed (pyuw_on_new_gdbarch);
673 if (PyType_Ready (&pending_frame_object_type) < 0)
675 rc = gdb_pymodule_addobject (gdb_module, "PendingFrame",
676 (PyObject *) &pending_frame_object_type);
680 if (PyType_Ready (&unwind_info_object_type) < 0)
682 return gdb_pymodule_addobject (gdb_module, "UnwindInfo",
683 (PyObject *) &unwind_info_object_type);
686 static PyMethodDef pending_frame_object_methods[] =
688 { "read_register", pending_framepy_read_register, METH_VARARGS,
689 "read_register (REG) -> gdb.Value\n"
690 "Return the value of the REG in the frame." },
691 { "create_unwind_info",
692 pending_framepy_create_unwind_info, METH_VARARGS,
693 "create_unwind_info (FRAME_ID) -> gdb.UnwindInfo\n"
694 "Construct UnwindInfo for this PendingFrame, using FRAME_ID\n"
696 {NULL} /* Sentinel */
699 PyTypeObject pending_frame_object_type =
701 PyVarObject_HEAD_INIT (NULL, 0)
702 "gdb.PendingFrame", /* tp_name */
703 sizeof (pending_frame_object), /* tp_basicsize */
711 0, /* tp_as_number */
712 0, /* tp_as_sequence */
713 0, /* tp_as_mapping */
716 pending_framepy_str, /* tp_str */
719 0, /* tp_as_buffer */
720 Py_TPFLAGS_DEFAULT, /* tp_flags */
721 "GDB PendingFrame object", /* tp_doc */
724 0, /* tp_richcompare */
725 0, /* tp_weaklistoffset */
728 pending_frame_object_methods, /* tp_methods */
733 0, /* tp_descr_get */
734 0, /* tp_descr_set */
735 0, /* tp_dictoffset */
740 static PyMethodDef unwind_info_object_methods[] =
742 { "add_saved_register",
743 unwind_infopy_add_saved_register, METH_VARARGS,
744 "add_saved_register (REG, VALUE) -> None\n"
745 "Set the value of the REG in the previous frame to VALUE." },
746 { NULL } /* Sentinel */
749 PyTypeObject unwind_info_object_type =
751 PyVarObject_HEAD_INIT (NULL, 0)
752 "gdb.UnwindInfo", /* tp_name */
753 sizeof (unwind_info_object), /* tp_basicsize */
755 unwind_infopy_dealloc, /* tp_dealloc */
761 0, /* tp_as_number */
762 0, /* tp_as_sequence */
763 0, /* tp_as_mapping */
766 unwind_infopy_str, /* tp_str */
769 0, /* tp_as_buffer */
770 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
771 "GDB UnwindInfo object", /* tp_doc */
774 0, /* tp_richcompare */
775 0, /* tp_weaklistoffset */
778 unwind_info_object_methods, /* tp_methods */
783 0, /* tp_descr_get */
784 0, /* tp_descr_set */
785 0, /* tp_dictoffset */