]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame_incremental - gdb/python/py-unwind.c
gas: Re-indent case OPTION_SFRAME:
[thirdparty/binutils-gdb.git] / gdb / python / py-unwind.c
... / ...
CommitLineData
1/* Python frame unwinder interface.
2
3 Copyright (C) 2015-2025 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 "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"
33
34
35/* Debugging of Python unwinders. */
36
37static bool pyuw_debug;
38
39/* Implementation of "show debug py-unwind". */
40
41static void
42show_pyuw_debug (struct ui_file *file, int from_tty,
43 struct cmd_list_element *c, const char *value)
44{
45 gdb_printf (file, _("Python unwinder debugging is %s.\n"), value);
46}
47
48/* Print a "py-unwind" debug statement. */
49
50#define pyuw_debug_printf(fmt, ...) \
51 debug_prefixed_printf_cond (pyuw_debug, "py-unwind", fmt, ##__VA_ARGS__)
52
53/* Print "py-unwind" enter/exit debug statements. */
54
55#define PYUW_SCOPED_DEBUG_ENTER_EXIT \
56 scoped_debug_enter_exit (pyuw_debug, "py-unwind")
57
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)
68
69struct pending_frame_object
70{
71 PyObject_HEAD
72
73 /* Frame we are unwinding. */
74 frame_info_ptr frame_info;
75
76 /* Its architecture, passed by the sniffer caller. */
77 struct gdbarch *gdbarch;
78};
79
80/* Saved registers array item. */
81
82struct saved_reg
83{
84 saved_reg (int n, gdbpy_ref<> &&v)
85 : number (n),
86 value (std::move (v))
87 {
88 }
89
90 int number;
91 gdbpy_ref<> value;
92};
93
94/* The data we keep for the PyUnwindInfo: pending_frame, saved registers
95 and frame ID. */
96
97struct unwind_info_object
98{
99 PyObject_HEAD
100
101 /* gdb.PendingFrame for the frame we are unwinding. */
102 PyObject *pending_frame;
103
104 /* Its ID. */
105 struct frame_id frame_id;
106
107 /* Saved registers array. */
108 std::vector<saved_reg> *saved_regs;
109};
110
111/* The data we keep for a frame we can unwind: frame ID and an array of
112 (register_number, register_value) pairs. */
113
114struct cached_frame_info
115{
116 /* Frame ID. */
117 struct frame_id frame_id;
118
119 /* GDB Architecture. */
120 struct gdbarch *gdbarch;
121
122 /* Length of the `reg' array below. */
123 int reg_count;
124
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:
128
129 error: flexible array member 'reg' of type 'cached_reg_t[]' with non-trivial destruction
130
131 Note we manually call the destructor of each array element in
132 pyuw_dealloc_cache. */
133 cached_reg_t reg[0];
134};
135
136extern PyTypeObject pending_frame_object_type
137 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("pending_frame_object");
138
139extern PyTypeObject unwind_info_object_type
140 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("unwind_info_object");
141
142/* An enum returned by pyuw_object_attribute_to_pointer, a function which
143 is used to extract an attribute from a Python object. */
144
145enum class pyuw_get_attr_code
146{
147 /* The attribute was present, and its value was successfully extracted. */
148 ATTR_OK,
149
150 /* The attribute was not present, or was present and its value was None.
151 No Python error has been set. */
152 ATTR_MISSING,
153
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,
158};
159
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.
162
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.
166
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.
171
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. */
175
176static pyuw_get_attr_code
177pyuw_object_attribute_to_pointer (PyObject *pyo, const char *attr_name,
178 CORE_ADDR *addr)
179{
180 if (!PyObject_HasAttrString (pyo, attr_name))
181 return pyuw_get_attr_code::ATTR_MISSING;
182
183 gdbpy_ref<> pyo_value (PyObject_GetAttrString (pyo, attr_name));
184 if (pyo_value == nullptr)
185 {
186 gdb_assert (PyErr_Occurred ());
187 return pyuw_get_attr_code::ATTR_ERROR;
188 }
189 if (pyo_value == Py_None)
190 return pyuw_get_attr_code::ATTR_MISSING;
191
192 if (get_addr_from_python (pyo_value.get (), addr) < 0)
193 {
194 gdb_assert (PyErr_Occurred ());
195 return pyuw_get_attr_code::ATTR_ERROR;
196 }
197
198 return pyuw_get_attr_code::ATTR_OK;
199}
200
201/* Called by the Python interpreter to obtain string representation
202 of the UnwindInfo object. */
203
204static PyObject *
205unwind_infopy_str (PyObject *self)
206{
207 unwind_info_object *unwind_info = (unwind_info_object *) self;
208 string_file stb;
209
210 stb.printf ("Frame ID: %s", unwind_info->frame_id.to_string ().c_str ());
211 {
212 const char *sep = "";
213 struct value_print_options opts;
214
215 get_user_print_options (&opts);
216 stb.printf ("\nSaved registers: (");
217 for (const saved_reg &reg : *unwind_info->saved_regs)
218 {
219 struct value *value = value_object_to_value (reg.value.get ());
220
221 stb.printf ("%s(%d, ", sep, reg.number);
222 if (value != NULL)
223 {
224 try
225 {
226 value_print (value, &stb, &opts);
227 stb.puts (")");
228 }
229 catch (const gdb_exception &except)
230 {
231 return gdbpy_handle_gdb_exception (nullptr, except);
232 }
233 }
234 else
235 stb.puts ("<BAD>)");
236 sep = ", ";
237 }
238 stb.puts (")");
239 }
240
241 return PyUnicode_FromString (stb.c_str ());
242}
243
244/* Implement UnwindInfo.__repr__(). */
245
246static PyObject *
247unwind_infopy_repr (PyObject *self)
248{
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;
253
254 if (frame == nullptr)
255 return PyUnicode_FromFormat ("<%s for an invalid frame>",
256 Py_TYPE (self)->tp_name);
257
258 std::string saved_reg_names;
259 struct gdbarch *gdbarch = pending_frame->gdbarch;
260
261 for (const saved_reg &reg : *unwind_info->saved_regs)
262 {
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;
268 }
269
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 ());
274}
275
276/* Create UnwindInfo instance for given PendingFrame and frame ID.
277 Sets Python error and returns NULL on error.
278
279 The PYO_PENDING_FRAME object must be valid. */
280
281static PyObject *
282pyuw_create_unwind_info (PyObject *pyo_pending_frame,
283 struct frame_id frame_id)
284{
285 gdb_assert (((pending_frame_object *) pyo_pending_frame)->frame_info
286 != nullptr);
287
288 unwind_info_object *unwind_info
289 = PyObject_New (unwind_info_object, &unwind_info_object_type);
290
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;
296}
297
298/* The implementation of
299 gdb.UnwindInfo.add_saved_register (REG, VALUE) -> None. */
300
301static PyObject *
302unwind_infopy_add_saved_register (PyObject *self, PyObject *args, PyObject *kw)
303{
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;
310
311 if (pending_frame->frame_info == NULL)
312 {
313 PyErr_SetString (PyExc_ValueError,
314 "UnwindInfo instance refers to a stale PendingFrame");
315 return nullptr;
316 }
317
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;
323
324 if (!gdbpy_parse_register_id (pending_frame->gdbarch, pyo_reg_id, &regnum))
325 return nullptr;
326
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))
334 {
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))
340 {
341 PyErr_SetString (PyExc_ValueError, "Bad register");
342 return NULL;
343 }
344 }
345
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);
352
353 ULONGEST reg_size = register_size (pending_frame->gdbarch, regnum);
354 if (reg_size != value->type ()->length ())
355 {
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;
362 }
363
364
365 try
366 {
367 if (value->optimized_out () || !value->entirely_available ())
368 {
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;
377 }
378 }
379 catch (const gdb_exception &except)
380 {
381 return gdbpy_handle_gdb_exception (nullptr, except);
382 }
383
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)
387 {
388 if (regnum == reg.number)
389 {
390 found = true;
391 reg.value = std::move (new_value);
392 break;
393 }
394 }
395 if (!found)
396 unwind_info->saved_regs->emplace_back (regnum, std::move (new_value));
397
398 Py_RETURN_NONE;
399}
400
401/* UnwindInfo cleanup. */
402
403static void
404unwind_infopy_dealloc (PyObject *self)
405{
406 unwind_info_object *unwind_info = (unwind_info_object *) self;
407
408 Py_XDECREF (unwind_info->pending_frame);
409 delete unwind_info->saved_regs;
410 Py_TYPE (self)->tp_free (self);
411}
412
413/* Called by the Python interpreter to obtain string representation
414 of the PendingFrame object. */
415
416static PyObject *
417pending_framepy_str (PyObject *self)
418{
419 frame_info_ptr frame = ((pending_frame_object *) self)->frame_info;
420 const char *sp_str = NULL;
421 const char *pc_str = NULL;
422
423 if (frame == NULL)
424 return PyUnicode_FromString ("Stale PendingFrame instance");
425 try
426 {
427 sp_str = core_addr_to_string_nz (get_frame_sp (frame));
428 pc_str = core_addr_to_string_nz (get_frame_pc (frame));
429 }
430 catch (const gdb_exception &except)
431 {
432 return gdbpy_handle_gdb_exception (nullptr, except);
433 }
434
435 return PyUnicode_FromFormat ("SP=%s,PC=%s", sp_str, pc_str);
436}
437
438/* Implement PendingFrame.__repr__(). */
439
440static PyObject *
441pending_framepy_repr (PyObject *self)
442{
443 pending_frame_object *pending_frame = (pending_frame_object *) self;
444 frame_info_ptr frame = pending_frame->frame_info;
445
446 if (frame == nullptr)
447 return gdb_py_invalid_object_repr (self);
448
449 const char *sp_str = nullptr;
450 const char *pc_str = nullptr;
451
452 try
453 {
454 sp_str = core_addr_to_string_nz (get_frame_sp (frame));
455 pc_str = core_addr_to_string_nz (get_frame_pc (frame));
456 }
457 catch (const gdb_exception &except)
458 {
459 return gdbpy_handle_gdb_exception (nullptr, except);
460 }
461
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);
467}
468
469/* Implementation of gdb.PendingFrame.read_register (self, reg) -> gdb.Value.
470 Returns the value of register REG as gdb.Value instance. */
471
472static PyObject *
473pending_framepy_read_register (PyObject *self, PyObject *args, PyObject *kw)
474{
475 pending_frame_object *pending_frame = (pending_frame_object *) self;
476 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
477
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;
482
483 int regnum;
484 if (!gdbpy_parse_register_id (pending_frame->gdbarch, pyo_reg_id, &regnum))
485 return nullptr;
486
487 PyObject *result = nullptr;
488 try
489 {
490 scoped_value_mark free_values;
491
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);
505 }
506 catch (const gdb_exception &except)
507 {
508 return gdbpy_handle_gdb_exception (nullptr, except);
509 }
510
511 return result;
512}
513
514/* Implement PendingFrame.is_valid(). Return True if this pending frame
515 object is still valid. */
516
517static PyObject *
518pending_framepy_is_valid (PyObject *self, PyObject *args)
519{
520 pending_frame_object *pending_frame = (pending_frame_object *) self;
521
522 if (pending_frame->frame_info == nullptr)
523 Py_RETURN_FALSE;
524
525 Py_RETURN_TRUE;
526}
527
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. */
530
531static PyObject *
532pending_framepy_name (PyObject *self, PyObject *args)
533{
534 pending_frame_object *pending_frame = (pending_frame_object *) self;
535
536 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
537
538 gdb::unique_xmalloc_ptr<char> name;
539
540 try
541 {
542 enum language lang;
543 frame_info_ptr frame = pending_frame->frame_info;
544
545 name = find_frame_funname (frame, &lang, nullptr);
546 }
547 catch (const gdb_exception &except)
548 {
549 return gdbpy_handle_gdb_exception (nullptr, except);
550 }
551
552 if (name != nullptr)
553 return PyUnicode_Decode (name.get (), strlen (name.get ()),
554 host_charset (), nullptr);
555
556 Py_RETURN_NONE;
557}
558
559/* Implement gdb.PendingFrame.pc(). Returns an integer containing the
560 frame's current $pc value. */
561
562static PyObject *
563pending_framepy_pc (PyObject *self, PyObject *args)
564{
565 pending_frame_object *pending_frame = (pending_frame_object *) self;
566
567 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
568
569 CORE_ADDR pc = 0;
570
571 try
572 {
573 pc = get_frame_pc (pending_frame->frame_info);
574 }
575 catch (const gdb_exception &except)
576 {
577 return gdbpy_handle_gdb_exception (nullptr, except);
578 }
579
580 return gdb_py_object_from_ulongest (pc).release ();
581}
582
583/* Implement gdb.PendingFrame.language(). Return the name of the language
584 for this frame. */
585
586static PyObject *
587pending_framepy_language (PyObject *self, PyObject *args)
588{
589 pending_frame_object *pending_frame = (pending_frame_object *) self;
590
591 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
592
593 try
594 {
595 frame_info_ptr fi = pending_frame->frame_info;
596
597 enum language lang = get_frame_language (fi);
598 const language_defn *lang_def = language_def (lang);
599
600 return host_string_to_python_string (lang_def->name ()).release ();
601 }
602 catch (const gdb_exception &except)
603 {
604 return gdbpy_handle_gdb_exception (nullptr, except);
605 }
606
607 Py_RETURN_NONE;
608}
609
610/* Implement PendingFrame.find_sal(). Return the PendingFrame's symtab and
611 line. */
612
613static PyObject *
614pending_framepy_find_sal (PyObject *self, PyObject *args)
615{
616 pending_frame_object *pending_frame = (pending_frame_object *) self;
617
618 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
619
620 PyObject *sal_obj = nullptr;
621
622 try
623 {
624 frame_info_ptr frame = pending_frame->frame_info;
625
626 symtab_and_line sal = find_frame_sal (frame);
627 sal_obj = symtab_and_line_to_sal_object (sal);
628 }
629 catch (const gdb_exception &except)
630 {
631 return gdbpy_handle_gdb_exception (nullptr, except);
632 }
633
634 return sal_obj;
635}
636
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. */
639
640static PyObject *
641pending_framepy_block (PyObject *self, PyObject *args)
642{
643 pending_frame_object *pending_frame = (pending_frame_object *) self;
644
645 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
646
647 frame_info_ptr frame = pending_frame->frame_info;
648 const struct block *block = nullptr, *fn_block;
649
650 try
651 {
652 block = get_frame_block (frame, nullptr);
653 }
654 catch (const gdb_exception &except)
655 {
656 return gdbpy_handle_gdb_exception (nullptr, except);
657 }
658
659 for (fn_block = block;
660 fn_block != nullptr && fn_block->function () == nullptr;
661 fn_block = fn_block->superblock ())
662 ;
663
664 if (block == nullptr
665 || fn_block == nullptr
666 || fn_block->function () == nullptr)
667 {
668 PyErr_SetString (PyExc_RuntimeError,
669 _("Cannot locate block for frame."));
670 return nullptr;
671 }
672
673 return block_to_block_object (block, fn_block->function ()->objfile ());
674}
675
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. */
679
680static PyObject *
681pending_framepy_function (PyObject *self, PyObject *args)
682{
683 pending_frame_object *pending_frame = (pending_frame_object *) self;
684
685 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
686
687 struct symbol *sym = nullptr;
688
689 try
690 {
691 enum language funlang;
692 frame_info_ptr frame = pending_frame->frame_info;
693
694 gdb::unique_xmalloc_ptr<char> funname
695 = find_frame_funname (frame, &funlang, &sym);
696 }
697 catch (const gdb_exception &except)
698 {
699 return gdbpy_handle_gdb_exception (nullptr, except);
700 }
701
702 if (sym != nullptr)
703 return symbol_to_symbol_object (sym);
704
705 Py_RETURN_NONE;
706}
707
708/* Implementation of
709 PendingFrame.create_unwind_info (self, frameId) -> UnwindInfo. */
710
711static PyObject *
712pending_framepy_create_unwind_info (PyObject *self, PyObject *args,
713 PyObject *kw)
714{
715 PyObject *pyo_frame_id;
716 CORE_ADDR sp;
717 CORE_ADDR pc;
718 CORE_ADDR special;
719
720 PENDING_FRAMEPY_REQUIRE_VALID ((pending_frame_object *) self);
721
722 static const char *keywords[] = { "frame_id", nullptr };
723 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "O", keywords,
724 &pyo_frame_id))
725 return nullptr;
726
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)
730 {
731 PyErr_SetString (PyExc_ValueError,
732 _("frame_id should have 'sp' attribute."));
733 return nullptr;
734 }
735 else if (code == pyuw_get_attr_code::ATTR_ERROR)
736 return nullptr;
737
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)
746 */
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));
752
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));
758
759 return pyuw_create_unwind_info (self,
760 frame_id_build_special (sp, pc, special));
761}
762
763/* Implementation of PendingFrame.architecture (self) -> gdb.Architecture. */
764
765static PyObject *
766pending_framepy_architecture (PyObject *self, PyObject *args)
767{
768 pending_frame_object *pending_frame = (pending_frame_object *) self;
769
770 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
771
772 return gdbarch_to_arch_object (pending_frame->gdbarch);
773}
774
775/* Implementation of PendingFrame.level (self) -> Integer. */
776
777static PyObject *
778pending_framepy_level (PyObject *self, PyObject *args)
779{
780 pending_frame_object *pending_frame = (pending_frame_object *) self;
781
782 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
783
784 int level = frame_relative_level (pending_frame->frame_info);
785 return gdb_py_object_from_longest (level).release ();
786}
787
788/* Class for frame unwinders registered by the Python architecture callback. */
789class frame_unwind_python : public frame_unwind
790{
791public:
792 frame_unwind_python (const struct frame_data *newarch)
793 : frame_unwind ("python", NORMAL_FRAME, FRAME_UNWIND_EXTENSION, newarch)
794 { }
795
796 /* No need to override stop_reason, we want the default. */
797
798 int sniff (const frame_info_ptr &this_frame,
799 void **this_prologue_cache) const override;
800
801 void this_id (const frame_info_ptr &this_frame, void **this_prologue_cache,
802 struct frame_id *id) const override;
803
804 struct value *prev_register (const frame_info_ptr &this_frame,
805 void **this_prologue_cache,
806 int regnum) const override;
807
808 void dealloc_cache (frame_info *self, void *this_cache) const override;
809};
810
811/* frame_unwind.this_id method. */
812
813void
814frame_unwind_python::this_id (const frame_info_ptr &this_frame,
815 void **cache_ptr,
816 struct frame_id *this_id) const
817{
818 *this_id = ((cached_frame_info *) *cache_ptr)->frame_id;
819 pyuw_debug_printf ("frame_id: %s", this_id->to_string ().c_str ());
820}
821
822/* frame_unwind.prev_register. */
823
824struct value *
825frame_unwind_python::prev_register (const frame_info_ptr &this_frame,
826 void **cache_ptr, int regnum) const
827{
828 PYUW_SCOPED_DEBUG_ENTER_EXIT;
829
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;
833
834 pyuw_debug_printf ("frame=%d, reg=%d",
835 frame_relative_level (this_frame), regnum);
836 for (; reg_info < reg_info_end; ++reg_info)
837 {
838 if (regnum == reg_info->num)
839 return frame_unwind_got_bytes (this_frame, regnum, reg_info->data);
840 }
841
842 return frame_unwind_got_optimized (this_frame, regnum);
843}
844
845/* Frame sniffer dispatch. */
846
847int
848frame_unwind_python::sniff (const frame_info_ptr &this_frame,
849 void **cache_ptr) const
850{
851 PYUW_SCOPED_DEBUG_ENTER_EXIT;
852
853 struct gdbarch *gdbarch = (struct gdbarch *) (this->unwind_data ());
854 cached_frame_info *cached_frame;
855
856 gdbpy_enter enter_py (gdbarch);
857
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)));
862
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)
868 {
869 gdbpy_print_stack ();
870 return 0;
871 }
872 pfo->gdbarch = gdbarch;
873 pfo->frame_info = nullptr;
874 scoped_restore invalidate_frame = make_scoped_restore (&pfo->frame_info,
875 this_frame);
876
877 /* Run unwinders. */
878 if (gdb_python_module == NULL
879 || ! PyObject_HasAttrString (gdb_python_module, "_execute_unwinders"))
880 {
881 PyErr_SetString (PyExc_NameError,
882 "Installation error: gdb._execute_unwinders function "
883 "is missing");
884 gdbpy_print_stack ();
885 return 0;
886 }
887 gdbpy_ref<> pyo_execute (PyObject_GetAttrString (gdb_python_module,
888 "_execute_unwinders"));
889 if (pyo_execute == nullptr)
890 {
891 gdbpy_print_stack ();
892 return 0;
893 }
894
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)
900 {
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;
905 }
906 if (pyo_execute_ret == Py_None)
907 return 0;
908
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);
912
913 if (pyuw_debug)
914 {
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);
918
919 /* This could happen if the user passed something else than a string
920 as the unwinder's name. */
921 if (name == nullptr)
922 {
923 gdbpy_print_stack ();
924 name = make_unique_xstrdup ("<failed to get unwinder name>");
925 }
926
927 pyuw_debug_printf ("frame claimed by unwinder %s", name.get ());
928 }
929
930 /* Received UnwindInfo, cache data. */
931 PyObject *pyo_unwind_info = PyTuple_GET_ITEM (pyo_execute_ret.get (), 0);
932 if (!PyObject_TypeCheck (pyo_unwind_info, &unwind_info_object_type))
933 error (_("an Unwinder should return gdb.UnwindInfo, not %s."),
934 Py_TYPE (pyo_unwind_info)->tp_name);
935
936 {
937 unwind_info_object *unwind_info =
938 (unwind_info_object *) pyo_unwind_info;
939 int reg_count = unwind_info->saved_regs->size ();
940
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;
948
949 /* Populate registers array. */
950 for (int i = 0; i < unwind_info->saved_regs->size (); ++i)
951 {
952 saved_reg *reg = &(*unwind_info->saved_regs)[i];
953
954 struct value *value = value_object_to_value (reg->value.get ());
955 size_t data_size = register_size (gdbarch, reg->number);
956
957 /* `value' validation was done before, just assert. */
958 gdb_assert (value != NULL);
959 gdb_assert (data_size == value->type ()->length ());
960
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 ());
966 }
967 }
968
969 *cache_ptr = cached_frame;
970 return 1;
971}
972
973/* Frame cache release shim. */
974
975void
976frame_unwind_python::dealloc_cache (frame_info *this_frame, void *cache) const
977{
978 PYUW_SCOPED_DEBUG_ENTER_EXIT;
979 cached_frame_info *cached_frame = (cached_frame_info *) cache;
980
981 for (int i = 0; i < cached_frame->reg_count; i++)
982 cached_frame->reg[i].~cached_reg_t ();
983
984 xfree (cache);
985}
986
987struct pyuw_gdbarch_data_type
988{
989 /* Has the unwinder shim been prepended? */
990 int unwinder_registered = 0;
991};
992
993static const registry<gdbarch>::key<pyuw_gdbarch_data_type> pyuw_gdbarch_data;
994
995/* New inferior architecture callback: register the Python unwinders
996 intermediary. */
997
998static void
999pyuw_on_new_gdbarch (gdbarch *newarch)
1000{
1001 struct pyuw_gdbarch_data_type *data = pyuw_gdbarch_data.get (newarch);
1002 if (data == nullptr)
1003 data= pyuw_gdbarch_data.emplace (newarch);
1004
1005 if (!data->unwinder_registered)
1006 {
1007 struct frame_unwind *unwinder
1008 = obstack_new<frame_unwind_python>
1009 (gdbarch_obstack (newarch), (const struct frame_data *) newarch);
1010
1011 frame_unwind_prepend_unwinder (newarch, unwinder);
1012 data->unwinder_registered = 1;
1013 }
1014}
1015
1016/* Initialize unwind machinery. */
1017
1018static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
1019gdbpy_initialize_unwind (void)
1020{
1021 gdb::observers::new_architecture.attach (pyuw_on_new_gdbarch, "py-unwind");
1022
1023 if (gdbpy_type_ready (&pending_frame_object_type) < 0)
1024 return -1;
1025
1026 if (gdbpy_type_ready (&unwind_info_object_type) < 0)
1027 return -1;
1028
1029 return 0;
1030}
1031
1032INIT_GDB_FILE (py_unwind)
1033{
1034 add_setshow_boolean_cmd
1035 ("py-unwind", class_maintenance, &pyuw_debug,
1036 _("Set Python unwinder debugging."),
1037 _("Show Python unwinder debugging."),
1038 _("When on, Python unwinder debugging is enabled."),
1039 NULL,
1040 show_pyuw_debug,
1041 &setdebuglist, &showdebuglist);
1042}
1043
1044GDBPY_INITIALIZE_FILE (gdbpy_initialize_unwind);
1045
1046\f
1047
1048static PyMethodDef pending_frame_object_methods[] =
1049{
1050 { "read_register", (PyCFunction) pending_framepy_read_register,
1051 METH_VARARGS | METH_KEYWORDS,
1052 "read_register (REG) -> gdb.Value\n"
1053 "Return the value of the REG in the frame." },
1054 { "create_unwind_info", (PyCFunction) pending_framepy_create_unwind_info,
1055 METH_VARARGS | METH_KEYWORDS,
1056 "create_unwind_info (FRAME_ID) -> gdb.UnwindInfo\n"
1057 "Construct UnwindInfo for this PendingFrame, using FRAME_ID\n"
1058 "to identify it." },
1059 { "architecture",
1060 pending_framepy_architecture, METH_NOARGS,
1061 "architecture () -> gdb.Architecture\n"
1062 "The architecture for this PendingFrame." },
1063 { "name",
1064 pending_framepy_name, METH_NOARGS,
1065 "name() -> String.\n\
1066Return the function name of the frame, or None if it can't be determined." },
1067 { "is_valid",
1068 pending_framepy_is_valid, METH_NOARGS,
1069 "is_valid () -> Boolean.\n\
1070Return true if this PendingFrame is valid, false if not." },
1071 { "pc",
1072 pending_framepy_pc, METH_NOARGS,
1073 "pc () -> Long.\n\
1074Return the frame's resume address." },
1075 { "language", pending_framepy_language, METH_NOARGS,
1076 "The language of this frame." },
1077 { "find_sal", pending_framepy_find_sal, METH_NOARGS,
1078 "find_sal () -> gdb.Symtab_and_line.\n\
1079Return the frame's symtab and line." },
1080 { "block", pending_framepy_block, METH_NOARGS,
1081 "block () -> gdb.Block.\n\
1082Return the frame's code block." },
1083 { "function", pending_framepy_function, METH_NOARGS,
1084 "function () -> gdb.Symbol.\n\
1085Returns the symbol for the function corresponding to this frame." },
1086 { "level", pending_framepy_level, METH_NOARGS,
1087 "The stack level of this frame." },
1088 {NULL} /* Sentinel */
1089};
1090
1091PyTypeObject pending_frame_object_type =
1092{
1093 PyVarObject_HEAD_INIT (NULL, 0)
1094 "gdb.PendingFrame", /* tp_name */
1095 sizeof (pending_frame_object), /* tp_basicsize */
1096 0, /* tp_itemsize */
1097 0, /* tp_dealloc */
1098 0, /* tp_print */
1099 0, /* tp_getattr */
1100 0, /* tp_setattr */
1101 0, /* tp_compare */
1102 pending_framepy_repr, /* tp_repr */
1103 0, /* tp_as_number */
1104 0, /* tp_as_sequence */
1105 0, /* tp_as_mapping */
1106 0, /* tp_hash */
1107 0, /* tp_call */
1108 pending_framepy_str, /* tp_str */
1109 0, /* tp_getattro */
1110 0, /* tp_setattro */
1111 0, /* tp_as_buffer */
1112 Py_TPFLAGS_DEFAULT, /* tp_flags */
1113 "GDB PendingFrame object", /* tp_doc */
1114 0, /* tp_traverse */
1115 0, /* tp_clear */
1116 0, /* tp_richcompare */
1117 0, /* tp_weaklistoffset */
1118 0, /* tp_iter */
1119 0, /* tp_iternext */
1120 pending_frame_object_methods, /* tp_methods */
1121 0, /* tp_members */
1122 0, /* tp_getset */
1123 0, /* tp_base */
1124 0, /* tp_dict */
1125 0, /* tp_descr_get */
1126 0, /* tp_descr_set */
1127 0, /* tp_dictoffset */
1128 0, /* tp_init */
1129 0, /* tp_alloc */
1130};
1131
1132static PyMethodDef unwind_info_object_methods[] =
1133{
1134 { "add_saved_register",
1135 (PyCFunction) unwind_infopy_add_saved_register,
1136 METH_VARARGS | METH_KEYWORDS,
1137 "add_saved_register (REG, VALUE) -> None\n"
1138 "Set the value of the REG in the previous frame to VALUE." },
1139 { NULL } /* Sentinel */
1140};
1141
1142PyTypeObject unwind_info_object_type =
1143{
1144 PyVarObject_HEAD_INIT (NULL, 0)
1145 "gdb.UnwindInfo", /* tp_name */
1146 sizeof (unwind_info_object), /* tp_basicsize */
1147 0, /* tp_itemsize */
1148 unwind_infopy_dealloc, /* tp_dealloc */
1149 0, /* tp_print */
1150 0, /* tp_getattr */
1151 0, /* tp_setattr */
1152 0, /* tp_compare */
1153 unwind_infopy_repr, /* tp_repr */
1154 0, /* tp_as_number */
1155 0, /* tp_as_sequence */
1156 0, /* tp_as_mapping */
1157 0, /* tp_hash */
1158 0, /* tp_call */
1159 unwind_infopy_str, /* tp_str */
1160 0, /* tp_getattro */
1161 0, /* tp_setattro */
1162 0, /* tp_as_buffer */
1163 Py_TPFLAGS_DEFAULT, /* tp_flags */
1164 "GDB UnwindInfo object", /* tp_doc */
1165 0, /* tp_traverse */
1166 0, /* tp_clear */
1167 0, /* tp_richcompare */
1168 0, /* tp_weaklistoffset */
1169 0, /* tp_iter */
1170 0, /* tp_iternext */
1171 unwind_info_object_methods, /* tp_methods */
1172 0, /* tp_members */
1173 0, /* tp_getset */
1174 0, /* tp_base */
1175 0, /* tp_dict */
1176 0, /* tp_descr_get */
1177 0, /* tp_descr_set */
1178 0, /* tp_dictoffset */
1179 0, /* tp_init */
1180 0, /* tp_alloc */
1181};