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 #define TRACE_PY_UNWIND(level, args...) if (pyuw_debug >= level) \
32 { fprintf_unfiltered (gdb_stdlog, args); }
34 struct pending_frame_object
38 /* Frame we are unwinding. */
39 struct frame_info
*frame_info
;
41 /* Its architecture, passed by the sniffer caller. */
42 struct gdbarch
*gdbarch
;
45 /* Saved registers array item. */
49 saved_reg (int n
, gdbpy_ref
<> &&v
)
59 /* The data we keep for the PyUnwindInfo: pending_frame, saved registers
62 struct unwind_info_object
66 /* gdb.PendingFrame for the frame we are unwinding. */
67 PyObject
*pending_frame
;
70 struct frame_id frame_id
;
72 /* Saved registers array. */
73 std::vector
<saved_reg
> *saved_regs
;
76 /* The data we keep for a frame we can unwind: frame ID and an array of
77 (register_number, register_value) pairs. */
79 struct cached_frame_info
82 struct frame_id frame_id
;
84 /* GDB Architecture. */
85 struct gdbarch
*gdbarch
;
87 /* Length of the `reg' array below. */
93 extern PyTypeObject pending_frame_object_type
94 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("pending_frame_object");
96 extern PyTypeObject unwind_info_object_type
97 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("unwind_info_object");
99 static unsigned int pyuw_debug
= 0;
101 static struct gdbarch_data
*pyuw_gdbarch_data
;
103 /* Convert gdb.Value instance to inferior's pointer. Return 1 on success,
107 pyuw_value_obj_to_pointer (PyObject
*pyo_value
, CORE_ADDR
*addr
)
114 if ((value
= value_object_to_value (pyo_value
)) != NULL
)
116 *addr
= unpack_pointer (value_type (value
),
117 value_contents (value
));
121 catch (const gdb_exception
&except
)
123 gdbpy_convert_exception (except
);
128 /* Get attribute from an object and convert it to the inferior's
129 pointer value. Return 1 if attribute exists and its value can be
130 converted. Otherwise, if attribute does not exist or its value is
131 None, return 0. In all other cases set Python error and return
135 pyuw_object_attribute_to_pointer (PyObject
*pyo
, const char *attr_name
,
140 if (PyObject_HasAttrString (pyo
, attr_name
))
142 gdbpy_ref
<> pyo_value (PyObject_GetAttrString (pyo
, attr_name
));
144 if (pyo_value
!= NULL
&& pyo_value
!= Py_None
)
146 rc
= pyuw_value_obj_to_pointer (pyo_value
.get (), addr
);
150 _("The value of the '%s' attribute is not a pointer."),
157 /* Called by the Python interpreter to obtain string representation
158 of the UnwindInfo object. */
161 unwind_infopy_str (PyObject
*self
)
163 unwind_info_object
*unwind_info
= (unwind_info_object
*) self
;
166 stb
.puts ("Frame ID: ");
167 fprint_frame_id (&stb
, unwind_info
->frame_id
);
169 const char *sep
= "";
170 struct value_print_options opts
;
172 get_user_print_options (&opts
);
173 stb
.printf ("\nSaved registers: (");
174 for (const saved_reg
®
: *unwind_info
->saved_regs
)
176 struct value
*value
= value_object_to_value (reg
.value
.get ());
178 stb
.printf ("%s(%d, ", sep
, reg
.number
);
183 value_print (value
, &stb
, &opts
);
186 catch (const gdb_exception
&except
)
188 GDB_PY_HANDLE_EXCEPTION (except
);
198 return PyString_FromString (stb
.c_str ());
201 /* Create UnwindInfo instance for given PendingFrame and frame ID.
202 Sets Python error and returns NULL on error. */
205 pyuw_create_unwind_info (PyObject
*pyo_pending_frame
,
206 struct frame_id frame_id
)
208 unwind_info_object
*unwind_info
209 = PyObject_New (unwind_info_object
, &unwind_info_object_type
);
211 if (((pending_frame_object
*) pyo_pending_frame
)->frame_info
== NULL
)
213 PyErr_SetString (PyExc_ValueError
,
214 "Attempting to use stale PendingFrame");
217 unwind_info
->frame_id
= frame_id
;
218 Py_INCREF (pyo_pending_frame
);
219 unwind_info
->pending_frame
= pyo_pending_frame
;
220 unwind_info
->saved_regs
= new std::vector
<saved_reg
>;
221 return (PyObject
*) unwind_info
;
224 /* The implementation of
225 gdb.UnwindInfo.add_saved_register (REG, VALUE) -> None. */
228 unwind_infopy_add_saved_register (PyObject
*self
, PyObject
*args
)
230 unwind_info_object
*unwind_info
= (unwind_info_object
*) self
;
231 pending_frame_object
*pending_frame
232 = (pending_frame_object
*) (unwind_info
->pending_frame
);
233 PyObject
*pyo_reg_id
;
234 PyObject
*pyo_reg_value
;
237 if (pending_frame
->frame_info
== NULL
)
239 PyErr_SetString (PyExc_ValueError
,
240 "UnwindInfo instance refers to a stale PendingFrame");
243 if (!PyArg_UnpackTuple (args
, "previous_frame_register", 2, 2,
244 &pyo_reg_id
, &pyo_reg_value
))
246 if (!gdbpy_parse_register_id (pending_frame
->gdbarch
, pyo_reg_id
, ®num
))
248 PyErr_SetString (PyExc_ValueError
, "Bad register");
255 if (pyo_reg_value
== NULL
256 || (value
= value_object_to_value (pyo_reg_value
)) == NULL
)
258 PyErr_SetString (PyExc_ValueError
, "Bad register value");
261 data_size
= register_size (pending_frame
->gdbarch
, regnum
);
262 if (data_size
!= TYPE_LENGTH (value_type (value
)))
266 "The value of the register returned by the Python "
267 "sniffer has unexpected size: %u instead of %u.",
268 (unsigned) TYPE_LENGTH (value_type (value
)),
269 (unsigned) data_size
);
274 gdbpy_ref
<> new_value
= gdbpy_ref
<>::new_reference (pyo_reg_value
);
276 for (saved_reg
®
: *unwind_info
->saved_regs
)
278 if (regnum
== reg
.number
)
281 reg
.value
= std::move (new_value
);
286 unwind_info
->saved_regs
->emplace_back (regnum
, std::move (new_value
));
291 /* UnwindInfo cleanup. */
294 unwind_infopy_dealloc (PyObject
*self
)
296 unwind_info_object
*unwind_info
= (unwind_info_object
*) self
;
298 Py_XDECREF (unwind_info
->pending_frame
);
299 delete unwind_info
->saved_regs
;
300 Py_TYPE (self
)->tp_free (self
);
303 /* Called by the Python interpreter to obtain string representation
304 of the PendingFrame object. */
307 pending_framepy_str (PyObject
*self
)
309 struct frame_info
*frame
= ((pending_frame_object
*) self
)->frame_info
;
310 const char *sp_str
= NULL
;
311 const char *pc_str
= NULL
;
314 return PyString_FromString ("Stale PendingFrame instance");
317 sp_str
= core_addr_to_string_nz (get_frame_sp (frame
));
318 pc_str
= core_addr_to_string_nz (get_frame_pc (frame
));
320 catch (const gdb_exception
&except
)
322 GDB_PY_HANDLE_EXCEPTION (except
);
325 return PyString_FromFormat ("SP=%s,PC=%s", sp_str
, pc_str
);
328 /* Implementation of gdb.PendingFrame.read_register (self, reg) -> gdb.Value.
329 Returns the value of register REG as gdb.Value instance. */
332 pending_framepy_read_register (PyObject
*self
, PyObject
*args
)
334 pending_frame_object
*pending_frame
= (pending_frame_object
*) self
;
335 struct value
*val
= NULL
;
337 PyObject
*pyo_reg_id
;
339 if (pending_frame
->frame_info
== NULL
)
341 PyErr_SetString (PyExc_ValueError
,
342 "Attempting to read register from stale PendingFrame");
345 if (!PyArg_UnpackTuple (args
, "read_register", 1, 1, &pyo_reg_id
))
347 if (!gdbpy_parse_register_id (pending_frame
->gdbarch
, pyo_reg_id
, ®num
))
349 PyErr_SetString (PyExc_ValueError
, "Bad register");
355 /* Fetch the value associated with a register, whether it's
356 a real register or a so called "user" register, like "pc",
357 which maps to a real register. In the past,
358 get_frame_register_value() was used here, which did not
359 handle the user register case. */
360 val
= value_of_register (regnum
, pending_frame
->frame_info
);
362 PyErr_Format (PyExc_ValueError
,
363 "Cannot read register %d from frame.",
366 catch (const gdb_exception
&except
)
368 GDB_PY_HANDLE_EXCEPTION (except
);
371 return val
== NULL
? NULL
: value_to_value_object (val
);
375 PendingFrame.create_unwind_info (self, frameId) -> UnwindInfo. */
378 pending_framepy_create_unwind_info (PyObject
*self
, PyObject
*args
)
380 PyObject
*pyo_frame_id
;
385 if (!PyArg_ParseTuple (args
, "O:create_unwind_info", &pyo_frame_id
))
387 if (!pyuw_object_attribute_to_pointer (pyo_frame_id
, "sp", &sp
))
389 PyErr_SetString (PyExc_ValueError
,
390 _("frame_id should have 'sp' attribute."));
394 /* The logic of building frame_id depending on the attributes of
396 Has Has Has Function to call
397 'sp'? 'pc'? 'special'?
398 ------|------|--------------|-------------------------
399 Y N * frame_id_build_wild (sp)
400 Y Y N frame_id_build (sp, pc)
401 Y Y Y frame_id_build_special (sp, pc, special)
403 if (!pyuw_object_attribute_to_pointer (pyo_frame_id
, "pc", &pc
))
404 return pyuw_create_unwind_info (self
, frame_id_build_wild (sp
));
405 if (!pyuw_object_attribute_to_pointer (pyo_frame_id
, "special", &special
))
406 return pyuw_create_unwind_info (self
, frame_id_build (sp
, pc
));
408 return pyuw_create_unwind_info (self
,
409 frame_id_build_special (sp
, pc
, special
));
412 /* Implementation of PendingFrame.architecture (self) -> gdb.Architecture. */
415 pending_framepy_architecture (PyObject
*self
, PyObject
*args
)
417 pending_frame_object
*pending_frame
= (pending_frame_object
*) self
;
419 if (pending_frame
->frame_info
== NULL
)
421 PyErr_SetString (PyExc_ValueError
,
422 "Attempting to read register from stale PendingFrame");
425 return gdbarch_to_arch_object (pending_frame
->gdbarch
);
428 /* frame_unwind.this_id method. */
431 pyuw_this_id (struct frame_info
*this_frame
, void **cache_ptr
,
432 struct frame_id
*this_id
)
434 *this_id
= ((cached_frame_info
*) *cache_ptr
)->frame_id
;
437 fprintf_unfiltered (gdb_stdlog
, "%s: frame_id: ", __FUNCTION__
);
438 fprint_frame_id (gdb_stdlog
, *this_id
);
439 fprintf_unfiltered (gdb_stdlog
, "\n");
443 /* frame_unwind.prev_register. */
445 static struct value
*
446 pyuw_prev_register (struct frame_info
*this_frame
, void **cache_ptr
,
449 cached_frame_info
*cached_frame
= (cached_frame_info
*) *cache_ptr
;
450 cached_reg_t
*reg_info
= cached_frame
->reg
;
451 cached_reg_t
*reg_info_end
= reg_info
+ cached_frame
->reg_count
;
453 TRACE_PY_UNWIND (1, "%s (frame=%p,...,reg=%d)\n", __FUNCTION__
, this_frame
,
455 for (; reg_info
< reg_info_end
; ++reg_info
)
457 if (regnum
== reg_info
->num
)
458 return frame_unwind_got_bytes (this_frame
, regnum
, reg_info
->data
);
461 return frame_unwind_got_optimized (this_frame
, regnum
);
464 /* Frame sniffer dispatch. */
467 pyuw_sniffer (const struct frame_unwind
*self
, struct frame_info
*this_frame
,
470 struct gdbarch
*gdbarch
= (struct gdbarch
*) (self
->unwind_data
);
471 cached_frame_info
*cached_frame
;
473 gdbpy_enter
enter_py (gdbarch
, current_language
);
475 TRACE_PY_UNWIND (3, "%s (SP=%s, PC=%s)\n", __FUNCTION__
,
476 paddress (gdbarch
, get_frame_sp (this_frame
)),
477 paddress (gdbarch
, get_frame_pc (this_frame
)));
479 /* Create PendingFrame instance to pass to sniffers. */
480 pending_frame_object
*pfo
= PyObject_New (pending_frame_object
,
481 &pending_frame_object_type
);
482 gdbpy_ref
<> pyo_pending_frame ((PyObject
*) pfo
);
483 if (pyo_pending_frame
== NULL
)
485 gdbpy_print_stack ();
488 pfo
->gdbarch
= gdbarch
;
489 scoped_restore invalidate_frame
= make_scoped_restore (&pfo
->frame_info
,
493 if (gdb_python_module
== NULL
494 || ! PyObject_HasAttrString (gdb_python_module
, "_execute_unwinders"))
496 PyErr_SetString (PyExc_NameError
,
497 "Installation error: gdb._execute_unwinders function "
499 gdbpy_print_stack ();
502 gdbpy_ref
<> pyo_execute (PyObject_GetAttrString (gdb_python_module
,
503 "_execute_unwinders"));
504 if (pyo_execute
== NULL
)
506 gdbpy_print_stack ();
510 gdbpy_ref
<> pyo_unwind_info
511 (PyObject_CallFunctionObjArgs (pyo_execute
.get (),
512 pyo_pending_frame
.get (), NULL
));
513 if (pyo_unwind_info
== NULL
)
515 /* If the unwinder is cancelled due to a Ctrl-C, then propagate
516 the Ctrl-C as a GDB exception instead of swallowing it. */
517 gdbpy_print_stack_or_quit ();
520 if (pyo_unwind_info
== Py_None
)
523 /* Received UnwindInfo, cache data. */
524 if (PyObject_IsInstance (pyo_unwind_info
.get (),
525 (PyObject
*) &unwind_info_object_type
) <= 0)
526 error (_("A Unwinder should return gdb.UnwindInfo instance."));
529 unwind_info_object
*unwind_info
=
530 (unwind_info_object
*) pyo_unwind_info
.get ();
531 int reg_count
= unwind_info
->saved_regs
->size ();
534 = ((cached_frame_info
*)
535 xmalloc (sizeof (*cached_frame
)
536 + reg_count
* sizeof (cached_frame
->reg
[0])));
537 cached_frame
->gdbarch
= gdbarch
;
538 cached_frame
->frame_id
= unwind_info
->frame_id
;
539 cached_frame
->reg_count
= reg_count
;
541 /* Populate registers array. */
542 for (int i
= 0; i
< unwind_info
->saved_regs
->size (); ++i
)
544 saved_reg
*reg
= &(*unwind_info
->saved_regs
)[i
];
546 struct value
*value
= value_object_to_value (reg
->value
.get ());
547 size_t data_size
= register_size (gdbarch
, reg
->number
);
549 cached_frame
->reg
[i
].num
= reg
->number
;
551 /* `value' validation was done before, just assert. */
552 gdb_assert (value
!= NULL
);
553 gdb_assert (data_size
== TYPE_LENGTH (value_type (value
)));
555 cached_frame
->reg
[i
].data
= (gdb_byte
*) xmalloc (data_size
);
556 memcpy (cached_frame
->reg
[i
].data
, value_contents (value
), data_size
);
560 *cache_ptr
= cached_frame
;
564 /* Frame cache release shim. */
567 pyuw_dealloc_cache (struct frame_info
*this_frame
, void *cache
)
569 TRACE_PY_UNWIND (3, "%s: enter", __FUNCTION__
);
570 cached_frame_info
*cached_frame
= (cached_frame_info
*) cache
;
572 for (int i
= 0; i
< cached_frame
->reg_count
; i
++)
573 xfree (cached_frame
->reg
[i
].data
);
578 struct pyuw_gdbarch_data_type
580 /* Has the unwinder shim been prepended? */
581 int unwinder_registered
;
585 pyuw_gdbarch_data_init (struct gdbarch
*gdbarch
)
587 return GDBARCH_OBSTACK_ZALLOC (gdbarch
, struct pyuw_gdbarch_data_type
);
590 /* New inferior architecture callback: register the Python unwinders
594 pyuw_on_new_gdbarch (struct gdbarch
*newarch
)
596 struct pyuw_gdbarch_data_type
*data
597 = (struct pyuw_gdbarch_data_type
*) gdbarch_data (newarch
,
600 if (!data
->unwinder_registered
)
602 struct frame_unwind
*unwinder
603 = GDBARCH_OBSTACK_ZALLOC (newarch
, struct frame_unwind
);
605 unwinder
->type
= NORMAL_FRAME
;
606 unwinder
->stop_reason
= default_frame_unwind_stop_reason
;
607 unwinder
->this_id
= pyuw_this_id
;
608 unwinder
->prev_register
= pyuw_prev_register
;
609 unwinder
->unwind_data
= (const struct frame_data
*) newarch
;
610 unwinder
->sniffer
= pyuw_sniffer
;
611 unwinder
->dealloc_cache
= pyuw_dealloc_cache
;
612 frame_unwind_prepend_unwinder (newarch
, unwinder
);
613 data
->unwinder_registered
= 1;
617 /* Initialize unwind machinery. */
620 gdbpy_initialize_unwind (void)
623 add_setshow_zuinteger_cmd
624 ("py-unwind", class_maintenance
, &pyuw_debug
,
625 _("Set Python unwinder debugging."),
626 _("Show Python unwinder debugging."),
627 _("When non-zero, Python unwinder debugging is enabled."),
630 &setdebuglist
, &showdebuglist
);
632 = gdbarch_data_register_post_init (pyuw_gdbarch_data_init
);
633 gdb::observers::architecture_changed
.attach (pyuw_on_new_gdbarch
);
635 if (PyType_Ready (&pending_frame_object_type
) < 0)
637 rc
= gdb_pymodule_addobject (gdb_module
, "PendingFrame",
638 (PyObject
*) &pending_frame_object_type
);
642 if (PyType_Ready (&unwind_info_object_type
) < 0)
644 return gdb_pymodule_addobject (gdb_module
, "UnwindInfo",
645 (PyObject
*) &unwind_info_object_type
);
648 static PyMethodDef pending_frame_object_methods
[] =
650 { "read_register", pending_framepy_read_register
, METH_VARARGS
,
651 "read_register (REG) -> gdb.Value\n"
652 "Return the value of the REG in the frame." },
653 { "create_unwind_info",
654 pending_framepy_create_unwind_info
, METH_VARARGS
,
655 "create_unwind_info (FRAME_ID) -> gdb.UnwindInfo\n"
656 "Construct UnwindInfo for this PendingFrame, using FRAME_ID\n"
659 pending_framepy_architecture
, METH_NOARGS
,
660 "architecture () -> gdb.Architecture\n"
661 "The architecture for this PendingFrame." },
662 {NULL
} /* Sentinel */
665 PyTypeObject pending_frame_object_type
=
667 PyVarObject_HEAD_INIT (NULL
, 0)
668 "gdb.PendingFrame", /* tp_name */
669 sizeof (pending_frame_object
), /* tp_basicsize */
677 0, /* tp_as_number */
678 0, /* tp_as_sequence */
679 0, /* tp_as_mapping */
682 pending_framepy_str
, /* tp_str */
685 0, /* tp_as_buffer */
686 Py_TPFLAGS_DEFAULT
, /* tp_flags */
687 "GDB PendingFrame object", /* tp_doc */
690 0, /* tp_richcompare */
691 0, /* tp_weaklistoffset */
694 pending_frame_object_methods
, /* tp_methods */
699 0, /* tp_descr_get */
700 0, /* tp_descr_set */
701 0, /* tp_dictoffset */
706 static PyMethodDef unwind_info_object_methods
[] =
708 { "add_saved_register",
709 unwind_infopy_add_saved_register
, METH_VARARGS
,
710 "add_saved_register (REG, VALUE) -> None\n"
711 "Set the value of the REG in the previous frame to VALUE." },
712 { NULL
} /* Sentinel */
715 PyTypeObject unwind_info_object_type
=
717 PyVarObject_HEAD_INIT (NULL
, 0)
718 "gdb.UnwindInfo", /* tp_name */
719 sizeof (unwind_info_object
), /* tp_basicsize */
721 unwind_infopy_dealloc
, /* tp_dealloc */
727 0, /* tp_as_number */
728 0, /* tp_as_sequence */
729 0, /* tp_as_mapping */
732 unwind_infopy_str
, /* tp_str */
735 0, /* tp_as_buffer */
736 Py_TPFLAGS_DEFAULT
| Py_TPFLAGS_BASETYPE
, /* tp_flags */
737 "GDB UnwindInfo object", /* tp_doc */
740 0, /* tp_richcompare */
741 0, /* tp_weaklistoffset */
744 unwind_info_object_methods
, /* tp_methods */
749 0, /* tp_descr_get */
750 0, /* tp_descr_set */
751 0, /* tp_dictoffset */