]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blame - gdb/python/py-unwind.c
libsframe: relax the assertion limit for fre_start_addr
[thirdparty/binutils-gdb.git] / gdb / python / py-unwind.c
CommitLineData
d11916aa
SS
1/* Python frame unwinder interface.
2
d01e8234 3 Copyright (C) 2015-2025 Free Software Foundation, Inc.
d11916aa
SS
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
d11916aa
SS
20#include "arch-utils.h"
21#include "frame-unwind.h"
bf31fd38 22#include "gdbsupport/gdb_obstack.h"
5b9707eb 23#include "cli/cli-cmds.h"
d11916aa 24#include "language.h"
76727919 25#include "observable.h"
d11916aa
SS
26#include "python-internal.h"
27#include "regcache.h"
28#include "valprint.h"
61e2dde2 29#include "user-regs.h"
86b35b71
AB
30#include "stack.h"
31#include "charset.h"
32#include "block.h"
33
d11916aa 34
1ef40c13
AB
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{
6cb06a8c 45 gdb_printf (file, _("Python unwinder debugging is %s.\n"), value);
1ef40c13
AB
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")
d11916aa 57
44d9b0a1
AB
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
f99b5177 69struct pending_frame_object
d11916aa
SS
70{
71 PyObject_HEAD
72
73 /* Frame we are unwinding. */
bd2b40ac 74 frame_info_ptr frame_info;
d11916aa
SS
75
76 /* Its architecture, passed by the sniffer caller. */
77 struct gdbarch *gdbarch;
f99b5177 78};
d11916aa
SS
79
80/* Saved registers array item. */
81
0c6aef22 82struct saved_reg
d11916aa 83{
0c6aef22
TT
84 saved_reg (int n, gdbpy_ref<> &&v)
85 : number (n),
86 value (std::move (v))
87 {
88 }
89
d11916aa 90 int number;
0c6aef22
TT
91 gdbpy_ref<> value;
92};
d11916aa
SS
93
94/* The data we keep for the PyUnwindInfo: pending_frame, saved registers
95 and frame ID. */
96
f99b5177 97struct unwind_info_object
d11916aa
SS
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. */
0c6aef22 108 std::vector<saved_reg> *saved_regs;
f99b5177 109};
d11916aa
SS
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
f99b5177 114struct cached_frame_info
d11916aa
SS
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
bfcfa995
PA
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];
f99b5177 134};
d11916aa 135
13fa0398 136extern PyTypeObject pending_frame_object_type
d11916aa
SS
137 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("pending_frame_object");
138
13fa0398 139extern PyTypeObject unwind_info_object_type
d11916aa
SS
140 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("unwind_info_object");
141
64826d05
AB
142/* An enum returned by pyuw_object_attribute_to_pointer, a function which
143 is used to extract an attribute from a Python object. */
d11916aa 144
64826d05 145enum class pyuw_get_attr_code
d11916aa 146{
64826d05
AB
147 /* The attribute was present, and its value was successfully extracted. */
148 ATTR_OK,
d11916aa 149
64826d05
AB
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.
d11916aa 162
64826d05
AB
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.
d11916aa 166
64826d05
AB
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
d11916aa 177pyuw_object_attribute_to_pointer (PyObject *pyo, const char *attr_name,
dda83cd7 178 CORE_ADDR *addr)
d11916aa 179{
64826d05
AB
180 if (!PyObject_HasAttrString (pyo, attr_name))
181 return pyuw_get_attr_code::ATTR_MISSING;
d11916aa 182
64826d05
AB
183 gdbpy_ref<> pyo_value (PyObject_GetAttrString (pyo, attr_name));
184 if (pyo_value == nullptr)
d11916aa 185 {
64826d05
AB
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;
d11916aa 191
64826d05
AB
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;
d11916aa 196 }
64826d05
AB
197
198 return pyuw_get_attr_code::ATTR_OK;
d11916aa
SS
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{
d11916aa 207 unwind_info_object *unwind_info = (unwind_info_object *) self;
d7e74731 208 string_file stb;
d11916aa 209
927c4e35 210 stb.printf ("Frame ID: %s", unwind_info->frame_id.to_string ().c_str ());
d11916aa 211 {
a121b7c1 212 const char *sep = "";
d11916aa 213 struct value_print_options opts;
d11916aa
SS
214
215 get_user_print_options (&opts);
d7e74731 216 stb.printf ("\nSaved registers: (");
0c6aef22 217 for (const saved_reg &reg : *unwind_info->saved_regs)
d11916aa 218 {
dda83cd7
SM
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 {
1ccb6f10 231 return gdbpy_handle_gdb_exception (nullptr, except);
dda83cd7
SM
232 }
233 }
234 else
235 stb.puts ("<BAD>)");
236 sep = ", ";
d11916aa 237 }
d7e74731 238 stb.puts (")");
d11916aa 239 }
d11916aa 240
5aee4587 241 return PyUnicode_FromString (stb.c_str ());
d11916aa
SS
242}
243
7e6af18d
AB
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
d11916aa 276/* Create UnwindInfo instance for given PendingFrame and frame ID.
44d9b0a1
AB
277 Sets Python error and returns NULL on error.
278
279 The PYO_PENDING_FRAME object must be valid. */
d11916aa
SS
280
281static PyObject *
282pyuw_create_unwind_info (PyObject *pyo_pending_frame,
dda83cd7 283 struct frame_id frame_id)
d11916aa 284{
44d9b0a1
AB
285 gdb_assert (((pending_frame_object *) pyo_pending_frame)->frame_info
286 != nullptr);
287
d11916aa 288 unwind_info_object *unwind_info
44d9b0a1 289 = PyObject_New (unwind_info_object, &unwind_info_object_type);
d11916aa 290
d11916aa
SS
291 unwind_info->frame_id = frame_id;
292 Py_INCREF (pyo_pending_frame);
293 unwind_info->pending_frame = pyo_pending_frame;
0c6aef22 294 unwind_info->saved_regs = new std::vector<saved_reg>;
d11916aa
SS
295 return (PyObject *) unwind_info;
296}
297
298/* The implementation of
299 gdb.UnwindInfo.add_saved_register (REG, VALUE) -> None. */
300
301static PyObject *
d2d62da6 302unwind_infopy_add_saved_register (PyObject *self, PyObject *args, PyObject *kw)
d11916aa
SS
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,
dda83cd7 314 "UnwindInfo instance refers to a stale PendingFrame");
d2d62da6 315 return nullptr;
d11916aa 316 }
d2d62da6
AB
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
43d5901d 324 if (!gdbpy_parse_register_id (pending_frame->gdbarch, pyo_reg_id, &regnum))
bdc8cfc1 325 return nullptr;
61e2dde2
AB
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);
736355f2 337 if (user_reg_value->lval () == lval_register)
78f2fd84 338 regnum = user_reg_value->regnum ();
61e2dde2
AB
339 if (regnum >= gdbarch_num_cooked_regs (pending_frame->gdbarch))
340 {
341 PyErr_SetString (PyExc_ValueError, "Bad register");
342 return NULL;
343 }
344 }
345
d2d62da6
AB
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
408bc9c5
TV
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)
2236c5e3 380 {
1ccb6f10 381 return gdbpy_handle_gdb_exception (nullptr, except);
2236c5e3
TV
382 }
383
d2d62da6
AB
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));
d11916aa 397
d11916aa
SS
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;
d11916aa
SS
407
408 Py_XDECREF (unwind_info->pending_frame);
0c6aef22 409 delete unwind_info->saved_regs;
d11916aa
SS
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{
bd2b40ac 419 frame_info_ptr frame = ((pending_frame_object *) self)->frame_info;
d11916aa
SS
420 const char *sp_str = NULL;
421 const char *pc_str = NULL;
422
423 if (frame == NULL)
5aee4587 424 return PyUnicode_FromString ("Stale PendingFrame instance");
a70b8144 425 try
d11916aa
SS
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 }
230d2906 430 catch (const gdb_exception &except)
d11916aa 431 {
1ccb6f10 432 return gdbpy_handle_gdb_exception (nullptr, except);
d11916aa 433 }
d11916aa 434
5aee4587 435 return PyUnicode_FromFormat ("SP=%s,PC=%s", sp_str, pc_str);
d11916aa
SS
436}
437
7e6af18d
AB
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)
aef117b7 447 return gdb_py_invalid_object_repr (self);
7e6af18d
AB
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 {
1ccb6f10 459 return gdbpy_handle_gdb_exception (nullptr, except);
7e6af18d
AB
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
d11916aa
SS
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 *
56fcb715 473pending_framepy_read_register (PyObject *self, PyObject *args, PyObject *kw)
d11916aa
SS
474{
475 pending_frame_object *pending_frame = (pending_frame_object *) self;
44d9b0a1
AB
476 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
477
d11916aa 478 PyObject *pyo_reg_id;
56fcb715
AB
479 static const char *keywords[] = { "register", nullptr };
480 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "O", keywords, &pyo_reg_id))
481 return nullptr;
d11916aa 482
56fcb715 483 int regnum;
43d5901d 484 if (!gdbpy_parse_register_id (pending_frame->gdbarch, pyo_reg_id, &regnum))
bdc8cfc1 485 return nullptr;
d11916aa 486
f3d3bbbc 487 PyObject *result = nullptr;
a70b8144 488 try
d11916aa 489 {
f3d3bbbc
TT
490 scoped_value_mark free_values;
491
33cc7d36
KB
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. */
a7952927
SM
497 value *val = value_of_register
498 (regnum, get_next_frame_sentinel_okay (pending_frame->frame_info));
d11916aa 499 if (val == NULL)
dda83cd7
SM
500 PyErr_Format (PyExc_ValueError,
501 "Cannot read register %d from frame.",
502 regnum);
f3d3bbbc
TT
503 else
504 result = value_to_value_object (val);
d11916aa 505 }
230d2906 506 catch (const gdb_exception &except)
d11916aa 507 {
1ccb6f10 508 return gdbpy_handle_gdb_exception (nullptr, except);
d11916aa 509 }
d11916aa 510
f3d3bbbc 511 return result;
d11916aa
SS
512}
513
86b35b71
AB
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 {
1ccb6f10 549 return gdbpy_handle_gdb_exception (nullptr, except);
86b35b71
AB
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 {
1ccb6f10 577 return gdbpy_handle_gdb_exception (nullptr, except);
86b35b71
AB
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 {
1ccb6f10 604 return gdbpy_handle_gdb_exception (nullptr, except);
86b35b71
AB
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 {
1ccb6f10 631 return gdbpy_handle_gdb_exception (nullptr, except);
86b35b71
AB
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 {
1ccb6f10 656 return gdbpy_handle_gdb_exception (nullptr, except);
86b35b71
AB
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 {
1ccb6f10 699 return gdbpy_handle_gdb_exception (nullptr, except);
86b35b71
AB
700 }
701
702 if (sym != nullptr)
703 return symbol_to_symbol_object (sym);
704
705 Py_RETURN_NONE;
706}
707
d11916aa
SS
708/* Implementation of
709 PendingFrame.create_unwind_info (self, frameId) -> UnwindInfo. */
710
711static PyObject *
56fcb715
AB
712pending_framepy_create_unwind_info (PyObject *self, PyObject *args,
713 PyObject *kw)
d11916aa
SS
714{
715 PyObject *pyo_frame_id;
716 CORE_ADDR sp;
717 CORE_ADDR pc;
718 CORE_ADDR special;
719
44d9b0a1
AB
720 PENDING_FRAMEPY_REQUIRE_VALID ((pending_frame_object *) self);
721
56fcb715
AB
722 static const char *keywords[] = { "frame_id", nullptr };
723 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "O", keywords,
724 &pyo_frame_id))
64826d05
AB
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)
d11916aa
SS
730 {
731 PyErr_SetString (PyExc_ValueError,
dda83cd7 732 _("frame_id should have 'sp' attribute."));
64826d05 733 return nullptr;
d11916aa 734 }
64826d05
AB
735 else if (code == pyuw_get_attr_code::ATTR_ERROR)
736 return nullptr;
d11916aa
SS
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 */
64826d05
AB
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)
d11916aa 751 return pyuw_create_unwind_info (self, frame_id_build_wild (sp));
64826d05
AB
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)
d11916aa 757 return pyuw_create_unwind_info (self, frame_id_build (sp, pc));
64826d05
AB
758
759 return pyuw_create_unwind_info (self,
760 frame_id_build_special (sp, pc, special));
d11916aa
SS
761}
762
87dbc774
AB
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
44d9b0a1
AB
770 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
771
87dbc774
AB
772 return gdbarch_to_arch_object (pending_frame->gdbarch);
773}
774
d52b8007
AB
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
44d9b0a1
AB
782 PENDING_FRAMEPY_REQUIRE_VALID (pending_frame);
783
d52b8007
AB
784 int level = frame_relative_level (pending_frame->frame_info);
785 return gdb_py_object_from_longest (level).release ();
786}
787
1239e7cf
GL
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
d11916aa
SS
811/* frame_unwind.this_id method. */
812
1239e7cf
GL
813void
814frame_unwind_python::this_id (const frame_info_ptr &this_frame,
815 void **cache_ptr,
816 struct frame_id *this_id) const
d11916aa
SS
817{
818 *this_id = ((cached_frame_info *) *cache_ptr)->frame_id;
1ef40c13 819 pyuw_debug_printf ("frame_id: %s", this_id->to_string ().c_str ());
d11916aa
SS
820}
821
822/* frame_unwind.prev_register. */
823
1239e7cf
GL
824struct value *
825frame_unwind_python::prev_register (const frame_info_ptr &this_frame,
826 void **cache_ptr, int regnum) const
d11916aa 827{
1ef40c13
AB
828 PYUW_SCOPED_DEBUG_ENTER_EXIT;
829
19ba03f4 830 cached_frame_info *cached_frame = (cached_frame_info *) *cache_ptr;
4fa847d7
AH
831 cached_reg_t *reg_info = cached_frame->reg;
832 cached_reg_t *reg_info_end = reg_info + cached_frame->reg_count;
d11916aa 833
1ef40c13
AB
834 pyuw_debug_printf ("frame=%d, reg=%d",
835 frame_relative_level (this_frame), regnum);
d11916aa
SS
836 for (; reg_info < reg_info_end; ++reg_info)
837 {
4fa847d7 838 if (regnum == reg_info->num)
ad592596 839 return frame_unwind_got_bytes (this_frame, regnum, reg_info->data);
d11916aa
SS
840 }
841
842 return frame_unwind_got_optimized (this_frame, regnum);
843}
844
845/* Frame sniffer dispatch. */
846
1239e7cf
GL
847int
848frame_unwind_python::sniff (const frame_info_ptr &this_frame,
849 void **cache_ptr) const
d11916aa 850{
1ef40c13
AB
851 PYUW_SCOPED_DEBUG_ENTER_EXIT;
852
1239e7cf 853 struct gdbarch *gdbarch = (struct gdbarch *) (this->unwind_data ());
d11916aa
SS
854 cached_frame_info *cached_frame;
855
1da5d0e6 856 gdbpy_enter enter_py (gdbarch);
c0171de6 857
1ef40c13
AB
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)));
d11916aa
SS
862
863 /* Create PendingFrame instance to pass to sniffers. */
c0171de6
TT
864 pending_frame_object *pfo = PyObject_New (pending_frame_object,
865 &pending_frame_object_type);
7780f186 866 gdbpy_ref<> pyo_pending_frame ((PyObject *) pfo);
d11916aa 867 if (pyo_pending_frame == NULL)
c0171de6
TT
868 {
869 gdbpy_print_stack ();
870 return 0;
871 }
872 pfo->gdbarch = gdbarch;
44d9b0a1 873 pfo->frame_info = nullptr;
c0171de6
TT
874 scoped_restore invalidate_frame = make_scoped_restore (&pfo->frame_info,
875 this_frame);
d11916aa
SS
876
877 /* Run unwinders. */
878 if (gdb_python_module == NULL
08235187 879 || ! PyObject_HasAttrString (gdb_python_module, "_execute_unwinders"))
d11916aa
SS
880 {
881 PyErr_SetString (PyExc_NameError,
dda83cd7
SM
882 "Installation error: gdb._execute_unwinders function "
883 "is missing");
c0171de6
TT
884 gdbpy_print_stack ();
885 return 0;
d11916aa 886 }
7780f186 887 gdbpy_ref<> pyo_execute (PyObject_GetAttrString (gdb_python_module,
08235187 888 "_execute_unwinders"));
4e317a76 889 if (pyo_execute == nullptr)
c0171de6
TT
890 {
891 gdbpy_print_stack ();
892 return 0;
893 }
894
4e317a76
SM
895 /* A (gdb.UnwindInfo, str) tuple, or None. */
896 gdbpy_ref<> pyo_execute_ret
c0171de6
TT
897 (PyObject_CallFunctionObjArgs (pyo_execute.get (),
898 pyo_pending_frame.get (), NULL));
4e317a76 899 if (pyo_execute_ret == nullptr)
c0171de6 900 {
9ccabccd
PA
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. */
6ef2312a 903 gdbpy_print_stack_or_quit ();
c0171de6
TT
904 return 0;
905 }
4e317a76 906 if (pyo_execute_ret == Py_None)
c0171de6 907 return 0;
d11916aa 908
4e317a76
SM
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
d11916aa 930 /* Received UnwindInfo, cache data. */
4e317a76 931 PyObject *pyo_unwind_info = PyTuple_GET_ITEM (pyo_execute_ret.get (), 0);
8e2ae00b
AB
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);
d11916aa
SS
935
936 {
c0171de6 937 unwind_info_object *unwind_info =
4e317a76 938 (unwind_info_object *) pyo_unwind_info;
0c6aef22 939 int reg_count = unwind_info->saved_regs->size ();
d11916aa 940
16892a03
AH
941 cached_frame
942 = ((cached_frame_info *)
943 xmalloc (sizeof (*cached_frame)
944 + reg_count * sizeof (cached_frame->reg[0])));
d11916aa
SS
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. */
0c6aef22 950 for (int i = 0; i < unwind_info->saved_regs->size (); ++i)
d11916aa 951 {
0c6aef22
TT
952 saved_reg *reg = &(*unwind_info->saved_regs)[i];
953
dda83cd7
SM
954 struct value *value = value_object_to_value (reg->value.get ());
955 size_t data_size = register_size (gdbarch, reg->number);
d11916aa 956
dda83cd7
SM
957 /* `value' validation was done before, just assert. */
958 gdb_assert (value != NULL);
d0c97917 959 gdb_assert (data_size == value->type ()->length ());
d11916aa 960
d5cebea1
PA
961 cached_reg_t *cached = new (&cached_frame->reg[i]) cached_reg_t ();
962 cached->num = reg->number;
ad592596
TJB
963 cached->data.resize (data_size);
964 gdb::array_view<const gdb_byte> contents = value->contents ();
965 cached->data.assign (contents.begin (), contents.end ());
d11916aa
SS
966 }
967 }
968
969 *cache_ptr = cached_frame;
d11916aa 970 return 1;
d11916aa
SS
971}
972
973/* Frame cache release shim. */
974
1239e7cf
GL
975void
976frame_unwind_python::dealloc_cache (frame_info *this_frame, void *cache) const
d11916aa 977{
1ef40c13 978 PYUW_SCOPED_DEBUG_ENTER_EXIT;
4fa847d7
AH
979 cached_frame_info *cached_frame = (cached_frame_info *) cache;
980
8455d262 981 for (int i = 0; i < cached_frame->reg_count; i++)
d5cebea1 982 cached_frame->reg[i].~cached_reg_t ();
4fa847d7 983
d11916aa
SS
984 xfree (cache);
985}
986
987struct pyuw_gdbarch_data_type
988{
989 /* Has the unwinder shim been prepended? */
cb275538 990 int unwinder_registered = 0;
d11916aa
SS
991};
992
cb275538 993static const registry<gdbarch>::key<pyuw_gdbarch_data_type> pyuw_gdbarch_data;
d11916aa
SS
994
995/* New inferior architecture callback: register the Python unwinders
996 intermediary. */
997
998static void
4b2f71e6 999pyuw_on_new_gdbarch (gdbarch *newarch)
d11916aa 1000{
cb275538
TT
1001 struct pyuw_gdbarch_data_type *data = pyuw_gdbarch_data.get (newarch);
1002 if (data == nullptr)
1003 data= pyuw_gdbarch_data.emplace (newarch);
d11916aa
SS
1004
1005 if (!data->unwinder_registered)
1006 {
1007 struct frame_unwind *unwinder
1239e7cf
GL
1008 = obstack_new<frame_unwind_python>
1009 (gdbarch_obstack (newarch), (const struct frame_data *) newarch);
1010
d11916aa
SS
1011 frame_unwind_prepend_unwinder (newarch, unwinder);
1012 data->unwinder_registered = 1;
1013 }
1014}
1015
8e3685bf
AB
1016/* Initialize unwind machinery. */
1017
3965bff5 1018static int CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
8e3685bf
AB
1019gdbpy_initialize_unwind (void)
1020{
4b2f71e6 1021 gdb::observers::new_architecture.attach (pyuw_on_new_gdbarch, "py-unwind");
d11916aa 1022
336bb2a1 1023 if (gdbpy_type_ready (&pending_frame_object_type) < 0)
d11916aa 1024 return -1;
d11916aa 1025
336bb2a1 1026 if (gdbpy_type_ready (&unwind_info_object_type) < 0)
d11916aa 1027 return -1;
336bb2a1
TT
1028
1029 return 0;
d11916aa
SS
1030}
1031
5fe70629 1032INIT_GDB_FILE (py_unwind)
3965bff5
AB
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
d11916aa
SS
1048static PyMethodDef pending_frame_object_methods[] =
1049{
56fcb715
AB
1050 { "read_register", (PyCFunction) pending_framepy_read_register,
1051 METH_VARARGS | METH_KEYWORDS,
d11916aa
SS
1052 "read_register (REG) -> gdb.Value\n"
1053 "Return the value of the REG in the frame." },
56fcb715
AB
1054 { "create_unwind_info", (PyCFunction) pending_framepy_create_unwind_info,
1055 METH_VARARGS | METH_KEYWORDS,
d11916aa
SS
1056 "create_unwind_info (FRAME_ID) -> gdb.UnwindInfo\n"
1057 "Construct UnwindInfo for this PendingFrame, using FRAME_ID\n"
1058 "to identify it." },
87dbc774
AB
1059 { "architecture",
1060 pending_framepy_architecture, METH_NOARGS,
1061 "architecture () -> gdb.Architecture\n"
1062 "The architecture for this PendingFrame." },
86b35b71
AB
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." },
d52b8007
AB
1086 { "level", pending_framepy_level, METH_NOARGS,
1087 "The stack level of this frame." },
d11916aa
SS
1088 {NULL} /* Sentinel */
1089};
1090
13fa0398 1091PyTypeObject pending_frame_object_type =
d11916aa
SS
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 */
7e6af18d 1102 pending_framepy_repr, /* tp_repr */
d11916aa
SS
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",
d2d62da6
AB
1135 (PyCFunction) unwind_infopy_add_saved_register,
1136 METH_VARARGS | METH_KEYWORDS,
d11916aa
SS
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
13fa0398 1142PyTypeObject unwind_info_object_type =
d11916aa
SS
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 */
7e6af18d 1153 unwind_infopy_repr, /* tp_repr */
d11916aa
SS
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 */
df4447e4 1163 Py_TPFLAGS_DEFAULT, /* tp_flags */
d11916aa
SS
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};