arm, objdump: print obsolote warning when 26-bit set in instructions
[binutils-gdb.git] / gdb / python / py-unwind.c
blob68deaf98d81f4d856421d3acf7d067c2c29a7dd8
1 /* Python frame unwinder interface.
3 Copyright (C) 2015-2024 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/>. */
20 #include "arch-utils.h"
21 #include "frame-unwind.h"
22 #include "gdbsupport/gdb_obstack.h"
23 #include "cli/cli-cmds.h"
24 #include "language.h"
25 #include "observable.h"
26 #include "python-internal.h"
27 #include "regcache.h"
28 #include "valprint.h"
29 #include "user-regs.h"
30 #include "stack.h"
31 #include "charset.h"
32 #include "block.h"
35 /* Debugging of Python unwinders. */
37 static bool pyuw_debug;
39 /* Implementation of "show debug py-unwind". */
41 static void
42 show_pyuw_debug (struct ui_file *file, int from_tty,
43 struct cmd_list_element *c, const char *value)
45 gdb_printf (file, _("Python unwinder debugging is %s.\n"), value);
48 /* Print a "py-unwind" debug statement. */
50 #define pyuw_debug_printf(fmt, ...) \
51 debug_prefixed_printf_cond (pyuw_debug, "py-unwind", fmt, ##__VA_ARGS__)
53 /* Print "py-unwind" enter/exit debug statements. */
55 #define PYUW_SCOPED_DEBUG_ENTER_EXIT \
56 scoped_debug_enter_exit (pyuw_debug, "py-unwind")
58 /* Require a valid pending frame. */
59 #define PENDING_FRAMEPY_REQUIRE_VALID(pending_frame) \
60 do { \
61 if ((pending_frame)->frame_info == nullptr) \
62 { \
63 PyErr_SetString (PyExc_ValueError, \
64 _("gdb.PendingFrame is invalid.")); \
65 return nullptr; \
66 } \
67 } while (0)
69 struct pending_frame_object
71 PyObject_HEAD
73 /* Frame we are unwinding. */
74 frame_info_ptr frame_info;
76 /* Its architecture, passed by the sniffer caller. */
77 struct gdbarch *gdbarch;
80 /* Saved registers array item. */
82 struct saved_reg
84 saved_reg (int n, gdbpy_ref<> &&v)
85 : number (n),
86 value (std::move (v))
90 int number;
91 gdbpy_ref<> value;
94 /* The data we keep for the PyUnwindInfo: pending_frame, saved registers
95 and frame ID. */
97 struct unwind_info_object
99 PyObject_HEAD
101 /* gdb.PendingFrame for the frame we are unwinding. */
102 PyObject *pending_frame;
104 /* Its ID. */
105 struct frame_id frame_id;
107 /* Saved registers array. */
108 std::vector<saved_reg> *saved_regs;
111 /* The data we keep for a frame we can unwind: frame ID and an array of
112 (register_number, register_value) pairs. */
114 struct cached_frame_info
116 /* Frame ID. */
117 struct frame_id frame_id;
119 /* GDB Architecture. */
120 struct gdbarch *gdbarch;
122 /* Length of the `reg' array below. */
123 int reg_count;
125 /* Flexible array member. Note: use a zero-sized array rather than
126 an actual C99-style flexible array member (unsized array),
127 because the latter would cause an error with Clang:
129 error: flexible array member 'reg' of type 'cached_reg_t[]' with non-trivial destruction
131 Note we manually call the destructor of each array element in
132 pyuw_dealloc_cache. */
133 cached_reg_t reg[0];
136 extern PyTypeObject pending_frame_object_type
137 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("pending_frame_object");
139 extern PyTypeObject unwind_info_object_type
140 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("unwind_info_object");
142 /* An enum returned by pyuw_object_attribute_to_pointer, a function which
143 is used to extract an attribute from a Python object. */
145 enum class pyuw_get_attr_code
147 /* The attribute was present, and its value was successfully extracted. */
148 ATTR_OK,
150 /* The attribute was not present, or was present and its value was None.
151 No Python error has been set. */
152 ATTR_MISSING,
154 /* The attribute was present, but there was some error while trying to
155 get the value from the attribute. A Python error will be set when
156 this is returned. */
157 ATTR_ERROR,
160 /* Get the attribute named ATTR_NAME from the object PYO and convert it to
161 an inferior pointer value, placing the pointer in *ADDR.
163 Return pyuw_get_attr_code::ATTR_OK if the attribute was present and its
164 value was successfully written into *ADDR. For any other return value
165 the contents of *ADDR are undefined.
167 Return pyuw_get_attr_code::ATTR_MISSING if the attribute was not
168 present, or it was present but its value was None. The contents of
169 *ADDR are undefined in this case. No Python error will be set in this
170 case.
172 Return pyuw_get_attr_code::ATTR_ERROR if the attribute was present, but
173 there was some error while extracting the attribute's value. A Python
174 error will be set in this case. The contents of *ADDR are undefined. */
176 static pyuw_get_attr_code
177 pyuw_object_attribute_to_pointer (PyObject *pyo, const char *attr_name,
178 CORE_ADDR *addr)
180 if (!PyObject_HasAttrString (pyo, attr_name))
181 return pyuw_get_attr_code::ATTR_MISSING;
183 gdbpy_ref<> pyo_value (PyObject_GetAttrString (pyo, attr_name));
184 if (pyo_value == nullptr)
186 gdb_assert (PyErr_Occurred ());
187 return pyuw_get_attr_code::ATTR_ERROR;
189 if (pyo_value == Py_None)
190 return pyuw_get_attr_code::ATTR_MISSING;
192 if (get_addr_from_python (pyo_value.get (), addr) < 0)
194 gdb_assert (PyErr_Occurred ());
195 return pyuw_get_attr_code::ATTR_ERROR;
198 return pyuw_get_attr_code::ATTR_OK;
201 /* Called by the Python interpreter to obtain string representation
202 of the UnwindInfo object. */
204 static PyObject *
205 unwind_infopy_str (PyObject *self)
207 unwind_info_object *unwind_info = (unwind_info_object *) self;
208 string_file stb;
210 stb.printf ("Frame ID: %s", unwind_info->frame_id.to_string ().c_str ());
212 const char *sep = "";
213 struct value_print_options opts;
215 get_user_print_options (&opts);
216 stb.printf ("\nSaved registers: (");
217 for (const saved_reg &reg : *unwind_info->saved_regs)
219 struct value *value = value_object_to_value (reg.value.get ());
221 stb.printf ("%s(%d, ", sep, reg.number);
222 if (value != NULL)
226 value_print (value, &stb, &opts);
227 stb.puts (")");
229 catch (const gdb_exception &except)
231 return gdbpy_handle_gdb_exception (nullptr, except);
234 else
235 stb.puts ("<BAD>)");
236 sep = ", ";
238 stb.puts (")");
241 return PyUnicode_FromString (stb.c_str ());
244 /* Implement UnwindInfo.__repr__(). */
246 static PyObject *
247 unwind_infopy_repr (PyObject *self)
249 unwind_info_object *unwind_info = (unwind_info_object *) self;
250 pending_frame_object *pending_frame
251 = (pending_frame_object *) (unwind_info->pending_frame);
252 frame_info_ptr frame = pending_frame->frame_info;
254 if (frame == nullptr)
255 return PyUnicode_FromFormat ("<%s for an invalid frame>",
256 Py_TYPE (self)->tp_name);
258 std::string saved_reg_names;
259 struct gdbarch *gdbarch = pending_frame->gdbarch;
261 for (const saved_reg &reg : *unwind_info->saved_regs)
263 const char *name = gdbarch_register_name (gdbarch, reg.number);
264 if (saved_reg_names.empty ())
265 saved_reg_names = name;
266 else
267 saved_reg_names = (saved_reg_names + ", ") + name;
270 return PyUnicode_FromFormat ("<%s frame #%d, saved_regs=(%s)>",
271 Py_TYPE (self)->tp_name,
272 frame_relative_level (frame),
273 saved_reg_names.c_str ());
276 /* Create UnwindInfo instance for given PendingFrame and frame ID.
277 Sets Python error and returns NULL on error.
279 The PYO_PENDING_FRAME object must be valid. */
281 static PyObject *
282 pyuw_create_unwind_info (PyObject *pyo_pending_frame,
283 struct frame_id frame_id)
285 gdb_assert (((pending_frame_object *) pyo_pending_frame)->frame_info
286 != nullptr);
288 unwind_info_object *unwind_info
289 = PyObject_New (unwind_info_object, &unwind_info_object_type);
291 unwind_info->frame_id = frame_id;
292 Py_INCREF (pyo_pending_frame);
293 unwind_info->pending_frame = pyo_pending_frame;
294 unwind_info->saved_regs = new std::vector<saved_reg>;
295 return (PyObject *) unwind_info;
298 /* The implementation of
299 gdb.UnwindInfo.add_saved_register (REG, VALUE) -> None. */
301 static PyObject *
302 unwind_infopy_add_saved_register (PyObject *self, PyObject *args, PyObject *kw)
304 unwind_info_object *unwind_info = (unwind_info_object *) self;
305 pending_frame_object *pending_frame
306 = (pending_frame_object *) (unwind_info->pending_frame);
307 PyObject *pyo_reg_id;
308 PyObject *pyo_reg_value;
309 int regnum;
311 if (pending_frame->frame_info == NULL)
313 PyErr_SetString (PyExc_ValueError,
314 "UnwindInfo instance refers to a stale PendingFrame");
315 return nullptr;
318 static const char *keywords[] = { "register", "value", nullptr };
319 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "OO!", keywords,
320 &pyo_reg_id, &value_object_type,
321 &pyo_reg_value))
322 return nullptr;
324 if (!gdbpy_parse_register_id (pending_frame->gdbarch, pyo_reg_id, &regnum))
325 return nullptr;
327 /* If REGNUM identifies a user register then *maybe* we can convert this
328 to a real (i.e. non-user) register. The maybe qualifier is because we
329 don't know what user registers each target might add, however, the
330 following logic should work for the usual style of user registers,
331 where the read function just forwards the register read on to some
332 other register with no adjusting the value. */
333 if (regnum >= gdbarch_num_cooked_regs (pending_frame->gdbarch))
335 struct value *user_reg_value
336 = value_of_user_reg (regnum, pending_frame->frame_info);
337 if (user_reg_value->lval () == lval_register)
338 regnum = user_reg_value->regnum ();
339 if (regnum >= gdbarch_num_cooked_regs (pending_frame->gdbarch))
341 PyErr_SetString (PyExc_ValueError, "Bad register");
342 return NULL;
346 /* The argument parsing above guarantees that PYO_REG_VALUE will be a
347 gdb.Value object, as a result the value_object_to_value call should
348 succeed. */
349 gdb_assert (pyo_reg_value != nullptr);
350 struct value *value = value_object_to_value (pyo_reg_value);
351 gdb_assert (value != nullptr);
353 ULONGEST reg_size = register_size (pending_frame->gdbarch, regnum);
354 if (reg_size != value->type ()->length ())
356 PyErr_Format (PyExc_ValueError,
357 "The value of the register returned by the Python "
358 "sniffer has unexpected size: %s instead of %s.",
359 pulongest (value->type ()->length ()),
360 pulongest (reg_size));
361 return nullptr;
367 if (value->optimized_out () || !value->entirely_available ())
369 /* If we allow this value to be registered here, pyuw_sniffer is going
370 to run into an exception when trying to access its contents.
371 Throwing an exception here just puts a burden on the user to
372 implement the same checks on the user side. We could return False
373 here and True otherwise, but again that might require changes in
374 user code. So, handle this with minimal impact for the user, while
375 improving robustness: silently ignore the register/value pair. */
376 Py_RETURN_NONE;
379 catch (const gdb_exception &except)
381 return gdbpy_handle_gdb_exception (nullptr, except);
384 gdbpy_ref<> new_value = gdbpy_ref<>::new_reference (pyo_reg_value);
385 bool found = false;
386 for (saved_reg &reg : *unwind_info->saved_regs)
388 if (regnum == reg.number)
390 found = true;
391 reg.value = std::move (new_value);
392 break;
395 if (!found)
396 unwind_info->saved_regs->emplace_back (regnum, std::move (new_value));
398 Py_RETURN_NONE;
401 /* UnwindInfo cleanup. */
403 static void
404 unwind_infopy_dealloc (PyObject *self)
406 unwind_info_object *unwind_info = (unwind_info_object *) self;
408 Py_XDECREF (unwind_info->pending_frame);
409 delete unwind_info->saved_regs;
410 Py_TYPE (self)->tp_free (self);
413 /* Called by the Python interpreter to obtain string representation
414 of the PendingFrame object. */
416 static PyObject *
417 pending_framepy_str (PyObject *self)
419 frame_info_ptr frame = ((pending_frame_object *) self)->frame_info;
420 const char *sp_str = NULL;
421 const char *pc_str = NULL;
423 if (frame == NULL)
424 return PyUnicode_FromString ("Stale PendingFrame instance");
427 sp_str = core_addr_to_string_nz (get_frame_sp (frame));
428 pc_str = core_addr_to_string_nz (get_frame_pc (frame));
430 catch (const gdb_exception &except)
432 return gdbpy_handle_gdb_exception (nullptr, except);
435 return PyUnicode_FromFormat ("SP=%s,PC=%s", sp_str, pc_str);
438 /* Implement PendingFrame.__repr__(). */
440 static PyObject *
441 pending_framepy_repr (PyObject *self)
443 pending_frame_object *pending_frame = (pending_frame_object *) self;
444 frame_info_ptr frame = pending_frame->frame_info;
446 if (frame == nullptr)
447 return gdb_py_invalid_object_repr (self);
449 const char *sp_str = nullptr;
450 const char *pc_str = nullptr;
454 sp_str = core_addr_to_string_nz (get_frame_sp (frame));
455 pc_str = core_addr_to_string_nz (get_frame_pc (frame));
457 catch (const gdb_exception &except)
459 return gdbpy_handle_gdb_exception (nullptr, except);
462 return PyUnicode_FromFormat ("<%s level=%d, sp=%s, pc=%s>",
463 Py_TYPE (self)->tp_name,
464 frame_relative_level (frame),
465 sp_str,
466 pc_str);
469 /* Implementation of gdb.PendingFrame.read_register (self, reg) -> gdb.Value.
470 Returns the value of register REG as gdb.Value instance. */
472 static PyObject *
473 pending_framepy_read_register (PyObject *self, PyObject *args, PyObject *kw)
475 pending_frame_object *pending_frame = (pending_frame_object *) self;
476 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
478 PyObject *pyo_reg_id;
479 static const char *keywords[] = { "register", nullptr };
480 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "O", keywords, &pyo_reg_id))
481 return nullptr;
483 int regnum;
484 if (!gdbpy_parse_register_id (pending_frame->gdbarch, pyo_reg_id, &regnum))
485 return nullptr;
487 PyObject *result = nullptr;
490 scoped_value_mark free_values;
492 /* Fetch the value associated with a register, whether it's
493 a real register or a so called "user" register, like "pc",
494 which maps to a real register. In the past,
495 get_frame_register_value() was used here, which did not
496 handle the user register case. */
497 value *val = value_of_register
498 (regnum, get_next_frame_sentinel_okay (pending_frame->frame_info));
499 if (val == NULL)
500 PyErr_Format (PyExc_ValueError,
501 "Cannot read register %d from frame.",
502 regnum);
503 else
504 result = value_to_value_object (val);
506 catch (const gdb_exception &except)
508 return gdbpy_handle_gdb_exception (nullptr, except);
511 return result;
514 /* Implement PendingFrame.is_valid(). Return True if this pending frame
515 object is still valid. */
517 static PyObject *
518 pending_framepy_is_valid (PyObject *self, PyObject *args)
520 pending_frame_object *pending_frame = (pending_frame_object *) self;
522 if (pending_frame->frame_info == nullptr)
523 Py_RETURN_FALSE;
525 Py_RETURN_TRUE;
528 /* Implement PendingFrame.name(). Return a string that is the name of the
529 function for this frame, or None if the name can't be found. */
531 static PyObject *
532 pending_framepy_name (PyObject *self, PyObject *args)
534 pending_frame_object *pending_frame = (pending_frame_object *) self;
536 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
538 gdb::unique_xmalloc_ptr<char> name;
542 enum language lang;
543 frame_info_ptr frame = pending_frame->frame_info;
545 name = find_frame_funname (frame, &lang, nullptr);
547 catch (const gdb_exception &except)
549 return gdbpy_handle_gdb_exception (nullptr, except);
552 if (name != nullptr)
553 return PyUnicode_Decode (name.get (), strlen (name.get ()),
554 host_charset (), nullptr);
556 Py_RETURN_NONE;
559 /* Implement gdb.PendingFrame.pc(). Returns an integer containing the
560 frame's current $pc value. */
562 static PyObject *
563 pending_framepy_pc (PyObject *self, PyObject *args)
565 pending_frame_object *pending_frame = (pending_frame_object *) self;
567 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
569 CORE_ADDR pc = 0;
573 pc = get_frame_pc (pending_frame->frame_info);
575 catch (const gdb_exception &except)
577 return gdbpy_handle_gdb_exception (nullptr, except);
580 return gdb_py_object_from_ulongest (pc).release ();
583 /* Implement gdb.PendingFrame.language(). Return the name of the language
584 for this frame. */
586 static PyObject *
587 pending_framepy_language (PyObject *self, PyObject *args)
589 pending_frame_object *pending_frame = (pending_frame_object *) self;
591 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
595 frame_info_ptr fi = pending_frame->frame_info;
597 enum language lang = get_frame_language (fi);
598 const language_defn *lang_def = language_def (lang);
600 return host_string_to_python_string (lang_def->name ()).release ();
602 catch (const gdb_exception &except)
604 return gdbpy_handle_gdb_exception (nullptr, except);
607 Py_RETURN_NONE;
610 /* Implement PendingFrame.find_sal(). Return the PendingFrame's symtab and
611 line. */
613 static PyObject *
614 pending_framepy_find_sal (PyObject *self, PyObject *args)
616 pending_frame_object *pending_frame = (pending_frame_object *) self;
618 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
620 PyObject *sal_obj = nullptr;
624 frame_info_ptr frame = pending_frame->frame_info;
626 symtab_and_line sal = find_frame_sal (frame);
627 sal_obj = symtab_and_line_to_sal_object (sal);
629 catch (const gdb_exception &except)
631 return gdbpy_handle_gdb_exception (nullptr, except);
634 return sal_obj;
637 /* Implement PendingFrame.block(). Return a gdb.Block for the pending
638 frame's code, or raise RuntimeError if the block can't be found. */
640 static PyObject *
641 pending_framepy_block (PyObject *self, PyObject *args)
643 pending_frame_object *pending_frame = (pending_frame_object *) self;
645 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
647 frame_info_ptr frame = pending_frame->frame_info;
648 const struct block *block = nullptr, *fn_block;
652 block = get_frame_block (frame, nullptr);
654 catch (const gdb_exception &except)
656 return gdbpy_handle_gdb_exception (nullptr, except);
659 for (fn_block = block;
660 fn_block != nullptr && fn_block->function () == nullptr;
661 fn_block = fn_block->superblock ())
664 if (block == nullptr
665 || fn_block == nullptr
666 || fn_block->function () == nullptr)
668 PyErr_SetString (PyExc_RuntimeError,
669 _("Cannot locate block for frame."));
670 return nullptr;
673 return block_to_block_object (block, fn_block->function ()->objfile ());
676 /* Implement gdb.PendingFrame.function(). Return a gdb.Symbol
677 representing the function of this frame, or None if no suitable symbol
678 can be found. */
680 static PyObject *
681 pending_framepy_function (PyObject *self, PyObject *args)
683 pending_frame_object *pending_frame = (pending_frame_object *) self;
685 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
687 struct symbol *sym = nullptr;
691 enum language funlang;
692 frame_info_ptr frame = pending_frame->frame_info;
694 gdb::unique_xmalloc_ptr<char> funname
695 = find_frame_funname (frame, &funlang, &sym);
697 catch (const gdb_exception &except)
699 return gdbpy_handle_gdb_exception (nullptr, except);
702 if (sym != nullptr)
703 return symbol_to_symbol_object (sym);
705 Py_RETURN_NONE;
708 /* Implementation of
709 PendingFrame.create_unwind_info (self, frameId) -> UnwindInfo. */
711 static PyObject *
712 pending_framepy_create_unwind_info (PyObject *self, PyObject *args,
713 PyObject *kw)
715 PyObject *pyo_frame_id;
716 CORE_ADDR sp;
717 CORE_ADDR pc;
718 CORE_ADDR special;
720 PENDING_FRAMEPY_REQUIRE_VALID ((pending_frame_object *) self);
722 static const char *keywords[] = { "frame_id", nullptr };
723 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "O", keywords,
724 &pyo_frame_id))
725 return nullptr;
727 pyuw_get_attr_code code
728 = pyuw_object_attribute_to_pointer (pyo_frame_id, "sp", &sp);
729 if (code == pyuw_get_attr_code::ATTR_MISSING)
731 PyErr_SetString (PyExc_ValueError,
732 _("frame_id should have 'sp' attribute."));
733 return nullptr;
735 else if (code == pyuw_get_attr_code::ATTR_ERROR)
736 return nullptr;
738 /* The logic of building frame_id depending on the attributes of
739 the frame_id object:
740 Has Has Has Function to call
741 'sp'? 'pc'? 'special'?
742 ------|------|--------------|-------------------------
743 Y N * frame_id_build_wild (sp)
744 Y Y N frame_id_build (sp, pc)
745 Y Y Y frame_id_build_special (sp, pc, special)
747 code = pyuw_object_attribute_to_pointer (pyo_frame_id, "pc", &pc);
748 if (code == pyuw_get_attr_code::ATTR_ERROR)
749 return nullptr;
750 else if (code == pyuw_get_attr_code::ATTR_MISSING)
751 return pyuw_create_unwind_info (self, frame_id_build_wild (sp));
753 code = pyuw_object_attribute_to_pointer (pyo_frame_id, "special", &special);
754 if (code == pyuw_get_attr_code::ATTR_ERROR)
755 return nullptr;
756 else if (code == pyuw_get_attr_code::ATTR_MISSING)
757 return pyuw_create_unwind_info (self, frame_id_build (sp, pc));
759 return pyuw_create_unwind_info (self,
760 frame_id_build_special (sp, pc, special));
763 /* Implementation of PendingFrame.architecture (self) -> gdb.Architecture. */
765 static PyObject *
766 pending_framepy_architecture (PyObject *self, PyObject *args)
768 pending_frame_object *pending_frame = (pending_frame_object *) self;
770 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
772 return gdbarch_to_arch_object (pending_frame->gdbarch);
775 /* Implementation of PendingFrame.level (self) -> Integer. */
777 static PyObject *
778 pending_framepy_level (PyObject *self, PyObject *args)
780 pending_frame_object *pending_frame = (pending_frame_object *) self;
782 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
784 int level = frame_relative_level (pending_frame->frame_info);
785 return gdb_py_object_from_longest (level).release ();
788 /* frame_unwind.this_id method. */
790 static void
791 pyuw_this_id (const frame_info_ptr &this_frame, void **cache_ptr,
792 struct frame_id *this_id)
794 *this_id = ((cached_frame_info *) *cache_ptr)->frame_id;
795 pyuw_debug_printf ("frame_id: %s", this_id->to_string ().c_str ());
798 /* frame_unwind.prev_register. */
800 static struct value *
801 pyuw_prev_register (const frame_info_ptr &this_frame, void **cache_ptr,
802 int regnum)
804 PYUW_SCOPED_DEBUG_ENTER_EXIT;
806 cached_frame_info *cached_frame = (cached_frame_info *) *cache_ptr;
807 cached_reg_t *reg_info = cached_frame->reg;
808 cached_reg_t *reg_info_end = reg_info + cached_frame->reg_count;
810 pyuw_debug_printf ("frame=%d, reg=%d",
811 frame_relative_level (this_frame), regnum);
812 for (; reg_info < reg_info_end; ++reg_info)
814 if (regnum == reg_info->num)
815 return frame_unwind_got_bytes (this_frame, regnum, reg_info->data.get ());
818 return frame_unwind_got_optimized (this_frame, regnum);
821 /* Frame sniffer dispatch. */
823 static int
824 pyuw_sniffer (const struct frame_unwind *self, const frame_info_ptr &this_frame,
825 void **cache_ptr)
827 PYUW_SCOPED_DEBUG_ENTER_EXIT;
829 struct gdbarch *gdbarch = (struct gdbarch *) (self->unwind_data);
830 cached_frame_info *cached_frame;
832 gdbpy_enter enter_py (gdbarch);
834 pyuw_debug_printf ("frame=%d, sp=%s, pc=%s",
835 frame_relative_level (this_frame),
836 paddress (gdbarch, get_frame_sp (this_frame)),
837 paddress (gdbarch, get_frame_pc (this_frame)));
839 /* Create PendingFrame instance to pass to sniffers. */
840 pending_frame_object *pfo = PyObject_New (pending_frame_object,
841 &pending_frame_object_type);
842 gdbpy_ref<> pyo_pending_frame ((PyObject *) pfo);
843 if (pyo_pending_frame == NULL)
845 gdbpy_print_stack ();
846 return 0;
848 pfo->gdbarch = gdbarch;
849 pfo->frame_info = nullptr;
850 scoped_restore invalidate_frame = make_scoped_restore (&pfo->frame_info,
851 this_frame);
853 /* Run unwinders. */
854 if (gdb_python_module == NULL
855 || ! PyObject_HasAttrString (gdb_python_module, "_execute_unwinders"))
857 PyErr_SetString (PyExc_NameError,
858 "Installation error: gdb._execute_unwinders function "
859 "is missing");
860 gdbpy_print_stack ();
861 return 0;
863 gdbpy_ref<> pyo_execute (PyObject_GetAttrString (gdb_python_module,
864 "_execute_unwinders"));
865 if (pyo_execute == nullptr)
867 gdbpy_print_stack ();
868 return 0;
871 /* A (gdb.UnwindInfo, str) tuple, or None. */
872 gdbpy_ref<> pyo_execute_ret
873 (PyObject_CallFunctionObjArgs (pyo_execute.get (),
874 pyo_pending_frame.get (), NULL));
875 if (pyo_execute_ret == nullptr)
877 /* If the unwinder is cancelled due to a Ctrl-C, then propagate
878 the Ctrl-C as a GDB exception instead of swallowing it. */
879 gdbpy_print_stack_or_quit ();
880 return 0;
882 if (pyo_execute_ret == Py_None)
883 return 0;
885 /* Verify the return value of _execute_unwinders is a tuple of size 2. */
886 gdb_assert (PyTuple_Check (pyo_execute_ret.get ()));
887 gdb_assert (PyTuple_GET_SIZE (pyo_execute_ret.get ()) == 2);
889 if (pyuw_debug)
891 PyObject *pyo_unwinder_name = PyTuple_GET_ITEM (pyo_execute_ret.get (), 1);
892 gdb::unique_xmalloc_ptr<char> name
893 = python_string_to_host_string (pyo_unwinder_name);
895 /* This could happen if the user passed something else than a string
896 as the unwinder's name. */
897 if (name == nullptr)
899 gdbpy_print_stack ();
900 name = make_unique_xstrdup ("<failed to get unwinder name>");
903 pyuw_debug_printf ("frame claimed by unwinder %s", name.get ());
906 /* Received UnwindInfo, cache data. */
907 PyObject *pyo_unwind_info = PyTuple_GET_ITEM (pyo_execute_ret.get (), 0);
908 if (PyObject_IsInstance (pyo_unwind_info,
909 (PyObject *) &unwind_info_object_type) <= 0)
910 error (_("A Unwinder should return gdb.UnwindInfo instance."));
913 unwind_info_object *unwind_info =
914 (unwind_info_object *) pyo_unwind_info;
915 int reg_count = unwind_info->saved_regs->size ();
917 cached_frame
918 = ((cached_frame_info *)
919 xmalloc (sizeof (*cached_frame)
920 + reg_count * sizeof (cached_frame->reg[0])));
921 cached_frame->gdbarch = gdbarch;
922 cached_frame->frame_id = unwind_info->frame_id;
923 cached_frame->reg_count = reg_count;
925 /* Populate registers array. */
926 for (int i = 0; i < unwind_info->saved_regs->size (); ++i)
928 saved_reg *reg = &(*unwind_info->saved_regs)[i];
930 struct value *value = value_object_to_value (reg->value.get ());
931 size_t data_size = register_size (gdbarch, reg->number);
933 /* `value' validation was done before, just assert. */
934 gdb_assert (value != NULL);
935 gdb_assert (data_size == value->type ()->length ());
937 cached_reg_t *cached = new (&cached_frame->reg[i]) cached_reg_t ();
938 cached->num = reg->number;
939 cached->data.reset ((gdb_byte *) xmalloc (data_size));
940 memcpy (cached->data.get (), value->contents ().data (), data_size);
944 *cache_ptr = cached_frame;
945 return 1;
948 /* Frame cache release shim. */
950 static void
951 pyuw_dealloc_cache (frame_info *this_frame, void *cache)
953 PYUW_SCOPED_DEBUG_ENTER_EXIT;
954 cached_frame_info *cached_frame = (cached_frame_info *) cache;
956 for (int i = 0; i < cached_frame->reg_count; i++)
957 cached_frame->reg[i].~cached_reg_t ();
959 xfree (cache);
962 struct pyuw_gdbarch_data_type
964 /* Has the unwinder shim been prepended? */
965 int unwinder_registered = 0;
968 static const registry<gdbarch>::key<pyuw_gdbarch_data_type> pyuw_gdbarch_data;
970 /* New inferior architecture callback: register the Python unwinders
971 intermediary. */
973 static void
974 pyuw_on_new_gdbarch (gdbarch *newarch)
976 struct pyuw_gdbarch_data_type *data = pyuw_gdbarch_data.get (newarch);
977 if (data == nullptr)
978 data= pyuw_gdbarch_data.emplace (newarch);
980 if (!data->unwinder_registered)
982 struct frame_unwind *unwinder
983 = GDBARCH_OBSTACK_ZALLOC (newarch, struct frame_unwind);
985 unwinder->name = "python";
986 unwinder->type = NORMAL_FRAME;
987 unwinder->stop_reason = default_frame_unwind_stop_reason;
988 unwinder->this_id = pyuw_this_id;
989 unwinder->prev_register = pyuw_prev_register;
990 unwinder->unwind_data = (const struct frame_data *) newarch;
991 unwinder->sniffer = pyuw_sniffer;
992 unwinder->dealloc_cache = pyuw_dealloc_cache;
993 frame_unwind_prepend_unwinder (newarch, unwinder);
994 data->unwinder_registered = 1;
998 /* Initialize unwind machinery. */
1000 static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
1001 gdbpy_initialize_unwind (void)
1003 gdb::observers::new_architecture.attach (pyuw_on_new_gdbarch, "py-unwind");
1005 if (gdbpy_type_ready (&pending_frame_object_type) < 0)
1006 return -1;
1008 if (gdbpy_type_ready (&unwind_info_object_type) < 0)
1009 return -1;
1011 return 0;
1014 void _initialize_py_unwind ();
1015 void
1016 _initialize_py_unwind ()
1018 add_setshow_boolean_cmd
1019 ("py-unwind", class_maintenance, &pyuw_debug,
1020 _("Set Python unwinder debugging."),
1021 _("Show Python unwinder debugging."),
1022 _("When on, Python unwinder debugging is enabled."),
1023 NULL,
1024 show_pyuw_debug,
1025 &setdebuglist, &showdebuglist);
1028 GDBPY_INITIALIZE_FILE (gdbpy_initialize_unwind);
1032 static PyMethodDef pending_frame_object_methods[] =
1034 { "read_register", (PyCFunction) pending_framepy_read_register,
1035 METH_VARARGS | METH_KEYWORDS,
1036 "read_register (REG) -> gdb.Value\n"
1037 "Return the value of the REG in the frame." },
1038 { "create_unwind_info", (PyCFunction) pending_framepy_create_unwind_info,
1039 METH_VARARGS | METH_KEYWORDS,
1040 "create_unwind_info (FRAME_ID) -> gdb.UnwindInfo\n"
1041 "Construct UnwindInfo for this PendingFrame, using FRAME_ID\n"
1042 "to identify it." },
1043 { "architecture",
1044 pending_framepy_architecture, METH_NOARGS,
1045 "architecture () -> gdb.Architecture\n"
1046 "The architecture for this PendingFrame." },
1047 { "name",
1048 pending_framepy_name, METH_NOARGS,
1049 "name() -> String.\n\
1050 Return the function name of the frame, or None if it can't be determined." },
1051 { "is_valid",
1052 pending_framepy_is_valid, METH_NOARGS,
1053 "is_valid () -> Boolean.\n\
1054 Return true if this PendingFrame is valid, false if not." },
1055 { "pc",
1056 pending_framepy_pc, METH_NOARGS,
1057 "pc () -> Long.\n\
1058 Return the frame's resume address." },
1059 { "language", pending_framepy_language, METH_NOARGS,
1060 "The language of this frame." },
1061 { "find_sal", pending_framepy_find_sal, METH_NOARGS,
1062 "find_sal () -> gdb.Symtab_and_line.\n\
1063 Return the frame's symtab and line." },
1064 { "block", pending_framepy_block, METH_NOARGS,
1065 "block () -> gdb.Block.\n\
1066 Return the frame's code block." },
1067 { "function", pending_framepy_function, METH_NOARGS,
1068 "function () -> gdb.Symbol.\n\
1069 Returns the symbol for the function corresponding to this frame." },
1070 { "level", pending_framepy_level, METH_NOARGS,
1071 "The stack level of this frame." },
1072 {NULL} /* Sentinel */
1075 PyTypeObject pending_frame_object_type =
1077 PyVarObject_HEAD_INIT (NULL, 0)
1078 "gdb.PendingFrame", /* tp_name */
1079 sizeof (pending_frame_object), /* tp_basicsize */
1080 0, /* tp_itemsize */
1081 0, /* tp_dealloc */
1082 0, /* tp_print */
1083 0, /* tp_getattr */
1084 0, /* tp_setattr */
1085 0, /* tp_compare */
1086 pending_framepy_repr, /* tp_repr */
1087 0, /* tp_as_number */
1088 0, /* tp_as_sequence */
1089 0, /* tp_as_mapping */
1090 0, /* tp_hash */
1091 0, /* tp_call */
1092 pending_framepy_str, /* tp_str */
1093 0, /* tp_getattro */
1094 0, /* tp_setattro */
1095 0, /* tp_as_buffer */
1096 Py_TPFLAGS_DEFAULT, /* tp_flags */
1097 "GDB PendingFrame object", /* tp_doc */
1098 0, /* tp_traverse */
1099 0, /* tp_clear */
1100 0, /* tp_richcompare */
1101 0, /* tp_weaklistoffset */
1102 0, /* tp_iter */
1103 0, /* tp_iternext */
1104 pending_frame_object_methods, /* tp_methods */
1105 0, /* tp_members */
1106 0, /* tp_getset */
1107 0, /* tp_base */
1108 0, /* tp_dict */
1109 0, /* tp_descr_get */
1110 0, /* tp_descr_set */
1111 0, /* tp_dictoffset */
1112 0, /* tp_init */
1113 0, /* tp_alloc */
1116 static PyMethodDef unwind_info_object_methods[] =
1118 { "add_saved_register",
1119 (PyCFunction) unwind_infopy_add_saved_register,
1120 METH_VARARGS | METH_KEYWORDS,
1121 "add_saved_register (REG, VALUE) -> None\n"
1122 "Set the value of the REG in the previous frame to VALUE." },
1123 { NULL } /* Sentinel */
1126 PyTypeObject unwind_info_object_type =
1128 PyVarObject_HEAD_INIT (NULL, 0)
1129 "gdb.UnwindInfo", /* tp_name */
1130 sizeof (unwind_info_object), /* tp_basicsize */
1131 0, /* tp_itemsize */
1132 unwind_infopy_dealloc, /* tp_dealloc */
1133 0, /* tp_print */
1134 0, /* tp_getattr */
1135 0, /* tp_setattr */
1136 0, /* tp_compare */
1137 unwind_infopy_repr, /* tp_repr */
1138 0, /* tp_as_number */
1139 0, /* tp_as_sequence */
1140 0, /* tp_as_mapping */
1141 0, /* tp_hash */
1142 0, /* tp_call */
1143 unwind_infopy_str, /* tp_str */
1144 0, /* tp_getattro */
1145 0, /* tp_setattro */
1146 0, /* tp_as_buffer */
1147 Py_TPFLAGS_DEFAULT, /* tp_flags */
1148 "GDB UnwindInfo object", /* tp_doc */
1149 0, /* tp_traverse */
1150 0, /* tp_clear */
1151 0, /* tp_richcompare */
1152 0, /* tp_weaklistoffset */
1153 0, /* tp_iter */
1154 0, /* tp_iternext */
1155 unwind_info_object_methods, /* tp_methods */
1156 0, /* tp_members */
1157 0, /* tp_getset */
1158 0, /* tp_base */
1159 0, /* tp_dict */
1160 0, /* tp_descr_get */
1161 0, /* tp_descr_set */
1162 0, /* tp_dictoffset */
1163 0, /* tp_init */
1164 0, /* tp_alloc */