More updated translations
[binutils-gdb.git] / gdb / python / py-unwind.c
blobaf8ee980ba7dc5225020324500a7e52902c9df16
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 /* Class for frame unwinders registered by the Python architecture callback. */
789 class frame_unwind_python : public frame_unwind
791 public:
792 frame_unwind_python (const struct frame_data *newarch)
793 : frame_unwind ("python", NORMAL_FRAME, FRAME_UNWIND_EXTENSION, newarch)
796 /* No need to override stop_reason, we want the default. */
798 int sniff (const frame_info_ptr &this_frame,
799 void **this_prologue_cache) const override;
801 void this_id (const frame_info_ptr &this_frame, void **this_prologue_cache,
802 struct frame_id *id) const override;
804 struct value *prev_register (const frame_info_ptr &this_frame,
805 void **this_prologue_cache,
806 int regnum) const override;
808 void dealloc_cache (frame_info *self, void *this_cache) const override;
811 /* frame_unwind.this_id method. */
813 void
814 frame_unwind_python::this_id (const frame_info_ptr &this_frame,
815 void **cache_ptr,
816 struct frame_id *this_id) const
818 *this_id = ((cached_frame_info *) *cache_ptr)->frame_id;
819 pyuw_debug_printf ("frame_id: %s", this_id->to_string ().c_str ());
822 /* frame_unwind.prev_register. */
824 struct value *
825 frame_unwind_python::prev_register (const frame_info_ptr &this_frame,
826 void **cache_ptr, int regnum) const
828 PYUW_SCOPED_DEBUG_ENTER_EXIT;
830 cached_frame_info *cached_frame = (cached_frame_info *) *cache_ptr;
831 cached_reg_t *reg_info = cached_frame->reg;
832 cached_reg_t *reg_info_end = reg_info + cached_frame->reg_count;
834 pyuw_debug_printf ("frame=%d, reg=%d",
835 frame_relative_level (this_frame), regnum);
836 for (; reg_info < reg_info_end; ++reg_info)
838 if (regnum == reg_info->num)
839 return frame_unwind_got_bytes (this_frame, regnum, reg_info->data);
842 return frame_unwind_got_optimized (this_frame, regnum);
845 /* Frame sniffer dispatch. */
848 frame_unwind_python::sniff (const frame_info_ptr &this_frame,
849 void **cache_ptr) const
851 PYUW_SCOPED_DEBUG_ENTER_EXIT;
853 struct gdbarch *gdbarch = (struct gdbarch *) (this->unwind_data ());
854 cached_frame_info *cached_frame;
856 gdbpy_enter enter_py (gdbarch);
858 pyuw_debug_printf ("frame=%d, sp=%s, pc=%s",
859 frame_relative_level (this_frame),
860 paddress (gdbarch, get_frame_sp (this_frame)),
861 paddress (gdbarch, get_frame_pc (this_frame)));
863 /* Create PendingFrame instance to pass to sniffers. */
864 pending_frame_object *pfo = PyObject_New (pending_frame_object,
865 &pending_frame_object_type);
866 gdbpy_ref<> pyo_pending_frame ((PyObject *) pfo);
867 if (pyo_pending_frame == NULL)
869 gdbpy_print_stack ();
870 return 0;
872 pfo->gdbarch = gdbarch;
873 pfo->frame_info = nullptr;
874 scoped_restore invalidate_frame = make_scoped_restore (&pfo->frame_info,
875 this_frame);
877 /* Run unwinders. */
878 if (gdb_python_module == NULL
879 || ! PyObject_HasAttrString (gdb_python_module, "_execute_unwinders"))
881 PyErr_SetString (PyExc_NameError,
882 "Installation error: gdb._execute_unwinders function "
883 "is missing");
884 gdbpy_print_stack ();
885 return 0;
887 gdbpy_ref<> pyo_execute (PyObject_GetAttrString (gdb_python_module,
888 "_execute_unwinders"));
889 if (pyo_execute == nullptr)
891 gdbpy_print_stack ();
892 return 0;
895 /* A (gdb.UnwindInfo, str) tuple, or None. */
896 gdbpy_ref<> pyo_execute_ret
897 (PyObject_CallFunctionObjArgs (pyo_execute.get (),
898 pyo_pending_frame.get (), NULL));
899 if (pyo_execute_ret == nullptr)
901 /* If the unwinder is cancelled due to a Ctrl-C, then propagate
902 the Ctrl-C as a GDB exception instead of swallowing it. */
903 gdbpy_print_stack_or_quit ();
904 return 0;
906 if (pyo_execute_ret == Py_None)
907 return 0;
909 /* Verify the return value of _execute_unwinders is a tuple of size 2. */
910 gdb_assert (PyTuple_Check (pyo_execute_ret.get ()));
911 gdb_assert (PyTuple_GET_SIZE (pyo_execute_ret.get ()) == 2);
913 if (pyuw_debug)
915 PyObject *pyo_unwinder_name = PyTuple_GET_ITEM (pyo_execute_ret.get (), 1);
916 gdb::unique_xmalloc_ptr<char> name
917 = python_string_to_host_string (pyo_unwinder_name);
919 /* This could happen if the user passed something else than a string
920 as the unwinder's name. */
921 if (name == nullptr)
923 gdbpy_print_stack ();
924 name = make_unique_xstrdup ("<failed to get unwinder name>");
927 pyuw_debug_printf ("frame claimed by unwinder %s", name.get ());
930 /* Received UnwindInfo, cache data. */
931 PyObject *pyo_unwind_info = PyTuple_GET_ITEM (pyo_execute_ret.get (), 0);
932 if (PyObject_IsInstance (pyo_unwind_info,
933 (PyObject *) &unwind_info_object_type) <= 0)
934 error (_("A Unwinder should return gdb.UnwindInfo instance."));
937 unwind_info_object *unwind_info =
938 (unwind_info_object *) pyo_unwind_info;
939 int reg_count = unwind_info->saved_regs->size ();
941 cached_frame
942 = ((cached_frame_info *)
943 xmalloc (sizeof (*cached_frame)
944 + reg_count * sizeof (cached_frame->reg[0])));
945 cached_frame->gdbarch = gdbarch;
946 cached_frame->frame_id = unwind_info->frame_id;
947 cached_frame->reg_count = reg_count;
949 /* Populate registers array. */
950 for (int i = 0; i < unwind_info->saved_regs->size (); ++i)
952 saved_reg *reg = &(*unwind_info->saved_regs)[i];
954 struct value *value = value_object_to_value (reg->value.get ());
955 size_t data_size = register_size (gdbarch, reg->number);
957 /* `value' validation was done before, just assert. */
958 gdb_assert (value != NULL);
959 gdb_assert (data_size == value->type ()->length ());
961 cached_reg_t *cached = new (&cached_frame->reg[i]) cached_reg_t ();
962 cached->num = reg->number;
963 cached->data.resize (data_size);
964 gdb::array_view<const gdb_byte> contents = value->contents ();
965 cached->data.assign (contents.begin (), contents.end ());
969 *cache_ptr = cached_frame;
970 return 1;
973 /* Frame cache release shim. */
975 void
976 frame_unwind_python::dealloc_cache (frame_info *this_frame, void *cache) const
978 PYUW_SCOPED_DEBUG_ENTER_EXIT;
979 cached_frame_info *cached_frame = (cached_frame_info *) cache;
981 for (int i = 0; i < cached_frame->reg_count; i++)
982 cached_frame->reg[i].~cached_reg_t ();
984 xfree (cache);
987 struct pyuw_gdbarch_data_type
989 /* Has the unwinder shim been prepended? */
990 int unwinder_registered = 0;
993 static const registry<gdbarch>::key<pyuw_gdbarch_data_type> pyuw_gdbarch_data;
995 /* New inferior architecture callback: register the Python unwinders
996 intermediary. */
998 static void
999 pyuw_on_new_gdbarch (gdbarch *newarch)
1001 struct pyuw_gdbarch_data_type *data = pyuw_gdbarch_data.get (newarch);
1002 if (data == nullptr)
1003 data= pyuw_gdbarch_data.emplace (newarch);
1005 if (!data->unwinder_registered)
1007 struct frame_unwind *unwinder
1008 = obstack_new<frame_unwind_python>
1009 (gdbarch_obstack (newarch), (const struct frame_data *) newarch);
1011 frame_unwind_prepend_unwinder (newarch, unwinder);
1012 data->unwinder_registered = 1;
1016 /* Initialize unwind machinery. */
1018 static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
1019 gdbpy_initialize_unwind (void)
1021 gdb::observers::new_architecture.attach (pyuw_on_new_gdbarch, "py-unwind");
1023 if (gdbpy_type_ready (&pending_frame_object_type) < 0)
1024 return -1;
1026 if (gdbpy_type_ready (&unwind_info_object_type) < 0)
1027 return -1;
1029 return 0;
1032 void _initialize_py_unwind ();
1033 void
1034 _initialize_py_unwind ()
1036 add_setshow_boolean_cmd
1037 ("py-unwind", class_maintenance, &pyuw_debug,
1038 _("Set Python unwinder debugging."),
1039 _("Show Python unwinder debugging."),
1040 _("When on, Python unwinder debugging is enabled."),
1041 NULL,
1042 show_pyuw_debug,
1043 &setdebuglist, &showdebuglist);
1046 GDBPY_INITIALIZE_FILE (gdbpy_initialize_unwind);
1050 static PyMethodDef pending_frame_object_methods[] =
1052 { "read_register", (PyCFunction) pending_framepy_read_register,
1053 METH_VARARGS | METH_KEYWORDS,
1054 "read_register (REG) -> gdb.Value\n"
1055 "Return the value of the REG in the frame." },
1056 { "create_unwind_info", (PyCFunction) pending_framepy_create_unwind_info,
1057 METH_VARARGS | METH_KEYWORDS,
1058 "create_unwind_info (FRAME_ID) -> gdb.UnwindInfo\n"
1059 "Construct UnwindInfo for this PendingFrame, using FRAME_ID\n"
1060 "to identify it." },
1061 { "architecture",
1062 pending_framepy_architecture, METH_NOARGS,
1063 "architecture () -> gdb.Architecture\n"
1064 "The architecture for this PendingFrame." },
1065 { "name",
1066 pending_framepy_name, METH_NOARGS,
1067 "name() -> String.\n\
1068 Return the function name of the frame, or None if it can't be determined." },
1069 { "is_valid",
1070 pending_framepy_is_valid, METH_NOARGS,
1071 "is_valid () -> Boolean.\n\
1072 Return true if this PendingFrame is valid, false if not." },
1073 { "pc",
1074 pending_framepy_pc, METH_NOARGS,
1075 "pc () -> Long.\n\
1076 Return the frame's resume address." },
1077 { "language", pending_framepy_language, METH_NOARGS,
1078 "The language of this frame." },
1079 { "find_sal", pending_framepy_find_sal, METH_NOARGS,
1080 "find_sal () -> gdb.Symtab_and_line.\n\
1081 Return the frame's symtab and line." },
1082 { "block", pending_framepy_block, METH_NOARGS,
1083 "block () -> gdb.Block.\n\
1084 Return the frame's code block." },
1085 { "function", pending_framepy_function, METH_NOARGS,
1086 "function () -> gdb.Symbol.\n\
1087 Returns the symbol for the function corresponding to this frame." },
1088 { "level", pending_framepy_level, METH_NOARGS,
1089 "The stack level of this frame." },
1090 {NULL} /* Sentinel */
1093 PyTypeObject pending_frame_object_type =
1095 PyVarObject_HEAD_INIT (NULL, 0)
1096 "gdb.PendingFrame", /* tp_name */
1097 sizeof (pending_frame_object), /* tp_basicsize */
1098 0, /* tp_itemsize */
1099 0, /* tp_dealloc */
1100 0, /* tp_print */
1101 0, /* tp_getattr */
1102 0, /* tp_setattr */
1103 0, /* tp_compare */
1104 pending_framepy_repr, /* tp_repr */
1105 0, /* tp_as_number */
1106 0, /* tp_as_sequence */
1107 0, /* tp_as_mapping */
1108 0, /* tp_hash */
1109 0, /* tp_call */
1110 pending_framepy_str, /* tp_str */
1111 0, /* tp_getattro */
1112 0, /* tp_setattro */
1113 0, /* tp_as_buffer */
1114 Py_TPFLAGS_DEFAULT, /* tp_flags */
1115 "GDB PendingFrame object", /* tp_doc */
1116 0, /* tp_traverse */
1117 0, /* tp_clear */
1118 0, /* tp_richcompare */
1119 0, /* tp_weaklistoffset */
1120 0, /* tp_iter */
1121 0, /* tp_iternext */
1122 pending_frame_object_methods, /* tp_methods */
1123 0, /* tp_members */
1124 0, /* tp_getset */
1125 0, /* tp_base */
1126 0, /* tp_dict */
1127 0, /* tp_descr_get */
1128 0, /* tp_descr_set */
1129 0, /* tp_dictoffset */
1130 0, /* tp_init */
1131 0, /* tp_alloc */
1134 static PyMethodDef unwind_info_object_methods[] =
1136 { "add_saved_register",
1137 (PyCFunction) unwind_infopy_add_saved_register,
1138 METH_VARARGS | METH_KEYWORDS,
1139 "add_saved_register (REG, VALUE) -> None\n"
1140 "Set the value of the REG in the previous frame to VALUE." },
1141 { NULL } /* Sentinel */
1144 PyTypeObject unwind_info_object_type =
1146 PyVarObject_HEAD_INIT (NULL, 0)
1147 "gdb.UnwindInfo", /* tp_name */
1148 sizeof (unwind_info_object), /* tp_basicsize */
1149 0, /* tp_itemsize */
1150 unwind_infopy_dealloc, /* tp_dealloc */
1151 0, /* tp_print */
1152 0, /* tp_getattr */
1153 0, /* tp_setattr */
1154 0, /* tp_compare */
1155 unwind_infopy_repr, /* tp_repr */
1156 0, /* tp_as_number */
1157 0, /* tp_as_sequence */
1158 0, /* tp_as_mapping */
1159 0, /* tp_hash */
1160 0, /* tp_call */
1161 unwind_infopy_str, /* tp_str */
1162 0, /* tp_getattro */
1163 0, /* tp_setattro */
1164 0, /* tp_as_buffer */
1165 Py_TPFLAGS_DEFAULT, /* tp_flags */
1166 "GDB UnwindInfo object", /* tp_doc */
1167 0, /* tp_traverse */
1168 0, /* tp_clear */
1169 0, /* tp_richcompare */
1170 0, /* tp_weaklistoffset */
1171 0, /* tp_iter */
1172 0, /* tp_iternext */
1173 unwind_info_object_methods, /* tp_methods */
1174 0, /* tp_members */
1175 0, /* tp_getset */
1176 0, /* tp_base */
1177 0, /* tp_dict */
1178 0, /* tp_descr_get */
1179 0, /* tp_descr_set */
1180 0, /* tp_dictoffset */
1181 0, /* tp_init */
1182 0, /* tp_alloc */