]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/python/py-unwind.c
Update copyright year range in header of all files managed by GDB
[thirdparty/binutils-gdb.git] / gdb / python / py-unwind.c
1 /* Python frame unwinder interface.
2
3 Copyright (C) 2015-2024 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 #include "stack.h"
32 #include "charset.h"
33 #include "block.h"
34
35
36 /* Debugging of Python unwinders. */
37
38 static bool pyuw_debug;
39
40 /* Implementation of "show debug py-unwind". */
41
42 static void
43 show_pyuw_debug (struct ui_file *file, int from_tty,
44 struct cmd_list_element *c, const char *value)
45 {
46 gdb_printf (file, _("Python unwinder debugging is %s.\n"), value);
47 }
48
49 /* Print a "py-unwind" debug statement. */
50
51 #define pyuw_debug_printf(fmt, ...) \
52 debug_prefixed_printf_cond (pyuw_debug, "py-unwind", fmt, ##__VA_ARGS__)
53
54 /* Print "py-unwind" enter/exit debug statements. */
55
56 #define PYUW_SCOPED_DEBUG_ENTER_EXIT \
57 scoped_debug_enter_exit (pyuw_debug, "py-unwind")
58
59 /* Require a valid pending frame. */
60 #define PENDING_FRAMEPY_REQUIRE_VALID(pending_frame) \
61 do { \
62 if ((pending_frame)->frame_info == nullptr) \
63 { \
64 PyErr_SetString (PyExc_ValueError, \
65 _("gdb.PendingFrame is invalid.")); \
66 return nullptr; \
67 } \
68 } while (0)
69
70 struct pending_frame_object
71 {
72 PyObject_HEAD
73
74 /* Frame we are unwinding. */
75 frame_info_ptr frame_info;
76
77 /* Its architecture, passed by the sniffer caller. */
78 struct gdbarch *gdbarch;
79 };
80
81 /* Saved registers array item. */
82
83 struct saved_reg
84 {
85 saved_reg (int n, gdbpy_ref<> &&v)
86 : number (n),
87 value (std::move (v))
88 {
89 }
90
91 int number;
92 gdbpy_ref<> value;
93 };
94
95 /* The data we keep for the PyUnwindInfo: pending_frame, saved registers
96 and frame ID. */
97
98 struct unwind_info_object
99 {
100 PyObject_HEAD
101
102 /* gdb.PendingFrame for the frame we are unwinding. */
103 PyObject *pending_frame;
104
105 /* Its ID. */
106 struct frame_id frame_id;
107
108 /* Saved registers array. */
109 std::vector<saved_reg> *saved_regs;
110 };
111
112 /* The data we keep for a frame we can unwind: frame ID and an array of
113 (register_number, register_value) pairs. */
114
115 struct cached_frame_info
116 {
117 /* Frame ID. */
118 struct frame_id frame_id;
119
120 /* GDB Architecture. */
121 struct gdbarch *gdbarch;
122
123 /* Length of the `reg' array below. */
124 int reg_count;
125
126 /* Flexible array member. Note: use a zero-sized array rather than
127 an actual C99-style flexible array member (unsized array),
128 because the latter would cause an error with Clang:
129
130 error: flexible array member 'reg' of type 'cached_reg_t[]' with non-trivial destruction
131
132 Note we manually call the destructor of each array element in
133 pyuw_dealloc_cache. */
134 cached_reg_t reg[0];
135 };
136
137 extern PyTypeObject pending_frame_object_type
138 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("pending_frame_object");
139
140 extern PyTypeObject unwind_info_object_type
141 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("unwind_info_object");
142
143 /* An enum returned by pyuw_object_attribute_to_pointer, a function which
144 is used to extract an attribute from a Python object. */
145
146 enum class pyuw_get_attr_code
147 {
148 /* The attribute was present, and its value was successfully extracted. */
149 ATTR_OK,
150
151 /* The attribute was not present, or was present and its value was None.
152 No Python error has been set. */
153 ATTR_MISSING,
154
155 /* The attribute was present, but there was some error while trying to
156 get the value from the attribute. A Python error will be set when
157 this is returned. */
158 ATTR_ERROR,
159 };
160
161 /* Get the attribute named ATTR_NAME from the object PYO and convert it to
162 an inferior pointer value, placing the pointer in *ADDR.
163
164 Return pyuw_get_attr_code::ATTR_OK if the attribute was present and its
165 value was successfully written into *ADDR. For any other return value
166 the contents of *ADDR are undefined.
167
168 Return pyuw_get_attr_code::ATTR_MISSING if the attribute was not
169 present, or it was present but its value was None. The contents of
170 *ADDR are undefined in this case. No Python error will be set in this
171 case.
172
173 Return pyuw_get_attr_code::ATTR_ERROR if the attribute was present, but
174 there was some error while extracting the attribute's value. A Python
175 error will be set in this case. The contents of *ADDR are undefined. */
176
177 static pyuw_get_attr_code
178 pyuw_object_attribute_to_pointer (PyObject *pyo, const char *attr_name,
179 CORE_ADDR *addr)
180 {
181 if (!PyObject_HasAttrString (pyo, attr_name))
182 return pyuw_get_attr_code::ATTR_MISSING;
183
184 gdbpy_ref<> pyo_value (PyObject_GetAttrString (pyo, attr_name));
185 if (pyo_value == nullptr)
186 {
187 gdb_assert (PyErr_Occurred ());
188 return pyuw_get_attr_code::ATTR_ERROR;
189 }
190 if (pyo_value == Py_None)
191 return pyuw_get_attr_code::ATTR_MISSING;
192
193 if (get_addr_from_python (pyo_value.get (), addr) < 0)
194 {
195 gdb_assert (PyErr_Occurred ());
196 return pyuw_get_attr_code::ATTR_ERROR;
197 }
198
199 return pyuw_get_attr_code::ATTR_OK;
200 }
201
202 /* Called by the Python interpreter to obtain string representation
203 of the UnwindInfo object. */
204
205 static PyObject *
206 unwind_infopy_str (PyObject *self)
207 {
208 unwind_info_object *unwind_info = (unwind_info_object *) self;
209 string_file stb;
210
211 stb.printf ("Frame ID: %s", unwind_info->frame_id.to_string ().c_str ());
212 {
213 const char *sep = "";
214 struct value_print_options opts;
215
216 get_user_print_options (&opts);
217 stb.printf ("\nSaved registers: (");
218 for (const saved_reg &reg : *unwind_info->saved_regs)
219 {
220 struct value *value = value_object_to_value (reg.value.get ());
221
222 stb.printf ("%s(%d, ", sep, reg.number);
223 if (value != NULL)
224 {
225 try
226 {
227 value_print (value, &stb, &opts);
228 stb.puts (")");
229 }
230 catch (const gdb_exception &except)
231 {
232 GDB_PY_HANDLE_EXCEPTION (except);
233 }
234 }
235 else
236 stb.puts ("<BAD>)");
237 sep = ", ";
238 }
239 stb.puts (")");
240 }
241
242 return PyUnicode_FromString (stb.c_str ());
243 }
244
245 /* Implement UnwindInfo.__repr__(). */
246
247 static PyObject *
248 unwind_infopy_repr (PyObject *self)
249 {
250 unwind_info_object *unwind_info = (unwind_info_object *) self;
251 pending_frame_object *pending_frame
252 = (pending_frame_object *) (unwind_info->pending_frame);
253 frame_info_ptr frame = pending_frame->frame_info;
254
255 if (frame == nullptr)
256 return PyUnicode_FromFormat ("<%s for an invalid frame>",
257 Py_TYPE (self)->tp_name);
258
259 std::string saved_reg_names;
260 struct gdbarch *gdbarch = pending_frame->gdbarch;
261
262 for (const saved_reg &reg : *unwind_info->saved_regs)
263 {
264 const char *name = gdbarch_register_name (gdbarch, reg.number);
265 if (saved_reg_names.empty ())
266 saved_reg_names = name;
267 else
268 saved_reg_names = (saved_reg_names + ", ") + name;
269 }
270
271 return PyUnicode_FromFormat ("<%s frame #%d, saved_regs=(%s)>",
272 Py_TYPE (self)->tp_name,
273 frame_relative_level (frame),
274 saved_reg_names.c_str ());
275 }
276
277 /* Create UnwindInfo instance for given PendingFrame and frame ID.
278 Sets Python error and returns NULL on error.
279
280 The PYO_PENDING_FRAME object must be valid. */
281
282 static PyObject *
283 pyuw_create_unwind_info (PyObject *pyo_pending_frame,
284 struct frame_id frame_id)
285 {
286 gdb_assert (((pending_frame_object *) pyo_pending_frame)->frame_info
287 != nullptr);
288
289 unwind_info_object *unwind_info
290 = PyObject_New (unwind_info_object, &unwind_info_object_type);
291
292 unwind_info->frame_id = frame_id;
293 Py_INCREF (pyo_pending_frame);
294 unwind_info->pending_frame = pyo_pending_frame;
295 unwind_info->saved_regs = new std::vector<saved_reg>;
296 return (PyObject *) unwind_info;
297 }
298
299 /* The implementation of
300 gdb.UnwindInfo.add_saved_register (REG, VALUE) -> None. */
301
302 static PyObject *
303 unwind_infopy_add_saved_register (PyObject *self, PyObject *args, PyObject *kw)
304 {
305 unwind_info_object *unwind_info = (unwind_info_object *) self;
306 pending_frame_object *pending_frame
307 = (pending_frame_object *) (unwind_info->pending_frame);
308 PyObject *pyo_reg_id;
309 PyObject *pyo_reg_value;
310 int regnum;
311
312 if (pending_frame->frame_info == NULL)
313 {
314 PyErr_SetString (PyExc_ValueError,
315 "UnwindInfo instance refers to a stale PendingFrame");
316 return nullptr;
317 }
318
319 static const char *keywords[] = { "register", "value", nullptr };
320 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "OO!", keywords,
321 &pyo_reg_id, &value_object_type,
322 &pyo_reg_value))
323 return nullptr;
324
325 if (!gdbpy_parse_register_id (pending_frame->gdbarch, pyo_reg_id, &regnum))
326 return nullptr;
327
328 /* If REGNUM identifies a user register then *maybe* we can convert this
329 to a real (i.e. non-user) register. The maybe qualifier is because we
330 don't know what user registers each target might add, however, the
331 following logic should work for the usual style of user registers,
332 where the read function just forwards the register read on to some
333 other register with no adjusting the value. */
334 if (regnum >= gdbarch_num_cooked_regs (pending_frame->gdbarch))
335 {
336 struct value *user_reg_value
337 = value_of_user_reg (regnum, pending_frame->frame_info);
338 if (user_reg_value->lval () == lval_register)
339 regnum = user_reg_value->regnum ();
340 if (regnum >= gdbarch_num_cooked_regs (pending_frame->gdbarch))
341 {
342 PyErr_SetString (PyExc_ValueError, "Bad register");
343 return NULL;
344 }
345 }
346
347 /* The argument parsing above guarantees that PYO_REG_VALUE will be a
348 gdb.Value object, as a result the value_object_to_value call should
349 succeed. */
350 gdb_assert (pyo_reg_value != nullptr);
351 struct value *value = value_object_to_value (pyo_reg_value);
352 gdb_assert (value != nullptr);
353
354 ULONGEST reg_size = register_size (pending_frame->gdbarch, regnum);
355 if (reg_size != value->type ()->length ())
356 {
357 PyErr_Format (PyExc_ValueError,
358 "The value of the register returned by the Python "
359 "sniffer has unexpected size: %s instead of %s.",
360 pulongest (value->type ()->length ()),
361 pulongest (reg_size));
362 return nullptr;
363 }
364
365 gdbpy_ref<> new_value = gdbpy_ref<>::new_reference (pyo_reg_value);
366 bool found = false;
367 for (saved_reg &reg : *unwind_info->saved_regs)
368 {
369 if (regnum == reg.number)
370 {
371 found = true;
372 reg.value = std::move (new_value);
373 break;
374 }
375 }
376 if (!found)
377 unwind_info->saved_regs->emplace_back (regnum, std::move (new_value));
378
379 Py_RETURN_NONE;
380 }
381
382 /* UnwindInfo cleanup. */
383
384 static void
385 unwind_infopy_dealloc (PyObject *self)
386 {
387 unwind_info_object *unwind_info = (unwind_info_object *) self;
388
389 Py_XDECREF (unwind_info->pending_frame);
390 delete unwind_info->saved_regs;
391 Py_TYPE (self)->tp_free (self);
392 }
393
394 /* Called by the Python interpreter to obtain string representation
395 of the PendingFrame object. */
396
397 static PyObject *
398 pending_framepy_str (PyObject *self)
399 {
400 frame_info_ptr frame = ((pending_frame_object *) self)->frame_info;
401 const char *sp_str = NULL;
402 const char *pc_str = NULL;
403
404 if (frame == NULL)
405 return PyUnicode_FromString ("Stale PendingFrame instance");
406 try
407 {
408 sp_str = core_addr_to_string_nz (get_frame_sp (frame));
409 pc_str = core_addr_to_string_nz (get_frame_pc (frame));
410 }
411 catch (const gdb_exception &except)
412 {
413 GDB_PY_HANDLE_EXCEPTION (except);
414 }
415
416 return PyUnicode_FromFormat ("SP=%s,PC=%s", sp_str, pc_str);
417 }
418
419 /* Implement PendingFrame.__repr__(). */
420
421 static PyObject *
422 pending_framepy_repr (PyObject *self)
423 {
424 pending_frame_object *pending_frame = (pending_frame_object *) self;
425 frame_info_ptr frame = pending_frame->frame_info;
426
427 if (frame == nullptr)
428 return gdb_py_invalid_object_repr (self);
429
430 const char *sp_str = nullptr;
431 const char *pc_str = nullptr;
432
433 try
434 {
435 sp_str = core_addr_to_string_nz (get_frame_sp (frame));
436 pc_str = core_addr_to_string_nz (get_frame_pc (frame));
437 }
438 catch (const gdb_exception &except)
439 {
440 GDB_PY_HANDLE_EXCEPTION (except);
441 }
442
443 return PyUnicode_FromFormat ("<%s level=%d, sp=%s, pc=%s>",
444 Py_TYPE (self)->tp_name,
445 frame_relative_level (frame),
446 sp_str,
447 pc_str);
448 }
449
450 /* Implementation of gdb.PendingFrame.read_register (self, reg) -> gdb.Value.
451 Returns the value of register REG as gdb.Value instance. */
452
453 static PyObject *
454 pending_framepy_read_register (PyObject *self, PyObject *args, PyObject *kw)
455 {
456 pending_frame_object *pending_frame = (pending_frame_object *) self;
457 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
458
459 PyObject *pyo_reg_id;
460 static const char *keywords[] = { "register", nullptr };
461 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "O", keywords, &pyo_reg_id))
462 return nullptr;
463
464 int regnum;
465 if (!gdbpy_parse_register_id (pending_frame->gdbarch, pyo_reg_id, &regnum))
466 return nullptr;
467
468 PyObject *result = nullptr;
469 try
470 {
471 scoped_value_mark free_values;
472
473 /* Fetch the value associated with a register, whether it's
474 a real register or a so called "user" register, like "pc",
475 which maps to a real register. In the past,
476 get_frame_register_value() was used here, which did not
477 handle the user register case. */
478 value *val = value_of_register
479 (regnum, get_next_frame_sentinel_okay (pending_frame->frame_info));
480 if (val == NULL)
481 PyErr_Format (PyExc_ValueError,
482 "Cannot read register %d from frame.",
483 regnum);
484 else
485 result = value_to_value_object (val);
486 }
487 catch (const gdb_exception &except)
488 {
489 GDB_PY_HANDLE_EXCEPTION (except);
490 }
491
492 return result;
493 }
494
495 /* Implement PendingFrame.is_valid(). Return True if this pending frame
496 object is still valid. */
497
498 static PyObject *
499 pending_framepy_is_valid (PyObject *self, PyObject *args)
500 {
501 pending_frame_object *pending_frame = (pending_frame_object *) self;
502
503 if (pending_frame->frame_info == nullptr)
504 Py_RETURN_FALSE;
505
506 Py_RETURN_TRUE;
507 }
508
509 /* Implement PendingFrame.name(). Return a string that is the name of the
510 function for this frame, or None if the name can't be found. */
511
512 static PyObject *
513 pending_framepy_name (PyObject *self, PyObject *args)
514 {
515 pending_frame_object *pending_frame = (pending_frame_object *) self;
516
517 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
518
519 gdb::unique_xmalloc_ptr<char> name;
520
521 try
522 {
523 enum language lang;
524 frame_info_ptr frame = pending_frame->frame_info;
525
526 name = find_frame_funname (frame, &lang, nullptr);
527 }
528 catch (const gdb_exception &except)
529 {
530 GDB_PY_HANDLE_EXCEPTION (except);
531 }
532
533 if (name != nullptr)
534 return PyUnicode_Decode (name.get (), strlen (name.get ()),
535 host_charset (), nullptr);
536
537 Py_RETURN_NONE;
538 }
539
540 /* Implement gdb.PendingFrame.pc(). Returns an integer containing the
541 frame's current $pc value. */
542
543 static PyObject *
544 pending_framepy_pc (PyObject *self, PyObject *args)
545 {
546 pending_frame_object *pending_frame = (pending_frame_object *) self;
547
548 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
549
550 CORE_ADDR pc = 0;
551
552 try
553 {
554 pc = get_frame_pc (pending_frame->frame_info);
555 }
556 catch (const gdb_exception &except)
557 {
558 GDB_PY_HANDLE_EXCEPTION (except);
559 }
560
561 return gdb_py_object_from_ulongest (pc).release ();
562 }
563
564 /* Implement gdb.PendingFrame.language(). Return the name of the language
565 for this frame. */
566
567 static PyObject *
568 pending_framepy_language (PyObject *self, PyObject *args)
569 {
570 pending_frame_object *pending_frame = (pending_frame_object *) self;
571
572 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
573
574 try
575 {
576 frame_info_ptr fi = pending_frame->frame_info;
577
578 enum language lang = get_frame_language (fi);
579 const language_defn *lang_def = language_def (lang);
580
581 return host_string_to_python_string (lang_def->name ()).release ();
582 }
583 catch (const gdb_exception &except)
584 {
585 GDB_PY_HANDLE_EXCEPTION (except);
586 }
587
588 Py_RETURN_NONE;
589 }
590
591 /* Implement PendingFrame.find_sal(). Return the PendingFrame's symtab and
592 line. */
593
594 static PyObject *
595 pending_framepy_find_sal (PyObject *self, PyObject *args)
596 {
597 pending_frame_object *pending_frame = (pending_frame_object *) self;
598
599 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
600
601 PyObject *sal_obj = nullptr;
602
603 try
604 {
605 frame_info_ptr frame = pending_frame->frame_info;
606
607 symtab_and_line sal = find_frame_sal (frame);
608 sal_obj = symtab_and_line_to_sal_object (sal);
609 }
610 catch (const gdb_exception &except)
611 {
612 GDB_PY_HANDLE_EXCEPTION (except);
613 }
614
615 return sal_obj;
616 }
617
618 /* Implement PendingFrame.block(). Return a gdb.Block for the pending
619 frame's code, or raise RuntimeError if the block can't be found. */
620
621 static PyObject *
622 pending_framepy_block (PyObject *self, PyObject *args)
623 {
624 pending_frame_object *pending_frame = (pending_frame_object *) self;
625
626 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
627
628 frame_info_ptr frame = pending_frame->frame_info;
629 const struct block *block = nullptr, *fn_block;
630
631 try
632 {
633 block = get_frame_block (frame, nullptr);
634 }
635 catch (const gdb_exception &except)
636 {
637 GDB_PY_HANDLE_EXCEPTION (except);
638 }
639
640 for (fn_block = block;
641 fn_block != nullptr && fn_block->function () == nullptr;
642 fn_block = fn_block->superblock ())
643 ;
644
645 if (block == nullptr
646 || fn_block == nullptr
647 || fn_block->function () == nullptr)
648 {
649 PyErr_SetString (PyExc_RuntimeError,
650 _("Cannot locate block for frame."));
651 return nullptr;
652 }
653
654 return block_to_block_object (block, fn_block->function ()->objfile ());
655 }
656
657 /* Implement gdb.PendingFrame.function(). Return a gdb.Symbol
658 representing the function of this frame, or None if no suitable symbol
659 can be found. */
660
661 static PyObject *
662 pending_framepy_function (PyObject *self, PyObject *args)
663 {
664 pending_frame_object *pending_frame = (pending_frame_object *) self;
665
666 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
667
668 struct symbol *sym = nullptr;
669
670 try
671 {
672 enum language funlang;
673 frame_info_ptr frame = pending_frame->frame_info;
674
675 gdb::unique_xmalloc_ptr<char> funname
676 = find_frame_funname (frame, &funlang, &sym);
677 }
678 catch (const gdb_exception &except)
679 {
680 GDB_PY_HANDLE_EXCEPTION (except);
681 }
682
683 if (sym != nullptr)
684 return symbol_to_symbol_object (sym);
685
686 Py_RETURN_NONE;
687 }
688
689 /* Implementation of
690 PendingFrame.create_unwind_info (self, frameId) -> UnwindInfo. */
691
692 static PyObject *
693 pending_framepy_create_unwind_info (PyObject *self, PyObject *args,
694 PyObject *kw)
695 {
696 PyObject *pyo_frame_id;
697 CORE_ADDR sp;
698 CORE_ADDR pc;
699 CORE_ADDR special;
700
701 PENDING_FRAMEPY_REQUIRE_VALID ((pending_frame_object *) self);
702
703 static const char *keywords[] = { "frame_id", nullptr };
704 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "O", keywords,
705 &pyo_frame_id))
706 return nullptr;
707
708 pyuw_get_attr_code code
709 = pyuw_object_attribute_to_pointer (pyo_frame_id, "sp", &sp);
710 if (code == pyuw_get_attr_code::ATTR_MISSING)
711 {
712 PyErr_SetString (PyExc_ValueError,
713 _("frame_id should have 'sp' attribute."));
714 return nullptr;
715 }
716 else if (code == pyuw_get_attr_code::ATTR_ERROR)
717 return nullptr;
718
719 /* The logic of building frame_id depending on the attributes of
720 the frame_id object:
721 Has Has Has Function to call
722 'sp'? 'pc'? 'special'?
723 ------|------|--------------|-------------------------
724 Y N * frame_id_build_wild (sp)
725 Y Y N frame_id_build (sp, pc)
726 Y Y Y frame_id_build_special (sp, pc, special)
727 */
728 code = pyuw_object_attribute_to_pointer (pyo_frame_id, "pc", &pc);
729 if (code == pyuw_get_attr_code::ATTR_ERROR)
730 return nullptr;
731 else if (code == pyuw_get_attr_code::ATTR_MISSING)
732 return pyuw_create_unwind_info (self, frame_id_build_wild (sp));
733
734 code = pyuw_object_attribute_to_pointer (pyo_frame_id, "special", &special);
735 if (code == pyuw_get_attr_code::ATTR_ERROR)
736 return nullptr;
737 else if (code == pyuw_get_attr_code::ATTR_MISSING)
738 return pyuw_create_unwind_info (self, frame_id_build (sp, pc));
739
740 return pyuw_create_unwind_info (self,
741 frame_id_build_special (sp, pc, special));
742 }
743
744 /* Implementation of PendingFrame.architecture (self) -> gdb.Architecture. */
745
746 static PyObject *
747 pending_framepy_architecture (PyObject *self, PyObject *args)
748 {
749 pending_frame_object *pending_frame = (pending_frame_object *) self;
750
751 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
752
753 return gdbarch_to_arch_object (pending_frame->gdbarch);
754 }
755
756 /* Implementation of PendingFrame.level (self) -> Integer. */
757
758 static PyObject *
759 pending_framepy_level (PyObject *self, PyObject *args)
760 {
761 pending_frame_object *pending_frame = (pending_frame_object *) self;
762
763 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
764
765 int level = frame_relative_level (pending_frame->frame_info);
766 return gdb_py_object_from_longest (level).release ();
767 }
768
769 /* frame_unwind.this_id method. */
770
771 static void
772 pyuw_this_id (frame_info_ptr this_frame, void **cache_ptr,
773 struct frame_id *this_id)
774 {
775 *this_id = ((cached_frame_info *) *cache_ptr)->frame_id;
776 pyuw_debug_printf ("frame_id: %s", this_id->to_string ().c_str ());
777 }
778
779 /* frame_unwind.prev_register. */
780
781 static struct value *
782 pyuw_prev_register (frame_info_ptr this_frame, void **cache_ptr,
783 int regnum)
784 {
785 PYUW_SCOPED_DEBUG_ENTER_EXIT;
786
787 cached_frame_info *cached_frame = (cached_frame_info *) *cache_ptr;
788 cached_reg_t *reg_info = cached_frame->reg;
789 cached_reg_t *reg_info_end = reg_info + cached_frame->reg_count;
790
791 pyuw_debug_printf ("frame=%d, reg=%d",
792 frame_relative_level (this_frame), regnum);
793 for (; reg_info < reg_info_end; ++reg_info)
794 {
795 if (regnum == reg_info->num)
796 return frame_unwind_got_bytes (this_frame, regnum, reg_info->data.get ());
797 }
798
799 return frame_unwind_got_optimized (this_frame, regnum);
800 }
801
802 /* Frame sniffer dispatch. */
803
804 static int
805 pyuw_sniffer (const struct frame_unwind *self, frame_info_ptr this_frame,
806 void **cache_ptr)
807 {
808 PYUW_SCOPED_DEBUG_ENTER_EXIT;
809
810 struct gdbarch *gdbarch = (struct gdbarch *) (self->unwind_data);
811 cached_frame_info *cached_frame;
812
813 gdbpy_enter enter_py (gdbarch);
814
815 pyuw_debug_printf ("frame=%d, sp=%s, pc=%s",
816 frame_relative_level (this_frame),
817 paddress (gdbarch, get_frame_sp (this_frame)),
818 paddress (gdbarch, get_frame_pc (this_frame)));
819
820 /* Create PendingFrame instance to pass to sniffers. */
821 pending_frame_object *pfo = PyObject_New (pending_frame_object,
822 &pending_frame_object_type);
823 gdbpy_ref<> pyo_pending_frame ((PyObject *) pfo);
824 if (pyo_pending_frame == NULL)
825 {
826 gdbpy_print_stack ();
827 return 0;
828 }
829 pfo->gdbarch = gdbarch;
830 pfo->frame_info = nullptr;
831 scoped_restore invalidate_frame = make_scoped_restore (&pfo->frame_info,
832 this_frame);
833
834 /* Run unwinders. */
835 if (gdb_python_module == NULL
836 || ! PyObject_HasAttrString (gdb_python_module, "_execute_unwinders"))
837 {
838 PyErr_SetString (PyExc_NameError,
839 "Installation error: gdb._execute_unwinders function "
840 "is missing");
841 gdbpy_print_stack ();
842 return 0;
843 }
844 gdbpy_ref<> pyo_execute (PyObject_GetAttrString (gdb_python_module,
845 "_execute_unwinders"));
846 if (pyo_execute == nullptr)
847 {
848 gdbpy_print_stack ();
849 return 0;
850 }
851
852 /* A (gdb.UnwindInfo, str) tuple, or None. */
853 gdbpy_ref<> pyo_execute_ret
854 (PyObject_CallFunctionObjArgs (pyo_execute.get (),
855 pyo_pending_frame.get (), NULL));
856 if (pyo_execute_ret == nullptr)
857 {
858 /* If the unwinder is cancelled due to a Ctrl-C, then propagate
859 the Ctrl-C as a GDB exception instead of swallowing it. */
860 gdbpy_print_stack_or_quit ();
861 return 0;
862 }
863 if (pyo_execute_ret == Py_None)
864 return 0;
865
866 /* Verify the return value of _execute_unwinders is a tuple of size 2. */
867 gdb_assert (PyTuple_Check (pyo_execute_ret.get ()));
868 gdb_assert (PyTuple_GET_SIZE (pyo_execute_ret.get ()) == 2);
869
870 if (pyuw_debug)
871 {
872 PyObject *pyo_unwinder_name = PyTuple_GET_ITEM (pyo_execute_ret.get (), 1);
873 gdb::unique_xmalloc_ptr<char> name
874 = python_string_to_host_string (pyo_unwinder_name);
875
876 /* This could happen if the user passed something else than a string
877 as the unwinder's name. */
878 if (name == nullptr)
879 {
880 gdbpy_print_stack ();
881 name = make_unique_xstrdup ("<failed to get unwinder name>");
882 }
883
884 pyuw_debug_printf ("frame claimed by unwinder %s", name.get ());
885 }
886
887 /* Received UnwindInfo, cache data. */
888 PyObject *pyo_unwind_info = PyTuple_GET_ITEM (pyo_execute_ret.get (), 0);
889 if (PyObject_IsInstance (pyo_unwind_info,
890 (PyObject *) &unwind_info_object_type) <= 0)
891 error (_("A Unwinder should return gdb.UnwindInfo instance."));
892
893 {
894 unwind_info_object *unwind_info =
895 (unwind_info_object *) pyo_unwind_info;
896 int reg_count = unwind_info->saved_regs->size ();
897
898 cached_frame
899 = ((cached_frame_info *)
900 xmalloc (sizeof (*cached_frame)
901 + reg_count * sizeof (cached_frame->reg[0])));
902 cached_frame->gdbarch = gdbarch;
903 cached_frame->frame_id = unwind_info->frame_id;
904 cached_frame->reg_count = reg_count;
905
906 /* Populate registers array. */
907 for (int i = 0; i < unwind_info->saved_regs->size (); ++i)
908 {
909 saved_reg *reg = &(*unwind_info->saved_regs)[i];
910
911 struct value *value = value_object_to_value (reg->value.get ());
912 size_t data_size = register_size (gdbarch, reg->number);
913
914 /* `value' validation was done before, just assert. */
915 gdb_assert (value != NULL);
916 gdb_assert (data_size == value->type ()->length ());
917
918 cached_reg_t *cached = new (&cached_frame->reg[i]) cached_reg_t ();
919 cached->num = reg->number;
920 cached->data.reset ((gdb_byte *) xmalloc (data_size));
921 memcpy (cached->data.get (), value->contents ().data (), data_size);
922 }
923 }
924
925 *cache_ptr = cached_frame;
926 return 1;
927 }
928
929 /* Frame cache release shim. */
930
931 static void
932 pyuw_dealloc_cache (frame_info *this_frame, void *cache)
933 {
934 PYUW_SCOPED_DEBUG_ENTER_EXIT;
935 cached_frame_info *cached_frame = (cached_frame_info *) cache;
936
937 for (int i = 0; i < cached_frame->reg_count; i++)
938 cached_frame->reg[i].~cached_reg_t ();
939
940 xfree (cache);
941 }
942
943 struct pyuw_gdbarch_data_type
944 {
945 /* Has the unwinder shim been prepended? */
946 int unwinder_registered = 0;
947 };
948
949 static const registry<gdbarch>::key<pyuw_gdbarch_data_type> pyuw_gdbarch_data;
950
951 /* New inferior architecture callback: register the Python unwinders
952 intermediary. */
953
954 static void
955 pyuw_on_new_gdbarch (gdbarch *newarch)
956 {
957 struct pyuw_gdbarch_data_type *data = pyuw_gdbarch_data.get (newarch);
958 if (data == nullptr)
959 data= pyuw_gdbarch_data.emplace (newarch);
960
961 if (!data->unwinder_registered)
962 {
963 struct frame_unwind *unwinder
964 = GDBARCH_OBSTACK_ZALLOC (newarch, struct frame_unwind);
965
966 unwinder->name = "python";
967 unwinder->type = NORMAL_FRAME;
968 unwinder->stop_reason = default_frame_unwind_stop_reason;
969 unwinder->this_id = pyuw_this_id;
970 unwinder->prev_register = pyuw_prev_register;
971 unwinder->unwind_data = (const struct frame_data *) newarch;
972 unwinder->sniffer = pyuw_sniffer;
973 unwinder->dealloc_cache = pyuw_dealloc_cache;
974 frame_unwind_prepend_unwinder (newarch, unwinder);
975 data->unwinder_registered = 1;
976 }
977 }
978
979 /* Initialize unwind machinery. */
980
981 static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
982 gdbpy_initialize_unwind (void)
983 {
984 gdb::observers::new_architecture.attach (pyuw_on_new_gdbarch, "py-unwind");
985
986 if (PyType_Ready (&pending_frame_object_type) < 0)
987 return -1;
988 int rc = gdb_pymodule_addobject (gdb_module, "PendingFrame",
989 (PyObject *) &pending_frame_object_type);
990 if (rc != 0)
991 return rc;
992
993 if (PyType_Ready (&unwind_info_object_type) < 0)
994 return -1;
995 return gdb_pymodule_addobject (gdb_module, "UnwindInfo",
996 (PyObject *) &unwind_info_object_type);
997 }
998
999 void _initialize_py_unwind ();
1000 void
1001 _initialize_py_unwind ()
1002 {
1003 add_setshow_boolean_cmd
1004 ("py-unwind", class_maintenance, &pyuw_debug,
1005 _("Set Python unwinder debugging."),
1006 _("Show Python unwinder debugging."),
1007 _("When on, Python unwinder debugging is enabled."),
1008 NULL,
1009 show_pyuw_debug,
1010 &setdebuglist, &showdebuglist);
1011 }
1012
1013 GDBPY_INITIALIZE_FILE (gdbpy_initialize_unwind);
1014
1015 \f
1016
1017 static PyMethodDef pending_frame_object_methods[] =
1018 {
1019 { "read_register", (PyCFunction) pending_framepy_read_register,
1020 METH_VARARGS | METH_KEYWORDS,
1021 "read_register (REG) -> gdb.Value\n"
1022 "Return the value of the REG in the frame." },
1023 { "create_unwind_info", (PyCFunction) pending_framepy_create_unwind_info,
1024 METH_VARARGS | METH_KEYWORDS,
1025 "create_unwind_info (FRAME_ID) -> gdb.UnwindInfo\n"
1026 "Construct UnwindInfo for this PendingFrame, using FRAME_ID\n"
1027 "to identify it." },
1028 { "architecture",
1029 pending_framepy_architecture, METH_NOARGS,
1030 "architecture () -> gdb.Architecture\n"
1031 "The architecture for this PendingFrame." },
1032 { "name",
1033 pending_framepy_name, METH_NOARGS,
1034 "name() -> String.\n\
1035 Return the function name of the frame, or None if it can't be determined." },
1036 { "is_valid",
1037 pending_framepy_is_valid, METH_NOARGS,
1038 "is_valid () -> Boolean.\n\
1039 Return true if this PendingFrame is valid, false if not." },
1040 { "pc",
1041 pending_framepy_pc, METH_NOARGS,
1042 "pc () -> Long.\n\
1043 Return the frame's resume address." },
1044 { "language", pending_framepy_language, METH_NOARGS,
1045 "The language of this frame." },
1046 { "find_sal", pending_framepy_find_sal, METH_NOARGS,
1047 "find_sal () -> gdb.Symtab_and_line.\n\
1048 Return the frame's symtab and line." },
1049 { "block", pending_framepy_block, METH_NOARGS,
1050 "block () -> gdb.Block.\n\
1051 Return the frame's code block." },
1052 { "function", pending_framepy_function, METH_NOARGS,
1053 "function () -> gdb.Symbol.\n\
1054 Returns the symbol for the function corresponding to this frame." },
1055 { "level", pending_framepy_level, METH_NOARGS,
1056 "The stack level of this frame." },
1057 {NULL} /* Sentinel */
1058 };
1059
1060 PyTypeObject pending_frame_object_type =
1061 {
1062 PyVarObject_HEAD_INIT (NULL, 0)
1063 "gdb.PendingFrame", /* tp_name */
1064 sizeof (pending_frame_object), /* tp_basicsize */
1065 0, /* tp_itemsize */
1066 0, /* tp_dealloc */
1067 0, /* tp_print */
1068 0, /* tp_getattr */
1069 0, /* tp_setattr */
1070 0, /* tp_compare */
1071 pending_framepy_repr, /* tp_repr */
1072 0, /* tp_as_number */
1073 0, /* tp_as_sequence */
1074 0, /* tp_as_mapping */
1075 0, /* tp_hash */
1076 0, /* tp_call */
1077 pending_framepy_str, /* tp_str */
1078 0, /* tp_getattro */
1079 0, /* tp_setattro */
1080 0, /* tp_as_buffer */
1081 Py_TPFLAGS_DEFAULT, /* tp_flags */
1082 "GDB PendingFrame object", /* tp_doc */
1083 0, /* tp_traverse */
1084 0, /* tp_clear */
1085 0, /* tp_richcompare */
1086 0, /* tp_weaklistoffset */
1087 0, /* tp_iter */
1088 0, /* tp_iternext */
1089 pending_frame_object_methods, /* tp_methods */
1090 0, /* tp_members */
1091 0, /* tp_getset */
1092 0, /* tp_base */
1093 0, /* tp_dict */
1094 0, /* tp_descr_get */
1095 0, /* tp_descr_set */
1096 0, /* tp_dictoffset */
1097 0, /* tp_init */
1098 0, /* tp_alloc */
1099 };
1100
1101 static PyMethodDef unwind_info_object_methods[] =
1102 {
1103 { "add_saved_register",
1104 (PyCFunction) unwind_infopy_add_saved_register,
1105 METH_VARARGS | METH_KEYWORDS,
1106 "add_saved_register (REG, VALUE) -> None\n"
1107 "Set the value of the REG in the previous frame to VALUE." },
1108 { NULL } /* Sentinel */
1109 };
1110
1111 PyTypeObject unwind_info_object_type =
1112 {
1113 PyVarObject_HEAD_INIT (NULL, 0)
1114 "gdb.UnwindInfo", /* tp_name */
1115 sizeof (unwind_info_object), /* tp_basicsize */
1116 0, /* tp_itemsize */
1117 unwind_infopy_dealloc, /* tp_dealloc */
1118 0, /* tp_print */
1119 0, /* tp_getattr */
1120 0, /* tp_setattr */
1121 0, /* tp_compare */
1122 unwind_infopy_repr, /* tp_repr */
1123 0, /* tp_as_number */
1124 0, /* tp_as_sequence */
1125 0, /* tp_as_mapping */
1126 0, /* tp_hash */
1127 0, /* tp_call */
1128 unwind_infopy_str, /* tp_str */
1129 0, /* tp_getattro */
1130 0, /* tp_setattro */
1131 0, /* tp_as_buffer */
1132 Py_TPFLAGS_DEFAULT, /* tp_flags */
1133 "GDB UnwindInfo object", /* tp_doc */
1134 0, /* tp_traverse */
1135 0, /* tp_clear */
1136 0, /* tp_richcompare */
1137 0, /* tp_weaklistoffset */
1138 0, /* tp_iter */
1139 0, /* tp_iternext */
1140 unwind_info_object_methods, /* tp_methods */
1141 0, /* tp_members */
1142 0, /* tp_getset */
1143 0, /* tp_base */
1144 0, /* tp_dict */
1145 0, /* tp_descr_get */
1146 0, /* tp_descr_set */
1147 0, /* tp_dictoffset */
1148 0, /* tp_init */
1149 0, /* tp_alloc */
1150 };