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 /* PyObject_CallMethod's 'method' and 'format' parameters were missing
149 the 'const' qualifier before Python 3.4. Hence, we wrap the
150 function in our own version to avoid errors with string literals.
151 Note, this is a variadic template because PyObject_CallMethod is a
152 varargs function and Python doesn't have a "PyObject_VaCallMethod"
153 variant taking a va_list that we could defer to instead. */
155 template<typename
... Args
>
156 static inline PyObject
*
157 gdb_PyObject_CallMethod (PyObject
*o
, const char *method
, const char *format
,
158 Args
... args
) /* ARI: editCase function */
160 return PyObject_CallMethod (o
,
161 const_cast<char *> (method
),
162 const_cast<char *> (format
),
166 #undef PyObject_CallMethod
167 #define PyObject_CallMethod gdb_PyObject_CallMethod
169 /* The 'name' parameter of PyErr_NewException was missing the 'const'
170 qualifier in Python <= 3.4. Hence, we wrap it in a function to
171 avoid errors when compiled with -Werror. */
173 static inline PyObject
*
174 gdb_PyErr_NewException (const char *name
, PyObject
*base
, PyObject
*dict
)
176 return PyErr_NewException (const_cast<char *> (name
), base
, dict
);
179 #define PyErr_NewException gdb_PyErr_NewException
181 /* PySys_GetObject's 'name' parameter was missing the 'const'
182 qualifier before Python 3.4. Hence, we wrap it in a function to
183 avoid errors when compiled with -Werror. */
185 static inline PyObject
*
186 gdb_PySys_GetObject (const char *name
)
188 return PySys_GetObject (const_cast<char *> (name
));
191 #define PySys_GetObject gdb_PySys_GetObject
193 /* PySys_SetPath was deprecated in Python 3.11. Disable the deprecated
194 code for Python 3.10 and newer. */
195 #if PY_VERSION_HEX < 0x030a0000
197 /* PySys_SetPath's 'path' parameter was missing the 'const' qualifier
198 before Python 3.6. Hence, we wrap it in a function to avoid errors
199 when compiled with -Werror. */
201 # define GDB_PYSYS_SETPATH_CHAR wchar_t
204 gdb_PySys_SetPath (const GDB_PYSYS_SETPATH_CHAR
*path
)
206 PySys_SetPath (const_cast<GDB_PYSYS_SETPATH_CHAR
*> (path
));
209 #define PySys_SetPath gdb_PySys_SetPath
212 /* Wrap PyGetSetDef to allow convenient construction with string
213 literals. Unfortunately, PyGetSetDef's 'name' and 'doc' members
214 are 'char *' instead of 'const char *', meaning that in order to
215 list-initialize PyGetSetDef arrays with string literals (and
216 without the wrapping below) would require writing explicit 'char *'
217 casts. Instead, we extend PyGetSetDef and add constexpr
218 constructors that accept const 'name' and 'doc', hiding the ugly
219 casts here in a single place. */
221 struct gdb_PyGetSetDef
: PyGetSetDef
223 constexpr gdb_PyGetSetDef (const char *name_
, getter get_
, setter set_
,
224 const char *doc_
, void *closure_
)
225 : PyGetSetDef
{const_cast<char *> (name_
), get_
, set_
,
226 const_cast<char *> (doc_
), closure_
}
229 /* Alternative constructor that allows omitting the closure in list
231 constexpr gdb_PyGetSetDef (const char *name_
, getter get_
, setter set_
,
233 : gdb_PyGetSetDef
{name_
, get_
, set_
, doc_
, NULL
}
236 /* Constructor for the sentinel entries. */
237 constexpr gdb_PyGetSetDef (std::nullptr_t
)
238 : gdb_PyGetSetDef
{NULL
, NULL
, NULL
, NULL
, NULL
}
242 /* The 'keywords' parameter of PyArg_ParseTupleAndKeywords has type
243 'char **'. However, string literals are const in C++, and so to
244 avoid casting at every keyword array definition, we'll need to make
245 the keywords array an array of 'const char *'. To avoid having all
246 callers add a 'const_cast<char **>' themselves when passing such an
247 array through 'char **', we define our own version of
248 PyArg_ParseTupleAndKeywords here with a corresponding 'keywords'
249 parameter type that does the cast in a single place. (This is not
250 an overload of PyArg_ParseTupleAndKeywords in order to make it
251 clearer that we're calling our own function instead of a function
252 that exists in some newer Python version.) */
255 gdb_PyArg_ParseTupleAndKeywords (PyObject
*args
, PyObject
*kw
,
256 const char *format
, const char **keywords
, ...)
261 va_start (ap
, keywords
);
262 res
= PyArg_VaParseTupleAndKeywords (args
, kw
, format
,
263 const_cast<char **> (keywords
),
270 /* In order to be able to parse symtab_and_line_to_sal_object function
271 a real symtab_and_line structure is needed. */
274 /* Also needed to parse enum var_types. */
276 #include "breakpoint.h"
278 enum gdbpy_iter_kind
{ iter_keys
, iter_values
, iter_items
};
282 struct language_defn
;
283 struct program_space
;
287 extern int gdb_python_initialized
;
289 extern PyObject
*gdb_module
;
290 extern PyObject
*gdb_python_module
;
291 extern PyTypeObject value_object_type
292 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("value_object");
293 extern PyTypeObject block_object_type
294 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF("block_object");
295 extern PyTypeObject symbol_object_type
296 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("symbol_object");
297 extern PyTypeObject event_object_type
298 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("event_object");
299 extern PyTypeObject breakpoint_object_type
300 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("breakpoint_object");
301 extern PyTypeObject frame_object_type
302 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("frame_object");
303 extern PyTypeObject thread_object_type
304 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("thread_object");
306 /* Ensure that breakpoint_object_type is initialized and return true. If
307 breakpoint_object_type can't be initialized then set a suitable Python
308 error and return false.
310 This function needs to be called from any gdbpy_initialize_* function
311 that wants to reference breakpoint_object_type. After all the
312 gdbpy_initialize_* functions have been called then breakpoint_object_type
313 is guaranteed to have been initialized, and this function does not need
314 calling before referencing breakpoint_object_type. */
316 extern bool gdbpy_breakpoint_init_breakpoint_type ();
318 struct gdbpy_breakpoint_object
322 /* The breakpoint number according to gdb. */
325 /* The gdb breakpoint object, or NULL if the breakpoint has been
327 struct breakpoint
*bp
;
329 /* 1 is this is a FinishBreakpoint object, 0 otherwise. */
333 /* Require that BREAKPOINT be a valid breakpoint ID; throw a Python
334 exception if it is invalid. */
335 #define BPPY_REQUIRE_VALID(Breakpoint) \
337 if ((Breakpoint)->bp == NULL) \
338 return PyErr_Format (PyExc_RuntimeError, \
339 _("Breakpoint %d is invalid."), \
340 (Breakpoint)->number); \
343 /* Require that BREAKPOINT be a valid breakpoint ID; throw a Python
344 exception if it is invalid. This macro is for use in setter functions. */
345 #define BPPY_SET_REQUIRE_VALID(Breakpoint) \
347 if ((Breakpoint)->bp == NULL) \
349 PyErr_Format (PyExc_RuntimeError, _("Breakpoint %d is invalid."), \
350 (Breakpoint)->number); \
356 /* Variables used to pass information between the Breakpoint
357 constructor and the breakpoint-created hook function. */
358 extern gdbpy_breakpoint_object
*bppy_pending_object
;
365 /* The thread we represent. */
366 struct thread_info
*thread
;
368 /* The Inferior object to which this thread belongs. */
371 /* Dictionary holding user-added attributes. This is the __dict__
372 attribute of the object. */
376 struct inferior_object
;
378 extern struct cmd_list_element
*set_python_list
;
379 extern struct cmd_list_element
*show_python_list
;
381 /* extension_language_script_ops "methods". */
383 /* Return true if auto-loading Python scripts is enabled.
384 This is the extension_language_script_ops.auto_load_enabled "method". */
386 extern bool gdbpy_auto_load_enabled (const struct extension_language_defn
*);
388 /* extension_language_ops "methods". */
390 extern enum ext_lang_rc gdbpy_apply_val_pretty_printer
391 (const struct extension_language_defn
*,
393 struct ui_file
*stream
, int recurse
,
394 const struct value_print_options
*options
,
395 const struct language_defn
*language
);
396 extern enum ext_lang_bt_status gdbpy_apply_frame_filter
397 (const struct extension_language_defn
*,
398 const frame_info_ptr
&frame
, frame_filter_flags flags
,
399 enum ext_lang_frame_args args_type
,
400 struct ui_out
*out
, int frame_low
, int frame_high
);
401 extern void gdbpy_preserve_values (const struct extension_language_defn
*,
402 struct objfile
*objfile
,
403 htab_t copied_types
);
404 extern enum ext_lang_bp_stop gdbpy_breakpoint_cond_says_stop
405 (const struct extension_language_defn
*, struct breakpoint
*);
406 extern int gdbpy_breakpoint_has_cond (const struct extension_language_defn
*,
407 struct breakpoint
*b
);
409 extern enum ext_lang_rc gdbpy_get_matching_xmethod_workers
410 (const struct extension_language_defn
*extlang
,
411 struct type
*obj_type
, const char *method_name
,
412 std::vector
<xmethod_worker_up
> *dm_vec
);
415 PyObject
*gdbpy_history (PyObject
*self
, PyObject
*args
);
416 PyObject
*gdbpy_add_history (PyObject
*self
, PyObject
*args
);
417 extern PyObject
*gdbpy_history_count (PyObject
*self
, PyObject
*args
);
418 PyObject
*gdbpy_convenience_variable (PyObject
*self
, PyObject
*args
);
419 PyObject
*gdbpy_set_convenience_variable (PyObject
*self
, PyObject
*args
);
420 PyObject
*gdbpy_breakpoints (PyObject
*, PyObject
*);
421 PyObject
*gdbpy_frame_stop_reason_string (PyObject
*, PyObject
*);
422 PyObject
*gdbpy_lookup_symbol (PyObject
*self
, PyObject
*args
, PyObject
*kw
);
423 PyObject
*gdbpy_lookup_global_symbol (PyObject
*self
, PyObject
*args
,
425 PyObject
*gdbpy_lookup_static_symbol (PyObject
*self
, PyObject
*args
,
427 PyObject
*gdbpy_lookup_static_symbols (PyObject
*self
, PyObject
*args
,
429 PyObject
*gdbpy_start_recording (PyObject
*self
, PyObject
*args
);
430 PyObject
*gdbpy_current_recording (PyObject
*self
, PyObject
*args
);
431 PyObject
*gdbpy_stop_recording (PyObject
*self
, PyObject
*args
);
432 PyObject
*gdbpy_newest_frame (PyObject
*self
, PyObject
*args
);
433 PyObject
*gdbpy_selected_frame (PyObject
*self
, PyObject
*args
);
434 PyObject
*gdbpy_lookup_type (PyObject
*self
, PyObject
*args
, PyObject
*kw
);
435 int gdbpy_is_field (PyObject
*obj
);
436 PyObject
*gdbpy_create_lazy_string_object (CORE_ADDR address
, long length
,
437 const char *encoding
,
439 PyObject
*gdbpy_inferiors (PyObject
*unused
, PyObject
*unused2
);
440 PyObject
*gdbpy_create_ptid_object (ptid_t ptid
);
441 PyObject
*gdbpy_selected_thread (PyObject
*self
, PyObject
*args
);
442 PyObject
*gdbpy_selected_inferior (PyObject
*self
, PyObject
*args
);
443 PyObject
*gdbpy_string_to_argv (PyObject
*self
, PyObject
*args
);
444 PyObject
*gdbpy_parameter_value (const setting
&var
);
445 gdb::unique_xmalloc_ptr
<char> gdbpy_parse_command_name
446 (const char *name
, struct cmd_list_element
***base_list
,
447 struct cmd_list_element
**start_list
);
448 PyObject
*gdbpy_register_tui_window (PyObject
*self
, PyObject
*args
,
451 PyObject
*symtab_and_line_to_sal_object (struct symtab_and_line sal
);
452 PyObject
*symtab_to_symtab_object (struct symtab
*symtab
);
453 PyObject
*symbol_to_symbol_object (struct symbol
*sym
);
454 PyObject
*block_to_block_object (const struct block
*block
,
455 struct objfile
*objfile
);
456 PyObject
*value_to_value_object (struct value
*v
);
457 PyObject
*type_to_type_object (struct type
*);
458 PyObject
*frame_info_to_frame_object (const frame_info_ptr
&frame
);
459 PyObject
*symtab_to_linetable_object (PyObject
*symtab
);
460 gdbpy_ref
<> pspace_to_pspace_object (struct program_space
*);
461 PyObject
*pspy_get_printers (PyObject
*, void *);
462 PyObject
*pspy_get_frame_filters (PyObject
*, void *);
463 PyObject
*pspy_get_frame_unwinders (PyObject
*, void *);
464 PyObject
*pspy_get_xmethods (PyObject
*, void *);
466 gdbpy_ref
<> objfile_to_objfile_object (struct objfile
*);
467 PyObject
*objfpy_get_printers (PyObject
*, void *);
468 PyObject
*objfpy_get_frame_filters (PyObject
*, void *);
469 PyObject
*objfpy_get_frame_unwinders (PyObject
*, void *);
470 PyObject
*objfpy_get_xmethods (PyObject
*, void *);
471 PyObject
*gdbpy_lookup_objfile (PyObject
*self
, PyObject
*args
, PyObject
*kw
);
473 PyObject
*gdbarch_to_arch_object (struct gdbarch
*gdbarch
);
474 PyObject
*gdbpy_all_architecture_names (PyObject
*self
, PyObject
*args
);
476 PyObject
*gdbpy_new_register_descriptor_iterator (struct gdbarch
*gdbarch
,
477 const char *group_name
);
478 PyObject
*gdbpy_new_reggroup_iterator (struct gdbarch
*gdbarch
);
480 gdbpy_ref
<thread_object
> create_thread_object (struct thread_info
*tp
);
481 gdbpy_ref
<> thread_to_thread_object (thread_info
*thr
);;
482 gdbpy_ref
<inferior_object
> inferior_to_inferior_object (inferior
*inf
);
484 PyObject
*gdbpy_buffer_to_membuf (gdb::unique_xmalloc_ptr
<gdb_byte
> buffer
,
485 CORE_ADDR address
, ULONGEST length
);
487 struct process_stratum_target
;
488 gdbpy_ref
<> target_to_connection_object (process_stratum_target
*target
);
489 PyObject
*gdbpy_connections (PyObject
*self
, PyObject
*args
);
491 const struct block
*block_object_to_block (PyObject
*obj
);
492 struct symbol
*symbol_object_to_symbol (PyObject
*obj
);
493 struct value
*value_object_to_value (PyObject
*self
);
494 struct value
*convert_value_from_python (PyObject
*obj
);
495 struct type
*type_object_to_type (PyObject
*obj
);
496 struct symtab
*symtab_object_to_symtab (PyObject
*obj
);
497 struct symtab_and_line
*sal_object_to_symtab_and_line (PyObject
*obj
);
498 frame_info_ptr
frame_object_to_frame_info (PyObject
*frame_obj
);
499 struct gdbarch
*arch_object_to_gdbarch (PyObject
*obj
);
501 extern PyObject
*gdbpy_execute_mi_command (PyObject
*self
, PyObject
*args
,
504 /* Serialize RESULTS and print it in MI format to the current_uiout.
506 This function handles the top-level results passed as a dictionary.
507 The caller is responsible for ensuring that. The values within this
508 dictionary can be a wider range of types. Handling the values of the top-level
509 dictionary is done by serialize_mi_result_1, see that function for more
512 If anything goes wrong while parsing and printing the MI output then an
515 extern void serialize_mi_results (PyObject
*results
);
517 /* Implementation of the gdb.notify_mi function. */
519 extern PyObject
*gdbpy_notify_mi (PyObject
*self
, PyObject
*args
,
522 /* Convert Python object OBJ to a program_space pointer. OBJ must be a
523 gdb.Progspace reference. Return nullptr if the gdb.Progspace is not
524 valid (see gdb.Progspace.is_valid), otherwise return the program_space
527 extern struct program_space
*progspace_object_to_program_space (PyObject
*obj
);
529 /* A class for managing the initialization, and finalization functions
530 from all Python files (e.g. gdb/python/py-*.c).
532 Within any Python file, create an instance of this class, passing in
533 the initialization function, and, optionally, the finalization
536 These functions are added to a single global list of functions, which
537 can then be called from do_start_initialization and finalize_python
538 (see python.c) to initialize all the Python files within GDB. */
540 class gdbpy_initialize_file
542 /* The type of a function that can be called just after GDB has setup the
543 Python interpreter. This function will setup any additional Python
544 state required by a particular subsystem. Return 0 if the setup was
545 successful, or return -1 if setup failed, in which case a Python
546 exception should have been raised. */
548 using gdbpy_initialize_file_ftype
= int (*) (void);
550 /* The type of a function that can be called just before GDB shuts down
551 the Python interpreter. This function can cleanup an Python state
552 that is cached within GDB, for example, if GDB is holding any
553 references to Python objects, these should be released before the
554 Python interpreter is shut down.
556 There is no error return in this case. This function is only called
557 when GDB is already shutting down. The function should make a best
558 effort to clean up, and then return. */
560 using gdbpy_finalize_file_ftype
= void (*) (void);
562 /* The type for an initialization and finalization function pair. */
564 using callback_pair_t
= std::pair
<gdbpy_initialize_file_ftype
,
565 gdbpy_finalize_file_ftype
>;
567 /* Return the vector of callbacks. The vector is defined as a static
568 variable within this function so that it will be initialized the first
569 time this function is called. This is important, as this function is
570 called as part of the global object initialization process; if the
571 vector was a static variable within this class then we could not
572 guarantee that it had been initialized before it was used. */
574 static std::vector
<callback_pair_t
> &
577 static std::vector
<callback_pair_t
> list
;
583 /* Register the initialization (INIT) and finalization (FINI) functions
584 for a Python file. See the comments on the function types above for
585 when these functions will be called.
587 Either of these functions can be nullptr, in which case no function
590 The FINI argument is optional, and defaults to nullptr (no function to
593 gdbpy_initialize_file (gdbpy_initialize_file_ftype init
,
594 gdbpy_finalize_file_ftype fini
= nullptr)
596 callbacks ().emplace_back (init
, fini
);
599 /* Run all the Python file initialize functions and return true. If any
600 of the initialize functions fails then this function returns false.
601 In the case of failure it is undefined how many of the initialize
602 functions will have been called. */
607 /* The initialize_all function should only be called once. The
608 following check reverses the global list, which will effect this
609 initialize_all call, as well as the later finalize_all call.
611 The environment variable checked here is the same as the one checked
612 in the generated init.c file. */
613 if (getenv ("GDB_REVERSE_INIT_FUNCTIONS") != nullptr)
614 std::reverse (callbacks ().begin (), callbacks ().end ());
616 for (const auto &p
: gdbpy_initialize_file::callbacks ())
618 if (p
.first
!= nullptr && p
.first () < 0)
624 /* Run all the Python file finalize functions. */
629 for (const auto &p
: gdbpy_initialize_file::callbacks ())
631 if (p
.second
!= nullptr)
637 /* Macro to simplify registering the initialization and finalization
638 functions for a Python file. */
640 #define GDBPY_INITIALIZE_FILE(INIT, ...) \
641 static gdbpy_initialize_file \
642 CONCAT(gdbpy_initialize_file_obj_, __LINE__) (INIT, ##__VA_ARGS__)
644 PyMODINIT_FUNC
gdbpy_events_mod_func ();
646 /* A wrapper for PyErr_Fetch that handles reference counting for the
648 class gdbpy_err_fetch
654 #if PY_VERSION_HEX < 0x030c0000
655 PyObject
*error_type
, *error_value
, *error_traceback
;
657 PyErr_Fetch (&error_type
, &error_value
, &error_traceback
);
658 m_error_type
.reset (error_type
);
659 m_error_value
.reset (error_value
);
660 m_error_traceback
.reset (error_traceback
);
662 /* PyErr_Fetch is deprecated in python 3.12, use PyErr_GetRaisedException
664 m_exc
.reset (PyErr_GetRaisedException ());
668 /* Call PyErr_Restore using the values stashed in this object.
669 After this call, this object is invalid and neither the to_string
670 nor restore methods may be used again. */
674 #if PY_VERSION_HEX < 0x030c0000
675 PyErr_Restore (m_error_type
.release (),
676 m_error_value
.release (),
677 m_error_traceback
.release ());
679 /* PyErr_Restore is deprecated in python 3.12, use PyErr_SetRaisedException
681 PyErr_SetRaisedException (m_exc
.release ());
685 /* Return the string representation of the exception represented by
686 this object. If the result is NULL a python error occurred, the
687 caller must clear it. */
689 gdb::unique_xmalloc_ptr
<char> to_string () const;
691 /* Return the string representation of the type of the exception
692 represented by this object. If the result is NULL a python error
693 occurred, the caller must clear it. */
695 gdb::unique_xmalloc_ptr
<char> type_to_string () const;
697 /* Return true if the stored type matches TYPE, false otherwise. */
699 bool type_matches (PyObject
*type
) const
701 gdbpy_ref
<> err_type
= this->type ();
702 return PyErr_GivenExceptionMatches (err_type
.get (), type
);
705 /* Return a new reference to the exception value object. */
707 gdbpy_ref
<> value () const
709 #if PY_VERSION_HEX < 0x030c0000
712 PyObject
*error_type
, *error_value
, *error_traceback
;
713 error_type
= m_error_type
.release ();
714 error_value
= m_error_value
.release ();
715 error_traceback
= m_error_traceback
.release ();
716 PyErr_NormalizeException (&error_type
, &error_value
, &error_traceback
);
717 m_error_type
.reset (error_type
);
718 m_error_value
.reset (error_value
);
719 m_error_traceback
.reset (error_traceback
);
722 return m_error_value
;
728 /* Return a new reference to the exception type object. */
730 gdbpy_ref
<> type () const
732 #if PY_VERSION_HEX < 0x030c0000
735 if (m_exc
.get() == nullptr)
737 return gdbpy_ref
<>::new_reference ((PyObject
*)Py_TYPE (m_exc
.get ()));
743 #if PY_VERSION_HEX < 0x030c0000
744 mutable gdbpy_ref
<> m_error_type
, m_error_value
, m_error_traceback
;
745 mutable bool m_normalized
= false;
751 /* Called before entering the Python interpreter to install the
752 current language and architecture to be used for Python values.
753 Also set the active extension language for GDB so that SIGINT's
754 are directed our way, and if necessary install the right SIGINT
760 /* Set the ambient Python architecture to GDBARCH and the language
761 to LANGUAGE. If GDBARCH is nullptr, then the architecture will
762 be computed, when needed, using get_current_arch; see the
763 get_gdbarch method. If LANGUAGE is not nullptr, then the current
764 language at time of construction will be saved (to be restored on
765 destruction), and the current language will be set to
767 explicit gdbpy_enter (struct gdbarch
*gdbarch
= nullptr,
768 const struct language_defn
*language
= nullptr);
772 DISABLE_COPY_AND_ASSIGN (gdbpy_enter
);
774 /* Return the current gdbarch, as known to the Python layer. This
775 is either python_gdbarch (which comes from the most recent call
776 to the gdbpy_enter constructor), or, if that is nullptr, the
777 result of get_current_arch. */
778 static struct gdbarch
*get_gdbarch ();
780 /* Called only during gdb shutdown. This sets python_gdbarch to an
782 static void finalize ();
786 /* The current gdbarch, according to Python. This can be
788 static struct gdbarch
*python_gdbarch
;
790 struct active_ext_lang_state
*m_previous_active
;
791 PyGILState_STATE m_state
;
792 struct gdbarch
*m_gdbarch
;
793 const struct language_defn
*m_language
;
795 /* An optional is used here because we don't want to call
796 PyErr_Fetch too early. */
797 std::optional
<gdbpy_err_fetch
> m_error
;
800 /* Like gdbpy_enter, but takes a varobj. This is a subclass just to
801 make constructor delegation a little nicer. */
802 class gdbpy_enter_varobj
: public gdbpy_enter
806 /* This is defined in varobj.c, where it can access varobj
808 gdbpy_enter_varobj (const struct varobj
*var
);
812 /* The opposite of gdb_enter: this releases the GIL around a region,
813 allowing other Python threads to run. No Python APIs may be used
814 while this is active. */
815 class gdbpy_allow_threads
819 gdbpy_allow_threads ()
820 : m_save (PyEval_SaveThread ())
822 gdb_assert (m_save
!= nullptr);
825 ~gdbpy_allow_threads ()
827 PyEval_RestoreThread (m_save
);
830 DISABLE_COPY_AND_ASSIGN (gdbpy_allow_threads
);
834 PyThreadState
*m_save
;
837 /* A helper class to save and restore the GIL, but without touching
838 the other globals that are handled by gdbpy_enter. */
845 : m_state (PyGILState_Ensure ())
851 PyGILState_Release (m_state
);
854 DISABLE_COPY_AND_ASSIGN (gdbpy_gil
);
858 PyGILState_STATE m_state
;
861 /* Use this in a 'catch' block to convert the exception to a Python
862 exception and return nullptr. */
863 #define GDB_PY_HANDLE_EXCEPTION(Exception) \
865 gdbpy_convert_exception (Exception); \
869 /* Use this in a 'catch' block to convert the exception to a Python
870 exception and return -1. */
871 #define GDB_PY_SET_HANDLE_EXCEPTION(Exception) \
873 gdbpy_convert_exception (Exception); \
877 int gdbpy_print_python_errors_p (void);
878 void gdbpy_print_stack (void);
879 void gdbpy_print_stack_or_quit ();
880 void gdbpy_handle_exception () ATTRIBUTE_NORETURN
;
882 /* A wrapper around calling 'error'. Prefixes the error message with an
883 'Error occurred in Python' string. Use this in C++ code if we spot
884 something wrong with an object returned from Python code. The prefix
885 string gives the user a hint that the mistake is within Python code,
886 rather than some other part of GDB.
888 This always calls error, and never returns. */
890 void gdbpy_error (const char *fmt
, ...)
891 ATTRIBUTE_NORETURN
ATTRIBUTE_PRINTF (1, 2);
893 gdbpy_ref
<> python_string_to_unicode (PyObject
*obj
);
894 gdb::unique_xmalloc_ptr
<char> unicode_to_target_string (PyObject
*unicode_str
);
895 gdb::unique_xmalloc_ptr
<char> python_string_to_target_string (PyObject
*obj
);
896 gdbpy_ref
<> python_string_to_target_python_string (PyObject
*obj
);
897 gdb::unique_xmalloc_ptr
<char> python_string_to_host_string (PyObject
*obj
);
898 gdbpy_ref
<> host_string_to_python_string (const char *str
);
899 int gdbpy_is_string (PyObject
*obj
);
900 gdb::unique_xmalloc_ptr
<char> gdbpy_obj_to_string (PyObject
*obj
);
902 int gdbpy_is_lazy_string (PyObject
*result
);
903 void gdbpy_extract_lazy_string (PyObject
*string
, CORE_ADDR
*addr
,
904 struct type
**str_type
,
906 gdb::unique_xmalloc_ptr
<char> *encoding
);
908 int gdbpy_is_value_object (PyObject
*obj
);
910 /* Note that these are declared here, and not in python.h with the
911 other pretty-printer functions, because they refer to PyObject. */
912 gdbpy_ref
<> apply_varobj_pretty_printer (PyObject
*print_obj
,
913 struct value
**replacement
,
914 struct ui_file
*stream
,
915 const value_print_options
*opts
);
916 gdbpy_ref
<> gdbpy_get_varobj_pretty_printer (struct value
*value
);
917 gdb::unique_xmalloc_ptr
<char> gdbpy_get_display_hint (PyObject
*printer
);
918 PyObject
*gdbpy_default_visualizer (PyObject
*self
, PyObject
*args
);
920 PyObject
*gdbpy_print_options (PyObject
*self
, PyObject
*args
);
921 void gdbpy_get_print_options (value_print_options
*opts
);
922 extern const struct value_print_options
*gdbpy_current_print_options
;
924 void bpfinishpy_pre_stop_hook (struct gdbpy_breakpoint_object
*bp_obj
);
925 void bpfinishpy_post_stop_hook (struct gdbpy_breakpoint_object
*bp_obj
);
926 void bpfinishpy_pre_delete_hook (struct gdbpy_breakpoint_object
*bp_obj
);
928 extern PyObject
*gdbpy_doc_cst
;
929 extern PyObject
*gdbpy_children_cst
;
930 extern PyObject
*gdbpy_to_string_cst
;
931 extern PyObject
*gdbpy_display_hint_cst
;
932 extern PyObject
*gdbpy_enabled_cst
;
933 extern PyObject
*gdbpy_value_cst
;
935 /* Exception types. */
936 extern PyObject
*gdbpy_gdb_error
;
937 extern PyObject
*gdbpy_gdb_memory_error
;
938 extern PyObject
*gdbpy_gdberror_exc
;
940 extern void gdbpy_convert_exception (const struct gdb_exception
&)
941 CPYCHECKER_SETS_EXCEPTION
;
943 int get_addr_from_python (PyObject
*obj
, CORE_ADDR
*addr
)
944 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
;
946 gdbpy_ref
<> gdb_py_object_from_longest (LONGEST l
);
947 gdbpy_ref
<> gdb_py_object_from_ulongest (ULONGEST l
);
948 int gdb_py_int_as_long (PyObject
*, long *);
950 PyObject
*gdb_py_generic_dict (PyObject
*self
, void *closure
);
952 int gdb_pymodule_addobject (PyObject
*module
, const char *name
,
954 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
;
957 /* Return a Python string (str) object that represents SELF. SELF can be
958 any object type, but should be in an "invalid" state. What "invalid"
959 means is up to the caller. The returned string will take the form
960 "<TYPENAME (invalid)>", without the quotes, and with TYPENAME replaced
961 with the type of SELF. */
963 PyObject
*gdb_py_invalid_object_repr (PyObject
*self
);
967 std::unique_ptr
<varobj_iter
> py_varobj_get_iterator
970 const value_print_options
*opts
);
972 /* Deleter for Py_buffer unique_ptr specialization. */
974 struct Py_buffer_deleter
976 void operator() (Py_buffer
*b
) const
978 PyBuffer_Release (b
);
982 /* A unique_ptr specialization for Py_buffer. */
983 typedef std::unique_ptr
<Py_buffer
, Py_buffer_deleter
> Py_buffer_up
;
985 /* Parse a register number from PYO_REG_ID and place the register number
986 into *REG_NUM. The register is a register for GDBARCH.
988 If a register is parsed successfully then *REG_NUM will have been
989 updated, and true is returned. Otherwise the contents of *REG_NUM are
990 undefined, and false is returned. When false is returned, the
993 The PYO_REG_ID object can be a string, the name of the register. This
994 is the slowest approach as GDB has to map the name to a number for each
995 call. Alternatively PYO_REG_ID can be an internal GDB register
996 number. This is quick but should not be encouraged as this means
997 Python scripts are now dependent on GDB's internal register numbering.
998 Final PYO_REG_ID can be a gdb.RegisterDescriptor object, these objects
999 can be looked up by name once, and then cache the register number so
1000 should be as quick as using a register number. */
1002 extern bool gdbpy_parse_register_id (struct gdbarch
*gdbarch
,
1003 PyObject
*pyo_reg_id
, int *reg_num
);
1005 /* Return true if OBJ is a gdb.Architecture object, otherwise, return
1008 extern bool gdbpy_is_architecture (PyObject
*obj
);
1010 /* Return true if OBJ is a gdb.Progspace object, otherwise, return false. */
1012 extern bool gdbpy_is_progspace (PyObject
*obj
);
1014 /* Take DOC, the documentation string for a GDB command defined in Python,
1015 and return an (possibly) modified version of that same string.
1017 When a command is defined in Python, the documentation string will
1018 usually be indented based on the indentation of the surrounding Python
1019 code. However, the documentation string is a literal string, all the
1020 white-space added for indentation is included within the documentation
1023 This indentation is then included in the help text that GDB displays,
1024 which looks odd out of the context of the original Python source code.
1026 This function analyses DOC and tries to figure out what white-space
1027 within DOC was added as part of the indentation, and then removes that
1028 white-space from the copy that is returned.
1030 If the analysis of DOC fails then DOC will be returned unmodified. */
1032 extern gdb::unique_xmalloc_ptr
<char> gdbpy_fix_doc_string_indentation
1033 (gdb::unique_xmalloc_ptr
<char> doc
);
1035 /* Implement the 'print_insn' hook for Python. Disassemble an instruction
1036 whose address is ADDRESS for architecture GDBARCH. The bytes of the
1037 instruction should be read with INFO->read_memory_func as the
1038 instruction being disassembled might actually be in a buffer.
1040 Used INFO->fprintf_func to print the results of the disassembly, and
1041 return the length of the instruction in octets.
1043 If no instruction can be disassembled then return an empty value. */
1045 extern std::optional
<int> gdbpy_print_insn (struct gdbarch
*gdbarch
,
1047 disassemble_info
*info
);
1049 #endif /* PYTHON_PYTHON_INTERNAL_H */