xref: /netbsd-src/external/gpl3/gdb.old/dist/gdb/python/py-unwind.c (revision 6881a4007f077b54e5f51159c52b9b25f57deb0d)
1 /* Python frame unwinder interface.
2 
3    Copyright (C) 2015-2023 Free Software Foundation, Inc.
4 
5    This file is part of GDB.
6 
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.
11 
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.
16 
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/>.  */
19 
20 #include "defs.h"
21 #include "arch-utils.h"
22 #include "frame-unwind.h"
23 #include "gdbsupport/gdb_obstack.h"
24 #include "gdbcmd.h"
25 #include "language.h"
26 #include "observable.h"
27 #include "python-internal.h"
28 #include "regcache.h"
29 #include "valprint.h"
30 #include "user-regs.h"
31 
32 /* Debugging of Python unwinders.  */
33 
34 static bool pyuw_debug;
35 
36 /* Implementation of "show debug py-unwind".  */
37 
38 static void
39 show_pyuw_debug (struct ui_file *file, int from_tty,
40 		 struct cmd_list_element *c, const char *value)
41 {
42   gdb_printf (file, _("Python unwinder debugging is %s.\n"), value);
43 }
44 
45 /* Print a "py-unwind" debug statement.  */
46 
47 #define pyuw_debug_printf(fmt, ...) \
48   debug_prefixed_printf_cond (pyuw_debug, "py-unwind", fmt, ##__VA_ARGS__)
49 
50 /* Print "py-unwind" enter/exit debug statements.  */
51 
52 #define PYUW_SCOPED_DEBUG_ENTER_EXIT \
53   scoped_debug_enter_exit (pyuw_debug, "py-unwind")
54 
55 struct pending_frame_object
56 {
57   PyObject_HEAD
58 
59   /* Frame we are unwinding.  */
60   frame_info_ptr frame_info;
61 
62   /* Its architecture, passed by the sniffer caller.  */
63   struct gdbarch *gdbarch;
64 };
65 
66 /* Saved registers array item.  */
67 
68 struct saved_reg
69 {
70   saved_reg (int n, gdbpy_ref<> &&v)
71     : number (n),
72       value (std::move (v))
73   {
74   }
75 
76   int number;
77   gdbpy_ref<> value;
78 };
79 
80 /* The data we keep for the PyUnwindInfo: pending_frame, saved registers
81    and frame ID.  */
82 
83 struct unwind_info_object
84 {
85   PyObject_HEAD
86 
87   /* gdb.PendingFrame for the frame we are unwinding.  */
88   PyObject *pending_frame;
89 
90   /* Its ID.  */
91   struct frame_id frame_id;
92 
93   /* Saved registers array.  */
94   std::vector<saved_reg> *saved_regs;
95 };
96 
97 /* The data we keep for a frame we can unwind: frame ID and an array of
98    (register_number, register_value) pairs.  */
99 
100 struct cached_frame_info
101 {
102   /* Frame ID.  */
103   struct frame_id frame_id;
104 
105   /* GDB Architecture.  */
106   struct gdbarch *gdbarch;
107 
108   /* Length of the `reg' array below.  */
109   int reg_count;
110 
111   cached_reg_t reg[];
112 };
113 
114 extern PyTypeObject pending_frame_object_type
115     CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("pending_frame_object");
116 
117 extern PyTypeObject unwind_info_object_type
118     CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("unwind_info_object");
119 
120 /* Convert gdb.Value instance to inferior's pointer.  Return 1 on success,
121    0 on failure.  */
122 
123 static int
124 pyuw_value_obj_to_pointer (PyObject *pyo_value, CORE_ADDR *addr)
125 {
126   int rc = 0;
127   struct value *value;
128 
129   try
130     {
131       if ((value = value_object_to_value (pyo_value)) != NULL)
132 	{
133 	  *addr = unpack_pointer (value_type (value),
134 				  value_contents (value).data ());
135 	  rc = 1;
136 	}
137     }
138   catch (const gdb_exception &except)
139     {
140       gdbpy_convert_exception (except);
141     }
142   return rc;
143 }
144 
145 /* Get attribute from an object and convert it to the inferior's
146    pointer value.  Return 1 if attribute exists and its value can be
147    converted.  Otherwise, if attribute does not exist or its value is
148    None, return 0.  In all other cases set Python error and return
149    0.  */
150 
151 static int
152 pyuw_object_attribute_to_pointer (PyObject *pyo, const char *attr_name,
153 				  CORE_ADDR *addr)
154 {
155   int rc = 0;
156 
157   if (PyObject_HasAttrString (pyo, attr_name))
158     {
159       gdbpy_ref<> pyo_value (PyObject_GetAttrString (pyo, attr_name));
160 
161       if (pyo_value != NULL && pyo_value != Py_None)
162 	{
163 	  rc = pyuw_value_obj_to_pointer (pyo_value.get (), addr);
164 	  if (!rc)
165 	    PyErr_Format (
166 		PyExc_ValueError,
167 		_("The value of the '%s' attribute is not a pointer."),
168 		attr_name);
169 	}
170     }
171   return rc;
172 }
173 
174 /* Called by the Python interpreter to obtain string representation
175    of the UnwindInfo object.  */
176 
177 static PyObject *
178 unwind_infopy_str (PyObject *self)
179 {
180   unwind_info_object *unwind_info = (unwind_info_object *) self;
181   string_file stb;
182 
183   stb.printf ("Frame ID: %s", unwind_info->frame_id.to_string ().c_str ());
184   {
185     const char *sep = "";
186     struct value_print_options opts;
187 
188     get_user_print_options (&opts);
189     stb.printf ("\nSaved registers: (");
190     for (const saved_reg &reg : *unwind_info->saved_regs)
191       {
192 	struct value *value = value_object_to_value (reg.value.get ());
193 
194 	stb.printf ("%s(%d, ", sep, reg.number);
195 	if (value != NULL)
196 	  {
197 	    try
198 	      {
199 		value_print (value, &stb, &opts);
200 		stb.puts (")");
201 	      }
202 	    catch (const gdb_exception &except)
203 	      {
204 		GDB_PY_HANDLE_EXCEPTION (except);
205 	      }
206 	  }
207 	else
208 	  stb.puts ("<BAD>)");
209 	sep = ", ";
210       }
211     stb.puts (")");
212   }
213 
214   return PyUnicode_FromString (stb.c_str ());
215 }
216 
217 /* Create UnwindInfo instance for given PendingFrame and frame ID.
218    Sets Python error and returns NULL on error.  */
219 
220 static PyObject *
221 pyuw_create_unwind_info (PyObject *pyo_pending_frame,
222 			 struct frame_id frame_id)
223 {
224   unwind_info_object *unwind_info
225       = PyObject_New (unwind_info_object, &unwind_info_object_type);
226 
227   if (((pending_frame_object *) pyo_pending_frame)->frame_info == NULL)
228     {
229       PyErr_SetString (PyExc_ValueError,
230 		       "Attempting to use stale PendingFrame");
231       return NULL;
232     }
233   unwind_info->frame_id = frame_id;
234   Py_INCREF (pyo_pending_frame);
235   unwind_info->pending_frame = pyo_pending_frame;
236   unwind_info->saved_regs = new std::vector<saved_reg>;
237   return (PyObject *) unwind_info;
238 }
239 
240 /* The implementation of
241    gdb.UnwindInfo.add_saved_register (REG, VALUE) -> None.  */
242 
243 static PyObject *
244 unwind_infopy_add_saved_register (PyObject *self, PyObject *args)
245 {
246   unwind_info_object *unwind_info = (unwind_info_object *) self;
247   pending_frame_object *pending_frame
248       = (pending_frame_object *) (unwind_info->pending_frame);
249   PyObject *pyo_reg_id;
250   PyObject *pyo_reg_value;
251   int regnum;
252 
253   if (pending_frame->frame_info == NULL)
254     {
255       PyErr_SetString (PyExc_ValueError,
256 		       "UnwindInfo instance refers to a stale PendingFrame");
257       return NULL;
258     }
259   if (!PyArg_UnpackTuple (args, "previous_frame_register", 2, 2,
260 			  &pyo_reg_id, &pyo_reg_value))
261     return NULL;
262   if (!gdbpy_parse_register_id (pending_frame->gdbarch, pyo_reg_id, &regnum))
263     return nullptr;
264 
265   /* If REGNUM identifies a user register then *maybe* we can convert this
266      to a real (i.e. non-user) register.  The maybe qualifier is because we
267      don't know what user registers each target might add, however, the
268      following logic should work for the usual style of user registers,
269      where the read function just forwards the register read on to some
270      other register with no adjusting the value.  */
271   if (regnum >= gdbarch_num_cooked_regs (pending_frame->gdbarch))
272     {
273       struct value *user_reg_value
274 	= value_of_user_reg (regnum, pending_frame->frame_info);
275       if (VALUE_LVAL (user_reg_value) == lval_register)
276 	regnum = VALUE_REGNUM (user_reg_value);
277       if (regnum >= gdbarch_num_cooked_regs (pending_frame->gdbarch))
278 	{
279 	  PyErr_SetString (PyExc_ValueError, "Bad register");
280 	  return NULL;
281 	}
282     }
283 
284   {
285     struct value *value;
286     size_t data_size;
287 
288     if (pyo_reg_value == NULL
289       || (value = value_object_to_value (pyo_reg_value)) == NULL)
290       {
291 	PyErr_SetString (PyExc_ValueError, "Bad register value");
292 	return NULL;
293       }
294     data_size = register_size (pending_frame->gdbarch, regnum);
295     if (data_size != value_type (value)->length ())
296       {
297 	PyErr_Format (
298 	    PyExc_ValueError,
299 	    "The value of the register returned by the Python "
300 	    "sniffer has unexpected size: %u instead of %u.",
301 	    (unsigned) value_type (value)->length (),
302 	    (unsigned) data_size);
303 	return NULL;
304       }
305   }
306   {
307     gdbpy_ref<> new_value = gdbpy_ref<>::new_reference (pyo_reg_value);
308     bool found = false;
309     for (saved_reg &reg : *unwind_info->saved_regs)
310       {
311 	if (regnum == reg.number)
312 	  {
313 	    found = true;
314 	    reg.value = std::move (new_value);
315 	    break;
316 	  }
317       }
318     if (!found)
319       unwind_info->saved_regs->emplace_back (regnum, std::move (new_value));
320   }
321   Py_RETURN_NONE;
322 }
323 
324 /* UnwindInfo cleanup.  */
325 
326 static void
327 unwind_infopy_dealloc (PyObject *self)
328 {
329   unwind_info_object *unwind_info = (unwind_info_object *) self;
330 
331   Py_XDECREF (unwind_info->pending_frame);
332   delete unwind_info->saved_regs;
333   Py_TYPE (self)->tp_free (self);
334 }
335 
336 /* Called by the Python interpreter to obtain string representation
337    of the PendingFrame object.  */
338 
339 static PyObject *
340 pending_framepy_str (PyObject *self)
341 {
342   frame_info_ptr frame = ((pending_frame_object *) self)->frame_info;
343   const char *sp_str = NULL;
344   const char *pc_str = NULL;
345 
346   if (frame == NULL)
347     return PyUnicode_FromString ("Stale PendingFrame instance");
348   try
349     {
350       sp_str = core_addr_to_string_nz (get_frame_sp (frame));
351       pc_str = core_addr_to_string_nz (get_frame_pc (frame));
352     }
353   catch (const gdb_exception &except)
354     {
355       GDB_PY_HANDLE_EXCEPTION (except);
356     }
357 
358   return PyUnicode_FromFormat ("SP=%s,PC=%s", sp_str, pc_str);
359 }
360 
361 /* Implementation of gdb.PendingFrame.read_register (self, reg) -> gdb.Value.
362    Returns the value of register REG as gdb.Value instance.  */
363 
364 static PyObject *
365 pending_framepy_read_register (PyObject *self, PyObject *args)
366 {
367   pending_frame_object *pending_frame = (pending_frame_object *) self;
368   struct value *val = NULL;
369   int regnum;
370   PyObject *pyo_reg_id;
371 
372   if (pending_frame->frame_info == NULL)
373     {
374       PyErr_SetString (PyExc_ValueError,
375 		       "Attempting to read register from stale PendingFrame");
376       return NULL;
377     }
378   if (!PyArg_UnpackTuple (args, "read_register", 1, 1, &pyo_reg_id))
379     return NULL;
380   if (!gdbpy_parse_register_id (pending_frame->gdbarch, pyo_reg_id, &regnum))
381     return nullptr;
382 
383   try
384     {
385       /* Fetch the value associated with a register, whether it's
386 	 a real register or a so called "user" register, like "pc",
387 	 which maps to a real register.  In the past,
388 	 get_frame_register_value() was used here, which did not
389 	 handle the user register case.  */
390       val = value_of_register (regnum, pending_frame->frame_info);
391       if (val == NULL)
392 	PyErr_Format (PyExc_ValueError,
393 		      "Cannot read register %d from frame.",
394 		      regnum);
395     }
396   catch (const gdb_exception &except)
397     {
398       GDB_PY_HANDLE_EXCEPTION (except);
399     }
400 
401   return val == NULL ? NULL : value_to_value_object (val);
402 }
403 
404 /* Implementation of
405    PendingFrame.create_unwind_info (self, frameId) -> UnwindInfo.  */
406 
407 static PyObject *
408 pending_framepy_create_unwind_info (PyObject *self, PyObject *args)
409 {
410   PyObject *pyo_frame_id;
411   CORE_ADDR sp;
412   CORE_ADDR pc;
413   CORE_ADDR special;
414 
415   if (!PyArg_ParseTuple (args, "O:create_unwind_info", &pyo_frame_id))
416       return NULL;
417   if (!pyuw_object_attribute_to_pointer (pyo_frame_id, "sp", &sp))
418     {
419       PyErr_SetString (PyExc_ValueError,
420 		       _("frame_id should have 'sp' attribute."));
421       return NULL;
422     }
423 
424   /* The logic of building frame_id depending on the attributes of
425      the frame_id object:
426      Has     Has    Has           Function to call
427      'sp'?   'pc'?  'special'?
428      ------|------|--------------|-------------------------
429      Y       N      *             frame_id_build_wild (sp)
430      Y       Y      N             frame_id_build (sp, pc)
431      Y       Y      Y             frame_id_build_special (sp, pc, special)
432   */
433   if (!pyuw_object_attribute_to_pointer (pyo_frame_id, "pc", &pc))
434     return pyuw_create_unwind_info (self, frame_id_build_wild (sp));
435   if (!pyuw_object_attribute_to_pointer (pyo_frame_id, "special", &special))
436     return pyuw_create_unwind_info (self, frame_id_build (sp, pc));
437   else
438     return pyuw_create_unwind_info (self,
439 				    frame_id_build_special (sp, pc, special));
440 }
441 
442 /* Implementation of PendingFrame.architecture (self) -> gdb.Architecture.  */
443 
444 static PyObject *
445 pending_framepy_architecture (PyObject *self, PyObject *args)
446 {
447   pending_frame_object *pending_frame = (pending_frame_object *) self;
448 
449   if (pending_frame->frame_info == NULL)
450     {
451       PyErr_SetString (PyExc_ValueError,
452 		       "Attempting to read register from stale PendingFrame");
453       return NULL;
454     }
455   return gdbarch_to_arch_object (pending_frame->gdbarch);
456 }
457 
458 /* Implementation of PendingFrame.level (self) -> Integer.  */
459 
460 static PyObject *
461 pending_framepy_level (PyObject *self, PyObject *args)
462 {
463   pending_frame_object *pending_frame = (pending_frame_object *) self;
464 
465   if (pending_frame->frame_info == NULL)
466     {
467       PyErr_SetString (PyExc_ValueError,
468 		       "Attempting to read stack level from stale PendingFrame");
469       return NULL;
470     }
471   int level = frame_relative_level (pending_frame->frame_info);
472   return gdb_py_object_from_longest (level).release ();
473 }
474 
475 /* frame_unwind.this_id method.  */
476 
477 static void
478 pyuw_this_id (frame_info_ptr this_frame, void **cache_ptr,
479 	      struct frame_id *this_id)
480 {
481   *this_id = ((cached_frame_info *) *cache_ptr)->frame_id;
482   pyuw_debug_printf ("frame_id: %s", this_id->to_string ().c_str ());
483 }
484 
485 /* frame_unwind.prev_register.  */
486 
487 static struct value *
488 pyuw_prev_register (frame_info_ptr this_frame, void **cache_ptr,
489 		    int regnum)
490 {
491   PYUW_SCOPED_DEBUG_ENTER_EXIT;
492 
493   cached_frame_info *cached_frame = (cached_frame_info *) *cache_ptr;
494   cached_reg_t *reg_info = cached_frame->reg;
495   cached_reg_t *reg_info_end = reg_info + cached_frame->reg_count;
496 
497   pyuw_debug_printf ("frame=%d, reg=%d",
498 		     frame_relative_level (this_frame), regnum);
499   for (; reg_info < reg_info_end; ++reg_info)
500     {
501       if (regnum == reg_info->num)
502 	return frame_unwind_got_bytes (this_frame, regnum, reg_info->data);
503     }
504 
505   return frame_unwind_got_optimized (this_frame, regnum);
506 }
507 
508 /* Frame sniffer dispatch.  */
509 
510 static int
511 pyuw_sniffer (const struct frame_unwind *self, frame_info_ptr this_frame,
512 	      void **cache_ptr)
513 {
514   PYUW_SCOPED_DEBUG_ENTER_EXIT;
515 
516   struct gdbarch *gdbarch = (struct gdbarch *) (self->unwind_data);
517   cached_frame_info *cached_frame;
518 
519   gdbpy_enter enter_py (gdbarch);
520 
521   pyuw_debug_printf ("frame=%d, sp=%s, pc=%s",
522 		     frame_relative_level (this_frame),
523 		     paddress (gdbarch, get_frame_sp (this_frame)),
524 		     paddress (gdbarch, get_frame_pc (this_frame)));
525 
526   /* Create PendingFrame instance to pass to sniffers.  */
527   pending_frame_object *pfo = PyObject_New (pending_frame_object,
528 					    &pending_frame_object_type);
529   gdbpy_ref<> pyo_pending_frame ((PyObject *) pfo);
530   if (pyo_pending_frame == NULL)
531     {
532       gdbpy_print_stack ();
533       return 0;
534     }
535   pfo->gdbarch = gdbarch;
536   scoped_restore invalidate_frame = make_scoped_restore (&pfo->frame_info,
537 							 this_frame);
538 
539   /* Run unwinders.  */
540   if (gdb_python_module == NULL
541       || ! PyObject_HasAttrString (gdb_python_module, "_execute_unwinders"))
542     {
543       PyErr_SetString (PyExc_NameError,
544 		       "Installation error: gdb._execute_unwinders function "
545 		       "is missing");
546       gdbpy_print_stack ();
547       return 0;
548     }
549   gdbpy_ref<> pyo_execute (PyObject_GetAttrString (gdb_python_module,
550 						   "_execute_unwinders"));
551   if (pyo_execute == nullptr)
552     {
553       gdbpy_print_stack ();
554       return 0;
555     }
556 
557   /* A (gdb.UnwindInfo, str) tuple, or None.  */
558   gdbpy_ref<> pyo_execute_ret
559     (PyObject_CallFunctionObjArgs (pyo_execute.get (),
560 				   pyo_pending_frame.get (), NULL));
561   if (pyo_execute_ret == nullptr)
562     {
563       /* If the unwinder is cancelled due to a Ctrl-C, then propagate
564 	 the Ctrl-C as a GDB exception instead of swallowing it.  */
565       gdbpy_print_stack_or_quit ();
566       return 0;
567     }
568   if (pyo_execute_ret == Py_None)
569     return 0;
570 
571   /* Verify the return value of _execute_unwinders is a tuple of size 2.  */
572   gdb_assert (PyTuple_Check (pyo_execute_ret.get ()));
573   gdb_assert (PyTuple_GET_SIZE (pyo_execute_ret.get ()) == 2);
574 
575   if (pyuw_debug)
576     {
577       PyObject *pyo_unwinder_name = PyTuple_GET_ITEM (pyo_execute_ret.get (), 1);
578       gdb::unique_xmalloc_ptr<char> name
579 	= python_string_to_host_string (pyo_unwinder_name);
580 
581       /* This could happen if the user passed something else than a string
582 	 as the unwinder's name.  */
583       if (name == nullptr)
584 	{
585 	  gdbpy_print_stack ();
586 	  name = make_unique_xstrdup ("<failed to get unwinder name>");
587 	}
588 
589       pyuw_debug_printf ("frame claimed by unwinder %s", name.get ());
590     }
591 
592   /* Received UnwindInfo, cache data.  */
593   PyObject *pyo_unwind_info = PyTuple_GET_ITEM (pyo_execute_ret.get (), 0);
594   if (PyObject_IsInstance (pyo_unwind_info,
595 			   (PyObject *) &unwind_info_object_type) <= 0)
596     error (_("A Unwinder should return gdb.UnwindInfo instance."));
597 
598   {
599     unwind_info_object *unwind_info =
600       (unwind_info_object *) pyo_unwind_info;
601     int reg_count = unwind_info->saved_regs->size ();
602 
603     cached_frame
604       = ((cached_frame_info *)
605 	 xmalloc (sizeof (*cached_frame)
606 		  + reg_count * sizeof (cached_frame->reg[0])));
607     cached_frame->gdbarch = gdbarch;
608     cached_frame->frame_id = unwind_info->frame_id;
609     cached_frame->reg_count = reg_count;
610 
611     /* Populate registers array.  */
612     for (int i = 0; i < unwind_info->saved_regs->size (); ++i)
613       {
614 	saved_reg *reg = &(*unwind_info->saved_regs)[i];
615 
616 	struct value *value = value_object_to_value (reg->value.get ());
617 	size_t data_size = register_size (gdbarch, reg->number);
618 
619 	cached_frame->reg[i].num = reg->number;
620 
621 	/* `value' validation was done before, just assert.  */
622 	gdb_assert (value != NULL);
623 	gdb_assert (data_size == value_type (value)->length ());
624 
625 	cached_frame->reg[i].data = (gdb_byte *) xmalloc (data_size);
626 	memcpy (cached_frame->reg[i].data,
627 		value_contents (value).data (), data_size);
628       }
629   }
630 
631   *cache_ptr = cached_frame;
632   return 1;
633 }
634 
635 /* Frame cache release shim.  */
636 
637 static void
638 pyuw_dealloc_cache (frame_info *this_frame, void *cache)
639 {
640   PYUW_SCOPED_DEBUG_ENTER_EXIT;
641   cached_frame_info *cached_frame = (cached_frame_info *) cache;
642 
643   for (int i = 0; i < cached_frame->reg_count; i++)
644     xfree (cached_frame->reg[i].data);
645 
646   xfree (cache);
647 }
648 
649 struct pyuw_gdbarch_data_type
650 {
651   /* Has the unwinder shim been prepended? */
652   int unwinder_registered = 0;
653 };
654 
655 static const registry<gdbarch>::key<pyuw_gdbarch_data_type> pyuw_gdbarch_data;
656 
657 /* New inferior architecture callback: register the Python unwinders
658    intermediary.  */
659 
660 static void
661 pyuw_on_new_gdbarch (struct gdbarch *newarch)
662 {
663   struct pyuw_gdbarch_data_type *data = pyuw_gdbarch_data.get (newarch);
664   if (data == nullptr)
665     data= pyuw_gdbarch_data.emplace (newarch);
666 
667   if (!data->unwinder_registered)
668     {
669       struct frame_unwind *unwinder
670 	  = GDBARCH_OBSTACK_ZALLOC (newarch, struct frame_unwind);
671 
672       unwinder->name = "python";
673       unwinder->type = NORMAL_FRAME;
674       unwinder->stop_reason = default_frame_unwind_stop_reason;
675       unwinder->this_id = pyuw_this_id;
676       unwinder->prev_register = pyuw_prev_register;
677       unwinder->unwind_data = (const struct frame_data *) newarch;
678       unwinder->sniffer = pyuw_sniffer;
679       unwinder->dealloc_cache = pyuw_dealloc_cache;
680       frame_unwind_prepend_unwinder (newarch, unwinder);
681       data->unwinder_registered = 1;
682     }
683 }
684 
685 void _initialize_py_unwind ();
686 void
687 _initialize_py_unwind ()
688 {
689   add_setshow_boolean_cmd
690       ("py-unwind", class_maintenance, &pyuw_debug,
691 	_("Set Python unwinder debugging."),
692 	_("Show Python unwinder debugging."),
693 	_("When on, Python unwinder debugging is enabled."),
694 	NULL,
695 	show_pyuw_debug,
696 	&setdebuglist, &showdebuglist);
697 }
698 
699 /* Initialize unwind machinery.  */
700 
701 int
702 gdbpy_initialize_unwind (void)
703 {
704   gdb::observers::architecture_changed.attach (pyuw_on_new_gdbarch,
705 					       "py-unwind");
706 
707   if (PyType_Ready (&pending_frame_object_type) < 0)
708     return -1;
709   int rc = gdb_pymodule_addobject (gdb_module, "PendingFrame",
710 				   (PyObject *) &pending_frame_object_type);
711   if (rc != 0)
712     return rc;
713 
714   if (PyType_Ready (&unwind_info_object_type) < 0)
715     return -1;
716   return gdb_pymodule_addobject (gdb_module, "UnwindInfo",
717       (PyObject *) &unwind_info_object_type);
718 }
719 
720 static PyMethodDef pending_frame_object_methods[] =
721 {
722   { "read_register", pending_framepy_read_register, METH_VARARGS,
723     "read_register (REG) -> gdb.Value\n"
724     "Return the value of the REG in the frame." },
725   { "create_unwind_info",
726     pending_framepy_create_unwind_info, METH_VARARGS,
727     "create_unwind_info (FRAME_ID) -> gdb.UnwindInfo\n"
728     "Construct UnwindInfo for this PendingFrame, using FRAME_ID\n"
729     "to identify it." },
730   { "architecture",
731     pending_framepy_architecture, METH_NOARGS,
732     "architecture () -> gdb.Architecture\n"
733     "The architecture for this PendingFrame." },
734   { "level", pending_framepy_level, METH_NOARGS,
735     "The stack level of this frame." },
736   {NULL}  /* Sentinel */
737 };
738 
739 PyTypeObject pending_frame_object_type =
740 {
741   PyVarObject_HEAD_INIT (NULL, 0)
742   "gdb.PendingFrame",             /* tp_name */
743   sizeof (pending_frame_object),  /* tp_basicsize */
744   0,                              /* tp_itemsize */
745   0,                              /* tp_dealloc */
746   0,                              /* tp_print */
747   0,                              /* tp_getattr */
748   0,                              /* tp_setattr */
749   0,                              /* tp_compare */
750   0,                              /* tp_repr */
751   0,                              /* tp_as_number */
752   0,                              /* tp_as_sequence */
753   0,                              /* tp_as_mapping */
754   0,                              /* tp_hash  */
755   0,                              /* tp_call */
756   pending_framepy_str,            /* tp_str */
757   0,                              /* tp_getattro */
758   0,                              /* tp_setattro */
759   0,                              /* tp_as_buffer */
760   Py_TPFLAGS_DEFAULT,             /* tp_flags */
761   "GDB PendingFrame object",      /* tp_doc */
762   0,                              /* tp_traverse */
763   0,                              /* tp_clear */
764   0,                              /* tp_richcompare */
765   0,                              /* tp_weaklistoffset */
766   0,                              /* tp_iter */
767   0,                              /* tp_iternext */
768   pending_frame_object_methods,   /* tp_methods */
769   0,                              /* tp_members */
770   0,                              /* tp_getset */
771   0,                              /* tp_base */
772   0,                              /* tp_dict */
773   0,                              /* tp_descr_get */
774   0,                              /* tp_descr_set */
775   0,                              /* tp_dictoffset */
776   0,                              /* tp_init */
777   0,                              /* tp_alloc */
778 };
779 
780 static PyMethodDef unwind_info_object_methods[] =
781 {
782   { "add_saved_register",
783     unwind_infopy_add_saved_register, METH_VARARGS,
784     "add_saved_register (REG, VALUE) -> None\n"
785     "Set the value of the REG in the previous frame to VALUE." },
786   { NULL }  /* Sentinel */
787 };
788 
789 PyTypeObject unwind_info_object_type =
790 {
791   PyVarObject_HEAD_INIT (NULL, 0)
792   "gdb.UnwindInfo",               /* tp_name */
793   sizeof (unwind_info_object),    /* tp_basicsize */
794   0,                              /* tp_itemsize */
795   unwind_infopy_dealloc,          /* tp_dealloc */
796   0,                              /* tp_print */
797   0,                              /* tp_getattr */
798   0,                              /* tp_setattr */
799   0,                              /* tp_compare */
800   0,                              /* tp_repr */
801   0,                              /* tp_as_number */
802   0,                              /* tp_as_sequence */
803   0,                              /* tp_as_mapping */
804   0,                              /* tp_hash  */
805   0,                              /* tp_call */
806   unwind_infopy_str,              /* tp_str */
807   0,                              /* tp_getattro */
808   0,                              /* tp_setattro */
809   0,                              /* tp_as_buffer */
810   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,  /* tp_flags */
811   "GDB UnwindInfo object",        /* tp_doc */
812   0,                              /* tp_traverse */
813   0,                              /* tp_clear */
814   0,                              /* tp_richcompare */
815   0,                              /* tp_weaklistoffset */
816   0,                              /* tp_iter */
817   0,                              /* tp_iternext */
818   unwind_info_object_methods,     /* tp_methods */
819   0,                              /* tp_members */
820   0,                              /* tp_getset */
821   0,                              /* tp_base */
822   0,                              /* tp_dict */
823   0,                              /* tp_descr_get */
824   0,                              /* tp_descr_set */
825   0,                              /* tp_dictoffset */
826   0,                              /* tp_init */
827   0,                              /* tp_alloc */
828 };
829