python.c revision 1.9 1 /* General python/gdb code
2
3 Copyright (C) 2008-2020 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 #include "defs.h"
21 #include "arch-utils.h"
22 #include "command.h"
23 #include "ui-out.h"
24 #include "cli/cli-script.h"
25 #include "gdbcmd.h"
26 #include "progspace.h"
27 #include "objfiles.h"
28 #include "value.h"
29 #include "language.h"
30 #include "gdbsupport/event-loop.h"
31 #include "readline/tilde.h"
32 #include "python.h"
33 #include "extension-priv.h"
34 #include "cli/cli-utils.h"
35 #include <ctype.h>
36 #include "location.h"
37 #include "run-on-main-thread.h"
38
39 /* Declared constants and enum for python stack printing. */
40 static const char python_excp_none[] = "none";
41 static const char python_excp_full[] = "full";
42 static const char python_excp_message[] = "message";
43
44 /* "set python print-stack" choices. */
45 static const char *const python_excp_enums[] =
46 {
47 python_excp_none,
48 python_excp_full,
49 python_excp_message,
50 NULL
51 };
52
53 /* The exception printing variable. 'full' if we want to print the
54 error message and stack, 'none' if we want to print nothing, and
55 'message' if we only want to print the error message. 'message' is
56 the default. */
57 static const char *gdbpy_should_print_stack = python_excp_message;
58
59 #ifdef HAVE_PYTHON
60 /* Forward decls, these are defined later. */
61 extern const struct extension_language_script_ops python_extension_script_ops;
62 extern const struct extension_language_ops python_extension_ops;
63 #endif
64
65 /* The main struct describing GDB's interface to the Python
66 extension language. */
67 const struct extension_language_defn extension_language_python =
68 {
69 EXT_LANG_PYTHON,
70 "python",
71 "Python",
72
73 ".py",
74 "-gdb.py",
75
76 python_control,
77
78 #ifdef HAVE_PYTHON
79 &python_extension_script_ops,
80 &python_extension_ops
81 #else
82 NULL,
83 NULL
84 #endif
85 };
86
87 #ifdef HAVE_PYTHON
89
90 #include "cli/cli-decode.h"
91 #include "charset.h"
92 #include "top.h"
93 #include "python-internal.h"
94 #include "linespec.h"
95 #include "source.h"
96 #include "gdbsupport/version.h"
97 #include "target.h"
98 #include "gdbthread.h"
99 #include "interps.h"
100 #include "event-top.h"
101 #include "py-event.h"
102
103 /* True if Python has been successfully initialized, false
104 otherwise. */
105
106 int gdb_python_initialized;
107
108 extern PyMethodDef python_GdbMethods[];
109
110 #ifdef IS_PY3K
111 extern struct PyModuleDef python_GdbModuleDef;
112 #endif
113
114 PyObject *gdb_module;
115 PyObject *gdb_python_module;
116
117 /* Some string constants we may wish to use. */
118 PyObject *gdbpy_to_string_cst;
119 PyObject *gdbpy_children_cst;
120 PyObject *gdbpy_display_hint_cst;
121 PyObject *gdbpy_doc_cst;
122 PyObject *gdbpy_enabled_cst;
123 PyObject *gdbpy_value_cst;
124
125 /* The GdbError exception. */
126 PyObject *gdbpy_gdberror_exc;
127
128 /* The `gdb.error' base class. */
129 PyObject *gdbpy_gdb_error;
130
131 /* The `gdb.MemoryError' exception. */
132 PyObject *gdbpy_gdb_memory_error;
133
134 static script_sourcer_func gdbpy_source_script;
135 static objfile_script_sourcer_func gdbpy_source_objfile_script;
136 static objfile_script_executor_func gdbpy_execute_objfile_script;
137 static void gdbpy_finish_initialization
138 (const struct extension_language_defn *);
139 static int gdbpy_initialized (const struct extension_language_defn *);
140 static void gdbpy_eval_from_control_command
141 (const struct extension_language_defn *, struct command_line *cmd);
142 static void gdbpy_start_type_printers (const struct extension_language_defn *,
143 struct ext_lang_type_printers *);
144 static enum ext_lang_rc gdbpy_apply_type_printers
145 (const struct extension_language_defn *,
146 const struct ext_lang_type_printers *, struct type *, char **);
147 static void gdbpy_free_type_printers (const struct extension_language_defn *,
148 struct ext_lang_type_printers *);
149 static void gdbpy_set_quit_flag (const struct extension_language_defn *);
150 static int gdbpy_check_quit_flag (const struct extension_language_defn *);
151 static enum ext_lang_rc gdbpy_before_prompt_hook
152 (const struct extension_language_defn *, const char *current_gdb_prompt);
153 static gdb::optional<std::string> gdbpy_colorize
154 (const std::string &filename, const std::string &contents);
155
156 /* The interface between gdb proper and loading of python scripts. */
157
158 const struct extension_language_script_ops python_extension_script_ops =
159 {
160 gdbpy_source_script,
161 gdbpy_source_objfile_script,
162 gdbpy_execute_objfile_script,
163 gdbpy_auto_load_enabled
164 };
165
166 /* The interface between gdb proper and python extensions. */
167
168 const struct extension_language_ops python_extension_ops =
169 {
170 gdbpy_finish_initialization,
171 gdbpy_initialized,
172
173 gdbpy_eval_from_control_command,
174
175 gdbpy_start_type_printers,
176 gdbpy_apply_type_printers,
177 gdbpy_free_type_printers,
178
179 gdbpy_apply_val_pretty_printer,
180
181 gdbpy_apply_frame_filter,
182
183 gdbpy_preserve_values,
184
185 gdbpy_breakpoint_has_cond,
186 gdbpy_breakpoint_cond_says_stop,
187
188 gdbpy_set_quit_flag,
189 gdbpy_check_quit_flag,
190
191 gdbpy_before_prompt_hook,
192
193 gdbpy_get_matching_xmethod_workers,
194
195 gdbpy_colorize,
196 };
197
198 /* Architecture and language to be used in callbacks from
199 the Python interpreter. */
200 struct gdbarch *python_gdbarch;
201 const struct language_defn *python_language;
202
203 gdbpy_enter::gdbpy_enter (struct gdbarch *gdbarch,
204 const struct language_defn *language)
205 : m_gdbarch (python_gdbarch),
206 m_language (python_language)
207 {
208 /* We should not ever enter Python unless initialized. */
209 if (!gdb_python_initialized)
210 error (_("Python not initialized"));
211
212 m_previous_active = set_active_ext_lang (&extension_language_python);
213
214 m_state = PyGILState_Ensure ();
215
216 python_gdbarch = gdbarch;
217 python_language = language;
218
219 /* Save it and ensure ! PyErr_Occurred () afterwards. */
220 m_error.emplace ();
221 }
222
223 gdbpy_enter::~gdbpy_enter ()
224 {
225 /* Leftover Python error is forbidden by Python Exception Handling. */
226 if (PyErr_Occurred ())
227 {
228 /* This order is similar to the one calling error afterwards. */
229 gdbpy_print_stack ();
230 warning (_("internal error: Unhandled Python exception"));
231 }
232
233 m_error->restore ();
234
235 python_gdbarch = m_gdbarch;
236 python_language = m_language;
237
238 restore_active_ext_lang (m_previous_active);
239 PyGILState_Release (m_state);
240 }
241
242 /* A helper class to save and restore the GIL, but without touching
243 the other globals that are handled by gdbpy_enter. */
244
245 class gdbpy_gil
246 {
247 public:
248
249 gdbpy_gil ()
250 : m_state (PyGILState_Ensure ())
251 {
252 }
253
254 ~gdbpy_gil ()
255 {
256 PyGILState_Release (m_state);
257 }
258
259 DISABLE_COPY_AND_ASSIGN (gdbpy_gil);
260
261 private:
262
263 PyGILState_STATE m_state;
264 };
265
266 /* Set the quit flag. */
267
268 static void
269 gdbpy_set_quit_flag (const struct extension_language_defn *extlang)
270 {
271 PyErr_SetInterrupt ();
272 }
273
274 /* Return true if the quit flag has been set, false otherwise. */
275
276 static int
277 gdbpy_check_quit_flag (const struct extension_language_defn *extlang)
278 {
279 if (!gdb_python_initialized)
280 return 0;
281
282 gdbpy_gil gil;
283 return PyOS_InterruptOccurred ();
284 }
285
286 /* Evaluate a Python command like PyRun_SimpleString, but uses
287 Py_single_input which prints the result of expressions, and does
288 not automatically print the stack on errors. */
289
290 static int
291 eval_python_command (const char *command)
292 {
293 PyObject *m, *d;
294
295 m = PyImport_AddModule ("__main__");
296 if (m == NULL)
297 return -1;
298
299 d = PyModule_GetDict (m);
300 if (d == NULL)
301 return -1;
302 gdbpy_ref<> v (PyRun_StringFlags (command, Py_single_input, d, d, NULL));
303 if (v == NULL)
304 return -1;
305
306 #ifndef IS_PY3K
307 if (Py_FlushLine ())
308 PyErr_Clear ();
309 #endif
310
311 return 0;
312 }
313
314 /* Implementation of the gdb "python-interactive" command. */
315
316 static void
317 python_interactive_command (const char *arg, int from_tty)
318 {
319 struct ui *ui = current_ui;
320 int err;
321
322 scoped_restore save_async = make_scoped_restore (¤t_ui->async, 0);
323
324 arg = skip_spaces (arg);
325
326 gdbpy_enter enter_py (get_current_arch (), current_language);
327
328 if (arg && *arg)
329 {
330 std::string script = std::string (arg) + "\n";
331 err = eval_python_command (script.c_str ());
332 }
333 else
334 {
335 err = PyRun_InteractiveLoop (ui->instream, "<stdin>");
336 dont_repeat ();
337 }
338
339 if (err)
340 {
341 gdbpy_print_stack ();
342 error (_("Error while executing Python code."));
343 }
344 }
345
346 /* A wrapper around PyRun_SimpleFile. FILE is the Python script to run
347 named FILENAME.
348
349 On Windows hosts few users would build Python themselves (this is no
350 trivial task on this platform), and thus use binaries built by
351 someone else instead. There may happen situation where the Python
352 library and GDB are using two different versions of the C runtime
353 library. Python, being built with VC, would use one version of the
354 msvcr DLL (Eg. msvcr100.dll), while MinGW uses msvcrt.dll.
355 A FILE * from one runtime does not necessarily operate correctly in
356 the other runtime.
357
358 To work around this potential issue, we run code in Python to load
359 the script. */
360
361 static void
362 python_run_simple_file (FILE *file, const char *filename)
363 {
364 #ifndef _WIN32
365
366 PyRun_SimpleFile (file, filename);
367
368 #else /* _WIN32 */
369
370 /* Because we have a string for a filename, and are using Python to
371 open the file, we need to expand any tilde in the path first. */
372 gdb::unique_xmalloc_ptr<char> full_path (tilde_expand (filename));
373
374 if (gdb_python_module == nullptr
375 || ! PyObject_HasAttrString (gdb_python_module, "_execute_file"))
376 error (_("Installation error: gdb._execute_file function is missing"));
377
378 gdbpy_ref<> return_value
379 (PyObject_CallMethod (gdb_python_module, "_execute_file", "s",
380 full_path.get ()));
381 if (return_value == nullptr)
382 {
383 /* Use PyErr_PrintEx instead of gdbpy_print_stack to better match the
384 behavior of the non-Windows codepath. */
385 PyErr_PrintEx(0);
386 }
387
388 #endif /* _WIN32 */
389 }
390
391 /* Given a command_line, return a command string suitable for passing
392 to Python. Lines in the string are separated by newlines. */
393
394 static std::string
395 compute_python_string (struct command_line *l)
396 {
397 struct command_line *iter;
398 std::string script;
399
400 for (iter = l; iter; iter = iter->next)
401 {
402 script += iter->line;
403 script += '\n';
404 }
405 return script;
406 }
407
408 /* Take a command line structure representing a 'python' command, and
409 evaluate its body using the Python interpreter. */
410
411 static void
412 gdbpy_eval_from_control_command (const struct extension_language_defn *extlang,
413 struct command_line *cmd)
414 {
415 int ret;
416
417 if (cmd->body_list_1 != nullptr)
418 error (_("Invalid \"python\" block structure."));
419
420 gdbpy_enter enter_py (get_current_arch (), current_language);
421
422 std::string script = compute_python_string (cmd->body_list_0.get ());
423 ret = PyRun_SimpleString (script.c_str ());
424 if (ret)
425 error (_("Error while executing Python code."));
426 }
427
428 /* Implementation of the gdb "python" command. */
429
430 static void
431 python_command (const char *arg, int from_tty)
432 {
433 gdbpy_enter enter_py (get_current_arch (), current_language);
434
435 scoped_restore save_async = make_scoped_restore (¤t_ui->async, 0);
436
437 arg = skip_spaces (arg);
438 if (arg && *arg)
439 {
440 if (PyRun_SimpleString (arg))
441 error (_("Error while executing Python code."));
442 }
443 else
444 {
445 counted_command_line l = get_command_line (python_control, "");
446
447 execute_control_command_untraced (l.get ());
448 }
449 }
450
451
452
454 /* Transform a gdb parameters's value into a Python value. May return
455 NULL (and set a Python exception) on error. Helper function for
456 get_parameter. */
457 PyObject *
458 gdbpy_parameter_value (enum var_types type, void *var)
459 {
460 switch (type)
461 {
462 case var_string:
463 case var_string_noescape:
464 case var_optional_filename:
465 case var_filename:
466 case var_enum:
467 {
468 const char *str = *(char **) var;
469
470 if (! str)
471 str = "";
472 return host_string_to_python_string (str).release ();
473 }
474
475 case var_boolean:
476 {
477 if (* (bool *) var)
478 Py_RETURN_TRUE;
479 else
480 Py_RETURN_FALSE;
481 }
482
483 case var_auto_boolean:
484 {
485 enum auto_boolean ab = * (enum auto_boolean *) var;
486
487 if (ab == AUTO_BOOLEAN_TRUE)
488 Py_RETURN_TRUE;
489 else if (ab == AUTO_BOOLEAN_FALSE)
490 Py_RETURN_FALSE;
491 else
492 Py_RETURN_NONE;
493 }
494
495 case var_integer:
496 if ((* (int *) var) == INT_MAX)
497 Py_RETURN_NONE;
498 /* Fall through. */
499 case var_zinteger:
500 case var_zuinteger_unlimited:
501 return PyLong_FromLong (* (int *) var);
502
503 case var_uinteger:
504 {
505 unsigned int val = * (unsigned int *) var;
506
507 if (val == UINT_MAX)
508 Py_RETURN_NONE;
509 return PyLong_FromUnsignedLong (val);
510 }
511
512 case var_zuinteger:
513 {
514 unsigned int val = * (unsigned int *) var;
515 return PyLong_FromUnsignedLong (val);
516 }
517 }
518
519 return PyErr_Format (PyExc_RuntimeError,
520 _("Programmer error: unhandled type."));
521 }
522
523 /* A Python function which returns a gdb parameter's value as a Python
524 value. */
525
526 static PyObject *
527 gdbpy_parameter (PyObject *self, PyObject *args)
528 {
529 struct cmd_list_element *alias, *prefix, *cmd;
530 const char *arg;
531 int found = -1;
532
533 if (! PyArg_ParseTuple (args, "s", &arg))
534 return NULL;
535
536 std::string newarg = std::string ("show ") + arg;
537
538 try
539 {
540 found = lookup_cmd_composition (newarg.c_str (), &alias, &prefix, &cmd);
541 }
542 catch (const gdb_exception &ex)
543 {
544 GDB_PY_HANDLE_EXCEPTION (ex);
545 }
546
547 if (!found)
548 return PyErr_Format (PyExc_RuntimeError,
549 _("Could not find parameter `%s'."), arg);
550
551 if (! cmd->var)
552 return PyErr_Format (PyExc_RuntimeError,
553 _("`%s' is not a parameter."), arg);
554 return gdbpy_parameter_value (cmd->var_type, cmd->var);
555 }
556
557 /* Wrapper for target_charset. */
558
559 static PyObject *
560 gdbpy_target_charset (PyObject *self, PyObject *args)
561 {
562 const char *cset = target_charset (python_gdbarch);
563
564 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
565 }
566
567 /* Wrapper for target_wide_charset. */
568
569 static PyObject *
570 gdbpy_target_wide_charset (PyObject *self, PyObject *args)
571 {
572 const char *cset = target_wide_charset (python_gdbarch);
573
574 return PyUnicode_Decode (cset, strlen (cset), host_charset (), NULL);
575 }
576
577 /* A Python function which evaluates a string using the gdb CLI. */
578
579 static PyObject *
580 execute_gdb_command (PyObject *self, PyObject *args, PyObject *kw)
581 {
582 const char *arg;
583 PyObject *from_tty_obj = NULL, *to_string_obj = NULL;
584 int from_tty, to_string;
585 static const char *keywords[] = { "command", "from_tty", "to_string", NULL };
586
587 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!O!", keywords, &arg,
588 &PyBool_Type, &from_tty_obj,
589 &PyBool_Type, &to_string_obj))
590 return NULL;
591
592 from_tty = 0;
593 if (from_tty_obj)
594 {
595 int cmp = PyObject_IsTrue (from_tty_obj);
596 if (cmp < 0)
597 return NULL;
598 from_tty = cmp;
599 }
600
601 to_string = 0;
602 if (to_string_obj)
603 {
604 int cmp = PyObject_IsTrue (to_string_obj);
605 if (cmp < 0)
606 return NULL;
607 to_string = cmp;
608 }
609
610 std::string to_string_res;
611
612 scoped_restore preventer = prevent_dont_repeat ();
613
614 try
615 {
616 gdbpy_allow_threads allow_threads;
617
618 struct interp *interp;
619
620 std::string arg_copy = arg;
621 bool first = true;
622 char *save_ptr = nullptr;
623 auto reader
624 = [&] ()
625 {
626 const char *result = strtok_r (first ? &arg_copy[0] : nullptr,
627 "\n", &save_ptr);
628 first = false;
629 return result;
630 };
631
632 counted_command_line lines = read_command_lines_1 (reader, 1, nullptr);
633
634 {
635 scoped_restore save_async = make_scoped_restore (¤t_ui->async,
636 0);
637
638 scoped_restore save_uiout = make_scoped_restore (¤t_uiout);
639
640 /* Use the console interpreter uiout to have the same print format
641 for console or MI. */
642 interp = interp_lookup (current_ui, "console");
643 current_uiout = interp->interp_ui_out ();
644
645 if (to_string)
646 to_string_res = execute_control_commands_to_string (lines.get (),
647 from_tty);
648 else
649 execute_control_commands (lines.get (), from_tty);
650 }
651
652 /* Do any commands attached to breakpoint we stopped at. */
653 bpstat_do_actions ();
654 }
655 catch (const gdb_exception &except)
656 {
657 /* If an exception occurred then we won't hit normal_stop (), or have
658 an exception reach the top level of the event loop, which are the
659 two usual places in which stdin would be re-enabled. So, before we
660 convert the exception and continue back in Python, we should
661 re-enable stdin here. */
662 async_enable_stdin ();
663 GDB_PY_HANDLE_EXCEPTION (except);
664 }
665
666 if (to_string)
667 return PyString_FromString (to_string_res.c_str ());
668 Py_RETURN_NONE;
669 }
670
671 /* Implementation of Python rbreak command. Take a REGEX and
672 optionally a MINSYMS, THROTTLE and SYMTABS keyword and return a
673 Python list that contains newly set breakpoints that match that
674 criteria. REGEX refers to a GDB format standard regex pattern of
675 symbols names to search; MINSYMS is an optional boolean (default
676 False) that indicates if the function should search GDB's minimal
677 symbols; THROTTLE is an optional integer (default unlimited) that
678 indicates the maximum amount of breakpoints allowable before the
679 function exits (note, if the throttle bound is passed, no
680 breakpoints will be set and a runtime error returned); SYMTABS is
681 an optional Python iterable that contains a set of gdb.Symtabs to
682 constrain the search within. */
683
684 static PyObject *
685 gdbpy_rbreak (PyObject *self, PyObject *args, PyObject *kw)
686 {
687 char *regex = NULL;
688 std::vector<symbol_search> symbols;
689 unsigned long count = 0;
690 PyObject *symtab_list = NULL;
691 PyObject *minsyms_p_obj = NULL;
692 int minsyms_p = 0;
693 unsigned int throttle = 0;
694 static const char *keywords[] = {"regex","minsyms", "throttle",
695 "symtabs", NULL};
696
697 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|O!IO", keywords,
698 ®ex, &PyBool_Type,
699 &minsyms_p_obj, &throttle,
700 &symtab_list))
701 return NULL;
702
703 /* Parse minsyms keyword. */
704 if (minsyms_p_obj != NULL)
705 {
706 int cmp = PyObject_IsTrue (minsyms_p_obj);
707 if (cmp < 0)
708 return NULL;
709 minsyms_p = cmp;
710 }
711
712 global_symbol_searcher spec (FUNCTIONS_DOMAIN, regex);
713 SCOPE_EXIT {
714 for (const char *elem : spec.filenames)
715 xfree ((void *) elem);
716 };
717
718 /* The "symtabs" keyword is any Python iterable object that returns
719 a gdb.Symtab on each iteration. If specified, iterate through
720 the provided gdb.Symtabs and extract their full path. As
721 python_string_to_target_string returns a
722 gdb::unique_xmalloc_ptr<char> and a vector containing these types
723 cannot be coerced to a const char **p[] via the vector.data call,
724 release the value from the unique_xmalloc_ptr and place it in a
725 simple type symtab_list_type (which holds the vector and a
726 destructor that frees the contents of the allocated strings. */
727 if (symtab_list != NULL)
728 {
729 gdbpy_ref<> iter (PyObject_GetIter (symtab_list));
730
731 if (iter == NULL)
732 return NULL;
733
734 while (true)
735 {
736 gdbpy_ref<> next (PyIter_Next (iter.get ()));
737
738 if (next == NULL)
739 {
740 if (PyErr_Occurred ())
741 return NULL;
742 break;
743 }
744
745 gdbpy_ref<> obj_name (PyObject_GetAttrString (next.get (),
746 "filename"));
747
748 if (obj_name == NULL)
749 return NULL;
750
751 /* Is the object file still valid? */
752 if (obj_name == Py_None)
753 continue;
754
755 gdb::unique_xmalloc_ptr<char> filename =
756 python_string_to_target_string (obj_name.get ());
757
758 if (filename == NULL)
759 return NULL;
760
761 /* Make sure there is a definite place to store the value of
762 filename before it is released. */
763 spec.filenames.push_back (nullptr);
764 spec.filenames.back () = filename.release ();
765 }
766 }
767
768 /* The search spec. */
769 symbols = spec.search ();
770
771 /* Count the number of symbols (both symbols and optionally minimal
772 symbols) so we can correctly check the throttle limit. */
773 for (const symbol_search &p : symbols)
774 {
775 /* Minimal symbols included? */
776 if (minsyms_p)
777 {
778 if (p.msymbol.minsym != NULL)
779 count++;
780 }
781
782 if (p.symbol != NULL)
783 count++;
784 }
785
786 /* Check throttle bounds and exit if in excess. */
787 if (throttle != 0 && count > throttle)
788 {
789 PyErr_SetString (PyExc_RuntimeError,
790 _("Number of breakpoints exceeds throttled maximum."));
791 return NULL;
792 }
793
794 gdbpy_ref<> return_list (PyList_New (0));
795
796 if (return_list == NULL)
797 return NULL;
798
799 /* Construct full path names for symbols and call the Python
800 breakpoint constructor on the resulting names. Be tolerant of
801 individual breakpoint failures. */
802 for (const symbol_search &p : symbols)
803 {
804 std::string symbol_name;
805
806 /* Skipping minimal symbols? */
807 if (minsyms_p == 0)
808 if (p.msymbol.minsym != NULL)
809 continue;
810
811 if (p.msymbol.minsym == NULL)
812 {
813 struct symtab *symtab = symbol_symtab (p.symbol);
814 const char *fullname = symtab_to_fullname (symtab);
815
816 symbol_name = fullname;
817 symbol_name += ":";
818 symbol_name += p.symbol->linkage_name ();
819 }
820 else
821 symbol_name = p.msymbol.minsym->linkage_name ();
822
823 gdbpy_ref<> argList (Py_BuildValue("(s)", symbol_name.c_str ()));
824 gdbpy_ref<> obj (PyObject_CallObject ((PyObject *)
825 &breakpoint_object_type,
826 argList.get ()));
827
828 /* Tolerate individual breakpoint failures. */
829 if (obj == NULL)
830 gdbpy_print_stack ();
831 else
832 {
833 if (PyList_Append (return_list.get (), obj.get ()) == -1)
834 return NULL;
835 }
836 }
837 return return_list.release ();
838 }
839
840 /* A Python function which is a wrapper for decode_line_1. */
841
842 static PyObject *
843 gdbpy_decode_line (PyObject *self, PyObject *args)
844 {
845 const char *arg = NULL;
846 gdbpy_ref<> result;
847 gdbpy_ref<> unparsed;
848 event_location_up location;
849
850 if (! PyArg_ParseTuple (args, "|s", &arg))
851 return NULL;
852
853 /* Treat a string consisting of just whitespace the same as
854 NULL. */
855 if (arg != NULL)
856 {
857 arg = skip_spaces (arg);
858 if (*arg == '\0')
859 arg = NULL;
860 }
861
862 if (arg != NULL)
863 location = string_to_event_location_basic (&arg, python_language,
864 symbol_name_match_type::WILD);
865
866 std::vector<symtab_and_line> decoded_sals;
867 symtab_and_line def_sal;
868 gdb::array_view<symtab_and_line> sals;
869 try
870 {
871 if (location != NULL)
872 {
873 decoded_sals = decode_line_1 (location.get (), 0, NULL, NULL, 0);
874 sals = decoded_sals;
875 }
876 else
877 {
878 set_default_source_symtab_and_line ();
879 def_sal = get_current_source_symtab_and_line ();
880 sals = def_sal;
881 }
882 }
883 catch (const gdb_exception &ex)
884 {
885 /* We know this will always throw. */
886 gdbpy_convert_exception (ex);
887 return NULL;
888 }
889
890 if (!sals.empty ())
891 {
892 result.reset (PyTuple_New (sals.size ()));
893 if (result == NULL)
894 return NULL;
895 for (size_t i = 0; i < sals.size (); ++i)
896 {
897 PyObject *obj = symtab_and_line_to_sal_object (sals[i]);
898 if (obj == NULL)
899 return NULL;
900
901 PyTuple_SetItem (result.get (), i, obj);
902 }
903 }
904 else
905 result = gdbpy_ref<>::new_reference (Py_None);
906
907 gdbpy_ref<> return_result (PyTuple_New (2));
908 if (return_result == NULL)
909 return NULL;
910
911 if (arg != NULL && strlen (arg) > 0)
912 {
913 unparsed.reset (PyString_FromString (arg));
914 if (unparsed == NULL)
915 return NULL;
916 }
917 else
918 unparsed = gdbpy_ref<>::new_reference (Py_None);
919
920 PyTuple_SetItem (return_result.get (), 0, unparsed.release ());
921 PyTuple_SetItem (return_result.get (), 1, result.release ());
922
923 return return_result.release ();
924 }
925
926 /* Parse a string and evaluate it as an expression. */
927 static PyObject *
928 gdbpy_parse_and_eval (PyObject *self, PyObject *args)
929 {
930 const char *expr_str;
931 struct value *result = NULL;
932
933 if (!PyArg_ParseTuple (args, "s", &expr_str))
934 return NULL;
935
936 try
937 {
938 gdbpy_allow_threads allow_threads;
939 result = parse_and_eval (expr_str);
940 }
941 catch (const gdb_exception &except)
942 {
943 GDB_PY_HANDLE_EXCEPTION (except);
944 }
945
946 return value_to_value_object (result);
947 }
948
949 /* Implementation of gdb.invalidate_cached_frames. */
950
951 static PyObject *
952 gdbpy_invalidate_cached_frames (PyObject *self, PyObject *args)
953 {
954 reinit_frame_cache ();
955 Py_RETURN_NONE;
956 }
957
958 /* Read a file as Python code.
959 This is the extension_language_script_ops.script_sourcer "method".
960 FILE is the file to load. FILENAME is name of the file FILE.
961 This does not throw any errors. If an exception occurs python will print
962 the traceback and clear the error indicator. */
963
964 static void
965 gdbpy_source_script (const struct extension_language_defn *extlang,
966 FILE *file, const char *filename)
967 {
968 gdbpy_enter enter_py (get_current_arch (), current_language);
969 python_run_simple_file (file, filename);
970 }
971
972
973
975 /* Posting and handling events. */
976
977 /* A single event. */
978 struct gdbpy_event
979 {
980 gdbpy_event (gdbpy_ref<> &&func)
981 : m_func (func.release ())
982 {
983 }
984
985 gdbpy_event (gdbpy_event &&other) noexcept
986 : m_func (other.m_func)
987 {
988 other.m_func = nullptr;
989 }
990
991 gdbpy_event (const gdbpy_event &other)
992 : m_func (other.m_func)
993 {
994 gdbpy_gil gil;
995 Py_XINCREF (m_func);
996 }
997
998 ~gdbpy_event ()
999 {
1000 gdbpy_gil gil;
1001 Py_XDECREF (m_func);
1002 }
1003
1004 gdbpy_event &operator= (const gdbpy_event &other) = delete;
1005
1006 void operator() ()
1007 {
1008 gdbpy_enter enter_py (get_current_arch (), current_language);
1009
1010 gdbpy_ref<> call_result (PyObject_CallObject (m_func, NULL));
1011 if (call_result == NULL)
1012 gdbpy_print_stack ();
1013 }
1014
1015 private:
1016
1017 /* The Python event. This is just a callable object. Note that
1018 this is not a gdbpy_ref<>, because we have to take particular
1019 care to only destroy the reference when holding the GIL. */
1020 PyObject *m_func;
1021 };
1022
1023 /* Submit an event to the gdb thread. */
1024 static PyObject *
1025 gdbpy_post_event (PyObject *self, PyObject *args)
1026 {
1027 PyObject *func;
1028
1029 if (!PyArg_ParseTuple (args, "O", &func))
1030 return NULL;
1031
1032 if (!PyCallable_Check (func))
1033 {
1034 PyErr_SetString (PyExc_RuntimeError,
1035 _("Posted event is not callable"));
1036 return NULL;
1037 }
1038
1039 gdbpy_ref<> func_ref = gdbpy_ref<>::new_reference (func);
1040 gdbpy_event event (std::move (func_ref));
1041 run_on_main_thread (event);
1042
1043 Py_RETURN_NONE;
1044 }
1045
1046
1047
1049 /* This is the extension_language_ops.before_prompt "method". */
1050
1051 static enum ext_lang_rc
1052 gdbpy_before_prompt_hook (const struct extension_language_defn *extlang,
1053 const char *current_gdb_prompt)
1054 {
1055 if (!gdb_python_initialized)
1056 return EXT_LANG_RC_NOP;
1057
1058 gdbpy_enter enter_py (get_current_arch (), current_language);
1059
1060 if (!evregpy_no_listeners_p (gdb_py_events.before_prompt)
1061 && evpy_emit_event (NULL, gdb_py_events.before_prompt) < 0)
1062 return EXT_LANG_RC_ERROR;
1063
1064 if (gdb_python_module
1065 && PyObject_HasAttrString (gdb_python_module, "prompt_hook"))
1066 {
1067 gdbpy_ref<> hook (PyObject_GetAttrString (gdb_python_module,
1068 "prompt_hook"));
1069 if (hook == NULL)
1070 {
1071 gdbpy_print_stack ();
1072 return EXT_LANG_RC_ERROR;
1073 }
1074
1075 if (PyCallable_Check (hook.get ()))
1076 {
1077 gdbpy_ref<> current_prompt (PyString_FromString (current_gdb_prompt));
1078 if (current_prompt == NULL)
1079 {
1080 gdbpy_print_stack ();
1081 return EXT_LANG_RC_ERROR;
1082 }
1083
1084 gdbpy_ref<> result
1085 (PyObject_CallFunctionObjArgs (hook.get (), current_prompt.get (),
1086 NULL));
1087 if (result == NULL)
1088 {
1089 gdbpy_print_stack ();
1090 return EXT_LANG_RC_ERROR;
1091 }
1092
1093 /* Return type should be None, or a String. If it is None,
1094 fall through, we will not set a prompt. If it is a
1095 string, set PROMPT. Anything else, set an exception. */
1096 if (result != Py_None && ! PyString_Check (result.get ()))
1097 {
1098 PyErr_Format (PyExc_RuntimeError,
1099 _("Return from prompt_hook must " \
1100 "be either a Python string, or None"));
1101 gdbpy_print_stack ();
1102 return EXT_LANG_RC_ERROR;
1103 }
1104
1105 if (result != Py_None)
1106 {
1107 gdb::unique_xmalloc_ptr<char>
1108 prompt (python_string_to_host_string (result.get ()));
1109
1110 if (prompt == NULL)
1111 {
1112 gdbpy_print_stack ();
1113 return EXT_LANG_RC_ERROR;
1114 }
1115
1116 set_prompt (prompt.get ());
1117 return EXT_LANG_RC_OK;
1118 }
1119 }
1120 }
1121
1122 return EXT_LANG_RC_NOP;
1123 }
1124
1125 /* This is the extension_language_ops.colorize "method". */
1126
1127 static gdb::optional<std::string>
1128 gdbpy_colorize (const std::string &filename, const std::string &contents)
1129 {
1130 if (!gdb_python_initialized)
1131 return {};
1132
1133 gdbpy_enter enter_py (get_current_arch (), current_language);
1134
1135 if (gdb_python_module == nullptr
1136 || !PyObject_HasAttrString (gdb_python_module, "colorize"))
1137 return {};
1138
1139 gdbpy_ref<> hook (PyObject_GetAttrString (gdb_python_module, "colorize"));
1140 if (hook == nullptr)
1141 {
1142 gdbpy_print_stack ();
1143 return {};
1144 }
1145
1146 if (!PyCallable_Check (hook.get ()))
1147 return {};
1148
1149 gdbpy_ref<> fname_arg (PyString_FromString (filename.c_str ()));
1150 if (fname_arg == nullptr)
1151 {
1152 gdbpy_print_stack ();
1153 return {};
1154 }
1155 gdbpy_ref<> contents_arg (PyString_FromString (contents.c_str ()));
1156 if (contents_arg == nullptr)
1157 {
1158 gdbpy_print_stack ();
1159 return {};
1160 }
1161
1162 gdbpy_ref<> result (PyObject_CallFunctionObjArgs (hook.get (),
1163 fname_arg.get (),
1164 contents_arg.get (),
1165 nullptr));
1166 if (result == nullptr)
1167 {
1168 gdbpy_print_stack ();
1169 return {};
1170 }
1171
1172 if (!gdbpy_is_string (result.get ()))
1173 return {};
1174
1175 gdbpy_ref<> unic = python_string_to_unicode (result.get ());
1176 if (unic == nullptr)
1177 {
1178 gdbpy_print_stack ();
1179 return {};
1180 }
1181 gdbpy_ref<> host_str (PyUnicode_AsEncodedString (unic.get (),
1182 host_charset (),
1183 nullptr));
1184 if (host_str == nullptr)
1185 {
1186 gdbpy_print_stack ();
1187 return {};
1188 }
1189
1190 return std::string (PyBytes_AsString (host_str.get ()));
1191 }
1192
1193
1194
1196 /* Printing. */
1197
1198 /* A python function to write a single string using gdb's filtered
1199 output stream . The optional keyword STREAM can be used to write
1200 to a particular stream. The default stream is to gdb_stdout. */
1201
1202 static PyObject *
1203 gdbpy_write (PyObject *self, PyObject *args, PyObject *kw)
1204 {
1205 const char *arg;
1206 static const char *keywords[] = { "text", "stream", NULL };
1207 int stream_type = 0;
1208
1209 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "s|i", keywords, &arg,
1210 &stream_type))
1211 return NULL;
1212
1213 try
1214 {
1215 switch (stream_type)
1216 {
1217 case 1:
1218 {
1219 fprintf_filtered (gdb_stderr, "%s", arg);
1220 break;
1221 }
1222 case 2:
1223 {
1224 fprintf_filtered (gdb_stdlog, "%s", arg);
1225 break;
1226 }
1227 default:
1228 fprintf_filtered (gdb_stdout, "%s", arg);
1229 }
1230 }
1231 catch (const gdb_exception &except)
1232 {
1233 GDB_PY_HANDLE_EXCEPTION (except);
1234 }
1235
1236 Py_RETURN_NONE;
1237 }
1238
1239 /* A python function to flush a gdb stream. The optional keyword
1240 STREAM can be used to flush a particular stream. The default stream
1241 is gdb_stdout. */
1242
1243 static PyObject *
1244 gdbpy_flush (PyObject *self, PyObject *args, PyObject *kw)
1245 {
1246 static const char *keywords[] = { "stream", NULL };
1247 int stream_type = 0;
1248
1249 if (!gdb_PyArg_ParseTupleAndKeywords (args, kw, "|i", keywords,
1250 &stream_type))
1251 return NULL;
1252
1253 switch (stream_type)
1254 {
1255 case 1:
1256 {
1257 gdb_flush (gdb_stderr);
1258 break;
1259 }
1260 case 2:
1261 {
1262 gdb_flush (gdb_stdlog);
1263 break;
1264 }
1265 default:
1266 gdb_flush (gdb_stdout);
1267 }
1268
1269 Py_RETURN_NONE;
1270 }
1271
1272 /* Return non-zero if print-stack is not "none". */
1273
1274 int
1275 gdbpy_print_python_errors_p (void)
1276 {
1277 return gdbpy_should_print_stack != python_excp_none;
1278 }
1279
1280 /* Print a python exception trace, print just a message, or print
1281 nothing and clear the python exception, depending on
1282 gdbpy_should_print_stack. Only call this if a python exception is
1283 set. */
1284 void
1285 gdbpy_print_stack (void)
1286 {
1287
1288 /* Print "none", just clear exception. */
1289 if (gdbpy_should_print_stack == python_excp_none)
1290 {
1291 PyErr_Clear ();
1292 }
1293 /* Print "full" message and backtrace. */
1294 else if (gdbpy_should_print_stack == python_excp_full)
1295 {
1296 PyErr_Print ();
1297 /* PyErr_Print doesn't necessarily end output with a newline.
1298 This works because Python's stdout/stderr is fed through
1299 printf_filtered. */
1300 try
1301 {
1302 begin_line ();
1303 }
1304 catch (const gdb_exception &except)
1305 {
1306 }
1307 }
1308 /* Print "message", just error print message. */
1309 else
1310 {
1311 gdbpy_err_fetch fetched_error;
1312
1313 gdb::unique_xmalloc_ptr<char> msg = fetched_error.to_string ();
1314 gdb::unique_xmalloc_ptr<char> type;
1315 /* Don't compute TYPE if MSG already indicates that there is an
1316 error. */
1317 if (msg != NULL)
1318 type = fetched_error.type_to_string ();
1319
1320 try
1321 {
1322 if (msg == NULL || type == NULL)
1323 {
1324 /* An error occurred computing the string representation of the
1325 error message. */
1326 fprintf_filtered (gdb_stderr,
1327 _("Error occurred computing Python error" \
1328 "message.\n"));
1329 PyErr_Clear ();
1330 }
1331 else
1332 fprintf_filtered (gdb_stderr, "Python Exception %s %s: \n",
1333 type.get (), msg.get ());
1334 }
1335 catch (const gdb_exception &except)
1336 {
1337 }
1338 }
1339 }
1340
1341 /* Like gdbpy_print_stack, but if the exception is a
1342 KeyboardException, throw a gdb "quit" instead. */
1343
1344 void
1345 gdbpy_print_stack_or_quit ()
1346 {
1347 if (PyErr_ExceptionMatches (PyExc_KeyboardInterrupt))
1348 {
1349 PyErr_Clear ();
1350 throw_quit ("Quit");
1351 }
1352 gdbpy_print_stack ();
1353 }
1354
1355
1356
1358 /* Return a sequence holding all the Progspaces. */
1359
1360 static PyObject *
1361 gdbpy_progspaces (PyObject *unused1, PyObject *unused2)
1362 {
1363 gdbpy_ref<> list (PyList_New (0));
1364 if (list == NULL)
1365 return NULL;
1366
1367 for (struct program_space *ps : program_spaces)
1368 {
1369 gdbpy_ref<> item = pspace_to_pspace_object (ps);
1370
1371 if (item == NULL || PyList_Append (list.get (), item.get ()) == -1)
1372 return NULL;
1373 }
1374
1375 return list.release ();
1376 }
1377
1378
1379
1381 /* The "current" objfile. This is set when gdb detects that a new
1382 objfile has been loaded. It is only set for the duration of a call to
1383 gdbpy_source_objfile_script and gdbpy_execute_objfile_script; it is NULL
1384 at other times. */
1385 static struct objfile *gdbpy_current_objfile;
1386
1387 /* Set the current objfile to OBJFILE and then read FILE named FILENAME
1388 as Python code. This does not throw any errors. If an exception
1389 occurs python will print the traceback and clear the error indicator.
1390 This is the extension_language_script_ops.objfile_script_sourcer
1391 "method". */
1392
1393 static void
1394 gdbpy_source_objfile_script (const struct extension_language_defn *extlang,
1395 struct objfile *objfile, FILE *file,
1396 const char *filename)
1397 {
1398 if (!gdb_python_initialized)
1399 return;
1400
1401 gdbpy_enter enter_py (objfile->arch (), current_language);
1402 gdbpy_current_objfile = objfile;
1403
1404 python_run_simple_file (file, filename);
1405
1406 gdbpy_current_objfile = NULL;
1407 }
1408
1409 /* Set the current objfile to OBJFILE and then execute SCRIPT
1410 as Python code. This does not throw any errors. If an exception
1411 occurs python will print the traceback and clear the error indicator.
1412 This is the extension_language_script_ops.objfile_script_executor
1413 "method". */
1414
1415 static void
1416 gdbpy_execute_objfile_script (const struct extension_language_defn *extlang,
1417 struct objfile *objfile, const char *name,
1418 const char *script)
1419 {
1420 if (!gdb_python_initialized)
1421 return;
1422
1423 gdbpy_enter enter_py (objfile->arch (), current_language);
1424 gdbpy_current_objfile = objfile;
1425
1426 PyRun_SimpleString (script);
1427
1428 gdbpy_current_objfile = NULL;
1429 }
1430
1431 /* Return the current Objfile, or None if there isn't one. */
1432
1433 static PyObject *
1434 gdbpy_get_current_objfile (PyObject *unused1, PyObject *unused2)
1435 {
1436 if (! gdbpy_current_objfile)
1437 Py_RETURN_NONE;
1438
1439 return objfile_to_objfile_object (gdbpy_current_objfile).release ();
1440 }
1441
1442 /* Compute the list of active python type printers and store them in
1443 EXT_PRINTERS->py_type_printers. The product of this function is used by
1444 gdbpy_apply_type_printers, and freed by gdbpy_free_type_printers.
1445 This is the extension_language_ops.start_type_printers "method". */
1446
1447 static void
1448 gdbpy_start_type_printers (const struct extension_language_defn *extlang,
1449 struct ext_lang_type_printers *ext_printers)
1450 {
1451 PyObject *printers_obj = NULL;
1452
1453 if (!gdb_python_initialized)
1454 return;
1455
1456 gdbpy_enter enter_py (get_current_arch (), current_language);
1457
1458 gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
1459 if (type_module == NULL)
1460 {
1461 gdbpy_print_stack ();
1462 return;
1463 }
1464
1465 gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
1466 "get_type_recognizers"));
1467 if (func == NULL)
1468 {
1469 gdbpy_print_stack ();
1470 return;
1471 }
1472
1473 printers_obj = PyObject_CallFunctionObjArgs (func.get (), (char *) NULL);
1474 if (printers_obj == NULL)
1475 gdbpy_print_stack ();
1476 else
1477 ext_printers->py_type_printers = printers_obj;
1478 }
1479
1480 /* If TYPE is recognized by some type printer, store in *PRETTIED_TYPE
1481 a newly allocated string holding the type's replacement name, and return
1482 EXT_LANG_RC_OK. The caller is responsible for freeing the string.
1483 If there's a Python error return EXT_LANG_RC_ERROR.
1484 Otherwise, return EXT_LANG_RC_NOP.
1485 This is the extension_language_ops.apply_type_printers "method". */
1486
1487 static enum ext_lang_rc
1488 gdbpy_apply_type_printers (const struct extension_language_defn *extlang,
1489 const struct ext_lang_type_printers *ext_printers,
1490 struct type *type, char **prettied_type)
1491 {
1492 PyObject *printers_obj = (PyObject *) ext_printers->py_type_printers;
1493 gdb::unique_xmalloc_ptr<char> result;
1494
1495 if (printers_obj == NULL)
1496 return EXT_LANG_RC_NOP;
1497
1498 if (!gdb_python_initialized)
1499 return EXT_LANG_RC_NOP;
1500
1501 gdbpy_enter enter_py (get_current_arch (), current_language);
1502
1503 gdbpy_ref<> type_obj (type_to_type_object (type));
1504 if (type_obj == NULL)
1505 {
1506 gdbpy_print_stack ();
1507 return EXT_LANG_RC_ERROR;
1508 }
1509
1510 gdbpy_ref<> type_module (PyImport_ImportModule ("gdb.types"));
1511 if (type_module == NULL)
1512 {
1513 gdbpy_print_stack ();
1514 return EXT_LANG_RC_ERROR;
1515 }
1516
1517 gdbpy_ref<> func (PyObject_GetAttrString (type_module.get (),
1518 "apply_type_recognizers"));
1519 if (func == NULL)
1520 {
1521 gdbpy_print_stack ();
1522 return EXT_LANG_RC_ERROR;
1523 }
1524
1525 gdbpy_ref<> result_obj (PyObject_CallFunctionObjArgs (func.get (),
1526 printers_obj,
1527 type_obj.get (),
1528 (char *) NULL));
1529 if (result_obj == NULL)
1530 {
1531 gdbpy_print_stack ();
1532 return EXT_LANG_RC_ERROR;
1533 }
1534
1535 if (result_obj == Py_None)
1536 return EXT_LANG_RC_NOP;
1537
1538 result = python_string_to_host_string (result_obj.get ());
1539 if (result == NULL)
1540 {
1541 gdbpy_print_stack ();
1542 return EXT_LANG_RC_ERROR;
1543 }
1544
1545 *prettied_type = result.release ();
1546 return EXT_LANG_RC_OK;
1547 }
1548
1549 /* Free the result of start_type_printers.
1550 This is the extension_language_ops.free_type_printers "method". */
1551
1552 static void
1553 gdbpy_free_type_printers (const struct extension_language_defn *extlang,
1554 struct ext_lang_type_printers *ext_printers)
1555 {
1556 PyObject *printers = (PyObject *) ext_printers->py_type_printers;
1557
1558 if (printers == NULL)
1559 return;
1560
1561 if (!gdb_python_initialized)
1562 return;
1563
1564 gdbpy_enter enter_py (get_current_arch (), current_language);
1565 Py_DECREF (printers);
1566 }
1567
1568 #else /* HAVE_PYTHON */
1569
1570 /* Dummy implementation of the gdb "python-interactive" and "python"
1571 command. */
1572
1573 static void
1574 python_interactive_command (const char *arg, int from_tty)
1575 {
1576 arg = skip_spaces (arg);
1577 if (arg && *arg)
1578 error (_("Python scripting is not supported in this copy of GDB."));
1579 else
1580 {
1581 counted_command_line l = get_command_line (python_control, "");
1582
1583 execute_control_command_untraced (l.get ());
1584 }
1585 }
1586
1587 static void
1588 python_command (const char *arg, int from_tty)
1589 {
1590 python_interactive_command (arg, from_tty);
1591 }
1592
1593 #endif /* HAVE_PYTHON */
1594
1595
1596
1598 /* Lists for 'set python' commands. */
1599
1600 static struct cmd_list_element *user_set_python_list;
1601 static struct cmd_list_element *user_show_python_list;
1602
1603 /* Initialize the Python code. */
1604
1605 #ifdef HAVE_PYTHON
1606
1607 /* This is installed as a final cleanup and cleans up the
1608 interpreter. This lets Python's 'atexit' work. */
1609
1610 static void
1611 finalize_python (void *ignore)
1612 {
1613 struct active_ext_lang_state *previous_active;
1614
1615 /* We don't use ensure_python_env here because if we ever ran the
1616 cleanup, gdb would crash -- because the cleanup calls into the
1617 Python interpreter, which we are about to destroy. It seems
1618 clearer to make the needed calls explicitly here than to create a
1619 cleanup and then mysteriously discard it. */
1620
1621 /* This is only called as a final cleanup so we can assume the active
1622 SIGINT handler is gdb's. We still need to tell it to notify Python. */
1623 previous_active = set_active_ext_lang (&extension_language_python);
1624
1625 (void) PyGILState_Ensure ();
1626 python_gdbarch = target_gdbarch ();
1627 python_language = current_language;
1628
1629 Py_Finalize ();
1630
1631 gdb_python_initialized = false;
1632 restore_active_ext_lang (previous_active);
1633 }
1634
1635 #ifdef IS_PY3K
1636 /* This is called via the PyImport_AppendInittab mechanism called
1637 during initialization, to make the built-in _gdb module known to
1638 Python. */
1639 PyMODINIT_FUNC init__gdb_module (void);
1640 PyMODINIT_FUNC
1641 init__gdb_module (void)
1642 {
1643 return PyModule_Create (&python_GdbModuleDef);
1644 }
1645 #endif
1646
1647 static bool
1648 do_start_initialization ()
1649 {
1650 #ifdef IS_PY3K
1651 size_t progsize, count;
1652 /* Python documentation indicates that the memory given
1653 to Py_SetProgramName cannot be freed. However, it seems that
1654 at least Python 3.7.4 Py_SetProgramName takes a copy of the
1655 given program_name. Making progname_copy static and not release
1656 the memory avoids a leak report for Python versions that duplicate
1657 program_name, and respect the requirement of Py_SetProgramName
1658 for Python versions that do not duplicate program_name. */
1659 static wchar_t *progname_copy;
1660 #endif
1661
1662 #ifdef WITH_PYTHON_PATH
1663 /* Work around problem where python gets confused about where it is,
1664 and then can't find its libraries, etc.
1665 NOTE: Python assumes the following layout:
1666 /foo/bin/python
1667 /foo/lib/pythonX.Y/...
1668 This must be done before calling Py_Initialize. */
1669 gdb::unique_xmalloc_ptr<char> progname
1670 (concat (ldirname (python_libdir.c_str ()).c_str (), SLASH_STRING, "bin",
1671 SLASH_STRING, "python", (char *) NULL));
1672 #ifdef IS_PY3K
1673 std::string oldloc = setlocale (LC_ALL, NULL);
1674 setlocale (LC_ALL, "");
1675 progsize = strlen (progname.get ());
1676 progname_copy = XNEWVEC (wchar_t, progsize + 1);
1677 count = mbstowcs (progname_copy, progname.get (), progsize + 1);
1678 if (count == (size_t) -1)
1679 {
1680 fprintf (stderr, "Could not convert python path to string\n");
1681 return false;
1682 }
1683 setlocale (LC_ALL, oldloc.c_str ());
1684
1685 /* Note that Py_SetProgramName expects the string it is passed to
1686 remain alive for the duration of the program's execution, so
1687 it is not freed after this call. */
1688 Py_SetProgramName (progname_copy);
1689
1690 /* Define _gdb as a built-in module. */
1691 PyImport_AppendInittab ("_gdb", init__gdb_module);
1692 #else
1693 Py_SetProgramName (progname.release ());
1694 #endif
1695 #endif
1696
1697 Py_Initialize ();
1698 #if PY_VERSION_HEX < 0x03090000
1699 /* PyEval_InitThreads became deprecated in Python 3.9 and will
1700 be removed in Python 3.11. Prior to Python 3.7, this call was
1701 required to initialize the GIL. */
1702 PyEval_InitThreads ();
1703 #endif
1704
1705 #ifdef IS_PY3K
1706 gdb_module = PyImport_ImportModule ("_gdb");
1707 #else
1708 gdb_module = Py_InitModule ("_gdb", python_GdbMethods);
1709 #endif
1710 if (gdb_module == NULL)
1711 return false;
1712
1713 if (PyModule_AddStringConstant (gdb_module, "VERSION", version) < 0
1714 || PyModule_AddStringConstant (gdb_module, "HOST_CONFIG", host_name) < 0
1715 || PyModule_AddStringConstant (gdb_module, "TARGET_CONFIG",
1716 target_name) < 0)
1717 return false;
1718
1719 /* Add stream constants. */
1720 if (PyModule_AddIntConstant (gdb_module, "STDOUT", 0) < 0
1721 || PyModule_AddIntConstant (gdb_module, "STDERR", 1) < 0
1722 || PyModule_AddIntConstant (gdb_module, "STDLOG", 2) < 0)
1723 return false;
1724
1725 gdbpy_gdb_error = PyErr_NewException ("gdb.error", PyExc_RuntimeError, NULL);
1726 if (gdbpy_gdb_error == NULL
1727 || gdb_pymodule_addobject (gdb_module, "error", gdbpy_gdb_error) < 0)
1728 return false;
1729
1730 gdbpy_gdb_memory_error = PyErr_NewException ("gdb.MemoryError",
1731 gdbpy_gdb_error, NULL);
1732 if (gdbpy_gdb_memory_error == NULL
1733 || gdb_pymodule_addobject (gdb_module, "MemoryError",
1734 gdbpy_gdb_memory_error) < 0)
1735 return false;
1736
1737 gdbpy_gdberror_exc = PyErr_NewException ("gdb.GdbError", NULL, NULL);
1738 if (gdbpy_gdberror_exc == NULL
1739 || gdb_pymodule_addobject (gdb_module, "GdbError",
1740 gdbpy_gdberror_exc) < 0)
1741 return false;
1742
1743 gdbpy_initialize_gdb_readline ();
1744
1745 if (gdbpy_initialize_auto_load () < 0
1746 || gdbpy_initialize_values () < 0
1747 || gdbpy_initialize_frames () < 0
1748 || gdbpy_initialize_commands () < 0
1749 || gdbpy_initialize_instruction () < 0
1750 || gdbpy_initialize_record () < 0
1751 || gdbpy_initialize_btrace () < 0
1752 || gdbpy_initialize_symbols () < 0
1753 || gdbpy_initialize_symtabs () < 0
1754 || gdbpy_initialize_blocks () < 0
1755 || gdbpy_initialize_functions () < 0
1756 || gdbpy_initialize_parameters () < 0
1757 || gdbpy_initialize_types () < 0
1758 || gdbpy_initialize_pspace () < 0
1759 || gdbpy_initialize_objfile () < 0
1760 || gdbpy_initialize_breakpoints () < 0
1761 || gdbpy_initialize_finishbreakpoints () < 0
1762 || gdbpy_initialize_lazy_string () < 0
1763 || gdbpy_initialize_linetable () < 0
1764 || gdbpy_initialize_thread () < 0
1765 || gdbpy_initialize_inferior () < 0
1766 || gdbpy_initialize_eventregistry () < 0
1767 || gdbpy_initialize_py_events () < 0
1768 || gdbpy_initialize_event () < 0
1769 || gdbpy_initialize_arch () < 0
1770 || gdbpy_initialize_registers () < 0
1771 || gdbpy_initialize_xmethods () < 0
1772 || gdbpy_initialize_unwind () < 0
1773 || gdbpy_initialize_tui () < 0)
1774 return false;
1775
1776 #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
1777 if (gdbpy_initialize_event_generic (&name##_event_object_type, py_name) < 0) \
1778 return false;
1779 #include "py-event-types.def"
1780 #undef GDB_PY_DEFINE_EVENT_TYPE
1781
1782 gdbpy_to_string_cst = PyString_FromString ("to_string");
1783 if (gdbpy_to_string_cst == NULL)
1784 return false;
1785 gdbpy_children_cst = PyString_FromString ("children");
1786 if (gdbpy_children_cst == NULL)
1787 return false;
1788 gdbpy_display_hint_cst = PyString_FromString ("display_hint");
1789 if (gdbpy_display_hint_cst == NULL)
1790 return false;
1791 gdbpy_doc_cst = PyString_FromString ("__doc__");
1792 if (gdbpy_doc_cst == NULL)
1793 return false;
1794 gdbpy_enabled_cst = PyString_FromString ("enabled");
1795 if (gdbpy_enabled_cst == NULL)
1796 return false;
1797 gdbpy_value_cst = PyString_FromString ("value");
1798 if (gdbpy_value_cst == NULL)
1799 return false;
1800
1801 /* Release the GIL while gdb runs. */
1802 PyEval_SaveThread ();
1803
1804 make_final_cleanup (finalize_python, NULL);
1805
1806 /* Only set this when initialization has succeeded. */
1807 gdb_python_initialized = 1;
1808 return true;
1809 }
1810
1811 #endif /* HAVE_PYTHON */
1812
1813 /* See python.h. */
1814 cmd_list_element *python_cmd_element = nullptr;
1815
1816 void _initialize_python ();
1817 void
1818 _initialize_python ()
1819 {
1820 add_com ("python-interactive", class_obscure,
1821 python_interactive_command,
1822 #ifdef HAVE_PYTHON
1823 _("\
1824 Start an interactive Python prompt.\n\
1825 \n\
1826 To return to GDB, type the EOF character (e.g., Ctrl-D on an empty\n\
1827 prompt).\n\
1828 \n\
1829 Alternatively, a single-line Python command can be given as an\n\
1830 argument, and if the command is an expression, the result will be\n\
1831 printed. For example:\n\
1832 \n\
1833 (gdb) python-interactive 2 + 3\n\
1834 5")
1835 #else /* HAVE_PYTHON */
1836 _("\
1837 Start a Python interactive prompt.\n\
1838 \n\
1839 Python scripting is not supported in this copy of GDB.\n\
1840 This command is only a placeholder.")
1841 #endif /* HAVE_PYTHON */
1842 );
1843 add_com_alias ("pi", "python-interactive", class_obscure, 1);
1844
1845 python_cmd_element = add_com ("python", class_obscure, python_command,
1846 #ifdef HAVE_PYTHON
1847 _("\
1848 Evaluate a Python command.\n\
1849 \n\
1850 The command can be given as an argument, for instance:\n\
1851 \n\
1852 python print (23)\n\
1853 \n\
1854 If no argument is given, the following lines are read and used\n\
1855 as the Python commands. Type a line containing \"end\" to indicate\n\
1856 the end of the command.")
1857 #else /* HAVE_PYTHON */
1858 _("\
1859 Evaluate a Python command.\n\
1860 \n\
1861 Python scripting is not supported in this copy of GDB.\n\
1862 This command is only a placeholder.")
1863 #endif /* HAVE_PYTHON */
1864 );
1865 add_com_alias ("py", "python", class_obscure, 1);
1866
1867 /* Add set/show python print-stack. */
1868 add_basic_prefix_cmd ("python", no_class,
1869 _("Prefix command for python preference settings."),
1870 &user_show_python_list, "show python ", 0,
1871 &showlist);
1872
1873 add_show_prefix_cmd ("python", no_class,
1874 _("Prefix command for python preference settings."),
1875 &user_set_python_list, "set python ", 0,
1876 &setlist);
1877
1878 add_setshow_enum_cmd ("print-stack", no_class, python_excp_enums,
1879 &gdbpy_should_print_stack, _("\
1880 Set mode for Python stack dump on error."), _("\
1881 Show the mode of Python stack printing on error."), _("\
1882 none == no stack or message will be printed.\n\
1883 full == a message and a stack will be printed.\n\
1884 message == an error message without a stack will be printed."),
1885 NULL, NULL,
1886 &user_set_python_list,
1887 &user_show_python_list);
1888
1889 #ifdef HAVE_PYTHON
1890 if (!do_start_initialization () && PyErr_Occurred ())
1891 gdbpy_print_stack ();
1892 #endif /* HAVE_PYTHON */
1893 }
1894
1895 #ifdef HAVE_PYTHON
1896
1897 /* Helper function for gdbpy_finish_initialization. This does the
1898 work and then returns false if an error has occurred and must be
1899 displayed, or true on success. */
1900
1901 static bool
1902 do_finish_initialization (const struct extension_language_defn *extlang)
1903 {
1904 PyObject *m;
1905 PyObject *sys_path;
1906
1907 /* Add the initial data-directory to sys.path. */
1908
1909 std::string gdb_pythondir = (std::string (gdb_datadir) + SLASH_STRING
1910 + "python");
1911
1912 sys_path = PySys_GetObject ("path");
1913
1914 /* If sys.path is not defined yet, define it first. */
1915 if (!(sys_path && PyList_Check (sys_path)))
1916 {
1917 #ifdef IS_PY3K
1918 PySys_SetPath (L"");
1919 #else
1920 PySys_SetPath ("");
1921 #endif
1922 sys_path = PySys_GetObject ("path");
1923 }
1924 if (sys_path && PyList_Check (sys_path))
1925 {
1926 gdbpy_ref<> pythondir (PyString_FromString (gdb_pythondir.c_str ()));
1927 if (pythondir == NULL || PyList_Insert (sys_path, 0, pythondir.get ()))
1928 return false;
1929 }
1930 else
1931 return false;
1932
1933 /* Import the gdb module to finish the initialization, and
1934 add it to __main__ for convenience. */
1935 m = PyImport_AddModule ("__main__");
1936 if (m == NULL)
1937 return false;
1938
1939 /* Keep the reference to gdb_python_module since it is in a global
1940 variable. */
1941 gdb_python_module = PyImport_ImportModule ("gdb");
1942 if (gdb_python_module == NULL)
1943 {
1944 gdbpy_print_stack ();
1945 /* This is passed in one call to warning so that blank lines aren't
1946 inserted between each line of text. */
1947 warning (_("\n"
1948 "Could not load the Python gdb module from `%s'.\n"
1949 "Limited Python support is available from the _gdb module.\n"
1950 "Suggest passing --data-directory=/path/to/gdb/data-directory."),
1951 gdb_pythondir.c_str ());
1952 /* We return "success" here as we've already emitted the
1953 warning. */
1954 return true;
1955 }
1956
1957 return gdb_pymodule_addobject (m, "gdb", gdb_python_module) >= 0;
1958 }
1959
1960 /* Perform the remaining python initializations.
1961 These must be done after GDB is at least mostly initialized.
1962 E.g., The "info pretty-printer" command needs the "info" prefix
1963 command installed.
1964 This is the extension_language_ops.finish_initialization "method". */
1965
1966 static void
1967 gdbpy_finish_initialization (const struct extension_language_defn *extlang)
1968 {
1969 gdbpy_enter enter_py (get_current_arch (), current_language);
1970
1971 if (!do_finish_initialization (extlang))
1972 {
1973 gdbpy_print_stack ();
1974 warning (_("internal error: Unhandled Python exception"));
1975 }
1976 }
1977
1978 /* Return non-zero if Python has successfully initialized.
1979 This is the extension_languages_ops.initialized "method". */
1980
1981 static int
1982 gdbpy_initialized (const struct extension_language_defn *extlang)
1983 {
1984 return gdb_python_initialized;
1985 }
1986
1987 #endif /* HAVE_PYTHON */
1988
1989
1990
1992 #ifdef HAVE_PYTHON
1993
1994 PyMethodDef python_GdbMethods[] =
1995 {
1996 { "history", gdbpy_history, METH_VARARGS,
1997 "Get a value from history" },
1998 { "execute", (PyCFunction) execute_gdb_command, METH_VARARGS | METH_KEYWORDS,
1999 "execute (command [, from_tty] [, to_string]) -> [String]\n\
2000 Evaluate command, a string, as a gdb CLI command. Optionally returns\n\
2001 a Python String containing the output of the command if to_string is\n\
2002 set to True." },
2003 { "parameter", gdbpy_parameter, METH_VARARGS,
2004 "Return a gdb parameter's value" },
2005
2006 { "breakpoints", gdbpy_breakpoints, METH_NOARGS,
2007 "Return a tuple of all breakpoint objects" },
2008
2009 { "default_visualizer", gdbpy_default_visualizer, METH_VARARGS,
2010 "Find the default visualizer for a Value." },
2011
2012 { "progspaces", gdbpy_progspaces, METH_NOARGS,
2013 "Return a sequence of all progspaces." },
2014
2015 { "current_objfile", gdbpy_get_current_objfile, METH_NOARGS,
2016 "Return the current Objfile being loaded, or None." },
2017
2018 { "newest_frame", gdbpy_newest_frame, METH_NOARGS,
2019 "newest_frame () -> gdb.Frame.\n\
2020 Return the newest frame object." },
2021 { "selected_frame", gdbpy_selected_frame, METH_NOARGS,
2022 "selected_frame () -> gdb.Frame.\n\
2023 Return the selected frame object." },
2024 { "frame_stop_reason_string", gdbpy_frame_stop_reason_string, METH_VARARGS,
2025 "stop_reason_string (Integer) -> String.\n\
2026 Return a string explaining unwind stop reason." },
2027
2028 { "start_recording", gdbpy_start_recording, METH_VARARGS,
2029 "start_recording ([method] [, format]) -> gdb.Record.\n\
2030 Start recording with the given method. If no method is given, will fall back\n\
2031 to the system default method. If no format is given, will fall back to the\n\
2032 default format for the given method."},
2033 { "current_recording", gdbpy_current_recording, METH_NOARGS,
2034 "current_recording () -> gdb.Record.\n\
2035 Return current recording object." },
2036 { "stop_recording", gdbpy_stop_recording, METH_NOARGS,
2037 "stop_recording () -> None.\n\
2038 Stop current recording." },
2039
2040 { "lookup_type", (PyCFunction) gdbpy_lookup_type,
2041 METH_VARARGS | METH_KEYWORDS,
2042 "lookup_type (name [, block]) -> type\n\
2043 Return a Type corresponding to the given name." },
2044 { "lookup_symbol", (PyCFunction) gdbpy_lookup_symbol,
2045 METH_VARARGS | METH_KEYWORDS,
2046 "lookup_symbol (name [, block] [, domain]) -> (symbol, is_field_of_this)\n\
2047 Return a tuple with the symbol corresponding to the given name (or None) and\n\
2048 a boolean indicating if name is a field of the current implied argument\n\
2049 `this' (when the current language is object-oriented)." },
2050 { "lookup_global_symbol", (PyCFunction) gdbpy_lookup_global_symbol,
2051 METH_VARARGS | METH_KEYWORDS,
2052 "lookup_global_symbol (name [, domain]) -> symbol\n\
2053 Return the symbol corresponding to the given name (or None)." },
2054 { "lookup_static_symbol", (PyCFunction) gdbpy_lookup_static_symbol,
2055 METH_VARARGS | METH_KEYWORDS,
2056 "lookup_static_symbol (name [, domain]) -> symbol\n\
2057 Return the static-linkage symbol corresponding to the given name (or None)." },
2058 { "lookup_static_symbols", (PyCFunction) gdbpy_lookup_static_symbols,
2059 METH_VARARGS | METH_KEYWORDS,
2060 "lookup_static_symbols (name [, domain]) -> symbol\n\
2061 Return a list of all static-linkage symbols corresponding to the given name." },
2062
2063 { "lookup_objfile", (PyCFunction) gdbpy_lookup_objfile,
2064 METH_VARARGS | METH_KEYWORDS,
2065 "lookup_objfile (name, [by_build_id]) -> objfile\n\
2066 Look up the specified objfile.\n\
2067 If by_build_id is True, the objfile is looked up by using name\n\
2068 as its build id." },
2069
2070 { "decode_line", gdbpy_decode_line, METH_VARARGS,
2071 "decode_line (String) -> Tuple. Decode a string argument the way\n\
2072 that 'break' or 'edit' does. Return a tuple containing two elements.\n\
2073 The first element contains any unparsed portion of the String parameter\n\
2074 (or None if the string was fully parsed). The second element contains\n\
2075 a tuple that contains all the locations that match, represented as\n\
2076 gdb.Symtab_and_line objects (or None)."},
2077 { "parse_and_eval", gdbpy_parse_and_eval, METH_VARARGS,
2078 "parse_and_eval (String) -> Value.\n\
2079 Parse String as an expression, evaluate it, and return the result as a Value."
2080 },
2081
2082 { "post_event", gdbpy_post_event, METH_VARARGS,
2083 "Post an event into gdb's event loop." },
2084
2085 { "target_charset", gdbpy_target_charset, METH_NOARGS,
2086 "target_charset () -> string.\n\
2087 Return the name of the current target charset." },
2088 { "target_wide_charset", gdbpy_target_wide_charset, METH_NOARGS,
2089 "target_wide_charset () -> string.\n\
2090 Return the name of the current target wide charset." },
2091 { "rbreak", (PyCFunction) gdbpy_rbreak, METH_VARARGS | METH_KEYWORDS,
2092 "rbreak (Regex) -> List.\n\
2093 Return a Tuple containing gdb.Breakpoint objects that match the given Regex." },
2094 { "string_to_argv", gdbpy_string_to_argv, METH_VARARGS,
2095 "string_to_argv (String) -> Array.\n\
2096 Parse String and return an argv-like array.\n\
2097 Arguments are separate by spaces and may be quoted."
2098 },
2099 { "write", (PyCFunction)gdbpy_write, METH_VARARGS | METH_KEYWORDS,
2100 "Write a string using gdb's filtered stream." },
2101 { "flush", (PyCFunction)gdbpy_flush, METH_VARARGS | METH_KEYWORDS,
2102 "Flush gdb's filtered stdout stream." },
2103 { "selected_thread", gdbpy_selected_thread, METH_NOARGS,
2104 "selected_thread () -> gdb.InferiorThread.\n\
2105 Return the selected thread object." },
2106 { "selected_inferior", gdbpy_selected_inferior, METH_NOARGS,
2107 "selected_inferior () -> gdb.Inferior.\n\
2108 Return the selected inferior object." },
2109 { "inferiors", gdbpy_inferiors, METH_NOARGS,
2110 "inferiors () -> (gdb.Inferior, ...).\n\
2111 Return a tuple containing all inferiors." },
2112
2113 { "invalidate_cached_frames", gdbpy_invalidate_cached_frames, METH_NOARGS,
2114 "invalidate_cached_frames () -> None.\n\
2115 Invalidate any cached frame objects in gdb.\n\
2116 Intended for internal use only." },
2117
2118 { "convenience_variable", gdbpy_convenience_variable, METH_VARARGS,
2119 "convenience_variable (NAME) -> value.\n\
2120 Return the value of the convenience variable $NAME,\n\
2121 or None if not set." },
2122 { "set_convenience_variable", gdbpy_set_convenience_variable, METH_VARARGS,
2123 "convenience_variable (NAME, VALUE) -> None.\n\
2124 Set the value of the convenience variable $NAME." },
2125
2126 #ifdef TUI
2127 { "register_window_type", (PyCFunction) gdbpy_register_tui_window,
2128 METH_VARARGS | METH_KEYWORDS,
2129 "register_window_type (NAME, CONSTRUCSTOR) -> None\n\
2130 Register a TUI window constructor." },
2131 #endif /* TUI */
2132
2133 {NULL, NULL, 0, NULL}
2134 };
2135
2136 #ifdef IS_PY3K
2137 struct PyModuleDef python_GdbModuleDef =
2138 {
2139 PyModuleDef_HEAD_INIT,
2140 "_gdb",
2141 NULL,
2142 -1,
2143 python_GdbMethods,
2144 NULL,
2145 NULL,
2146 NULL,
2147 NULL
2148 };
2149 #endif
2150
2151 /* Define all the event objects. */
2152 #define GDB_PY_DEFINE_EVENT_TYPE(name, py_name, doc, base) \
2153 PyTypeObject name##_event_object_type \
2154 CPYCHECKER_TYPE_OBJECT_FOR_TYPEDEF ("event_object") \
2155 = { \
2156 PyVarObject_HEAD_INIT (NULL, 0) \
2157 "gdb." py_name, /* tp_name */ \
2158 sizeof (event_object), /* tp_basicsize */ \
2159 0, /* tp_itemsize */ \
2160 evpy_dealloc, /* tp_dealloc */ \
2161 0, /* tp_print */ \
2162 0, /* tp_getattr */ \
2163 0, /* tp_setattr */ \
2164 0, /* tp_compare */ \
2165 0, /* tp_repr */ \
2166 0, /* tp_as_number */ \
2167 0, /* tp_as_sequence */ \
2168 0, /* tp_as_mapping */ \
2169 0, /* tp_hash */ \
2170 0, /* tp_call */ \
2171 0, /* tp_str */ \
2172 0, /* tp_getattro */ \
2173 0, /* tp_setattro */ \
2174 0, /* tp_as_buffer */ \
2175 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ \
2176 doc, /* tp_doc */ \
2177 0, /* tp_traverse */ \
2178 0, /* tp_clear */ \
2179 0, /* tp_richcompare */ \
2180 0, /* tp_weaklistoffset */ \
2181 0, /* tp_iter */ \
2182 0, /* tp_iternext */ \
2183 0, /* tp_methods */ \
2184 0, /* tp_members */ \
2185 0, /* tp_getset */ \
2186 &base, /* tp_base */ \
2187 0, /* tp_dict */ \
2188 0, /* tp_descr_get */ \
2189 0, /* tp_descr_set */ \
2190 0, /* tp_dictoffset */ \
2191 0, /* tp_init */ \
2192 0 /* tp_alloc */ \
2193 };
2194 #include "py-event-types.def"
2195 #undef GDB_PY_DEFINE_EVENT_TYPE
2196
2197 #endif /* HAVE_PYTHON */
2198