Update readelf's display of RELR sections to include the number of locations relocated
[binutils-gdb.git] / gdb / python / python-internal.h
blob5132ec15ba668abb42b0c9c6e8f338a8a4b3e549
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
32 gdb. */
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)))
37 #else
38 #define CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF(ARG)
39 #endif
41 #ifdef WITH_CPYCHECKER_SETS_EXCEPTION_ATTRIBUTE
42 #define CPYCHECKER_SETS_EXCEPTION __attribute__ ((cpychecker_sets_exception))
43 #else
44 #define CPYCHECKER_SETS_EXCEPTION
45 #endif
47 #ifdef WITH_CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION_ATTRIBUTE
48 #define CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION \
49 __attribute__ ((cpychecker_negative_result_sets_exception))
50 #else
51 #define CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
52 #endif
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
62 #undef _XOPEN_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
72 #endif
74 /* Another kludge to avoid compilation errors because MinGW defines
75 'hypot' to '_hypot', but the C++ headers says "using ::hypot". */
76 #ifdef __MINGW32__
77 # define _hypot hypot
78 #endif
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. */
86 #include <Python.h>
87 #include <frameobject.h>
88 #include "py-ref.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. */
95 #ifndef WITH_THREAD
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()
101 #endif
103 /* Python supplies HAVE_LONG_LONG and some `long long' support when it
104 is available. These defines let us handle the differences more
105 cleanly. */
106 #ifdef HAVE_LONG_LONG
108 #define GDB_PY_LL_ARG "L"
109 #define GDB_PY_LLU_ARG "K"
110 typedef PY_LONG_LONG gdb_py_longest;
111 typedef unsigned PY_LONG_LONG gdb_py_ulongest;
112 #define gdb_py_long_as_ulongest PyLong_AsUnsignedLongLong
113 #define gdb_py_long_as_long_and_overflow PyLong_AsLongLongAndOverflow
115 #else /* HAVE_LONG_LONG */
117 #define GDB_PY_LL_ARG "L"
118 #define GDB_PY_LLU_ARG "K"
119 typedef long gdb_py_longest;
120 typedef unsigned long gdb_py_ulongest;
121 #define gdb_py_long_as_ulongest PyLong_AsUnsignedLong
122 #define gdb_py_long_as_long_and_overflow PyLong_AsLongAndOverflow
124 #endif /* HAVE_LONG_LONG */
126 #if PY_VERSION_HEX < 0x03020000
127 typedef long Py_hash_t;
128 #endif
130 /* PyMem_RawMalloc appeared in Python 3.4. For earlier versions, we can just
131 fall back to PyMem_Malloc. */
133 #if PY_VERSION_HEX < 0x03040000
134 #define PyMem_RawMalloc PyMem_Malloc
135 #endif
137 /* PyObject_CallMethod's 'method' and 'format' parameters were missing
138 the 'const' qualifier before Python 3.4. Hence, we wrap the
139 function in our own version to avoid errors with string literals.
140 Note, this is a variadic template because PyObject_CallMethod is a
141 varargs function and Python doesn't have a "PyObject_VaCallMethod"
142 variant taking a va_list that we could defer to instead. */
144 template<typename... Args>
145 static inline PyObject *
146 gdb_PyObject_CallMethod (PyObject *o, const char *method, const char *format,
147 Args... args) /* ARI: editCase function */
149 return PyObject_CallMethod (o,
150 const_cast<char *> (method),
151 const_cast<char *> (format),
152 args...);
155 #undef PyObject_CallMethod
156 #define PyObject_CallMethod gdb_PyObject_CallMethod
158 /* The 'name' parameter of PyErr_NewException was missing the 'const'
159 qualifier in Python <= 3.4. Hence, we wrap it in a function to
160 avoid errors when compiled with -Werror. */
162 static inline PyObject*
163 gdb_PyErr_NewException (const char *name, PyObject *base, PyObject *dict)
165 return PyErr_NewException (const_cast<char *> (name), base, dict);
168 #define PyErr_NewException gdb_PyErr_NewException
170 /* PySys_GetObject's 'name' parameter was missing the 'const'
171 qualifier before Python 3.4. Hence, we wrap it in a function to
172 avoid errors when compiled with -Werror. */
174 static inline PyObject *
175 gdb_PySys_GetObject (const char *name)
177 return PySys_GetObject (const_cast<char *> (name));
180 #define PySys_GetObject gdb_PySys_GetObject
182 /* PySys_SetPath was deprecated in Python 3.11. Disable the deprecated
183 code for Python 3.10 and newer. */
184 #if PY_VERSION_HEX < 0x030a0000
186 /* PySys_SetPath's 'path' parameter was missing the 'const' qualifier
187 before Python 3.6. Hence, we wrap it in a function to avoid errors
188 when compiled with -Werror. */
190 # define GDB_PYSYS_SETPATH_CHAR wchar_t
192 static inline void
193 gdb_PySys_SetPath (const GDB_PYSYS_SETPATH_CHAR *path)
195 PySys_SetPath (const_cast<GDB_PYSYS_SETPATH_CHAR *> (path));
198 #define PySys_SetPath gdb_PySys_SetPath
199 #endif
201 /* Wrap PyGetSetDef to allow convenient construction with string
202 literals. Unfortunately, PyGetSetDef's 'name' and 'doc' members
203 are 'char *' instead of 'const char *', meaning that in order to
204 list-initialize PyGetSetDef arrays with string literals (and
205 without the wrapping below) would require writing explicit 'char *'
206 casts. Instead, we extend PyGetSetDef and add constexpr
207 constructors that accept const 'name' and 'doc', hiding the ugly
208 casts here in a single place. */
210 struct gdb_PyGetSetDef : PyGetSetDef
212 constexpr gdb_PyGetSetDef (const char *name_, getter get_, setter set_,
213 const char *doc_, void *closure_)
214 : PyGetSetDef {const_cast<char *> (name_), get_, set_,
215 const_cast<char *> (doc_), closure_}
218 /* Alternative constructor that allows omitting the closure in list
219 initialization. */
220 constexpr gdb_PyGetSetDef (const char *name_, getter get_, setter set_,
221 const char *doc_)
222 : gdb_PyGetSetDef {name_, get_, set_, doc_, NULL}
225 /* Constructor for the sentinel entries. */
226 constexpr gdb_PyGetSetDef (std::nullptr_t)
227 : gdb_PyGetSetDef {NULL, NULL, NULL, NULL, NULL}
231 /* The 'keywords' parameter of PyArg_ParseTupleAndKeywords has type
232 'char **'. However, string literals are const in C++, and so to
233 avoid casting at every keyword array definition, we'll need to make
234 the keywords array an array of 'const char *'. To avoid having all
235 callers add a 'const_cast<char **>' themselves when passing such an
236 array through 'char **', we define our own version of
237 PyArg_ParseTupleAndKeywords here with a corresponding 'keywords'
238 parameter type that does the cast in a single place. (This is not
239 an overload of PyArg_ParseTupleAndKeywords in order to make it
240 clearer that we're calling our own function instead of a function
241 that exists in some newer Python version.) */
243 static inline int
244 gdb_PyArg_ParseTupleAndKeywords (PyObject *args, PyObject *kw,
245 const char *format, const char **keywords, ...)
247 va_list ap;
248 int res;
250 va_start (ap, keywords);
251 res = PyArg_VaParseTupleAndKeywords (args, kw, format,
252 const_cast<char **> (keywords),
253 ap);
254 va_end (ap);
256 return res;
259 /* In order to be able to parse symtab_and_line_to_sal_object function
260 a real symtab_and_line structure is needed. */
261 #include "symtab.h"
263 /* Also needed to parse enum var_types. */
264 #include "command.h"
265 #include "breakpoint.h"
267 enum gdbpy_iter_kind { iter_keys, iter_values, iter_items };
269 struct block;
270 struct value;
271 struct language_defn;
272 struct program_space;
273 struct bpstat;
274 struct inferior;
276 extern int gdb_python_initialized;
278 extern PyObject *gdb_module;
279 extern PyObject *gdb_python_module;
280 extern PyTypeObject value_object_type
281 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("value_object");
282 extern PyTypeObject block_object_type
283 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF("block_object");
284 extern PyTypeObject symbol_object_type
285 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("symbol_object");
286 extern PyTypeObject event_object_type
287 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("event_object");
288 extern PyTypeObject breakpoint_object_type
289 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("breakpoint_object");
290 extern PyTypeObject frame_object_type
291 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("frame_object");
292 extern PyTypeObject thread_object_type
293 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("thread_object");
295 /* Ensure that breakpoint_object_type is initialized and return true. If
296 breakpoint_object_type can't be initialized then set a suitable Python
297 error and return false.
299 This function needs to be called from any gdbpy_initialize_* function
300 that wants to reference breakpoint_object_type. After all the
301 gdbpy_initialize_* functions have been called then breakpoint_object_type
302 is guaranteed to have been initialized, and this function does not need
303 calling before referencing breakpoint_object_type. */
305 extern bool gdbpy_breakpoint_init_breakpoint_type ();
307 struct gdbpy_breakpoint_object
309 PyObject_HEAD
311 /* The breakpoint number according to gdb. */
312 int number;
314 /* The gdb breakpoint object, or NULL if the breakpoint has been
315 deleted. */
316 struct breakpoint *bp;
318 /* 1 is this is a FinishBreakpoint object, 0 otherwise. */
319 int is_finish_bp;
322 /* Require that BREAKPOINT be a valid breakpoint ID; throw a Python
323 exception if it is invalid. */
324 #define BPPY_REQUIRE_VALID(Breakpoint) \
325 do { \
326 if ((Breakpoint)->bp == NULL) \
327 return PyErr_Format (PyExc_RuntimeError, \
328 _("Breakpoint %d is invalid."), \
329 (Breakpoint)->number); \
330 } while (0)
332 /* Require that BREAKPOINT be a valid breakpoint ID; throw a Python
333 exception if it is invalid. This macro is for use in setter functions. */
334 #define BPPY_SET_REQUIRE_VALID(Breakpoint) \
335 do { \
336 if ((Breakpoint)->bp == NULL) \
338 PyErr_Format (PyExc_RuntimeError, _("Breakpoint %d is invalid."), \
339 (Breakpoint)->number); \
340 return -1; \
342 } while (0)
345 /* Variables used to pass information between the Breakpoint
346 constructor and the breakpoint-created hook function. */
347 extern gdbpy_breakpoint_object *bppy_pending_object;
350 struct thread_object
352 PyObject_HEAD
354 /* The thread we represent. */
355 struct thread_info *thread;
357 /* The Inferior object to which this thread belongs. */
358 PyObject *inf_obj;
360 /* Dictionary holding user-added attributes. This is the __dict__
361 attribute of the object. */
362 PyObject *dict;
365 struct inferior_object;
367 extern struct cmd_list_element *set_python_list;
368 extern struct cmd_list_element *show_python_list;
370 /* extension_language_script_ops "methods". */
372 /* Return true if auto-loading Python scripts is enabled.
373 This is the extension_language_script_ops.auto_load_enabled "method". */
375 extern bool gdbpy_auto_load_enabled (const struct extension_language_defn *);
377 /* extension_language_ops "methods". */
379 extern enum ext_lang_rc gdbpy_apply_val_pretty_printer
380 (const struct extension_language_defn *,
381 struct value *value,
382 struct ui_file *stream, int recurse,
383 const struct value_print_options *options,
384 const struct language_defn *language);
385 extern enum ext_lang_bt_status gdbpy_apply_frame_filter
386 (const struct extension_language_defn *,
387 const frame_info_ptr &frame, frame_filter_flags flags,
388 enum ext_lang_frame_args args_type,
389 struct ui_out *out, int frame_low, int frame_high);
390 extern void gdbpy_preserve_values (const struct extension_language_defn *,
391 struct objfile *objfile,
392 htab_t copied_types);
393 extern enum ext_lang_bp_stop gdbpy_breakpoint_cond_says_stop
394 (const struct extension_language_defn *, struct breakpoint *);
395 extern int gdbpy_breakpoint_has_cond (const struct extension_language_defn *,
396 struct breakpoint *b);
398 extern enum ext_lang_rc gdbpy_get_matching_xmethod_workers
399 (const struct extension_language_defn *extlang,
400 struct type *obj_type, const char *method_name,
401 std::vector<xmethod_worker_up> *dm_vec);
404 PyObject *gdbpy_history (PyObject *self, PyObject *args);
405 PyObject *gdbpy_add_history (PyObject *self, PyObject *args);
406 extern PyObject *gdbpy_history_count (PyObject *self, PyObject *args);
407 PyObject *gdbpy_convenience_variable (PyObject *self, PyObject *args);
408 PyObject *gdbpy_set_convenience_variable (PyObject *self, PyObject *args);
409 PyObject *gdbpy_breakpoints (PyObject *, PyObject *);
410 PyObject *gdbpy_frame_stop_reason_string (PyObject *, PyObject *);
411 PyObject *gdbpy_lookup_symbol (PyObject *self, PyObject *args, PyObject *kw);
412 PyObject *gdbpy_lookup_global_symbol (PyObject *self, PyObject *args,
413 PyObject *kw);
414 PyObject *gdbpy_lookup_static_symbol (PyObject *self, PyObject *args,
415 PyObject *kw);
416 PyObject *gdbpy_lookup_static_symbols (PyObject *self, PyObject *args,
417 PyObject *kw);
418 PyObject *gdbpy_start_recording (PyObject *self, PyObject *args);
419 PyObject *gdbpy_current_recording (PyObject *self, PyObject *args);
420 PyObject *gdbpy_stop_recording (PyObject *self, PyObject *args);
421 PyObject *gdbpy_newest_frame (PyObject *self, PyObject *args);
422 PyObject *gdbpy_selected_frame (PyObject *self, PyObject *args);
423 PyObject *gdbpy_lookup_type (PyObject *self, PyObject *args, PyObject *kw);
424 int gdbpy_is_field (PyObject *obj);
425 PyObject *gdbpy_create_lazy_string_object (CORE_ADDR address, long length,
426 const char *encoding,
427 struct type *type);
428 PyObject *gdbpy_inferiors (PyObject *unused, PyObject *unused2);
429 PyObject *gdbpy_create_ptid_object (ptid_t ptid);
430 PyObject *gdbpy_selected_thread (PyObject *self, PyObject *args);
431 PyObject *gdbpy_selected_inferior (PyObject *self, PyObject *args);
432 PyObject *gdbpy_string_to_argv (PyObject *self, PyObject *args);
433 PyObject *gdbpy_parameter_value (const setting &var);
434 gdb::unique_xmalloc_ptr<char> gdbpy_parse_command_name
435 (const char *name, struct cmd_list_element ***base_list,
436 struct cmd_list_element **start_list);
437 PyObject *gdbpy_register_tui_window (PyObject *self, PyObject *args,
438 PyObject *kw);
440 PyObject *symtab_and_line_to_sal_object (struct symtab_and_line sal);
441 PyObject *symtab_to_symtab_object (struct symtab *symtab);
442 PyObject *symbol_to_symbol_object (struct symbol *sym);
443 PyObject *block_to_block_object (const struct block *block,
444 struct objfile *objfile);
445 PyObject *value_to_value_object (struct value *v);
446 PyObject *type_to_type_object (struct type *);
447 PyObject *frame_info_to_frame_object (const frame_info_ptr &frame);
448 PyObject *symtab_to_linetable_object (PyObject *symtab);
449 gdbpy_ref<> pspace_to_pspace_object (struct program_space *);
450 PyObject *pspy_get_printers (PyObject *, void *);
451 PyObject *pspy_get_frame_filters (PyObject *, void *);
452 PyObject *pspy_get_frame_unwinders (PyObject *, void *);
453 PyObject *pspy_get_xmethods (PyObject *, void *);
455 gdbpy_ref<> objfile_to_objfile_object (struct objfile *);
456 PyObject *objfpy_get_printers (PyObject *, void *);
457 PyObject *objfpy_get_frame_filters (PyObject *, void *);
458 PyObject *objfpy_get_frame_unwinders (PyObject *, void *);
459 PyObject *objfpy_get_xmethods (PyObject *, void *);
460 PyObject *gdbpy_lookup_objfile (PyObject *self, PyObject *args, PyObject *kw);
462 PyObject *gdbarch_to_arch_object (struct gdbarch *gdbarch);
463 PyObject *gdbpy_all_architecture_names (PyObject *self, PyObject *args);
465 PyObject *gdbpy_new_register_descriptor_iterator (struct gdbarch *gdbarch,
466 const char *group_name);
467 PyObject *gdbpy_new_reggroup_iterator (struct gdbarch *gdbarch);
469 gdbpy_ref<thread_object> create_thread_object (struct thread_info *tp);
470 gdbpy_ref<> thread_to_thread_object (thread_info *thr);;
471 gdbpy_ref<inferior_object> inferior_to_inferior_object (inferior *inf);
473 PyObject *gdbpy_buffer_to_membuf (gdb::unique_xmalloc_ptr<gdb_byte> buffer,
474 CORE_ADDR address, ULONGEST length);
476 struct process_stratum_target;
477 gdbpy_ref<> target_to_connection_object (process_stratum_target *target);
478 PyObject *gdbpy_connections (PyObject *self, PyObject *args);
480 const struct block *block_object_to_block (PyObject *obj);
481 struct symbol *symbol_object_to_symbol (PyObject *obj);
482 struct value *value_object_to_value (PyObject *self);
483 struct value *convert_value_from_python (PyObject *obj);
484 struct type *type_object_to_type (PyObject *obj);
485 struct symtab *symtab_object_to_symtab (PyObject *obj);
486 struct symtab_and_line *sal_object_to_symtab_and_line (PyObject *obj);
487 frame_info_ptr frame_object_to_frame_info (PyObject *frame_obj);
488 struct gdbarch *arch_object_to_gdbarch (PyObject *obj);
490 extern PyObject *gdbpy_execute_mi_command (PyObject *self, PyObject *args,
491 PyObject *kw);
493 /* Serialize RESULTS and print it in MI format to the current_uiout.
495 This function handles the top-level results passed as a dictionary.
496 The caller is responsible for ensuring that. The values within this
497 dictionary can be a wider range of types. Handling the values of the top-level
498 dictionary is done by serialize_mi_result_1, see that function for more
499 details.
501 If anything goes wrong while parsing and printing the MI output then an
502 error is thrown. */
504 extern void serialize_mi_results (PyObject *results);
506 /* Implementation of the gdb.notify_mi function. */
508 extern PyObject *gdbpy_notify_mi (PyObject *self, PyObject *args,
509 PyObject *kw);
511 /* Convert Python object OBJ to a program_space pointer. OBJ must be a
512 gdb.Progspace reference. Return nullptr if the gdb.Progspace is not
513 valid (see gdb.Progspace.is_valid), otherwise return the program_space
514 pointer. */
516 extern struct program_space *progspace_object_to_program_space (PyObject *obj);
518 /* A class for managing the initialization, and finalization functions
519 from all Python files (e.g. gdb/python/py-*.c).
521 Within any Python file, create an instance of this class, passing in
522 the initialization function, and, optionally, the finalization
523 function.
525 These functions are added to a single global list of functions, which
526 can then be called from do_start_initialization and finalize_python
527 (see python.c) to initialize all the Python files within GDB. */
529 class gdbpy_initialize_file
531 /* The type of a function that can be called just after GDB has setup the
532 Python interpreter. This function will setup any additional Python
533 state required by a particular subsystem. Return 0 if the setup was
534 successful, or return -1 if setup failed, in which case a Python
535 exception should have been raised. */
537 using gdbpy_initialize_file_ftype = int (*) (void);
539 /* The type of a function that can be called just before GDB shuts down
540 the Python interpreter. This function can cleanup an Python state
541 that is cached within GDB, for example, if GDB is holding any
542 references to Python objects, these should be released before the
543 Python interpreter is shut down.
545 There is no error return in this case. This function is only called
546 when GDB is already shutting down. The function should make a best
547 effort to clean up, and then return. */
549 using gdbpy_finalize_file_ftype = void (*) (void);
551 /* The type for an initialization and finalization function pair. */
553 using callback_pair_t = std::pair<gdbpy_initialize_file_ftype,
554 gdbpy_finalize_file_ftype>;
556 /* Return the vector of callbacks. The vector is defined as a static
557 variable within this function so that it will be initialized the first
558 time this function is called. This is important, as this function is
559 called as part of the global object initialization process; if the
560 vector was a static variable within this class then we could not
561 guarantee that it had been initialized before it was used. */
563 static std::vector<callback_pair_t> &
564 callbacks ()
566 static std::vector<callback_pair_t> list;
567 return list;
570 public:
572 /* Register the initialization (INIT) and finalization (FINI) functions
573 for a Python file. See the comments on the function types above for
574 when these functions will be called.
576 Either of these functions can be nullptr, in which case no function
577 will be called.
579 The FINI argument is optional, and defaults to nullptr (no function to
580 call). */
582 gdbpy_initialize_file (gdbpy_initialize_file_ftype init,
583 gdbpy_finalize_file_ftype fini = nullptr)
585 callbacks ().emplace_back (init, fini);
588 /* Run all the Python file initialize functions and return true. If any
589 of the initialize functions fails then this function returns false.
590 In the case of failure it is undefined how many of the initialize
591 functions will have been called. */
593 static bool
594 initialize_all ()
596 /* The initialize_all function should only be called once. The
597 following check reverses the global list, which will effect this
598 initialize_all call, as well as the later finalize_all call.
600 The environment variable checked here is the same as the one checked
601 in the generated init.c file. */
602 if (getenv ("GDB_REVERSE_INIT_FUNCTIONS") != nullptr)
603 std::reverse (callbacks ().begin (), callbacks ().end ());
605 for (const auto &p : gdbpy_initialize_file::callbacks ())
607 if (p.first != nullptr && p.first () < 0)
608 return false;
610 return true;
613 /* Run all the Python file finalize functions. */
615 static void
616 finalize_all ()
618 for (const auto &p : gdbpy_initialize_file::callbacks ())
620 if (p.second != nullptr)
621 p.second ();
626 /* Macro to simplify registering the initialization and finalization
627 functions for a Python file. */
629 #define GDBPY_INITIALIZE_FILE(INIT, ...) \
630 static gdbpy_initialize_file \
631 CONCAT(gdbpy_initialize_file_obj_, __LINE__) (INIT, ##__VA_ARGS__)
633 PyMODINIT_FUNC gdbpy_events_mod_func ();
635 /* A wrapper for PyErr_Fetch that handles reference counting for the
636 caller. */
637 class gdbpy_err_fetch
639 public:
641 gdbpy_err_fetch ()
643 #if PY_VERSION_HEX < 0x030c0000
644 PyObject *error_type, *error_value, *error_traceback;
646 PyErr_Fetch (&error_type, &error_value, &error_traceback);
647 m_error_type.reset (error_type);
648 m_error_value.reset (error_value);
649 m_error_traceback.reset (error_traceback);
650 #else
651 /* PyErr_Fetch is deprecated in python 3.12, use PyErr_GetRaisedException
652 instead. */
653 m_exc.reset (PyErr_GetRaisedException ());
654 #endif
657 /* Call PyErr_Restore using the values stashed in this object.
658 After this call, this object is invalid and neither the to_string
659 nor restore methods may be used again. */
661 void restore ()
663 #if PY_VERSION_HEX < 0x030c0000
664 PyErr_Restore (m_error_type.release (),
665 m_error_value.release (),
666 m_error_traceback.release ());
667 #else
668 /* PyErr_Restore is deprecated in python 3.12, use PyErr_SetRaisedException
669 instead. */
670 PyErr_SetRaisedException (m_exc.release ());
671 #endif
674 /* Return the string representation of the exception represented by
675 this object. If the result is NULL a python error occurred, the
676 caller must clear it. */
678 gdb::unique_xmalloc_ptr<char> to_string () const;
680 /* Return the string representation of the type of the exception
681 represented by this object. If the result is NULL a python error
682 occurred, the caller must clear it. */
684 gdb::unique_xmalloc_ptr<char> type_to_string () const;
686 /* Return true if the stored type matches TYPE, false otherwise. */
688 bool type_matches (PyObject *type) const
690 gdbpy_ref<> err_type = this->type ();
691 return PyErr_GivenExceptionMatches (err_type.get (), type);
694 /* Return a new reference to the exception value object. */
696 gdbpy_ref<> value () const
698 #if PY_VERSION_HEX < 0x030c0000
699 if (!m_normalized)
701 PyObject *error_type, *error_value, *error_traceback;
702 error_type = m_error_type.release ();
703 error_value = m_error_value.release ();
704 error_traceback = m_error_traceback.release ();
705 PyErr_NormalizeException (&error_type, &error_value, &error_traceback);
706 m_error_type.reset (error_type);
707 m_error_value.reset (error_value);
708 m_error_traceback.reset (error_traceback);
709 m_normalized = true;
711 return m_error_value;
712 #else
713 return m_exc;
714 #endif
717 /* Return a new reference to the exception type object. */
719 gdbpy_ref<> type () const
721 #if PY_VERSION_HEX < 0x030c0000
722 return m_error_type;
723 #else
724 if (m_exc.get() == nullptr)
725 return nullptr;
726 return gdbpy_ref<>::new_reference ((PyObject *)Py_TYPE (m_exc.get ()));
727 #endif
730 private:
732 #if PY_VERSION_HEX < 0x030c0000
733 mutable gdbpy_ref<> m_error_type, m_error_value, m_error_traceback;
734 mutable bool m_normalized = false;
735 #else
736 gdbpy_ref<> m_exc;
737 #endif
740 /* Called before entering the Python interpreter to install the
741 current language and architecture to be used for Python values.
742 Also set the active extension language for GDB so that SIGINT's
743 are directed our way, and if necessary install the right SIGINT
744 handler. */
745 class gdbpy_enter
747 public:
749 /* Set the ambient Python architecture to GDBARCH and the language
750 to LANGUAGE. If GDBARCH is nullptr, then the architecture will
751 be computed, when needed, using get_current_arch; see the
752 get_gdbarch method. If LANGUAGE is not nullptr, then the current
753 language at time of construction will be saved (to be restored on
754 destruction), and the current language will be set to
755 LANGUAGE. */
756 explicit gdbpy_enter (struct gdbarch *gdbarch = nullptr,
757 const struct language_defn *language = nullptr);
759 ~gdbpy_enter ();
761 DISABLE_COPY_AND_ASSIGN (gdbpy_enter);
763 /* Return the current gdbarch, as known to the Python layer. This
764 is either python_gdbarch (which comes from the most recent call
765 to the gdbpy_enter constructor), or, if that is nullptr, the
766 result of get_current_arch. */
767 static struct gdbarch *get_gdbarch ();
769 /* Called only during gdb shutdown. This sets python_gdbarch to an
770 acceptable value. */
771 static void finalize ();
773 private:
775 /* The current gdbarch, according to Python. This can be
776 nullptr. */
777 static struct gdbarch *python_gdbarch;
779 struct active_ext_lang_state *m_previous_active;
780 PyGILState_STATE m_state;
781 struct gdbarch *m_gdbarch;
782 const struct language_defn *m_language;
784 /* An optional is used here because we don't want to call
785 PyErr_Fetch too early. */
786 std::optional<gdbpy_err_fetch> m_error;
789 /* Like gdbpy_enter, but takes a varobj. This is a subclass just to
790 make constructor delegation a little nicer. */
791 class gdbpy_enter_varobj : public gdbpy_enter
793 public:
795 /* This is defined in varobj.c, where it can access varobj
796 internals. */
797 gdbpy_enter_varobj (const struct varobj *var);
801 /* The opposite of gdb_enter: this releases the GIL around a region,
802 allowing other Python threads to run. No Python APIs may be used
803 while this is active. */
804 class gdbpy_allow_threads
806 public:
808 gdbpy_allow_threads ()
809 : m_save (PyEval_SaveThread ())
811 gdb_assert (m_save != nullptr);
814 ~gdbpy_allow_threads ()
816 PyEval_RestoreThread (m_save);
819 DISABLE_COPY_AND_ASSIGN (gdbpy_allow_threads);
821 private:
823 PyThreadState *m_save;
826 /* A helper class to save and restore the GIL, but without touching
827 the other globals that are handled by gdbpy_enter. */
829 class gdbpy_gil
831 public:
833 gdbpy_gil ()
834 : m_state (PyGILState_Ensure ())
838 ~gdbpy_gil ()
840 PyGILState_Release (m_state);
843 DISABLE_COPY_AND_ASSIGN (gdbpy_gil);
845 private:
847 PyGILState_STATE m_state;
850 /* Use this in a 'catch' block to convert the exception to a Python
851 exception and return nullptr. */
852 #define GDB_PY_HANDLE_EXCEPTION(Exception) \
853 do { \
854 gdbpy_convert_exception (Exception); \
855 return nullptr; \
856 } while (0)
858 /* Use this in a 'catch' block to convert the exception to a Python
859 exception and return -1. */
860 #define GDB_PY_SET_HANDLE_EXCEPTION(Exception) \
861 do { \
862 gdbpy_convert_exception (Exception); \
863 return -1; \
864 } while (0)
866 int gdbpy_print_python_errors_p (void);
867 void gdbpy_print_stack (void);
868 void gdbpy_print_stack_or_quit ();
869 void gdbpy_handle_exception () ATTRIBUTE_NORETURN;
871 /* A wrapper around calling 'error'. Prefixes the error message with an
872 'Error occurred in Python' string. Use this in C++ code if we spot
873 something wrong with an object returned from Python code. The prefix
874 string gives the user a hint that the mistake is within Python code,
875 rather than some other part of GDB.
877 This always calls error, and never returns. */
879 void gdbpy_error (const char *fmt, ...)
880 ATTRIBUTE_NORETURN ATTRIBUTE_PRINTF (1, 2);
882 gdbpy_ref<> python_string_to_unicode (PyObject *obj);
883 gdb::unique_xmalloc_ptr<char> unicode_to_target_string (PyObject *unicode_str);
884 gdb::unique_xmalloc_ptr<char> python_string_to_target_string (PyObject *obj);
885 gdbpy_ref<> python_string_to_target_python_string (PyObject *obj);
886 gdb::unique_xmalloc_ptr<char> python_string_to_host_string (PyObject *obj);
887 gdbpy_ref<> host_string_to_python_string (const char *str);
888 int gdbpy_is_string (PyObject *obj);
889 gdb::unique_xmalloc_ptr<char> gdbpy_obj_to_string (PyObject *obj);
891 int gdbpy_is_lazy_string (PyObject *result);
892 void gdbpy_extract_lazy_string (PyObject *string, CORE_ADDR *addr,
893 struct type **str_type,
894 long *length,
895 gdb::unique_xmalloc_ptr<char> *encoding);
897 int gdbpy_is_value_object (PyObject *obj);
899 /* Note that these are declared here, and not in python.h with the
900 other pretty-printer functions, because they refer to PyObject. */
901 gdbpy_ref<> apply_varobj_pretty_printer (PyObject *print_obj,
902 struct value **replacement,
903 struct ui_file *stream,
904 const value_print_options *opts);
905 gdbpy_ref<> gdbpy_get_varobj_pretty_printer (struct value *value);
906 gdb::unique_xmalloc_ptr<char> gdbpy_get_display_hint (PyObject *printer);
907 PyObject *gdbpy_default_visualizer (PyObject *self, PyObject *args);
909 PyObject *gdbpy_print_options (PyObject *self, PyObject *args);
910 void gdbpy_get_print_options (value_print_options *opts);
911 extern const struct value_print_options *gdbpy_current_print_options;
913 void bpfinishpy_pre_stop_hook (struct gdbpy_breakpoint_object *bp_obj);
914 void bpfinishpy_post_stop_hook (struct gdbpy_breakpoint_object *bp_obj);
915 void bpfinishpy_pre_delete_hook (struct gdbpy_breakpoint_object *bp_obj);
917 extern PyObject *gdbpy_doc_cst;
918 extern PyObject *gdbpy_children_cst;
919 extern PyObject *gdbpy_to_string_cst;
920 extern PyObject *gdbpy_display_hint_cst;
921 extern PyObject *gdbpy_enabled_cst;
922 extern PyObject *gdbpy_value_cst;
924 /* Exception types. */
925 extern PyObject *gdbpy_gdb_error;
926 extern PyObject *gdbpy_gdb_memory_error;
927 extern PyObject *gdbpy_gdberror_exc;
929 extern void gdbpy_convert_exception (const struct gdb_exception &)
930 CPYCHECKER_SETS_EXCEPTION;
932 int get_addr_from_python (PyObject *obj, CORE_ADDR *addr)
933 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION;
935 gdbpy_ref<> gdb_py_object_from_longest (LONGEST l);
936 gdbpy_ref<> gdb_py_object_from_ulongest (ULONGEST l);
937 int gdb_py_int_as_long (PyObject *, long *);
939 PyObject *gdb_py_generic_dict (PyObject *self, void *closure);
941 int gdb_pymodule_addobject (PyObject *module, const char *name,
942 PyObject *object)
943 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION;
946 /* Return a Python string (str) object that represents SELF. SELF can be
947 any object type, but should be in an "invalid" state. What "invalid"
948 means is up to the caller. The returned string will take the form
949 "<TYPENAME (invalid)>", without the quotes, and with TYPENAME replaced
950 with the type of SELF. */
952 PyObject *gdb_py_invalid_object_repr (PyObject *self);
954 struct varobj_iter;
955 struct varobj;
956 std::unique_ptr<varobj_iter> py_varobj_get_iterator
957 (struct varobj *var,
958 PyObject *printer,
959 const value_print_options *opts);
961 /* Deleter for Py_buffer unique_ptr specialization. */
963 struct Py_buffer_deleter
965 void operator() (Py_buffer *b) const
967 PyBuffer_Release (b);
971 /* A unique_ptr specialization for Py_buffer. */
972 typedef std::unique_ptr<Py_buffer, Py_buffer_deleter> Py_buffer_up;
974 /* Parse a register number from PYO_REG_ID and place the register number
975 into *REG_NUM. The register is a register for GDBARCH.
977 If a register is parsed successfully then *REG_NUM will have been
978 updated, and true is returned. Otherwise the contents of *REG_NUM are
979 undefined, and false is returned. When false is returned, the
980 Python error is set.
982 The PYO_REG_ID object can be a string, the name of the register. This
983 is the slowest approach as GDB has to map the name to a number for each
984 call. Alternatively PYO_REG_ID can be an internal GDB register
985 number. This is quick but should not be encouraged as this means
986 Python scripts are now dependent on GDB's internal register numbering.
987 Final PYO_REG_ID can be a gdb.RegisterDescriptor object, these objects
988 can be looked up by name once, and then cache the register number so
989 should be as quick as using a register number. */
991 extern bool gdbpy_parse_register_id (struct gdbarch *gdbarch,
992 PyObject *pyo_reg_id, int *reg_num);
994 /* Return true if OBJ is a gdb.Architecture object, otherwise, return
995 false. */
997 extern bool gdbpy_is_architecture (PyObject *obj);
999 /* Return true if OBJ is a gdb.Progspace object, otherwise, return false. */
1001 extern bool gdbpy_is_progspace (PyObject *obj);
1003 /* Take DOC, the documentation string for a GDB command defined in Python,
1004 and return an (possibly) modified version of that same string.
1006 When a command is defined in Python, the documentation string will
1007 usually be indented based on the indentation of the surrounding Python
1008 code. However, the documentation string is a literal string, all the
1009 white-space added for indentation is included within the documentation
1010 string.
1012 This indentation is then included in the help text that GDB displays,
1013 which looks odd out of the context of the original Python source code.
1015 This function analyses DOC and tries to figure out what white-space
1016 within DOC was added as part of the indentation, and then removes that
1017 white-space from the copy that is returned.
1019 If the analysis of DOC fails then DOC will be returned unmodified. */
1021 extern gdb::unique_xmalloc_ptr<char> gdbpy_fix_doc_string_indentation
1022 (gdb::unique_xmalloc_ptr<char> doc);
1024 /* Implement the 'print_insn' hook for Python. Disassemble an instruction
1025 whose address is ADDRESS for architecture GDBARCH. The bytes of the
1026 instruction should be read with INFO->read_memory_func as the
1027 instruction being disassembled might actually be in a buffer.
1029 Used INFO->fprintf_func to print the results of the disassembly, and
1030 return the length of the instruction in octets.
1032 If no instruction can be disassembled then return an empty value. */
1034 extern std::optional<int> gdbpy_print_insn (struct gdbarch *gdbarch,
1035 CORE_ADDR address,
1036 disassemble_info *info);
1038 #endif /* PYTHON_PYTHON_INTERNAL_H */