1 /* Gdb/Python header for private use by Python module.
3 Copyright (C) 2008-2025 Free Software Foundation, Inc.
5 This file is part of GDB.
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
20 #ifndef GDB_PYTHON_PYTHON_INTERNAL_H
21 #define GDB_PYTHON_PYTHON_INTERNAL_H
23 #include "extension.h"
24 #include "extension-priv.h"
27 /* These WITH_* macros are defined by the CPython API checker that
28 comes with the Python plugin for GCC. See:
29 https://gcc-python-plugin.readthedocs.org/en/latest/cpychecker.html
30 The checker defines a WITH_ macro for each attribute it
31 exposes. Note that we intentionally do not use
32 'cpychecker_returns_borrowed_ref' -- that idiom is forbidden in
35 #ifdef WITH_CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF_ATTRIBUTE
36 #define CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF(ARG) \
37 __attribute__ ((cpychecker_type_object_for_typedef (ARG)))
39 #define CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF(ARG)
42 #ifdef WITH_CPYCHECKER_SETS_EXCEPTION_ATTRIBUTE
43 #define CPYCHECKER_SETS_EXCEPTION __attribute__ ((cpychecker_sets_exception))
45 #define CPYCHECKER_SETS_EXCEPTION
48 #ifdef WITH_CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION_ATTRIBUTE
49 #define CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION \
50 __attribute__ ((cpychecker_negative_result_sets_exception))
52 #define CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
55 /* /usr/include/features.h on linux systems will define _POSIX_C_SOURCE
56 if it sees _GNU_SOURCE (which config.h will define).
57 pyconfig.h defines _POSIX_C_SOURCE to a different value than
58 /usr/include/features.h does causing compilation to fail.
59 To work around this, undef _POSIX_C_SOURCE before we include Python.h.
61 Same problem with _XOPEN_SOURCE. */
62 #undef _POSIX_C_SOURCE
65 /* On sparc-solaris, /usr/include/sys/feature_tests.h defines
66 _FILE_OFFSET_BITS, which pyconfig.h also defines. Same work
67 around technique as above. */
68 #undef _FILE_OFFSET_BITS
70 /* A kludge to avoid redefinition of snprintf on Windows by pyerrors.h. */
71 #if defined(_WIN32) && defined(HAVE_DECL_SNPRINTF)
72 #define HAVE_SNPRINTF 1
75 /* Another kludge to avoid compilation errors because MinGW defines
76 'hypot' to '_hypot', but the C++ headers says "using ::hypot". */
81 /* Request clean size types from Python. */
82 #define PY_SSIZE_T_CLEAN
84 /* Include the Python header files using angle brackets rather than
85 double quotes. On case-insensitive filesystems, this prevents us
86 from including our python/python.h header file. */
88 #include <frameobject.h>
91 static_assert (PY_VERSION_HEX
>= 0x03040000);
93 #define Py_TPFLAGS_CHECKTYPES 0
95 /* If Python.h does not define WITH_THREAD, then the various
96 GIL-related functions will not be defined. However,
97 PyGILState_STATE will be. */
99 #define PyGILState_Ensure() ((PyGILState_STATE) 0)
100 #define PyGILState_Release(ARG) ((void)(ARG))
101 #define PyEval_InitThreads()
102 #define PyThreadState_Swap(ARG) ((void)(ARG))
103 #define PyEval_ReleaseLock()
106 /* Python supplies HAVE_LONG_LONG and some `long long' support when it
107 is available. These defines let us handle the differences more
110 Starting with python 3.6, support for platforms without long long support
111 has been removed [1]. HAVE_LONG_LONG and PY_LONG_LONG are still defined,
112 but only for compatibility, so we no longer rely on them.
114 [1] https://github.com/python/cpython/issues/72148. */
115 #if PY_VERSION_HEX >= 0x03060000 || defined (HAVE_LONG_LONG)
117 #define GDB_PY_LL_ARG "L"
118 #define GDB_PY_LLU_ARG "K"
119 #if PY_VERSION_HEX >= 0x03060000
120 typedef long long gdb_py_longest
;
121 typedef unsigned long long gdb_py_ulongest
;
123 typedef PY_LONG_LONG gdb_py_longest
;
124 typedef unsigned PY_LONG_LONG gdb_py_ulongest
;
126 #define gdb_py_long_as_ulongest PyLong_AsUnsignedLongLong
127 #define gdb_py_long_as_long_and_overflow PyLong_AsLongLongAndOverflow
129 #else /* HAVE_LONG_LONG */
131 #define GDB_PY_LL_ARG "l"
132 #define GDB_PY_LLU_ARG "k"
133 typedef long gdb_py_longest
;
134 typedef unsigned long gdb_py_ulongest
;
135 #define gdb_py_long_as_ulongest PyLong_AsUnsignedLong
136 #define gdb_py_long_as_long_and_overflow PyLong_AsLongAndOverflow
138 #endif /* HAVE_LONG_LONG */
140 /* A template variable holding the format character (as for
141 Py_BuildValue) for a given type. */
143 struct gdbpy_method_format
{};
146 struct gdbpy_method_format
<gdb_py_longest
>
148 static constexpr char format
= GDB_PY_LL_ARG
[0];
152 struct gdbpy_method_format
<gdb_py_ulongest
>
154 static constexpr char format
= GDB_PY_LLU_ARG
[0];
158 struct gdbpy_method_format
<int>
160 static constexpr char format
= 'i';
164 struct gdbpy_method_format
<unsigned>
166 static constexpr char format
= 'I';
169 /* A helper function to compute the PyObject_CallMethod /
170 Py_BuildValue format given the argument types. */
172 template<typename
... Args
>
173 constexpr std::array
<char, sizeof... (Args
) + 1>
176 return { gdbpy_method_format
<Args
>::format
..., '\0' };
179 /* Typesafe wrapper around PyObject_CallMethod.
181 This variant accepts no arguments. */
183 static inline gdbpy_ref
<>
184 gdbpy_call_method (PyObject
*o
, const char *method
)
186 /* PyObject_CallMethod's 'method' and 'format' parameters were missing the
187 'const' qualifier before Python 3.4. */
188 return gdbpy_ref
<> (PyObject_CallMethod (o
,
189 const_cast<char *> (method
),
193 /* Typesafe wrapper around PyObject_CallMethod.
195 This variant accepts any number of arguments and automatically
196 computes the format string, ensuring that format/argument
197 mismatches are impossible. */
199 template<typename Arg
, typename
... Args
>
200 static inline gdbpy_ref
<>
201 gdbpy_call_method (PyObject
*o
, const char *method
,
202 Arg arg
, Args
... args
)
204 constexpr const auto fmt
= gdbpy_make_fmt
<Arg
, Args
...> ();
206 /* PyObject_CallMethod's 'method' and 'format' parameters were missing the
207 'const' qualifier before Python 3.4. */
208 return gdbpy_ref
<> (PyObject_CallMethod (o
,
209 const_cast<char *> (method
),
210 const_cast<char *> (fmt
.data ()),
214 /* An overload that takes a gdbpy_ref<> rather than a raw 'PyObject *'. */
216 template<typename
... Args
>
217 static inline gdbpy_ref
<>
218 gdbpy_call_method (const gdbpy_ref
<> &o
, const char *method
, Args
... args
)
220 return gdbpy_call_method (o
.get (), method
, args
...);
223 /* Poison PyObject_CallMethod. The typesafe wrapper gdbpy_call_method should be
225 #undef PyObject_CallMethod
227 # pragma GCC poison PyObject_CallMethod
229 # define PyObject_CallMethod POISONED_PyObject_CallMethod
232 /* The 'name' parameter of PyErr_NewException was missing the 'const'
233 qualifier in Python <= 3.4. Hence, we wrap it in a function to
234 avoid errors when compiled with -Werror. */
236 static inline PyObject
*
237 gdb_PyErr_NewException (const char *name
, PyObject
*base
, PyObject
*dict
)
239 return PyErr_NewException (const_cast<char *> (name
), base
, dict
);
242 #define PyErr_NewException gdb_PyErr_NewException
244 /* PySys_GetObject's 'name' parameter was missing the 'const'
245 qualifier before Python 3.4. Hence, we wrap it in a function to
246 avoid errors when compiled with -Werror. */
248 static inline PyObject
*
249 gdb_PySys_GetObject (const char *name
)
251 return PySys_GetObject (const_cast<char *> (name
));
254 #define PySys_GetObject gdb_PySys_GetObject
256 /* PySys_SetPath was deprecated in Python 3.11. Disable the deprecated
257 code for Python 3.10 and newer. */
258 #if PY_VERSION_HEX < 0x030a0000
260 /* PySys_SetPath's 'path' parameter was missing the 'const' qualifier
261 before Python 3.6. Hence, we wrap it in a function to avoid errors
262 when compiled with -Werror. */
264 # define GDB_PYSYS_SETPATH_CHAR wchar_t
267 gdb_PySys_SetPath (const GDB_PYSYS_SETPATH_CHAR
*path
)
269 PySys_SetPath (const_cast<GDB_PYSYS_SETPATH_CHAR
*> (path
));
272 #define PySys_SetPath gdb_PySys_SetPath
275 /* Wrap PyGetSetDef to allow convenient construction with string
276 literals. Unfortunately, PyGetSetDef's 'name' and 'doc' members
277 are 'char *' instead of 'const char *', meaning that in order to
278 list-initialize PyGetSetDef arrays with string literals (and
279 without the wrapping below) would require writing explicit 'char *'
280 casts. Instead, we extend PyGetSetDef and add constexpr
281 constructors that accept const 'name' and 'doc', hiding the ugly
282 casts here in a single place. */
284 struct gdb_PyGetSetDef
: PyGetSetDef
286 constexpr gdb_PyGetSetDef (const char *name_
, getter get_
, setter set_
,
287 const char *doc_
, void *closure_
)
288 : PyGetSetDef
{const_cast<char *> (name_
), get_
, set_
,
289 const_cast<char *> (doc_
), closure_
}
292 /* Alternative constructor that allows omitting the closure in list
294 constexpr gdb_PyGetSetDef (const char *name_
, getter get_
, setter set_
,
296 : gdb_PyGetSetDef
{name_
, get_
, set_
, doc_
, NULL
}
299 /* Constructor for the sentinel entries. */
300 constexpr gdb_PyGetSetDef (std::nullptr_t
)
301 : gdb_PyGetSetDef
{NULL
, NULL
, NULL
, NULL
, NULL
}
305 /* The 'keywords' parameter of PyArg_ParseTupleAndKeywords has type
306 'char **'. However, string literals are const in C++, and so to
307 avoid casting at every keyword array definition, we'll need to make
308 the keywords array an array of 'const char *'. To avoid having all
309 callers add a 'const_cast<char **>' themselves when passing such an
310 array through 'char **', we define our own version of
311 PyArg_ParseTupleAndKeywords here with a corresponding 'keywords'
312 parameter type that does the cast in a single place. (This is not
313 an overload of PyArg_ParseTupleAndKeywords in order to make it
314 clearer that we're calling our own function instead of a function
315 that exists in some newer Python version.) */
318 gdb_PyArg_ParseTupleAndKeywords (PyObject
*args
, PyObject
*kw
,
319 const char *format
, const char **keywords
, ...)
324 va_start (ap
, keywords
);
325 res
= PyArg_VaParseTupleAndKeywords (args
, kw
, format
,
326 const_cast<char **> (keywords
),
333 /* In order to be able to parse symtab_and_line_to_sal_object function
334 a real symtab_and_line structure is needed. */
337 /* Also needed to parse enum var_types. */
339 #include "breakpoint.h"
341 enum gdbpy_iter_kind
{ iter_keys
, iter_values
, iter_items
};
345 struct language_defn
;
346 struct program_space
;
350 extern int gdb_python_initialized
;
352 extern PyObject
*gdb_module
;
353 extern PyObject
*gdb_python_module
;
354 extern PyTypeObject value_object_type
355 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("value_object");
356 extern PyTypeObject block_object_type
357 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF("block_object");
358 extern PyTypeObject symbol_object_type
359 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("symbol_object");
360 extern PyTypeObject event_object_type
361 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("event_object");
362 extern PyTypeObject breakpoint_object_type
363 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("breakpoint_object");
364 extern PyTypeObject frame_object_type
365 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("frame_object");
366 extern PyTypeObject thread_object_type
367 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("thread_object");
369 /* Ensure that breakpoint_object_type is initialized and return true. If
370 breakpoint_object_type can't be initialized then set a suitable Python
371 error and return false.
373 This function needs to be called from any gdbpy_initialize_* function
374 that wants to reference breakpoint_object_type. After all the
375 gdbpy_initialize_* functions have been called then breakpoint_object_type
376 is guaranteed to have been initialized, and this function does not need
377 calling before referencing breakpoint_object_type. */
379 extern bool gdbpy_breakpoint_init_breakpoint_type ();
381 struct gdbpy_breakpoint_object
385 /* The breakpoint number according to gdb. */
388 /* The gdb breakpoint object, or NULL if the breakpoint has been
390 struct breakpoint
*bp
;
392 /* 1 is this is a FinishBreakpoint object, 0 otherwise. */
396 /* Require that BREAKPOINT be a valid breakpoint ID; throw a Python
397 exception if it is invalid. */
398 #define BPPY_REQUIRE_VALID(Breakpoint) \
400 if ((Breakpoint)->bp == NULL) \
401 return PyErr_Format (PyExc_RuntimeError, \
402 _("Breakpoint %d is invalid."), \
403 (Breakpoint)->number); \
406 /* Require that BREAKPOINT be a valid breakpoint ID; throw a Python
407 exception if it is invalid. This macro is for use in setter functions. */
408 #define BPPY_SET_REQUIRE_VALID(Breakpoint) \
410 if ((Breakpoint)->bp == NULL) \
412 PyErr_Format (PyExc_RuntimeError, _("Breakpoint %d is invalid."), \
413 (Breakpoint)->number); \
419 /* Variables used to pass information between the Breakpoint
420 constructor and the breakpoint-created hook function. */
421 extern gdbpy_breakpoint_object
*bppy_pending_object
;
428 /* The thread we represent. */
429 struct thread_info
*thread
;
431 /* The Inferior object to which this thread belongs. */
434 /* Dictionary holding user-added attributes. This is the __dict__
435 attribute of the object. */
439 struct inferior_object
;
441 extern struct cmd_list_element
*set_python_list
;
442 extern struct cmd_list_element
*show_python_list
;
444 /* extension_language_script_ops "methods". */
446 /* Return true if auto-loading Python scripts is enabled.
447 This is the extension_language_script_ops.auto_load_enabled "method". */
449 extern bool gdbpy_auto_load_enabled (const struct extension_language_defn
*);
451 /* extension_language_ops "methods". */
453 extern enum ext_lang_rc gdbpy_apply_val_pretty_printer
454 (const struct extension_language_defn
*,
456 struct ui_file
*stream
, int recurse
,
457 const struct value_print_options
*options
,
458 const struct language_defn
*language
);
459 extern void gdbpy_load_ptwrite_filter
460 (const struct extension_language_defn
*extlang
,
461 struct btrace_thread_info
*btinfo
);
462 extern enum ext_lang_bt_status gdbpy_apply_frame_filter
463 (const struct extension_language_defn
*,
464 const frame_info_ptr
&frame
, frame_filter_flags flags
,
465 enum ext_lang_frame_args args_type
,
466 struct ui_out
*out
, int frame_low
, int frame_high
);
467 extern void gdbpy_preserve_values (const struct extension_language_defn
*,
468 struct objfile
*objfile
,
469 copied_types_hash_t
&copied_types
);
470 extern enum ext_lang_bp_stop gdbpy_breakpoint_cond_says_stop
471 (const struct extension_language_defn
*, struct breakpoint
*);
472 extern int gdbpy_breakpoint_has_cond (const struct extension_language_defn
*,
473 struct breakpoint
*b
);
475 extern enum ext_lang_rc gdbpy_get_matching_xmethod_workers
476 (const struct extension_language_defn
*extlang
,
477 struct type
*obj_type
, const char *method_name
,
478 std::vector
<xmethod_worker_up
> *dm_vec
);
481 PyObject
*gdbpy_history (PyObject
*self
, PyObject
*args
);
482 PyObject
*gdbpy_add_history (PyObject
*self
, PyObject
*args
);
483 extern PyObject
*gdbpy_history_count (PyObject
*self
, PyObject
*args
);
484 PyObject
*gdbpy_convenience_variable (PyObject
*self
, PyObject
*args
);
485 PyObject
*gdbpy_set_convenience_variable (PyObject
*self
, PyObject
*args
);
486 PyObject
*gdbpy_breakpoints (PyObject
*, PyObject
*);
487 PyObject
*gdbpy_frame_stop_reason_string (PyObject
*, PyObject
*);
488 PyObject
*gdbpy_lookup_symbol (PyObject
*self
, PyObject
*args
, PyObject
*kw
);
489 PyObject
*gdbpy_lookup_global_symbol (PyObject
*self
, PyObject
*args
,
491 PyObject
*gdbpy_lookup_static_symbol (PyObject
*self
, PyObject
*args
,
493 PyObject
*gdbpy_lookup_static_symbols (PyObject
*self
, PyObject
*args
,
495 PyObject
*gdbpy_start_recording (PyObject
*self
, PyObject
*args
);
496 PyObject
*gdbpy_current_recording (PyObject
*self
, PyObject
*args
);
497 PyObject
*gdbpy_stop_recording (PyObject
*self
, PyObject
*args
);
498 PyObject
*gdbpy_newest_frame (PyObject
*self
, PyObject
*args
);
499 PyObject
*gdbpy_selected_frame (PyObject
*self
, PyObject
*args
);
500 PyObject
*gdbpy_lookup_type (PyObject
*self
, PyObject
*args
, PyObject
*kw
);
501 int gdbpy_is_field (PyObject
*obj
);
502 PyObject
*gdbpy_create_lazy_string_object (CORE_ADDR address
, long length
,
503 const char *encoding
,
505 PyObject
*gdbpy_inferiors (PyObject
*unused
, PyObject
*unused2
);
506 PyObject
*gdbpy_create_ptid_object (ptid_t ptid
);
507 PyObject
*gdbpy_selected_thread (PyObject
*self
, PyObject
*args
);
508 PyObject
*gdbpy_selected_inferior (PyObject
*self
, PyObject
*args
);
509 PyObject
*gdbpy_string_to_argv (PyObject
*self
, PyObject
*args
);
510 PyObject
*gdbpy_parameter_value (const setting
&var
);
511 gdb::unique_xmalloc_ptr
<char> gdbpy_parse_command_name
512 (const char *name
, struct cmd_list_element
***base_list
,
513 struct cmd_list_element
**start_list
,
514 struct cmd_list_element
**prefix_cmd
= nullptr);
515 PyObject
*gdbpy_register_tui_window (PyObject
*self
, PyObject
*args
,
518 PyObject
*symtab_and_line_to_sal_object (struct symtab_and_line sal
);
519 PyObject
*symtab_to_symtab_object (struct symtab
*symtab
);
520 PyObject
*symbol_to_symbol_object (struct symbol
*sym
);
521 PyObject
*block_to_block_object (const struct block
*block
,
522 struct objfile
*objfile
);
523 PyObject
*value_to_value_object (struct value
*v
);
524 PyObject
*type_to_type_object (struct type
*);
525 PyObject
*frame_info_to_frame_object (const frame_info_ptr
&frame
);
526 PyObject
*symtab_to_linetable_object (PyObject
*symtab
);
527 gdbpy_ref
<> pspace_to_pspace_object (struct program_space
*);
528 PyObject
*pspy_get_printers (PyObject
*, void *);
529 PyObject
*pspy_get_frame_filters (PyObject
*, void *);
530 PyObject
*pspy_get_frame_unwinders (PyObject
*, void *);
531 PyObject
*pspy_get_xmethods (PyObject
*, void *);
533 gdbpy_ref
<> objfile_to_objfile_object (struct objfile
*);
534 PyObject
*objfpy_get_printers (PyObject
*, void *);
535 PyObject
*objfpy_get_frame_filters (PyObject
*, void *);
536 PyObject
*objfpy_get_frame_unwinders (PyObject
*, void *);
537 PyObject
*objfpy_get_xmethods (PyObject
*, void *);
538 PyObject
*gdbpy_lookup_objfile (PyObject
*self
, PyObject
*args
, PyObject
*kw
);
540 PyObject
*gdbarch_to_arch_object (struct gdbarch
*gdbarch
);
541 PyObject
*gdbpy_all_architecture_names (PyObject
*self
, PyObject
*args
);
543 PyObject
*gdbpy_new_register_descriptor_iterator (struct gdbarch
*gdbarch
,
544 const char *group_name
);
545 PyObject
*gdbpy_new_reggroup_iterator (struct gdbarch
*gdbarch
);
547 gdbpy_ref
<thread_object
> create_thread_object (struct thread_info
*tp
);
548 gdbpy_ref
<> thread_to_thread_object (thread_info
*thr
);;
549 gdbpy_ref
<inferior_object
> inferior_to_inferior_object (inferior
*inf
);
551 PyObject
*gdbpy_buffer_to_membuf (gdb::unique_xmalloc_ptr
<gdb_byte
> buffer
,
552 CORE_ADDR address
, ULONGEST length
);
554 struct process_stratum_target
;
555 gdbpy_ref
<> target_to_connection_object (process_stratum_target
*target
);
556 PyObject
*gdbpy_connections (PyObject
*self
, PyObject
*args
);
558 const struct block
*block_object_to_block (PyObject
*obj
);
559 struct symbol
*symbol_object_to_symbol (PyObject
*obj
);
560 struct value
*value_object_to_value (PyObject
*self
);
561 struct value
*convert_value_from_python (PyObject
*obj
);
562 struct type
*type_object_to_type (PyObject
*obj
);
563 struct symtab
*symtab_object_to_symtab (PyObject
*obj
);
564 struct symtab_and_line
*sal_object_to_symtab_and_line (PyObject
*obj
);
565 frame_info_ptr
frame_object_to_frame_info (PyObject
*frame_obj
);
566 struct gdbarch
*arch_object_to_gdbarch (PyObject
*obj
);
568 extern PyObject
*gdbpy_execute_mi_command (PyObject
*self
, PyObject
*args
,
571 /* Serialize RESULTS and print it in MI format to the current_uiout.
573 This function handles the top-level results passed as a dictionary.
574 The caller is responsible for ensuring that. The values within this
575 dictionary can be a wider range of types. Handling the values of the top-level
576 dictionary is done by serialize_mi_result_1, see that function for more
579 If anything goes wrong while parsing and printing the MI output then an
582 extern void serialize_mi_results (PyObject
*results
);
584 /* Implementation of the gdb.notify_mi function. */
586 extern PyObject
*gdbpy_notify_mi (PyObject
*self
, PyObject
*args
,
589 /* Convert Python object OBJ to a program_space pointer. OBJ must be a
590 gdb.Progspace reference. Return nullptr if the gdb.Progspace is not
591 valid (see gdb.Progspace.is_valid), otherwise return the program_space
594 extern struct program_space
*progspace_object_to_program_space (PyObject
*obj
);
596 /* A class for managing the initialization, and finalization functions
597 from all Python files (e.g. gdb/python/py-*.c).
599 Within any Python file, create an instance of this class, passing in
600 the initialization function, and, optionally, the finalization
603 These functions are added to a single global list of functions, which
604 can then be called from do_start_initialization and finalize_python
605 (see python.c) to initialize all the Python files within GDB. */
607 class gdbpy_initialize_file
609 /* The type of a function that can be called just after GDB has setup the
610 Python interpreter. This function will setup any additional Python
611 state required by a particular subsystem. Return 0 if the setup was
612 successful, or return -1 if setup failed, in which case a Python
613 exception should have been raised. */
615 using gdbpy_initialize_file_ftype
= int (*) (void);
617 /* The type of a function that can be called just before GDB shuts down
618 the Python interpreter. This function can cleanup an Python state
619 that is cached within GDB, for example, if GDB is holding any
620 references to Python objects, these should be released before the
621 Python interpreter is shut down.
623 There is no error return in this case. This function is only called
624 when GDB is already shutting down. The function should make a best
625 effort to clean up, and then return. */
627 using gdbpy_finalize_file_ftype
= void (*) (void);
629 /* The type for an initialization and finalization function pair. */
631 using callback_pair_t
= std::pair
<gdbpy_initialize_file_ftype
,
632 gdbpy_finalize_file_ftype
>;
634 /* Return the vector of callbacks. The vector is defined as a static
635 variable within this function so that it will be initialized the first
636 time this function is called. This is important, as this function is
637 called as part of the global object initialization process; if the
638 vector was a static variable within this class then we could not
639 guarantee that it had been initialized before it was used. */
641 static std::vector
<callback_pair_t
> &
644 static std::vector
<callback_pair_t
> list
;
650 /* Register the initialization (INIT) and finalization (FINI) functions
651 for a Python file. See the comments on the function types above for
652 when these functions will be called.
654 Either of these functions can be nullptr, in which case no function
657 The FINI argument is optional, and defaults to nullptr (no function to
660 gdbpy_initialize_file (gdbpy_initialize_file_ftype init
,
661 gdbpy_finalize_file_ftype fini
= nullptr)
663 callbacks ().emplace_back (init
, fini
);
666 /* Run all the Python file initialize functions and return true. If any
667 of the initialize functions fails then this function returns false.
668 In the case of failure it is undefined how many of the initialize
669 functions will have been called. */
674 /* The initialize_all function should only be called once. The
675 following check reverses the global list, which will effect this
676 initialize_all call, as well as the later finalize_all call.
678 The environment variable checked here is the same as the one checked
679 in the generated init.c file. */
680 if (getenv ("GDB_REVERSE_INIT_FUNCTIONS") != nullptr)
681 std::reverse (callbacks ().begin (), callbacks ().end ());
683 for (const auto &p
: gdbpy_initialize_file::callbacks ())
685 if (p
.first
!= nullptr && p
.first () < 0)
691 /* Run all the Python file finalize functions. */
696 for (const auto &p
: gdbpy_initialize_file::callbacks ())
698 if (p
.second
!= nullptr)
704 /* Macro to simplify registering the initialization and finalization
705 functions for a Python file. */
707 #define GDBPY_INITIALIZE_FILE(INIT, ...) \
708 static gdbpy_initialize_file \
709 CONCAT(gdbpy_initialize_file_obj_, __LINE__) (INIT, ##__VA_ARGS__)
711 PyMODINIT_FUNC
gdbpy_events_mod_func ();
713 /* A wrapper for PyErr_Fetch that handles reference counting for the
715 class gdbpy_err_fetch
721 #if PY_VERSION_HEX < 0x030c0000
722 PyObject
*error_type
, *error_value
, *error_traceback
;
724 PyErr_Fetch (&error_type
, &error_value
, &error_traceback
);
725 m_error_type
.reset (error_type
);
726 m_error_value
.reset (error_value
);
727 m_error_traceback
.reset (error_traceback
);
729 /* PyErr_Fetch is deprecated in python 3.12, use PyErr_GetRaisedException
731 m_exc
.reset (PyErr_GetRaisedException ());
735 /* Call PyErr_Restore using the values stashed in this object.
736 After this call, this object is invalid and neither the to_string
737 nor restore methods may be used again. */
741 #if PY_VERSION_HEX < 0x030c0000
742 PyErr_Restore (m_error_type
.release (),
743 m_error_value
.release (),
744 m_error_traceback
.release ());
746 /* PyErr_Restore is deprecated in python 3.12, use PyErr_SetRaisedException
748 PyErr_SetRaisedException (m_exc
.release ());
752 /* Return the string representation of the exception represented by
753 this object. If the result is NULL a python error occurred, the
754 caller must clear it. */
756 gdb::unique_xmalloc_ptr
<char> to_string () const;
758 /* Return the string representation of the type of the exception
759 represented by this object. If the result is NULL a python error
760 occurred, the caller must clear it. */
762 gdb::unique_xmalloc_ptr
<char> type_to_string () const;
764 /* Return true if the stored type matches TYPE, false otherwise. */
766 bool type_matches (PyObject
*type
) const
768 gdbpy_ref
<> err_type
= this->type ();
769 return PyErr_GivenExceptionMatches (err_type
.get (), type
);
772 /* Return a new reference to the exception value object. */
774 gdbpy_ref
<> value () const
776 #if PY_VERSION_HEX < 0x030c0000
779 PyObject
*error_type
, *error_value
, *error_traceback
;
780 error_type
= m_error_type
.release ();
781 error_value
= m_error_value
.release ();
782 error_traceback
= m_error_traceback
.release ();
783 PyErr_NormalizeException (&error_type
, &error_value
, &error_traceback
);
784 m_error_type
.reset (error_type
);
785 m_error_value
.reset (error_value
);
786 m_error_traceback
.reset (error_traceback
);
789 return m_error_value
;
795 /* Return a new reference to the exception type object. */
797 gdbpy_ref
<> type () const
799 #if PY_VERSION_HEX < 0x030c0000
802 if (m_exc
.get() == nullptr)
804 return gdbpy_ref
<>::new_reference ((PyObject
*)Py_TYPE (m_exc
.get ()));
810 #if PY_VERSION_HEX < 0x030c0000
811 mutable gdbpy_ref
<> m_error_type
, m_error_value
, m_error_traceback
;
812 mutable bool m_normalized
= false;
818 /* Called before entering the Python interpreter to install the
819 current language and architecture to be used for Python values.
820 Also set the active extension language for GDB so that SIGINT's
821 are directed our way, and if necessary install the right SIGINT
827 /* Set the ambient Python architecture to GDBARCH and the language
828 to LANGUAGE. If GDBARCH is nullptr, then the architecture will
829 be computed, when needed, using get_current_arch; see the
830 get_gdbarch method. If LANGUAGE is not nullptr, then the current
831 language at time of construction will be saved (to be restored on
832 destruction), and the current language will be set to
834 explicit gdbpy_enter (struct gdbarch
*gdbarch
= nullptr,
835 const struct language_defn
*language
= nullptr);
839 DISABLE_COPY_AND_ASSIGN (gdbpy_enter
);
841 /* Return the current gdbarch, as known to the Python layer. This
842 is either python_gdbarch (which comes from the most recent call
843 to the gdbpy_enter constructor), or, if that is nullptr, the
844 result of get_current_arch. */
845 static struct gdbarch
*get_gdbarch ();
847 /* Called only during gdb shutdown. This sets python_gdbarch to an
849 static void finalize ();
853 /* The current gdbarch, according to Python. This can be
855 static struct gdbarch
*python_gdbarch
;
857 struct active_ext_lang_state
*m_previous_active
;
858 PyGILState_STATE m_state
;
859 struct gdbarch
*m_gdbarch
;
860 const struct language_defn
*m_language
;
862 /* An optional is used here because we don't want to call
863 PyErr_Fetch too early. */
864 std::optional
<gdbpy_err_fetch
> m_error
;
867 /* Like gdbpy_enter, but takes a varobj. This is a subclass just to
868 make constructor delegation a little nicer. */
869 class gdbpy_enter_varobj
: public gdbpy_enter
873 /* This is defined in varobj.c, where it can access varobj
875 gdbpy_enter_varobj (const struct varobj
*var
);
879 /* The opposite of gdb_enter: this releases the GIL around a region,
880 allowing other Python threads to run. No Python APIs may be used
881 while this is active. */
882 class gdbpy_allow_threads
886 gdbpy_allow_threads ()
887 : m_save (PyEval_SaveThread ())
889 gdb_assert (m_save
!= nullptr);
892 ~gdbpy_allow_threads ()
894 PyEval_RestoreThread (m_save
);
897 DISABLE_COPY_AND_ASSIGN (gdbpy_allow_threads
);
901 PyThreadState
*m_save
;
904 /* A helper class to save and restore the GIL, but without touching
905 the other globals that are handled by gdbpy_enter. */
912 : m_state (PyGILState_Ensure ())
918 PyGILState_Release (m_state
);
921 DISABLE_COPY_AND_ASSIGN (gdbpy_gil
);
925 PyGILState_STATE m_state
;
928 int gdbpy_print_python_errors_p (void);
929 void gdbpy_print_stack (void);
930 void gdbpy_print_stack_or_quit ();
931 [[noreturn
]] void gdbpy_handle_exception ();
933 /* A wrapper around calling 'error'. Prefixes the error message with an
934 'Error occurred in Python' string. Use this in C++ code if we spot
935 something wrong with an object returned from Python code. The prefix
936 string gives the user a hint that the mistake is within Python code,
937 rather than some other part of GDB.
939 This always calls error, and never returns. */
941 [[noreturn
]] void gdbpy_error (const char *fmt
, ...) ATTRIBUTE_PRINTF (1, 2);
943 gdbpy_ref
<> python_string_to_unicode (PyObject
*obj
);
944 gdb::unique_xmalloc_ptr
<char> unicode_to_target_string (PyObject
*unicode_str
);
945 gdb::unique_xmalloc_ptr
<char> python_string_to_target_string (PyObject
*obj
);
946 gdbpy_ref
<> python_string_to_target_python_string (PyObject
*obj
);
947 gdb::unique_xmalloc_ptr
<char> python_string_to_host_string (PyObject
*obj
);
948 gdbpy_ref
<> host_string_to_python_string (const char *str
);
949 int gdbpy_is_string (PyObject
*obj
);
950 gdb::unique_xmalloc_ptr
<char> gdbpy_obj_to_string (PyObject
*obj
);
952 int gdbpy_is_lazy_string (PyObject
*result
);
953 void gdbpy_extract_lazy_string (PyObject
*string
, CORE_ADDR
*addr
,
954 struct type
**str_type
,
956 gdb::unique_xmalloc_ptr
<char> *encoding
);
958 int gdbpy_is_value_object (PyObject
*obj
);
960 /* Note that these are declared here, and not in python.h with the
961 other pretty-printer functions, because they refer to PyObject. */
962 gdbpy_ref
<> apply_varobj_pretty_printer (PyObject
*print_obj
,
963 struct value
**replacement
,
964 struct ui_file
*stream
,
965 const value_print_options
*opts
);
966 gdbpy_ref
<> gdbpy_get_varobj_pretty_printer (struct value
*value
);
967 gdb::unique_xmalloc_ptr
<char> gdbpy_get_display_hint (PyObject
*printer
);
968 PyObject
*gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
);
970 PyObject
*gdbpy_print_options (PyObject
*self
, PyObject
*args
);
971 void gdbpy_get_print_options (value_print_options
*opts
);
972 extern const struct value_print_options
*gdbpy_current_print_options
;
974 void bpfinishpy_pre_stop_hook (struct gdbpy_breakpoint_object
*bp_obj
);
975 void bpfinishpy_post_stop_hook (struct gdbpy_breakpoint_object
*bp_obj
);
976 void bpfinishpy_pre_delete_hook (struct gdbpy_breakpoint_object
*bp_obj
);
978 extern PyObject
*gdbpy_doc_cst
;
979 extern PyObject
*gdbpy_children_cst
;
980 extern PyObject
*gdbpy_to_string_cst
;
981 extern PyObject
*gdbpy_display_hint_cst
;
982 extern PyObject
*gdbpy_enabled_cst
;
983 extern PyObject
*gdbpy_value_cst
;
985 /* Exception types. */
986 extern PyObject
*gdbpy_gdb_error
;
987 extern PyObject
*gdbpy_gdb_memory_error
;
988 extern PyObject
*gdbpy_gdberror_exc
;
990 extern void gdbpy_convert_exception (const struct gdb_exception
&)
991 CPYCHECKER_SETS_EXCEPTION
;
993 /* Use this in a 'catch' block to convert the exception E to a Python
994 exception and return value VAL to signal that an exception occurred.
995 Typically at the use site, that value will be returned immediately. */
999 gdbpy_handle_gdb_exception (T val
, const gdb_exception
&e
)
1001 gdbpy_convert_exception (e
);
1005 int get_addr_from_python (PyObject
*obj
, CORE_ADDR
*addr
)
1006 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
;
1008 gdbpy_ref
<> gdb_py_object_from_longest (LONGEST l
);
1009 gdbpy_ref
<> gdb_py_object_from_ulongest (ULONGEST l
);
1010 int gdb_py_int_as_long (PyObject
*, long *);
1012 PyObject
*gdb_py_generic_dict (PyObject
*self
, void *closure
);
1014 int gdb_pymodule_addobject (PyObject
*module
, const char *name
,
1016 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
;
1019 /* Return a Python string (str) object that represents SELF. SELF can be
1020 any object type, but should be in an "invalid" state. What "invalid"
1021 means is up to the caller. The returned string will take the form
1022 "<TYPENAME (invalid)>", without the quotes, and with TYPENAME replaced
1023 with the type of SELF. */
1025 PyObject
*gdb_py_invalid_object_repr (PyObject
*self
);
1029 std::unique_ptr
<varobj_iter
> py_varobj_get_iterator
1030 (struct varobj
*var
,
1032 const value_print_options
*opts
);
1034 /* Deleter for Py_buffer unique_ptr specialization. */
1036 struct Py_buffer_deleter
1038 void operator() (Py_buffer
*b
) const
1040 PyBuffer_Release (b
);
1044 /* A unique_ptr specialization for Py_buffer. */
1045 typedef std::unique_ptr
<Py_buffer
, Py_buffer_deleter
> Py_buffer_up
;
1047 /* Parse a register number from PYO_REG_ID and place the register number
1048 into *REG_NUM. The register is a register for GDBARCH.
1050 If a register is parsed successfully then *REG_NUM will have been
1051 updated, and true is returned. Otherwise the contents of *REG_NUM are
1052 undefined, and false is returned. When false is returned, the
1053 Python error is set.
1055 The PYO_REG_ID object can be a string, the name of the register. This
1056 is the slowest approach as GDB has to map the name to a number for each
1057 call. Alternatively PYO_REG_ID can be an internal GDB register
1058 number. This is quick but should not be encouraged as this means
1059 Python scripts are now dependent on GDB's internal register numbering.
1060 Final PYO_REG_ID can be a gdb.RegisterDescriptor object, these objects
1061 can be looked up by name once, and then cache the register number so
1062 should be as quick as using a register number. */
1064 extern bool gdbpy_parse_register_id (struct gdbarch
*gdbarch
,
1065 PyObject
*pyo_reg_id
, int *reg_num
);
1067 /* Return true if OBJ is a gdb.Architecture object, otherwise, return
1070 extern bool gdbpy_is_architecture (PyObject
*obj
);
1072 /* Return true if OBJ is a gdb.Progspace object, otherwise, return false. */
1074 extern bool gdbpy_is_progspace (PyObject
*obj
);
1076 /* Take DOC, the documentation string for a GDB command defined in Python,
1077 and return an (possibly) modified version of that same string.
1079 When a command is defined in Python, the documentation string will
1080 usually be indented based on the indentation of the surrounding Python
1081 code. However, the documentation string is a literal string, all the
1082 white-space added for indentation is included within the documentation
1085 This indentation is then included in the help text that GDB displays,
1086 which looks odd out of the context of the original Python source code.
1088 This function analyses DOC and tries to figure out what white-space
1089 within DOC was added as part of the indentation, and then removes that
1090 white-space from the copy that is returned.
1092 If the analysis of DOC fails then DOC will be returned unmodified. */
1094 extern gdb::unique_xmalloc_ptr
<char> gdbpy_fix_doc_string_indentation
1095 (gdb::unique_xmalloc_ptr
<char> doc
);
1097 /* Implement the 'print_insn' hook for Python. Disassemble an instruction
1098 whose address is ADDRESS for architecture GDBARCH. The bytes of the
1099 instruction should be read with INFO->read_memory_func as the
1100 instruction being disassembled might actually be in a buffer.
1102 Used INFO->fprintf_func to print the results of the disassembly, and
1103 return the length of the instruction in octets.
1105 If no instruction can be disassembled then return an empty value. */
1107 extern std::optional
<int> gdbpy_print_insn (struct gdbarch
*gdbarch
,
1109 disassemble_info
*info
);
1111 /* A wrapper for PyType_Ready that also automatically registers the
1112 type in the appropriate module. Returns 0 on success, -1 on error.
1113 If MOD is supplied, then the type is added to that module. If MOD
1114 is not supplied, the type name (tp_name field) must be of the form
1115 "gdb.Mumble", and the type will be added to the gdb module. */
1118 gdbpy_type_ready (PyTypeObject
*type
, PyObject
*mod
= nullptr)
1120 if (PyType_Ready (type
) < 0)
1124 gdb_assert (startswith (type
->tp_name
, "gdb."));
1127 const char *dot
= strrchr (type
->tp_name
, '.');
1128 gdb_assert (dot
!= nullptr);
1129 return gdb_pymodule_addobject (mod
, dot
+ 1, (PyObject
*) type
);
1132 /* Poison PyType_Ready. Only gdbpy_type_ready should be used, to
1133 avoid forgetting to register the type. See PR python/32163. */
1136 # pragma GCC poison PyType_Ready
1138 # define PyType_Ready POISONED_PyType_Ready
1141 /* A class to manage lifecycle of Python objects for objects that are "owned"
1142 by an objfile or a gdbarch. It keeps track of Python objects and when
1143 the "owning" object (objfile or gdbarch) is about to be freed, ensures that
1144 all Python objects "owned" by that object are properly invalidated.
1146 The actual tracking of "owned" Python objects is handled externally
1147 by storage class. Storage object is created for each owning object
1148 on demand and it is deleted when owning object is about to be freed.
1150 The storage class must provide two member types:
1152 * obj_type - the type of Python object whose lifecycle is managed.
1153 * val_type - the type of GDB structure the Python objects are
1156 It must also provide following methods:
1158 void add (obj_type *obj);
1159 void remove (obj_type *obj);
1161 Memoizing storage must in addition to method above provide:
1163 obj_type *lookup (val_type *val);
1165 Finally it must invalidate all registered Python objects upon deletion. */
1166 template <typename Storage
>
1167 class gdbpy_registry
1170 using obj_type
= typename
Storage::obj_type
;
1171 using val_type
= typename
Storage::val_type
;
1173 /* Register Python object OBJ as being "owned" by OWNER. When OWNER is
1174 about to be freed, OBJ will be invalidated. */
1175 template <typename O
>
1176 void add (O
*owner
, obj_type
*obj
) const
1178 get_storage (owner
)->add (obj
);
1181 /* Unregister Python object OBJ. OBJ will no longer be invalidated when
1182 OWNER is about to be be freed. */
1183 template <typename O
>
1184 void remove (O
*owner
, obj_type
*obj
) const
1186 get_storage (owner
)->remove (obj
);
1189 /* Lookup pre-existing Python object for given VAL. Return such object
1190 if found, otherwise return NULL. This method always returns new
1192 template <typename O
>
1193 obj_type
*lookup (O
*owner
, val_type
*val
) const
1195 obj_type
*obj
= get_storage (owner
)->lookup (val
);
1202 template<typename O
>
1203 using StorageKey
= typename registry
<O
>::template key
<Storage
>;
1205 template<typename O
>
1206 Storage
*get_storage (O
*owner
, const StorageKey
<O
> &key
) const
1208 Storage
*r
= key
.get (owner
);
1217 Storage
*get_storage (struct objfile
* objf
) const
1219 return get_storage (objf
, m_key_for_objf
);
1222 Storage
*get_storage (struct gdbarch
* arch
) const
1224 return get_storage (arch
, m_key_for_arch
);
1227 const registry
<objfile
>::key
<Storage
> m_key_for_objf
;
1228 const registry
<gdbarch
>::key
<Storage
> m_key_for_arch
;
1231 /* Default invalidator for Python objects. */
1232 template <typename P
, typename V
, V
* P::*val_slot
>
1233 struct gdbpy_default_invalidator
1235 void operator() (P
*obj
)
1237 obj
->*val_slot
= nullptr;
1241 /* A "storage" implementation suitable for temporary (on-demand) objects. */
1242 template <typename P
,
1245 typename Invalidator
= gdbpy_default_invalidator
<P
, V
, val_slot
>>
1246 class gdbpy_tracking_registry_storage
1252 void add (obj_type
*obj
)
1254 gdb_assert (obj
!= nullptr && obj
->*val_slot
!= nullptr);
1256 m_objects
.insert (obj
);
1259 void remove (obj_type
*obj
)
1261 gdb_assert (obj
!= nullptr && obj
->*val_slot
!= nullptr);
1262 gdb_assert (m_objects
.contains (obj
));
1264 m_objects
.erase (obj
);
1267 ~gdbpy_tracking_registry_storage ()
1269 Invalidator invalidate
;
1270 gdbpy_enter enter_py
;
1272 for (auto each
: m_objects
)
1278 gdb::unordered_set
<obj_type
*> m_objects
;
1281 /* A "storage" implementation suitable for memoized (interned) Python objects.
1283 Python objects are memoized (interned) temporarily, meaning that when user
1284 drops all their references the Python object is deallocated and removed
1287 template <typename P
,
1290 typename Invalidator
= gdbpy_default_invalidator
<P
, V
, val_slot
>>
1291 class gdbpy_memoizing_registry_storage
1297 void add (obj_type
*obj
)
1299 gdb_assert (obj
!= nullptr && obj
->*val_slot
!= nullptr);
1301 m_objects
[obj
->*val_slot
] = obj
;
1304 void remove (obj_type
*obj
)
1306 gdb_assert (obj
!= nullptr && obj
->*val_slot
!= nullptr);
1307 gdb_assert (m_objects
.contains (obj
->*val_slot
));
1309 m_objects
.erase (obj
->*val_slot
);
1312 obj_type
*lookup (val_type
*val
) const
1314 auto result
= m_objects
.find (val
);
1315 if (result
!= m_objects
.end ())
1316 return result
->second
;
1321 ~gdbpy_memoizing_registry_storage ()
1323 Invalidator invalidate
;
1324 gdbpy_enter enter_py
;
1326 for (auto each
: m_objects
)
1327 invalidate (each
.second
);
1332 gdb::unordered_map
<val_type
*, obj_type
*> m_objects
;
1335 #endif /* GDB_PYTHON_PYTHON_INTERNAL_H */