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