1 /* Python frame unwinder interface.
3 Copyright (C) 2015-2020 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"
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. */
50 saved_reg (int n
, gdbpy_ref
<> &&v
)
60 /* The data we keep for the PyUnwindInfo: pending_frame, saved registers
67 /* gdb.PendingFrame for the frame we are unwinding. */
68 PyObject
*pending_frame
;
71 struct frame_id frame_id
;
73 /* Saved registers array. */
74 std::vector
<saved_reg
> *saved_regs
;
77 /* The data we keep for a frame we can unwind: frame ID and an array of
78 (register_number, register_value) pairs. */
83 struct frame_id frame_id
;
85 /* GDB Architecture. */
86 struct gdbarch
*gdbarch
;
88 /* Length of the `reg' array below. */
94 extern PyTypeObject pending_frame_object_type
95 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("pending_frame_object");
97 extern PyTypeObject unwind_info_object_type
98 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("unwind_info_object");
100 static unsigned int pyuw_debug
= 0;
102 static struct gdbarch_data
*pyuw_gdbarch_data
;
104 /* Parses register id, which can be either a number or a name.
105 Returns 1 on success, 0 otherwise. */
108 pyuw_parse_register_id (struct gdbarch
*gdbarch
, PyObject
*pyo_reg_id
,
111 if (pyo_reg_id
== NULL
)
113 if (gdbpy_is_string (pyo_reg_id
))
115 gdb::unique_xmalloc_ptr
<char> reg_name (gdbpy_obj_to_string (pyo_reg_id
));
117 if (reg_name
== NULL
)
119 *reg_num
= user_reg_map_name_to_regnum (gdbarch
, reg_name
.get (),
120 strlen (reg_name
.get ()));
121 return *reg_num
>= 0;
123 else if (PyInt_Check (pyo_reg_id
))
126 if (gdb_py_int_as_long (pyo_reg_id
, &value
) && (int) value
== value
)
128 *reg_num
= (int) value
;
129 return user_reg_map_regnum_to_name (gdbarch
, *reg_num
) != NULL
;
135 /* Convert gdb.Value instance to inferior's pointer. Return 1 on success,
139 pyuw_value_obj_to_pointer (PyObject
*pyo_value
, CORE_ADDR
*addr
)
146 if ((value
= value_object_to_value (pyo_value
)) != NULL
)
148 *addr
= unpack_pointer (value_type (value
),
149 value_contents (value
));
153 catch (const gdb_exception
&except
)
155 gdbpy_convert_exception (except
);
160 /* Get attribute from an object and convert it to the inferior's
161 pointer value. Return 1 if attribute exists and its value can be
162 converted. Otherwise, if attribute does not exist or its value is
163 None, return 0. In all other cases set Python error and return
167 pyuw_object_attribute_to_pointer (PyObject
*pyo
, const char *attr_name
,
172 if (PyObject_HasAttrString (pyo
, attr_name
))
174 gdbpy_ref
<> pyo_value (PyObject_GetAttrString (pyo
, attr_name
));
176 if (pyo_value
!= NULL
&& pyo_value
!= Py_None
)
178 rc
= pyuw_value_obj_to_pointer (pyo_value
.get (), addr
);
182 _("The value of the '%s' attribute is not a pointer."),
189 /* Called by the Python interpreter to obtain string representation
190 of the UnwindInfo object. */
193 unwind_infopy_str (PyObject
*self
)
195 unwind_info_object
*unwind_info
= (unwind_info_object
*) self
;
198 stb
.puts ("Frame ID: ");
199 fprint_frame_id (&stb
, unwind_info
->frame_id
);
201 const char *sep
= "";
202 struct value_print_options opts
;
204 get_user_print_options (&opts
);
205 stb
.printf ("\nSaved registers: (");
206 for (const saved_reg
®
: *unwind_info
->saved_regs
)
208 struct value
*value
= value_object_to_value (reg
.value
.get ());
210 stb
.printf ("%s(%d, ", sep
, reg
.number
);
215 value_print (value
, &stb
, &opts
);
218 catch (const gdb_exception
&except
)
220 GDB_PY_HANDLE_EXCEPTION (except
);
230 return PyString_FromString (stb
.c_str ());
233 /* Create UnwindInfo instance for given PendingFrame and frame ID.
234 Sets Python error and returns NULL on error. */
237 pyuw_create_unwind_info (PyObject
*pyo_pending_frame
,
238 struct frame_id frame_id
)
240 unwind_info_object
*unwind_info
241 = PyObject_New (unwind_info_object
, &unwind_info_object_type
);
243 if (((pending_frame_object
*) pyo_pending_frame
)->frame_info
== NULL
)
245 PyErr_SetString (PyExc_ValueError
,
246 "Attempting to use stale PendingFrame");
249 unwind_info
->frame_id
= frame_id
;
250 Py_INCREF (pyo_pending_frame
);
251 unwind_info
->pending_frame
= pyo_pending_frame
;
252 unwind_info
->saved_regs
= new std::vector
<saved_reg
>;
253 return (PyObject
*) unwind_info
;
256 /* The implementation of
257 gdb.UnwindInfo.add_saved_register (REG, VALUE) -> None. */
260 unwind_infopy_add_saved_register (PyObject
*self
, PyObject
*args
)
262 unwind_info_object
*unwind_info
= (unwind_info_object
*) self
;
263 pending_frame_object
*pending_frame
264 = (pending_frame_object
*) (unwind_info
->pending_frame
);
265 PyObject
*pyo_reg_id
;
266 PyObject
*pyo_reg_value
;
269 if (pending_frame
->frame_info
== NULL
)
271 PyErr_SetString (PyExc_ValueError
,
272 "UnwindInfo instance refers to a stale PendingFrame");
275 if (!PyArg_UnpackTuple (args
, "previous_frame_register", 2, 2,
276 &pyo_reg_id
, &pyo_reg_value
))
278 if (!pyuw_parse_register_id (pending_frame
->gdbarch
, pyo_reg_id
, ®num
))
280 PyErr_SetString (PyExc_ValueError
, "Bad register");
287 if (pyo_reg_value
== NULL
288 || (value
= value_object_to_value (pyo_reg_value
)) == NULL
)
290 PyErr_SetString (PyExc_ValueError
, "Bad register value");
293 data_size
= register_size (pending_frame
->gdbarch
, regnum
);
294 if (data_size
!= TYPE_LENGTH (value_type (value
)))
298 "The value of the register returned by the Python "
299 "sniffer has unexpected size: %u instead of %u.",
300 (unsigned) TYPE_LENGTH (value_type (value
)),
301 (unsigned) data_size
);
306 gdbpy_ref
<> new_value
= gdbpy_ref
<>::new_reference (pyo_reg_value
);
308 for (saved_reg
®
: *unwind_info
->saved_regs
)
310 if (regnum
== reg
.number
)
313 reg
.value
= std::move (new_value
);
318 unwind_info
->saved_regs
->emplace_back (regnum
, std::move (new_value
));
323 /* UnwindInfo cleanup. */
326 unwind_infopy_dealloc (PyObject
*self
)
328 unwind_info_object
*unwind_info
= (unwind_info_object
*) self
;
330 Py_XDECREF (unwind_info
->pending_frame
);
331 delete unwind_info
->saved_regs
;
332 Py_TYPE (self
)->tp_free (self
);
335 /* Called by the Python interpreter to obtain string representation
336 of the PendingFrame object. */
339 pending_framepy_str (PyObject
*self
)
341 struct frame_info
*frame
= ((pending_frame_object
*) self
)->frame_info
;
342 const char *sp_str
= NULL
;
343 const char *pc_str
= NULL
;
346 return PyString_FromString ("Stale PendingFrame instance");
349 sp_str
= core_addr_to_string_nz (get_frame_sp (frame
));
350 pc_str
= core_addr_to_string_nz (get_frame_pc (frame
));
352 catch (const gdb_exception
&except
)
354 GDB_PY_HANDLE_EXCEPTION (except
);
357 return PyString_FromFormat ("SP=%s,PC=%s", sp_str
, pc_str
);
360 /* Implementation of gdb.PendingFrame.read_register (self, reg) -> gdb.Value.
361 Returns the value of register REG as gdb.Value instance. */
364 pending_framepy_read_register (PyObject
*self
, PyObject
*args
)
366 pending_frame_object
*pending_frame
= (pending_frame_object
*) self
;
367 struct value
*val
= NULL
;
369 PyObject
*pyo_reg_id
;
371 if (pending_frame
->frame_info
== NULL
)
373 PyErr_SetString (PyExc_ValueError
,
374 "Attempting to read register from stale PendingFrame");
377 if (!PyArg_UnpackTuple (args
, "read_register", 1, 1, &pyo_reg_id
))
379 if (!pyuw_parse_register_id (pending_frame
->gdbarch
, pyo_reg_id
, ®num
))
381 PyErr_SetString (PyExc_ValueError
, "Bad register");
387 /* Fetch the value associated with a register, whether it's
388 a real register or a so called "user" register, like "pc",
389 which maps to a real register. In the past,
390 get_frame_register_value() was used here, which did not
391 handle the user register case. */
392 val
= value_of_register (regnum
, pending_frame
->frame_info
);
394 PyErr_Format (PyExc_ValueError
,
395 "Cannot read register %d from frame.",
398 catch (const gdb_exception
&except
)
400 GDB_PY_HANDLE_EXCEPTION (except
);
403 return val
== NULL
? NULL
: value_to_value_object (val
);
407 PendingFrame.create_unwind_info (self, frameId) -> UnwindInfo. */
410 pending_framepy_create_unwind_info (PyObject
*self
, PyObject
*args
)
412 PyObject
*pyo_frame_id
;
417 if (!PyArg_ParseTuple (args
, "O:create_unwind_info", &pyo_frame_id
))
419 if (!pyuw_object_attribute_to_pointer (pyo_frame_id
, "sp", &sp
))
421 PyErr_SetString (PyExc_ValueError
,
422 _("frame_id should have 'sp' attribute."));
426 /* The logic of building frame_id depending on the attributes of
428 Has Has Has Function to call
429 'sp'? 'pc'? 'special'?
430 ------|------|--------------|-------------------------
431 Y N * frame_id_build_wild (sp)
432 Y Y N frame_id_build (sp, pc)
433 Y Y Y frame_id_build_special (sp, pc, special)
435 if (!pyuw_object_attribute_to_pointer (pyo_frame_id
, "pc", &pc
))
436 return pyuw_create_unwind_info (self
, frame_id_build_wild (sp
));
437 if (!pyuw_object_attribute_to_pointer (pyo_frame_id
, "special", &special
))
438 return pyuw_create_unwind_info (self
, frame_id_build (sp
, pc
));
440 return pyuw_create_unwind_info (self
,
441 frame_id_build_special (sp
, pc
, special
));
444 /* Implementation of PendingFrame.architecture (self) -> gdb.Architecture. */
447 pending_framepy_architecture (PyObject
*self
, PyObject
*args
)
449 pending_frame_object
*pending_frame
= (pending_frame_object
*) self
;
451 if (pending_frame
->frame_info
== NULL
)
453 PyErr_SetString (PyExc_ValueError
,
454 "Attempting to read register from stale PendingFrame");
457 return gdbarch_to_arch_object (pending_frame
->gdbarch
);
460 /* frame_unwind.this_id method. */
463 pyuw_this_id (struct frame_info
*this_frame
, void **cache_ptr
,
464 struct frame_id
*this_id
)
466 *this_id
= ((cached_frame_info
*) *cache_ptr
)->frame_id
;
469 fprintf_unfiltered (gdb_stdlog
, "%s: frame_id: ", __FUNCTION__
);
470 fprint_frame_id (gdb_stdlog
, *this_id
);
471 fprintf_unfiltered (gdb_stdlog
, "\n");
475 /* frame_unwind.prev_register. */
477 static struct value
*
478 pyuw_prev_register (struct frame_info
*this_frame
, void **cache_ptr
,
481 cached_frame_info
*cached_frame
= (cached_frame_info
*) *cache_ptr
;
482 cached_reg_t
*reg_info
= cached_frame
->reg
;
483 cached_reg_t
*reg_info_end
= reg_info
+ cached_frame
->reg_count
;
485 TRACE_PY_UNWIND (1, "%s (frame=%p,...,reg=%d)\n", __FUNCTION__
, this_frame
,
487 for (; reg_info
< reg_info_end
; ++reg_info
)
489 if (regnum
== reg_info
->num
)
490 return frame_unwind_got_bytes (this_frame
, regnum
, reg_info
->data
);
493 return frame_unwind_got_optimized (this_frame
, regnum
);
496 /* Frame sniffer dispatch. */
499 pyuw_sniffer (const struct frame_unwind
*self
, struct frame_info
*this_frame
,
502 struct gdbarch
*gdbarch
= (struct gdbarch
*) (self
->unwind_data
);
503 cached_frame_info
*cached_frame
;
505 gdbpy_enter
enter_py (gdbarch
, current_language
);
507 TRACE_PY_UNWIND (3, "%s (SP=%s, PC=%s)\n", __FUNCTION__
,
508 paddress (gdbarch
, get_frame_sp (this_frame
)),
509 paddress (gdbarch
, get_frame_pc (this_frame
)));
511 /* Create PendingFrame instance to pass to sniffers. */
512 pending_frame_object
*pfo
= PyObject_New (pending_frame_object
,
513 &pending_frame_object_type
);
514 gdbpy_ref
<> pyo_pending_frame ((PyObject
*) pfo
);
515 if (pyo_pending_frame
== NULL
)
517 gdbpy_print_stack ();
520 pfo
->gdbarch
= gdbarch
;
521 scoped_restore invalidate_frame
= make_scoped_restore (&pfo
->frame_info
,
525 if (gdb_python_module
== NULL
526 || ! PyObject_HasAttrString (gdb_python_module
, "_execute_unwinders"))
528 PyErr_SetString (PyExc_NameError
,
529 "Installation error: gdb._execute_unwinders function "
531 gdbpy_print_stack ();
534 gdbpy_ref
<> pyo_execute (PyObject_GetAttrString (gdb_python_module
,
535 "_execute_unwinders"));
536 if (pyo_execute
== NULL
)
538 gdbpy_print_stack ();
542 gdbpy_ref
<> pyo_unwind_info
543 (PyObject_CallFunctionObjArgs (pyo_execute
.get (),
544 pyo_pending_frame
.get (), NULL
));
545 if (pyo_unwind_info
== NULL
)
547 /* If the unwinder is cancelled due to a Ctrl-C, then propagate
548 the Ctrl-C as a GDB exception instead of swallowing it. */
549 gdbpy_print_stack_or_quit ();
552 if (pyo_unwind_info
== Py_None
)
555 /* Received UnwindInfo, cache data. */
556 if (PyObject_IsInstance (pyo_unwind_info
.get (),
557 (PyObject
*) &unwind_info_object_type
) <= 0)
558 error (_("A Unwinder should return gdb.UnwindInfo instance."));
561 unwind_info_object
*unwind_info
=
562 (unwind_info_object
*) pyo_unwind_info
.get ();
563 int reg_count
= unwind_info
->saved_regs
->size ();
566 = ((cached_frame_info
*)
567 xmalloc (sizeof (*cached_frame
)
568 + reg_count
* sizeof (cached_frame
->reg
[0])));
569 cached_frame
->gdbarch
= gdbarch
;
570 cached_frame
->frame_id
= unwind_info
->frame_id
;
571 cached_frame
->reg_count
= reg_count
;
573 /* Populate registers array. */
574 for (int i
= 0; i
< unwind_info
->saved_regs
->size (); ++i
)
576 saved_reg
*reg
= &(*unwind_info
->saved_regs
)[i
];
578 struct value
*value
= value_object_to_value (reg
->value
.get ());
579 size_t data_size
= register_size (gdbarch
, reg
->number
);
581 cached_frame
->reg
[i
].num
= reg
->number
;
583 /* `value' validation was done before, just assert. */
584 gdb_assert (value
!= NULL
);
585 gdb_assert (data_size
== TYPE_LENGTH (value_type (value
)));
587 cached_frame
->reg
[i
].data
= (gdb_byte
*) xmalloc (data_size
);
588 memcpy (cached_frame
->reg
[i
].data
, value_contents (value
), data_size
);
592 *cache_ptr
= cached_frame
;
596 /* Frame cache release shim. */
599 pyuw_dealloc_cache (struct frame_info
*this_frame
, void *cache
)
601 TRACE_PY_UNWIND (3, "%s: enter", __FUNCTION__
);
602 cached_frame_info
*cached_frame
= (cached_frame_info
*) cache
;
604 for (int i
= 0; i
< cached_frame
->reg_count
; i
++)
605 xfree (cached_frame
->reg
[i
].data
);
610 struct pyuw_gdbarch_data_type
612 /* Has the unwinder shim been prepended? */
613 int unwinder_registered
;
617 pyuw_gdbarch_data_init (struct gdbarch
*gdbarch
)
619 return GDBARCH_OBSTACK_ZALLOC (gdbarch
, struct pyuw_gdbarch_data_type
);
622 /* New inferior architecture callback: register the Python unwinders
626 pyuw_on_new_gdbarch (struct gdbarch
*newarch
)
628 struct pyuw_gdbarch_data_type
*data
629 = (struct pyuw_gdbarch_data_type
*) gdbarch_data (newarch
,
632 if (!data
->unwinder_registered
)
634 struct frame_unwind
*unwinder
635 = GDBARCH_OBSTACK_ZALLOC (newarch
, struct frame_unwind
);
637 unwinder
->type
= NORMAL_FRAME
;
638 unwinder
->stop_reason
= default_frame_unwind_stop_reason
;
639 unwinder
->this_id
= pyuw_this_id
;
640 unwinder
->prev_register
= pyuw_prev_register
;
641 unwinder
->unwind_data
= (const struct frame_data
*) newarch
;
642 unwinder
->sniffer
= pyuw_sniffer
;
643 unwinder
->dealloc_cache
= pyuw_dealloc_cache
;
644 frame_unwind_prepend_unwinder (newarch
, unwinder
);
645 data
->unwinder_registered
= 1;
649 /* Initialize unwind machinery. */
652 gdbpy_initialize_unwind (void)
655 add_setshow_zuinteger_cmd
656 ("py-unwind", class_maintenance
, &pyuw_debug
,
657 _("Set Python unwinder debugging."),
658 _("Show Python unwinder debugging."),
659 _("When non-zero, Python unwinder debugging is enabled."),
662 &setdebuglist
, &showdebuglist
);
664 = gdbarch_data_register_post_init (pyuw_gdbarch_data_init
);
665 gdb::observers::architecture_changed
.attach (pyuw_on_new_gdbarch
);
667 if (PyType_Ready (&pending_frame_object_type
) < 0)
669 rc
= gdb_pymodule_addobject (gdb_module
, "PendingFrame",
670 (PyObject
*) &pending_frame_object_type
);
674 if (PyType_Ready (&unwind_info_object_type
) < 0)
676 return gdb_pymodule_addobject (gdb_module
, "UnwindInfo",
677 (PyObject
*) &unwind_info_object_type
);
680 static PyMethodDef pending_frame_object_methods
[] =
682 { "read_register", pending_framepy_read_register
, METH_VARARGS
,
683 "read_register (REG) -> gdb.Value\n"
684 "Return the value of the REG in the frame." },
685 { "create_unwind_info",
686 pending_framepy_create_unwind_info
, METH_VARARGS
,
687 "create_unwind_info (FRAME_ID) -> gdb.UnwindInfo\n"
688 "Construct UnwindInfo for this PendingFrame, using FRAME_ID\n"
691 pending_framepy_architecture
, METH_NOARGS
,
692 "architecture () -> gdb.Architecture\n"
693 "The architecture for this PendingFrame." },
694 {NULL
} /* Sentinel */
697 PyTypeObject pending_frame_object_type
=
699 PyVarObject_HEAD_INIT (NULL
, 0)
700 "gdb.PendingFrame", /* tp_name */
701 sizeof (pending_frame_object
), /* tp_basicsize */
709 0, /* tp_as_number */
710 0, /* tp_as_sequence */
711 0, /* tp_as_mapping */
714 pending_framepy_str
, /* tp_str */
717 0, /* tp_as_buffer */
718 Py_TPFLAGS_DEFAULT
, /* tp_flags */
719 "GDB PendingFrame object", /* tp_doc */
722 0, /* tp_richcompare */
723 0, /* tp_weaklistoffset */
726 pending_frame_object_methods
, /* tp_methods */
731 0, /* tp_descr_get */
732 0, /* tp_descr_set */
733 0, /* tp_dictoffset */
738 static PyMethodDef unwind_info_object_methods
[] =
740 { "add_saved_register",
741 unwind_infopy_add_saved_register
, METH_VARARGS
,
742 "add_saved_register (REG, VALUE) -> None\n"
743 "Set the value of the REG in the previous frame to VALUE." },
744 { NULL
} /* Sentinel */
747 PyTypeObject unwind_info_object_type
=
749 PyVarObject_HEAD_INIT (NULL
, 0)
750 "gdb.UnwindInfo", /* tp_name */
751 sizeof (unwind_info_object
), /* tp_basicsize */
753 unwind_infopy_dealloc
, /* tp_dealloc */
759 0, /* tp_as_number */
760 0, /* tp_as_sequence */
761 0, /* tp_as_mapping */
764 unwind_infopy_str
, /* tp_str */
767 0, /* tp_as_buffer */
768 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
769 "GDB UnwindInfo object", /* tp_doc */
772 0, /* tp_richcompare */
773 0, /* tp_weaklistoffset */
776 unwind_info_object_methods
, /* tp_methods */
781 0, /* tp_descr_get */
782 0, /* tp_descr_set */
783 0, /* tp_dictoffset */