1 /* Gdb/Python header for private use by Python module.
3 Copyright (C) 2008-2024 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 PYTHON_PYTHON_INTERNAL_H
21 #define PYTHON_PYTHON_INTERNAL_H
23 #include "extension.h"
24 #include "extension-priv.h"
26 /* These WITH_* macros are defined by the CPython API checker that
27 comes with the Python plugin for GCC. See:
28 https://gcc-python-plugin.readthedocs.org/en/latest/cpychecker.html
29 The checker defines a WITH_ macro for each attribute it
30 exposes. Note that we intentionally do not use
31 'cpychecker_returns_borrowed_ref' -- that idiom is forbidden in
34 #ifdef WITH_CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF_ATTRIBUTE
35 #define CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF(ARG) \
36 __attribute__ ((cpychecker_type_object_for_typedef (ARG)))
38 #define CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF(ARG)
41 #ifdef WITH_CPYCHECKER_SETS_EXCEPTION_ATTRIBUTE
42 #define CPYCHECKER_SETS_EXCEPTION __attribute__ ((cpychecker_sets_exception))
44 #define CPYCHECKER_SETS_EXCEPTION
47 #ifdef WITH_CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION_ATTRIBUTE
48 #define CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION \
49 __attribute__ ((cpychecker_negative_result_sets_exception))
51 #define CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
54 /* /usr/include/features.h on linux systems will define _POSIX_C_SOURCE
55 if it sees _GNU_SOURCE (which config.h will define).
56 pyconfig.h defines _POSIX_C_SOURCE to a different value than
57 /usr/include/features.h does causing compilation to fail.
58 To work around this, undef _POSIX_C_SOURCE before we include Python.h.
60 Same problem with _XOPEN_SOURCE. */
61 #undef _POSIX_C_SOURCE
64 /* On sparc-solaris, /usr/include/sys/feature_tests.h defines
65 _FILE_OFFSET_BITS, which pyconfig.h also defines. Same work
66 around technique as above. */
67 #undef _FILE_OFFSET_BITS
69 /* A kludge to avoid redefinition of snprintf on Windows by pyerrors.h. */
70 #if defined(_WIN32) && defined(HAVE_DECL_SNPRINTF)
71 #define HAVE_SNPRINTF 1
74 /* Another kludge to avoid compilation errors because MinGW defines
75 'hypot' to '_hypot', but the C++ headers says "using ::hypot". */
80 /* Request clean size types from Python. */
81 #define PY_SSIZE_T_CLEAN
83 /* Include the Python header files using angle brackets rather than
84 double quotes. On case-insensitive filesystems, this prevents us
85 from including our python/python.h header file. */
87 #include <frameobject.h>
90 #define Py_TPFLAGS_CHECKTYPES 0
92 /* If Python.h does not define WITH_THREAD, then the various
93 GIL-related functions will not be defined. However,
94 PyGILState_STATE will be. */
96 #define PyGILState_Ensure() ((PyGILState_STATE) 0)
97 #define PyGILState_Release(ARG) ((void)(ARG))
98 #define PyEval_InitThreads()
99 #define PyThreadState_Swap(ARG) ((void)(ARG))
100 #define PyEval_ReleaseLock()
103 /* Python supplies HAVE_LONG_LONG and some `long long' support when it
104 is available. These defines let us handle the differences more
107 Starting with python 3.6, support for platforms without long long support
108 has been removed [1]. HAVE_LONG_LONG and PY_LONG_LONG are still defined,
109 but only for compatibility, so we no longer rely on them.
111 [1] https://github.com/python/cpython/issues/72148. */
112 #if PY_VERSION_HEX >= 0x03060000 || defined (HAVE_LONG_LONG)
114 #define GDB_PY_LL_ARG "L"
115 #define GDB_PY_LLU_ARG "K"
116 #if PY_VERSION_HEX >= 0x03060000
117 typedef long long gdb_py_longest
;
118 typedef unsigned long long gdb_py_ulongest
;
120 typedef PY_LONG_LONG gdb_py_longest
;
121 typedef unsigned PY_LONG_LONG gdb_py_ulongest
;
123 #define gdb_py_long_as_ulongest PyLong_AsUnsignedLongLong
124 #define gdb_py_long_as_long_and_overflow PyLong_AsLongLongAndOverflow
126 #else /* HAVE_LONG_LONG */
128 #define GDB_PY_LL_ARG "l"
129 #define GDB_PY_LLU_ARG "k"
130 typedef long gdb_py_longest
;
131 typedef unsigned long gdb_py_ulongest
;
132 #define gdb_py_long_as_ulongest PyLong_AsUnsignedLong
133 #define gdb_py_long_as_long_and_overflow PyLong_AsLongAndOverflow
135 #endif /* HAVE_LONG_LONG */
137 #if PY_VERSION_HEX < 0x03020000
138 typedef long Py_hash_t
;
141 /* PyMem_RawMalloc appeared in Python 3.4. For earlier versions, we can just
142 fall back to PyMem_Malloc. */
144 #if PY_VERSION_HEX < 0x03040000
145 #define PyMem_RawMalloc PyMem_Malloc
148 /* A template variable holding the format character (as for
149 Py_BuildValue) for a given type. */
151 struct gdbpy_method_format
{};
154 struct gdbpy_method_format
<gdb_py_longest
>
156 static constexpr char format
= GDB_PY_LL_ARG
[0];
160 struct gdbpy_method_format
<gdb_py_ulongest
>
162 static constexpr char format
= GDB_PY_LLU_ARG
[0];
166 struct gdbpy_method_format
<int>
168 static constexpr char format
= 'i';
172 struct gdbpy_method_format
<unsigned>
174 static constexpr char format
= 'I';
177 /* A helper function to compute the PyObject_CallMethod /
178 Py_BuildValue format given the argument types. */
180 template<typename
... Args
>
181 constexpr std::array
<char, sizeof... (Args
) + 1>
184 return { gdbpy_method_format
<Args
>::format
..., '\0' };
187 /* Typesafe wrapper around PyObject_CallMethod.
189 This variant accepts no arguments. */
191 static inline gdbpy_ref
<>
192 gdbpy_call_method (PyObject
*o
, const char *method
)
194 /* PyObject_CallMethod's 'method' and 'format' parameters were missing the
195 'const' qualifier before Python 3.4. */
196 return gdbpy_ref
<> (PyObject_CallMethod (o
,
197 const_cast<char *> (method
),
201 /* Typesafe wrapper around PyObject_CallMethod.
203 This variant accepts any number of arguments and automatically
204 computes the format string, ensuring that format/argument
205 mismatches are impossible. */
207 template<typename Arg
, typename
... Args
>
208 static inline gdbpy_ref
<>
209 gdbpy_call_method (PyObject
*o
, const char *method
,
210 Arg arg
, Args
... args
)
212 constexpr const auto fmt
= gdbpy_make_fmt
<Arg
, Args
...> ();
214 /* PyObject_CallMethod's 'method' and 'format' parameters were missing the
215 'const' qualifier before Python 3.4. */
216 return gdbpy_ref
<> (PyObject_CallMethod (o
,
217 const_cast<char *> (method
),
218 const_cast<char *> (fmt
.data ()),
222 /* An overload that takes a gdbpy_ref<> rather than a raw 'PyObject *'. */
224 template<typename
... Args
>
225 static inline gdbpy_ref
<>
226 gdbpy_call_method (const gdbpy_ref
<> &o
, const char *method
, Args
... args
)
228 return gdbpy_call_method (o
.get (), method
, args
...);
231 /* Poison PyObject_CallMethod. The typesafe wrapper gdbpy_call_method should be
233 #undef PyObject_CallMethod
235 # pragma GCC poison PyObject_CallMethod
237 # define PyObject_CallMethod POISONED_PyObject_CallMethod
240 /* The 'name' parameter of PyErr_NewException was missing the 'const'
241 qualifier in Python <= 3.4. Hence, we wrap it in a function to
242 avoid errors when compiled with -Werror. */
244 static inline PyObject
*
245 gdb_PyErr_NewException (const char *name
, PyObject
*base
, PyObject
*dict
)
247 return PyErr_NewException (const_cast<char *> (name
), base
, dict
);
250 #define PyErr_NewException gdb_PyErr_NewException
252 /* PySys_GetObject's 'name' parameter was missing the 'const'
253 qualifier before Python 3.4. Hence, we wrap it in a function to
254 avoid errors when compiled with -Werror. */
256 static inline PyObject
*
257 gdb_PySys_GetObject (const char *name
)
259 return PySys_GetObject (const_cast<char *> (name
));
262 #define PySys_GetObject gdb_PySys_GetObject
264 /* PySys_SetPath was deprecated in Python 3.11. Disable the deprecated
265 code for Python 3.10 and newer. */
266 #if PY_VERSION_HEX < 0x030a0000
268 /* PySys_SetPath's 'path' parameter was missing the 'const' qualifier
269 before Python 3.6. Hence, we wrap it in a function to avoid errors
270 when compiled with -Werror. */
272 # define GDB_PYSYS_SETPATH_CHAR wchar_t
275 gdb_PySys_SetPath (const GDB_PYSYS_SETPATH_CHAR
*path
)
277 PySys_SetPath (const_cast<GDB_PYSYS_SETPATH_CHAR
*> (path
));
280 #define PySys_SetPath gdb_PySys_SetPath
283 /* Wrap PyGetSetDef to allow convenient construction with string
284 literals. Unfortunately, PyGetSetDef's 'name' and 'doc' members
285 are 'char *' instead of 'const char *', meaning that in order to
286 list-initialize PyGetSetDef arrays with string literals (and
287 without the wrapping below) would require writing explicit 'char *'
288 casts. Instead, we extend PyGetSetDef and add constexpr
289 constructors that accept const 'name' and 'doc', hiding the ugly
290 casts here in a single place. */
292 struct gdb_PyGetSetDef
: PyGetSetDef
294 constexpr gdb_PyGetSetDef (const char *name_
, getter get_
, setter set_
,
295 const char *doc_
, void *closure_
)
296 : PyGetSetDef
{const_cast<char *> (name_
), get_
, set_
,
297 const_cast<char *> (doc_
), closure_
}
300 /* Alternative constructor that allows omitting the closure in list
302 constexpr gdb_PyGetSetDef (const char *name_
, getter get_
, setter set_
,
304 : gdb_PyGetSetDef
{name_
, get_
, set_
, doc_
, NULL
}
307 /* Constructor for the sentinel entries. */
308 constexpr gdb_PyGetSetDef (std::nullptr_t
)
309 : gdb_PyGetSetDef
{NULL
, NULL
, NULL
, NULL
, NULL
}
313 /* The 'keywords' parameter of PyArg_ParseTupleAndKeywords has type
314 'char **'. However, string literals are const in C++, and so to
315 avoid casting at every keyword array definition, we'll need to make
316 the keywords array an array of 'const char *'. To avoid having all
317 callers add a 'const_cast<char **>' themselves when passing such an
318 array through 'char **', we define our own version of
319 PyArg_ParseTupleAndKeywords here with a corresponding 'keywords'
320 parameter type that does the cast in a single place. (This is not
321 an overload of PyArg_ParseTupleAndKeywords in order to make it
322 clearer that we're calling our own function instead of a function
323 that exists in some newer Python version.) */
326 gdb_PyArg_ParseTupleAndKeywords (PyObject
*args
, PyObject
*kw
,
327 const char *format
, const char **keywords
, ...)
332 va_start (ap
, keywords
);
333 res
= PyArg_VaParseTupleAndKeywords (args
, kw
, format
,
334 const_cast<char **> (keywords
),
341 /* In order to be able to parse symtab_and_line_to_sal_object function
342 a real symtab_and_line structure is needed. */
345 /* Also needed to parse enum var_types. */
347 #include "breakpoint.h"
349 enum gdbpy_iter_kind
{ iter_keys
, iter_values
, iter_items
};
353 struct language_defn
;
354 struct program_space
;
358 extern int gdb_python_initialized
;
360 extern PyObject
*gdb_module
;
361 extern PyObject
*gdb_python_module
;
362 extern PyTypeObject value_object_type
363 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("value_object");
364 extern PyTypeObject block_object_type
365 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF("block_object");
366 extern PyTypeObject symbol_object_type
367 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("symbol_object");
368 extern PyTypeObject event_object_type
369 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("event_object");
370 extern PyTypeObject breakpoint_object_type
371 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("breakpoint_object");
372 extern PyTypeObject frame_object_type
373 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("frame_object");
374 extern PyTypeObject thread_object_type
375 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("thread_object");
377 /* Ensure that breakpoint_object_type is initialized and return true. If
378 breakpoint_object_type can't be initialized then set a suitable Python
379 error and return false.
381 This function needs to be called from any gdbpy_initialize_* function
382 that wants to reference breakpoint_object_type. After all the
383 gdbpy_initialize_* functions have been called then breakpoint_object_type
384 is guaranteed to have been initialized, and this function does not need
385 calling before referencing breakpoint_object_type. */
387 extern bool gdbpy_breakpoint_init_breakpoint_type ();
389 struct gdbpy_breakpoint_object
393 /* The breakpoint number according to gdb. */
396 /* The gdb breakpoint object, or NULL if the breakpoint has been
398 struct breakpoint
*bp
;
400 /* 1 is this is a FinishBreakpoint object, 0 otherwise. */
404 /* Require that BREAKPOINT be a valid breakpoint ID; throw a Python
405 exception if it is invalid. */
406 #define BPPY_REQUIRE_VALID(Breakpoint) \
408 if ((Breakpoint)->bp == NULL) \
409 return PyErr_Format (PyExc_RuntimeError, \
410 _("Breakpoint %d is invalid."), \
411 (Breakpoint)->number); \
414 /* Require that BREAKPOINT be a valid breakpoint ID; throw a Python
415 exception if it is invalid. This macro is for use in setter functions. */
416 #define BPPY_SET_REQUIRE_VALID(Breakpoint) \
418 if ((Breakpoint)->bp == NULL) \
420 PyErr_Format (PyExc_RuntimeError, _("Breakpoint %d is invalid."), \
421 (Breakpoint)->number); \
427 /* Variables used to pass information between the Breakpoint
428 constructor and the breakpoint-created hook function. */
429 extern gdbpy_breakpoint_object
*bppy_pending_object
;
436 /* The thread we represent. */
437 struct thread_info
*thread
;
439 /* The Inferior object to which this thread belongs. */
442 /* Dictionary holding user-added attributes. This is the __dict__
443 attribute of the object. */
447 struct inferior_object
;
449 extern struct cmd_list_element
*set_python_list
;
450 extern struct cmd_list_element
*show_python_list
;
452 /* extension_language_script_ops "methods". */
454 /* Return true if auto-loading Python scripts is enabled.
455 This is the extension_language_script_ops.auto_load_enabled "method". */
457 extern bool gdbpy_auto_load_enabled (const struct extension_language_defn
*);
459 /* extension_language_ops "methods". */
461 extern enum ext_lang_rc gdbpy_apply_val_pretty_printer
462 (const struct extension_language_defn
*,
464 struct ui_file
*stream
, int recurse
,
465 const struct value_print_options
*options
,
466 const struct language_defn
*language
);
467 extern void gdbpy_load_ptwrite_filter
468 (const struct extension_language_defn
*extlang
,
469 struct btrace_thread_info
*btinfo
);
470 extern enum ext_lang_bt_status gdbpy_apply_frame_filter
471 (const struct extension_language_defn
*,
472 const frame_info_ptr
&frame
, frame_filter_flags flags
,
473 enum ext_lang_frame_args args_type
,
474 struct ui_out
*out
, int frame_low
, int frame_high
);
475 extern void gdbpy_preserve_values (const struct extension_language_defn
*,
476 struct objfile
*objfile
,
477 htab_t copied_types
);
478 extern enum ext_lang_bp_stop gdbpy_breakpoint_cond_says_stop
479 (const struct extension_language_defn
*, struct breakpoint
*);
480 extern int gdbpy_breakpoint_has_cond (const struct extension_language_defn
*,
481 struct breakpoint
*b
);
483 extern enum ext_lang_rc gdbpy_get_matching_xmethod_workers
484 (const struct extension_language_defn
*extlang
,
485 struct type
*obj_type
, const char *method_name
,
486 std::vector
<xmethod_worker_up
> *dm_vec
);
489 PyObject
*gdbpy_history (PyObject
*self
, PyObject
*args
);
490 PyObject
*gdbpy_add_history (PyObject
*self
, PyObject
*args
);
491 extern PyObject
*gdbpy_history_count (PyObject
*self
, PyObject
*args
);
492 PyObject
*gdbpy_convenience_variable (PyObject
*self
, PyObject
*args
);
493 PyObject
*gdbpy_set_convenience_variable (PyObject
*self
, PyObject
*args
);
494 PyObject
*gdbpy_breakpoints (PyObject
*, PyObject
*);
495 PyObject
*gdbpy_frame_stop_reason_string (PyObject
*, PyObject
*);
496 PyObject
*gdbpy_lookup_symbol (PyObject
*self
, PyObject
*args
, PyObject
*kw
);
497 PyObject
*gdbpy_lookup_global_symbol (PyObject
*self
, PyObject
*args
,
499 PyObject
*gdbpy_lookup_static_symbol (PyObject
*self
, PyObject
*args
,
501 PyObject
*gdbpy_lookup_static_symbols (PyObject
*self
, PyObject
*args
,
503 PyObject
*gdbpy_start_recording (PyObject
*self
, PyObject
*args
);
504 PyObject
*gdbpy_current_recording (PyObject
*self
, PyObject
*args
);
505 PyObject
*gdbpy_stop_recording (PyObject
*self
, PyObject
*args
);
506 PyObject
*gdbpy_newest_frame (PyObject
*self
, PyObject
*args
);
507 PyObject
*gdbpy_selected_frame (PyObject
*self
, PyObject
*args
);
508 PyObject
*gdbpy_lookup_type (PyObject
*self
, PyObject
*args
, PyObject
*kw
);
509 int gdbpy_is_field (PyObject
*obj
);
510 PyObject
*gdbpy_create_lazy_string_object (CORE_ADDR address
, long length
,
511 const char *encoding
,
513 PyObject
*gdbpy_inferiors (PyObject
*unused
, PyObject
*unused2
);
514 PyObject
*gdbpy_create_ptid_object (ptid_t ptid
);
515 PyObject
*gdbpy_selected_thread (PyObject
*self
, PyObject
*args
);
516 PyObject
*gdbpy_selected_inferior (PyObject
*self
, PyObject
*args
);
517 PyObject
*gdbpy_string_to_argv (PyObject
*self
, PyObject
*args
);
518 PyObject
*gdbpy_parameter_value (const setting
&var
);
519 gdb::unique_xmalloc_ptr
<char> gdbpy_parse_command_name
520 (const char *name
, struct cmd_list_element
***base_list
,
521 struct cmd_list_element
**start_list
);
522 PyObject
*gdbpy_register_tui_window (PyObject
*self
, PyObject
*args
,
525 PyObject
*symtab_and_line_to_sal_object (struct symtab_and_line sal
);
526 PyObject
*symtab_to_symtab_object (struct symtab
*symtab
);
527 PyObject
*symbol_to_symbol_object (struct symbol
*sym
);
528 PyObject
*block_to_block_object (const struct block
*block
,
529 struct objfile
*objfile
);
530 PyObject
*value_to_value_object (struct value
*v
);
531 PyObject
*type_to_type_object (struct type
*);
532 PyObject
*frame_info_to_frame_object (const frame_info_ptr
&frame
);
533 PyObject
*symtab_to_linetable_object (PyObject
*symtab
);
534 gdbpy_ref
<> pspace_to_pspace_object (struct program_space
*);
535 PyObject
*pspy_get_printers (PyObject
*, void *);
536 PyObject
*pspy_get_frame_filters (PyObject
*, void *);
537 PyObject
*pspy_get_frame_unwinders (PyObject
*, void *);
538 PyObject
*pspy_get_xmethods (PyObject
*, void *);
540 gdbpy_ref
<> objfile_to_objfile_object (struct objfile
*);
541 PyObject
*objfpy_get_printers (PyObject
*, void *);
542 PyObject
*objfpy_get_frame_filters (PyObject
*, void *);
543 PyObject
*objfpy_get_frame_unwinders (PyObject
*, void *);
544 PyObject
*objfpy_get_xmethods (PyObject
*, void *);
545 PyObject
*gdbpy_lookup_objfile (PyObject
*self
, PyObject
*args
, PyObject
*kw
);
547 PyObject
*gdbarch_to_arch_object (struct gdbarch
*gdbarch
);
548 PyObject
*gdbpy_all_architecture_names (PyObject
*self
, PyObject
*args
);
550 PyObject
*gdbpy_new_register_descriptor_iterator (struct gdbarch
*gdbarch
,
551 const char *group_name
);
552 PyObject
*gdbpy_new_reggroup_iterator (struct gdbarch
*gdbarch
);
554 gdbpy_ref
<thread_object
> create_thread_object (struct thread_info
*tp
);
555 gdbpy_ref
<> thread_to_thread_object (thread_info
*thr
);;
556 gdbpy_ref
<inferior_object
> inferior_to_inferior_object (inferior
*inf
);
558 PyObject
*gdbpy_buffer_to_membuf (gdb::unique_xmalloc_ptr
<gdb_byte
> buffer
,
559 CORE_ADDR address
, ULONGEST length
);
561 struct process_stratum_target
;
562 gdbpy_ref
<> target_to_connection_object (process_stratum_target
*target
);
563 PyObject
*gdbpy_connections (PyObject
*self
, PyObject
*args
);
565 const struct block
*block_object_to_block (PyObject
*obj
);
566 struct symbol
*symbol_object_to_symbol (PyObject
*obj
);
567 struct value
*value_object_to_value (PyObject
*self
);
568 struct value
*convert_value_from_python (PyObject
*obj
);
569 struct type
*type_object_to_type (PyObject
*obj
);
570 struct symtab
*symtab_object_to_symtab (PyObject
*obj
);
571 struct symtab_and_line
*sal_object_to_symtab_and_line (PyObject
*obj
);
572 frame_info_ptr
frame_object_to_frame_info (PyObject
*frame_obj
);
573 struct gdbarch
*arch_object_to_gdbarch (PyObject
*obj
);
575 extern PyObject
*gdbpy_execute_mi_command (PyObject
*self
, PyObject
*args
,
578 /* Serialize RESULTS and print it in MI format to the current_uiout.
580 This function handles the top-level results passed as a dictionary.
581 The caller is responsible for ensuring that. The values within this
582 dictionary can be a wider range of types. Handling the values of the top-level
583 dictionary is done by serialize_mi_result_1, see that function for more
586 If anything goes wrong while parsing and printing the MI output then an
589 extern void serialize_mi_results (PyObject
*results
);
591 /* Implementation of the gdb.notify_mi function. */
593 extern PyObject
*gdbpy_notify_mi (PyObject
*self
, PyObject
*args
,
596 /* Convert Python object OBJ to a program_space pointer. OBJ must be a
597 gdb.Progspace reference. Return nullptr if the gdb.Progspace is not
598 valid (see gdb.Progspace.is_valid), otherwise return the program_space
601 extern struct program_space
*progspace_object_to_program_space (PyObject
*obj
);
603 /* A class for managing the initialization, and finalization functions
604 from all Python files (e.g. gdb/python/py-*.c).
606 Within any Python file, create an instance of this class, passing in
607 the initialization function, and, optionally, the finalization
610 These functions are added to a single global list of functions, which
611 can then be called from do_start_initialization and finalize_python
612 (see python.c) to initialize all the Python files within GDB. */
614 class gdbpy_initialize_file
616 /* The type of a function that can be called just after GDB has setup the
617 Python interpreter. This function will setup any additional Python
618 state required by a particular subsystem. Return 0 if the setup was
619 successful, or return -1 if setup failed, in which case a Python
620 exception should have been raised. */
622 using gdbpy_initialize_file_ftype
= int (*) (void);
624 /* The type of a function that can be called just before GDB shuts down
625 the Python interpreter. This function can cleanup an Python state
626 that is cached within GDB, for example, if GDB is holding any
627 references to Python objects, these should be released before the
628 Python interpreter is shut down.
630 There is no error return in this case. This function is only called
631 when GDB is already shutting down. The function should make a best
632 effort to clean up, and then return. */
634 using gdbpy_finalize_file_ftype
= void (*) (void);
636 /* The type for an initialization and finalization function pair. */
638 using callback_pair_t
= std::pair
<gdbpy_initialize_file_ftype
,
639 gdbpy_finalize_file_ftype
>;
641 /* Return the vector of callbacks. The vector is defined as a static
642 variable within this function so that it will be initialized the first
643 time this function is called. This is important, as this function is
644 called as part of the global object initialization process; if the
645 vector was a static variable within this class then we could not
646 guarantee that it had been initialized before it was used. */
648 static std::vector
<callback_pair_t
> &
651 static std::vector
<callback_pair_t
> list
;
657 /* Register the initialization (INIT) and finalization (FINI) functions
658 for a Python file. See the comments on the function types above for
659 when these functions will be called.
661 Either of these functions can be nullptr, in which case no function
664 The FINI argument is optional, and defaults to nullptr (no function to
667 gdbpy_initialize_file (gdbpy_initialize_file_ftype init
,
668 gdbpy_finalize_file_ftype fini
= nullptr)
670 callbacks ().emplace_back (init
, fini
);
673 /* Run all the Python file initialize functions and return true. If any
674 of the initialize functions fails then this function returns false.
675 In the case of failure it is undefined how many of the initialize
676 functions will have been called. */
681 /* The initialize_all function should only be called once. The
682 following check reverses the global list, which will effect this
683 initialize_all call, as well as the later finalize_all call.
685 The environment variable checked here is the same as the one checked
686 in the generated init.c file. */
687 if (getenv ("GDB_REVERSE_INIT_FUNCTIONS") != nullptr)
688 std::reverse (callbacks ().begin (), callbacks ().end ());
690 for (const auto &p
: gdbpy_initialize_file::callbacks ())
692 if (p
.first
!= nullptr && p
.first () < 0)
698 /* Run all the Python file finalize functions. */
703 for (const auto &p
: gdbpy_initialize_file::callbacks ())
705 if (p
.second
!= nullptr)
711 /* Macro to simplify registering the initialization and finalization
712 functions for a Python file. */
714 #define GDBPY_INITIALIZE_FILE(INIT, ...) \
715 static gdbpy_initialize_file \
716 CONCAT(gdbpy_initialize_file_obj_, __LINE__) (INIT, ##__VA_ARGS__)
718 PyMODINIT_FUNC
gdbpy_events_mod_func ();
720 /* A wrapper for PyErr_Fetch that handles reference counting for the
722 class gdbpy_err_fetch
728 #if PY_VERSION_HEX < 0x030c0000
729 PyObject
*error_type
, *error_value
, *error_traceback
;
731 PyErr_Fetch (&error_type
, &error_value
, &error_traceback
);
732 m_error_type
.reset (error_type
);
733 m_error_value
.reset (error_value
);
734 m_error_traceback
.reset (error_traceback
);
736 /* PyErr_Fetch is deprecated in python 3.12, use PyErr_GetRaisedException
738 m_exc
.reset (PyErr_GetRaisedException ());
742 /* Call PyErr_Restore using the values stashed in this object.
743 After this call, this object is invalid and neither the to_string
744 nor restore methods may be used again. */
748 #if PY_VERSION_HEX < 0x030c0000
749 PyErr_Restore (m_error_type
.release (),
750 m_error_value
.release (),
751 m_error_traceback
.release ());
753 /* PyErr_Restore is deprecated in python 3.12, use PyErr_SetRaisedException
755 PyErr_SetRaisedException (m_exc
.release ());
759 /* Return the string representation of the exception represented by
760 this object. If the result is NULL a python error occurred, the
761 caller must clear it. */
763 gdb::unique_xmalloc_ptr
<char> to_string () const;
765 /* Return the string representation of the type of the exception
766 represented by this object. If the result is NULL a python error
767 occurred, the caller must clear it. */
769 gdb::unique_xmalloc_ptr
<char> type_to_string () const;
771 /* Return true if the stored type matches TYPE, false otherwise. */
773 bool type_matches (PyObject
*type
) const
775 gdbpy_ref
<> err_type
= this->type ();
776 return PyErr_GivenExceptionMatches (err_type
.get (), type
);
779 /* Return a new reference to the exception value object. */
781 gdbpy_ref
<> value () const
783 #if PY_VERSION_HEX < 0x030c0000
786 PyObject
*error_type
, *error_value
, *error_traceback
;
787 error_type
= m_error_type
.release ();
788 error_value
= m_error_value
.release ();
789 error_traceback
= m_error_traceback
.release ();
790 PyErr_NormalizeException (&error_type
, &error_value
, &error_traceback
);
791 m_error_type
.reset (error_type
);
792 m_error_value
.reset (error_value
);
793 m_error_traceback
.reset (error_traceback
);
796 return m_error_value
;
802 /* Return a new reference to the exception type object. */
804 gdbpy_ref
<> type () const
806 #if PY_VERSION_HEX < 0x030c0000
809 if (m_exc
.get() == nullptr)
811 return gdbpy_ref
<>::new_reference ((PyObject
*)Py_TYPE (m_exc
.get ()));
817 #if PY_VERSION_HEX < 0x030c0000
818 mutable gdbpy_ref
<> m_error_type
, m_error_value
, m_error_traceback
;
819 mutable bool m_normalized
= false;
825 /* Called before entering the Python interpreter to install the
826 current language and architecture to be used for Python values.
827 Also set the active extension language for GDB so that SIGINT's
828 are directed our way, and if necessary install the right SIGINT
834 /* Set the ambient Python architecture to GDBARCH and the language
835 to LANGUAGE. If GDBARCH is nullptr, then the architecture will
836 be computed, when needed, using get_current_arch; see the
837 get_gdbarch method. If LANGUAGE is not nullptr, then the current
838 language at time of construction will be saved (to be restored on
839 destruction), and the current language will be set to
841 explicit gdbpy_enter (struct gdbarch
*gdbarch
= nullptr,
842 const struct language_defn
*language
= nullptr);
846 DISABLE_COPY_AND_ASSIGN (gdbpy_enter
);
848 /* Return the current gdbarch, as known to the Python layer. This
849 is either python_gdbarch (which comes from the most recent call
850 to the gdbpy_enter constructor), or, if that is nullptr, the
851 result of get_current_arch. */
852 static struct gdbarch
*get_gdbarch ();
854 /* Called only during gdb shutdown. This sets python_gdbarch to an
856 static void finalize ();
860 /* The current gdbarch, according to Python. This can be
862 static struct gdbarch
*python_gdbarch
;
864 struct active_ext_lang_state
*m_previous_active
;
865 PyGILState_STATE m_state
;
866 struct gdbarch
*m_gdbarch
;
867 const struct language_defn
*m_language
;
869 /* An optional is used here because we don't want to call
870 PyErr_Fetch too early. */
871 std::optional
<gdbpy_err_fetch
> m_error
;
874 /* Like gdbpy_enter, but takes a varobj. This is a subclass just to
875 make constructor delegation a little nicer. */
876 class gdbpy_enter_varobj
: public gdbpy_enter
880 /* This is defined in varobj.c, where it can access varobj
882 gdbpy_enter_varobj (const struct varobj
*var
);
886 /* The opposite of gdb_enter: this releases the GIL around a region,
887 allowing other Python threads to run. No Python APIs may be used
888 while this is active. */
889 class gdbpy_allow_threads
893 gdbpy_allow_threads ()
894 : m_save (PyEval_SaveThread ())
896 gdb_assert (m_save
!= nullptr);
899 ~gdbpy_allow_threads ()
901 PyEval_RestoreThread (m_save
);
904 DISABLE_COPY_AND_ASSIGN (gdbpy_allow_threads
);
908 PyThreadState
*m_save
;
911 /* A helper class to save and restore the GIL, but without touching
912 the other globals that are handled by gdbpy_enter. */
919 : m_state (PyGILState_Ensure ())
925 PyGILState_Release (m_state
);
928 DISABLE_COPY_AND_ASSIGN (gdbpy_gil
);
932 PyGILState_STATE m_state
;
935 int gdbpy_print_python_errors_p (void);
936 void gdbpy_print_stack (void);
937 void gdbpy_print_stack_or_quit ();
938 [[noreturn
]] void gdbpy_handle_exception ();
940 /* A wrapper around calling 'error'. Prefixes the error message with an
941 'Error occurred in Python' string. Use this in C++ code if we spot
942 something wrong with an object returned from Python code. The prefix
943 string gives the user a hint that the mistake is within Python code,
944 rather than some other part of GDB.
946 This always calls error, and never returns. */
948 [[noreturn
]] void gdbpy_error (const char *fmt
, ...) ATTRIBUTE_PRINTF (1, 2);
950 gdbpy_ref
<> python_string_to_unicode (PyObject
*obj
);
951 gdb::unique_xmalloc_ptr
<char> unicode_to_target_string (PyObject
*unicode_str
);
952 gdb::unique_xmalloc_ptr
<char> python_string_to_target_string (PyObject
*obj
);
953 gdbpy_ref
<> python_string_to_target_python_string (PyObject
*obj
);
954 gdb::unique_xmalloc_ptr
<char> python_string_to_host_string (PyObject
*obj
);
955 gdbpy_ref
<> host_string_to_python_string (const char *str
);
956 int gdbpy_is_string (PyObject
*obj
);
957 gdb::unique_xmalloc_ptr
<char> gdbpy_obj_to_string (PyObject
*obj
);
959 int gdbpy_is_lazy_string (PyObject
*result
);
960 void gdbpy_extract_lazy_string (PyObject
*string
, CORE_ADDR
*addr
,
961 struct type
**str_type
,
963 gdb::unique_xmalloc_ptr
<char> *encoding
);
965 int gdbpy_is_value_object (PyObject
*obj
);
967 /* Note that these are declared here, and not in python.h with the
968 other pretty-printer functions, because they refer to PyObject. */
969 gdbpy_ref
<> apply_varobj_pretty_printer (PyObject
*print_obj
,
970 struct value
**replacement
,
971 struct ui_file
*stream
,
972 const value_print_options
*opts
);
973 gdbpy_ref
<> gdbpy_get_varobj_pretty_printer (struct value
*value
);
974 gdb::unique_xmalloc_ptr
<char> gdbpy_get_display_hint (PyObject
*printer
);
975 PyObject
*gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
);
977 PyObject
*gdbpy_print_options (PyObject
*self
, PyObject
*args
);
978 void gdbpy_get_print_options (value_print_options
*opts
);
979 extern const struct value_print_options
*gdbpy_current_print_options
;
981 void bpfinishpy_pre_stop_hook (struct gdbpy_breakpoint_object
*bp_obj
);
982 void bpfinishpy_post_stop_hook (struct gdbpy_breakpoint_object
*bp_obj
);
983 void bpfinishpy_pre_delete_hook (struct gdbpy_breakpoint_object
*bp_obj
);
985 extern PyObject
*gdbpy_doc_cst
;
986 extern PyObject
*gdbpy_children_cst
;
987 extern PyObject
*gdbpy_to_string_cst
;
988 extern PyObject
*gdbpy_display_hint_cst
;
989 extern PyObject
*gdbpy_enabled_cst
;
990 extern PyObject
*gdbpy_value_cst
;
992 /* Exception types. */
993 extern PyObject
*gdbpy_gdb_error
;
994 extern PyObject
*gdbpy_gdb_memory_error
;
995 extern PyObject
*gdbpy_gdberror_exc
;
997 extern void gdbpy_convert_exception (const struct gdb_exception
&)
998 CPYCHECKER_SETS_EXCEPTION
;
1000 /* Use this in a 'catch' block to convert the exception E to a Python
1001 exception and return value VAL to signal that an exception occurred.
1002 Typically at the use site, that value will be returned immediately. */
1004 template<typename T
>
1006 gdbpy_handle_gdb_exception (T val
, const gdb_exception
&e
)
1008 gdbpy_convert_exception (e
);
1012 int get_addr_from_python (PyObject
*obj
, CORE_ADDR
*addr
)
1013 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
;
1015 gdbpy_ref
<> gdb_py_object_from_longest (LONGEST l
);
1016 gdbpy_ref
<> gdb_py_object_from_ulongest (ULONGEST l
);
1017 int gdb_py_int_as_long (PyObject
*, long *);
1019 PyObject
*gdb_py_generic_dict (PyObject
*self
, void *closure
);
1021 int gdb_pymodule_addobject (PyObject
*module
, const char *name
,
1023 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
;
1026 /* Return a Python string (str) object that represents SELF. SELF can be
1027 any object type, but should be in an "invalid" state. What "invalid"
1028 means is up to the caller. The returned string will take the form
1029 "<TYPENAME (invalid)>", without the quotes, and with TYPENAME replaced
1030 with the type of SELF. */
1032 PyObject
*gdb_py_invalid_object_repr (PyObject
*self
);
1036 std::unique_ptr
<varobj_iter
> py_varobj_get_iterator
1037 (struct varobj
*var
,
1039 const value_print_options
*opts
);
1041 /* Deleter for Py_buffer unique_ptr specialization. */
1043 struct Py_buffer_deleter
1045 void operator() (Py_buffer
*b
) const
1047 PyBuffer_Release (b
);
1051 /* A unique_ptr specialization for Py_buffer. */
1052 typedef std::unique_ptr
<Py_buffer
, Py_buffer_deleter
> Py_buffer_up
;
1054 /* Parse a register number from PYO_REG_ID and place the register number
1055 into *REG_NUM. The register is a register for GDBARCH.
1057 If a register is parsed successfully then *REG_NUM will have been
1058 updated, and true is returned. Otherwise the contents of *REG_NUM are
1059 undefined, and false is returned. When false is returned, the
1060 Python error is set.
1062 The PYO_REG_ID object can be a string, the name of the register. This
1063 is the slowest approach as GDB has to map the name to a number for each
1064 call. Alternatively PYO_REG_ID can be an internal GDB register
1065 number. This is quick but should not be encouraged as this means
1066 Python scripts are now dependent on GDB's internal register numbering.
1067 Final PYO_REG_ID can be a gdb.RegisterDescriptor object, these objects
1068 can be looked up by name once, and then cache the register number so
1069 should be as quick as using a register number. */
1071 extern bool gdbpy_parse_register_id (struct gdbarch
*gdbarch
,
1072 PyObject
*pyo_reg_id
, int *reg_num
);
1074 /* Return true if OBJ is a gdb.Architecture object, otherwise, return
1077 extern bool gdbpy_is_architecture (PyObject
*obj
);
1079 /* Return true if OBJ is a gdb.Progspace object, otherwise, return false. */
1081 extern bool gdbpy_is_progspace (PyObject
*obj
);
1083 /* Take DOC, the documentation string for a GDB command defined in Python,
1084 and return an (possibly) modified version of that same string.
1086 When a command is defined in Python, the documentation string will
1087 usually be indented based on the indentation of the surrounding Python
1088 code. However, the documentation string is a literal string, all the
1089 white-space added for indentation is included within the documentation
1092 This indentation is then included in the help text that GDB displays,
1093 which looks odd out of the context of the original Python source code.
1095 This function analyses DOC and tries to figure out what white-space
1096 within DOC was added as part of the indentation, and then removes that
1097 white-space from the copy that is returned.
1099 If the analysis of DOC fails then DOC will be returned unmodified. */
1101 extern gdb::unique_xmalloc_ptr
<char> gdbpy_fix_doc_string_indentation
1102 (gdb::unique_xmalloc_ptr
<char> doc
);
1104 /* Implement the 'print_insn' hook for Python. Disassemble an instruction
1105 whose address is ADDRESS for architecture GDBARCH. The bytes of the
1106 instruction should be read with INFO->read_memory_func as the
1107 instruction being disassembled might actually be in a buffer.
1109 Used INFO->fprintf_func to print the results of the disassembly, and
1110 return the length of the instruction in octets.
1112 If no instruction can be disassembled then return an empty value. */
1114 extern std::optional
<int> gdbpy_print_insn (struct gdbarch
*gdbarch
,
1116 disassemble_info
*info
);
1118 /* A wrapper for PyType_Ready that also automatically registers the
1119 type in the appropriate module. Returns 0 on success, -1 on error.
1120 If MOD is supplied, then the type is added to that module. If MOD
1121 is not supplied, the type name (tp_name field) must be of the form
1122 "gdb.Mumble", and the type will be added to the gdb module. */
1125 gdbpy_type_ready (PyTypeObject
*type
, PyObject
*mod
= nullptr)
1127 if (PyType_Ready (type
) < 0)
1131 gdb_assert (startswith (type
->tp_name
, "gdb."));
1134 const char *dot
= strrchr (type
->tp_name
, '.');
1135 gdb_assert (dot
!= nullptr);
1136 return gdb_pymodule_addobject (mod
, dot
+ 1, (PyObject
*) type
);
1139 /* Poison PyType_Ready. Only gdbpy_type_ready should be used, to
1140 avoid forgetting to register the type. See PR python/32163. */
1143 # pragma GCC poison PyType_Ready
1145 # define PyType_Ready POISONED_PyType_Ready
1148 #endif /* PYTHON_PYTHON_INTERNAL_H */