]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/python/python-internal.h
gas: introduce .errif and .warnif
[thirdparty/binutils-gdb.git] / gdb / python / python-internal.h
1 /* Gdb/Python header for private use by Python module.
2
3 Copyright (C) 2008-2025 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 #ifndef GDB_PYTHON_PYTHON_INTERNAL_H
21 #define GDB_PYTHON_PYTHON_INTERNAL_H
22
23 #include "extension.h"
24 #include "extension-priv.h"
25 #include "registry.h"
26
27 /* These WITH_* macros are defined by the CPython API checker that
28 comes with the Python plugin for GCC. See:
29 https://gcc-python-plugin.readthedocs.org/en/latest/cpychecker.html
30 The checker defines a WITH_ macro for each attribute it
31 exposes. Note that we intentionally do not use
32 'cpychecker_returns_borrowed_ref' -- that idiom is forbidden in
33 gdb. */
34
35 #ifdef WITH_CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF_ATTRIBUTE
36 #define CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF(ARG) \
37 __attribute__ ((cpychecker_type_object_for_typedef (ARG)))
38 #else
39 #define CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF(ARG)
40 #endif
41
42 #ifdef WITH_CPYCHECKER_SETS_EXCEPTION_ATTRIBUTE
43 #define CPYCHECKER_SETS_EXCEPTION __attribute__ ((cpychecker_sets_exception))
44 #else
45 #define CPYCHECKER_SETS_EXCEPTION
46 #endif
47
48 #ifdef WITH_CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION_ATTRIBUTE
49 #define CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION \
50 __attribute__ ((cpychecker_negative_result_sets_exception))
51 #else
52 #define CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION
53 #endif
54
55 /* /usr/include/features.h on linux systems will define _POSIX_C_SOURCE
56 if it sees _GNU_SOURCE (which config.h will define).
57 pyconfig.h defines _POSIX_C_SOURCE to a different value than
58 /usr/include/features.h does causing compilation to fail.
59 To work around this, undef _POSIX_C_SOURCE before we include Python.h.
60
61 Same problem with _XOPEN_SOURCE. */
62 #undef _POSIX_C_SOURCE
63 #undef _XOPEN_SOURCE
64
65 /* On sparc-solaris, /usr/include/sys/feature_tests.h defines
66 _FILE_OFFSET_BITS, which pyconfig.h also defines. Same work
67 around technique as above. */
68 #undef _FILE_OFFSET_BITS
69
70 /* A kludge to avoid redefinition of snprintf on Windows by pyerrors.h. */
71 #if defined(_WIN32) && defined(HAVE_DECL_SNPRINTF)
72 #define HAVE_SNPRINTF 1
73 #endif
74
75 /* Another kludge to avoid compilation errors because MinGW defines
76 'hypot' to '_hypot', but the C++ headers says "using ::hypot". */
77 #ifdef __MINGW32__
78 # define _hypot hypot
79 #endif
80
81 /* Request clean size types from Python. */
82 #define PY_SSIZE_T_CLEAN
83
84 /* Include the Python header files using angle brackets rather than
85 double quotes. On case-insensitive filesystems, this prevents us
86 from including our python/python.h header file. */
87 #include <Python.h>
88 #include <frameobject.h>
89 #include "py-ref.h"
90
91 static_assert (PY_VERSION_HEX >= 0x03040000);
92
93 #define Py_TPFLAGS_CHECKTYPES 0
94
95 /* If Python.h does not define WITH_THREAD, then the various
96 GIL-related functions will not be defined. However,
97 PyGILState_STATE will be. */
98 #ifndef WITH_THREAD
99 #define PyGILState_Ensure() ((PyGILState_STATE) 0)
100 #define PyGILState_Release(ARG) ((void)(ARG))
101 #define PyEval_InitThreads()
102 #define PyThreadState_Swap(ARG) ((void)(ARG))
103 #define PyEval_ReleaseLock()
104 #endif
105
106 /* Python supplies HAVE_LONG_LONG and some `long long' support when it
107 is available. These defines let us handle the differences more
108 cleanly.
109
110 Starting with python 3.6, support for platforms without long long support
111 has been removed [1]. HAVE_LONG_LONG and PY_LONG_LONG are still defined,
112 but only for compatibility, so we no longer rely on them.
113
114 [1] https://github.com/python/cpython/issues/72148. */
115 #if PY_VERSION_HEX >= 0x03060000 || defined (HAVE_LONG_LONG)
116
117 #define GDB_PY_LL_ARG "L"
118 #define GDB_PY_LLU_ARG "K"
119 #if PY_VERSION_HEX >= 0x03060000
120 typedef long long gdb_py_longest;
121 typedef unsigned long long gdb_py_ulongest;
122 #else
123 typedef PY_LONG_LONG gdb_py_longest;
124 typedef unsigned PY_LONG_LONG gdb_py_ulongest;
125 #endif
126 #define gdb_py_long_as_ulongest PyLong_AsUnsignedLongLong
127 #define gdb_py_long_as_long_and_overflow PyLong_AsLongLongAndOverflow
128
129 #else /* HAVE_LONG_LONG */
130
131 #define GDB_PY_LL_ARG "l"
132 #define GDB_PY_LLU_ARG "k"
133 typedef long gdb_py_longest;
134 typedef unsigned long gdb_py_ulongest;
135 #define gdb_py_long_as_ulongest PyLong_AsUnsignedLong
136 #define gdb_py_long_as_long_and_overflow PyLong_AsLongAndOverflow
137
138 #endif /* HAVE_LONG_LONG */
139
140 /* A template variable holding the format character (as for
141 Py_BuildValue) for a given type. */
142 template<typename T>
143 struct gdbpy_method_format {};
144
145 template<>
146 struct gdbpy_method_format<gdb_py_longest>
147 {
148 static constexpr char format = GDB_PY_LL_ARG[0];
149 };
150
151 template<>
152 struct gdbpy_method_format<gdb_py_ulongest>
153 {
154 static constexpr char format = GDB_PY_LLU_ARG[0];
155 };
156
157 template<>
158 struct gdbpy_method_format<int>
159 {
160 static constexpr char format = 'i';
161 };
162
163 template<>
164 struct gdbpy_method_format<unsigned>
165 {
166 static constexpr char format = 'I';
167 };
168
169 /* A helper function to compute the PyObject_CallMethod /
170 Py_BuildValue format given the argument types. */
171
172 template<typename... Args>
173 constexpr std::array<char, sizeof... (Args) + 1>
174 gdbpy_make_fmt ()
175 {
176 return { gdbpy_method_format<Args>::format..., '\0' };
177 }
178
179 /* Typesafe wrapper around PyObject_CallMethod.
180
181 This variant accepts no arguments. */
182
183 static inline gdbpy_ref<>
184 gdbpy_call_method (PyObject *o, const char *method)
185 {
186 /* PyObject_CallMethod's 'method' and 'format' parameters were missing the
187 'const' qualifier before Python 3.4. */
188 return gdbpy_ref<> (PyObject_CallMethod (o,
189 const_cast<char *> (method),
190 nullptr));
191 }
192
193 /* Typesafe wrapper around PyObject_CallMethod.
194
195 This variant accepts any number of arguments and automatically
196 computes the format string, ensuring that format/argument
197 mismatches are impossible. */
198
199 template<typename Arg, typename... Args>
200 static inline gdbpy_ref<>
201 gdbpy_call_method (PyObject *o, const char *method,
202 Arg arg, Args... args)
203 {
204 constexpr const auto fmt = gdbpy_make_fmt<Arg, Args...> ();
205
206 /* PyObject_CallMethod's 'method' and 'format' parameters were missing the
207 'const' qualifier before Python 3.4. */
208 return gdbpy_ref<> (PyObject_CallMethod (o,
209 const_cast<char *> (method),
210 const_cast<char *> (fmt.data ()),
211 arg, args...));
212 }
213
214 /* An overload that takes a gdbpy_ref<> rather than a raw 'PyObject *'. */
215
216 template<typename... Args>
217 static inline gdbpy_ref<>
218 gdbpy_call_method (const gdbpy_ref<> &o, const char *method, Args... args)
219 {
220 return gdbpy_call_method (o.get (), method, args...);
221 }
222
223 /* Poison PyObject_CallMethod. The typesafe wrapper gdbpy_call_method should be
224 used instead. */
225 #undef PyObject_CallMethod
226 #ifdef __GNUC__
227 # pragma GCC poison PyObject_CallMethod
228 #else
229 # define PyObject_CallMethod POISONED_PyObject_CallMethod
230 #endif
231
232 /* The 'name' parameter of PyErr_NewException was missing the 'const'
233 qualifier in Python <= 3.4. Hence, we wrap it in a function to
234 avoid errors when compiled with -Werror. */
235
236 static inline PyObject*
237 gdb_PyErr_NewException (const char *name, PyObject *base, PyObject *dict)
238 {
239 return PyErr_NewException (const_cast<char *> (name), base, dict);
240 }
241
242 #define PyErr_NewException gdb_PyErr_NewException
243
244 /* PySys_GetObject's 'name' parameter was missing the 'const'
245 qualifier before Python 3.4. Hence, we wrap it in a function to
246 avoid errors when compiled with -Werror. */
247
248 static inline PyObject *
249 gdb_PySys_GetObject (const char *name)
250 {
251 return PySys_GetObject (const_cast<char *> (name));
252 }
253
254 #define PySys_GetObject gdb_PySys_GetObject
255
256 /* PySys_SetPath was deprecated in Python 3.11. Disable the deprecated
257 code for Python 3.10 and newer. */
258 #if PY_VERSION_HEX < 0x030a0000
259
260 /* PySys_SetPath's 'path' parameter was missing the 'const' qualifier
261 before Python 3.6. Hence, we wrap it in a function to avoid errors
262 when compiled with -Werror. */
263
264 # define GDB_PYSYS_SETPATH_CHAR wchar_t
265
266 static inline void
267 gdb_PySys_SetPath (const GDB_PYSYS_SETPATH_CHAR *path)
268 {
269 PySys_SetPath (const_cast<GDB_PYSYS_SETPATH_CHAR *> (path));
270 }
271
272 #define PySys_SetPath gdb_PySys_SetPath
273 #endif
274
275 /* Wrap PyGetSetDef to allow convenient construction with string
276 literals. Unfortunately, PyGetSetDef's 'name' and 'doc' members
277 are 'char *' instead of 'const char *', meaning that in order to
278 list-initialize PyGetSetDef arrays with string literals (and
279 without the wrapping below) would require writing explicit 'char *'
280 casts. Instead, we extend PyGetSetDef and add constexpr
281 constructors that accept const 'name' and 'doc', hiding the ugly
282 casts here in a single place. */
283
284 struct gdb_PyGetSetDef : PyGetSetDef
285 {
286 constexpr gdb_PyGetSetDef (const char *name_, getter get_, setter set_,
287 const char *doc_, void *closure_)
288 : PyGetSetDef {const_cast<char *> (name_), get_, set_,
289 const_cast<char *> (doc_), closure_}
290 {}
291
292 /* Alternative constructor that allows omitting the closure in list
293 initialization. */
294 constexpr gdb_PyGetSetDef (const char *name_, getter get_, setter set_,
295 const char *doc_)
296 : gdb_PyGetSetDef {name_, get_, set_, doc_, NULL}
297 {}
298
299 /* Constructor for the sentinel entries. */
300 constexpr gdb_PyGetSetDef (std::nullptr_t)
301 : gdb_PyGetSetDef {NULL, NULL, NULL, NULL, NULL}
302 {}
303 };
304
305 /* The 'keywords' parameter of PyArg_ParseTupleAndKeywords has type
306 'char **'. However, string literals are const in C++, and so to
307 avoid casting at every keyword array definition, we'll need to make
308 the keywords array an array of 'const char *'. To avoid having all
309 callers add a 'const_cast<char **>' themselves when passing such an
310 array through 'char **', we define our own version of
311 PyArg_ParseTupleAndKeywords here with a corresponding 'keywords'
312 parameter type that does the cast in a single place. (This is not
313 an overload of PyArg_ParseTupleAndKeywords in order to make it
314 clearer that we're calling our own function instead of a function
315 that exists in some newer Python version.) */
316
317 static inline int
318 gdb_PyArg_ParseTupleAndKeywords (PyObject *args, PyObject *kw,
319 const char *format, const char **keywords, ...)
320 {
321 va_list ap;
322 int res;
323
324 va_start (ap, keywords);
325 res = PyArg_VaParseTupleAndKeywords (args, kw, format,
326 const_cast<char **> (keywords),
327 ap);
328 va_end (ap);
329
330 return res;
331 }
332
333 /* In order to be able to parse symtab_and_line_to_sal_object function
334 a real symtab_and_line structure is needed. */
335 #include "symtab.h"
336
337 /* Also needed to parse enum var_types. */
338 #include "command.h"
339 #include "breakpoint.h"
340
341 enum gdbpy_iter_kind { iter_keys, iter_values, iter_items };
342
343 struct block;
344 struct value;
345 struct language_defn;
346 struct program_space;
347 struct bpstat;
348 struct inferior;
349
350 extern int gdb_python_initialized;
351
352 extern PyObject *gdb_module;
353 extern PyObject *gdb_python_module;
354 extern PyTypeObject value_object_type
355 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("value_object");
356 extern PyTypeObject block_object_type
357 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF("block_object");
358 extern PyTypeObject symbol_object_type
359 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("symbol_object");
360 extern PyTypeObject event_object_type
361 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("event_object");
362 extern PyTypeObject breakpoint_object_type
363 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("breakpoint_object");
364 extern PyTypeObject frame_object_type
365 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("frame_object");
366 extern PyTypeObject thread_object_type
367 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("thread_object");
368
369 /* Ensure that breakpoint_object_type is initialized and return true. If
370 breakpoint_object_type can't be initialized then set a suitable Python
371 error and return false.
372
373 This function needs to be called from any gdbpy_initialize_* function
374 that wants to reference breakpoint_object_type. After all the
375 gdbpy_initialize_* functions have been called then breakpoint_object_type
376 is guaranteed to have been initialized, and this function does not need
377 calling before referencing breakpoint_object_type. */
378
379 extern bool gdbpy_breakpoint_init_breakpoint_type ();
380
381 struct gdbpy_breakpoint_object
382 {
383 PyObject_HEAD
384
385 /* The breakpoint number according to gdb. */
386 int number;
387
388 /* The gdb breakpoint object, or NULL if the breakpoint has been
389 deleted. */
390 struct breakpoint *bp;
391
392 /* 1 is this is a FinishBreakpoint object, 0 otherwise. */
393 int is_finish_bp;
394 };
395
396 /* Require that BREAKPOINT be a valid breakpoint ID; throw a Python
397 exception if it is invalid. */
398 #define BPPY_REQUIRE_VALID(Breakpoint) \
399 do { \
400 if ((Breakpoint)->bp == NULL) \
401 return PyErr_Format (PyExc_RuntimeError, \
402 _("Breakpoint %d is invalid."), \
403 (Breakpoint)->number); \
404 } while (0)
405
406 /* Require that BREAKPOINT be a valid breakpoint ID; throw a Python
407 exception if it is invalid. This macro is for use in setter functions. */
408 #define BPPY_SET_REQUIRE_VALID(Breakpoint) \
409 do { \
410 if ((Breakpoint)->bp == NULL) \
411 { \
412 PyErr_Format (PyExc_RuntimeError, _("Breakpoint %d is invalid."), \
413 (Breakpoint)->number); \
414 return -1; \
415 } \
416 } while (0)
417
418
419 /* Variables used to pass information between the Breakpoint
420 constructor and the breakpoint-created hook function. */
421 extern gdbpy_breakpoint_object *bppy_pending_object;
422
423
424 struct thread_object
425 {
426 PyObject_HEAD
427
428 /* The thread we represent. */
429 struct thread_info *thread;
430
431 /* The Inferior object to which this thread belongs. */
432 PyObject *inf_obj;
433
434 /* Dictionary holding user-added attributes. This is the __dict__
435 attribute of the object. */
436 PyObject *dict;
437 };
438
439 struct inferior_object;
440
441 extern struct cmd_list_element *set_python_list;
442 extern struct cmd_list_element *show_python_list;
443 \f
444 /* extension_language_script_ops "methods". */
445
446 /* Return true if auto-loading Python scripts is enabled.
447 This is the extension_language_script_ops.auto_load_enabled "method". */
448
449 extern bool gdbpy_auto_load_enabled (const struct extension_language_defn *);
450
451 /* extension_language_ops "methods". */
452
453 extern enum ext_lang_rc gdbpy_apply_val_pretty_printer
454 (const struct extension_language_defn *,
455 struct value *value,
456 struct ui_file *stream, int recurse,
457 const struct value_print_options *options,
458 const struct language_defn *language);
459 extern void gdbpy_load_ptwrite_filter
460 (const struct extension_language_defn *extlang,
461 struct btrace_thread_info *btinfo);
462 extern enum ext_lang_bt_status gdbpy_apply_frame_filter
463 (const struct extension_language_defn *,
464 const frame_info_ptr &frame, frame_filter_flags flags,
465 enum ext_lang_frame_args args_type,
466 struct ui_out *out, int frame_low, int frame_high);
467 extern void gdbpy_preserve_values (const struct extension_language_defn *,
468 struct objfile *objfile,
469 copied_types_hash_t &copied_types);
470 extern enum ext_lang_bp_stop gdbpy_breakpoint_cond_says_stop
471 (const struct extension_language_defn *, struct breakpoint *);
472 extern int gdbpy_breakpoint_has_cond (const struct extension_language_defn *,
473 struct breakpoint *b);
474
475 extern enum ext_lang_rc gdbpy_get_matching_xmethod_workers
476 (const struct extension_language_defn *extlang,
477 struct type *obj_type, const char *method_name,
478 std::vector<xmethod_worker_up> *dm_vec);
479
480 \f
481 PyObject *gdbpy_history (PyObject *self, PyObject *args);
482 PyObject *gdbpy_add_history (PyObject *self, PyObject *args);
483 extern PyObject *gdbpy_history_count (PyObject *self, PyObject *args);
484 PyObject *gdbpy_convenience_variable (PyObject *self, PyObject *args);
485 PyObject *gdbpy_set_convenience_variable (PyObject *self, PyObject *args);
486 PyObject *gdbpy_breakpoints (PyObject *, PyObject *);
487 PyObject *gdbpy_frame_stop_reason_string (PyObject *, PyObject *);
488 PyObject *gdbpy_lookup_symbol (PyObject *self, PyObject *args, PyObject *kw);
489 PyObject *gdbpy_lookup_global_symbol (PyObject *self, PyObject *args,
490 PyObject *kw);
491 PyObject *gdbpy_lookup_static_symbol (PyObject *self, PyObject *args,
492 PyObject *kw);
493 PyObject *gdbpy_lookup_static_symbols (PyObject *self, PyObject *args,
494 PyObject *kw);
495 PyObject *gdbpy_start_recording (PyObject *self, PyObject *args);
496 PyObject *gdbpy_current_recording (PyObject *self, PyObject *args);
497 PyObject *gdbpy_stop_recording (PyObject *self, PyObject *args);
498 PyObject *gdbpy_newest_frame (PyObject *self, PyObject *args);
499 PyObject *gdbpy_selected_frame (PyObject *self, PyObject *args);
500 PyObject *gdbpy_lookup_type (PyObject *self, PyObject *args, PyObject *kw);
501 int gdbpy_is_field (PyObject *obj);
502 PyObject *gdbpy_create_lazy_string_object (CORE_ADDR address, long length,
503 const char *encoding,
504 struct type *type);
505 PyObject *gdbpy_inferiors (PyObject *unused, PyObject *unused2);
506 PyObject *gdbpy_create_ptid_object (ptid_t ptid);
507 PyObject *gdbpy_selected_thread (PyObject *self, PyObject *args);
508 PyObject *gdbpy_selected_inferior (PyObject *self, PyObject *args);
509 PyObject *gdbpy_string_to_argv (PyObject *self, PyObject *args);
510 PyObject *gdbpy_parameter_value (const setting &var);
511 gdb::unique_xmalloc_ptr<char> gdbpy_parse_command_name
512 (const char *name, struct cmd_list_element ***base_list,
513 struct cmd_list_element **start_list,
514 struct cmd_list_element **prefix_cmd = nullptr);
515 PyObject *gdbpy_register_tui_window (PyObject *self, PyObject *args,
516 PyObject *kw);
517
518 PyObject *symtab_and_line_to_sal_object (struct symtab_and_line sal);
519 PyObject *symtab_to_symtab_object (struct symtab *symtab);
520 PyObject *symbol_to_symbol_object (struct symbol *sym);
521 PyObject *block_to_block_object (const struct block *block,
522 struct objfile *objfile);
523 PyObject *value_to_value_object (struct value *v);
524 PyObject *type_to_type_object (struct type *);
525 PyObject *frame_info_to_frame_object (const frame_info_ptr &frame);
526 PyObject *symtab_to_linetable_object (PyObject *symtab);
527 gdbpy_ref<> pspace_to_pspace_object (struct program_space *);
528 PyObject *pspy_get_printers (PyObject *, void *);
529 PyObject *pspy_get_frame_filters (PyObject *, void *);
530 PyObject *pspy_get_frame_unwinders (PyObject *, void *);
531 PyObject *pspy_get_xmethods (PyObject *, void *);
532
533 gdbpy_ref<> objfile_to_objfile_object (struct objfile *);
534 PyObject *objfpy_get_printers (PyObject *, void *);
535 PyObject *objfpy_get_frame_filters (PyObject *, void *);
536 PyObject *objfpy_get_frame_unwinders (PyObject *, void *);
537 PyObject *objfpy_get_xmethods (PyObject *, void *);
538 PyObject *gdbpy_lookup_objfile (PyObject *self, PyObject *args, PyObject *kw);
539
540 PyObject *gdbarch_to_arch_object (struct gdbarch *gdbarch);
541 PyObject *gdbpy_all_architecture_names (PyObject *self, PyObject *args);
542
543 PyObject *gdbpy_new_register_descriptor_iterator (struct gdbarch *gdbarch,
544 const char *group_name);
545 PyObject *gdbpy_new_reggroup_iterator (struct gdbarch *gdbarch);
546
547 gdbpy_ref<thread_object> create_thread_object (struct thread_info *tp);
548 gdbpy_ref<> thread_to_thread_object (thread_info *thr);;
549 gdbpy_ref<inferior_object> inferior_to_inferior_object (inferior *inf);
550
551 PyObject *gdbpy_buffer_to_membuf (gdb::unique_xmalloc_ptr<gdb_byte> buffer,
552 CORE_ADDR address, ULONGEST length);
553
554 struct process_stratum_target;
555 gdbpy_ref<> target_to_connection_object (process_stratum_target *target);
556 PyObject *gdbpy_connections (PyObject *self, PyObject *args);
557
558 const struct block *block_object_to_block (PyObject *obj);
559 struct symbol *symbol_object_to_symbol (PyObject *obj);
560 struct value *value_object_to_value (PyObject *self);
561 struct value *convert_value_from_python (PyObject *obj);
562 struct type *type_object_to_type (PyObject *obj);
563 struct symtab *symtab_object_to_symtab (PyObject *obj);
564 struct symtab_and_line *sal_object_to_symtab_and_line (PyObject *obj);
565 frame_info_ptr frame_object_to_frame_info (PyObject *frame_obj);
566 struct gdbarch *arch_object_to_gdbarch (PyObject *obj);
567
568 extern PyObject *gdbpy_execute_mi_command (PyObject *self, PyObject *args,
569 PyObject *kw);
570
571 /* Serialize RESULTS and print it in MI format to the current_uiout.
572
573 This function handles the top-level results passed as a dictionary.
574 The caller is responsible for ensuring that. The values within this
575 dictionary can be a wider range of types. Handling the values of the top-level
576 dictionary is done by serialize_mi_result_1, see that function for more
577 details.
578
579 If anything goes wrong while parsing and printing the MI output then an
580 error is thrown. */
581
582 extern void serialize_mi_results (PyObject *results);
583
584 /* Implementation of the gdb.notify_mi function. */
585
586 extern PyObject *gdbpy_notify_mi (PyObject *self, PyObject *args,
587 PyObject *kw);
588
589 /* Convert Python object OBJ to a program_space pointer. OBJ must be a
590 gdb.Progspace reference. Return nullptr if the gdb.Progspace is not
591 valid (see gdb.Progspace.is_valid), otherwise return the program_space
592 pointer. */
593
594 extern struct program_space *progspace_object_to_program_space (PyObject *obj);
595
596 /* A class for managing the initialization, and finalization functions
597 from all Python files (e.g. gdb/python/py-*.c).
598
599 Within any Python file, create an instance of this class, passing in
600 the initialization function, and, optionally, the finalization
601 function.
602
603 These functions are added to a single global list of functions, which
604 can then be called from do_start_initialization and finalize_python
605 (see python.c) to initialize all the Python files within GDB. */
606
607 class gdbpy_initialize_file
608 {
609 /* The type of a function that can be called just after GDB has setup the
610 Python interpreter. This function will setup any additional Python
611 state required by a particular subsystem. Return 0 if the setup was
612 successful, or return -1 if setup failed, in which case a Python
613 exception should have been raised. */
614
615 using gdbpy_initialize_file_ftype = int (*) (void);
616
617 /* The type of a function that can be called just before GDB shuts down
618 the Python interpreter. This function can cleanup an Python state
619 that is cached within GDB, for example, if GDB is holding any
620 references to Python objects, these should be released before the
621 Python interpreter is shut down.
622
623 There is no error return in this case. This function is only called
624 when GDB is already shutting down. The function should make a best
625 effort to clean up, and then return. */
626
627 using gdbpy_finalize_file_ftype = void (*) (void);
628
629 /* The type for an initialization and finalization function pair. */
630
631 using callback_pair_t = std::pair<gdbpy_initialize_file_ftype,
632 gdbpy_finalize_file_ftype>;
633
634 /* Return the vector of callbacks. The vector is defined as a static
635 variable within this function so that it will be initialized the first
636 time this function is called. This is important, as this function is
637 called as part of the global object initialization process; if the
638 vector was a static variable within this class then we could not
639 guarantee that it had been initialized before it was used. */
640
641 static std::vector<callback_pair_t> &
642 callbacks ()
643 {
644 static std::vector<callback_pair_t> list;
645 return list;
646 }
647
648 public:
649
650 /* Register the initialization (INIT) and finalization (FINI) functions
651 for a Python file. See the comments on the function types above for
652 when these functions will be called.
653
654 Either of these functions can be nullptr, in which case no function
655 will be called.
656
657 The FINI argument is optional, and defaults to nullptr (no function to
658 call). */
659
660 gdbpy_initialize_file (gdbpy_initialize_file_ftype init,
661 gdbpy_finalize_file_ftype fini = nullptr)
662 {
663 callbacks ().emplace_back (init, fini);
664 }
665
666 /* Run all the Python file initialize functions and return true. If any
667 of the initialize functions fails then this function returns false.
668 In the case of failure it is undefined how many of the initialize
669 functions will have been called. */
670
671 static bool
672 initialize_all ()
673 {
674 /* The initialize_all function should only be called once. The
675 following check reverses the global list, which will effect this
676 initialize_all call, as well as the later finalize_all call.
677
678 The environment variable checked here is the same as the one checked
679 in the generated init.c file. */
680 if (getenv ("GDB_REVERSE_INIT_FUNCTIONS") != nullptr)
681 std::reverse (callbacks ().begin (), callbacks ().end ());
682
683 for (const auto &p : gdbpy_initialize_file::callbacks ())
684 {
685 if (p.first != nullptr && p.first () < 0)
686 return false;
687 }
688 return true;
689 }
690
691 /* Run all the Python file finalize functions. */
692
693 static void
694 finalize_all ()
695 {
696 for (const auto &p : gdbpy_initialize_file::callbacks ())
697 {
698 if (p.second != nullptr)
699 p.second ();
700 }
701 }
702 };
703
704 /* Macro to simplify registering the initialization and finalization
705 functions for a Python file. */
706
707 #define GDBPY_INITIALIZE_FILE(INIT, ...) \
708 static gdbpy_initialize_file \
709 CONCAT(gdbpy_initialize_file_obj_, __LINE__) (INIT, ##__VA_ARGS__)
710
711 PyMODINIT_FUNC gdbpy_events_mod_func ();
712
713 /* A wrapper for PyErr_Fetch that handles reference counting for the
714 caller. */
715 class gdbpy_err_fetch
716 {
717 public:
718
719 gdbpy_err_fetch ()
720 {
721 #if PY_VERSION_HEX < 0x030c0000
722 PyObject *error_type, *error_value, *error_traceback;
723
724 PyErr_Fetch (&error_type, &error_value, &error_traceback);
725 m_error_type.reset (error_type);
726 m_error_value.reset (error_value);
727 m_error_traceback.reset (error_traceback);
728 #else
729 /* PyErr_Fetch is deprecated in python 3.12, use PyErr_GetRaisedException
730 instead. */
731 m_exc.reset (PyErr_GetRaisedException ());
732 #endif
733 }
734
735 /* Call PyErr_Restore using the values stashed in this object.
736 After this call, this object is invalid and neither the to_string
737 nor restore methods may be used again. */
738
739 void restore ()
740 {
741 #if PY_VERSION_HEX < 0x030c0000
742 PyErr_Restore (m_error_type.release (),
743 m_error_value.release (),
744 m_error_traceback.release ());
745 #else
746 /* PyErr_Restore is deprecated in python 3.12, use PyErr_SetRaisedException
747 instead. */
748 PyErr_SetRaisedException (m_exc.release ());
749 #endif
750 }
751
752 /* Return the string representation of the exception represented by
753 this object. If the result is NULL a python error occurred, the
754 caller must clear it. */
755
756 gdb::unique_xmalloc_ptr<char> to_string () const;
757
758 /* Return the string representation of the type of the exception
759 represented by this object. If the result is NULL a python error
760 occurred, the caller must clear it. */
761
762 gdb::unique_xmalloc_ptr<char> type_to_string () const;
763
764 /* Return true if the stored type matches TYPE, false otherwise. */
765
766 bool type_matches (PyObject *type) const
767 {
768 gdbpy_ref<> err_type = this->type ();
769 return PyErr_GivenExceptionMatches (err_type.get (), type);
770 }
771
772 /* Return a new reference to the exception value object. */
773
774 gdbpy_ref<> value () const
775 {
776 #if PY_VERSION_HEX < 0x030c0000
777 if (!m_normalized)
778 {
779 PyObject *error_type, *error_value, *error_traceback;
780 error_type = m_error_type.release ();
781 error_value = m_error_value.release ();
782 error_traceback = m_error_traceback.release ();
783 PyErr_NormalizeException (&error_type, &error_value, &error_traceback);
784 m_error_type.reset (error_type);
785 m_error_value.reset (error_value);
786 m_error_traceback.reset (error_traceback);
787 m_normalized = true;
788 }
789 return m_error_value;
790 #else
791 return m_exc;
792 #endif
793 }
794
795 /* Return a new reference to the exception type object. */
796
797 gdbpy_ref<> type () const
798 {
799 #if PY_VERSION_HEX < 0x030c0000
800 return m_error_type;
801 #else
802 if (m_exc.get() == nullptr)
803 return nullptr;
804 return gdbpy_ref<>::new_reference ((PyObject *)Py_TYPE (m_exc.get ()));
805 #endif
806 }
807
808 private:
809
810 #if PY_VERSION_HEX < 0x030c0000
811 mutable gdbpy_ref<> m_error_type, m_error_value, m_error_traceback;
812 mutable bool m_normalized = false;
813 #else
814 gdbpy_ref<> m_exc;
815 #endif
816 };
817
818 /* Called before entering the Python interpreter to install the
819 current language and architecture to be used for Python values.
820 Also set the active extension language for GDB so that SIGINT's
821 are directed our way, and if necessary install the right SIGINT
822 handler. */
823 class gdbpy_enter
824 {
825 public:
826
827 /* Set the ambient Python architecture to GDBARCH and the language
828 to LANGUAGE. If GDBARCH is nullptr, then the architecture will
829 be computed, when needed, using get_current_arch; see the
830 get_gdbarch method. If LANGUAGE is not nullptr, then the current
831 language at time of construction will be saved (to be restored on
832 destruction), and the current language will be set to
833 LANGUAGE. */
834 explicit gdbpy_enter (struct gdbarch *gdbarch = nullptr,
835 const struct language_defn *language = nullptr);
836
837 ~gdbpy_enter ();
838
839 DISABLE_COPY_AND_ASSIGN (gdbpy_enter);
840
841 /* Return the current gdbarch, as known to the Python layer. This
842 is either python_gdbarch (which comes from the most recent call
843 to the gdbpy_enter constructor), or, if that is nullptr, the
844 result of get_current_arch. */
845 static struct gdbarch *get_gdbarch ();
846
847 /* Called only during gdb shutdown. This sets python_gdbarch to an
848 acceptable value. */
849 static void finalize ();
850
851 private:
852
853 /* The current gdbarch, according to Python. This can be
854 nullptr. */
855 static struct gdbarch *python_gdbarch;
856
857 struct active_ext_lang_state *m_previous_active;
858 PyGILState_STATE m_state;
859 struct gdbarch *m_gdbarch;
860 const struct language_defn *m_language;
861
862 /* An optional is used here because we don't want to call
863 PyErr_Fetch too early. */
864 std::optional<gdbpy_err_fetch> m_error;
865 };
866
867 /* Like gdbpy_enter, but takes a varobj. This is a subclass just to
868 make constructor delegation a little nicer. */
869 class gdbpy_enter_varobj : public gdbpy_enter
870 {
871 public:
872
873 /* This is defined in varobj.c, where it can access varobj
874 internals. */
875 gdbpy_enter_varobj (const struct varobj *var);
876
877 };
878
879 /* The opposite of gdb_enter: this releases the GIL around a region,
880 allowing other Python threads to run. No Python APIs may be used
881 while this is active. */
882 class gdbpy_allow_threads
883 {
884 public:
885
886 gdbpy_allow_threads ()
887 : m_save (PyEval_SaveThread ())
888 {
889 gdb_assert (m_save != nullptr);
890 }
891
892 ~gdbpy_allow_threads ()
893 {
894 PyEval_RestoreThread (m_save);
895 }
896
897 DISABLE_COPY_AND_ASSIGN (gdbpy_allow_threads);
898
899 private:
900
901 PyThreadState *m_save;
902 };
903
904 /* A helper class to save and restore the GIL, but without touching
905 the other globals that are handled by gdbpy_enter. */
906
907 class gdbpy_gil
908 {
909 public:
910
911 gdbpy_gil ()
912 : m_state (PyGILState_Ensure ())
913 {
914 }
915
916 ~gdbpy_gil ()
917 {
918 PyGILState_Release (m_state);
919 }
920
921 DISABLE_COPY_AND_ASSIGN (gdbpy_gil);
922
923 private:
924
925 PyGILState_STATE m_state;
926 };
927
928 int gdbpy_print_python_errors_p (void);
929 void gdbpy_print_stack (void);
930 void gdbpy_print_stack_or_quit ();
931 [[noreturn]] void gdbpy_handle_exception ();
932
933 /* A wrapper around calling 'error'. Prefixes the error message with an
934 'Error occurred in Python' string. Use this in C++ code if we spot
935 something wrong with an object returned from Python code. The prefix
936 string gives the user a hint that the mistake is within Python code,
937 rather than some other part of GDB.
938
939 This always calls error, and never returns. */
940
941 [[noreturn]] void gdbpy_error (const char *fmt, ...) ATTRIBUTE_PRINTF (1, 2);
942
943 gdbpy_ref<> python_string_to_unicode (PyObject *obj);
944 gdb::unique_xmalloc_ptr<char> unicode_to_target_string (PyObject *unicode_str);
945 gdb::unique_xmalloc_ptr<char> python_string_to_target_string (PyObject *obj);
946 gdbpy_ref<> python_string_to_target_python_string (PyObject *obj);
947 gdb::unique_xmalloc_ptr<char> python_string_to_host_string (PyObject *obj);
948 gdbpy_ref<> host_string_to_python_string (const char *str);
949 int gdbpy_is_string (PyObject *obj);
950 gdb::unique_xmalloc_ptr<char> gdbpy_obj_to_string (PyObject *obj);
951
952 int gdbpy_is_lazy_string (PyObject *result);
953 void gdbpy_extract_lazy_string (PyObject *string, CORE_ADDR *addr,
954 struct type **str_type,
955 long *length,
956 gdb::unique_xmalloc_ptr<char> *encoding);
957
958 int gdbpy_is_value_object (PyObject *obj);
959
960 /* Note that these are declared here, and not in python.h with the
961 other pretty-printer functions, because they refer to PyObject. */
962 gdbpy_ref<> apply_varobj_pretty_printer (PyObject *print_obj,
963 struct value **replacement,
964 struct ui_file *stream,
965 const value_print_options *opts);
966 gdbpy_ref<> gdbpy_get_varobj_pretty_printer (struct value *value);
967 gdb::unique_xmalloc_ptr<char> gdbpy_get_display_hint (PyObject *printer);
968 PyObject *gdbpy_default_visualizer (PyObject *self, PyObject *args);
969
970 PyObject *gdbpy_print_options (PyObject *self, PyObject *args);
971 void gdbpy_get_print_options (value_print_options *opts);
972 extern const struct value_print_options *gdbpy_current_print_options;
973
974 void bpfinishpy_pre_stop_hook (struct gdbpy_breakpoint_object *bp_obj);
975 void bpfinishpy_post_stop_hook (struct gdbpy_breakpoint_object *bp_obj);
976 void bpfinishpy_pre_delete_hook (struct gdbpy_breakpoint_object *bp_obj);
977
978 extern PyObject *gdbpy_doc_cst;
979 extern PyObject *gdbpy_children_cst;
980 extern PyObject *gdbpy_to_string_cst;
981 extern PyObject *gdbpy_display_hint_cst;
982 extern PyObject *gdbpy_enabled_cst;
983 extern PyObject *gdbpy_value_cst;
984
985 /* Exception types. */
986 extern PyObject *gdbpy_gdb_error;
987 extern PyObject *gdbpy_gdb_memory_error;
988 extern PyObject *gdbpy_gdberror_exc;
989
990 extern void gdbpy_convert_exception (const struct gdb_exception &)
991 CPYCHECKER_SETS_EXCEPTION;
992
993 /* Use this in a 'catch' block to convert the exception E to a Python
994 exception and return value VAL to signal that an exception occurred.
995 Typically at the use site, that value will be returned immediately. */
996
997 template<typename T>
998 [[nodiscard]] T
999 gdbpy_handle_gdb_exception (T val, const gdb_exception &e)
1000 {
1001 gdbpy_convert_exception (e);
1002 return val;
1003 }
1004
1005 int get_addr_from_python (PyObject *obj, CORE_ADDR *addr)
1006 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION;
1007
1008 gdbpy_ref<> gdb_py_object_from_longest (LONGEST l);
1009 gdbpy_ref<> gdb_py_object_from_ulongest (ULONGEST l);
1010 int gdb_py_int_as_long (PyObject *, long *);
1011
1012 PyObject *gdb_py_generic_dict (PyObject *self, void *closure);
1013
1014 int gdb_pymodule_addobject (PyObject *module, const char *name,
1015 PyObject *object)
1016 CPYCHECKER_NEGATIVE_RESULT_SETS_EXCEPTION;
1017
1018
1019 /* Return a Python string (str) object that represents SELF. SELF can be
1020 any object type, but should be in an "invalid" state. What "invalid"
1021 means is up to the caller. The returned string will take the form
1022 "<TYPENAME (invalid)>", without the quotes, and with TYPENAME replaced
1023 with the type of SELF. */
1024
1025 PyObject *gdb_py_invalid_object_repr (PyObject *self);
1026
1027 struct varobj_iter;
1028 struct varobj;
1029 std::unique_ptr<varobj_iter> py_varobj_get_iterator
1030 (struct varobj *var,
1031 PyObject *printer,
1032 const value_print_options *opts);
1033
1034 /* Deleter for Py_buffer unique_ptr specialization. */
1035
1036 struct Py_buffer_deleter
1037 {
1038 void operator() (Py_buffer *b) const
1039 {
1040 PyBuffer_Release (b);
1041 }
1042 };
1043
1044 /* A unique_ptr specialization for Py_buffer. */
1045 typedef std::unique_ptr<Py_buffer, Py_buffer_deleter> Py_buffer_up;
1046
1047 /* Parse a register number from PYO_REG_ID and place the register number
1048 into *REG_NUM. The register is a register for GDBARCH.
1049
1050 If a register is parsed successfully then *REG_NUM will have been
1051 updated, and true is returned. Otherwise the contents of *REG_NUM are
1052 undefined, and false is returned. When false is returned, the
1053 Python error is set.
1054
1055 The PYO_REG_ID object can be a string, the name of the register. This
1056 is the slowest approach as GDB has to map the name to a number for each
1057 call. Alternatively PYO_REG_ID can be an internal GDB register
1058 number. This is quick but should not be encouraged as this means
1059 Python scripts are now dependent on GDB's internal register numbering.
1060 Final PYO_REG_ID can be a gdb.RegisterDescriptor object, these objects
1061 can be looked up by name once, and then cache the register number so
1062 should be as quick as using a register number. */
1063
1064 extern bool gdbpy_parse_register_id (struct gdbarch *gdbarch,
1065 PyObject *pyo_reg_id, int *reg_num);
1066
1067 /* Return true if OBJ is a gdb.Architecture object, otherwise, return
1068 false. */
1069
1070 extern bool gdbpy_is_architecture (PyObject *obj);
1071
1072 /* Return true if OBJ is a gdb.Progspace object, otherwise, return false. */
1073
1074 extern bool gdbpy_is_progspace (PyObject *obj);
1075
1076 /* Take DOC, the documentation string for a GDB command defined in Python,
1077 and return an (possibly) modified version of that same string.
1078
1079 When a command is defined in Python, the documentation string will
1080 usually be indented based on the indentation of the surrounding Python
1081 code. However, the documentation string is a literal string, all the
1082 white-space added for indentation is included within the documentation
1083 string.
1084
1085 This indentation is then included in the help text that GDB displays,
1086 which looks odd out of the context of the original Python source code.
1087
1088 This function analyses DOC and tries to figure out what white-space
1089 within DOC was added as part of the indentation, and then removes that
1090 white-space from the copy that is returned.
1091
1092 If the analysis of DOC fails then DOC will be returned unmodified. */
1093
1094 extern gdb::unique_xmalloc_ptr<char> gdbpy_fix_doc_string_indentation
1095 (gdb::unique_xmalloc_ptr<char> doc);
1096
1097 /* Implement the 'print_insn' hook for Python. Disassemble an instruction
1098 whose address is ADDRESS for architecture GDBARCH. The bytes of the
1099 instruction should be read with INFO->read_memory_func as the
1100 instruction being disassembled might actually be in a buffer.
1101
1102 Used INFO->fprintf_func to print the results of the disassembly, and
1103 return the length of the instruction in octets.
1104
1105 If no instruction can be disassembled then return an empty value. */
1106
1107 extern std::optional<int> gdbpy_print_insn (struct gdbarch *gdbarch,
1108 CORE_ADDR address,
1109 disassemble_info *info);
1110
1111 /* A wrapper for PyType_Ready that also automatically registers the
1112 type in the appropriate module. Returns 0 on success, -1 on error.
1113 If MOD is supplied, then the type is added to that module. If MOD
1114 is not supplied, the type name (tp_name field) must be of the form
1115 "gdb.Mumble", and the type will be added to the gdb module. */
1116
1117 static inline int
1118 gdbpy_type_ready (PyTypeObject *type, PyObject *mod = nullptr)
1119 {
1120 if (PyType_Ready (type) < 0)
1121 return -1;
1122 if (mod == nullptr)
1123 {
1124 gdb_assert (startswith (type->tp_name, "gdb."));
1125 mod = gdb_module;
1126 }
1127 const char *dot = strrchr (type->tp_name, '.');
1128 gdb_assert (dot != nullptr);
1129 return gdb_pymodule_addobject (mod, dot + 1, (PyObject *) type);
1130 }
1131
1132 /* Poison PyType_Ready. Only gdbpy_type_ready should be used, to
1133 avoid forgetting to register the type. See PR python/32163. */
1134 #undef PyType_Ready
1135 #ifdef __GNUC__
1136 # pragma GCC poison PyType_Ready
1137 #else
1138 # define PyType_Ready POISONED_PyType_Ready
1139 #endif
1140
1141 /* A class to manage lifecycle of Python objects for objects that are "owned"
1142 by an objfile or a gdbarch. It keeps track of Python objects and when
1143 the "owning" object (objfile or gdbarch) is about to be freed, ensures that
1144 all Python objects "owned" by that object are properly invalidated.
1145
1146 The actual tracking of "owned" Python objects is handled externally
1147 by storage class. Storage object is created for each owning object
1148 on demand and it is deleted when owning object is about to be freed.
1149
1150 The storage class must provide two member types:
1151
1152 * obj_type - the type of Python object whose lifecycle is managed.
1153 * val_type - the type of GDB structure the Python objects are
1154 representing.
1155
1156 It must also provide following methods:
1157
1158 void add (obj_type *obj);
1159 void remove (obj_type *obj);
1160
1161 Memoizing storage must in addition to method above provide:
1162
1163 obj_type *lookup (val_type *val);
1164
1165 Finally it must invalidate all registered Python objects upon deletion. */
1166 template <typename Storage>
1167 class gdbpy_registry
1168 {
1169 public:
1170 using obj_type = typename Storage::obj_type;
1171 using val_type = typename Storage::val_type;
1172
1173 /* Register Python object OBJ as being "owned" by OWNER. When OWNER is
1174 about to be freed, OBJ will be invalidated. */
1175 template <typename O>
1176 void add (O *owner, obj_type *obj) const
1177 {
1178 get_storage (owner)->add (obj);
1179 }
1180
1181 /* Unregister Python object OBJ. OBJ will no longer be invalidated when
1182 OWNER is about to be be freed. */
1183 template <typename O>
1184 void remove (O *owner, obj_type *obj) const
1185 {
1186 get_storage (owner)->remove (obj);
1187 }
1188
1189 /* Lookup pre-existing Python object for given VAL. Return such object
1190 if found, otherwise return NULL. This method always returns new
1191 reference. */
1192 template <typename O>
1193 obj_type *lookup (O *owner, val_type *val) const
1194 {
1195 obj_type *obj = get_storage (owner)->lookup (val);
1196 Py_XINCREF (obj);
1197 return obj;
1198 }
1199
1200 private:
1201
1202 template<typename O>
1203 using StorageKey = typename registry<O>::template key<Storage>;
1204
1205 template<typename O>
1206 Storage *get_storage (O *owner, const StorageKey<O> &key) const
1207 {
1208 Storage *r = key.get (owner);
1209 if (r == nullptr)
1210 {
1211 r = new Storage();
1212 key.set (owner, r);
1213 }
1214 return r;
1215 }
1216
1217 Storage *get_storage (struct objfile* objf) const
1218 {
1219 return get_storage (objf, m_key_for_objf);
1220 }
1221
1222 Storage *get_storage (struct gdbarch* arch) const
1223 {
1224 return get_storage (arch, m_key_for_arch);
1225 }
1226
1227 const registry<objfile>::key<Storage> m_key_for_objf;
1228 const registry<gdbarch>::key<Storage> m_key_for_arch;
1229 };
1230
1231 /* Default invalidator for Python objects. */
1232 template <typename P, typename V, V* P::*val_slot>
1233 struct gdbpy_default_invalidator
1234 {
1235 void operator() (P *obj)
1236 {
1237 obj->*val_slot = nullptr;
1238 }
1239 };
1240
1241 /* A "storage" implementation suitable for temporary (on-demand) objects. */
1242 template <typename P,
1243 typename V,
1244 V* P::*val_slot,
1245 typename Invalidator = gdbpy_default_invalidator<P, V, val_slot>>
1246 class gdbpy_tracking_registry_storage
1247 {
1248 public:
1249 using obj_type = P;
1250 using val_type = V;
1251
1252 void add (obj_type *obj)
1253 {
1254 gdb_assert (obj != nullptr && obj->*val_slot != nullptr);
1255
1256 m_objects.insert (obj);
1257 }
1258
1259 void remove (obj_type *obj)
1260 {
1261 gdb_assert (obj != nullptr && obj->*val_slot != nullptr);
1262 gdb_assert (m_objects.contains (obj));
1263
1264 m_objects.erase (obj);
1265 }
1266
1267 ~gdbpy_tracking_registry_storage ()
1268 {
1269 Invalidator invalidate;
1270 gdbpy_enter enter_py;
1271
1272 for (auto each : m_objects)
1273 invalidate (each);
1274 m_objects.clear ();
1275 }
1276
1277 protected:
1278 gdb::unordered_set<obj_type *> m_objects;
1279 };
1280
1281 /* A "storage" implementation suitable for memoized (interned) Python objects.
1282
1283 Python objects are memoized (interned) temporarily, meaning that when user
1284 drops all their references the Python object is deallocated and removed
1285 from storage.
1286 */
1287 template <typename P,
1288 typename V,
1289 V* P::*val_slot,
1290 typename Invalidator = gdbpy_default_invalidator<P, V, val_slot>>
1291 class gdbpy_memoizing_registry_storage
1292 {
1293 public:
1294 using obj_type = P;
1295 using val_type = V;
1296
1297 void add (obj_type *obj)
1298 {
1299 gdb_assert (obj != nullptr && obj->*val_slot != nullptr);
1300
1301 m_objects[obj->*val_slot] = obj;
1302 }
1303
1304 void remove (obj_type *obj)
1305 {
1306 gdb_assert (obj != nullptr && obj->*val_slot != nullptr);
1307 gdb_assert (m_objects.contains (obj->*val_slot));
1308
1309 m_objects.erase (obj->*val_slot);
1310 }
1311
1312 obj_type *lookup (val_type *val) const
1313 {
1314 auto result = m_objects.find (val);
1315 if (result != m_objects.end ())
1316 return result->second;
1317 else
1318 return nullptr;
1319 }
1320
1321 ~gdbpy_memoizing_registry_storage ()
1322 {
1323 Invalidator invalidate;
1324 gdbpy_enter enter_py;
1325
1326 for (auto each : m_objects)
1327 invalidate (each.second);
1328 m_objects.clear ();
1329 }
1330
1331 protected:
1332 gdb::unordered_map<val_type *, obj_type *> m_objects;
1333 };
1334
1335 #endif /* GDB_PYTHON_PYTHON_INTERNAL_H */